LangChain create_agent() Function

create_agent() is the core function of LangChain. It creates a complete Agent graph (StateGraph), including all logic such as model invocation, tool execution, and loop control.

Syntax

The syntax of the create_agent() function is as follows:

from langchain.agents import create_agent

agent = create_agent(
    model,                     # str | BaseChatModel:语言模型
    tools=None,                # Sequence:工具列表
    *,
    system_prompt=None,        # str | SystemMessage:系统提示
    middleware=(),             # Sequence[AgentMiddleware]:中间件列表
    response_format=None,      # ResponseFormat | type:结构化输出配置
    state_schema=None,         # type[AgentState]:自定义状态结构
    context_schema=None,       # type:运行时上下文结构
    checkpointer=None,         # Checkpointer:对话持久化
    store=None,                # BaseStore:跨会话存储
    interrupt_before=None,     # list[str]:在哪些节点前暂停
    interrupt_after=None,      # list[str]:在哪些节点后暂停
    debug=False,               # bool:是否输出详细日志
    name=None,                 # str:Agent 名称
    cache=None,                # BaseCache:缓存配置
)

model Parameter - Model Configuration

The model parameter accepts two forms: a string (processed by init_chat_model()) or an already constructed BaseChatModel instance.

Example

from langchain.agents import create_agent
from langchain.chat_models import init_chat_model

# Method 1: Pass a string (most common)
# create_agent internally calls init_chat_model() for processing
agent = create_agent(
    model="deepseek:deepseek-v4-flash",
    system_prompt="You are the assistant of EXAMPLE",
)

# Method 2: Pass an already constructed model instance
# Suitable for scenarios where you need fine-grained control over model parameters
model = init_chat_model("deepseek:deepseek-v4-flash", temperature=0.3, max_tokens=500)
agent = create_agent(
    model=model,
    system_prompt="You are the assistant of EXAMPLE",
)

# Method 3: Pass a model instance with tools already bound
# Less common; usually let create_agent handle tool binding itself
model_with_tools = init_chat_model("deepseek:deepseek-v4-flash").bind_tools([...])

Method 1 (passing a string) is recommended. create_agent() automatically handles model initialization, tool binding, structured output, and other logic internally. Method 2 is suitable for scenarios where you need to use the same model instance outside the Agent.

tools Parameter - Tool List

The tools parameter accepts tools in three formats:

Example

from langchain.tools import tool
from langchain.agents import create_agent

# Format 1: A function decorated with @tool (most common)
@tool
def search_course(keyword: str) -> str:
    """Search EXAMPLE courses"""
    return f"Search results: {keyword} related courses"


# Format 2: A Pydantic BaseModel class
from pydantic import BaseModel, Field

class WeatherQuery(BaseModel):
    """Query weather"""
    city: str = Field(description="City name")


# Format 3: A dictionary (describing remote tools or built-in tools)
mcp_tool = {
    "type": "mcp",
    "server_label": "weather_server",
    "server_url": "https://weather.example.com/sse",
    "allowed_tools": ["get_forecast"],
}

# Mixed usage
agent = create_agent(
    model="deepseek:deepseek-v4-flash",
    tools=[search_course, WeatherQuery, mcp_tool],
)

Passing None or an empty list means the Agent has no tools available; in this case, it is simply a pure conversation model:

Example

from langchain.agents import create_agent
from langchain.messages import HumanMessage

# Agent without tools - equivalent to directly calling the model
agent = create_agent(
    model="deepseek:deepseek-v4-flash",
    tools=None,
    system_prompt="You are the assistant of EXAMPLE",
)

result = agent.invoke({
    "messages": [HumanMessage(content="Is Python suitable for complete beginners?")]
})
print(result["messages"][-1].content)

system_prompt Parameter - System Prompt

Defines the Agent's behavioral role and constraint rules. Supports strings and SystemMessage objects.

Example

from langchain.agents import create_agent
from langchain.messages import SystemMessage

# Method 1: String (simple and direct)
agent = create_agent(
    model="deepseek:deepseek-v4-flash",
    system_prompt="You are the learning consultant of EXAMPLE. Keep answers concise, no more than 100 characters.",
)

# Method 2: SystemMessage object (can be reused across multiple Agents)
system_msg = SystemMessage(
    content="You are the learning consultant of EXAMPLE. Keep answers concise, no more than 100 characters."
)
agent = create_agent(
    model="deepseek:deepseek-v4-flash",
    system_prompt=system_msg,
)

system_prompt is optional, but if not provided, the model will respond in the role of a "general-purpose assistant". For applications with clear business scenarios, it is recommended to always set system_prompt to constrain the model's behavior boundaries.

state_schema Parameter - Custom State

The default AgentState only includes messages, jump_to, and structured_response. If you need additional state fields, you can extend it:

Example

from typing import Annotated
from langchain.agents import create_agent, AgentState
from langchain.messages import HumanMessage
from langchain.tools import tool, InjectedState
from typing_extensions import TypedDict


# Extend AgentState and add custom fields
class LearningAgentState(AgentState):
    """Custom state, adding fields related to learning progress"""
    user_level: str                       # User level
    completed_topics: list[str]           # List of completed topics


@tool
def track_progress(
    topic: str,
    state: Annotated[dict, InjectedState],
) -> str:
    """Record the user's learning progress.

    Args:
topic: The name of the topic just completed
    """

    completed = state.get("completed_topics", [])
    completed.append(topic)
    return (
        f"Learning progress recorded. Currently completed {len(completed)} topics:"
        f"{', '.join(completed)}"
    )


agent = create_agent(
    model="deepseek:deepseek-v4-flash",
    tools=[track_progress],
    state_schema=LearningAgentState,  # Using custom state
    system_prompt="You are the learning assistant of EXAMPLE.",
)

# The initial value of the custom state must be provided at runtime
result = agent.invoke({
    "messages": [HumanMessage(content="I have finished learning Python basics. Please record it for me.")],
    "user_level": "Beginner",
    "completed_topics": ["HTML Basics"],
})

print(f"User level: {result.get('user_level')}")
print(f"Completed topics: {result.get('completed_topics')}")
print(f"Reply: {result['messages'][-1].content[:100]}")

Output:

User level: 入门
Completed topics: ['HTML 基础', 'Python 基础']
Reply: Learning progress recorded. Completed 2 topics: HTML Basics, Python Basics

Return Value - CompiledStateGraph

create_agent() returns aCompiledStateGraphobject, which is the compiled graph of LangGraph and provides multiple ways to run:

MethodDescriptionUse Case
invoke(input, config)Synchronous run, wait for the complete resultScripts, simple interfaces
ainvoke(input, config)Asynchronous run, wait for the complete resultWeb services
stream(input, config, stream_mode)Synchronous streaming runDisplay intermediate steps in real time
astream(input, config, stream_mode)Asynchronous streaming runWebSocket、SSE
get_state(config)Get the current stateView/restore conversation state
update_state(config, values)Update stateManually modify conversation state
Other extensions