Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

LangChain create_agent() Function

LangChain create_agent() Function

create_agent() is the core function for creating AI agents in LangChain 1.x.

It can combine a language model, tools, system prompts, and middleware to create an agent that can automatically call tools and execute tasks in a loop.

Unlike ordinary model calls, an agent can not only answer questions but also call Python functions and read external data as needed by the task, and decide the next action based on the results returned by the tools.

In LangChain 1.x,create_agent() It builds and compiles the agent execution graph based on LangGraph, supporting features such as state management, streaming output, structured responses, runtime context, and session persistence.

This section will provide a complete introduction to the create_agent() parameters and common methods, and use the DeepSeek Flash model for demonstration.


1. How create_agent() Works

Use create_agent() The created agent typically runs according to the following flow:

用户输入

    |

    v

  Model 节点

    |

    | 模型是否发起工具调用?

    |

    +-- 否 --> 返回最终结果

    |

    +-- 是

          |

          v

       Tools 节点

          |

          | 执行工具

          | 将结果加入消息历史

          |

          v

       Model 节点

          |

          | 继续判断是否调用工具

          v

        ...

Where:

An agent generally continues executing until the model no longer requests tools or another stop condition is triggered.

Therefore,create_agent() What is created is not a simple chat model, but an application component with execution flow and state management capabilities.


2. Installation and Environment Setup

This tutorial uses LangChain 1.x and uses DeepSeek as the main model provider.

Install dependencies:

pip install -U langchain langchain-deepseek langgraph python-dotenv pydantic

Create a in the current project directory .env File:

DEEPSEEK_API_KEY=your_deepseek_api_key

Python program via load_dotenv() load the secret key.

Create Your First Agent

Example

from

dotenv

import

load_dotenv

from

langchain.

agents

import

create_agent

load_dotenv

(

)

agent

=

create_agent

(

    model

=

"deepseek:deepseek-flash"

,

    tools

=

[

]

,

    system_prompt

=

"You are a Chinese programming assistant."

)

result

=

agent.

invoke

(

{

   

"messages"

:

[

       

{

           

"role"

:

"user"

,

           

"content"

:

"What is Python?"

       

}

   

]

}

)

print

(

result

[

"messages"

]

[

1

]

.

content

)

No tools are configured for the agent here, so it mainly generates answers through the model.

Although there are no tools,create_agent() an executable LangGraph object is still returned.

**Note:** Currently recommended model names for DeepSeek include deepseek-flash and deepseek-v4-pro. New tutorials no longer use the old deepseek-v4-flash as the default model name.


3. create_agent() Function Syntax

According to the official LangChain API Reference, the function syntax is as follows:

from langchain.agents import create_agent



agent = create_agent(

    model,

    tools=None,

    *,

    system_prompt=None,

    middleware=(),

    response_format=None,

    state_schema=None,

    context_schema=None,

    checkpointer=None,

    store=None,

    interrupt_before=None,

    interrupt_after=None,

    debug=False,

    name=None,

    cache=None,

    transformers=None,

)

Parameter Description:

Parameters Description Default value
model Model name string or BaseChatModel instance Required
tools List of tools, supporting executable tools, functions, and supported provider tool definitions None
system_prompt System prompt, which can be a string or SystemMessage None
middleware List of agent middleware ()
response_format Structured output schema or strategy None
state_schema Custom state structure extending AgentState None
context_schema Runtime Context structure None
checkpointer Checkpointer component that saves and restores session state None
store Store for sharing data across sessions None
interrupt_before Specify which graph nodes to pause before execution None
interrupt_after Specify which graph nodes to pause after execution None
debug Whether to output graph execution debug information False
name Name of the compiled agent graph None
cache LangGraph graph execution cache configuration None
transformers Register additional stream event transformers for the graph None

For beginners, the most commonly used are model、tools and system_prompt。

When building complex agents, gradually use middleware、response_format、checkpointer and other advanced parameters.


4. model Parameter: Specifying the Language Model

model is a required parameter and mainly supports two forms:

Method 1: Pass the Model Name Directly

Example

from

langchain.

agents

import

create_agent

agent

=

create_agent

(

    model

=

"deepseek:deepseek-flash"

,

    tools

=

[

]

,

    system_prompt

=

"You are the programming assistant of Runoob Tutorial RUNOOB."

)

This approach is simple and direct; LangChain selects the corresponding provider based on the model name and initializes the model.

It is recommended to explicitly use:

provider:model

For example:

deepseek:deepseek-flash

deepseek:deepseek-v4-pro

openai:gpt-4o-mini

In actual use, you need to install the corresponding provider integration package and configure the API Key.

Method 2: Pass an Initialized Model

Example

from

langchain.

agents

import

create_agent

from

langchain.

chat_models

import

init_chat_model

Initialize the model and configure parameters

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

,

    max_tokens

=

500

,

    timeout

=

30

,

    max_retries

=

2

)

agent

=

create_agent

(

    model

=

model

,

    tools

=

[

]

,

    system_prompt

=

"You are the programming assistant of Runoob Tutorial RUNOOB."

)

This approach is suitable for scenarios that need to configure model timeouts, number of retries, output limits, or reuse a model instance.

**Note:** It is not recommended to call create_agent() yourself before passing it to model.bind_tools()。

because the agent manages tool binding based on its tool list and runtime strategy. Pre-binding tools may conflict with the agent's tool registration or dynamic tool management mechanism.


5. tools Parameter: Registering Agent Tools

tools Used to specify which tools the agent can call.

The main officially supported types include:

A special distinction needs to be made:A tool's argument schema is not the same as the tool's actual execution logic.

Method 1: Using the @tool Decorator

Example

from

langchain.

tools

import

tool

from

langchain.

agents

import

create_agent

@

tool

def

search_course

(

keyword

:

str

)

str

:

   

"""Search mock programming courses by keyword."""

    courses

=

{

       

"python"

:

"Python Basics, Python Data Analysis"

,

       

"java"

:

"Java Fundamentals, Java Object-Oriented"

   

}

   

return

courses.

get

(

       

keyword

.

lower

(

)

,

       

"No relevant mock courses found"

   

)

agent

=

create_agent

(

    model

=

"deepseek:deepseek-flash"

,

    tools

=

[

search_course

]

,

    system_prompt

=

(

       

"You are a programming learning assistant."

       

"Course data is for teaching simulation only."

       

"Use the tool when you need to query courses."

   

)

)

This approach is suitable for most tool definition scenarios.

The model can see the tool name, description, and argument schema, and decides whether to request a tool call.

Method 2: Using an Ordinary Python Function

LangChain can also accept Python functions with appropriate signatures and descriptions.

Example

from

langchain.

agents

import

create_agent

def

calculate_sum

(

a:

int

,

b:

int

)

int

:

   

"""Calculate the sum of two integers."""

   

return

a + b

agent

=

create_agent

(

    model

=

"deepseek:deepseek-flash"

,

    tools

=

[

calculate_sum

]

)

result

=

agent.

invoke

(

{

   

"messages"

:

[

       

{

           

"role"

:

"user"

,

           

"content"

:

"Please use the tool to calculate 125 + 375."

       

}

   

]

}

)

print

(

result

[

"messages"

]

[

1

]

.

content

)

The function here does not need to manually add @tool; the agent creation process can convert it into an executable tool.

Method 3: Provider-Native Tools

create_agent() Native tool definitions from certain model providers are also supported.

Such tools may be executed by the model service side rather than by local Python functions.

However, their dictionary structure is determined by the specific provider.

**Note:** You cannot simply pass an arbitrary MCP server description dictionary directly to toolsand assume LangChain will automatically connect to the MCP server.

If you need to access MCP tools, you should use a compatible MCP integration or adapter to convert remote tools into tool definitions usable by the agent, and complete the corresponding connection, authentication, and execution configuration.

tools=None: No Tools Used

Example

from

langchain.

agents

import

create_agent

agent

=

create_agent

(

    model

=

"deepseek:deepseek-flash"

,

    tools

=

None

,

    system_prompt

=

"You are a Python programming assistant."

)

result

=

agent.

invoke

(

{

   

"messages"

:

[

       

{

           

"role"

:

"user"

,

           

"content"

:

"Is Python suitable for beginners?"

       

}

   

]

}

)

print

(

result

[

"messages"

]

[

1

]

.

content

)

When no tools are passed, the agent does not execute the ordinary client tool call loop.

But it is still a compiled LangGraph object, which is not exactly the same as directly calling model.invoke() and getting its return structure.


6. system_prompt Parameter: System Instructions

system_prompt Used to define the agent's role, task objectives, and answer rules.

Supports strings and SystemMessage object.

Method 1: String

agent = create_agent(

    model="deepseek:deepseek-flash",

    tools=[],

    system_prompt=(

        "你是Runoob Tutorial RUNOOB 的编程助手。"

        "请使用简洁、准确的中文回答。"

    )

)

Method 2: SystemMessage

Example

from

langchain.

messages

import

SystemMessage

from

langchain.

agents

import

create_agent

system_message

=

SystemMessage

(

    content

=

(

       

"You are a Python programming tutorial author."

       

"Try to use language that beginners can understand."

   

)

)

agent

=

create_agent

(

    model

=

"deepseek:deepseek-flash"

,

    tools

=

[

]

,

    system_prompt

=

system_message

)

The system prompt is usually added to the front of the message list during a model call.

If you need to dynamically generate the system prompt based on the user, session, or task, you can use Middleware.

**Note:** A system prompt is not a reliable security boundary. Authentication, user permissions, and tool execution restrictions still need to be implemented in the application code.


7. middleware Parameter: Agent Middleware

middleware is an important extension mechanism for LangChain 1.x agents.

It can run custom logic at specific stages of the agent execution process.

For example:

The official provides a variety of middleware that can be used directly.

Example: Limiting the Number of Model Calls

Example

from

langchain.

agents

import

create_agent

from

langchain.

agents

.

middleware

import

(

    ModelCallLimitMiddleware

)

agent

=

create_agent

(

    model

=

"deepseek:deepseek-flash"

,

    tools

=

[

]

,

    middleware

=

[

        ModelCallLimitMiddleware

(

            run_limit

=

5

,

            exit_behavior

=

"end"

       

)

   

]

,

    system_prompt

=

"You are a Chinese programming assistant."

)

result

=

agent.

invoke

(

{

   

"messages"

:

[

       

{

           

"role"

:

"user"

,

           

"content"

:

"Explain what a Python decorator is."

       

}

   

]

}

)

print

(

result

[

"messages"

]

[

1

]

.

content

)

Here, the following is used ModelCallLimitMiddleware Limit the number of model calls in a single run.

Note that a model call limit is not the same as a token budget or an API cost cap.

Middleware can also implement more complex behaviors through before_model、after_model、wrap_model_call and wrap_tool_call and other mechanisms.


8. response_format Parameter: Structured Output

If you want the agent to return data in a specific format, you can use response_format。

For example, have the agent return tutorial recommendation results, including recommended courses and reasons.

LangChain supports Pydantic models, as well as ProviderStrategy、ToolStrategy and other structured output strategies.

Example: Defining a Structure with Pydantic

Example

from

pydantic

import

BaseModel

,

Field

from

langchain.

agents

import

create_agent

class

CourseRecommendation

(

BaseModel

)

:

   

"""Course recommendation result."""

    course:

str

=

Field

(

        description

=

"Recommended course name"

   

)

    reason:

str

=

Field

(

        description

=

"Reason for recommendation"

   

)

agent

=

create_agent

(

    model

=

"deepseek:deepseek-flash"

,

    tools

=

[

]

,

    response_format

=

CourseRecommendation

,

    system_prompt

=

(

       

"You are a programming learning advisor."

       

"Please return course recommendations based on the user's question."

   

)

)

result

=

agent.

invoke

(

{

   

"messages"

:

[

       

{

           

"role"

:

"user"

,

           

"content"

:

(

               

"I am a developer with zero basics, "

               

"and I want to learn Python. Please give me a recommendation."

           

)

       

}

   

]

}

)

structured

=

result

[

"structured_response"

]

print

(

"Course:"

,

structured.

course

)

print

(

"Reason:"

,

structured.

reason

)

If structured output succeeds, the returned state will contain:

result["structured_response"]

This field usually stores the result parsed according to the specified schema.

For example:

{

    "course": "Python 基础教程",

    "reason": "适合初学者了解 Python 的基本语法。"

}

What is shown here is an illustration of the result structure, not a fixed output of the model.

**Note:** Different models may have different support for native structured output, Tool Calling, and JSON Schema.

LangChain can select a structured output strategy based on model capabilities, but does not guarantee success with any model and any schema.


9. state_schema Parameter: Custom Agent State

An agent saves state during execution.

The most common state field is:

messages

Used to store user messages, model replies, and tool execution results.

AgentState may also contain fields related to execution control or structured responses, depending on the current LangChain version.

If you need to store additional application state, you can extend AgentState。

For example, create a learning assistant that records the current user level and completed topics.

1. Define a Custom State

Example

from

langchain.

agents

import

AgentState

class

LearningAgentState

(

AgentState

)

:

   

"""Programming learning agent state."""

    user_level:

str

    completed_topics:

list

[

str

]

Where:

But merely declaring state fields does not mean these fields will be automatically updated after tool execution.

2. Modifying State Using Command

If a tool needs to modify the agent state, it can return LangGraph's Command。

You should not only perform runtime.state on the list in append()and assume the state has been correctly submitted.

Example

from

langchain.

agents

import

AgentState

from

langchain.

messages

import

ToolMessage

from

langchain.

tools

import

tool

,

ToolRuntime

from

langgraph.

types

import

Command

class

LearningAgentState

(

AgentState

)

:

    user_level:

str

    completed_topics:

list

[

str

]

@

tool

def

track_progress

(

    topic:

str

,

    runtime: ToolRuntime

)

Command:

   

"""Add the specified topic to the current completed list."""

    completed

=

list

(

        runtime.

state

.

get

(

           

"completed_topics"

,

[

]

       

)

   

)

   

if

topic

not

in

completed:

        completed.

append

(

topic

)

   

return

Command

(

        update

=

{

           

"completed_topics"

: completed

,

           

"messages"

:

[

                ToolMessage

(

                    content

=

(

                        f

"Processed learning topic: {topic}"

                   

)

,

                    tool_call_id

=

runtime.

tool_call_id

               

)

           

]

       

}

   

)

The above uses Command(update=...) to explicitly declare the state fields to be updated.

ToolMessage Associated with the model's tool request via the current tool call ID.

3. Create the Agent and Read the Updated State

Example

from

dotenv

import

load_dotenv

from

langchain.

agents

import

create_agent

load_dotenv

(

)

agent

=

create_agent

(

    model

=

"deepseek:deepseek-flash"

,

    tools

=

[

track_progress

]

,

    state_schema

=

LearningAgentState

,

    system_prompt

=

(

       

"You are a learning progress assistant."

       

"When the user explicitly asks to record a completed topic, "

       

"call the track_progress tool."

   

)

)

result

=

agent.

invoke

(

{

   

"messages"

:

[

       

{

           

"role"

:

"user"

,

           

"content"

:

(

               

"I have finished learning Python basics, "

               

"please help me record this topic."

           

)

       

}

   

]

,

   

"user_level"

:

"Beginner"

,

   

"completed_topics"

:

[

       

"HTML basics"

   

]

}

)

print

(

"User level: "

,

result.

get

(

"user_level"

)

)

print

(

"Completed topics: "

,

result.

get

(

"completed_topics"

)

)

print

(

"Final answer: "

)

print

(

result

[

"messages"

]

[

1

]

.

content

)

If the model correctly calls track_progressthe updated state might be:

用户等级: 入门

已完成主题: ['HTML 基础', 'Python 基础']

Since whether a tool is called is determined by the model, you cannot assume this result will necessarily occur.

If learning progress must be updated, you should explicitly perform the state change at the application layer, or set a mandatory execution step in the workflow.

**Note:** The above approach applies to relatively simple state updates. If multiple tools write to the same field in parallel, you need to consider an appropriate reducer or concurrency control to avoid state update conflicts.


10. context_schema Parameter: Runtime Context

context_schema Used to define the structure of the agent's runtime Context.

Unlike State, Context is usually provided by the application on each call to store trusted information needed for the current run.

For example:

Example: Passing the Current User Identity

Example

from

dataclasses

import

dataclass

from

langchain.

agents

import

create_agent

from

langchain.

tools

import

tool

,

ToolRuntime

@

dataclass

class

UserContext:

    user_id:

str

@

tool

def

get_current_user

(

    runtime: ToolRuntime

[

UserContext

]

)

str

:

   

"""Return the mock user identifier for the current request."""

   

return

runtime.

context

.

user_id

agent

=

create_agent

(

    model

=

"deepseek:deepseek-flash"

,

    tools

=

[

get_current_user

]

,

    context_schema

=

UserContext

,

    system_prompt

=

(

       

"You are a user information assistant."

       

"Use the tool when querying the current user identifier."

   

)

)

result

=

agent.

invoke

(

   

{

       

"messages"

:

[

           

{

               

"role"

:

"user"

,

               

"content"

:

"Query my user identifier."

           

}

       

]

   

}

,

    context

=

UserContext

(

        user_id

=

"user_001"

   

)

)

print

(

result

[

"messages"

]

[

1

]

.

content

)

Here, user_id Provided by the application, not a tool argument generated by the model.

**Note:** Context is only a mechanism for passing runtime information and does not automatically complete user authentication. In real projects, you should first verify the user's login status and then build a trusted Context.


11. checkpointer Parameter: Session Persistence

If you want the agent to remember previous conversations, you can configure checkpointer。

Checkpointer is responsible for saving and restoring the agent's execution state.

LangGraph provides a suitable for development and testing InMemorySaver。

Example: Saving a Multi-turn Conversation

Example

from

langchain.

agents

import

create_agent

from

langgraph.

checkpoint

.

memory

import

InMemorySaver

agent

=

create_agent

(

    model

=

"deepseek:deepseek-flash"

,

    tools

=

[

]

,

    checkpointer

=

InMemorySaver

(

)

,

    system_prompt

=

"You are a programming learning assistant."

)

Using the Same Thread ID

config

=

{

   

"configurable"

:

{

       

"thread_id"

:

"learning_session_001"

   

}

}

First Round

agent.

invoke

(

   

{

       

"messages"

:

[

           

{

               

"role"

:

"user"

,

               

"content"

:

"I'm learning Python."

           

}

       

]

   

}

,

    config

=

config

)

Second Round

result

=

agent.

invoke

(

   

{

       

"messages"

:

[

           

{

               

"role"

:

"user"

,

               

"content"

:

"What did I just say I was learning?"

           

}

       

]

   

}

,

    config

=

config

)

print

(

result

[

"messages"

]

[

1

]

.

content

)

Since both requests use the same thread_idthe agent can restore previous session messages from the Checkpointer.

Note thatInMemorySaver Only saves in-process data.

After the program exits, in-memory session state is usually lost.

For production projects that require true persistence, you can use a database-backed Checkpointer.

get_state(): Viewing the Saved State

After configuring a Checkpointer, you can use get_state() to get a state snapshot for a specified thread.

snapshot = agent.get_state(config)



print(snapshot.values)

Wheresnapshot.values Saves the currently recorded state data.

If no Checkpointer is configured or there is no corresponding thread record, you cannot assume get_state() will necessarily return a valid historical state.

update_state(): Updating the Saved State

You can also use:

agent.update_state(

    config,

    {

        "user_level": "进阶"

    }

)

to modify fields supported by the state schema.

Note:update_state() is a graph state management operation, not simply modifying an ordinary Python dictionary. Before use, you should confirm that the graph is configured with an appropriate checkpointer and understand the state merging and reducer rules.


12. store Parameter: Sharing Data Across Sessions

store Used to provide a LangGraph Store to the agent.

Unlike Checkpointer, Store is mainly used to share data across threads or sessions.

For example:

During development, you can use InMemoryStore。

Example: Creating a Shared Store

Example

from

langchain.

agents

import

create_agent

from

langgraph.

store

.

memory

import

InMemoryStore

store

=

InMemoryStore

(

)

Save mock course data

store.

put

(

   

(

"demo"

,

"courses"

)

,

   

"python"

,

   

{

       

"name"

:

"Python Basics"

,

       

"level"

:

"Beginner"

   

}

)

agent

=

create_agent

(

    model

=

"deepseek:deepseek-flash"

,

    tools

=

[

]

,

    store

=

store

)

Directly View Store Data

item

=

store.

get

(

   

(

"demo"

,

"courses"

)

,

   

"python"

)

print

(

item.

value

)

Execution result:

{'name': 'Python 基础', 'level': '入门'}

When a tool needs to access the Store, it can be used together with the ToolRuntime, using runtime.store introduced in the previous section to read data.

Note:InMemoryStore Data can be shared across calls within the same process, but it is not a database-level persistent store.


13. interrupt_before and interrupt_after

These two parameters are used to control LangGraph to pause before or after the execution of specified nodes.

Common nodes include:

model

tools

For example, you can pause before tool execution to let the program inspect the tool call request.

Example: Interrupting Before Tool Execution

Example

from

langchain.

agents

import

create_agent

from

langchain.

tools

import

tool

from

langgraph.

checkpoint

.

memory

import

InMemorySaver

@

tool

def

delete_demo_file

(

filename:

str

)

str

:

   

"""Simulate deleting a file without performing an actual file operation."""

   

return

f

"Simulating file deletion: {filename}"

agent

=

create_agent

(

    model

=

"deepseek:deepseek-flash"

,

    tools

=

[

delete_demo_file

]

,

    checkpointer

=

InMemorySaver

(

)

,

    interrupt_before

=

[

"tools"

]

,

    system_prompt

=

(

       

"You are a file operation demonstration assistant."

       

"Use the tool when the user asks to simulate deleting a file."

       

"All operations are simulated."

   

)

)

config

=

{

   

"configurable"

:

{

       

"thread_id"

:

"demo_delete_001"

   

}

}

result

=

agent.

invoke

(

   

{

       

"messages"

:

[

           

{

               

"role"

:

"user"

,

               

"content"

:

"Please simulate deleting report.txt"

           

}

       

]

   

}

,

    config

=

config

)

Check whether there are nodes pending to continue execution

snapshot

=

agent.

get_state

(

config

)

print

(

"Pending nodes: "

,

snapshot.

next

)

If the model initiates a tool call, the graph may pause before the tools node executes.

At this point, you can inspect the tool call request in the state.

**Note:** Setting an interrupt does not mean approval is automatically completed. For sensitive actions such as real file deletion or financial operations, you need to complete reliable human confirmation and permission checks before resuming graph execution.

If you need to continue executing a paused graph, you should follow LangGraph's resume mechanism and use the same session configuration.


14. debug, name, cache, and transformers

These parameters are mainly used for debugging, integration, and extending the execution graph.

debug: Enable Debug Output

agent = create_agent(

    model="deepseek:deepseek-flash",

    tools=[],

    debug=True

)

When debugging is enabled, LangGraph can output information such as node execution, state updates, and graph flow.

Debug output may contain user input and tool results, so production environments should pay attention to sensitive data in logs.

name: Specify the Agent Name

agent = create_agent(

    model="deepseek:deepseek-flash",

    tools=[],

    name="runoob_learning_agent"

)

The name helps identify the execution graph and is also useful when using the agent as a subgraph in other LangGraph workflows.

cache: Graph Execution Cache

cache Used to configure LangGraph's graph execution caching capability.

It is not the same as automatically caching all large language model API responses.

Whether caching actually occurs may also depend on the configuration of nodes and cache policies.

transformers: Stream Event Transformers

transformers Used to register additional stream event transformers.

It is mainly aimed at developers who need deep customization of the streaming event handling flow.

For ordinary chat agents or tutorial examples, it is usually not necessary to set this.


15. Return Value of create_agent()

create_agent() Returns a CompiledStateGraph object.

This means you can use the synchronous, asynchronous, streaming, and state management interfaces provided by LangGraph.

Method Purpose
invoke() Execute the agent synchronously and wait for the task result
ainvoke() Execute the Agent asynchronously
stream() Get execution results synchronously in a streaming manner
astream() Asynchronous streaming execution
get_state() Read a saved graph state snapshot
update_state() Update graph state
get_state_history() Get supported state history records

1. invoke(): Synchronous Call

Example

result

=

agent.

invoke

(

{

   

"messages"

:

[

       

{

           

"role"

:

"user"

,

           

"content"

:

"What is LangChain?"

       

}

   

]

}

)

print

(

result

[

"messages"

]

[

1

]

.

content

)

This is the most commonly used way to call an agent.

2. ainvoke(): Asynchronous Call

Example

import

asyncio

from

langchain.

agents

import

create_agent

agent

=

create_agent

(

    model

=

"deepseek:deepseek-flash"

,

    tools

=

[

]

)

async

def

main

(

)

:

    result

=

await agent.

ainvoke

(

{

       

"messages"

:

[

           

{

               

"role"

:

"user"

,

               

"content"

:

"Introduce Python."

           

}

       

]

   

}

)

   

print

(

result

[

"messages"

]

[

1

]

.

content

)

if

name

==

"main"

:

    asyncio.

run

(

main

(

)

)

Suitable for asynchronous web services and other applications that use asyncio .

3. stream(): Streaming the Execution Process

Use stream_mode="updates" You can view the agent's node updates.

Example

from

langchain.

agents

import

create_agent

from

langchain.

tools

import

tool

@

tool

def

calculate

(

a:

int

,

b:

int

)

int

:

   

"""Calculate the sum of two integers."""

   

return

a + b

agent

=

create_agent

(

    model

=

"deepseek:deepseek-flash"

,

    tools

=

[

calculate

]

)

for

update

in

agent.

stream

(

   

{

       

"messages"

:

[

           

{

               

"role"

:

"user"

,

               

"content"

:

"Please use the tool to calculate 25 + 18."

           

}

       

]

   

}

,

    stream_mode

=

"updates"

)

:

   

print

(

update

)

If the model calls a tool, the streaming updates may include the execution results of the model node and the tool node.

Note thatstream_mode="updates" It gets graph node state updates, rather than outputting model text token by token.

If you want to display the tokens generated by the model in real time, you should use the corresponding message streaming mode.


16. Complete Example: Course Learning Agent

Next, integrate the model, tools, system prompt, and call flow into a runnable example.

This agent can query mock courses and return learning suggestions based on user questions.

Filename:create_agent_demo.py

Complete example

from

dotenv

import

load_dotenv

from

langchain.

tools

import

tool

from

langchain.

agents

import

create_agent

from

langchain.

chat_models

import

init_chat_model

load_dotenv

(

)

-------------------------

Mock Course Data

-------------------------

COURSES

=

{

   

"python"

:

[

       

"Python Basics Tutorial"

,

       

"Python Data Analysis"

   

]

,

   

"java"

:

[

       

"Java Basics Tutorial"

,

       

"Java Object-Oriented"

   

]

,

   

"html"

:

[

       

"HTML Basics Tutorial"

   

]

}

-------------------------

Define tools

-------------------------

@

tool

def

search_courses

(

keyword

:

str

)

str

:

   

"""Query mock courses by programming language keyword."""

    results

=

COURSES.

get

(

       

keyword

.

lower

(

)

   

)

   

if

not

results:

       

return

"No matching mock course found"

   

return

"、"

.

join

(

results

)

@

tool

def

count_courses

(

keyword

:

str

)

str

:

   

"""Count the number of mock courses for a specified language."""

    results

=

COURSES.

get

(

       

keyword

.

lower

(

)

,

       

[

]

   

)

   

return

(

        f

"{keyword} has a total of "

        f

"{len(results)} mock courses"

   

)

-------------------------

Initialize the model

-------------------------

model

=

init_chat_model

(

   

"deepseek:deepseek-flash"

,

    timeout

=

30

,

    max_retries

=

2

)

-------------------------

Creating the Agent

-------------------------

agent

=

create_agent

(

    model

=

model

,

    tools

=

[

        search_courses

,

        count_courses

   

]

,

    system_prompt

=

(

       

"You are a learning advisor for Runoob Tutorial RUNOOB."

       

"All data in the tools is teaching mock data."

       

"Prefer using tools when querying courses and counts."

       

"If the tools have no corresponding data,"

       

"Do not fabricate course names or counts."

       

"Please answer in concise and accurate Chinese."

   

)

,

    name

=

"runoob_course_agent"

)

-------------------------

Execute Agent

-------------------------

def

ask

(

question:

str

)

:

    result

=

agent.

invoke

(

       

{

           

"messages"

:

[

               

{

                   

"role"

:

"user"

,

                   

"content"

: question

               

}

           

]

       

}

,

        config

=

{

           

"recursion_limit"

:

15

       

}

   

)

   

print

(

"\nQuestion:"

,

question

)

   

for

message

in

result

[

"messages"

]

:

       

Model initiates tool call

       

if

(

            message.

type

==

"ai"

           

and

message.

tool_calls

       

)

:

           

for

call

in

message.

tool_calls

:

               

print

(

                   

"[Tool Call]"

,

                    call

[

"name"

]

,

                    call

[

"args"

]

               

)

       

Tool result

       

elif

message.

type

==

"tool"

:

           

print

(

               

"[Tool result]"

,

                message.

name

,

                message.

content

           

)

   

print

(

       

"Final answer: "

,

        result

[

"messages"

]

[

1

]

.

content

   

)

if

name

==

"main"

:

    ask

(

"What Python mock courses are available?"

)

    ask

(

"How many Java mock courses are there in total?"

)

    ask

(

"Where is a good place to start learning HTML?"

)

Run the program

python create_agent_demo.py

If the Agent correctly calls the corresponding tools, it can obtain mock course data:

Python 模拟课程:

Python 基础教程、Python 数据分析



Java simulation course count:

2 门



HTML Simulation Course:

HTML 基础教程

The actual number of tool calls, execution order, and language model responses may differ.

The course data shown here comes from a Python dictionary and does not access the real course database of Runoob Tutorial.


17. Frequently Asked Questions

1. What is the difference between create_agent() and init_chat_model()?

init_chat_model() Used to create a chat model object.

create_agent() adds capabilities such as tool calling, execution loops, state management, and middleware on top of the model.

The former mainly handles model initialization, while the latter mainly handles Agent execution.

2. Can tools be omitted?

can.

When tools=None or is an empty list, the Agent has no executable client-side tool call loop.

But you can still use system prompts and other supported execution graph features.

3. Does create_agent() execute tools automatically?

For registered executable client-side tools, the Agent can execute them based on tool call requests generated by the model.

But whether tools are called is still determined jointly by the model and the Agent configuration.

Provider-native tools may be executed by the remote model service and should not be confused with local Python tools.

4. Why can't a Pydantic class be used directly as a tool?

Pydantic classes are mainly used to define data structures and parameter schemas.

They do not necessarily provide the tool's execution logic themselves.

If you want the Agent to perform Python operations, you should use @tool, callable functions, or other tool objects that implement an execution interface.

5. Why isn't the list in state_schema updated?

Because reading the state or directly modifying the state dictionary does not equal submitting a state update to the graph.

If a tool needs to update a custom State, it should use a supported state update mechanism, such as returning Command。

6. Why doesn't result["structured_response"] exist?

Usually because there is no response_format, or the structured output process did not complete successfully.

If you need structured results, configure the output schema correctly and confirm that the current model supports the required structured output strategy.

7. How can the Agent remember previous conversations?

You can configure a Checkpointer and use the same thread_id。

If you need to restore records after a program restart, use a database-backed Checkpointer.

8. What is the difference between store and checkpointer?

checkpointer Used to save and restore conversation state.

store Used to share data across threads or sessions, such as user preferences and long-term learning progress.

The two serve different purposes and cannot simply replace each other.

9. Does interrupt_before=["tools"] automatically implement human approval?

No.

It only provides a pause mechanism before the tool node executes.

Actual approval requires the application to read pending operations, check permissions, and decide whether to resume.

10. How can you limit the number of Agent executions?

At runtime, you can use recursion_limit to limit the number of graph execution steps:

result = agent.invoke(

    {

        "messages": [

            {

                "role": "user",

                "content": "你好"

            }

        ]

    },

    config={

        "recursion_limit": 15

    }

)

Note thatrecursion_limit It is not a strict limit on the number of tool calls, nor a cap on Token costs.

If you need to limit the number of model calls, consider using LangChain middleware.

11. Can create_agent() connect to MCP?

You can provide remote MCP tools to the Agent through compatible MCP integrations or adapters.

But you cannot assume that any MCP configuration dictionary can be passed directly to tools and automatically complete the remote connection and tool execution.

12. When should you use LangGraph instead of create_agent()?

If you only need the model to automatically select tools, process results, and loop,create_agent() is usually sufficient.

If a task requires explicit node ordering, complex branching, multiple Agents collaborating, or strict execution control, you can use LangGraph to build a custom workflow.

create_agent() itself is implemented based on LangGraph.


Summary

create_agent() It is the core entry point for creating an Agent in LangChain 1.x.

The simplest usage only requires specifying a model and tools:

from langchain.agents import create_agent



agent = create_agent(

    model="deepseek:deepseek-flash",

    tools=[]

)



result = agent.invoke({

    "messages": [

        {

            "role": "user",

            "content": "你好"

        }

    ]

})

As project complexity grows, you can gradually configure:

Note:create_agent() is responsible for organizing the Agent's execution flow, the model is responsible for making tool call requests, tools are responsible for actually performing operations, while State and Middleware help manage the entire execution process.