<?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 Aditya S on Medium]]></title>
        <description><![CDATA[Stories by Aditya S on Medium]]></description>
        <link>https://medium.com/@s.aditya1317?source=rss-2d1520186482------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*pxqxU59ffWadWpvq</url>
            <title>Stories by Aditya S on Medium</title>
            <link>https://medium.com/@s.aditya1317?source=rss-2d1520186482------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 03:05:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@s.aditya1317/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[Build a Multi-Source AI Research Assistant Using Web Search, Documents, and LLMs]]></title>
            <link>https://medium.com/@s.aditya1317/build-a-multi-source-ai-research-assistant-using-web-search-documents-and-llms-90678e38db77?source=rss-2d1520186482------2</link>
            <guid isPermaLink="false">https://medium.com/p/90678e38db77</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Aditya S]]></dc:creator>
            <pubDate>Fri, 20 Nov 2026 15:14:15 GMT</pubDate>
            <atom:updated>2026-11-20T15:14:15.564Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Introduction: Research Is More Than Finding Information</h3><p>Imagine researching a technical topic such as Retrieval-Augmented Generation (RAG).</p><p>You might search Google for recent developments, read research papers, review technical documentation, and compare information across multiple sources.</p><p>The challenge is not finding information. It is collecting information from different places, understanding it, identifying relevant facts, and combining everything into one reliable answer.</p><p>Now imagine having an AI assistant that can perform these tasks for you.</p><p>It can search the web for recent information, read your uploaded documents, retrieve relevant content, and use an LLM to generate a structured research summary.</p><p>This is the idea behind a <strong>Multi-Source AI Research Assistant</strong>.</p><p>Instead of depending on a single information source, the system combines web search, document retrieval, and LLM reasoning into one workflow.</p><p>In this project, we will build a simplified research assistant that accepts a question, gathers information from multiple sources, and generates an answer based on the collected context.</p><h3>2. What You Will Learn</h3><p>By the end of this project, you will understand:</p><ul><li>How multi-source AI research systems work.</li><li>How to integrate web search into an AI application.</li><li>How to process and retrieve information from documents.</li><li>How to use vector embeddings and vector databases.</li><li>How to combine retrieved information using an LLM.</li><li>How to generate answers with source references.</li><li>How to structure the application for future improvements.</li></ul><h3>3. Prerequisites</h3><p>Before starting, you should have:</p><ul><li>Basic Python knowledge.</li><li>Understanding of APIs and JSON responses.</li><li>Basic understanding of LLMs.</li><li>Familiarity with prompt engineering.</li><li>Basic knowledge of embeddings and vector databases (helpful but optional).</li></ul><p><strong>Technology stack:</strong></p><ul><li>Python — Application development.</li><li>LangChain — Document processing and retrieval.</li><li>OpenAI API — Embeddings and answer generation.</li><li>Tavily Search API — Web search.</li><li>ChromaDB — Vector storage.</li><li>Streamlit — User interface.</li></ul><h3>4. Understanding the Problem</h3><p>Traditional research involves collecting information manually.</p><p>Suppose you ask:</p><p>“How are AI agents using RAG to improve enterprise knowledge management?”</p><p>To answer this properly, you may need:</p><ol><li>Recent articles about AI agents.</li><li>Technical documentation about RAG.</li><li>Research papers discussing enterprise applications.</li><li>Your own project documents or notes.</li></ol><p>A conventional chatbot may answer using its existing model knowledge, but it might not have access to your private documents or the latest information.</p><p>A multi-source research assistant solves this limitation by retrieving information from different sources before generating an answer.</p><p>The important idea is that <strong>the LLM should not be responsible for finding everything from memory. It should reason over information retrieved from relevant sources.</strong></p><h3>5. Understanding the Core Architecture</h3><p>Before writing code, let’s understand the major components.</p><h3>5.1 Web Search</h3><p>Web search allows the application to retrieve information from publicly available websites.</p><p><strong>Why do we need it?</strong></p><p>LLMs have knowledge limitations and may not know about recent developments.</p><p>Web search provides access to external information that can be retrieved when the user asks a question.</p><p>For example, if someone asks about the latest developments in AI agents, the system can search for relevant articles and documentation.</p><p>We will use Tavily as our search provider.</p><h3>5.2 Document Processing</h3><p>The second source is user-provided documents.</p><p>These could include:</p><ul><li>PDF research papers.</li><li>Technical documentation.</li><li>Word documents.</li><li>Project reports.</li><li>Internal knowledge documents.</li></ul><p>The application extracts text from these files and prepares it for retrieval.</p><h3>5.3 Embeddings and Vector Database</h3><p>Documents can be large, making it inefficient to send their entire contents to an LLM for every question.</p><p>Instead, we divide documents into smaller chunks and convert those chunks into numerical representations called embeddings.</p><p>These embeddings capture semantic meaning and allow the system to find content related to a user’s question.</p><p>ChromaDB stores the embeddings and their associated text.</p><h3>5.4 LLM-Based Answer Generation</h3><p>After collecting relevant information from the web and documents, the system combines the results into a common context.</p><p>The LLM uses this context to generate a readable answer.</p><p>It can also identify supporting sources and organize the response into sections.</p><h3>6. Step-by-Step Project Implementation</h3><p>Let’s build the application progressively.</p><h3>Step 1: Install Dependencies</h3><p>Create a Python environment and install the required packages.</p><pre>pip install langchain langchain-openai<br>pip install langchain-community langchain-chroma<br>pip install tavily-python<br>pip install pypdf streamlit python-dotenv</pre><p>These packages provide document loading, embeddings, vector storage, web search, and application development capabilities.</p><h3>Step 2: Configure API Keys</h3><p>Create a .env file.</p><pre>OPENAI_API_KEY=your_openai_api_key<br>TAVILY_API_KEY=your_tavily_api_key</pre><p>Load the credentials into Python.</p><pre>import os<br>from dotenv import load_dotenv</pre><pre>load_dotenv()</pre><pre>OPENAI_API_KEY = os.getenv(&quot;OPENAI_API_KEY&quot;)<br>TAVILY_API_KEY = os.getenv(&quot;TAVILY_API_KEY&quot;)</pre><p>Never hardcode API credentials in your application or commit the .env file to GitHub.</p><h3>Step 3: Implement Web Search</h3><p>Let’s create a function that retrieves information from the internet.</p><pre>from tavily import TavilyClient</pre><pre>tavily = TavilyClient(<br>    api_key=TAVILY_API_KEY<br>)</pre><pre>def search_web(query):</pre><pre>    response = tavily.search(<br>        query=query,<br>        max_results=5<br>    )</pre><pre>    results = []</pre><pre>    for item in response[&quot;results&quot;]:<br>        results.append({<br>            &quot;title&quot;: item[&quot;title&quot;],<br>            &quot;content&quot;: item[&quot;content&quot;],<br>            &quot;url&quot;: item[&quot;url&quot;]<br>        })</pre><pre>    return results</pre><p><strong>How it works:</strong></p><ul><li>The user provides a research question.</li><li>Tavily searches the web.</li><li>The API returns relevant search results.</li><li>We extract the title, content, and URL.</li></ul><p>Returning the URLs is important because the final answer should identify where the information came from.</p><h3>Step 4: Process Uploaded Documents</h3><p>Now let’s implement document loading.</p><p>We will use PDF files for this example.</p><pre>from langchain_community.document_loaders import (<br>    PyPDFLoader<br>)</pre><pre>def load_document(file_path):</pre><pre>    loader = PyPDFLoader(file_path)</pre><pre>    documents = loader.load()</pre><pre>    return documents</pre><p>The PDF loader extracts text and creates document objects containing the page content and metadata.</p><p>Next, divide the extracted content into smaller chunks.</p><pre>from langchain_text_splitters import (<br>    RecursiveCharacterTextSplitter<br>)</pre><pre>def split_documents(documents):</pre><pre>    splitter = RecursiveCharacterTextSplitter(<br>        chunk_size=1000,<br>        chunk_overlap=200<br>    )</pre><pre>    chunks = splitter.split_documents(documents)</pre><pre>    return chunks</pre><p><strong>Why do we split documents?</strong></p><p>Imagine a 100-page research paper.</p><p>Sending the entire document to an LLM for every question can increase token consumption and introduce irrelevant information.</p><p>Chunking creates smaller sections that can be retrieved independently.</p><p>The overlap helps preserve context between neighboring chunks.</p><h3>Step 5: Generate Embeddings and Store Them in ChromaDB</h3><p>Now we need to convert the document chunks into embeddings.</p><pre>from langchain_openai import OpenAIEmbeddings<br>from langchain_chroma import Chroma</pre><pre>embeddings = OpenAIEmbeddings(<br>    model=&quot;text-embedding-3-small&quot;<br>)</pre><pre>def create_vector_store(chunks):</pre><pre>    vector_store = Chroma.from_documents(<br>        documents=chunks,<br>        embedding=embeddings,<br>        persist_directory=&quot;./chroma_db&quot;<br>    )</pre><pre>    return vector_store</pre><p>The embedding model converts each text chunk into a numerical vector.</p><p>ChromaDB stores these vectors along with their original text and metadata.</p><p>When a user asks a question, the same embedding model converts the question into a vector so that semantically similar chunks can be retrieved.</p><h3>Step 6: Retrieve Relevant Document Information</h3><p>Let’s implement document retrieval.</p><pre>def retrieve_documents(vector_store, query):</pre><pre>    results = vector_store.similarity_search(<br>        query,<br>        k=4<br>    )</pre><pre>    return results</pre><p>Here, k=4 means the system retrieves four relevant document chunks.</p><p>For example, if the user asks about RAG evaluation, the vector database searches for document chunks that are semantically related to RAG evaluation.</p><p>This is more useful than simply searching for exact keyword matches.</p><p>However, similarity does not guarantee factual relevance. Production systems may benefit from metadata filtering, hybrid retrieval, and reranking.</p><h3>Step 7: Combine Multiple Sources</h3><p>We now have two independent information sources:</p><ul><li>Web search results.</li><li>Retrieved document chunks.</li></ul><p>The next step is to combine them into a unified context.</p><pre>def build_context(web_results, document_results):</pre><pre>    context = &quot;WEB SOURCES:\n&quot;</pre><pre>    for result in web_results:<br>        context += (<br>            f&quot;Title: {result[&#39;title&#39;]}\n&quot;<br>            f&quot;Content: {result[&#39;content&#39;]}\n&quot;<br>            f&quot;URL: {result[&#39;url&#39;]}\n\n&quot;<br>        )</pre><pre>    context += &quot;\nUPLOADED DOCUMENTS:\n&quot;</pre><pre>    for doc in document_results:<br>        context += (<br>            f&quot;Content: {doc.page_content}\n&quot;<br>            f&quot;Metadata: {doc.metadata}\n\n&quot;<br>        )</pre><pre>    return context</pre><p>This function creates a shared context containing information from both sources.</p><p>Keeping source information and document metadata is important for traceability.</p><h3>Step 8: Generate the Research Answer Using an LLM</h3><p>Now comes the final stage.</p><p>We send the research question and collected context to an LLM.</p><pre>from langchain_openai import ChatOpenAI</pre><pre>llm = ChatOpenAI(<br>    model=&quot;gpt-4.1-mini&quot;,<br>    temperature=0<br>)</pre><pre>def generate_answer(query, context):</pre><pre>    prompt = f&quot;&quot;&quot;<br>    You are an AI research assistant.</pre><pre>    Answer the question using the<br>    provided research context.</pre><pre>    Instructions:<br>    - Use relevant information only.<br>    - Do not invent facts.<br>    - Identify supporting sources.<br>    - Mention when information is insufficient.<br>    - Organize the answer clearly.</pre><pre>    Research Question:<br>    {query}</pre><pre>    Research Context:<br>    {context}<br>    &quot;&quot;&quot;</pre><pre>    response = llm.invoke(prompt)</pre><pre>    return response.content</pre><p><strong>Why use temperature 0?</strong></p><p>For research-oriented applications, we generally want consistent and focused responses rather than unnecessary creative variations.</p><p>However, a low temperature does not guarantee factual accuracy. The application still needs source validation and appropriate evaluation.</p><h3>Step 9: Connect Everything</h3><p>We now have all the individual components.</p><p>Let’s connect them into one research pipeline.</p><pre>def research_assistant(query, vector_store):</pre><pre>    # Search the web<br>    web_results = search_web(query)</pre><pre>    # Retrieve relevant document chunks<br>    document_results = retrieve_documents(<br>        vector_store,<br>        query<br>    )</pre><pre>    # Combine the sources<br>    context = build_context(<br>        web_results,<br>        document_results<br>    )</pre><pre>    # Generate the final answer<br>    answer = generate_answer(<br>        query,<br>        context<br>    )</pre><pre>    return answer</pre><p>The function coordinates the entire workflow.</p><p>A single research question triggers web search, document retrieval, context construction, and LLM-based answer generation.</p><p>The important architectural decision is that each component has a separate responsibility.</p><p>This makes the application easier to debug, test, and extend.</p><h3>7. Visualizing the Complete Architecture</h3><p>Let’s visualize how information moves through the application.</p><pre>flowchart TD<br>    A[User Research Question] --&gt; B[Research Assistant]<br>    B --&gt; C[Web Search]<br>    B --&gt; D[Document Retrieval]<br>    D --&gt; E[Embedding Model]<br>    E --&gt; F[ChromaDB]<br>    C --&gt; G[Source Collection]<br>    F --&gt; G<br>    G --&gt; H[Context Builder]<br>    H --&gt; I[LLM]<br>    I --&gt; J[Research Answer]<br>    J --&gt; K[Display Sources and Response]</pre><p>The web search and document retrieval components work independently.</p><p>Their results are combined before reaching the LLM.</p><p>This architecture makes it possible to introduce additional information sources without redesigning the entire application.</p><h3>8. Building a Simple User Interface with Streamlit</h3><p>A research assistant should be easy to interact with.</p><p>Streamlit allows us to build a basic interface without developing a separate frontend.</p><pre>import streamlit as st</pre><pre>st.title(&quot;Multi-Source AI Research Assistant&quot;)</pre><pre>query = st.text_input(<br>    &quot;Enter your research question&quot;<br>)</pre><pre>if st.button(&quot;Research&quot;) and query:</pre><pre>    with st.spinner(&quot;Researching...&quot;):</pre><pre>        answer = research_assistant(<br>            query,<br>            vector_store<br>        )</pre><pre>    st.subheader(&quot;Research Results&quot;)<br>    st.write(answer)</pre><p>The interface accepts a research question and displays the generated answer.</p><p>For a complete application, add PDF upload functionality, document indexing, source links, and error handling.</p><h3>9. Real-World Applications</h3><p>This architecture can support several useful applications:</p><p><strong>Academic Research Assistant:</strong> Search research papers and combine them with recent web publications.</p><p><strong>Enterprise Knowledge Assistant:</strong> Answer employee questions using internal documentation and external technical resources.</p><p><strong>Technical Documentation Assistant:</strong> Search official documentation alongside uploaded engineering guides.</p><p><strong>Market Research Assistant:</strong> Combine public industry reports with internal business documents.</p><p><strong>AI Engineering Research Tool:</strong> Investigate frameworks, compare technical approaches, and summarize implementation strategies.</p><h3>10. Best Practices for Production-Ready Systems</h3><ul><li><strong>Preserve source metadata:</strong> Store URLs, document names, page numbers, and publication details.</li><li><strong>Control context size:</strong> Avoid sending unnecessarily large amounts of retrieved text to the LLM.</li><li><strong>Use source attribution:</strong> Make it possible to trace generated claims to their supporting information.</li><li><strong>Handle unavailable sources:</strong> Web search and document retrieval should fail independently without crashing the entire application.</li><li><strong>Avoid duplicate information:</strong> Similar documents and repeated search results can introduce redundant context.</li><li><strong>Validate retrieved content:</strong> Do not assume that the most similar chunk is always relevant.</li><li><strong>Protect against prompt injection:</strong> Treat retrieved web pages and uploaded documents as untrusted data, not instructions.</li><li><strong>Manage API costs:</strong> Monitor embedding requests, search usage, and LLM token consumption.</li><li><strong>Evaluate retrieval quality:</strong> Test whether the system retrieves the correct information before evaluating answer generation.</li><li><strong>Respect data privacy:</strong> Avoid sending confidential documents to external services without appropriate authorization.</li></ul><h3>11. Common Mistakes Developers Should Avoid</h3><ul><li>Sending entire PDFs directly to an LLM.</li><li>Choosing chunk sizes without testing retrieval quality.</li><li>Assuming vector similarity guarantees accurate retrieval.</li><li>Combining sources without preserving their metadata.</li><li>Generating answers without source attribution.</li><li>Ignoring outdated or contradictory information.</li><li>Treating LLM-generated answers as automatically factual.</li><li>Exposing API keys in source code.</li><li>Ignoring API failures and rate limits.</li><li>Failing to evaluate the complete research pipeline.</li></ul><h3>12. Performance and Scalability Considerations</h3><p>As the number of documents and research requests increases, performance becomes important.</p><p>Some improvements include:</p><p><strong>Asynchronous execution:</strong> Run web search and document retrieval concurrently because they are independent operations.</p><p><strong>Caching:</strong> Cache frequently requested search results and reusable document retrieval results, with appropriate freshness controls.</p><p><strong>Persistent vector storage:</strong> Avoid recreating document embeddings every time the application starts.</p><p><strong>Retrieval optimization:</strong> Use metadata filtering, hybrid search, and reranking to improve retrieval quality.</p><p><strong>Context optimization:</strong> Retrieve only the information needed to answer the question.</p><p>For larger systems, you can also introduce background document indexing, task queues, observability, and distributed storage.</p><h3>13. Summary: Bringing Multiple Knowledge Sources Together</h3><p>In this project, we built the foundation of a multi-source AI research assistant using web search, uploaded documents, vector embeddings, ChromaDB, and an LLM.</p><p>The central idea is simple:</p><p><strong>Search for information, retrieve relevant knowledge, combine the context, and let the LLM generate a grounded response.</strong></p><p>Key takeaways:</p><ul><li>Web search provides access to external information.</li><li>Document processing makes private knowledge searchable.</li><li>Embeddings enable semantic retrieval.</li><li>Vector databases store and retrieve relevant content.</li><li>LLMs synthesize information from multiple sources.</li><li>Source metadata makes research more transparent and verifiable.</li></ul><p>This project is a starting point rather than a complete production research platform.</p><p>You can extend it with hybrid retrieval, reranking, citation verification, query decomposition, multi-agent research workflows, and evaluation pipelines.</p><p>The real value of a multi-source research assistant is not simply that it can search multiple places.</p><p><strong>It is that it can bring scattered information together and turn it into structured, traceable, and useful knowledge.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*22aEXoRKPE8QESzHRtevAw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90678e38db77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implement Human-in-the-Loop Workflows for Safer AI Agents]]></title>
            <link>https://medium.com/@s.aditya1317/implement-human-in-the-loop-workflows-for-safer-ai-agents-9d24db43cae7?source=rss-2d1520186482------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d24db43cae7</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Aditya S]]></dc:creator>
            <pubDate>Thu, 19 Nov 2026 14:30:29 GMT</pubDate>
            <atom:updated>2026-11-19T14:30:29.955Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Introduction: Why AI Agents Still Need Human Oversight</h3><p>AI agents are becoming increasingly capable of performing complex tasks. They can search the web, query databases, execute code, send emails, update records, and interact with external services.</p><p>But there is one important question:</p><p><strong>Should an AI agent be allowed to make every decision and execute every action without human approval?</strong></p><p>Imagine building an AI agent that manages customer support. It can read customer complaints, identify problems, and issue refunds.</p><p>Now consider what happens when it incorrectly interprets a complaint and issues a $5,000 refund.</p><p>The problem is not necessarily that the AI cannot understand the request. The problem is that it was allowed to execute a high-impact action without human verification.</p><p>This is where Human-in-the-Loop (HITL) workflows become important.</p><p>Instead of allowing an agent to operate completely autonomously, we introduce checkpoints where a human can review, approve, reject, or modify its proposed actions.</p><p>The goal is not to make AI agents less autonomous. It is to make their autonomy safer and more controlled.</p><h3>2. What You Will Learn</h3><p>By the end of this tutorial, you will understand:</p><ul><li>What Human-in-the-Loop workflows are.</li><li>Why autonomous AI agents need human supervision.</li><li>How approval and rejection mechanisms work.</li><li>How to implement human approval using Python.</li><li>How to build stateful HITL workflows using LangGraph.</li><li>How to handle interruptions, retries, and human feedback.</li><li>How to design safer production-ready AI agents.</li></ul><h3>3. Prerequisites</h3><ul><li>Basic Python programming.</li><li>Understanding of LLMs and AI agents.</li><li>Familiarity with APIs and tool calling.</li><li>Basic knowledge of LangChain is helpful.</li><li>Familiarity with LangGraph is useful but not mandatory.</li></ul><h3>4. Understanding the Problem: The Risks of Fully Autonomous Agents</h3><p>Traditional software systems generally execute predefined instructions.</p><p>AI agents are different. They can dynamically decide which tools to use, what actions to perform, and how to approach a task.</p><p>This flexibility creates opportunities, but it also introduces risks.</p><p>Consider an AI agent responsible for managing business operations.</p><p>It might:</p><ol><li>Read an incoming email.</li><li>Identify a customer request.</li><li>Retrieve customer information.</li><li>Decide whether a refund is required.</li><li>Execute the refund through a payment API.</li></ol><p>Steps 1–4 involve information processing and decision-making. Step 5 creates a real-world financial consequence.</p><p>What if the agent misunderstood the request?</p><p>What if the customer is not eligible for a refund?</p><p>What if the agent generated incorrect payment parameters?</p><p>Without human oversight, the agent could execute an incorrect decision immediately.</p><p><strong>The fundamental problem is that an AI-generated decision should not automatically be treated as an authorized action.</strong></p><h3>5. What Is Human-in-the-Loop (HITL)?</h3><p>Human-in-the-Loop is a system design approach where humans participate in an AI workflow at specific decision points.</p><p>Instead of allowing an AI agent to execute every action independently, the system pauses when human judgment or authorization is required.</p><p>A human can generally:</p><ul><li>Approve an action.</li><li>Reject an action.</li><li>Modify the proposed action.</li><li>Provide additional information.</li><li>Request the agent to reconsider its decision.</li></ul><p>Think of it like an airport security checkpoint.</p><p>Passengers can move through the airport independently, but certain actions require verification before they are allowed to proceed.</p><p>Similarly, an AI agent can perform routine tasks autonomously while sensitive operations require human authorization.</p><h3>Why do we need HITL?</h3><p>HITL helps address three important limitations of autonomous AI systems:</p><p><strong>1. Uncertainty:</strong> LLMs can produce incorrect information or misinterpret instructions.</p><p><strong>2. Accountability:</strong> Certain decisions require an identifiable human authority.</p><p><strong>3. Risk management:</strong> Some actions can cause financial, operational, legal, or security consequences.</p><h3>When should we use it?</h3><p>Use HITL when an agent performs actions such as:</p><ul><li>Processing financial transactions.</li><li>Sending external emails.</li><li>Deleting or modifying important records.</li><li>Approving customer refunds.</li><li>Publishing content.</li><li>Changing production configurations.</li><li>Accessing sensitive business systems.</li></ul><p>For low-risk tasks, such as summarizing documents or categorizing text, human approval may introduce unnecessary friction.</p><p>The objective is to apply human oversight proportionally to the risk.</p><h3>6. Understanding the Three HITL Interaction Patterns</h3><p>Human involvement does not always mean approving every action.</p><p>There are three useful interaction patterns.</p><h3>6.1 Human Approval</h3><p>The agent proposes an action and waits for explicit authorization.</p><p>Example:</p><p>An agent prepares a customer refund of $500. Before calling the payment API, it requests approval from an authorized employee.</p><p>Use this when an action has significant consequences and must be authorized before execution.</p><h3>6.2 Human Review and Modification</h3><p>The agent generates a proposed result, but a human can modify it before execution.</p><p>Example:</p><p>An AI agent drafts an email to a customer. A support employee reviews and edits the message before sending it.</p><p>Use this when the AI can prepare most of the work but human judgment improves accuracy or communication quality.</p><h3>6.3 Human Feedback and Replanning</h3><p>The human provides additional information or corrections, and the agent uses that feedback to determine its next action.</p><p>Example:</p><p>An agent recommends a refund, but the manager explains that the customer is outside the refund policy.</p><p>The agent receives this information and revises its recommendation.</p><p>Use this when the task involves ambiguity, changing requirements, or decisions that benefit from human expertise.</p><h3>7. Building a Simple Human-in-the-Loop Workflow with Python</h3><p>Let’s implement a basic approval mechanism before introducing an agent framework.</p><p>Our example will involve an AI agent proposing a financial transaction.</p><h3>Level 1: Basic Approval Mechanism</h3><p>First, define a function that requests human approval.</p><pre>def request_approval(action, amount):</pre><pre>    print(&quot;\nAction requires approval&quot;)<br>    print(f&quot;Action: {action}&quot;)<br>    print(f&quot;Amount: ${amount}&quot;)</pre><pre>    decision = input(<br>        &quot;Approve this action? (yes/no): &quot;<br>    ).strip().lower()</pre><pre>    return decision == &quot;yes&quot;<br></pre><pre>def execute_refund(amount):</pre><pre>    print(f&quot;Refund of ${amount} executed.&quot;)<br></pre><pre>amount = 500</pre><pre>if request_approval(&quot;Customer Refund&quot;, amount):<br>    execute_refund(amount)<br>else:<br>    print(&quot;Refund rejected.&quot;)</pre><p><strong>How it works:</strong></p><ol><li>The agent proposes a refund.</li><li>The approval function displays the proposed action.</li><li>A human enters an approval decision.</li><li>The refund executes only when approval is granted.</li></ol><p>This introduces an important architectural separation:</p><p><strong>The agent proposes an action; the human authorizes it; the system executes it.</strong></p><p>This example is intentionally simple. In production, approval should happen through an authenticated interface rather than a terminal input.</p><h3>Level 2: Add Approval States</h3><p>A production workflow needs more than a yes-or-no response.</p><p>We should explicitly track the status of an action.</p><pre>def process_action(action, approved):</pre><pre>    if approved:<br>        status = &quot;APPROVED&quot;<br>        print(f&quot;Executing: {action}&quot;)</pre><pre>    else:<br>        status = &quot;REJECTED&quot;<br>        print(f&quot;Action rejected: {action}&quot;)</pre><pre>    return {<br>        &quot;action&quot;: action,<br>        &quot;status&quot;: status<br>    }<br></pre><pre>result = process_action(<br>    action=&quot;Delete customer record&quot;,<br>    approved=False<br>)</pre><pre>print(result)</pre><p><strong>Why is this better?</strong></p><p>The workflow now maintains an explicit execution outcome.</p><p>You can extend this design with additional states:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*2HbOPchvTbUf-G2vOjjIQw.png" /></figure><p>These states make it easier to monitor workflows, investigate failures, and maintain audit records.</p><h3>8. Implementing Human Approval with LangGraph</h3><p>The previous examples demonstrate the concept, but real AI agents often execute multiple interconnected steps.</p><p>For these workflows, LangGraph provides a useful approach.</p><p>LangGraph supports stateful agent execution, conditional routing, and human intervention through interrupts.</p><p>One particularly useful feature is interrupt().</p><p>It allows a workflow to pause at a specific point and wait for external input. The workflow can later resume using Command(resume=...).</p><h3>Step 1: Install Dependencies</h3><pre>pip install -U langgraph langchain-openai</pre><p>Configure your OpenAI API key using a secure environment variable.</p><h3>Step 2: Define the Workflow State</h3><p>The state stores information shared between workflow nodes.</p><pre>from typing import TypedDict<br></pre><pre>class AgentState(TypedDict):<br>    amount: float<br>    action: str<br>    approval: str<br>    result: str</pre><p>Here, we maintain the proposed action, transaction amount, approval decision, and execution result.</p><h3>Step 3: Create the Approval Node</h3><pre>from langgraph.types import interrupt<br></pre><pre>def human_approval(state: AgentState):</pre><pre>    decision = interrupt({<br>        &quot;message&quot;: &quot;Approval required&quot;,<br>        &quot;action&quot;: state[&quot;action&quot;],<br>        &quot;amount&quot;: state[&quot;amount&quot;]<br>    })</pre><pre>    return {<br>        &quot;approval&quot;: decision<br>    }</pre><p>The interrupt() function pauses the graph and exposes the approval request to the external application.</p><p>The workflow does not continue until a resume value is supplied.</p><h3>Step 4: Create the Execution Node</h3><pre>def execute_action(state: AgentState):</pre><pre>    if state[&quot;approval&quot;] == &quot;approved&quot;:</pre><pre>        return {<br>            &quot;result&quot;: &quot;Action executed successfully.&quot;<br>        }</pre><pre>    return {<br>        &quot;result&quot;: &quot;Action rejected.&quot;<br>    }</pre><p>The execution node checks the human’s decision before proceeding.</p><p>For this example, execution is simulated rather than connected to a real payment service.</p><h3>Step 5: Connect the Workflow</h3><pre>from langgraph.graph import StateGraph, START, END<br></pre><pre>builder = StateGraph(AgentState)</pre><pre>builder.add_node(&quot;approval&quot;, human_approval)<br>builder.add_node(&quot;execute&quot;, execute_action)</pre><pre>builder.add_edge(START, &quot;approval&quot;)</pre><pre>builder.add_conditional_edges(<br>    &quot;approval&quot;,<br>    lambda state: (<br>        &quot;execute&quot;<br>        if state[&quot;approval&quot;] == &quot;approved&quot;<br>        else END<br>    ),<br>    {<br>        &quot;execute&quot;: &quot;execute&quot;,<br>        END: END<br>    }<br>)</pre><pre>builder.add_edge(&quot;execute&quot;, END)</pre><p>The workflow follows a simple structure:</p><ul><li>Start the workflow.</li><li>Request human approval.</li><li>Execute the action if approved.</li><li>End the workflow if rejected.</li></ul><h3>Step 6: Add a Checkpointer and Run the Workflow</h3><p>LangGraph needs a checkpointer to preserve workflow state across interruptions.</p><pre>from langgraph.checkpoint.memory import InMemorySaver</pre><pre>checkpointer = InMemorySaver()</pre><pre>graph = builder.compile(<br>    checkpointer=checkpointer<br>)</pre><pre>config = {<br>    &quot;configurable&quot;: {<br>        &quot;thread_id&quot;: &quot;refund-001&quot;<br>    }<br>}</pre><pre>initial_state = {<br>    &quot;amount&quot;: 500,<br>    &quot;action&quot;: &quot;Customer Refund&quot;,<br>    &quot;approval&quot;: &quot;&quot;,<br>    &quot;result&quot;: &quot;&quot;<br>}</pre><pre>response = graph.invoke(<br>    initial_state,<br>    config=config<br>)</pre><pre>print(response)</pre><p>At this point, the graph pauses at the approval node.</p><p>In a real application, the interrupted state can be presented through a web interface, dashboard, or approval system.</p><h3>Step 7: Resume After Human Approval</h3><p>Once a human reviews the proposed action, the application resumes the workflow.</p><pre>from langgraph.types import Command</pre><pre>response = graph.invoke(<br>    Command(resume=&quot;approved&quot;),<br>    config=config<br>)</pre><pre>print(response)</pre><p>The graph resumes from the interrupted point and continues execution.</p><p><strong>Important:</strong> The example uses an in-memory checkpointer for demonstration. Production workflows should use durable persistence, authenticated approval interfaces, and appropriate authorization checks.</p><h3>9. Visualizing the Human-in-the-Loop Architecture</h3><p>Here is how a typical HITL workflow operates.</p><pre>flowchart TD<br>    A[User Request] --&gt; B[AI Agent]<br>    B --&gt; C[Analyze and Plan]<br>    C --&gt; D[Propose Action]<br>    D --&gt; E{Human Approval}<br>    E --&gt;|Approved| F[Execute Tool]<br>    E --&gt;|Rejected| G[Stop Execution]<br>    E --&gt;|Modified| H[Update Action]<br>    H --&gt; E<br>    F --&gt; I[Validate Result]<br>    I --&gt; J[Return Final Response]<br>    G --&gt; K[Return Rejection Status]</pre><p>Notice that human approval happens between decision-making and execution.</p><p>This is important because reviewing an action after it has already been executed cannot prevent its original consequences.</p><h3>10. Real-World Applications</h3><p>HITL workflows are useful across multiple industries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*0jlbfMmhrvdfPkI0XFxm0Q.png" /></figure><p>The level of human involvement should depend on the potential impact of an incorrect action.</p><h3>11. Best Practices for Production-Ready HITL Systems</h3><ol><li><strong>Use risk-based approval:</strong> Require approval for high-impact actions, not every tool call.</li><li><strong>Maintain durable state:</strong> Preserve workflow progress across interruptions and application restarts.</li><li><strong>Authenticate reviewers:</strong> Ensure approvals come from authorized individuals.</li><li><strong>Validate approved actions:</strong> Revalidate parameters before execution, especially if the action has been modified.</li><li><strong>Maintain audit logs:</strong> Record who approved an action, when it happened, and what was executed.</li><li><strong>Implement timeouts:</strong> Define what happens when an approval request receives no response.</li><li><strong>Prevent duplicate execution:</strong> Use idempotency keys for operations that could cause repeated side effects.</li><li><strong>Apply least privilege:</strong> Give agents only the permissions required for their tasks.</li><li><strong>Separate approval from execution:</strong> Never treat an LLM-generated approval decision as human authorization.</li><li><strong>Test failure scenarios:</strong> Test rejection, timeout, modified requests, interrupted workflows, and execution failures.</li></ol><h3>12. Common Mistakes Developers Should Avoid</h3><ul><li>Asking humans to approve every small operation.</li><li>Allowing the agent to bypass approval checkpoints.</li><li>Treating a model-generated response as human consent.</li><li>Failing to persist workflow state during interruptions.</li><li>Not verifying whether the person approving an action has the required permissions.</li><li>Executing modified actions without validating their parameters.</li><li>Ignoring approval timeouts.</li><li>Assuming that human approval guarantees the underlying action will succeed.</li><li>Failing to maintain an audit trail.</li></ul><h3>13. Performance and Design Considerations</h3><p>Human approval introduces additional latency because the workflow must wait for an external decision.</p><p>However, not every operation needs to be paused.</p><p>A practical approach is to classify operations by risk:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*ty96vuZkuv_Y2_i_qjcSeA.png" /></figure><p>This risk-based design maintains efficiency without sacrificing control.</p><p>For large-scale systems, approval workflows should also support asynchronous notifications, durable execution, timeout handling, and workflow recovery.</p><h3>14. Summary: Build Agents That Know When to Ask</h3><p>Human-in-the-Loop workflows introduce an important control mechanism into autonomous AI systems.</p><p>They allow agents to handle routine operations independently while ensuring that sensitive decisions receive appropriate human oversight.</p><p>The key concepts to remember:</p><ul><li>HITL introduces human supervision into AI workflows.</li><li>Approval, rejection, modification, and feedback are different interaction patterns.</li><li>LangGraph’s interrupt() enables workflows to pause and resume.</li><li>State persistence is essential for reliable execution.</li><li>Risk-based approval prevents unnecessary human intervention.</li><li>Authentication, authorization, and audit logs are essential for production systems.</li></ul><p><strong>The future of reliable AI agents is not necessarily complete autonomy. It is controlled autonomy, where AI handles what it can and knows when human judgment is necessary.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rofg2-ClnDJgSIBRyJPRHw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d24db43cae7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why AI Agents Make Repeated Tool Calls: Understanding Planning and Execution Failures]]></title>
            <link>https://medium.com/@s.aditya1317/why-ai-agents-make-repeated-tool-calls-understanding-planning-and-execution-failures-b21bf849436f?source=rss-2d1520186482------2</link>
            <guid isPermaLink="false">https://medium.com/p/b21bf849436f</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Aditya S]]></dc:creator>
            <pubDate>Wed, 18 Nov 2026 09:11:13 GMT</pubDate>
            <atom:updated>2026-11-18T09:11:13.555Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Have you ever built an AI agent that keeps calling the same tool repeatedly, even after receiving the information it needs?</p><p>For example, an AI agent is asked to search for a customer’s order status. It calls the order lookup tool, receives the result, calls it again, and then repeats the same operation without making progress.</p><p>This is not necessarily a tool problem. In many cases, the underlying issue is how the agent plans, interprets results, and decides what to do next.</p><p>AI agents are designed to reason, plan, use tools, and execute multi-step tasks. However, having access to tools does not automatically mean an agent knows when to use them or when to stop.</p><p>Understanding repeated tool calls is important when building reliable AI applications, especially systems using LangChain, LangGraph, APIs, and autonomous workflows.</p><p>Let’s understand why this happens and how to fix it.</p><h3>1. What You Will Learn</h3><p>By the end of this article, you will understand:</p><ul><li>Why AI agents repeatedly call the same tools.</li><li>The difference between planning failures and execution failures.</li><li>How an agent decides which tool to invoke.</li><li>How to detect repetitive tool-call patterns.</li><li>How to implement safeguards against unnecessary executions.</li><li>How state management and termination conditions improve agent reliability.</li></ul><h3>2. Prerequisites</h3><p>You should have a basic understanding of:</p><ul><li>Python fundamentals.</li><li>Large Language Models (LLMs).</li><li>AI agents and tool calling.</li><li>APIs and function execution.</li><li>Basic familiarity with LangChain or LangGraph (helpful but optional).</li></ul><h3>3. Understanding the Problem</h3><p>Imagine asking an AI agent:</p><p>“Find the latest weather information for Mumbai and summarize it.”</p><p>A properly functioning agent should:</p><ol><li>Understand the request.</li><li>Identify the weather tool.</li><li>Call the tool.</li><li>Receive the weather information.</li><li>Summarize the result.</li><li>Return the final response.</li></ol><p>But something different can happen.</p><p>The agent calls the weather tool, receives the result, and calls it again. It continues repeating the operation instead of producing an answer.</p><p>Why?</p><p>Because the agent may not recognize that the previous tool call successfully completed the required task.</p><p>This creates a repetitive execution loop.</p><p><strong>The important distinction:</strong> A tool call is an action. It is not proof of progress.</p><p>An agent can perform multiple actions without getting closer to its objective.</p><h3>4. Why Do AI Agents Repeat Tool Calls?</h3><p>There are several underlying causes.</p><h3>4.1 Planning Failure</h3><p><strong>What is it?</strong></p><p>Planning failure occurs when an agent cannot create a clear sequence of actions to accomplish its objective.</p><p>Instead of deciding what information it needs and how to obtain it, the agent repeatedly selects actions without a meaningful plan.</p><p><strong>Why does it happen?</strong></p><p>LLMs generate decisions based on available context. If the objective, intermediate steps, or expected outcomes are unclear, the agent may struggle to determine its next action.</p><p>For example:</p><ul><li>Objective: Find customer information.</li><li>Action: Call customer lookup.</li><li>Result: Customer information retrieved.</li><li>Next decision: Call customer lookup again.</li></ul><p>The agent has no explicit completion criteria.</p><p><strong>How to prevent it?</strong></p><p>Break complex objectives into smaller tasks and define what successful completion looks like.</p><h3>4.2 Execution Failure</h3><p>Planning and execution are different.</p><p>An agent might have a perfectly reasonable plan but fail while carrying it out.</p><p>For example, an agent plans to retrieve customer information and generate a report. However, the API returns incomplete information.</p><p>Instead of handling the missing data, the agent repeatedly retries the same request.</p><p>Common execution failures include:</p><ul><li>API timeouts.</li><li>Invalid tool responses.</li><li>Missing fields.</li><li>Authentication failures.</li><li>Incorrect parameter generation.</li><li>Poor error handling</li></ul><p>The solution is to distinguish between retryable failures and failures that require a different strategy.</p><p>A timeout may justify another attempt. An invalid customer ID usually requires correcting the input, not repeating the same request.</p><h3>4.3 Poor State Management</h3><p>State represents what an agent currently knows about a task.</p><p>It includes previous actions, tool outputs, intermediate results, and task progress.</p><p>Without proper state management, an agent may lose track of what it has already accomplished.</p><p>Consider this example:</p><pre>history = []</pre><pre>def call_tool(tool, query):<br>    result = tool(query)<br>    history.append(result)<br>    return result</pre><p>The history stores results, but storing information alone does not guarantee that the agent will use it.</p><p>A better approach is to maintain explicit execution state, including completed actions and pending tasks.</p><h3>4.4 Missing Termination Conditions</h3><p>Every agent needs a clear stopping condition.</p><p>Without one, an agent may continue executing actions even after completing its objective.</p><p>For example:</p><pre>while True:<br>    action = agent.decide_next_action()<br>    result = execute(action)</pre><p>This loop has no termination condition.</p><p>Even if the agent successfully retrieves the required information, nothing tells the execution system to stop.</p><p>A reliable agent should stop when:</p><ul><li>The objective is completed.</li><li>A final answer is generated.</li><li>The maximum execution limit is reached.</li><li>An unrecoverable error occurs.</li></ul><h3>5. How Tool Calling Actually Works</h3><p>Before fixing repeated tool calls, understand the basic execution cycle.</p><p>An AI agent generally follows this process:</p><p><strong>Observe → Reason → Act → Observe → Decide</strong></p><p>Let’s break it down.</p><ol><li><strong>Observe:</strong> The agent receives the user request and available context.</li><li><strong>Reason:</strong> The LLM determines what action is required.</li><li><strong>Act:</strong> The agent invokes a tool.</li><li><strong>Observe:</strong> The tool returns its result.</li><li><strong>Decide:</strong> The agent evaluates the result and chooses the next action.</li></ol><p>This cycle is commonly associated with the ReAct (Reasoning and Acting) approach.</p><p>The problem occurs when the agent fails to interpret the observation correctly or cannot decide that the task is complete.</p><h3>6. Practical Implementation: Detecting and Preventing Repeated Calls</h3><p>Let’s build the solution progressively.</p><h3>Level 1: Introduce a Maximum Execution Limit</h3><p>The simplest safeguard is to limit the number of tool executions.</p><pre>MAX_ITERATIONS = 5</pre><pre>for iteration in range(MAX_ITERATIONS):<br>    action = agent.decide_next_action()</pre><pre>    if action == &quot;DONE&quot;:<br>        break</pre><pre>    result = execute_tool(action)<br>    agent.update_context(result)<br>else:<br>    print(&quot;Maximum execution limit reached.&quot;)</pre><p><strong>How it works:</strong></p><ul><li>The agent gets a maximum of five execution opportunities.</li><li>After every tool call, the result is added to the context.</li><li>If the agent decides the task is complete, execution stops.</li><li>If the limit is reached, the loop terminates.</li></ul><p><strong>When should you use it?</strong></p><p>This is useful for almost every agent workflow because it prevents uncontrolled execution.</p><p>However, it does not identify whether repeated calls are actually unnecessary.</p><h3>Level 2: Detect Duplicate Tool Calls</h3><p>A more effective solution is to track previously executed tool calls.</p><pre>executed_calls = set()</pre><pre>def execute_safely(tool_name, parameters):</pre><pre>    call_signature = (<br>        tool_name,<br>        tuple(sorted(parameters.items()))<br>    )</pre><pre>    if call_signature in executed_calls:<br>        return &quot;Duplicate tool call detected.&quot;</pre><pre>    executed_calls.add(call_signature)</pre><pre>    return execute_tool(tool_name, parameters)</pre><p><strong>How it works:</strong></p><ul><li>Each tool call is represented by its name and parameters.</li><li>Before execution, the system checks whether the same call already exists.</li><li>If it does, execution is blocked.</li><li>Otherwise, the tool executes normally.</li></ul><p>For example, calling get_weather(city=&quot;Mumbai&quot;) twice with identical parameters will trigger duplicate detection.</p><p><strong>Important edge case:</strong> Not every repeated call is unnecessary. A second call might be required if the underlying data has changed or the previous execution failed.</p><p>Production systems should therefore distinguish between successful calls, failed calls, and intentionally repeatable operations.</p><h3>Level 3: Combine State Tracking and Termination Conditions</h3><p>Now let’s combine execution limits, duplicate detection, and task completion.</p><pre>MAX_ITERATIONS = 5</pre><pre>state = {<br>    &quot;completed&quot;: False,<br>    &quot;tool_calls&quot;: set(),<br>    &quot;results&quot;: []<br>}</pre><pre>for _ in range(MAX_ITERATIONS):</pre><pre>    action = agent.decide_next_action(state)</pre><pre>    if action[&quot;type&quot;] == &quot;finish&quot;:<br>        state[&quot;completed&quot;] = True<br>        break</pre><pre>    signature = (<br>        action[&quot;tool&quot;],<br>        tuple(sorted(action[&quot;parameters&quot;].items()))<br>    )</pre><pre>    if signature in state[&quot;tool_calls&quot;]:<br>        print(&quot;Repeated tool call detected.&quot;)<br>        break</pre><pre>    state[&quot;tool_calls&quot;].add(signature)</pre><pre>    result = execute_tool(<br>        action[&quot;tool&quot;],<br>        action[&quot;parameters&quot;]<br>    )</pre><pre>    state[&quot;results&quot;].append(result)</pre><pre>if not state[&quot;completed&quot;]:<br>    print(&quot;Task stopped before successful completion.&quot;)</pre><p><strong>What improved?</strong></p><p>The agent now has three important safeguards:</p><ul><li>Execution limits prevent infinite loops.</li><li>Duplicate detection prevents identical calls from executing repeatedly.</li><li>Completion tracking distinguishes successful termination from forced termination.</li></ul><p>This is a simplified implementation. A production agent should also handle tool exceptions, timeouts, retries, and persistent state.</p><h3>7. Visualizing the Failure and Solution</h3><p>The following diagram illustrates how a repeated tool-call loop develops and how execution controls prevent it.</p><pre>flowchart TD<br>    A[User Request] --&gt; B[Agent Planning]<br>    B --&gt; C[Select Tool]<br>    C --&gt; D[Execute Tool]<br>    D --&gt; E[Receive Result]<br>    E --&gt; F{Task Completed?}<br>    F --&gt;|No| G{Duplicate Call?}<br>    G --&gt;|Yes| H[Stop or Replan]<br>    G --&gt;|No| B<br>    F --&gt;|Yes| I[Generate Final Response]<br>    H --&gt; J[Return Controlled Result]</pre><p>The key improvement is that the agent evaluates its execution history before deciding to repeat an action.</p><p>Instead of blindly continuing, it can stop, replan, or request additional information.</p><h3>8. How Frameworks Like LangGraph Help</h3><p>When building more complex agents, managing execution through a simple Python loop becomes difficult.</p><p>This is where frameworks like LangGraph become useful.</p><p>LangGraph supports stateful workflows using nodes, edges, conditional routing, and controlled execution.</p><p>For example, an agent workflow can contain:</p><ul><li>A planning node.</li><li>A tool execution node.</li><li>A result validation node.</li><li>A conditional routing node.</li><li>A final response node.</li></ul><p>You can define explicit conditions for whether the workflow should continue, retry, replan, or terminate.</p><p>This makes execution more predictable than relying entirely on an LLM to decide when to stop.</p><p>However, using LangGraph does not automatically eliminate repeated tool calls. Developers must still design appropriate state transitions, retry policies, and termination conditions.</p><h3>9. Real-World Applications</h3><p>Understanding repeated tool calls becomes especially important in:</p><ul><li><strong>RAG systems:</strong> Agents repeatedly retrieve similar documents instead of synthesizing available context.</li><li><strong>Customer support agents:</strong> An agent repeatedly queries the same customer record.</li><li><strong>Research agents:</strong> An agent searches for the same information across multiple iterations.</li><li><strong>Database agents:</strong> An agent executes identical SQL queries unnecessarily.</li><li><strong>Multi-agent systems:</strong> Multiple agents repeat the same operation because task ownership is unclear.</li><li><strong>API automation:</strong> Repeated requests create unnecessary costs or duplicate operations.</li></ul><p>In production environments, these failures can increase latency, API consumption, infrastructure costs, and the risk of unintended side effects.</p><h3>10. Best Practices for Building Reliable AI Agents</h3><p>Follow these principles when designing agent workflows:</p><ol><li><strong>Define clear objectives:</strong> Every agent should know what successful completion means.</li><li><strong>Maintain execution state:</strong> Track completed actions, tool outputs, and pending tasks.</li><li><strong>Set iteration limits:</strong> Never allow an agent to execute indefinitely.</li><li><strong>Implement duplicate detection:</strong> Identify repeated calls with identical parameters.</li><li><strong>Validate tool responses:</strong> Check whether returned information is sufficient before continuing.</li><li><strong>Use controlled retries:</strong> Retry transient failures, not every unsuccessful operation.</li><li><strong>Add observability:</strong> Log tool names, parameters, execution times, results, and retry counts.</li><li><strong>Use deterministic workflows where possible:</strong> Avoid unnecessary LLM decisions for predictable operations.</li><li><strong>Handle side effects carefully:</strong> Use idempotency keys for operations such as payments and record creation.</li><li><strong>Evaluate agent behavior:</strong> Test whether the agent completes tasks without unnecessary tool executions.</li></ol><h3>11. Common Mistakes Developers Make</h3><ul><li>Assuming repeated tool calls are always caused by poor prompting.</li><li>Increasing the iteration limit instead of investigating the underlying problem.</li><li>Treating every API failure as retryable.</li><li>Storing tool results without making them available to subsequent decisions.</li><li>Using an LLM to decide everything instead of introducing deterministic controls.</li><li>Ignoring API costs and execution latency.</li><li>Treating forced termination as successful task completion.</li><li>Blocking all repeated calls without considering legitimate retries.</li></ul><h3>12. Performance Considerations</h3><p>Repeated tool calls affect more than execution quality.</p><p>Each unnecessary call can introduce:</p><ul><li>Additional LLM or API latency.</li><li>Increased token consumption.</li><li>Higher infrastructure costs.</li><li>More opportunities for failures.</li><li>Potentially duplicated side effects.</li></ul><p>For example, if an agent makes five unnecessary API calls per request and handles 10,000 requests daily, that creates 50,000 avoidable API calls every day.</p><p>This is why execution control should be considered an essential part of agent architecture, not an optional optimization.</p><h3>13. Summary: Key Takeaways</h3><p>Repeated tool calls are not simply a tool-calling issue. They often indicate deeper problems in planning, execution, state management, or termination logic.</p><p>Remember these principles:</p><ul><li>Planning determines what an agent should do.</li><li>Execution determines whether it can do it correctly.</li><li>State management helps it remember what has already happened.</li><li>Duplicate detection prevents unnecessary repeated actions.</li><li>Termination conditions ensure the agent knows when to stop.</li><li>Observability helps developers identify and debug failures.</li></ul><p><strong>The goal of a reliable AI agent is not to perform more actions. It is to complete the right actions with the least unnecessary execution.</strong></p><p>As AI applications become more autonomous, controlling how agents plan, execute, and terminate their workflows will become just as important as improving the intelligence of the underlying models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Rqxl67d-bikhr60NwGV5g.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b21bf849436f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM Quantization Explained: How 4-Bit and 8-Bit Models Reduce Memory Requirements]]></title>
            <link>https://medium.com/@s.aditya1317/llm-quantization-explained-how-4-bit-and-8-bit-models-reduce-memory-requirements-653de6ee7013?source=rss-2d1520186482------2</link>
            <guid isPermaLink="false">https://medium.com/p/653de6ee7013</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Aditya S]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 06:11:28 GMT</pubDate>
            <atom:updated>2026-11-16T06:11:28.377Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Large Language Models are powerful, but running them comes with a practical challenge: <strong>memory consumption</strong>.</p><p>A model with billions of parameters needs a significant amount of GPU memory just to load its weights. Add the memory required for input tokens, attention, intermediate computations, and generation, and running a large model locally can become expensive.</p><p>This is where <strong>LLM quantization</strong> becomes important.</p><p>Quantization reduces the number of bits used to represent model parameters. Instead of storing every weight in 32-bit or 16-bit precision, we can use 8-bit or even 4-bit representations.</p><p>The result? A model that requires significantly less memory and can often run on more affordable hardware.</p><p>But how does this work without completely destroying model quality?</p><p>Let’s understand it from first principles.</p><h3>1. What You Will Learn</h3><p>By the end of this article, you will understand:</p><ul><li>Why LLMs consume so much memory.</li><li>What quantization means and how it works.</li><li>The difference between FP32, FP16, INT8, and INT4.</li><li>How 4-bit and 8-bit quantization reduce memory requirements.</li><li>The difference between weight-only and activation quantization.</li><li>How to load a quantized model using Hugging Face and BitsAndBytes.</li><li>When to use 4-bit, 8-bit, or full-precision models.</li><li>The trade-offs between memory, speed, and model quality.</li></ul><h3>2. Prerequisites</h3><p>You should have a basic understanding of:</p><ul><li>Python fundamentals.</li><li>Neural networks and model parameters.</li><li>Large Language Models (LLMs).</li><li>GPU memory and model inference.</li></ul><p>You do not need advanced knowledge of numerical computing.</p><h3>3. Why Do LLMs Need So Much Memory?</h3><p>An LLM learns by adjusting millions or billions of numerical values called <strong>parameters</strong>.</p><p>These parameters include weights and biases that determine how the model processes information and generates responses.</p><p>Consider a model with 7 billion parameters.</p><p>If every parameter is stored using 32-bit floating-point precision, each parameter requires 4 bytes.</p><p>The memory required for model weights is:</p><p>That is only the memory needed to store the weights.</p><p>During inference, additional memory is required for:</p><ul><li>Activations generated during computation.</li><li>The Key-Value (KV) cache used by attention.</li><li>Temporary computation buffers.</li><li>Runtime and framework overhead.</li></ul><p>This means a model that theoretically requires 28 GB for its weights may need considerably more GPU memory to run.</p><p><strong>The problem:</strong> Even when a model is capable of running on consumer hardware, its original numerical precision may make it impractical.</p><p>Quantization helps reduce this memory requirement.</p><h3>4. What Is LLM Quantization?</h3><p><strong>Quantization is the process of representing numerical values using fewer bits.</strong></p><p>In an LLM, it commonly means converting model weights from higher-precision formats, such as FP32 or FP16, into lower-precision representations such as INT8 or 4-bit values.</p><p>Think of it like compressing an image.</p><p>A high-quality image stores a large amount of colour information. Reducing its colour depth can make the file smaller, although some visual information may be lost.</p><p>Quantization follows a similar idea: represent model weights more compactly while trying to preserve the model’s useful behaviour.</p><p>For example:</p><ul><li>FP32 uses 32 bits per value.</li><li>FP16 uses 16 bits per value.</li><li>INT8 uses 8 bits per value.</li><li>INT4 uses 4 bits per value.</li></ul><p>Fewer bits generally mean less memory is needed to store the weights.</p><p>However, there is a trade-off: lower precision can introduce numerical errors that affect model quality.</p><h3>5. Understanding Precision: FP32, FP16, INT8, and INT4</h3><p>Before exploring quantization, let’s understand what these formats represent.</p><h3>FP32–32-bit Floating Point</h3><p>FP32 represents numbers using 32 bits, including a sign, exponent, and fraction.</p><p>It offers relatively high numerical precision and is commonly used in training and numerical computation.</p><p>However, it requires 4 bytes per parameter.</p><h3>FP16–16-bit Floating Point</h3><p>FP16 uses 16 bits per value, reducing storage requirements by half compared with FP32.</p><p>It is widely used in deep learning because modern GPUs support efficient lower-precision computation.</p><h3>INT8–8-bit Integer</h3><p>INT8 represents values using 8 bits.</p><p>In quantization, floating-point weights are mapped to a smaller integer range using scaling and, in some methods, a zero-point.</p><p>It requires only 1 byte per value.</p><h3>INT4–4-bit Representation</h3><p>INT4 uses 4 bits per value, meaning each value requires half a byte.</p><p>This can reduce weight storage significantly, but representing a wide range of values with only 16 possible integer codes requires careful scaling and quantization techniques.</p><p><strong>Important:</strong> INT4 quantization does not mean the model becomes a completely different architecture. Its learned weights are represented using fewer bits.</p><h3>6. How Does Quantization Work?</h3><p>Let’s understand the basic process.</p><p>Suppose a model contains the following floating-point weights:</p><pre>weights = [0.12, -0.45, 0.78, 0.31, -0.92]</pre><p>These values can be mapped to a smaller numerical range.</p><p>A simplified symmetric quantization approach uses a scale factor:</p><p>Where:</p><ul><li>(W) represents the original weights.</li><li>(b) represents the number of bits.</li><li>scale determines how floating-point values map to integer values.</li></ul><p>The quantized value is calculated as:</p><p>To approximately reconstruct the original value:</p><p>The reconstructed value may differ slightly from the original. This difference is called <strong>quantization error</strong>.</p><h3>Why Do We Need a Scale Factor?</h3><p>Imagine converting temperatures into integers.</p><p>If we simply round every temperature to the nearest whole number, we lose decimal information.</p><p>A scale factor helps map values into a smaller range while preserving their relative magnitudes.</p><p>Real quantization methods can use more sophisticated approaches, including zero-points, per-channel scaling, group-wise quantization, and calibration.</p><p>The equations above illustrate the basic idea rather than every implementation detail.</p><h3>7. How Much Memory Can 4-Bit and 8-Bit Quantization Save?</h3><p>Let’s use a 7-billion-parameter model as an example.</p><p>For a simple estimate, assume each parameter is stored independently without accounting for metadata or runtime overhead.</p><ul><li>FP32: 4 bytes per parameter.</li><li>FP16: 2 bytes per parameter.</li><li>INT8: 1 byte per parameter.</li><li>INT4: 0.5 bytes per parameter.</li></ul><p>For 7 billion parameters:</p><ul><li>FP32: approximately 28 GB.</li><li>FP16: approximately 14 GB.</li><li>INT8: approximately 7 GB.</li><li>INT4: approximately 3.5 GB.</li></ul><p>The reduction is substantial.</p><p>However, actual GPU memory usage will be higher because quantization metadata, temporary buffers, activations, KV cache, and framework overhead also consume memory.</p><p>This is why a 4-bit model does not necessarily fit into a GPU with exactly 3.5 GB of memory.</p><h3>8. 8-Bit vs 4-Bit Quantization</h3><p>Both approaches reduce memory requirements, but they offer different trade-offs.</p><h3>8-Bit Quantization</h3><p>8-bit quantization provides a balance between memory reduction and numerical precision.</p><p>It is useful when:</p><ul><li>You want to reduce GPU memory consumption.</li><li>You want to retain relatively high model quality.</li><li>Your hardware supports efficient INT8 operations.</li><li>You have enough memory for a larger quantized representation.</li></ul><p>It may be less suitable when memory is extremely limited.</p><h3>4-Bit Quantization</h3><p>4-bit quantization reduces memory requirements further.</p><p>It is particularly useful for running larger LLMs on consumer GPUs or machines with limited memory.</p><p>It is useful when:</p><ul><li>GPU memory is your main constraint.</li><li>You want to experiment with larger models locally.</li><li>You are building cost-conscious inference workflows.</li><li>A small reduction in model quality is acceptable after evaluation.</li></ul><p>However, 4-bit quantization can introduce greater numerical error, and performance depends heavily on the quantization method and hardware.</p><p><strong>Remember:</strong> 4-bit is not automatically faster than 8-bit. Smaller weights reduce memory traffic, but actual speed depends on the GPU, kernels, batch size, and inference framework.</p><h3>9. Weight Quantization vs Activation Quantization</h3><p>Quantization does not always apply to the same parts of a model.</p><p>Two important approaches are:</p><h3>Weight Quantization</h3><p>Weight quantization reduces the precision used to store model parameters.</p><p>For example, a model may store its weights in 4-bit format while performing certain computations using higher-precision values.</p><p>This is called <strong>weight-only quantization</strong>.</p><p>It is particularly useful for LLM inference because model weights can account for a large portion of memory consumption.</p><h3>Activation Quantization</h3><p>Activations are intermediate numerical values produced as data moves through the network.</p><p>Activation quantization reduces the precision of these intermediate values.</p><p>It can reduce memory usage and improve computation efficiency, but it may require more careful calibration because activation distributions can vary depending on the input.</p><h3>When Should You Use Each?</h3><ul><li>Weight quantization: when model weight storage is your primary memory bottleneck.</li><li>Activation quantization: when you want to optimize intermediate computation and memory usage.</li><li>Combined quantization: when the hardware and inference framework support efficient low-precision execution.</li></ul><h3>10. Practical Example: Load a 4-Bit LLM Using Python</h3><p>Now let’s see how quantization works in practice.</p><p>We will use Hugging Face Transformers and BitsAndBytes to load a model in 4-bit precision.</p><h3>Step 1: Install Dependencies</h3><pre>pip install transformers accelerate bitsandbytes torch</pre><p>These libraries provide:</p><ul><li>transformers: Loads pretrained language models.</li><li>accelerate: Helps manage model placement and device execution.</li><li>bitsandbytes: Provides low-bit quantization support.</li><li>torch: Provides the underlying deep learning framework.</li></ul><h3>Step 2: Configure 4-Bit Quantization</h3><pre>import torch<br>from transformers import BitsAndBytesConfig</pre><pre>quantization_config = BitsAndBytesConfig(<br>    load_in_4bit=True,<br>    bnb_4bit_quant_type=&quot;nf4&quot;,<br>    bnb_4bit_compute_dtype=torch.float16,<br>    bnb_4bit_use_double_quant=True<br>)</pre><p>Let’s understand the configuration:</p><ul><li>load_in_4bit=True: Loads model weights in 4-bit format.</li><li>bnb_4bit_quant_type=&quot;nf4&quot;: Uses NormalFloat4, a 4-bit format designed for normally distributed weights.</li><li>bnb_4bit_compute_dtype=torch.float16: Uses FP16 for supported computation.</li><li>bnb_4bit_use_double_quant=True: Quantizes quantization constants to reduce additional memory overhead.</li></ul><p>Notice that <strong>4-bit storage does not mean every computation happens in 4-bit precision</strong>.</p><p>The compute data type can be different from the weight storage format.</p><h3>Step 3: Load the Model</h3><pre>from transformers import AutoModelForCausalLM, AutoTokenizer</pre><pre>model_name = &quot;your-compatible-model-id&quot;</pre><pre>tokenizer = AutoTokenizer.from_pretrained(model_name)</pre><pre>model = AutoModelForCausalLM.from_pretrained(<br>    model_name,<br>    quantization_config=quantization_config,<br>    device_map=&quot;auto&quot;<br>)</pre><p>Replace your-compatible-model-id with the identifier of a compatible pretrained causal language model.</p><p>The quantization configuration tells Transformers to load the model using BitsAndBytes 4-bit quantization.</p><p>device_map=&quot;auto&quot; allows the library to determine how model components should be placed across available devices.</p><p>Hardware, model architecture, and library compatibility requirements still apply.</p><h3>Step 4: Generate a Response</h3><pre>prompt = &quot;Explain LLM quantization in simple terms.&quot;</pre><pre>inputs = tokenizer(prompt, return_tensors=&quot;pt&quot;).to(model.device)</pre><pre>outputs = model.generate(<br>    **inputs,<br>    max_new_tokens=100<br>)</pre><pre>response = tokenizer.decode(<br>    outputs[0],<br>    skip_special_tokens=True<br>)</pre><pre>print(response)</pre><p>This example tokenizes a prompt, passes it to the quantized model, and generates a response.</p><p>The model performs inference using its quantized weights and the configured computation precision.</p><p>You can apply a similar approach for supported 8-bit loading by changing the configuration:</p><pre>quantization_config = BitsAndBytesConfig(<br>    load_in_8bit=True<br>)</pre><p>The exact supported options depend on the model, hardware, and installed library versions.</p><h3>11. Visualizing the Quantization Workflow</h3><p>The following diagram illustrates how a pretrained model can be converted into a lower-precision representation before inference.</p><pre>flowchart TD<br>    A[&quot;Pretrained LLM&quot;] --&gt; B[&quot;Original FP16 / FP32 Weights&quot;]<br>    B --&gt; C[&quot;Quantization Process&quot;]<br>    C --&gt; D[&quot;Choose Precision&quot;]<br>    D --&gt; E[&quot;8-Bit Quantization&quot;]<br>    D --&gt; F[&quot;4-Bit Quantization&quot;]<br>    E --&gt; G[&quot;Reduced Memory Model&quot;]<br>    F --&gt; G<br>    G --&gt; H[&quot;Load Model into GPU&quot;]<br>    H --&gt; I[&quot;Run Inference&quot;]<br>    I --&gt; J[&quot;Generated Response&quot;]</pre><p>The important point is that quantization changes how model weights are represented and stored. It does not require redesigning the entire Transformer architecture.</p><h3>12. What Is QLoRA, and How Is It Related to Quantization?</h3><p>You may encounter another term when exploring quantized LLMs: <strong>QLoRA</strong>.</p><p>QLoRA stands for Quantized Low-Rank Adaptation.</p><p>It combines a quantized base model with LoRA adapters to make fine-tuning more memory-efficient.</p><p>The general idea is:</p><ol><li>Load the pretrained model in 4-bit precision.</li><li>Keep the base model weights frozen.</li><li>Add trainable low-rank adapter layers.</li><li>Train the adapters instead of updating all base model parameters.</li></ol><p>This makes it possible to fine-tune large models using significantly less GPU memory than traditional full fine-tuning.</p><p><strong>Important distinction:</strong> Quantization and QLoRA are not the same thing.</p><p>Quantization reduces the precision used to represent weights. QLoRA uses quantization as part of a parameter-efficient fine-tuning approach.</p><p>Use ordinary quantization when your goal is efficient inference. Consider QLoRA when you want to adapt a model while keeping training memory requirements manageable.</p><h3>13. Real-World Applications</h3><p>LLM quantization is useful across several practical scenarios:</p><ul><li><strong>Local LLM deployment:</strong> Run models on personal computers and consumer GPUs.</li><li><strong>Edge AI:</strong> Deploy language models on devices with limited computing resources.</li><li><strong>Cost optimization:</strong> Reduce memory requirements and potentially lower infrastructure costs.</li><li><strong>Chatbots:</strong> Serve models using more affordable hardware.</li><li><strong>Private AI applications:</strong> Run supported models locally without sending prompts to an external inference provider</li><li><strong>Fine-tuning experiments:</strong> Use quantized base models with approaches such as QLoRA.</li></ul><h3>14. Best Practices</h3><ul><li>Start with 8-bit quantization when preserving model quality is a priority.</li><li>Consider 4-bit quantization when GPU memory is your primary constraint.</li><li>Evaluate model quality on representative prompts and tasks.</li><li>Check compatibility between the model architecture, quantization library, and GPU.</li><li>Monitor GPU memory during inference, not just model loading.</li><li>Measure latency and throughput instead of assuming fewer bits always mean faster inference.</li><li>Test long prompts because the KV cache can become a significant memory bottleneck.</li><li>Keep the original model available for comparison.</li><li>Use established quantization formats and methods rather than applying arbitrary rounding to model weights.</li></ul><h3>15. Common Mistakes</h3><ul><li><strong>Assuming 4-bit means exactly one-eighth of FP32 runtime memory:</strong> Weight storage may approach that ratio, but total memory usage includes additional overhead.</li><li><strong>Assuming quantization always reduces latency:</strong> Performance depends on hardware and optimized kernels.</li><li><strong>Ignoring model quality:</strong> Lower precision can affect reasoning, generation, and task-specific accuracy.</li><li><strong>Confusing quantization with pruning:</strong> Quantization reduces numerical precision; pruning removes selected parameters or connections.</li><li><strong>Confusing quantization with distillation:</strong> Distillation trains a smaller model to imitate a larger one.</li><li><strong>Ignoring the KV cache:</strong> Long-context inference can consume substantial memory even when weights are quantized.</li><li><strong>Assuming 4-bit computation:</strong> A model can store weights in 4-bit format while using FP16 or another supported precision for computation.</li></ul><h3>16. Performance and Memory Considerations</h3><p>Quantization primarily reduces the memory required to store model weights.</p><p>For a model with (N) parameters and (b) bits per parameter, the idealized weight storage is:</p><p>For example, a 7-billion-parameter model using 4-bit weights requires approximately:</p><p>This is an estimate, not a complete GPU memory requirement.</p><p>Actual memory consumption depends on:</p><ul><li>Quantization metadata and scaling factors.</li><li>Model architecture.</li><li>KV cache size.</li><li>Batch size and sequence length.</li><li>Temporary computation buffers.</li><li>GPU and framework overhead.</li></ul><p>In practice, quantization can make a model fit on hardware where its original representation would not. However, the best configuration must be measured on the target system.</p><h3>17. Summary: Key Takeaways</h3><p>LLM quantization makes large language models more practical by reducing the number of bits used to represent their weights.</p><p>The key ideas to remember:</p><ul><li><strong>FP32:</strong> High-precision representation requiring 4 bytes per value.</li><li><strong>FP16:</strong> Uses 2 bytes per value and is widely used for efficient deep learning.</li><li><strong>INT8:</strong> Reduces weight storage to approximately 1 byte per value.</li><li><strong>INT4:</strong> Reduces weight storage to approximately half a byte per value.</li><li><strong>Weight quantization:</strong> Reduces the memory required for model parameters.</li><li><strong>Activation quantization:</strong> Reduces the precision of intermediate values.</li><li><strong>QLoRA:</strong> Combines a quantized base model with trainable LoRA adapters for memory-efficient fine-tuning.</li></ul><p>Ultimately, quantization is about finding the right balance between <strong>model quality, memory consumption, and inference performance</strong>.</p><p>A model does not always need full precision to be useful. With the right quantization method and proper evaluation, developers can run powerful LLMs on more accessible hardware.</p><p>And that is what makes quantization one of the most important techniques for practical LLM deployment.<strong>LLM Quantization Explained: How 4-Bit and 8-Bit Models Reduce Memory Requirements</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UENPmoTCjSPAMRRzPlIt0Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=653de6ee7013" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Function Calling in LLMs: Build Your First AI Tool-Calling Workflow]]></title>
            <link>https://medium.com/@s.aditya1317/function-calling-in-llms-build-your-first-ai-tool-calling-workflow-e6f6c446665e?source=rss-2d1520186482------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6f6c446665e</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Aditya S]]></dc:creator>
            <pubDate>Sat, 14 Nov 2026 15:47:20 GMT</pubDate>
            <atom:updated>2026-11-14T15:47:20.474Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Imagine asking an AI assistant:</p><p><em>“What is the weather in Mumbai right now?”</em></p><p>A traditional LLM can generate a response based on patterns learned during training. But it cannot automatically access live weather information unless your application connects it to an external data source.</p><p>Now imagine asking:</p><p><em>“Calculate the total price of 5 products costing ₹499 each, including 18% GST.”</em></p><p>The model can attempt the calculation itself, but what if you want it to use a reliable Python function instead?</p><p>This is where <strong>Function Calling</strong> becomes important.</p><p>Function calling allows an LLM to request the execution of external functions or tools. Your application executes the requested function, returns its result to the model, and lets the model generate a final response.</p><p>It is one of the fundamental building blocks behind AI assistants, agents, and tool-enabled applications.</p><p>In this tutorial, we’ll build a practical function-calling workflow using Python and the OpenAI API.</p><h3>What You’ll Learn</h3><ul><li>What function calling is and why it matters.</li><li>How LLMs decide when to request a function.</li><li>The difference between function calling and normal text generation.</li><li>How to define tools using JSON Schema.</li><li>How to execute tool calls using Python.</li><li>How to handle multiple tool calls and errors.</li><li>How function calling fits into AI agent architectures.</li></ul><h3>Prerequisites</h3><ul><li>Basic Python knowledge.</li><li>Familiarity with functions and dictionaries.</li><li>Basic understanding of LLMs.</li><li>An OpenAI API key.</li></ul><h3>1. The Problem: Why Do LLMs Need Tools?</h3><p>An LLM is good at understanding language, generating text, summarizing information, and following instructions.</p><p>However, it does not automatically have access to every external system.</p><p>Consider these requests:</p><ul><li>Check the latest stock price.</li><li>Retrieve a customer’s order status.</li><li>Calculate a complex invoice.</li><li>Search a company’s internal database.</li><li>Send an email to a customer.</li></ul><p>These tasks require external capabilities.</p><p>One approach is to write separate application logic for every possible user request. But this becomes difficult as the number of tasks increases.</p><p>Function calling provides a structured way for an LLM to request these operations.</p><p>Instead of generating an answer directly, the model can identify the appropriate function, provide its arguments, and ask the application to execute it.</p><p>The application remains responsible for actually performing the operation.</p><h3>2. What Is Function Calling?</h3><p><strong>Function calling is a mechanism that allows an LLM to request the execution of predefined functions through a structured interface.</strong></p><p>Think of it like an assistant working with a team.</p><p>You ask the assistant to calculate an invoice. Instead of calculating everything manually, the assistant identifies that a calculator is needed, provides the required numbers, and asks the calculator to perform the operation.</p><p>The calculator returns the result, and the assistant explains it to you.</p><p>An LLM works similarly.</p><h3>How Does It Work?</h3><p>A typical function-calling workflow has five steps:</p><ol><li>The user sends a request.</li><li>The LLM identifies whether an available function can help.</li><li>The LLM generates a structured tool-call request.</li><li>Your application executes the corresponding function.</li><li>The result is sent back to the LLM, which generates the final response.</li></ol><p>An important distinction:</p><p><strong>The LLM does not directly execute your Python function. It requests a tool call. Your application executes it.</strong></p><p>This separation gives developers control over permissions, validation, and execution.</p><h3>3. Understanding the Main Components</h3><p>Before writing code, let’s understand three important components.</p><h3>Function Definition</h3><p>A function definition describes what a tool does, its name, and the parameters it accepts.</p><p>For example, a calculator function might accept two numbers and an operation.</p><h3>Tool Schema</h3><p>A tool schema describes the function’s expected arguments using a structured format, commonly JSON Schema.</p><p>It tells the model:</p><ul><li>Which function is available.</li><li>What the function does.</li><li>Which arguments are required.</li><li>What types of values those arguments should contain.</li></ul><h3>Tool Execution</h3><p>Once the model requests a function call, the application reads the requested function name and arguments, validates them, and executes the corresponding Python function.</p><p>The result is then returned to the model.</p><h3>4. Step-by-Step Implementation</h3><p>Let’s build a simple calculator assistant.</p><p>Our application will support:</p><ul><li>Addition.</li><li>Subtraction.</li><li>Multiplication.</li><li>Division.</li></ul><p>The user will communicate naturally, while the LLM decides when to use the calculator.</p><h3>Step 1: Install Dependencies</h3><pre>pip install openai python-dotenv</pre><p>Create a .env file:</p><pre>OPENAI_API_KEY=your_api_key_here</pre><p>Initialize the client:</p><pre>import os<br>from dotenv import load_dotenv<br>from openai import OpenAI</pre><pre>load_dotenv()</pre><pre>client = OpenAI(<br>    api_key=os.getenv(&quot;OPENAI_API_KEY&quot;)<br>)</pre><p><strong>Explanation:</strong></p><p>We initialize the OpenAI client using an API key stored in an environment variable.</p><p>Keeping credentials outside your source code reduces the risk of accidentally exposing them.</p><h3>Step 2: Create the Python Functions</h3><p>First, define the actual functions that will perform calculations.</p><pre>def calculate(a, b, operation):</pre><pre>    if operation == &quot;add&quot;:<br>        return a + b</pre><pre>    elif operation == &quot;subtract&quot;:<br>        return a - b</pre><pre>    elif operation == &quot;multiply&quot;:<br>        return a * b</pre><pre>    elif operation == &quot;divide&quot;:<br>        if b == 0:<br>            raise ValueError(&quot;Cannot divide by zero&quot;)</pre><pre>        return a / b</pre><pre>    else:<br>        raise ValueError(&quot;Unsupported operation&quot;)</pre><p><strong>Explanation:</strong></p><p>This function accepts two numbers and an operation.</p><p>It performs the requested calculation and returns the result.</p><p>Notice that we explicitly handle division by zero and unsupported operations. Tool execution should not assume that every request is valid.</p><h3>Step 3: Define the Tool Schema</h3><p>Now we need to tell the LLM that this calculator function is available.</p><pre>tools = [<br>    {<br>        &quot;type&quot;: &quot;function&quot;,<br>        &quot;function&quot;: {<br>            &quot;name&quot;: &quot;calculate&quot;,<br>            &quot;description&quot;: (<br>                &quot;Perform basic mathematical calculations&quot;<br>            ),<br>            &quot;parameters&quot;: {<br>                &quot;type&quot;: &quot;object&quot;,<br>                &quot;properties&quot;: {<br>                    &quot;a&quot;: {<br>                        &quot;type&quot;: &quot;number&quot;,<br>                        &quot;description&quot;: &quot;First number&quot;<br>                    },<br>                    &quot;b&quot;: {<br>                        &quot;type&quot;: &quot;number&quot;,<br>                        &quot;description&quot;: &quot;Second number&quot;<br>                    },<br>                    &quot;operation&quot;: {<br>                        &quot;type&quot;: &quot;string&quot;,<br>                        &quot;enum&quot;: [<br>                            &quot;add&quot;,<br>                            &quot;subtract&quot;,<br>                            &quot;multiply&quot;,<br>                            &quot;divide&quot;<br>                        ]<br>                    }<br>                },<br>                &quot;required&quot;: [<br>                    &quot;a&quot;,<br>                    &quot;b&quot;,<br>                    &quot;operation&quot;<br>                ],<br>                &quot;additionalProperties&quot;: False<br>            },<br>            &quot;strict&quot;: True<br>        }<br>    }<br>]</pre><p><strong>Explanation:</strong></p><p>This schema describes the function without executing it.</p><ul><li>name identifies the function.</li><li>description explains its purpose.</li><li>properties define its arguments.</li><li>required specifies mandatory arguments.</li><li>enum restricts the operation to supported values.</li><li>strict enables strict schema adherence for supported function definitions.</li></ul><p>The schema helps the model generate arguments in the expected structure.</p><p>It does not replace application-side validation or authorization.</p><h3>Step 4: Send the User Request to the LLM</h3><p>Now let’s send a request using the Chat Completions API.</p><pre>messages = [<br>    {<br>        &quot;role&quot;: &quot;user&quot;,<br>        &quot;content&quot;: (<br>            &quot;Calculate 250 multiplied by 4&quot;<br>        )<br>    }<br>]</pre><pre>response = client.chat.completions.create(<br>    model=&quot;gpt-4.1-mini&quot;,<br>    messages=messages,<br>    tools=tools,<br>    tool_choice=&quot;auto&quot;<br>)</pre><pre>message = response.choices[0].message</pre><p><strong>Explanation:</strong></p><p>The model receives the user request and the available tool definitions.</p><p>tool_choice=&quot;auto&quot; allows the model to decide whether a tool is necessary.</p><p>For our calculation request, it can request the calculate function instead of attempting to generate the result directly.</p><p>The model identifier is an example; use a model that supports function calling and is available to your account.</p><h3>Step 5: Execute the Requested Function</h3><p>Now inspect the model response.</p><pre>import json</pre><pre>if message.tool_calls:</pre><pre>    for tool_call in message.tool_calls:</pre><pre>        function_name = tool_call.function.name</pre><pre>        arguments = json.loads(<br>            tool_call.function.arguments<br>        )</pre><pre>        if function_name == &quot;calculate&quot;:</pre><pre>            result = calculate(**arguments)</pre><pre>            print(&quot;Result:&quot;, result)</pre><p><strong>Explanation:</strong></p><p>The model returns a tool call containing:</p><ul><li>The requested function name.</li><li>Its arguments in JSON format.</li><li>A unique tool-call ID.</li></ul><p>Our application parses the arguments and executes the corresponding Python function.</p><p>For the example request, the model may generate arguments equivalent to:</p><pre>{<br>    &quot;a&quot;: 250,<br>    &quot;b&quot;: 4,<br>    &quot;operation&quot;: &quot;multiply&quot;<br>}</pre><p>The Python function calculates the result and returns 1000.</p><p>Notice that we explicitly check the function name before execution. Never execute arbitrary function names supplied by a model.</p><h3>Step 6: Send the Tool Result Back to the LLM</h3><p>Executing the function is only part of the workflow.</p><p>The model needs to receive the result so it can produce a natural-language response.</p><pre>messages.append(message)</pre><pre>for tool_call in message.tool_calls:</pre><pre>    arguments = json.loads(<br>        tool_call.function.arguments<br>    )</pre><pre>    result = calculate(**arguments)</pre><pre>    messages.append({<br>        &quot;role&quot;: &quot;tool&quot;,<br>        &quot;tool_call_id&quot;: tool_call.id,<br>        &quot;content&quot;: str(result)<br>    })</pre><pre>final_response = client.chat.completions.create(<br>    model=&quot;gpt-4.1-mini&quot;,<br>    messages=messages<br>)</pre><pre>print(<br>    final_response.choices[0].message.content<br>)</pre><p><strong>Explanation:</strong></p><p>We add the assistant’s tool-call message to the conversation, followed by the tool’s result.</p><p>The second API request allows the LLM to use that result when generating its final answer.</p><p>The response might be:</p><p><em>250 multiplied by 4 is 1,000.</em></p><p>This completes the function-calling cycle.</p><h3>5. Understanding the Complete Workflow</h3><pre>flowchart TD<br>    A[User Request] --&gt; B[LLM Receives Request and Tool Schema]<br>    B --&gt; C{Tool Required?}</pre><pre>    C --&gt;|No| D[Generate Direct Response]<br>    C --&gt;|Yes| E[Generate Structured Tool Call]</pre><pre>    E --&gt; F[Application Validates Arguments]<br>    F --&gt; G[Execute Python Function]<br>    G --&gt; H[Return Tool Result to LLM]<br>    H --&gt; I[Generate Final Response]</pre><pre>    D --&gt; J[User Receives Answer]<br>    I --&gt; J</pre><p>The important idea is that the LLM decides what operation may be useful, while the application controls its execution.</p><h3>6. Handling Multiple Tool Calls</h3><p>A user request may require more than one operation.</p><p>For example:</p><p><em>“Calculate 100 multiplied by 5 and then add 200.”</em></p><p>A model may request multiple tool calls in one response.</p><p>Your application should therefore iterate through all returned tool calls, execute each supported function, and send every result back using its corresponding tool_call_id.</p><p>Do not assume that every model response contains exactly one tool call.</p><p>Also, if operations depend on one another, execute them in the correct order rather than assuming that all requested tools can run independently.</p><h3>7. Function Calling vs. Tool Calling</h3><p>You may encounter both terms while working with LLM frameworks.</p><p><strong>Function calling</strong> traditionally refers to asking the model to request a predefined function with structured arguments.</p><p><strong>Tool calling</strong> is a broader term that includes functions and other external capabilities such as web search, database access, code execution, and application integrations.</p><p>In modern LLM development, these terms are often used interchangeably.</p><h3>8. Real-World Applications</h3><p>Function calling is used in many AI-powered applications:</p><ul><li><strong>AI assistants:</strong> Retrieve information, perform calculations, and interact with external services.</li><li><strong>Customer support:</strong> Check order status, retrieve account information, and create support tickets.</li><li><strong>RAG systems:</strong> Search vector databases and retrieve relevant documents.</li><li><strong>AI agents:</strong> Call multiple tools to complete multi-step tasks.</li><li><strong>Business automation:</strong> Create records, schedule tasks, and interact with business applications.</li></ul><h3>9. Best Practices</h3><ul><li>Define clear function names and descriptions.</li><li>Keep tool schemas simple and specific.</li><li>Validate arguments before execution.</li><li>Restrict which functions the model can call.</li><li>Handle invalid inputs and execution failures.</li><li>Apply authentication and authorization checks.</li><li>Add timeouts to external operations.</li><li>Log tool calls without exposing sensitive information.</li><li>Require user confirmation for sensitive or irreversible actions.</li><li>Return structured error information when a tool fails.</li></ul><p>Remember: a valid tool call does not automatically mean the requested action is safe or authorized.</p><h3>10. Common Mistakes</h3><ul><li>Assuming the LLM executes Python functions directly.</li><li>Forgetting to send tool results back to the model.</li><li>Ignoring tool-call IDs.</li><li>Trusting model-generated arguments without validation.</li><li>Allowing unrestricted function execution.</li><li>Failing to handle multiple tool calls.</li><li>Ignoring API errors and timeouts.</li><li>Exposing API keys or sensitive data in logs.</li></ul><h3>11. Performance and Cost Considerations</h3><p>Function calling introduces additional steps compared with a simple LLM request.</p><p>A typical workflow may require:</p><ol><li>One model request to select a tool.</li><li>One external function execution.</li><li>Another model request to generate the final answer.</li></ol><p>Each model request can add latency and token usage.</p><p>The actual cost depends on the model, prompt size, tool definitions, and number of interactions.</p><p>For production systems, avoid unnecessary tool calls, keep tool descriptions concise, set execution timeouts, and cache results when appropriate.</p><h3>12. Summary: Key Takeaways</h3><p>Function calling allows LLMs to interact with external systems through structured tool requests.</p><p>Remember:</p><ul><li>The LLM identifies when a tool may be useful.</li><li>The tool schema describes the available function and its arguments.</li><li>Your application executes the requested function.</li><li>The tool result is returned to the model.</li><li>The model uses that result to generate a final response.</li></ul><p>The most important distinction is that <strong>an LLM can decide which tool to request, but your application remains responsible for executing and controlling that tool.</strong></p><p>This is the foundation of tool-enabled AI applications.</p><p>Once you understand this workflow, you can extend the same architecture to web search, databases, APIs, RAG pipelines, and multi-agent systems.</p><p><strong>Function calling is one of the steps that transforms an LLM from a text-generation system into an application that can interact with the real world.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H97T-jW2i6Vr39TWBlQLbg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6f6c446665e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why LLMs Forget Previous Instructions in Long Conversations: Understanding Context Degradation]]></title>
            <link>https://medium.com/@s.aditya1317/why-llms-forget-previous-instructions-in-long-conversations-understanding-context-degradation-2df20b259bd0?source=rss-2d1520186482------2</link>
            <guid isPermaLink="false">https://medium.com/p/2df20b259bd0</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Aditya S]]></dc:creator>
            <pubDate>Fri, 13 Nov 2026 07:06:38 GMT</pubDate>
            <atom:updated>2026-11-13T07:06:38.968Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Have you ever spent several messages explaining exactly how you want an AI assistant to respond, only to find that it starts ignoring those instructions later in the conversation?</p><p>You might ask it to use simple English, avoid unnecessary explanations, follow a particular format, or remember specific project requirements.</p><p>Initially, everything works perfectly. But after a long conversation, the model starts repeating information, missing earlier constraints, or producing responses that contradict your original instructions.</p><p>Does the model actually forget?</p><p>Not exactly.</p><p>The problem is often related to <strong>context degradation</strong>: as conversations grow, important information can become harder for an LLM to use reliably.</p><p>Understanding why this happens is important when building chatbots, AI agents, RAG applications, and long-running AI workflows.</p><p>Let’s explore what happens inside an LLM’s context, why earlier instructions become less effective, and how developers can design systems to handle long conversations more reliably.</p><h3>What You’ll Learn</h3><ul><li>What context windows are and how they work.</li><li>Why LLMs struggle with long conversations.</li><li>The difference between context limits and context degradation.</li><li>How token usage affects conversation history.</li><li>What attention dilution and the “Lost in the Middle” problem mean.</li><li>How to manage long conversations using practical techniques.</li><li>How to design more reliable conversational AI applications.</li></ul><h3>Prerequisites</h3><ul><li>Basic understanding of Large Language Models.</li><li>Familiarity with prompts and chat messages.</li><li>Basic Python knowledge.</li><li>Understanding of tokens and APIs is helpful.</li></ul><h3>1. The Problem: Why Does an LLM Stop Following Instructions?</h3><p>Imagine starting a conversation with these instructions:</p><pre>You are my technical learning assistant.</pre><pre>Follow these rules:<br>- Explain concepts in simple English.<br>- Do not provide code unless I request it.<br>- Keep answers within 2–3 lines.<br>- Avoid unnecessary theory.</pre><p>Initially, the model follows every instruction.</p><p>Now imagine continuing the conversation for another 100 messages. You discuss Python, machine learning, debugging, databases, and several unrelated topics.</p><p>Eventually, you ask a simple question.</p><p>The model responds with a long explanation and includes code you never requested.</p><p>Why?</p><p>The original instructions may still be present in the conversation history, but the model may not use them as effectively as expected.</p><p>Several factors can contribute:</p><ul><li>The conversation consumes more tokens.</li><li>Important instructions compete with other contextual information.</li><li>Earlier messages may be removed or summarized.</li><li>Relevant information may be buried inside a large context.</li><li>The model may prioritize more recent or prominent information.</li></ul><p>This is not necessarily a failure of intelligence. It is partly a consequence of how LLMs process context.</p><h3>2. Understanding the Context Window</h3><p>Before discussing context degradation, we need to understand the context window.</p><p><strong>A context window is the maximum amount of information a model can process in a single interaction, measured in tokens.</strong></p><p>A token is a small unit of text. It can represent a complete word, part of a word, punctuation, or other text elements.</p><p>For example:</p><pre>Artificial Intelligence is changing software development.</pre><p>The sentence is converted into tokens before being processed by the model.</p><p>The context window can contain:</p><ul><li>System instructions.</li><li>Developer instructions.</li><li>Conversation history.</li><li>User messages.</li><li>Tool results.</li><li>Retrieved documents.</li><li>The model’s generated response.</li></ul><p>Think of the context window as a workspace.</p><p>If the workspace has limited capacity, adding more information means there is less room for other information.</p><h3>Why Does It Matter?</h3><p>Suppose a model supports a context window of 32,000 tokens.</p><p>Your conversation gradually consumes that capacity.</p><p>Eventually, the application must manage the available context. Depending on its implementation, it might remove older messages, summarize previous interactions, or reject requests that exceed the limit.</p><p>One important distinction:</p><p><strong>A context window limit and context degradation are not the same thing.</strong></p><p>A model can struggle to use information effectively even when the conversation is still within its context limit.</p><h3>3. Why Does Context Degradation Happen?</h3><p>There are several reasons why long conversations can reduce response quality.</p><h3>3.1 Context Window Consumption</h3><p>Every message contributes to the conversation context.</p><p>Consider a chatbot that stores the entire conversation and sends it to the model with every new request.</p><p>As the conversation grows, the number of tokens increases.</p><p>Eventually, the application may reach the model’s context limit.</p><p>When this happens, the system must decide what information to preserve.</p><p>Some implementations remove older messages. Others summarize history or reject requests that exceed the available capacity.</p><p>If an important instruction is removed, the model can no longer directly access it.</p><h3>3.2 Attention Dilution</h3><p>Transformers use an attention mechanism to process relationships between tokens.</p><p>Attention helps a model determine which parts of the available context are relevant when generating the next token.</p><p>However, providing more context does not guarantee that every important detail will receive equal attention.</p><p>Imagine searching for one important sentence inside a 100-page document. The information may be present, but finding and using it correctly becomes more difficult.</p><p>A similar challenge can occur in long LLM contexts.</p><p>When conversations contain large amounts of unrelated information, important instructions can become less effective.</p><h3>3.3 The Lost in the Middle Problem</h3><p>Research has demonstrated that some language models perform less reliably when relevant information appears in the middle of long input contexts.</p><p>This is commonly known as the <strong>Lost in the Middle</strong> problem.</p><p>For example, imagine providing a model with:</p><ul><li>Important instructions at the beginning.</li><li>Hundreds of unrelated messages in the middle.</li><li>A new question at the end.</li></ul><p>The model may use information near the beginning and end more effectively than information buried in the middle.</p><p>This behavior varies across models and tasks, but it highlights an important lesson:</p><p><strong>A large context window does not guarantee that a model will use every piece of information equally well.</strong></p><h3>3.4 Conflicting Instructions</h3><p>Long conversations can introduce contradictory instructions.</p><p>For example:</p><p>Earlier instruction:</p><pre>Always answer in 2–3 lines.</pre><p>Later instruction:</p><pre>Explain this topic in detail with examples.</pre><p>The model now has two different requirements.</p><p>Depending on instruction hierarchy and the exact wording, the later request may intentionally override the earlier preference.</p><p>This is not necessarily context degradation. It can simply be an instruction conflict.</p><p>Developers should distinguish between instructions that remain permanent and instructions that apply only to a particular task.</p><h3>3.5 Information Is Not the Same as Memory</h3><p>Another common misconception is that an LLM automatically remembers everything discussed in previous conversations.</p><p>It does not.</p><p>A model processes the context supplied to it for a particular request. Persistent memory is an additional application-level capability that stores or retrieves selected information across interactions.</p><p>If an application does not preserve an important preference or retrieve it later, the model cannot reliably use it.</p><h3>4. How Developers Can Solve Context Degradation</h3><p>There is no single solution that works for every application.</p><p>Instead, developers should manage context deliberately.</p><p>Let’s explore some practical approaches.</p><h3>Approach 1: Keep Important Instructions Separate</h3><p>System-level and developer-level instructions should be maintained separately from ordinary conversation history.</p><p>This makes it easier to preserve important application rules even when older user messages are removed.</p><p>For example:</p><pre>SYSTEM_PROMPT = &quot;&quot;&quot;<br>You are a technical learning assistant.</pre><pre>Rules:<br>- Use simple English.<br>- Keep explanations concise.<br>- Avoid unnecessary theory.<br>- Provide code only when requested.<br>&quot;&quot;&quot;</pre><pre>messages = [<br>    {<br>        &quot;role&quot;: &quot;system&quot;,<br>        &quot;content&quot;: SYSTEM_PROMPT<br>    },<br>    {<br>        &quot;role&quot;: &quot;user&quot;,<br>        &quot;content&quot;: &quot;What is an embedding?&quot;<br>    }<br>]</pre><p><strong>Explanation:</strong></p><p>The system instruction is stored separately from the user’s conversation messages.</p><p>When managing conversation history, the application can preserve this instruction rather than accidentally deleting it while trimming older messages.</p><p>The actual instruction hierarchy depends on the model API being used. Application developers should also avoid allowing untrusted user content to override trusted instructions.</p><h3>Approach 2: Limit Conversation History</h3><p>Instead of sending every previous message, retain only the most relevant messages.</p><p>For example, an application can preserve the system prompt and the most recent conversation exchanges.</p><pre>def build_messages(<br>    system_prompt,<br>    history,<br>    current_question,<br>    max_messages=6<br>):</pre><pre>    recent_history = history[-max_messages:]</pre><pre>    messages = [<br>        {<br>            &quot;role&quot;: &quot;system&quot;,<br>            &quot;content&quot;: system_prompt<br>        }<br>    ]</pre><pre>    messages.extend(recent_history)</pre><pre>    messages.append({<br>        &quot;role&quot;: &quot;user&quot;,<br>        &quot;content&quot;: current_question<br>    })</pre><pre>    return messages</pre><p><strong>Explanation:</strong></p><p>This function keeps the system instructions, the latest six history messages, and the current question.</p><p>It prevents conversation history from growing indefinitely.</p><p>However, message count is only a rough approximation of context size. Six messages could contain thousands of tokens.</p><p>For production applications, use token-aware context management rather than relying only on message count.</p><h3>Approach 3: Summarize Older Conversations</h3><p>Sometimes, removing older messages is not enough.</p><p>You may need to preserve important information from previous interactions.</p><p>This is where conversation summarization becomes useful.</p><p>Instead of keeping the entire conversation, create a compact summary containing:</p><ul><li>Important user preferences.</li><li>Project requirements.</li><li>Decisions already made.</li><li>Relevant technical details.</li><li>Unresolved tasks.</li></ul><p>For example:</p><pre>Conversation Summary:</pre><pre>The user is building a RAG application.</pre><pre>Technology:<br>- Python<br>- LangChain<br>- FastAPI<br>- Vector database</pre><pre>Requirements:<br>- Use simple explanations.<br>- Avoid unnecessary code.<br>- Preserve the existing architecture.</pre><pre>Current Progress:<br>- Document ingestion is complete.<br>- Retrieval evaluation is pending.</pre><p><strong>Explanation:</strong></p><p>The summary acts as compressed conversation history.</p><p>The application can include it in future requests without sending every previous message.</p><p>However, summarization is lossy. Important details may be omitted or distorted.</p><p>For critical information, preserve structured records or retrieve the original source instead of relying entirely on a generated summary.</p><h3>Approach 4: Use RAG for Long-Term Knowledge</h3><p>What if the conversation contains hundreds of documents, technical decisions, or project notes?</p><p>Sending everything to the model is inefficient.</p><p>Instead, store the information externally and retrieve relevant content when needed.</p><p>This is where Retrieval-Augmented Generation becomes useful.</p><p>A typical workflow:</p><ol><li>Store documents or conversation summaries.</li><li>Convert them into embeddings.</li><li>Index them in a retrieval system.</li><li>Search for relevant information when a new question arrives.</li><li>Add the retrieved information to the model’s context.</li></ol><p>RAG helps provide relevant information without loading the entire knowledge base into every request.</p><p>However, retrieval quality matters. If the correct information is not retrieved, the model cannot reliably use it.</p><h3>5. Visualizing Context Management</h3><pre>flowchart TD<br>    A[New User Message] --&gt; B[Load System Instructions]<br>    B --&gt; C[Load Recent Conversation]<br>    C --&gt; D{Context Too Large?}</pre><pre>    D --&gt;|No| F[Build Model Context]<br>    D --&gt;|Yes| E[Summarize or Retrieve Relevant History]</pre><pre>    E --&gt; F<br>    F --&gt; G[Send Request to LLM]<br>    G --&gt; H[Generate Response]<br>    H --&gt; I[Update Conversation History]</pre><p>The objective is to build a controlled context rather than blindly sending the entire conversation.</p><h3>6. Real-World Applications</h3><p>Context management becomes especially important in applications that maintain long-running interactions.</p><p><strong>AI Coding Assistants</strong></p><p>A coding assistant needs to preserve project architecture, coding conventions, and previous decisions without sending every debugging message indefinitely.</p><p><strong>Customer Support Chatbots</strong></p><p>A chatbot should retain relevant customer details and conversation history while avoiding unnecessary information from unrelated interactions.</p><p><strong>AI Agents</strong></p><p>Agents may execute multiple steps, call tools, and accumulate large amounts of intermediate information. Managing this state prevents context from growing uncontrollably.</p><p><strong>RAG Applications</strong></p><p>A RAG system needs to retrieve relevant information for each question instead of repeatedly inserting an entire document collection into the prompt.</p><h3>7. Best Practices for Managing Long Contexts</h3><ul><li>Keep permanent instructions separate from conversation history.</li><li>Use token-aware context budgeting.</li><li>Preserve important decisions and user preferences.</li><li>Summarize older conversations carefully.</li><li>Retrieve external knowledge only when relevant.</li><li>Remove redundant tool outputs and repeated messages.</li><li>Track instruction conflicts explicitly.</li><li>Evaluate model behavior with long-context test cases.</li><li>Preserve original records when summaries are insufficient.</li><li>Monitor token usage, latency, and response quality.</li></ul><h3>8. Common Mistakes</h3><ul><li>Assuming a larger context window eliminates context degradation.</li><li>Sending the entire conversation with every request.</li><li>Removing older messages without preserving important information.</li><li>Treating summaries as perfect replacements for original conversations.</li><li>Storing every interaction as long-term memory.</li><li>Mixing permanent instructions with temporary task requirements.</li><li>Assuming RAG automatically solves every memory problem.</li><li>Ignoring token usage and context limits.</li></ul><h3>9. Performance Considerations</h3><p>Longer contexts can increase input-token usage, processing cost, and latency.</p><p>The exact impact depends on the model architecture, provider, attention implementation, caching, and API configuration.</p><p>Context management can reduce unnecessary processing by sending only relevant information.</p><p>However, aggressive trimming can remove useful details and reduce answer quality.</p><p>The goal is not to create the shortest possible context. It is to create the <strong>smallest useful context that preserves everything required for the current task</strong>.</p><h3>10. Summary: Key Takeaways</h3><p>LLMs do not behave like humans with unlimited conversational memory.</p><p>They process the context supplied to them, and their ability to use that context can be affected by length, relevance, conflicting instructions, and how information is positioned.</p><p>Remember:</p><ul><li><strong>Context windows</strong> define how much information a model can process in one request.</li><li><strong>Context degradation</strong> describes declining effectiveness in using information as context grows or becomes less focused.</li><li><strong>Attention mechanisms</strong> help models process relationships between tokens, but do not guarantee equal use of every detail.</li><li><strong>Summarization</strong> compresses older conversations into useful information.</li><li><strong>RAG</strong> retrieves relevant external knowledge when needed.</li><li><strong>Context management</strong> helps preserve important information while controlling token usage.</li></ul><p>The biggest lesson is simple:</p><p><strong>Don’t expect an LLM to remember everything. Design your application to preserve, organize, and retrieve the information that matters.</strong></p><p>That is how you move from a basic chatbot to a reliable conversational AI system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8y_b0HMp-Jl38X1WApQelA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2df20b259bd0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-Tuning vs RAG vs Prompt Engineering: Which Approach Should You Choose?]]></title>
            <link>https://medium.com/@s.aditya1317/fine-tuning-vs-rag-vs-prompt-engineering-which-approach-should-you-choose-39102acbec77?source=rss-2d1520186482------2</link>
            <guid isPermaLink="false">https://medium.com/p/39102acbec77</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Aditya S]]></dc:creator>
            <pubDate>Thu, 12 Nov 2026 09:18:04 GMT</pubDate>
            <atom:updated>2026-11-12T09:18:04.780Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>You’ve built an application using an LLM. It generates good responses, understands instructions, and handles basic questions.</p><p>But as your application grows, you encounter new requirements:</p><ul><li>You want the model to answer questions using your company’s private documents.</li><li>You want it to follow a consistent response format.</li><li>You want it to behave according to your organization’s specific requirements.</li><li>You want to improve its performance on specialized tasks.</li></ul><p>At this point, you’ll likely come across three approaches: <strong>Prompt Engineering, Retrieval-Augmented Generation (RAG), and Fine-Tuning</strong>.</p><p>All three can improve an LLM-powered application, but they solve different problems.</p><p>Choosing the wrong approach can increase development costs, introduce unnecessary complexity, and still fail to deliver the expected results.</p><p>In this article, we’ll understand how each approach works, compare their strengths and limitations, and learn how to choose the right one for a real-world AI application.</p><h3>What You’ll Learn</h3><ul><li>What Prompt Engineering, RAG, and Fine-Tuning mean.</li><li>How each approach improves an LLM application.</li><li>The differences between their architectures.</li><li>Practical examples of each approach.</li><li>When to use one approach over another.</li><li>How to combine all three in production systems.</li></ul><h3>Prerequisites</h3><ul><li>Basic understanding of Large Language Models.</li><li>Familiarity with Python.</li><li>Basic understanding of API calls.</li><li>Basic knowledge of embeddings and vector databases is helpful.</li></ul><h3>1. Understanding the Problem</h3><p>An LLM is trained on large amounts of data and learns patterns that help it generate human-like responses.</p><p>However, a general-purpose model may not automatically know your company’s internal policies, follow your preferred output format, or perform consistently on a specialized task.</p><p>For example, imagine building an AI assistant for a healthcare organization.</p><p>You want it to:</p><ul><li>Answer questions using internal medical documentation.</li><li>Follow a specific response structure.</li><li>Understand domain-specific terminology.</li><li>Provide information based on the latest approved documents.</li></ul><p>A single prompt may not solve all these requirements.</p><p>This is where Prompt Engineering, RAG, and Fine-Tuning become useful.</p><p>The important thing to understand is that these techniques improve different parts of the application.</p><h3>2. What Is Prompt Engineering?</h3><p><strong>Prompt Engineering is the process of designing and refining instructions given to an LLM to guide its behavior and output.</strong></p><p>Think of it like giving an employee clear instructions.</p><p>If you ask someone to write a report, the result may vary. But if you specify the audience, format, tone, and requirements, the result becomes more consistent.</p><p>Prompt Engineering works similarly.</p><h3>How Does It Work?</h3><p>The application provides instructions along with the user’s question.</p><p>For example:</p><pre>prompt = &quot;&quot;&quot;<br>You are a technical assistant.</pre><pre>Explain the following concept:<br>{question}</pre><pre>Instructions:<br>- Use simple English.<br>- Provide a practical example.<br>- Keep the explanation concise.<br>- Include a summary at the end.<br>&quot;&quot;&quot;</pre><p>The LLM uses these instructions when generating its response.</p><p>You can guide:</p><ul><li>Response format.</li><li>Tone and writing style.</li><li>Task-specific behavior.</li><li>Output constraints.</li><li>Reasoning instructions and task decomposition.</li></ul><h3>When Should You Use It?</h3><p>Use Prompt Engineering when:</p><ul><li>You need to control response structure.</li><li>You want to define an assistant’s role.</li><li>You need to provide task-specific instructions.</li><li>You are building prototypes or simple AI applications.</li><li>The model already has the knowledge needed to perform the task.</li></ul><h3>When Should You Avoid Relying on It Alone?</h3><p>Prompt Engineering is not a reliable way to provide large collections of private information or permanently teach a model new knowledge.</p><p>You can ask a model to answer using your company’s policies, but if those policies are not included in its available context, the instruction alone cannot provide them.</p><p><strong>Common mistake:</strong> Assuming that a longer, more detailed prompt automatically produces a more accurate response.</p><p>Prompt quality matters, but so do the model’s capabilities, available context, and input data.</p><h3>3. What Is Retrieval-Augmented Generation (RAG)?</h3><p><strong>Retrieval-Augmented Generation (RAG) is an approach that provides an LLM with relevant external information before it generates a response.</strong></p><p>Instead of expecting the model to already know everything, the application retrieves useful information from an external knowledge source.</p><p>Think of it like an open-book examination.</p><p>The model receives the question and relevant reference material before generating its answer.</p><h3>How Does It Work?</h3><p>A typical RAG pipeline contains two major stages.</p><p><strong>Stage 1: Indexing</strong></p><p>Before users ask questions, the application prepares its knowledge base.</p><ol><li>Collect documents.</li><li>Extract text.</li><li>Split documents into smaller chunks.</li><li>Convert chunks into embeddings.</li><li>Store embeddings and associated metadata in a vector database or another retrieval system.</li></ol><p><strong>Stage 2: Retrieval and Generation</strong></p><p>When a user asks a question:</p><ol><li>Convert the question into an embedding.</li><li>Search for relevant document chunks.</li><li>Retrieve the most relevant information.</li><li>Add the retrieved context to the LLM prompt.</li><li>Generate an answer based on the available context.</li></ol><h3>Practical Example</h3><p>Imagine building an internal company assistant that answers questions about employee policies.</p><pre>question = &quot;What is the company&#39;s leave policy?&quot;</pre><pre>documents = vector_store.similarity_search(<br>    question,<br>    k=3<br>)</pre><pre>context = &quot;\n&quot;.join(<br>    doc.page_content for doc in documents<br>)</pre><pre>response = llm.invoke(<br>    f&quot;&quot;&quot;<br>    Answer using the provided context.</pre><pre>    Context:<br>    {context}</pre><pre>    Question:<br>    {question}</pre><pre>    If the answer is not available in the<br>    context, say that you do not know.<br>    &quot;&quot;&quot;<br>)</pre><p><strong>Explanation:</strong></p><ul><li>similarity_search() retrieves relevant document chunks.</li><li>The retrieved content becomes the context.</li><li>The LLM uses that context to generate its response.</li></ul><p>This is a simplified RAG example. A production implementation should also consider metadata filtering, retrieval quality, access permissions, source citations, and context limits.</p><h3>When Should You Use RAG?</h3><p>Use RAG when:</p><ul><li>Your application needs private or proprietary information.</li><li>Information changes frequently.</li><li>You need answers grounded in external documents.</li><li>You want to provide source references.</li><li>You need to update knowledge without retraining the model.</li></ul><h3>When Should You Avoid RAG?</h3><p>RAG may be unnecessary when the task does not require external knowledge.</p><p>For example, if your only requirement is to make an LLM return responses in a specific JSON structure, building a vector database and retrieval pipeline adds complexity without solving the actual problem.</p><p><strong>Common mistake:</strong> Assuming that retrieving relevant documents guarantees a correct answer.</p><p>RAG quality depends on the entire pipeline. Poor chunking, weak embeddings, irrelevant retrieval, or missing information can still produce incorrect responses.</p><h3>4. What Is Fine-Tuning?</h3><p><strong>Fine-Tuning is the process of further training a pretrained model on a curated dataset to adapt its behavior to a particular task or domain.</strong></p><p>Think of it like specialized professional training.</p><p>A person may already understand general concepts, but additional training helps them perform a specific job more effectively.</p><p>Fine-Tuning adjusts model parameters using training examples so the model learns patterns that are useful for the target task.</p><h3>How Does It Work?</h3><p>A typical supervised fine-tuning workflow involves:</p><ol><li>Selecting a suitable pretrained model.</li><li>Preparing a high-quality dataset.</li><li>Formatting examples into the required training structure.</li><li>Training the model on those examples.</li><li>Evaluating its performance.</li><li>Deploying the fine-tuned version.</li></ol><p>For example, you might prepare training examples for a customer-support assistant.</p><pre>training_data = [<br>    {<br>        &quot;messages&quot;: [<br>            {<br>                &quot;role&quot;: &quot;user&quot;,<br>                &quot;content&quot;: &quot;I cannot access my account.&quot;<br>            },<br>            {<br>                &quot;role&quot;: &quot;assistant&quot;,<br>                &quot;content&quot;: (<br>                    &quot;I can help you recover access. &quot;<br>                    &quot;Please follow the account recovery process.&quot;<br>                )<br>            }<br>        ]<br>    },<br>    {<br>        &quot;messages&quot;: [<br>            {<br>                &quot;role&quot;: &quot;user&quot;,<br>                &quot;content&quot;: &quot;How do I reset my password?&quot;<br>            },<br>            {<br>                &quot;role&quot;: &quot;assistant&quot;,<br>                &quot;content&quot;: (<br>                    &quot;Open account settings and select &quot;<br>                    &quot;the password reset option.&quot;<br>                )<br>            }<br>        ]<br>    }<br>]</pre><p><strong>Explanation:</strong></p><p>These examples demonstrate the desired input-output behavior.</p><p>During supervised fine-tuning, the model learns from many such examples. The dataset must be representative, consistent, and carefully reviewed.</p><p>This example illustrates the training-data structure, not a complete training procedure.</p><h3>Common Fine-Tuning Techniques</h3><ul><li><strong>Full Fine-Tuning:</strong> Updates the model’s trainable parameters.</li><li><strong>LoRA:</strong> Uses low-rank trainable adapters to reduce the number of parameters that need updating.</li><li><strong>QLoRA:</strong> Combines quantization with LoRA to reduce memory requirements during fine-tuning.</li></ul><h3>When Should You Use Fine-Tuning?</h3><p>Use Fine-Tuning when:</p><ul><li>You need consistent task-specific behavior.</li><li>You have a high-quality dataset of representative examples.</li><li>You want a model to learn a specialized response style or output pattern.</li><li>Prompt Engineering alone does not provide the required consistency.</li><li>You need to adapt a model to a repeated, well-defined task.</li></ul><h3>When Should You Avoid Fine-Tuning?</h3><p>Avoid it when your primary requirement is simply to provide frequently changing facts or private documents.</p><p>Fine-Tuning is not an efficient replacement for a searchable knowledge base.</p><p>It also requires training infrastructure, evaluation, maintenance, and careful dataset preparation.</p><p><strong>Common mistake:</strong> Assuming that fine-tuning automatically gives a model accurate access to new or frequently updated information.</p><p>Fine-Tuning primarily adapts learned behavior. It does not guarantee factual recall or provide a live connection to external data.</p><h3>5. Fine-Tuning vs RAG vs Prompt Engineering</h3><p>Now that we understand each approach, let’s compare them based on the problem they solve.</p><h3>What Each Approach Changes</h3><ul><li><strong>Prompt Engineering:</strong> Changes the instructions and context supplied to the model.</li><li><strong>RAG:</strong> Changes the information available to the model at inference time.</li><li><strong>Fine-Tuning:</strong> Changes the model itself through additional training.</li></ul><p>This is the most important distinction.</p><h3>Practical Comparison</h3><p><strong>Prompt Engineering</strong></p><ul><li>Main purpose: Guide model behavior.</li><li>Data requirement: Instructions and examples when needed.</li><li>Training required: No.</li><li>Knowledge updates: Update the prompt or supplied context.</li><li>Complexity: Usually low.</li><li>Best suited for: Formatting, roles, instructions, and task guidance.</li></ul><p><strong>RAG</strong></p><ul><li>Main purpose: Ground responses in external information.</li><li>Data requirement: Documents or other searchable data.</li><li>Training required: No model fine-tuning required.</li><li>Knowledge updates: Update or re-index the knowledge source.</li><li>Complexity: Medium to high, depending on the retrieval architecture.</li><li>Best suited for: Private knowledge bases and frequently changing information.</li></ul><p><strong>Fine-Tuning</strong></p><ul><li>Main purpose: Adapt model behavior.</li><li>Data requirement: Curated training examples.</li><li>Training required: Yes.</li><li>Knowledge updates: Requires additional training or adapter updates.</li><li>Complexity: Medium to high.</li><li>Best suited for: Specialized tasks, response patterns, and domain-specific behavior.</li></ul><h3>6. Visualizing the Differences</h3><pre>flowchart TD<br>    A[LLM Application Requirement] --&gt; B{What Needs Improvement?}</pre><pre>    B --&gt;|Instructions or Format| C[Prompt Engineering]<br>    B --&gt;|External or Private Knowledge| D[RAG]<br>    B --&gt;|Specialized Model Behavior| E[Fine-Tuning]</pre><pre>    C --&gt; F[Refined Instructions]<br>    D --&gt; G[Retrieve Relevant Context]<br>    G --&gt; H[Generate Grounded Response]<br>    E --&gt; I[Train on Curated Examples]</pre><pre>    F --&gt; J[LLM Application]<br>    H --&gt; J<br>    I --&gt; J</pre><p>The diagram shows that the choice depends on the problem, not on which technique is more advanced.</p><h3>7. Can We Combine All Three?</h3><p>Absolutely.</p><p>In fact, production AI applications often combine Prompt Engineering, RAG, and Fine-Tuning.</p><p>Consider an enterprise AI assistant.</p><ul><li><strong>Fine-Tuning</strong> adapts the model to a specialized task and preferred response patterns.</li><li><strong>RAG</strong> retrieves the latest company policies and internal documentation.</li><li><strong>Prompt Engineering</strong> defines the assistant’s role, instructions, and response requirements.</li></ul><p>The combined workflow looks like this:</p><pre>flowchart TD<br>    A[User Question] --&gt; B[Prompt Instructions]<br>    B --&gt; C[RAG Retrieval]<br>    C --&gt; D[Relevant Context]<br>    D --&gt; E[Fine-Tuned LLM]<br>    E --&gt; F[Generated Response]</pre><p>This architecture separates responsibilities.</p><p>The prompt guides the task, RAG supplies relevant information, and the fine-tuned model provides adapted behavior.</p><p>However, combining all three is not automatically better. Each additional component introduces complexity, cost, and potential failure points.</p><h3>8. Real-World Applications</h3><p><strong>Customer Support Assistant</strong></p><ul><li>Prompt Engineering: Defines the support assistant’s behavior.</li><li>RAG: Retrieves product documentation and support policies.</li><li>Fine-Tuning: Adapts the model to consistent support-response patterns when necessary.</li></ul><p><strong>Enterprise Knowledge Assistant</strong></p><ul><li>Prompt Engineering: Defines response rules.</li><li>RAG: Retrieves internal documents.</li><li>Fine-Tuning: May help with specialized terminology or task behavior.</li></ul><p><strong>Code Generation Assistant</strong></p><ul><li>Prompt Engineering: Specifies coding conventions and output requirements.</li><li>RAG: Retrieves relevant internal code examples and documentation.</li><li>Fine-Tuning: Can adapt the model to organization-specific coding patterns.</li></ul><h3>9. Best Practices</h3><p>Before selecting an approach, follow these principles:</p><ul><li>Start with Prompt Engineering. It is often the simplest baseline.</li><li>Introduce RAG when the application needs external or frequently updated knowledge.</li><li>Consider Fine-Tuning when you have a clear behavioral requirement and quality training data.</li><li>Evaluate each approach using representative test cases.</li><li>Measure accuracy, latency, cost, and consistency.</li><li>Validate RAG retrieval quality independently from answer quality.</li><li>Avoid fine-tuning on small, noisy, or poorly curated datasets.</li><li>Use source citations and access controls when working with private information.</li><li>Combine approaches only when each one solves a specific requirement.</li></ul><h3>10. Common Mistakes</h3><ul><li>Using Fine-Tuning to solve a frequently changing knowledge problem.</li><li>Building a RAG pipeline when a well-designed prompt is sufficient.</li><li>Expecting Prompt Engineering to permanently teach new knowledge.</li><li>Assuming RAG guarantees factual accuracy.</li><li>Assuming Fine-Tuning eliminates hallucinations.</li><li>Ignoring evaluation before and after implementation.</li><li>Choosing an architecture because it is popular rather than because it fits the requirement.</li></ul><p>11. Performance and Cost Considerations</p><p>Each approach introduces different operational costs.</p><p><strong>Prompt Engineering:</strong> Usually has the lowest infrastructure complexity, but longer prompts increase input-token usage and can consume more context.</p><p><strong>RAG:</strong> Adds embedding, retrieval, storage, and orchestration costs. It can reduce the need to include entire document collections in every prompt, but poor retrieval can increase latency without improving answer quality.</p><p><strong>Fine-Tuning:</strong> Requires training resources and ongoing evaluation. It may improve performance on repeated specialized tasks, but the benefits must justify training and maintenance costs.</p><p>There is no universally cheapest or fastest option. Actual performance depends on the model, workload, data, and implementation.</p><h3>12. Summary: Which Approach Should You Choose?</h3><p>The right approach depends on what you are trying to improve.</p><ul><li><strong>Choose Prompt Engineering</strong> when you need better instructions, formatting, or task guidance.</li><li><strong>Choose RAG</strong> when your application needs access to private, external, or frequently changing information.</li><li><strong>Choose Fine-Tuning</strong> when you need to adapt model behavior using high-quality training examples.</li><li><strong>Combine them</strong> when your application has multiple distinct requirements that justify the added complexity.</li></ul><p>One useful way to remember the difference:</p><p><strong>Prompt Engineering tells the model what to do.</strong></p><p><strong>RAG gives the model information to work with.</strong></p><p><strong>Fine-Tuning adapts how the model performs a task.</strong></p><p>Before building a complex AI architecture, identify the actual limitation in your application.</p><p>Sometimes a better prompt is enough. Sometimes you need retrieval. And sometimes specialized training is the right investment.</p><p>The best AI architecture is not the one with the most components. It is the one that solves the problem reliably with the least unnecessary complexity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MjUZfxLCML0N3pbPjGrX7A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39102acbec77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mixture of Experts (MoE) Explained: How Modern LLMs Activate Only the Parameters They Need]]></title>
            <link>https://medium.com/@s.aditya1317/mixture-of-experts-moe-explained-how-modern-llms-activate-only-the-parameters-they-need-6ee630439247?source=rss-2d1520186482------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ee630439247</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Aditya S]]></dc:creator>
            <pubDate>Wed, 11 Nov 2026 10:36:36 GMT</pubDate>
            <atom:updated>2026-11-11T10:36:36.043Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Modern Large Language Models (LLMs) are becoming increasingly powerful, but building larger models comes with a challenge: <strong>computation becomes expensive as the number of parameters grows.</strong></p><p>A traditional Transformer model activates most of its parameters for every input token. This means that even when a particular token needs only a small part of the model’s knowledge, the entire relevant network still performs computation.</p><p>What if a model could choose which parts of its network to activate for each token?</p><p>That is the central idea behind <strong>Mixture of Experts (MoE)</strong>.</p><p>Instead of sending every token through the same feed-forward network, an MoE model uses multiple specialized networks called <em>experts</em>. A routing mechanism selects a small number of experts for each token.</p><p>The result is a model that can have a very large total number of parameters while activating only a fraction of them for each token.</p><p>This approach has become an important architecture in modern LLM development because it offers a way to scale model capacity without proportionally increasing computation per token.</p><p>Let’s understand how it works, why it matters, and how to build a simplified version using PyTorch.</p><h3>What You Will Learn</h3><p>By the end of this article, you will understand:</p><ul><li>What Mixture of Experts means and why it exists.</li><li>How experts and gating networks work.</li><li>How tokens are routed to different experts.</li><li>The difference between active parameters and total parameters.</li><li>How MoE differs from a traditional dense Transformer.</li><li>How to implement a basic MoE layer using PyTorch.</li><li>The advantages, limitations, and practical considerations of MoE.</li></ul><h3>Prerequisites</h3><p>You should have a basic understanding of:</p><ul><li>Python and PyTorch fundamentals.</li><li>Neural networks and feed-forward layers.</li><li>Transformer architecture at a high level.</li><li>Tokens and embeddings in LLMs.</li></ul><p>You do not need advanced knowledge of distributed training.</p><h3>1. The Problem: Scaling Large Language Models Is Expensive</h3><p>Let’s start with a traditional neural network.</p><p>In a dense model, an input passes through the same network layers. In a Transformer, each token typically passes through an attention layer and a feed-forward network (FFN).</p><p>The FFN performs transformations on the token representation and helps the model learn complex patterns.</p><p>As models grow, these layers become larger and contain more parameters.</p><p>For example, imagine a model with a feed-forward network containing 10 billion parameters.</p><p>Every token passing through that network uses the same FFN.</p><p>Now imagine increasing the model’s capacity to 100 billion parameters. A dense architecture generally requires substantially more computation when processing each token.</p><p>This creates a trade-off:</p><ul><li>Larger models can represent more complex patterns.</li><li>More parameters usually require more computation and memory.</li><li>Serving large models becomes increasingly expensive.</li></ul><p><strong>The key question:</strong> Can we increase a model’s total capacity without activating every parameter for every token?</p><p>Mixture of Experts provides one approach.</p><h3>2. What Is Mixture of Experts (MoE)?</h3><p>Mixture of Experts is a neural network architecture that contains multiple smaller networks, called <strong>experts</strong>, and a routing mechanism that decides which experts should process an input.</p><p>Instead of sending every token through one large feed-forward network, the model selects a small number of experts for each token.</p><p>Think of a company with multiple departments:</p><ul><li>The finance team handles financial questions.</li><li>The engineering team handles technical problems.</li><li>The marketing team handles customer and market-related questions.</li></ul><p>When a request arrives, a coordinator sends it to the appropriate department rather than asking every department to handle every task.</p><p>An MoE model follows a similar idea.</p><ul><li><strong>Experts:</strong> Individual neural networks that process token representations.</li><li><strong>Router (or gate):</strong> Decides which experts receive each token.</li><li><strong>Top-K selection:</strong> Determines how many experts are activated for a token.</li><li><strong>Combination:</strong> Combines the selected experts’ outputs.</li></ul><p>One important clarification: experts are not manually assigned roles such as finance or coding. They learn different patterns during training. Their specialization emerges from the training process.</p><h3>3. Core Components of an MoE Layer</h3><p>An MoE layer has three important components.</p><h3>3.1 Experts</h3><p>An expert is usually a feed-forward neural network.</p><p>For example, an MoE layer might contain eight experts:</p><ul><li>Expert 1</li><li>Expert 2</li><li>Expert 3</li><li>Expert 4</li><li>Expert 5</li><li>Expert 6</li><li>Expert 7</li><li>Expert 8</li></ul><p>Each expert has its own trainable parameters.</p><p>When a token reaches the MoE layer, it does not necessarily pass through all eight experts. The router selects only a subset.</p><p><strong>Why do we need multiple experts?</strong></p><p>Multiple experts increase the model’s representational capacity. Different experts can learn different transformations that are useful for different input patterns.</p><h3>3.2 Router or Gating Network</h3><p>The router is a small neural network that calculates how suitable each expert is for a given token.</p><p>Suppose a token has an embedding represented by a vector:</p><pre>token = [0.2, 0.5, 0.1, 0.8]</pre><p>The router processes this representation and produces scores for each expert.</p><p>For eight experts, it produces eight scores.</p><p>These scores indicate the relative preference for each expert.</p><p>A softmax function can convert the scores into probabilities:</p><pre>probabilities = softmax(router_scores)</pre><p>For example:</p><pre>Expert 1: 0.05<br>Expert 2: 0.10<br>Expert 3: 0.60<br>Expert 4: 0.05<br>Expert 5: 0.08<br>Expert 6: 0.04<br>Expert 7: 0.03<br>Expert 8: 0.05</pre><p>Expert 3 receives the highest probability.</p><p>The router uses these scores to decide which experts should process the token.</p><p><strong>Important:</strong> The router does not understand the token like a human. It learns routing patterns through training.</p><h3>3.3 Top-K Selection</h3><p>Selecting only the highest-scoring experts is called Top-K routing.</p><p>Suppose we have eight experts and choose K = 2.</p><p>The router selects the two experts with the highest scores.</p><p>For the previous example:</p><pre>Expert 3: 0.60<br>Expert 2: 0.10</pre><p>Only Expert 3 and Expert 2 are selected.</p><p>Their outputs are combined using their routing weights.</p><p>This is how MoE avoids activating every expert for every token.</p><h3>4. How Does MoE Work? Step by Step</h3><p>Let’s follow one token through an MoE layer.</p><p><strong>Step 1: Token Representation</strong></p><p>The input token is converted into an embedding vector by the model.</p><p><strong>Step 2: Router Calculates Scores</strong></p><p>The router receives the token representation and calculates a score for every available expert.</p><p><strong>Step 3: Top-K Experts Are Selected</strong></p><p>The router selects the experts with the highest scores.</p><p><strong>Step 4: Selected Experts Process the Token</strong></p><p>The token representation is passed through the selected experts.</p><p><strong>Step 5: Expert Outputs Are Combined</strong></p><p>The outputs are weighted using the router’s selected probabilities and combined into one representation.</p><p>The resulting representation continues through the Transformer.</p><p>The important point is that routing happens at the token level. Different tokens in the same sentence can be sent to different experts.</p><h3>5. Visualizing the MoE Architecture</h3><p>The following diagram shows how a token moves through an MoE layer.</p><pre>flowchart TD<br>    A[&quot;Input Token&quot;] --&gt; B[&quot;Token Embedding&quot;]<br>    B --&gt; C[&quot;Router / Gating Network&quot;]<br>    C --&gt; D[&quot;Calculate Expert Scores&quot;]<br>    D --&gt; E[&quot;Top-K Selection&quot;]<br>    E --&gt; F[&quot;Expert 1&quot;]<br>    E --&gt; G[&quot;Expert 3&quot;]<br>    F --&gt; H[&quot;Weighted Combination&quot;]<br>    G --&gt; H<br>    H --&gt; I[&quot;Output Representation&quot;]</pre><p>Notice that the router selects only two experts in this example.</p><p>The other experts remain inactive for that token.</p><h3>6. Dense Models vs Mixture of Experts</h3><p>To understand the benefit of MoE, compare it with a traditional dense feed-forward layer.</p><h3>Dense Model</h3><p>In a dense architecture, every token passes through the same feed-forward network.</p><pre>Token → Feed-Forward Network → Output</pre><p>The same network parameters are used for every token.</p><h3>MoE Model</h3><p>In an MoE architecture, the router selects a subset of experts.</p><pre>Token → Router → Selected Experts → Output</pre><p>The model has multiple expert networks, but only a few are activated for each token.</p><p>Consider a simplified example:</p><ul><li>8 experts.</li><li>Each expert has 1 billion parameters.</li><li>The router selects 2 experts per token.</li></ul><p>The MoE layer contains 8 billion expert parameters, but only 2 billion expert parameters are active for a token.</p><p>This illustrates the distinction between <strong>total parameters</strong> and <strong>active parameters</strong>.</p><p>It does not mean the entire model uses only 2 billion parameters. Attention layers, embeddings, the router, and other components also contribute to the model’s parameter count.</p><h3>7. Practical Implementation: Building a Simple MoE Layer with PyTorch</h3><p>Now let’s implement a simplified MoE layer.</p><p>The goal is to understand the architecture, not to build a production-ready LLM.</p><h3>Level 1: Create the Expert Networks</h3><p>Each expert will be a small feed-forward neural network.</p><pre>import torch<br>import torch.nn as nn</pre><pre>class Expert(nn.Module):<br>    def __init__(self, input_dim, hidden_dim):<br>        super().__init__()</pre><pre>        self.network = nn.Sequential(<br>            nn.Linear(input_dim, hidden_dim),<br>            nn.ReLU(),<br>            nn.Linear(hidden_dim, input_dim)<br>        )</pre><pre>    def forward(self, x):<br>        return self.network(x)</pre><p><strong>Explanation:</strong></p><ul><li>input_dim defines the input representation size.</li><li>hidden_dim defines the expert&#39;s internal hidden layer size.</li><li>The first linear layer transforms the input.</li><li>ReLU introduces non-linearity.</li><li>The final layer returns an output with the original input dimension.</li></ul><p>We can create multiple independent instances of this network.</p><h3>Level 2: Build the Router</h3><p>The router calculates a score for every expert.</p><pre>class Router(nn.Module):<br>    def __init__(self, input_dim, num_experts):<br>        super().__init__()</pre><pre>        self.gate = nn.Linear(input_dim, num_experts)</pre><pre>    def forward(self, x):<br>        scores = self.gate(x)</pre><pre>        probabilities = torch.softmax(scores, dim=-1)</pre><pre>        return probabilities</pre><p><strong>Explanation:</strong></p><p>If the input has four features and we have eight experts, the router produces eight scores for each token.</p><p>Softmax converts those scores into probabilities.</p><p>The probabilities help determine which experts should receive the token.</p><h3>Level 3: Build the MoE Layer</h3><p>Now combine the experts and router into a single layer.</p><pre>class MoELayer(nn.Module):<br>    def __init__(<br>        self,<br>        input_dim,<br>        hidden_dim,<br>        num_experts,<br>        top_k<br>    ):<br>        super().__init__()</pre><pre>        self.num_experts = num_experts<br>        self.top_k = top_k</pre><pre>        self.experts = nn.ModuleList([<br>            Expert(input_dim, hidden_dim)<br>            for _ in range(num_experts)<br>        ])</pre><pre>        self.router = Router(input_dim, num_experts)</pre><pre>    def forward(self, x):</pre><pre>        probabilities = self.router(x)</pre><pre>        top_values, top_indices = torch.topk(<br>            probabilities,<br>            self.top_k,<br>            dim=-1<br>        )</pre><pre>        top_weights = top_values / top_values.sum(<br>            dim=-1,<br>            keepdim=True<br>        )</pre><pre>        output = torch.zeros_like(x)</pre><pre>        for expert_id, expert in enumerate(self.experts):</pre><pre>            token_indices = (<br>                top_indices == expert_id<br>            ).nonzero(as_tuple=True)</pre><pre>            if token_indices[0].numel() == 0:<br>                continue</pre><pre>            batch_indices = token_indices[0]<br>            sequence_indices = token_indices[1]<br>            selected_tokens = x[batch_indices, sequence_indices]</pre><pre>            expert_output = expert(selected_tokens)</pre><pre>            weights = top_weights[<br>                batch_indices,<br>                sequence_indices,<br>                token_indices[2]<br>            ].unsqueeze(-1)</pre><pre>            output[batch_indices, sequence_indices] += (<br>                expert_output * weights<br>            )</pre><pre>        return output</pre><p><strong>Explanation:</strong></p><p>The forward pass follows the MoE workflow:</p><ol><li>The router calculates probabilities for each token.</li><li>torch.topk() selects the highest-scoring experts.</li><li>The selected routing weights are normalized.</li><li>Each expert processes the tokens assigned to it.</li><li>The expert outputs are weighted and combined.</li></ol><p>This is an educational implementation of token-level Top-K routing. It assumes a three-dimensional input shaped as [batch, sequence, features].</p><p>Production MoE implementations use more efficient dispatch and aggregation operations. They also handle capacity limits, distributed expert placement, and load balancing.</p><h3>Level 4: Test the MoE Layer</h3><p>Let’s create a small example.</p><pre>moe = MoELayer(<br>    input_dim=16,<br>    hidden_dim=32,<br>    num_experts=4,<br>    top_k=2<br>)</pre><pre>x = torch.randn(2, 5, 16)</pre><pre>output = moe(x)</pre><pre>print(&quot;Input shape:&quot;, x.shape)<br>print(&quot;Output shape:&quot;, output.shape)</pre><p>Expected output:</p><pre>Input shape: torch.Size([2, 5, 16])<br>Output shape: torch.Size([2, 5, 16])</pre><p>The output preserves the input shape, allowing the MoE layer to replace a conventional feed-forward layer inside a Transformer block.</p><p>The example demonstrates the forward computation. A production implementation would need additional work for efficient training, expert capacity management, and load balancing.</p><h3>8. Why Do Modern LLMs Use MoE?</h3><p>MoE is useful because it provides a way to increase model capacity without requiring every parameter to participate in every token’s computation.</p><p>Some important benefits include:</p><h3>8.1 Higher Model Capacity</h3><p>Adding experts increases the number of available parameters.</p><p>This allows the model to learn more complex patterns and representations.</p><h3>8.2 Conditional Computation</h3><p>The model activates only selected experts for each token.</p><p>This avoids performing computation through every expert for every token.</p><h3>8.3 Scaling Opportunities</h3><p>MoE architectures can distribute experts across multiple GPUs or machines.</p><p>This makes it possible to train and serve models with very large parameter counts, although distributed communication introduces additional complexity.</p><h3>9. Challenges and Limitations of MoE</h3><p>MoE is powerful, but it is not automatically faster or cheaper in every situation.</p><h3>9.1 Load Balancing</h3><p>Imagine a model with eight experts.</p><p>If the router sends most tokens to Expert 1 and almost none to the remaining experts, the system becomes inefficient.</p><p>One expert receives too much work while others remain underused.</p><p>To address this, MoE training commonly uses auxiliary load-balancing losses or other routing strategies to encourage a more balanced distribution.</p><h3>9.2 Communication Overhead</h3><p>In distributed MoE models, experts may reside on different GPUs.</p><p>Tokens must be transferred to the devices hosting their selected experts. This communication can become a major performance bottleneck.</p><h3>9.3 Memory Requirements</h3><p>Even though only a subset of experts is activated per token, the model still needs to store its expert parameters.</p><p>Therefore, low active-parameter counts do not automatically mean low memory requirements.</p><h3>9.4 Routing Instability</h3><p>The router must learn useful expert assignments.</p><p>Poor routing can lead to underused experts, overloaded experts, or ineffective specialization.</p><h3>10. Best Practices When Working with MoE</h3><p>When designing or experimenting with MoE architectures, keep these points in mind:</p><ul><li>Start with a small number of experts before increasing model complexity.</li><li>Monitor how frequently each expert receives tokens.</li><li>Use appropriate load-balancing techniques during training.</li><li>Measure communication overhead when experts are distributed across devices.</li><li>Track both total parameters and active parameters.</li><li>Benchmark real latency and throughput rather than assuming fewer active parameters guarantee faster inference.</li><li>Use optimized expert dispatch and aggregation implementations for production workloads.</li></ul><h3>11. Common Misconceptions About MoE</h3><p><strong>Misconception 1: Each expert is manually trained for a specific subject.</strong></p><p>Not necessarily. Experts generally learn different representations through training. Their specialization is not usually assigned by developers.</p><p><strong>Misconception 2: Inactive experts do not consume memory.</strong></p><p>Incorrect. Their parameters still need to be stored, even when they are not selected for a particular token.</p><p><strong>Misconception 3: MoE always makes inference faster.</strong></p><p>Not always. Routing, communication, memory access, and hardware utilization all affect actual performance.</p><p><strong>Misconception 4: Only one expert is activated at a time.</strong></p><p>Not necessarily. Top-1 routing selects one expert, while Top-2 routing selects two. The number depends on the architecture.</p><h3>12. Performance Considerations</h3><p>The most important distinction when evaluating MoE is between total model size and computation per token.</p><p>For example:</p><ul><li>Total expert parameters: 8 billion.</li><li>Experts selected per token: 2.</li><li>Parameters per expert: 1 billion.</li><li>Active expert parameters per token: 2 billion.</li></ul><p>This simplified calculation excludes shared layers, attention, embeddings, and routing parameters.</p><p>MoE can reduce the amount of expert computation performed per token compared with activating all experts. However, it introduces routing and communication costs.</p><p>In practice, performance depends on:</p><ul><li>Number and size of experts.</li><li>Top-K routing strategy.</li><li>Token distribution across experts.</li><li>GPU memory and compute capacity.</li><li>Communication between devices.</li><li>Batch size and sequence length.</li></ul><p><strong>Interview tip:</strong> If asked whether MoE reduces model parameters, explain that it increases total model capacity while limiting the number of expert parameters activated for each token. It does not eliminate the need to store the other experts.</p><h3>13. Real-World Applications</h3><p>MoE is especially useful in large-scale models where increasing capacity while controlling per-token computation is important.</p><p>Common application areas include:</p><ul><li><strong>Large Language Models:</strong> Scaling model capacity for language understanding and generation.</li><li><strong>Multilingual Models:</strong> Learning different patterns across languages and linguistic structures.</li><li><strong>Code Generation:</strong> Supporting complex patterns across programming languages and software concepts.</li><li><strong>Multimodal Models:</strong> Combining different processing pathways for text, images, audio, or other modalities, depending on the architecture.</li></ul><p>MoE is not limited to LLMs. The broader idea of combining specialized neural networks has existed in machine learning for many years.</p><h3>14. Summary: Key Takeaways</h3><p>Mixture of Experts is an architectural approach that allows a neural network to increase its total capacity without activating every expert for every input token.</p><p>Remember these key points:</p><ul><li><strong>Experts:</strong> Independent neural networks that learn different transformations.</li><li><strong>Router:</strong> Selects which experts process each token.</li><li><strong>Top-K routing:</strong> Activates only a selected number of experts.</li><li><strong>Active parameters:</strong> Parameters used for a particular token’s computation.</li><li><strong>Total parameters:</strong> All parameters stored in the model, including inactive experts.</li><li><strong>Load balancing:</strong> Helps distribute tokens across experts.</li><li><strong>Communication overhead:</strong> Can affect performance in distributed MoE systems.</li></ul><p>The central idea is simple:</p><p><strong>A model does not always need to use its entire network to process every token. It can activate only the parts that are useful for the current computation.</strong></p><p>That is what makes Mixture of Experts an important approach to scaling modern neural networks and large language models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5r1xcGmcQjFqT7VeP0GUaw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ee630439247" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Multi-Agent Research System Using LangGraph and Tool Calling]]></title>
            <link>https://medium.com/@s.aditya1317/build-a-multi-agent-research-system-using-langgraph-and-tool-calling-9a84c7191734?source=rss-2d1520186482------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a84c7191734</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Aditya S]]></dc:creator>
            <pubDate>Tue, 10 Nov 2026 11:36:41 GMT</pubDate>
            <atom:updated>2026-11-10T11:36:41.091Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Imagine asking an AI assistant to research a complex topic such as:</p><p><em>“Analyze the current applications of RAG in healthcare, identify its limitations, and compare the leading approaches.”</em></p><p>A basic LLM might generate an answer from its existing knowledge. But it may miss recent developments, overlook important details, or produce unsupported claims.</p><p>A better approach is to divide the research into smaller tasks.</p><p>One agent can investigate applications, another can examine limitations, and a third can compare technical approaches. A coordinator can then combine their findings into one structured report.</p><p>This is the idea behind <strong>multi-agent AI systems</strong>.</p><p>In this project, we’ll build a multi-agent research system using <strong>LangGraph, tool calling, and web search</strong>. We’ll use LangGraph to coordinate specialized agents, allow them to search for information, and combine their findings into a final research report.</p><h3>What You’ll Learn</h3><ul><li>What multi-agent systems are and why they are useful.</li><li>How LangGraph manages agent workflows.</li><li>How tool calling allows agents to interact with external systems.</li><li>How to divide research into specialized tasks.</li><li>How to execute multiple research agents in parallel.</li><li>How to combine individual findings into a final report.</li></ul><h3>Prerequisites</h3><p>You should have:</p><ul><li>Basic Python knowledge.</li><li>A basic understanding of LLMs and prompting.</li><li>Familiarity with API calls.</li><li>Basic knowledge of LangChain is helpful.</li><li>An OpenAI API key and a Tavily API key.</li></ul><h3>1. The Problem: Why Build a Multi-Agent Research System?</h3><p>A traditional LLM application usually follows a simple workflow:</p><ol><li>Receive a user question.</li><li>Send the question to an LLM.</li><li>Generate a response.</li><li>Return the response.</li></ol><p>This works well for simple questions, but complex research requires multiple activities.</p><p>For example, researching a technology might involve:</p><ul><li>Finding relevant information.</li><li>Investigating different aspects of the topic.</li><li>Comparing findings from multiple sources.</li><li>Identifying limitations and disagreements.</li><li>Producing a structured summary.</li></ul><p>Asking one LLM to perform everything in a single prompt can make the task difficult to manage.</p><p>A multi-agent system addresses this by distributing responsibilities across specialized agents.</p><p>Think of it like a research team:</p><ul><li>A coordinator assigns tasks.</li><li>Researchers investigate specific areas.</li><li>Each researcher uses tools to gather information.</li><li>The coordinator combines their findings into a final report.</li></ul><p>The objective is not simply to use more LLMs. It is to organize complex work into smaller, manageable tasks.</p><h3>2. Core Concepts</h3><p>Before building the system, let’s understand the main components.</p><h3>What Is a Multi-Agent System?</h3><p>A multi-agent system consists of multiple AI agents that work together to accomplish a larger objective.</p><p>Each agent can have a different role, instructions, tools, or responsibilities.</p><p>For our project:</p><ul><li><strong>Planner Agent:</strong> Breaks the research question into smaller tasks.</li><li><strong>Research Agents:</strong> Investigate individual topics using web search.</li><li><strong>Synthesis Agent:</strong> Combines the findings into a final report.</li></ul><p>We are using specialized roles to separate responsibilities, not necessarily separate foundation models. All agents can use the same underlying LLM with different instructions.</p><h3>What Is LangGraph?</h3><p>LangGraph is a framework for building stateful, multi-step AI workflows.</p><p>Instead of treating an AI application as one large prompt, LangGraph allows us to represent it as a graph.</p><p>A graph contains:</p><ul><li><strong>Nodes:</strong> Individual processing steps or agents.</li><li><strong>Edges:</strong> Connections between nodes.</li><li><strong>State:</strong> Shared information passed through the workflow.</li><li><strong>Conditional routing:</strong> Decisions about which node should execute next.</li></ul><p>For example, after an agent generates a response, the graph can check whether it requested a tool. If it did, execution moves to the tool node. Otherwise, the workflow can continue or finish.</p><h3>What Is Tool Calling?</h3><p>Tool calling allows an LLM to request the execution of an external function.</p><p>For example, a research agent may decide that it needs current information and request a web search.</p><p>The workflow is:</p><ol><li>The agent receives a research question.</li><li>The model decides whether to call a search tool.</li><li>The tool executes the search.</li><li>The result is returned to the agent.</li><li>The agent uses the result to continue its research.</li></ol><p>The model does not independently execute the Python function. Your application or agent framework executes the requested tool.</p><p>This distinction is important for security and control.</p><h3>3. Project Architecture</h3><p>We’ll build a research workflow with three stages.</p><p><strong>Stage 1: Planning</strong></p><p>The planner converts the user’s question into smaller research topics.</p><p><strong>Stage 2: Parallel Research</strong></p><p>Multiple researcher agents investigate their assigned topics. Each researcher can call the web search tool to gather relevant information.</p><p><strong>Stage 3: Synthesis</strong></p><p>The final agent receives all research findings and creates one organized report.</p><p>The advantage of this architecture is that independent research tasks can run concurrently rather than waiting for one another.</p><h3>4. Step-by-Step Implementation</h3><h3>Step 1: Install Dependencies</h3><p>We’ll use LangGraph for orchestration, LangChain for agent and model integration, and Tavily for web search.</p><pre>pip install -U langgraph langchain langchain-openai langchain-tavily tavily-python python-dotenv</pre><p>Create a .env file:</p><pre>OPENAI_API_KEY=your_openai_api_key<br>TAVILY_API_KEY=your_tavily_api_key</pre><p>Keep your API keys outside your source code and never commit them to a public repository.</p><h3>Step 2: Initialize the Model and Search Tool</h3><p>First, initialize the LLM and web search tool.</p><pre>import os<br>from dotenv import load_dotenv</pre><pre>from langchain_openai import ChatOpenAI<br>from langchain_tavily import TavilySearch</pre><pre>load_dotenv()</pre><pre>llm = ChatOpenAI(<br>    model=&quot;gpt-4.1-mini&quot;,<br>    temperature=0<br>)</pre><pre>search_tool = TavilySearch(<br>    max_results=5<br>)</pre><p><strong>Explanation:</strong></p><ul><li>ChatOpenAI initializes the language model.</li><li>temperature=0 encourages more consistent outputs.</li><li>TavilySearch provides a web search tool.</li><li>max_results=5 limits the number of results returned per search.</li></ul><p>The model identifier is an example; use a currently available model supported by your account.</p><h3>Step 3: Define the Research Plan</h3><p>The planner should not investigate the entire topic itself. Its responsibility is to divide the question into smaller research tasks.</p><p>We’ll use Pydantic to define the expected output structure.</p><pre>from pydantic import BaseModel, Field</pre><pre>class ResearchPlan(BaseModel):</pre><pre>    topics: list[str] = Field(<br>        description=&quot;Independent research topics&quot;<br>    )</pre><p>Now create the planner function:</p><pre>def plan_research(state):</pre><pre>    planner = llm.with_structured_output(<br>        ResearchPlan<br>    )</pre><pre>    plan = planner.invoke(<br>        f&quot;&quot;&quot;<br>        Break this research question into<br>        three independent research topics.</pre><pre>        Research question:<br>        {state[&#39;query&#39;]}</pre><pre>        Each topic should investigate a<br>        different aspect of the question.<br>        &quot;&quot;&quot;<br>    )</pre><pre>    return {<br>        &quot;topics&quot;: plan.topics<br>    }</pre><p><strong>Explanation:</strong></p><p>The planner uses structured output to produce a predictable list of research topics.</p><p>For example, if the user asks about RAG in healthcare, the planner might generate:</p><ul><li>Applications of RAG in healthcare.</li><li>Technical challenges and limitations.</li><li>Evaluation methods and future opportunities.</li></ul><p>This makes the workflow easier to control than relying on an unstructured paragraph.</p><h3>Step 4: Create the Research Agent</h3><p>Now we need an agent that can investigate an assigned topic.</p><p>Instead of manually implementing the tool-calling loop, we’ll use LangChain’s create_agent, which manages model-tool interactions.</p><pre>from langchain.agents import create_agent</pre><pre>research_agent = create_agent(<br>    model=llm,<br>    tools=[search_tool],<br>    system_prompt=&quot;&quot;&quot;<br>    You are a specialized research agent.</pre><pre>    Investigate the assigned research topic.</pre><pre>    Use web search to gather relevant information.<br>    Prefer reliable and relevant sources.</pre><pre>    Summarize:<br>    - Important findings<br>    - Supporting evidence<br>    - Relevant source URLs<br>    - Limitations or uncertainty</pre><pre>    Do not invent facts or sources.<br>    &quot;&quot;&quot;<br>)</pre><p><strong>Explanation:</strong></p><p>The research agent receives access to the search tool.</p><p>When it needs external information, the model can request a tool call. The agent framework executes the tool, returns its result to the model, and allows the model to continue.</p><p>This is the tool-calling loop.</p><p>The important benefit is that the agent can decide when it needs to search rather than receiving search results blindly.</p><h3>Step 5: Define the LangGraph State</h3><p>LangGraph needs a shared state to manage information across the workflow.</p><p>We’ll use a TypedDict to define it.</p><pre>import operator</pre><pre>from typing import Annotated<br>from typing_extensions import TypedDict</pre><pre>class ResearchState(TypedDict):</pre><pre>    query: str<br>    topics: list[str]</pre><pre>    findings: Annotated[<br>        list[str],<br>        operator.add<br>    ]</pre><pre>    report: str</pre><p><strong>Explanation:</strong></p><ul><li>query stores the original research question.</li><li>topics stores the tasks generated by the planner.</li><li>findings stores the results from individual researchers.</li><li>report stores the final synthesized output.</li></ul><p>Notice operator.add on findings.</p><p>When multiple researcher agents finish, their findings need to be combined into one list. The reducer tells LangGraph how to merge those updates.</p><p>Without an appropriate reducer, parallel updates to the same state field can conflict.</p><h3>Step 6: Build the Research Worker</h3><p>Each research worker receives one topic and the original question.</p><pre>def research_worker(state):</pre><pre>    topic = state[&quot;topic&quot;]<br>    query = state[&quot;query&quot;]</pre><pre>    result = research_agent.invoke({<br>        &quot;messages&quot;: [<br>            {<br>                &quot;role&quot;: &quot;user&quot;,<br>                &quot;content&quot;: f&quot;&quot;&quot;<br>                Overall research question:<br>                {query}</pre><pre>                Your assigned topic:<br>                {topic}</pre><pre>                Investigate this topic and<br>                return a concise research summary.<br>                &quot;&quot;&quot;<br>            }<br>        ]<br>    })</pre><pre>    summary = result[&quot;messages&quot;][-1].content</pre><pre>    return {<br>        &quot;findings&quot;: [<br>            f&quot;Topic: {topic}\n{summary}&quot;<br>        ]<br>    }</pre><p><strong>Explanation:</strong></p><p>Each worker performs an independent research task.</p><p>The agent can use web search, examine the returned information, and produce a summary.</p><p>Because every worker returns a list containing its own finding, LangGraph can merge the results using the operator.add reducer.</p><h3>Step 7: Add Parallel Execution</h3><p>This is where LangGraph becomes particularly useful.</p><p>We can use Send to dispatch multiple tasks to the same research node.</p><pre>from langgraph.types import Send</pre><pre>def dispatch_research(state):</pre><pre>    return [<br>        Send(<br>            &quot;researcher&quot;,<br>            {<br>                &quot;query&quot;: state[&quot;query&quot;],<br>                &quot;topic&quot;: topic<br>            }<br>        )<br>        for topic in state[&quot;topics&quot;]<br>    ]</pre><p><strong>Explanation:</strong></p><p>Suppose the planner creates three research topics.</p><p>Instead of executing them one after another, Send creates three worker tasks:</p><ul><li>Researcher 1 investigates applications.</li><li>Researcher 2 investigates limitations.</li><li>Researcher 3 investigates evaluation methods.</li></ul><p>LangGraph can execute these independent tasks in parallel.</p><p>This is useful when tasks do not depend on each other’s results.</p><h3>Step 8: Create the Synthesis Agent</h3><p>Once research is complete, we need to combine the findings.</p><pre>def synthesize_research(state):</pre><pre>    research_data = &quot;\n\n&quot;.join(<br>        state[&quot;findings&quot;]<br>    )</pre><pre>    response = llm.invoke(<br>        f&quot;&quot;&quot;<br>        You are a senior research analyst.</pre><pre>        Original research question:<br>        {state[&#39;query&#39;]}</pre><pre>        Research findings:<br>        {research_data}</pre><pre>        Create a structured research report.</pre><pre>        Include:<br>        1. Executive summary<br>        2. Key findings<br>        3. Important comparisons<br>        4. Limitations and challenges<br>        5. Final conclusions</pre><pre>        Preserve relevant source URLs.<br>        Do not invent unsupported information.<br>        &quot;&quot;&quot;<br>    )</pre><pre>    return {<br>        &quot;report&quot;: response.content<br>    }</pre><p><strong>Explanation:</strong></p><p>The synthesis agent receives the findings from all researchers.</p><p>Its responsibility is to organize the information, identify common themes, highlight differences, and create a readable report.</p><p>Importantly, synthesis should not be treated as automatic fact verification. A production system should independently validate important claims and sources.</p><h3>Step 9: Assemble the LangGraph Workflow</h3><p>Now connect all the components.</p><pre>from langgraph.graph import (<br>    StateGraph,<br>    START,<br>    END<br>)</pre><pre>builder = StateGraph(ResearchState)</pre><pre>builder.add_node(<br>    &quot;planner&quot;,<br>    plan_research<br>)</pre><pre>builder.add_node(<br>    &quot;researcher&quot;,<br>    research_worker<br>)</pre><pre>builder.add_node(<br>    &quot;synthesizer&quot;,<br>    synthesize_research<br>)</pre><pre>builder.add_edge(<br>    START,<br>    &quot;planner&quot;<br>)</pre><pre>builder.add_conditional_edges(<br>    &quot;planner&quot;,<br>    dispatch_research<br>)</pre><pre>builder.add_edge(<br>    &quot;researcher&quot;,<br>    &quot;synthesizer&quot;<br>)</pre><pre>builder.add_edge(<br>    &quot;synthesizer&quot;,<br>    END<br>)</pre><pre>research_graph = builder.compile()</pre><p><strong>Explanation:</strong></p><p>The graph now contains three main stages:</p><ul><li>Planner creates research topics.</li><li>Researcher executes the dispatched tasks.</li><li>Synthesizer combines the findings.</li></ul><p>The conditional edge uses the list of Send objects to create parallel research tasks. The synthesis node runs after the dispatched researcher tasks have completed.</p><h3>Step 10: Run the Research System</h3><p>Our system is ready.</p><p>Let’s test it with a research question.</p><pre>result = research_graph.invoke({<br>    &quot;query&quot;: &quot;&quot;&quot;<br>    Analyze the applications of RAG in healthcare,<br>    its technical limitations, and evaluation methods.<br>    &quot;&quot;&quot;,<br>    &quot;topics&quot;: [],<br>    &quot;findings&quot;: [],<br>    &quot;report&quot;: &quot;&quot;<br>})</pre><pre>print(result[&quot;report&quot;])</pre><p>The system will:</p><ol><li>Receive the research question.</li><li>Generate independent research topics.</li><li>Dispatch research workers.</li><li>Allow workers to search the web using tool calling.</li><li>Collect their findings.</li><li>Generate a consolidated research report.</li></ol><p>You now have the foundation of a multi-agent research system.</p><h3>5. Visualizing the Architecture</h3><pre>flowchart TD<br>    A[User Research Query] --&gt; B[Planner Agent]<br>    B --&gt; C[Generate Research Topics]</pre><pre>    C --&gt; D[Research Worker 1]<br>    C --&gt; E[Research Worker 2]<br>    C --&gt; F[Research Worker 3]</pre><pre>    D &lt;--&gt; G[Web Search Tool]<br>    E &lt;--&gt; G<br>    F &lt;--&gt; G</pre><pre>    D --&gt; H[Shared Research State]<br>    E --&gt; H<br>    F --&gt; H</pre><pre>    H --&gt; I[Synthesis Agent]<br>    I --&gt; J[Final Research Report]</pre><p>The diagram highlights the most important design decision: independent research tasks run separately, but their results are collected in a shared workflow state.</p><h3>6. Real-World Applications</h3><p>This architecture can be extended to several practical applications:</p><ul><li><strong>Market research:</strong> Separate agents investigate competitors, pricing, customer feedback, and industry trends.</li><li><strong>Technical research:</strong> Agents investigate architectures, frameworks, benchmarks, and implementation approaches.</li><li><strong>Financial research:</strong> Agents examine company performance, market developments, and risk factors. Financial outputs still require appropriate verification.</li><li><strong>Academic research:</strong> Agents explore related work, methodologies, limitations, and research gaps.</li><li><strong>RAG evaluation:</strong> Agents investigate retrieval quality, evaluation techniques, hallucinations, and system performance.</li></ul><h3>7. Best Practices</h3><p>Building a multi-agent system introduces additional complexity. Keep these principles in mind:</p><ul><li><strong>Give every agent a clear responsibility:</strong> Avoid creating multiple agents that perform the same task.</li><li><strong>Keep state structured:</strong> Use typed schemas instead of passing large unorganized strings everywhere.</li><li><strong>Limit tool access:</strong> Give each agent only the tools it actually needs.</li><li><strong>Preserve source URLs:</strong> Research findings should retain traceable references.</li><li><strong>Control parallelism:</strong> Too many simultaneous agents can increase API costs and rate-limit errors.</li><li><strong>Add execution limits:</strong> Bound the number of research tasks, tool calls, and agent iterations.</li><li><strong>Handle failures:</strong> One failed researcher should not silently produce an incomplete report.</li><li><strong>Evaluate outputs:</strong> Check factual accuracy, source quality, completeness, and citation validity.</li><li><strong>Use human review:</strong> Require approval for high-impact research or decisions.</li></ul><h3>8. Common Mistakes</h3><ul><li>Creating multiple agents without defining distinct responsibilities.</li><li>Assuming parallel agents automatically produce better research.</li><li>Allowing agents to search indefinitely.</li><li>Ignoring rate limits and API costs.</li><li>Combining findings without preserving source references.</li><li>Treating LLM-generated summaries as verified facts.</li><li>Using shared state without appropriate reducers.</li><li>Forgetting that parallel execution introduces synchronization and failure-handling requirements.</li></ul><h3>9. Performance and Complexity</h3><p>A sequential research system waits for each researcher to finish before starting the next.</p><p>A parallel system can reduce total research time because independent tasks execute concurrently.</p><p>If three research tasks take approximately 10 seconds each, sequential execution could take around 30 seconds, while parallel execution may approach the duration of the slowest task.</p><p>These are illustrative estimates, not guaranteed performance results. Actual latency depends on provider response times, rate limits, search latency, and graph execution overhead.</p><p>Parallel execution can also increase simultaneous API usage and cost. More agents do not automatically mean better results.</p><h3>10. Summary: Key Takeaways</h3><p>In this project, we built a multi-agent research workflow using LangGraph and tool calling.</p><p>The important concepts are:</p><ul><li><strong>Multi-agent systems</strong> divide complex tasks among specialized agents.</li><li><strong>LangGraph</strong> manages workflow execution, state, and routing.</li><li><strong>Tool calling</strong> allows agents to interact with external services.</li><li><strong>Send</strong> enables parallel execution of independent tasks.</li><li><strong>Reducers</strong> help combine results from parallel workers.</li><li><strong>Synthesis</strong> transforms individual findings into a consolidated report.</li></ul><p>The bigger lesson is that building useful AI systems is not just about choosing a powerful LLM.</p><p>It is about designing the workflow around the problem.</p><p>A well-designed multi-agent system gives each component a clear responsibility, controls how information moves between agents, and makes the entire process easier to monitor, evaluate, and improve.</p><h3>Further Reading</h3><ul><li><a href="https://docs.langchain.com/oss/python/langgraph/overview">LangGraph Documentation</a></li><li><a href="https://docs.langchain.com/oss/python/langgraph/graph-api">LangGraph Graph API</a></li><li><a href="https://docs.langchain.com/oss/python/langchain/agents">LangChain Agents and Tool Calling</a></li><li><a href="https://docs.tavily.com/">Tavily Documentation</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LnMpGRgzq3Upg5-YEFTwyw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a84c7191734" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implement LLM Fallbacks: Build AI Applications That Handle Model Failures]]></title>
            <link>https://medium.com/@s.aditya1317/implement-llm-fallbacks-build-ai-applications-that-handle-model-failures-29961bd8a166?source=rss-2d1520186482------2</link>
            <guid isPermaLink="false">https://medium.com/p/29961bd8a166</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Aditya S]]></dc:creator>
            <pubDate>Mon, 09 Nov 2026 11:36:23 GMT</pubDate>
            <atom:updated>2026-11-09T11:36:23.171Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Imagine building an AI-powered application that works perfectly during development. Your LLM generates accurate responses, processes requests quickly, and handles user queries without problems.</p><p>Then, one day, your primary model becomes unavailable.</p><p>Maybe the provider experiences an outage. Perhaps you hit a rate limit, encounter a timeout, or receive an unexpected server error.</p><p>Your entire application stops working.</p><p>This is a common challenge when building applications with Large Language Models (LLMs). Unlike traditional functions, LLM calls depend on external services, network connections, provider availability, and usage limits.</p><p>One way to make these applications more reliable is to implement <strong>LLM fallbacks</strong>.</p><p>An LLM fallback allows your application to switch to another model or provider when the primary model cannot complete a request.</p><p>In this tutorial, we’ll build a practical fallback mechanism using Python and the OpenAI SDK.</p><h3>What You’ll Learn</h3><p>By the end of this tutorial, you’ll understand:</p><ul><li>What LLM fallbacks are and why they matter.</li><li>The difference between retries and fallbacks.</li><li>How to identify failures that should trigger a fallback.</li><li>How to implement a basic fallback mechanism.</li><li>How to add timeouts, retries, and error handling.</li><li>How to design a more reliable multi-provider architecture.</li></ul><h3>Prerequisites</h3><p>You should have:</p><ul><li>Basic Python knowledge.</li><li>A basic understanding of API calls.</li><li>Familiarity with LLMs and model providers.</li><li>Python installed on your system.</li><li>API keys for the model providers you want to use.</li></ul><p>We’ll use the OpenAI Python SDK for the primary model and a second provider as an example fallback.</p><h3>1. The Problem: What Happens When an LLM Fails?</h3><p>Consider an application that uses an LLM to summarize documents.</p><p>The request flow looks simple:</p><ol><li>A user submits a document.</li><li>Your application sends it to an LLM.</li><li>The model generates a summary.</li><li>Your application returns the result.</li></ol><p>But the model call introduces external dependencies.</p><p>For example:</p><ul><li><strong>Rate limit:</strong> Your application sends more requests than the provider allows.</li><li><strong>Timeout:</strong> The model takes too long to respond.</li><li><strong>Server error:</strong> The provider returns a temporary server-side failure.</li><li><strong>Service outage:</strong> The model endpoint becomes unavailable.</li><li><strong>Model error:</strong> The requested model is temporarily unavailable or no longer accessible.</li></ul><p>Without a fallback mechanism, these failures can directly affect the user experience.</p><p>A production application should not assume that one model will always be available.</p><p>Instead, it should have a recovery strategy.</p><h3>2. What Are LLM Fallbacks?</h3><p>An LLM fallback is a reliability mechanism that allows an application to use an alternative model when the primary model fails.</p><p>Think of it like having a backup internet connection.</p><p>If your primary connection stops working, your device switches to another connection instead of leaving you completely offline.</p><p>The same idea applies to LLM applications.</p><p>For example:</p><ul><li>Primary model: GPT model from Provider A.</li><li>Fallback model: Gemini model from Provider B.</li><li>Optional secondary fallback: Another available model.</li></ul><p>The application first attempts the primary model. If a recoverable failure occurs, it tries the configured alternative.</p><p><strong>Why do we need fallbacks?</strong></p><ul><li>Improve application availability.</li><li>Reduce dependency on a single provider.</li><li>Handle temporary outages and rate limits.</li><li>Maintain service continuity.</li><li>Improve resilience in production environments.</li></ul><p><strong>When should we use them?</strong></p><p>Fallbacks are useful in customer-support assistants, document-processing systems, RAG applications, AI agents, and other applications where model availability matters.</p><p><strong>When should we avoid them?</strong></p><p>A fallback is not automatically beneficial for every application. If an alternative model cannot meet the required accuracy, privacy, latency, or output-format requirements, switching to it may create a worse result than returning a controlled error.</p><h3>3. Retries vs. Fallbacks: Understanding the Difference</h3><p>These two techniques are related, but they solve different problems.</p><h3>Retries</h3><p>A retry means attempting the same operation again.</p><p>For example, if a model request fails because of a temporary network issue, your application waits briefly and sends the request again to the same model.</p><h3>Fallbacks</h3><p>A fallback means switching to an alternative model or provider after the primary model cannot complete the request.</p><p>For example, if the primary model repeatedly returns a server error, your application sends the request to another provider.</p><p>A reliable architecture often combines both:</p><ol><li>Retry temporary failures a limited number of times.</li><li>If the primary model still fails, attempt the fallback.</li><li>If all configured models fail, return a controlled error.</li></ol><p>One important detail: do not retry every error. Authentication failures, invalid requests, and malformed inputs generally require correction rather than another identical request.</p><h3>4. Understanding the Fallback Architecture</h3><p>Before writing code, let’s understand the components.</p><p>A basic fallback architecture contains:</p><ul><li><strong>Primary model:</strong> The model your application normally uses.</li><li><strong>Fallback model:</strong> An alternative model used when the primary fails</li><li><strong>Error handler:</strong> Identifies whether an error should trigger a fallback.</li><li><strong>Retry mechanism:</strong> Reattempts temporary failures.</li><li><strong>Response handler:</strong> Returns a successful result or a controlled failure.</li></ul><p>The key idea is that your application controls the decision-making process. It does not depend on the user to manually select another model.</p><h3>5. Step-by-Step Implementation</h3><p>Let’s build this functionality using Python.</p><h3>Step 1: Install Dependencies</h3><p>We’ll use the OpenAI SDK and Google’s Gen AI SDK.</p><pre>pip install openai google-genai python-dotenv</pre><p>Create a .env file:</p><pre>OPENAI_API_KEY=your_openai_api_key<br>GEMINI_API_KEY=your_gemini_api_key</pre><p>Never hardcode API keys directly into your source code or commit them to GitHub.</p><h3>Step 2: Configure the Model Providers</h3><p>First, initialize both providers.</p><pre>import os</pre><pre>from dotenv import load_dotenv<br>from openai import OpenAI<br>from google import genai</pre><pre>load_dotenv()</pre><pre>openai_client = OpenAI(<br>    api_key=os.getenv(&quot;OPENAI_API_KEY&quot;),<br>    timeout=20.0,<br>    max_retries=0<br>)</pre><pre>gemini_client = genai.Client(<br>    api_key=os.getenv(&quot;GEMINI_API_KEY&quot;)<br>)</pre><p><strong>Explanation:</strong></p><ul><li>OpenAI() initializes the primary provider.</li><li>genai.Client() initializes the fallback provider.</li><li>timeout=20.0 limits how long the OpenAI request can wait.</li><li>max_retries=0 disables automatic SDK retries so our example controls retry behavior explicitly.</li></ul><p>The SDKs have their own retry and timeout behavior. When building a production system, configure these deliberately to avoid accidentally multiplying retry attempts.</p><h3>Step 3: Create the Primary Model Function</h3><p>Now create a function that sends a prompt to the primary model.</p><pre>def call_primary_model(prompt):</pre><pre>    response = openai_client.responses.create(<br>        model=&quot;gpt-4.1-mini&quot;,<br>        input=prompt<br>    )</pre><pre>    return response.output_text</pre><p><strong>Explanation:</strong></p><p>This function sends the user’s prompt to the primary model and returns the generated text.</p><p>Keeping the model call inside a separate function makes it easier to test, monitor, and replace later.</p><h3>Step 4: Create the Fallback Model Function</h3><p>Next, define the alternative model.</p><pre>def call_fallback_model(prompt):</pre><pre>    response = gemini_client.models.generate_content(<br>        model=&quot;gemini-2.5-flash&quot;,<br>        contents=prompt<br>    )</pre><pre>    return response.text</pre><p><strong>Explanation:</strong></p><p>This function performs the same logical task using a different provider.</p><p>Notice that the application does not need to change its overall workflow. Only the underlying model call changes.</p><p>The exact model identifiers shown are examples. Check current provider documentation and account availability before deploying them.</p><h3>Step 5: Implement the Fallback Logic</h3><p>Now connect both functions.</p><pre>def generate_response(prompt):</pre><pre>    try:<br>        print(&quot;Using primary model...&quot;)</pre><pre>        return call_primary_model(prompt)</pre><pre>    except Exception as primary_error:</pre><pre>        print(&quot;Primary model failed:&quot;, primary_error)<br>        print(&quot;Switching to fallback model...&quot;)</pre><pre>        try:<br>            return call_fallback_model(prompt)</pre><pre>        except Exception as fallback_error:</pre><pre>            print(&quot;Fallback model failed:&quot;, fallback_error)</pre><pre>            raise RuntimeError(<br>                &quot;All configured LLM providers failed.&quot;<br>            ) from fallback_error</pre><p><strong>Explanation:</strong></p><p>This is the central fallback mechanism.</p><ul><li>The application first calls the primary model.</li><li>If it succeeds, its response is returned.</li><li>If it fails, the application attempts the fallback model.</li><li>If the fallback also fails, the application raises a controlled error.</li></ul><p>For a learning example, this demonstrates the basic idea.</p><p>However, catching every Exception is too broad for production. It can hide programming errors and trigger unnecessary provider switches. We&#39;ll improve that next.</p><h3>6. Improving the Fallback: Add Retries and Error Classification</h3><p>Not every failure should trigger a fallback.</p><p>For example:</p><ul><li>A temporary server error may justify a retry.</li><li>A rate limit may justify waiting or switching providers.</li><li>An authentication error usually requires fixing credentials.</li><li>An invalid request should not be sent repeatedly.</li></ul><p>Let’s implement a more controlled approach.</p><pre>import time</pre><pre>from openai import (<br>    APIConnectionError,<br>    APITimeoutError,<br>    RateLimitError,<br>    InternalServerError<br>)</pre><pre>RETRYABLE_ERRORS = (<br>    APIConnectionError,<br>    APITimeoutError,<br>    RateLimitError,<br>    InternalServerError<br>)<br></pre><pre>def call_with_retry(model_function, prompt, max_attempts=2):</pre><pre>    for attempt in range(max_attempts):</pre><pre>        try:<br>            return model_function(prompt)</pre><pre>        except RETRYABLE_ERRORS:</pre><pre>            if attempt == max_attempts - 1:<br>                raise</pre><pre>            wait_time = 2 ** attempt</pre><pre>            print(f&quot;Retrying in {wait_time} seconds...&quot;)<br>            time.sleep(wait_time)</pre><p><strong>Explanation:</strong></p><p>This function retries only selected temporary failures.</p><p>It uses exponential backoff:</p><ul><li>First retry: wait 1 second.</li><li>Second retry: wait 2 seconds.</li><li>Third retry: wait 4 seconds.</li></ul><p>Exponential backoff helps reduce pressure on an already struggling service.</p><p>For production systems, add jitter (a small random delay) to prevent many clients from retrying simultaneously.</p><p>Now connect retries with fallbacks:</p><pre>def generate_response(prompt):</pre><pre>    try:<br>        return call_with_retry(<br>            call_primary_model,<br>            prompt<br>        )</pre><pre>    except RETRYABLE_ERRORS:</pre><pre>        print(&quot;Primary model unavailable.&quot;)<br>        print(&quot;Trying fallback provider...&quot;)</pre><pre>        try:<br>            return call_with_retry(<br>                call_fallback_model,<br>                prompt<br>            )</pre><pre>        except Exception as error:</pre><pre>            raise RuntimeError(<br>                &quot;All model attempts failed.&quot;<br>            ) from error</pre><p>This implementation is more selective about primary-provider failures.</p><p>For a production implementation, define provider-specific retryable exceptions for the fallback too, and let non-retryable errors propagate rather than treating every failure as an outage.</p><h3>7. Visualizing the Fallback Workflow</h3><p>The following diagram illustrates how a request moves through the system.</p><pre>flowchart TD<br>    A[User Request] --&gt; B[Primary LLM]<br>    B --&gt; C{Request Successful?}</pre><pre>    C --&gt;|Yes| D[Return Response]<br>    C --&gt;|No| E{Retryable Error?}</pre><pre>    E --&gt;|Yes| F[Retry Primary Model]<br>    F --&gt; G{Retry Successful?}</pre><pre>    G --&gt;|Yes| D<br>    G --&gt;|No| H[Call Fallback LLM]</pre><pre>    E --&gt;|No| I[Return Controlled Error]</pre><pre>    H --&gt; J{Fallback Successful?}<br>    J --&gt;|Yes| D<br>    J --&gt;|No| K[Return Controlled Failure]</pre><p>The important point is that fallback is not simply another API call.</p><p>It is a decision-making process based on the type of failure and the availability of alternative models.</p><h3>8. Real-World Applications</h3><p>LLM fallbacks are useful across several AI application architectures.</p><p><strong>RAG applications</strong></p><p>If the primary model becomes unavailable after document retrieval, a compatible fallback can generate the answer using the same retrieved context.</p><p><strong>AI agents</strong></p><p>An agent may use a fallback model when its primary reasoning model becomes unavailable. However, tool permissions and execution rules must remain unchanged.</p><p><strong>Customer support systems</strong></p><p>A customer-support assistant can switch to an alternative model instead of immediately failing when its primary provider experiences an outage.</p><p><strong>Document processing</strong></p><p>Invoice extraction, document classification, and summarization systems can use alternative models to maintain processing continuity.</p><p>In all these cases, the fallback should preserve the application’s expected behavior — not merely return any response.</p><h3>9. Best Practices for Production Systems</h3><p>Implementing a basic fallback is straightforward. Building a dependable fallback architecture requires additional considerations.</p><ul><li><strong>Use compatible models:</strong> Ensure fallback models support the required context length, output format, and capabilities.</li><li><strong>Classify errors:</strong> Retry temporary failures, but do not retry invalid requests or authentication failures blindly.</li><li><strong>Set timeouts:</strong> Avoid allowing requests to wait indefinitely.</li><li><strong>Use exponential backoff with jitter:</strong> Reduce retry storms during provider outages.</li><li><strong>Monitor provider health:</strong> Track latency, errors, rate limits, and fallback frequency.</li><li><strong>Control costs:</strong> A fallback provider may have different pricing.</li><li><strong>Validate outputs:</strong> Different models can produce different structures and response quality.</li><li><strong>Protect sensitive data:</strong> Check provider data-handling policies before sending user information to another provider.</li><li><strong>Set a total deadline:</strong> Ensure retries and fallback attempts fit within the application’s response-time budget.</li><li><strong>Use circuit breakers:</strong> Temporarily stop sending requests to a provider that is consistently failing.</li></ul><p>A circuit breaker is especially useful in larger applications. Instead of discovering the same outage through repeated failed requests, the system temporarily marks the provider as unavailable and routes eligible requests elsewhere.</p><h3>10. Common Mistakes to Avoid</h3><ul><li>Retrying every error without checking its type.</li><li>Switching providers for invalid input or authentication failures.</li><li>Using fallback models with incompatible capabilities.</li><li>Ignoring differences in model response quality.</li><li>Forgetting to configure timeouts.</li><li>Allowing unlimited retries.</li><li>Logging API keys, personal information, or complete sensitive prompts.</li><li>Assuming a fallback response is automatically correct.</li><li>Failing to monitor how often fallback activation occurs.</li></ul><p>Remember: <strong>availability does not guarantee correctness.</strong> A fallback model can successfully return a response while still producing inaccurate information.</p><h3>11. Performance and Cost Considerations</h3><p>Fallbacks improve resilience, but they introduce additional trade-offs.</p><p><strong>Latency:</strong> If the primary model times out before the fallback starts, users experience both attempts. Set an overall deadline and allocate time carefully between providers.</p><p><strong>Cost:</strong> A request that reaches two providers may cost more than a successful primary-only request.</p><p><strong>Reliability:</strong> If providers have independent failure modes, using multiple providers can improve availability. However, shared infrastructure dependencies can reduce that benefit.</p><p><strong>Consistency:</strong> Different models may interpret prompts differently. For structured tasks, validate the response against a common schema and test each fallback model against the same evaluation dataset.</p><p>A production fallback strategy should balance availability, latency, cost, privacy, and response quality.</p><h3>12. Summary: Key Takeaways</h3><p>LLM failures are unavoidable when applications depend on external model providers. A reliable AI application should be designed to handle those failures rather than assume they will never happen.</p><p>Remember these key ideas:</p><ul><li><strong>Retries</strong> repeat a request to the same provider.</li><li><strong>Fallbacks</strong> switch to an alternative model or provider.</li><li>Error classification determines which failures should trigger recovery.</li><li>Timeouts and exponential backoff help control request behavior.</li><li>Multiple providers can reduce single-provider dependency.</li><li>Output validation and monitoring are essential for production reliability.</li></ul><p>The goal is not to make your LLM application depend on as many models as possible.</p><p>The goal is to build an application that can handle failures gracefully while maintaining acceptable accuracy, latency, cost, and security.</p><p><strong>A production-ready AI system is not one that never fails. It is one that knows how to respond when something fails.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GdXSNwL0FXVQAKTW0oVmmQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29961bd8a166" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>