Tuesday, May 12, 2026

Agents in LangChain With Examples

In the post Tool Calling in LangChain we saw how to execute the created tools manually by parsing the tool call sent by LLM and then explicitly invoking the required function. While effective for simple workflows, this manual orchestration quickly becomes hard to follow, when tasks demand multiple steps, dynamic reasoning and adaptive decision making.

This is where agents in LangChain change the way tools are executed. Agents automate tool calling by using a Large Language Model (LLM) as a reasoning engine. Instead of manually deciding which tool to call and when, agents use a loop to iteratively reason about a task, select necessary tools and invoke them automatically, and observe outcomes until the task is complete.

Agents in LangChain: Smarter Task Automation

At their core, agents combine four essential components:

  • LLM (The Brain): Provides reasoning and decision logic.
  • Tools: External functions, APIs, or data sources that are to be called automatically by agents.
  • Memory: Maintains context across multiple turns for continuity.
  • Agent Runtime (LangGraph): A graph-based agent runtime using LangGraph is created that defines how your agent processes information.

create_agent function in LangChain

In earlier versions of LangChain, developers had to choose between multiple specialized agent constructors such as create_react_agent, create_openai_functions_agent, and others. Each of these was tailored to a specific agent type or execution style, but this fragmented the developer experience and made maintenance harder.

Over time, the LangChain team consolidated these patterns. All the older agent creation functions were deprecated, and the unified create_agent function was introduced which builds a graph based agent runtime powered by LangGraph.

  • A graph is made up of nodes (steps) and edges (connections) that defines how your agent processes information.
  • Nodes represent actions such as calling the model, executing tools, or running middleware.
  • Edges define how the agent moves between these steps.

create_agent function syntax

create_agent(
  model,  
  tools,
  system_prompt,
  middleware,
  response_format,
  ...
)

Parameters:

  1. model
    • The LLM you want the agent to use (e.g., OpenAI, Anthropic, Gemini).
    • This is the reasoning engine that interprets input, decides actions, and generates responses.
  2. tools
    • A list of external functions or APIs the agent can call (e.g., calculator, search, database query).
  3. system_prompt
    • An optional system prompt for the LLM that sets the agent's role, tone, and behavior.
    • Example: "You are a helpful assistant that uses tools when needed."
  4. middleware
    • Optional components that intercept or modify the agent's behaviour at various stages.
    • Can be used for logging, monitoring, or injecting custom logic before/after tool calls.
  5. response_format
    • Defines how the agent should structure its final output.
    • Can be a ToolStrategy, ProviderStrategy, or a Pydantic model class.

Apart from these parameters there are other optional parameters to persist the state of graph (checkpoint), persisting data (store) and many more.

How Agent Loop Works with create_agent

Agents in LangChain
  1. Agent Node Calls the Model
    • The agent starts by sending the messages list to the language model.
    • The system prompt is applied first to guide the model's behavior.
  2. Model Produces a Response
    • The model returns an AIMessage.
    • If this AIMessage contains tool_calls, it means the model wants to use a tool.
  3. Tools Node Executes the Tools
    • The agent passes the tool calls to the Tools node.
    • Each tool is executed with the provided arguments.
    • The results are wrapped as ToolMessage objects and added back to the messages list.
  4. Agent Node Calls the Model Again
    • With the updated messages list (including tool results), the agent re invokes the model.
    • This allows the model to reason over the new information.
  5. Loop Continues
    • Repeat steps 2–4
    • The process repeats until no more tool_calls are present in the response.

LangChain Example - Agent with Web Search + Math Tools

Imagine you want an agent that can handle questions requiring both real time data and calculations. For example: "What is the commission on 15 grams of gold at 5% commission rate?"

This workflow requires two tasks-

  1. Fetching the current rate of gold per gram and then calculating cost price of given quantity.
  2. Apply the commission rate to compute the commission amount on that cost price.

So, we can define two tools for these 2 tasks:

  1. Web search tool- Searches the current market rate of gold per gram.
  2. Commission Calculator Tool- takes the cost price and commission rate, then returns the commission value.

The agent orchestrates these tools in sequence; first retrieving the gold price, then performing the commission calculation, and finally returning the complete answer to the user. Important thing here is as a developer you don’t need to call any of the tools manually it will be handled by agent run-time.

Note that the code uses OpenRouter as inference provider which needs registering with the OpenRouter and getting the API key (in case you are going to use the same setup). That API key needs to be stored in .env file with the key as "OPENROUTER_API_KEY". Needs installation of langchain-openrouter and pytz packages too.

from langchain_community.tools import DuckDuckGoSearchRun
from langchain_core.tools import tool
from langchain_openrouter import ChatOpenRouter
from langchain.agents.structured_output import ToolStrategy
from datetime import datetime
import pytz
from langchain.agents import create_agent
from dotenv import load_dotenv
load_dotenv()  # Load environment variables from .env file
from langchain_core.output_parsers import PydanticOutputParser
from pydantic import BaseModel, Field

# Pydantic model for structured output
class GoldCommissionResult(BaseModel):
    gold_price_per_gram: float = Field(..., description="Today's 24K gold price per gram in INR (Mumbai, IST)")
    grams: int = Field(..., description="Number of grams requested")
    cost_price: float = Field(..., description="Total cost price in INR for the requested grams")
    commission_rate: float = Field(..., description="Commission rate applied (decimal, e.g., 0.05 for 5%)")
    commission_value: float = Field(..., description="Final commission value in INR")

@tool
def search_web_tool(query: str):
    '''Tool function to search the web for the given query using DuckDuckGo search results.'''
    print(f"Searching the web for: {query}")
    search_tool = DuckDuckGoSearchRun(num_results=3)
    results = search_tool.run(query)
    return results

@tool
def calculate_commission(cost_price: float, commission_rate: float) -> float:
    '''Tool function to evaluate commission on the cost price.'''
    print(f"Calculating commission for cost price: {cost_price} and commission rate: {commission_rate}")
    return cost_price * commission_rate

model = ChatOpenRouter(model="openai/gpt-oss-120b", temperature=0.1)

system_prompt = """
You are a helpful assistant working in Mumbai, India.
All tool calls, time-sensitive tasks and responses must adhere to IST.
When asked about gold price and commission:
1. Use search_web_tool to fetch today's 24K gold price in Mumbai (per gram, INR).
2. Multiply by the grams requested to get cost price.
3. Pass that cost price into calculate_commission with the given commission rate.
"""

# Create agent with tools
agent = create_agent(model,
    tools=[search_web_tool, calculate_commission],
    system_prompt=system_prompt,
    response_format=ToolStrategy(GoldCommissionResult)
)

# This function gets today's date in IST timezone, which is crucial for accurate web search results related to gold prices in India.
def get_today_date_ist():
    ist = pytz.timezone("Asia/Kolkata")
    return datetime.now(ist).strftime("%Y-%m-%d")

today = get_today_date_ist()

result = agent.invoke({"messages": [{"role": "user", "content": f"What is the commission on 15 gram of gold on {today} price for 24K in INR at 5% commission rate?"}]})

print(result)
#final answer is in structured_response field of the result, which is an instance of GoldCommissionResult
print("Answer:",result["structured_response"])

Output

Searching the web for: 24K gold price per gram Mumbai today
Calculating commission for cost price: 243225.0 and commission rate: 0.05
{'messages': [HumanMessage(content='What is the commission on 15 gram of gold on 2026-05-11 price for 24K in INR at 5% commission 
rate?', additional_kwargs={}, response_metadata={}, id='560afba8-0100-4d00-9bc5-2ee91ec8404a'), AIMessage(content='', 
additional_kwargs={'reasoning_content': 'We need to get today\'s 24K gold price in Mumbai per gram, but the user asks for price on 2026-05-11. That\'s a future date. We cannot fetch future price. Probably we interpret "today\'s price" as of now (IST). The user asks "on 2026-05-11 price". That date is in future, we cannot get. We could respond that we can only fetch current price. But the instruction says: When asked about gold price and commission: Use search_web_tool to fetch today\'s 24K gold price in Mumbai (per gram, INR). So we should fetch current price. Then compute for 15 grams, commission 5%.\n\nThus steps: search web for "24K gold price per gram Mumbai today". Then calculate cost = price * 15. Then calculate commission with rate 0.05.\n\nLet\'s do search.', 'reasoning_details': [{'type': 'reasoning.text', 'format': 'unknown', 'index': 0, 'text': 'We need to get today\'s 24K gold price in Mumbai per gram, but the user asks for price on 2026-05-11. That\'s a future date. We cannot fetch future price. Probably we interpret "today\'s price" as of now (IST). The user asks "on 2026-05-11 price". That date is in future, we cannot get. We could respond that we can only fetch current price. But the instruction says: When asked about gold price and commission: Use search_web_tool to fetch today\'s 24K gold price in Mumbai (per gram, INR). So we should fetch current price. Then compute for 15 grams, commission 5%.\n\nThus steps: search web for "24K gold price per gram Mumbai today". Then calculate cost = price * 15. Then calculate commission with rate 0.05.\n\nLet\'s do search.'}]}, response_metadata={'model_name': 'openai/gpt-oss-120b', 'id': 'gen-1778481749-VEyzaZUsFowGl8YVTxNr', 'created': 1778481749, 'object': 'chat.completion', 'finish_reason': 'tool_calls', 'logprobs': None, 'model_provider': 'openrouter'}, id='lc_run--019e15c5-db77-7482-8235-aa43535013e1-0', 
tool_calls=[{'name': 'search_web_tool', 'args': {'query': '24K gold price per gram Mumbai today'}, 'id': 'chatcmpl-tool-038985043b0542f19f4f98bb50691877', 'type': 'tool_call'}], invalid_tool_calls=[], usage_metadata={'input_tokens': 362, 'output_tokens': 215, 'total_tokens': 577, 'input_token_details': {'cache_read': 0, 'cache_creation': 0}, 'output_token_details': {'reasoning': 185}}), 
ToolMessage(content="Checktoday's livegoldrate inMumbaifor 22K and24Kgoldpergram. Get real-timepriceupdates, compare daily rates, and track 10-day historicalgoldpricetrends across major Indian cities on Upstox. 24KGoldRate.Today,goldremains deeply rooted in the culture ofMumbai. From the iconicgold'taalis' (mangalsutras) exchanged during Maharashtrian weddings to the delicategold'nath' (nose rings) adorning women during festivals,goldsignifies prosperity, blessings, and the... GoldPriceTodayinMumbaiis 16,215 Indian Rupee (INR)/gram24K. This is equal to 625.17 (AED) and 170.22 (USD).Goldpricein India is calculated bothperounce,gram, kilogram and tola and for the most common karats. Today'sgoldpricein India stands at ?15,234pergramfor 24 karatgold(99.9% purity), ?13,964pergramfor 22 karatgold(91.6% purity), and ?11,425pergramfor 18 karatgold(75% purity).Goldhas over the years been a perfect hedge against inflation. Investors are increasingly looking... Today24K, 22K & 18K CaratGoldPricePerGramin India (INR).This tools helps you project your potentialgoldrate aspertodaysgoldrate.", name='search_web_tool', id='b9f343d2-4312-4ee1-ab03-7afb687fba02', tool_call_id='chatcmpl-tool-038985043b0542f19f4f98bb50691877'), AIMessage(content='', additional_kwargs={'reasoning_content': 'The user asks: "What is the commission on 15 gram of gold on 2026-05-11 price for 24K in INR at 5% commission rate?" We need today\'s price? Actually date is 2026-05-11, which is future. We cannot fetch future price. Probably they meant today\'s price (current date). We have fetched a price: 16,215 INR per gram (source says). Need to compute cost price = 15 * 16215 = 243,225 INR. 
Then commission = 5% of that = 0.05 * 243,225 = 12,161.25 INR.\n\nWe need to call calculate_commission with cost_price and commission_rate. Then output result with details. Let\'s call calculate_commission.', 'reasoning_details': [{'type': 'reasoning.text', 'format': 'unknown', 'index': 0, 'text': 'The user asks: "What is the commission on 15 gram of gold on 2026-05-11 price for 24K in INR at 5% commission rate?" We need today\'s price? Actually date is 2026-05-11, which is future. We cannot fetch future price. Probably they meant today\'s price (current date). We have fetched a price: 16,215 INR per gram (source says). Need to compute cost price = 15 * 16215 = 243,225 INR. Then commission = 5% of that = 0.05 * 243,225 = 12,161.25 INR.\n\nWe need to call calculate_commission with cost_price and commission_rate. Then output result with details. Let\'s call calculate_commission.'}]}, response_metadata={'model_name': 'openai/gpt-oss-120b', 'id': 'gen-1778481758-mex8jK3ZFTGVBLri5Qps', 'created': 1778481758, 'object': 'chat.completion', 'finish_reason': 'tool_calls', 'logprobs': None, 'model_provider': 'openrouter'}, id='lc_run--019e15c6-01d5-7f82-8647-cb759f32def0-0', tool_calls=[{'name': 'calculate_commission', 'args': {'cost_price': 243225, 'commission_rate': 0.05}, 'id': 'chatcmpl-tool-b3af5980739b4d6e936aba6193b19634', 'type': 'tool_call'}], invalid_tool_calls=[], usage_metadata={'input_tokens': 703, 'output_tokens': 201, 'total_tokens': 904, 'input_token_details': {'cache_read': 0, 'cache_creation': 0}, 'output_token_details': {'reasoning': 148}}), 
ToolMessage(content='12161.25', name='calculate_commission', id='31475b2e-6486-40bd-98f9-681e5d1b5409', tool_call_id='chatcmpl-tool-b3af5980739b4d6e936aba6193b19634'), AIMessage(content='', additional_kwargs={'reasoning_content': 'We need to produce final answer with details: gold price per gram, cost price for 15g, commission value. The search result gave two different numbers: 16,215 INR per gram and 15,234 INR per gram. Need to pick correct today\'s 24K gold price in Mumbai. 
The snippet includes both. Which is correct? Probably the first line "GoldPriceTodayinMumbaiis 16,215 Indian Rupee (INR)/gram24K." 
We'll use 16,215. Multiply 16,215 * 15 = 243,225 INR cost price. Commission 5% = 12,161.25 INR.\n\nWe should also provide a 
structured result using GoldCommissionResult. Let\'s call the function to output structured result.', 'reasoning_details': 
[{'type': 'reasoning.text', 'format': 'unknown', 'index': 0, 'text': 'We need to produce final answer with details: gold price 
per gram, cost price for 15g, commission value. The search result gave two different numbers: 16,215 INR per gram and 15,234 
INR per gram. Need to pick correct today\'s 24K gold price in Mumbai. The snippet includes both. Which is correct? Probably 
the first line "GoldPriceTodayinMumbaiis 16,215 Indian Rupee (INR)/gram24K." We\'ll use 16,215. Multiply 16,215 * 15 = 243,225 
INR cost price. Commission 5% = 12,161.25 INR.\n\nWe should also provide a structured result using GoldCommissionResult. 
Let\'s call the function to output structured result.'}]}, response_metadata={'model_name': 'openai/gpt-oss-120b', 
'id': 'gen-1778481765-OxLjqE7vxagJ3S8GCBsj', 'created': 1778481765, 'object': 'chat.completion', 'finish_reason': 'tool_calls', 
'logprobs': None, 'model_provider': 'openrouter'}, id='lc_run--019e15c6-1e35-74a0-931d-09a06aa9991f-0', 
tool_calls=[{'name': 'GoldCommissionResult', 'args': {'gold_price_per_gram': 16215, 'grams': 15, 'cost_price': 243225, 
'commission_rate': 0.05, 'commission_value': 12161.25}, 'id': 'chatcmpl-tool-9242b32b242f41efa62c40fd5d0e5343', 'type': 'tool_call'}], 
invalid_tool_calls=[], usage_metadata={'input_tokens': 751, 'output_tokens': 225, 'total_tokens': 976, 
'input_token_details': {'cache_read': 0, 'cache_creation': 0}, 'output_token_details': {'reasoning': 152}}), 
ToolMessage(content='Returning structured response: gold_price_per_gram=16215.0 grams=15 cost_price=243225.0 commission_rate=0.05 commission_value=12161.25', name='GoldCommissionResult', id='1c92da8d-4ac0-4c0c-a822-365427d5df38', 
tool_call_id='chatcmpl-tool-9242b32b242f41efa62c40fd5d0e5343')], 'structured_response': GoldCommissionResult(gold_price_per_gram=16215.0, 
grams=15, cost_price=243225.0, commission_rate=0.05, commission_value=12161.25)}
Answer: gold_price_per_gram=16215.0 grams=15 cost_price=243225.0 commission_rate=0.05 commission_value=12161.25

Points to note here

  1. Two tools are defined using the @tool decorator. In search tool DuckDuckGoSearchRun tool is used for doing the web search.
  2. Pydantic model class GoldCommissionResult is defined to instruct how the agent should structure its final output.
  3. In the create_agent function tools are configured as a list and Pydantic model class is wrapped with in the ToolStrategy class. With that agent runtime knows which tools are available and how to format the final response.
  4. In the attached output, go through the ToolMessage objects to see how interaction happens between the LLM and your code.

That's all for this topic Agents in LangChain With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Tools in LangChain With Examples
  2. Citation Aware RAG Application in LangChain
  3. LangChain Conversational RAG with Multi-user Sessions
  4. Embeddings in LangChain With Examples
  5. Vector Stores in LangChain With Examples

You may also like-

  1. Chain Using LangChain Expression Language With Examples
  2. Messages in LangChain
  3. Var type in Java - Local Variable Type Inference
  4. Java DelayQueue With Examples
  5. output() Function in Angular With Examples
  6. Python while Loop With Examples
  7. Strings in Python With Method Examples
  8. Index Route in React Router

No comments:

Post a Comment