<?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 Duhamasoodi on Medium]]></title>
        <description><![CDATA[Stories by Duhamasoodi on Medium]]></description>
        <link>https://medium.com/@duhamasoodi04?source=rss-2585f9d0a547------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gNDg1HM00cGGgcdbpVmDCA.jpeg</url>
            <title>Stories by Duhamasoodi on Medium</title>
            <link>https://medium.com/@duhamasoodi04?source=rss-2585f9d0a547------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 11:36:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@duhamasoodi04/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[MCP (Model Context Protocol), the USB-C of AI Applications]]></title>
            <link>https://medium.com/@duhamasoodi04/mcp-model-context-protocol-the-usb-c-of-ai-applications-b0d929c2b9dd?source=rss-2585f9d0a547------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0d929c2b9dd</guid>
            <category><![CDATA[mcps]]></category>
            <category><![CDATA[llm-applications]]></category>
            <dc:creator><![CDATA[Duhamasoodi]]></dc:creator>
            <pubDate>Tue, 10 Nov 2026 15:17:22 GMT</pubDate>
            <atom:updated>2026-11-10T15:18:47.640Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Today I learned how AI applications connect to external tools and data through one common standard. I’ve also filled in the parts that are easy to miss in beginner notes: the three MCP primitives, the connection handshake, a working Python server, and security.</em></p><h3>1. What Is MCP?</h3><p><strong>MCP (Model Context Protocol)</strong> is an open standard that lets AI applications connect to external tools and data sources through a common interface. Think of it as <strong>USB-C for AI apps</strong>.</p><p>Without MCP, every AI app needs a custom integration for every service (GitHub, Google Drive, databases, Slack, Google Calendar). With 5 apps and 5 services, that’s up to 25 separate integrations. With MCP, each side implements the standard once and they all work together.</p><blockquote><strong><em>Remember:</em></strong><em> MCP is a </em>protocol<em>, not a server. It’s the set of communication rules.</em></blockquote><h3>2. The Main Components</h3><p>Component Role <strong>Host</strong> The AI application the user interacts with (a chat app, an IDE, your own agent) <strong>MCP Client</strong> Lives inside the host, connects to one MCP server and sends requests <strong>MCP Server</strong> Exposes tools and resources and executes requests <strong>LLM</strong> Understands the request and decides which tool is needed</p><p>A host usually runs one client per server it connects to.</p><pre>User<br>  |<br>  v<br>LLM (decides which tool to use)<br>  |<br>  v<br>MCP Client (sends request)<br>  |<br>  v<br>MCP Server (executes tool)<br>  |<br>  v<br>Result returned to LLM<br>  |<br>  v<br>Final Answer</pre><p><strong>Example:</strong> the user asks, <em>“Find all open GitHub issues.”</em> The LLM decides it needs GitHub data, the MCP client talks to the GitHub MCP server, the server runs a tool like search_github_issues() and returns the results, and the LLM writes the final answer.</p><p><strong>Easy memory trick:</strong></p><ul><li>LLM = decides</li><li>MCP Client = requests</li><li>MCP Server = provides and executes</li><li>MCP = the communication rules</li></ul><h3>3. What Can a Server Offer? The Three Primitives</h3><p>This was the part missing from my first notes. An MCP server can expose three kinds of things:</p><p>Primitive What it is Who controls it <strong>Tools</strong> Functions the model can call (query a database, create an issue) The model <strong>Resources</strong> Read-only data and context (files, database records, documents) The application <strong>Prompts</strong> Reusable prompt templates the user can pick The user</p><p>Tools get the most attention, but resources and prompts are part of the standard too.</p><h3>4. Transport Types</h3><p>A <strong>transport</strong> is the method the client and server use to talk. MCP defines two standard ones.</p><h3>A. Streamable HTTP</h3><p>Used when the server is reachable through a <strong>URL</strong>, over a network.</p><p>Term Meaning HTTP A standard way for computers to communicate over a network URL The address of a server or resource Request A message sent by the client Response The reply from the server</p><pre>config = {<br>    &quot;transport&quot;: &quot;http&quot;,<br>    &quot;url&quot;: &quot;https://api.mycompany.com/mcp&quot;<br>}</pre><pre>MCP Client  --HTTP Request--&gt;  MCP Server (URL)<br>MCP Client  &lt;--HTTP Response-- MCP Server (URL)</pre><p>The server can be local (your own machine) or remote (cloud). Streamable HTTP is the usual choice for remote servers.</p><blockquote><strong><em>Good to know:</em></strong><em> Streamable HTTP replaced the older HTTP+SSE transport, so you may still see SSE in older tutorials.</em></blockquote><h3>B. stdio</h3><p>Used when the server is a <strong>separate program started by your application</strong>. No URL is involved. The client launches the server and talks to it through input/output streams.</p><p>Term Meaning Process A program that is currently running Parent / child process The program that starts another / the program that was started stdin Standard input, where a program receives data stdout Standard output, where a program sends data stderr Standard error, where error messages go</p><pre>config = {<br>    &quot;transport&quot;: &quot;stdio&quot;,<br>    &quot;command&quot;: &quot;python&quot;,<br>    &quot;args&quot;: [&quot;/path/to/server.py&quot;]<br>}</pre><pre>Parent Application --starts--&gt; MCP Server (child process)<br>Parent Application &lt;-- stdin / stdout --&gt; MCP Server</pre><blockquote><strong><em>Gotcha:</em></strong><em> with stdio, your server must never </em><em>print() ordinary text to stdout, because stdout carries the protocol messages and stray output corrupts them. Send logs to </em><strong><em>stderr</em></strong><em> instead.</em></blockquote><blockquote><strong><em>Note:</em></strong><em> these dictionaries only represent configuration. Real connections use an MCP client library (see section 7).</em></blockquote><h3>HTTP vs stdio</h3><p>Feature Streamable HTTP stdio Communication Over a network Input/output streams Connection URL Local process Server Accessed through an endpoint Started by the application Common use Remote/cloud servers Local servers</p><h3>5. The Connection Lifecycle</h3><p>Another gap in my first notes: a client doesn’t jump straight to calling tools. There’s a short handshake first.</p><ol><li><strong>Initialize:</strong> the client sends an initialize request with its protocol version and capabilities.</li><li><strong>Server replies</strong> with its own version and capabilities (for example, “I offer tools and resources”).</li><li><strong>Initialized:</strong> the client sends an initialized notification.</li><li><strong>Normal operation:</strong> the client lists and calls tools, reads resources, and so on.</li></ol><p>This is how both sides agree on what they support before doing any real work.</p><h3>6. JSON-RPC Messages</h3><p>MCP messages use <strong>JSON-RPC</strong>, a format for sending requests and responses as JSON. Requests carry an id so each response can be matched to its request. (One-way <em>notifications</em>, like the initialized one above, carry no id and get no reply.)</p><p><strong>Discover tools</strong></p><pre>{ &quot;jsonrpc&quot;: &quot;2.0&quot;, &quot;method&quot;: &quot;tools/list&quot;, &quot;id&quot;: 1 }</pre><p><strong>Server response</strong></p><pre>{<br>  &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>  &quot;result&quot;: {<br>    &quot;tools&quot;: [<br>      { &quot;name&quot;: &quot;query_database&quot; }<br>    ]<br>  },<br>  &quot;id&quot;: 1<br>}</pre><p>A real response also includes each tool’s description and inputSchema (which describes its arguments). That&#39;s how the LLM knows when and how to use it.</p><p><strong>Call a tool</strong></p><pre>{<br>  &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>  &quot;method&quot;: &quot;tools/call&quot;,<br>  &quot;params&quot;: {<br>    &quot;name&quot;: &quot;query_database&quot;,<br>    &quot;arguments&quot;: { &quot;query&quot;: &quot;SELECT * FROM customers&quot; }<br>  },<br>  &quot;id&quot;: 2<br>}</pre><p>The server runs the tool and replies with a result containing the tool’s output.</p><h3>7. Building One in Python</h3><p>Here’s a tiny server using the official Python SDK’s FastMCP helper:</p><pre># server.py<br>from mcp.server.fastmcp import FastMCP</pre><pre>mcp = FastMCP(&quot;weather&quot;)</pre><pre>@mcp.tool()<br>def get_weather(city: str) -&gt; str:<br>    &quot;&quot;&quot;Get the current temperature for a city.&quot;&quot;&quot;<br>    temps = {&quot;Seattle&quot;: 62, &quot;Paris&quot;: 18, &quot;Tokyo&quot;: 24}<br>    return f&quot;Current temperature in {city}: {temps.get(city, 72)}°F&quot;</pre><pre>if __name__ == &quot;__main__&quot;:<br>    mcp.run(transport=&quot;stdio&quot;)</pre><p>The function name, type hints, and docstring become the tool’s name, input schema, and description. This is the same idea as the @tool decorator from earlier posts.</p><p>To use it from LangChain, the langchain-mcp-adapters package connects to servers and turns their tools into LangChain tools:</p><pre>from langchain_mcp_adapters.client import MultiServerMCPClient</pre><pre>client = MultiServerMCPClient({<br>    &quot;weather&quot;: {<br>        &quot;transport&quot;: &quot;stdio&quot;,<br>        &quot;command&quot;: &quot;python&quot;,<br>        &quot;args&quot;: [&quot;server.py&quot;],<br>    }<br>})</pre><pre>tools = await client.get_tools()</pre><p>From there you can pass tools to an agent, or bind them to a model with bind_tools(), exactly like the tools from earlier days. Config details such as the exact transport names for HTTP can vary between versions, so check the current docs.</p><h3>8. Security: Don’t Skip This</h3><p>MCP is powerful because it connects an LLM to real systems, so be careful:</p><ul><li><strong>Only connect to servers you trust.</strong> A server’s tool descriptions and outputs go into the LLM’s context, so a malicious server can attempt prompt injection.</li><li><strong>Use least privilege.</strong> Give tools only the access they need (read-only database users, for example).</li><li><strong>Keep a human in the loop</strong> for dangerous actions like deleting data or sending emails.</li><li><strong>Use proper authentication</strong> for remote servers.</li></ul><p>This connects back to the idea from my function-calling post: the LLM can <em>request</em> an action, but your code decides whether to <em>run</em> it.</p><h3>Key Takeaways</h3><ol><li>MCP is a communication protocol, not a server.</li><li>The host runs MCP clients, which connect to MCP servers.</li><li>Servers expose tools, resources, and prompts.</li><li>The LLM decides which tools to use.</li><li>Transports define how client and server communicate: Streamable HTTP for URLs, stdio for local processes.</li><li>A connection starts with an initialize handshake, then tools are discovered with tools/list and run with tools/call.</li><li>Treat MCP servers like any other code you give access to your systems.</li></ol><h3>Interview Questions</h3><p><strong>What is MCP?</strong><br> An open standard that lets AI applications connect to external tools and data sources through a common protocol.</p><p><strong>What is an MCP client?</strong><br> The component that connects to an MCP server, discovers its tools, and sends requests to run them.</p><p><strong>What is an MCP server?</strong><br> A program that exposes tools, resources, and prompts through MCP and handles client requests.</p><p><strong>HTTP vs stdio?</strong><br> Streamable HTTP communicates over a network using a URL. stdio communicates through standard input/output between local processes.</p><p><strong>What are the three MCP primitives?</strong><br> Tools (model-controlled actions), resources (application-controlled data), and prompts (user-controlled templates).</p><p><strong>What is JSON-RPC?</strong><br> A message format for exchanging requests and responses as JSON.</p><h3>Conclusion</h3><p>MCP does for AI tools what USB-C did for chargers: build the integration once, and it works everywhere. Now that I understand the roles, the transports, and the handshake, I’m ready to build my own server.</p><p><em>Thanks for reading!</em></p><h3><strong>REFERENCE:</strong></h3><p><a href="https://github.com/microsoft/langchainjs-for-beginners/tree/main/06-mcp">https://github.com/microsoft/langchainjs-for-beginners/tree/main/06-mcp</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0d929c2b9dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LangChain Agents, Middleware, and Fixing What Breaks]]></title>
            <link>https://medium.com/@duhamasoodi04/langchain-agents-middleware-and-fixing-what-breaks-57a4fa8e8100?source=rss-2585f9d0a547------2</link>
            <guid isPermaLink="false">https://medium.com/p/57a4fa8e8100</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[langchain-agents]]></category>
            <dc:creator><![CDATA[Duhamasoodi]]></dc:creator>
            <pubDate>Mon, 09 Nov 2026 15:40:07 GMT</pubDate>
            <atom:updated>2026-11-09T15:40:07.389Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Today I learned how middleware makes agents more reliable, how to keep long conversations affordable with summarization, and how to troubleshoot the most common agent problems. As before, I converted the JavaScript concepts into Python.</em></p><h3>1. What Is Middleware?</h3><p>Middleware is an extra layer that sits between the agent and the model or tools. It lets you add behaviour <strong>without changing the agent’s main logic</strong>.</p><p>Typical uses:</p><ul><li>Logging</li><li>Error handling</li><li>Model selection</li><li>Security checks</li></ul><h3>Custom Middleware: Dynamic Model Selection</h3><p>A neat trick is to pick the model based on how long the conversation is:</p><ul><li><strong>Short conversation</strong> → use a basic (cheaper) model</li><li><strong>Long conversation</strong> (more than 10 messages) → use a more capable model</li></ul><pre>def dynamic_model_selection(request):<br>    message_count = len(request[&quot;messages&quot;])</pre><pre>    if message_count &gt; 10:<br>        return capable_model<br>    return basic_model</pre><blockquote><strong><em>Note:</em></strong><em> this is a simplified Python version of the selection logic, not a direct LangChain middleware implementation.</em></blockquote><h3>Custom Middleware: Error Handling</h3><p>Tools fail sometimes. In JavaScript you’d use try-catch; in Python it&#39;s try-except:</p><pre>try:<br>    result = calculator_tool.invoke({&quot;expression&quot;: &quot;5+5&quot;})<br>    print(result)<br>except Exception as error:<br>    print(f&quot;Tool failed: {error}&quot;)<br>    print(&quot;Let me try a different approach.&quot;)</pre><p>This stops a single failing tool from crashing the whole application.</p><h3>2. Built-in Middleware: Summarization</h3><p>LangChain ships with summarizationMiddleware(), which automatically summarizes older messages in long conversations.</p><p><strong>Why it’s useful:</strong></p><ul><li>Reduces token usage</li><li>Reduces API costs</li><li>Keeps conversations within the model’s context window</li><li>Preserves the important information</li></ul><h3>How It Works</h3><p>Instead of sending the whole conversation every time, older messages are replaced with a summary while recent messages stay as they are.</p><p><strong>Before summarization:</strong></p><pre>User: Explain AI.<br>Assistant: ...</pre><pre>User: Explain machine learning.<br>Assistant: ...</pre><pre>User: Explain deep learning.<br>Assistant: ...</pre><p><strong>After summarization:</strong></p><pre>Summary:<br>- AI was discussed.<br>- Machine learning was explained.<br>- Deep learning was discussed.</pre><pre>Recent messages:<br>User: Explain neural networks.<br>Assistant: ...</pre><h3>Key Configuration Options</h3><p><strong>1. Trigger: when should summarization happen?</strong></p><pre>trigger = {<br>    &quot;tokens&quot;: 200,<br>    &quot;messages&quot;: 4<br>}</pre><ul><li>A single object uses <strong>AND</strong> logic: both conditions must be met</li><li>An array of objects uses <strong>OR</strong> logic: either condition can trigger it</li></ul><p><strong>2. Keep: what should be preserved?</strong></p><pre>keep = {<br>    &quot;messages&quot;: 2<br>}</pre><p>This keeps the latest two messages after summarization.</p><h3>The Concept in Python</h3><pre>def summarize_conversation(messages, summary_model):<br>    if len(messages) &gt; 4:<br>        old_messages = messages[:-2]<br>        recent_messages = messages[-2:]</pre><pre>        summary = summary_model.invoke(<br>            f&quot;Summarize this conversation: {old_messages}&quot;<br>        )</pre><pre>        return [summary] + recent_messages</pre><pre>    return messages</pre><blockquote><strong><em>Note:</em></strong><em> this demonstrates the idea. It is not how LangChain’s built-in middleware is actually implemented.</em></blockquote><h3>3. Agent Troubleshooting: Six Common Problems</h3><p>Problem Cause Solution tool_calls undefined Tools aren&#39;t attached to the model Bind tools with bind_tools() Infinite loop Agent doesn&#39;t know when to stop Add a stopping condition Tool not found Tool names don&#39;t match Use exactly the same name Wrong tool chosen Tool descriptions are unclear Write specific descriptions JSON parsing error Tool arguments contain invalid JSON Use try-except Same tool repeated Tool output is unclear Return descriptive results</p><h3>Python Fixes</h3><p><strong>1. Bind your tools</strong></p><pre>model_with_tools = model.bind_tools([calculator_tool])</pre><p>This tells the model which tools are available.</p><p><strong>2. Add a stopping condition</strong></p><pre>if not response.tool_calls:<br>    break</pre><p>When the model requests no more tools, the agent loop ends. (This sits inside the loop that keeps calling the model.)</p><p><strong>3. Handle errors</strong></p><pre>try:<br>    result = calculator_tool.invoke({&quot;number&quot;: 10})<br>except Exception as error:<br>    print(f&quot;Error: {error}&quot;)</pre><p><strong>4. Return descriptive output</strong></p><pre>return &quot;The calculation result is 42. This is the answer to 6 * 7.&quot;</pre><p>A result like this helps the agent understand what happened and decide what to do next, instead of calling the same tool again.</p><h3>4. Key Concepts at a Glance</h3><p>Concept What it does createAgent() Creates an AI agent createMiddleware() Creates custom middleware wrapModelCall Intercepts model calls wrapToolCall Intercepts tool calls bindTools() Connects tools to a model summarizationMiddleware() Summarizes long conversations try-catch / try-except Handles errors maxIterations Limits agent execution attempts</p><h3>Conclusion</h3><p>Here’s what I took away from today:</p><ol><li>Custom middleware controls agent behaviour without touching the core logic</li><li>Models can be selected dynamically based on conversation length</li><li>Tool errors can be handled without crashing the app</li><li>Summarization middleware cuts conversation history and token costs</li><li>Most agent bugs (infinite loops, wrong tools, bad arguments) have simple, predictable fixes</li></ol><p><strong>Main takeaway:</strong> middleware is what makes agents production-ready. It adds model selection, error handling, logging, and summarization without changing what the agent fundamentally does.</p><p><em>Thanks for reading! See you in tomorrow’s post.</em></p><h3><strong>REFERENCES:</strong></h3><p>[1] Microsoft, “Agents,” LangChain.js for Beginners. [Online]. Available: <a href="https://github.com/microsoft/langchainjs-for-beginners/tree/main/05-agents?utm_source=chatgpt.com">https://github.com/microsoft/langchainjs-for-beginners/tree/main/05-agents</a>. [Accessed: Nov. 9, 2026].</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57a4fa8e8100" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Function Calling and Tools in LangChain, or How an LLM Learns to Use a Calculator]]></title>
            <link>https://medium.com/@duhamasoodi04/function-calling-and-tools-in-langchain-or-how-an-llm-learns-to-use-a-calculator-385b6dc33a52?source=rss-2585f9d0a547------2</link>
            <guid isPermaLink="false">https://medium.com/p/385b6dc33a52</guid>
            <category><![CDATA[llm-function-calling]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Duhamasoodi]]></dc:creator>
            <pubDate>Sun, 08 Nov 2026 09:28:49 GMT</pubDate>
            <atom:updated>2026-11-08T09:28:49.993Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Today I learned how LLMs go beyond generating text and actually use tools: calculators, weather lookups, database queries, API calls. I followed the Microsoft “LangChain.js for Beginners” course and converted the examples into Python.</em></p><h3>1. What Is Function Calling?</h3><p>Function calling lets an LLM use external functions (tools) to get things done. Instead of trying to do everything itself, the model decides which tool is needed and <em>requests</em> that it be run.</p><p>There are three stages:</p><p><strong>1. The LLM plans.</strong></p><ul><li>Understands the user’s request</li><li>Decides which function to use</li><li>Generates a structured function call with arguments (often JSON)</li><li><strong>Does not execute the function itself</strong></li></ul><p><strong>2. Your code does the work.</strong></p><ul><li>Receives the function call</li><li>Executes the function (calculation, API call, database query)</li><li>Sends the result back to the LLM</li></ul><p><strong>3. The LLM communicates.</strong></p><ul><li>Receives the result</li><li>Turns it into a natural-language answer for the user</li></ul><h3>A Simple Example</h3><p>The user asks: <em>“What is 25 × 17?”</em></p><ol><li>The LLM decides to use a calculator</li><li>It generates a tool call with the expression 25 * 17</li><li>Python runs the calculation</li><li>The result (425) goes back to the LLM</li><li>The LLM replies: “25 × 17 = 425.”</li></ol><h3>2. Why Does the Separation Matter?</h3><p>Keeping the LLM’s planning separate from code execution gives you security and control:</p><ul><li><strong>Security:</strong> the LLM can’t directly run arbitrary operations</li><li><strong>Control:</strong> developers decide which tools exist</li><li><strong>Validation:</strong> inputs can be checked before anything runs</li><li><strong>Permissions:</strong> dangerous operations can require approval</li><li><strong>Error handling:</strong> failures can be handled safely</li></ul><p>If a user asks to “delete all files”, your application can simply refuse.</p><blockquote><strong><em>Key idea:</em></strong><em> the LLM can </em>request<em> an action, but your code decides whether to </em>execute<em> it.</em></blockquote><h3>3. Creating Tools in LangChain</h3><p>In LangChain.js, tools are built with the tool() function and <strong>Zod</strong> schemas. Zod is a JavaScript/TypeScript library for validating data. For example, z.string() means the value must be a string.</p><p>In Python, the equivalent is simply a type hint: expression: str.</p><pre>from langchain.tools import tool</pre><pre>@tool<br>def calculator(expression: str) -&gt; str:<br>    &quot;&quot;&quot;Perform mathematical calculations.&quot;&quot;&quot;<br>    result = eval(expression)<br>    return f&quot;The result is: {result}&quot;</pre><p>What’s happening:</p><ul><li>@tool registers the function as a tool the AI can use</li><li>expression: str says the input must be text</li><li>The docstring tells the LLM what the tool does</li><li>return sends the result back</li></ul><blockquote><strong><em>Warning:</em></strong><em> </em><em>eval() is only here to keep the example simple. Never use it on untrusted input in a real application. Use a safe math expression parser instead.</em></blockquote><h3>4. Async and Await</h3><p>async lets a function do slow work (API calls, database queries) without blocking everything else. await pauses until that work finishes.</p><p>In Python:</p><pre>import asyncio</pre><pre>async def greet():<br>    return &quot;Hello&quot;</pre><pre>async def main():<br>    result = await greet()<br>    print(result)</pre><pre>asyncio.run(main())</pre><p>Output:</p><pre>Hello</pre><p>Async matters most when you’re working with APIs, databases, and web requests.</p><h3>5. Binding and Invoking Tools</h3><p>To make tools available to the model, LangChain.js uses .bindTools(). In Python it&#39;s bind_tools():</p><pre>from langchain_openai import ChatOpenAI</pre><pre>model = ChatOpenAI(model=&quot;gpt-4o-mini&quot;)</pre><pre>model_with_tools = model.bind_tools([calculator])</pre><pre>response = model_with_tools.invoke(&quot;What is 25 * 17?&quot;)<br>print(response.tool_calls)</pre><p>The model returns a structured request like this:</p><pre>{<br>  &quot;name&quot;: &quot;calculator&quot;,<br>  &quot;args&quot;: {<br>    &quot;expression&quot;: &quot;25 * 17&quot;<br>  }<br>}</pre><p>The important part: <strong>this is only a request.</strong> The calculation hasn’t happened yet.</p><h3>6. A Complete Example: The Weather Tool</h3><p>Here’s the full flow with a tool that returns a city’s temperature:</p><pre>from langchain.tools import tool<br>from langchain_openai import ChatOpenAI</pre><pre># Step 1: Create the weather tool<br>@tool<br>def get_weather(city: str) -&gt; str:<br>    &quot;&quot;&quot;Get current weather for a city.&quot;&quot;&quot;<br>    temps = {<br>        &quot;Seattle&quot;: 62,<br>        &quot;Paris&quot;: 18,<br>        &quot;Tokyo&quot;: 24<br>    }<br>    temp = temps.get(city, 72)<br>    return f&quot;Current temperature in {city}: {temp}°F&quot;</pre><pre># Step 2: Create the model<br>model = ChatOpenAI(model=&quot;gpt-4o-mini&quot;)</pre><pre># Step 3: Bind the tool to the model<br>model_with_tools = model.bind_tools([get_weather])</pre><pre># Step 4: Send the user&#39;s question<br>response = model_with_tools.invoke(&quot;What&#39;s the weather in Seattle?&quot;)</pre><pre># Step 5: Check the tool calls<br>print(response.tool_calls)</pre><pre># Step 6: Execute the tool<br>tool_call = response.tool_calls[0]<br>tool_result = get_weather.invoke(tool_call[&quot;args&quot;])<br>print(tool_result)</pre><p>Walking through it:</p><ul><li><strong>Step 5:</strong> the LLM generates a tool call:</li></ul><pre>{<br>  &quot;name&quot;: &quot;get_weather&quot;,<br>  &quot;args&quot;: { &quot;city&quot;: &quot;Seattle&quot; }<br>}</pre><ul><li><strong>Step 6:</strong> your Python code runs the tool and gets:</li></ul><pre>Current temperature in Seattle: 62°F</pre><p>That result can then be sent back to the LLM so it can write a friendly final answer. (The temperatures here are hard-coded sample data. A real tool would call a weather API.)</p><h3>7. Best Practices for Building Tools</h3><p>Practice Meaning Clear descriptions Explain exactly what the tool does Descriptive parameter names Use city, not x Error handling Handle failures without crashing the app Validation Check inputs before running anything</p><h3>Error Handling</h3><pre>@tool<br>def safe_tool(param: str) -&gt; str:<br>    &quot;&quot;&quot;Performs an operation safely.&quot;&quot;&quot;<br>    try:<br>        result = dangerous_operation(param)<br>        return result<br>    except Exception as error:<br>        return f&quot;Error: {error}. Please try again.&quot;</pre><h3>Input Validation with Pydantic</h3><pre>from pydantic import BaseModel, EmailStr, Field</pre><pre>class EmailInput(BaseModel):<br>    email: EmailStr<br>    subject: str = Field(min_length=1)<br>    body: str</pre><ul><li>EmailStr checks the email format</li><li>min_length=1 prevents an empty subject</li><li>body holds the email content</li></ul><h3>8. Custom Tools vs Provider Built-in Tools</h3><p>AI providers also ship ready-made tools:</p><p>Provider Built-in tools OpenAI Web search, file search, code interpreter, image generation Anthropic Web search, web fetch, text editor, computer use Custom tools Provider built-in tools Created by developers Provided by AI providers You write the execution logic Provider manages execution Full control Limited configuration Great for business-specific tasks Great for common tasks</p><p><strong>Use custom tools for:</strong> company databases, customer invoices, membership details, business-specific operations.</p><p><strong>Use built-in tools for:</strong> web search, file search, running code, generating images.</p><p>For example, a carpet business could build a tool to look up invoices:</p><pre>@tool<br>def get_invoice(invoice_id: str) -&gt; str:<br>    &quot;&quot;&quot;Retrieve an invoice using its ID.&quot;&quot;&quot;<br>    # Database query goes here<br>    return &quot;Invoice details&quot;</pre><p>It’s a custom tool because we write the logic that talks to our own database.</p><h3>9. Quick Revision</h3><p>Concept Meaning Function calling Lets LLMs request external functions Tool A function an LLM can use tool() Creates a tool in LangChain.js @tool Creates a tool in LangChain Python Zod JavaScript input validation library Pydantic Python data validation library async / await Define and wait on asynchronous operations bindTools() / bind_tools() Makes tools available to the LLM invoke() Sends a request to the model, or runs a tool tool_calls The LLM&#39;s requested tool calls Tool execution Actually running the requested function</p><h3>Conclusion</h3><p>The big idea from today: <strong>the LLM decides <em>what</em> should happen, and your application decides <em>whether and how</em> it happens.</strong> Once the tool returns a result, the LLM uses it to write a helpful answer. That separation is what makes tool-using AI both powerful and safe to build with.</p><p><strong>Reference:</strong> Microsoft, <a href="https://github.com/microsoft/langchainjs-for-beginners/tree/main/04-function-calling-tools">LangChain.js for Beginners: Function Calling &amp; Tools</a></p><p><em>Note: the examples are converted from JavaScript to Python, and some implementation details differ between the two libraries.</em></p><p><em>Thanks for reading! See you in tomorrow’s post.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=385b6dc33a52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prompts, Templates, and Getting Structured JSON from an LLM with LangChain]]></title>
            <link>https://medium.com/@duhamasoodi04/prompts-templates-and-getting-structured-json-from-an-llm-with-langchain-1b9eeadb6600?source=rss-2585f9d0a547------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b9eeadb6600</guid>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[writing-prompts]]></category>
            <dc:creator><![CDATA[Duhamasoodi]]></dc:creator>
            <pubDate>Sat, 07 Nov 2026 14:01:10 GMT</pubDate>
            <atom:updated>2026-11-07T14:01:10.648Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Today I explored how LangChain handles prompts and messages, how to build reusable prompt templates, and how to turn messy text into clean, structured data. I took the JavaScript examples from the Microsoft LangChain.js beginner course and rewrote them in Python using LangChain and Pydantic.</em></p><h3>1. Messages vs Prompt Templates</h3><p>LangChain gives you two ways to send instructions to a model.</p><h3>Messages</h3><p>Messages are direct instructions or conversation turns. There are three types:</p><ul><li>SystemMessage: defines the AI&#39;s role or behaviour</li><li>HumanMessage: the user&#39;s message</li><li>AIMessage: the AI&#39;s previous response</li></ul><pre>from langchain_core.messages import SystemMessage, HumanMessage</pre><pre>messages = [<br>    SystemMessage(content=&quot;You are a helpful translator.&quot;),<br>    HumanMessage(content=&quot;Translate &#39;Hello, world!&#39; to French.&quot;)<br>]</pre><pre>response = model.invoke(messages)<br>print(response.content)</pre><h3>Prompt Templates</h3><p>Templates are reusable prompts with placeholders like {text} and {language}. Instead of writing near-identical prompts again and again, you write one template and fill in different values.</p><pre>from langchain_core.prompts import ChatPromptTemplate</pre><pre>template = ChatPromptTemplate.from_messages([<br>    (&quot;system&quot;, &quot;You are a helpful translator.&quot;),<br>    (&quot;human&quot;, &quot;Translate &#39;{text}&#39; to {language}.&quot;)<br>])</pre><pre>chain = template | model</pre><pre>response = chain.invoke({<br>    &quot;text&quot;: &quot;Hello, world!&quot;,<br>    &quot;language&quot;: &quot;French&quot;<br>})</pre><pre>print(response.content)</pre><p><strong>The difference in one line:</strong> messages build direct conversations; templates build reusable prompts with dynamic values.</p><h3>2. Dynamic Message Construction and Few-Shot Prompting</h3><p>Dynamic message construction means building message lists in code instead of typing every message by hand.</p><p>This pairs nicely with <strong>few-shot prompting</strong>: teaching the AI by showing examples before asking a new question.</p><pre>Human: happy      AI: 😊<br>Human: sad        AI: 😢<br>Human: excited    AI: 🎉<br>Human: surprised  AI: ?</pre><p>The model spots the pattern and fills in an emoji that fits.</p><pre>from langchain_core.messages import SystemMessage, HumanMessage, AIMessage</pre><pre>def create_conversation(role, examples, new_question):<br>    messages = [SystemMessage(content=f&quot;You are a {role}.&quot;)]</pre><pre>    for example in examples:<br>        messages.append(HumanMessage(content=example[&quot;question&quot;]))<br>        messages.append(AIMessage(content=example[&quot;answer&quot;]))</pre><pre>    messages.append(HumanMessage(content=new_question))<br>    return messages</pre><pre>examples = [<br>    {&quot;question&quot;: &quot;happy&quot;, &quot;answer&quot;: &quot;😊&quot;},<br>    {&quot;question&quot;: &quot;sad&quot;, &quot;answer&quot;: &quot;😢&quot;},<br>    {&quot;question&quot;: &quot;excited&quot;, &quot;answer&quot;: &quot;🎉&quot;}<br>]</pre><pre>messages = create_conversation(&quot;emoji translator&quot;, examples, &quot;surprised&quot;)</pre><pre>response = model.invoke(messages)<br>print(response.content)</pre><p>The function assembles the role, the examples, and the new question into one conversation. This is the kind of technique AI agents use when they need to build conversations from history or runtime information.</p><h3>3. Basic Prompt Templates</h3><p>Here’s a more flexible template with three placeholders:</p><pre>from langchain_core.prompts import ChatPromptTemplate</pre><pre>template = ChatPromptTemplate.from_messages([<br>    (&quot;system&quot;,<br>     &quot;You are a helpful assistant that translates &quot;<br>     &quot;{input_language} to {output_language}.&quot;),<br>    (&quot;human&quot;, &quot;{text}&quot;)<br>])</pre><pre>chain = template | model</pre><pre>result = chain.invoke({<br>    &quot;input_language&quot;: &quot;English&quot;,<br>    &quot;output_language&quot;: &quot;French&quot;,<br>    &quot;text&quot;: &quot;Hello, how are you?&quot;<br>})</pre><pre>print(result.content)</pre><ul><li>{input_language}: the original language</li><li>{output_language}: the target language</li><li>{text}: the sentence to translate</li></ul><p>invoke() fills in the placeholders and sends the finished prompt to the model. Change the values and the same template translates into any language.</p><h3>4. ChatPromptTemplate vs PromptTemplate</h3><p>ChatPromptTemplate PromptTemplate Format Structured messages with roles (system, human) Plain text string Best for Chatbots, agents, RAG apps Simple, single-prompt tasks Fills placeholders with invoke() in a chain .format()</p><pre>from langchain_core.prompts import PromptTemplate</pre><pre>template = PromptTemplate.from_template(&quot;Translate {text} to French.&quot;)<br>prompt = template.format(text=&quot;Hello&quot;)</pre><pre>print(prompt)</pre><p>Output:</p><pre>Translate Hello to French.</pre><p>ChatPromptTemplate creates structured chat messages. PromptTemplate creates a plain text prompt.</p><h3>5. Zod and Pydantic: Defining the Shape of Your Data</h3><p>In JavaScript, <strong>Zod</strong> is a TypeScript-first schema validation library. In Python, the equivalent is <strong>Pydantic</strong>.</p><p>Both let you describe what data should look like. If you’re extracting information about a person, you might expect:</p><ul><li>Name: string</li><li>Age: number</li><li>Email: valid email address</li><li>Occupation: string</li></ul><pre>from pydantic import BaseModel, EmailStr, Field</pre><pre>class Person(BaseModel):<br>    name: str = Field(description=&quot;The person&#39;s full name&quot;)<br>    age: int = Field(description=&quot;The person&#39;s age in years&quot;)<br>    email: EmailStr = Field(description=&quot;The person&#39;s email address&quot;)<br>    occupation: str = Field(description=&quot;The person&#39;s job or profession&quot;)</pre><p>This class is a blueprint for the information we expect back.</p><h3>6. Structured Output with with_structured_output()</h3><p>By default, a model replies with a paragraph:</p><pre>Alice Johnson is 28 years old.<br>She works as a software engineer.<br>Her email is alice@email.com.</pre><p>But applications need data they can use:</p><pre>{<br>  &quot;name&quot;: &quot;Alice Johnson&quot;,<br>  &quot;age&quot;: 28,<br>  &quot;email&quot;: &quot;alice@email.com&quot;,<br>  &quot;occupation&quot;: &quot;software engineer&quot;<br>}</pre><p>LangChain’s with_structured_output() makes the model follow your schema:</p><pre>structured_model = model.with_structured_output(Person)</pre><pre>result = structured_model.invoke(<br>    &quot;My name is Alice Johnson, I&#39;m 28 years old, &quot;<br>    &quot;work as a software engineer, and you can reach &quot;<br>    &quot;me at alice.j@email.com&quot;<br>)</pre><pre>print(result)<br>print(result.name)<br>print(result.age)<br>print(result.email)<br>print(result.occupation)</pre><p>The model returns a Person object, and you access fields directly. There&#39;s no regex or string splitting needed.</p><h3>7. Nested Objects and Arrays</h3><p>Schemas can contain nested objects, lists, and different data types. Say we want to extract company information from this text:</p><pre>Apple was founded in 1976.<br>Its headquarters are in Cupertino, USA.<br>It makes iPhones and MacBooks.<br>It has 160000 employees.<br>It is a public company.</pre><pre>from pydantic import BaseModel</pre><pre>class Headquarters(BaseModel):<br>    city: str<br>    country: str</pre><pre>class Company(BaseModel):<br>    name: str<br>    founded: int<br>    headquarters: Headquarters<br>    products: list[str]<br>    employeeCount: int<br>    isPublic: bool</pre><ul><li>str is text</li><li>int is a whole number</li><li>bool is True or False</li><li>list[str] is a list of text values</li><li>Headquarters is a nested object holding city and country</li></ul><pre>structured_company_model = model.with_structured_output(Company)</pre><pre>result = structured_company_model.invoke(<br>    &quot;Apple was founded in 1976. Its headquarters are &quot;<br>    &quot;in Cupertino, USA. It makes iPhones and MacBooks. &quot;<br>    &quot;It has 160000 employees. It is a public company.&quot;<br>)</pre><pre>print(result)</pre><h3>8. Where This Gets Used in the Real World</h3><ul><li><strong>RAG systems:</strong> reusable templates combine retrieved document context with the user’s question</li><li><strong>AI agents:</strong> messages are built dynamically from conversation history and tool results</li><li><strong>Resume parsing:</strong> extract names, skills, experience, and contact details</li><li><strong>Email extraction:</strong> turn customer emails into structured database records</li><li><strong>Document processing:</strong> pull data out of PDFs, invoices, and forms</li><li><strong>API integration:</strong> return predictable data structures other applications can consume</li></ul><h3>Conclusion</h3><p>Today clicked a lot of pieces together. <strong>Messages</strong> manage conversations, <strong>templates</strong> make instructions reusable, and <strong>structured outputs</strong> make AI responses easy to plug into real software.</p><p>I also saw how Zod handles schema validation in JavaScript and how Pydantic does the same job in Python.</p><p><strong>A few honest notes:</strong></p><ul><li>The Python examples use LangChain’s Python packages rather than line-by-line translations of the JavaScript API.</li><li>EmailStr needs an extra package: pip install &quot;pydantic[email]&quot;.</li><li>Structured output guarantees the <em>shape</em> of the data, not that every extracted fact is correct. Always validate important results.</li><li>Options like strict=True in the original JavaScript example depend on the model provider.</li></ul><p><em>Thanks for reading! See you in tomorrow’s post.</em></p><h3><strong>REFERENCE:</strong></h3><p>Microsoft, “Prompts, Messages, and Outputs,” LangChain.js for Beginners. [Online]. Available: <a href="https://github.com/microsoft/langchainjs-for-beginners/tree/main/03-prompts-messages-outputs?utm_source=chatgpt.com">https://github.com/microsoft/langchainjs-for-beginners/tree/main/03-prompts-messages-outputs</a>. [Accessed: Nov. 7, 2026].</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b9eeadb6600" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Teaching an AI to Remember — LangChain Conversation History, Streaming, and Reliability]]></title>
            <link>https://medium.com/@duhamasoodi04/teaching-an-ai-to-remember-langchain-conversation-history-streaming-and-reliability-7121bc483477?source=rss-2585f9d0a547------2</link>
            <guid isPermaLink="false">https://medium.com/p/7121bc483477</guid>
            <category><![CDATA[chat-model]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Duhamasoodi]]></dc:creator>
            <pubDate>Mon, 02 Nov 2026 07:54:04 GMT</pubDate>
            <atom:updated>2026-11-02T07:54:04.273Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Today I went deeper into LangChain chat models. Here’s what I learned, in plain language, with Python code you can run yourself.</em></p><h3>1. Conversation History: How Chatbots “Remember”</h3><p>Until now I was sending the AI just one message at a time. Real conversations don’t work like that. They involve back-and-forth exchanges where later questions depend on earlier ones.</p><p>Here’s the key insight: <strong>the model doesn’t remember anything on its own. We send the entire conversation history with every new request.</strong></p><p>LangChain gives us three message types for this:</p><p>Message Type Purpose SystemMessage Gives instructions to the AI HumanMessage Stores the user&#39;s message AIMessage Stores the AI&#39;s response</p><p>The flow looks like this:</p><ol><li>Create a messages list</li><li>Add a system instruction and the user’s question</li><li>Send it with invoke()</li><li>Store the AI’s reply as an AIMessage</li><li>Add the next user question</li><li>Send the updated history again</li></ol><h3>Python Example</h3><pre>from langchain_openai import ChatOpenAI<br>from langchain_core.messages import SystemMessage, HumanMessage, AIMessage<br>from dotenv import load_dotenv</pre><pre>load_dotenv()</pre><pre>model = ChatOpenAI(model=&quot;your-model-name&quot;, temperature=0)</pre><pre># Create conversation history<br>messages = [<br>    SystemMessage(content=&quot;You are a helpful coding tutor.&quot;),<br>    HumanMessage(content=&quot;What is Python?&quot;)<br>]</pre><pre># First AI response<br>response1 = model.invoke(messages)<br>print(&quot;AI:&quot;, response1.content)</pre><pre># Save AI response<br>messages.append(AIMessage(content=response1.content))</pre><pre># Add another user question<br>messages.append(HumanMessage(content=&quot;Can you show me a simple example?&quot;))</pre><pre># Second AI response<br>response2 = model.invoke(messages)<br>print(&quot;AI:&quot;, response2.content)</pre><p>Because the second request includes the first question and answer, the AI knows what “a simple example” refers to.</p><p><strong>Quick note for JavaScript developers:</strong> messages.push() becomes messages.append() in Python. Everything else (invoke(), response.content) stays the same.</p><h3>2. Streaming: Show the Answer as It’s Written</h3><p>There are two ways to get a response:</p><ul><li>invoke() waits for the complete response</li><li>stream() returns the response in small chunks as it&#39;s generated</li></ul><p>Streaming makes apps feel much faster, because users start reading immediately instead of staring at a blank screen.</p><pre>from langchain_openai import ChatOpenAI<br>from dotenv import load_dotenv</pre><pre>load_dotenv()</pre><pre>model = ChatOpenAI(model=&quot;your-model-name&quot;)</pre><pre>print(&quot;AI (streaming): &quot;)<br>stream = model.stream(&quot;Explain how the internet works.&quot;)</pre><pre>for chunk in stream:<br>    print(chunk.content, end=&quot;&quot;, flush=True)</pre><pre>print(&quot;\n\nStream complete!&quot;)</pre><p>What’s happening:</p><ul><li>model.stream() starts the stream</li><li>for chunk in stream processes each piece as it arrives</li><li>chunk.content holds the text of that piece</li><li>end=&quot;&quot; stops each chunk from landing on a new line</li><li>flush=True displays the text immediately</li></ul><h3>3. Temperature: Predictable vs Creative</h3><p>Temperature controls how predictable or creative the response is.</p><p>Temperature Behaviour 0 More predictable and consistent 1 Balanced creativity 2 More random and creative (if supported)</p><p>A good rule of thumb: use <strong>low temperature</strong> for coding, SQL, and factual tasks, and <strong>higher temperature</strong> for brainstorming and creative writing.</p><p>Not every model supports every value, so wrap calls in try-except to handle errors without crashing the whole program.</p><h3>4. Max Tokens: Controlling Response Length</h3><p>A <strong>token</strong> is a small piece of text the model processes. It can be a whole word, part of a word, or punctuation.</p><p>max_tokens sets the maximum number of tokens in the response:</p><p>Max Tokens Expected Response 50 Short 150 Medium 500 Longer</p><p>Be careful: set it too low and the answer may stop mid-explanation.</p><p>I also practised measuring <strong>character count</strong>, which is different from tokens:</p><pre>response = model.invoke(&quot;Explain Machine Learning.&quot;)<br>print(response.content)</pre><pre>character_count = len(response.content)<br>print(&quot;Character count:&quot;, character_count)</pre><p>Remember: <strong>tokens are what the AI processes; characters are the text we actually see.</strong> They’re not the same thing.</p><h3>5. Automatic Retries: Handling Failures Gracefully</h3><p>API requests sometimes fail for temporary reasons:</p><ul><li>429: too many requests</li><li>500: server error</li><li>Timeout: the request took too long</li></ul><p>Instead of crashing, we can retry automatically using <strong>exponential backoff</strong>, which means waiting longer between each attempt:</p><pre>First attempt  → Failed<br>Wait 1 second<br>Second attempt → Failed<br>Wait 2 seconds<br>Third attempt  → Failed<br>Wait 4 seconds<br>Try again...</pre><p>In Python, LangChain offers with_retry():</p><pre>from langchain_openai import ChatOpenAI</pre><pre>model = ChatOpenAI(model=&quot;your-model-name&quot;)</pre><pre># Add automatic retry functionality<br>retry_model = model.with_retry(<br>    stop_after_attempt=3,<br>    wait_exponential_jitter=False<br>)</pre><pre>try:<br>    response = retry_model.invoke(&quot;Explain Artificial Intelligence.&quot;)<br>    print(response.content)<br>except Exception as e:<br>    print(&quot;Request failed:&quot;, e)</pre><p>How it works: with_retry() wraps the model, retries on temporary errors, and raises an error after the maximum attempts, which try-except then catches.</p><p><strong>Heads up:</strong> retries with stream() can be less reliable. For critical requests, prefer invoke().</p><h3>6. Chains, RAG, and Agents: The Big Picture</h3><p>These are three ways to build applications around an LLM:</p><p>Component Purpose Chain Connects multiple steps to process a request RAG Retrieves relevant information from documents before generating an answer Agent Makes decisions and uses tools to complete tasks LLM The language model that generates responses</p><pre>Chain → LLM<br>RAG   → Retrieve Information → LLM<br>Agent → Decide Which Tools to Use → LLM</pre><p>All three use an LLM underneath. And if you add retry functionality to the model, every application built on it benefits automatically.</p><h3>Key Takeaways</h3><ol><li>LangChain maintains conversation history using SystemMessage, HumanMessage, and AIMessage.</li><li>invoke() returns a complete response; stream() returns it gradually.</li><li>Temperature controls creativity vs predictability.</li><li>max_tokens caps response length, and tokens are not characters.</li><li>with_retry() makes apps more reliable against temporary API failures.</li><li>Chains, RAG, and Agents are different ways to build on top of an LLM.</li></ol><p><strong>Overall learning:</strong> I now know how to manage multi-turn conversations, control AI responses, display streaming output, and make LangChain apps more reliable. I also practised converting LangChain JavaScript code into Python.</p><p><strong>To follow along, install:</strong></p><pre>pip install langchain-openai langchain-core python-dotenv</pre><h3><strong>References:</strong></h3><p>Microsoft, “Chat Models,” LangChain.js for Beginners, GitHub. [Online]. Available: <a href="https://github.com/microsoft/langchainjs-for-beginners/tree/main/02-chat-models?utm_source=chatgpt.com">https://github.com/microsoft/langchainjs-for-beginners/tree/main/02-chat-models</a>. [Accessed: Nov. 2, 2026].</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7121bc483477" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning LangChain: Connecting Gemini, Understanding Messages, and Converting JavaScript to Python]]></title>
            <link>https://medium.com/@duhamasoodi04/learning-langchain-connecting-gemini-understanding-messages-and-converting-javascript-to-python-e8dedce4577b?source=rss-2585f9d0a547------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8dedce4577b</guid>
            <category><![CDATA[writing-prompts]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Duhamasoodi]]></dc:creator>
            <pubDate>Sun, 01 Nov 2026 10:07:28 GMT</pubDate>
            <atom:updated>2026-11-01T10:09:25.567Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently started learning <strong>LangChain</strong>, a framework used to build applications powered by Large Language Models (LLMs).</p><p>The learning material I followed used JavaScript, but I wanted to work with Python because it is the language I am more familiar with from my data science learning.</p><p>So, instead of simply copying the JavaScript examples, I converted them into Python and tried to understand how each part worked.</p><p>Here is what I explored.</p><h3>1. First, connecting Gemini to LangChain</h3><p>Before building anything, we need to connect our application to an AI model.</p><p>Think of LangChain as a bridge between our Python application and Gemini.</p><p>The flow looks like this:</p><p><strong>Python application → LangChain → Google Gemini → Response → Python application</strong></p><h3>Step 1: Install the required packages</h3><pre>pip install langchain-google-genai python-dotenv</pre><ul><li>langchain-google-genai allows LangChain to communicate with Gemini.</li><li>python-dotenv helps us load environment variables from a .env file.</li></ul><h3>Step 2: Store the API key</h3><p>Instead of writing our API key directly in the Python file, we store it in a .env file.</p><pre>GOOGLE_API_KEY=your_api_key<br>AI_MODEL=gemini-2.5-flash</pre><p>This keeps sensitive information separate from our main code.</p><h3>Step 3: Connect to Gemini</h3><pre>import os<br>from dotenv import load_dotenv<br>from langchain_google_genai import ChatGoogleGenerativeAI</pre><pre>load_dotenv()</pre><pre>model = ChatGoogleGenerativeAI(<br>    model=os.getenv(&quot;AI_MODEL&quot;),<br>    google_api_key=os.getenv(&quot;GOOGLE_API_KEY&quot;)<br>)</pre><p>Let’s understand the execution flow:</p><ol><li>import os allows Python to access environment variables.</li><li>load_dotenv() reads the values stored in our .env file.</li><li>ChatGoogleGenerativeAI imports the LangChain integration for Gemini.</li><li>os.getenv(&quot;AI_MODEL&quot;) retrieves the model name.</li><li>os.getenv(&quot;GOOGLE_API_KEY&quot;) retrieves the API key.</li><li>We create a model object and store it in a variable called model.</li></ol><p>At this point, we have configured our connection. We haven’t asked Gemini anything yet.</p><h3>Step 4: Send a question to Gemini</h3><pre>response = model.invoke(&quot;What is artificial intelligence?&quot;)</pre><pre>print(response.content)</pre><p>What happens here?</p><ol><li>model.invoke() sends our question to Gemini through LangChain.</li><li>Gemini processes the question and generates an answer.</li><li>The answer comes back and is stored in response.</li><li>response.content extracts the actual text of the answer.</li><li>print() displays it on the screen.</li></ol><p><strong>Important:</strong> model represents our configured AI model. response represents the answer returned by that model.</p><h3>2. Understanding the three message types</h3><p>After connecting Gemini, I explored how LangChain handles conversations.</p><p>Instead of sending only plain text, LangChain allows us to structure a conversation using different message types.</p><p>There are three important ones:</p><p>MessagePurposeSystemMessageTells the AI how to behaveHumanMessageContains the user’s questionAIMessageContains the AI’s previous response</p><p>For example:</p><pre>from langchain_core.messages import (<br>    SystemMessage,<br>    HumanMessage,<br>    AIMessage<br>)</pre><pre>messages = [<br>    SystemMessage(content=&quot;You are a helpful coding teacher.&quot;),<br>    HumanMessage(content=&quot;What is Python?&quot;)<br>]</pre><p>Let’s understand what we created.</p><ul><li>First,we imported the three message types.</li><li>Then, we created a list called messages.</li><li>Inside that list, we added a system instruction.</li><li>After that, we added the user’s question.</li></ul><p>The order matters because the AI receives the instructions before the question.</p><p>We can send this list to Gemini:</p><pre>response = model.invoke(messages)</pre><pre>print(response.content)</pre><p>Now Gemini receives both the instruction and the question.</p><h3>3. Experimenting with different AI personalities</h3><p>I wanted to understand how much system instructions can influence an AI’s responses.</p><p>So I used the same question but gave Gemini three different instructions.</p><p>The question was:</p><p>“What is artificial intelligence?”</p><p>The three instructions were:</p><ul><li>Pirate: Answer like a pirate.</li><li>Business Analyst: Answer professionally using precise, data-driven language.</li><li>Teacher: Explain the concept as if teaching an eight-year-old.</li></ul><p>I used a Python list to store these instructions:</p><pre>personalities = [<br>    {<br>        &quot;name&quot;: &quot;Pirate&quot;,<br>        &quot;prompt&quot;: &quot;Answer like a pirate.&quot;<br>    },<br>    {<br>        &quot;name&quot;: &quot;Business Analyst&quot;,<br>        &quot;prompt&quot;: &quot;Answer like a professional business analyst.&quot;<br>    },<br>    {<br>        &quot;name&quot;: &quot;Teacher&quot;,<br>        &quot;prompt&quot;: &quot;Explain concepts to an eight-year-old.&quot;<br>    }<br>]</pre><p>Then I used a for loop:</p><pre>question = &quot;What is artificial intelligence?&quot;</pre><pre>for personality in personalities:</pre><pre>    messages = [<br>        SystemMessage(content=personality[&quot;prompt&quot;]),<br>        HumanMessage(content=question)<br>    ]</pre><pre>    response = model.invoke(messages)</pre><pre>    print(personality[&quot;name&quot;])<br>    print(response.content)</pre><h3>How does this code flow?</h3><ol><li>Python stores the three personalities in a list.</li><li>The for loop takes the first personality.</li><li>It extracts that personality’s prompt.</li><li>It creates a conversation containing the system instruction and the same question.</li><li>model.invoke(messages) sends the conversation to Gemini.</li><li>Gemini generates a response based on the instruction.</li><li>Python prints the personality name and its response.</li><li>The loop repeats the same process for the other two personalities.</li></ol><p>The important thing I learned is that we don’t need three different AI models. We can use the same model and change its behaviour through system prompts.</p><h3>4. Understanding multi-turn conversations</h3><p>This was another important concept.</p><p>A single-turn conversation is when we send one question and receive one answer.</p><p>A multi-turn conversation allows us to continue asking questions while maintaining the earlier context.</p><p>For example:</p><ul><li>User: What is Python?</li><li>AI: Python is a programming language.</li><li>User: Who created it?</li><li>AI: Python was created by Guido van Rossum.</li></ul><p>The second question uses information from the first question.</p><p>But there is something important to understand: the model does not automatically remember previous requests just because we called it earlier.</p><p><strong>We need to send the conversation history again.</strong></p><p>Here is how I implemented this in Python:</p><pre>messages = [<br>    SystemMessage(<br>        content=&quot;You are a helpful coding tutor.&quot;<br>    ),<br>    HumanMessage(<br>        content=&quot;What is Python?&quot;<br>    )<br>]</pre><pre># First interaction<br>response1 = model.invoke(messages)</pre><pre>print(&quot;AI:&quot;, response1.content)</pre><pre># Store the AI&#39;s first response<br>messages.append(<br>    AIMessage(content=str(response1.content))<br>)</pre><pre># Add the user&#39;s next question<br>messages.append(<br>    HumanMessage(content=&quot;Who created it?&quot;)<br>)</pre><pre># Second interaction<br>response2 = model.invoke(messages)</pre><pre>print(&quot;AI:&quot;, response2.content)</pre><h3>Let’s follow the execution step by step.</h3><p><strong>Step 1: Create the conversation</strong></p><p>We create a list containing the system instruction and the first user question.</p><p><strong>Step 2: Send the first question</strong></p><p>model.invoke(messages) sends the conversation to Gemini.</p><p>Gemini responds, and we store the result in response1.</p><p><strong>Step 3: Save the AI’s answer</strong></p><pre>messages.append(<br>    AIMessage(content=str(response1.content))<br>)</pre><p>This is important.</p><p>We add the AI’s response to the messages list so that it becomes part of the conversation history.</p><p><strong>Step 4: Add another user question</strong></p><pre>messages.append(<br>    HumanMessage(content=&quot;Who created it?&quot;)<br>)</pre><p>Now our list contains:</p><ol><li>System instruction</li><li>First user question</li><li>First AI response</li><li>Second user question</li></ol><p><strong>Step 5: Send the complete conversation again</strong></p><pre>response2 = model.invoke(messages)</pre><p>This time, Gemini receives the entire conversation, not just the latest question.</p><p>That is how it understands what the word “it” refers to.</p><h3>The complete flow</h3><pre>Create message history<br>        |<br>        v<br>Add system instruction<br>        |<br>        v<br>Add first user question<br>        |<br>        v<br>Send messages to Gemini<br>        |<br>        v<br>Receive AI response<br>        |<br>        v<br>Save AI response in history<br>        |<br>        v<br>Add second user question<br>        |<br>        v<br>Send complete history again<br>        |<br>        v<br>Receive contextual response</pre><h3>5. Converting JavaScript into Python</h3><p>Since the original learning material used JavaScript, I converted the examples into Python.</p><p>I noticed that although the syntax changes, the underlying logic remains the same.</p><p>For example:</p><p><strong>JavaScript:</strong></p><pre>const animals = [&quot;Cat&quot;, &quot;Dog&quot;, &quot;Tiger&quot;];</pre><pre>for (const animal of animals) {<br>    console.log(animal);<br>}</pre><p><strong>Python:</strong></p><pre>animals = [&quot;Cat&quot;, &quot;Dog&quot;, &quot;Tiger&quot;]</pre><pre>for animal in animals:<br>    print(animal)</pre><p>Both examples do exactly the same thing: they go through each animal in the list and print its name.</p><p>I applied the same approach when converting the LangChain examples.</p><p>Some of the main differences I encountered were:</p><p>JavaScriptPythonconstNo equivalent needed for ordinary variable assignmentconsole.log()print()for...offor...inimportimportasync / awaitasync / awaitnew HumanMessage()HumanMessage()</p><p>The package names and some method arguments can also differ between the JavaScript and Python versions of LangChain, so conversion is not always a direct line-by-line replacement.</p><h3>6. Key takeaways</h3><p>Through these examples, I learned:</p><ol><li>How to connect Google Gemini with LangChain using Python.</li><li>How invoke() sends information to an AI model.</li><li>How SystemMessage, HumanMessage, and AIMessage structure conversations.</li><li>How system prompts change the way an AI responds.</li><li>How Python loops can automate repeated prompts.</li><li>How conversation history helps an AI maintain context.</li><li>How to convert JavaScript LangChain examples into Python.</li></ol><p>The biggest lesson for me was understanding the complete flow: <strong>we prepare the instructions and messages, send them to the model, receive a response, and manage the conversation history ourselves.</strong></p><p>This gives me a foundation for exploring more advanced LangChain concepts, including document loading, embeddings, vector databases, and Retrieval-Augmented Generation (RAG).</p><h3><strong>References:</strong></h3><p>[1] Microsoft, “LangChain.js for Beginners — Introduction,” GitHub. [Online]. Available: <a href="https://github.com/microsoft/langchainjs-for-beginners/tree/main/01-introduction?utm_source=chatgpt.com">https://github.com/microsoft/langchainjs-for-beginners/tree/main/01-introduction</a>. [Accessed: Nov. 1, 2026].</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8dedce4577b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Langchain Agents For Beginners:]]></title>
            <link>https://medium.com/@duhamasoodi04/langchain-agents-for-beginners-4a7ad7092170?source=rss-2585f9d0a547------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a7ad7092170</guid>
            <dc:creator><![CDATA[Duhamasoodi]]></dc:creator>
            <pubDate>Tue, 28 Oct 2025 10:16:17 GMT</pubDate>
            <atom:updated>2025-10-28T10:16:40.374Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction:</strong></h3><p>LangChain is a framework that helps connect large language models (LLMs) (like GPT-4 or Gemini) to web pages, files, databases and tools so they can do useful tasks.</p><p>The six main parts</p><ul><li><strong>LLM (the model)</strong> <br> The AI “brain” you use — for example GPT-4 or Gemini. LangChain plugs these models into workflows.</li><li><strong>Prompt templates</strong> <br> Reusable prompts with blanks you can fill (variables). <br> Example: “Summarize this article for a {role}.” — you only change {role}.</li><li><strong>Chains</strong> <br> Step-by-step pipelines that connect components. <br> Examples:</li></ul><p>Prompt → LLM</p><p>LLM → another LLM</p><p>LLM → Tool → final answer</p><ul><li><strong>Memory</strong> <br> Lets the AI remember past conversation or facts. Three common types:</li></ul><p><strong><em>Buffer memory:</em></strong> full chat history.</p><p><strong><em>Summary memory</em>:</strong> short summary of past conversation.</p><p><strong><em>Entity memory:</em></strong> remembers specific facts (name, age, preferences).</p><ul><li><strong>Tools</strong></li></ul><p>Extra capabilities the agent can call when needed, such as:</p><p><em>Calculator (math)</em></p><p><em>Web search (internet lookup)</em></p><p><em>Python runner (execute code)</em></p><p><em>Database connector (query stored data)</em></p><ul><li><strong>Retriever</strong> <br> A component that searches internal documents or data and returns relevant information. When used, the AI answers using only that internal info.</li><li><strong>Agents</strong></li></ul><p>Agents manage thinking and tool use: they decide which tools to call and perform multi-step reasoning.</p><h3><strong>Types Of Agents:</strong></h3><p>There are about six different types of AI “agents” or prompt patterns basically, different ways an AI like ChatGPT can think and act.</p><p>We’ll go through them one by one</p><h3><strong>Zero-Shot ReAct Description</strong></h3><p>An AI agent that reasons step by step, uses tools based on their descriptions, and answers without prior examples or memory.</p><p><strong>Zero-Shot:</strong> <br><strong> </strong>The AI can solve a task without any prior examples or training. It uses general reasoning skills to understand and answer new questions directly.</p><p><strong>ReAct (Reason + Act):</strong> <br><strong> </strong>The agent thinks before acting — it reasons step by step, decides which tool to use, performs the action, and then gives the answer.</p><p><strong>Description:</strong> <br><strong> </strong>The AI chooses tools based on their text descriptions, such as “useful for solving math problems” or “helps with translations</p><p><strong>Example:</strong> <br> You ask:</p><p>“Translate ‘Bonjour’ to English.”</p><p>The AI responds:</p><p>“Hello.”</p><p>It has never seen this exact example before, but it understands what “translate” means and acts accordingly. <br> This agent handles single question–answer tasks and does not store memory from past interactions.</p><h3><strong>Chat — zero-shot –ReAct- Description:</strong></h3><p>An AI that reasons before answering, remembers past messages, and uses tools based on descriptions — without needing prior examples.</p><p><strong>Chat:</strong> <br> This agent works like a <strong>normal conversation</strong>, where the AI can <strong>remember previous messages</strong> and use them to respond naturally — just like this chat!</p><p><strong>Zero-Shot:</strong> <br> The AI can answer questions <strong>without seeing examples beforehand</strong>, relying on its general reasoning ability.</p><p><strong>ReAct (Reason + Act):</strong> <br> The AI <strong>thinks before acting</strong> — it reasons step by step, decides how to respond, and then gives the answer.</p><p><strong>Description:</strong> <br> The AI selects tools based on their <strong>descriptions</strong>, such as “useful for calculations” or “helps with translations.”</p><p><strong>Example:</strong> <br> You say:</p><p>“Hi, what is 10 + 2?”</p><p>AI:</p><p>“It’s 12.”</p><p>Then you say:</p><p>“Now divide that by 3.”</p><p>AI remembers that “that” refers to <strong>12</strong>, and replies:</p><p>“12 divided by 3 is 4.”</p><h3><strong>ReAct — <em>“Reason + Act”</em></strong></h3><p>The ReAct approach combines reasoning and action. <br> The AI first thinks step by step to understand the problem (Reason), <br> and then takes an action — such as performing a calculation or using a tool (Act) — to find the answer.</p><p><strong>Example:</strong></p><p>You ask:</p><p>“If I have 5 apples and I eat 2, how many are left?”</p><p>The AI reasons and responds: <br> I start with 5 apples and eat 2. <br> 5 − 2 = 3. <br> So, you have 3 apples left.</p><h3><strong>Self-Ask with Search</strong></h3><p>The AI asks itself smaller questions to solve a bigger one. <br> It can use a search tool to find real-world information for accuracy.</p><p><strong>Example:</strong></p><p>You ask:</p><p>“Who is the mother of the current president of France?”</p><p>AI reasoning:</p><ol><li>“Who is the current president of France?” → (search) → <em>Emmanuel Macron</em></li><li>“Who is Emmanuel Macron’s mother?” → (search) → <em>Françoise Noguès</em></li><li>“Final answer: The mother of the current president of France is Françoise Noguès.”</li></ol><p>The AI breaks down the question into smaller steps and uses search to find facts.</p><h3><strong>Plan and Execute</strong></h3><p>The AI first creates a plan outlining what steps it needs to take, <br> and then executes each step in order.</p><p><strong>Example:</strong></p><p>You ask:</p><p>“Write a short paragraph about solar energy and then summarize it.”</p><p>AI:</p><p>Step 1: Write about solar energy. <br> Solar energy comes from sunlight and is a clean, renewable power source.</p><p>Step 2: Summarize it. <br> Summary: Solar energy is a clean and renewable source of power.</p><p>The AI thinks ahead, plans its steps, and completes them one by one.</p><h3><strong>Tool Calling</strong></h3><p>The AI automatically decides when and which tool to use — for example, a calculator for math, or a search tool for facts.</p><p><strong>Example:</strong></p><p>You ask:</p><p>“What is 45 × 2?”</p><p>AI reasoning:</p><p>This is a math problem. I’ll use the calculator tool. <br> <em>(uses calculator)</em> <br> The answer is 90.</p><p>The AI identifies the task and selects the appropriate tool on its own<strong>.</strong></p><h3>References:</h3><ul><li>GeeksforGeeks. <em>Introduction to LangChain</em>. Last Updated: 25 Aug 2025. Available at: <a href="https://www.geeksforgeeks.org/artificial-intelligence/introduction-to-langchain/?utm_source=chatgpt.com">https://www.geeksforgeeks.org/artificial-intelligence/introduction-to-langchain/</a> [Accessed: 28 Oct 2025].</li><li>Kaggle, n.d. <em>Agents Whitepaper</em> [online]. Available at: <a href="https://www.kaggle.com/whitepaper-agents?utm_source=chatgpt.com">https://www.kaggle.com/whitepaper-agents</a> [Accessed 28 October 2025].</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a7ad7092170" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrieval Augmented Generation (RAG):]]></title>
            <link>https://medium.com/@duhamasoodi04/retrieval-augmented-generation-rag-6254727e3f3c?source=rss-2585f9d0a547------2</link>
            <guid isPermaLink="false">https://medium.com/p/6254727e3f3c</guid>
            <dc:creator><![CDATA[Duhamasoodi]]></dc:creator>
            <pubDate>Mon, 21 Apr 2025 11:35:08 GMT</pubDate>
            <atom:updated>2025-04-21T11:35:08.483Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction:</h3><p>One of the main limitations of using Large Language Models (LLMs) is that they are only trained on publicly available data and cannot access new or private information on their own. To overcome this, a technique called <strong>Retrieval-Augmented Generation (RAG)</strong> was introduced.</p><p>With RAG, your LLM can:</p><ul><li>Answer questions based on <strong>information it wasn’t originally trained on</strong>, such as private company documents, recent news, or live data.</li><li><strong>Stay up-to-date</strong> without needing to be retrained.</li><li><strong>Handle more information efficiently</strong> by only retrieving and using the most relevant data, helping to work around the LLM’s limited context window.</li></ul><h3>Understanding How Retrieval-Augmented Generation (RAG) Works:</h3><p>There are three main parts of RAG:</p><p>1. <strong>Indexing:</strong></p><p>We start by preparing the documents or information we want the LLM to use.</p><p><strong>texts = [</strong></p><p><strong>“The MagicPhone X1 has a 108MP camera and 5000mAh battery.”,</strong></p><p><strong>“The SmartWatch Pro is waterproof and tracks sleep, heart rate, and steps.”,</strong></p><p><strong>“The AirCooler 3000 uses hydro-cooling technology for fast cooling.”</strong></p><p><strong>]</strong></p><p>The text is converted into vectors using <strong>embeddings</strong></p><p><strong>Example:</strong></p><p><strong>Text :</strong>“The SmartWatch tracks sleep”</p><p><strong>Embedding :</strong>[0.12, -0.45, 0.88, …, 0.03]</p><p><strong>Text :</strong>“It helps monitor your sleep”</p><p><strong>Embedding :</strong>[0.11, -0.43, 0.86, …, 0.05]</p><p>Finally, these vectors are stored in chroma a vector database. They are stored as searchable vectors.</p><p>2. <strong>Retrieval:</strong></p><p>It finds the best-matching content for a question. It is done using vector similarity. Usually, we use Cosine similarity. Cosine similarity measures the angle between two vectors. If the angle is small (cosine is close to 1), it means the vectors are very similar (i.e., texts are semantically related).</p><p>For example:</p><p>If embeddings are:</p><p><strong>A = [1, 2]</strong></p><p><strong>B = [1, 2]</strong></p><p><strong>C = [-1, 0]</strong></p><p>Then:</p><p>· Cosine (A, B) = 1 → <strong>exact same direction (very similar)</strong></p><p>· Cosine (A, C) = near 0 → <strong>completely different meaning</strong></p><p>So, during retrieval, we compare the user’s question embedding to each document embedding and pick the top closest ones.</p><p>3. <strong>Generation:</strong></p><p>Once we find the most relevant documents, we pass them along with the user’s question to the LLM (like Gemini).</p><p>Gemini then reads this information and uses its built-in intelligence to generate a clear and accurate answer.</p><p>For Example:</p><p>We type a query:</p><p><strong>query = “What are the features of the SmartWatch Pro?”</strong></p><p>The Gemini receives:</p><p><strong>Context: “The SmartWatch Pro is waterproof and tracks sleep, heart rate, and steps.”</strong></p><p><strong>Question: “What are the features of the SmartWatch Pro?”</strong></p><p>And then it generates:</p><p><strong>Answer: “The SmartWatch Pro is waterproof and tracks sleep, heart rate, and steps.”</strong></p><h3>References:</h3><p>· <strong>Kaggle</strong>, <em>Embeddings &amp; Vector Stores</em>. Available: <a href="https://www.kaggle.com/whitepaper-embeddings-and-vector-stores">https://www.kaggle.com/whitepaper-embeddings-and-vector-stores</a>. [Accessed: 13-Apr-2025].</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6254727e3f3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prompt Engineering Basics:]]></title>
            <link>https://medium.com/@duhamasoodi04/prompt-engineering-basics-bd1f4c21d424?source=rss-2585f9d0a547------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd1f4c21d424</guid>
            <dc:creator><![CDATA[Duhamasoodi]]></dc:creator>
            <pubDate>Sun, 13 Apr 2025 10:21:02 GMT</pubDate>
            <atom:updated>2025-04-13T10:21:02.331Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction:</h3><p>Prompt Engineering is giving instruction to the LLM so it gives better response. It is the process of creating well-designed prompts that help large language models (LLMs) give accurate and useful answers. It includes experimenting with different ways of asking, adjusting how long the prompt is, and choosing the right style and structure based on the task.</p><h3>Model Output Settings:</h3><p>When you’re doing prompt engineering, the first step is to choose which AI model you want to use. Each model is a bit different, so you may need to adjust your prompt to work best with the one you pick — whether it’s Gemini, GPT, Claude, or an open-source model like Gemma or LLaMA.</p><p>To control how creative our model is we use <strong>Sampling Control.</strong> There are three ways we can control this:</p><p><strong>Temperature:</strong></p><p>This controls how <strong>random</strong> or <strong>creative</strong> the model is.</p><p>Example:</p><p><strong>prompt </strong>= “Pick a color”</p><p><strong>temperature = 0.2 — Very safe and predictable</strong></p><p><strong>Output:</strong> “Blue”</p><p><strong>temperature = 0.7</strong> <strong>— A bit creative</strong></p><p><strong>Output: </strong>“green”, “red”, or maybe “purple”</p><p><strong>temperature = 1.0 — Very Creative &amp; Random</strong></p><p><strong>Output:</strong> “neon avocado”</p><p><strong>Top-K Sampling:</strong></p><p>When using top-k sampling, the model chooses from K most likely option. Example:</p><p><strong>prompt = “Pick a color”</strong></p><p><strong>top_k = 1</strong> — <strong>Only picks the #1 color</strong></p><p><strong>Output:</strong> “blue” (always the same because it’s the most likely)</p><p>The model only picks the <strong>most common color</strong>.</p><p><strong>top_k = 3</strong> — <strong>Pick from the top 3 most likely colors</strong></p><p><strong>Output: </strong>“blue”, “red”, or “green”</p><p>Now, the model can choose from <strong>3 different options</strong>. But it still picks from a limited group.</p><p><strong>Top-P Sampling:</strong></p><p>In Top-P, the model can choose from all words that, together, account for P percentage of the likelihood. It doesn’t have a fixed number like Top-K. Example:</p><p><strong>prompt = “Pick a color”</strong></p><p><strong>top_p = 0.7 — Pick from the most likely colors that add up to 70% of the chance</strong></p><p><strong>Output</strong>: “blue”, “green”, or “red” (because together, these 3 colors make up 70% of the likelihood)</p><p>The model picks <strong>the most likely colors</strong>, but it chooses enough of them (in total) to cover 70% of the possibilities.</p><p><strong>top_p = 0.9</strong> — <strong>Pick from colors that add up to 90% of the chance</strong></p><p><strong>Output</strong>: “blue”, “green”, “red”, “purple”, or “yellow”</p><p>The model now picks <strong>enough options</strong> to cover 90% of the likely choices. It’s a broader selection of possible colors.</p><p><strong>Putting it all together:</strong></p><p>Let’s combine <strong>Top-P</strong>, <strong>Top-K</strong>, and <strong>Temperature</strong> for a single prompt:</p><p><strong>Top-P = 0.7, Top-K = 3, Temperature = 1.0</strong></p><p><strong>Prompt</strong>: “Pick a color”</p><ul><li><strong>Top-P = 0.7</strong> means the model will select from the <strong>set of colors</strong> that together make up 70% of the total probability.</li><li><strong>Top-K = 3</strong> means the model will only consider the <strong>top 3 most likely colors</strong>.</li><li><strong>Temperature = 1.0</strong> means the model will make a <strong>random selection</strong> from the top choices.</li></ul><p><strong>Output:</strong></p><ul><li>“blue”, “green”, or “yellow” — The model will likely pick one of the top 3 most likely colors (because <strong>Top-K = 3</strong>), but since <strong>Temperature = 1.0</strong>, it might not always pick the most likely one. The choice could have some <strong>randomness</strong>.</li></ul><h3>Techniques for Prompting:</h3><p>Now that we’ve covered the basics of prompt engineering and its key elements, let’s explore some of the most essential prompting techniques through examples.</p><p><strong>Zero shot Prompting:</strong></p><p>In zero shot the model is not given any prior example and it rely on its general knowledge to generate the answer.</p><p>Let’s say we want the model to classify the sentiment of a movie review. We simply ask:</p><p><strong>Prompt:</strong><br> “Classify the following movie review as positive, neutral, or negative: ‘I loved the movie, it was amazing!’”</p><p>In this case, the model hasn’t seen any previous examples of sentiment classification. It needs to infer from its training what a positive sentiment looks like.</p><p><strong>Model Output:</strong><br> “Positive”</p><p>The key here is that the model doesn’t have any prior examples to go off of. It uses its general understanding of language, context, and the task to make an educated guess.</p><p><strong>One-shot &amp; few-shot:</strong></p><p>One-shot prompting means showing the model one example, then asking it to use that example to answer a similar question. For example:</p><p><strong>Prompt: “</strong>Classify the following movie review as positive, neutral, or negative.</p><p>Example: “The plot was boring and the acting was terrible.” → Negative</p><p>Now classify: “The movie had great visuals and I really enjoyed it!””</p><p><strong>Output:</strong> Positive</p><p>The model is given <strong>one clear example</strong> to understand how to respond. Then, it applies that logic to the new input.</p><p>In few-shot prompting we give model more than one example so it can understand the task better and generate a response accordingly. For example:</p><p><strong>Prompt: “</strong>Classify the following movie reviews as positive, neutral, or negative.</p><p>Example 1: “It was a waste of time and money.” → Negative</p><p>Example 2: “It was okay, not too bad but not great either.” → Neutral</p><p>Example 3: “Absolutely loved it! Best movie of the year.” → Positive</p><p>Now classify: “The story was interesting but the pacing felt slow.””</p><p><strong>Output:</strong> Neutral</p><p>The model sees <strong>multiple examples</strong> that show how to label different types of reviews. It uses those patterns to figure out the right answer.</p><p><strong>Chain Of Thoughts:</strong></p><p>Chain of Thought prompting is a technique where we ask the model to <strong>show its thinking step-by-step</strong> before giving the final answer. For example:</p><p><strong>Prompt:</strong></p><p>“Emma has 12 candies. She gives 3 to her friend, then buys 7 more. How many candies does she have now? Let’s think step by step.”</p><p><strong>Model Output:</strong></p><p>Emma starts with 12 candies.<br> She gives away 3, so 12–3 = 9.<br> Then she buys 7 more, so 9 + 7 = 16.<strong><br> Answer: 16</strong></p><p>It helps the model:</p><ul><li>Break down complex tasks</li><li>Avoid silly mistakes</li><li>Give more accurate answers</li></ul><p><strong>ReAct (Reason &amp; Act):</strong></p><p>ReAct stands for Reason + Act.<br> It’s a prompting technique where the model:</p><ol><li>Reasons about the problem (thinks step by step),</li><li>Then Acts (takes an action, like calling a tool, looking something up, or giving an answer).</li></ol><p>For example:</p><p><strong>Prompt:</strong></p><p><strong>Question</strong>: What is the square root of the sum of 49 and 51?</p><p><strong>Thought</strong>: Let’s first find the sum of 49 and 51.<br> <strong>Action</strong>: Calculator.add (49, 51)<br> <strong>Observation</strong>: 100<br> <strong>Thought</strong>: Now find the square root of 100.<br> <strong>Action</strong>: Calculator.sqrt(100)<br> <strong>Observation</strong>: 10<br> <strong>Answer</strong>: 10</p><p>In this format, the model reasons, takes action, sees the result, and continues thinking.</p><p><strong>Automatic Prompt Engineering:</strong></p><p>Automatic Prompt Engineering means the system <strong>automatically tries different prompts</strong> to get the best result, <strong>learns from the feedback</strong>, and then <strong>refines</strong> the prompt to keep improving. For example:</p><p>You have a simple prompt:</p><ul><li><strong>Prompt</strong>: “Describe this product: ‘SuperFast 3000 Laptop’.”</li></ul><p>The system automatically creates several variations of the prompt to improve its effectiveness:</p><ul><li><strong>Prompt Variation 1</strong>: “Write a catchy description for the ‘SuperFast 3000 Laptop’ that highlights its speed and key features.”</li><li><strong>Prompt Variation 2</strong>: “Generate a creative and engaging description for the ‘SuperFast 3000 Laptop’ focusing on its performance and design.”</li><li><strong>Prompt Variation 3</strong>: “Describe the ‘SuperFast 3000 Laptop’ in a way that will appeal to tech enthusiasts and buyers looking for fast laptops.”</li></ul><p>Each of the generated prompts is tested with the LLM, and you compare the results:</p><ul><li><strong>Prompt 1</strong> might result in a basic description.</li><li><strong>Prompt 2</strong> might result in a more detailed, engaging description.</li><li><strong>Prompt 3</strong> might produce a description that’s highly technical, but maybe not suitable for the general public.</li></ul><p>Based on the evaluation, the system selects <strong>Prompt Variation 2</strong> because it produces the most engaging and relevant product description.</p><h3>References:</h3><p><strong>Kaggle</strong>, <em>Prompt Engineering</em>. Available: <a href="https://www.kaggle.com/whitepaper-prompt-engineering">https://www.kaggle.com/whitepaper-prompt-engineering</a>. [Accessed: 13-Apr-2025].</p><p><strong>Google Developers</strong>, <em>Machine Learning Crash Course: LLMs — Fine-tuning, Distillation, and Prompt Engineering</em>. Available: <a href="https://developers.google.com/machine-learning/crash-course/llm/tuning">https://developers.google.com/machine-learning/crash-course/llm/tuning</a>. [Accessed: 13-Apr-2025].</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd1f4c21d424" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Large Language Models for Beginners:]]></title>
            <link>https://medium.com/@duhamasoodi04/large-language-models-for-beginners-7a86f0a43d97?source=rss-2585f9d0a547------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a86f0a43d97</guid>
            <dc:creator><![CDATA[Duhamasoodi]]></dc:creator>
            <pubDate>Sat, 12 Apr 2025 16:53:22 GMT</pubDate>
            <atom:updated>2025-04-12T16:53:22.667Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction:</h3><p>LLM stands for Large Language Models. They are typically implemented as a deep neural network and are trained on a massive amount of data. They can do many complex tasks like</p><p>· Answering questions</p><p>· Solving reasoning problems</p><p>· Translating one language into another</p><p>· Writing and completing code</p><p>· Writing stories, summaries, or emails</p><p>· Classifying text (e.g., “is this message spam or not?”)</p><p>Sometimes, LLMs can do things they were <strong>never specifically trained for</strong> — just because they’ve seen so much data.<br> This is called <strong>emergent behavior</strong>.<br> For example:<br> They might learn how to write poems even if no one asked them to specifically learn poetry.</p><p>What is a Language Model?</p><p>A <strong>language model</strong> is like a smart text predictor.<br> It tries to <strong>guess the next word(s)</strong> in a sentence.</p><p><strong>For example:</strong></p><p>If I say:<br> “The most famous city in the US is…”</p><p>The model might guess:<br> “New York” (high probability)<br> “Los Angeles” (also high)<br> “laptop” or “apple” (low probability — those don’t make sense here)</p><p>So, it’s all about <strong>predicting the next word</strong> based on the words before it.</p><p>A <strong>basic version</strong> of a language model is called an <strong>n-gram model</strong>.</p><ul><li>They help capture <strong>local context</strong> in a sentence</li><li>With unigrams: you only see each word.</li><li>With bigrams: you start seeing <em>“the cat”</em>, <em>“cat sat”</em>, etc.</li><li>With trigrams: you see patterns like <em>“the cat sat”</em>, <em>“cat sat on”</em>, etc.</li></ul><p>“The cat sat on the mat”</p><p><strong>Unigrams (n=1):</strong></p><p>[“The”, “cat”, “sat”, “on”, “the”, “mat”]</p><p><strong>Bigrams (n=2):</strong></p><p>[“The cat”, “cat sat”, “sat on”, “on the”, “the mat”]</p><p><strong>Trigrams (n=3):</strong></p><p>[“The cat sat”, “cat sat on”, “sat on the”, “on the mat”]</p><p>But n-gram models are <strong>very simple</strong> and <strong>can’t understand deeper meaning</strong> or long sentences.</p><p>Transformers came along and changed the game. The transformer is a special type of neural network designed to takes in a sequence of words (like a sentence in one language) and produces another sequence (like a translation in another language, or a summary, or an answer).</p><p>This is called a sequence-to-sequence (or seq2seq) task.</p><h3>Structure Of Transformers:</h3><p><strong>Two Main Parts of a Transformer:</strong></p><p>The original transformer is made of two big blocks:</p><ol><li>Encoder</li><li>Decoder</li></ol><p><strong>Encoder</strong> reads and understands the input</p><p><strong>Decoder</strong> uses that understanding to generate the output (English sentence), one word at a time.</p><p>Lets understand the whole architecture in details:</p><p>The encoder and decoder blocks both contain different layers.</p><p><strong>Imagine this Input Sentence:</strong></p><p><strong>“je suis étudiant”</strong> (French for “I am a student”).This is the input that enters the model.</p><p><strong>Step 1: Input Embedding</strong></p><p>The machine doesn’t understand text directly like “je”, “suis”, or “étudiant”,<br> so it converts each word into a bunch of numbers (called <strong>vectors</strong>). It also add position info so it knows the order of the word.</p><p>Our input has five words :</p><p><strong>[“je”, “suis”, “un”, “bon”, “étudiant”]</strong></p><p>Each word becomes a vector using embeddings:</p><p><strong>[“je”] → [0.2, 0.4, 0.8, 0.1]</strong></p><p>Then we add positional encodings like:</p><p><strong>Position 0 → [0.1, 0.01, 0.03, 0.04]</strong></p><p><strong>Position 1 → [0.05, 0.02, 0.06, 0.01]</strong></p><p>So, the final embedded vector becomes:</p><p><strong>Word + Position = Final input</strong></p><p><strong>Step 2: Encoder Layers:</strong></p><p><strong>1.</strong> <strong>Multi-Head Attention:</strong></p><p>It looks at the input sentence in different ways — grammar, meaning, position, etc. So, when the model reads:</p><p><strong>“Je suis étudiant”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*DF3XDjOJ9POfY5EiwYzYyA.png" /></figure><p>Each “head” learns to focus on different parts of the sentence depending on the task:</p><ul><li>One head might learn grammar</li><li>Another might learn meaning</li><li>Another might focus on position</li></ul><p>All these heads look at the <strong>same sentence</strong> but from different angles and combine their insights</p><p><strong>2.</strong> <strong>Add &amp; Norm:</strong></p><p>The model processes the word <strong>“je”</strong> in <strong>“je suis étudiant”. </strong>After attention, it has learned something new about “je”. Now before moving on, it wants to:</p><p>· Keep the original version of “je”</p><p>· Mix it with the new info from attention</p><p>· Normalize the result so nothing is too big or small</p><p>This way, it doesn’t forget the original word and keeps things balanced.</p><p><strong>3.</strong> <strong>Feed Forward Neural Network (FNN):</strong></p><p>· This is just a small 2-layer neural network with ReLU or GELU in between</p><p>· Adds more complexity and helps the model understand better</p><p><strong>Step 3: Decoder Layers:</strong></p><p><strong>1.</strong> <strong>Masked Multi-Head Attention</strong></p><p>Imagine the decoder is trying to write:</p><p><strong>“I am a student”</strong><br> But it hasn’t written anything yet. It starts with:<br> → <strong>“I”</strong></p><p>It can’t look ahead to “am” or “student”.</p><p>→ <strong>“am”</strong></p><p>It can see earlier token ‘I’ but can’t look at ‘a’ or ‘student’</p><p>→ <strong>“a”</strong></p><p>It can see earlier token ‘I’ and ‘am’ but can’t look at ‘student’</p><p>→ <strong>“student”</strong></p><p>It can see all earlier tokens.</p><p>It only looks at what it already wrote. That’s why it’s called <strong>masked</strong> — the model is <strong>blind to the future.</strong> Without masking, the model would see the whole sentence and just copy the answer. But we want to <strong>learn how to predict</strong>, not memorize.</p><p><strong>2. Cross Attention (with Encoder)</strong></p><p>It simply looks back at the encoder and helps matching the French words to English words.</p><p>This layer <strong>looks at the encoder’s output</strong> and picks the matching info.</p><p>Like:</p><ul><li>“je” → “I”</li><li>“suis” → “am”</li><li>“étudiant” → “student”</li></ul><p><strong>3. Feed-Forward + Add &amp; Norm again</strong></p><p>Same as encoder — transforms and balances the data.</p><p><strong>Step 4: Linear+Softmax:</strong></p><p>The decoder gives you a vector like this:</p><p><strong>Decoder_output = [1.4, -0.3, 0.9, …]</strong> ← A list of numbers (NOT a word yet)</p><p>The <strong>Linear layer</strong> is a huge matrix that stores <strong>every word’s meaning</strong> as a vector:</p><p><strong>student → [1.2, -0.5, 1.0, …]</strong></p><p><strong>apple → [-0.3, 0.7, 0.2, …]</strong></p><p><strong>rocket → [0.1, 0.9, 1.3, …]</strong></p><p>The Linear layer takes your decoder_output and compares it to every word vector using dot product to calculate a score.</p><p>So, the output is :</p><p><strong>student: 4.8</strong></p><p><strong>apple: 1.9</strong></p><p><strong>rocket: 0.4</strong></p><p>Now you take all those scores and run <strong>SoftMax</strong> on them. SoftMax turns the scores into probabilities:</p><p><strong>student: 0.90 ✅</strong></p><p><strong>apple: 0.08</strong></p><p><strong>rocket: 0.02</strong></p><p>Now the model is confident:</p><p><strong>“The next word is student!”</strong></p><p>Hence it add this word to the sentence and we get the output as :</p><p><strong>I am a Student.</strong></p><h3>References:</h3><p><strong>Kaggle</strong>, <em>Foundational Large Language Models &amp; Text Generation</em>. Available: <a href="https://www.kaggle.com/whitepaper-foundational-llm-and-text-generation">https://www.kaggle.com/whitepaper-foundational-llm-and-text-generation</a>. [Accessed: 12-Apr-2025].</p><p><strong>Google Developers</strong>, <em>Machine Learning Crash Course: Large Language Models</em>. Available: <a href="https://developers.google.com/machine-learning/crash-course/llm">https://developers.google.com/machine-learning/crash-course/llm</a>. [Accessed: 12-Apr-2025].</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a86f0a43d97" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>