AI Hints
Home›LangChain Tutorial›Structured Answers and Middleware
LangChain · Lesson 49 of 120

Structured Agent Answers

Response_format.

⏱ 2 min read▶ Video at 54:06🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

Agents usually end with a friendly sentence. But if another program uses the answer, it needs data. The response format option makes an agent finish with a structured object, after using its tools.

Structured Agent Answers
From the video: Structured Agent Answers
  • Agents end with text
  • Programs need data
  • response_format

An agent that returns data

We describe the answer we want as a Pydantic model, a stock report with the title, the number of copies, and whether it's available. We pass it as response format. Run it. The agent uses the stock tool, then returns a stock report object, under the key structured response.

agent_format.pypython
from pydantic import BaseModel
from langchain.agents import create_agent
from shop_tools import check_stock

class StockReport(BaseModel):
    title: str
    copies: int
    available: bool

agent = create_agent("google_genai:gemini-flash-lite-latest",
                     tools=[check_stock], response_format=StockReport)
out = agent.invoke({"messages": [{"role": "user", "content": "Check Circe for me."}]})

report = out["structured_response"]
print(type(report).__name__, report)
Output
StockReport title='Circe' copies=0 available=False
Also uses shop_tools.py
from langchain.tools import tool

BOOKS = {
    "The Hobbit": {"stock": 7, "price": 8.99, "author": "J.R.R. Tolkien"},
    "Dune": {"stock": 3, "price": 9.99, "author": "Frank Herbert"},
    "Circe": {"stock": 0, "price": 10.99, "author": "Madeline Miller"},
}

@tool
def check_stock(title: str) -> int:
    """Copies of a book in stock at Riverside Books."""
    return BOOKS.get(title, {}).get("stock", 0)

@tool
def get_price(title: str) -> float:
    """Price of a book in pounds."""
    return BOOKS.get(title, {}).get("price", 0.0)

@tool
def get_author(title: str) -> str:
    """Author of a book."""
    return BOOKS.get(title, {}).get("author", "unknown")

When to use it

Use response format when the agent's answer feeds another system, like a dashboard, a database, or another agent. The agent still reasons and uses tools freely, but its final answer has a guaranteed shape. You get the flexibility of an agent, and the reliability of structured output.

keyvalue
Feeds a systemdashboards, databases
Toolsstill used freely
Final answerguaranteed shape
Keystructured_response

Summary

Response format makes an agent finish with a structured object, found under structured response. Next, middleware, the way to customise what happens inside an agent.

Key takeaways
  • response_format=Model
  • Tools, then data
  • out['structured_response']
Next up: Middleware — hooks around the model