<?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 Anubhav Mishra on Medium]]></title>
        <description><![CDATA[Stories by Anubhav Mishra on Medium]]></description>
        <link>https://medium.com/@anubhavm48?source=rss-9b2585e2d20e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xbZUC-WxjKix5e7mnCI9Vw.jpeg</url>
            <title>Stories by Anubhav Mishra on Medium</title>
            <link>https://medium.com/@anubhavm48?source=rss-9b2585e2d20e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 07:16:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anubhavm48/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[Solving Intelligent Excel Analysis using Multi-Agents with LangGraph]]></title>
            <link>https://medium.com/@anubhavm48/solving-intelligent-excel-analysis-using-multi-agents-with-langgraph-115ca44ade65?source=rss-9b2585e2d20e------2</link>
            <guid isPermaLink="false">https://medium.com/p/115ca44ade65</guid>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[langgraph-use-cases]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Anubhav Mishra]]></dc:creator>
            <pubDate>Mon, 24 Nov 2025 05:26:23 GMT</pubDate>
            <atom:updated>2025-11-24T06:40:16.640Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In the era of data-driven decision-making, Excel remains the ubiquitous tool for data analysis across organizations. However, extracting meaningful insights from spreadsheets often requires programming expertise, statistical knowledge, and significant time investment. What if we could simply <strong>ask questions in plain English</strong> and get sophisticated analysis, visualizations, and insights automatically?</p><p>This article chronicles our journey building an <strong>Excel Analysis Agent, </strong>a multi-agent AI system that takes natural language queries and Excel files as input, then autonomously plans, codes, and executes complex data analysis. We’ll explore the architecture, design patterns, challenges, and key learnings from building this system using <strong>LangGraph</strong> and <strong>LangChain</strong>.</p><h3>Table of Contents</h3><ol><li>The Problem We Set Out to Solve</li><li>Our Approach: Multi-Agent Architecture</li><li>Design Patterns and Architectural Decisions</li><li>Key Considerations and Principles</li><li>Challenges We Faced</li><li>Learnings and Takeaways</li><li>Scope for Improvement</li><li>Conclusion</li></ol><h3>1. The Problem <em>I </em>Set Out to Solve</h3><h3>The Challenge</h3><p>Picture this scenario: A business analyst receives a sales dataset with thousands of rows. They need to:</p><ul><li>Understand the data structure</li><li>Identify trends and patterns</li><li>Build predictive models</li><li>Create visualizations</li><li>Extract actionable insights</li></ul><p><strong>Traditional Workflow:</strong></p><ol><li>Open Excel, manually explore columns and data types</li><li>Think about analysis approach</li><li>Write Python/R code for data processing</li><li>Debug errors and iterate</li><li>Create visualizations</li><li>Interpret results</li><li>Repeat for follow-up questions</li></ol><p><strong>Time investment:</strong> Hours to days, depending on complexity.</p><p><strong>Required expertise:</strong> Programming (pandas, matplotlib, sklearn), statistics, domain knowledge.</p><h3>My Vision</h3><p>What if this entire workflow could be conversational?</p><pre>User: &quot;Analyze this sales data and predict next quarter&#39;s revenue&quot;</pre><pre>Agent: *Inspects data*<br>    *Plans analysis strategy*<br>    *Executes multi-step analysis*<br>    *Generates visualizations*<br>    *Provides insights with confidence intervals*</pre><pre>User: &quot;What features drive revenue the most?&quot;</pre><pre>Agent: *Answers using existing context*<br>    *Provides feature importance plot*</pre><p><strong>The Goal:</strong> Build an autonomous agent that:</p><ul><li>✅ Understands Excel data structure automatically</li><li>✅ Plans sophisticated analysis strategies</li><li>✅ Writes and executes Python code autonomously</li><li>✅ Self-corrects errors and iterates</li><li>✅ Produces multi-modal outputs (text, plots, tables)</li><li>✅ Handles follow-up questions intelligently</li></ul><h3>2. Our Approach: Multi-Agent Architecture</h3><h3>The Mindset: Divide and Conquer</h3><p>Rather than building a monolithic agent, we adopted a <strong>multi-agent architecture</strong> inspired by how humans approach complex tasks. Just as a data science team has specialists (data engineer, analyst, ML engineer), our system delegates to specialized agents.</p><h3>The Agent Hierarchy</h3><pre>┌─────────────────────────────────────────────────────────┐<br>│                    USER QUERY                           │<br>└────────────────────┬────────────────────────────────────┘<br>                    │<br>                    ▼<br>            ┌──────────────┐<br>            │   ROUTER     │ ◄── &quot;What type of query is this?&quot;<br>            │   AGENT      │     (chat | analysis | followup)<br>            └──────┬───────┘<br>                    │<br>        ┌──────────┴──────────┐<br>        │                     │<br>        ▼                     ▼<br>    ┌──────────┐         ┌──────────────┐<br>    │   CHAT   │         │    DATA      │ ◄── &quot;Inspect Excel file&quot;<br>    │   NODE   │         │  INSPECTOR   │     Generate context<br>    └──────────┘         └──────┬───────┘<br>                                │<br>                                ▼<br>                        ┌──────────────┐<br>                        │  SUPERVISOR  │ ◄── &quot;Can I answer from context?&quot;<br>                        │    AGENT     │     (plan | answer directly)<br>                        └──────┬───────┘<br>                                │<br>                    ┌─────────┴─────────┐<br>                    │                   │<br>                    ▼                   ▼<br>            ┌──────────────┐    ┌──────────────┐<br>            │   PLANNING   │    │   FOLLOWUP   │<br>            │    AGENT     │    │    ANSWER    │<br>            └──────┬───────┘    └──────────────┘<br>                    │<br>                    ▼<br>            ┌──────────────┐<br>            │    CODING    │ ◄── Execute analysis plan<br>            │  AGENT (SUB) │     Generate visualizations<br>            └──────────────┘     Extract insights</pre><h3>Agent Responsibilities</h3><h4>1. Router Agent</h4><p><strong>Role:</strong> Traffic controller <strong>Decision:</strong> Should this go to chat, fresh analysis, or followup?</p><pre>class RouterDecision(BaseModel):<br>    route: Literal[&quot;chat&quot;, &quot;analysis&quot;, &quot;analysis_followup&quot;]<br>    reasoning: str</pre><pre># Example reasoning:<br># &quot;User asks about data. No prior data context exists. Route: analysis&quot;<br># &quot;User asks &#39;why?&#39; after getting results. Route: analysis_followup&quot;<br># &quot;User asks &#39;how are you?&#39;. Route: chat&quot;</pre><p><strong>Why it matters:</strong> Prevents unnecessary data inspection and code execution for simple follow-ups.</p><h4>2. Data Inspector Agent</h4><p><strong>Role:</strong> Data archaeologist <strong>Responsibility:</strong> Understand Excel structure and create rich textual context</p><pre># Generates context like:<br>{<br>    &quot;file_path&quot;: &quot;sales_data.xlsx&quot;,<br>    &quot;rows&quot;: 10000,<br>    &quot;columns&quot;: 15,<br>    &quot;column_info&quot;: {<br>        &quot;date&quot;: {&quot;type&quot;: &quot;datetime&quot;, &quot;sample&quot;: &quot;2024-01-01&quot;},<br>        &quot;revenue&quot;: {&quot;type&quot;: &quot;float64&quot;, &quot;range&quot;: &quot;[100, 50000]&quot;},<br>        &quot;category&quot;: {&quot;type&quot;: &quot;object&quot;, &quot;unique_values&quot;: 5}<br>    },<br>    &quot;missing_values&quot;: {&quot;price&quot;: 23, &quot;customer_id&quot;: 0},<br>    &quot;description&quot;: &quot;Sales dataset with temporal, numerical, and categorical features...&quot;<br>}</pre><p><strong>Why it matters:</strong> Provides LLM with grounded understanding of data, enabling better planning.</p><h4>3. Supervisor Agent</h4><p><strong>Role:</strong> Decision strategist <strong>Decision:</strong> Do we need new code execution, or can we answer from existing context?</p><pre>class SupervisorDecision(BaseModel):<br>    next_step: Literal[&quot;plan_analysis&quot;, &quot;answer_from_context&quot;]<br>    reasoning: str</pre><pre># Example:<br># &quot;User asks for visualization. Need code execution. Next: plan_analysis&quot;<br># &quot;User asks &#39;what does this mean?&#39; after getting results. Next: answer_from_context&quot;</pre><p><strong>Why it matters:</strong> Saves computational resources and time on followup questions.</p><h4>4. Planning Agent</h4><p><strong>Role:</strong> Analysis strategist <strong>Responsibility:</strong> Create detailed, step-by-step analysis plan</p><pre># Example plan output:<br>{<br>    &quot;steps&quot;: [<br>        {<br>            &quot;order&quot;: 1,<br>            &quot;description&quot;: &quot;Load data and perform initial exploration (head, info, describe)&quot;,<br>            &quot;status&quot;: &quot;pending&quot;<br>        },<br>        {<br>            &quot;order&quot;: 2,<br>            &quot;description&quot;: &quot;Handle missing values using forward fill for dates&quot;,<br>            &quot;status&quot;: &quot;pending&quot;<br>        },<br>        {<br>            &quot;order&quot;: 3,<br>            &quot;description&quot;: &quot;Engineer temporal features (month, quarter, day_of_week)&quot;,<br>            &quot;status&quot;: &quot;pending&quot;<br>        },<br>        {<br>            &quot;order&quot;: 4,<br>            &quot;description&quot;: &quot;Train RandomForest model with train-test split (80-20)&quot;,<br>            &quot;status&quot;: &quot;pending&quot;<br>        },<br>        {<br>            &quot;order&quot;: 5,<br>            &quot;description&quot;: &quot;Generate feature importance plot and predictions&quot;,<br>            &quot;status&quot;: &quot;pending&quot;<br>        }<br>    ]<br>}</pre><p><strong>Why it matters:</strong> Provides structure, enables progress tracking, improves agent focus.</p><h4>5. Coding Agent (Subgraph)</h4><p><strong>Role:</strong> Code executor <strong>Responsibility:</strong> Execute plan, write Python code, iterate on errors, collect artifacts</p><pre># Has access to 3 tools:<br>1. python_repl_tool(code: str) -&gt; ExecutionResult<br>2. bash_tool(command: str) -&gt; str<br>3. think_tool(reflection: str) -&gt; str  # Forces strategic thinking!</pre><pre># Example iteration:<br>User → &quot;Load the data&quot;<br>Agent → python_repl_tool(&quot;import pandas as pd; df = pd.read_excel(...)&quot;)<br>    → think_tool(&quot;Data loaded successfully. 10000 rows. Next: explore&quot;)<br>    → python_repl_tool(&quot;print(df.info())&quot;)<br>    → think_tool(&quot;5 numerical, 10 categorical columns. Next: missing values&quot;)<br>    ...</pre><p><strong>Why it matters:</strong> Autonomous execution with self-correction and artifact collection.</p><h3>3. Design Patterns and Architectural Decisions</h3><p>Building this system required several key architectural patterns. Let’s explore them in depth.</p><h3>Pattern 1: Subgraph State Isolation</h3><h4>The Problem</h4><p>When an agent uses tools (like python_repl), LangGraph adds <strong>ToolMessage</strong> objects to the conversation state. For an agent that iterates 20+ times, this pollutes the message history and makes conversation visualization messy.</p><h4>The Solution: Subgraph Isolation</h4><pre># Parent state (clean conversation)<br>class ExcelAnalysisState(MessagesState):<br>    messages: List[BaseMessage]          # Only user/assistant messages<br>    excel_file_path: str<br>    data_context: Dict<br>    analysis_plan: str<br>    artifacts: List[Artifact]           # Plots, tables, insights</pre><pre># Subgraph state (internal execution)<br>class CodingSubgraphState(MessagesState):<br>    messages: List[BaseMessage]          # Tool calls stay HERE<br>    code_iterations: int<br>    final_analysis: str<br>    artifacts: List[Artifact]</pre><pre># Control what flows between parent and subgraph<br>class CodingSubgraphInput(TypedDict):<br>    excel_file_path: str<br>    data_context: Dict<br>    analysis_plan: str<br>    # Note: messages excluded!</pre><pre>class CodingSubgraphOutput(TypedDict):<br>    messages: List[BaseMessage]          # Only final summary message<br>    artifacts: List[Artifact]<br>    # Note: Tool messages excluded!</pre><p><strong>Result:</strong> Parent graph stays clean. LangGraph Studio shows readable conversation. Internal iterations hidden.</p><p><strong>Key Insight:</strong> Think of subgraphs as <strong>functions with isolated scope</strong>. You control inputs/outputs explicitly.</p><h3>Pattern 2: Microservice Sandbox Architecture</h3><h4>The Problem</h4><p>Executing user-generated Python code requires isolation. Traditional approaches:</p><ul><li><strong>Option A:</strong> Spawn subprocess per execution ❌ Slow, no persistent state</li><li><strong>Option B:</strong> Use exec() in main process ❌ Security risk, namespace pollution</li></ul><h4>The Solution: HTTP-Based Sandbox Server</h4><pre># Architecture:<br>Main LangGraph App (Port 8000) ←→ Sandbox Server (Port 8765)<br>                                ├── FastAPI service<br>                                ├── Separate Python venv<br>                                ├── In-memory session contexts<br>                                └── Persistent variable state</pre><pre># Tool implementation:<br>@tool<br>def python_repl_tool(code: str) -&gt; dict:<br>    &quot;&quot;&quot;Execute Python code in isolated sandbox&quot;&quot;&quot;<br>    response = requests.post(&quot;http://localhost:8765/execute&quot;, json={<br>        &quot;session_id&quot;: get_current_session(),<br>        &quot;code&quot;: code<br>    })</pre><pre>    return response.json()  # {output, plots, tables, errors}</pre><p><strong>Sandbox Server (Simplified):</strong></p><pre># FastAPI server in separate process<br>from fastapi import FastAPI<br>import sys</pre><pre>app = FastAPI()</pre><pre># In-memory storage (no pickling overhead!)<br>SESSION_CONTEXTS: Dict[str, Dict[str, Any]] = {}</pre><pre>@app.post(&quot;/execute&quot;)<br>async def execute_code(request: ExecuteRequest):<br>    session_id = request.session_id<br>    code = request.code</pre><pre>    # Get or create session context<br>    if session_id not in SESSION_CONTEXTS:<br>        SESSION_CONTEXTS[session_id] = {<br>            &quot;plots_dir&quot;: &quot;/path/to/plots&quot;,  # Pre-injected<br>        }</pre><pre>    context = SESSION_CONTEXTS[session_id]</pre><pre>    # Execute in persistent context<br>    try:<br>        exec(code, {&quot;__builtins__&quot;: __builtins__}, context)</pre><pre>        # Auto-detect artifacts<br>        plots = detect_saved_plots()<br>        tables = detect_dataframes(context)</pre><pre>        return {<br>            &quot;success&quot;: True,<br>            &quot;output&quot;: captured_stdout,<br>            &quot;plots&quot;: plots,<br>            &quot;tables&quot;: tables<br>        }<br>    except Exception as e:<br>        return {&quot;success&quot;: False, &quot;error&quot;: str(e)}</pre><p><strong>Benefits:</strong></p><ul><li>⚡ <strong>Fast:</strong> No subprocess spawn overhead (10x faster)</li><li>🔒 <strong>Isolated:</strong> Separate process, separate venv</li><li>💾 <strong>Stateful:</strong> Variables persist across executions (DataFrames stay in memory)</li><li>📊 <strong>Smart:</strong> Auto-detects plots and tables</li><li>🚀 <strong>Scalable:</strong> Could run on different machine/container</li></ul><p><strong>Key Insight:</strong> Treat code execution as a <strong>microservice</strong>, not a subprocess.</p><h3>Pattern 3: Reflection-Driven Execution</h3><h4>The Problem</h4><p>LLM agents often waste iterations:</p><ul><li>Execute code without analyzing results</li><li>Continue unnecessarily after success</li><li>Miss errors from previous steps</li></ul><h4>The Solution: think_tool — Forced Reflection</h4><pre>@tool<br>def think_tool(reflection: str) -&gt; str:<br>    &quot;&quot;&quot;<br>    Use this tool to reflect on code execution results BEFORE continuing.</pre><pre>    When to use:<br>    - After each code execution, analyze the output<br>    - Decide if you&#39;ve achieved the step&#39;s goal<br>    - Determine next actions or if you can finish</pre><pre>    Args:<br>        reflection: Your analysis of progress, next steps, or decision to finish<br>    &quot;&quot;&quot;<br>    return f&quot;Reflection recorded: {reflection}&quot;</pre><pre># System prompt enforces usage:<br>&quot;&quot;&quot;<br>IMPORTANT: After EACH code execution, you MUST use think_tool to:<br>1. Analyze the output<br>2. Check if the current step is complete<br>3. Decide next action or finish if all steps done</pre><pre>Example workflow:<br>- Execute: python_repl_tool(&quot;df.info()&quot;)<br>- Reflect: think_tool(&quot;Data loaded. 10k rows, 15 cols. Missing values in &#39;price&#39;. Next: handle missing data&quot;)<br>- Execute: python_repl_tool(&quot;df[&#39;price&#39;].fillna(...)&quot;)<br>- Reflect: think_tool(&quot;Missing values handled. Ready for modeling...&quot;)<br>&quot;&quot;&quot;</pre><p><strong>Before think_tool:</strong></p><pre>Iteration 1: Load data<br>Iteration 2: Load data again (forgot it was loaded)<br>Iteration 3: Try to plot before exploring<br>Iteration 4: Error, try again<br>...<br>Iteration 20: Still confused</pre><p><strong>After think_tool:</strong></p><pre>Iteration 1: Load data → Reflect: &quot;Loaded. Need to explore&quot;<br>Iteration 2: Explore data → Reflect: &quot;Found missing values. Handle them&quot;<br>Iteration 3: Handle missing values → Reflect: &quot;Clean. Ready for analysis&quot;<br>Iteration 4: Run analysis → Reflect: &quot;Complete. Have all artifacts&quot;</pre><p><strong>Key Insight:</strong> Metacognition matters. Force agents to “think about thinking.”</p><h3>Pattern 4: Hierarchical LLM-Based Routing</h3><h4>The Problem</h4><p>Hard-coded routing rules become brittle:</p><pre>if &quot;plot&quot; in query or &quot;graph&quot; in query:<br>    return &quot;analysis&quot;<br>elif &quot;why&quot; in query or &quot;how&quot; in query:<br>    return &quot;followup&quot;<br># What about &quot;visualize&quot;, &quot;show&quot;, &quot;explain&quot;?</pre><h4>The Solution: LLM-Powered Routing with Structured Output</h4><pre>from pydantic import BaseModel, Field<br>from langchain_core.language_models import init_chat_model</pre><pre>class RouterDecision(BaseModel):<br>    route: Literal[&quot;chat&quot;, &quot;analysis&quot;, &quot;analysis_followup&quot;]<br>    reasoning: str = Field(description=&quot;Explain why you chose this route&quot;)</pre><pre># Router prompt:<br>ROUTER_PROMPT = &quot;&quot;&quot;<br>You are a routing agent. Classify the user&#39;s query:</pre><pre>1. &quot;chat&quot; - General conversation, greetings, off-topic<br>2. &quot;analysis&quot; - Request for data analysis (requires new code execution)<br>3. &quot;analysis_followup&quot; - Follow-up question about existing results</pre><pre>Consider:<br>- Conversation history<br>- Whether data context already exists<br>- Whether previous analysis exists<br>&quot;&quot;&quot;</pre><pre># Implementation:<br>def router_node(state: ExcelAnalysisState) -&gt; ExcelAnalysisState:<br>    llm = init_chat_model(&quot;gpt-4o&quot;)<br>    llm_with_structure = llm.with_structured_output(RouterDecision)</pre><pre>    decision = llm_with_structure.invoke([<br>        SystemMessage(content=ROUTER_PROMPT),<br>        *state[&quot;messages&quot;]<br>    ])</pre><pre>    return {&quot;route_decision&quot;: decision}</pre><pre># Conditional routing:<br>def route_after_router(state: ExcelAnalysisState) -&gt; str:<br>    route = state[&quot;route_decision&quot;][&quot;route&quot;]</pre><pre>    if route == &quot;chat&quot;:<br>        return &quot;chat_node&quot;<br>    elif route == &quot;analysis&quot;:<br>        return &quot;data_inspector&quot;<br>    else:  # analysis_followup<br>        return &quot;supervisor&quot;</pre><p><strong>Benefits:</strong></p><ul><li>🧠 <strong>Intelligent:</strong> Understands context and nuance</li><li>📝 <strong>Transparent:</strong> Reasoning is logged</li><li>🎯 <strong>Accurate:</strong> Handles edge cases naturally</li><li>🔧 <strong>Maintainable:</strong> No hardcoded rules</li></ul><p><strong>Two-Layer Decision Making:</strong></p><ol><li><strong>Router:</strong> Fast classification (chat vs analysis)</li><li><strong>Supervisor:</strong> Deep evaluation (need code vs answer from context)</li></ol><p><strong>Key Insight:</strong> Use LLMs for <strong>decisions</strong>, not just generation. Structured output ensures type safety.</p><h3>Pattern 5: Artifact Accumulation System</h3><h4>The Problem</h4><p>Analysis produces multiple outputs:</p><ul><li>Plots (PNG files)</li><li>Tables (pandas DataFrames)</li><li>Statistical insights</li><li>Code snippets</li></ul><p>How do we collect, persist, and present them?</p><h4>The Solution: Typed Artifact State with Custom Reducer</h4><pre>class Artifact(TypedDict):<br>    type: Literal[&quot;plot&quot;, &quot;table&quot;, &quot;insight&quot;, &quot;code&quot;]<br>    content: str              # File path or markdown<br>    description: str<br>    timestamp: str</pre><pre>class ExcelAnalysisState(MessagesState):<br>    artifacts: Annotated[List[Artifact], add_artifacts]<br>    # Custom reducer prevents overwriting</pre><pre>def add_artifacts(existing: List[Artifact], new: List[Artifact]) -&gt; List[Artifact]:<br>    &quot;&quot;&quot;Accumulate artifacts instead of replacing&quot;&quot;&quot;<br>    return existing + new</pre><pre># Usage in coding agent:<br>def coding_agent_node(state: CodingSubgraphState):<br>    # ... execute code ...</pre><pre>    # When python_repl returns plots<br>    if execution_result[&quot;plots&quot;]:<br>        artifacts = [<br>            {<br>                &quot;type&quot;: &quot;plot&quot;,<br>                &quot;content&quot;: plot_path,<br>                &quot;description&quot;: &quot;Revenue trend over time&quot;,<br>                &quot;timestamp&quot;: datetime.now().isoformat()<br>            }<br>            for plot_path in execution_result[&quot;plots&quot;]<br>        ]</pre><pre>        state[&quot;artifacts&quot;].extend(artifacts)</pre><pre>    # When execution produces insights<br>    if &quot;correlation&quot; in analysis_output:<br>        state[&quot;artifacts&quot;].append({<br>            &quot;type&quot;: &quot;insight&quot;,<br>            &quot;content&quot;: &quot;Strong positive correlation (0.87) between marketing spend and revenue&quot;,<br>            &quot;description&quot;: &quot;Statistical insight&quot;,<br>            &quot;timestamp&quot;: datetime.now().isoformat()<br>        })</pre><p><strong>Final Output to User:</strong></p><pre>## Analysis Results</pre><pre>### Insights<br>- Strong positive correlation (0.87) between marketing spend and revenue<br>- Seasonal pattern detected: Q4 shows 35% higher revenue<br>- 3 outliers identified in February 2024</pre><pre>### Visualizations<br>![Revenue Trend](path/to/revenue_trend.png)<br>*Revenue trend over time showing seasonal patterns*</pre><pre>![Feature Importance](path/to/feature_importance.png)<br>*Top 5 features driving revenue*</pre><pre>### Data Tables<br>| Feature | Importance | P-value |<br>|---------|-----------|---------|<br>| marketing_spend | 0.43 | 0.001 |<br>| season_Q4 | 0.28 | 0.003 |<br>| customer_count | 0.19 | 0.012 |</pre><p><strong>Key Insight:</strong> Treat outputs as <strong>structured data</strong>, not just text. Custom reducers enable proper accumulation.</p><h3>Pattern 6: TodoList Pattern for Progress Tracking</h3><h4>The Problem</h4><p>Users don’t know what the agent is doing during long-running analyses. Black box execution is frustrating.</p><h4>The Solution: Structured Analysis Steps with Status Tracking</h4><pre>class AnalysisStep(TypedDict):<br>    description: str<br>    status: Literal[&quot;pending&quot;, &quot;in_progress&quot;, &quot;completed&quot;, &quot;skipped&quot;]<br>    order: int<br>    result_summary: str</pre><pre>class ExcelAnalysisState(MessagesState):<br>    analysis_steps: Annotated[List[AnalysisStep], update_analysis_steps]</pre><pre>def update_analysis_steps(existing: List[AnalysisStep],<br>                        new: List[AnalysisStep]) -&gt; List[AnalysisStep]:<br>    &quot;&quot;&quot;Merge step updates based on order&quot;&quot;&quot;<br>    step_dict = {s[&quot;order&quot;]: s for s in existing}<br>    for step in new:<br>        step_dict[step[&quot;order&quot;]] = step<br>    return sorted(step_dict.values(), key=lambda x: x[&quot;order&quot;])</pre><pre># Planning agent creates steps:<br>def planning_node(state: ExcelAnalysisState):<br>    plan = llm.invoke(&quot;Create analysis steps...&quot;)</pre><pre>    steps = [<br>        {&quot;description&quot;: &quot;Load and explore data&quot;, &quot;status&quot;: &quot;pending&quot;, &quot;order&quot;: 1},<br>        {&quot;description&quot;: &quot;Handle missing values&quot;, &quot;status&quot;: &quot;pending&quot;, &quot;order&quot;: 2},<br>        {&quot;description&quot;: &quot;Engineer features&quot;, &quot;status&quot;: &quot;pending&quot;, &quot;order&quot;: 3},<br>        {&quot;description&quot;: &quot;Train model&quot;, &quot;status&quot;: &quot;pending&quot;, &quot;order&quot;: 4},<br>        {&quot;description&quot;: &quot;Generate visualizations&quot;, &quot;status&quot;: &quot;pending&quot;, &quot;order&quot;: 5},<br>    ]</pre><pre>    return {&quot;analysis_steps&quot;: steps}</pre><pre># Coding agent updates progress:<br>def coding_agent_node(state: CodingSubgraphState):<br>    for step in state[&quot;analysis_steps&quot;]:<br>        if step[&quot;status&quot;] == &quot;pending&quot;:<br>            # Update to in_progress<br>            update_step_status(step[&quot;order&quot;], &quot;in_progress&quot;)</pre><pre>            # Execute step<br>            result = execute_step(step)</pre><pre>            # Update to completed with summary<br>            update_step_status(step[&quot;order&quot;], &quot;completed&quot;,<br>                            result_summary=result[&quot;summary&quot;])</pre><p><strong>Visual Feedback (Console Output):</strong></p><pre>📊 Analysis Plan Created</pre><pre>✓ Step 1: Load and explore data [COMPLETED]<br>→ Loaded 10,000 rows, 15 columns</pre><pre>⏳ Step 2: Handle missing values [IN PROGRESS]</pre><pre>⏺ Step 3: Engineer features [PENDING]</pre><pre>⏺ Step 4: Train model [PENDING]</pre><pre>⏺ Step 5: Generate visualizations [PENDING]</pre><p><strong>Key Insight:</strong> Progress visibility builds trust. Users tolerate longer wait times when they see progress.</p><h3>4. Key Considerations and Principles</h3><h3>🎯 Principle 1: Separation of Concerns</h3><p><strong>Every agent has ONE job:</strong></p><ul><li>Router → Classify</li><li>Inspector → Understand data</li><li>Supervisor → Strategize</li><li>Planner → Create roadmap</li><li>Coder → Execute</li></ul><p><strong>Anti-pattern:</strong> A single “do everything” agent that tries to inspect data, plan, and code simultaneously.</p><p><strong>Benefit:</strong> Easier debugging, testing, and improvement of individual components.</p><h3>🎯 Principle 2: Fail Fast with Validation</h3><p><strong>Pre-flight checks everywhere:</strong></p><pre>def data_inspector_node(state: ExcelAnalysisState):<br>    # Health check sandbox<br>    if not is_sandbox_healthy():<br>        raise SandboxNotAvailableError(&quot;Start sandbox server first&quot;)</pre><pre>    # Validate file exists<br>    if not Path(state[&quot;excel_file_path&quot;]).exists():<br>        raise FileNotFoundError(f&quot;Excel file not found: {state[&#39;excel_file_path&#39;]}&quot;)</pre><pre>    # Reset REPL context for clean slate<br>    reset_python_context()</pre><pre>    # Now proceed with inspection<br>    ...</pre><p><strong>Benefit:</strong> Clear error messages. Avoid wasting LLM tokens on doomed executions.</p><h3>🎯 Principle 3: Prompt Engineering is Architecture</h3><p><strong>Bad prompt:</strong></p><pre>&quot;Analyze the data and create a model.&quot;</pre><p><strong>Good prompt (Planning Agent):</strong></p><pre>You are an expert data scientist creating an analysis plan.</pre><pre>BEST PRACTICES:<br>1. Feature Engineering<br>- NEVER use raw date columns. Extract: month, quarter, day_of_week, is_weekend<br>- For timestamps: time_since_start, days_since_last_event</pre><pre>2. Model Selection<br>- For regression with mixed features: prefer RandomForest over LinearRegression<br>- For time series: consider temporal validation splits</pre><pre>3. Handling Missing Data<br>- Numerical: median imputation (robust to outliers)<br>- Categorical: mode or separate &quot;missing&quot; category<br>- Time series: forward fill or interpolation</pre><pre>4. Validation<br>- Always use train-test split (80-20 minimum)<br>- For time series: use temporal splits (no future data in training)</pre><pre>5. Interpretability<br>- Include feature importance analysis<br>- Provide confidence intervals for predictions<br>- Flag anomalies and outliers</pre><pre>OUTPUT FORMAT:<br>Return a JSON list of analysis steps with &quot;order&quot; and &quot;description&quot; fields.</pre><p><strong>Benefit:</strong> Domain knowledge embedded in prompts. Better plans without more tokens.</p><h3>🎯 Principle 4: State is Sacred</h3><p><strong>Type every state field:</strong></p><pre># Bad: Generic dict<br>state = {&quot;data&quot;: {...}, &quot;stuff&quot;: [...]}</pre><pre># Good: Typed state<br>class ExcelAnalysisState(MessagesState):<br>    excel_file_path: str<br>    data_context: Dict[str, Any]<br>    route_decision: RouterDecision<br>    supervisor_decision: SupervisorDecision<br>    analysis_plan: str<br>    artifacts: Annotated[List[Artifact], add_artifacts]<br>    analysis_steps: Annotated[List[AnalysisStep], update_analysis_steps]</pre><p><strong>Benefits:</strong></p><ul><li>Type checking catches errors</li><li>Self-documenting code</li><li>IDE autocomplete</li><li>Custom reducers for complex updates</li></ul><h3>🎯 Principle 5: Observability &gt; Debugging</h3><p><strong>Logging strategy:</strong></p><pre>import logging</pre><pre>logger = logging.getLogger(__name__)</pre><pre>def router_node(state: ExcelAnalysisState):<br>    logger.info(&quot;Router node invoked&quot;)</pre><pre>    decision = llm_router.invoke(...)</pre><pre>    logger.info(f&quot;Route decision: {decision.route}&quot;)<br>    logger.debug(f&quot;Reasoning: {decision.reasoning}&quot;)</pre><pre>    return {&quot;route_decision&quot;: decision}</pre><p><strong>Console feedback for users:</strong></p><pre>from rich.console import Console</pre><pre>console = Console()</pre><pre>def display_progress(step: AnalysisStep):<br>    status_emoji = {<br>        &quot;pending&quot;: &quot;⏺&quot;,<br>        &quot;in_progress&quot;: &quot;⏳&quot;,<br>        &quot;completed&quot;: &quot;✓&quot;,<br>        &quot;skipped&quot;: &quot;⊘&quot;<br>    }</pre><pre>    console.print(<br>        f&quot;{status_emoji[step[&#39;status&#39;]]} &quot;<br>        f&quot;Step {step[&#39;order&#39;]}: {step[&#39;description&#39;]} &quot;<br>        f&quot;[{step[&#39;status&#39;].upper()}]&quot;<br>    )</pre><p><strong>Benefit:</strong> Understand system behavior in production. Debug faster. Build user trust.</p><h3>🎯 Principle 6: Graceful Degradation</h3><p><strong>Handle failures elegantly:</strong></p><pre>def coding_agent_node(state: CodingSubgraphState):<br>    max_iterations = 40<br>    iteration = 0</pre><pre>    while iteration &lt; max_iterations:<br>        # Execute code<br>        result = python_repl_tool(code)</pre><pre>        if result[&quot;success&quot;]:<br>            # Continue<br>            iteration += 1<br>        else:<br>            # Try to fix error<br>            error_msg = result[&quot;error&quot;]<br>            logger.warning(f&quot;Execution error: {error_msg}&quot;)</pre><pre>            # Give LLM error context to fix<br>            # But prevent infinite error loops<br>            if iteration &gt; 30:<br>                return {<br>                    &quot;final_analysis&quot;: &quot;Analysis incomplete due to persistent errors. &quot;<br>                                    &quot;Please check data quality or simplify query.&quot;,<br>                    &quot;artifacts&quot;: state[&quot;artifacts&quot;]  # Return partial results<br>                }</pre><p><strong>Benefit:</strong> Even failed analyses provide value. Partial results &gt; nothing.</p><h3>5. Challenges We Faced</h3><h3>Challenge 1: Message State Pollution</h3><p><strong>Problem:</strong> When the coding agent used tools iteratively, every tool call added messages to state:</p><pre>messages = [<br>    HumanMessage(&quot;Analyze data&quot;),<br>    AIMessage(&quot;I&#39;ll start by loading...&quot;),<br>    ToolMessage(&quot;df loaded&quot;),  # Iteration 1<br>    AIMessage(&quot;Now exploring...&quot;),<br>    ToolMessage(&quot;df.info() output&quot;),  # Iteration 2<br>    AIMessage(&quot;Handling missing...&quot;),<br>    ToolMessage(&quot;fillna() output&quot;),  # Iteration 3<br>    ... # 30+ more tool messages<br>]</pre><p><strong>Impact:</strong></p><ul><li>LangGraph Studio visualization became unreadable</li><li>Langsmith tracing became too polluted to be comprehensible</li><li>Context window filled with tool messages</li><li>Cost heavy due to high token usage</li><li>Hard to find actual user conversation</li></ul><p><strong>Solution:</strong> Subgraph with isolated state:</p><pre># Parent graph: Clean conversation<br># Subgraph: Internal tool iterations</pre><pre>class CodingSubgraphOutput(TypedDict):<br>    messages: List[BaseMessage]  # ONLY final summary message<br>    artifacts: List[Artifact]     # Collected results</pre><p><strong>Learning:</strong> Subgraphs aren’t just for organization — they’re for <strong>state hygiene</strong>.</p><h3>Challenge 2: Code Execution Performance</h3><p><strong>Problem:</strong> Initially used subprocess.Popen() for each code execution:</p><pre># Old approach<br>def execute_code(code: str):<br>    process = subprocess.Popen(<br>        [&quot;python&quot;, &quot;-c&quot;, code],<br>        stdout=subprocess.PIPE,<br>        stderr=subprocess.PIPE<br>    )<br>    output, error = process.communicate()</pre><p><strong>Impact:</strong></p><ul><li>2–3 seconds per execution (subprocess spawn overhead)</li><li>20 iterations = 40–60 seconds just in process creation</li><li>Variables don’t persist (df gone after each execution)</li></ul><p><strong>Solution:</strong> HTTP-based microservice with in-memory session contexts:</p><pre># New approach<br>SESSION_CONTEXTS = {}  # Persistent contexts</pre><pre>@app.post(&quot;/execute&quot;)<br>def execute(session_id: str, code: str):<br>    if session_id not in SESSION_CONTEXTS:<br>        SESSION_CONTEXTS[session_id] = {}</pre><pre>    context = SESSION_CONTEXTS[session_id]<br>    exec(code, {&quot;__builtins__&quot;: __builtins__}, context)<br>    # Variables persist in context!</pre><p><strong>Results:</strong></p><ul><li>~200ms per execution (10x faster)</li><li>DataFrames persist across iterations</li><li>Cleaner architecture</li></ul><p><strong>Learning:</strong> For stateful execution, <strong>microservices &gt; subprocesses</strong>.</p><h3>Challenge 3: Agent Iteration Efficiency</h3><p><strong>Problem:</strong> Coding agent wasted iterations:</p><ul><li>Iteration 5: Create plot</li><li>Iteration 6: Create the same plot again</li><li>Iteration 7: Try to load data that’s already loaded</li><li>Iteration 15: Still confused</li></ul><p><strong>Impact:</strong> Simple analyses took 20+ iterations when 5 should suffice.</p><p><strong>Solution:</strong> Forced reflection with think_tool:</p><pre>CODING_PROMPT = &quot;&quot;&quot;<br>CRITICAL: After EVERY code execution, use think_tool to:<br>1. Analyze what you just did<br>2. Check if step goal is achieved<br>3. Decide next action</pre><pre>EFFICIENCY GUIDELINES:<br>- Simple tasks (basic stats, single plot): 3-5 iterations<br>- Medium tasks (data cleaning + analysis): 6-10 iterations<br>- Complex tasks (ML pipeline): 10-15 iterations</pre><pre>If you exceed these, you&#39;re likely repeating work!<br>&quot;&quot;&quot;</pre><p><strong>Results:</strong></p><ul><li>Average iterations dropped from 18 to 7</li><li>More deliberate, less trial-and-error</li><li>Better final outputs</li></ul><p><strong>Learning:</strong> <strong>Metacognition tools</strong> (think_tool) dramatically improve efficiency.</p><h3>Challenge 4: Context Window Management</h3><p><strong>Problem:</strong> After 10 iterations, conversation history + data context + code outputs = 50k+ tokens.</p><p><strong>Impact:</strong></p><ul><li>High API costs</li><li>Slower responses</li><li>Context limit errors</li></ul><p><strong>Solution 1:</strong> Supervisor short-circuits</p><pre>def supervisor_node(state):<br>    if can_answer_from_context(state):<br>        return &quot;answer_directly&quot;  # Skip code execution<br>    else:<br>        return &quot;plan_analysis&quot;</pre><p><strong>Solution 2:</strong> Summarize intermediate steps</p><pre>def summarize_step_result(code_output: str) -&gt; str:<br>    if len(code_output) &gt; 1000:<br>        # Use LLM to summarize long outputs<br>        summary = llm.invoke(f&quot;Summarize this output in 2-3 sentences: {code_output}&quot;)<br>        return summary<br>    return code_output</pre><p><strong>Solution 3:</strong> Trim old messages</p><pre>def trim_messages(messages: List[BaseMessage], keep_last_n: int = 10):<br>    # Always keep system message and last N exchanges<br>    return [messages[0]] + messages[-keep_last_n:]</pre><p><strong>Learning:</strong> <strong>Context management is a first-class concern</strong>, not an afterthought.</p><h3>Challenge 5: Handling Vague Queries</h3><p><strong>Problem:</strong> User asks: “Analyze this data”</p><p><strong>What should the agent do?</strong></p><ul><li>Descriptive statistics?</li><li>Predictive modeling?</li><li>Anomaly detection?</li><li>All of the above?</li></ul><p><strong>Solution:</strong> Planning prompt includes smart defaults:</p><pre>PLANNING_PROMPT = &quot;&quot;&quot;<br>When the user&#39;s request is vague, apply these defaults:</pre><pre>1. &quot;Analyze data&quot; →<br>- Descriptive statistics (mean, median, std)<br>- Distribution plots for numerical features<br>- Value counts for categorical features<br>- Correlation analysis<br>- Anomaly detection</pre><pre>2. &quot;Predict X&quot; →<br>- Feature engineering<br>- Train-test split<br>- RandomForest model (robust default)<br>- Feature importance analysis<br>- Prediction with confidence intervals</pre><pre>3. &quot;Find insights&quot; →<br>- Correlation analysis<br>- Trend detection<br>- Seasonal patterns (if temporal data)<br>- Top/bottom performers<br>- Statistical anomalies</pre><pre>Always ask clarifying questions if truly ambiguous.<br>&quot;&quot;&quot;</pre><p><strong>Learning:</strong> <strong>Intelligent defaults</strong> beat asking users 10 clarifying questions.</p><h3>Challenge 6: Debugging Multi-Agent Flows</h3><p><strong>Problem:</strong> Bug manifests at step 5 (coding agent), but root cause is in step 2 (data inspector).</p><p><strong>Impact:</strong> Hard to trace errors through multi-step flow.</p><p><strong>Solution:</strong> Comprehensive logging + LangGraph Studio:</p><pre>import logging<br>from datetime import datetime</pre><pre>logger = logging.getLogger(__name__)</pre><pre>def data_inspector_node(state):<br>    logger.info(f&quot;=== DATA INSPECTOR NODE START [{datetime.now()}] ===&quot;)<br>    logger.debug(f&quot;Input state keys: {state.keys()}&quot;)<br>    logger.debug(f&quot;Excel file: {state[&#39;excel_file_path&#39;]}&quot;)</pre><pre>    # ... execute inspection ...</pre><pre>    logger.info(f&quot;Generated data context with {len(data_context)} keys&quot;)<br>    logger.debug(f&quot;Data context: {json.dumps(data_context, indent=2)}&quot;)<br>    logger.info(f&quot;=== DATA INSPECTOR NODE END ===&quot;)</pre><pre>    return {&quot;data_context&quot;: data_context}</pre><p><strong>Plus:</strong> LangGraph Studio visualization shows exact state at each node.</p><p><strong>Learning:</strong> <strong>Observability investment pays 10x dividends</strong> during debugging.</p><h3>6. Learnings and Takeaways</h3><h3>💡 Learning 1: Multi-Agent &gt; Monolithic (For Complex Tasks)</h3><p><strong>Single Agent Approach:</strong></p><pre>agent = &quot;You are an expert data analyst. When given Excel data:<br>1. Inspect it<br>2. Plan analysis<br>3. Execute code<br>4. Generate insights&quot;</pre><p><strong>Result:</strong> Agent tries to do everything at once, gets confused, poor separation of concerns.</p><p><strong>Multi-Agent Approach:</strong> Each agent is an expert at ONE thing.</p><p><strong>Result:</strong> Better performance, easier debugging, clearer reasoning.</p><p><strong>When to use which:</strong></p><ul><li><strong>Simple tasks (1–2 steps):</strong> Single agent</li><li><strong>Complex tasks (3+ distinct phases):</strong> Multi-agent</li><li><strong>Tasks requiring different expertise:</strong> Multi-agent</li></ul><h3>💡 Learning 2: Structured Output is Non-Negotiable</h3><p><strong>Before:</strong></p><pre># LLM returns text, we parse it<br>response = llm.invoke(&quot;Should we analyze or chat?&quot;)<br>if &quot;analyze&quot; in response.lower():<br>    route = &quot;analysis&quot;<br>elif &quot;chat&quot; in response.lower():<br>    route = &quot;chat&quot;<br># What if LLM returns &quot;I think this is an analysis request&quot;?</pre><p><strong>After:</strong></p><pre>class RouterDecision(BaseModel):<br>    route: Literal[&quot;chat&quot;, &quot;analysis&quot;, &quot;analysis_followup&quot;]<br>    reasoning: str</pre><pre>llm_with_structure = llm.with_structured_output(RouterDecision)<br>decision = llm_with_structure.invoke(...)<br># Guaranteed type-safe route</pre><p><strong>Benefits:</strong></p><ul><li>No parsing errors</li><li>Type safety</li><li>Better prompts (LLM knows expected structure)</li><li>Easier testing</li></ul><h3>💡 Learning 3: Prompts Are Architecture</h3><p><strong>Underdeveloped systems:</strong> 80% code, 20% prompts <strong>Mature systems:</strong> 50% code, 50% prompts</p><p><strong>Good prompts:</strong></p><ul><li>Encode domain knowledge</li><li>Provide examples</li><li>Set expectations</li><li>Define success criteria</li></ul><p><strong>Example:</strong> Our planning prompt is 162 lines with ML best practices. This <strong>IS</strong> the intelligence of the system.</p><h3>💡 Learning 4: State Design Impacts Everything</h3><p><strong>Poor state design:</strong></p><pre>state = {<br>    &quot;data&quot;: {...},<br>    &quot;results&quot;: [...],<br>    &quot;stuff&quot;: {...}<br>}</pre><p><strong>Issues:</strong></p><ul><li>What’s in “stuff”?</li><li>How do “results” accumulate?</li><li>No type safety</li></ul><p><strong>Good state design:</strong></p><pre>class ExcelAnalysisState(MessagesState):<br>    excel_file_path: str<br>    data_context: Dict[str, Any]<br>    artifacts: Annotated[List[Artifact], add_artifacts]  # Custom reducer<br>    analysis_steps: Annotated[List[AnalysisStep], update_analysis_steps]</pre><p><strong>Benefits:</strong></p><ul><li>Self-documenting</li><li>Type-safe</li><li>Custom accumulation logic</li><li>Clear ownership</li></ul><p><strong>Takeaway:</strong> Design state FIRST, then build nodes.</p><h3>💡 Learning 5: Observability Enables Iteration</h3><p><strong>Without observability:</strong></p><ul><li>“It doesn’t work” → Spend hours debugging</li></ul><p><strong>With observability:</strong></p><ul><li>Check logs → “Router sent to wrong node”</li><li>Check LangGraph Studio → “Data context empty at step 3”</li><li>Check console output → “Sandbox server not responding”</li><li><strong>Fix in minutes</strong></li></ul><p><strong>Investment areas:</strong></p><ol><li>Structured logging (info, debug, error levels)</li><li>Console feedback for users (rich library)</li><li>LangGraph Studio integration</li><li>Step-by-step progress indicators</li></ol><h3>💡 Learning 6: Performance Optimization ≠ Premature</h3><p><strong>When we optimized:</strong></p><ul><li>Subgraph isolation → After message pollution became problem</li><li>Microservice sandbox → After subprocess slowness became obvious</li><li>Supervisor short-circuit → After seeing repeated unnecessary executions</li></ul><p><strong>When we didn’t optimize:</strong></p><ul><li>Database for session storage (in-memory works fine)</li><li>Caching analysis results (premature — need more usage data)</li><li>Distributed execution (single machine sufficient)</li></ul><p><strong>Principle:</strong> Optimize based on <strong>observed bottlenecks</strong>, not hypothetical ones.</p><h3>💡 Learning 7: Agent Tools Shape Behavior</h3><p><strong>Minimal tools:</strong></p><pre>tools = [python_repl_tool]</pre><p><strong>Result:</strong> Agent executes blindly, wastes iterations.</p><p><strong>Reflection tools:</strong></p><pre>tools = [python_repl_tool, think_tool]</pre><p><strong>Result:</strong> Agent becomes deliberate, reduces wasted work.</p><p><strong>Takeaway:</strong> Tools aren’t just capabilities — they’re <strong>behavioral nudges</strong>.</p><h3>💡 Learning 8: LangGraph Studio comes in clutch !</h3><p><strong>LangGraph Studio provides:</strong></p><ul><li>Visual graph representation</li><li>State inspection at each node</li><li>Message flow visualization</li><li>Debugging playback</li></ul><p><strong>Impact:</strong></p><ul><li>10x faster debugging</li><li>Better understanding of agent reasoning</li><li>Easier to explain system to stakeholders</li></ul><p><strong>Investment:</strong> Setting up local LangGraph Studio (langgraph dev) pays off immediately.</p><h3>💡 Learning 9: Error Handling is Product Design</h3><p><strong>Bad error handling:</strong></p><pre>except Exception as e:<br>    return {&quot;error&quot;: str(e)}</pre><p><strong>User sees:</strong> “KeyError: ‘data_context’”</p><p><strong>Good error handling:</strong></p><pre>except FileNotFoundError:<br>    return {<br>        &quot;final_analysis&quot;: &quot;❌ Excel file not found. Please check the file path and try again.&quot;,<br>        &quot;artifacts&quot;: []<br>    }<br>except SandboxError:<br>    return {<br>        &quot;final_analysis&quot;: &quot;❌ Code execution service unavailable. Please ensure the sandbox server is running (python run_sandbox_server.py)&quot;,<br>        &quot;artifacts&quot;: []<br>    }<br>except Exception as e:<br>    logger.error(f&quot;Unexpected error: {e}&quot;, exc_info=True)<br>    return {<br>        &quot;final_analysis&quot;: f&quot;❌ An unexpected error occurred: {str(e)}. Please try simplifying your query.&quot;,<br>        &quot;artifacts&quot;: []<br>    }</pre><p><strong>User sees:</strong> Actionable error message with next steps.</p><p><strong>Takeaway:</strong> Error messages are UX, not debugging info.</p><h3>💡 Learning 10: Know When to Use LLMs</h3><p><strong>Use LLMs for:</strong></p><ul><li>Ambiguous decisions (routing, classification)</li><li>Planning and strategy</li><li>Code generation</li><li>Natural language generation</li></ul><p><strong>Don’t use LLMs for:</strong></p><ul><li>Deterministic logic (use Python)</li><li>Fast lookups (use databases)</li><li>Exact calculations (use code)</li><li>Always-same responses (use templates)</li></ul><p><strong>Example:</strong></p><pre># Bad: Using LLM for simple check<br>def check_if_excel_file(path: str) -&gt; bool:<br>    return llm.invoke(f&quot;Is {path} an Excel file? Answer yes or no&quot;) == &quot;yes&quot;</pre><pre># Good: Use Python<br>def check_if_excel_file(path: str) -&gt; bool:<br>    return path.endswith((&#39;.xlsx&#39;, &#39;.xls&#39;))</pre><p><strong>Takeaway:</strong> LLMs are expensive. Use them where they add unique value.</p><h3>7. Scope for Improvement</h3><h3>📈 Improvement Area 1: Conversation Memory</h3><p><strong>Current State:</strong> Each session is independent. No memory across conversations.</p><p><strong>Limitation:</strong> User can’t say: “Remember that sales analysis from yesterday? Apply the same approach to this new dataset.”</p><p><strong>Future Enhancement:</strong></p><pre>from langchain.memory import ConversationSummaryMemory</pre><pre>class ExcelAnalysisState(MessagesState):<br>    session_id: str<br>    conversation_summary: str  # Persistent across sessions<br>    past_analyses: List[AnalysisReference]  # Links to previous work</pre><pre># Enable:<br># &quot;Use the same features you engineered last week&quot;<br># &quot;Compare this quarter&#39;s results to last quarter&#39;s analysis&quot;</pre><p><strong>Implementation Considerations:</strong></p><ul><li>Store conversation summaries in database</li><li>Reference artifacts from previous sessions</li><li>Privacy: User data isolation</li></ul><h3>📈 Improvement Area 2: Collaborative Analysis</h3><p><strong>Current State:</strong> Single user, single Excel file, single analysis thread.</p><p><strong>Limitation:</strong> Teams can’t collaborate on analysis. No shared context.</p><p><strong>Future Enhancement:</strong></p><pre># Multi-user session<br>class TeamAnalysisState(ExcelAnalysisState):<br>    team_members: List[UserId]<br>    shared_context: SharedDataContext<br>    analysis_comments: List[Comment]</pre><pre># Enable:<br># - User A: &quot;Analyze sales trends&quot;<br># - User B: &quot;Why did Q2 drop?&quot; (in same context)<br># - User C: &quot;Add regional breakdown&quot; (augments existing analysis)</pre><p><strong>Implementation Considerations:</strong></p><ul><li>Real-time collaboration (WebSocket)</li><li>Conflict resolution (multiple users editing)</li><li>Permissions and access control</li></ul><h3>📈 Improvement Area 3: Streaming Responses</h3><p><strong>Current State:</strong> User waits for entire analysis to complete before seeing results.</p><p><strong>Limitation:</strong> 20-second wait time feels long. No intermediate feedback.</p><p><strong>Future Enhancement:</strong></p><pre># Stream partial results<br>async def coding_agent_node_streaming(state: CodingSubgraphState):<br>    for step in analysis_steps:<br>        # Execute step<br>        result = await execute_step(step)</pre><pre>        # Stream partial result to user<br>        yield {<br>            &quot;partial_artifact&quot;: result.artifact,<br>            &quot;step_completed&quot;: step.order<br>        }</pre><pre># User sees:<br># [5s] ✓ Data loaded (10,000 rows)<br># [8s] ✓ Missing values handled<br># [12s] 📊 [First plot appears]<br># [18s] ✓ Model trained (R² = 0.85)<br># [20s] 📊 [Feature importance plot appears]</pre><p><strong>Implementation Considerations:</strong></p><ul><li>LangGraph streaming support</li><li>Frontend needs to handle partial updates</li><li>Error handling during streams</li></ul><h3>📈 Improvement Area 4: Multi-File Analysis</h3><p><strong>Current State:</strong> Single Excel file per analysis.</p><p><strong>Limitation:</strong> Can’t join data from multiple sources or analyze across files.</p><p><strong>Future Enhancement:</strong></p><pre>class ExcelAnalysisState(MessagesState):<br>    excel_files: List[FileContext]  # Multiple files<br>    join_strategy: JoinConfig       # How to combine data</pre><pre># Enable queries like:<br># &quot;Join sales.xlsx with customers.xlsx on customer_id and analyze revenue by segment&quot;<br># &quot;Compare Q1_results.xlsx with Q2_results.xlsx&quot;</pre><p><strong>Implementation Considerations:</strong></p><ul><li>Data inspector handles multiple files</li><li>Planning agent decides join strategy</li><li>Memory management for large datasets</li></ul><h3>📈 Improvement Area 5: Export and Sharing</h3><p><strong>Current State:</strong> Results exist in conversation. No easy export.</p><p><strong>Limitation:</strong> Users can’t easily share analyses with teammates or save for later.</p><p><strong>Future Enhancement:</strong></p><pre># Generate shareable reports<br>@tool<br>def export_analysis_tool(format: Literal[&quot;pdf&quot;, &quot;html&quot;, &quot;notebook&quot;]) -&gt; str:<br>    &quot;&quot;&quot;Export complete analysis with plots, code, and insights&quot;&quot;&quot;</pre><pre>    if format == &quot;pdf&quot;:<br>        return generate_pdf_report(artifacts, analysis_steps)<br>    elif format == &quot;html&quot;:<br>        return generate_interactive_dashboard(artifacts)<br>    elif format == &quot;notebook&quot;:<br>        return generate_jupyter_notebook(code_history, artifacts)</pre><pre># Enable:<br># User: &quot;Export this analysis as a PDF report&quot;<br># User: &quot;Create an interactive dashboard I can share&quot;<br># User: &quot;Give me a Jupyter notebook with all the code&quot;</pre><p><strong>Implementation Considerations:</strong></p><ul><li>Template system for reports</li><li>Code cleanup (remove iterations, show final code)</li><li>Branding and customization</li></ul><h3>📈 Improvement Area 6: Learning from Feedback</h3><p><strong>Current State:</strong> Agent doesn’t learn from user corrections or preferences.</p><p><strong>Limitation:</strong> Repeats mistakes. Doesn’t adapt to user’s style.</p><p><strong>Future Enhancement:</strong></p><pre>class UserPreferences(TypedDict):<br>    preferred_plot_style: str       # &quot;seaborn&quot;, &quot;plotly&quot;, &quot;minimal&quot;<br>    modeling_preferences: Dict      # {&quot;algorithm&quot;: &quot;xgboost&quot;, &quot;validation&quot;: &quot;k-fold&quot;}<br>    analysis_depth: str             # &quot;quick&quot;, &quot;standard&quot;, &quot;comprehensive&quot;</pre><pre># Feedback loop<br>@tool<br>def record_feedback_tool(rating: int, feedback: str):<br>    &quot;&quot;&quot;User rates analysis quality and provides feedback&quot;&quot;&quot;<br>    store_feedback(session_id, rating, feedback)</pre><pre>    # Future analyses incorporate feedback<br>    if &quot;too slow&quot; in feedback:<br>        adjust_iteration_limits(decrease=True)<br>    if &quot;not enough detail&quot; in feedback:<br>        adjust_analysis_depth(increase=True)</pre><pre># Enable:<br># Agent learns user prefers XGBoost over RandomForest<br># Agent learns user wants 95% confidence intervals (not 90%)<br># Agent learns user&#39;s industry-specific terminology</pre><p><strong>Implementation Considerations:</strong></p><ul><li>Reinforcement learning from human feedback (RLHF)</li><li>Preference storage and retrieval</li><li>Privacy considerations</li></ul><h3>📈 Improvement Area 7: Proactive Insights</h3><p><strong>Current State:</strong> Agent only responds to queries. Reactive, not proactive.</p><p><strong>Limitation:</strong> Might miss important patterns user didn’t think to ask about.</p><p><strong>Future Enhancement:</strong></p><pre>class ProactiveInsight(TypedDict):<br>    type: str                    # &quot;anomaly&quot;, &quot;trend&quot;, &quot;correlation&quot;, &quot;warning&quot;<br>    description: str<br>    severity: Literal[&quot;info&quot;, &quot;warning&quot;, &quot;critical&quot;]<br>    suggested_action: str</pre><pre>def generate_proactive_insights(data_context: Dict) -&gt; List[ProactiveInsight]:<br>    &quot;&quot;&quot;Analyze data and surface interesting patterns proactively&quot;&quot;&quot;</pre><pre>    insights = []</pre><pre>    # Check for data quality issues<br>    if high_missing_rate(data_context):<br>        insights.append({<br>            &quot;type&quot;: &quot;warning&quot;,<br>            &quot;description&quot;: &quot;Column &#39;revenue&#39; has 35% missing values&quot;,<br>            &quot;severity&quot;: &quot;warning&quot;,<br>            &quot;suggested_action&quot;: &quot;Consider imputation or removal before modeling&quot;<br>        })</pre><pre>    # Check for temporal patterns<br>    if has_temporal_column(data_context):<br>        insights.append({<br>            &quot;type&quot;: &quot;info&quot;,<br>            &quot;description&quot;: &quot;Detected strong weekly seasonality&quot;,<br>            &quot;severity&quot;: &quot;info&quot;,<br>            &quot;suggested_action&quot;: &quot;Consider adding day_of_week feature&quot;<br>        })</pre><pre>    return insights</pre><pre># Enable:<br># Agent: &quot;🔍 I noticed something: Your data shows a spike in errors every Sunday.<br>#         This might indicate a batch process issue.&quot;<br># Agent: &quot;⚠️ Warning: 3 outliers detected that are 5σ from mean. Review before modeling?&quot;</pre><p><strong>Implementation Considerations:</strong></p><ul><li>Heuristics + ML for pattern detection</li><li>Threshold tuning (avoid alert fatigue)</li><li>User preference for proactivity level</li></ul><h3>📈 Improvement Area 8: Domain Specialization</h3><p><strong>Current State:</strong> General-purpose analysis agent.</p><p><strong>Limitation:</strong> Lacks deep domain expertise (finance, healthcare, retail, etc.).</p><p><strong>Future Enhancement:</strong></p><pre># Domain-specific sub-agents<br>DOMAIN_AGENTS = {<br>    &quot;finance&quot;: FinanceAnalysisAgent(<br>        knowledge=[&quot;risk metrics&quot;, &quot;portfolio optimization&quot;, &quot;time series forecasting&quot;],<br>        constraints=[&quot;regulatory compliance&quot;, &quot;audit trail&quot;]<br>    ),<br>    &quot;healthcare&quot;: HealthcareAnalysisAgent(<br>        knowledge=[&quot;patient cohorts&quot;, &quot;survival analysis&quot;, &quot;clinical metrics&quot;],<br>        constraints=[&quot;HIPAA compliance&quot;, &quot;PHI protection&quot;]<br>    ),<br>    &quot;retail&quot;: RetailAnalysisAgent(<br>        knowledge=[&quot;customer segmentation&quot;, &quot;churn prediction&quot;, &quot;basket analysis&quot;],<br>        constraints=[&quot;PII handling&quot;, &quot;seasonal adjustments&quot;]<br>    )<br>}</pre><pre># Router detects domain<br>def enhanced_router(query: str, data_context: Dict) -&gt; str:<br>    domain = detect_domain(query, data_context)<br>    return DOMAIN_AGENTS[domain]</pre><pre># Enable:<br># Finance query → Uses Sharpe ratio, VaR, beta calculations automatically<br># Healthcare query → Uses survival curves, hazard ratios, cohort analysis<br># Retail query → Uses RFM analysis, CLV, market basket analysis</pre><p><strong>Implementation Considerations:</strong></p><ul><li>Domain knowledge bases</li><li>Specialized prompt libraries</li><li>Domain-specific tool sets</li></ul><h3>📈 Improvement Area 9: Cost Optimization</h3><p><strong>Current State:</strong> Every query uses GPT-4/GPT-5. No cost awareness.</p><p><strong>Limitation:</strong> Expensive for simple queries. Not sustainable at scale.</p><p><strong>Future Enhancement:</strong></p><pre># Tiered model usage<br>MODEL_STRATEGY = {<br>    &quot;router&quot;: &quot;gpt-4o-mini&quot;,           # Fast, cheap classification<br>    &quot;data_inspector&quot;: &quot;gpt-4o-mini&quot;,   # Structured task<br>    &quot;supervisor&quot;: &quot;gpt-4o&quot;,            # Needs reasoning<br>    &quot;planning&quot;: &quot;gpt-4o&quot;,              # Needs expertise<br>    &quot;coding&quot;: &quot;gpt-5&quot;,                 # Needs best code generation<br>}</pre><pre># Dynamic model selection<br>def select_model(task_complexity: str) -&gt; str:<br>    if task_complexity == &quot;simple&quot;:<br>        return &quot;gpt-4o-mini&quot;  # $0.10/1M tokens<br>    elif task_complexity == &quot;medium&quot;:<br>        return &quot;gpt-4o&quot;       # $2.50/1M tokens<br>    else:<br>        return &quot;gpt-5&quot;        # $5.00/1M tokens</pre><pre># Caching<br>@lru_cache(maxsize=100)<br>def get_data_context(file_path: str, file_hash: str) -&gt; Dict:<br>    &quot;&quot;&quot;Cache data inspection results&quot;&quot;&quot;<br>    # Same file → reuse context, don&#39;t re-inspect</pre><p><strong>Estimated Savings:</strong> 40–60% cost reduction with no quality loss.</p><h3>📈 Improvement Area 10: Human-in-the-Loop</h3><p><strong>Current State:</strong> Agent executes plan autonomously. No checkpoints.</p><p><strong>Limitation:</strong> Can’t catch major misunderstandings before expensive execution.</p><p><strong>Future Enhancement:</strong></p><pre># Confirmation checkpoints<br>def planning_node_with_confirmation(state: ExcelAnalysisState):<br>    plan = generate_analysis_plan(state)</pre><pre>    # Present plan to user<br>    await ask_user_confirmation(<br>        message=f&quot;I&#39;ve created this analysis plan:\n{format_plan(plan)}\n\nProceed?&quot;,<br>        options=[&quot;Yes&quot;, &quot;Modify&quot;, &quot;Cancel&quot;]<br>    )</pre><pre>    if user_response == &quot;Modify&quot;:<br>        modifications = await get_user_input(&quot;What would you like to change?&quot;)<br>        plan = revise_plan(plan, modifications)</pre><pre>    return {&quot;analysis_plan&quot;: plan}</pre><pre># Enable:<br># Agent: &quot;I plan to: 1) Build linear regression 2) Use raw dates 3) No validation. Proceed?&quot;<br># User: &quot;No, use RandomForest and add cross-validation&quot;<br># Agent: *Revises plan* &quot;Updated plan: 1) Build RandomForest 2) 5-fold CV. Proceed?&quot;<br># User: &quot;Yes!&quot;</pre><p><strong>Implementation Considerations:</strong></p><ul><li>Async user input handling</li><li>Timeout handling (user doesn’t respond)</li><li>Plan revision logic</li></ul><h3>📈 Improvement Area 11: Testing and Validation</h3><p><strong>Current State:</strong> Manual testing. No automated test suite.</p><p><strong>Limitation:</strong> Changes might break existing functionality. Hard to ensure quality.</p><p><strong>Future Enhancement:</strong></p><pre># Test suite for agents<br>class TestExcelAnalysisAgent:</pre><pre>    def test_router_classification(self):<br>        &quot;&quot;&quot;Test router correctly classifies query types&quot;&quot;&quot;<br>        assert route_query(&quot;Hello!&quot;) == &quot;chat&quot;<br>        assert route_query(&quot;Analyze sales.xlsx&quot;) == &quot;analysis&quot;<br>        assert route_query(&quot;Why did revenue drop?&quot;) == &quot;analysis_followup&quot;</pre><pre>    def test_data_inspector_handles_missing_values(self):<br>        &quot;&quot;&quot;Test data inspector correctly identifies missing data&quot;&quot;&quot;<br>        context = inspect_data(&quot;data/test_missing_values.xlsx&quot;)<br>        assert context[&quot;missing_values&quot;][&quot;price&quot;] == 10</pre><pre>    def test_end_to_end_simple_analysis(self):<br>        &quot;&quot;&quot;Test complete flow for simple analysis query&quot;&quot;&quot;<br>        result = run_analysis(<br>            query=&quot;What&#39;s the average revenue?&quot;,<br>            file=&quot;data/test_sales.xlsx&quot;<br>        )</pre><pre>        assert result[&quot;success&quot;] == True<br>        assert &quot;average revenue&quot; in result[&quot;final_analysis&quot;].lower()<br>        assert len(result[&quot;artifacts&quot;]) &gt; 0</pre><pre># Integration tests<br>def test_coding_agent_handles_errors():<br>    &quot;&quot;&quot;Test coding agent gracefully handles execution errors&quot;&quot;&quot;<br>    result = run_coding_agent(<br>        plan=&quot;Load non-existent file&quot;,<br>        file=&quot;data/test.xlsx&quot;<br>    )</pre><pre>    # Should fail gracefully, not crash<br>    assert &quot;error&quot; in result[&quot;final_analysis&quot;].lower()<br>    assert result[&quot;code_iterations&quot;] &lt; 5  # Don&#39;t waste iterations</pre><p><strong>Implementation Considerations:</strong></p><ul><li>Test data fixtures</li><li>Mocking LLM responses (for deterministic tests)</li><li>CI/CD integration</li></ul><h3>8. Conclusion</h3><h3>What We Built</h3><p>An <strong>autonomous Excel analysis agent</strong> that:</p><ul><li>✅ Understands data structure automatically</li><li>✅ Plans sophisticated analysis strategies</li><li>✅ Writes and executes Python code iteratively</li><li>✅ Self-corrects errors through reflection</li><li>✅ Produces multi-modal outputs (plots, tables, insights)</li><li>✅ Handles follow-up questions intelligently</li></ul><h3>Why It Matters</h3><p>This project demonstrates that <strong>multi-agent AI systems</strong> can tackle complex, multi-step workflows that previously required human expertise. The architecture patterns we developed, subgraph isolation, microservice sandboxing, reflection-driven execution, are applicable far beyond data analysis.</p><h3>Key Architectural Innovations</h3><ol><li><strong>Subgraph State Isolation</strong> — Clean conversation history despite complex internal iterations</li><li><strong>Microservice Sandbox</strong> — 10x faster execution with persistent state</li><li><strong>Reflection-Driven Agents</strong> — Metacognition tools (think_tool) reduce wasted iterations</li><li><strong>Hierarchical Routing</strong> — Router + Supervisor layers prevent unnecessary work</li><li><strong>Artifact Accumulation</strong> — Structured multi-modal outputs</li><li><strong>TodoList Pattern</strong> — Visual progress tracking builds user trust</li></ol><h3>The Broader Lessons</h3><h4>1. Agent Specialization Wins</h4><p>Instead of one “do everything” agent, create specialized agents for distinct tasks. Easier to build, debug, and improve.</p><h4>2. Prompts Are Architecture</h4><p>Don’t underestimate prompt engineering. Half your intelligence lives in prompts, not code.</p><h4>3. State Design is Critical</h4><p>Type your state. Use custom reducers. Design state before building nodes.</p><h4>4. Observability Enables Iteration</h4><p>Invest in logging, visualization, and progress indicators. Debugging and user trust both improve.</p><h4>5. LLMs Are Tools, Not Magic</h4><p>Use LLMs where they excel (ambiguous decisions, planning, generation). Use code for deterministic logic.</p><h4>6. Performance Optimization Should Be Pragmatic</h4><p>Optimize observed bottlenecks, not hypothetical ones. Our microservice migration was driven by measured 10x slowdown.</p><h4>7. Error Handling is UX</h4><p>Users don’t care about stack traces. Provide actionable error messages with next steps.</p><h3>Who Should Build Similar Systems?</h3><p>This architecture is valuable for:</p><ul><li><strong>Data teams</strong> wanting to democratize analysis</li><li><strong>Enterprises</strong> with domain-specific workflows</li><li><strong>SaaS products</strong> adding AI-powered features</li><li><strong>Researchers</strong> exploring multi-agent systems</li></ul><h3>Resources</h3><ul><li><strong>LangGraph Docs:</strong> <a href="https://langchain-ai.github.io/langgraph/">https://langchain-ai.github.io/langgraph/</a></li><li><strong>LangChain Docs:</strong> <a href="https://python.langchain.com/">https://python.langchain.com/</a></li><li><strong>LangGraph Studio:</strong> <a href="https://github.com/langchain-ai/langgraph-studio">https://github.com/langchain-ai/langgraph-studio</a></li><li><strong>Multi-Agent Patterns:</strong> <a href="https://langchain-ai.github.io/langgraph/concepts/multi_agent/">https://langchain-ai.github.io/langgraph/concepts/multi_agent/</a></li></ul><h3>Final Thoughts</h3><p>Building this Excel Analysis Agent taught us that <strong>AI agents are not just about LLMs, </strong>they’re about:</p><ul><li>Thoughtful architecture</li><li>Intelligent delegation</li><li>Robust error handling</li><li>User-centric design</li></ul><p>The future of software isn’t just LLMs in isolation. It’s <strong>orchestrated systems of specialized agents</strong>, working together to solve complex problems autonomously.</p><p>We hope this deep dive inspires you to build your own multi-agent systems. The patterns we’ve shared are battle-tested and ready to be adapted to your domain.</p><p><strong>Happy building!</strong></p><p>Github Repo: <a href="https://github.com/AdolfFiddler/crafting-ai-agents/tree/98536bec1c09218212e9202e292419fbe6dff57e/excel_analysis_agent">https://github.com/AdolfFiddler/crafting-ai-agents/tree/98536bec1c09218212e9202e292419fbe6dff57e/excel_analysis_agent</a><br>Linkedin: <a href="http://www.linkedin.com/in/anubhavmishra7200">www.linkedin.com/in/anubhavmishra7200</a></p><p><em>Have questions or want to discuss multi-agent architecture? Feel free to reach out or leave comments below. I’d love to hear about your own agent-building experiences!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=115ca44ade65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[95% of Generative AI Pilots Fail to Deliver Measurable Impact | My Take on What We’re Missing.]]></title>
            <link>https://medium.com/@anubhavm48/95-of-generative-ai-pilots-fail-to-deliver-measurable-impact-my-take-on-what-were-missing-361454c451f6?source=rss-9b2585e2d20e------2</link>
            <guid isPermaLink="false">https://medium.com/p/361454c451f6</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Anubhav Mishra]]></dc:creator>
            <pubDate>Sat, 04 Oct 2025 17:56:38 GMT</pubDate>
            <atom:updated>2025-10-04T17:56:38.029Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QpXBsHvEDxKR3Mxgu0IhDQ.png" /></figure><p>Over the past two years, I’ve worked on multiple projects applying Large language models to solve complex business problems. From automating document creation to building intelligent assistants, I’ve seen firsthand both the power and the pitfalls of Generative AI in enterprise settings.</p><p>And through these experiences and countless conversations with stakeholders and end-users, I’ve come to a simple realization:</p><p>One of the biggest reasons, Generative AI applications are failing to realize the expected value is user trust.</p><h3>Technically Brilliant, Practically Underused:</h3><p>A lot of these applications are <em>technically</em> excellent, they use complex frameworks and architectures to parse documents, generate reports, summarize data, or even create regulatory content with impressive precision.</p><p>But the reality? Many of them end up being under-utilized by the very users they were meant to help.</p><p>Why?</p><p>Because in industries dealing with proprietary or critical information — pharma, finance, legal, or consumer goods — users don’t fully trust the black-box nature of AI outputs. They’re accountable for every word and every number in those documents. So when the AI produces a “complete” output, users feel the need to re-read, re-verify, and cross-check everything.</p><p>The outcome: instead of saving time, the app adds work.</p><h3>What I’ve Heard From Users and Stakeholders:</h3><p>“I can’t approve this unless I know where the information came from.”</p><p>“This looks great, but I’ll still have to verify it manually.”</p><p>“The system is smart, but I don’t <em>feel</em> in control.”</p><p>And these aren’t isolated reactions, they reflect a broader industry trend. Studies show that while 71% of companies have adopted GenAI in at least one function (McKinsey, 2024), less than 30% of enterprise users report trusting AI outputs without verification.</p><p>In short: we’re automating faster than we’re earning trust.</p><h3>My Opinion: Useful AI Isn’t About Full Automation</h3><p>Through all these projects, I’ve learned that a truly useful AI application doesn’t have to automate everything. It should, instead, enhance understanding and enable collaboration between the human and the systems.</p><p>That’s where design plays a crucial role.</p><p>Even if the backend architecture is complex, with multi-agent workflows, retrieval systems, and vector databases, what users see is the interface. That’s their window into the system. And if that interface doesn’t clearly explain <em>what’s happening behind the scenes</em>, the magic stays hidden, and trust never forms.</p><h3>How can we start building trust via the UI?</h3><p>A transparent, user-friendly UI should let users <em>see and feel</em> the model’s reasoning process, not in a technical sense, but intuitively. Here’s what that looks like in practice:</p><ol><li>Visible lineage: Every AI-generated line should have a trace, a “show sources” button, evidence panel, or retrieval preview.</li><li>Interactive validation: Allow users to click and verify sections, re-run retrievals, or toggle between data views.</li><li>Step-by-step explainability: Use expandable logs that show how the system reached a conclusion, e.g., which documents it used, what transformations it applied.</li><li>Confidence cues: Display how confident the system is in its output, not just with percentages, but with natural language hints (“High confidence — source verified yesterday”).</li><li>Human-in-loop checkpoints: Give users control points where they can edit, comment, or approve outputs before they flow downstream.</li></ol><p>This way, even a non-technical user can understand <em>why</em> the model said what it said, and begin to trust the process, not just the result.</p><h3>Shifting the mindset from “Automation” to “Augmentation”</h3><p>When users can interactively explore how content was generated, when they can see the lineage, evidence, and decision path, the AI stops being a mysterious black box and becomes a collaborative assistant.</p><p>And that’s where adoption takes off. Because users don’t just consume outputs, they participate in them.</p><p>Ultimately, AI shouldn’t aim to replace judgment, but to strengthen it. The goal isn’t to hand over control, it’s to make control easier, faster, and smarter.</p><h3>✍️ Final Thought</h3><p>From my experience, the most successful GenAI applications are not the ones with the most sophisticated models, but the ones that make their sophistication <em>visible and comprehensible</em> to users.</p><p>No matter how complex the backend is, LangGraph pipelines, multi-agent systems, retrieval orchestration, or custom validators, if the front-end doesn’t make users feel included in the reasoning process, adoption will always lag behind innovation.</p><p>So, as builders and designers, our goal shouldn’t just be to make AI <em>perform</em> better. It should be to make it feel human, transparent, and trustworthy, one interactive interface at a time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=361454c451f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Production-Grade Agentic RAG System | Week-1]]></title>
            <link>https://medium.com/@anubhavm48/building-a-production-grade-agentic-rag-system-week-1-5b21a24449fe?source=rss-9b2585e2d20e------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b21a24449fe</guid>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <dc:creator><![CDATA[Anubhav Mishra]]></dc:creator>
            <pubDate>Thu, 02 Oct 2025 11:05:38 GMT</pubDate>
            <atom:updated>2025-10-02T11:06:10.317Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction:</h3><p>Retrieval-Augmented Generation (RAG) systems have become the backbone of modern AI assistants and chatbots. They promise contextual relevance, dynamic responses, and deep integration with proprietary data. Yet, despite their popularity, many RAG implementations fall short of delivering real-world value. Why?</p><p>Because most systems are rigid, they struggle with diverse query types, fail to adapt to user expectations, and often overlook the richness of structured data. Users expect generative AI to answer not just semantic questions, but also keyword-based lookups, filtered queries, aggregations, and more.</p><p>To meet these expectations, we need more than a basic RAG setup. We need an <strong>agentic RAG system</strong> : one that combines semantic intelligence with structured reasoning, powered by flexible vector databases and orchestrated workflows.</p><h3><strong>About the Project:</strong></h3><p>That’s why I’ve decided to build a <strong>production-grade agentic RAG application</strong>, end-to-end. This project will explore how to:</p><ul><li>Ingest structured data containing semantic information as well as keyword based fields from a PostgreSQL database.</li><li>Synchronize it with a vector database using CDC (Change Data Capture).</li><li>Embed semantic fields while preserving keyword metadata.</li><li>Build an agentic RAG workflow using LangGraph/Langchain.</li><li>Handle diverse user queries by using multi search strategies in tandem such as semantic search, keyword filters, and aggregation logic, etc.</li></ul><p>The goal is simple: <strong>generate real value from structured data</strong> and deliver it to users through a flexible, intelligent assistant.</p><p>This will be a <strong>week-by-week build series</strong>, where I incrementally develop each component, explain the rationale, apply best practices, and share learnings along the way.</p><p>PS: The code will be available after a while as a GitHub link.</p><h3>Week 1: Summary</h3><p>In the first week of development, we laid the foundation for a production-grade agentic RAG system by building a robust ingestion pipeline. We set up a Supabase-hosted PostgreSQL database with a real-world product dataset and enabled change tracking via a dedicated CDC table. On the vector side, we initialized a Qdrant cloud collection with semantic and keyword-aware indexing to support hybrid queries.</p><p>We developed a scheduled ingestion worker that reads changes from the source DB, embeds semantic fields using OpenAI models, and upserts enriched points into Qdrant. All secrets are securely managed via Infisical, ensuring cloud-ready deployment. With this pipeline in place, our system now supports real-time synchronization between structured data and vector search, a critical step toward enabling intelligent, flexible retrieval in the upcoming agentic RAG workflow.</p><p>Below, we will explore the high level flow of this development and details about the individual components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TbV60ZbP2pgToQGugcoE_g.png" /></figure><h3><strong>Dataset: Product Details in Supabase:</strong></h3><p>The foundation of this project is a real-world dataset of product details stored in a <strong>Supabase-hosted PostgreSQL instance</strong>. Each product record contains:</p><ul><li>id: Unique identifier</li><li>name: Product name</li><li>brand: Brand name</li><li>color: Available color</li><li>description: Free-text semantic field</li><li>price, category, and other structured attributes</li></ul><p>To enable CDC, I’ve created a <strong>dedicated change tracking table</strong> that logs inserts, updates, and deletes on the products table. This will allow us to detect changes and propagate them to our vector store.</p><h3><strong>Vector Store: Qdrant Cloud Instance:</strong></h3><p>With our source data in place, the next step is to define the target schema in <strong>Qdrant</strong>, a powerful vector database optimized for semantic search and metadata filtering.</p><p>I’ve created a Qdrant collection with:</p><ul><li><strong>Vector embeddings</strong> for semantic fields like description and name</li><li><strong>Payload metadata</strong> for keyword fields like brand, color, category</li><li><strong>Indexed fields</strong> to support filtering and faceted search</li></ul><p>This setup ensures that we can perform hybrid queries, combining semantic similarity with structured filters, which is essential for a robust RAG system.</p><p>A sample point from QDrant depicting information about a product.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CZifQd7YKsq9kN69lGjuLg.png" /></figure><h3><strong>Ingestion Worker: CDC + Embedding Pipeline</strong></h3><p>To keep Qdrant in sync with Supabase, I’ve built an <strong>ingestion worker</strong> that runs on a scheduled interval (via cron job). Its responsibilities:</p><p><strong>Connect to Supabase PostgreSQL</strong></p><ul><li>Read from the products table and the change tracking table</li><li>Detect new or updated rows</li></ul><p><strong>Embed semantic fields</strong></p><ul><li>Use OpenAI embeddings to vectorize description and name</li><li>Normalize and clean text before embedding</li></ul><p><strong>Prepare payload metadata</strong></p><ul><li>Extract keyword fields like brand, color, category</li><li>Attach them as payload for filtering in Qdrant</li></ul><p><strong>Upsert into Qdrant</strong></p><ul><li>Insert or update points in the Qdrant collection</li><li>Maintain idempotency and error handling</li></ul><p>This ingestion worker ensures that our vector store reflects the latest state of the source database, a critical requirement for real-time RAG applications.</p><h3><strong>Secrets Management: Infisical</strong></h3><p>All credentials like the Supabase connection strings, Qdrant API keys, embedding model secrets are securely managed using <strong>Infisical</strong>, a modern secrets management platform.</p><ul><li>Secrets are stored as environment variables</li><li>Access tokens are retrieved via Infisical’s Universal Auth flow</li><li>The ingestion worker loads secrets dynamically at runtime</li></ul><p>This setup ensures that our pipeline is secure, maintainable, and production-ready.</p><h3><strong>Models and Embeddings</strong></h3><p>We’ll be using <strong>OpenAI’s embedding models and LLMs </strong>to vectorize semantic fields and build the rag pipeline in the upcoming weeks. These embeddings will power similarity search in Qdrant and enable the agentic RAG system to retrieve relevant context for user queries.</p><h3>What’s Next:</h3><p>In the upcoming weeks, I’ll build the <strong>LangGraph-powered agentic RAG workflow</strong> and the auxilliary components that connects user queries to Qdrant, interprets intent, and generates responses using LLMs.</p><p>We’ll explore:</p><ul><li>Query parsing and routing</li><li>Semantic vs keyword vs aggregation queries</li><li>LangGraph node design and orchestration</li><li>Response generation and formatting</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b21a24449fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency-Aware Document Retrieval: Revolutionizing RAG with Graph Databases]]></title>
            <link>https://medium.com/@anubhavm48/dependency-aware-document-retrieval-revolutionizing-rag-with-graph-databases-8c8af96504f3?source=rss-9b2585e2d20e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c8af96504f3</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[graphdb]]></category>
            <dc:creator><![CDATA[Anubhav Mishra]]></dc:creator>
            <pubDate>Tue, 08 Jul 2025 10:07:49 GMT</pubDate>
            <atom:updated>2025-07-08T10:07:49.787Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction: The Hidden Connections Problem</h3><p>Traditional Retrieval-Augmented Generation (RAG) systems treat document chunks as isolated islands of information. When your technical manual states “performance metrics discussed in Section 4” or “detailed specifications in Appendix A,” these critical cross-references are lost in conventional chunking strategies. The result? Fragmented responses that miss the rich interconnections authors intentionally built into their documents.</p><p>Consider this scenario: A user asks about a product’s performance capabilities. A traditional RAG system might return the overview section mentioning “excellent performance” but completely miss the referenced section containing actual benchmarks, detailed metrics, and supporting evidence. This limitation becomes particularly problematic with technical documentation, research papers, legal documents, and any content where authors deliberately structure information across multiple sections.</p><h3>The Graph Database Solution</h3><p>Graph databases excel at capturing and traversing relationships — exactly what we need for dependency-aware document retrieval. By modeling documents as interconnected knowledge graphs, we can preserve the author’s intended information architecture and enable retrieval systems that automatically follow dependency chains to provide comprehensive, contextually rich responses.</p><h3>Core Concept: Section Dependencies in Action</h3><p>Let’s examine a practical example using a technical report about “Car A”:</p><blockquote><strong>Section 1 — Executive Summary:</strong></blockquote><p><em>“Multiple technical reviews about Car A were conducted (see Appendix)”</em></p><blockquote><strong>Section 2 — Performance Analysis:</strong></blockquote><p><em>“Performance benchmarks exceeded expectations, with detailed metrics in Section 4”</em></p><blockquote><strong>Section 3 — Safety Features:</strong></blockquote><p><em>“Safety ratings improved significantly over previous models as shown in the testing results”</em></p><p>Each reference creates a dependency relationship that should inform retrieval decisions. When someone asks about Car A’s performance, the system should automatically include both the main discussion AND the referenced benchmarks, creating a complete picture for the LLM to work with.</p><h3>System Architecture Overview:</h3><p>Our dependency-aware retrieval system consists of four main components:</p><blockquote><strong>Intelligent Document Parsing</strong>: Structure-aware chunking that preserves section boundaries</blockquote><blockquote><strong>LLM-Powered Dependency Detection</strong>: Automated extraction of cross-references and relationships</blockquote><blockquote><strong>Graph Database Construction</strong>: Building interconnected knowledge representations</blockquote><blockquote><strong>Hybrid Retrieval Engine</strong>: Combining vector similarity with graph traversal</blockquote><h3>Implementation Deep Dive:</h3><blockquote>Phase 1: Document Parsing and Chunking</blockquote><p>We start with structure-aware document parsing that respects natural section boundaries:</p><pre>from langchain.text_splitter import MarkdownHeaderTextSplitter<br>from langchain_openai import ChatOpenAI, OpenAIEmbeddings<br>import json<br><br>class SectionAwareDocumentParser:<br>    def __init__(self):<br>        # Define headers to split on - focusing on section headers<br>        self.headers_to_split_on = [<br>            (&quot;##&quot;, &quot;Section&quot;),  # Second-level headers for sections<br>        ]<br>        self.markdown_splitter = MarkdownHeaderTextSplitter(<br>            headers_to_split_on=self.headers_to_split_on,<br>            strip_headers=False<br>        )<br>    <br>    def parse_document(self, markdown_content: str, document_id: str) -&gt; List[Dict]:<br>        &quot;&quot;&quot;Parse markdown document into sections&quot;&quot;&quot;<br>        sections = self.markdown_splitter.split_text(markdown_content)<br>        <br>        parsed_sections = []<br>        for i, section in enumerate(sections):<br>            section_metadata = section.metadata.copy()<br>            section_title = section_metadata.get(&#39;Section&#39;, f&#39;Section {i+1}&#39;)<br>            <br>            section_data = {<br>                &#39;section_id&#39;: f&quot;{document_id}_section_{i+1}&quot;,<br>                &#39;document_id&#39;: document_id,<br>                &#39;title&#39;: section_title,<br>                &#39;content&#39;: section.page_content,<br>                &#39;index&#39;: i,<br>                &#39;metadata&#39;: section_metadata<br>            }<br>            parsed_sections.append(section_data)<br>        <br>        return parsed_sections</pre><blockquote>Phase 2: LLM-Powered Dependency Extraction</blockquote><p>The heart of our system lies in using LLMs to automatically detect dependencies between sections:</p><pre>class DependencyExtractor:<br>    def __init__(self, llm_model: str = &quot;gpt-4o-mini&quot;):<br>        self.llm = ChatOpenAI(<br>            model=llm_model,<br>            temperature=0,<br>            model_kwargs={&quot;response_format&quot;: {&quot;type&quot;: &quot;json_object&quot;}}<br>        )<br>        <br>        self.extraction_prompt = &quot;&quot;&quot;<br>Analyze this text section and identify any references to other parts of the document.<br>Look for phrases like &quot;see section X&quot;, &quot;detailed in appendix&quot;, &quot;as mentioned in&quot;, <br>&quot;refer to chapter&quot;, or implicit references to other content.<br><br>For each reference found, extract:<br>- Source section: [current section]<br>- Target section: [referenced section] <br>- Relationship type: [references/details/continues/supports]<br>- Context: [brief description of why it&#39;s referenced]<br><br>Return as JSON with this structure:<br>{<br>  &quot;dependencies&quot;: [...],<br>  &quot;entities&quot;: [...]<br>}<br><br>Text: {text}<br>&quot;&quot;&quot;<br><br>    async def extract_dependencies(self, section_data: Dict) -&gt; Dict:<br>        &quot;&quot;&quot;Extract dependencies and entities from a section&quot;&quot;&quot;<br>        formatted_prompt = self.extraction_prompt.format(<br>            text=section_data[&#39;content&#39;]<br>        )<br>        <br>        try:<br>            response = await self.llm.ainvoke(formatted_prompt)<br>            extracted_data = json.loads(response.content)<br>            <br>            return {<br>                &#39;section_id&#39;: section_data[&#39;section_id&#39;],<br>                &#39;dependencies&#39;: extracted_data.get(&#39;dependencies&#39;, []),<br>                &#39;entities&#39;: extracted_data.get(&#39;entities&#39;, [])<br>            }<br>        except Exception as e:<br>            print(f&quot;Error extracting from section {section_data[&#39;section_id&#39;]}: {e}&quot;)<br>            return {<br>                &#39;section_id&#39;: section_data[&#39;section_id&#39;],<br>                &#39;dependencies&#39;: [],<br>                &#39;entities&#39;: []<br>            }</pre><h3>Sample Input and Output</h3><p><strong>Input Section:</strong></p><pre>{<br>    &quot;section_id&quot;: &quot;car_a_report_section_1&quot;,<br>    &quot;document_id&quot;: &quot;car_a_report&quot;, <br>    &quot;title&quot;: &quot;Executive Summary&quot;,<br>    &quot;content&quot;: &quot;Car A represents a breakthrough in automotive engineering, combining advanced electric powertrain technology with innovative safety features. Multiple technical reviews about Car A were conducted (see Appendix). The vehicle achieved exceptional performance metrics across all testing categories.&quot;,<br>    &quot;index&quot;: 0,<br>    &quot;metadata&quot;: {&quot;level&quot;: 2, &quot;word_count&quot;: 45}<br>}</pre><p><strong>LLM Output:</strong></p><pre>{<br>    &quot;section_id&quot;: &quot;car_a_report_section_1&quot;,<br>    &quot;dependencies&quot;: [<br>        {<br>            &quot;source_section&quot;: &quot;Executive Summary&quot;,<br>            &quot;target_section&quot;: &quot;Appendix&quot;,<br>            &quot;relationship_type&quot;: &quot;references&quot;,<br>            &quot;context&quot;: &quot;Technical reviews provide supporting evidence for breakthrough claims&quot;,<br>            &quot;confidence&quot;: 0.95,<br>            &quot;reference_text&quot;: &quot;see Appendix&quot;<br>        }<br>    ],<br>    &quot;entities&quot;: [<br>        {&quot;name&quot;: &quot;Car A&quot;, &quot;type&quot;: &quot;Vehicle&quot;},<br>        {&quot;name&quot;: &quot;electric powertrain technology&quot;, &quot;type&quot;: &quot;Technology&quot;},<br>        {&quot;name&quot;: &quot;safety features&quot;, &quot;type&quot;: &quot;Feature&quot;},<br>        {&quot;name&quot;: &quot;performance metrics&quot;, &quot;type&quot;: &quot;Metric&quot;}<br>    ]<br>}</pre><blockquote>Phase 3: Dependency Mapping and Resolution</blockquote><p>After extracting dependencies from all sections, we consolidate and resolve them into a structured dependency map:</p><pre>class DependencyResolver:<br>    def __init__(self):<br>        self.section_mapping = {}<br>    <br>    def resolve_dependencies(self, all_sections: List[Dict], <br>                           extracted_dependencies: List[Dict]) -&gt; Dict:<br>        &quot;&quot;&quot;Resolve section references to actual section IDs&quot;&quot;&quot;<br>        <br>        # Build section mapping for resolution<br>        for section in all_sections:<br>            self.section_mapping[section[&#39;title&#39;].lower()] = section[&#39;section_id&#39;]<br>            # Also map common variations<br>            if &#39;appendix&#39; in section[&#39;title&#39;].lower():<br>                self.section_mapping[&#39;appendix&#39;] = section[&#39;section_id&#39;]<br>        <br>        resolved_dependencies = []<br>        <br>        for dep_result in extracted_dependencies:<br>            for dependency in dep_result[&#39;dependencies&#39;]:<br>                target_section = dependency[&#39;target_section&#39;].lower()<br>                <br>                # Resolve target section to actual section ID<br>                target_id = self._resolve_section_reference(target_section)<br>                <br>                if target_id:<br>                    resolved_dep = {<br>                        &quot;source_id&quot;: dep_result[&#39;section_id&#39;],<br>                        &quot;target_id&quot;: target_id,<br>                        &quot;relationship_type&quot;: dependency[&#39;relationship_type&#39;].upper(),<br>                        &quot;context&quot;: dependency[&#39;context&#39;],<br>                        &quot;confidence&quot;: dependency.get(&#39;confidence&#39;, 0.8)<br>                    }<br>                    resolved_dependencies.append(resolved_dep)<br>        <br>        return {&quot;resolved_dependencies&quot;: resolved_dependencies}<br>    <br>    def _resolve_section_reference(self, reference: str) -&gt; str:<br>        &quot;&quot;&quot;Resolve section reference to actual section ID&quot;&quot;&quot;<br>        # Handle various reference patterns<br>        for section_name, section_id in self.section_mapping.items():<br>            if section_name in reference or reference in section_name:<br>                return section_id<br>        return None</pre><p><strong>Sample Consolidated Dependency Map:</strong></p><pre>{<br>  &quot;resolved_dependencies&quot;: [<br>    {<br>      &quot;source_id&quot;: &quot;car_a_report_section_1&quot;,<br>      &quot;target_id&quot;: &quot;car_a_report_section_5&quot;,<br>      &quot;relationship_type&quot;: &quot;REFERENCES&quot;,<br>      &quot;context&quot;: &quot;Technical reviews provide supporting evidence&quot;,<br>      &quot;confidence&quot;: 0.95<br>    },<br>    {<br>      &quot;source_id&quot;: &quot;car_a_report_section_2&quot;,<br>      &quot;target_id&quot;: &quot;car_a_report_section_4&quot;,<br>      &quot;relationship_type&quot;: &quot;REFERENCES&quot;,<br>      &quot;context&quot;: &quot;Detailed metrics provide quantitative support&quot;,<br>      &quot;confidence&quot;: 0.98<br>    }<br>  ]<br>}</pre><blockquote>Phase 4: Knowledge Graph Construction</blockquote><p>Now we build the complete knowledge graph with multiple layers:</p><pre>from neo4j import GraphDatabase<br><br>class KnowledgeGraphBuilder:<br>    def __init__(self, neo4j_uri: str, username: str, password: str):<br>        self.driver = GraphDatabase.driver(neo4j_uri, auth=(username, password))<br>        self.embedder = OpenAIEmbeddings(model=&quot;text-embedding-3-small&quot;)<br>    <br>    def build_knowledge_graph(self, document_id: str, sections: List[Dict], <br>                            dependencies: Dict, entities: List[Dict]):<br>        &quot;&quot;&quot;Build complete knowledge graph in Neo4j&quot;&quot;&quot;<br>        <br>        with self.driver.session() as session:<br>            # Create Document Layer<br>            self._create_document_node(session, document_id, len(sections))<br>            <br>            # Create Section Layer with embeddings<br>            for section in sections:<br>                self._create_section_node(session, section)<br>            <br>            # Create Entity Layer<br>            for entity_data in entities:<br>                self._create_entity_nodes(session, entity_data)<br>            <br>            # Create Dependency Layer<br>            self._create_dependency_relationships(session, dependencies)<br>    <br>    def _create_section_node(self, session, section: Dict):<br>        &quot;&quot;&quot;Create section node with embedding&quot;&quot;&quot;<br>        # Generate embedding for section content<br>        embedding = self.embedder.embed_query(section[&#39;content&#39;])<br>        <br>        session.run(&quot;&quot;&quot;<br>            MERGE (s:Section {id: $section_id})<br>            SET s.title = $title,<br>                s.content = $content,<br>                s.index = $index,<br>                s.embedding = $embedding,<br>                s.word_count = $word_count<br>            WITH s<br>            MATCH (d:Document {id: $doc_id})<br>            MERGE (s)-[:FROM_DOCUMENT]-&gt;(d)<br>        &quot;&quot;&quot;, <br>        section_id=section[&#39;section_id&#39;],<br>        title=section[&#39;title&#39;],<br>        content=section[&#39;content&#39;],<br>        index=section[&#39;index&#39;],<br>        embedding=embedding,<br>        word_count=len(section[&#39;content&#39;].split()),<br>        doc_id=section[&#39;document_id&#39;])<br>    <br>    def _create_dependency_relationships(self, session, dependencies: Dict):<br>        &quot;&quot;&quot;Create cross-section dependency relationships&quot;&quot;&quot;<br>        for dep in dependencies[&#39;resolved_dependencies&#39;]:<br>            session.run(&quot;&quot;&quot;<br>                MATCH (source:Section {id: $source_id})<br>                MATCH (target:Section {id: $target_id})<br>                MERGE (source)-[r:REFERENCES_SECTION]-&gt;(target)<br>                SET r.context = $context,<br>                    r.confidence = $confidence,<br>                    r.relationship_type = $rel_type<br>            &quot;&quot;&quot;,<br>            source_id=dep[&#39;source_id&#39;],<br>            target_id=dep[&#39;target_id&#39;],<br>            context=dep[&#39;context&#39;],<br>            confidence=dep[&#39;confidence&#39;],<br>            rel_type=dep[&#39;relationship_type&#39;])</pre><h4>Knowledge Graph Layers</h4><p>Our knowledge graph consists of four interconnected layers:</p><p><strong>1. Document Layer</strong>: Contains each document as a root node with metadata<br> <strong>2. Section Layer</strong>: Individual sections (chunks) with embeddings and relationships<br> <strong>3. Entity Layer</strong>: Extracted entities connected to their source sections<br> <strong>4. Dependency Layer</strong>: Cross-section relationships like REFERENCES, SUPPORTS, ELABORATES_ON</p><blockquote>Phase 5: Hybrid Retrieval Engine</blockquote><p>The retrieval system combines the best of both vector similarity and graph traversal:</p><pre>class HybridDependencyRetriever:<br>    def __init__(self, neo4j_driver, embedder):<br>        self.driver = neo4j_driver<br>        self.embedder = embedder<br>    <br>    async def retrieve_with_dependencies(self, query: str, top_k: int = 3) -&gt; Dict:<br>        &quot;&quot;&quot;Retrieve sections using hybrid approach&quot;&quot;&quot;<br>        <br>        # Phase 1: Vector similarity search<br>        query_embedding = await self.embedder.aembed_query(query)<br>        primary_sections = self._vector_search(query_embedding, top_k)<br>        <br>        # Phase 2: Graph traversal for dependencies<br>        comprehensive_context = []<br>        <br>        for section in primary_sections:<br>            section_context = {<br>                &#39;primary_section&#39;: section,<br>                &#39;dependencies&#39;: self._get_dependencies(section[&#39;section_id&#39;]),<br>                &#39;supporting_sections&#39;: self._get_supporting_sections(section[&#39;section_id&#39;])<br>            }<br>            comprehensive_context.append(section_context)<br>        <br>        return self._format_retrieval_context(comprehensive_context)<br>    <br>    def _vector_search(self, query_embedding: List[float], top_k: int) -&gt; List[Dict]:<br>        &quot;&quot;&quot;Perform vector similarity search on sections&quot;&quot;&quot;<br>        with self.driver.session() as session:<br>            result = session.run(&quot;&quot;&quot;<br>                CALL db.index.vector.queryNodes(&#39;section_embeddings&#39;, $k, $query_vector)<br>                YIELD node AS section, score<br>                RETURN section.id AS section_id, section.title AS title,<br>                       section.content AS content, score<br>                ORDER BY score DESC<br>            &quot;&quot;&quot;, k=top_k, query_vector=query_embedding)<br>            <br>            return [dict(record) for record in result]<br>    <br>    def _get_dependencies(self, section_id: str) -&gt; List[Dict]:<br>        &quot;&quot;&quot;Get sections referenced by the current section&quot;&quot;&quot;<br>        with self.driver.session() as session:<br>            result = session.run(&quot;&quot;&quot;<br>                MATCH (source:Section {id: $section_id})-[r:REFERENCES_SECTION]-&gt;(target:Section)<br>                RETURN target.id AS section_id, target.title AS title,<br>                       target.content AS content, r.context AS context,<br>                       r.confidence AS confidence<br>                ORDER BY r.confidence DESC<br>            &quot;&quot;&quot;, section_id=section_id)<br>            <br>            return [dict(record) for record in result]<br>    <br>    def _get_supporting_sections(self, section_id: str) -&gt; List[Dict]:<br>        &quot;&quot;&quot;Get sections that reference the current section&quot;&quot;&quot;<br>        with self.driver.session() as session:<br>            result = session.run(&quot;&quot;&quot;<br>                MATCH (source:Section)-[r:REFERENCES_SECTION]-&gt;(target:Section {id: $section_id})<br>                RETURN source.id AS section_id, source.title AS title,<br>                       source.content AS content, r.context AS context<br>            &quot;&quot;&quot;, section_id=section_id)<br>            <br>            return [dict(record) for record in result]</pre><h3>Complete Retrieval Workflow Illustration:</h3><p>Let’s trace through a complete example:</p><p><strong>User Query</strong>: “What are Car A’s performance capabilities?”</p><blockquote>Step 1: Vector Search</blockquote><p>The system performs similarity search and identifies the primary match:</p><p><strong>Primary Section: Performance Analysis</strong></p><p><em>“Performance benchmarks exceeded expectations, with detailed metrics in Section 4…”</em></p><blockquote>Step 2: Dependency Traversal</blockquote><p>The system follows the REFERENCES_SECTION relationship and automatically includes:</p><p><strong>Referenced Section: Detailed Performance Metrics</strong></p><p><em>“0–60 mph acceleration: 3.2 seconds, Top speed: 155 mph, Range: 400 miles…”</em></p><blockquote>Step 3: Supporting Context Discovery</blockquote><p>The system also finds supporting sections:</p><p><strong>Supporting Context: Executive Summary</strong></p><p><em>“Car A represents a breakthrough in automotive engineering…”</em></p><blockquote>Step 4: Context Assembly</blockquote><pre>def _format_retrieval_context(self, comprehensive_context: List[Dict]) -&gt; str:<br>    &quot;&quot;&quot;Format comprehensive context for LLM&quot;&quot;&quot;<br>    context_parts = []<br>    <br>    for section_group in comprehensive_context:<br>        primary = section_group[&#39;primary_section&#39;]<br>        context_parts.append(f&quot;## Primary Section: {primary[&#39;title&#39;]}&quot;)<br>        context_parts.append(primary[&#39;content&#39;])<br>        <br>        # Add referenced sections<br>        for dep in section_group[&#39;dependencies&#39;]:<br>            context_parts.append(f&quot;## Referenced Section: {dep[&#39;title&#39;]}&quot;)<br>            context_parts.append(f&quot;Context: {dep[&#39;context&#39;]}&quot;)<br>            context_parts.append(dep[&#39;content&#39;])<br>        <br>        # Add supporting sections<br>        for support in section_group[&#39;supporting_sections&#39;]:<br>            context_parts.append(f&quot;## Supporting Context: {support[&#39;title&#39;]}&quot;)<br>            context_parts.append(support[&#39;content&#39;])<br>        <br>        context_parts.append(&quot;---&quot;)<br>    <br>    return &quot;\n\n&quot;.join(context_parts)</pre><p>This comprehensive approach ensures that queries about Car A’s performance automatically include both the primary discussion alongside all referenced sections, providing complete and contextually rich responses through intelligent dependency-aware retrieval.</p><h3>Advanced Features and Extensions:</h3><blockquote>Multi-Hop Dependency Traversal</blockquote><p>The system can follow dependency chains multiple levels deep, discovering related content that might be 2–3 relationships away from the initial query match.</p><blockquote>Semantic Relationship Detection</blockquote><p>Beyond explicit references, the system can identify implicit relationships through:</p><ul><li>Shared entity mentions</li><li>Thematic similarity</li><li>Continuation patterns</li><li>Supporting evidence relationships</li></ul><blockquote>Dynamic Confidence Scoring</blockquote><p>Each dependency relationship includes confidence scores that help prioritize which sections to include in the final context assembly.</p><h3>Benefits and Impact:</h3><blockquote>Enhanced Answer Quality</blockquote><p>By following dependency chains, responses become more complete and accurate. Users receive comprehensive information without needing to manually discover and read related sections.</p><blockquote>Reduced Information Fragmentation</blockquote><p>Traditional RAG often provides partial answers because relevant information is scattered across sections. Graph-based retrieval assembles complete pictures by following documented relationships.</p><blockquote>Improved Source Attribution</blockquote><p>The system provides clear trails showing how different pieces of information connect, making it easier to verify answers and understand the reasoning behind responses.</p><blockquote>Scalable Complexity</blockquote><p>As documents grow larger and more complex, the graph structure scales naturally. New sections integrate into existing relationship networks without requiring system redesign.</p><h3>Implementation Considerations:</h3><blockquote>Performance Optimization</blockquote><p>Graph traversal adds computational overhead, but targeted indexing and caching strategies maintain responsive performance. Pre-computing common dependency paths and using efficient graph algorithms ensures real-time query response.</p><blockquote>Quality Control</blockquote><p>LLM-based dependency detection requires validation mechanisms. Implementing confidence scoring and human review workflows for critical relationships ensures accuracy, especially in specialized domains.</p><blockquote>Maintenance and Updates</blockquote><p>As documents evolve, the system automatically updates dependency relationships. New sections are analyzed for connections to existing content, maintaining graph coherence over time.</p><h3>Conclusion:</h3><p>Effectively managing highly interconnected documents is both a challenge and an opportunity. The approach outlined here offers a promising foundation for handling documents as they exist in reality — richly linked, context-dependent, and often non-linear in structure. While the current methodology is intentionally basic, it serves as a robust baseline from which more advanced solutions can be developed.</p><p>A key to designing reliable workflows is understanding the logic, intent, and value behind the documents and the specific goals of the application. Generic solutions rarely fit all cases, but targeted workflows can effectively address the most important and frequent challenges.</p><p>AI development in this space benefits most from collaboration across business functions. When domain experts, technical teams, and stakeholders work together, the resulting solutions are more likely to deliver real value and meet practical needs. Focusing on purpose-driven design and teamwork ensures that document intelligence systems are both effective and relevant.</p><p>This dependency-aware approach transforms document retrieval from simple similarity matching into intelligent knowledge assembly, creating RAG systems that truly understand document structure and relationships. As we continue to push the boundaries of what’s possible with AI-powered document understanding, graph databases will play an increasingly crucial role in bridging the gap between how humans structure information and how machines can intelligently retrieve and reason about it.</p><p>Document problems will keep haunting us, but it’s really important to know what weapons we have at our disposal. This graph-based approach is one powerful weapon in our arsenal for taming the complexity of interconnected document ecosystems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c8af96504f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Langchain Internals: Diving into PydanticOutputParser]]></title>
            <link>https://medium.com/@anubhavm48/mastering-langchain-internals-diving-into-pydanticoutputparser-9445c628bff0?source=rss-9b2585e2d20e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9445c628bff0</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[llm-applications]]></category>
            <dc:creator><![CDATA[Anubhav Mishra]]></dc:creator>
            <pubDate>Mon, 23 Jun 2025 18:46:57 GMT</pubDate>
            <atom:updated>2025-06-23T18:46:57.362Z</atom:updated>
            <content:encoded><![CDATA[<p>LangChain is catching fire these days.</p><p>With more and more AI applications moving into production, it’s becoming the go-to framework for developers building with LLMs.</p><p>But here’s the catch, if you don’t understand the internals, you’ll eventually hit a wall. Especially when things break (and they will), surface-level knowledge isn’t enough. If you want to build reliable, production-grade applications, you need to know what’s happening under the hood.</p><p>So today, let’s take a deep dive into one such module that quietly does a lot of heavy lifting:</p><h3><strong>PydanticOutputParser:</strong></h3><p>This module is all about one powerful idea — converting the messy, unstructured output of an LLM into clean, validated Python objects using Pydantic.</p><p><strong>Why does that matter?</strong></p><p>Because most enterprise applications downstream expect structure, type safety, and consistency. You can’t afford a rogue comma to crash a workflow.</p><p><strong>Here’s what PydanticOutputParser actually does:</strong></p><p>It takes a Pydantic model and:</p><ol><li>Extracts its schema and injects it into the prompt.</li><li>Parses the LLM output and validates it against the schema.</li><li>Returns a fully validated, strongly-typed Python object.</li></ol><p><strong>Here’s what that looks like step-by-step:</strong></p><p><strong>Step 1: Define your schema using Pydantic’s BaseModel</strong></p><pre>class Joke(BaseModel):<br>setup: str = Field(description=&quot;Joke setup&quot;)<br>punchline: str</pre><p>This gets translated into a JSON schema like:</p><pre>{<br>&quot;properties&quot;: {<br>&quot;setup&quot;: { &quot;type&quot;: &quot;string&quot; },<br>&quot;punchline&quot;: { &quot;type&quot;: &quot;string&quot; }<br>},<br>&quot;required&quot;: [&quot;setup&quot;, &quot;punchline&quot;]<br>}</pre><p><strong>Step 2: Inject format instructions into the prompt</strong></p><pre>parser = PydanticOutputParser(pydantic_object=Joke)<br>prompt = PromptTemplate(<br>template=&quot;Tell a joke.\n{format_instructions}\n&quot;,<br>partial_variables={&quot;format_instructions&quot;: parser.get_format_instructions()}<br>)</pre><p><strong>Let’s see how these format instructions impact the prompt:</strong></p><p><strong>Prompt Before injection:</strong></p><pre>Tell a joke.</pre><p><strong>Prompt After injection:</strong></p><pre>Tell me a joke.<br>The output should be formatted as a JSON instance that conforms to the JSON schema below.<br><br>As an example, for the schema {&quot;properties&quot;: {&quot;foo&quot;: {&quot;title&quot;: &quot;Foo&quot;, &quot;description&quot;: &quot;a list of strings&quot;, &quot;type&quot;: &quot;array&quot;, &quot;items&quot;: {&quot;type&quot;: &quot;string&quot;}}}, &quot;required&quot;: [&quot;foo&quot;]}<br>the object {&quot;foo&quot;: [&quot;bar&quot;, &quot;baz&quot;]} is a well-formatted instance of the schema. The object {&quot;properties&quot;: {&quot;foo&quot;: [&quot;bar&quot;, &quot;baz&quot;]}} is not well-formatted.<br><br>Here is the output schema:<br>{&quot;properties&quot;: {&quot;setup&quot;: {&quot;title&quot;: &quot;Setup&quot;, &quot;description&quot;: &quot;question to set up a joke&quot;, &quot;type&quot;: &quot;string&quot;}, &quot;punchline&quot;: {&quot;title&quot;: &quot;Punchline&quot;, &quot;description&quot;: &quot;answer to resolve the joke&quot;, &quot;type&quot;: &quot;string&quot;}}, &quot;required&quot;: [&quot;setup&quot;, &quot;punchline&quot;]}</pre><p><strong>Step 3: LLM generates output</strong></p><p>The LLM tries its best to follow the pattern and returns something like:</p><pre>{<br>&quot;setup&quot;: &quot;Why did the developer go broke?&quot;,<br>&quot;punchline&quot;: &quot;Because he used up all his cache.&quot;<br>}</pre><p><strong>Step 4: Validation and parsing</strong></p><p>The parser:</p><ul><li>Extracts the JSON from the text</li><li>Parses it into a Pydantic object</li><li>Applies any custom validators (e.g., string format, regex, etc.)</li><li>Throws a OutputParserException if something doesn’t match</li></ul><h3>Why does this approach work?</h3><p>Because LLMs are pattern learners. When you give them a structure via in-context learning or what we call few-shot learning, they tend to follow it surprisingly well even without fine-tuning. And if they miss the mark, Pydantic catches the errors early.</p><h3>Why you should care?</h3><p><strong>Pros:</strong></p><ul><li>Type-safe structured output</li><li>Plug-and-play with APIs, DBs</li><li>Custom validation via Pydantic</li><li>Easy to debug, extend, and test</li></ul><p><strong>Cons:</strong></p><ul><li>Complex schemas may confuse smaller LLMs</li><li>Retry logic may be needed for malformed outputs</li><li>Doesn’t support streaming partial output</li><li>Requires high-capacity models (e.g., GPT-4o)</li></ul><h3>Bottom Line:</h3><p>LangChain has many parsers such as JSONOutputParser, XMLOutputParser, OutputFixingParser, OpenAI’s native function calling which can be simply used by importing them and plugging them in, but if you’re building robust LLM apps that depend on clean, validated data, it’s really important to understand what goes on under the hood of these modules.</p><p>So, when the backend fails silently or your pipeline gets tripped by a rogue string field, you’ll be glad you understood where the rat’s hiding.</p><p>#LangChain #LLM #AIapplications #BackendDebugging #StructuredOutput #Pydantic #GenerativeAI #PromptEngineering</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9445c628bff0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When (and When Not) to use Agents]]></title>
            <link>https://medium.com/@anubhavm48/when-and-when-not-to-use-agents-6bb8f507b4ca?source=rss-9b2585e2d20e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bb8f507b4ca</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[generative-ai-development]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software]]></category>
            <dc:creator><![CDATA[Anubhav Mishra]]></dc:creator>
            <pubDate>Sun, 22 Jun 2025 08:14:54 GMT</pubDate>
            <atom:updated>2025-06-22T08:14:54.324Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*2IIGVLwZmtV03sP-w9nrmg.jpeg" /></figure><h3><strong>Background:</strong></h3><p>Following up on the gazillion discussions around building and leveraging agents to generate tangible value, it’s pretty imperative to discuss When (and When Not) to Use Agents in LLM Applications.</p><p>As more teams explore the power of large language models (LLMs), the idea of building agentic systems, where LLMs reason, plan, and act feels exciting, sellable, and futuristic. But not every problem needs an agent.<br>Here’s a simple, structured take on when agents make sense and when they don’t.</p><h3><strong>When to Use Agents:</strong></h3><p><strong>1. The task at hand is open-ended or ill-defined.<br></strong>If your use case can’t be easily broken into predictable steps or decision trees, agents help by choosing what to do next based on the context.</p><p><strong>2. Flexibility and adaptability are critical.</strong><br>Agents shine when they need to make choices dynamically, selecting tools, invoking APIs, or reasoning through ambiguity in real time.</p><p><strong>3. You’re solving problems at scale where workflows are too rigid.</strong><br>Traditional pipelines might not cut it when you have hundreds of slightly different tasks. Agents provide generalizability without needing to rewrite logic each time.</p><p><strong>4. The payoff justifies the cost.</strong><br>Yes, agents introduce latency and resource overhead. But if that results in significantly better outcomes, like deeper insights, automation of high-value workflows, or reduced human supervision, they’re worth it.</p><h3><strong>When Not to Use Agents:</strong></h3><p><strong>1. The task is well-defined and repeatable.</strong><br>If the input and expected output follow clear, rule-based patterns, simple retrieval-augmented generation (RAG) or even a single prompt with in-context examples can outperform a full-blown agent, with lower cost and latency.</p><p><strong>2. You need deterministic and consistent outputs.</strong><br>Agents usually rely on LLM-driven decision-making, which can sometimes introduce unpredictability. For high-stakes or regulatory contexts (which make up a large portion of enterprise use cases), consider using structured workflows or templates instead.</p><p><strong>3. You’re early in product development.</strong><br>Start simple. Nail the problem. Only introduce agentic logic when you need more power or automation. Complexity adds tech debt.</p><p><strong>4. You’re optimizing for performance or cost at scale.</strong><br>Agents can get expensive. Unless your task truly needs dynamic planning or tool-use, stick with more efficient patterns.</p><h3>Bottom Line:</h3><p>Not every problem is an agent problem. There are numerous successful use cases generating tangible business value using simple, well-defined, and structured workflows: retrieval, good prompting, and clear evaluation loops.<br>But when your app needs real-time decisions, multi-step reasoning, and dynamic tool use — agents might be the leap worth taking.</p><p>So, bottom line: <strong>build thoughtfully.</strong></p><p>Refer to Anthropic’s guide on building effective agents to hear what experts from Anthropic have to say about building agents:<br>🔗 <a href="https://lnkd.in/gjRsdgtp">https://lnkd.in/gjRsdgtp</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bb8f507b4ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical Introduction to LLM tools in Lang chain.]]></title>
            <link>https://medium.com/@anubhavm48/practical-introduction-to-llm-tools-in-lang-chain-bb6b8b42d8b6?source=rss-9b2585e2d20e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb6b8b42d8b6</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Anubhav Mishra]]></dc:creator>
            <pubDate>Thu, 10 Oct 2024 17:58:40 GMT</pubDate>
            <atom:updated>2024-10-10T17:58:40.996Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tool — calling:</h3><p>Tool calling allows a <a href="https://python.langchain.com/docs/concepts/#chat-models">chat model</a> to respond to a given prompt by generating output that matches a user-defined schema.</p><p>But not all chat models are fine-tuned for tool calling. Examples of model which are capable of tool calling efficiently is OpenAI, Anthropic’s Claude, etc..</p><p>Some models are capable of <a href="https://python.langchain.com/docs/concepts/#functiontool-calling"><strong>tool calling</strong></a> — generating arguments that conform to a specific user-provided schema.</p><h3>What’s tool calling?</h3><p>Tool calling sounds like the model is actually doing something, but it’s not. It’s just suggesting what to do. The model only comes up with the information (or arguments) that could be used to run a tool. It doesn’t actually run the tool itself. It’s up to the user to decide whether to use this information to run the tool or not.</p><p>Sometimes, you might not want to run a tool at all. For example, if you’re trying to get specific information from a chunk of text, you could give the model an “extraction tool”. The model would then give you the information in the format you want, without actually running any real tool. In this case, the information the model gives you is your final result. You don’t need to do anything else with it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HFYuPFpCZtd2V-L0B4EAnA.png" /><figcaption>Tool calls in a nutshell</figcaption></figure><p>Let’s see the general flow of a tool call :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*YjytlQqCdl4vAj445uaZfg.png" /><figcaption>Workflow with tools</figcaption></figure><p>Process basically has these steps:</p><ol><li>User asks a query to an LLM to which a set of tools are binded. (Might be one tool or more)</li><li><strong>Tool Calling</strong>This LLM decides on what tool to call and generates the argument for this tool as per the argument schema of that tool.</li><li>This tool call is then used to invoke the tool and get an output out of it in the form of toolmessages.</li><li>This output is then again fed back to the LLM and the LLM decides on whether to covert this toolmessage to a proper natural language response or call tools again for a better response.</li></ol><h3>Binding tools to an LLM:</h3><p>The interface which we mainly use to deal with tool calling in Langchain is Chatmodel.bind_tools() ChatModel.bind_tools(): a method for specifying which tools are available for a model to call. This method accepts <a href="https://python.langchain.com/docs/concepts/#tools">LangChain tools</a> as well as <a href="https://pydantic.dev/">Pydantic</a> objects.</p><p>When we create a tool, we define the arguments, arguments schema and description of that tool. When we bind a tool to an LLM the arguments schema and the tool description info is passed to the LLM in the form of type hints and docstrings respectively.</p><p>Let’s see an example of it:</p><p>We are defining two tools, one for addition and one for multiplication.</p><p>First we are defining the argument schemas for both.</p><pre>from pydantic import BaseModel, Field`</pre><pre>class add(BaseModel):<br>&quot;&quot;&quot;Add two integers.&quot;&quot;&quot;`<br>	a: int = Field(..., description=&quot;First integer&quot;)<br>	b: int = Field(..., description=&quot;Second integer&quot;)</pre><pre>class multiply(BaseModel):<br>&quot;&quot;&quot;Multiply two integers.&quot;&quot;&quot;<br>a: int = Field(..., description=&quot;First integer&quot;)<br>b: int = Field(..., description=&quot;Second integer&quot;)</pre><pre># Defining the tool functionalities<br>from langchain_core.tools import tool</pre><pre>@tool<br>def add(a: int, b: int) -&gt; int:<br>    &quot;&quot;&quot;Adds a and b.&quot;&quot;&quot;<br>    return a + b</pre><pre>@tool<br>def multiply(a: int, b: int) -&gt; int:<br>    &quot;&quot;&quot;Multiplies a and b.&quot;&quot;&quot;<br>    return a * b</pre><pre># Defining the tool list<br>tools = [add,multiply]</pre><p>Now, if we bind both these to an LLM, the LLM based on the query provided by the user will select a tool out of these and generate a response in the structured schema pertaining to that tool.</p><pre>from langchain_openai import ChatOpenAI</pre><pre>llm = ChatOpenAI(model=&quot;gpt-4o-mini&quot;)</pre><pre># Binding the tools to the LLM<br>llm_with_tools = llm.bind_tools(tools)</pre><pre>query = &quot;What is 3 * 12?&quot;</pre><pre>llm_with_tools.invoke(query)</pre><p>Here, the output would be:</p><pre>AIMessage(content=&#39;&#39;, <br>additional_kwargs={&#39;tool_calls&#39;: [{&#39;id&#39;: &#39;call_iXj4DiW1p7WLjTAQMRO0jxMs&#39;, <br>&#39;function&#39;: {&#39;arguments&#39;: &#39;{&quot;a&quot;:3,&quot;b&quot;:12}&#39;, &#39;name&#39;: &#39;multiply&#39;}, &#39;type&#39;: &#39;function&#39;}],<br> &#39;refusal&#39;: None},<br>  response_metadata={&#39;token_usage&#39;: {&#39;completion_tokens&#39;: 17, &#39;prompt_tokens&#39;: 80,<br>   &#39;total_tokens&#39;: 97}, &#39;model_name&#39;: &#39;gpt-4o-mini-2024-07-18&#39;, <br>   &#39;system_fingerprint&#39;: &#39;fp_483d39d857&#39;, &#39;finish_reason&#39;: &#39;tool_calls&#39;, <br>   &#39;logprobs&#39;: None}, id=&#39;run-0b620986-3f62-4df7-9ba3-4595089f9ad4-0&#39;,<br>    tool_calls=[{&#39;name&#39;: &#39;multiply&#39;, &#39;args&#39;: {&#39;a&#39;: 3, &#39;b&#39;: 12},<br>     &#39;id&#39;: &#39;call_iXj4DiW1p7WLjTAQMRO0jxMs&#39;, &#39;type&#39;: &#39;tool_call&#39;}], <br>     usage_metadata={&#39;input_tokens&#39;: 80, &#39;output_tokens&#39;: 17, &#39;total_tokens&#39;: 97})</pre><p>In the output we can see that instead of producing a generic LLM response it has produced a tool call. In the additional_kwargs metadata , the tool calls is mentioned and it has converted the user query into the argument format &#39;arguments&#39;: &#39;{&quot;a&quot;:3,&quot;b&quot;:12}&#39; and has selected the multiply tool to be called: &#39;name&#39;: &#39;multiply&#39;.</p><h4>Now, one interesting fact is that the LLM might not choose to call any tool if required. In that case, the response would be a generic LLM response. That’s completely optimal because it’s possible that the user query is not relevant to any of the tools in the tool list. But, we might change this behaviour by adding args to the bind_tools() method.</h4><blockquote>How to make an LLM forcefully call a tool:</blockquote><p><a href="https://python.langchain.com/docs/how_to/tool_choice/">https://python.langchain.com/docs/how_to/tool_choice/</a></p><h3>Tool calls attribute</h3><p>Whenever we use an LLM for a tool call, the tool calls can be accessed through the .toolcalls attribute.</p><p>Its a dictionary that include the called tool name and the arguments for it.</p><p>Let’s see a demonstration below:</p><pre>query = &quot;What is 3 * 12? Also, what is 11 + 49?&quot;<br>llm_with_tools.invoke(query).tool_calls</pre><p>Output:</p><pre>[{&#39;name&#39;: &#39;multiply&#39;,<br>&#39;args&#39;: {&#39;a&#39;: 3, &#39;b&#39;: 12},<br>&#39;id&#39;: &#39;call_1fyhJAbJHuKQe6n0PacubGsL&#39;,<br>&#39;type&#39;: &#39;tool_call&#39;},<br>{&#39;name&#39;: &#39;add&#39;,<br>&#39;args&#39;: {&#39;a&#39;: 11, &#39;b&#39;: 49},<br>&#39;id&#39;: &#39;call_fc2jVkKzwuPWyU7kS9qn1hyG&#39;,<br>&#39;type&#39;: &#39;tool_call&#39;}]</pre><h3>Passing tool outputs back to LLMs:</h3><p>Now, let’s see this thing roll in Python!</p><pre># creating the llm runnable<br>from langchain_openai import ChatOpenAI<br>llm = ChatOpenAI(model=&quot;gpt-3.5-turbo&quot;)</pre><pre># Defining the add and multiply tools<br>from langchain_core.tools import tool</pre><pre>@tool<br>def add(a: int, b: int) -&gt; int:<br>    &quot;&quot;&quot;Adds a and b.&quot;&quot;&quot;<br>    return a + b</pre><pre>@tool<br>def multiply(a: int, b: int) -&gt; int:<br>    &quot;&quot;&quot;Multiplies a and b.&quot;&quot;&quot;<br>    return a * b<br>    <br># Creating the tool list<br>tools = [add, multiply]</pre><pre># Binding the tools to the llm<br>llm_with_tools = llm.bind_tools(tools)</pre><p>Now, we have the llm thing set-up for action. Now, when we call it, it’ll respond with a tool call. (i,e converting the user query to arguments). We’ll add this response to a list of messages that we can treat as conversation history that we can again feed to the LLM. (Refer to the logic diagram above)</p><pre>from langchain_core.messages import HumanMessage</pre><pre>query = &quot;What is 3 * 12? Also, what is 11 + 49?&quot;</pre><pre># Initiating the messages list with the user query as the first element<br>messages = [HumanMessage(query)]</pre><pre>ai_msg = llm_with_tools.invoke(messages)</pre><pre>messages.append(ai_msg)</pre><p>This is how the messages.tool_calls looks like:</p><pre>[{&#39;name&#39;: &#39;multiply&#39;, &#39;args&#39;: {&#39;a&#39;: 3, &#39;b&#39;: 12}, <br>&#39;id&#39;: &#39;call_GPGPE943GORirhIAYnWv00rK&#39;, &#39;type&#39;: &#39;tool_call&#39;},<br> {&#39;name&#39;: &#39;add&#39;, &#39;args&#39;: {&#39;a&#39;: 11, &#39;b&#39;: 49}, <br> &#39;id&#39;: &#39;call_dm8o64ZrY3WFZHAvCh1bEJ6i&#39;, &#39;type&#39;: &#39;tool_call&#39;}]</pre><p>As we can see it has called the multiply tool first with the respective arguments and then the add tool with its corresponding arguments.</p><p>Now, this tool call can be fed to the corresponding tools (multiplu and add) to get the desired outputs.</p><p>Now, we feed the tool calls to the respective tools , get response and then again append it back to the messages list.</p><pre>for tool_call in ai_msg.tool_calls:<br>selected_tool = {&quot;add&quot;: add, &quot;multiply&quot;: multiply}[tool_call[&quot;name&quot;].lower()]<br>tool_msg = selected_tool.invoke(tool_call)<br>messages.append(tool_msg)<br>messages</pre><p>This is how the messages list looks like now:</p><pre>[HumanMessage(content=&#39;What is 3 * 12? Also, what is 11 + 49?&#39;),<br>AIMessage(content=&#39;&#39;, additional_kwargs={&#39;tool_calls&#39;: [{&#39;id&#39;: &#39;call_loT2pliJwJe3p7nkgXYF48A1&#39;, &#39;function&#39;: {&#39;arguments&#39;: &#39;{&quot;a&quot;: 3, &quot;b&quot;: 12}&#39;, &#39;name&#39;: &#39;multiply&#39;}, &#39;type&#39;: &#39;function&#39;}, {&#39;id&#39;: &#39;call_bG9tYZCXOeYDZf3W46TceoV4&#39;, &#39;function&#39;: {&#39;arguments&#39;: &#39;{&quot;a&quot;: 11, &quot;b&quot;: 49}&#39;, &#39;name&#39;: &#39;add&#39;}, &#39;type&#39;: &#39;function&#39;}]}, response_metadata={&#39;token_usage&#39;: {&#39;completion_tokens&#39;: 50, &#39;prompt_tokens&#39;: 87, &#39;total_tokens&#39;: 137}, &#39;model_name&#39;: &#39;gpt-4o-mini-2024-07-18&#39;, &#39;system_fingerprint&#39;: &#39;fp_661538dc1f&#39;, &#39;finish_reason&#39;: &#39;tool_calls&#39;, &#39;logprobs&#39;: None}, id=&#39;run-e3db3c46-bf9e-478e-abc1-dc9a264f4afe-0&#39;, tool_calls=[{&#39;name&#39;: &#39;multiply&#39;, &#39;args&#39;: {&#39;a&#39;: 3, &#39;b&#39;: 12}, &#39;id&#39;: &#39;call_loT2pliJwJe3p7nkgXYF48A1&#39;, &#39;type&#39;: &#39;tool_call&#39;}, {&#39;name&#39;: &#39;add&#39;, &#39;args&#39;: {&#39;a&#39;: 11, &#39;b&#39;: 49}, &#39;id&#39;: &#39;call_bG9tYZCXOeYDZf3W46TceoV4&#39;, &#39;type&#39;: &#39;tool_call&#39;}], usage_metadata={&#39;input_tokens&#39;: 87, &#39;output_tokens&#39;: 50, &#39;total_tokens&#39;: 137}),<br>ToolMessage(content=&#39;36&#39;, name=&#39;multiply&#39;, tool_call_id=&#39;call_loT2pliJwJe3p7nkgXYF48A1&#39;),<br>ToolMessage(content=&#39;60&#39;, name=&#39;add&#39;, tool_call_id=&#39;call_bG9tYZCXOeYDZf3W46TceoV4&#39;)]</pre><p>Now, again we feed this entire convo to the llm:</p><pre>llm_with_tools.invoke(messages)</pre><p>The LLM comprehends the entire flow that has happened and generates a natural language response to the results of the tools.</p><pre>AIMessage(content=&#39;**The result of \\\\(3 \\\\times 12\\\\) is 36, <br>and the result of \\\\(11 + 49\\\\) is 60.**&#39;, <br>response_metadata={&#39;token_usage&#39;: {&#39;completion_tokens&#39;: 31, <br>&#39;prompt_tokens&#39;: 153, &#39;total_tokens&#39;: 184}, &#39;model_name&#39;: &#39;gpt-4o-mini-2024-07-18&#39;,<br> &#39;system_fingerprint&#39;: &#39;fp_661538dc1f&#39;, &#39;finish_reason&#39;: &#39;stop&#39;, &#39;logprobs&#39;: None}, <br> id=&#39;run-87d1ef0a-1223-4bb3-9310-7b591789323d-0&#39;, <br> usage_metadata={&#39;input_tokens&#39;: 153, &#39;output_tokens&#39;: 31, &#39;total_tokens&#39;: 184})</pre><p>So, here is it, I hope you learned sth. Thanks for the read!</p><p>Good luck in your learning journey traveller! ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb6b8b42d8b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gradient Descent: A friendly introduction]]></title>
            <link>https://medium.com/@anubhavm48/gradient-descent-a-friendly-introduction-03db17417a92?source=rss-9b2585e2d20e------2</link>
            <guid isPermaLink="false">https://medium.com/p/03db17417a92</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Anubhav Mishra]]></dc:creator>
            <pubDate>Thu, 05 Sep 2024 16:55:26 GMT</pubDate>
            <atom:updated>2024-09-05T16:55:26.246Z</atom:updated>
            <content:encoded><![CDATA[<p>Buckle up, because we’re about to explore one of the coolest techniques out there: gradient descent. Trust me, it’s not as intimidating as it sounds — in fact, it’s downright fascinating!</p><p>Picture This: You’re a Hiker in the Dark 🏔️🔦</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*45XdeOiidoOujGUbDkDRXA.jpeg" /></figure><p>Imagine you’re on a hiking adventure, but here’s the twist — it’s pitch black, and you’ve got to find your way to the bottom of a hill. Sounds tricky, right? Well, not if you’ve got a trusty torch and some clever tactics up your sleeve!</p><p>Here’s what you’d do:<br>1. Shine your torch around your feet. (Look at you, being all resourceful!)<br>2. Figure out which way is downhill. (You’ve got this!)<br>3. Take a small step in that direction. (Easy peasy!)<br>4. Repeat until you’re high-fiving yourself at the bottom. (Victory dance optional, but recommended 💃🕺)</p><p>Guess what? You’ve just discovered the secret sauce of gradient descent! How cool is that?</p><p>So, What’s This Gradient Descent Thing Anyway? 🤔</p><p>Alright, let’s put on our math hats for a sec (don’t worry, I promise it’ll be fun!). Gradient descent is like your hiking strategy, but for solving complex problems in machine learning. Here’s how it works:</p><ol><li>Start somewhere random on our mathematical “landscape.”<br>2. Check which way is “downhill” (we call this the gradient).<br>3. Take a step in the opposite direction of the gradient.<br>4. Keep going until you’re at the bottom (or close enough to do a happy dance 🎉).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Uu9DNTuxQseoNIXbclTRg.png" /></figure><p>It’s like playing the world’s most epic game of “Hot and Cold,” where “cold” is the direction we want to go!</p><p>Why Should You Care? Neural Networks, That’s Why! 🧠</p><p>Now, you might be wondering, “This is cool and all, but what’s it got to do with those neural networks I keep hearing about?” Great question! You’re so smart for asking. 😉</p><p>Here’s the deal: When we’re training neural networks, we’re basically trying to find the perfect set of “weights” (think of them as the network’s brain cells) that will make our AI as smart as possible. But here’s the kicker — there are often thousands, sometimes millions of these weights!</p><p>Imagine trying to adjust millions of knobs to get the perfect TV picture. Sounds impossible, right? Well, gradient descent is our superhero, swooping in to save the day! It helps us tweak all these weights efficiently, guiding our neural network to become smarter and smarter.</p><p>Making It Work: The Art of the Perfect Step 👣</p><p>Now, here’s where it gets really interesting. When we’re doing gradient descent, we’ve got to decide how big our steps should be. It’s like Goldilocks — we don’t want steps too big or too small, we want them juuuust right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PeF4N6HFLOUqZfik5SnlEw.png" /></figure><p>- Big steps: We might overshoot and end up playing hopscotch around the bottom. (Oops! 😅)<br>- Tiny steps: We’ll get there… eventually… maybe next century? (Yawn 😴)</p><p>The secret? Adaptive step sizes! We take bigger steps when we’re far from the bottom (gotta make progress, right?), and dainty little steps when we’re close (precision is key!). It’s like having a super-smart hiking buddy who knows exactly how to pace you.</p><p>Leveling Up: Gradient Descent in the Multi-Dimensional Universe 🌌</p><p>Okay, are you ready for this? Everything we’ve talked about so far is like the “easy mode” of gradient descent. In the real world of neural networks, we’re not just going downhill — we’re navigating a mind-bending landscape with hundreds or thousands of dimensions!</p><p>It’s like trying to find the lowest point in a universe with more directions than you can imagine. Sounds impossible? That’s where gradient descent really shines! It’s like having a magical compass that points you in the right direction, no matter how complex the space.</p><p>Wrapping It Up:</p><p>Can you believe it? You’ve just leveled up your machine learning knowledge! Let’s recap our awesome journey:</p><p>1. We learned how finding your way down a dark hill is surprisingly similar to optimizing neural networks. (Who knew hiking could be so educational?)<br>2. We discovered that gradient descent is like having a super-smart GPS for navigating complex mathematical landscapes.<br>3. We saw how this clever technique helps us train neural networks, making our AIs smarter and more efficient.</p><p>The next time you hear about a cool new AI doing amazing things, you can nod knowingly and think, “Ah yes, gradient descent probably helped train that!” How’s that for feeling like an insider? 😎</p><p>So, what do you think? Isn’t machine learning incredible? And trust me, this is just the tip of the iceberg! There’s a whole world of fascinating concepts out there waiting for curious minds like yours. Ready to dive deeper? Let me know what you want to explore next — the world of AI is our oyster! 🦪🌟</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03db17417a92" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>