<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Daniel Le on Medium]]></title>
        <description><![CDATA[Stories by Daniel Le on Medium]]></description>
        <link>https://medium.com/@khoadaniel?source=rss-39eff8d630fd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TJzSpU4qNpXTpQQswWFFqg.jpeg</url>
            <title>Stories by Daniel Le on Medium</title>
            <link>https://medium.com/@khoadaniel?source=rss-39eff8d630fd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 23:14:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@khoadaniel/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Judge an LLM Judge: A Dual-Layer Evaluation Framework for Continuous Improvement of LLM Evaluation]]></title>
            <link>https://medium.com/data-science/judge-an-llm-judge-a-dual-layer-evaluation-framework-for-continous-improvement-of-llm-apps-7450d0e81e17?source=rss-39eff8d630fd------2</link>
            <guid isPermaLink="false">https://medium.com/p/7450d0e81e17</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm-evaluation]]></category>
            <dc:creator><![CDATA[Daniel Le]]></dc:creator>
            <pubDate>Wed, 17 Jul 2024 03:38:07 GMT</pubDate>
            <atom:updated>2024-10-08T11:59:51.624Z</atom:updated>
            <content:encoded><![CDATA[<h3>“Judge an LLM Judge”: A Dual-Layer Evaluation (QA) Framework for Continuous Improvement of LLM Application’s Evaluation</h3><h4>Can “the evaluation of an LLM app by an LLM judge” be audited by another LLM judge for the continuous improvement of the evaluation process?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M_arucf6tJY40kQNaVAdMw.png" /><figcaption>Continuous Improvement Framework for LLM Application’s Evaluation with Reference-free Approach — Image by Author</figcaption></figure><h3>TLDR</h3><blockquote>This article explains the concept and the low-abstraction implementation of employing an LLM judge to evaluate another LLM judge. The purpose is to improve the evaluation process of LLM applications, reducing cases where LLM judges fail to make fair assessments.</blockquote><h3>Table of Contents</h3><ul><li><a href="#f147">Introduction</a></li><li><a href="#422d">Research Question</a></li><li><a href="#1e42">Experiment Design</a></li><li><a href="#2805">Implementation</a></li><li><a href="#1fe0">Experiment Results</a></li><li><a href="#41bc">Conclusions</a></li></ul><h3>👉 Introduction</h3><p>❇️ In the field of building LLM applications, how to ensure consistent and reliable performance is one of the most frequently asked questions regarding QA (Quality Assurance). Due to their indeterministic nature, LLM models can produce great variability in their outputs. Hence, rigorous evaluation of LLM applications is strictly required. <strong>Without good evaluation methods, we must accept a certain level of risk (e.g. customer complaints, etc.) due to the inability to promptly identify unexpected behaviors in LLM applications. </strong>Common LLM evaluation methodologies include heuristic evaluations, LLM-as-judge, and human review.</p><ul><li>📍 <strong>Heuristic evaluators: </strong>e.g. a function to check whether output = “yes” or whether the output &gt; 10.</li><li>📍 <strong>LLM-as-judge: </strong>using an LLM to judge the output of another LLM.</li><li>📍<strong>Human judge: </strong>employ a human to evaluate the LLM’s output.</li></ul><p>❇️ Employing an LLM judge is a top choice as it can be automated and is much cheaper (and more feasible) than human judges. Besides, LLM judges can deal with the free-text format, unlike heuristic evaluators. However, the non-deterministic nature of LLMs implies that even with controlled parameters, outputs may vary, raising concerns about the reliability of these judgments.</p><p>💥 <strong>The concern we will address today:</strong></p><blockquote>When opting for an LLM judge to evaluate our LLM application, we should also question the integrity of the LLM judge itself.</blockquote><p>✅ So, the experiment described below aims to determine whether we can use an LLM judge (let’s call it “Supreme LLM Judge”) to evaluate the judgments of another LLM judge without any ground truth reference (<strong>reference-free evaluation</strong>). The ultimate goal is to find ways to improve the first LLM judge.</p><p>The graph below explains such a framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_1WUNR67wovJfpPtJd2u2g.png" /><figcaption>High-level architecture of using an LLM judge to judge another LLM judge (reference-free) — Image by Author</figcaption></figure><h3>👉 Research Question</h3><blockquote>Can “the evaluation of an LLM application by an LLM judge” be audited by another LLM judge for the continuous improvement of the evaluation process?</blockquote><h3>👉 Experiment Design</h3><p>🔹 One important constraint set out in this experiment that I must mention is that <strong>both LLM judges will evaluate without a ground-truth reference</strong>. Evaluation with ground-truth reference would provide the judges with the correct answers and ask them to compare. However, for most scenarios where we do not have datasets curated by humans, reference-free evaluation is the preferred approach.</p><p>🔹 The proposed framework improves the conventional single-layer evaluation of LLM applications by adding a Supreme LLM Judge. We can have two approaches for this framework.</p><ul><li><strong>Approach 1</strong>: An LLM Application is evaluated by an LLM Judge, whose judgment is afterward reviewed by a Supreme LLM Judge (reference-free). Disagreements or anomalies are subsequently reviewed by a human.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_rr0SXBGr2DLibYYMOk9mA.png" /><figcaption>Approach 1 — Image by Author</figcaption></figure><ul><li><strong>Approach 2</strong>: Both the LLM Judge and the Supreme LLM Judge independently evaluate the LLM Application (reference-free). The judgments are then compared, and any discrepancies are flagged for human review.</li></ul><p><strong>Approach</strong> <strong>1 will be discussed further in this article.</strong></p><h3>👉 Implementation</h3><p>🔹 <strong>The implementation of the aforementioned framework I opted for focuses on the high-level concept without delving too deeply into the fine-tuning for perfect performance.</strong></p><p>No LLM evaluation libraries or platforms (e.g., LangChain, LangSmith, LangFuse, etc.) were used. The code implementation has low abstraction, allowing readers to easily follow without getting lost in the intricate details of the code.</p><p>Since referencing the <em>LLM judge</em> and the <em>Supreme LLM Judge</em> can be hard to follow, let’s assign nominal roles for the components in the evaluation setup:</p><ul><li>LLM Application ➡️The Student</li><li>LLM Judge ➡️ The Teacher</li><li>Supreme LLM Judge ➡️ The Reviewer</li></ul><p><strong>💥 The complete code can be found in </strong><a href="https://github.com/khoadaniel/judge-an-llm-judge"><strong>this repository</strong></a><strong>.</strong></p><pre># LLM Application<br>def trigger_llm_app(context: str, question: str):<br>    fmt_context_and_question = f&quot;&quot;&quot;Context: {context}\nQuestion: {question}&quot;&quot;&quot;<br>    messages = [<br>        llm_app_prompt,<br>        {&quot;role&quot;: &quot;user&quot;,<br>         &quot;content&quot;: fmt_context_and_question}<br>    ]<br><br>    response = openai_client.chat.completions.create(messages=messages,<br>                                                     model=&quot;gpt-3.5-turbo&quot;)<br>    return response.choices[0].message.content<br><br><br># LLM Judge<br>def eval_llm_app(context: str, question: str, predicted_answer: str):<br>    fmt_input = f&quot;&quot;&quot;Context: {context}\nQuestion: {<br>        question}\nStudent&#39;s Answer: {predicted_answer}&quot;&quot;&quot;<br>    messages = [<br>        llm_judge_prompt,<br>        {&quot;role&quot;: &quot;user&quot;,<br>         &quot;content&quot;: fmt_input}<br>    ]<br><br>    response = openai_client.chat.completions.create(messages=messages,<br>                                                     model=&quot;gpt-3.5-turbo&quot;)<br>    return response.choices[0].message.content<br><br><br># Superior LLM Judge<br>def eval_llm_judge(context: str, question: str, student_answer: str, teacher_grading: str):<br>    fmt_input = f&quot;&quot;&quot;Context: {context}\nQuestion: {question}\nStudent&#39;s Answer: {<br>        student_answer}\nTeacher&#39;s Grading: {teacher_grading}&quot;&quot;&quot;<br>    messages = [<br>        supreme_llm_judge_prompt,<br>        {&quot;role&quot;: &quot;user&quot;,<br>         &quot;content&quot;: fmt_input}<br>    ]<br><br>    response = openai_client.chat.completions.create(messages=messages,<br>                                                     model=&quot;gpt-4&quot;)<br>    return response.choices[0].message.content</pre><blockquote>A subtle but important decision in this experiment design is to use GPT-4 as the Supreme LLM Judge, while the LLM Application and LLM Judge use GPT-3.5-turbo. This ensures that the Supreme LLM Judge’s evaluations are more robust and reliable (read more about the comparison <a href="https://techcommunity.microsoft.com/t5/ai-azure-ai-services-blog/comparing-gpt-3-5-amp-gpt-4-a-thought-framework-on-when-to-use/ba-p/4088645#:~:text=GPT%2D3.5%20was%20trained%20on,to%20their%20GPT%2D3.5%20counterparts.">here</a>).</blockquote><p>The prompts for each of the components in this experiment are as follows. You can see that I used few-shot prompting technique to improve the consistency of the evaluation outputs.</p><pre><br>llm_app_prompt = {&quot;role&quot;: &quot;system&quot;,<br>                  &quot;content&quot;: &quot;&quot;&quot;You are a helpful assistant. Please use step-by-step reasoning to address questions based on the specific context provided.&quot;&quot;&quot;}<br><br>llm_judge_prompt = {<br>    &quot;role&quot;: &quot;system&quot;,<br>    &quot;content&quot;: &quot;&quot;&quot;You are a math teacher tasked with grading a student&#39;s answer.<br>        Evaluate the student&#39;s response considering the context of the question, the correctness of the answer, and the reasoning provided.<br>        Conclude with a grade: assign &#39;0&#39; if the answer and the reasoning is incorrect and &#39;1&#39; if it is correct.<br>        Your grading output should be strictly in this format (no other words allowed): &#39;Grade: 0&#39; or &#39;Grade: 1&#39;.<br><br>        Below are examples for your reference:<br>            - Example:<br>            Question: How long does it take to drive 100 kilometers at 50 kilometers per hour?<br>            Student&#39;s Answer: To find the time, divide the distance by the speed: 100 km / 50 km/h = 2 hours.<br>            Grade: 1<br><br>            - Example:<br>            Question: Calculate the area of a square with a side length of 5 meters.<br>            Student&#39;s Answer: Given that the side length of the square is 5 meters, the answer is: 5*4=20 square meters.<br>            Grade: 0<br><br>            - Example:<br>            Question: How many seconds are in an hour?<br>            Student&#39;s Answer: 3600 seconds<br>            Grade: 1<br><br>            - Example:<br>            Question: Given two sets, Set A containing the elements 1, 2, and 3, and Set B containing the elements 3, 4, and 5, what is the intersection of Set A and Set B?<br>            Student&#39;s Answer: The element that is common to both sets is 1.<br>            Grade: 0<br>        &quot;&quot;&quot;<br>}<br><br>supreme_llm_judge_prompt = {<br>    &quot;role&quot;: &quot;system&quot;,<br>    &quot;content&quot;: &quot;&quot;&quot;You are an exam reviewer tasked with evaluating teachers&#39; grading. Your job is to review the grade given by the teacher to a student&#39;s answer and assess its correctness.<br>                Important: Your review is of the teacher&#39;s grading, not the student&#39;s answer.<br>                Output Format: Your review output should be strictly in this format (no other words allowed): &#39;Correctness: 0&#39; or &#39;Correctness: 1&#39;.<br><br>                Below are examples for your reference:<br>                    - Example:<br>                    Question: How long does it take to drive 100 kilometers at 50 kilometers per hour?<br>                    Student&#39;s Answer: To find the time, divide the distance by the speed: 100 km / 50 km/h = 2 hours.<br>                    Grade: 1<br>                    Correctness: 1<br><br>                    - Example:<br>                    Question: Calculate the area of a square with a side length of 5 meters.<br>                    Student&#39;s Answer: Given that the side length of the square is 5 meters, the answer is: 5*4=20 square meters.<br>                    Grade: 0<br>                    Correctness: 1<br><br>                    - Example:<br>                    Question: How many seconds are in an hour?<br>                    Student&#39;s Answer: 3600 seconds<br>                    Grade: 0<br>                    Correctness: 0<br><br>                    - Example:<br>                    Question: Given two sets, Set A containing the elements 1, 2, and 3, and Set B containing the elements 3, 4, and 5, what is the intersection of Set A and Set B?<br>                    Student&#39;s Answer: The element that is common to both sets is 1.<br>                    Grade: 1<br>                    Correctness: 0<br>         &quot;&quot;&quot;<br>}</pre><p>🔹 <strong>The question we asked the LLM application:</strong></p><blockquote>In a group of 30 people who can speak either English or German, 10 can speak both, and 25 can speak German.<br>How many speak only English?</blockquote><p>The LLM Application must not only provide the correct answer but also explain its reasoning. The LLM Judge then evaluates this output — both the final answer and the reasoning. Finally, the Supreme LLM Judge will evaluate the evaluation given by the LLM Judge.</p><p>You can notice that I left redundant information in the context of this question to challenge the LLM Application.</p><p>🔹 <strong>I ran this evaluation cycle 100 times with the default temperature set by OpenAI API using the same question to examine the performance of the judges.</strong></p><pre>if __name__ == &quot;__main__&quot;:<br>    context = &quot;In a group of 30 people who can speak either English or German, 10 can speak both, and 25 can speak German.&quot;<br>    user_question = &quot;How many speak only English?&quot;<br><br>    list_results = []<br>    for i in range(100):<br>        print(f&quot;===&gt; Iteration {i+1}&quot;)<br>        list_results.append(evaluate(context, user_question))</pre><h3>👉 Experiment Results</h3><p>💥 Once again, before reading our results, just a reminder of our definitions:</p><ul><li>LLM Application ➡️The Student</li><li>LLM Judge ➡️ The Teacher</li><li>Supreme LLM Judge ➡️ The Reviewer</li></ul><p>💥 <strong>IMPORTANT:</strong> We define a “positive case” as when the evaluation of the Teacher is wrong.</p><p>We will measure the performance of the Reviewer (Supreme LLM Judge) by the following metrics.</p><ul><li><strong>recall_of_reviewer: </strong>measures the ability of the Reviewer to identify all the positive cases. It indicates how effectively the Reviewer can capture mistakes from the Teacher.</li><li><strong>precision_of_reviewer: </strong>is defined as the proportion of the Reviewer’s identified positive cases that are actually positive.</li></ul><p>There is always a tradeoff between precision and recall. The more true positive cases you want to capture in your predictions (and you do not care much about false positive cases), the less precise your model becomes.</p><pre>reviewer_precision: 0.43<br>reviewer_recall: 0.70</pre><p>Let’s revisit our Research Question to see how the Supreme LLM Judge (the Reviewer) can help to audit the work of the LLM Judge (the Teacher).</p><blockquote>The Supreme LLM Judge can identify 70% of the instances where the LLM Judge made incorrect evaluations. By analyzing these identified cases, we can understand why the LLM Judge was confused and improve our LLM Application’s evaluation process.</blockquote><p><strong>😮 You might be curious about the wrong judgments from the LLM Judge that the Supreme LLM Judge has captured.</strong></p><p>Below are examples where the Reviewer successfully identified the Teacher’s grading errors. By looking into these examples, we can study why the LLM Judge did not perform well.</p><p>👋 <strong>Before reading the examples below, about the “human evaluator”:</strong></p><ul><li>Yes, I (the Author) am the human evaluator!</li><li>In the context of this experiment, the human will grade the student’s answers as correct if the reasoning is sound, even if it is lengthy and contains redundant calculations and reasonings.</li><li>Please note that this human_gradingis against the Student’s answers.</li></ul><pre>    {<br>        &quot;student_answer&quot;: &quot;1. We know that there are 10 people who can speak both English and German.\n2. There are 25 people who can speak German.\n3. To find out how many speak only English, we need to subtract the number of people who can speak both English and German from the total number of people who can speak German.\n4. So, the number of people who speak only English is 25 (people who speak German) - 10 (people who speak both) = 15 people.\n5. Therefore, there are 15 people who speak only English in the group of 30 people.&quot;,<br>        &quot;teacher_grading&quot;: &quot;1&quot;,<br>        &quot;reviewer_feedback&quot;: &quot;0&quot;,<br>        &quot;human_grading&quot;: &quot;0&quot;<br>    },<br>    {<br>        &quot;student_answer&quot;: &quot;To find out how many people speak only English, we first calculate the total number of people who can speak English by subtracting the number of people who can speak both English and German (10) from the total number of people who can speak German (25). This is because those 10 people are counted twice - once in the English-speaking group and once in the German-speaking group.\n\nTotal number of people who can speak English = Total number of people who can speak German - Number of people who can speak both English and German\nTotal number of people who can speak English = 25 - 10\nTotal number of people who can speak English = 15\n\nTherefore, there are 15 people who speak only English.&quot;,<br>        &quot;teacher_grading&quot;: &quot;1&quot;,<br>        &quot;reviewer_feedback&quot;: &quot;0&quot;,<br>        &quot;human_grading&quot;: &quot;0&quot;<br>    },<br>    {<br>        &quot;student_answer&quot;: &quot;Given that 10 people can speak both English and German, and 25 people can speak German, it means that 25 - 10 = 15 people speak only German.\nSince there are 30 people in total and we have now found the number of people who speak only German, the number of people who speak only English is 30 - 15 - 10 = 5.\nTherefore, 5 people speak only English.&quot;,<br>        &quot;teacher_grading&quot;: &quot;0&quot;,<br>        &quot;reviewer_feedback&quot;: &quot;0&quot;,<br>        &quot;human_grading&quot;: &quot;1&quot;<br>    },<br>    {<br>        &quot;student_answer&quot;: &quot;To find out how many people speak only English, we can start by calculating the total number of people who can speak English. \n\nFrom the information provided, we know that there are 10 people who can speak both English and German. Since there are a total of 30 people in the group, and 25 of them can speak German, the remaining 5 people must be the ones who speak only English.\n\nTherefore, the number of people who speak only English is 5.&quot;,<br>        &quot;teacher_grading&quot;: &quot;0&quot;,<br>        &quot;reviewer_feedback&quot;: &quot;0&quot;,<br>        &quot;human_grading&quot;: &quot;1&quot;<br>    },<br>    {<br>        &quot;student_answer&quot;: &quot;To find out how many people speak only English, we will first subtract the total number of German speakers from the total number of people in the group:\n\nTotal number of people = 30\nNumber of German speakers = 25\n\nTherefore, the number of people who speak only English is:\n30 - 25 = 5\n\nSo, there are 5 people in the group who speak only English.&quot;,<br>        &quot;teacher_grading&quot;: &quot;0&quot;,<br>        &quot;reviewer_feedback&quot;: &quot;0&quot;,<br>        &quot;human_grading&quot;: &quot;1&quot;<br>    },</pre><h3>👉 Conclusions</h3><p>✅ The evaluation of the LLM Judge by the Supreme LLM Judge gave us insights into the effectiveness of a multi-layered evaluation system for LLM applications. The Supreme LLM Judge achieved a <strong>recall rate of 70%,</strong> successfully identifying 70% of the incorrect evaluations made by the LLM Judge. <strong>This is not bad for the case of reference-free evaluation</strong> and for the proof-of-concept implementation.<strong> These captured incorrect evaluations will potentially help us derive solutions to continuously improve our LLM Judge.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6dSmEgPDB12B0pzIU1EtYA.png" /><figcaption>Continuous Improvement of the LLM Judge — Image by Author</figcaption></figure><p>✅ <strong>The difficulties we encounter when using an LLM judge to evaluate an LLM application also apply to using a Supreme LLM Judge to judge an LLM Judge (tongue twister!). </strong>Besides the quest to aim for high accuracy of the evaluations, ensuring consistent evaluation outputs is also a big challenge.</p><p>✅ Given that the second layer of evaluation requires human assessment with considerable effort, <strong>this approach is more suitable for audits or periodic offline evaluations </strong>rather than ongoing evaluations.</p><p>✅ <strong>It is also worth noting that using a random sampling method for evaluation might be a good approach to save resources. </strong>By strategically deploying a second layer of LLM evaluation with human reviewers, we can enhance the overall reliability and accuracy of the evaluation system, contributing to a high-performing LLM Application.</p><h3>About me</h3><p>I am Daniel Le, based in Berlin. I currently work in the fields of Machine Learning and Data Engineering.</p><p>I am interested in new technologies and how they can be implemented to solve real-world problems.</p><p>Should you have any inquiries or wish to discuss these interests further, please do not hesitate to connect with me on <a href="https://www.linkedin.com/in/khoadaniel/">LinkedIn</a>.</p><h3>Reference</h3><ul><li><a href="https://docs.smith.langchain.com/old/evaluation">https://docs.smith.langchain.com/old/evaluation</a></li><li><a href="https://huyenchip.com/2023/04/11/llm-engineering.html">https://huyenchip.com/2023/04/11/llm-engineering.html</a></li><li><a href="https://github.com/khoadaniel/judge-an-llm-judge/tree/main">https://github.com/khoadaniel/judge-an-llm-judge/tree/main</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7450d0e81e17" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/judge-an-llm-judge-a-dual-layer-evaluation-framework-for-continous-improvement-of-llm-apps-7450d0e81e17">Judge an LLM Judge: A Dual-Layer Evaluation Framework for Continuous Improvement of LLM Evaluation</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 Essential Questions to Address When Building an API-Involved Incremental Data Loading Script]]></title>
            <link>https://medium.com/data-science/3-essential-questions-to-address-when-building-an-api-involved-incremental-data-loading-script-03723cad3411?source=rss-39eff8d630fd------2</link>
            <guid isPermaLink="false">https://medium.com/p/03723cad3411</guid>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[business-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Daniel Le]]></dc:creator>
            <pubDate>Sun, 30 Jun 2024 15:27:35 GMT</pubDate>
            <atom:updated>2024-07-13T21:30:21.182Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>TLDR</strong></h3><blockquote>This article explains both the conceptual framework and practical code implementation for syncing data from API endpoints to your database using dlt (a Python library).</blockquote><blockquote>At the end of this tutorial, you will understand (and know how to implement) the sync behavior in the following illustration where we extract data <strong>incrementally</strong> and write to the destination table with the merge (dedup) strategy.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4rsdx0SxBPW2UX4Znebs-Q.gif" /><figcaption>Image by Author</figcaption></figure><h3>The context</h3><ol><li>You want to sync data from an application (e.g., ads performance, sales figures, etc.) to your database.</li><li>Your application provides API endpoints to retrieve its data.</li><li>The data needs to be synced daily to your database.</li><li>You want to load only the ❗<strong><em>“new” data (or the changes)</em></strong>❗ into your database. You do not want to load the entire set of data all over again every time you sync.</li></ol><p>How would you do it in Python?</p><blockquote>I will walk you through the solution by addressing the following 3 questions.</blockquote><h3>💥 Question 1: What do I need from an API to sync data incrementally?</h3><p>Before developing an incremental loading script, we need to understand the behavior of the API endpoints we are working with.</p><p>❗Not all APIs can facilitate incremental loading.</p><h4>👉 Answer: Query params that support incremental loading</h4><p>Let’s look at an example of an application (or “source” application) that tracks your sales performance. In this application, each record represents a product along with its sales volume. The fields created_at and updated_at indicate when the record was created and updated.</p><p>Changes in the sales data typically occur in two main ways:</p><ol><li>New products are added to the list.</li><li>Updates are made to the sales figures of existing records, <strong>which results in a new value for </strong><strong>updated_at </strong>. This helps us to track the new changes; without it, we cannot know which records have been modified.</li></ol><p>👁️👁️ Below is the example sales table in the source application’s database.</p><p>↪️ <strong>Yesterday&#39;s data: 2 records</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*0N3uob6HRTDGcUl57cAqMg.png" /><figcaption>Image by Author</figcaption></figure><p>↪️ <strong>Today&#39;s data: a new record added and a change made to an existing record</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*xh2_yClGAJnvhCCRWutv1A.png" /><figcaption>Image by Author</figcaption></figure><p>🟢 <strong>Takeaways: </strong>If the API endpoint allows queries based on theupdated_at parameter, you can implement incremental loading by making requests to retrieve only records that have an updated_at value later than the most recent updated_at value saved from the previous sync. In this context, updated_at is referred to as the incremental cursor, and its value, which persists through to the next sync, is known as the state.</p><p>The updated_at field is a common choice for an incremental cursor. Other query params, such as <strong>id</strong> or <strong>sales,</strong> cannot help us to request data incrementally as they cannot tell us which records have been added or updated since the last sync.</p><p><strong>Which query param do you need to load data incrementally?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*kA1Q_DRbViBi7n6ot5-1_w.png" /><figcaption>Image by Author</figcaption></figure><blockquote>Since we’re developing a data loading script that works with API, I’ll introduce two other important aspects of APIs for the code implementation: <strong>pagination and path parameters</strong>. They have nothing to do with incremental loading though.</blockquote><h4>🤷 Pagination mechanism</h4><p>APIs often return results in small chunks to enhance performance. For instance, instead of returning 10,000 records at once, an API might limit the response to a maximum of 100 records per request, requiring you to iterate through subsequent batches.</p><p>To manage this, you typically (not always) need to use two query parameters: limit and skip (or offset).</p><p>Here’s a simple example to illustrate:</p><p>For the first request:</p><ul><li>limit=100</li><li>skip=0</li></ul><p>For the second request, to skip the first 100 records we’ve already synced:</p><ul><li>limit=100</li><li>skip=100</li></ul><p>This pattern continues, incrementing the skip value by the limit after each batch until all records are retrieved.</p><p>🟢 <strong>Takeaways: </strong>You need to understand how APIs return responses so that you won’t miss any records while extracting. There are many approaches an API can use to manage pagination, beyond the commonly used methods of skip and offset. But that’s a story for another day.</p><h4>🤷 Path param</h4><p>Path parameters are included directly in the URL of an API and are typically used to distinguish between different segments (partitions) of data. For example, they might specify different campaigns within your marketing account or different sub-accounts managed in the source application.</p><p>In the example below: the path params are applicationId and campaignId.</p><p><a href="https://yourbaseurl.talon.one/v1/applications/%7BapplicationId%7D/campaigns/%7BcampaignId%7D/coupons/no_total">https://yourbaseurl.myapp/v1/applications/{applicationId}/campaigns/{campaignId}/</a>sales</p><p>🟢 <strong>Takeaways: </strong>You need to decide whether you will sync data from the same API but with different path params to a single table or different tables (sales_campaign_1, sales_campaign_2, etc.).</p><h3>💥 Question 2: How do I want to write the extracted records to the destination table?</h3><p>Now let’s say you already extracted a bunch of records by making API requests with the above-mentioned params, it’s time for you to decide how you want to write them to the destination table.</p><h4>👉 Answer: Merge/Dedup mode (recommended)</h4><p>This question concerns the choice of <strong>Write disposition</strong> or <strong>Sync mode</strong>. The immediate answer is that, given you are looking to load your data incrementally, you will likely opt to write your extracted data in either append mode or merge mode (also known as deduplication mode).</p><p>However, let’s step back to examine our options more closely and determine which method is best suited for incremental loading.</p><p>Here are the popular write dispositions.</p><ul><li>🟪 <strong>overwrite/replace:</strong> drop all existing records in the destination tables and then insert the extracted records.</li><li>🟪 <strong>append: </strong>simply append extracted records to the destination tables.</li><li>🟪 <strong>merge / dedup: </strong>insert new(*) records and update(**) existing records.</li></ul><p>(*) How do we know which records are new?: Usually, we will use a primary key to determine that. If you use dlt, their merging strategy can be more sophisticated than that, including the distinction between merge_key and primary_key <em>(one is used for merging and one is used for dedupication before merging)</em> or dedup_sort <em>(which records are to be deleted with the same key in the dedup process)</em>. I will leave that part for another tutorial.</p><p>(**) This is a simple explanation, if you want to find out more about how dlt handles this merging strategy, read more <a href="https://dlthub.com/docs/general-usage/incremental-loading#merge-incremental-loading">here</a>.</p><p>👁️👁️ Here is an example to help us understand the results of different write dispositions.</p><p>↪️ <strong>On 2024.06.19: We make the first sync.</strong></p><p>🅰️ <strong>Data in </strong><strong>source application</strong>️️</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*C4qVYzYM4d7wnA7TnmegCA.png" /><figcaption>Image by Author</figcaption></figure><p>🅱️ ️<strong>Data loaded to our </strong><strong>destination database</strong></p><p>No matter what sync strategy you choose, the table at the destination is <strong>literally a copy</strong> of the source table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*C4qVYzYM4d7wnA7TnmegCA.png" /><figcaption>Image by Author</figcaption></figure><p>Saved state of updated_at= 2024–06–03, which is the latest updated_at mong the 2 records we synced.</p><p>↪️ <strong>On 2024.06.2: We make the second sync.</strong></p><p><strong>🅰️ ️️️️️️️Data in </strong><strong>source application</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*zx_CZq_rPpk-EBftj_rDog.png" /><figcaption>Image by Author</figcaption></figure><p>✍️ Changes in the source table:</p><ul><li>Record id=1 was updated (sales figure).</li><li>Record id=2 was dropped.</li><li>Record id=3 was inserted.</li></ul><p>At this sync, we ONLY extract records with the updated_at&gt; 2024–06–03 (state saved from last sync). Therefore, we will extracted only record id=1 and id=3. Since record id=2 was removed from the source data, there is no way for us to recognize this change.</p><p>With the second sync, you now will see the difference among the write strategies.</p><p>🅱️ <strong>Data loaded to our </strong><strong>destination database</strong></p><p>❗ <strong>Scenario 1: Overwrite</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*b8dhvAJKm1f5BhWa8P5ilQ.png" /><figcaption>Image by Author</figcaption></figure><p>The destination table will be overwritten by the 2 records extracted this time.</p><p>❗ <strong>Scenario 2: Append</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*TZnoowZmM8q868it7okgwA.png" /><figcaption>Image by Author</figcaption></figure><p>The 2 extracted records will be appended to the destination table, the existing records are not affected.</p><p>❗ <strong>Scenario 3: Merge or dedup</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*eGgD7e3yAcZWU9c1-p2Ybg.png" /><figcaption>Image by Author</figcaption></figure><p>The 2 extracted records with id=1 and 3 will replace the existing records at destination. This processing is so called merging or deduplicating. Record id=2 in the destination table remains intact.</p><p>🟢 <strong>Takeaways: </strong>The merge (dedup) strategy can be effective in the incremental data loading pipeline, but if your table is very large, this dedup process might take a considerable amount of time.</p><h3>💥 Question 3: How do I implement it in code?</h3><h4>👉 Answer: dlt — as it is lightweight, well-documented, and has an active community for support.</h4><blockquote><a href="https://dlthub.com/">dlt</a> is an excellent choice because it provides you with the right level of abstraction. In fact, you can choose how much abstraction you want. As you can see in my example code below, I have taken the liberty of writing my own request loop, but dlt offers helper functions that can do this for you with much fewer lines of code. This flexibility makes dlt stand out compared to other solutions.</blockquote><p>You can refer to the diagram for a high-level view and then drill down to the code with detailed remarks below.</p><p>Quick note: dlt uses the terms <strong>source</strong> and <strong>resources </strong>in its structuring. A resource typically corresponds to an API endpoint and writes data to a table in the destination database. A source is a collection of resources.</p><p>In the illustration below, you can see the answers to the two questions we discussed:</p><ul><li>Answer to Question 1: Make requests to an API endpoint using a date cursor to get data incrementally (and persist the cursor value, also known as state, for subsequent runs).</li><li>Answer to Question 2: Write data to the destination table using the merge strategy.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qMfE09esdjRFwK99DZ1KMQ.gif" /></figure><blockquote>Now, you might wonder how to run this Python script? I suggest you to go to <a href="https://github.com/khoadaniel/incremental-data-loading-guide">this repository</a> and try out yourself. This repository also provides you with a mock API that you can deploy locally for testing purposes. Check out the README for the detailed execution guide.</blockquote><p>💥 Here is a snippet of the dlt implementation with my remarks 💥</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f3a9b007b6272f15218e9238e44d876/href">https://medium.com/media/4f3a9b007b6272f15218e9238e44d876/href</a></iframe><p>🟣️ <strong>Full code can be seen at the repository </strong><a href="https://github.com/khoadaniel/incremental-data-loading-guide"><strong>here</strong></a><strong> </strong>🟣</p><p>✅ This concludes the tutorial. I hope you have learned about the different components that make up an incremental loading script, as well as the code implementation.</p><p>If you’re interested in finding out more about how to build an incremental loading script with dlt, check out their documentation <a href="https://dlthub.com/docs/general-usage/incremental-loading">here</a>.</p><h3>About me</h3><p>I am Daniel Le, based in Berlin. I currently work in the fields of Data Engineering and Machine Learning.</p><p>I am interested in new technologies and how they can be implemented to solve real-world problems.</p><p>Should you have any inquiries or wish to discuss these interests further, please do not hesitate to connect with me on <a href="https://www.linkedin.com/in/khoadaniel/">LinkedIn</a>.</p><h3>Reference</h3><ul><li><a href="https://dlthub.com/docs/general-usage/incremental-loading">https://dlthub.com/docs/general-usage/incremental-loading</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03723cad3411" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/3-essential-questions-to-address-when-building-an-api-involved-incremental-data-loading-script-03723cad3411">3 Essential Questions to Address When Building an API-Involved Incremental Data Loading Script</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google Ads API Refresh Token: How to get it]]></title>
            <link>https://medium.com/@khoadaniel/google-ads-api-refresh-token-the-nightmare-of-data-engineers-df0ed04922e5?source=rss-39eff8d630fd------2</link>
            <guid isPermaLink="false">https://medium.com/p/df0ed04922e5</guid>
            <category><![CDATA[dlt]]></category>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[airbyte]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Daniel Le]]></dc:creator>
            <pubDate>Tue, 30 Apr 2024 11:11:56 GMT</pubDate>
            <atom:updated>2024-10-08T11:52:08.465Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to get Google Ads API Refresh Token</h3><h3>If you’re finding the process of obtaining API credentials from Google Ads / Google Adwords, particularly the Refresh Token, frustrating 🥵, this quick tutorial is for you.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*n9GtzAbMh3loY4-hlQ1Q6A.png" /><figcaption>Image by Google</figcaption></figure><p>This tutorial is intended for those who start from scratch to get a Refresh Token for syncing data from Google Ads.</p><p><strong>It assumes that:</strong></p><ul><li>You do not have an existing Google Cloud Platform (GCP) project (<a href="https://cloud.google.com/">https://cloud.google.com/</a>).</li><li>But you do have a Google Ads Account (<a href="https://ads.google.com/">https://ads.google.com/</a>) as you are planning to get data from your Google Ads performance. You already have the Developer Token (see Appendix) (<a href="https://ads.google.com/aw/accountaccess/">https://ads.google.com/aw/accountaccess/</a>).</li></ul><p><strong>Please disregard any steps that do not apply to you.</strong></p><h3>➡️ Step 1: GCP Project</h3><ul><li>Create a GCP project (<a href="https://cloud.google.com/">https://cloud.google.com/</a>) or use your existing one.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jl9wUQyhc4kXCpUJJzY2Yw.png" /><figcaption>Image by Author</figcaption></figure><h3>➡️ Step 2: Google Ads API</h3><p>Go to Google Ads API and ENABLE it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0zRhqgH7D4kH-GohPIMRhw.png" /><figcaption>Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r0xGWnXHPtjaFWRCoawakQ.png" /><figcaption>Image by Author</figcaption></figure><h3>➡️ Step 3: Consent Screen</h3><ul><li>Navigate to the Credentials page.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eq5N1G_Y1NiT-BLVhZ9_rA.png" /><figcaption>Image by Author</figcaption></figure><ul><li>Select the Credentials tab.</li><li>Click on CONFIGURE CONSENT SCREEN.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KYNd6ANec7sZ6lTtF1t88A.png" /><figcaption>Image by Author</figcaption></figure><ul><li>Opt for the EXTERNAL choice, unless you have a different preference.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eT5wUhmN8xTQgjEJILmqHw.png" /><figcaption>Image by Author</figcaption></figure><ul><li>Fill in only the required fields and go on, the rest can be left blank.</li></ul><h3>➡️ Step 3: Client ID &amp; Client Secrets</h3><ul><li>Navigate back to the Credentials tab. You&#39;ll see an option to + CREATE CREDENTIALS.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BGa9jl74fknTatjZ-lx48Q.png" /><figcaption>Image by Author</figcaption></figure><ul><li>Click on + CREATE CREDENTIALS and select OAuth client ID from the drop-down menu.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*QDVsmlyjbEHOKY7CwRwjwg.png" /><figcaption>Image by Author</figcaption></figure><ul><li>Choose theWeb application from the given list.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tvh1S8a4XAS7fzTVlN9jEg.png" /><figcaption>Image by Author</figcaption></figure><ul><li>Assign a Name to your client.</li><li>The URI at Authorised redirect URIs should be: [&lt;http://localhost&gt;](&lt;http://localhost/&gt;)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M3GQct2cnJSV0N-CAYptXg.png" /><figcaption>Image by Author</figcaption></figure><p>→ Now, you have the Client ID and Client secret.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cBXJTuOU4X4sTvDqt9exMA.png" /><figcaption>Image by Author</figcaption></figure><h3>➡️ Step 4: Authorization Code</h3><ul><li>Replace $CLIENT_ID below with your Client ID in the last step.</li><li>Enter this URL into your browser.</li></ul><pre>https://accounts.google.com/o/oauth2/auth?client_id=$CLIENT_ID&amp;redirect_uri=http://localhost&amp;response_type=code&amp;scope=https://www.googleapis.com/auth/adwords&amp;access_type=offline</pre><p>The email you use in this authorization process represents the Google account that holds permissions to access Google Ads. This email must be linked to a Google Ads account as a user with appropriate access levels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8lthlTAZ5btkLLvbeqB7nA.png" /><figcaption>Image by Author</figcaption></figure><p>The email is used to grant consent to the Application you just created in GCP to access Google Ads data. This is done through the OAuth 2.0 flow, where the user logs in with their Google account (email) and explicitly allows your application to access their Google Ads data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/0*0l5-JUy8xFGnJw5-.png" /><figcaption>Image by Google (<a href="https://developers.google.com/identity/protocols/oauth2">link</a>)</figcaption></figure><ul><li>At first glance, it may seem like it didn’t work. However, if you check your URL bar, you will find the Authorization Code (highlighted below).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ME5Vroa0tAu5RxVzocgU2A.png" /><figcaption>Image by Author</figcaption></figure><pre>http://localhost/?code=4/0Axy...ADI-ebQ&amp;scope=https://www.googleapis.com/auth/adwords</pre><p>→ Now you have the Authorization Code .</p><h3>➡️ Step 5: Refresh Token (finally!)</h3><p>You need to act quickly 🏃! The Authorization code expires very fast.</p><p>After replacing the required credentials in the shell command below, execute it in your shell.</p><pre>AUTHORIZATION_CODE=&lt;replace this&gt; &amp;&amp;<br>CLIENT_ID=&lt;replace this&gt; &amp;&amp;<br>CLIENT_SECRET=&lt;replace this&gt; &amp;&amp;<br>curl \\<br>--request POST \\<br>--data  &quot;code=${AUTHORIZATION_CODE}&amp;client_id=${CLIENT_ID}&amp;client_secret=${CLIENT_SECRET}&amp;redirect_uri=http://localhost&amp;grant_type=authorization_code&quot; &lt;https://oauth2.googleapis.com/token&gt;</pre><p>The command would look like this:</p><pre>AUTHORIZATION_CODE=4/0Be...BcpYX &amp;&amp;<br>CLIENT_ID=467...m134.apps.googleusercontent.com &amp;&amp;<br>CLIENT_SECRET=TXA...zgB &amp;&amp;<br>curl \<br>--request POST \<br>--data  &quot;code=${AUTHORIZATION_CODE}&amp;client_id=${CLIENT_ID}&amp;client_secret=${CLIENT_SECRET}&amp;redirect_uri=http://localhost&amp;grant_type=authorization_code&quot; https://oauth2.googleapis.com/token</pre><p>❌ For the first time you run the command, you may encounter an invalid_grant error. This is most likely because your Authorization code has expired. The error message isn&#39;t exactly clear, is it? 🙄</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*jh6zE-Rmms7Pvt2Llb-FJg.png" /><figcaption>Image by Author</figcaption></figure><p>→ Now you need to repeat Step 3 , and quickly jump to Step 4.</p><pre>{<br>  &quot;error&quot;: &quot;invalid_grant&quot;,<br>  &quot;error_description&quot;: &quot;Bad Request&quot;<br>}%</pre><p>✅ This is what you get if you do it right. Eccolo! The Refresh Token is here.</p><pre>{<br>  &quot;access_token&quot;: &quot;sa51.a0A...0111&quot;,<br>  &quot;expires_in&quot;: 3599,<br>  &quot;refresh_token&quot;: &quot;1//000_II...w88&quot;,<br>  &quot;scope&quot;: &quot;&lt;https://www.googleapis.com/auth/adwords&gt;&quot;,<br>  &quot;token_type&quot;: &quot;Bearer&quot;<br>}%</pre><h3>✴️ Appendix</h3><p>I did not mention that you may also need the Developer Token. For instance, Airbyte requires a Developer Token to sync data from Google Ads (<em>Airbyte has a verified Google Ads connector </em><a href="https://docs.airbyte.com/integrations/sources/google-ads"><em>here</em></a><em>).</em></p><p>➡️ You need to visit <a href="https://ads.google.com/aw/apicenter">https://ads.google.com/aw/apicenter</a> to create a Developer Token. This is quite straightforward.</p><p>I assume that you are using the same email for the Google Ads console and for the GCP (as mentioned above).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*r2gBlgOS_dGOWjwxX2CLlw.png" /><figcaption>Image by Author</figcaption></figure><h3>About me</h3><p>I am Daniel Le, based in Berlin. I currently work as a Machine Learning Engineer. I am interested in new technologies and how they can be implemented to solve real-world problems.</p><p>Should you have any inquiries or wish to discuss these interests further, please do not hesitate to contact me on <a href="https://www.linkedin.com/in/khoadaniel/">LinkedIn</a>.</p><h3>📚 Reference</h3><ul><li><a href="https://developers.google.com/google-ads/api/docs/start">https://developers.google.com/google-ads/api/docs/start</a></li><li><a href="https://www.youtube.com/watch?v=wli0liBhGRs">https://www.youtube.com/watch?v=wli0liBhGRs</a></li><li><a href="https://www.youtube.com/watch?v=_yvqUyZ72Kc&amp;t=175s">https://www.youtube.com/watch?v=_yvqUyZ72Kc&amp;t=175s</a></li><li><a href="https://www.youtube.com/watch?v=t0RKgHskYwI">https://www.youtube.com/watch?v=t0RKgHskYwI</a></li><li><a href="https://gist.github.com/eruffaldi/98cfb6cc5b11a3778ac9dcb507ac75f4">https://gist.github.com/eruffaldi/98cfb6cc5b11a3778ac9dcb507ac75f4</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df0ed04922e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Guide to Integrating LLM Agent into POS Systems]]></title>
            <link>https://pub.towardsai.net/a-guide-to-integrating-llm-agent-into-pos-systems-3511d67980a9?source=rss-39eff8d630fd------2</link>
            <guid isPermaLink="false">https://medium.com/p/3511d67980a9</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Daniel Le]]></dc:creator>
            <pubDate>Sat, 13 Apr 2024 12:14:42 GMT</pubDate>
            <atom:updated>2024-05-07T19:41:27.611Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Guide to Integrating LLM Agents into POS Systems</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ewJXTL--ticPGJEDOkWrPA.png" /><figcaption>Custom LLM agent interacting with external systems (Image by Author)</figcaption></figure><h3>Overview:</h3><ul><li><a href="#13c7"><strong>The Story</strong></a></li><li><a href="#c2cf"><strong>The Codes</strong></a></li><li><a href="#0431"><strong>Conclusion</strong></a></li></ul><h3>🫖 TLDR</h3><blockquote>This article presents an LLM-powered solution to improve the efficiency of ordering and payment processes in food establishments. It involves the integration of an LLM Agent (built with LangChain) which is capable of interacting with API endpoints (e.g. the POS System). This article walks through the codes to build such an agent with practical examples. The codes are published <a href="https://github.com/khoadaniel/custom-llm-agent-demo">here</a>. You can also interact with the agent <a href="http://18.199.129.28:8002/">here</a>.</blockquote><p><strong>Demo Video:</strong> Notice the signposting/cues agent … please <em>(read more below)</em> in this conversation and how the agent picked only the relevant information to make respective API requests.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F4dHBJDix9Is%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D4dHBJDix9Is&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F4dHBJDix9Is%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1959ddde1092005c8d3230d13eb7f454/href">https://medium.com/media/1959ddde1092005c8d3230d13eb7f454/href</a></iframe><h3>🥖 The Story</h3><h4>🧀 The Inspiration</h4><p>I am a fan of the tasty Käsedings at Zeit für Brot (Berlin, Germany) and I’ve spent quite a bit of time hanging out at their busy Eberswalder spot. It’s where my interest in the tasty breads collides with the reality of waiting in line.</p><blockquote>I noticed and hypothesized that, to maintain hygiene, cashiers don’t directly handle the food.</blockquote><p>There would be one cashier and one other staff working in a pair to deal with customers. The cashiers only manage orders and payments, leaving food handling to their peers.</p><p><strong>➡️ This observation sparked an idea:</strong> What if we could make the ordering and payment process more efficient, enhancing customer satisfaction, streamlining staff workflow, and ultimately boosting Zeit für Brot’s revenue (sorry for the buzzwords)?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dD_279vRfPRuXgFlWW7jsA.png" /><figcaption>Illustration generated by Author via ChatGPT</figcaption></figure><h4>💡 The Solution: The Integration of an LLM-agent</h4><p>This solution proposes integrating a custom LLM agent into the Point of Sale (POS) system. The agent will translate the staff’s orders into API requests, registering items in the POS system without manual entry.</p><h4>💡 Workflow Simplified:</h4><p>👩‍💼 Staff-Customer Interaction: A staff member receives an order from a customer. He communicates with the LLM agent through his headset. The staff member can engage in conversation with the customer without needing to deactivate the headset, allowing for a seamless interaction.</p><blockquote>The LLM agent listens to the entire conversation, filtering out irrelevant chatter and focusing on the important details.</blockquote><p>This is facilitated by the use of specific “agent” and “please” cues (signposting), which enables the LLM agent to distinguish between casual conversation and a direct request for assistance.</p><p><strong>Example:</strong></p><blockquote><em>- Customer A: Do you want to get an espresso and two cinnamon rolls?<br>- Customer B: I don’t know.<br>- Customer A: OK, I’ll decide then. I’ll get a baguette, a cappuccino, and two cheesecakes.<br>- Staff: Agent, add a baguette, a cappuccino, and two cheesecakes, please.<br>- Customer A: Sorry I changed my mind, I won’t get the baguette.<br>- Staff: Agent, remove the baguette, please.<br>- Staff: Agent, proceed to payment by card, please.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eiAxbWyBkBOxzsf1jhMKCg.png" /><figcaption>You can check out the demo <a href="http://18.199.129.28:8002/">here</a> (Image by Author)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CYjKu66fiEQbQym2arZEMw.png" /><figcaption>Request made to the mentioned API endpoints (Image by Author)</figcaption></figure><p><strong>Under the hood:</strong></p><ul><li>The agent processes this speech, generating API request(s) to register items to the order.</li><li>If there’s a change in the order, the staff can proceed with:<em> “Agent, remove one cinnamon roll.”</em> The agent will adjust the order accordingly.</li><li>Upon finalizing the order,<em> “Agent, proceed to payment with QR codes / cards please”</em> prompts the agent to initiate the payment process, creating a smooth end-to-end transaction.</li></ul><h3>🔌 The Codes</h3><p>In this session, I will focus on discussing how to build a custom LLM agent with LangChain. I assume you are familiar to a certain extent with LangChain’s terms and usage. If not, you can checkout their documentation <a href="https://python.langchain.com/docs/get_started">here</a>.</p><blockquote>I suggest you also refer to my <a href="https://github.com/khoadaniel/custom-llm-agent-demo">repository</a> when reading the following, as I will not display the entire scripts in this article. Instead, I will highlight the key takeaways for you.</blockquote><h4>What do you need to create a custom LLM agent that can interact with external systems?</h4><ol><li>The tools (that interact with external systems)</li><li>The prompt (that guides the agent)</li><li>The agent (and its executor)</li></ol><p>Now, let’s go through it one by one.</p><h4>🔧 The tools</h4><p>I created 3 simple tools to</p><ul><li>add item(s) to an order</li><li>remove item(s) from an order</li><li>proceed to payment with a preferred method</li></ul><p>These tools are simple functions created with the langchain @tool decorators.</p><p>You might wonder how the agent knows which tools to take. The answer is that it bases its decisions on the name and the description of the tools.</p><p>In the following codes:</p><ul><li>The function’s name add_orders will be considered as the <strong>tool’s name</strong>. The function’s docstring is treated as the <strong>tool’s descriptions</strong>. The description of the tool plays an important role because it helps the LLM to reason and decide which tools are relevant in a given context.</li><li>This add_orders function take an argument order_data in the format of a dictionary (see codes below). The LLM will make sure that the order_data is in the format that we want. You can see that I wrote the docstring as if I am giving instructions to the LLM.</li><li>The function makes a POST request to an API endpoint. This, ideally, is the system that we want the agent to control. In my case, it is the POS system that the staff uses at the store.</li></ul><pre>@tool<br>def add_orders(order_data):<br>    &quot;&quot;&quot;Add items to an order by making a POST request with the order_data argument strictly following this format:<br>    order_data = [<br>    {&#39;quantity&#39;: 2, &#39;item&#39;: &#39;apple&#39;},<br>    {&#39;quantity&#39;: 1, &#39;item&#39;: &#39;banana&#39;},<br>    {&#39;quantity&#39;: 3, &#39;item&#39;: &#39;cherry&#39;}<br>            ]<br>    &quot;&quot;&quot;<br>    # Make a POST request to the FastAPI endpoint<br>    url = &quot;http://localhost:8889/add&quot;<br>    # Adhere to the expected format of the FastAPI endpoint<br>    request_json = {&quot;list_items&quot;: order_data}<br>    response = requests.post(url,<br>                             headers={<br>                                 &quot;Content-Type&quot;: &quot;application/json&quot;},<br>                             json=request_json)</pre><p>As mentioned previously, besides this add_orders, I have remove_orders and pay_orders functions as well. They form a list of tools at the disposal of the agent. Here is how you do it:</p><pre># Create an LLM model<br>llm = ChatOpenAI(model=&quot;gpt-3.5-turbo&quot;, temperature=0)<br># Create a list of tools for the LLM to pick<br>tools = [add_orders, remove_orders, pay_orders]<br># Bind the tools to the LLM, the result is an LLM with tools<br>llm_with_tools = llm.bind_tools(tools)</pre><h4>💬 The prompt</h4><p>I created a simple prompt with ChatPromptTemplate .</p><ul><li>It starts with a system role, depicting the tasks that the agent needs to perform. This will govern the behavior of the agent. I think most of “the art” belongs to this part.</li><li>Then the user role comes in, with a place holder of {input} for us to pass the user’s “prompt” in. For example: <em>“Agent please add a baguette to my order please.”</em></li><li>Finally, the MessagesPlaceholder is required so that the agent can store intermediate information about how it reasons and what steps have been taken. You do not need to worry about this one.</li></ul><pre>prompt = ChatPromptTemplate.from_messages(<br>    [<br>        (&quot;system&quot;,<br>         &quot;You are a helpful assistant, you extract user&#39;s food orders from a conversation and add or remove them to POS system by making POST request with the extracted order data.\\<br>         User can also request to pay with a preferred payment method.\\<br>            The real order information starts from a signpost word &#39;agent&#39; and ends with a signpost word &#39;please&#39;.\\<br>                The rest of the conversation is not important, you must strictly ignore it. The extracted order should contain the items and their quantity,\\<br>                    and it is in the format of a python list of multiple dictionaries.&quot;),<br>        (&quot;user&quot;,<br>         &quot;{input}&quot;),<br>        MessagesPlaceholder(variable_name=&quot;agent_scratchpad&quot;),<br>    ]<br>)</pre><h4>🤖 The agent</h4><p>We form the agent by chaining all the langchain components together, including the before-mentioned prompt and the LLM model with its toolset.</p><p>You might wonder why we need to construct an input dictionary firsthand. It is because the agent will be called many times by its agent_executor after our invocation; and the agent_executor needs to pass on inputs that in the correct format to the agent. You see my point when you remove this step, langchain will tell you that it does not expect intermediate_steps in the input (see above where we constructed the prompt with agent_scratchpad not intermediate_steps ).</p><pre># Create the agent<br>agent = (<br>    {<br>        &quot;input&quot;: lambda x: x[&quot;input&quot;],<br>        &quot;agent_scratchpad&quot;: lambda x: format_to_openai_tool_messages(x[&quot;intermediate_steps&quot;]),<br>    }<br>    | prompt<br>    | llm_with_tools<br>    | OpenAIToolsAgentOutputParser()<br>)<br><br># And we need to create an agent executor, we cannot just call the agent directly<br>agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)<br>agent_output = agent_executor.invoke(<br>    {&quot;input&quot;: conversation}<br>)</pre><p>Let’s discuss a little bit about the flow of the AgentExecutor . The AgentExecutor will carry out the following steps in sequence:</p><ul><li><strong>Format</strong> the input</li><li><strong>Pass</strong> the output of the last step to the prompt</li><li><strong>Pass</strong> the output of the last step to the LLM agent with its tools (a tool might be called here)</li><li><strong>Parse</strong> the output of the last step and use it for further reasonings (e.g. maybe AgentExecutor will call another tool here)</li></ul><p>Let’s try to invoke the AgentExecutor we just built. You can see (in the LangSmith log below) that after calling add_orders, the AgentExecutor can then call pay_orders as well.</p><pre>agent_executor.invoke(<br>    {&quot;input&quot;: &quot;Agent please add a baguette please.\<br>     Agent please proceed to payment by card&quot;})</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BJ7N_1GXC9BOlgD107SC7Q.png" /><figcaption>Under the hood of the AgentExecutor via LangSmith (Image by Author)</figcaption></figure><h3>✍️ Conclusion</h3><p>Congratulations on reaching the conclusion of this tutorial!</p><p>Up to now, we have created a custom LLM agent with Langchain from the 3 components: <strong>the tools, the prompt, and the agent.</strong></p><blockquote>This LLM agent can reason and interact with external systems (APIs).</blockquote><p>Now, it’s up to your use cases that you can tailor these interactions by changing the tools and the prompt.</p><p>As I tried to keep the article succinct, I suggest you clone my repository and execute the complete script on your own.</p><p>➡️ You can find the repository <a href="https://github.com/khoadaniel/custom-llm-agent-demo">here</a>.</p><p>➡️ ️The live demo is available <a href="http://18.199.129.28:8002/">here</a>.</p><p>If you have any questions, feel free to reach out to me on <a href="https://www.linkedin.com/in/khoadaniel/">LinkedIn</a>.</p><h3>About me</h3><p>I am Daniel Le, based in Berlin. I currently work as a Data Engineer — with a great passion for Machine Learning.</p><p>I am based in Berlin, Germany and I am interested in new technologies and how they can be implemented to solve real-world problems.</p><p>Should you have any inquiries or wish to discuss these interests further, please do not hesitate to connect with me on <a href="https://www.linkedin.com/in/khoadaniel/">LinkedIn</a>.</p><h3>Reference</h3><ul><li><a href="https://python.langchain.com/docs/modules/agents/how_to/custom_agent">https://python.langchain.com/docs/modules/agents/how_to/custom_agent</a></li><li><a href="https://python.langchain.com/docs/modules/agents/tools/custom_tools">https://python.langchain.com/docs/modules/agents/tools/custom_tools</a></li><li><a href="https://python.langchain.com/docs/modules/agents/tools/tools_as_openai_functions">https://python.langchain.com/docs/modules/agents/tools/tools_as_openai_functions</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3511d67980a9" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/a-guide-to-integrating-llm-agent-into-pos-systems-3511d67980a9">A Guide to Integrating LLM Agent into POS Systems</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>