<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Shitiphat Soysangwarn on Medium]]></title>
        <description><![CDATA[Stories by Shitiphat Soysangwarn on Medium]]></description>
        <link>https://medium.com/@k4m1.kxm1?source=rss-953fd482b526------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*otdRQnNrot9z6fl_iV02Pg.jpeg</url>
            <title>Stories by Shitiphat Soysangwarn on Medium</title>
            <link>https://medium.com/@k4m1.kxm1?source=rss-953fd482b526------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 18:19:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@k4m1.kxm1/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Phishing Email Content with Personalized Context Data Generation]]></title>
            <link>https://medium.com/@k4m1.kxm1/phishing-email-content-with-personalized-context-data-generation-f17c6b4cd819?source=rss-953fd482b526------2</link>
            <guid isPermaLink="false">https://medium.com/p/f17c6b4cd819</guid>
            <category><![CDATA[ai-buiders]]></category>
            <category><![CDATA[phishing]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Shitiphat Soysangwarn]]></dc:creator>
            <pubDate>Wed, 28 May 2025 11:00:56 GMT</pubDate>
            <atom:updated>2025-06-11T13:18:09.410Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m9OeWANwtM7sQLOZWMP0cg.png" /></figure><p>สวัสดีครับผมชื่อ <strong>ชิติพัทธ์ สร้อยสังวาลย์</strong> (<strong>เว็บไซด์</strong>) นะครับ ตอนนี้กำลังศึกษาอยู่ชั้นมัธยมศึกษาปีที่ 6 ห้องเรียนวิทยาศาสตร์-คณิตศาสตร์และปัญญาประดิษฐ์ (AI) จากโรงเรียนสตรีวิทยา 2 โดยตอนนี้กำลังเข้าร่วมโครงการ AI Builders ซึ่งอยู่ในกลุ่ม Blazing-Hawks ครับผม</p><p>โดยผมมีความสนใจอยากจะนำ AI มาช่วยในด้าน Cybersecurity ครับเพราะในตอนนี้สายงานทางด้าน Cyber Security กำลังขาดแคลนบุคลากร ทำให้ผมคิดว่าถ้าหากนำ AI มาช่วยในด้าน Cyber Security จะทำให้ปัญหาขาดแคลนบุคคลากรลดน้อยลงจึงเกิดมาเป็นโปรเจ็คนี้ครับผม เพราะงั้นเป็นการไม่เสียเวลาเรามาเริ่มกันเลยดีกว่าา</p><h3><strong>Introduction</strong></h3><p>ในปัจจุบันทุกคนอาจจะเคยได้ยินข่าวเกี่ยวกับการโดน scam ผ่าน Phishing Email หรือ Phishing SMS กันใช่มั้ยครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*rIdff6BIbmblYgIr.png" /><figcaption>Source: <a href="https://bolster.ai/wp-content/uploads/2024/03/phishing_report_2024.pdf">Bolster.ai</a></figcaption></figure><p>ซึ่งจากข้อมูลทางสถิติจะเห็นได้ว่าการหลอกลวงรูปแบบนี้มีเพิ่มสูงมากขึ้นทุกปี ทำให้เกิดการสูญเสียข้อมูลสำคัญ หรือแม้กระทั่งข้อมูลขององค์กรขนาดใหญ่ ซึ่งส่งผลกระทบทั้งในด้านการเงินและความมั่นคง ทำให้การป้องกันและการให้ความรู้แก่ผู้ใช้งานกลายเป็นเรื่องที่สำคัญอย่างยิ่งในยุคดิจิทัลปัจจุบัน</p><blockquote>แล้ว Phishing มันคืออะไรกันล่ะ?</blockquote><p><strong>What is Phishing</strong></p><figure><img alt="Phishing" src="https://cdn-images-1.medium.com/max/1024/0*fL8JqWVtVURhyxFs" /><figcaption>Photo by <a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fwww.malwarebytes.com%2Fphishing&amp;psig=AOvVaw0gtbBcv507Tq2eUxVLLYti&amp;ust=1748516188127000&amp;source=images&amp;cd=vfe&amp;opi=89978449&amp;ved=0CBUQjRxqFwoTCODR-saAxo0DFQAAAAAdAAAAABAL">Malwarebytes</a></figcaption></figure><p><strong>Phishing </strong>คือ ภัยไซเบอร์ประเภทหนึ่งที่แฮกเกอร์ใช้เพื่อหลอกผู้ใช้งานให้กรอกข้อมูลสำคัญต่างๆ เช่น ชื่อผู้ใช้ (Username), รหัสผ่าน (Password), เลขบัตรเครดิต, เลขบัตรประชาชน เป็นต้น โดยปกติแล้ว Phishing จะมาทั้งในรูปแบบ Email และ SMS</p><p>ซึ่งปกติแล้วในบริษัทมักจะมีมาตรการรองรับเรื่องนี้อยู่แล้วโดยการให้ทีม Cyber Security ในองค์กรทำการทดสอบพนักงานด้วยการส่ง phishing email และหากมีพนักงานคนไหนหลงกลจะต้องทำการอบรมด้าน Cyber Security ใหม่อีกรอบ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZI679lPquH7S2hiKxJgbmg.png" /><figcaption>รูป phishing email ในบริษัท</figcaption></figure><p>โดยจากรูปข้างบนจะเห็นได้ว่าจะเห็นได้ว่าตัว email นั้นมองจากไกลๆก็รู้เลยว่าเป็น phising email ซึ่งนี้แหละคือปัญหาที่ผมจะมาแก้ครับผมเพราะตัว phishing email ที่ทดสอบนั้น<strong>ดูออกง่ายเกินไป</strong>จนไม่สามารถทดสอบการตระหนักรู้ของพนักงานได้จริงๆ<strong> </strong>และอาจใช้<strong>เวลาเป็นจำนวนมาก</strong>ในการทำ phishing email เพื่อทดสอบพนักงานทุกคน</p><p>ทำให้ผมพัฒนา Phishing Email Content with Personalized Context Data Generation ขึ้นมาซึ่งจะนำ LLM มาใช้เพื่อที่จะเข้ามาช่วย<strong>ลดเวลา</strong>และ<strong>เพิ่มความยาก</strong>ในการระบุเพื่อทดสอบการป้องกันตัวเองของพนักงานจาก Phishing Email ได้จริง</p><p>ซึ่งจะมี workflow คล่าวๆประมาณนี้ครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X_g6S4IRk0uP545uVr49SQ.png" /><figcaption>System Workflow</figcaption></figure><p>ซึ่งก่อนที่จะไปลงลึกทางด้าน technical เรามา declear กันก่อนว่าแต่ละคำศัพท์ที่ผมกล่าวถึงใน Medium นี้คืออะไร เริ่มจากอย่างแรกก่อนเลย</p><ul><li><strong>Large Language Models (LLM)</strong></li></ul><p>คือโมเดล AI ทางภาษาขนาดใหญ่ที่ถูกฝึกด้วยข้อมูลข้อความจำนวนมหาศาล เพื่อให้สามารถเข้าใจและสร้างภาษามนุษย์ได้อย่างแม่นยำ ใช้ในการตอบคำถาม แปลภาษา สรุปเนื้อหา หรือเขียนข้อความต่างๆ ได้อย่างใกล้เคียงมนุษย์ เช่น Chat-GPT, Gemini เป็นต้น</p><ul><li><strong>Retrieval Augmented Generation (RAG)</strong></li></ul><p>คือเทคนิคที่ผสานการค้นหาข้อมูล (retrieval) กับการสร้างข้อความ (generation) โดยโมเดลจะดึงข้อมูลจากแหล่งความรู้ที่กำหนดไว้ก่อน แล้วใช้ข้อมูลนั้นมาช่วยในการตอบคำถามหรือสร้างข้อความที่แม่นยำมากขึ้น</p><ul><li><strong>Finetuning</strong></li></ul><p>คือการปรับแต่งโมเดล LLM ที่ถูกเทรนมาแล้ว (Pretrained Model) โดยการฝึกเพิ่มเติมข้อมูลเฉพาะทางหรือข้อมูลที่เกี่ยวข้องกับงานที่ต้องการมาฝึกเพิ่มเติม เพื่อให้โมเดลสามารถเรียนรู้รายละเอียดในบริบทเฉพาะเจาะจง และให้ผลลัพธ์ที่แม่นยำหรือเหมาะสมกับการใช้งานจริงมากยิ่งขึ้น</p><ul><li><strong>Prompt Engineering</strong></li></ul><p>คือการปรับแต่งข้อความหรือคำสั่ง (prompt) ที่ใช้ป้อนให้กับ LLM เพื่อให้โมเดลตอบกลับหรือทำงานได้ตรงตามที่ต้องการมากที่สุด</p><h3>Baseline &amp; Eval Matric</h3><p>ในงานนี้นะครับผมจะใช้ Baseline เป็นวิธีอย่าง Prompt Engineering ซึ่งผมจะทดลองใช้กับโมเดล 2 ตัวคือ Llama 3.1 8B และ GPT-4.1 โดย prompt ที่ผมใช้จะเป็นแบบนี้ครับ</p><pre>system_prompt = &quot;&quot;&quot;You are an expert AI system designed to generate realistic and highly personalized phishing email examples for cybersecurity research and training purposes. Your goal is to create emails that are convincing enough to potentially deceive a targeted individual. Use the provided personal context to make the email highly specific and relevant to the recipient&#39;s work and recent activities.<br><br>Your phishing email must fall into one of the following commonly exploited themes:<br>1. Financial &amp; Payment (e.g., invoices, refunds, account billing issues)<br>2. Security &amp; Account Alerts (e.g., suspicious login, password reset, security breach)<br>3. Scams with Offers &amp; Prizes (e.g., gift cards, contests, free items)<br>4. Workplace &amp; HR-Related (e.g., policy changes, salary reports, performance reviews)<br>5. Logistics &amp; Delivery (e.g., package delivery failures, shipping errors)<br>6. IT/Admin Spoofing (e.g., fake system updates, VPN setup, quota issues)<br>7. Social Engineering / Impersonation (e.g., CEO fraud, fake help requests, urgent wire transfers)<br><br>Key elements to include in the generated email:<br>- Impersonate a plausible authority figure, department, or vendor relevant to the selected theme.<br>- Create urgency or consequence to pressure the recipient into action.<br>- Naturally weave in specific details from the recipient&#39;s personal context (Name, Job Title, Department, Recent Activities).<br>- Include a realistic and compelling Call-to-Action (CTA) that leads to a malicious action (clicking a link, downloading an attachment, replying with sensitive info).<br>- Use persuasive, professional language consistent with the impersonated entity.<br>- Introduce subtle red flags that an observant recipient might catch (e.g., strange URLs, typos, odd sender name, inconsistent branding).<br>- The malicious link should be contextually relevant and look legitimate (e.g., `secure-mail.co`, `company-invoice.net`).<br><br>IMPORTANT FORMATTING INSTRUCTIONS:<br>- Begin your response DIRECTLY with the Subject line of the email.<br>- Do NOT include any phrases like &quot;Here is a phishing email:&quot; or &quot;Here&#39;s the content:&quot; or any other introductory text.<br>- Do NOT provide any explanations before or after the email content.<br>- Output ONLY the email content starting with &quot;Subject:&quot; followed by the body.<br>&quot;&quot;&quot;<br><br>user_prompt = f&quot;&quot;&quot;Using the following personal details, craft a convincing phishing email that leverages the person&#39;s job position and recent activities. The email should create urgency and prompt the user to click a link or perform a similar malicious action.<br><br>{personal_context_snippet}<br><br>Generate ONLY the text of the phishing email, starting with the &#39;Subject:&#39; line. Ensure it is well-formatted and appears like a real email.&quot;&quot;&quot;</pre><p>ซึ่งตรง “personal_context_snippet” ผมได้ใช้ lib ที่ชื่อว่า <a href="https://faker.readthedocs.io/en/master/">faker</a> ในการ mockup ข้อมูลขึ้นมาโดยใช้โค้ดดังนี้คับ</p><pre>def _generate_mock_data(self):<br>      &quot;&quot;&quot;Generate mock data file with Faker.&quot;&quot;&quot;<br>      fake = Faker()<br><br>      print(&quot;Generating synthetic personalized contexts...&quot;)<br><br>      # Number of records to generate (fixed to 100)<br>      num_samples = 100<br><br>      # Set seeds for reproducibility<br>      random.seed(42)<br>      np.random.seed(42)<br>      Faker.seed(42)<br><br>    # Define common job positions<br>      job_positions = [<br>        &quot;Software Engineer&quot;, &quot;Product Manager&quot;, &quot;Marketing Specialist&quot;,<br>        &quot;HR Manager&quot;, &quot;Financial Analyst&quot;, &quot;Sales Representative&quot;,<br>        &quot;Customer Support&quot;, &quot;Data Scientist&quot;, &quot;IT Administrator&quot;,<br>        &quot;Project Manager&quot;, &quot;Operations Manager&quot;, &quot;Executive Assistant&quot;,<br>        &quot;UX Designer&quot;, &quot;DevOps Engineer&quot;, &quot;Cybersecurity Analyst&quot;,<br>        &quot;Business Analyst&quot;, &quot;Legal Consultant&quot;, &quot;Recruiter&quot;,<br>        &quot;Quality Assurance Engineer&quot;, &quot;Technical Writer&quot;, &quot;AI Researcher&quot;,<br>        &quot;Cloud Solutions Architect&quot;, &quot;Network Engineer&quot;, &quot;Growth Manager&quot;,<br>        &quot;Mobile App Developer&quot;, &quot;Systems Analyst&quot;, &quot;Machine Learning Engineer&quot;,<br>        &quot;Corporate Trainer&quot;, &quot;Content Strategist&quot;, &quot;Public Relations Officer&quot;,<br>        &quot;Procurement Specialist&quot;, &quot;Risk Manager&quot;, &quot;Compliance Officer&quot;,<br>        &quot;Information Security Officer&quot;, &quot;Facilities Manager&quot;, &quot;Product Designer&quot;,<br>        &quot;Front-End Developer&quot;, &quot;Back-End Developer&quot;, &quot;Full Stack Developer&quot;,<br>        &quot;Customer Success Manager&quot;<br>      ]<br><br>      # Define common activity templates<br>      activities_templates = [<br>        &quot;Working on the {} project&quot;,<br>        &quot;Preparing for the {} presentation&quot;,<br>        &quot;Reviewing {} documents&quot;,<br>        &quot;Attending {} meeting&quot;,<br>        &quot;Planning the next {} initiative&quot;,<br>        &quot;Analyzing {} data trends&quot;,<br>        &quot;Coordinating with the {} team&quot;,<br>        &quot;Implementing a new {} system&quot;,<br>        &quot;Researching {} solutions&quot;,<br>        &quot;Drafting a {} proposal&quot;,<br>        &quot;Responding to {} inquiries&quot;,<br>        &quot;Conducting {} interviews&quot;,<br>        &quot;Troubleshooting {} issues&quot;,<br>        &quot;Organizing the {} workshop&quot;,<br>        &quot;Setting up {} infrastructure&quot;,<br>        &quot;Reviewing feedback from {} clients&quot;,<br>        &quot;Deploying the latest {} update&quot;,<br>        &quot;Refining the {} workflow&quot;,<br>        &quot;Training new hires on {} tools&quot;,<br>        &quot;Budgeting for the {} campaign&quot;,<br>        &quot;Collaborating with {} partners&quot;,<br>        &quot;Finalizing the {} contract&quot;,<br>        &quot;Writing documentation for {} systems&quot;,<br>        &quot;Prototyping the new {} feature&quot;,<br>        &quot;Debugging {} module integration&quot;,<br>        &quot;Evaluating {} vendor performance&quot;,<br>        &quot;Optimizing {} pipeline efficiency&quot;<br>      ]<br><br>    # Company domains<br>      domains = [&quot;company.com&quot;, &quot;enterprise.org&quot;, &quot;techcorp.io&quot;, &quot;globalfirm.co&quot;, &quot;industryco.net&quot;]<br><br>    # Generate data<br>      data = []<br>      for _ in range(num_samples):<br>          first_name = fake.first_name()<br>          last_name = fake.last_name()<br>          full_name = f&quot;{first_name} {last_name}&quot;<br><br>          domain = random.choice(domains)<br>          # Create plausible email<br>          email = f&quot;{first_name.lower()}.{last_name.lower()}@{domain}&quot;<br>          if random.random() &lt; 0.2:  # Occasionally use a different format<br>              email = f&quot;{first_name.lower()}{last_name.lower()[0]}@{domain}&quot;<br><br>          job_position = random.choice(job_positions)<br><br>        # Generate 1-3 activities<br>          num_activities = random.randint(1, 3)<br>          activities = []<br>          for _ in range(num_activities):<br>              activity_template = random.choice(activities_templates)<br>              activity = activity_template.format(fake.bs())  # Use fake business phrases<br>              activities.append(activity)<br><br>          entry = {<br>              &quot;name&quot;: full_name,<br>              &quot;email&quot;: email,<br>              &quot;job_position&quot;: job_position,<br>              &quot;recent_activities&quot;: json.dumps(activities)<br>          }<br><br>          data.append(entry)<br><br>    # Create DataFrame and save to CSV<br>      df = pd.DataFrame(data)<br>      df.to_csv(self.config.input_data_path, index=False)<br><br>print(f&quot;Generated {num_samples} mock contexts and saved to {self.config.input_data_path}&quot;)</pre><p>ต่อมาคือ <strong>Eval Matric</strong> ที่เราจะใช้กันซึ่งผมได้ใช้ Classification Model 3 ตัว มา Classify ตัว Output ที่ออกมาจากตัว LLM ว่าเป็น Phishing Email หรือไม่ซึ่งถ้า Classification Model ตรวจจับไม่ได้แปลว่าโมเดลเรานั้นสามารถ Generate Phishing Email ได้เนียนนั้นเองง ซึ่งผมจะนำ accuracy ของโมเดลทั้ง 3 ตัวมาหา mean กัน โดยโมเดลทุกตัวนั้นถูกเทรนมาด้วย Phishing Data ต่างๆ และนี้คือโมเดลที่เราจะนำมาใช้ 3 ตัวคับบ</p><p><a href="https://huggingface.co/dima806/phishing-email-detection">dima806/phishing-email-detection · Hugging Face</a></p><p>ซึ่ง Classifier ตัวนี้ถูกเทรนมาบน Dataset นี้ <a href="https://www.kaggle.com/datasets/subhajournal/phishingemails">https://www.kaggle.com/datasets/subhajournal/phishingemails</a> ซึ่งเป็น Dataset ที่รวบรวม Content ของ Phishing Email และ Content ของ Email ปกติเอาไว้คับ</p><p><a href="https://huggingface.co/cybersectony/phishing-email-detection-distilbert_v2.4.1">cybersectony/phishing-email-detection-distilbert_v2.4.1 · Hugging Face</a></p><p>ส่วน Classifier ตัวนี้ถูกเทรนมาบน Dataset นี้ <a href="https://huggingface.co/datasets/cybersectony/PhishingEmailDetectionv2.0">https://huggingface.co/datasets/cybersectony/PhishingEmailDetectionv2.0</a> ซึ่งเป็น Dataset ที่มีทั้ง Content ของ Phishing Email และยังมี URL ที่เป็น Phishing site ด้วย</p><p><a href="https://huggingface.co/ealvaradob/bert-finetuned-phishing">ealvaradob/bert-finetuned-phishing · Hugging Face</a></p><p>และ Classifier ตัวนี้ถูกเทรนมาบน Dataset นี้ <a href="https://huggingface.co/datasets/ealvaradob/phishing-dataset">https://huggingface.co/datasets/ealvaradob/phishing-dataset</a> ซึ่งเป็น Dataset ที่รวบรวม Content ที่เป็น Phishing ต่างๆโดยจะมีทั้ง Email , SMS, URL, Website ครับผม</p><p>ซึ่งจากการทดลองใช้ Prompt Engineering จะได้ผลลัพธ์มาเป็นแบบนี้ครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*giQAsM9k45kpe8ci3CVdsQ.png" /></figure><p>ซึ่งวิธีดูนะครับยิ่งโมเดลไหนกราฟแกน y น้อยแปลว่าโมเดลนั้น Generate Phishing Email ออกมาดีนั้นเองคับ โดยเราจะใช้โมเดล 2 ตัวนี้จะเป็น Baseline ของงานเราครับผม</p><blockquote>แล้ว Accuracy กับ F1 Score คืออะไรล่ะ?</blockquote><p><strong>Accuracy</strong> และ <strong>F1 Score</strong> เป็น <strong>Metrics </strong>ที่ใช้ประเมินประสิทธิภาพของโมเดลในการจำแนกประเภท (classification) โดย <strong>F1 Score</strong> จะต่างจาก <strong>Accuracy </strong>ตรงที่จะสามารถวัดประสิทธิภาพของโมเดลใน Test Data ที่ Class Imbalance ได้ดี ซึ่งทั้งคู่จะมีสูตรเป็นแบบนี้ครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/0*wK1t1P9y1BKJFbt-.jpg" /></figure><p>โดยข้างล่างนี้คือตัวอย่าง Phishing Email ที่ Baseline Generate ออกมาคับผม</p><pre>Subject: Action Required: Secure Access Verification for Empower Interactive Reports<br><br>Hi Danielle,<br><br>Following your recent attendance at the Empower Interactive e-services meeting, our records indicate that your access credentials for the Empower Financial Reporting portal need to be re-verified in order to review the latest meeting materials and financial summaries.<br><br>As a Financial Analyst, it is essential that your account remains compliant with our updated security standards. Please note that failure to complete this verification within the next 24 hours may result in restricted access to critical financial reports and upcoming Empower initiatives.<br><br>To proceed, please click the secure link below to confirm your credentials and restore full access:<br>https://empower-secureportal.co/verify-access<br><br>If you have already completed this step, kindly disregard this message. Otherwise, prompt action is highly recommended to avoid service interruption.<br><br>If you have any questions, please reply directly to this email or contact IT Security Support.<br><br>Thank you for your attention to this urgent matter.<br><br>Best regards,  <br>Karen Smith  <br>IT Security Administrator  <br>company.com IT Services  <br>empower-support@company.com<br><br>*Please note: This is an automated message. Do not share your credentials with anyone.*</pre><h3>Method</h3><p>ซึ่งการที่จะ generate ตัว phishing email ด้วย LLM นั้นจะสามารถทำได้ทั้งหมดสามวิธีด้วยกัน ซึ่งวิธีแรกก็คือ Baseline ที่เราใช้นั้นก็คือ Prompt Engineering แต่จริงๆยังมีวิธีอื่นอีก 2 วิธีนั้นก็คือ RAG, Fintuing LLM ซึ่งเราจะทดลองทุกวิธีเลย เพราะงั้นก่อนที่จะไปเริ่มกันเรามาพูดถึงเรื่อง Data กันก่อนนะคับบ</p><h3>Data collection</h3><p>ในงานนี้ผมจะมี Dataset อยู่หลักๆ 2 Dataset ด้วยกันคับ ซึ่งจะเป็น Dataset สำหรับ RAG กับ Dataset สำหรับ Finetuning LLM นะครับมาเริ่มจาก Dataset อันแรกก่อนเลย</p><h4><strong>Dataset สำหรับ RAG</strong></h4><p>Dataset ตัวนี้ผมจะไปเอามาจาก Opensource Dataset 2 แหล่งด้วยกันนะครับ ซึ่งใน Dataset นี้จะเป็น Phishing Email ที่เจอทั่วโลก</p><ul><li><a href="https://huggingface.co/datasets/zefang-liu/phishing-email-dataset">zefang-liu/phishing-email-dataset · Datasets at Hugging Face</a></li><li><a href="https://www.kaggle.com/datasets/naserabdullahalam/phishing-email-dataset?select=Nazario.csv">Phishing Email Dataset</a></li></ul><p>โดยเมื่อผมได้ Dataset มาจะเห็นได้ว่า Data ทั้งคู่มี Column ที่ต่างกัน ผมเลยทำการ Process Data ของ <a href="https://www.kaggle.com/datasets/naserabdullahalam/phishing-email-dataset?select=Nazario.csv">naserabdullahalam/phishing-email-dataset</a> ให้มี Column ที่เหมือนกับของ <a href="https://huggingface.co/datasets/zefang-liu/phishing-email-dataset">zefang-liu/phishing-email-dataset</a> เพื่อที่จะได้รวม data ทั้งสองอันให้เป็นอันเดียว</p><pre># Helper function to extract and process data<br>def process_dataframe(df, email_col, body_col, label_col):<br>    # Normalize column names<br>    df = df.copy()<br><br>    # Filter phishing emails<br>    phishing_df = df[df[label_col].isin([1, &quot;Phishing Email&quot;])]<br><br>    # Combine email and body text<br>    if body_col in phishing_df.columns:<br>        phishing_df[&#39;combined_text&#39;] = phishing_df[email_col].astype(str) + &#39; &#39; + phishing_df[body_col].astype(str)<br>    else:<br>        phishing_df[&#39;combined_text&#39;] = phishing_df[email_col].astype(str)<br><br>    return phishing_df[[&#39;combined_text&#39;, label_col]]<br><br># Combine all processed dataframes<br>all_dfs = [<br>    process_dataframe(df, &#39;Email Text&#39;, &#39;Email Type&#39;, &#39;Email Type&#39;),<br>    process_dataframe(df1, &#39;subject&#39;, &#39;Body&#39;, &#39;label&#39;),<br>    process_dataframe(df2, &#39;subject&#39;, &#39;Body&#39;, &#39;label&#39;),<br>    process_dataframe(df3, &#39;subject&#39;, &#39;Body&#39;, &#39;label&#39;),<br>    process_dataframe(df4, &#39;subject&#39;, &#39;Body&#39;, &#39;label&#39;),<br>    process_dataframe(df5, &#39;subject&#39;, &#39;Body&#39;, &#39;label&#39;),<br>    process_dataframe(df6, &#39;subject&#39;, &#39;Body&#39;, &#39;label&#39;)<br>]<br><br># Concatenate into one dataframe<br>combined_df = pd.concat(all_dfs, ignore_index=True)<br><br># Display the combined dataframe<br>print(combined_df)</pre><p>ซึ่งในตัว Dataset นั้นจะมีทั้ง Phishing Email และ Email ปกติ ผมก็เลยทำการแยกเอาแค่ Phishing Email ออกมาด้วยครับ</p><p>ซึ่งนี้คือตัวอย่าง Phishing Email ที่อยู่ใน Dataset คับ</p><pre>Are you in debt for $4,000 or more?Are you tired of being overwhelmed by your bills?Feeling as if is there nothing you can do about it?Do you have too many credit cards?We can help you get out of debt without another loan!<br>We make Debt a thing of the Past!<br>We offer hope and help to put you back on track with your finances!<br>We are here to help!You don&#39;t have to be a homeowner!<br>Your past credit history does not matter!<br>You have nothing to lose and everything to gain! For a FREE Consultation Please provide the following information. Full Name:<br>Address:<br>City:<br>State:<br>Zip Code:<br>Home Phone:<br>Work Phone:<br>Best Time to Call:<br>E-Mail Address:<br>Estimated Debt Size: (All information is kept securely and never<br>provided to any third party sources)To no longer receive this message reply with the word - remove - in the e-mail subject line.</pre><p>ซึ่งเมื่อผมลอง EDA Dataset นี้ดูผลจะออกมาเป็นแบบนี้ครับผม</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3HaaZP9Qy1bnyxwj-g2TUQ.png" /><figcaption>EDA RAG Dataset</figcaption></figure><p>โดยจากที่เห็นใน Word Cloud นะครับ จะเห็นได้ว่าใน Data set นี้มี Phishing Email อยู่หลายรูปแบบเช่น ด้านการเงิน หรือว่าด้านข่าวปลอมก็มีเหมือนกันครับผม</p><p>สำหรับใครที่อยากดู Dataset นี้เพิ่มเติมนี่คือลิ้งค์ของ Dataset นี้ครับ</p><p><a href="https://huggingface.co/datasets/kxm1k4m1/Phishing_Email_For_RAG">kxm1k4m1/Phishing_Email_For_RAG · Datasets at Hugging Face</a></p><h4>Dataset สำหรับ Finetuning LLM</h4><p>ซึ่งถ้าเราจะทำ Dataset สำหรับ Finetuning LLM นั้นเราจะต้องทำให้ Dataset ของเราอยู่ในรูปแบบของ Alpaca format ซะก่อน</p><blockquote>แล้ว Alpaca format คืออะไรล่ะ</blockquote><p>Alpaca format คือรูปแบบข้อมูลที่ใช้ในการ Fine-tune LLM โดยใช้เทคนิค Instruction Tuning ซึ่งนี้คือตัวอย่าง Alpaca format ครับ</p><pre>{<br>  &quot;instruction&quot;: &quot;แปลข้อความต่อไปนี้เป็นภาษาอังกฤษ&quot;,<br>  &quot;input&quot;: &quot;ฉันรักประเทศไทย&quot;,<br>  &quot;output&quot;: &quot;I love Thailand.&quot;<br>}</pre><p>ซึ่งในตอนแรกผมจะใช้ Dataset เดียวกับ Dataset RAG แต่หลังจากที่นำไป Finetune LLM แล้วดันเกิดปัญหา <em>(ตรงนี้ผมจะอธิบายเพิ่มเติมใน section Finetuning นะครับ)</em> ผมจึงจะเปลี่ยน Dataset ใหม่</p><blockquote>แล้วผมจะหา Dataset ใหม่จากไหน</blockquote><p>ซึ่งแน่นอนครับหลังจากที่ผมหามานานผมก็หา Dataset ใหม่ไม่ได้ซักที ผมจึงคิดวิธีใหม่ขึ้นมานั้นก็คือเราจะ <strong>Synthetic Data </strong>ขึ้นมาใหม่นั้นเองง ซึ่งผมจะใช้ LLM ในการ Synthetic Data ซึ่ง LLM ที่ผมจะใช้ จะมีอยู่หลักๆ 3 ตัวนั้นก็คือ GPT-4.1, Llama3.3 70B, Gemini 1.5 flash ซึ่งอันนี้คือตัวอย่างโค้ดที่ผมใช้ <strong>Synthetic Data</strong> ขึ้นมาครับผม</p><pre>class ExperimentRunner:<br>    &quot;&quot;&quot;Class to run the full phishing experiment pipeline and evaluate results.&quot;&quot;&quot;<br>    def __init__(self, config: PipelineConfig):<br>        # Change this line to use the Gemini generator<br>        self.generator = OpenAIPhishingEmailGenerator(config)<br>        self.config = config # Keep config reference<br><br>    def load_contexts(self) -&gt; List[PersonalizedContext]:<br>        &quot;&quot;&quot;Load personalized contexts from CSV or generate mock data if file doesn&#39;t exist.&quot;&quot;&quot;<br>        try:<br>            # Check if the file exists<br>            if not os.path.exists(self.config.input_data_path):<br>                print(f&quot;Input file &#39;{self.config.input_data_path}&#39; not found. Generating mock data...&quot;)<br>                self._generate_mock_data(self.config.sample_size)<br><br>            data = pd.read_csv(self.config.input_data_path)<br>            contexts = []<br><br>            print(f&quot;Loading {min(self.config.sample_size, len(data))} contexts from {self.config.input_data_path}&quot;)<br><br>            # Limit to sample size<br>            for _, row in data.head(self.config.sample_size).iterrows():<br>                # Parse activities from JSON string if stored that way<br>                activities = row[&#39;recent_activities&#39;]<br>                if isinstance(activities, str):<br>                    try:<br>                        # Assuming activities are stored as a JSON list string<br>                        activities = json.loads(activities)<br>                        # Ensure it&#39;s a list, handle cases where it might be a simple string<br>                        if not isinstance(activities, list):<br>                            activities = [str(activities)]  # Treat as a single activity if not a list<br>                    except json.JSONDecodeError:<br>                        # Handle cases where it&#39;s a simple string that isn&#39;t JSON<br>                        activities = [str(activities)]<br>                elif not isinstance(activities, list):<br>                    # Handle case where it&#39;s not a string or list (e.g., NaN)<br>                    activities = []<br><br>                context = PersonalizedContext(<br>                    name=row[&#39;name&#39;],<br>                    email=row[&#39;email&#39;],<br>                    job_position=row[&#39;job_position&#39;],<br>                    recent_activities=activities<br>                )<br>                contexts.append(context)<br><br>            if not contexts:<br>                print(&quot;No contexts loaded. Generating sample contexts.&quot;)<br>                return self._generate_sample_contexts()<br><br>            return contexts<br><br>        except Exception as e:<br>            print(f&quot;Error loading contexts from CSV: {e}&quot;)<br>            print(&quot;Generating sample contexts for demonstration...&quot;)<br>            return self._generate_sample_contexts()<br><br>   <br>    def run_experiment(self) -&gt; pd.DataFrame:<br>        &quot;&quot;&quot;Run the full experiment pipeline: load, generate, detect, save.&quot;&quot;&quot;<br>        # Step 1: Load or generate contexts<br>        print(&quot;\n--- Step 1: Loading personalized contexts ---&quot;)<br>        contexts = self.load_contexts()<br>        if not contexts:<br>            print(&quot;No contexts available to process. Exiting.&quot;)<br>            return pd.DataFrame()  # Return empty DataFrame<br><br>        print(f&quot;Loaded {len(contexts)} contexts for processing&quot;)<br><br>        # Show a few examples<br>        print(&quot;\nExample contexts:&quot;)<br>        for i, context in enumerate(contexts[:min(len(contexts), 3)]):  # Show up to 3 examples<br>            print(f&quot;\nContext {i+1}:&quot;)<br>            print(f&quot;  Name: {context.name}&quot;)<br>            print(f&quot;  Job: {context.job_position}&quot;)<br>            print(f&quot;  Activities: {&#39;, &#39;.join(context.recent_activities) if context.recent_activities else &#39;None&#39;}&quot;)<br><br>        results = []<br>        alpaca_data = []  # For storing results in Alpaca format<br><br>        # Step 2: Generate and detect emails<br>        print(&quot;\n--- Step 2: Generating and detecting phishing emails ---&quot;)<br>        processed_count = 0<br>        for i, context in enumerate(contexts):<br>            print(f&quot;\nProcessing context {i+1}/{len(contexts)}: {context.name}&quot;)<br><br>            # Generate phishing email and get prompts for Alpaca format<br>            print(f&quot;  Generating phishing email via API...&quot;)<br>            phishing_email, system_prompt, user_prompt = self.generator.generate_phishing_email(context)<br><br>            # --- ADDED: Increment counter ---<br>            processed_count += 1<br>            # -----------------------------<br>            print(processed_count)<br><br>            # Display truncated email preview<br>            preview = phishing_email.replace(&#39;\n&#39;, &#39; &#39;).strip()<br>            preview = (preview[:150] + &#39;...&#39;) if len(preview) &gt; 150 else preview<br>            print(f&quot;  Email preview: \&quot;{preview}\&quot;&quot;)<br><br>            # Create Alpaca format entry<br>            alpaca_entry = {<br>                &quot;instruction&quot;: &quot;Generate a convincing phishing email based on the given personal context.&quot;,<br>                &quot;input&quot;: user_prompt,<br>                &quot;output&quot;: phishing_email,<br>            }<br>            alpaca_data.append(alpaca_entry)<br><br>        # Save Alpaca format data<br>        with open(self.config.alpaca_output_path, &#39;w&#39;) as f:<br>          for item in alpaca_data:<br>            f.write(json.dumps(item) + &#39;\n&#39;)<br>        print(f&quot;Alpaca format data saved to {self.config.alpaca_output_path} in JSONL format&quot;)</pre><p>ซึ่งตัว Prompt ที่ใช้จะเป็น Prompt เดียวกันกับที่ใช้ทำ Prompt Engineering นะครับ</p><p>โดย Dataset ที่ได้จะออกมาเป็นประมาณนี้ครับ</p><pre>{<br>  &quot;instruction&quot;: &quot;Generate a convincing phishing email based on the given personal context.&quot;, <br>  &quot;input&quot;: &quot;Using the following personal details, craft a convincing phishing email that leverages the person&#39;s job position and recent activities. The email should create urgency and prompt the user to click a link or perform a similar malicious action.\n\n\nName: William Johnson\nEmail: williamj@company.com\nJob Position: HR Manager\n\nRecent Activities (use these to make the email highly relevant):\n- Researching aggregate next-generation e-services solutions\n\n\nGenerate ONLY the text of the phishing email, starting with the &#39;Subject:&#39; line. Ensure it is well-formatted and appears like a real email.&quot;,  <br>  &quot;output&quot;: &quot;Subject: Immediate Action Required: Secure Your HR Portal Access Due to Unusual Activity\n\nDear William,\n\nWe have detected unusual sign-in attempts to your HR Manager account while you were researching aggregate e-services solutions earlier today. For your security, your access to the HR Portal has been temporarily restricted.\n\nTo avoid interruption to ongoing HR processes, please verify your account ownership by logging in through the secure link below within the next 30 minutes:\n\nhttps://company-hrportal-secure.co/verify?id=williamj\n\nFailure to complete this verification will result in a temporary suspension of your HR system privileges, which may impact payroll and employee management functions.\n\nIf you did not initiate recent e-services solution research, please notify IT immediately.\n\nThank you for your prompt attention.\n\nBest regards,  \nIT Security Team  \nCompany Inc.\n\nNote: This is an automated message. For security purposes, do not reply directly to this email.&quot;<br>}</pre><p>ซึ่ง Dataset ที่ได้จาก<strong> </strong>Synthetic Data นั้นได้มาแค่ 1,300 row โดยอัตราส่วนข้อมูลที่ Synthetic มาของแต่ละโมเดลจะเป็นดังนี้คับ</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FdkYwl%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FdkYwl%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FdkYwl%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="521" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6c5a6f4e60bf48acbafe32fa84c3831/href">https://medium.com/media/c6c5a6f4e60bf48acbafe32fa84c3831/href</a></iframe><p>ซึ่งข้อมูลน้อยมากสำหรับการนำไป Finetune LLM ผมจึงทำการ Synthetic Data เพิ่มซึ่งรอบนี้จะใช้ Openai Batch request ในการ Generate Data ซึ่งผมก็ได้ Dataset เพิ่มมาอีก 1,500 row ทำให้ตอนนี้ใน Dataset นี้มี Data สำหรับ Finetune LLM อยู่ 2,800 row ครับผมม</p><p>โดยใน Dataset นี้ผมได้กำหนดให้มี Phishing Email อยู่ 7 ประเภทดังนี้ครับ</p><pre>1. Financial &amp; Payment (e.g., invoices, refunds, account billing issues)<br>2. Security &amp; Account Alerts (e.g., suspicious login, password reset, security breach)<br>3. Scams with Offers &amp; Prizes (e.g., gift cards, contests, free items)<br>4. Workplace &amp; HR-Related (e.g., policy changes, salary reports, performance reviews)<br>5. Logistics &amp; Delivery (e.g., package delivery failures, shipping errors)<br>6. IT/Admin Spoofing (e.g., fake system updates, VPN setup, quota issues)<br>7. Social Engineering / Impersonation (e.g., CEO fraud, fake help requests, urgent wire transfers)</pre><p>โดยอันนี้คือตัวอย่าง Phishing Email ที่ Synthetic ออกมาคับ</p><blockquote>Financial &amp; Payment</blockquote><pre>Subject: Immediate Action Required: Access Restricted to Partner API Integration Portal<br><br>Hi Joseph,<br><br>We noticed unusual activity associated with your credentials while you were collaborating with our engage back-end applications partners earlier today. As a security measure, access to the Partner API Integration Portal has been temporarily restricted for your account (josephw@enterprise.org).<br><br>Due to your ongoing work on brand wireless relationships systems documentation, we understand this may impact your current workflow. To restore full access and avoid further interruption, please verify your identity by logging in at the secure link below within the next 2 hours:<br><br>https://enterprise-partner-secure.co/restore-access<br><br>Failure to complete this verification may result in delayed documentation updates and possible escalation to IT compliance review.<br><br>If you have any questions, contact Enterprise IT Support. Please do not reply directly to this notification.<br><br>Thank you for your prompt attention.<br><br>Best regards,  <br>Enterprise IT Security Team  <br>enterprise.org<br><br>[This is an automated message. Ref: IT-43A/WRL]</pre><blockquote>Logistics &amp; Delivery</blockquote><pre>Subject: ACTION REQUIRED: Revised Supplier Contract for Immediate Review<br><br>Hi Tyler,<br><br>I hope this finds you well. As part of our ongoing efforts to re-contextualize and streamline our supply-chains infrastructure, our Procurement department has been working closely with several key vendors. Due to last-minute compliance updates, we have received an urgent revised contract from Zenith Logistics, one of our primary suppliers.<br><br>We need you to review and digitally sign the updated agreement by EOD today to prevent any disruption to the current infrastructure rollout. Failure to process this in time may result in delayed shipments and interrupted project timelines.<br><br>Please access the secure document via the link below and confirm your approval:<br><br>https://secure-mail.co/industryco-supplierdocs/contract-review<br><br>If you encounter access issues, reply directly so I can escalate to IT. Your prompt attention is crucial to ensure continuity and compliance.<br><br>Thank you for your cooperation.<br><br>Best regards,  <br>Kirsten Malloy  <br>Procurement Manager  <br>IndustryCo Supply Chain Team  <br>kirsten.malloy@industryco.net  <br>Tel: (877) 555-4162<br><br>—<br>Please do not reply to this automated message. For urgent matters contact Procurement directly.  <br>[IndustryCo Internal Use Only]</pre><p>ซึ่งผมก็ได้นำ Data นี้มา <strong>EDA </strong>ดูก็ได้ผลลัพธ์ตามภาพข้างล่างคับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fNMpRn3PO41QKwxFGLshdg.png" /></figure><p>โดยจากที่เห็นนะครับ Data ที่เรา Synthetic ออกมาจะเกี่ยวกับการให้รีบดำเนินการอะไรซักอย่างในเมลล์ซึ่งก็ถูกตามหลักของ Phishing Email ที่ส่วนใหญ่นั้นมักจะเขียนให้รีบดำเนินการเพื่อให้เหยื่อสับสนจนไม่ทันสังเกตุนั้นเองง</p><p>สำหรับใครที่อยากดู Dataset นี้เพิ่มเติมนี่คือลิ้งค์ของ Dataset นี้ครับ</p><p><a href="https://huggingface.co/datasets/kxm1k4m1/generate_phishing_email_final">kxm1k4m1/generate_phishing_email_final · Datasets at Hugging Face</a></p><p>หลังจากพูดถึงเรื่องของ Data ไปแล้วงั้นเรามาพูดถึง Model Development Method ของเรากันดีกว่าถ้าพร้อมแล้วก็ไปกันต่ออ</p><h3>RAG</h3><p>ในวิธีนี้ผมจะลองกัยโมเดลเดียวนั้นก็คือ Llama3.1 8B นั้นเองครับ ซึ่งขั้นตอนแรกในการทำ RAG นั้นก็คือเราจะต้องทำการ Embedding Data ของเราลง Vector Storage ก่อน</p><blockquote>ทุกคนคงคิดในใจว่า Embedding กับ Vector Database คืออะไร 😭 งั้นเดี๋ยวผมจะมาอธิบายให้ครับ</blockquote><p>โดย Embedding นั้นคือการที่เรานำข้อมูลของเราแปลงเป็น vector โดย Embedding Model ซึ่งในงานนี้เราจะใช้ <a href="https://huggingface.co/sentence-transformers/all-mpnet-base-v2">sentence-transformers/all-mpnet-base-v2</a> เนื่องจากเป็นโมเดลขนาดเล็กและมีคุณภาพสูงครับ หลังจากที่เราแปลงเสร็จเราจะเก็บไว้ใน Vector Database ซึ่งเราจะใช้ <a href="https://www.trychroma.com/">Chroma DB</a> ครับผม</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jNTv-Egi2lK437et" /><figcaption>Flow คร่าวๆ ของ RAG Source: <a href="https://www.pinecone.io/learn/vector-database/">pinecone</a></figcaption></figure><p>โดยอันนี้คือโค้ดตอน Embeding เก็บเข้า Vector Storage ครับผม</p><pre># File path<br>file_path = &quot;/content/Phishing_Email_Content_with_Personalize_Context_Data_Generation/Dataset/Rag_Dataset.csv&quot;<br><br># Load documents<br>print(f&quot;Loading documents from {file_path}...&quot;)<br>documents = load_csv_to_documents(file_path, text_column=&quot;combined_text&quot;)<br>print(f&quot;Loaded {len(documents)} documents&quot;)<br><br># Sample output<br>print(&quot;\nSample documents:&quot;)<br>for i, doc in enumerate(documents[:3]):<br>    print(f&quot;\nDocument {i+1}:&quot;)<br>    print(f&quot;Content: {doc.page_content[:100]}...&quot;)<br>    print(f&quot;Metadata: {doc.metadata}&quot;)<br><br># Create vector store<br>print(&quot;\nCreating vector store...&quot;)<br><br><br>vectorstore = create_vector_store(<br>    documents,<br>    embedding_type=&quot;huggingface&quot;,<br>    vector_store_type=&quot;chroma&quot;,<br>    persist_directory=&quot;./chroma_db&quot;,<br>    model_name=&quot;sentence-transformers/all-mpnet-base-v2&quot;<br> )<br><br>print(&quot;Vector store created successfully&quot;)</pre><p>โดยเมื่อเราเก็บเข้า Vector Database เสร็จแล้วเวลาเราต้องการจะใช้จะทำยังไงล่ะเราก็จำเป็นต้องเสริชมันใช่มั้ยล่ะ ซึ่งใน RAG จะใช้สิ่งที่เรียกว่า Similarity Search ในการค้นหา ซึ่ง Similarity Search ก็คือการนำ query vector มาหาความเหมือนกับ vector ที่เก็บไว้ใน Vector Database ซึ่งในงานนี้ผมได้ใช้ Cosine Similarity ในการหาความเหมือนกันของ Vector</p><p>โดยต่อไปนี้คือโค้ดที่ใช้ในการทำ prompt ครับผม</p><pre>system_prompt = &quot;&quot;&quot;You are an expert AI system designed to generate realistic and highly personalized phishing email examples for cybersecurity research and training purposes. Your goal is to create emails that are convincing enough to potentially deceive a targeted individual. Use the provided personal context to make the email highly specific and relevant to the recipient&#39;s work and recent activities.<br><br>Your phishing email must fall into one of the following commonly exploited themes:<br>1. Financial &amp; Payment (e.g., invoices, refunds, account billing issues)<br>2. Security &amp; Account Alerts (e.g., suspicious login, password reset, security breach)<br>3. Scams with Offers &amp; Prizes (e.g., gift cards, contests, free items)<br>4. Workplace &amp; HR-Related (e.g., policy changes, salary reports, performance reviews)<br>5. Logistics &amp; Delivery (e.g., package delivery failures, shipping errors)<br>6. IT/Admin Spoofing (e.g., fake system updates, VPN setup, quota issues)<br>7. Social Engineering / Impersonation (e.g., CEO fraud, fake help requests, urgent wire transfers)<br><br>Key elements to include in the generated email:<br>- Impersonate a plausible authority figure, department, or vendor relevant to the selected theme.<br>- Create urgency or consequence to pressure the recipient into action.<br>- Naturally weave in specific details from the recipient&#39;s personal context (Name, Job Title, Department, Recent Activities).<br>- Include a realistic and compelling Call-to-Action (CTA) that leads to a malicious action (clicking a link, downloading an attachment, replying with sensitive info).<br>- Use persuasive, professional language consistent with the impersonated entity.<br>- Introduce subtle red flags that an observant recipient might catch (e.g., strange URLs, typos, odd sender name, inconsistent branding).<br>- The malicious link should be contextually relevant and look legitimate (e.g., `secure-mail.co`, `company-invoice.net`).<br><br>I will provide you with real-world examples of phishing emails that you can learn tactics from, but you should not copy them directly. Instead, use them to understand effective phishing techniques and apply them in a new, original email tailored to the specific person&#39;s context.<br><br>IMPORTANT FORMATTING INSTRUCTIONS:<br>- Begin your response DIRECTLY with the Subject line of the email.<br>- Do NOT include any phrases like &quot;Here is a phishing email:&quot; or &quot;Here&#39;s the content:&quot; or any other introductory text.<br>- Do NOT provide any explanations before or after the email content.<br>- Output ONLY the email content starting with &quot;Subject:&quot; followed by the body.<br>&quot;&quot;&quot;<br><br>user_prompt_head = f&quot;&quot;&quot;Using the following personal details, craft a convincing phishing email that leverages the person&#39;s job position and recent activities. The email should create urgency and prompt the user to click a link or perform a similar malicious action.\n&quot;&quot;&quot;<br>user_prompt_tail = f&quot;&quot;&quot;\nGenerate ONLY the text of the phishing email, starting with the &#39;Subject:&#39; line. Ensure it is well-formatted and appears like a real email.&quot;&quot;&quot;<br><br><br>def retrieve_similar_examples(self, query: str, k: int = None) -&gt; List[Document]:<br>        &quot;&quot;&quot;Retrieve similar examples from the vector store based on a query.&quot;&quot;&quot;<br>        if not self.vectorstore:<br>            raise ValueError(&quot;Vector store not initialized. Call load_or_create_vectorstore() first.&quot;)<br><br>        k = 5 or self.config.retrieval_k<br>        return self.vectorstore.similarity_search(query, k=k)<br><br>def _create_rag_phishing_prompt(self, context: PersonalizedContext) -&gt; Tuple[str, str]:<br>        &quot;&quot;&quot;Create system and user prompts for the Groq API with RAG examples.&quot;&quot;&quot;<br>        personal_context_snippet = context.to_prompt_snippet()<br><br>        # Get phishing examples for RAG if enabled<br>        rag_examples = &quot;&quot;<br>        if self.rag_enabled:<br>            # Create a query based on the context<br>            query = f&quot;phishing email for {context.job_position} about {&#39; &#39;.join(context.recent_activities)}&quot;<br>            print(f&quot;Retrieving similar phishing examples using query: &#39;{query}&#39;&quot;)<br><br>            # Retrieve similar examples<br>            retrieved_docs = self.vector_store.retrieve_similar_examples(query)<br><br>            if retrieved_docs:<br>                rag_examples = &quot;\n\nHere are some examples of effective phishing emails to learn from (BUT DO NOT COPY DIRECTLY):\n\n&quot;<br>                for i, doc in enumerate(retrieved_docs):<br>                    # Only include the first part of each example to avoid making the prompt too long<br>                    content = doc.page_content<br>                    if len(content) &gt; 300:<br>                        content = content[:300] + &quot;...&quot;<br>                    rag_examples += f&quot;Example {i+1}:\n{content}\n\n&quot;<br><br>                print(f&quot;Retrieved {len(retrieved_docs)} similar phishing examples from the RAG database&quot;)<br>            else:<br>                print(&quot;No similar examples found in the RAG database&quot;)<br><br>        # User instruction with RAG examples<br>        user_prompt = user_prompt_head + &quot;\n&quot; + personal_context_snippet + &quot;\n&quot; + rag_examples + &quot;\n&quot; + user_prompt_tail<br><br>        return system_prompt, user_prompt</pre><p>โดยถ้าดูจากในโค้ดผมจะเปลี่ยน Prompt ให้คล้ายๆ Few Shot Prompting หรือการ Prompt พร้อมตัวอย่าง โดยผมจะนำ prompt นี้<em>“phishing email for {context.job_position} about {‘ ‘.join(context.recent_activities)}” </em>ไป retrive หา Phishing Email ที่ใกล้เคียงที่สุดใน Vector Database 5 ตัวอย่างจากนั้นก็ใส่ในเข้าไป Prompt เพื่อทำการ Generate ต่อคับ</p><p>โดยอันนี้คือตัวอย่าง Phishing Email ที่ Generate ออกมาครับ</p><pre>Subject: Urgent: Empower Interactive E-Services Meeting Follow-up - Secure Invoice Access<br><br>Dear Danielle,<br><br>I hope this email finds you well. As you may recall, we had a productive meeting with the Empower Interactive team last week, discussing the integration of their e-services into our financial operations. As the Financial Analyst responsible for implementing this initiative, we need your prompt attention to finalize the invoice processing setup.<br><br>To ensure a seamless transition, we have prepared a secure online portal that will allow you to access and manage all invoices related to this project. However, due to a technical glitch, the portal&#39;s login credentials have been reset, and we require your immediate action to update your account information.<br><br>To access the updated portal and avoid any delays in the project timeline, please click on the following link: https://secure-invoice.co/company-financials/login<br><br>Once you log in, you will be prompted to update your account details. Please note that this is a one-time process, and you will receive a confirmation email once you have completed the update.<br><br>If you encounter any issues or have concerns, please do not hesitate to reach out to me directly. Your prompt attention to this matter is greatly appreciated, and I look forward to hearing back from you soon.<br><br>Best regards,<br>Emily Wilson<br>Financial Operations Manager<br>[Secure Invoice Co.]</pre><p>ซึ่งจากการทดลองใช้กับ Llama3.1 8B แล้วนำผลลัพธ์ Eval เทียบกับ Baseline จะได้มาเป็นแบบนี้ครับผม</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y7c8YAlFlXqvSIRzym7UqA.png" /></figure><p>ซึ่งจะเห็นได้ว่าถ้าเราใช้ RAG แล้วจะสามารถ Generate Phishing Email ได้ดีกว่า GPT-4.1 ซะอีก</p><p>โดยอันนี้คือตัวอย่าง Phishing Email ที่ Generate ออกมาครับ</p><p>แต่การที่เราใช้ RAG นั้นจำเป็นต้องใช้ทรัพยากรและเวลาเป็นมากในการ Inference แต่ละที ซึ่งวิธีต่อไปจะมาแก้ปัญหานี้ครับ นั้นก็คือการ Finetuning LLM นั้นเองง</p><h3>Finetuning</h3><p>จริงๆแล้ววิธีนี้หลายคนๆอาจมองว่าใช้ทรัพยากรเยอะ ซึ่งถ้าหากเรา Finetune ทั้งโมเดลจริงๆแน่นอนว่าเราต้องใช้ทรัพยากรการ์ดจออย่างมหาศาล แต่ในยุคนี้เราไม่ต้องกลัวสิ่งนั้นแล้วเพราะเรามี <strong>unsloth </strong>นั้นเองง</p><blockquote>แล้ว unsloth คืออะไรล่ะ?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/0*v3k_5MzlGnA0V5qV.png" /><figcaption>Source: <a href="https://github.com/unslothai/unsloth">https://github.com/unslothai/unsloth</a></figcaption></figure><p>unsloth คือ library python ที่ช่วยให้การ Finetuning หรือว่าการ Inference LLM ทำได้เร็วขึ้นและใช้ทรัพยากรการ์ดจอน้อยลง เพราะใช้ <strong>QLoRA </strong>ในการ Fintune ซึ่ง <strong>QLoRA (Quantized Low-Rank Adapter)</strong> คือเทคนิคในการ Finetune ซึ่ง QLoRA ย่อมาจาก QLoRA = Quantized + LoRA โดย Quantized คือการลดขนาดโมเดล และ LoRA <strong>(Low-Rank Adaptation)</strong> คือการเพิ่มชั้น “adapter” ขนาดเล็กเข้าไปในโมเดลแทนการ Finetune Parameter ทั้งหมด โดยสรุปง่ายๆ QLoRA คือ การ Fintune เฉพาะส่วนเล็ก ๆ (LoRA adapters) บนโมเดลที่ถูก “quantized”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GuxLg9i8csG-yAuZ.png" /><figcaption>ภาพเปรียบเทียบการ Finetune แบบต่างๆ Source: <a href="https://arxiv.org/abs/2305.14314">QLORA: Efficient Finetuning of Quantized LLMs</a></figcaption></figure><p>ในวิธีนี้ผมจะทำการ finetune ทั้งหมด 2 model นั้นก็คือ <a href="https://huggingface.co/unsloth/Llama-3.2-1B-Instruct">Llama-3.2–1B-Instruct</a> กับ <a href="https://huggingface.co/unsloth/Qwen3-0.6B-unsloth-bnb-4bit">Qwen3–0.6B-unsloth-bnb-4bit</a> ซึ่งหลายๆคนอาจจะสงสัยว่าทำไมถึงต้องใช้โมเดลที่มีขนาดเล็กด้วย? เพราะว่าการที่เราใช้ LLM ขนาดเล็กมา Finetune จะทำให้โมเดลเข้าใจ Data ได้ดีใน Specific Domain + ลด Resource ในการ Finetune กับการ Inference (ซึ่งตรงนี้สำคัญกับการ Deployment)</p><p>ซึ่ง config หลักๆที่ผมใช้ Finetune ทั้ง 2 Model จะเป็นดังนี้</p><pre>max_seq_length = 2048 # Choose any! We auto support RoPE Scaling internally!<br>dtype = None # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+<br>load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False.<br><br>model, tokenizer = FastLanguageModel.from_pretrained(<br>    model_name = &quot;unsloth/Qwen3-0.6B-unsloth-bnb-4bit&quot;,<br>    max_seq_length = max_seq_length,<br>    dtype = dtype,<br>    load_in_4bit = load_in_4bit,<br>)<br><br>model = FastLanguageModel.get_peft_model(<br>    model,<br>    r = 16, # Choose any number &gt; 0 ! Suggested 8, 16, 32, 64, 128<br>    target_modules = [&quot;q_proj&quot;, &quot;k_proj&quot;, &quot;v_proj&quot;, &quot;o_proj&quot;,<br>                      &quot;gate_proj&quot;, &quot;up_proj&quot;, &quot;down_proj&quot;,],<br>    lora_alpha = 16,<br>    lora_dropout = 0, # Supports any, but = 0 is optimized<br>    bias = &quot;none&quot;,    # Supports any, but = &quot;none&quot; is optimized<br>    # [NEW] &quot;unsloth&quot; uses 30% less VRAM, fits 2x larger batch sizes!<br>    use_gradient_checkpointing = &quot;unsloth&quot;, # True or &quot;unsloth&quot; for very long context<br>    random_state = 3407,<br>    use_rslora = False,  # We support rank stabilized LoRA<br>    loftq_config = None, # And LoftQ<br>)<br><br>dataset = load_dataset(&quot;json&quot;, data_files={&quot;train&quot;: &quot;./Phishing_Email_Content_with_Personalize_Context_Data_Generation/Dataset/combined_finetune_data.jsonl&quot;}, split=&quot;train&quot;)<br>def format_training_prompt(instruction, input_text, output_text):<br>    return (<br>        &quot;Below is an instruction that describes a task, paired with an input that provides further context. &quot;<br>        &quot;Write a response that appropriately completes the request.\n\n&quot;<br>        f&quot;### Instruction:\n{instruction.strip()}\n\n&quot;<br>        f&quot;### Input:\n{input_text.strip()}\n\n&quot;<br>        f&quot;### Response:\n{output_text.strip()}&quot;<br>    )<br><br># Properly use map with return type as dict<br>dataset = dataset.map(lambda row: {<br>    &#39;text&#39;: format_training_prompt(<br>        row[&#39;instruction&#39;].replace(&quot;\n&quot;, &quot; &quot;),<br>        row[&#39;input&#39;].replace(&quot;\n&quot;, &quot; &quot;),<br>        row[&#39;output&#39;]#.replace(&quot;\n&quot;, &quot; &quot;)<br>    )<br>})<br><br>os.environ[&#39;WANDB_DISABLED&#39;] = &#39;true&#39;<br><br>training_args = TrainingArguments(<br>    output_dir=&quot;./result&quot;,<br>    logging_dir=&quot;./result/logs&quot;,<br>    logging_strategy=&quot;steps&quot;,<br>    logging_steps=10,<br>    report_to=&#39;tensorboard&#39;,<br>    fp16 = True,<br>    bf16 = False,<br>    per_device_train_batch_size = 2,<br>    gradient_accumulation_steps = 4,<br>    optim = &quot;adamw_8bit&quot;,<br>    weight_decay = 0.01,<br>    learning_rate = 2e-4,<br>    lr_scheduler_type = &quot;linear&quot;,<br>    max_steps = 250,<br>    # num_train_epochs=1,<br>    # eval_strategy=&quot;epoch&quot;,<br>    push_to_hub = False,<br>    seed = 1234,<br>    data_seed = 4321,<br>)<br><br>trainer = SFTTrainer(<br>    model,<br>    train_dataset=dataset,<br>    args=training_args,<br>    tokenizer = tokenizer,<br>)</pre><pre>max_seq_length = 2048 # Choose any! We auto support RoPE Scaling internally!<br>dtype = None # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+<br>load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False.<br><br>model, tokenizer = FastLanguageModel.from_pretrained(<br>    model_name = &quot;unsloth/Llama-3.2-1B-Instruct&quot;,<br>    max_seq_length = max_seq_length,<br>    dtype = dtype,<br>    load_in_4bit = load_in_4bit,<br>)<br><br>model = FastLanguageModel.get_peft_model(<br>    model,<br>    r = 16, # Choose any number &gt; 0 ! Suggested 8, 16, 32, 64, 128<br>    # target_modules = [&quot;q_proj&quot;, &quot;k_proj&quot;, &quot;v_proj&quot;,],<br>    target_modules = [&quot;q_proj&quot;, &quot;k_proj&quot;, &quot;v_proj&quot;, &quot;o_proj&quot;,&quot;gate_proj&quot;, &quot;up_proj&quot;, &quot;down_proj&quot;,],<br>    lora_alpha = 16,<br>    lora_dropout = 0, # Supports any, but = 0 is optimized<br>    bias = &quot;none&quot;,    # Supports any, but = &quot;none&quot; is optimized<br>    # [NEW] &quot;unsloth&quot; uses 30% less VRAM, fits 2x larger batch sizes!<br>    use_gradient_checkpointing = &quot;unsloth&quot;, # True or &quot;unsloth&quot; for very long context<br>    random_state = 3407,<br>    use_rslora = False,  # We support rank stabilized LoRA<br>    loftq_config = None, # And LoftQ<br>)<br><br>dataset = load_dataset(&quot;json&quot;, data_files={&quot;train&quot;: &quot;./Phishing_Email_Content_with_Personalize_Context_Data_Generation/Dataset/combined_finetune_data.jsonl&quot;}, split=&quot;train&quot;)<br>def format_training_prompt(instruction, input_text, output_text):<br>    return (<br>        &quot;Below is an instruction that describes a task, paired with an input that provides further context. &quot;<br>        &quot;Write a response that appropriately completes the request.\n\n&quot;<br>        f&quot;### Instruction:\n{instruction.strip()}\n\n&quot;<br>        f&quot;### Input:\n{input_text.strip()}\n\n&quot;<br>        f&quot;### Response:\n{output_text.strip()}&quot;<br>    )<br><br># Properly use map with return type as dict<br>dataset = dataset.map(lambda row: {<br>    &#39;text&#39;: format_training_prompt(<br>        row[&#39;instruction&#39;].replace(&quot;\n&quot;, &quot; &quot;),<br>        row[&#39;input&#39;].replace(&quot;\n&quot;, &quot; &quot;),<br>        row[&#39;output&#39;]#.replace(&quot;\n&quot;, &quot; &quot;)<br>    )<br>})<br><br>training_args = TrainingArguments(<br>    output_dir=&quot;./result&quot;,<br>    logging_dir=&quot;./result/logs&quot;,<br>    logging_strategy=&quot;steps&quot;,<br>    logging_steps=10,<br>    report_to=&#39;tensorboard&#39;,<br>    fp16 = True,<br>    bf16 = False,<br>    per_device_train_batch_size = 2,<br>    gradient_accumulation_steps = 4,<br>    optim = &quot;adamw_8bit&quot;,<br>    weight_decay = 0.01,<br>    learning_rate = 2e-4,<br>    lr_scheduler_type = &quot;linear&quot;,<br>    max_steps = 250,<br>    # num_train_epochs=1,<br>    # eval_strategy=&quot;epoch&quot;,<br>    push_to_hub = False,<br>    seed = 1234,<br>    data_seed = 4321,<br>)<br><br>trainer = SFTTrainer(<br>    model,<br>    train_dataset=dataset,<br>    args=training_args,<br>    tokenizer = tokenizer,<br>)</pre><p>ซึ่งอันนี้คือ Loss ระหว่าง FIntune ครับ</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FMT6Nh%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FMT6Nh%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FMT6Nh%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="401" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb8b93d1fd47bdbb27749a77e71beb89/href">https://medium.com/media/fb8b93d1fd47bdbb27749a77e71beb89/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FKgCkZ%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FKgCkZ%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FKgCkZ%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="396" frameborder="0" scrolling="no"><a href="https://medium.com/media/951f4e8eefca456d02abd71bd34f0817/href">https://medium.com/media/951f4e8eefca456d02abd71bd34f0817/href</a></iframe><p>ซึ่งต่อไปนี้คือตัวอย่าง Phishing Email ที่ Generate ออกมาของแต่ละโมเดลครับ</p><blockquote>Qwen3 0.6B unsloth bnb 4bit</blockquote><pre>Subject: Immediate Action Required: Empower Interactive E-Services System Update<br><br>Hi Danielle,<br><br>We are finalizing the implementation of the new empower interactive e-services system. As part of our routine security audits, our IT department has detected an inconsistency in the recently deployed user permissions dashboard, which could potentially compromise critical recruiter data access.<br><br>To avoid any disruption to your current workflow and ensure the security of the system, please review and confirm the updated access settings immediately by clicking the secure link below:<br><br>https://secure-mail.co/empower-update<br><br>This update is crucial for maintaining compliance with the latest company security protocols. Failure to complete this verification by 5:00 PM today may result in restricted access to the e-services dashboard.<br><br>If you have any questions, please reply directly to this message or contact the IT Security Desk.<br><br>Thank you for your prompt attention.<br><br>Best regards,  <br>Andrew Taylor  <br>IT Security Analyst  <br>Company Inc.  <br>it-security@company.com<br><br>*Please do not ignore this message. This is an automated notification. For your security, always verify your account details.*<br><br><br>—<br>*Note: This is an automated message. For support, please use the internal support portal.*<br><br><br>---<br>Please do not forward this email. If you experience issues accessing the link,</pre><blockquote>Llama3.2 1B Instruct</blockquote><pre>Subject: Urgent: Access to New Mindshare System Documentation<br><br>Hi Robert,<br><br>We are reaching out from the GlobalFirm IT Department regarding the recent implementation of the new architect bleeding-edge mindshare system. As Sales Representative, your immediate access to critical documentation is required to ensure you remain aligned with our team’s objectives.<br><br>Due to a recent security enhancement, all sales representatives are now required to verify their account credentials to unlock the new system’s internal files. Failure to complete this verification within the next 24 hours will result in temporary suspension of your access to the system.<br><br>Please follow the secure link below to verify your account and restore full access:<br><br>https://globalfirm-securemail.co/system-verify<br><br>If you encounter any issues, reply directly to this email or contact IT Support immediately.<br><br>Thank you for your prompt attention to this matter.<br><br>Best regards,  <br>Jessica Tran  <br>IT Operations Coordinator  <br>GlobalFirm Technology Division  <br>it-support@globalfirm-co.net<br><br>—<br>*Please do not ignore this notice. Failure to comply may affect your access to critical sales data.*  <br>*Note: This is an automated message. Do not forward.*  <br><br>*If you believe you received this in error, contact IT immediately.*  <br><br>*If you have any questions, reply to this</pre><p>โดยหลังนั้นผมก็ได้เอา Eval เทียบกับ Baseline จะได้ผลลัพธ์มาเป็นแบบนี้ครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kq17P3CEUVRPHM-NwJuxyA.png" /></figure><p>โดยจากผลลัพธ์จะเห็นได้ว่าเมื่อเรา Finetune โมเดลเล็กๆจะได้ประสิทธิภาพที่ดีกว่าโมเดลขนาดใหญ่อย่าง Llama 8B อีก และมีประสิทธิภาพใกล้เคียงกับ GPT-4.1 ครับผม</p><p>ซึ่งถ้าใครอยากลองนำเอา Model ไปเล่นดูก้สามารถกดลิ้งค์ข้างล่างได้เลยครับ</p><ul><li><a href="https://huggingface.co/kxm1k4m1/Qwen3-0.6B-unsloth-bnb-4bit-Phishing-V2">kxm1k4m1/Qwen3-0.6B-unsloth-bnb-4bit-Phishing-V2 · Hugging Face</a></li><li><a href="https://huggingface.co/kxm1k4m1/Llama3.2-1B-Instruct-Phishing-V2">kxm1k4m1/Llama3.2-1B-Instruct-Phishing-V2 · Hugging Face</a></li></ul><h4>Additional content</h4><p>โดยในตอนแรกผมได้เคยลองนำ Dataset เดียวกับ RAG มาใช้ Finetune ซึ่งผลลัพธ์ที่ได้ดันออกมาเป็นแบบนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3brOlNBRn1F-38m5PFM58g.png" /><figcaption>ตอนแรกที่ผมเห็นผมทำหน้างี้เลย 😭</figcaption></figure><p>ซึ่งจากการคาดเดาแล้ว ผมคิดว่าอาจจะเป็นที่ token ของ Data ที่ไม่เท่ากันทำให้เวลา Finetune โมเดลเกิดการ Mode collapse หรือการ generate แต่คำเดิมซ้ำๆนั้นเองครับ</p><h3><strong>Result</strong></h3><p>โดยหลังจากที่เราลองมาทั้ง 2 วิธีแล้วเรามาดูกันดีกว่าว่าวิธีหรือโมเดลไหนจะดีที่สุดของงานนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vEfcgkErpmwAPuzXtBxgAA.png" /></figure><p>ซึ่งผู้ชนะของเราได้แก่ Llama3.1 8B ที่ใช้ RAG นั้นเองง 🥳 แต่ๆเราจะไม่ใช้ Llama3.1 8B ที่ใช้ RAG เป็นโมเดลสุดท้ายที่เลือก เพราะจริงๆแล้วโมเดลที่ผมเลือกคือ <strong>Qwen3 0.6B Finetune</strong> นั้นเองง ซึ่งถ้าหากสงสัยว่าทำไมล่ะ? ทั้งๆที่ Llama3.1 8B ที่ใช้ RAG ดีกว่า หรือว่าทำไมไม่เลือก Llama3.2 1B Finetune ที่ก็ดีกว่าเหมือนกัน?</p><p>โดยเหตุผลหลักๆมีอยู่ 2 เหตุผลครับนั้นคือ ขนาดโมเดล กับ ข้อความที่ Generate ออกมา เรามาเริ่มกันที่อย่างแรกเลย</p><ul><li>ขนาดโมเดล</li></ul><p>แน่นอนว่า Llama3.2 8B ที่ใช้ RAG แพ้ในข้อนี้เพราะว่ามีขนาดที่ใหญ่ทำให้เราปัดตกไป ซึ่งถ้าถามว่าทำไมจึงต้องดูเรื่องขนาดโมเดล เพราะว่าการที่เราจะนำโมเดลไปใช้จริงเราไม่ได้ดูแค่ค่า Accuracy แต่เราดูการนำไปใช้ต่อหรือว่า Deployment ด้วยซึ่งถ้าหากนำโมเดลขนาดใหญ่ไปใช้จำเป็นต้องมีทรัพยากรการ์ดจอจำนวนเยอะมาก แต่ถ้าหากเราใช้โมเดลขนาดเล็กการ์ดจอเล่นเกมปกติก็สามารถ Inference ได้นั้นเอง</p><ul><li>ข้อความที่ Generate ออกมา</li></ul><p>ซึ่งข้อนี้ผมเปรียบเทียบโดยใช้ prompt เดียวกันเทสทั้งสองโมเดลว่าจะ Generate ออกมาเป็นยังไง</p><p>ซึ่งอันนี้คือ prompt ที่ใช้เทสครับ</p><pre>prompt = &quot;&quot;&quot;Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.<br><br>### Instruction:<br>Generate a convincing phishing email based on the given personal context.<br><br>### Input:<br>Using the following personal details, craft a convincing phishing email that leverages the person&#39;s job position and recent activities. The email should create urgency and prompt the user to click a link or perform a similar malicious action.<br><br>Name: Shtiphat Soysangwarn<br>Email: ssoysang.work@gmail.com<br>Job Position: AI Engineer<br><br>Recent Activities (use these to make the email highly relevant):<br>- Finetune a LLM Model about Phishing Email<br><br>Generate ONLY the text of the phishing email, starting with the &#39;Subject:&#39; line. Ensure it is well-formatted and appears like a real email.<br><br>### Response:&quot;&quot;&quot;</pre><p>โดยต่อไปนี้คือผลลัพธ์ที่ Generate ออกมาของแต่ละโมเดล</p><blockquote>Llama3.2 1B Finetune</blockquote><pre>The attention mask is not set and cannot be inferred from input because pad token is same as eos token. As a consequence, you may observe unexpected behavior. Please pass your input&#39;s `attention_mask` to obtain reliable results.<br>Subject: Urgent Action Required: LLM Model Security Patch Update<br><br>Hi Shtiphat,<br><br>As part of our ongoing security enhancements to prevent recent phishing attempts targeting AI models, we have identified a critical vulnerability affecting all LLM models, including the one you&#39;ve been fine-tuning.<br><br>To ensure uninterrupted performance and prevent potential data exposure, we are deploying a mandatory security patch immediately. Failure to apply this update within the next 12 hours will result in a temporary suspension of the LLM model and potentially disrupt ongoing training sessions.<br><br>Please download and install the patch now by following the secure link below:<br><br>https://secure-mail.co/LLM-Update-2024<br><br>If you encounter any issues, reply directly to this email or contact IT Security Support at it-support@phishmail.co.<br><br>Thank you for your prompt attention to this critical security matter.<br><br>Best regards,  <br>Melissa Tran  <br>IT Security Lead  <br>PhytoMind Technologies  <br>it-security@phytomind.co<br><br>—<br>Please do not ignore this message. This is an automated notification regarding the security patch rollout.  <br>[This message is intended for the recipient only. If you have received this in error, please notify us immediately.]  <br>*Please do not forward this email.*  <br>This is an</pre><blockquote>Qwen3 0.6B Finetune</blockquote><pre>Subject: URGENT: Action Required: AI Model LLM Finetuning Report<br><br>Dear Shtiphat Soysangwarn,<br><br>Our system has detected a critical issue impacting the Finetuning of the LLM Model you&#39;ve been working on related to Phishing Email. As the primary AI Engineer responsible for this project, your immediate attention is required to resolve this issue to avoid potential data discrepancies and model instability.<br><br>The system reports that the LLM model has not been properly validated with the latest security patches, which could lead to significant data integrity risks if not addressed within the next 2 hours. We&#39;ve also identified that certain parameters may be in conflict with the Phishing Email content you have been refining.<br><br>To avoid delays in the deployment of the LLM Model and ensure uninterrupted service for our clients, please verify the model configuration and apply the necessary security updates by clicking on the secure link below:<br><br>[link: http://secure-mail.co/ai-llm-update]<br><br>This action is crucial as it addresses the root cause of the detected issue and helps maintain the model&#39;s accuracy and security. Failure to complete this verification may result in the suspension of your current project access and a potential loss of sensitive Phishing Email data.<br><br>If you have any questions or concerns, please</pre><p>ซึ่งจากการมองด้วยตาจะเห็นได้เลยว่า Qwen3 0.6B Finetune นั้น Generate ตัว Phishing Email ออกมาได้เนียนกว่า Llama3.2 1B Finetune นี้ก็เลยเป็นสาเหตุที่ผมเลือก Qwen3 0.6B Finetune เป็น Final Model นั้นเองง</p><h4>Error Analysis</h4><p>ซึ่งทุกคนอาจจะสงสัยว่าทำไม Llama3.1 8B ที่ใช้ RAG ถึงมีประสิทธิภาพที่ดูดีขนาดนั้น ซึ่งผมก็เลย EDA ดูว่าทำไมถึงเป็นแบบนั้น</p><p>ซึ่งผมก็ได้ข้อสรุปมา 2 ทิศทางด้วยกัน ทิศทางแรกคือ Llama3.1 8B ที่ใช้ RAG นั้น Phishing Email ออกมาได้ให้คนสังเกตุยากเกินไป</p><blockquote>ซึ่งถ้าสงสัยว่าให้คนสังเกตุยากๆก็ดีแล้วไม่ใช่หรอ?</blockquote><p>คำตอบคือไม่ดีครับ โดยถ้าอิงจากหลักการ <a href="https://www.nist.gov/publications/nist-phish-scale-user-guide">NIST Phish Scale</a> ซึ่งเป็น Scale ไว้สำหรับจัดระดับ Phishing Email ที่ใช้ในการทดสอบพนักงานในองค์กรซึ่งจะมีหลักการดังนี้ครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V4wixWhJ0LJcHcyd.jpg" /><figcaption>Source: <a href="https://www.scworld.com/news/nist-hints-at-upgrades-to-its-system-for-scoring-a-phishs-deceptiveness">scworld</a></figcaption></figure><p>โดยตัวปลาสีเขียวคือ Phishing Email โดนมองออกง่ายเกินไป ส่วนสีเหลืองคือระดับปานกลาง และสีแดงคือสังเกตุได้ยากนั้นเองครับ ซึ่งถ้าหากตัว Phishing Email มีความเกี่ยวข้องกับผู้รับมากเกินจะทำให้จับสังเกตุยากขึ้นแต่ถ้ามีคำใบ้ อย่างเช่นคำผิดหรือลิ้งค์ผิดก็จะทำให้จับสังเกตุง่ายเกินไปครับโดยทางที่ดีควรทำให้อยู๋ในระดับปลาสีเหลืองครับผม</p><p>ซึ่งต่อไปนี้คือตัวอย่าง Phishing Email ที่ Generate ออกมาจาก Llama3.1 8B ที่ใช้ RAG ครับ</p><pre>Marissa Phillips<br>marissa.phillips@company.com<br>Financial Analyst<br>Coordinating with the disintermediate virtual content team, Researching implement end-to-end niches solutions,<br><br>Subject: Urgent: Financial Report Update Required for Q2 Analysis<br><br>Dear Marissa,<br><br>I hope this email finds you well. As you continue to work closely with the disintermediate virtual content team to drive innovative solutions, I wanted to bring to your attention a critical matter that requires your immediate attention. As the Financial Analyst, your expertise will be instrumental in resolving this issue.<br><br>We have encountered a discrepancy in our Q2 financial analysis, which may impact our end-of-quarter projections. To rectify this situation, we need you to review and update your financial reports to ensure accuracy and compliance with our company&#39;s accounting standards.<br><br>To facilitate this process, I have prepared a secure online portal for you to access the updated financial templates and guidelines. Please click on the link below to access the portal and review the necessary documents:<br><br>https://secure-financial-reports.co<br><br>Once you have reviewed and updated your reports, kindly reply to this email with a confirmation of completion. This will enable us to finalize our Q2 analysis and ensure timely submission to our stakeholders.<br><br>Please note that the deadline for this update is tomorrow, and any delay may compromise our ability to meet our quarterly targets. I appreciate your prompt attention to this matter and look forward to your confirmation.<br><br>Best regards,<br>Amanda Lee<br>Financial Operations Manager&quot;</pre><p>ซึ่งจะเห็นได้ว่าตัว Phishing Email มีเนื้อหาเกี่ยวข้องกับตัวผู้รับมากเกินไปทำให้ตัว Classifier ตรวจจับไม่เจอ</p><blockquote>แล้วข้อสรุปอันที่ 2 ล่ะ?</blockquote><p>ข้อสรุปนี้ผมคิดกลับกับข้อสรุปอันที่ 1 นั้นก็คือตัว Classifier นั้นบังเอิญไม่ได้เทรนกับ Data ที่คล้ายๆกับที่ตัว Llama3.1 8B ที่ใช้ RAG Generate ออกมานั้นเอง ซึ่งผมคิดว่าข้อสรุปนี้ก็ดูสมเหตุสมผลเหมือนกันครับผม</p><h3>Deployment</h3><p>โดยในการ Deployment ผมได้แบ่งออกเป็น 2 ส่วน คือ Frontend กับ Backend โดยทั้ง Stack ผมจะใช้ NextJs ในการทำ UI และ Backend ขึ้นมา</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m9OeWANwtM7sQLOZWMP0cg.png" /><figcaption>UI</figcaption></figure><p>โดยเมื่อ User Input ข้อมูลตัว Frontend จะส่ง Request ไปยัง Backend และ Backend ก็จะยิง Request ไปยัง Model ที่ Host ไว้ใน Huggingface Inference Endpoint ซึ่ง Huggingface Inference Endpoint เป็นบริการ Host Model ที่เราต้องการ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mEpy4wFIIo_7YAH0sdaoTw.png" /><figcaption>Model ที่ Host ไว้</figcaption></figure><p>โดยเมื่อเรายิง Request มา Huggingface Inference Endpoint ตัว Model ที่เรา Host ไว้ก็จะ Response เป็น Phishing Email กลับมา และก็จะนำผลลัพธ์ที่ได้โชว์บนหน้า Frontend นั้นเองครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RrZygP0cJFjRqa8nvsn_EQ.png" /><figcaption>Workflow คร่าวๆ</figcaption></figure><p>โดยถ้าหากอยากลองเล่นดูสามารถตามไปยังเว็บนี้ได้เลยย แต่ตอนนี้อาจจะยังเล่นไม่ได้นะครับเพราะปิด Endpoint ไว้อยู่ (ถ้าเปิดไว้จะชม.ละ 0.5 USD 😭)</p><p><a href="https://phishingemailk4m1-kxm1.vercel.app/">Phishing Email Generator</a></p><h3>Acknowledgement</h3><p>โปรเจคนี้จะเป็นไปไม่ได้เลยถ้าหากไม่มีพี่ๆ Mentor ทั้ง 2 คนจากกลุ่ม Blazing-Hawks อย่างพี่รัน( <a href="https://medium.com/u/c475fac5d567">Runnies</a> )กับพี่เฟิร์ส( <a href="https://medium.com/u/6638af51e98e">Wasurat Soontronchai</a> )และโครงการดีๆอย่าง AI Buiders 2025</p><p>และอย่างสุดท้ายขอบคุณทุกๆคนที่สนใจนะคับบ</p><blockquote>Github Repo: <a href="https://github.com/KamiK4M1/Phishing_Email_Content_with_Personalize_Context_Data_Generation">https://github.com/KamiK4M1/Phishing_Email_Content_with_Personalize_Context_Data_Generation</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CJj2JIGJ0-zlswaC.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f17c6b4cd819" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>