LangChain Agent Builder's Guide: From create_agent to Streaming Structured Output
LangChain Agent Assistant Building Notes: Creation, Tool Calling, Structured Output, and Streaming
1. The Core Formula of an Intelligent Assistant
LangChain officially defines an Agent as "Model + Harness (execution framework)". Harness is everything outside the model loop: prompts, tools, middleware, state management. create_agent is the minimal implementation of this Harness, letting you assemble a runnable assistant with the least code[citation:1][citation:9].
The minimal closed loop for an intelligent assistant is: user input → model decides → call tools (if needed) → send results back → model composes a final reply. The Tool Calling loop, Message flow, and structured output you've learned all play their specific roles in this loop.
2. Creating an Intelligent Assistant
2.1 The Simplest Creation Method
from langchain.agents import create_agent
def get_weather(city: str) -> str:
"""Get weather for a given city."""
return f"It's always sunny in {city}!"
agent = create_agent(
model="openai:gpt-5.5",
tools=[get_weather],
system_prompt="You are a helpful assistant",
)
The model supports multiple formats: "openai:gpt-5.5", "anthropic:claude-sonnet-4-6", "google_genai:gemini-2.5-flash-lite", "ollama:devstral-2", etc. tools is the list of tools you define, and system_prompt defines the assistant's role and behavioral guidelines.
2.2 Key Parameters
| Parameter | Purpose | When Needed |
|---|---|---|
model |
Model identifier or model object | Required |
tools |
List of tools | Required (can be empty) |
system_prompt |
Role and behavior definition | Strongly recommended |
response_format |
Structured output strategy | When typed return is needed |
checkpointer |
Memory for multi-turn conversation | When history needs to be remembered |
The quality of system_prompt directly affects assistant performance. The official recommendation is to be "specific and actionable", clearly stating what abilities the assistant has, when to use which tool, and when not to guess.
3. Tool Calling
3.1 Defining Tools
Use the @tool decorator to wrap a normal function into a tool callable by the model. The docstring and parameter names enter the prompt the model sees, so writing clearly "what this tool does" is crucial:
from langchain.tools import tool
@tool
def search_flights(origin: str, destination: str, date: str) -> str:
"""Search for available flights between two cities on a given date."""
# actual query logic
return f"Flights from {origin} to {destination} on {date}: ..."
3.2 Agent Handles the Calling Loop Automatically
You don't need to write a manual while loop or construct ToolMessage yourself. create_agent internally wraps the complete Tool Calling loop:
- The model determines that a tool needs to be called and returns
tool_calls - The Agent executes the tool and gets the result
- The result is wrapped as a ToolMessage and sent back to the model
- The model decides based on the result: continue calling tools or generate a final reply
This loop continues until the model no longer requests tools. In the LangSmith trace tree, each model call and tool execution appears as nested nodes, letting you clearly see what the assistant "thought and did".
3.3 Runtime Context in Tools
If a tool needs to read user identity, session state, or other information that should not be exposed to the model, use the ToolRuntime parameter:
from langchain.tools import tool, ToolRuntime
@tool
def get_user_orders(runtime: ToolRuntime) -> str:
"""Get orders for the current user."""
user_id = runtime.context.user_id
return fetch_orders(user_id)
This parameter does not appear in the tool Schema the model sees; the Agent injects it automatically during execution.
4. Structured Output
4.1 Why It's Needed
Plain text responses are hard to process programmatically. Structured output makes the assistant return typed data that conforms to a predefined Schema, which can be directly used to render cards, tables, or passed to downstream systems.
The underlying mechanism is still tool calling: you define a Schema, LangChain wraps it into a "structured output tool". When the model calls this tool, the arguments are the data matching the Schema. The tool itself does not execute logic; it purely serves as a carrier for typed data.
4.2 Using It in an Agent
from pydantic import BaseModel, Field
from typing import Literal
from langchain.agents import create_agent
from langchain.agents.structured_output import ToolStrategy
class ProductReview(BaseModel):
"""Analyze a product review."""
rating: int = Field(description="Rating 1-5")
sentiment: Literal["positive", "negative"] = Field(description="Sentiment")
key_points: list[str] = Field(description="Key points, lowercase, each 1-3 words")
agent = create_agent(
model="gpt-5.5",
tools=[],
response_format=ToolStrategy(ProductReview)
)
result = agent.invoke({
"messages": [{"role": "user", "content": "Analyze review: 'Great product: 5 out of 5 stars. Fast shipping, but expensive'"}]
})
# Access values
review = result["structured_response"]
print(review.rating, review.sentiment, review.key_points)
# 5 positive ['fast shipping', 'expensive']
ToolStrategy is the structured output strategy for Agent scenarios; under the hood it goes through the tool calling path. If you use it on a plain model (not through an Agent), use model.with_structured_output(Schema) instead.
4.3 Error Retry
The model may generate non-compliant structured output. LangChain includes smart retry: if the model calls multiple structured tools, or field validation fails, the system sends the error information back to the model and prompts it to fix it. You don't need to write a manual try/except.
5. Streaming Output
5.1 Why Streaming Is Needed
Intelligent assistant responses often take seconds or even tens of seconds. Streaming lets users see content as it's generated, changing the experience from "wait → appear all at once" to "appear token by token / chunk by chunk".
5.2 Using stream_events
LangChain Agent is built on LangGraph; streaming capability is exposed via stream_events (or astream_events). Core projections include:
| Projection | Purpose |
|---|---|
stream.messages |
Message stream for each LLM call |
message.text |
Text increments (token by token) |
message.toolCalls |
Tool call parameter increments |
stream.toolCalls |
Tool execution lifecycle |
stream.output |
Final Agent state |
5.3 Basic Streaming Example
stream = agent.stream_events(
{"messages": [{"role": "user", "content": "Tell a story about a goldfish"}]},
version="v3"
)
async for message in stream.messages:
async for delta in message.text:
print(delta, end="", flush=True)
5.4 Considerations for Structured Output + Streaming
Streaming behavior for structured output differs from plain text: chunks are progressively complete snapshots, not incremental deltas. During streaming, tool_calls parameters may be only partially filled. If you render structured data in the frontend, you need to check whether fields are complete before displaying.
6. Complete Intelligent Assistant Example
Combining the above capabilities, an assistant with tool calling, structured output, and streaming responses:
import os
from datetime import datetime
from pathlib import Path
from dotenv import load_dotenv
from langchain.chat_models import init_chat_model
from langchain.agents import create_agent
from langchain.agents.structured_output import ToolStrategy
from langchain_core.tools import tool
from pydantic import BaseModel, Field
# Load DeepSeek parameters from .env in the project root (api_key / base_url / model)
load_dotenv(dotenv_path=Path(__file__).resolve().parent.parent / ".env", override=True)
# 1. Initialize model (all parameters from environment variables)
model = init_chat_model(
model=os.getenv("DEEPSEEK_MODEL", "deepseek-v4-flash"),
model_provider="openai",
api_key=os.getenv("DEEPSEEK_API_KEY"),
base_url=os.getenv("DEEPSEEK_BASE_URL"),
# Thinking mode does not support the forced tool_choice required for structured output; disable it here
extra_body={"thinking": {"type": "disabled"}},
)
# 2. Define two tools
@tool
def get_weather(city: str) -> str:
"""Query weather for a given city (sample data)"""
return f"{city} is sunny today, 25°C"
@tool
def get_current_time() -> str:
"""Query current date and time"""
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# 3. Define structured output Schema
class WeatherAnswer(BaseModel):
"""Summarize weather and time query results"""
city: str = Field(description="Queried city")
weather: str = Field(description="Weather condition")
temperature: str = Field(description="Temperature with unit")
current_time: str = Field(description="Queried current date and time")
# 4. Create agent (one step)
# create_agent parameters:
# model: str | BaseChatModel # Required: chat model
# tools: Sequence[BaseTool] # Tool list; if empty, no tool calling loop
# *,
# system_prompt: str = "" # System prompt
# middleware: Sequence[AgentMiddleware] = () # Middleware
# response_format: ResponseFormat | type | dict | None = None # Structured output
# interrupt_before: list[str] | None = None # Pause before certain tools (human-in-the-loop)
# interrupt_after: list[str] | None = None # Pause after certain tools
# debug: bool = False # Debug mode
# name: str | None = None # Agent name (for tracing)
agent = create_agent(
model=model,
tools=[get_weather, get_current_time],
system_prompt="You are a concise, helpful assistant.",
middleware=(),
response_format=ToolStrategy(WeatherAnswer),
interrupt_before=None,
interrupt_after=None,
debug=False,
name="test01_agent",
)
# 5. Invoke: one sentence triggers both tools, finally returns structured result per Schema
result = agent.invoke({
"messages": [{"role": "user", "content": "How's the weather in Beijing? What time is it now?"}]
})
for msg in result["messages"]:
if getattr(msg, "tool_calls", None):
print("Tool call:", [call["name"] for call in msg.tool_calls])
elif getattr(msg, "type", None) == "tool":
print("Tool result:", msg.content)
answer = result["structured_response"]
print("Structured output:", answer)
print("Access by field:", answer.city, answer.weather, answer.temperature, answer.current_time)
## 7. Learning Path Recommendations
- Get the simplest creation working: use `create_agent` + one tool + `invoke`, confirm the assistant can properly call tools
- Go to LangSmith and look at the trace tree: find the model decision node and tool execution node, compare against the Tool Calling loop you learned
- Add `response_format=ToolStrategy(Schema)`: observe what returns as `structured_response`, and what new node appears in the trace tree
- Switch to `stream_events`: experience streaming output, observe the incremental output of `message.text`
- Combine them: let the assistant return a structured result while streaming output
The "intelligence" of an intelligent assistant comes from the model, but usability comes from the Harness. When you define tools clearly, constrain the output structure, and polish the streaming experience, the assistant becomes truly usable.