<?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 MaYa on Medium]]></title>
        <description><![CDATA[Stories by MaYa on Medium]]></description>
        <link>https://medium.com/@myasaie.65?source=rss-74a8f5405748------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*q6dHqrXzExnMp57uFQvpyw.jpeg</url>
            <title>Stories by MaYa on Medium</title>
            <link>https://medium.com/@myasaie.65?source=rss-74a8f5405748------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 10:53:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@myasaie.65/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[# Build Your First AI Support Agent Using LangChain]]></title>
            <link>https://medium.com/@myasaie.65/build-your-first-ai-support-agent-using-langchain-b6edcb14a58a?source=rss-74a8f5405748------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6edcb14a58a</guid>
            <dc:creator><![CDATA[MaYa]]></dc:creator>
            <pubDate>Thu, 26 Mar 2026 05:23:17 GMT</pubDate>
            <atom:updated>2026-03-30T00:31:54.133Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Build Your First AI Support Agent Using LangChain</strong></h3><h3><strong>Why Agentic AI?</strong></h3><p>Most AI integrations today follow a simple pattern: send a prompt, get a response. That works fine for chatbots that answer questions. But what happens when you need the AI to <strong><em>do</em></strong> things — look up a customer’s account, search internal documentation, create a support ticket — all within a single conversation, deciding on the fly which actions to take and in what order?</p><p>That’s the shift from <strong>generative AI</strong> to <strong>agentic AI</strong>.</p><p>A traditional LLM call is stateless and passive. You ask, it answers. An <strong><em>agent</em></strong>, on the other hand, operates in a loop: it observes the situation, reasons about what to do next, takes action using external tools, observes the result, and repeats — until the task is done. The LLM becomes the brain of a system that can actually interact with the world.</p><p>This distinction matters because real support workflows aren’t single-turn Q&amp;A. A support agent needs to:</p><p>- Pull up who the customer is and what plan they’re on</p><p>- Search documentation for relevant troubleshooting steps</p><p>- Decide whether to escalate by creating a ticket</p><p>- Set the right priority based on context — not just keywords</p><p>No single prompt-response cycle handles that. You need an agent.</p><p>In real-world support systems, this kind of agent can:</p><p>- reduce response time significantly <br>- automate repetitive support workflows <br>- ensure consistent decision-making across teams <br>- and prioritize high-value customers more effectively</p><p>In this article, I’ll walk you through building exactly that: <strong>an AI-powered</strong> <strong>support agent</strong> using <strong>TypeScript</strong>, <strong>LangChain</strong>, and <strong>OpenAI’s tool </strong>calling <strong>API</strong>. By the end, you’ll have a working CLI agent that reasons through multi-step support scenarios autonomously. Unlike simple chatbot tutorials, this project focuses on building an agent that can reason, take actions, and handle multi-step workflows.</p><p>The full source code is available on : <a href="https://github.com/maryamyasaei/ai-support-agent">https://github.com/maryamyasaei/ai-support-agent</a></p><h4><strong>Architecture</strong></h4><p>Before diving into code, let’s look at how the pieces fit together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vUsWmdwriSXToX5FvbZgYA.png" /></figure><p>The user types a message into the <strong>CLI</strong>. That message, along with the full conversation history, gets passed to the <strong>LangChain Agent Executor</strong>. The executor sends it to the LLM, which decides whether to call any tools. If it does, the results flow back into the agent’s scratchpad, and the LLM reasons again — possibly calling more tools — until it produces a final response.</p><h4><strong>Three tools are available:</strong></h4><p><strong>searchDocs </strong>— searches a mock knowledge base of 7 articles using weighted keyword matching</p><p><strong>createTicket</strong>— creates a support ticket with an auto-generated ID and priority level</p><p><strong>getUserContext</strong> — retrieves a user’s plan, role, and recent activity</p><p>The agent decides <strong><em>which</em> </strong>tools to call, <strong><em>when</em></strong>, and <strong><em>in what order</em></strong> — entirely based on the conversation context and its system prompt.</p><p>Now that we understand how the system works at a high level, let’s look at how to implement it step by step.</p><h4><strong>Setting Up the LLM</strong></h4><p>Everything starts with the language model. In LangChain, you initialize it as an object that your agent will use for reasoning:</p><pre>const model = process.env.OPENAI_MODEL || &quot;gpt-4o-mini&quot;;<br><br>  const llm = new ChatOpenAI({<br>    modelName: model,<br>    temperature: 0,<br>  });</pre><p>Two deliberate choices here:</p><p><strong>gpt-4o-mini </strong>as the default model.It’s fast, cheap, and more than capable enough for tool-calling decisions. For a support agent that needs to route queries and invoke tools with structured arguments, you don’t need the full weight of GPT-4o. The model name is configurable via an environment variable, so swapping to a more powerful model is a one-line change in <strong>.env</strong>.</p><p><strong>temperature: 0 </strong>for determinism<strong>.</strong> A support agent should give the <strong><em>same</em></strong> answer to the <strong><em>same</em></strong> question every time. Creative variation is a liability here — you want consistency, not surprises. Setting temperature to zero also makes the system easier to test and debug: given the same inputs, the agent will make the same tool-calling decisions.</p><h4><strong>Building the Agent</strong></h4><p>With the LLM initialized, the next step is wiring it into an agent that can reason and call tools. This is where LangChain’s abstractions earn their keep:</p><pre>import { ChatOpenAI } from &quot;@langchain/openai&quot;;<br>import { createToolCallingAgent, AgentExecutor } from &quot;langchain/agents&quot;;<br>import {ChatPromptTemplate, MessagesPlaceholder} from &quot;@langchain/core/prompts&quot;;<br>import { allTools } from &quot;../tools&quot;;<br><br>export async function createSupportAgent(): Promise&lt;AgentExecutor&gt; {<br>  const model = process.env.OPENAI_MODEL || &quot;gpt-4o-mini&quot;;<br>  const llm = new ChatOpenAI({<br>    modelName: model,<br>    temperature: 0,<br>  });<br><br>  const prompt = ChatPromptTemplate.fromMessages([<br>    [&quot;system&quot;, SYSTEM_PROMPT],<br>    new MessagesPlaceholder(&quot;chat_history&quot;),<br>    [&quot;human&quot;, &quot;{input}&quot;],<br>    new MessagesPlaceholder(&quot;agent_scratchpad&quot;),<br>  ]);<br><br>  const agent = await createToolCallingAgent({<br>    llm,<br>    tools: allTools,<br>    prompt,<br>  });<br><br>  return new AgentExecutor({<br>    agent,<br>    tools: allTools,<br>    returnIntermediateSteps: true,<br>    handleParsingErrors: true,<br>    maxIterations: 6,<br>  });</pre><p>Let’s break this down.</p><p><strong>The Prompt Template</strong></p><p>The prompt has four parts, and their order matters:</p><p>1. <strong>System message</strong> — defines the agent’s persona and decision-making rules (more on this below)</p><p>2. <strong>Chat history </strong>— the full conversation so far, injected as a <strong>MessagesPlaceholder</strong>. This gives the agent memory across turns.</p><p>3. <strong>Human input</strong> — the current user message</p><p>4. <strong>Agent scratchpad</strong> — LangChain uses this internally to track the agent’s reasoning chain. When the agent calls a tool, the tool’s result gets appended here, and the LLM sees it on the next iteration.</p><p><strong>createToolCallingAgent vs. ReAct</strong></p><p>LangChain offers multiple agent types. I chose <strong>createToolCallingAgent</strong> over the classic ReAct agent for a specific reason: <strong>it uses OpenAI’s native tool calling API</strong> rather than text-based reasoning.</p><p>With ReAct, the LLM writes text like <strong><em>”I should search the docs. Action: searchDocs. Input: password reset”</em></strong>, and LangChain parses that text to extract the tool call. It works, but it’s fragile — the model can format things slightly wrong, and parsing fails.</p><p>With <strong>createToolCallingAgent</strong>, the LLM returns structured JSON tool calls as part of its API response. No parsing needed. The trade-off is tighter coupling to providers that suppport structured tool calling, but for a production system, I’ll take reliability over provider flexibility every time.</p><p>The <strong>AgentExecutor</strong> is the runtime loop that ties everything together. A few key configuration choices:</p><p><strong>returnIntermediateSteps</strong>:<strong> true </strong>— this exposes every tool call the agent makes, which is essential for transparency. In the CLI, we display each tool call and its result so the support team can see <strong><em>why </em></strong>the agent reached its conclusion.</p><p><strong>handleParsingErrors: true </strong>— if the LLM produces malformed output, the executor recovers gracefully instead of crashing.</p><p><strong>maxIterations: 6 </strong>— a safety limit. Most support requests need 2–3 tool calls at most (fetch context → search docs → create ticket). Setting the cap at 6 gives headroom while preventing runaway loops if the model gets confused.</p><h4><strong>The System Prompt: Giving the Agent Judgment</strong></h4><p>The system prompt is arguably the most important part of the agent. It’s where you define not just <strong><em>what</em> </strong>the agent can do, but <em>how</em> it should think:</p><p><strong>Decision Guidelines</strong></p><p>1. <strong>Documentation First</strong>: For product questions, search the documentation before responding. Do NOT make up answers.</p><p>2. <strong>User Context</strong>: When a userId is mentioned, fetch the user’s context to personalize your response and inform priority decisions.</p><p>3. <strong>Ticket Creation</strong>: Only create tickets when:</p><p>- The user explicitly requests one</p><p>- The issue cannot be resolved through documentation alone</p><p>- The issue requires engineering intervention</p><p>4. <strong>Priority Assessment</strong> (when creating tickets):</p><p>- HIGH: Enterprise plan users, admin roles with blocking issues,</p><p>or explicit urgency language</p><p>- MEDIUM: Pro plan users, moderate impact issues</p><p>- LOW: Free plan users with general inquiries, non-blocking issues</p><p>5. <strong>Efficiency:</strong> Do not call tools unnecessarily. If you already have the information from a previous tool call, reuse it.</p><p>Notice that priority logic isn’t hard-coded in the application — it lives in the prompt. The LLM reasons about priority based on the user’s plan, role, the language they use (“urgent”, “blocked”, “critical”), and the nature of the issue. This is more flexible than rigid<strong> if/else</strong> rules because it handles edge cases naturally — like a free-tier user who’s completely locked out and uses urgent language.</p><p>The trade-off is less predictability. In a production system, you’d likely combine prompt-driven reasoning with rule-based guardrails.</p><h4>Tools: Giving the Agent Capabilities</h4><p>Each tool is defined using LangChain’s <strong>DynamicStructuredTool</strong> with a Zod schema for input validation. Here’s the ticket creation tool as an example:</p><pre>import { DynamicStructuredTool } from &quot;@langchain/core/tools&quot;;<br>import { z } from &quot;zod&quot;;<br><br>let ticketCounter = 1000;<br><br>const createTicketSchema = z.object({<br>  title: z.string(),<br>  priority: z.enum([&quot;low&quot;, &quot;medium&quot;, &quot;high&quot;]),<br>});<br><br>export const createTicketTool = new DynamicStructuredTool({<br>  name: &quot;createTicket&quot;,<br>  description:<br>    &quot;Create a support ticket for issues that cannot be resolved through documentation alone, &quot; +<br>    &quot;or when the user explicitly requests a ticket. &quot; +<br>    &quot;Takes &#39;title&#39; (string) and &#39;priority&#39; (&#39;low&#39; | &#39;medium&#39; | &#39;high&#39;) parameters. &quot; +<br>    &quot;Returns the new ticket ID and details.&quot;,<br>  schema: createTicketSchema,<br>  func: async ({ title, priority }: z.infer&lt;typeof createTicketSchema&gt;) =&gt; {<br>    ticketCounter++;<br>    const ticketId = `TKT-${ticketCounter}`;<br><br>    if (title.trim().length === 0) {<br>      return JSON.stringify({<br>        success: false,<br>        error: &quot;Ticket title cannot be empty.&quot;,<br>      });<br>    }<br><br>    return JSON.stringify({<br>      success: true,<br>      ticketId,<br>      title,<br>      priority,<br>      status: &quot;open&quot;,<br>      createdAt: new Date().toISOString(),<br>    });<br>  },<br>});</pre><p>The tool’s <strong>description</strong> is what the LLM reads to decide when and how to use it. Clear, specific descriptions are critical — vague descriptions lead to the agent calling tools at the wrong times.</p><p>The Zod schema enforces that <strong>priority</strong> must be one of ”low”, ”medium”, or ”high”. If the LLM passes something invalid, it’s caught before the function runs. This is one of the advantages of structured tool calling over text-based approaches.</p><h3>Seeing It in Action</h3><p><em>Here’s what a multi-step interaction looks like. The agent autonomously chains three tool calls to resolve an urgent billing issue:</em></p><pre>You: User user-1 is blocked from billing and this is urgent.<br><br>  --- Agent Tool Calls ---<br>  [getUserContext] called with: {&quot;userId&quot;:&quot;user-1&quot;}<br>  Result:<br>    { &quot;found&quot;: true, &quot;userId&quot;: &quot;user-1&quot;, &quot;name&quot;: &quot;Alice Johnson&quot;,<br>      &quot;plan&quot;: &quot;enterprise&quot;, &quot;role&quot;: &quot;admin&quot;, ... }<br>  ---<br>  [searchDocs] called with: {&quot;query&quot;:&quot;billing blocked access&quot;}<br>  Result:<br>    { &quot;results&quot;: [{ &quot;id&quot;: &quot;doc-2&quot;, &quot;title&quot;: &quot;Billing &amp; Subscription<br>      Management&quot;, ... }], ... }<br>  ---<br>  [createTicket] called with: {&quot;title&quot;:&quot;Enterprise admin blocked from<br>    billing access&quot;,&quot;priority&quot;:&quot;high&quot;}<br>  Result:<br>    { &quot;success&quot;: true, &quot;ticketId&quot;: &quot;TKT-1001&quot;, &quot;priority&quot;: &quot;high&quot;, ... }<br>  ---<br><br>Agent: I&#39;ve looked into this for Alice Johnson (Enterprise Admin). She has<br>recent billing activity, so this appears to be an ongoing issue. I&#39;ve<br>created a high-priority ticket:<br><br>  Ticket ID: TKT-1001<br>  Priority: High (Enterprise admin, urgent blocking issue)</pre><p><em>Three tool calls, fully autonomous. The agent:</em></p><ol><li><em>Recognized a user ID in the message and fetched their context</em></li><li><em>Searched documentation for billing-related content</em></li><li><em>Created a high-priority ticket — because the user is enterprise-tier, an admin, and the language indicated urgency</em></li></ol><p><em>No explicit instructions told it to do these three things in this order. The agent reasoned through the workflow based on its system prompt and the conversation context.</em></p><h4>Running It Yourself</h4><pre>git clone https://github.com/maryamyasaei/ai-support-agent.git<br>cd ai-support-agent<br>npm install<br>cp .env.example .env<br># Add your OpenAI API key to .env<br>npm start</pre><p>You’ll need Node.js 18+ and an <strong>OpenAI API Key </strong>: https://platform.openai.com</p><h4>What I’d Change for Production</h4><p>This is a working prototype with mock data. To take it to production, the key upgrades would be:</p><p><strong>Vector search</strong> instead of keyword matching — replace the mock knowledge base with an embedding store like Pinecone or Chroma for semantic retrieval</p><p><strong>Persistent memory</strong> — swap the in-memory chat history for Redis or a database to support multi-session conversations</p><p><strong>Streaming responses </strong>— use LangChain’s streaming API so users see tokens in real-time instead of waiting for the full response</p><p><strong>Observability </strong>— add LangSmith tracing to monitor tool-calling decisions and catch agent misbehavior</p><p><strong>HTTP API layer</strong> — add an Express or Fastify server so other systems can integrate with the agent beyond the CLI</p><h4>Wrapping Up</h4><p>Agentic AI is not just about generating better responses — it’s about building systems that can take meaningful actions.</p><p>This project is a small step in that direction.</p><p>By combining an LLM with structured tools and a reasoning loop, we move from passive responses to active problem-solving systems.</p><p>If you’re exploring AI systems beyond chat interfaces, agents are one of the most powerful patterns to understand.</p><p>And if you’re working on similar problems, I’d love to connect and learn from your experience.</p><p><strong><em>Built with TypeScript, LangChain, and OpenAI. Opinions are my own.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6edcb14a58a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>