<?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 Elkhan Alizada on Medium]]></title>
        <description><![CDATA[Stories by Elkhan Alizada on Medium]]></description>
        <link>https://medium.com/@elkhan.alizada?source=rss-d6958a3299b0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*QWgTEHbdXOvzSdEb</url>
            <title>Stories by Elkhan Alizada on Medium</title>
            <link>https://medium.com/@elkhan.alizada?source=rss-d6958a3299b0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 15:13:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@elkhan.alizada/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[AI Agent Architecture — A Practical Guide to Building Reliable Systems]]></title>
            <link>https://medium.com/@elkhan.alizada/ai-agent-architecture-a-practical-guide-to-building-reliable-systems-6bd0ef29b07d?source=rss-d6958a3299b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bd0ef29b07d</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Elkhan Alizada]]></dc:creator>
            <pubDate>Thu, 26 Mar 2026 10:56:26 GMT</pubDate>
            <atom:updated>2026-03-26T10:56:26.614Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Everyone is talking about AI agents. Few are building </em><strong><em>reliable ones</em></strong><em>.</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GZXfAqZOw9DeK60XqZY3GQ.png" /></figure><p>Most AI agent articles stop at the demo stage: a model, a few tools, a clever prompt, and a loop.</p><p>That is enough to impress people in a notebook. It is not enough to run a reliable system in production.</p><p>If you want agents that survive real traffic, real failures, real latency, and real users, you need to think in terms of architecture, not just prompting.</p><p>This guide combines two useful perspectives:</p><ul><li>the <strong>production-system view</strong> of agent infrastructure — gateways, context, memory, safety, and analytics</li><li>the <strong>planning-agent view</strong> of how an orchestrator should break work down and execute it reliably</li></ul><p>The goal is simple: help you design an agent system that is effective, observable, and predictable enough to trust.</p><h3>Why “Just Call the LLM” Breaks Down</h3><p>A single LLM call works for narrow tasks — rewrite text, classify a ticket, summarize a document. An agent system appears when the model must do more than one step:</p><ul><li>decide what to do</li><li>choose tools</li><li>retrieve or compress context</li><li>remember prior state</li><li>recover from failures</li><li>verify results before responding</li></ul><p>At that point, your main problem is no longer “which model should I use?” It becomes:</p><ul><li>How does the system <strong>plan</strong>?</li><li>How does it <strong>route</strong> requests?</li><li>How does it <strong>control context growth</strong>?</li><li>How does it <strong>isolate failures</strong>?</li><li>How does it <strong>observe</strong> what happened?</li><li>How does it <strong>stop</strong> bad outputs from becoming bad actions?</li></ul><p>Those are architecture questions.</p><h3>The Mental Model: An Agent is an Orchestrated System</h3><blockquote>The LLM is not the system. The LLM is one component inside the system.</blockquote><p>In production, the center of gravity is the <strong>orchestrator</strong>. It coordinates models, tools, memory, context assembly, safety checks, and telemetry. Everything else connects through controlled gateways.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*_dDccDvWQqZPv8VOVlC23w.png" /></figure><p>This architecture separates concerns:</p><ul><li>the <strong>orchestrator</strong> decides the workflow</li><li>the <strong>LLM gateway</strong> standardizes model access and policy enforcement</li><li>the <strong>tools gateway</strong> controls external actions with schema validation, auth, timeouts, and audit logs</li><li>the <strong>memory gateway</strong> manages persistent state — short-term task variables, conversation summaries, user preferences, episodic memory</li><li>the <strong>context gateway</strong> decides what the model sees <em>right now</em> — not everything, just the right information</li><li>the <strong>safety and analytics layer</strong> makes the whole system governable</li></ul><p>That is the difference between a neat prototype and a system you can operate.</p><h3>The Core Building Blocks</h3><h3>1. Orchestrator</h3><p>The runtime brain. In simple systems it’s a loop. In mature systems it becomes a state machine or workflow engine. Responsibilities include selecting the execution pattern, tracking step state, handling retries, and deciding when to stop.</p><h3>2. LLM Gateway</h3><p>A production agent should never call model providers directly from random parts of the codebase. The gateway centralizes authentication, rate limiting, provider failover, prompt injection screening, cost tracking, model routing, caching, and degradation policies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*MLwlvzCKpxzptbm6zD4IBg.png" /></figure><p>Without this layer, every product team implements its own model access logic, and reliability collapses into duplication.</p><h3>3. Context Gateway</h3><p>Most agent failures are context failures, not model failures. The model can only reason over what it sees. If the context is incomplete, overloaded, stale, or contradictory, the output will degrade no matter how good the model is.</p><blockquote>Do not treat the context window as storage. Treat it as working memory.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eycrV_0MAq4NaV57UYRANw.png" /></figure><h3>4. Memory Gateway</h3><p>Memory should be explicit, typed, and governed:</p><ul><li><strong>Short-term state</strong>: current task variables, tool outputs, temporary plan artifacts</li><li><strong>Conversation memory</strong>: condensed summary of prior turns</li><li><strong>User memory</strong>: stable preferences, permissions, profile facts</li><li><strong>Episodic memory</strong>: notable past interactions or outcomes</li></ul><p>Bad memory systems write everything and retrieve everything. Good systems are selective in both directions.</p><h3>5. Tools Gateway</h3><p>Tools are where agents stop being chatbots and start affecting the outside world. That also makes them the biggest source of risk. The gateway provides schema validation, auth isolation, timeouts, retries, idempotency, and audit logs.</p><p>If an agent can send emails, create tickets, move money, or trigger workflows, you need a controlled action boundary.</p><h3>Picking the Right Execution Pattern</h3><p>Not every task needs the same kind of agent. Choosing the wrong pattern is a common source of latency, cost, and failure. Here are seven patterns, ordered from most deterministic to most autonomous.</p><h3>Pattern 1: LLM Workflow (Deterministic)</h3><p>The simplest pattern. You define the execution graph explicitly — the LLM handles individual steps, but the flow is predetermined with conditional branches. No autonomy, maximum reliability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2OxGo73eXhSSGtcwPUmaHw.png" /></figure><p><strong><em>Use when:</em></strong><em> high-risk processes where reliability matters more than flexibility- document processing, structured extraction, compliance workflows.</em></p><pre>from langchain_openai import ChatOpenAI<br>from langgraph.graph import StateGraph, END<br>from typing import TypedDict<br><br>llm = ChatOpenAI(model=&quot;gpt-5&quot;)<br><br>class State(TypedDict):<br>    input: str<br>    classification: str<br>    result: str<br><br>def classify(state: State) -&gt; State:<br>    result = llm.invoke(f&quot;Classify this request: {state[&#39;input&#39;]}&quot;)<br>    return {&quot;classification&quot;: result.content}<br><br>def handle_billing(state: State) -&gt; State:<br>    result = llm.invoke(f&quot;Handle billing inquiry: {state[&#39;input&#39;]}&quot;)<br>    return {&quot;result&quot;: result.content}<br><br>def handle_technical(state: State) -&gt; State:<br>    result = llm.invoke(f&quot;Handle technical issue: {state[&#39;input&#39;]}&quot;)<br>    return {&quot;result&quot;: result.content}<br><br>def route(state: State) -&gt; str:<br>    if &quot;billing&quot; in state[&quot;classification&quot;].lower():<br>        return &quot;billing&quot;<br>    return &quot;technical&quot;<br><br>workflow = StateGraph(State)<br>workflow.add_node(&quot;classify&quot;, classify)<br>workflow.add_node(&quot;billing&quot;, handle_billing)<br>workflow.add_node(&quot;technical&quot;, handle_technical)<br><br>workflow.set_entry_point(&quot;classify&quot;)<br>workflow.add_conditional_edges(&quot;classify&quot;, route, {<br>    &quot;billing&quot;: &quot;billing&quot;,<br>    &quot;technical&quot;: &quot;technical&quot;,<br>})<br>workflow.add_edge(&quot;billing&quot;, END)<br>workflow.add_edge(&quot;technical&quot;, END)<br><br>app = workflow.compile()</pre><h3>Pattern 2: ReAct (Reason + Act)</h3><p>The classic agentic loop: think, call a tool, observe, repeat. A good default when the path is not known in advance and the agent needs step-by-step interaction with the environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6oZYMQJ99h1MX9cFT7e4Lw.png" /></figure><p><strong><em>Use when:</em></strong><em> the task is exploratory, tool outputs affect the next decision, and you need flexibility more than efficiency.</em></p><p><strong><em>Main downside:</em></strong><em> too many LLM calls, too much latency, and unstable trajectories for long tasks.</em></p><pre>from langchain_openai import ChatOpenAI<br>from langchain_core.tools import tool<br>from langgraph.prebuilt import create_react_agent<br><br>@tool<br>def search_database(query: str) -&gt; str:<br>    &quot;&quot;&quot;Search the product database for information.&quot;&quot;&quot;<br>    return f&quot;Found 3 results for: {query}&quot;<br><br>@tool<br>def calculate_price(item: str, quantity: int) -&gt; str:<br>    &quot;&quot;&quot;Calculate the total price for an item.&quot;&quot;&quot;<br>    prices = {&quot;widget&quot;: 9.99, &quot;gadget&quot;: 24.99}<br>    total = prices.get(item, 0) * quantity<br>    return f&quot;Total: ${total:.2f}&quot;<br><br>llm = ChatOpenAI(model=&quot;gpt-5&quot;)<br>agent = create_react_agent(llm, [search_database, calculate_price])<br><br>result = agent.invoke({<br>    &quot;messages&quot;: [(&quot;user&quot;, &quot;How much would 5 widgets cost?&quot;)]<br>})</pre><h3>Pattern 3: Reflexion</h3><p>Extends ReAct by adding a self-critique step. The agent generates a draft, evaluates it, and iterates — essentially building in a “code review” loop.</p><p>Do not add reflection everywhere. It increases latency and cost. Use it where error reduction justifies the extra pass.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uIKC3vXJ-2F311G10iGTWA.png" /></figure><p><strong><em>Use when:</em></strong><em> output quality is critical and verifiable — code generation, mathematical reasoning, report drafting, structured extraction.</em></p><pre>from langchain_openai import ChatOpenAI<br>from langgraph.graph import StateGraph, END<br>from typing import TypedDict, List<br><br>llm = ChatOpenAI(model=&quot;gpt-5&quot;)<br><br>class ReflexionState(TypedDict):<br>    task: str<br>    draft: str<br>    critique: str<br>    history: List[str]<br>    iteration: int<br><br>def generate_draft(state: ReflexionState) -&gt; ReflexionState:<br>    history_context = &quot;\n&quot;.join(state.get(&quot;history&quot;, []))<br>    prompt = f&quot;&quot;&quot;Task: {state[&#39;task&#39;]}<br>Previous attempts and feedback: {history_context}<br>Generate an improved solution:&quot;&quot;&quot;<br>    result = llm.invoke(prompt)<br>    return {&quot;draft&quot;: result.content, &quot;iteration&quot;: state.get(&quot;iteration&quot;, 0) + 1}<br><br>def critique_draft(state: ReflexionState) -&gt; ReflexionState:<br>    prompt = f&quot;&quot;&quot;Evaluate this solution for correctness and quality:<br>Task: {state[&#39;task&#39;]}<br>Solution: {state[&#39;draft&#39;]}<br>Provide specific feedback on what&#39;s wrong and how to improve:&quot;&quot;&quot;<br>    result = llm.invoke(prompt)<br>    history = state.get(&quot;history&quot;, [])<br>    history.append(f&quot;Draft: {state[&#39;draft&#39;]}\nFeedback: {result.content}&quot;)<br>    return {&quot;critique&quot;: result.content, &quot;history&quot;: history}<br><br>def should_continue(state: ReflexionState) -&gt; str:<br>    if state[&quot;iteration&quot;] &gt;= 3:<br>        return &quot;end&quot;<br>    if &quot;looks good&quot; in state[&quot;critique&quot;].lower():<br>        return &quot;end&quot;<br>    return &quot;retry&quot;<br><br>graph = StateGraph(ReflexionState)<br>graph.add_node(&quot;generate&quot;, generate_draft)<br>graph.add_node(&quot;critique&quot;, critique_draft)<br>graph.set_entry_point(&quot;generate&quot;)<br>graph.add_edge(&quot;generate&quot;, &quot;critique&quot;)<br>graph.add_conditional_edges(&quot;critique&quot;, should_continue, {<br>    &quot;retry&quot;: &quot;generate&quot;,<br>    &quot;end&quot;: END,<br>})<br><br>reflexion_agent = graph.compile()</pre><h3>Pattern 4: Plan-and-Execute</h3><p>Instead of figuring out one step at a time, the agent first creates a complete plan, then executes each step sequentially. This separation offers three advantages: <strong>faster execution</strong> (fewer LLM consultations), <strong>lower cost</strong> (smaller models can handle sub-tasks), and <strong>better performance</strong> (explicit planning forces comprehensive reasoning upfront).</p><p>If the initial plan is wrong, execution may drift before the system notices — so the evaluator can trigger replanning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ch_oEvFH_H72iEKc0x8ZQ.png" /></figure><p><strong><em>Use when:</em></strong><em> the task is multi-step but reasonably decomposable, and the workflow benefits from a visible intermediate plan.</em></p><pre>from langchain_openai import ChatOpenAI<br>from langgraph.graph import StateGraph, END<br>from typing import TypedDict, List, Optional<br><br>llm = ChatOpenAI(model=&quot;gpt-5&quot;)<br><br>class PlanExecuteState(TypedDict):<br>    objective: str<br>    plan: List[str]<br>    current_step: int<br>    results: List[str]<br>    final_answer: Optional[str]<br><br>def planner(state: PlanExecuteState) -&gt; PlanExecuteState:<br>    prompt = f&quot;&quot;&quot;Break this objective into concrete steps:<br>Objective: {state[&#39;objective&#39;]}<br>Previous results: {state.get(&#39;results&#39;, [])}<br>Return a numbered list of steps:&quot;&quot;&quot;<br>    result = llm.invoke(prompt)<br>    steps = [s.strip() for s in result.content.split(&quot;\n&quot;) if s.strip()]<br>    return {&quot;plan&quot;: steps, &quot;current_step&quot;: 0, &quot;results&quot;: []}<br><br>def executor(state: PlanExecuteState) -&gt; PlanExecuteState:<br>    step = state[&quot;plan&quot;][state[&quot;current_step&quot;]]<br>    context = &quot;\n&quot;.join(state[&quot;results&quot;])<br>    prompt = f&quot;&quot;&quot;Execute this step:<br>Step: {step}<br>Context from previous steps: {context}&quot;&quot;&quot;<br>    result = llm.invoke(prompt)<br>    results = state[&quot;results&quot;] + [f&quot;{step}: {result.content}&quot;]<br>    return {&quot;results&quot;: results, &quot;current_step&quot;: state[&quot;current_step&quot;] + 1}<br><br>def should_continue(state: PlanExecuteState) -&gt; str:<br>    if state[&quot;current_step&quot;] &gt;= len(state[&quot;plan&quot;]):<br>        return &quot;evaluate&quot;<br>    return &quot;execute&quot;<br><br>def evaluate(state: PlanExecuteState) -&gt; PlanExecuteState:<br>    prompt = f&quot;&quot;&quot;Based on these results, is the objective achieved?<br>Objective: {state[&#39;objective&#39;]}<br>Results: {chr(10).join(state[&#39;results&#39;])}<br>If yes, provide the final answer. If no, say REPLAN.&quot;&quot;&quot;<br>    result = llm.invoke(prompt)<br>    if &quot;REPLAN&quot; in result.content:<br>        return {&quot;final_answer&quot;: None}<br>    return {&quot;final_answer&quot;: result.content}<br><br>def route_after_eval(state: PlanExecuteState) -&gt; str:<br>    return &quot;done&quot; if state[&quot;final_answer&quot;] else &quot;replan&quot;<br><br>graph = StateGraph(PlanExecuteState)<br>graph.add_node(&quot;planner&quot;, planner)<br>graph.add_node(&quot;executor&quot;, executor)<br>graph.add_node(&quot;evaluate&quot;, evaluate)<br>graph.set_entry_point(&quot;planner&quot;)<br>graph.add_conditional_edges(&quot;planner&quot;, should_continue, {<br>    &quot;execute&quot;: &quot;executor&quot;, &quot;evaluate&quot;: &quot;evaluate&quot;<br>})<br>graph.add_conditional_edges(&quot;executor&quot;, should_continue, {<br>    &quot;execute&quot;: &quot;executor&quot;, &quot;evaluate&quot;: &quot;evaluate&quot;<br>})<br>graph.add_conditional_edges(&quot;evaluate&quot;, route_after_eval, {<br>    &quot;replan&quot;: &quot;planner&quot;, &quot;done&quot;: END<br>})<br><br>plan_execute_agent = graph.compile()</pre><h3>Pattern 5: ReWOO (Reasoning Without Observations)</h3><p>ReWOO improves planning by separating reasoning from tool execution and allowing <strong>variable assignment</strong> across steps. The planner produces a structured task list with placeholders like #E1, #E2 that reference prior results. The worker executes tasks sequentially, substituting variables, and a solver synthesizes the final answer.</p><p>This eliminates unnecessary LLM calls between steps — the plan is made once, and execution is mechanical.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*dlG8EKcxCRFzV5leNJ_aQg.png" /></figure><p><strong><em>Use when:</em></strong><em> tasks can be decomposed ahead of time, intermediate results feed later steps, and you want lower cost than fully reactive loops.</em></p><p><strong><em>Main downside:</em></strong><em> more complexity in state representation and execution.</em></p><h3>Pattern 6: LLMCompiler (Parallel DAG Execution)</h3><p>For some tasks, the best plan is not a sequence — it is a graph. The planner outputs a <strong>DAG (Directed Acyclic Graph)</strong> of tasks with explicit dependencies. A Task Fetching Unit schedules tasks for parallel execution as soon as their dependencies are satisfied. A Joiner decides whether to respond or replan.</p><p><a href="https://arxiv.org/abs/2312.04511">The original paper</a> reports <strong>3.6x speedup</strong> over sequential approaches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*Z2RjJPrD1reLuWd2oThw9g.png" /></figure><p><strong><em>Use when:</em></strong><em> independent sub-tasks exist, tool calls are slow, latency matters, and task dependencies can be expressed explicitly.</em></p><p><strong><em>Main downside:</em></strong><em> orchestration complexity increases quickly.</em></p><h3>Pattern 7: Multi-Agent Systems</h3><p>The most powerful — and complex — pattern. A planner distributes tasks to <strong>separate sub-agents</strong>, each with its own orchestrator, tools, and context. Sub-agents can run in parallel with full isolation.</p><p>But many multi-agent designs are just complexity disguised as architecture. Use multiple agents only when specialization creates a measurable gain in quality, isolation, parallelism, or governance. Otherwise, a single orchestrator with typed tools is usually simpler and more reliable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*kMrra9002jTZ_g-iLK7PRQ.png" /></figure><h3>Pattern Selection Guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*udllh4yEyCi8yNXW4lN9YA.png" /></figure><p>When in doubt, start simple and add complexity only when needed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*y7hnnBKUMlWVum5fRcQXVA.png" /></figure><h3>Reliability Is Mostly About Control Loops</h3><p>The reliability of an agent system is not determined by model intelligence. It comes from the engineering around the model — feedback loops and control mechanisms.</p><p>Every production agent needs these loops:</p><ul><li><strong>Validation before action</strong> — check tool arguments against schemas, verify user permissions, enforce policy constraints before any real-world side effect. If the agent is uncertain, it should ask, defer, or route to a human. Reliability is partly the ability to stop.</li><li><strong>Retry with backoff</strong> — LLM calls fail, APIs time out, rate limits hit. Transient failures should not kill the entire run.</li><li><strong>Fallback chains</strong> — if the primary model is down or returns garbage, route to a secondary model or a simpler deterministic path.</li><li><strong>Escalation to humans</strong> — for sensitive actions (payments, deletions, external communications), require explicit human approval before execution.</li><li><strong>Cost and step budgets</strong> — hard limits on token spend and iteration count prevent runaway agents from burning money or looping forever.</li></ul><p>The patterns in the previous section (Reflexion, Plan-and-Execute) provide <em>task-level</em> control loops. The mechanisms above provide <em>system-level</em> control loops. You need both.</p><h3>From Patterns to Production Code</h3><p>The patterns above are conceptual. To make them real, you need concrete runtime boundaries: centralized model access, validated tool execution, structured tracing, and explicit termination.</p><p>Below is a realistic skeleton for a reliable agent orchestrator. It is intentionally simple, but it demonstrates the right boundaries.</p><pre>from __future__ import annotations<br><br>from dataclasses import dataclass, field<br>from typing import Any, Protocol<br>import time<br><br><br>class LLMClient(Protocol):<br>    def generate(<br>        self,<br>        *,<br>        system: str,<br>        messages: list[dict[str, str]],<br>        tools: list[dict[str, Any]] | None = None,<br>    ) -&gt; dict[str, Any]: ...<br><br><br>class Tool(Protocol):<br>    name: str<br>    def run(self, arguments: dict[str, Any]) -&gt; dict[str, Any]: ...<br><br><br>@dataclass<br>class TraceEvent:<br>    step: str<br>    started_at: float<br>    ended_at: float<br>    metadata: dict[str, Any] = field(default_factory=dict)<br><br><br>@dataclass<br>class RunState:<br>    user_input: str<br>    messages: list[dict[str, str]] = field(default_factory=list)<br>    tool_results: list[dict[str, Any]] = field(default_factory=list)<br>    trace: list[TraceEvent] = field(default_factory=list)<br><br><br>class AgentOrchestrator:<br>    def __init__(self, llm: LLMClient, tools: list[Tool], system_prompt: str) -&gt; None:<br>        self.llm = llm<br>        self.tools = {tool.name: tool for tool in tools}<br>        self.system_prompt = system_prompt<br><br>    def run(self, user_input: str, max_steps: int = 8) -&gt; str:<br>        state = RunState(<br>            user_input=user_input,<br>            messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_input}],<br>        )<br><br>        for step_index in range(max_steps):<br>            llm_response = self._call_model(state, step=f&quot;reason-{step_index}&quot;)<br>            action = llm_response.get(&quot;action&quot;, &quot;respond&quot;)<br><br>            if action == &quot;respond&quot;:<br>                return llm_response[&quot;answer&quot;]<br><br>            if action == &quot;tool&quot;:<br>                tool_name = llm_response[&quot;tool_name&quot;]<br>                arguments = llm_response.get(&quot;arguments&quot;, {})<br>                tool_output = self._run_tool(tool_name, arguments, step=f&quot;tool-{step_index}&quot;)<br>                state.tool_results.append(tool_output)<br>                state.messages.append({<br>                    &quot;role&quot;: &quot;tool&quot;,<br>                    &quot;content&quot;: f&quot;{tool_name} returned: {tool_output}&quot;,<br>                })<br>                continue<br><br>            raise RuntimeError(f&quot;Unknown action: {action}&quot;)<br><br>        raise TimeoutError(&quot;Agent exceeded max_steps&quot;)<br><br>    def _call_model(self, state: RunState, step: str) -&gt; dict[str, Any]:<br>        started_at = time.time()<br>        response = self.llm.generate(<br>            system=self.system_prompt,<br>            messages=state.messages,<br>            tools=[{&quot;name&quot;: name} for name in self.tools],<br>        )<br>        ended_at = time.time()<br>        state.trace.append(TraceEvent(<br>            step=step, started_at=started_at, ended_at=ended_at,<br>            metadata={&quot;response_keys&quot;: list(response.keys())},<br>        ))<br>        return response<br><br>    def _run_tool(self, tool_name: str, arguments: dict[str, Any], step: str) -&gt; dict[str, Any]:<br>        if tool_name not in self.tools:<br>            raise ValueError(f&quot;Tool not registered: {tool_name}&quot;)<br>        if not isinstance(arguments, dict):<br>            raise TypeError(f&quot;Arguments for {tool_name} must be a dict&quot;)<br><br>        started_at = time.time()<br>        result = self.tools[tool_name].run(arguments)<br>        ended_at = time.time()<br><br>        return {<br>            &quot;tool_name&quot;: tool_name,<br>            &quot;arguments&quot;: arguments,<br>            &quot;result&quot;: result,<br>            &quot;duration_ms&quot;: int((ended_at - started_at) * 1000),<br>            &quot;trace_step&quot;: step,<br>        }</pre><p>This skeleton is still missing production-grade features, but the boundaries are already correct: model access is centralized, tool execution is validated, step tracing is first-class, and termination is explicit.</p><h3>Adding Production Layers</h3><p>The next step is wrapping the orchestrator with context assembly, policy enforcement, and observability.</p><pre>from dataclasses import dataclass<br><br><br>@dataclass<br>class UserContext:<br>    user_id: str<br>    permissions: set[str]<br>    preferences: dict[str, str]<br><br><br>class ContextGateway:<br>    def build(<br>        self,<br>        user_ctx: UserContext,<br>        user_input: str,<br>        memory: list[str],<br>        docs: list[str],<br>    ) -&gt; list[dict[str, str]]:<br>        summary = &quot;\n&quot;.join(memory[-3:])<br>        references = &quot;\n&quot;.join(docs[:3])<br>        return [<br>            {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;Use retrieved facts when available. If evidence is insufficient, say so explicitly.&quot;},<br>            {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: f&quot;User preferences: {user_ctx.preferences}&quot;},<br>            {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: f&quot;Relevant memory summary:\n{summary}&quot;},<br>            {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: f&quot;Retrieved references:\n{references}&quot;},<br>            {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_input},<br>        ]<br><br><br>class PolicyEngine:<br>    def allow(self, user_ctx: UserContext, tool_name: str) -&gt; bool:<br>        return tool_name in user_ctx.permissions<br><br><br>class SafeToolRunner:<br>    def __init__(self, policy: PolicyEngine) -&gt; None:<br>        self.policy = policy<br><br>    def execute(self, user_ctx: UserContext, tool: Tool, arguments: dict[str, object]) -&gt; dict[str, object]:<br>        if not self.policy.allow(user_ctx, tool.name):<br>            raise PermissionError(f&quot;User cannot invoke tool {tool.name}&quot;)<br>        return tool.run(arguments)</pre><p>This is the shape of a reliable system: the orchestrator runs the workflow, the context layer constructs the model input deliberately, the policy layer gates actions, and the trace layer records what happened.</p><h3>Modern Production Considerations</h3><p>If you are building agents today, these practices have become standard:</p><p><strong>Structured outputs.</strong> Modern LLM APIs (OpenAI’s response_format, Anthropic&#39;s tool use) can return validated JSON matching a schema. Use this instead of parsing free-text responses — it eliminates an entire class of output-parsing bugs.</p><p><strong>Model Context Protocol (MCP).</strong> Anthropic’s MCP is becoming a standard interface for connecting agents to external tools and data sources. Instead of writing custom tool wrappers for each integration, MCP provides a unified protocol. If you are building a tool ecosystem, design for MCP compatibility.</p><p><strong>Streaming and async execution.</strong> Production agents should stream intermediate results to the user. Nobody wants to stare at a spinner for 30 seconds. LangGraph supports streaming natively via .astream() and .astream_events() — use them.</p><p><strong>Evaluation and tracing platforms.</strong> Observability is not just logging. Platforms like LangSmith, Braintrust, and Arize Phoenix provide trace visualization, regression testing, and automated evaluation pipelines. Integrate one from day one — retrofitting observability is painful.</p><p><strong>Model cascading.</strong> Use expensive models (GPT-5, Claude Sonnet/Opus) for planning and complex reasoning. Route simpler sub-tasks to faster, cheaper models (GPT-5-mini, Claude Haiku). The gateway layer makes this routing transparent to the rest of the system.</p><h3>Failure Modes to Design For</h3><p>Reliable agent systems are built around expected failure modes:</p><h3>1. Tool Hallucination</h3><p>The model invents a tool, uses the wrong schema, or passes malformed arguments. <strong>Mitigation:</strong> strict schema validation, limited tool exposure, typed wrappers.</p><h3>2. Context Poisoning</h3><p>Retrieved documents, user content, or tool outputs inject instructions that hijack the agent. <strong>Mitigation:</strong> isolate untrusted content, label sources, use policy prompts and allowlists, scan risky inputs.</p><h3>3. Infinite or Wasteful Loops</h3><p>The agent keeps thinking, replanning, or re-calling tools without meaningful progress. <strong>Mitigation:</strong> max step limits, progress checks, cost budgets, loop detectors.</p><h3>4. Over-Retrieval</h3><p>The system shoves too much context into the prompt and makes the model less accurate. <strong>Mitigation:</strong> rank aggressively, summarize, enforce context budgets.</p><h3>5. Silent Action Risk</h3><p>The agent performs irreversible actions too early or without authorization. <strong>Mitigation:</strong> approval gates, dry-run mode, two-phase execution, role-based permissions.</p><h3>When Not to Use an Agent</h3><p>This is just as important as knowing when to use one.</p><p>Do <strong>not</strong> use an agent when:</p><ul><li>a deterministic workflow is enough</li><li>the task can be solved by retrieval plus one response generation step</li><li>tool use is minimal and fixed</li><li>latency requirements are strict and multi-step reasoning is unnecessary</li></ul><p>Many systems labeled “agents” should actually be a classifier plus a workflow engine, RAG plus templates, or search plus deterministic post-processing.</p><p>Agents are powerful, but they are not free. They add complexity, latency, and new failure modes.</p><h3>Final Takeaway</h3><blockquote>Reliable AI agents are not prompt chains with ambition. They are controlled systems with planning, memory, context, action boundaries, and observability.</blockquote><p>The model is important. The architecture is what makes it dependable.</p><p>If you remember only three things, make them these:</p><ol><li><strong>Put an orchestrator at the center.</strong> It is the runtime brain that coordinates everything else.</li><li><strong>Treat context and memory as separate system responsibilities.</strong> Context is what the model sees now. Memory is what the system retains across time. Conflating them is a top source of bugs.</li><li><strong>Build guardrails and tracing before you scale usage.</strong> If you cannot trace every decision, tool call, and failure, you do not operate the agent — you merely host it.</li></ol><p>Start simple. Add complexity when the task demands it. And always, always make the system observable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bd0ef29b07d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Own MCP Playground: Build It with Streamlit, LangGraph, and Docker]]></title>
            <link>https://medium.com/@elkhan.alizada/your-own-ai-agent-playground-build-it-with-streamlit-langgraph-and-docker-4caeb6fe0ac4?source=rss-d6958a3299b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/4caeb6fe0ac4</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Elkhan Alizada]]></dc:creator>
            <pubDate>Tue, 20 May 2025 13:03:17 GMT</pubDate>
            <atom:updated>2025-05-20T14:18:35.158Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, I’ll show you how to create a chat-based AI that can call MCP servers (like weather or currency tools) in real-time, using a modular and containerized setup.</p><p>Imagine asking your language model:<br> <em>“What’s the weather like in Tokyo tomorrow? And how much is 100 USD in yen?”</em><br> Now imagine it responds — clearly, usefully, with up-to-date information.</p><p>No plugins to configure, no extra overhead — just a simple way to connect your LLM to real-world tools. That’s what the MCP Playground offers: a lightweight, containerized environment where language models can interact with external APIs and services.</p><p>Using a straightforward Streamlit-based chat interface, your model can access real-time data — from weather forecasts to currency conversions — or any custom tool you define.</p><p>Whether you’re experimenting with AI capabilities, prototyping practical agents, or just exploring what’s possible, MCP Playground provides a flexible starting point.</p><h3><strong>🛠️ Building a Tool-Using LLM Agent with MCP Playground</strong></h3><p>When we think of large language models (LLMs), we often think of them as conversational engines — good at answering questions, summarizing text, or generating content.</p><p>But what if they could <em>act</em>?</p><p>What if your LLM could <em>act</em> — calling a weather API, fetching exchange rates, or executing custom code — all in real time?</p><p>That’s the core idea behind MCP Playground: an architecture for connecting LLMs to external tools through a simple, extensible framework.</p><p>In this post, I’ll break down how it’s structured and how to build something similar yourself.</p><h3><strong>🔧 System Architecture Overview</strong></h3><figure><img alt="“MCP Playground architecture: Streamlit frontend + LangGraph agent + Dockerized tool servers”" src="https://cdn-images-1.medium.com/max/1024/1*hOi911FG9Uz0L3S3ymmHzA.png" /><figcaption>MCP Playground architecture: Streamlit frontend + LangGraph agent + Dockerized MCP servers</figcaption></figure><p>At a high level, the system consists of:</p><ol><li><strong>Tool Servers</strong> — Microservices that perform real-world tasks (e.g. get weather, convert currency).</li><li><strong>Agent Framework</strong> — A LangGraph-based agent that can select and use tools based on the user prompt.</li><li><strong>Frontend UI</strong> — A simple Streamlit interface for interacting with the LLM.</li><li><strong>LLM Provider Layer</strong> — Abstracts different model APIs (OpenAI, Anthropic, Bedrock, etc.)</li><li><strong>Containerization</strong> — Docker used to spin everything up with one command.</li></ol><p>Each part is modular and can be swapped out or extended.</p><h3><strong>🧵 Solving Async Woes in Streamlit</strong></h3><p>Streamlit doesn’t support `asyncio` out of the box — and that causes crashes or frozen sessions when working with persistent async LLM clients.</p><p><strong>Fix:</strong></p><pre>import streamlit as st<br>import nest_asyncio, asyncio, atexit<br><br># Apply nest_asyncio to allow nested asyncio event loops (required by Streamlit)<br>nest_asyncio.apply()<br><br># Initialize session state for event loop<br>if &quot;loop&quot; not in st.session_state:<br>    st.session_state.loop = asyncio.new_event_loop()<br>    asyncio.set_event_loop(st.session_state.loop)<br><br># Helper function for running async functions<br>def run_async(coro):<br>    &quot;&quot;&quot;Run an async function within the stored event loop.&quot;&quot;&quot;<br>    return st.session_state.loop.run_until_complete(coro)<br><br>def reset_connection_state():<br>    &quot;&quot;&quot;Reset all connection-related session state variables.&quot;&quot;&quot;<br>    if st.session_state.client is not None:<br>        try:<br>            # Close the existing client properly<br>            run_async(st.session_state.client.__aexit__(None, None, None))<br>        except Exception as e:<br>            st.error(f&quot;Error closing previous client: {str(e)}&quot;)<br>    <br>    st.session_state.client = None<br>    st.session_state.agent = None<br>    st.session_state.tools = []<br><br>def on_shutdown():<br>    &quot;&quot;&quot;Proper cleanup when the session ends.&quot;&quot;&quot;<br>    if st.session_state.client is not None:<br>        try:<br>            # Close the client properly<br>            run_async(st.session_state.client.__aexit__(None, None, None))<br>        except Exception as e:<br>            st.error(f&quot;Error during shutdown: {str(e)}&quot;)<br><br># Register cleanup logic on program exit<br>atexit.register(on_shutdown)</pre><p>Now, you can safely run asynchronous MCP calls like this:</p><pre># Setup new MCP client<br>st.session_state.client = run_async(setup_mcp_client(st.session_state.servers))<br><br># Fetch available tools from MCP servers<br>st.session_state.tools = run_async(get_tools_from_client(st.session_state.client))<br><br># Initialize the AI agent with those tools<br>st.session_state.agent = create_react_agent(llm, st.session_state.tools)</pre><p>✅ This setup ensures reliable tool calls, clean async shutdowns, and zero memory leaks — all within Streamlit’s synchronous execution model.</p><h3><strong>🚀 Getting Started: Run It Locally</strong></h3><pre>git clone https://github.com/Elkhn/mcp-playground.git<br>cd mcp-playground<br>docker compose up --build</pre><p>- Streamlit: http://localhost:8501</p><p>- Weather API: http://localhost:8000</p><p>- Currency API: <a href="http://localhost:8001/">http://localhost:8001</a></p><h3><strong>💬 Using the Playground</strong></h3><ul><li><strong>Step 1: Choose Provider</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*EVffb6m0L02Dz_86dnonbw.png" /><figcaption>Selecting an LLM provider and managing tool servers in the MCP Playground sidebar</figcaption></figure><p>OpenAI, Anthropic, Google Gemini, Bedrock — all supported.</p><ul><li><strong>Step 2: Connect MCP Servers</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*BXmP1WRvNNfZRq10fE3IVw.png" /><figcaption>Connecting to MCP servers</figcaption></figure><p>Once you’ve successfully connected to an MCP server, the sidebar will display the list of available tools along with their documentation. This allows you to easily explore each tool’s functionality and understand how to use them within your chat session.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*2T_WzoAnXp6SGRGBlcR_fw.png" /><figcaption>Viewing available tools</figcaption></figure><ul><li><strong>Step 3: Ask Away</strong></li></ul><p>&gt; “What’s the weather in Berlin and the currency prices for today?”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jr44xjKs3aue1kn6D7-60Q.png" /><figcaption>Full MCP Playground chat interface in action</figcaption></figure><p>As shown in the screenshot, we entered a single prompt asking about the weather in Berlin and today’s currency exchange rates. The agent automatically determined that it needed to use two separate tools from different MCP services to answer the question. Thanks to the LangGraph interface and the create_react_agent setup, this entire process happens seamlessly behind the scenes.</p><p>You can review the tool execution history displayed below the chat. This section provides a transparent view of which tools were called, the inputs they received, and the results they returned — giving you insight into how the agent formulated its final response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*AAIDjXlFDYjEqjL4kmxN_w.png" /><figcaption>Transparent tool execution history</figcaption></figure><h3><strong>🔧 Extending the Playground</strong></h3><p>Want to add your own MCP server?</p><p>1. Drop a new directory in `servers/`</p><p>2. Add a `main.py` using `FastMCP`</p><p>3. Register it in `servers_config.json`:</p><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;WeatherAPI&quot;: {<br>      &quot;transport&quot;: &quot;sse&quot;,<br>      &quot;url&quot;: &quot;http://mcpserver1:8000/sse&quot;,<br>      &quot;timeout&quot;: 600,<br>      &quot;headers&quot;: null,<br>      &quot;sse_read_timeout&quot;: 900<br>    },<br>    &quot;CurrencyAPI&quot;: {<br>      &quot;transport&quot;: &quot;sse&quot;,<br>      &quot;url&quot;: &quot;http://mcpserver2:8001/sse&quot;,<br>      &quot;timeout&quot;: 600,<br>      &quot;headers&quot;: null,<br>      &quot;sse_read_timeout&quot;: 900<br>    }<br>  }<br>}</pre><h3><strong>🧠 Client-Side Architecture</strong></h3><p>In the client-side implementation of our AI application, we’ve organized the logic into three distinct Python modules to ensure modularity, maintainability, and clarity:</p><ul><li><strong>1. chat_service.py</strong><br> This module handles all UI-related operations using <strong>Streamlit</strong>. It defines the user interface, manages user interactions, and streams the AI-generated responses in real time. Think of it as the bridge between the user and the AI pipeline.</li><li><strong>2. ai_service.py</strong><br> The core of the AI logic lives here. This module defines the <strong>AI pipeline</strong>, orchestrating tasks such as prompt engineering, response generation, post-processing, and any additional reasoning workflows.</li><li><strong>3. mcp_service.py</strong><br> This service is responsible for managing connections with <strong>MCP (Model Context Protocol) Servers</strong>. It encapsulates all communication and coordination with external control systems, ensuring seamless integration with back-end components or external hardware.</li></ul><p>By decoupling responsibilities across these modules, the system remains highly flexible and easier to scale or refactor. This structure allows developers to focus on one part of the system without the risk of unintended side effects in another.</p><h3><strong>🏢 Server-Side Architecture</strong></h3><p>The server-side architecture of our AI-enabled system is structured around modular, independently deployable <strong>MCP (Model Control Protocol)</strong> servers. Each MCP server encapsulates a specific domain of functionality (e.g., weather data, currency exchange), exposing tools that can be discovered and used by LangChain agents in the client-side interface.</p><p>These servers follow a plug-and-play model, managed via a docker-compose.yaml file that allows one-command orchestration of multiple services.</p><pre>mcp-playground/<br>├─ docker-compose.yaml          # One-command orchestration<br>├─ client/                      # Streamlit UI frontend<br>│  └─ ...<br>└─ servers/                     # All backend MCP tool servers<br>   ├─ server1/                  # Weather Service<br>   │  └─ main.py<br>   └─ server2/                  # Currency Exchange Service<br>      └─ main.py</pre><p>This structure allows seamless addition or removal of backends with zero impact on the frontend, promoting loose coupling and high scalability.</p><p><strong>🌐 Each MCP Server: A Self-Contained Tool Host</strong></p><p>Each server, such as server1/ or server2/, is a standalone microservice that runs an instance of FastMCP — a fast, async-capable implementation of the MCP protocol. These services register tools (functions) that LangChain agents can discover, call, and orchestrate in a reasoning chain.</p><p>Servers run independently on their own ports using Server-Sent Events (SSE) for real-time communication:</p><pre>if __name__ == &quot;__main__&quot;:<br>    mcp.run(transport=&quot;sse&quot;)</pre><p>Typical launch output:</p><pre>Starting Weather Service MCP server on port 8000...<br>Connect to this server using http://localhost:8000/sse</pre><p>The docker-compose.yaml file provides a declarative setup to:</p><ul><li>Launch all MCP servers</li><li>Handle shared networking</li><li>Simplify local development and deployment</li></ul><pre>version: &quot;3.9&quot;<br><br>services:<br>  mcpserver1:<br>    build: ./servers/server1<br>    container_name: mcpserver_1<br>    restart: on-failure<br>    volumes:<br>      - ./servers/server1:/app<br>    ports:<br>      - &quot;8000:8000&quot;<br>  <br>  mcpserver2:<br>    build: ./servers/server2<br>    container_name: mcpserver_2<br>    restart: on-failure<br>    volumes:<br>      - ./servers/server2:/app<br>    ports:<br>      - &quot;8001:8001&quot;<br><br>  hostclient:<br>    build: ./client<br>    container_name: hostclient<br>    restart: on-failure<br>    volumes:<br>      - ./client/:/app<br>    ports:<br>      - &quot;8501:8501&quot;<br>    command: &gt;<br>      streamlit run app.py<br>    depends_on:<br>      - mcpserver1<br>      - mcpserver2</pre><h3><strong>❤️ Final Thoughts</strong></h3><p>The MCP Playground is:</p><p>- 🧪 A live, LLM + Local Tools sandbox</p><p>- 🔁 Easy to extend and experiment</p><p>-🌍 Provider-flexible and UI-rich</p><h3><strong>🙌 Acknowledgements</strong></h3><ul><li>[<a href="https://github.com/langchain-ai/langchain">LangChain</a>](https://github.com/langchain-ai/langchain)</li><li>[<a href="https://github.com/langchain-ai/langgraph">LangGraph</a>](https://github.com/langchain-ai/langgraph)</li><li>[<a href="https://github.com/jlowin/fastmcp">FastMCP</a>](https://github.com/jlowin/fastmcp)</li><li>[<a href="https://streamlit.io/">Streamlit</a>](https://streamlit.io)</li><li>[<a href="https://www.docker.com/">Docker</a>](https://www.docker.com)</li><li>Special thanks to <a href="https://medium.com/u/cf3796b9951d">Suleyman Suleymanzade</a> for co-developing and troubleshooting key parts of this project.</li></ul><h3><strong>👋 Get Involved</strong></h3><p>🔗GitHub Repo — <a href="https://github.com/Elkhn/mcp-playground">https://github.com/Elkhn/mcp-playground</a></p><p>🛠️ Fork it, add tools, have fun!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4caeb6fe0ac4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>