<?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[PALO IT THAILAND - Medium]]></title>
        <description><![CDATA[We’re a global technology consultancy that designs, develops and scales digital and sustainable products and services to unlock value across the triple bottom line: people, planet, profit. - Medium]]></description>
        <link>https://medium.com/palo-it-thailand?source=rss----3ae4f2a55b01---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>PALO IT THAILAND - Medium</title>
            <link>https://medium.com/palo-it-thailand?source=rss----3ae4f2a55b01---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 11:03:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/palo-it-thailand" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Convert Pytorch Model to Quantize GGUF to Run on Ollama]]></title>
            <link>https://medium.com/palo-it-thailand/convert-pytorch-model-to-quantize-gguf-to-run-on-ollama-5c5dbc458208?source=rss----3ae4f2a55b01---4</link>
            <guid isPermaLink="false">https://medium.com/p/5c5dbc458208</guid>
            <category><![CDATA[model-quantization]]></category>
            <category><![CDATA[dataset]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[llama-cpp]]></category>
            <category><![CDATA[ollama]]></category>
            <dc:creator><![CDATA[Sarin Suriyakoon]]></dc:creator>
            <pubDate>Wed, 11 Feb 2026 08:57:18 GMT</pubDate>
            <atom:updated>2026-02-11T08:57:16.874Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LIAID9npuUUZaOLllcRgfQ.jpeg" /></figure><h4>Pytorch Model(Bonito)-&gt;GGUF-&gt;Quantize for your local inference using Ollama</h4><h3>Background</h3><p>Most of the Huggingface model is in Pytorch format, it is sometimes difficult for me to run on my local with all the underlying knowledge involved. Here I propose a slightly easier way to convert to GGUF and Quantize it then run it with Ollama, plus a few examples of huggingface usage. These small pieces of knowledge will serve you well in the long run.</p><p>Here are a few points before we start</p><ul><li>Quantization is a way to reduce resource usage when running a model. This suits me well because I always use the model on my local laptop with minimum RAM and only Intel Iris Plus Graphics 1536 MB</li><li>Suppose you find a Pytorch model that looks interesting from huggingface and want to try it out on <a href="https://sarinsuriyakoon.medium.com/run-ollama-in-5-minutes-free-open-source-llm-on-your-local-bonus-section-e520e452de86">Ollama</a> or GPT4All. This guide is for you.</li><li>We will use the Bonito model in this example because it has such a great use case. It helps turn unstructured text into dataset format, ready to train. It also has such a different template from other models, which makes it a little difficult to write Modelfile, which is great to help us learn.</li></ul><h3>Overview</h3><ul><li><strong>Tools</strong></li><li><strong>Download a source model — We will use </strong><a href="https://huggingface.co/BatsResearch/bonito-v1"><strong>https://huggingface.co/BatsResearch/bonito-v1</strong></a></li><li><strong>Convert to GGUF</strong></li><li><strong>Quantize to GGUF Q4_K_M</strong></li><li><strong>Upload to Huggingface</strong></li><li><strong>Use it in Ollama(two methods provided)</strong></li></ul><h3><strong>Tools</strong></h3><p>Download, Setup and Skim around these tools documentation</p><ul><li><a href="https://huggingface.co/docs/huggingface_hub/en/guides/cli">huggingface-cli</a></li><li><a href="https://ollama.com/">Ollama</a></li><li><a href="https://github.com/ggerganov/llama.cpp">llama.cpp</a></li></ul><p>Ready? Let’s go!</p><h3>Download a Source Model</h3><pre>huggingface-cli download BatsResearch/bonito-v1<br>cp -r [hugginface saved path] [new easy to remember path]/bonito</pre><h3>Convert to GGUF</h3><pre>git clone https://github.com/ggerganov/llama.cpp/tree/master<br>cd llama.cpp<br>pip install -r requirements.txt<br>cd ..<br>python llama.cpp/convert.py bonito</pre><h3>Quantize to Q4_K_M</h3><pre>cd llama.cpp<br>make<br>./quantize [your path to]/bonito/ggml-model-f32.gguf [your path to]/bonito/ggml-model-f32.gguf-Q4_K_M.gguf Q4_K_M</pre><h3>Upload to Huggingface</h3><pre>cd ~/bonito-gguf<br>huggingface-cli upload bonito-gguf . .</pre><h3>Use it in Ollama(Two methods provided)</h3><p>There are two ways.</p><ul><li>First, Import locally, create Modelfile and add this content(at FROM use your local path)</li></ul><pre>FROM ./ggml-model-f32.gguf-Q4_K_M.gguf<br>TEMPLATE &quot;&quot;&quot;&lt;|tasktype|&gt;<br>{{ if .System }}{{ .System }}{{ end }}<br>&lt;|context|&gt;<br>{{ .Prompt }}<br>&lt;|task|&gt;<br>&quot;&quot;&quot;<br><br>PARAMETER stop &quot;&lt;|task|&gt;&quot;<br>PARAMETER stop &quot;&lt;|context|&gt;&quot;<br>PARAMETER stop &quot;&lt;|tasktype|&gt;&quot;</pre><ul><li>Second, use the model from the Ollama library here <a href="https://ollama.com/pacozaa/bonito">https://ollama.com/pacozaa/bonito</a></li></ul><p>Run this command on your terminal</p><pre>ollama run pacozaa/bonito</pre><p>Try to add an article content to the command like this</p><pre>ollama run pacozaa/bonito &quot;RAG is a technique for augmenting LLM knowledge with additional data.<br><br>LLMs can reason about wide-ranging topics, but their knowledge is limited to the public data up to a specific point in time that they were trained on. If you want to build AI applications that can reason about private data or data introduced after a model&#39;s cutoff date, you need to augment the knowledge of the model with the specific information it needs. The process of bringing the appropriate information and inserting it into the model prompt is known as Retrieval Augmented Generation (RAG).<br><br>LangChain has a number of components designed to help build Q&amp;A applications, and RAG applications more generally.&quot;</pre><h3>Usage</h3><p>Setting the proper task type is crucial for Bonito.</p><p>Here are the task types we can use</p><pre>SHORTFORM_TO_FULL_TASK_TYPES = {<br>    &quot;exqa&quot;: &quot;extractive question answering&quot;,<br>    &quot;mcqa&quot;: &quot;multiple-choice question answering&quot;,<br>    &quot;qg&quot;: &quot;question generation&quot;,<br>    &quot;qa&quot;: &quot;question answering without choices&quot;,<br>    &quot;ynqa&quot;: &quot;yes-no question answering&quot;,<br>    &quot;coref&quot;: &quot;coreference resolution&quot;,<br>    &quot;paraphrase&quot;: &quot;paraphrase generation&quot;,<br>    &quot;paraphrase_id&quot;: &quot;paraphrase identification&quot;,<br>    &quot;sent_comp&quot;: &quot;sentence completion&quot;,<br>    &quot;sentiment&quot;: &quot;sentiment&quot;,<br>    &quot;summarization&quot;: &quot;summarization&quot;,<br>    &quot;text_gen&quot;: &quot;text generation&quot;,<br>    &quot;topic_class&quot;: &quot;topic classification&quot;,<br>    &quot;wsd&quot;: &quot;word sense disambiguation&quot;,<br>    &quot;te&quot;: &quot;textual entailment&quot;,<br>    &quot;nli&quot;: &quot;natural language inference&quot;,<br>}</pre><p>Check out their implementation <a href="https://github.com/BatsResearch/bonito/blob/main/bonito/abstract.py#L5">here</a>.</p><p>To set the task type with Ollama, we need to use &gt;&gt;&gt;/set system after ollama run pacozaa/bonito</p><p>For example</p><p>&gt;&gt;&gt;/set system question generation</p><p>&gt;&gt;&gt;[paste your long unstructured text as an input]</p><h3>Conclusion</h3><p>With these steps and examples, you now learn how to download a Huggingface Pytorch model, convert it to GGUF, quantize it, contribute/upload it on Huggingface then run it with Ollama.</p><p>Also, with Bonito, you can use it to generate datasets from unstructured text. Just run Bonito with Ollama, and use LangChain to organize the dataset generation.</p><p>If you’d like hands-on help converting PyTorch models to GGUF, quantizing for local/Ollama, or building RAG + dataset pipelines with LangChain, our team at PALO IT Thailand can support from POC to production. Reach out via our Facebook page: <strong>PALO IT Thailand</strong>.</p><p>— — — — — — — — — — — — — — — — -</p><p>Need a partner to turn Unsloth LoRA into a fast, local model on Ollama — templates, evals, safety, and CI/CD included? Message us on Facebook: <strong>PALO IT Thailand</strong>.</p><p>— — — — — — — — — — — — — — — — -</p><p>FB Link: <a href="https://www.facebook.com/PALOITTH">https://www.facebook.com/PALOITTH</a></p><h3>Source and Credit</h3><ul><li><a href="https://github.com/BatsResearch/bonito/blob/main/bonito/abstract.py#L5">bonito/bonito/abstract.py at main · BatsResearch/bonito</a></li><li><a href="https://arxiv.org/abs/2402.18334">Learning to Generate Instruction Tuning Datasets for Zero-Shot Task Adaptation</a></li><li><a href="https://github.com/ggerganov/llama.cpp/discussions/2948">Tutorial: How to convert HuggingFace model to GGUF format · ggerganov llama.cpp · Discussion #2948</a></li><li><a href="https://github.com/ollama/ollama/blob/main/docs/import.md">ollama/docs/import.md at main · ollama/ollama</a></li><li><a href="https://github.com/ollama/ollama/blob/main/docs/modelfile.md">ollama/docs/modelfile.md at main · ollama/ollama</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c5dbc458208" width="1" height="1" alt=""><hr><p><a href="https://medium.com/palo-it-thailand/convert-pytorch-model-to-quantize-gguf-to-run-on-ollama-5c5dbc458208">Convert Pytorch Model to Quantize GGUF to Run on Ollama</a> was originally published in <a href="https://medium.com/palo-it-thailand">PALO IT THAILAND</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[เพิ่มความปลอดภัยด้วย Two-Factor Authentication (2FA) บน Next.js + Amazon Cognito]]></title>
            <link>https://medium.com/palo-it-thailand/%E0%B9%80%E0%B8%9E%E0%B8%B4%E0%B9%88%E0%B8%A1%E0%B8%84%E0%B8%A7%E0%B8%B2%E0%B8%A1%E0%B8%9B%E0%B8%A5%E0%B8%AD%E0%B8%94%E0%B8%A0%E0%B8%B1%E0%B8%A2%E0%B8%94%E0%B9%89%E0%B8%A7%E0%B8%A2-two-factor-authentication-2fa-%E0%B8%9A%E0%B8%99-next-js-amazon-cognito-17f503b75cd6?source=rss----3ae4f2a55b01---4</link>
            <guid isPermaLink="false">https://medium.com/p/17f503b75cd6</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[2fa]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[amazon-cognito]]></category>
            <category><![CDATA[amazon-web-services]]></category>
            <dc:creator><![CDATA[Vatcharat R.]]></dc:creator>
            <pubDate>Thu, 27 Nov 2025 14:01:24 GMT</pubDate>
            <atom:updated>2025-11-27T14:01:23.428Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7adfMhXa0WEHWoafYRE1Rg.png" /></figure><p>บทความนี้จะพาทำ 2FA แบบใช้แอป Authenticator (TOTP) บน Next.js + Amazon Cognito ครับ สามารถใช้กับ Google Authenticator, Microsoft Authenticator, หรือ Authy ได้เลย</p><h4><strong>สิ่งที่จะได้</strong></h4><ul><li>เข้าใจ flow การทำงานของ MFA Challenge</li><li>รู้วิธีสร้าง QR Code สำหรับ Authenticator</li><li>ตั้งค่า Cognito ให้รองรับ TOTP</li><li>จัดการ error และ security best practices</li></ul><blockquote>💡 <strong>โค้ดเต็มอยู่บน </strong><a href="https://github.com/GLOBAL-PALO-IT/nextjs-amazon-cognito"><strong>GitHub</strong></a> — บทความนี้เน้นอธิบาย concepts และ key decisions ครับ ไม่ได้วางโค้ดทั้งหมด</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*6LO_98u6eQqcW30kMDh-7Q.png" /><figcaption>หน้าเว็บที่แสดงว่า login ด้วย 2FA สำเร็จ</figcaption></figure><h3>2FA คืออะไร สำคัญยังไง</h3><p>2FA (Two-Factor Authentication) = ใช้ “สองอย่าง” ยืนยันตัวตน:</p><p>1. <strong>สิ่งที่รู้</strong> — Email + Password</p><p>2. <strong>สิ่งที่ถืออยู่</strong> — โค้ด 6 หลักจากแอป Authenticator (เปลี่ยนทุก 30 วินาที)</p><h4><strong>ทำไมต้องมี?</strong></h4><p>ต่อให้รหัสผ่านหลุดจากฟิชชิ่ง คนร้ายก็ยังเข้าไม่ได้ เพราะไม่มีโค้ดจากมือถือคุณ</p><h3>ต้องเตรียมอะไรใน AWS Cognito</h3><h4>สิ่งที่ต้องมีใน AWS</h4><ul><li><strong>Cognito User Pool</strong> ตั้ง MFA เป็น “Optional”</li><li><strong>App Client</strong> เปิด Software Token MFA (TOTP)</li><li><strong>User Pool ID</strong> + <strong>App Client ID</strong></li></ul><blockquote>📖 <strong>วิธีตั้งค่าละเอียด</strong>: ดู <a href="https://medium.com/palo-it-thailand/%E0%B8%A7%E0%B8%B4%E0%B8%98%E0%B8%B5%E0%B9%80%E0%B8%9B%E0%B8%B4%E0%B8%94%E0%B9%83%E0%B8%8A%E0%B9%89-mfa-%E0%B9%81%E0%B8%A5%E0%B8%B0-sms-%E0%B8%9A%E0%B8%99-amazon-cognito-daa68f2e5ef1">วิธีเปิดใช้ MFA และ SMS บน Amazon Cognito</a></blockquote><p>Environment Variables</p><pre># .env.local<br>NEXT_PUBLIC_COGNITO_USER_POOL_ID=us-east-1_xxxxxxxxx<br>NEXT_PUBLIC_COGNITO_CLIENT_ID=xxxxxxxxxxxxxxxxxxxxxxxxxx<br>NEXT_PUBLIC_APP_NAME=YourAppName</pre><blockquote><strong>ทำไมต้องมี NEXT_PUBLIC</strong>: เพราะ Cognito SDK ทำงานฝั่ง client</blockquote><blockquote><strong>APP_NAME</strong>: จะโชว์ในแอป Authenticator ให้รู้ว่าโค้ดนี้สำหรับระบบไหน</blockquote><h4>Dependencies</h4><pre>npm install amazon-cognito-identity-js qrcode.react<br>npm install --save-dev @types/qrcode</pre><h3>เข้าใจ Flow การล็อกอินแบบมี 2FA</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k3WQ1u9dQJBH2XXEg_HtLg.png" /><figcaption>Flow Diagram</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2h6ffrvf4xdyntd_oH-WXw.png" /><figcaption>Sequence Diagram</figcaption></figure><h4>สถาปัตยกรรมและไฟล์สำคัญ</h4><pre>src/<br>├── config/<br>│   └── cognito.ts              # User Pool configuration<br>├── services/<br>│   └── auth.ts                 # ฟังก์ชัน MFA ทั้งหมด<br>├── components/<br>│   ├── LoginForm.tsx           # ฟอร์มล็อกอิน<br>│   ├── MfaVerificationForm.tsx # ฟอร์มกรอกโค้ด MFA<br>│   ├── AuthenticatorSetup.tsx  # สร้าง QR Code<br>│   └── VerifyAuthenticator.tsx # ยืนยัน + เปิดใช้งาน<br>├── types/<br>│   └── cognito-errors.ts       # Error type guards<br>└── pages/<br>    ├── login.tsx               # Orchestrate login flow<br>    └── setup-2fa.tsx           # Setup 2FA flow</pre><h4>ฟังก์ชันหลักใน services/auth.ts</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*Db_UXm1y3b4dUfCvJoLhAQ.png" /></figure><h3>ขั้นตอนการทำ</h3><h4>1. Cognito Configuration</h4><p>สร้าง User Pool connection:</p><pre>// config/cognito.ts<br>import { CognitoUserPool } from &quot;amazon-cognito-identity-js&quot;;<br><br>export const userPool = new CognitoUserPool({<br>  UserPoolId: process.env.NEXT_PUBLIC_COGNITO_USER_POOL_ID || &quot;&quot;,<br>  ClientId: process.env.NEXT_PUBLIC_COGNITO_CLIENT_ID || &quot;&quot;,<br>});</pre><h4>2. MFA Challenge Detection</h4><p><strong>Concept หลัก</strong>: Cognito callbacks บอกสถานะ authentication</p><pre>cognitoUser.authenticateUser(authDetails, {<br>  onSuccess: (result) =&gt; {<br>    // ไม่มี MFA หรือ trusted device<br>    return result.getIdToken().getJwtToken();<br>  },<br>  totpRequired: (challengeName, params) =&gt; {<br>    // ต้องใช้ Authenticator app<br>    return { email, password, challengeName, params };<br>  },<br>  mfaRequired: (challengeName, params) =&gt; {<br>    // ต้องใช้ SMS<br>    return { email, password, challengeName, params };<br>  },<br>  onFailure: (err) =&gt; reject(err),<br>});</pre><blockquote>💡 <strong>ทำไมเก็บ email + password ใน Challenge?</strong></blockquote><blockquote>เพราะตอนส่ง MFA code ต้อง re-authenticate กับ Cognito อีกรอบ</blockquote><p><strong>Type Definition</strong>:</p><pre>export interface MfaChallenge {<br>  email: string;<br>  password: string;<br>  challengeName: &quot;SMS_MFA&quot; | &quot;SOFTWARE_TOKEN_MFA&quot;;<br>  challengeParameters: {<br>    CODE_DELIVERY_DESTINATION?: string;<br>  };<br>}ะ</pre><p><a href="https://github.com/gamertense/nextjs-amazon-cognito/blob/main/src/services/auth.ts">ดูโค้ดเต็ม signIn()</a></p><h4>3. Component Integration Pattern</h4><p><strong>Page-level orchestration</strong> (ไม่ใช่ component-level):</p><pre>// pages/login.tsx<br>const [mfaChallenge, setMfaChallenge] = useState&lt;MfaChallenge | null&gt;(null);<br><br>const handleLogin = async (email: string, password: string) =&gt; {<br>  const result = await signIn(email, password);<br><br>  if (typeof result === &quot;string&quot;) {<br>    // Got token directly<br>    saveToken(result);<br>    router.push(&quot;/home&quot;);<br>  } else {<br>    // Got MFA challenge<br>    setMfaChallenge(result);<br>  }<br>};<br><br>// Conditional rendering<br>{<br>  !mfaChallenge ? (<br>    &lt;LoginForm onLoginSuccess={handleLogin} /&gt;<br>  ) : (<br>    &lt;MfaVerificationForm<br>      mfaChallenge={mfaChallenge}<br>      onSuccess={() =&gt; router.push(&quot;/home&quot;)}<br>    /&gt;<br>  );<br>}</pre><blockquote>⚠️ <strong>Common Mistake</strong>: อย่าใส่ logic routing ใน component — ใช้ callback props แทน</blockquote><p><a href="https://github.com/gamertense/nextjs-amazon-cognito/tree/main/src/components">ดูโค้ดเต็ม Components</a></p><h4>4. QR Code Generation</h4><p><strong>Concept</strong>: สร้าง `otpauth://` URI สำหรับ Authenticator apps</p><p><strong>ขั้นตอน</strong>:</p><ol><li>ขอ <em>secretCode</em> จาก Cognito</li><li>สร้าง URI format ตามมาตรฐาน</li><li>แปลงเป็น QR Code ด้วย <em>qrcode.react</em></li></ol><pre>const secret = await setupAuthenticatorApp(); // Get from Cognito<br><br>const otpauthUri = `otpauth://totp/${encodeURIComponent(<br>  issuer<br>)}:${encodeURIComponent(email)}?secret=${secret}&amp;issuer=${encodeURIComponent(<br>  issuer<br>)}`;<br><br>// Render QR<br>&lt;QRCodeSVG value={otpauthUri} size={200} /&gt;;</pre><p><strong>URI Structure</strong>:</p><pre>otpauth://totp/MyApp:user@example.com?secret=SECRETKEY&amp;issuer=MyApp<br>         │     │                        │              │<br>         │     └─ Issuer:Account        └─ TOTP secret └─ App name<br>         └─ Protocol (TOTP)</pre><p><a href="https://github.com/gamertense/nextjs-amazon-cognito/blob/main/src/components/AuthenticatorSetup.tsx">ดูโค้ดเต็ม QR Generation</a></p><h4>5. Verification &amp; Activation</h4><p><strong>2 ขั้นตอนสำคัญ</strong></p><pre>// 1. ยืนยันโค้ดแรกจาก Authenticator<br>await verifyAuthenticatorCode(code, &quot;DeviceName&quot;);<br><br>// 2. ตั้งให้ TOTP เป็นวิธี MFA หลัก<br>await setPreferredMfaMethod(&quot;SOFTWARE_TOKEN_MFA&quot;);</pre><p><strong>Cognito callbacks</strong></p><pre>cognitoUser.verifySoftwareToken(code, deviceName, {<br>  onSuccess: () =&gt; {<br>    /* ยืนยันสำเร็จ */<br>  },<br>  onFailure: (err) =&gt; {<br>    /* โค้ดผิด */<br>  },<br>});<br><br>cognitoUser.setUserMfaPreference(smsSettings, totpSettings, callback);</pre><h4>6. Error Handling</h4><p><strong>Best Practice</strong>: ใช้ type guards แยกประเภท error</p><pre>// types/cognito-errors.ts<br>type CognitoAuthErrorCode =<br>  | &quot;UserNotConfirmedException&quot;<br>  | &quot;NotAuthorizedException&quot;<br>  | &quot;UserNotFoundException&quot;<br>  | &quot;CodeMismatchException&quot;<br>  | &quot;ExpiredCodeException&quot;<br>  | &quot;InvalidParameterException&quot;<br>  | &quot;UsernameExistsException&quot;;<br><br>export type CognitoAuthError = {<br>  message: string;<br>  code: CognitoAuthErrorCode;<br>};<br><br>export const isCognitoAuthError = (error: unknown): error is CognitoAuthError =&gt;<br>  typeof error === &quot;object&quot; &amp;&amp;<br>  error !== null &amp;&amp;<br>  &quot;code&quot; in error &amp;&amp;<br>  &quot;message&quot; in error;<br><br>export const isCognitoCodeMismatchError = (error: unknown): boolean =&gt; {<br>  return isCognitoAuthError(error) &amp;&amp; error.code === &quot;CodeMismatchException&quot;;<br>};<br><br>export const isExpiredCodeError = (error: unknown): boolean =&gt; {<br>  return isCognitoAuthError(error) &amp;&amp; error.code === &quot;ExpiredCodeException&quot;;<br>};<br><br>export const isNotAuthorizedError = (error: unknown): boolean =&gt; {<br>  return isCognitoAuthError(error) &amp;&amp; error.code === &quot;NotAuthorizedException&quot;;<br>};</pre><p><strong>ใช้งาน</strong>:</p><pre>try {<br>  await submitMfaCode(email, password, code, challengeName);<br>} catch (error) {<br>  if (isCognitoCodeMismatchError(error)) {<br>    setError(&quot;รหัสไม่ถูกต้อง กรุณาลองใหม่&quot;);<br>  } else if (isExpiredCodeError(error)) {<br>    setError(&quot;โค้ดนี้ถูกใช้ไปแล้ว รอโค้ดใหม่จากแอป&quot;);<br>  } else {<br>    setError(&quot;เกิดข้อผิดพลาด&quot;);<br>  }<br>}</pre><p><a href="https://github.com/gamertense/nextjs-amazon-cognito/blob/main/src/types/cognito-errors.ts">ดูโค้ดเต็ม Error Handling</a></p><h3>ทดสอบว่า 2FA ทำงานถูกต้อง</h3><ol><li>เข้าเพจตั้งค่า 2FA โดยกดปุ่ม Set Up Authenticator App</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*QwGd7bmNR_ia4dmaY05Fow.png" /></figure><p>2. พิมพ์ email ที่ต้องการเปิด 2FA แล้วกดปุ่ม Generate QR Code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*Un5qy_yV_fzZ39aipwb1_g.png" /></figure><p>3. สแกน QR code ด้วย Google Authenticator / Microsoft Authenticator</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*b0IFwnl7OULN_IcZMpWkNw.png" /></figure><p>4. สังเกตชื่อที่แสดงบน Authenticator จะตรงตาม env variable <em>NEXT_PUBLIC_APP_NAME</em></p><p>5. กดปุ่ม Continue to Verification</p><p>6. กรอกโค้ดแรกผ่าน → กดปุ่ม Verify and Enable 2FA</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*rZxWtE7-t8nyTxg_kQMkzw.png" /></figure><p>7. จะได้ข้อความว่า Authenticator setup successful! 2FA is now enabled. Redirecting…</p><h4>ล็อกอินด้วยบัญชีที่มี 2FA</h4><p>1. Login ด้วย email ที่เพิ่งเปิด 2FA</p><p>2. กรอกโค้ดที่แสดงบน Authenticator app</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*RGq6xQHUBQiPwegsXWXnfA.png" /></figure><p>3. หน้าเว็บจะแสดงว่าบัญชีนี้ถูกปกป้องด้วย 2FA</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*6LO_98u6eQqcW30kMDh-7Q.png" /></figure><h3>ปัญหาที่มักเจอ + วิธีแก้</h3><h4>MFA เปิดอยู่แล้ว ไม่สามารถ setup ใหม่ได้</h4><p><strong>อาการ</strong>: Error “Software token MFA is already enabled”</p><p><strong>วิธีแก้</strong>:</p><p>1. ไปที่ Amazon Cognito</p><p>2. เลือก user pool และเปิดหน้า Users (ใต้ User management แถบด้านข้าง)</p><p>3. ​ค้นหาบัญชีที่ต้องการ</p><p>4. คลิ๊กที่บัญชี จะเห็นว่าสถานะเป็น active</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*QglyqV4V3gktyOAK0vprgA.png" /></figure><p>5. กดปุ่ม Actions ขวาบน &gt; Update MFA configuration</p><p>6. เลือก MFA inactive</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*Y7v0PTlz5QBx-kSbyUIUIQ.png" /></figure><p>7. กดปุ่ม Save changes</p><h4>เว็บไม่ถาม MFA แม้เปิดใช้แล้ว</h4><p><strong>สาเหตุ</strong>: Device tracking จำเครื่องไว้แล้ว</p><p><strong>วิธีแก้</strong>:</p><ul><li>ตัวเลือก<strong> 1</strong>: ปิด “Trust remembered devices” ใน Cognito Console</li><li>ตัวเลือก <strong>2</strong>: Forget device ของ user นั้น (Actions → Forget device)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*fIQHg8ypgi5XBUDblf82Rg.png" /></figure><h4>โค้ดถูกแต่ยัง error “Code mismatch”</h4><p><strong>สาเหตุที่เป็นไปได้</strong>:</p><ul><li>เวลาเครื่องไม่ตรง (TOTP ใช้ time-based)</li><li>ใช้โค้ดเดิมซ้ำ (แต่ละโค้ดใช้ได้ครั้งเดียว)</li><li>ตั้งค่า Cognito ไม่ถูก (ไม่ได้เปิด TOTP)</li></ul><p><strong>วิธีแก้</strong>:</p><ul><li>ตรวจเวลาบนมือถือให้ตรง (sync กับ network time)</li><li>รอโค้ดใหม่ (ประมาณ 30 วินาที)</li><li>ตรวจสอบ User Pool settings</li></ul><h3>Tips ความปลอดภัยตอนขึ้น Production</h3><h4>1. เก็บ Token ให้ปลอดภัย</h4><p>ใช้ HttpOnly Cookies (ตั้งฝั่ง server)</p><pre>// ✅ API Route (server-side only)<br>// pages/api/auth/set-token.ts<br>export default function handler(req, res) {<br>  res.setHeader(<br>    &quot;Set-Cookie&quot;,<br>    `authToken=${token}; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=3600`<br>  );<br>  res.status(200).json({ success: true });<br>}</pre><blockquote>⚠️ HttpOnly cookies <strong>ไม่สามารถตั้งจาก client-side JavaScript ได้</strong> — ต้องทำผ่าน API Route หรือ server response เท่านั้น</blockquote><h4>2. HTTPS Only</h4><pre>// next.config.ts<br>export default {<br>  async headers() {<br>    return [<br>      {<br>        source: &quot;/:path*&quot;,<br>        headers: [<br>          {<br>            key: &quot;Strict-Transport-Security&quot;,<br>            value: &quot;max-age=63072000; includeSubDomains; preload&quot;,<br>          },<br>        ],<br>      },<br>    ];<br>  },<br>};</pre><h4>แหล่งอ้างอิง</h4><ul><li><a href="https://docs.aws.amazon.com/cognito">Amazon Cognito</a></li><li><a href="https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-mfa.html">Adding MFA to a user pool</a></li><li><a href="https://github.com/gamertense/nextjs-amazon-cognito">GitHub Repository</a></li></ul><h3>สรุป</h3><p>เพิ่ม 2FA ด้วย Authenticator ทำให้ระบบคุณปลอดภัยขึ้นเยอะมากครับ ต่อให้รหัสผ่านหลุด ผู้โจมตีก็ยังต้องผ่านด่านโค้ดที่เปลี่ยนทุก 30 วินาทีอยู่ดี</p><p><strong>ใจความหลัก:</strong></p><ul><li>ความปลอดภัยเพิ่ม ไม่ยุ่งยากเกินไป</li><li>ผู้ใช้ตั้งค่าง่ายด้วย QR Code สแกนจบ</li><li>ปล่อยให้ Cognito ดูแลงานยากๆ (โทเคน / session / scale)</li><li>ถ้าเก็บ token ดี ก็พร้อมขึ้น production ได้เลยครับ</li></ul><p>ขอให้สนุกกับการทำ 2FA ครับ! 🔐</p><p>สำหรับใครที่กำลังมองหาทีมงานมืออาชีพในการพัฒนาซอฟต์แวร์หรือแอปพลิเคชันเพื่อนำไปใช้งานในองค์กร ที่ PALO IT เรามีทีมผู้เชี่ยวชาญด้าน Software Development และ Application Development พร้อมช่วยคุณตั้งแต่เริ่มต้นจนสามารถใช้งานได้จริง!</p><p><strong>บริการของเราครอบคลุม:</strong></p><ul><li>ออกแบบและพัฒนาซอฟต์แวร์ (Software Development) ตามความต้องการเฉพาะของธุรกิจคุณ</li><li>สร้างแอปพลิเคชัน (Application Development) ให้ตอบโจทย์การใช้งานขององค์กรในทุกมิติ</li><li>ปรับแต่งและดูแลระบบให้มีประสิทธิภาพสูง รองรับการขยายตัวของธุรกิจในอนาคต</li><li>ทดสอบและประเมินผลอย่างมืออาชีพ เพื่อให้มั่นใจว่าระบบของคุณใช้งานได้จริงและมีประสิทธิภาพ</li><li>ไม่ว่าคุณจะมีไอเดียใหม่ๆ หรือมีระบบอยู่แล้วที่อยากต่อยอด PALO IT พร้อมเป็น partner ที่จะช่วยให้คุณก้าวไปได้ไกลยิ่งขึ้น</li></ul><p>ทักไปที่เพจ Facebook: PALO IT Thailand ได้เลยครับ 🎉 (<a href="https://www.facebook.com/PALOITTH/">https://www.facebook.com/PALOITTH/</a>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17f503b75cd6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/palo-it-thailand/%E0%B9%80%E0%B8%9E%E0%B8%B4%E0%B9%88%E0%B8%A1%E0%B8%84%E0%B8%A7%E0%B8%B2%E0%B8%A1%E0%B8%9B%E0%B8%A5%E0%B8%AD%E0%B8%94%E0%B8%A0%E0%B8%B1%E0%B8%A2%E0%B8%94%E0%B9%89%E0%B8%A7%E0%B8%A2-two-factor-authentication-2fa-%E0%B8%9A%E0%B8%99-next-js-amazon-cognito-17f503b75cd6">เพิ่มความปลอดภัยด้วย Two-Factor Authentication (2FA) บน Next.js + Amazon Cognito</a> was originally published in <a href="https://medium.com/palo-it-thailand">PALO IT THAILAND</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[วิธีเปิดใช้ MFA และ SMS บน Amazon Cognito]]></title>
            <link>https://medium.com/palo-it-thailand/%E0%B8%A7%E0%B8%B4%E0%B8%98%E0%B8%B5%E0%B9%80%E0%B8%9B%E0%B8%B4%E0%B8%94%E0%B9%83%E0%B8%8A%E0%B9%89-mfa-%E0%B9%81%E0%B8%A5%E0%B8%B0-sms-%E0%B8%9A%E0%B8%99-amazon-cognito-daa68f2e5ef1?source=rss----3ae4f2a55b01---4</link>
            <guid isPermaLink="false">https://medium.com/p/daa68f2e5ef1</guid>
            <category><![CDATA[mfa]]></category>
            <category><![CDATA[sms]]></category>
            <category><![CDATA[amazon-cognito]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[amazon-web-services]]></category>
            <dc:creator><![CDATA[Vatcharat R.]]></dc:creator>
            <pubDate>Thu, 27 Nov 2025 13:59:39 GMT</pubDate>
            <atom:updated>2025-11-27T13:59:38.574Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yW8nhxeDMMYv-9cx4xVRIg.png" /></figure><p>บทความนี้แบ่งเป็นสองส่วนหลัก ๆ ครับ</p><p>1. วิธีออกจากโหมด SMS Sandbox ของ AWS SNS เพื่อส่งข้อความไปยังเบอร์ผู้ใช้จริง (ที่ไม่ได้เพิ่มเป็นเบอร์ทดสอบ)</p><p>2. การตั้งค่า Amazon Cognito ให้รองรับ MFA แบบเลือกใช้งาน (Optional) ทั้งแอป Authenticator (TOTP) และ SMS พร้อมฟีเจอร์จำเครื่อง (Trusted Device)</p><h3>ออกจาก AWS SMS Sandbox</h3><p>ถ้าอยากส่ง SMS ถึงผู้ใช้ทั่วไป (เบอร์ที่ไม่ได้ Verify) ต้องออกจาก Sandbox ก่อนครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j0tigcsZq8X7dAZl.png" /></figure><p>หลังจากกด “Exit SMS Sandbox” จะมีฟอร์มคำขอขึ้นมาแบบตัวอย่างด้านล่าง:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K3bhQLiBLAYhRDLW.png" /></figure><p>กรอกข้อมูลให้ครบและตรงตามจริง ถ้า AWS ต้องการรายละเอียดเพิ่ม เขาอาจถามประมาณนี้ เตรียมตอบไว้ล่วงหน้าจะเร็วขึ้นครับ</p><pre>Before we can evaluate your case, please reply and provide the following additional details:<br>- Company name:<br>- Company URL:<br>- AWS region:<br>- Requested Monthly spend (USD) [1]:<br>- SMS Service use-case information<br>    SMS service or program name:<br>    Company relationship to the SMS service (purpose &amp; how users opt in):<br>    SMS service or program website URL:<br>    Service opt-in location and process (app / website / form):<br>    Desired launch date:<br>    Origination identity to be used [2] (SenderID / LongCode / ShortCode / 10DLC):<br>        Is the identity registered or unregistered?<br>    Destination country/countries [3]:<br>    Message type (transactional / promotional):<br>    Expected messages per day:<br>    Expected messages per second [4]:<br>    Message templates (one per use case):<br>    URLs that will appear in messages (one per use case):<br>    If domains differ between your AWS account and the URLs used, explain the relationship:</pre><p>ตัวอย่างอีเมลตอบรับเมื่ออนุมัติ</p><blockquote>Thank you for submitting your request to increase your SMS monthly spending limits. Your new SMS monthly spending limit of $50 USD was implemented in Asia Pacific (Singapore) region…</blockquote><h3>ตั้งค่า Cognito สำหรับ MFA แบบเลือกใช้ (TOTP + SMS)</h3><p>ให้ผู้ใช้เปิด MFA เพิ่มเองได้ จะใช้แอป Authenticator หรือ SMS ก็ได้ อัปเดต phone_number ได้ และเครื่องที่เคยยืนยันสำเร็จครั้งหนึ่งสามารถข้าม MFA รอบต่อไปได้ (Trusted Device) ลด friction ครับ</p><p>สิ่งที่ควรมี (Prerequisites)</p><ul><li>สร้าง User Pool ไว้แล้ว</li><li>มี IAM Role ที่มีสิทธิ์ sns:Publish (สำหรับส่ง SMS) หรือเตรียมจะสร้างใหม่</li></ul><h4>ขั้นตอนที่ 1: เปิดสิทธิ์ Attribute phone_number</h4><p>1. ไปที่: User Pool → App clients → เลือก client ของคุณ</p><p>2. คลิก: “Set attribute read and write permissions”</p><p>3. เปิด:</p><p>- Read: <em>phone_number</em></p><p>- Write: <em>phone_number</em></p><p>เพื่อให้ frontend อ่านและแก้ไขเบอร์โทรของผู้ใช้สำหรับการลงทะเบียนรับ SMS ครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3VBLUeACAlxM2yzf.png" /></figure><h4>ขั้นตอนที่ 2: ตั้งค่า SMS Settings</h4><p>1. ไปที่: Authentication → Authentication methods → SMS</p><p>2. เลือก IAM role ที่มีสิทธิ์ <em>sns:Publish</em> (หรือสร้างใหม่)</p><p>3. กด Save</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6Nu0fDWLjjBWQf-l.png" /></figure><h4>ขั้นตอนที่ 3: เปิด Optional MFA</h4><p>1. ไปที่: Authentication → Sign-in → Multi-factor authentication</p><p>2. ตั้งค่า MFA configuration: Optional</p><p>3. เลือกประเภท MFA:</p><ul><li>Authenticator Apps (TOTP)</li><li>SMS message</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VFHoDbBy88LfXbPD.png" /></figure><h4>ขั้นตอนที่ 4: เปิด Device Tracking &amp; Trusted Devices</h4><p>1. ไปที่: Authentication → Sign-in → Device tracking</p><p>2. ตั้งค่า Tracking: Always remember</p><p>3. เปิด: “Allow users to bypass MFA for trusted devices”</p><p>ผลลัพธ์: เครื่องที่ผ่าน MFA สำเร็จแล้ว ครั้งถัดไปสามารถข้ามได้ (ถ้าไม่มีการ reset หรือ revoke) ช่วยให้ประสบการณ์ดีขึ้นครับ</p><h3>สรุป / เช็กลิสต์ตรวจสอบ</h3><ul><li>ออกจาก SMS Sandbox และได้วงเงินส่ง SMS แล้ว</li><li>App client เปิด Read/Write ให้ phone_number</li><li>ตั้งค่า SMS พร้อม IAM role ถูกต้อง</li><li>MFA เป็น Optional และเลือก TOTP + SMS</li><li>Device tracking เปิด และ Trusted bypass ทำงาน</li></ul><p>ตอนนี้ผู้ใช้สามารถเลือกเปิด MFA จะใช้ Authenticator หรือ SMS ก็ได้ และเครื่องที่เชื่อถือแล้วช่วยลดการถาม MFA ซ้ำ ๆ ครับ</p><p><strong>แหล่งอ้างอิง</strong></p><ul><li><a href="https://docs.aws.amazon.com/cognito">AWS Cognito User Pool Creation Guide</a></li><li><a href="https://docs.aws.amazon.com/sns/">AWS SNS SMS Sandbox Exit Process</a></li></ul><p>สำหรับใครที่กำลังมองหาทีมงานมืออาชีพในการพัฒนาซอฟต์แวร์หรือแอปพลิเคชันเพื่อนำไปใช้งานในองค์กร ที่ PALO IT เรามีทีมผู้เชี่ยวชาญด้าน Software Development และ Application Development พร้อมช่วยคุณตั้งแต่เริ่มต้นจนสามารถใช้งานได้จริง!</p><p><strong>บริการของเราครอบคลุม:</strong></p><ul><li>ออกแบบและพัฒนาซอฟต์แวร์ (Software Development) ตามความต้องการเฉพาะของธุรกิจคุณ</li><li>สร้างแอปพลิเคชัน (Application Development) ให้ตอบโจทย์การใช้งานขององค์กรในทุกมิติ</li><li>ปรับแต่งและดูแลระบบให้มีประสิทธิภาพสูง รองรับการขยายตัวของธุรกิจในอนาคต</li><li>ทดสอบและประเมินผลอย่างมืออาชีพ เพื่อให้มั่นใจว่าระบบของคุณใช้งานได้จริงและมีประสิทธิภาพ</li><li>ไม่ว่าคุณจะมีไอเดียใหม่ๆ หรือมีระบบอยู่แล้วที่อยากต่อยอด PALO IT พร้อมเป็น partner ที่จะช่วยให้คุณก้าวไปได้ไกลยิ่งขึ้น</li></ul><p>ทักไปที่เพจ Facebook: PALO IT Thailand ได้เลยครับ 🎉 (<a href="https://www.facebook.com/PALOITTH/">https://www.facebook.com/PALOITTH/</a>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=daa68f2e5ef1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/palo-it-thailand/%E0%B8%A7%E0%B8%B4%E0%B8%98%E0%B8%B5%E0%B9%80%E0%B8%9B%E0%B8%B4%E0%B8%94%E0%B9%83%E0%B8%8A%E0%B9%89-mfa-%E0%B9%81%E0%B8%A5%E0%B8%B0-sms-%E0%B8%9A%E0%B8%99-amazon-cognito-daa68f2e5ef1">วิธีเปิดใช้ MFA และ SMS บน Amazon Cognito</a> was originally published in <a href="https://medium.com/palo-it-thailand">PALO IT THAILAND</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[4 ยักษ์ใหญ่ IDE : Antigravity vs Cursor vs VS Code vs IntelliJ กับยุค AI]]></title>
            <link>https://medium.com/palo-it-thailand/4-%E0%B8%A2%E0%B8%B1%E0%B8%81%E0%B8%A9%E0%B9%8C%E0%B9%83%E0%B8%AB%E0%B8%8D%E0%B9%88-ide-antigravity-vs-cursor-vs-vs-code-vs-intellij-%E0%B8%81%E0%B8%B1%E0%B8%9A%E0%B8%A2%E0%B8%B8%E0%B8%84-ai-f2929f3e6edf?source=rss----3ae4f2a55b01---4</link>
            <guid isPermaLink="false">https://medium.com/p/f2929f3e6edf</guid>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[google-antigravity]]></category>
            <category><![CDATA[intellij]]></category>
            <category><![CDATA[cursor]]></category>
            <dc:creator><![CDATA[Warakron Kanthawong]]></dc:creator>
            <pubDate>Wed, 26 Nov 2025 06:52:16 GMT</pubDate>
            <atom:updated>2025-11-26T06:51:53.326Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AaMwJCMpuZOxdvYvUz4tbA.jpeg" /></figure><h3>4 ยักษ์ใหญ่ IDE : Antigravity vs Cursor vs VS Code vs IntelliJ กับยุค AI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NK2xUWTNbOU6u4ms3Nnvhw.png" /></figure><p>โลกของการเขียนโปรแกรมกำลังเปลี่ยนผ่านครั้งใหญ่ จากยุคที่เราต้อง “พิมพ์เองทุกบรรทัด” (Manual) เข้าสู่ยุค “AI ช่วยพิมพ์” (Copilot) และล่าสุดเรากำลังก้าวเข้าสู่ยุค <strong>“Agentic Workflow”</strong> หรือการให้ AI เป็นคนทำ โดยเราเป็นคนสั่งการ</p><p>วันนี้เราจะมาจับคู่ชก 4 ตัวตึงแห่งวงการ: <strong>IntelliJ</strong> (พี่ใหญ่สายแข็ง), <strong>VS Code</strong> (มาตรฐานโลก), <strong>Cursor</strong> (ผู้มาก่อนกาล), และน้องใหม่มาแรง <strong>Google Antigravity</strong></p><p>เริ่มจาก น้องใหม่กันก่อนเลยคือ <strong>Google Antigravity</strong> โดยจับคู่กับ Gemini 3 Pro</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fltN6YycdIbTa2fEI0BRmQ.png" /></figure><p>จากที่ได้ลองใช้มา ผมชอบ concept การ planning ก่อนที่จะ implement ซึ่งทำให้เราเห็นภาพรวมและขั้นตอนที่ AI จะทำต่อไป Antigravity ทำได้ค่อนข้างดีในส่วนนี้ รวมถึงความเร็วในการทำงานของ AI โดยรวมแล้วถือว่าค่อนข้างดี</p><p><strong>ข้อดี</strong></p><ul><li>AI ประมวลผลได้เร็ว</li><li>แรง</li><li>วางแผนงานก่อนลงมือทำ ทำให้เราเห็นภาพว่า AI จะทำอะไรต่อไปบ้าง</li><li>ตอนนี้ยังฟรี สามารถไปลองใช้งานกันได้ เพียงแค่มี Google account</li></ul><p><strong>ข้อเสีย</strong></p><ul><li>ยังอยู่ในช่วง Preview อาจมีบั๊กหรือความไม่เสถียร</li><li>ในอนาคตอาจมีค่าใช้จ่ายเพิ่มเติม</li></ul><p>ต่อมาใน IDE ตัวที่ 2 <strong>Cursor </strong>จับคู่กับ Composer 1 ซึ่งเป็น AI ของ Cursor เอง</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SPQuP_vNVzeaxL-ojwAgNw.png" /></figure><p>จากที่ได้ลอง ตัว Curosr มาก็เจอว่าต้องมี subscription ก่อนถึงจะเลือกใช้งาน agent ได้ แต่ code ที่ได้ค่อนข้างดี มีการแยกไฟล์ ระหว่าง component และ style โดยรวมแล้วค่อนข้างดีเช่นกัน</p><p><strong>ข้อดี</strong></p><ul><li>AI ประมวลผลได้เร็ว</li><li>แรง</li><li>ใช้งานค่อนข้างง่าย ไม่ได้มีตัวเลือก ซับซ้อน(แอบยากตอนเลือก agent ตอนแรก 555+ )</li><li>เข้าใจ context ได้ดี UI ทำออกมาได้ดีมาก</li></ul><p><strong>ข้อเสีย</strong></p><ul><li>ต้องจ่ายรายเดือน (20 USD) ถึงจะเลือก AI model ได้ และ</li><li>เขียน code เน้น style ไวๆ เกินไปจนเสีย structure ของ project</li></ul><p>ต่อมา VSCode ของ Microsoft มาคู่กับ GPT-5 ของทาง OpenAI</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BR7f1EjhosbO-EBlmL3Vpw.png" /></figure><p>IDE สุด classic ที่ผมเชื่อว่าแทบทุกคนเคยใช้ ผมได้ลอง GPT-5 ผ่านทาง github copilot แล้ว รู้สึกว่าช้า และให้ code ออกมาที่ ค่อนข้างแย่กว่า 2 ตัวที่ผ่านมา UI ทำออกมาได้ครึ่งๆกลางๆ เหมือนทำไม่เสร็จ อาจต้องให้ prompt ท่ีละเอียดถึงจะได้งานได้ดี</p><p><strong>ข้อดี</strong></p><ul><li>ใช้งานง่าย UI ดูเรียบง่าย</li><li>มี extension เป็น ล้านน ปรับแต่งได้ตามใจ</li></ul><p><strong>ข้อเสีย</strong></p><ul><li>ต้องจ่ายรายเดือน (10 USD) ถึงจะใช้ agent mode ได้</li><li>GitHub Copilot มันยังรู้สึกว่าเป็น “ส่วนเสริม” (Add-on) ไม่ได้หลอมรวมเป็นเนื้อเดียวกับ Editor เหมือน Cursor หรือ Antigravity อาจทำให้ ผลลัพธ์ไม่ดีสู้เจ้าอื่น</li></ul><p>ตัวสุดท้ายพี่ใหญ่ IntelliJ ผมเลือกตัว WebStrom มา กับ Junie AI ของทาง IntelliJ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uvoF-Hp5Q52fdXTMMvGT3g.png" /></figure><p>IDE สำหรับสายเก๋า และ เก่า 5555+ IntelliJ เป็น สำหรับมืออาชีพที่ต้องการความสมบูรณ์แบบและการจัดการโปรเจกต์ขนาดใหญ่ โดยรวมทำได้โอเค ระดับเดียวกับ VSCode มีความช้าบ้าง เพราะ กินแรมเยอะ ตัว AI ทำงานโอเค ออกไปทางกลางๆ อาจต้องการ prompt ที่ละเอียดแบบ GPT ถึงจะทำงานได้ดี</p><p><strong>ข้อดี</strong></p><ul><li>UI ใช้งาน style classic ของ IntelliJ ตัว IDE ทำงานได้ดี</li><li>Code suggestion ดีเยี่ยม</li><li>การจัดการ lib ค่อนข้างทำได้ง่าย</li></ul><p><strong>ข้อเสีย</strong></p><ul><li>ตัว IDE ค่อนข้างแพง และต้อง subscription รายปี (200 USD)</li><li>ให้ credit AI น้อยกว่าเจ้าอื่น</li><li>ราคา credit AI เสริมค่อนข้างแพง</li><li>Junnie เองยังทำงานได้ช้าและ UI ไม่ค่อยสวย</li></ul><p>ถ้าให้เลือกส่วนตัว ตอนนี้ก็คงเป็น Antigravity ของทาง Google ยอมรับว่า มาแรงจริงๆ</p><p>ผมได้เปรียบเทียบแบบคร่าวๆ ไว้แล้วลองดูกันเลยย</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q7lI7r09784iElXKLR1_9A.png" /></figure><p>สำหรับใครที่กำลังมองหาทีมงานมืออาชีพในการพัฒนาซอฟต์แวร์หรือแอปพลิเคชันเพื่อนำไปใช้งานในองค์กร ที่ PALO IT เรามีทีมผู้เชี่ยวชาญด้าน Software Development และ Application Development พร้อมช่วยคุณตั้งแต่เริ่มต้นจนสามารถใช้งานได้จริง!</p><p>บริการของเราครอบคลุม:</p><ul><li>ออกแบบและพัฒนาซอฟต์แวร์ (Software Development) ตามความต้องการเฉพาะของธุรกิจคุณ</li><li>สร้างแอปพลิเคชัน (Application Development) ให้ตอบโจทย์การใช้งานขององค์กรในทุกมิติ</li><li>ปรับแต่งและดูแลระบบให้มีประสิทธิภาพสูง รองรับการขยายตัวของธุรกิจในอนาคต</li><li>ทดสอบและประเมินผลอย่างมืออาชีพ เพื่อให้มั่นใจว่าระบบของคุณใช้งานได้จริงและมีประสิทธิภาพ</li><li>ไม่ว่าคุณจะมีไอเดียใหม่ๆ หรือมีระบบอยู่แล้วที่อยากต่อยอด PALO IT พร้อมเป็น partner ที่จะช่วยให้คุณก้าวไปได้ไกลยิ่งขึ้น</li></ul><p>ทักไปที่เพจ Facebook: <a href="https://www.facebook.com/PALOITTH/">PALO IT Thailand</a> ได้เลยครับ 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2929f3e6edf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/palo-it-thailand/4-%E0%B8%A2%E0%B8%B1%E0%B8%81%E0%B8%A9%E0%B9%8C%E0%B9%83%E0%B8%AB%E0%B8%8D%E0%B9%88-ide-antigravity-vs-cursor-vs-vs-code-vs-intellij-%E0%B8%81%E0%B8%B1%E0%B8%9A%E0%B8%A2%E0%B8%B8%E0%B8%84-ai-f2929f3e6edf">4 ยักษ์ใหญ่ IDE : Antigravity vs Cursor vs VS Code vs IntelliJ กับยุค AI</a> was originally published in <a href="https://medium.com/palo-it-thailand">PALO IT THAILAND</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[สร้าง ReAct Agent ด้วย Python]]></title>
            <link>https://medium.com/palo-it-thailand/%E0%B8%AA%E0%B8%A3%E0%B9%89%E0%B8%B2%E0%B8%87-react-agent-%E0%B8%94%E0%B9%89%E0%B8%A7%E0%B8%A2-python-8ded7805328a?source=rss----3ae4f2a55b01---4</link>
            <guid isPermaLink="false">https://medium.com/p/8ded7805328a</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Manatsawi Sutlaeo]]></dc:creator>
            <pubDate>Fri, 21 Nov 2025 08:40:30 GMT</pubDate>
            <atom:updated>2025-11-24T06:52:16.190Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V2EEyLravMYJMULTPbFExg.jpeg" /></figure><h3><strong>Table of content</strong></h3><p>ReAct Agent</p><ul><li><a href="#4fd2">ReAct Agent คืออะไร</a></li><li><a href="#a2e6">ตัวอย่าง Diagram ของ ReAct Agent</a></li><li><a href="#7400">เอกสารอ้างอิง ReAct Agent</a></li><li><a href="#dc2d">ตัวอย่างการประยุกต์ใช้</a></li></ul><p>ReAct + Chatbot ด้วย Python</p><ul><li>เ<a href="#f71a">ครื่องมือที่ใช้</a></li><li><a href="#c6e5">โครงสร้าง Diagram : ReAct + Chatbot</a></li><li><a href="#4f0e">ตัวอย่างโครงสร้าง Project</a></li><li><a href="#3f7b">Code</a></li><li><a href="#9dfd">ตัวอย่าง Log file การทำงานของ ReAct Agent</a></li></ul><p><a href="#5c3b">สรุป</a></p><p><a href="#723f">Link ตัวอย่างโค้ดแบบเต็มๆ</a></p><p>ในโลกที่ AI ถูกใช้แก้ปัญหาซับซ้อนมากขึ้น การให้ <strong>LLM แค่ตอบคำถาม</strong> อย่างเดียวอาจยังไม่พอ เพราะมันไม่สามารถรู้ข้อมูลใหม่ หรือตรวจสอบความถูกต้องของคำตอบได้ด้วยตัวเอง นี่จึงเป็นจุดเริ่มต้นของแนวคิด <strong>ReAct — Reason + Act</strong> ที่ทำให้ AI ไม่เพียง “คิดวิเคราะห์” แต่ยัง “ลงมือทำ” ได้จริง เช่น ค้นข้อมูล คำนวณ หรือใช้เครื่องมือภายนอก เพื่อให้ได้คำตอบที่ถูกต้องและมีเหตุผลมากขึ้น</p><h3><strong>ReAct </strong>Agent <strong>คืออะไร (ไม่ใช่ React Frontend Framework นะ)</strong></h3><p>มาทำความรู้จักกับ Concept ของ ReAct Agent กันแบบคร่าวๆ ว่าคืออะไร และมีประโยชน์อย่างไร สามารถนำไปประยุกต์ใช้ทำอะไรได้บ้าง</p><p>ถ้าเราพูดถึง “Agent” ในโลกของ AI ปัจจุบัน หมายถึงระบบที่สามารถ “คิดและลงมือทำ” ได้ด้วยตัวเอง โดยมีเป้าหมายหรือภารกิจบางอย่างที่เรามอบหมายให้ เช่น การตอบคำถาม, ค้นหาข้อมูล, วิเคราะห์เนื้อหา หรือแม้กระทั่งเขียนโค้ดแก้ปัญหา</p><blockquote><strong>ReAct ย่อมาจากคำว่า Reasoning + Acting</strong></blockquote><p>ซึ่งเป็นแนวคิดที่รวม “การให้เหตุผล (Reason)” และ “การลงมือทำ (Act)” เข้าด้วยกันในกระบวนการทำงานของ LLM (Large Language Model)</p><p>พูดง่ายๆ คือ ReAct Agent ไม่ได้แค่ “ตอบคำถาม” แบบปกติ แต่ยังสามารถ “วางแผนการคิด → ตัดสินใจ → เรียกใช้เครื่องมือภายนอก (tools)” แล้ว “นำผลลัพธ์กลับมาคิดต่อ” เพื่อให้ได้คำตอบที่แม่นยำและฉลาดขึ้น</p><p>ตัวอย่าง Diagram ของ ReAct Agent</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7aBUrdE0urXh56m1iq5RYQ.png" /></figure><h3>💡 ทำไมแนวคิดนี้ถึงน่าสนใจ</h3><p>ก่อนมีแนวคิด ReAct โมเดลมักจะทำได้เพียง “คาดเดาคำตอบ” จากข้อมูลใน prompt เท่านั้น</p><p>แต่ในโลกจริง ปัญหามักซับซ้อนกว่านั้น เช่น ต้องค้นข้อมูล, คำนวณ, หรือใช้ API ภายนอก ซึ่งโมเดลเดี่ยวๆ ทำไม่ได้</p><p>ReAct จึงเข้ามาเติมเต็มส่วนนี้ โดยให้โมเดลสามารถ</p><ol><li><strong>คิดเป็นลำดับขั้นตอน (Reasoning chain)</strong></li><li><strong>เลือกว่าจะทำอะไรต่อ (Action selection)</strong></li><li><strong>สรุปคำตอบ (Final Answer)</strong></li></ol><p>สามารถอ่านเพิ่มเติมเกี่ยวกับ ReAct Agent ได้ที่นี่</p><ol><li><a href="https://arxiv.org/abs/2210.03629">ReAct: Synergizing Reasoning and Acting in Language Models</a></li><li><a href="https://www.ibm.com/think/topics/react-agent">What is a ReAct agent?</a> (IBM)</li></ol><h3>ตัวอย่างการประยุกต์ใช้</h3><ol><li>Chatbot ที่สามารถค้นข้อมูลจากเว็บหรือฐานข้อมูลได้</li><li>Data Assistant ที่คำนวณหรือวิเคราะห์ข้อมูลจริงก่อนตอบ</li><li>Dev Agent ที่เขียนโค้ด ทดสอบ และดีบักแบบอัตโนมัติ</li><li>Workflow Agent ที่ประสานการทำงานหลายขั้นตอน เช่น สั่งงาน API, แปลภาษา, สร้างรายงาน ฯลฯ</li></ol><h3>โครงสร้างการทำงานของ ReAct Agent</h3><p>หัวใจของ ReAct Agent อยู่ที่ “วงจรการคิดและลงมือทำซ้ำๆ” ซึ่งประกอบด้วย 4 ขั้นตอนหลักคือ</p><p><strong>Reason → Action → Observation → Reason → … → Final Answer</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jlTLI982wpVFmKX36zjPow.png" /></figure><p>โมเดลจะเริ่มจากการ <em>ให้เหตุผล</em> (Reason) เพื่อวางแผนว่าจะทำอะไร จากนั้น <em>ลงมือทำ</em> (Action) เช่น ค้นข้อมูลหรือเรียกใช้เครื่องมือ แล้วนำผลที่ได้กลับมาเป็น <em>Observation</em> เพื่อคิดต่อว่าควรทำอะไรขั้นถัดไป จนกว่าจะได้คำตอบสุดท้ายที่มั่นใจ</p><p>ตัวอย่าง</p><blockquote><em>ผู้ใช้ถามว่า “ใครเป็นผู้ก่อตั้งบริษัท Tesla?”</em></blockquote><p>1️⃣ <strong>LLM Reason:</strong> “ตรวจสอบ context ก่อน เผื่อมีข้อมูลเกี่ยวกับผู้ก่อตั้งบริษัท Tesla”</p><p>2️⃣ <strong>Action:</strong> search_context(“ผู้ก่อตั้ง Tesla”)</p><p>3️⃣ <strong>Observation:</strong> “ไม่พบข้อมูลใน context”</p><p>4️⃣ <strong>Reason:</strong> “ต้องเรียกข้อมูลจาก Web search เพื่อให้คำตอบครบถ้วน”</p><p>5️⃣ <strong>Action:</strong> call_web_search(“ผู้ก่อตั้งบริษัท Tesla”)</p><p>6️⃣ <strong>Observation:</strong> “ผลจาก Web search : Elon Musk, Martin Eberhard และ Marc Tarpenning เป็นผู้ก่อตั้งบริษัท Tesla”</p><p>7️⃣ <strong>Reason:</strong> “นำข้อมูลนี้มาสรุปตอบผู้ใช้”</p><p>✅ <strong>Final Answer:</strong> “บริษัท Tesla ก่อตั้งโดย Elon Musk, Martin Eberhard และ Marc Tarpenning ครับ”</p><p>การ “วนลูป” แบบนี้สำคัญมาก เพราะทำให้ Agent <strong>ปรับกลยุทธ์ระหว่างทางได้เอง</strong> หากเจอข้อมูลไม่ครบหรือคำตอบยังไม่ชัดเจน</p><p>ในบทความนี้ เราจะลองสร้าง <strong>ReAct Agent แบบง่าย</strong> สำหรับ Chatbot ที่สามารถ “หาคำตอบจาก context ที่ให้มา (Mock Document ที่ได้จาก ระบบ RAG)”</p><p>และถ้าไม่เจอคำตอบใน context ก็จะ “หาข้อมูลเพิ่มเติมจาก web search” ก่อนสรุปผลให้ผู้ใช้ —</p><p>นั่นแหละคือพลังของแนวคิด <em>Reason + Act</em> ที่ทำให้ Chatbot ฉลาดขึ้นอีกระดับ 🚀</p><h3><strong>ReAct + Chatbot ด้วย Python</strong></h3><p><strong>เครื่องมือที่ใช้</strong></p><p><strong>Python</strong></p><ul><li>ใช้เป็นภาษาโปรแกรมหลักสำหรับสร้าง ReAct Agent</li><li>ทำงานได้ทั้งการเรียก LLM, จัดการ RAG (ในบทความนี้เราจะ Mock ในส่วน RAG System), และ Web search</li></ul><p><strong>LLM (Large Language Model) — ในที่นี้เราจะใช้ </strong>Google Gemini (มี Free quota)</p><ul><li>ทำหน้าที่ <strong>Reasoning + Generation</strong> ของ Agent</li><li>รับ input เป็น context จาก RAG และ user prompt</li><li>ต้องใช้ API key นะ สร้างได้จาก Link นี้ &gt; <a href="https://ai.google.dev/gemini-api/docs/api-key">สร้าง API KEY</a></li></ul><p><strong>Document / Mock RAG (Static Knowledge)</strong></p><ul><li>เก็บข้อมูลจำลอง (Markdown / JSON)</li><li>Agent ใช้ <strong>search_context()</strong> เลือกข้อมูลเพื่อทำ Reasoning</li></ul><p><strong>Web search — DuckDuckGo (ddgs)</strong></p><ul><li>ใช้สำหรับเรียกค้นหาข้อมูลบนเว็ปไซต์</li><li>ไม่ต้องใช้ API Key</li></ul><p>โครงสร้าง Diagram : ReAct + Chatbot</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wdajFIe2NF_-yLe1HLAnuA.png" /></figure><p>ตัวอย่างโครงสร้าง Project</p><pre><br>```<br>basic-re-act-python/<br>├── main.py                      # Entry point และ main execution<br>├── react_agent.py               # Core ReAct Agent implementation<br>├── agent_actions.py             # Agent actions และ tools<br>├── rag.py                       # RAG (Retrieval-Augmented Generation) system<br>├── constants.py                 # Configuration และ API keys<br>├── requirements.txt             # Python dependencies<br>├── LICENSE                      # Project license<br>└── data/<br>    └── mock_rag_document.md     # Mock knowledge base<br>```</pre><p>ลองไปดูรายละเอียดในแต่ละไฟล์กัน ว่าจะมีฟังก์ชั่นอะไรบ้างอยู่ข้างใน (ก่อนเขียนโค้ดเต็มๆ)</p><p>ไฟล์ : requirements.txt<br>Python Library ที่จะใช้ใน Project</p><pre>google-generativeai<br>ddgs</pre><p>Install :</p><pre>pip install -r requirements.txt</pre><p>ไฟล์ : constant.py</p><p>เก็บค่า API KEY และ LLM Model Name</p><p><a href="https://ai.google.dev/gemini-api/docs/api-key">สร้าง API KEY</a></p><pre>GOOGLE_GEMINI_API_KEY = &quot;&lt;your-api-key&gt;&quot;<br>GOOGLE_GEMINI_MODEL_NAME = &quot;gemini-2.5-flash&quot;</pre><p>ไฟล์ : data/mock_rag_document.md</p><p>Mock Knowledge Base ในระบบ RAG System</p><pre># Company HR Information Database<br><br>## 1. Leave Policies<br>All employees are entitled to 15 days of annual leave per year. For employees with more than 5 years of service, they will receive an additional 1 day per year, up to a maximum of 20 days per year. Sick leave entitlement is 30 days per year with a medical certificate. Special leave such as maternity leave, ordination leave, and personal leave can be consulted with HR.<br><br>Leave applications must be submitted through the HR Online system at least 3 days in advance, except for emergency sick leave cases. Consecutive leave exceeding 3 days must be approved by the supervisor and HR. Leave during festivals or high season must be planned in advance and receive special approval. Employees can accumulate up to 5 days of leave to carry over to the following year.<br><br>---<br><br>## 2. Employee Benefits<br>The company provides comprehensive benefits for employees and their families. Health insurance covers 100% for employees and 80% for family members. Life insurance of 1 million baht, accident insurance of 500,000 baht, and provident fund with 5% company contribution.<br><br>Additional benefits include monthly attendance allowance, travel allowance, phone allowance, internet allowance, annual bonus (depending on company performance), bereavement assistance, birthday gifts, and 20% discount on company products. Employees also receive rights to skills development training, budget for purchasing books and online courses, and opportunities for career advancement.<br><br>---<br><br>## 3. Company Policies<br>The company adheres to principles of good governance and business ethics. Employees must comply with anti-bribery policies, avoid conflicts of interest, and maintain company confidentiality. Use of company equipment and resources must be for business purposes only.<br><br>Workplace safety policies require employees to wear personal protective equipment, report accidents immediately, and participate in annual safety training. The company has a No Smoking Area policy throughout the building and promotes a safe working environment, environmental consciousness, and Work-Life Balance policy for employees&#39; mental well-being.<br><br>---<br><br>## 4. Working Hours &amp; Holidays<br>Standard working hours are Monday-Friday 08:30-17:30 with lunch break 12:00-13:00, totaling 8 hours per day. Employees can choose Flexible Working Hours between 07:30-16:30 or 09:30-18:30 according to job requirements. Overtime work requires prior approval and will be compensated according to labor law.<br><br>Annual holidays follow the government calendar, including New Year&#39;s Day, Songkran Festival, Labor Day, Royal Celebration Day, Father&#39;s Day, Mother&#39;s Day, and Royal Birthday. Additionally, the company provides 2 special holidays: pre-Songkran holiday and New Year special holiday. Employees can use Work From Home 2 days per week according to the new policy.<br><br>---<br><br>## 5. Performance Review &amp; Career Development<br>Performance evaluations are conducted every 6 months using a 360 Degree Feedback system that includes evaluations from supervisors, colleagues, and internal customers. Evaluation criteria include Key Performance Indicators (KPIs), Core Competencies, and Leadership Skills. Evaluation results will be linked to salary adjustments, bonuses, and promotion opportunities.<br><br>The company has long-term personnel development plans (Career Path) for all positions. Employees will receive Individual Development Plans (IDP) and have opportunities to participate in Training Programs both within and outside the organization. The company supports further education and professional licensing, has Mentoring and Job Rotation systems to enhance experience, and provides opportunities for cross-departmental work for career advancement.</pre><p>ไฟล์: rag.py</p><ul><li>rag_load_context : โหลด Mock knowledge base</li><li>rag_search_context: Mock search context</li></ul><pre># rag.py<br>from typing import List, Dict<br><br>def rag_load_context(file_path: str) -&gt; List[Dict[str, str]]:<br>    &quot;&quot;&quot;<br>    อ่านไฟล์ Markdown และแยกเป็น sections<br>    - file_path: path ของ Markdown file<br>    Return: list ของ document [{&#39;title&#39;: ..., &#39;content&#39;: ...}]<br>    Note:<br>        แต่ละ section เริ่มด้วย ## และสามารถมี separator --- <br>        ฟังก์ชันนี้ใช้สำหรับเตรียมข้อมูล Mock RAG<br>    &quot;&quot;&quot;<br>    pass  # logic การอ่านไฟล์และแยก section จะใส่ในเวอร์ชันจริง<br><br>def rag_search_context(query: str, top_k: int = 1) -&gt; List[Dict[str, str]]:<br>    &quot;&quot;&quot;<br>    ค้นหา context จาก Mock RAG<br>    - query: คำค้นหา<br>    - top_k: จำนวน document ที่ต้องการคืนค่า<br>    Return: list ของ document ที่เกี่ยวข้องที่สุด<br>    Note:<br>        - ใช้ rag_load_context() เพื่อโหลด document<br>        - คำนวณความเกี่ยวข้องแบบง่าย (title + content match)<br>    &quot;&quot;&quot;<br>    pass  # logic การค้นหา context จะใส่ในเวอร์ชันจริง<br><br># ------------------------<br># ตัวอย่างการใช้งาน (abstract)<br># ------------------------<br>if __name__ == &quot;__main__&quot;:<br>    query = &quot;Amazon&quot;<br>    results = rag_search_context(query, top_k=2)<br>    for r in results:<br>        print(f&quot;Title: {r[&#39;title&#39;]}&quot;)<br>        print(f&quot;Content preview: {r[&#39;content&#39;][:200]}...&quot;)</pre><p>ไฟล์ : agent_actions.py</p><p>Actions ที่ ReAct Agent จะสามารถเรียกได้</p><pre># agent_actions.py<br>from typing import Dict, List<br><br>def search_context(query: str, top_k: int = 1) -&gt; List[Dict[str, str]]:<br>    &quot;&quot;&quot;<br>    Action: ค้นหาข้อมูลจาก Mock RAG Knowledge Base<br>    - query: คำถามหรือ keyword ของผู้ใช้<br>    - top_k: จำนวน document ที่ต้องการคืนค่า<br>    Return:<br>        list ของ document ที่เกี่ยวข้อง [{&#39;title&#39;: ..., &#39;content&#39;: ...}]<br>    Note:<br>        ฟังก์ชันนี้จะใช้ RAG system (mock) เพื่อจำลอง retrieval<br>    &quot;&quot;&quot;<br>    pass  # จะใส่ logic ของ search_context ในไฟล์ rag.py<br><br>def call_web_search(query: str, max_results: int = 2) -&gt; str:<br>     &quot;&quot;&quot;<br>    Action: ค้นหาข้อมูลจากเว็บโดยใช้ DuckDuckGo<br>    - query: ข้อความคำถามที่ต้องการค้นหา<br>    - max_results: จำนวนผลการค้นหาที่ต้องการคืนค่า<br>    Return: สรุปข้อความที่รวมผลลัพธ์อันดับต้นๆ<br>    &quot;&quot;&quot;<br>    pass</pre><p>ไฟล์ : react_agent.py</p><p>Workflow ของ ReAct Agent</p><pre># react_agent.py<br>from typing import List, Dict<br>from agent_actions import search_context, call_wiki_api<br>from rag import rag_search_context<br><br>class ReActAgent:<br>    def __init__(self):<br>        &quot;&quot;&quot;<br>        Initialize ReAct Agent<br>        &quot;&quot;&quot;<br>        pass<br><br>    def reason(self, user_input: str, observations: List[str]) -&gt; str:<br>        &quot;&quot;&quot;<br>        LLM Reasoning step<br>        - user_input: ข้อความคำถามจากผู้ใช้<br>        - observations: list ของผลลัพธ์จาก Action ก่อนหน้า<br>        Return: string -&gt; prompt/คำสั่งสำหรับ Action หรือ final answer<br>        Note:<br>            ใน abstract version จะยังไม่เรียก LLM จริง<br>            สามารถ mock output เพื่อสาธิต flow<br>        &quot;&quot;&quot;<br>        pass<br><br>    def act(self, action_type: str, query: str):<br>        &quot;&quot;&quot;<br>        Action step<br>        - action_type: &#39;search_context&#39;, &#39;web_search&#39;, &#39;final_answer&#39;<br>        - query: ข้อมูลสำหรับ Action<br>        Return: observation (ผลลัพธ์ของ Action)<br>        Note:<br>            - &#39;search_context&#39; -&gt; เรียก rag_search_context() ของ Mock RAG<br>            - &#39;web_search&#39; -&gt; search query for the internet<br>            - &#39;final_answer&#39; -&gt; ใช้รวบรวม observations เป็น answer<br>        &quot;&quot;&quot;<br>        pass<br><br>    def run(self, user_input: str) -&gt; str:<br>        &quot;&quot;&quot;<br>        ตัว Flow หลักของ ReAct Agent<br>        Reason -&gt; Action -&gt; Observation -&gt; Reason -&gt; Final Answer<br>        Return: final_answer (string)<br>        Note:<br>            - สามารถ loop หลายรอบได้ (multi-step reasoning)<br>            - ใน abstract version จะ mock flow เพื่อสาธิต<br>        &quot;&quot;&quot;<br>        pass</pre><p>ไฟล์ : main.py</p><p>สำหรับ เรียกใช้งาน ReAct Agent</p><pre># main.py<br>from react_agent import ReActAgent<br><br>def main():<br>    &quot;&quot;&quot;<br>    ตัวรันหลักของ ReAct Agent<br>    - สร้าง Agent instance<br>    - รับ input จากผู้ใช้<br>    - เรียก Agent.run() และแสดง Final Answer<br>    &quot;&quot;&quot;<br>    # 1️⃣ สร้าง ReAct Agent<br>    agent = ReActAgent()<br><br>    # 2️⃣ รับ input จากผู้ใช้ (ตัวอย่าง)<br>    user_query = input(&quot;Query: &quot;)<br><br>    # 3️⃣ เรียก Agent.run() → ได้ Final Answer<br>    final_answer = agent.run(user_query)<br><br>    # 4️⃣ แสดงผล<br>    print(&quot;\n=== Final Answer ===&quot;)<br>    print(final_answer)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h3><strong>เริ่ม Implement Code กันเลย</strong></h3><h3><strong>rag.py</strong></h3><p>สำหรับ Project ReAct Agent ของเราจะข้ามเรื่อง RAG System ไปโดยจะทำการจำลอง (Mock) Search Context จาก static data ที่เตรียมไว้แทน</p><p>สามารถค้นหาเพิ่มเติมได้ว่า RAG คืออะไร (ในบทความนี้เราจะข้ามขั้นตอนนี้ไป)</p><pre>from typing import List, Dict<br>import re<br><br>def rag_load_context(file_path: str) -&gt; List[Dict[str, str]]:<br>    &quot;&quot;&quot;<br>    อ่านไฟล์ Markdown และแยกเป็น sections<br>    แต่ละ section จะคืนค่าเป็น dict {&#39;title&#39;: ..., &#39;content&#39;: ...}<br>    Assumption: แต่ละ section เริ่มด้วย ## และข้อมูลแยกด้วย ---<br>    &quot;&quot;&quot;<br>    documents = []<br>    current_doc = None<br><br>    with open(file_path, &#39;r&#39;, encoding=&#39;utf-8-sig&#39;) as f:<br>        for line in f:<br>            line = line.strip()<br>            <br>            # ข้าม header หลัก &quot;# Knowledge Base&quot;<br>            if line.startswith(&quot;# &quot;):<br>                continue<br>                <br>            # เริ่ม section ใหม่ที่ขึ้นต้นด้วย ##<br>            if line.startswith(&quot;## &quot;):<br>                if current_doc:<br>                    # ล้าง --- ออกจากท้าย content<br>                    current_doc[&quot;content&quot;] = current_doc[&quot;content&quot;].strip()<br>                    documents.append(current_doc)<br>                <br>                title = line[3:].strip()  # เอา &quot;## &quot; ออก<br>                current_doc = {&quot;title&quot;: title, &quot;content&quot;: &quot;&quot;}<br>            <br>            # ข้ามเส้น separator ---<br>            elif line == &quot;---&quot;:<br>                continue<br>            <br>            # เพิ่มเนื้อหาถ้ามี section ปัจจุบัน และไม่ใช่บรรทัดว่าง<br>            elif current_doc is not None and line:<br>                current_doc[&quot;content&quot;] += line + &quot;\n&quot;<br><br>    # append last section<br>    if current_doc:<br>        current_doc[&quot;content&quot;] = current_doc[&quot;content&quot;].strip()<br>        documents.append(current_doc)<br><br>    return documents<br><br>def rag_search_context(query: str, top_k: int = 1) -&gt; List[Dict[str, str]]:<br>    &quot;&quot;&quot;<br>    ค้นหา context จาก Mock RAG<br>    - query: คำค้นหา (string)<br>    - top_k: จำนวน document ที่ต้องการคืนค่า<br>    คืนค่าเป็น list ของ document ที่เกี่ยวข้องที่สุด<br>    &quot;&quot;&quot;<br>    <br>    # โหลดเอกสารทั้งหมดจาก Mock RAG database<br>    rag_docs = rag_load_context(&quot;data/mock_rag_document.md&quot;)<br>    <br>    # แปลงคำค้นหาเป็นตัวพิมพ์เล็กเพื่อการเปรียบเทียบที่ไม่สนใจตัวพิมพ์ใหญ่เล็ก    <br>    query_lower = query.lower()<br>    scored_docs = []<br><br>    # วนลูปผ่านเอกสารทั้งหมดเพื่อหาความเกี่ยวข้อง<br>    for doc in rag_docs:<br>        # นับจำนวนครั้งที่คำค้นหาปรากฏใน title และ content (ไม่สนใจตัวพิมพ์ใหญ่เล็ก)<br>        title_score = len(re.findall(re.escape(query_lower), doc[&quot;title&quot;].lower()))<br>        content_score = len(re.findall(re.escape(query_lower), doc[&quot;content&quot;].lower()))<br>        # คำนวณคะแนนรวม โดยให้น้ำหนัก title มากกว่า content เป็น 2 เท่า<br>        score = title_score * 2 + content_score<br>        <br>        # เก็บเฉพาะเอกสารที่มีคะแนนมากกว่า 0 (มีความเกี่ยวข้อง)<br>        if score &gt; 0:<br>            scored_docs.append((score, doc))<br><br>    # เรียงลำดับเอกสารตามคะแนนจากมากไปน้อย<br>    scored_docs.sort(key=lambda x: x[0], reverse=True)<br><br>    # คืนค่าเอกสาร top_k อันดับแรกที่เกี่ยวข้องที่สุด<br>    return [doc for _, doc in scored_docs[:top_k]]<br><br># ------------------------<br># ตัวอย่างการใช้งาน<br># ------------------------<br>if __name__ == &quot;__main__&quot;:<br>    # ค้นหา context<br>    query = &quot;Amazon&quot;<br>    results = rag_search_context(query, top_k=2)<br><br>    for r in results:<br>        print(f&quot;Title: {r[&#39;title&#39;]}&quot;)<br>        print(f&quot;Content preview: {r[&#39;content&#39;][:200]}...\n&quot;)</pre><h3>1. rag_load_context</h3><p><strong>หน้าที่หลัก:</strong></p><ul><li>อ่านไฟล์ Markdown ที่เก็บ knowledge base ของ Mock RAG</li><li>แยกแต่ละ section (เริ่มด้วย ##) ออกเป็น document แต่ละอัน</li><li>คืนค่าเป็น <strong>list ของ dict</strong> แต่ละ dict มี title และ content</li></ul><p><strong>รายละเอียด:</strong></p><ul><li>ข้าม header หลัก (# Knowledge Base)</li><li>ข้าม separator ( — -)</li><li>รวมทุกบรรทัดของ section เป็น string เดียว (content)</li><li>append section สุดท้ายหลัง loop เสร็จ</li></ul><p>Return:</p><pre>[<br>    {&quot;title&quot;: &quot;ชื่อหัวข้อ&quot;, &quot;content&quot;: &quot;เนื้อหาของ section&quot;},<br>    ...<br>]</pre><h3>2. rag_search_context</h3><p><strong>หน้าที่หลัก:</strong></p><ul><li>ค้นหา document ที่เกี่ยวข้องที่สุดกับ query จาก Mock RAG</li><li>ใช้ scoring แบบง่าย: match keyword กับ <strong>title + content</strong></li></ul><p><strong>รายละเอียด:</strong></p><ol><li>โหลด Mock RAG ผ่าน rag_load_context()</li><li>แปลง query เป็น lowercase</li><li>วนดูทุก document:</li></ol><ul><li>นับจำนวน keyword ใน <strong>title</strong> → weight 2</li><li>นับจำนวน keyword ใน <strong>content</strong> → weight 1</li><li>รวมเป็น score document</li></ul><p>4. sort document ตาม score ลดหลั่น</p><p>5. return <strong>top_k document</strong></p><p><strong>Return:</strong></p><ul><li>list ของ document ที่เกี่ยวข้องที่สุด เช่น:</li></ul><pre>[<br>    {&quot;title&quot;: &quot;Amazon Company&quot;, &quot;content&quot;: &quot;...&quot;},<br>    {&quot;title&quot;: &quot;Amazon Rainforest&quot;, &quot;content&quot;: &quot;...&quot;}<br>]</pre><p>ภาพรวม flow ของ RAG ในไฟล์นี้</p><pre>Markdown file --&gt; rag_load_context() --&gt; list of documents<br>User query --&gt; rag_search_context() --&gt; top_k documents</pre><h3><strong>agent_actions.py</strong></h3><h3>หน้าที่หลัก</h3><ul><li>ไฟล์นี้ทำหน้าที่เป็น <strong>“Action Layer”</strong> ของระบบ ReAct Agent</li><li>เป็นส่วนที่ใช้ <strong>เชื่อมต่อกับระบบค้นหาภายนอก (Web Search)</strong> และ <strong>ฐานความรู้ภายใน (RAG System)</strong></li><li>โดยแต่ละ action จะถูกเรียกจากคลาส ReActAgent เมื่อ LLM ตัดสินใจเลือกขั้นตอนการทำงาน (เช่น search_context หรือ web_search)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XxNy-JGOnnpy8SVoOF7AJg.png" /></figure><pre># agent_actions.py<br>from typing import Dict, List<br>from rag import rag_search_context  # เรียกฟังก์ชันจาก rag.py<br>from ddgs import DDGS<br><br>def search_context(query: str, top_k: int = 1) -&gt; List[Dict[str, str]]:<br>    &quot;&quot;&quot;<br>    Action: ค้นหาข้อมูลจาก Mock RAG Knowledge Base<br>    - query: คำถามหรือ keyword ของผู้ใช้<br>    - top_k: จำนวน document ที่ต้องการคืนค่า<br>    Return:<br>        list ของ document ที่เกี่ยวข้อง [{&#39;title&#39;: ..., &#39;content&#39;: ...}]<br>    Note:<br>        ฟังก์ชันนี้ใช้ RAG system (mock) เพื่อจำลอง retrieval<br>    &quot;&quot;&quot;<br>    # เรียกใช้ฟังก์ชันค้นหาจาก RAG system และส่งคืนผลลัพธ์<br>    return rag_search_context(query, top_k=top_k)<br><br><br>def call_web_search(query: str, max_results: int = 2) -&gt; str:<br>    &quot;&quot;&quot;<br>    Action: Web search using DuckDuckGo<br>    - query: search query string<br>    - max_results: number of search results to return<br>    Return: plain text summary combining top results<br>    &quot;&quot;&quot;<br>    try:<br>        # ใช้ DuckDuckGo API เพื่อค้นหาข้อมูลจากอินเทอร์เน็ต<br>        with DDGS() as ddgs:<br>            # ค้นหาและแปลงผลลัพธ์เป็น list<br>            results = list(ddgs.text(query, max_results=max_results))<br>        <br>        # ตรวจสอบว่าพบข้อมูลหรือไม่<br>        if not results:<br>            return &quot;No relevant information found on the web.&quot;<br>        <br>        # รวมผลการค้นหาหลายๆ รายการเป็นข้อความเดียว<br>        combined = &quot; | &quot;.join([r[&#39;body&#39;] for r in results if &#39;body&#39; in r])<br>        return combined<br>    except Exception as e:<br>        # จัดการข้อผิดพลาดที่อาจเกิดขึ้นระหว่างการค้นหา<br>        return f&quot;Error during web search: {e}&quot;</pre><h3>1. search_context</h3><p><strong>หน้าที่หลัก:</strong></p><p>ค้นหาข้อมูลที่เกี่ยวข้องจากระบบฐานความรู้ภายใน (RAG system) ตามคำถามหรือคีย์เวิร์ดที่ผู้ใช้ป้อนมา</p><p><strong>รายละเอียด:</strong></p><ul><li>ฟังก์ชันนี้จะเรียกใช้งาน rag_search_context() จากไฟล์ rag.py</li><li>เป็นการจำลอง (mock) ระบบ Retrieval-Augmented Generation (RAG) เพื่อค้นหาเอกสารที่มีเนื้อหาเกี่ยวข้องกับคำถาม</li><li>ใช้ในกรณีที่ LLM ตัดสินใจว่า “ข้อมูลอาจมีอยู่ในฐานความรู้ภายใน” โดยไม่ต้องออกไปค้นเว็บจริง</li></ul><p><strong>Parameter:</strong></p><ul><li>query — ข้อความคำถามหรือคีย์เวิร์ดที่ต้องการค้นหา</li><li>top_k — จำนวนเอกสารสูงสุดที่ต้องการให้คืนกลับ</li></ul><p><strong>Return:</strong></p><pre>[<br>    {<br>        &quot;title&quot;: &quot;ชื่อเอกสาร&quot;,<br>        &quot;content&quot;: &quot;เนื้อหาในเอกสาร&quot;<br>    },<br>    ...<br>]</pre><h3>2. call_web_search</h3><p><strong>หน้าที่หลัก:</strong></p><p>ค้นหาข้อมูลจากอินเทอร์เน็ตผ่าน DuckDuckGo Search API (ผ่านไลบรารี ddgs)</p><p><strong>รายละเอียด:</strong></p><ul><li>ใช้เมื่อ LLM ตัดสินใจว่า “คำถามต้องการข้อมูลอัปเดต หรือข้อมูลที่อยู่นอกฐานความรู้”</li><li>ฟังก์ชันนี้จะดึงผลการค้นหาจาก DuckDuckGo และรวมเนื้อหาหลายรายการเข้าด้วยกันเป็นข้อความเดียว</li><li>ถ้าการค้นหาไม่สำเร็จ จะส่งข้อความแสดงข้อผิดพลาดกลับแทน</li></ul><p><strong>Parameter:</strong></p><ul><li>query — คำค้นที่ต้องการค้นหา</li><li>max_results — จำนวนผลลัพธ์สูงสุดที่ต้องการรวมในคำตอบ</li></ul><p><strong>Return:</strong></p><p>ข้อความสรุปผลลัพธ์จากการค้นหา (plain text) เช่น:</p><pre>&quot;Tesla, Inc. is an American electric vehicle company founded in 2003... | Elon Musk joined Tesla later as an investor...&quot;</pre><h3><strong>react_agent.py</strong></h3><p><strong>หน้าที่หลักของไฟล์:</strong></p><ul><li>เป็น <strong>ReAct Agent core</strong> ของระบบ</li><li>จัดการ flow ของ <strong>Reason → Action → Observation → Reason → Final Answer</strong></li><li>ใช้ <strong>Agent Actions</strong> เช่น search_context และ call_web_search เป็น Action step</li><li>เพื่อให้ได้คำตอบที่ถูกต้องและครบถ้วนที่สุด โดย Agent จะประเมินสถานการณ์ในแต่ละรอบ ตัดสินใจว่าจะค้นจาก knowledge base, ค้นจากเว็บ หรือสร้างคำตอบสุดท้าย จากนั้นจะวนซ้ำไปจนกว่าจะได้คำตอบที่สมบูรณ์</li></ul><pre># react_agent.py<br>from typing import List, Dict<br>from agent_actions import search_context, call_web_search<br>from constants import GOOGLE_GEMINI_API_KEY, GOOGLE_GEMINI_MODEL_NAME<br><br>import google.generativeai as genai<br>import json<br>import re<br>import os<br>from datetime import datetime<br><br># ตั้งค่า Google Gemini API<br>genai.configure(api_key=GOOGLE_GEMINI_API_KEY)<br>gemini_client = genai.GenerativeModel(GOOGLE_GEMINI_MODEL_NAME)<br><br><br>class ReActAgent:<br>    def __init__(self, max_steps: int = 5, enable_logging: bool = True):<br>        self.observations: List[str] = []<br>        self.max_steps = max_steps<br>        self.enable_logging = enable_logging<br>        self.log_lines: List[str] = []<br><br>    # -------------------------<br>    # Logging helpers<br>    # -------------------------<br>    def log(self, message: str):<br>        if self.enable_logging:<br>            self.log_lines.append(message)<br>            print(message)<br><br>    # -------------------------<br>    # Save log to file (output data/debug/&lt;file&gt;.md)<br>    # -------------------------<br>    def save_log(self):<br>        output_dir = &quot;data/debug&quot;<br>        timestamp = datetime.now().strftime(&quot;%Y%m%d_%H%M%S&quot;)<br>        filepath = f&quot;{output_dir}/react_agent_log_{timestamp}.md&quot;<br>        <br>        # สร้างโฟลเดอร์ถ้ายังไม่มี<br>        os.makedirs(output_dir, exist_ok=True)<br>        <br>        with open(filepath, &quot;w&quot;, encoding=&quot;utf-8&quot;) as f:<br>            f.write(&quot;\n&quot;.join(self.log_lines))<br><br>    # -------------------------<br>    # Reasoning step<br>    # -------------------------<br>    def reason(self, user_input: str, observations: List[str], step: int) -&gt; Dict[str, str]:<br>        &quot;&quot;&quot;<br>        LLM reasoning - let AI decide what to do based on the query type and current observations<br>        &quot;&quot;&quot;<br><br>        # -------------------------<br>        # Clean ข้อมูล observations สำหรับ input ของ LLM<br>        # -------------------------<br>        # กรองเอา HTML tags ออกและไม่รวม &quot;FINAL_STEP&quot; <br>        obs_texts = [re.sub(r&quot;&lt;[^&gt;]+&gt;&quot;, &quot;&quot;, o) for o in observations if o != &quot;FINAL_STEP&quot;]<br>        # รวมข้อความทั้งหมดเป็นข้อความเดียว<br>        obs_text = &quot; &quot;.join(obs_texts)<br>        # ลบช่องว่างเกินและทำให้เป็นรูปแบบมาตรฐาน<br>        obs_text = re.sub(r&quot;\s+&quot;, &quot; &quot;, obs_text).strip()<br><br>        # สร้าง prompt สำหรับให้ LLM ตัดสินใจ<br>        prompt = f&quot;&quot;&quot;<br>        You are a ReAct Agent AI assistant. Analyze the current situation and decide the next action.<br>        <br>        Current observations: {obs_text if obs_text else &quot;No observations yet&quot;}<br>        User question: {user_input}<br>        Current step: {step}<br><br>        Available actions:<br>        - &#39;search_context&#39; if you need to search the internal knowledge base/RAG system for relevant information<br>        - &#39;web_search&#39; if you need additional current/external information from the internet<br>        - &#39;final_answer&#39; if you have sufficient information to provide a complete answer<br><br>        Decision criteria:<br>        - If no observations yet, consider what type of information is needed first<br>        - If observations exist, evaluate if they provide sufficient information<br>        - Consider whether the question requires real-time/current information vs historical/factual information<br>        - Think about the most logical sequence of actions to answer the question effectively<br>        <br>        Respond in JSON format: {{ &quot;action&quot;: &quot;...&quot;, &quot;query&quot;: &quot;...&quot; }}<br>        <br>        Query field should contain:<br>        - For &#39;search_context&#39;: search keywords or phrases for the knowledge base<br>        - For &#39;web_search&#39;: search query for the internet<br>        - For &#39;final_answer&#39;: the original user question being answered<br>        &quot;&quot;&quot;<br>        try:<br>            # เรียกใช้ Gemini AI เพื่อตัดสินใจการกระทำต่อไป<br>            response = gemini_client.generate_content(<br>                prompt,<br>                generation_config=genai.types.GenerationConfig(<br>                    temperature=0.2,  # ใช้ความสร้างสรรค์ปานกลาง<br>                    max_output_tokens=500  # จำกัด token สำหรับการตอบกลับ<br>                )<br>            )<br><br>            # ดึงข้อความจาก response<br>            text = getattr(response, &quot;text&quot;, None)<br>            if not text:<br>                raise ValueError(&quot;No text returned from LLM&quot;)<br>            # ลบ code block markers ออกจาก JSON response<br>            text = re.sub(r&quot;^```json|```$&quot;, &quot;&quot;, text, flags=re.MULTILINE).strip()<br>            # แปลง JSON string เป็น dictionary<br>            decision = json.loads(text)<br>        except Exception as e:<br>            # หากเกิดข้อผิดพลาดให้บันทึกและใช้การตัดสินใจ default<br>            self.log(f&quot;Error parsing LLM response: {e}&quot;)<br>            decision = {&quot;action&quot;: &quot;final_answer&quot;, &quot;query&quot;: user_input}<br><br>        return decision<br><br>    # -------------------------<br>    # Action step<br>    # -------------------------<br>    def act(self, action_type: str, query: str, user_input: str = None) -&gt; str:<br>        &quot;&quot;&quot;<br>        Execute action and return observation<br>        &quot;&quot;&quot;<br>        # ตรวจสอบประเภทของ action_type ที่ต้องการทำ<br>        if action_type == &quot;search_context&quot;:<br>            # ค้นหาข้อมูลในฐานความรู้ภายใน (RAG system) โดยใช้คำค้นหา<br>            docs = search_context(query, top_k=2) <br>            if docs:<br>                # สร้างสรุปเอกสารที่พบจากการค้นหา<br>                doc_summaries = [f&quot;Title: {doc[&#39;title&#39;]}, Content: {doc[&#39;content&#39;]}&quot; for doc in docs]<br>                obs = f&quot;Found {len(docs)} relevant document(s) in knowledge base: &quot; + &quot;; &quot;.join(doc_summaries)<br>            else:<br>                # ไม่พบข้อมูลที่เกี่ยวข้องในฐานความรู้ภายใน (RAG system)<br>                obs = &quot;No relevant information found in the internal knowledge base&quot;<br>        elif action_type == &quot;web_search&quot;:<br>            # ค้นหาข้อมูลจากอินเทอร์เน็ต โดยใช้คำค้นหา<br>            obs = call_web_search(query)<br>        elif action_type == &quot;final_answer&quot;:<br>            # สร้างคำตอบสุดท้ายโดยใช้ข้อมูลทั้งหมดที่รวบรวมได้<br>            obs = self.generate_final_answer(user_input or query)<br>        else:<br>            # ประเภทการกระทำที่ไม่รู้จัก<br>            obs = f&quot;Unknown action: {action_type}&quot;<br><br>        # บันทึกผลการสังเกตลงในรายการ observations<br>        self.observations.append(obs)<br>        return obs<br><br>    # -------------------------<br>    # Final answer generation<br>    # -------------------------<br>    def generate_final_answer(self, user_input: str) -&gt; str:<br>        &quot;&quot;&quot;<br>        Generate final answer based on all current observations (true ReAct pattern)<br>        &quot;&quot;&quot;<br>        # Clean ข้อมูล observations โดยลบ HTML tags ออก<br>        obs_texts = [re.sub(r&quot;&lt;[^&gt;]+&gt;&quot;, &quot;&quot;, o) for o in self.observations]<br>        # รวมข้อความทั้งหมดเป็นข้อความเดียว<br>        obs_text = &quot; &quot;.join(obs_texts)<br>        # ลบช่องว่างที่ไม่จำเป็นและ normalize ข้อความ<br>        obs_text = re.sub(r&quot;\s+&quot;, &quot; &quot;, obs_text).strip()<br><br>        # ตรวจสอบว่ามีข้อมูลจาก observations หรือไม่<br>        if not obs_text or obs_text.strip() == &quot;&quot;:<br>            # กรณีไม่มีข้อมูลจาก observations ให้ตอบคำถามโดยตรง<br>            prompt = f&quot;&quot;&quot;<br>            Please provide a helpful, direct answer to this user question:<br><br>            {user_input}<br><br>            Provide a clear, informative response in 2-3 sentences.<br>            &quot;&quot;&quot;<br>        else:<br>            # กรณีมีข้อมูลจาก observations ให้ใช้ข้อมูลนั้นในการตอบ<br>            prompt = f&quot;&quot;&quot;<br>            Based on the information gathered, provide a clear final answer:<br><br>            Question: {user_input}<br>            Information gathered: {obs_text}<br><br>            Provide a complete answer in 2-3 clear sentences.<br>            &quot;&quot;&quot;<br><br>        try:<br>            # เรียกใช้ Gemini AI เพื่อสร้างคำตอบสุดท้าย<br>            response = gemini_client.generate_content(<br>                prompt,<br>                generation_config=genai.types.GenerationConfig(<br>                    temperature=0.1,  # ใช้ temperature ต่ำเพื่อความแม่นยำ<br>                    max_output_tokens=2000  # จำกัดจำนวน token สูงสุด<br>                )<br>            )<br>            <br>            # ดึงข้อความคำตอบจาก response<br>            final_answer = getattr(response, &quot;text&quot;, None)<br>            if not final_answer:<br>                raise ValueError(&quot;No text returned from LLM&quot;)<br>            <br>            # ส่งคืนคำตอบพร้อมกับ prefix &quot;FINAL_ANSWER: &quot;<br>            return f&quot;FINAL_ANSWER: {final_answer}&quot;<br>                <br>        except Exception as e:<br>            # จัดการข้อผิดพลาดและบันทึก log<br>            self.log(f&quot;Error generating final answer: {type(e).__name__}: {e}&quot;)<br>            return f&quot;FINAL_ANSWER: Unable to generate final answer due to error: {e}&quot;<br><br><br><br>    # -------------------------<br>    # Main agent flow<br>    # -------------------------<br>    def run(self, user_input: str) -&gt; str:<br>        # เริ่มต้นการทำงานใหม่โดยเคลียร์ข้อมูลเก่า<br>        self.observations = []<br>        self.log_lines = []<br>        # สร้าง log header สำหรับการทำงานครั้งนี้<br>        self.log(f&quot;# ReAct Agent Log&quot;)<br>        self.log(f&quot;**Generated:** {datetime.now().strftime(&#39;%Y-%m-%d %H:%M:%S&#39;)}&quot;)<br>        self.log(f&quot;**User Query:** {user_input}\n&quot;)<br>        self.log(f&quot;## 🚀 Starting ReAct Agent Process\nMaximum Steps: {self.max_steps}\n&quot;)<br>        <br>        # วนลูปทำงานตามจำนวนขั้นตอนสูงสุดที่กำหนด<br>        for step in range(1, self.max_steps + 1):<br>            # ให้ LLM ตัดสินใจการกระทำต่อไปตามสถานการณ์ปัจจุบัน<br>            decision = self.reason(user_input, self.observations, step)<br>            action_type = decision.get(&quot;action&quot;, &quot;final_answer&quot;)<br>            query = decision.get(&quot;query&quot;, user_input)<br>            <br>            # บันทึก log สำหรับขั้นตอนนี้<br>            self.log(f&quot;# Step {step}/{self.max_steps}&quot;)<br>            self.log(f&quot;**Thought:** LLM decided to perform &#39;{action_type}&#39; action&quot;)<br>            self.log(f&quot;**Action:** {action_type}&quot;)<br>            self.log(f&quot;**Query:** {query}&quot;)<br><br>            # ดำเนินการตามที่ LLM ตัดสินใจและรับผลการสังเกต<br>            obs = self.act(action_type, query, user_input)<br>            self.log(f&quot;**Observation:** {obs}\n&quot;)<br><br>            # ตรวจสอบว่าได้คำตอบสุดท้ายแล้วหรือไม่<br>            if action_type == &quot;final_answer&quot;:<br>                # ดึงคำตอบสุดท้ายจากผลการสังเกต (รูปแบบ ReAct แท้จริง)<br>                if obs.startswith(&quot;FINAL_ANSWER: &quot;):<br>                    final_answer = obs[14:]  # ลบ prefix &quot;FINAL_ANSWER: &quot; ออก<br>                    self.log(f&quot;=== Final Answer ===\n{final_answer}\n&quot;)<br>                    self.save_log()<br>                    return final_answer<br>                break<br><br>        # กรณีที่จบลูปโดยไม่มีการทำ final_answer action (fallback)<br>        self.log(&quot;⚠️  Agent reached maximum steps without final_answer action&quot;)<br>        self.log(&quot;🔄  Forcing final answer generation...\n&quot;)<br>        <br>        # บังคับสร้างคำตอบสุดท้าย<br>        fallback_obs = self.generate_final_answer(user_input)<br>        if fallback_obs.startswith(&quot;FINAL_ANSWER: &quot;):<br>            fallback_answer = fallback_obs[14:]  # ลบ prefix &quot;FINAL_ANSWER: &quot; ออก<br>            self.log(f&quot;=== Fallback Answer ===\n{fallback_answer}\n&quot;)<br>            self.save_log()<br>            return fallback_answer<br>        else:<br>            # กรณีพิเศษ: แม้แต่ generate_final_answer ก็ล้มเหลว<br>            error_msg = f&quot;Unable to generate answer after {self.max_steps} steps&quot;<br>            self.log(f&quot;❌ {error_msg}&quot;)<br>            self.save_log()<br>            return error_msg<br><br><br># ------------------------<br># Example usage<br># ------------------------<br>if __name__ == &quot;__main__&quot;:<br>    agent = ReActAgent()<br>    <br>    # Test with a question that might benefit from internal knowledge first<br>    question = &quot;Employee Benefits&quot;<br>    print(&quot;Testing with question:&quot;, question)<br>    answer = agent.run(question)</pre><h3><strong>1. __init__()</strong></h3><p><strong>หน้าที่หลัก:</strong></p><p>ใช้สำหรับเตรียมค่าเริ่มต้นของ Agent เช่น จำนวนรอบสูงสุดที่ให้ทำงาน (max_steps) การเปิด/ปิดระบบ log และสร้างตัวแปรเก็บข้อมูลภายใน</p><p><strong>รายละเอียด:</strong></p><ul><li>สร้าง list สำหรับเก็บ observations (สิ่งที่พบในแต่ละขั้นตอน)</li><li>เปิดหรือปิด logging ได้ผ่าน enable_logging</li><li>ตั้งค่า default ของจำนวนรอบสูงสุด</li></ul><p><strong>Return:</strong></p><ul><li>ไม่มี (เป็น constructor ของคลาส)</li></ul><h3><strong>2. log()</strong></h3><p><strong>หน้าที่หลัก:</strong></p><p>ใช้สำหรับบันทึกข้อความ log ของแต่ละขั้นตอน</p><p><strong>รายละเอียด:</strong></p><ul><li>ถ้าเปิดโหมด logging จะเพิ่มข้อความลงใน self.log_lines</li><li>แสดงข้อความออกทาง console</li></ul><p><strong>Return:</strong></p><ul><li>ไม่มี</li></ul><h3><strong>3. save_log()</strong></h3><p><strong>หน้าที่หลัก:</strong></p><p>บันทึก log การทำงานของ Agent ทั้งหมดลงไฟล์ markdown เพื่อใช้วิเคราะห์ย้อนหลัง</p><p><strong>รายละเอียด:</strong></p><ul><li>สร้างโฟลเดอร์ data/debug อัตโนมัติถ้ายังไม่มีตั้งชื่อไฟล์ตามเวลาปัจจุบัน</li><li>เขียนข้อความ log ที่บันทึกไว้ทั้งหมดลงไฟล์</li></ul><p><strong>Return:</strong></p><ul><li>ไม่มี</li></ul><h3><strong>4. reason()</strong></h3><p><strong>หน้าที่หลัก:</strong></p><p>ให้ LLM วิเคราะห์สถานการณ์ปัจจุบันและตัดสินใจว่าจะทำ action อะไรต่อไป</p><p><strong>รายละเอียด:</strong></p><ul><li>รวม observations ทั้งหมดที่ผ่านการ clean แล้ว</li><li>สร้าง prompt โดยมีรายละเอียดของ user_input, current observations และ step ปัจจุบัน</li><li>เรียกใช้ Gemini (Generative AI) เพื่อให้ตอบกลับเป็น JSON ที่ระบุว่า action ถัดไปคืออะไร</li><li>หาก parsing JSON ล้มเหลว จะ fallback เป็น “final_answer”</li></ul><p><strong>Return:</strong></p><pre>Dictionary ในรูป { &quot;action&quot;: &quot;...&quot;, &quot;query&quot;: &quot;...&quot; }</pre><h3><strong>5. act()</strong></h3><p><strong>หน้าที่หลัก:</strong></p><p>ทำการ “ลงมือทำ” ตาม action ที่ LLM ตัดสินใจไว้</p><p><strong>รายละเอียด:</strong></p><ul><li>ถ้า action = “search_context” → ค้นข้อมูลจากฐานความรู้ภายใน (RAG)</li><li>ถ้า action = “web_search” → เรียก DuckDuckGo เพื่อค้นข้อมูลจากอินเทอร์เน็ต</li><li>ถ้า action = “final_answer” → เรียก generate_final_answer() เพื่อสร้างคำตอบสุดท้าย</li><li>ผลลัพธ์แต่ละขั้นตอนจะถูกเพิ่มใน self.observations</li></ul><p><strong>Return:</strong></p><pre>ข้อความ observation ที่เกิดจากการทำ action</pre><h3><strong>6. generate_final_answer()</strong></h3><p><strong>หน้าที่หลัก:</strong></p><p>สร้างคำตอบสุดท้ายโดยใช้ข้อมูลทั้งหมดที่ Agent รวบรวมได้</p><p><strong>รายละเอียด:</strong></p><ul><li>รวมและ clean ข้อมูลจาก observations</li><li>ถ้าไม่มีข้อมูลเลย จะให้ LLM ตอบคำถามโดยตรง</li><li>ถ้ามีข้อมูลจากการค้นหา จะให้ LLM ใช้ข้อมูลนั้นในการสรุปคำตอบ</li><li>ใช้ Gemini สร้างคำตอบสุดท้ายในรูปข้อความ</li></ul><p><strong>Return:</strong></p><pre>ข้อความในรูปแบบ &quot;FINAL_ANSWER: &lt;ข้อความคำตอบ&gt;&quot;</pre><h3><strong>7. run()</strong></h3><p><strong>หน้าที่หลัก:</strong></p><p>เป็นฟังก์ชันหลักที่ควบคุมวงจรการทำงานของ Agent ตั้งแต่เริ่มจนได้คำตอบสุดท้าย</p><p><strong>รายละเอียด:</strong></p><ul><li>เริ่มต้น log ใหม่และตั้งค่า observations ว่าง</li><li>วน loop ตามจำนวน max_steps</li><li>ให้ LLM reason → ตัดสินใจ action → เรียก act() เพื่อทำ</li><li>ถ้าเจอ “final_answer” จะหยุดและคืนคำตอบ</li><li>ถ้าหมดรอบแล้วยังไม่มีคำตอบ จะบังคับให้ generate_final_answer()</li><li>ทุกขั้นตอนมีการบันทึก log ลงไฟล์</li></ul><p><strong>Return:</strong></p><pre>คำตอบสุดท้ายจาก Agent ในรูปแบบข้อความ</pre><h3><strong>ตัวอย่าง Log file การทำงานของ ReAct Agent</strong></h3><ol><li>แบบที่เรียก search_context แล้วเจอคำตอบเลย</li></ol><pre># ReAct Agent Log<br>**Generated:** 2025-10-14 18:28:26<br>**User Query:** Company Policies<br><br>## 🚀 Starting ReAct Agent Process<br>Maximum Steps: 5<br><br># Step 1/5<br>**Thought:** LLM decided to perform &#39;search_context&#39; action<br>**Action:** search_context<br>**Query:** Company Policies<br>**Observation:** Found 1 relevant document(s) in knowledge base: Title: 3. Company Policies, Content: The company adheres to principles of good governance and business ethics. Employees must comply with anti-bribery policies, avoid conflicts of interest, and maintain company confidentiality. Use of company equipment and resources must be for business purposes only.<br>Workplace safety policies require employees to wear personal protective equipment, report accidents immediately, and participate in annual safety training. The company has a No Smoking Area policy throughout the building and promotes a safe working environment, environmental consciousness, and Work-Life Balance policy for employees&#39; mental well-being.<br><br># Step 2/5<br>**Thought:** LLM decided to perform &#39;final_answer&#39; action<br>**Action:** final_answer<br>**Query:** Company Policies<br>**Observation:** FINAL_ANSWER: The company policies are built on principles of good governance and business ethics, requiring employees to comply with anti-bribery measures, avoid conflicts of interest, maintain confidentiality, and use company resources solely for business purposes. Workplace safety is paramount, mandating the use of personal protective equipment, immediate accident reporting, and participation in annual safety training, alongside a strict No Smoking Area policy. Furthermore, the company promotes environmental consciousness and supports employee well-being through a Work-Life Balance policy.<br><br>=== Final Answer ===<br>The company policies are built on principles of good governance and business ethics, requiring employees to comply with anti-bribery measures, avoid conflicts of interest, maintain confidentiality, and use company resources solely for business purposes. Workplace safety is paramount, mandating the use of personal protective equipment, immediate accident reporting, and participation in annual safety training, alongside a strict No Smoking Area policy. Furthermore, the company promotes environmental consciousness and supports employee well-being through a Work-Life Balance policy.</pre><p>2. แบบที่เรียก search_context ก่อน แต่ยังไม่เจอคำตอบ &gt; LLM ตัดสินใจ เรียก call_web_search &gt; เจอคำตอบ</p><pre># ReAct Agent Log<br>**Generated:** 2025-10-14 18:30:34<br>**User Query:** Python programming language<br><br>## 🚀 Starting ReAct Agent Process<br>Maximum Steps: 5<br><br># Step 1/5<br>**Thought:** LLM decided to perform &#39;search_context&#39; action<br>**Action:** search_context<br>**Query:** Python programming language overview<br>**Observation:** No relevant information found in the internal knowledge base<br><br># Step 2/5<br>**Thought:** LLM decided to perform &#39;web_search&#39; action<br>**Action:** web_search<br>**Query:** Python programming language<br>**Observation:** Python is a high-level, general-purpose programming language. Its design philosophy emphasizes code readability with the use of significant indentation.Python is dynamically type-checked and garbage-collected. It supports multiple programming paradigms, including structured (particularly procedural), object-oriented and functional programming.Guido van Rossum began working on Python in the late 1980s as a successor to the ABC programming language. Python 3.0, released in 2008, was a major revision and not completely backward-compatible with earlier versions. Recent versions, such as Python 3.13, 3.12 and older (and 3.14), have added capabilities and keywords for typing (and more; e.g. increasing speed); helping with (optional) static typing. Currently only versions in the 3.x series are supported.Python consistently ranks as one of the most popular programming languages, and it has gained widespread use in the machine learning community. It is widely taught as an introductory programming language. | The official home of the Python Programming Language<br><br># Step 3/5<br>**Thought:** LLM decided to perform &#39;final_answer&#39; action<br>**Action:** final_answer<br>**Query:** Python programming language<br>**Observation:** FINAL_ANSWER: Python is a high-level, general-purpose programming language known for its design philosophy emphasizing code readability through significant indentation. It is dynamically type-checked, supports multiple programming paradigms, and consistently ranks as one of the most popular languages, widely used in machine learning and as an introductory language. Developed by Guido van Rossum, only Python 3.x versions are currently supported, with recent updates enhancing capabilities like optional static typing.<br><br>=== Final Answer ===<br>Python is a high-level, general-purpose programming language known for its design philosophy emphasizing code readability through significant indentation. It is dynamically type-checked, supports multiple programming paradigms, and consistently ranks as one of the most popular languages, widely used in machine learning and as an introductory language. Developed by Guido van Rossum, only Python 3.x versions are currently supported, with recent updates enhancing capabilities like optional static typing.</pre><p>ไฟล์ react_agent.py คือหัวใจหลักของระบบ <strong>ReAct Agent </strong>ซึ่งออกแบบให้ AI สามารถ “คิดเป็นขั้นตอน (Reason)” และ “ลงมือทำ (Act)” ได้อย่างมีตรรกะ โดยไม่จำกัดเพียงการตอบตรงคำถามเท่านั้น แต่ยังสามารถวางแผนการค้นคว้า ตัดสินใจเลือกแหล่งข้อมูลที่เหมาะสม และสร้างคำตอบสุดท้ายที่มีบริบทครบถ้วนที่สุด</p><p>การทำงานของ Agent จะมีโครงสร้างแบบวนลูป ได้แก่</p><ol><li>วิเคราะห์บริบทปัจจุบัน (reason)</li><li>ตัดสินใจเลือกการกระทำ (search_context, web_search, หรือ final_answer)</li><li>ลงมือทำจริง (act)</li><li>ประเมินผลลัพธ์และบันทึก (observation)</li><li>วนซ้ำจนได้คำตอบที่สมบูรณ์ (generate_final_answer)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*kXiDBgswATETVFSM5EAl_w.png" /></figure><h3><strong>สรุป</strong></h3><blockquote><em>บทความนี้อธิบายโครงสร้างและการทำงานของ</em><strong><em> ReAct Agent</em></strong><em> — ตัวกลางที่เชื่อมระหว่างกระบวนการ “คิดวิเคราะห์และตัดสินใจ” ของ LLM กับการ “ลงมือปฏิบัติ” ผ่านชุด Action เช่น search_context และ web_search ระบบนี้ช่วยให้ AI สามารถวางแผน เลือกวิธีแก้ปัญหา และสรุปคำตอบได้อย่างมีลำดับขั้น</em></blockquote><p>“Reason + Act + Observe”</p><p>เราได้สร้างต้นแบบ ReAct Agent ด้วย Python ที่สามารถ:</p><p>✅ อ่าน context จาก knowledge base (RAG)</p><p>✅ ค้นหาข้อมูลภายนอกจากเว็บจริง</p><p>✅ รวมผลลัพธ์มาสรุปเป็นคำตอบสุดท้าย</p><p>เพื่อให้ผลลัพธ์ที่ได้มีความแม่นยำและอิงข้อมูลจริง สุดท้าย Agent จะรวมผลการค้นหาทั้งหมดมาเรียบเรียงเป็นคำตอบสุดท้ายที่กระชับและครบถ้วน ถือเป็นแนวทางสำคัญในการสร้าง <strong>LLM Agent ที่มีความสามารถในการคิดและเรียนรู้จากกระบวนการของตนเอง</strong></p><p>จากการลองลงมือทำตามด้านบนทำให้เราเข้าใจเบื้องหลัง หลักการทำงานของ ReAct Agent มากยิ่งขึ้น</p><p>ซึ่ง Concept นี้ก็อยู่เบื้องหลังการทำงานของ AI Assistant Tools ดังๆ มากมายในระดับ Design คือ <strong>ReAct-based reasoning system</strong> เช่น <strong>GitHub Copilot, etc.</strong></p><p>จริงๆ มี Library ที่ช่วยจัดการเรื่องพวกนี้ให้อยู่เหมือนกันนะเช่น LangChain, LlamaIndex, etc.</p><blockquote>ตัวอย่างโค้ดแบบเต็มๆ : <a href="https://github.com/GLOBAL-PALO-IT/th_PALO-LLM-Basic-ReAct-python">GitHub Repository</a></blockquote><p>สำหรับใครที่กำลังมองหาวิธีสร้าง RAG Application หรือ Chatbot เพื่อใช้งานในองค์กร ที่ <strong>PALO IT</strong> เรามีทีมผู้เชี่ยวชาญพร้อมช่วยตั้งแต่เริ่มต้นจนระบบใช้งานได้จริง! ไม่ว่าจะเป็น</p><ul><li>Data Cleaning — เตรียมข้อมูลให้สะอาด พร้อมใช้งาน เพื่อผลลัพธ์ที่แม่นยำ</li><li>RAG Optimisation — ปรับแต่งระบบให้ตอบไว ตรงประเด็น และพร้อมรองรับการใช้งานระดับองค์กร</li><li>Evaluation — ทดสอบและวัดผลลัพธ์ของโมเดล เพื่อให้มั่นใจว่า RAG ของคุณตอบได้ดีจริง</li></ul><p>ไม่ว่าคุณจะเพิ่งเริ่มต้น หรือมีระบบอยู่แล้วและอยากต่อยอด เราพร้อมเป็น partner ที่จะช่วยให้คุณไปได้ไกลกว่าเดิม</p><p>ทักไปที่เพจ Facebook: <a href="https://www.facebook.com/PALOITTH/"><strong>PALO IT Thailand</strong></a> ได้เลยครับ 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ded7805328a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/palo-it-thailand/%E0%B8%AA%E0%B8%A3%E0%B9%89%E0%B8%B2%E0%B8%87-react-agent-%E0%B8%94%E0%B9%89%E0%B8%A7%E0%B8%A2-python-8ded7805328a">สร้าง ReAct Agent ด้วย Python</a> was originally published in <a href="https://medium.com/palo-it-thailand">PALO IT THAILAND</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Figma Make - อย่าพึ่งเริ่มโปรเจกต์ ถ้ายังไม่รู้จัก AI Design Tool ที่เปลี่ยนเกมของ Dev และ Designer]]></title>
            <link>https://medium.com/palo-it-thailand/figma-make-%E0%B8%AD%E0%B8%A2%E0%B9%88%E0%B8%B2%E0%B8%9E%E0%B8%B6%E0%B9%88%E0%B8%87%E0%B9%80%E0%B8%A3%E0%B8%B4%E0%B9%88%E0%B8%A1%E0%B9%82%E0%B8%9B%E0%B8%A3%E0%B9%80%E0%B8%88%E0%B8%81%E0%B8%95%E0%B9%8C-%E0%B8%96%E0%B9%89%E0%B8%B2%E0%B8%A2%E0%B8%B1%E0%B8%87%E0%B9%84%E0%B8%A1%E0%B9%88%E0%B8%A3%E0%B8%B9%E0%B9%89%E0%B8%88%E0%B8%B1%E0%B8%81-ai-design-tool-%E0%B8%97%E0%B8%B5%E0%B9%88%E0%B9%80%E0%B8%9B%E0%B8%A5%E0%B8%B5%E0%B9%88%E0%B8%A2%E0%B8%99%E0%B9%80%E0%B8%81%E0%B8%A1%E0%B8%82%E0%B8%AD%E0%B8%87-dev-%E0%B9%81%E0%B8%A5%E0%B8%B0-designer-70af158b024e?source=rss----3ae4f2a55b01---4</link>
            <guid isPermaLink="false">https://medium.com/p/70af158b024e</guid>
            <category><![CDATA[figma-make]]></category>
            <category><![CDATA[dev]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[figma]]></category>
            <category><![CDATA[prototyping]]></category>
            <dc:creator><![CDATA[Thanapat Juthavantana]]></dc:creator>
            <pubDate>Tue, 11 Nov 2025 02:01:04 GMT</pubDate>
            <atom:updated>2025-11-11T02:01:04.652Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2wNjkV_5S403OgU95bw0LQ.jpeg" /></figure><h3>Figma Make — เครื่องมือ AI Design Tool ที่พลิกโฉมการทำงานของทีม Dev และ Design</h3><blockquote>ถ้าคุณเป็น dev เคยไหมครับเวลาอยากทำ side project หรือต้องทำ PoC เร็วๆ แต่ไม่มี designer มาช่วย</blockquote><blockquote>หรือถ้าคุณคือ non-dev เช่น project manager, product owner ที่อยากทำ prototype ออกมาให้ทีมดูไว ๆ แต่ต้องมานั่งงมวิธีการใช้ Figma จนเสียเวลากว่าเดิม</blockquote><p>ผมเป็นคนหนึ่งที่เจอปัญหาแบบนี้เหมือนกัน จนกระทั่งได้มาเจอกับ “Figma Make” — AI assistant tool ตัวใหม่จาก Figma ที่ทำให้ dev หรือ manager แทบจะเหมือนมี designer เทพ ๆ ส่วนตัวเลยทีเดียว 😎</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AhnrhsTXknxqHervo4Xnsg.gif" /></figure><p>สวัสดีเพื่อน ๆ ทุกคนนะครับ ผมภัทรครับ <br>เป็น software developer ที่บริษัท PALO IT</p><p>ในช่วงเดือนที่ผ่านมา ผมได้มีโอกาสลงโปรเจ็กต์ร่วมกับทีมที่ Australia เลยได้รู้จักและลองใช้ Figma Make จริงจังเป็นครั้งแรก บอกเลยว่ามันเปลี่ยนขั้นตอนการทำงานของผมไปเลยโดยสิ้นเชิง</p><p>โดยเฉพาะเวลาเราขึ้นโปรเจกต์ใหม่ ที่เป็น <strong>PoC (Proof of Concept)</strong> หรือ <strong>side project </strong>ที่ไม่ได้มี designer มาช่วย แต่ก็อยากให้ UX/UI ออกมาดี</p><p><strong>ก่อนมี Figma Make ชีวิตมันเป็นแบบนี้…</strong></p><ul><li>ต้องเสียเวลานั่งวาด wireframe เอง</li><li>ถ้าอยากได้ design ที่มากกว่า wireframe ก็ต้องมาฝึกใช้ Figma เอง แถมยังต้องจัดการเรื่อง responsive อีก ซึ่งส่วนใหญ่ก็ไม่ค่อยสวยเท่า designer ทำ (ที่จริงเรียกว่าไม่สวยเลยดีกว่า 555)</li><li>ถ้าไม่ทำ design พอเริ่มเขียนโค้ดส่วน frontend ก็จะจินตนาการยากว่า component ไหนควรอยู่ตรงไหน จะมีกี่หน้า หรือ flow จะเป็นยังไง</li><li>เวลาใช้ Copilot ช่วยเขียนโค้ด ก็ต้อง prompt อธิบายยาวมาก แต่ผลที่ได้มักไม่ตรงใจ ต้อง prompt ซ้ำ ๆ</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*EvAPHxwhy-zNSmSsiJFk9Q.gif" /><figcaption>Depression sad cat</figcaption></figure><p>แต่ทั้งหมดนี้ สามารถแก้ได้ ด้วย Figma Make!! ช่วยลดเวลาการทำ prototype หรือสร้างดีไซน์สำหรับ prototype ได้จากหลักวันเหลือหลักชั่วโมงเท่านั้น</p><h3>What is “Figma Make”?</h3><p>Figma Make พึ่งเปิดตัวเมื่อเดือนพฤษภาคม 2025 ที่ผ่านมา ซึ่งตอนแรกอยู่ใน paid plan แต่ตอนนี้ปล่อยให้ใช้งาน Free แล้ว!</p><p>โดย Figma ได้อธิบายไว้ว่า Figma Make คือ <strong>“Prompt-to-app tool”</strong> หรือกล่าวได้ว่า มันคือเครื่องมือที่ช่วยสร้าง application แบบ prototype ผ่านการ prompt และสามารถ export ออกมาเป็น source code ได้ทันที</p><p>สรุปสั้นๆ มันคือ</p><blockquote>“การรวมกันของ Figma + AI Designer Assistant + Code Generator”</blockquote><p>แต่ถ้าใครเคยเล่น Figma มาก่อนจะรู้ว่ามันมี Figma AI อยู่แล้ว งั้น Figma Make ต่างกับ Figma AI ตัวเก่ายังไงกันนะ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/0*wmszFdJdq-DweVI0" /><figcaption>Figma AI example</figcaption></figure><h3>Figma Make vs Figma AI</h3><h4>1. เข้าใจ Prompt ซับซ้อน กว่าเดิม</h4><p>Figma Make สามารถเข้าใจ prompt ที่มีความซับซ้อน และ generate ผลลัพธ์ออกมาเป็น prototype ได้หลายหน้า หลาย flow เช่น</p><blockquote>Create a cat-matching mobile app like Tinder, but for cats. After a successful match, show a celebration page with the text: “Congrats, you’ve been adopted by the cat!” Also include match history, and user settings features.</blockquote><p>Figma Make จะสร้าง prototype และ UI ออกมาได้ทั้ง flow ทันที ในขณะที่ Figma AI จะทำได้แค่ทีละ 1 หน้า หรือทีละ component เท่านั้น</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0OjL0UBFD2cttmpNR8_9Rg.gif" /><figcaption>Example of creating a design with Figma Make</figcaption></figure><h4>2. มี Context Reference และ Chain Prompt</h4><h4><strong>Context Reference</strong></h4><p>หมายถึงความสามารถของ Figma Make ในการ “เข้าใจบริบทของดีไซน์” ที่เรามีอยู่แล้ว อ้างอิงดีไซน์ดิม, screenshot หรือ component จาก design library ของทีม เพื่อให้การออกแบบฟีเจอร์ใหม่ยังคงสไตล์และโทนของโปรเจกต์เดิมไว้</p><h4><strong>Chain Prompt</strong></h4><p>คือการที่สั่งงาน AI แบบต่อเนื่อง (step-by-step) ทำให้เราไม่จำเป็นต้องเขียน prompt ยาวตั้งแต่แรก แต่สามารถ ปรับ เพิ่ม หรือต่อยอด จากผลลัพธ์เดิม ได้เรื่อย ๆ เหมือนเราคุยกับ AI</p><p>ทั้งสองฟีเจอร์นี้ช่วยให้การสร้างฟีเจอร์ใหม่ <strong>ไม่หลุดโทนของดีไซน์เดิม </strong><br>และถ้า prompt แรกออกมาไม่ตรงใจ เราก็สามารถ chain prompt ต่อได้เรื่อย ๆ จนได้ผลลัพธ์ที่ต้องการ</p><p>เทคนิคหนึ่งที่ผมใช้คือ แยก design แต่ละฟีเจอร์ออกเป็นหลายไฟล์ ของ Figma Make เพื่อลดความซับซ้อนแต่ยังคงความสอดคล้องของโปรเจ็กต์ได้อยู่ระดับหนึ่ง</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1lqfhEkll1C5RoWT6VROLw.gif" /><figcaption>Using reference design and chain prompt with Figma Make</figcaption></figure><h4>3. Precise Edit</h4><p>เราสามารถจำกัดขอบเขตการแก้ไขได้ เช่น ให้แก้เฉพาะใน component นี้เท่านั้น ช่วยลดปัญหา prompt ผิดพลาด ไปโดน layout ส่วนอื่น แต่ถ้าเลือกขอบเขตผิด Figma Make ก็จะบอกเรา ให้เรากำหนดขอบเขตใหม่ให้ถูกต้อง</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rNgkphtJtiT4D67fYftpug.gif" /><figcaption>Using precise edit with Figma Make</figcaption></figure><h4>4. Code Generation</h4><p>ผลลัพธ์ที่ได้ไม่ใช่แค่ design แต่ยัง generate source code ออกมาให้ด้วย</p><p>ตอน dev สร้าง app จริง สามารถเปิด prototype มาดู logic และ flow ประกอบได้เลย ถือว่าช่วย dev ได้เยอะมากๆๆ 🤩</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t-8_Jt1_R4StHWH4oz7lFw.gif" /><figcaption>Viewing code generation with Figma Make</figcaption></figure><h4>5. ได้ Prototype ที่ กดเล่นได้จริง</h4><p>การที่เราแค่ prompt แล้วได้ prototype ที่กดเล่นได้จริงออกมาเลย เหมาะมากกับการช่วยทดสอบคอนเซปต์แบบไว ๆ โดยไม่ต้องเสียเวลานาน</p><p>รวมไปถึง dev สามารถทำความเข้าใจผ่านการเล่นกับ prototype ลดเวลาประชุมไปได้อีกเป็นกอง</p><p>จากประสบการณ์ของผมตอนทำงานกับทีม Australia — พอ PM และ designer ใช้ Figma Make สร้าง prototype แล้วส่งต่อให้ dev ดู เราประชุมแค่ 15–20 นาทีเพื่อ ทำความเข้าใจประเด็นที่สำคัญให้ตรงกัน แทนที่จะต้อง groom feature กันเป็นชั่วโมง</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M4mqzJSSLdhcZIdunFrf9A.gif" /><figcaption>Interact the prototype on Figma Make</figcaption></figure><h4>6. สามารถ Export ออกมาเป็น Figma Layout</h4><p>เป็นฟีเจอร์ใหม่ที่พึ่งอัปเดตเมื่อไม่นานมานี้ ซึ่งทำให้เราสามารถแปลงหน้านั้นๆ จาก prototype ออกมาเป็น Figma layout สามารถนำไปทำงานต่อใน Figma Design ได้ทันที</p><p>ตรงส่วนนี้ เราสามารถใช้ Figma MCP ให้ Copilot มองเห็นดีไซน์จริง และนำไปขึ้น component ต่อได้โดยตรง ช่วยให้การอ้างอิงดีไซน์มีความแม่นยำกว่าการใช้ screenshot อย่างมาก</p><p>สำหรับใครที่ยังไม่เคยใช้ Figma MCP แนะนำให้ลองดูเพิ่มเติมได้ที่ลิงก์นี้ครับ:</p><ul><li><a href="https://www.figma.com/blog/introducing-figma-mcp-server/">Introducing Figma MCP Server</a></li><li><a href="https://github.com/GLips/Figma-Context-MCP">Figma Context MCP</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h0eZe5jNzdSCJSt0z9Gx3w.gif" /><figcaption>Example of exporting Figma Layout from prototype</figcaption></figure><p><strong>ถ้าคุณเป็น Dev</strong></p><ul><li>ใช้ Figma Make เป็น designer assistant ได้เลยสำหรับ PoC หรือ side project</li><li>เข้าใจฟีเจอร์ใหม่ ได้ง่ายขึ้น จาก prototype ที่ กดเล่นได้จริง</li><li>ดู source code จาก prototype เพื่อทำความเข้าใจ logic ก่อนสร้างจริงได้</li></ul><p><strong>ถ้าคุณเป็น Manager / Product Manager / Designer</strong></p><ul><li>สร้าง prototype ที่ใช้งานได้จริง ภายใน ไม่กี่นาที เพื่อนำเสนอหรือทดสอบคอนเซปต์ได้อย่างรวดเร็ว</li><li>ส่ง prototype ให้ dev ไปต่อยอดได้ทันที ลดเวลาอธิบาย และลดความเข้าใจที่ไม่ตรงกัน</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*daN59GVKBCasOoAYaC6NWA.png" /><figcaption>Table display feature comparing between Figma AI and Figma Make</figcaption></figure><h3>Limitation — ข้อจำกัดที่ควรรู้</h3><h4>1. ไม่สามารถแทนที่ designer ได้</h4><p>ในข้อนี้ใส่ดอกจันไว้ล้านตัวเลยครับ ⭐️ <br>ถึงแม้ Figma Make จะสร้าง UI ที่สวยได้ แต่ UX (User Experience) ที่ดี ยังต้องอาศัยประสบการณ์และความเข้าใจในผู้ใช้งานของ designer อยู่ดี</p><h4><strong>2. “Prototype”</strong> is not <strong>“Production”</strong></h4><p>การที่เราสามารถสร้าง prototype ได้ภายใน 15 นาที ไม่ได้หมายความว่าพร้อมขึ้น production คุณยังต้องมี development team มาดู architecture, code quality, security, deployment และอื่นๆอีกมากมายอยู่ดี</p><h4>3. Coding language และ Library ยังจำกัด</h4><p>เท่าที่ผมหาข้อมูล ปัจจุบัน Figma Make ยังรองรับแค่ React (Typescript), Js, HTML และ CSS</p><p>หวังว่าในอนาคต Figma จะเพิ่ม framework หรือภาษาอื่น ๆ อย่าง Vue, Flutter หรือ Java ให้รองรับมากขึ้น</p><h4>4. <strong>ใช้งานได้เฉพาะบน PC / Desktop</strong></h4><p>ปัจจุบัน Figma Make ยังไม่สามารถใช้งานบนแท็บเล็ตหรือสมาร์ตโฟนได้ ดังนั้นถ้าใครชอบพกแค่ iPad แบบผม อาจจะยังใช้งานไม่สะดวกมากนัก</p><h4>5. ไม่สามารถเลือก AI model ได้</h4><p>ตอนนี้ยังไม่มีตัวเลือกให้เปลี่ยน AI model ทำให้ใช้ได้แค่ตัวที่ Figma กำหนดไว้เท่านั้น แต่เราสามารถปรับ <strong>Guideline.md</strong> ซึ่งเป็นไฟล์ที่ใช้กำหนดกรอบคำสั่ง (instruction) เบื้องต้นให้ AI ช่วยคุมโทนหรือแนวทางการออกแบบได้</p><h4>6. Limitation ของ plan และ seat <strong>ในการใช้งาน Figma Make</strong></h4><p>ใน Figma มีการแบ่งประเภทผู้ใช้ตาม <strong>Plan</strong> และ <strong>Seat</strong> ซึ่งจะเป็นตัวกำหนดสิทธิ์การเข้าถึงฟีเจอร์ต่าง ๆ รวมถึง Figma Make</p><p>ถ้าใครใช้แบบ <strong>Starter (Free) plan</strong> อันนี้สามารถใช้งาน Figma Make ได้ในระดับหนึ่ง แต่จะมีข้อจำกัดบางในบางฟีเจอร์ เช่น library reference</p><p>ส่วนใน <strong>Paid Plan</strong> จะมีสิทธิ์ใช้งานที่แตกต่างกันตามประเภท <strong>Seat</strong> เช่น Full, Dev, Collab และ View โดย</p><ul><li><strong>Full Seat</strong> จะเข้าถึง Figma Make ได้ครบทุกฟีเจอร์ รวมถึงการ Export เป็น React Code และ Figma Layout</li><li><strong>Seat อื่น ๆ</strong> ยังสามารถใช้งานได้ในระดับหนึ่ง แต่จะถูกจำกัดไว้เฉพาะใน draft file หรือโหมดทดลอง</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*WhHlPsyjC0Gd05cGwhI6dA.png" /></figure><p>นอกจากนี้ Figma Make ยังมีระบบ AI Credits ซึ่งจะจำกัดจำนวนการ prompt <strong>ต่อเดือน</strong> หากใช้เยอะจน credit หมด ก็อาจต้องรอรอบเดือนถัดไป หรือ อัปเกรด Plan เพื่อเพิ่มโควตา</p><h3>Conclusion</h3><blockquote><em>ส่วนตัวผมมองว่า Figma Make คือจุดเปลี่ยนสำคัญของการทำงานระหว่าง </em><strong><em>Tech — Design — Business</em></strong><em> เพราะมันทำให้ทุกคนเริ่มจาก idea ไปสู่ prototype ได้ง่ายขึ้น ก่อนพัฒนาไปเป็น </em>application<em> จริง</em></blockquote><p>ผมเชื่อว่าการมาของเทคโนโลยีแบบ Figma Make จะทำให้ในอนาคต เราได้เห็น idea ใหม่ ๆ ถูกทดลองและพัฒนา จนกลายเป็น application ที่สร้าง business value ได้จริงมากขึ้น</p><p>ถ้าใครเป็น dev, PM, หรือ startup founder ที่อยากทำโปรเจกต์เร็ว ๆ ลองใช้ดูครับ แล้วจะเข้าใจว่าทำไมผมถึงตื่นเต้นกับมันขนาดนี้ 😄</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*Y-5bMV1fcy1VLIAT1YQflA.gif" /><figcaption>Cat dancing with joy</figcaption></figure><p>สุดท้ายแล้ว ใครที่อ่านแล้วคิดว่าทีมยังติดปัญหาเกี่ยวกับการรันโปรเจ็กต์อยู่ <br>ทีม PALO IT ของพวกเรายินดีเข้าไปช่วยได้นะครับ (ขายของ ๆ 😁)</p><p>ไม่ว่าจะเป็น</p><ul><li>ทำ “Prototype-to-Production Sprint”</li><li>ทำ user research หรือ product proof of concept เพื่อทดสอบความเป็นไปได้ทางธุรกิจ</li><li>Team transformation ในเรื่องของ Agile หรือ AI adoption</li><li>Migrate system หรือ service รวมถึงเปลี่ยนเทคโนโลยีหรือภาษาโปรแกรม เช่น React หรือ Flutter</li><li>ออกแบบ system architecture ให้ขึ้นโปรดักชันได้อย่างลื่นๆ</li></ul><p>ติดต่อพวกเราได้ที่ <br>Facebook: PALO IT Thailand (<a href="https://www.facebook.com/PALOITTH">https://www.facebook.com/PALOITTH</a>)</p><h3>Reference:</h3><ul><li><strong><em>Introducing Figma Make: A new way to test, edit, and prompt designs — Peter Ng, Rohit Chouhan, Tom Duncalf:</em></strong><em> </em><a href="https://www.figma.com/blog/introducing-figma-make/"><em>https://www.figma.com/blog/introducing-figma-make/</em></a></li><li><strong>Bringing Figma Make to the canvas — Nikolas Klein:</strong> <a href="https://www.figma.com/blog/bringing-figma-make-to-the-canvas/">https://www.figma.com/blog/bringing-figma-make-to-the-canvas/</a></li><li><strong>Meet Figma AI: Empowering designers with intelligent tools — Kris Rasmussen: </strong><br><a href="https://www.figma.com/blog/introducing-figma-ai/">https://www.figma.com/blog/introducing-figma-ai/</a></li><li><strong>Use First Draft with Figma AI:<br></strong><a href="https://help.figma.com/hc/en-us/articles/23955143044247-Use-First-Draft-with-Figma-AI">https://help.figma.com/hc/en-us/articles/23955143044247-Use-First-Draft-with-Figma-AI</a></li><li><strong>Figma Make FAQs: <br></strong><a href="https://help.figma.com/hc/en-us/articles/31722591905559-Figma-Make-FAQs">https://help.figma.com/hc/en-us/articles/31722591905559-Figma-Make-FAQs</a></li><li><strong>Figma Picing Plan:<br></strong><a href="https://www.figma.com/pricing/">https://www.figma.com/pricing/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70af158b024e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/palo-it-thailand/figma-make-%E0%B8%AD%E0%B8%A2%E0%B9%88%E0%B8%B2%E0%B8%9E%E0%B8%B6%E0%B9%88%E0%B8%87%E0%B9%80%E0%B8%A3%E0%B8%B4%E0%B9%88%E0%B8%A1%E0%B9%82%E0%B8%9B%E0%B8%A3%E0%B9%80%E0%B8%88%E0%B8%81%E0%B8%95%E0%B9%8C-%E0%B8%96%E0%B9%89%E0%B8%B2%E0%B8%A2%E0%B8%B1%E0%B8%87%E0%B9%84%E0%B8%A1%E0%B9%88%E0%B8%A3%E0%B8%B9%E0%B9%89%E0%B8%88%E0%B8%B1%E0%B8%81-ai-design-tool-%E0%B8%97%E0%B8%B5%E0%B9%88%E0%B9%80%E0%B8%9B%E0%B8%A5%E0%B8%B5%E0%B9%88%E0%B8%A2%E0%B8%99%E0%B9%80%E0%B8%81%E0%B8%A1%E0%B8%82%E0%B8%AD%E0%B8%87-dev-%E0%B9%81%E0%B8%A5%E0%B8%B0-designer-70af158b024e">Figma Make - อย่าพึ่งเริ่มโปรเจกต์ ถ้ายังไม่รู้จัก AI Design Tool ที่เปลี่ยนเกมของ Dev และ Designer</a> was originally published in <a href="https://medium.com/palo-it-thailand">PALO IT THAILAND</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[เจาะลึก Test-time Scaling ตอนที่ 1: Self-Consistency + Code ตัวอย่าง]]></title>
            <link>https://medium.com/palo-it-thailand/%E0%B9%80%E0%B8%88%E0%B8%B2%E0%B8%B0%E0%B8%A5%E0%B8%B6%E0%B8%81-test-time-scaling-%E0%B8%95%E0%B8%AD%E0%B8%99%E0%B8%97%E0%B8%B5%E0%B9%88-1-self-consistency-code-%E0%B8%95%E0%B8%B1%E0%B8%A7%E0%B8%AD%E0%B8%A2%E0%B9%88%E0%B8%B2%E0%B8%87-e85d581816af?source=rss----3ae4f2a55b01---4</link>
            <guid isPermaLink="false">https://medium.com/p/e85d581816af</guid>
            <category><![CDATA[thai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[test-time-scaling]]></category>
            <dc:creator><![CDATA[Sarin Suriyakoon]]></dc:creator>
            <pubDate>Tue, 04 Nov 2025 02:48:33 GMT</pubDate>
            <atom:updated>2025-11-11T09:36:30.348Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YYGQ_o31f0nxwYCK1e39hg.jpeg" /></figure><h4>Test-time scaling หรือศาสตร์ในการ Optimize Accuracy ของ LLM/Agent</h4><p>เพื่อที่จะ Optimize Accuracy หรือเพิ่มความแม่นยำของ Agent/LLM เราจำเป็นจะต้องเข้าใจว่า Test-time Scaling คืออะไร ในบทความนี้เรามาเร่ิมจากทำความเข้าใจพื้นฐานและเทคนิคจากเปเปอร์ที่ชื่อว่า Self-Consistency พร้อมดู Code ตัวอย่างกัน</p><h3><strong>Table of Content</strong></h3><ol><li><a href="#4c05"><strong>พื้นฐาน</strong></a></li><li><a href="#1d69"><strong>ทำไมถึงเลือก Paper นี้มาเล่าให้ฟัง</strong></a></li><li><a href="#4b90"><strong>ที่มาและความสำคัญ</strong></a></li><li><a href="#9bfc"><strong>Self-Consistency คืออะไร</strong></a></li><li><a href="#87d7"><strong>ลอง Self-Consistency</strong></a></li><li><a href="#082c"><strong>การนำไปใช้</strong></a></li><li><a href="#9c0e"><strong>ปิดท้าย</strong></a></li></ol><h3>1. พื้นฐาน</h3><h4>Test-time scaling</h4><p>คือเทคนิคนึงในการเพิ่มความแม่นยำหรือความฉลาดโดยการเพิ่ม “เวลา” หรือ “Resource”ในการตอบสนองของ LLM ผ่านการใช้งาน <strong>เรียกง่ายๆคือ ใช้เวลาตอบนานขึ้นเพื่อความแม่นยำที่มากขึ้น(นานขึ้น คือใช้ resource มากขึ้น)</strong></p><p>Test-time = ตอนเรียกใช้ ตอน Inference จริง</p><p>Scaling = การ scale ความฉลาด</p><p>เทคนิคที่ถูกพูดถึงคู่กับ Test-time scaling คือ <strong>Train-time scaling</strong> หมายถึงการเพิ่มความฉลาดตอนที่ Train model นั่นเอง</p><p>ตัวอย่างที่เห็นได้ชัดของ Test-time scaling คือการใช้ Chain of Thought เพื่อให้ LLM มีการให้เหตุผลก่อนคำตอบสุดท้ายทำให้ความแม่นยำมากขึ้น</p><p>ส่วนตัวอย่างของ Train-time scaling คือยิ่งโมเดลใช้เวลาเทรนนานมากขึ้น ด้วย data ที่ใหญ่ขึ้น ทำให้โมเดลมีความฉลาดมากขึ้น</p><h4>Chain of Thought(CoT)</h4><p>ก่อนจะถลำลึกไปกว่านี้ อยากอธิบายก่อนว่า <a href="https://www.promptingguide.ai/techniques/cot">Chain of Thought</a> หรือ CoT คือเทคนิคการเขียน Prompt ที่ “บังคับ” หรือ “โน้มน้าว” ให้ LLM คิดเป็นขั้นเป็นตอน โดยการทำสิ่งต่อไปนี้</p><ul><li>เติม คำว่า <strong>“Think Step by Step”</strong> ต่อท้าย Prompt ที่ใช้</li><li>เติม <strong>“ตัวอย่าง”</strong> ของการคิดเป็นลำดับขั้น เหมือนอาจารย์คณิตศาสตร์สอนวิธีคิดโจทย์ตัวอย่าง แล้วให้นักเรียนใช้วิธีการเดียวกันกับโจทย์ที่ต่างออกไป</li></ul><p>โดยเทคนิค Chain of Thought เป็นพื้นฐานสำคัญมากๆ เนื่องจากเทคนิคที่ใช้เพิ่มความแม่นยำต่างๆ ส่วนใหญ่เกิดมาจากงานวิจัยตัวนี้ รวมไปถึง การ Train พวก Reasoning model หรือ Non-Reasoning model ในยุคหลังๆ ที่ LLM เริ่มมีการทำ Chain of Thought โดยไม่ต้องพิมพ์ Prompt บอกกันแล้ว</p><p>มาต่อที่ <strong>Self-Consistency</strong> กันครับ</p><h3>2. ทำไมถึงเลือก Paper นี้มาเล่าให้ฟัง</h3><p>ต้องบอกก่อนว่า Paper ตัวนี้ถือได้ว่า “เก่า” ออกมาในช่วงปี 2023 ช่วงก่อน ChatGPT บูมซะอีก แต่ว่าเป็นเปเปอร์ตัวหนึ่งที่ถูก reference ในช่วงหลังๆ ระหว่างปี 2024–2025 บ่อยมากๆ โดยเฉพาะ paper ประเภท Test-time scaling จนผมต้องกลับมาอ่านและทบทวนดูว่า เจ้า Self-Consistency นี่คืออะไรกันแน่ แล้วมันใช้งานยังไง</p><p>สุดท้ายตัว method เป็นที่น่าสนใจกว่าผลลัพธ์ซะอีก เราไปดูกันครับ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HF1MHpNKZ4IUhBRdCaShEw.png" /><figcaption>Gemini generated art — Bill of Accuracy</figcaption></figure><h3>3. ที่มาและความสำคัญ</h3><p>ผู้เขียนกล่าวว่า <strong>Self-Consistency</strong> ตัวนี้ ช่วยเพิ่มความสามารถในการให้เหตุผลได้ดีขึ้นมากใน Benchmark ต่างๆ เช่น</p><ul><li><strong>GSM8K</strong>(ที่ใช้วัดความสามารถของ LLMในการแก้โจทย์คณิตศาสตร์ระดับประถมศึกษา) —<strong>GPT-3</strong>: CoT 14.6, Self-Consistency 23.4</li><li><strong>StrategyQA</strong>(สำหรับทดสอบความสามารถในการให้เหตุผลแบบหลายขั้นตอน) — <strong>GPT-3</strong>:Cot 56.7, Self-Consistency 61.7</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SBIBC2fLMP4wKEhgHBHhzQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vFisynkARfa9gYLNHdLsyA.png" /></figure><p>ในตอนแรกก็ไม่ได้ว้าวอะไรมากเพราะ Method/Paper ต่างๆ ก็มี base เป็น Chain-of-Thought (CoT) ต้องเอาชนะอยู่แล้ว</p><p>มาสะดุดตรง…</p><p>แรงบันดาลใจของ paper ตัวนี้เกิดจากว่า</p><blockquote>วิธีการแก้ปัญหาสามารถมีได้หลายวิธี เพื่อแก้ปัญหาเดียว</blockquote><h3>4. Self-Consistency คืออะไร</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UUIFMMjd25e5LkuoJH10jA.png" /><figcaption>Figure 1 from Original Paper</figcaption></figure><p><strong>Self-Consistency</strong> เป็นเทคนิคที่ใช้ร่วมกับ Chain-of-Thought (CoT) prompting เพื่อเพิ่มความแม่นยำของคำตอบ โดยมีหลักการดังนี้:</p><h4>ขั้นตอนการทำงาน</h4><ol><li><strong>ใช้ Chain-of-Thought Prompting</strong>: ให้ LLM คิดทีละขั้นตอน (think step by step) เพื่อแก้ปัญหา</li><li><strong>Generate หลายครั้ง</strong>: สำหรับโจทย์เดียวกัน ให้ LLM generate คำตอบพร้อมเหตุผล <strong>หลายๆ รอบ</strong> (เช่น 5–10 ครั้ง) โดยแต่ละครั้งอาจมีวิธีคิดที่แตกต่างกันไป</li><li><strong>นับเสียง (Majority Voting)</strong>: นำคำตอบสุดท้ายทั้งหมดมาหาว่าคำตอบไหนปรากฏบ่อยที่สุด แล้วเลือกคำตอบนั้นเป็นคำตอบขั้นสุดท้าย</li></ol><ul><li>จุดประสงค์คือใช้ “ภูมิปัญญาของฝูงชน” (wisdom of crowds) — ถ้าหลายๆ วิธีคิดให้คำตอบเดียวกัน คำตอบนั้นน่าจะถูกต้อง</li></ul><h4>ตัวอย่าง</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*61pSPXIq-Jyz4CEnEcS8sw.png" /></figure><p>จากรูปด้านบน(Figure 1) มี Generate 3 ครั้ง ได้คำตอบ:</p><ul><li>18USD 2 ครั้ง</li><li>26USD 1 ครั้ง</li></ul><p>คำตอบสุดท้ายจึงเป็น 18USD</p><h3>5. ลอง Self-Consistency + อธิบาย Code Example</h3><p>เพื่อนๆสามารถลอง Self-Consistency ผ่าน Google Colab ตามขั้นตอนด้านล่างได้เลย</p><ol><li>เปิด Google Colab Notebook จาก <a href="https://github.com/GLOBAL-PALO-IT/th_LLM-PALO-IT-Paper-To-Code/blob/main/Self_Consistency_Code.ipynb">https://github.com/GLOBAL-PALO-IT/th_LLM-PALO-IT-Paper-To-Code/blob/main/Self_Consistency_Code.ipynb</a></li><li>เราจะใช้ <a href="https://docs.github.com/en/github-models/use-github-models/prototyping-with-ai-models#rate-limits">GitHub Models Free Tier</a> ที่ให้เราใช้ LLM Model แบบฟรีๆ</li><li>Copy GitHub Token เก็บไว้ ใน <a href="https://www.analyticsvidhya.com/blog/2024/12/api-keys-in-google-colab/">Google Colab Secrets</a> ตาม <a href="https://docs.github.com/en/github-models/quickstart#step-2-make-an-api-call">https://docs.github.com/en/github-models/quickstart#step-2-make-an-api-call</a></li><li>กด “Run all” เพื่อดูผลลัพธ์</li><li>ส่วนสำคัญของ Code ที่อยากให้เข้าใจมีดังนี้</li></ol><h4>Code Flowchart</h4><p>Task หลักของ Agent เราในตัวอย่างนี้คือการแก้ Puzzle ที่เลือกมาจาก <a href="https://huggingface.co/blog/yuchenlin/zebra-logic">ZebraLogic Benchmark</a> ซึ่งจะเห็นได้ว่า Prompt และ Extraction Code แต่ส่วนถูกเขียนมาเพื่อแก้โจทย์นี้โดยเฉพาะ</p><p>หลักการทำงานของโค้ดชุดนี้คือ</p><ol><li>Load dataset แล้ววน loop แต่ละโจทย์</li><li>ส่งโจทย์แต่ละอันไปให้ function ที่รัน self-consistency — runSC</li><li>ภายใน self-consistency function ก็จะมี loop ตามจำนวน sample ที่ set ไว้ ในแต่ละ loop ก็จะเป็นการเรียก LLM ด้วย Prompt ที่กำหนดแล้วทำการ extract คำตอบไว้</li><li>หลังจากเก็บ sample ทั้งหมดในโจทย์นึงก็จะหา Common Answer/Majority Vote ออกมา</li><li>แล้วนำไปตรวจคำตอบ แล้วเก็บไว้เป็นผลลัพธ์</li><li>รวบรวมผลลัพธ์ทั้งหมดเพื่อสรุปเป็น Accuracy โดยรวม</li></ol><h4>วิเคราะห์โจทย์</h4><p>การหาโจทย์มาเป็นตัวอย่างที่ชัดเจนสำหรับ paper ตัวนี้ค่อนข้างยากมาก เนื่องจาก benchmark ใน paper อย่าง <a href="https://huggingface.co/datasets/madrylab/gsm8k-platinum">GSM8K</a>โดน LLM ตั้งแต่ 3B เกมหมดแล้ว เลยต้องออกตามหาโจทย์แปลกๆ แต่ไม่ยากจนเกินไป และเลือกโมเดลที่เก่งพอดีๆ ไม่มากไป เพื่อหลีกเลี่ยงการตอบผิดหมดทุก Sample กับตอบถูกหมดทุก Sample</p><p>เลยมาลงที่ <a href="https://huggingface.co/blog/yuchenlin/zebra-logic">ZebraLogic Benchmark</a> นี่แหละ</p><p>ซึ่งตัว ZebraLogic เป็น Puzzle ประเภทนึงที่ทดสอบความสามารถในการให้เหตุผลอย่างเข้มข้น</p><h4>ตัวอย่างรูป Logic Grid</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*omoiQfyc2feNd2ohgu9tvQ.png" /><figcaption>Logic Grid Example</figcaption></figure><h4>สามารถอ่านเพิ่มเติมได้ที่</h4><p><a href="https://en.wikipedia.org/wiki/Zebra_Puzzle">https://en.wikipedia.org/wiki/Zebra_Puzzle</a></p><p><a href="https://en.wikipedia.org/wiki/Logic_puzzle">Logic puzzle - Wikipedia</a></p><p>จากการทดสอบสรุปได้ว่า Model ส่วนใหญ่ยังไม่ได้ถูกเทรนด้วย Benchmark ตัวนี้มากนัก ดังนั้นจึงเหมาะอย่างยิ่งสำหรับการทดสอบของเรา</p><p>เรามาดูโค้ดส่วนที่สำคัญๆ กันต่อได้เลย</p><h4>Prepare Prompt</h4><pre># Prompt<br># CoT Prompt<br>system_prompt=&quot;&quot;&quot;<br> Each example/input/question is a Logic Grid Puzzle, also known as a Zebra Puzzle. In each puzzle, we are given N houses (numbered 1 to N from left to right) and M features for each house. There are N distinct values for each feature, and each house must have a unique value for each feature. Given a list of clues, one should be able to deduce a unique correct assignment of values. The logic grid puzzle is a typical Constraint Satisfaction Problem (CSP) and is often used to test humans&#39; logical reasoning abilities in exams such as the Law School Admission Test (LSAT).<br><br>You always solve problem step by step<br>start answering with `## Reasoning steps:` and end with<br><br>## Final answer:<br>```json<br><br>````<br>&quot;&quot;&quot;<br># Example Input Prompt<br>user_prompt=&quot;&quot;&quot;<br>There are 2 houses, numbered 1 to 2 from left to right.<br>Each house is occupied by a different person.<br>Each house has a unique attribute for each of the following characteristics:<br>- Each person has a unique name: **Arnold, Eric**<br>- People own unique car models: **ford f150, tesla model 3**<br>- The people keep unique animals: **cat, horse**<br><br>**Clues**:<br>1. Eric is directly left of the person who owns a Tesla Model 3.<br>2. The person who keeps horses is in the first house.<br>&quot;&quot;&quot;<br># Example Output Prompt<br>assistant_message=&quot;&quot;&quot;<br>## Reasoning steps:<br><br>From Clue 1, we know that Eric is to the left of someone, so he must be the owner of House 1 because House 2 is the rightmost house.<br>Additionally, we know that the person in House 2 must be Arnold, and he owns a Tesla Model 3. Thus, Eric owns a Ford F150.<br>From Clue 2, we know that Eric keeps horses in House 1, which means the other house must keep cats. Finally, we arrive at the unique solution to this puzzle.<br>The solution is presented in table format:<br><br>## Final answer:<br><br>```json<br>{<br>   &quot;header&quot;:[<br>      &quot;Houses&quot;,<br>      &quot;Name&quot;,<br>      &quot;CarModel&quot;,<br>      &quot;Animal&quot;<br>   ],<br>   &quot;rows&quot;:[<br>      [<br>         &quot;1&quot;,<br>         &quot;Eric&quot;,<br>         &quot;ford f150&quot;,<br>         &quot;horse&quot;<br>      ],<br>      [<br>         &quot;2&quot;,<br>         &quot;Arnold&quot;,<br>         &quot;tesla model 3&quot;,<br>         &quot;cat&quot;<br>      ]<br>   ]<br>}<br>```<br>&quot;&quot;&quot;<br># lgp-test-2x2-33<br># lgp-test-6x5-2<br># lgp-test-2x4-33<br># lgp-test-6x6-5<br># lgp-test-3x3-24<br>question=&quot;&quot;&quot;<br>Question:<br>There are 3 houses, numbered 1 to 3 from left to right, as seen from across the street. Each house is occupied by a different person. Each house has a unique attribute for each of the following characteristics:<br>- Each person has a unique name: `Peter`, `Eric`, `Arnold`<br>- Each person has a favorite color: `red`, `white`, `yellow`<br>- Each mother is accompanied by their child: `Fred`, `Meredith`, `Bella`<br><br>## Clues:<br>1. Arnold is the person whose favorite color is red.<br>2. The person&#39;s child is named Fred is somewhere to the left of Eric.<br>3. The person whose favorite color is red is in the second house.<br>4. The person&#39;s child is named Bella is in the first house.<br>5. The person who loves white is the person&#39;s child is named Meredith.<br><br>## Headers<br>&quot;header&quot;: [<br>&quot;House&quot;,<br>&quot;Name&quot;,<br>&quot;Color&quot;,<br>&quot;Children&quot;<br>]<br>&quot;&quot;&quot;<br>correct_answer=&quot;&quot;&quot;<br>```json<br>{<br>  &quot;header&quot;: [<br>    &quot;House&quot;,<br>    &quot;Name&quot;,<br>    &quot;Color&quot;,<br>    &quot;Children&quot;<br>  ],<br>  &quot;rows&quot;: [<br>    [&quot;1&quot;, &quot;Peter&quot;, &quot;yellow&quot;, &quot;Bella&quot;],<br>    [&quot;2&quot;, &quot;Arnold&quot;, &quot;red&quot;, &quot;Fred&quot;],<br>    [&quot;3&quot;, &quot;Eric&quot;, &quot;white&quot;, &quot;Meredith&quot;]<br>  ]<br>}<br>```<br>&quot;&quot;&quot;</pre><p>คือโค้ดส่วนที่เขียน Prompt</p><p><strong>system_prompt</strong> คือส่วนที่เป็น Instruction หลัก</p><p><strong>user_prompt</strong> โจทย์ตัวอย่าง</p><p><strong>assistant_prompt</strong> คำตอบของโจทย์ตัวอย่าง เพื่อแสดงให้เห็นวิธีการคิด(CoT) และรูปแบบ output</p><p><strong>question</strong> คือโจทย์ที่เราต้องการให้ LLM แก้</p><p><strong>correct_answer </strong>คือเฉลยของโจทย์</p><h4><strong>Set Up Parameters</strong></h4><pre>model_name = &quot;openai/gpt-4.1-nano&quot; # Choose not too smart model to see the diversity (phi-4,openai/gpt-4.1,deepseek/DeepSeek-R1-0528,xai/grok-3,openai/gpt-4.1-mini,deepseek/DeepSeek-V3-0324)<br>temperature=1.0 # Choose 1.0 for the most diverse answers<br>top_p=1.0 # Choose 1.0 for the most diverse answers</pre><p>คือโค้ดส่วนที่เรา set up parameter และ configuration ต่างๆ</p><p>ส่วนที่อยากเน้นคือ</p><p><strong>number_samples = 20</strong> คือ จำนวน Sample ที่เราจะใช้ หรือจำนวนครั้งที่เราจะเรียก LLM เพื่อเอาคำตอบทั้งหมดมาให้ Majority Vote</p><p><strong>model_name = “</strong>openai/gpt-4.1-nano<strong>”</strong> คือโมเดลที่เราจะใช้ เราเลือกใช้ openai/gpt-4.1-nano เพราะว่า จำเป็นต้องใช้ Model ที่ไม่ฉลาดเกินไป เพื่อจะ demo ประโยชน์ ของ Self-Consistency ถ้าเลือกโมเดลฉลาดเกินที่ตอบถูกโดยไม่ต้องใช้ Self-Consistency อาจจะไม่เห็นประโยชน์ของมันเท่าที่ควร</p><p><strong>temperature=1.0 และ top_p=1.0 </strong>คือค่าที่ควบคุมความ random ของคำตอบ เราตั้งไว้สูงสุดเพื่อให้ LLM มีคำตอบที่หลากหลายมากที่สุด</p><h4>Call LLM in loop to get samples</h4><pre><br>responses = []<br>final_answers = []  # Collect all final answers<br>try:<br>  for i in range(num_samples):<br>      response = client.complete(<br>          messages=messages,<br>          temperature=temperature,<br>          top_p=top_p,<br>          model=model_name,<br>      )<br>      responses.append(response.choices[0])<br>      answer = response.choices[0].message.content<br>      final_ans = extract_final_answer_regex(answer)<br>      if final_ans is None:<br>        print(f&quot;Warning: Could not extract answer from sample {i+1}&quot;)<br>      clean_ans = final_ans.lower().replace(&quot; &quot;, &quot;&quot;)<br>      json_object = extract_json_from_string(clean_ans)<br>      final_answers.append(json_object)  # Store the final answer<br><br>      print(f&quot;\nSample {i+1}: {json_object}&quot;)<br>      print(f&quot;{&#39;=&#39;*50}&quot;)<br>except Exception as e:<br>    print(f&quot;Error processing sample {i+1}: {e}&quot;)</pre><p>โค้ดส่วนนี้เป็นส่วนที่วน loop เพื่อเรียก LLM เพื่อเก็บ Sample จากการเรียกหลายๆ ครั้ง พร้อมกับ Extract คำตอบสุดท้ายของแต่ละ Call</p><h4>Get final Answer</h4><pre>if final_answers:<br><br>    # Convert answers to normalized format for counting<br>    normalized_answers = [normalize_answer(ans, for_comparison=False) for ans in final_answers]<br><br>    answer_counts = Counter(normalized_answers)<br>    most_common_string, count = answer_counts.most_common(1)[0]<br><br>    # Convert back to original type for display<br>    try:<br>        most_common_normalized = json.loads(most_common_string)<br>        # Find the original answer that matches this normalized version<br>        for ans in final_answers:<br>            if normalize_answer(ans, for_comparison=False) == most_common_string:<br>                most_common_answer = ans<br>                break<br>        else:<br>            most_common_answer = most_common_normalized<br>    except (json.JSONDecodeError, TypeError):<br>        most_common_answer = most_common_string<br><br>    print(f&quot;\n{&#39;=&#39;*50}&quot;)<br>    print(f&quot;MOST COMMON ANSWER (appeared {count}/{num_samples} times):&quot;)<br>    print(f&quot;{most_common_answer}&quot;)<br>    print(f&quot;{&#39;=&#39;*50}\n&quot;)<br><br>    # Optional: print all answer frequencies<br>    print(&quot;All answer frequencies:&quot;)<br>    for ans_str, freq in answer_counts.most_common():<br>        # Find the original answer that matches this normalized version<br>        original_ans = None<br>        for ans in final_answers:<br>            if normalize_answer(ans, for_comparison=False) == ans_str:<br>                original_ans = ans<br>                break<br><br>        if original_ans:<br>            print(f&quot;{original_ans} (appeared {freq} times)&quot;)<br>        else:<br>            try:<br>                ans_display = json.loads(ans_str)<br>                print(f&quot;{ans_display} (appeared {freq} times)&quot;)<br>            except (json.JSONDecodeError, TypeError):<br>                print(f&quot;{ans_str} (appeared {freq} times)&quot;)</pre><p>นำคำตอบทุกอันจาก Sample ที่เรามีมาหา Common Answer หรือ Majority Vote</p><h4>วิเคราะห์ผลลัพธ์</h4><p>จากการทดสอบพบว่า ด้วย Dataset 20 row(grid_size 3*3 ล้วน) กับ Model <strong>gpt-4.1-nano</strong></p><p>แบบ Sample = 1 หรือไม่ได้ใช้ Self-Consistency เลย ได้ Accuracy ที่ 35%</p><p>แบบ Sample = 5 หรือใช้ Self-Consistenccy ขนาดเท่ากับ 5 ได้ Accuracy ที่ 60%</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*QxylGo78EDuUowBTb-rFyw.png" /><figcaption>Without Self-Consistency — 20 zebra logic problems</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*XWmPxf3ZPftGH4hPhfMbmg.png" /><figcaption>With Self-Consistency — 20 zebra logic problems</figcaption></figure><p>ทั้งนี้อยากให้ลองรันการทดลองนี้ด้วยตัวเอง แล้วลองปรับ model และ parameter และ grid_size เพื่อความเข้าใจที่ลึกซึ้งยิ่งขึ้น</p><h3>6. การนำไปใช้</h3><h4>เมื่อไหร่ควรใช้ Self-Consistency</h4><p><strong>Self-Consistency</strong> เหมาะกับงานที่ต้องการ<strong>ความแม่นยำสูง</strong> และ End User ยินดีรอผลลัพธ์สักพัก ยกตัวอย่างเช่น งานวิเคราะห์ทางการเงิน หรือการตรวจสอบเอกสารสำคัญ <strong><em>ที่ความถูกต้องสำคัญกว่าความเร็ว</em></strong> หรือ Data Pipeline สามารถ manage ความคาดหวังของ user ได้ว่าต้องรอ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gPa9yHfg9HVacXr65Kfk0A.png" /><figcaption>Accuracy vs Speed</figcaption></figure><h4>เมื่อไหร่ไม่ควรใช้ Self-Consistency</h4><p>ถ้าเป็น <strong>Agentic System ที่มีการ Execute หลาย step</strong> อย่าง Coding Agent ที่ต้องทำหลายขั้นตอนต่อเนื่อง การใช้ Sampling N ที่สูง (เช่น 10–20) ในทุก step จะทำให้ใช้เวลาและ Token เยอะมาก ไม่ค่อยเหมาะ กับ LLM Inference latency ณ ปัจจุบัน</p><h4>การนำ Self-Consistency ไปใช้กับคำตอบแบบ Qualitative</h4><p>จากตัวอย่างก่อนหน้านี้ เราใช้ Self-Consistency กับโจทย์คณิตศาสตร์ที่มีคำตอบเป็นตัวเลขชัดเจน การหา Majority Vote ทำได้ง่ายด้วยการเปรียบเทียบค่าตรงๆ</p><p>แต่ในความเป็นจริง โจทย์ส่วนใหญ่ไม่ใช่แค่ตัวเลข เช่น:</p><ul><li><strong>การตอบคำถามเกี่ยวกับสุขภาพ</strong>: “การออกกำลังกายตอนเช้ามีประโยชน์อย่างไร?”</li><li><strong>งานเขียน</strong>: “เขียนอีเมลขอร้องให้ลูกค้าต่ออายุสัญญา”</li><li><strong>งานวิเคราะห์</strong>: “สรุปประเด็นสำคัญจากรีวิวสินค้า 100 รีวิว”</li></ul><p>คำตอบเหล่านี้อาจมีถ้อยคำต่างกัน แต่ให้<strong>ความหมายเดียวกัน</strong> เช่น:</p><p>คำตอบ 1: “ออกกำลังกายตอนเช้าช่วยเพิ่มพลังงานตลอดทั้งวัน”</p><p>คำตอบ 2: “การออกกำลังกายในช่วงเช้าทำให้มีแรงมากขึ้นตลอดวัน”</p><p>คำตอบ 3: “การวิ่งเช้าๆ ช่วยให้รู้สึกกระฉับกระเฉงตลอดวัน”</p><p>ทั้ง 3 คำตอบนี้ต่างกัน แต่ <strong>แก่นของเนื้อหาเหมือนกัน</strong> ถ้าเราเช็คแบบ exact match จะไม่เจอ Majority Vote เลย</p><h4>วิธีแก้ปัญหา</h4><p>ใช้ LLM อีกตัวเป็น Judge + Semantic Clustering เมื่อคำตอบไม่ใช่ตัวเลข เราต้องใช้ LLM อีกตัว มาช่วยตัดสินว่า(คล้ายๆ กับ <a href="https://arxiv.org/abs/2411.15594">LLM-as-a-Judge</a>)คำตอบไหนมีความหมายเหมือนกัน หรือใช้เทคนิค <a href="https://en.wikipedia.org/wiki/Semantic_similarity">Semantic Similarity</a> เพื่อจัดกลุ่มคำตอบ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y4xgl1L3YzAXtePIx08QIg.png" /><figcaption>Qualitative answer</figcaption></figure><h4>ข้อจำกัดของ Self-Consistency</h4><ul><li>Cost: ใช้ tokens เยอะกว่าปกติ N เท่า</li><li>ไม่เหมาะกับโจทย์ creative ที่ต้องการความหลากหลาย</li><li>ถ้า model มี systematic bias อาจได้คำตอบผิดซ้ำๆ กัน</li></ul><h3>7. ปิดท้าย</h3><p>สำหรับผม Self-Consistency เป็นเปเปอร์ที่ช่วยให้การก้าวเข้าสู่โลก Test-time scaling ง่ายขึ้น เนื่องจากเห็นชัดเจนว่า Test-time เพิ่มขึ้นจาก Sample N ที่มากขึ้น และเห็นความแม่นยำที่เพิ่มมากขึ้นอีกด้วย</p><p>Self-Consistency ด้วยตัวมันเองมีประโยชน์ในการ Optimize Accuracy มาก ถ้าเทียบกับความง่ายในการใช้งาน เพียงแค่เพิ่ม Sample แล้วหา Majority Vote แต่หากยังไม่เพียงพอ หรือใครอยากศึกษาต่อผมแนะนำให้ปรับ parameter ในโค้ด และเลือกโมเดลหลายๆตัวมาลองดูผลลัพธ์เทียบกัน หรือจะลองเปลี่ยนโจทย์เป็น Level ยากสุก 6*6 ก็ได้ครับ จะได้เห็นความแตกต่างว่าในแต่ละโจทย์หรือแต่ละ parameter ได้ผลต่างกันยังไง</p><p>สุดท้ายถ้าอยากไปต่อให้ลอง Implement Tree of Thought เพิ่มเติมครับ</p><p>หากใครกำลังมองหา Consult มาช่วยสร้าง Agentic AI หรือช่วยปรับปรุง AI Agent ที่มีอยู่แล้วให้มี Accuracy และ Scale ได้</p><p>ติดต่อทีมงาน PALO IT Thailand ได้ที่ <strong>Facebook: PALO IT Thailand</strong> <strong>(</strong><a href="https://www.facebook.com/PALOITTH"><strong>https://www.facebook.com/PALOITTH</strong></a><strong>)</strong></p><h3>Reference</h3><ul><li>Original paper: <a href="https://arxiv.org/abs/2203.11171">Self-Consistency Improves Chain of Thought Reasoning in Language Models</a></li><li><a href="https://huggingface.co/blog/yuchenlin/zebra-logic">https://huggingface.co/blog/yuchenlin/zebra-logic</a></li><li><a href="https://huggingface.co/datasets/allenai/ZebraLogicBench-private">https://huggingface.co/datasets/allenai/ZebraLogicBench-private</a></li><li><a href="https://openai.com/index/learning-to-reason-with-llms/">https://openai.com/index/learning-to-reason-with-llms/</a></li><li><a href="https://huggingface.co/blog/Kseniase/testtimecompute">https://huggingface.co/blog/Kseniase/testtimecompute</a></li></ul><h3>Recommend Read</h3><ul><li><a href="https://arxiv.org/abs/2305.10601">Tree of Thoughts: Deliberate Problem Solving with Large Language Models</a></li><li><a href="https://arxiv.org/abs/2501.19306">SETS: Leveraging Self-Verification and Self-Correction for Improved Test-Time Scaling</a></li><li><a href="https://arxiv.org/abs/2502.06233">Confidence Improves Self-Consistency in LLMs</a></li><li><a href="https://github.com/SuperBruceJia/Awesome-LLM-Self-Consistency">Awesome LLM Self-Consistency</a></li><li><a href="https://arxiv.org/abs/2201.11903">Chain-of-Thought Prompting Elicits Reasoning in Large Language Models</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e85d581816af" width="1" height="1" alt=""><hr><p><a href="https://medium.com/palo-it-thailand/%E0%B9%80%E0%B8%88%E0%B8%B2%E0%B8%B0%E0%B8%A5%E0%B8%B6%E0%B8%81-test-time-scaling-%E0%B8%95%E0%B8%AD%E0%B8%99%E0%B8%97%E0%B8%B5%E0%B9%88-1-self-consistency-code-%E0%B8%95%E0%B8%B1%E0%B8%A7%E0%B8%AD%E0%B8%A2%E0%B9%88%E0%B8%B2%E0%B8%87-e85d581816af">เจาะลึก Test-time Scaling ตอนที่ 1: Self-Consistency + Code ตัวอย่าง</a> was originally published in <a href="https://medium.com/palo-it-thailand">PALO IT THAILAND</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Prompt for Coding GPT-5 เมื่อ ศิลปะกับวิทยาศาสตร์มาเจอกัน]]></title>
            <link>https://medium.com/palo-it-thailand/advanced-prompt-for-coding-gpt-5-%E0%B9%80%E0%B8%A1%E0%B8%B7%E0%B9%88%E0%B8%AD-%E0%B8%A8%E0%B8%B4%E0%B8%A5%E0%B8%9B%E0%B8%B0%E0%B8%81%E0%B8%B1%E0%B8%9A%E0%B8%A7%E0%B8%B4%E0%B8%97%E0%B8%A2%E0%B8%B2%E0%B8%A8%E0%B8%B2%E0%B8%AA%E0%B8%95%E0%B8%A3%E0%B9%8C%E0%B8%A1%E0%B8%B2%E0%B9%80%E0%B8%88%E0%B8%AD%E0%B8%81%E0%B8%B1%E0%B8%99-99422e48c480?source=rss----3ae4f2a55b01---4</link>
            <guid isPermaLink="false">https://medium.com/p/99422e48c480</guid>
            <category><![CDATA[writing-prompts]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Warakron Kanthawong]]></dc:creator>
            <pubDate>Wed, 15 Oct 2025 03:01:55 GMT</pubDate>
            <atom:updated>2025-10-15T03:01:54.784Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SJmgxGS9mDareqql1K68XA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z2AKjuqL5LZFElP9sAbKYA.png" /></figure><p>ในบทความนี้ผมจะพูดถึงเรื่อง prompting และการใช้งาน GPT-5 Model ใหม่ล่าสุดของ OpenAI บอกว่าเป็น The best model</p><h3>Introducing GPT-5</h3><p>GPT-5 เป็น large language model (LLM) ล่าสุดของทาง OpenAI ที่เคลมว่าดีกว่าในด้านเหตุผล การเขียนโค้ด และการเข้าใจ context ยาว ๆ ได้แม่นกว่า และมีการพัฒนามาจาก GPT-4 แต่หลายคนกลับเจอปัญหาว่า GPT-4 นั้นตอบโจทย์มากกว่า GPT-5 ทั้งในเรื่อง คุณภาพและ ความเร็ว แต่ ปัญหาอยู่ที่ GPT-5 ไม่เก่งเท่า GPT-4 หรือเรายังใช้งาน GPT-5 ได้ไม่เต็มประสิทธิภาพ</p><h3>Prompting</h3><p>เป็นส่วนที่สำคัญเพราะมันคือ<strong> “ภาษาที่เราคุยกับ AI”</strong> — ถ้าเราพูดไม่ชัด หรือไม่เป็นโครงสร้าง AI ก็จะตอบไม่ตรงใจ หรือไม่ถูกต้อง ดังนั้นเราลองมาดูตัวอย่างง่ายๆกัน</p><h3>Prompting basic techniques</h3><p><strong>Zero-shot prompting</strong> เป็นการบอกให้ AI ทำอะไรให้เราสักอย่าง โดยที่เราไม่ได้ให้ตัวอย่างไปเลย</p><blockquote>Write a function that multiply two number in JavaScript</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OtQdaUgJlIUSbwRf2nAO-Q.png" /></figure><p><strong>Few-shot prompting</strong> เป็นการบอกให้ AI ทำอะไรให้เราสักอย่าง แต่ เราเพิ่มตัวอย่างของคำตอบ หรือ เราไกด์ให้ AI ว่าเราต้องการคำตอบ แบบไหน วิธีนี้ทำให้เราได้คำตอบที่ตรงมากขึ้น</p><blockquote>Create a JavaScript function that reverse string example cat to tac</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4I5f6K6V9ehOfPuRoKygng.png" /></figure><p><strong>Chain-of-Thought prompting </strong>เป็นการบอกให้ AI ทำอะไรสักอย่าง แต่ ต้องอธิบายมาว่า ทำยังไง/คิดยังไง ถึงได้คำตอบนี้มา</p><blockquote>Create a JavaScript function that reverse string explain step by step</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AEq_n3Ol-qYpTtd-C78M_A.png" /></figure><p>นี่เป็นตัวอย่างง่ายๆ ที่เราใช้กันทั่วไป เพื่อที่เราจะได้คำตอบจาก AI เรามาเริ่ม Advanced Prompt for Coding GPT-5 ตามหัวข้อกันเลยดีกว่า อิงตาม <a href="https://www.promptingguide.ai/"><strong>Prompt Engineering Guide</strong></a> ยังมีอีกหลาย technique ที่เราใช้</p><p>นอกจาก 3 วิธีที่อธิบายไปแล้ว ยังมีอีก 15 วิธี 🤯</p><ol><li><strong>Meta Prompting</strong> — สั่งให้ AI สร้างหรือปรับ <em>prompt</em> ให้ดียิ่งขึ้น</li><li><strong>Self-Consistency</strong> — สร้างหลายคำตอบแล้วเลือกอันที่สอดคล้อง/เหมือนกันที่สุด</li><li><strong>Prompt Chaining</strong> — แบ่ง task ออกเป็นลำดับ <em>prompt</em> ต่อเนื่อง แต่ละขั้น feed กัน</li><li><strong>Tree of Thoughts (ToT)</strong> — สำรวจหลาย <em>reasoning path</em> ก่อนเลือกวิธีแก้ที่ดีที่สุด</li><li><strong>Generated Knowledge Prompting</strong> — ให้โมเดลสร้าง <em>facts/knowledge</em> ก่อนตอบคำถาม</li><li><strong>Retrieval Augmented Generation (RAG)</strong> — ดึงข้อมูลจาก <em>external source</em> ก่อน generate คำตอบ</li><li><strong>Automatic Reasoning and Tool-use (ART)</strong> — ให้โมเดลเลือกและใช้ <em>tool</em> ภายนอกเอง</li><li><strong>Automatic Prompt Engineer (APE)</strong> — ใช้ AI สร้างและเลือก <em>prompt</em> ที่ดีที่สุดอัตโนมัติ</li><li><strong>Active-Prompt</strong> — โมเดลถามคำถามเพิ่มเติมเมื่อเจอกรณีไม่มั่นใจ</li><li><strong>Directional Stimulus Prompting</strong> — ใส่ <em>keyword/hint</em> เพื่อชี้นำ output ไปทิศทางที่ต้องการ</li><li><strong>PAL (Program-Aided Language Models)</strong> — ให้โมเดลเขียน/รันโค้ดเพื่อแก้ปัญหา</li><li><strong>ReAct Prompting</strong> — ผสม <em>reasoning (thought)</em> กับ <em>action (act)</em> แบบ dynamic</li><li><strong>Reflexion</strong> — โมเดลวิจารณ์ความผิดพลาดตัวเองเพื่อปรับปรุงรอบถัดไป</li><li><strong>Multimodal CoT Prompting</strong> — ขยาย <em>Chain-of-Thought</em> ให้ reasoning ได้ทั้ง text + image</li><li><strong>GraphPrompts</strong> — ใช้ <em>graph structure</em> ใน prompt เพื่อ reasoning ความสัมพันธ์ที่ซับซ้อน</li></ol><p>ซึ่งจะเห็นได้ว่าเยอะ และ ดูซับซ้อนจน งง ดังนั้นผมจึงสรุปการ craft prompt เพื่อใช้ใน GPT-5 มาให้เป็นตัวอย่างลองมาดูกันครับ</p><h3>Advanced Prompting in GPT-5</h3><p>โมเดลภาษา (Large Language Model: LLM) รุ่นล่าสุดของ OpenAI ให้ความสำคัญกับ <strong>reasoning และ understanding</strong> มากขึ้น ดังนั้นผู้ใช้งานจึงจำเป็นต้องอธิบายหลักเหตุและผลอย่างชัดเจน เพื่อให้ AI ทำงานได้อย่างถูกต้องและแม่นยำ</p><p>แม้ว่า <strong>GPT-5</strong> จะถูกพัฒนาต่อยอดมาจาก GPT-4 แต่ก็มีผู้ใช้จำนวนไม่น้อยที่รู้สึกว่า GPT-4 ตอบโจทย์มากกว่า ทั้งในด้านคุณภาพ ความตรงประเด็น และการหลีกเลี่ยงการ “over-engineer” หรือการทำงานที่ซับซ้อนเกินความจำเป็น</p><p>ด้วยเหตุนี้ <strong>prompting</strong> จึงมีบทบาทสำคัญในการช่วยให้ AI ทำงานได้อย่างมีประสิทธิภาพมากขึ้น วันนี้เราจะพามาทำความรู้จักกับ <strong>Advanced Prompting<br></strong>ตัวแรกคือ <strong>Multimodal CoT Prompting</strong></p><p><strong>Multimodal CoT Prompting</strong> เป็น prompt ที่เราจะให้ context ไม่ว่าจะเป็น ข้อความ รูป เสียง กราฟ ไปกับ prompt รวมกับการใช้ Chain-of-Thoughts เพื่อให้ AI อธิบายเป็นเหตุเป็นผลมากขึ้น ตัวอย่าง Prompt เช่น</p><blockquote>Here’s a step that shows:</blockquote><blockquote>1. Input a string 2. Reverse it 3. Compare with original 4. Return true/false</blockquote><blockquote>Think step by step and implement the JavaScript palindrome check function.</blockquote><p>จะเห็นได้ว่า เรามีการบอกว่าให้ step เข้าไปเพื่อให้ AI ได้ทำตามจากนั้นบอกว่า ทำให้ AI รู้และเข้าใจ context ของเรามากขึ้น</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZUp1pdMZb613JkqBLkXAEg.png" /></figure><p><strong>Prompt Chaining </strong>เป็นวิธีที่เราใช้ในงานที่ซับซ้อนขึ้นมา โดยเราแตกงานเป็นหลายขั้นตอน เอาผลลัพธ์ของแต่ละ prompt มาต่อกัน เพื่อให้ได้คำตอบสุดท้ายที่เราต้องการ</p><blockquote>Write a function in JavaScript that calculates the factorial of a number</blockquote><pre>function factorial(n) {<br>  if (n === 0) return 1;<br>  return n * factorial(n - 1);<br>}</pre><blockquote>From function above make the function iterative instead to avoid stack overflow for large numbers</blockquote><pre>function factorial(n) {<br>  if (typeof n !== &quot;number&quot; || n &lt; 0) {<br>    throw new Error(&quot;Input must be a non-negative number&quot;);<br>  }<br><br>  let result = 1;<br>  for (let i = 1; i &lt;= n; i++) {<br>    result *= i;<br>  }<br>  return result;<br>}</pre><p>จะเห็นได้ว่าเราแยก prompt ออกเป็น 2 prompt โดยใช้คำตอบของ อันแรกมาเป็นตัวอย่างให้ prompt ครั้งต่อไป แบบนี้จะทำให้ AI เข้าใจ context และ สิ่งที่เราจะทำมากขึ้นนั้นเอง</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bKVB0WLXj-BohS4aJylwbw.png" /></figure><p>เราดู 2 ตัวอย่างข้างบนเป็น advanced prompt ไปแล้ว เรามาลองเปรียบเทียบกับแบบที่เราไม่ใช้ prompting technique กัน</p><p>โดยตัวอย่างแรก prompt แบบไม่ใช้ technique</p><blockquote>Write a JavaScript function that checks if a number is prime</blockquote><pre>function isPrime(n) {<br>  if (n &lt;= 1) return false;<br>  for (let i = 2; i &lt; n; i++) {<br>    if (n % i === 0) {<br>      return false;<br>    }<br>  }<br>  return true;<br>}</pre><p>ในตัวอย่างนี้เราจะเห็นว่า Code ยังทำงานได้ก็จริง แต่! ไม่มีคำอธิบายว่า code นี้ทำงานยังไง และรวมไปถึงไม่ครอบคลุม Edge case เมื่อ input เยอะขึ้นเรามีการ loop ที่ไม่จำเป็น</p><p>ตัวอย่างที่สอง ใช้ <strong>Multimodal CoT Prompting</strong></p><blockquote>Think step by step using reasoning and if useful, show me a diagram or explanation before writing the JavaScript function that checks if a number is prime</blockquote><pre>Check n:<br> ├─ If n ≤ 1 → Not prime<br> ├─ If n = 2 → Prime<br> ├─ If n % 2 = 0 → Not prime<br> └─ Loop from 3 to √n, step 2:<br>        ├─ If divisible → Not prime<br>        └─ Else continue</pre><pre>function isPrime(n) {<br>  if (n &lt;= 1) return false;<br>  if (n === 2) return true;<br>  if (n % 2 === 0) return false;<br><br>  for (let i = 3; i &lt;= Math.sqrt(n); i += 2) {<br>    if (n % i === 0) {<br>      return false;<br>    }<br>  }<br>  return true;<br>}</pre><p>โดยเราจะเห็นว่า AI แสดงวิธีการทำงานของ function นี้ รวมถึงการ optimization และ ครอบคลุม edge cases</p><p>โดยสรุปแล้ว การให้ AI ทำงานเหมือนกัน แต่ ผลลัพธ์กลับต่างกันในด้านการใช้งาน การครอบคลุมผลลัพธ์และการทำความเข้าใจในการนำไปใช้ เมื่อเทียบกับการไม่ใช้ technique อะไรเลย</p><p>ผมยกมา 2 ตัวอย่างก็เริ่มงงกันแล้ว แต่!!! ผมมีวิธีเด็ดมานำเสนอ ที่จะเพิ่มประสิทธิ AI และรวมไปถึงได้ผลลัพธ์ที่มีสิทธิภาพใน Software development ผมมีวิธีการใหม่มานำเสนอคือ <strong>Gen-e2</strong></p><h3>PALO IT Gen-e2 Powered by GitHub Copilot</h3><p>Gen-e2 ย่อมาจาก <strong>Generative AI Enhanced Engineering</strong> เป็นการปฏิรูปวิธีพัฒนา Software โดยการที่เรา focus ไปที่ end-to-end product มากกว่าที่จะมา focus ที่ software engineering</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zX_JKrjnyNgDQKGUREAlpQ.png" /></figure><p>โดยภาพตัวอย่างเป็นข้อแตกต่าง ระหว่าง Traditional Approach กับ Gen-e2 โดยเราจะเห็นว่า Gen-e2 เน้นไปที่การเสริมสร้าง context ซึ่งสอดคล้องกับ GPT-5 ที่เน้น context และ reasoning เพื่อให้ AI สร้างผลลัพธ์ที่ตรงตามที่เราอยากได้</p><p>ทำไมต้อง Gen-e2</p><ol><li>Software delivers ได้เร็วขึ้น 2–5 เท่าในระยะเวลาเท่ากัน</li><li>Business team มีความมั่นใจในการ delivery with AI ถึง 90%</li><li>ลูกค้าประหยัดเวลาและต้นทุนถึง 25%-30%</li></ol><p>ตารางเปรียบเทียบระหว่าง การทำงานแบบ Traditional Approach กับ Gen-e2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PE5PqnkV3p7DGTI7vZrRwQ.png" /></figure><p>อธิบายคร่าวๆ สำหรับ Gen-e2 Powered by GitHub Copilot ไปแล้วเรามาดูวิธีการใช้ ในการ coding กันเลย โดยที่ผมจะจำลองว่าเราทำ dashboard เพื่อแสดงยอดขายในบริษัท PALO IT</p><p>เริ่มจาก project ที่ชื่อว่า PALO IT dashboard แล้วสร้าง directory ชื่อว่า ai-rules อยู่ภายใน project เพื่อใช้เป็น context ที่ AI จะอ่านเมื่อเรา prompt โดยเราจะสร้าง instructions file เพื่ออธิบายให้ AI ได้รู้ว่าเราจะทำอะไร และ ทำยังไง ในตัวอย่างนี้ผมจะสร้าง rule ง่ายๆ โดย step ดังนี้</p><ol><li>project-overview.instructions.md ใน file นี้เราจะอธิบายว่า project ของเรานั้นทำอะไร มีหน้าตาประมาณไหน มี business logic ยังไงบ้าง</li><li>design-system.instructions.md ใน file นี้เราจะอธิบายในเรื่องของ design เช่น การใช้สี การใช้ theme typography ขนาดของ font และ layout ของเรา</li><li>implementation-plan.instructions.md ใน file นี้เราจะอธิบายคร่าวๆ ว่า project ของเรามี development plan อย่างไร อะไรทำก่อน อะไรทำหลังและ status ของ plan</li></ol><p>มาเริ่ม set up กันเลย โดยเราcopilot-instructions.md โดยเราจะสร้าง prompt โดยให้ AI สร้าง instruction ให้เรา</p><blockquote>please create copilot-instructions.md to read my instructions in ai-rules directory</blockquote><p>โดยหน้าตาของ directory เราก็จะได้แบบนี้</p><pre>├── ai-rules<br>│   ├── design-system.instructions.md<br>│   ├── implementation-plan.instructions.md<br>│   └── project-overview.instructions.md<br>└──copilot-instructions.md</pre><p>เรามาดู ในแต่ละ file ของเราดีกว่า เริ่มจาก Project overview กันก่อนเลย โดยเราจะให้ AI generate project overview ให้เรา โดยเราจะ prompt ไปกับ AI ในแบบ <strong>Multimodal CoT Prompting</strong></p><blockquote>I am a developer I want you to create project overview for me, my project is to create sale dashboard for company named PALO IT</blockquote><blockquote>1. There will be 3 dashboards to show sale based on day,month, and year</blockquote><blockquote>2. When I click on dashboard I can compare my company sale with previous peroid</blockquote><blockquote>3. Only company admin is able to access this dashboard</blockquote><blockquote>4. This dashboard will only be used internally</blockquote><p>เราก็จะได้ผลลัพธ์แบบนี้ ใน file project overview</p><pre>---<br>description: Sales Performance Dashboard - Project Overview<br>applyTo: &quot;**&quot;<br>---<br><br># Sales Performance Dashboard - Project Overview (PALO IT Internal)<br><br>## Product Vision<br>Provide PALO IT company administrators with a fast, reliable, single internal interface to monitor, compare, and analyze sales performance across daily, monthly, and yearly perspectives to enable timely, data‑driven decisions.<br><br>## Strategic Objectives<br>- Unify sales visibility (day / month / year) in one secure internal tool<br>- Accelerate decision cycles via instant comparative analytics<br>- Standardize KPIs and reduce manual spreadsheet effort<br>- Ensure only authorized company admins access sensitive revenue data<br><br>## Core User Journey<br>1. Authenticate (Company Admin SSO / IAM)  <br>2. Land on default (Today vs Previous Day) dashboard  <br>3. Switch tabs: Daily | Monthly | Yearly  <br>4. Apply filters (date range, business unit, region, product category)  <br>5. (Optional) Enable Compare Mode (e.g., This Month vs Last Month / This Year vs Last Year / Custom Period vs Period)  <br>6. Drill into variance explanations (delta, % change, contribution)  <br>7. Export snapshot / share internal link  <br>8. Sign out (session timeout enforced)<br><br>## Primary Persona<br>- Company Admin (Finance / Sales Ops / Leadership) – Full read access, comparison, export.<br><br>## Non-Persona (Explicitly Excluded)<br>- External users / clients (no access)  <br>- Standard employees without sales clearance  <br><br></pre><p>เรามาดูในส่วนของ design system กันต่อเลย prompt สร้างตามนี้ได้เลย รอบนี้เราจะอ้างอิง doc จาก ตัว project overview ของเรา</p><blockquote>From project-overview.instructions.md I’ve created project overview now let’s create design system I will be using</blockquote><blockquote>1.Chakra UI v2 as</blockquote><blockquote>2.React with TypeScript</blockquote><blockquote>3.My font will be `’Open Sans’, ‘Montserrat’, sans-serif` with different size</blockquote><pre>---<br>description: Any frontend implementation, this is the design guidelines<br>applyTo: &quot;**&quot;<br>---<br>## Design System Overview<br>Sale Dashboard System is built on **Chakra UI v2** and provides a <br>comprehensive set of design tokens, components, and guidelines for <br>building consistent user interfaces across the Impact Tracker platform. <br>The system follows atomic design principles and emphasizes accessibility, <br>customization, and developer experience.<br><br>**Key Technologies:**<br>- Chakra UI v2 as the foundation<br>- React with TypeScript<br>**Design Principles:**<br><br>- **Developer Experience**: Well-documented APIs and reusable components<br>## Typography<br><br>The typography system uses a hierarchical scale with semantic naming <br>conventions for different text styles.<br><br>### Font Family<br>- **Primary**: `&#39;Open Sans&#39;, &#39;Montserrat&#39;, sans-serif`<br>- **Weights**: 300 (Light), 400 (Regular), 500 (Medium), <br>600 (SemiBold), 700 (Bold)</pre><p>ส่วนสุดท้าย คือ implementation-plan โดยเราจะกำหนด develop ment plan ว่าอันไหนทำก่อน ทำหลัง และ status</p><blockquote>Refer to my design-system.instructions.md and project-overview.instructions.md create implementation plan that will be implement in next 4 weeks</blockquote><pre>---<br>status: draft<br>source: design-system + project-overview<br>scope: Sales Performance Dashboard (Internal)<br>lastUpdated: 2025-09-15<br>---<br><br># Implementation Plan<br><br>## 1. Objectives Alignment<br>- Deliver an internal Sales Performance Dashboard enabling unified day/month/year KPIs, comparative analytics, and secure access.<br>- Adhere to design system basics (typography + Chakra UI v2 foundation) while anticipating expansion of tokens/components.<br>- Optimize for accessibility, reliability, and extensibility.<br><br>## 2. High-Level Architecture<br>- Frontend: React + TypeScript + Chakra UI v2 (component theming, responsive layout) <br>- State Management: React Query (server cache) + lightweight local UI state via React Context or zustand if complexity grows.<br>- Auth: Placeholder SSO/IAM adapter (mock for initial phase, interface-driven for future integration).<br>- Data Layer: API service abstraction (REST endpoints; future GraphQL compatibility). <br>- Feature Modules: `auth`, `dashboard-core`, `filters`, `analytics-comparison`, `exporting`.<br>- Theming: Central `theme` extending Chakra (typography scale, color palette once defined, spacing ramp).<br>- Testing: Jest + React Testing Library + MSW (API mocking) + Playwright (critical flows, later phase).<br><br>## 3. Delivery .... week 1 to 4<br>Phase 0: Set up tooling (Vite/TS/Chakra), theme scaffold, auth mock, API client, routing, and CI baseline.<br>Phase 1: Build core dashboard shell with daily KPIs, charts, filters, and resilient loading/error states.<br>Phase 2: Add monthly/yearly views, compare mode, and initial variance explanation drawer.<br>Phase 3: Introduce contribution breakdown, export (CSV/PNG groundwork), and sharable state links.<br>Phase 4: Harden performance, accessibility (WCAG AA), error boundaries, and security checks.<br>Phase 5: Finalize docs, monitoring hooks, backlog triage, and release readiness.</pre><p>ผลลัพธ์ก็ตามนี้เลย</p><p>จะเห็นได้ว่า แค่นี้ set up ของเราก็เสร็จแล้วพร้อมใช้สำหรับ user story ของเราได้เลย โดย AI จะอิงจาก instruction ที่เราสร้างไว้แล้ว แล้วนำไป implement ให้เราโดยที่เราไม่ต้องลง technical เรื่อง prompt เลย โดยให้ AI implement ตาม plan ที่สร้างไว้แล้ว</p><p>จะเห็นได้ว่า set up แค่ไม่กี่นาที ก็สามารถสร้าง contextให้ AI ทำงานได้ในแบบที่เราต้องการได้แล้ว เพียงแค่ prompt <strong>Let’s create our app</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NcxqOqv938wGzS-fxLD8FA.png" /></figure><p>เราก็จะได้ผลลัพธ์แบบนี้เลย โดยไม่ต้องใช้เทคนิคอะไรให้ยุ่งยาก</p><p>หากองค์กรของคุณต้องการเพิ่ม Productivity ให้กับทีมงาน ด้วยการอัปสกิลให้ใช้ AI และ GPT-5 ได้อย่างเต็มประสิทธิภาพ ปลอดภัย และตรงตามมาตรฐานขององค์กร ติดต่อ PALO IT Thailand เพื่อช่วยประเมิน เทรนนิ่ง ออกแบบเวิร์กโฟลว์ หรือทำ Pilot Project แบบวัดผลได้ ติดต่อพวกเราได้ที่ <strong>Facebook Page: </strong><a href="https://www.palo-it.com/th/"><strong>PALO IT Thailand</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99422e48c480" width="1" height="1" alt=""><hr><p><a href="https://medium.com/palo-it-thailand/advanced-prompt-for-coding-gpt-5-%E0%B9%80%E0%B8%A1%E0%B8%B7%E0%B9%88%E0%B8%AD-%E0%B8%A8%E0%B8%B4%E0%B8%A5%E0%B8%9B%E0%B8%B0%E0%B8%81%E0%B8%B1%E0%B8%9A%E0%B8%A7%E0%B8%B4%E0%B8%97%E0%B8%A2%E0%B8%B2%E0%B8%A8%E0%B8%B2%E0%B8%AA%E0%B8%95%E0%B8%A3%E0%B9%8C%E0%B8%A1%E0%B8%B2%E0%B9%80%E0%B8%88%E0%B8%AD%E0%B8%81%E0%B8%B1%E0%B8%99-99422e48c480">Advanced Prompt for Coding GPT-5 เมื่อ ศิลปะกับวิทยาศาสตร์มาเจอกัน</a> was originally published in <a href="https://medium.com/palo-it-thailand">PALO IT THAILAND</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agentic Pattern Design ภาคปฏิบัติ โจทย์ ที่ 2— Unstructured Dataset Analytic Agent]]></title>
            <link>https://medium.com/palo-it-thailand/agentic-pattern-design-%E0%B8%A0%E0%B8%B2%E0%B8%84%E0%B8%9B%E0%B8%8F%E0%B8%B4%E0%B8%9A%E0%B8%B1%E0%B8%95%E0%B8%B4-%E0%B9%82%E0%B8%88%E0%B8%97%E0%B8%A2%E0%B9%8C-%E0%B8%97%E0%B8%B5%E0%B9%88-2-unstructured-dataset-analytic-agent-1a71956ddb46?source=rss----3ae4f2a55b01---4</link>
            <guid isPermaLink="false">https://medium.com/p/1a71956ddb46</guid>
            <dc:creator><![CDATA[Sarin Suriyakoon]]></dc:creator>
            <pubDate>Fri, 10 Oct 2025 04:33:42 GMT</pubDate>
            <atom:updated>2025-10-23T04:39:29.153Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3y6hcuJdwQ7EDV-U_C07Xg.jpeg" /></figure><p>ในโจทย์นี้เรามาดูอีกหนึ่งงานจริงที่ทางผมและน้องในทีมได้ร่วมมือกับทีมวิจัย IRD ในการ วิเคราะห์ฐานข้อมูล (PDF, Image ทั้งหมด 2,287 files) ข่าวเกี่ยวกับ Air Pollution ทั้งภาษาไทยและอังกฤษ โดยใช้ LLM ช่วยแปล และคัดกรองข้อมูลให้สามารถเอาไปทำ Data Analytics ได้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hHyOqFmLraJberWw65NMkg.png" /></figure><h3>ที่มาและความสำคัญ</h3><p>โจทย์จากลูกค้าซึ่งเป็นนักวิจัยของสถาบันวิจัย IRD คือ ก่อนหน้านี้เค้ามีการทำงานวิจัยที่คล้ายๆ กันนี้กับข่าวที่เกี่ยวกับ Air Pollution ของเชียงใหม่เท่านั้น ซึ่งสมัยก่อนข่าวเป็นภาษาอังกฤษ และ เป็นข่าวของเชียงใหม่เท่านั้น ทางทีมงานวิจัยใช้วิธีอ่านและวิเคราะห์ลง Excel เพื่อนำตัวเลขที่น่าสนใจมาสรุปเป็นกราฟ</p><p>สามารถอ่านผ่านๆ กันได้ ใน <a href="https://englishkyoto-seas.org/2023/08/vol-12-no-2-olivier-evrard-and-mary-mostafanezhad/">https://englishkyoto-seas.org/2023/08/vol-12-no-2-olivier-evrard-and-mary-mostafanezhad/</a></p><p>หลายปีถัดมา ในปี 2025 คราวนี้นักวิจัยต้องการนำข่าวทั้งภาษาไทยและภาษาอังกฤษ ในเขตพื้นที่กรุงเทพมาวิเคราะห์รวมกัน ซึ่งเป็นปริมาณที่มากขึ้นและเป็นภาษาที่นักวิจัยไม่คุ้นเคย (ภาษาไทย) การจะวิเคราะห์ฐานข้อมูลชุดใหม่นี้ได้ จำเป็นต้องใช้นักแปล หรือ …LLM</p><p>จะเห็นได้ว่า LLM หรือเทคโนโลยีที่เกิดขึ้นใหม่สามารถช่วยเร่งความเร็วในการทำงานวิจัยตัวนี้ได้ (แน่นอนว่าต้องแสดงความโปร่งใสในการใช้ LLM ในการทำงานวิจัย) เงื่อนไขคือ Agent ตัวนี้ต้องใช้เวลาเขียนโค้ด ออกมาให้ได้เป็น Excel/CSV ภายในสองอาทิตย์ และนักวิจัยจะนำ Excel/CSV ไปวิเคราะห์ต่อเอง</p><h3>วิเคราะห์ Pain Point</h3><p>หลังจากหา pain point และปัญหาจากนักวิจัยอย่างละเอียดแล้ว สิ่งที่เสนอคือ ทาง PALO IT จะ produce Excel/CSV ให้ทางนักวิจัยจะนำไปถาม Chatbot ในท้องตลาดเอง (ChatGPT,Google Gemini, Google BigQuery etc) เนื่องจากในปัจจุบัน Chatbot สามารถเขียนโค้ดในการวิเคราะห์ dataset ได้เป็นอย่างดี และ domain knowledge เกี่ยวกับ dataset ชุดนี้รวมถึงคำถามที่นักวิจัยอยากรู้และพล็อตเป็นกราฟ นักวิจัยจะรู้ดีที่สุด (Subject Matter Expert)</p><p>ทาง PALO IT จะสร้าง Agent ที่สามารถ Digest PDF และ Image Dataset ให้มาอยู่ในรูปแบบ Excel/CSV ที่นักวิจัยคุ้นเคยเอง</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EuHV8rcMsR7nJtXzAz70Jw.png" /></figure><h3>Solution</h3><p>หลังจากวิเคราะห์ Pain Point และความปรับความคาดหวังของนักวิจัยเรียบร้อยแล้ว ทางเราจึงได้เสนอ Solution ตามด้านล่าง</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JTumdoARAMehqPOxW1NQfw.png" /><figcaption>Data Pipeline Workflow</figcaption></figure><h4><strong>Solution Explanation</strong></h4><p>A — ตรงนี้ถือเป็นจุดเริ่มต้นเรานำ Database ไว้ใน Repository เรา</p><p>B — หลังจากนั้นเราจะใช้ PDF to Markdown Agent ในการแปลง PDF ทั้งหมดให้อยู่ในรูปแบบที่ LLM เอาไปอ่านต่อได้ (อ่านเพิ่มเติมได้ใน section “Model Selection”)</p><p>C — ใน Step นี้เราจะได้ Markdown ออกมา Save เก็บไว้เป็น 1 PDF ต่อ 1 Markdown file ใน path รูปแบบเดียวกับ Dataset สาเหตุที่เลือกจะเก็บ Markdown ในรูปแบบนี้เพราะ 1. ทางเราต้องการใช้ Human และ <strong>LLM-as-a-judge</strong> เพื่อตรวจสอบผลลัพธ์บางส่วนก่อน ไปขั้นตอนถัดไป หากคุณภาพไม่ได้ (จากการ sample 20–30 file) ก็จะทำการ ปรับ Prompt และรัน pipeline ใหม่ 2. PDF ใน Dataset มีแค่ 1 หน้า ต่อไฟล์เท่านั้น จึงเหมาะกับจะทำเป็น 1 Markdown อย่างยิ่ง</p><p>D — ในขั้นตอนนี้เราจะนำ Markdown File ที่ได้มาใช้ในการวิเคราะห์ในหัวข้อเฉพาะเจาะจง โดยในแต่ละหัวข้อมีความซับซ้อน (มี json keys หลายตัว) แตกต่างกันไป ทางเราได้ตัดสินใจ แยก Agent ออกเป็นหัวข้อ เพื่อให้ Agent แต่ละตัวมี seperation of concert กับ Optimize prompt / json output แยกกันไป และสามรถช่วยกันทำงานได้เป็นส่วนๆ โดยไม่กระทบ accuracy กัน</p><p>E — หลังจากที่ เหล่า [Topic] Extract Agent ทำงานเสร็จเราจะเก็บ result แต่ละอันไว้เป็นไฟล์ JSON แล้วนำไป Clean และ Process ใน Google BigQuery และแปลงกลับมาเป็น CSV/Excel ของแต่ละหัวข้อ ซึ่งแต่ละ Excel/CSV จะถูกนำไป plot เป็น graph ต่อใน Paper โดยนักวิจัย</p><h4>Model Selection สำหรับ Data Ingestion/OCR</h4><p>Model ที่เลือกใช้ในโปรเจคนี้คือ <strong>Gemini 2.5 Pro/Flash</strong>(ในส่วนที่รัน pipeline ใหญ่) เพราะจากการทดลอกับ Dataset ที่มีได้ความแม่นยำสำหรับงานอ่าน PDF ได้ผลลัพธ์ที่ดีกว่าตัวอื่นๆ ในตลาด เช่น Typhoon OCR, GPT-4.1, Qwen2.5-VL, LLama 4.1</p><p>ในทางเขียน Code เราใช้ Google Gen AI SDK ที่ทำการแปลง PDF ไปอยู่ในรูปแบบ Markdown ให้แบบ <a href="https://ai.google.dev/gemini-api/docs/document-processing">Native Vision</a> เราแค่ใช้ SDK ชี้ไปที่ไฟล์ที่ต้องการอัพโหลดไปพร้อมกับ prompt “Convert the document content to English text formatted in markdown”</p><p>หมายความว่า PDF “น่าจะ” ถูกแปลงเป็น Image ก่อนส่งไปให้ Model นั่นทำให้ตัว Gemini Leverage Multimodal Capability ได้อย่างเต็มที่ ต่างจาก การ Parse PDF to Raw Text ซึ่งโดยส่วนใหญ่ ได้ Output ออกมาอ่านยากและทำให้ LLM ให้ผลลัพธ์ที่ไม่ดี</p><p>ด้วยความที่ Dataset ของเราส่วนใหญ่เป็น 1 page PDF กระบวนการที่กล่าวไปข้างบนจึงเหมาะสมที่สุด</p><h3>รายชื่อ Extractor Agents</h3><p>ก่อนและระหว่างทำงานเราได้มีการพูดคุยกับนักวิจัยอย่างใกล้ชิดว่า graph ที่อยากได้สุดท้ายมีอะไรบ้าง แล้วเราตีโจทย์ออกมาเป็น Agent แต่ละตัวโดยตรงที่สามารถนำผลลัพธ์ไป Plot ได้เลย ซึ่งรายชื่อของ Agent มีดังนี้</p><ul><li><strong>Causes Extractor Agent</strong></li><li><strong>Health Problem Extractor Agent</strong></li><li><strong>Location Extractor Agent</strong></li><li><strong>Severity Extractor Agent</strong></li><li><strong>Stakeholder Extractor Agent</strong></li><li><strong>Obstacle Extractor Agent</strong></li><li><strong>Civil Society Movement Extractor Agent</strong></li></ul><h3>บทสรุป</h3><p>หากใครกำลังมองหา Consult มาช่วยสร้าง Agentic AI หรือช่วยปรับปรุง AI Agent ที่มีอยู่แล้วให้มี Accuracy และ Scale ได้</p><p>ติดต่อทีมงาน PALO IT Thailand ได้ที่ <strong>Facebook: PALO IT Thailand</strong> <strong>(</strong><a href="https://www.facebook.com/PALOITTH"><strong>https://www.facebook.com/PALOITTH</strong></a><strong>)</strong></p><h3>Special Thanks to Reviewers</h3><ul><li>คุณ Sippakorn Raksakiart ที่ช่วยรีวิวและเสนอแนะเรื่องการใช้ Final Merger</li><li>คุณ Job Natdhanai ที่ช่วยรีวิวและชี้แนะเรื่องการใส่รายละเอียดในส่วนของ data ingestion</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a71956ddb46" width="1" height="1" alt=""><hr><p><a href="https://medium.com/palo-it-thailand/agentic-pattern-design-%E0%B8%A0%E0%B8%B2%E0%B8%84%E0%B8%9B%E0%B8%8F%E0%B8%B4%E0%B8%9A%E0%B8%B1%E0%B8%95%E0%B8%B4-%E0%B9%82%E0%B8%88%E0%B8%97%E0%B8%A2%E0%B9%8C-%E0%B8%97%E0%B8%B5%E0%B9%88-2-unstructured-dataset-analytic-agent-1a71956ddb46">Agentic Pattern Design ภาคปฏิบัติ โจทย์ ที่ 2— Unstructured Dataset Analytic Agent</a> was originally published in <a href="https://medium.com/palo-it-thailand">PALO IT THAILAND</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agentic Pattern Design ภาคปฏิบัติ โจทย์ ที่ 1 — Document to Graph Agent]]></title>
            <link>https://medium.com/palo-it-thailand/agentic-pattern-design-%E0%B8%A0%E0%B8%B2%E0%B8%84%E0%B8%9B%E0%B8%8F%E0%B8%B4%E0%B8%9A%E0%B8%B1%E0%B8%95%E0%B8%B4-%E0%B9%82%E0%B8%88%E0%B8%97%E0%B8%A2%E0%B9%8C-%E0%B8%97%E0%B8%B5%E0%B9%88-1-document-to-graph-agent-e4b8e9f705c5?source=rss----3ae4f2a55b01---4</link>
            <guid isPermaLink="false">https://medium.com/p/e4b8e9f705c5</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agentic-workflow]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Sarin Suriyakoon]]></dc:creator>
            <pubDate>Fri, 19 Sep 2025 03:18:12 GMT</pubDate>
            <atom:updated>2025-09-19T03:17:28.677Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*vjyixFqlQVd6GAECPWcJIg.jpeg" /></figure><h3>Agentic Pattern Design ภาคปฏิบัติ โจทย์ ที่ 1 — Document to Graph Agent</h3><p>ปัญหาหลักที่ได้รับฟี้ดแบคมาคือ Developer ที่เพิ่งเริ่มต้นทำระบบ LLM/Agent ไม่รู้จะนำ ทฤษฎี <a href="https://www.anthropic.com/engineering/building-effective-agents"><strong>Agentic Pattern</strong></a> ที่อ่านมาจากในเน็ต มาประยุกต์ยังไง บทความนี้จะมาเล่าให้ฟังว่า จากโจทย์ที่เราได้รับมาจากลูกค้า เราใช้ Agentic Pattern อันไหน ที่เราใช้ช่วยแก้ปัญหาให้ลูกค้าได้จริงๆ</p><p>ด้วยเหตุนี้เลยอยากเขียนบทความนำเคสการออกแบบ Agentic Pattern จริงๆ มาแบ่งปันกัน โดยดั้งใจว่าจะแบ่งออกเป็นตอนๆ</p><h3>Pre-requisite</h3><ol><li>เคยอ่านบทความ <a href="https://www.anthropic.com/engineering/building-effective-agents">https://www.anthropic.com/engineering/building-effective-agents</a> ผ่านๆ มาบ้าง</li><li>เคยมีประสบการณ์การใช้ LLM ทำแอพมาก่อน ไม่ว่าจะเป็นโปรเจคเล่นๆ หรือทำให้ลูกค้าจริงจัง</li></ol><h3>หมายเหตุ</h3><ol><li>ก่อนอื่นต้องของท้าวความก่อนว่า Agentic Pattern มีการพูดถึงแต่ยังไม่มีใคร standadize terms อย่างเป็นทางการ จน Anthropic เค้าออกบทความและ learning resource อื่นๆ มาเพื่อ standadize terms ให้เข้าใจตรงกัน บทความนี้ผมก็จะใช้ term เหล่านั้นในการอ้างอิง</li><li>ตัวอย่างที่เห็นในบทความนี้คือประสบการณ์จริง ที่เอามาดัดแปลงเพื่อให้สามารถถ่ายทอดเป็นความรู้ได้</li><li>เพื่อความง่ายในการทำความเข้าใจ ให้คิดไว้ว่าจุดประสงค์ของ Agentic Pattern เหล่านี้คือการเพิ่มความแม่นยำของคำตอบ ให้ได้มากที่สุด ในเวลาที่เร็วที่สุด</li><li>บทความเหล่านี้ เหมาะสำหรับ Developer ที่กำลังทำ backend application ที่ใช้ LLM ในการแก้ปัญาทางธุรกิจ เรียกง่ายๆ ก็คือ backend คุณไปเรียก LLM api นั่นเอง</li></ol><h3>โจทย์ที่ 1: Document to Graph Agent— Agent สำหรับ วิเคราะห์รายงานประจำปีของบริษัทใน SET (ตลาดหุ้นไทย)</h3><p>หน้าที่ของ agent ตัวนี้คือการอ่าน และวิเคราะห์ รายงานประจำปี และทำรายงานสรุปออกมาเฉพาะส่วนที่สนใจ อย่างเช่น งบกำไรขาดทุน งบฐานะการเงิน งบกำไรขาดทุนเบ็ดเสร็จ</p><p><strong>Input คือ รายงานประจำปี</strong></p><p><strong>Output คือ JSON data ที่จะนำไป ทำกราฟสรุป 3 กราฟ</strong></p><ul><li>Graph งบกำไรขาดทุน</li><li>Graph งบฐานะการเงิน</li><li>Graph งบกำไรขาดทุนเบ็ดเสร็จ</li></ul><p>ตัวอย่างด้านล่างคือ JSON และ กราฟที่จะนำไปพล็อต</p><pre>{<br>  &quot;periods&quot;: [&quot;Q1&quot;, &quot;Q2&quot;, &quot;Q3&quot;, &quot;Q4&quot;],<br>  &quot;incomeStatement&quot;: {<br>    &quot;revenue&quot;: [120, 150, 170, 200],<br>    &quot;expenses&quot;: [80, 100, 120, 140]<br>  },<br>  &quot;balanceSheet&quot;: {<br>    &quot;assets&quot;: [500, 550, 600, 650],<br>    &quot;liabilities&quot;: [300, 320, 340, 360]<br>  },<br>  &quot;comprehensiveIncome&quot;: {<br>    &quot;netIncome&quot;: [40, 50, 55, 60],<br>    &quot;otherIncome&quot;: [5, -3, 8, 2]<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BsW66m7FsMDQ1UpaS9xuzQ.png" /></figure><p>เรามาลองวิเคราะห์การวาง structure AI แบบต่างๆ เริ่มจากแบบแรก</p><h3><strong>Solution เริ่มต้น — Naive Approach(กำปั้นทุบดิน)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HpiLK8OnJrNVBVZ8_xH10Q.png" /><figcaption>Naive Approach</figcaption></figure><p><strong>ตัวอย่าง Pseudo Prompt</strong></p><blockquote>&lt;Context&gt;[Report Content]&lt;/Context&gt;<br>From the given report in xml tag above, Extract ….</blockquote><p>โครงสร้างแรกที่เรามักจะเริ่มคือการใช้ LLM ในแบบเดียวกับ ChatGPT ปี 2023 นั่นก็คือใส่ Input ให้ LLM ส่งทุกอย่างออกมาเป็นอันจบ</p><h4><strong>วิเคราะห์ Input</strong></h4><p>ข้อเสียของวิธีนี้คือ ถ้า report มีขนาดใหญ่ LLM มีโอกาส Hullucinate สูงมาก ซึ่งในความเป็นจริง report ทางการเงินของบริษัทในตลาดหุ้นจะมีขนาดค่อนข้างใหญ่ ประมาณ 100–1000 หน้า โดยประมาณ</p><p>และถ้า Input content มีขนาดใหญ่เกิน LLM ก็จะส่ง error กลับมา</p><h4>วิเคราะห์ Output</h4><p>ลองสมมุติว่า LLM เราสามารถ รับ Input ได้ และเราจะใช้การ plot graph โดยการให้ LLM extract เฉพาะตัวเลขของแต่ละไตรมาส ของแต่ละ graph ออกมา เป็น JSON ให้ function code ของเราเอาไปใช้ต่อได้ อันนี้น่าจะทำได้ไม่ยาก เพราะ LLM api ส่วนใหญ่ support structure output แล้ว</p><p>ฝากไว้อีกนิดนึง ถ้าหากสามารถ ให้ LLM แค่ extract text/number แล้วสามารถคำณวนต่อเองในโค้ดได้แนะนำให้ทำเป็นอย่างยิ่ง พยายามอย่าให้ LLM คำณวนตัวเลขเองเพื่อความแม่นยำสูงสุด</p><h4>วิเคราะห์การเขียน Prompt</h4><p>การที่จะ fine tune prompt ให้สามารถทำ graph ทั้ง 3 อันเป็นไปได้ยาก หากมีความต้องการยิบย่อยจากลูกค้าเพียงเล็กน้อย เราจำเป็นต้องทดสอบและปรับแก้ Prompt ที่มีขนาดใหญ่มากๆ หากท่านเคย fine-tune prompt ก็จะรู้ว่าเพียงแค่ขยับนิดหน่อยจะทำให้ผลลัพธ์ต่างออกไปมากน้อย ก็ไม่สามารถคาดเดาได้</p><h4>สรุปการวิเคราะห์ Solution เริ่มต้น</h4><p>จากการ วิเคราะห์ทั้งสามส่วนสามารถ สรุปได้ว่า</p><ol><li>ขนาด output มีขนาดใหญ่เกิน สามารถแก้ได้ด้วยการใช้ RAG</li><li>งานที่ LLM ต้องทำมี scope กว้างเกิน สามารถแก้ได้ด้วยการให้ 1 LLM Agent ทำแค่ 1 Graph ซึ่งจะง่ายต่อการ Optimize Accuracy ให้จบทีละตัว</li></ol><h3>Solution ปรับปรุง — RAG+Apply Agentic Pattern “Workflow: Parallelization”</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*shc3blspFtuB-rUeQyqV9g.png" /><figcaption>RAG+Apply Agentic Pattern</figcaption></figure><p><strong>ตัวอย่าง Pseudo Prompt</strong></p><blockquote>&lt;Context&gt;[Only Relevant Report Content]&lt;/Context&gt;<br>From the given report in xml tag above, Extract [Income Sheet/Balance Sheet/Comprehensive Income]….</blockquote><p>จากบทสรุปของ Solution แรก ทำให้เราต้องปรับปรุง Agentic Design ของเราวะน้อย มาสู่ Diagram ที่เป็น RAG+Agentic Pattern(ในที่นี้ผมไม่ได้อธิบายเรื่อง RAG อย่างละเอียด แนะนำให้ไป google เพิ่มเติมหรือดูในบทความน้องริวกับน้องนัด)</p><p><strong>RAG</strong> มีหน้าที่ในการหา Relevant content(เนื้อหาหน้าที่เกี่ยวข้องกับกราฟนั้นๆ) ไปเป็นส่วนหนึ่งของ Prompt</p><p><strong>Agentic Pattern</strong> ที่เหมาะกับงานนี้คือ <a href="https://www.anthropic.com/engineering/building-effective-agents#:~:text=cost%20and%20speed.-,Workflow%3A%20Parallelization,-LLMs%20can%20sometimes"><strong>Workflow: Parallelization</strong></a> คือการแบ่งงานเป็น section แล้วเรียก LLM parallel กัน(นึกถึง promise all ใน javascript/typescript)</p><p>เมื่อได้รับ result ของทุกตัวออกมาแล้วเราก็จะเขียนโค้ดให้ รวม JSON ของทั้ง 3 agent เข้าด้วยกัน</p><p>เรามาวิเคราะห์ Agentic Design ตัวนี้กัน</p><h4>วิเคราะห์ Input</h4><p>จะเห็น ได้ว่า Prompt จะมีขนาดเล็กลงอย่างเห็นได้ชัด เพราะคัดมาแต่เนื้อหาที่เกี่ยวข้อง ทำให้ความแม่นยำไม่เปลี่ยนไปตามขนาดของ Report(แต่ RAG ก็ยังต้อง Optimize อีก)</p><h4>วิเคราะห์ Output</h4><p>Output ของแต่ละ LLM Call มีขนาดเล็กลง เพราะแต่ละตัว โฟกัสแค่งานอย่างเดียว</p><h4>วิเคราะห์การเขียน Prompt</h4><p>จะเห็นได้ว่าหลังจากแยก LLM หรือ Agent เป็น กราฟละหนึ่งตัวแล้ว การเขียน Prompt จะง่ายขึ้นมาก เพราะสามารถแก้ prompt ของ แต่ละอันได้อย่างอิสระหรือมี seperation of concern นั่นเอง เราสามารถ แก้ Income Statement Prompt ได้ โดยที่ไม่ต้องกังวลว่าจะมีผลกับ Balance Sheet</p><h4>สรุปการวิเคราะห์ Solution ปรับปรุง</h4><p>จากการปรับปรุงและวิเคราะห์ Agentic Pattern ทั้งสามส่วนด้านบน สามารถสรุปได้ว่า</p><ol><li>Agentic Pattern — Workflow: Parallelizationไม่เพียงทำให้ความแม่นยำของ Agent มากขึ้น แต่ความเร็วในการทำงานของระบบไม่ได้ตกลงเยอะ เพราะสามารถ ทำงานคู่ขนานกันไปได้</li><li>Agentic Pattern — Workflow: Parallelization นอกจากจะเป็นประโยชน์ในการเพิ่มประสิทธิภาพของ Agent แล้วยังช่วยให้การ develope ระบบง่ายขึ้นเพราะ developer ไม่จำเป็นต้องรอหรือมี dependency ระหว่างกันตอนพัฒนาแต่ละส่วน</li><li>RAG มีส่วนสำคัญที่ช่วยให้ขนาดของ Relevant Content ลดลงเป็นอย่างมาก ซึ่งช่วยให้การ scale เป็นไปได้มากขึ้นถ้าขนาด document มีขนาดมากขึ้น ตัวอย่างเช่น ไม่ว่าเอกสารต้นฉบับจะมี 100 หน้า หรือ 200 หน้า RAG ก็ยังดึง Top K ปริมาณเท่าเดิมออกมา</li></ol><h3>สรุปโจทย์ 1</h3><p>จากตัวอย่างการออกแบบ Agentic Pattern ด้านบนจะเห็นได้ว่า Parallelization จะค่อนข้างทรงพลังอย่างมากถ้าเอามาใช้ให้ถูกกับเนื้องาน ซึ่งส่วนตัวมองว่า Parallelization เป็น Pattern แรกๆที่ทุกคนมีโอกาสจะหยิบไปใช้งาน</p><p>ถ้าใครชอบบทความนี้แล้วอยากเห็นโจทย์ถัดไปสามารถติดตามกันได้เลย</p><p>หากท่านไหนต้องการปรึกษาหรือหาคนช่วยทำ Agentic AI Workflow, รีวิว Agentic Architecture, ปรับ Prompt &amp; Template, เลือกเครื่องมือ RAG, เขียนโค้ดรวมผลลัพธ์/แปลงเป็น JSON, ไปจนถึงตั้งค่า Guardrails/Observability สำหรับใช้งานจริงในองค์กร ให้ทีม <strong>PALO IT Thailand</strong> เข้าไปช่วยทำได้เลย!</p><p>ติดต่อพวกเราผ่าน <a href="https://www.facebook.com/PALOITTH"><strong>Facebook: PALO IT Thailand</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4b8e9f705c5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/palo-it-thailand/agentic-pattern-design-%E0%B8%A0%E0%B8%B2%E0%B8%84%E0%B8%9B%E0%B8%8F%E0%B8%B4%E0%B8%9A%E0%B8%B1%E0%B8%95%E0%B8%B4-%E0%B9%82%E0%B8%88%E0%B8%97%E0%B8%A2%E0%B9%8C-%E0%B8%97%E0%B8%B5%E0%B9%88-1-document-to-graph-agent-e4b8e9f705c5">Agentic Pattern Design ภาคปฏิบัติ โจทย์ ที่ 1 — Document to Graph Agent</a> was originally published in <a href="https://medium.com/palo-it-thailand">PALO IT THAILAND</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>