Skip to main content

Building a Real-Time Multi-Tool AI Agent Using LangChain & FastAPI

Updated 5 min readMarkdown

How to make your AI not just think — but act.


Imagine asking an AI :

“Can you check today’s weather in Pune, create a graph of the temperature trend for this week, and explain it like I’m five?”

A basic chatbot might give you a generic answer or hallucinate.
But a multi-tool AI agent built with LangChain and FastAPI will actually fetch the data, generate the chart, and talk you through it — all in real time.

That’s the beauty of combining reasoning (LLMs) with action (tools).
In this blog, we’ll explore how to build a real-time, multi-tool AI agent, capable of calling APIs, running Python code, and streaming responses interactively.


Why Multi-Tool Agents Matter

Large Language Models (LLMs) like GPT, Claude, or Gemini are smart — but isolated.
They don’t know what’s happening right now. They can’t browse, compute, or query databases on their own.

That’s where LangChain Agents come in. They let you connect external tools so your AI can:

  • Search the Web: Fetch live news or stock prices.

  • Run Python Code: Analyze data or generate visualizations.

  • Query Databases: Retrieve real user data from structured sources.

  • Stream Live Results: Respond progressively as it thinks.

Example :
A user says, “Find the top 3 trending AI startups today and generate a table with their funding data.”
The agent can :

  1. Use a web search tool to get the latest results.

  2. Use Python to format and display the data.

  3. Stream back the summary while it works.

It’s like talking to a virtual data scientist.


The Architecture Overview

Let’s break down how the system works:

Client → FastAPI Server → LangChain Agent → Tools (Search, Python, DB)

Step-by-Step Flow :

  1. Client (Frontend / API call) sends a user query.

  2. FastAPI receives the request and passes it to the LangChain agent.

  3. The Agent decides :

  • Do I need to call a search tool?

  • Should I execute code?

  • Or can I answer directly?

  1. It calls the right tool (one or more).

  2. The response is streamed back to the client in real time.

This setup lets users see updates like:

“Fetching data… Processing results… Generating chart… Done!”


Building Blocks

1. Define the Tools

Tools are like the agent’s superpowers.
You define what the AI is allowed to do.

Here’s a simple example :

from langchain.tools import Tool

def search_web(query):
    # Your search API logic here
    return f"Results for {query}: ..."

def run_python(code):
    try:
        exec_globals = {}
        exec(code, exec_globals)
        return exec_globals.get('result', 'Executed successfully')
    except Exception as e:
        return str(e)

tools = [
    Tool(name="search", func=search_web, description="Search the web for live data"),
    Tool(name="python", func=run_python, description="Execute Python code safely"),
]

Tip:
Describe each tool clearly. The LLM decides which tool to use based on your descriptions.


2. Create the Agent

Now let’s connect the tools and LLM together.

from langchain.agents import initialize_agent, AgentType
from langchain.chat_models import ChatOpenAI

llm = ChatOpenAI(temperature=0, streaming=True)

agent = initialize_agent(
    tools=tools,
    llm=llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True
)

This makes an agent that can reason, pick tools, and combine outputs.


3. Add Streaming with FastAPI

To give users a “real-time” experience, we’ll use FastAPI and Server-Sent Events (SSE).


from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse

app = FastAPI()

async def agent_runner(prompt):
    async for chunk in agent.astream(prompt):
        yield f"data: {chunk}\n\n"

@app.post("/chat")
async def chat(request: Request):
    body = await request.json()
    prompt = body["prompt"]
    return StreamingResponse(agent_runner(prompt), media_type="text/event-stream")

The user sees partial results as soon as they’re generated — no waiting for the entire response.


Real-Time Examples

Let’s bring this to life with a few real-world scenarios.

Example 1 : Real-Time Stock Insights

User : “Plot the last 5 days of Tesla stock prices and summarize the trend.”

Agent Workflow :

  1. Uses the Search Tool to fetch Tesla’s stock data via Yahoo Finance API.

  2. Calls the Python Tool to create a matplotlib line chart.

  3. Streams the steps:

  • “Fetching data…”

  • “Generating visualization…”

  • “Here’s your chart and summary.”

Output:

Tesla’s stock has risen 3.2% this week, driven by strong delivery numbers.


Example 2: Real-Time Weather Reporter

User: “What’s the current temperature in Mumbai and how does it compare to Delhi?”

Agent Workflow :

  1. Uses Weather API (wrapped in the search tool).

  2. Runs Python tool to compare and summarize.

  3. Streams :

  • “Fetching data for Mumbai and Delhi…”

  • “Calculating difference…”

  • “Mumbai is 4°C warmer than Delhi today.”


Example 3: News Briefing Assistant

User : “Summarize the top 3 AI news stories from today.”

Agent Workflow :

  1. Calls Search Tool → fetches headlines from Google News or Bing API.

  2. Uses LLM summarization to condense them.

  3. Streams each story as it arrives.

Output :

OpenAI announces GPT-Next,
Google Cloud adds new AI features,
Meta launches AI-powered collaboration tools.


Scaling Your Agent

When your prototype works, you can take it to production with these enhancements:

| Need                  | Solution                                   
 ---------------------  | ------------------------------------------ 
 High traffic           | Deploy FastAPI with **Uvicorn + Gunicorn** 
 Tool optimization      | Use caching and rate limiting              
 Secure code execution  | Sandbox Python using `restrictedpython`    
 Add context memory     | Use LangChain memory modules               
 Custom domain tools    | Build tools for your product APIs

Common Challenges

| Problem               | Fix                                             |
 ---------------------  | ----------------------------------------------- 
 Model uses wrong tool  | Improve tool descriptions and few-shot examples 
 Slow response          | Enable streaming and async execution            
 Security issues        | Restrict tool access and sanitize inputs        
 Context overflow       | Summarize or truncate old history

Putting It All Together

You’ve now got the recipe for a fully functional, real-time, multi-tool AI agent:

  • LangChain for reasoning

  • Tools for action

  • FastAPI for real-time streaming

And the best part? It’s modular. You can extend it endlessly — connect your CRM, run SQL queries, or even trigger workflows.


Conclusion

We’re entering an era where AI isn’t just conversational — it’s operational.
By blending LangChain’s agent framework with FastAPI’s real-time capabilities, you can build assistants that reason, act, and respond live.

Whether it’s analyzing data, summarizing news, or visualizing trends — your agent can handle it all.

So the next time you ask,

“What’s happening in AI today?”
Your AI won’t just tell you — it’ll
show you.


💬 Let’s Connect : LinkedIn

Please feel free to reach out if you have any questions .

No comments yet. Be the first to comment.