Module 4 Wrap-up: Your First LangChain Agent
Hands-on: Build a tool-using LangChain agent and observe the reasoning traces in real-time.
Module 4 Wrap-up: From Script to Framework
You have learned the components of LangChain. Now, let’s put them together to build a "Stock Analyst" agent. This agent will have two tools: a search engine and a calculator.
Hands-on Exercise: The LangChain Stock Analyst
1. Requirements
Ensure you have the libraries:
pip install langchain langchain-openai pydantic
2. The Code
Create a file named langchain_agent.py:
from langchain_openai import ChatOpenAI
from langchain.agents import create_openai_functions_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.tools import tool
# 1. Define the Tools
@tool
def get_stock_price(symbol: str) -> float:
"""Returns the current stock price for a given ticker."""
# Simulated data
prices = {"AAPL": 150.0, "NVDA": 900.0, "MSFT": 420.0}
return prices.get(symbol.upper(), 100.0)
@tool
def calculate_growth(initial: float, final: float) -> str:
"""Calculates percentage growth between two numbers."""
growth = ((final - initial) / initial) * 100
return f"{growth}%"
tools = [get_stock_price, calculate_growth]
# 2. Define the LLM
llm = ChatOpenAI(model="gpt-4o", temperature=0)
# 3. Define the Prompt (Standard LangChain format)
prompt = ChatPromptTemplate.from_messages([
("system", "You are a professional financial analyst. Use tools for all calculations."),
("human", "{input}"),
("placeholder", "{agent_scratchpad}"),
])
# 4. Initialize the Agent & Executor
agent = create_openai_functions_agent(llm, tools, prompt)
agent_executor = AgentExecutor(
agent=agent,
tools=tools,
verbose=True, # This lets us see the reasoning!
max_iterations=5
)
# 5. Run the Test
query = "What is the growth if AAPL goes from its current price to 200?"
agent_executor.invoke({"input": query})
3. Observe the Trace
Run the script. In the terminal, you will see a green/blue log showing exactly how the model:
- Called
get_stock_pricefor AAPL. - Received
150.0. - Called
calculate_growthfor 150.0 to 200. - Received
33.33%. - Formulated the final natural language answer.
Module 4 Summary
- LangChain provides the standard "Stack" for agent development.
- Tool Decorators make it easy to expose Python functions to AI.
- AgentExecutor handles the loop, error handling, and state management.
- Verbosity is your primary debugging tool in high-level frameworks.
Coming Up Next...
In Module 5, we look at the "Dark Side" of agents. We will study the Limits of traditional loops and learn why we eventually need more advanced control architectures like LangGraph.
Module 4 Checklist
- I have installed the LangChain libraries.
- I can describe the difference between an Agent and an Executor.
- I have successfully run the
langchain_agent.pyscript. - I understand how the
agent_scratchpadvariable works. - I can identify where to set the
max_iterationslimit.