YouTip LogoYouTip

Langchain Create_Agent

LangChain create_agent() Function | Online Tutorial

create_agent() is the most core function in LangChain. It creates a complete Agent graph (StateGraph), including all logic for model calls, tool execution, loop control, etc.

Syntax

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

from langchain.agents import create_agent
agent = create_agent(
    model,  # str | BaseChatModel: Language model
    tools=None,  # Sequence: List of tools
    *, 
    system_prompt=None,  # str | SystemMessage: System prompt
    middleware=(),  # Sequence: List of middleware
    response_format=None,  # ResponseFormat | type: Structured output configuration
    state_schema=None,  # type: Custom state structure
    context_schema=None,  # type: Runtime context structure
    checkpointer=None,  # Checkpointer: Conversation persistence
    store=None,  # BaseStore: Cross-session storage
    interrupt_before=None,  # list: Pause before which nodes
    interrupt_after=None,  # list: Pause after which nodes
    debug=False,  # bool: Whether to output detailed logs
    name=None,  # str: Agent name
    cache=None,  # BaseCache: Cache configuration
)

model Parameter β€” Model Configuration

model can accept two forms: a string (processed by init_chat_model()) or a pre-built BaseChatModel instance.

Example

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

# Method 1: Pass string (most commonly used)
# create_agent will internally call init_chat_model() to process it
agent = create_agent(
    model="deepseek:deepseek-v4-flash",
    system_prompt="You are the assistant of Online Tutorial",
)

# Method 2: Pass pre-built model instance
# Suitable for scenarios requiring fine-grained control of 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 Online Tutorial",
)

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

Method 1 (passing string) is recommended. create_agent() will automatically handle model initialization, tool binding, structured output, and other logic internally. Method 2 is suitable when you need to use the same model instance outside of the Agent as well.

tools Parameter β€” Tool List

tools accepts tools in three formats:

Example

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

# Format 1: @tool decorated function (most commonly used)
@tool
def search_course(keyword: str) -> str:
    """Search Online Tutorial courses"""
    return f"Search results: {keyword} related courses"

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

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

# Format 3: 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": ,
}

# 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 which case it is just a pure conversational model:

Example

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

# Tool-less Agent β€” equivalent to directly calling the model
agent = create_agent(
    model="deepseek:deepseek-v4-flash",
    tools=None,
    system_prompt="You are the assistant of Online Tutorial",
)

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

print(result.content)

system_prompt Parameter β€” System Prompt

Defines the Agent's behavior role and constraint rules. Supports string 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 Online Tutorial. Keep answers concise, no more than 100 words.",
)

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

system_prompt is optional, but if not passed, the model will answer in the role of a "general 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 contains 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, add custom fields
class LearningAgentState(AgentState):
    """Custom state, add learning progress related fields"""
    user_level: str  # User level
    completed_topics: list  # List of completed topics

@tool
def track_progress(
    topic: str,
    state: Annotated[dict, InjectedState],
) -> str:
    """Record user's learning progress.
    Args:
        topic: 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=,
    state_schema=LearningAgentState,  # Use custom state
    system_prompt="You are the learning assistant of Online Tutorial.",
)

# Runtime needs to provide initial values for custom state
result = agent.invoke({
    "messages": [HumanMessage(content="I finished Python basics, please record it for me")],
    "user_level": "Beginner",
    "completed_topics": ,
})

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

Running result:

User level: Beginner
Completed topics: ['HTML Basics', 'Python Basics']
Response: Learning progress recorded. Currently completed 2 topics: HTML Basics, Python Basics

Return Value β€” CompiledStateGraph

create_agent() returns a CompiledStateGraph object, which is LangGraph's compiled graph providing multiple running methods:

← Langchain Agent StateLangchain Tool Advanced β†’

YouTip © 2024-2026 | Home | Learn Technology, Build Dreams!

All content is for educational and learning purposes only.

Method Description Applicable Scenario
invoke(input, config)