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

LangChain Prompts — System Prompt and Dynamic Prompt

LangChain Prompts——System Prompt and Dynamic Prompt

Prompts are an important way to control the behavior of large language models.

In LangChain Agents, the System Prompt is used to define the model's role, responsibilities, answer style, and tool usage rules.

If you need to adjust prompts for different users, tasks, or conversation stages, you can also dynamically generate the system prompt with @dynamic_prompt.

This chapter introduces static and dynamic prompts in LangChain 1.x, demonstrated with the DeepSeek Flash model.


1. Basic usage of System Prompt

create_agent() Pass system_prompt The parameter accepts the system prompt, supporting both strings and SystemMessage two common forms.

Method 1: Using a string

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 learning advisor for Runoob Tutorial RUNOOB; answers should be concise, accurate, and easy to understand."

)

result

=

agent.

invoke

(

{

   

"messages"

:

[

{

"role"

:

"user"

,

"content"

:

"Is Python suitable for beginners with no background?"

}

]

}

)

print

(

result

[

"messages"

]

[

1

]

.

content

)

This method is the simplest, suitable for scenarios where the system prompt is relatively fixed.

Method 2: Using SystemMessage

Example

from

langchain.

agents

import

create_agent

from

langchain.

messages

import

SystemMessage

system_msg

=

SystemMessage

(

content

=

"You are a learning advisor for Runoob Tutorial RUNOOB; answers should be concise and professional."

)

agent

=

create_agent

(

    model

=

"deepseek:deepseek-flash"

,

    tools

=

[

]

,

    system_prompt

=

system_msg

)

SystemMessage is a LangChain message object that can be reused across multiple Agents or model configurations.

Both methods are used to set the system prompt; usually a string is sufficient.

**Note:** The System Prompt can influence model behavior but cannot guarantee the model always follows it strictly. Operations involving permissions, payments, and data access should be validated by the application.


2. How to design an effective System Prompt?

A good system prompt is not necessarily long; the key is to make the model clear about its responsibilities, which tools it can use, and how to handle unknown information.

It can generally contain five parts:

Element Purpose Example
Role definition Describe the AI's identity You are a programming learning advisor
Task responsibilities State what needs to be accomplished Recommend courses, answer learning questions
Tool rules State when to use tools Use search_course when querying courses
Answer guidelines Control language and format Answer in Chinese, keep it concise
Boundary constraints Handle unknown and exceptional cases Do not fabricate when there is no data

Example: Course recommendation assistant

Example

from

langchain.

tools

import

tool

from

langchain.

agents

import

create_agent

@

tool

def

search_course

(

keyword

:

str

)

str

:

   

"""Search mock courses by programming language."""

    courses

=

{

"python"

:

"Python3 Basic Tutorial"

,

"html"

:

"HTML Basics Tutorial"

}

   

return

courses.

get

(

keyword

.

lower

(

)

,

"No relevant mock courses found"

)

GOOD_PROMPT

=

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

Responsibility

Answer rules

agent

=

create_agent

(

    model

=

"deepseek:deepseek-flash"

,

    tools

=

[

search_course

]

,

    system_prompt

=

GOOD_PROMPT

)

result

=

agent.

invoke

(

{

   

"messages"

:

[

{

"role"

:

"user"

,

"content"

:

"I have no background and want to learn Python. What courses are available?"

}

]

}

)

print

(

result

[

"messages"

]

[

1

]

.

content

)

If the model calls the tool correctly, it may answer:

可以先学习 Python3 基础教程,从变量、数据类型和基本语法开始。



这是演示课程数据,实际课程信息请以网站页面为准。

Whether the model calls the tool and the exact wording of the final answer are not fixed.

It is recommended to make prompts as clear as possible and avoid contradictory requirements at the same time, such as requiring both 'detailed explanation' and 'answer in one sentence only'.


3. @dynamic_prompt: Dynamically generating system prompts

A static System Prompt remains relatively fixed across calls, but real applications may need to modify it dynamically based on the current task.

For example:

LangChain provides @dynamic_prompt decorator, which is a type of Middleware that can generate the system prompt used for each model call.

Basic Syntax

from langchain.agents.middleware import dynamic_prompt, ModelRequest



@dynamic_prompt

def my_prompt(request: ModelRequest) -> str:

    return "你是一名编程助手。"

Then add it to create_agent() 's middleware Parameters:

agent = create_agent(

    model="deepseek:deepseek-flash",

    middleware=[my_prompt]

)

@dynamic_prompt receive ModelRequest, return str or SystemMessage, as the system prompt for the current model request.


4. Dynamically adjusting prompts based on conversation stage

can be used via request.state Read the current Agent state and adjust the prompt based on the number of messages.

Example: Short conversations and long conversations

Example

from

langchain.

agents

import

create_agent

from

langchain.

agents

.

middleware

import

dynamic_prompt

,

ModelRequest

@

dynamic_prompt

def

personalized_prompt

(

request: ModelRequest

)

str

:

   

"""Adjust answer style based on the number of messages."""

    count

=

len

(

request.

state

.

get

(

"messages"

,

[

]

)

)

    base

=

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

   

if

count

<=

2

:

       

return

base +

"The user has just started the conversation; please introduce things patiently and learn about their learning goals."

   

if

count

10

:

       

return

base +

"There is already a lot of conversation content; please prioritize answering the current question and keep it concise."

   

return

base +

"Based on the existing conversation, give practical programming learning advice."

agent

=

create_agent

(

    model

=

"deepseek:deepseek-flash"

,

    tools

=

[

]

,

    middleware

=

[

personalized_prompt

]

)

result

=

agent.

invoke

(

{

   

"messages"

:

[

{

"role"

:

"user"

,

"content"

:

"Hello, I want to learn programming."

}

]

}

)

print

(

result

[

"messages"

]

[

1

]

.

content

)

On the first call, with fewer messages, the model may use a guiding answer:

你好!你想学习 Python、Java 还是前端开发?

目前是否有编程基础?

When the message history is long, the dynamic prompt will require the model to be more concise.

**Note:** The number of messages is not the same as the number of conversation turns. One round of Agent execution may produce multiple messages such as AIMessage and ToolMessage.

Also, if no Checkpointer is configured, multiple independent invoke() will not automatically share the complete conversation history from the previous round.


5. What information does ModelRequest provide?

@dynamic_prompt The parameter is ModelRequest, which contains information about the current model request.

property Description
request.state Current Agent State; you can read message history and custom fields
request.runtime Current runtime object, containing information such as Context
request.system_prompt The system prompt text of the current request
request.model The currently used model object
request.messages The messages of the current model request
request.tools Tool definitions available for the current model request

Among these, the most commonly used is request.state and request.runtime.context。

Note:request.runtime.context data structure is determined by the application's context_schema and cannot be assumed to always be a dictionary.


6. Dynamically generating prompts based on user level

Compared with adjusting prompts based on the number of messages, a more common business need is to adjust based on user information.

For example, a programming learning website can provide different explanation styles based on the user's learning level.

Here it is recommended to use context_schema to define runtime context, with the user level passed in by the application.

Complete example: Learning assistants of different levels

Example

from

dataclasses

import

dataclass

from

langchain.

agents

import

create_agent

from

langchain.

agents

.

middleware

import

dynamic_prompt

,

ModelRequest

@

dataclass

class

UserContext:

    level:

str

=

"Beginner"

    language:

str

=

"Chinese"

@

dynamic_prompt

def

learning_prompt

(

request: ModelRequest

[

UserContext

]

)

str

:

   

"""Generate a system prompt based on learning level."""

    context

=

request.

runtime

.

context

    level

=

context.

level

    base

=

f

"You are a programming mentor for Runoob Tutorial RUNOOB; please answer using {context.language}."

   

if

level

==

"Beginner"

:

       

return

base +

"The user is a beginner; use fewer technical terms and explain with simple examples."

   

if

level

==

"Intermediate"

:

       

return

base +

"The user has a programming background; you can introduce principles, best practices, and cautions."

   

return

base +

"The user is an advanced developer; focus on analyzing implementation principles, performance, and design trade-offs."

agent

=

create_agent

(

    model

=

"deepseek:deepseek-flash"

,

    tools

=

[

]

,

    context_schema

=

UserContext

,

    middleware

=

[

learning_prompt

]

)

question

=

{

"messages"

:

[

{

"role"

:

"user"

,

"content"

:

"What is a Python decorator?"

}

]

}

Beginners

result

=

agent.

invoke

(

question

,

context

=

UserContext

(

level

=

"Beginner"

)

)

print

(

"Beginner version:"

,

result

[

"messages"

]

[

1

]

.

content

)

Advanced developer

result

=

agent.

invoke

(

question

,

context

=

UserContext

(

level

=

"Advanced"

)

)

print

(

"Advanced version:"

,

result

[

"messages"

]

[

1

]

.

content

)

The questions in the two calls are the same, but different user levels are provided.

The model may therefore use different explanation styles:

User level Answer focus
Getting started Plain-language explanations, simple examples, fewer terms
Advanced Implementation principles, usage tips, common questions
Advanced Design mechanisms, performance impact, engineering trade-offs

The Context here is passed in by the application; you should not directly trust the user identity or permissions claimed by the model itself.


7. Dynamically generating prompts based on time

Dynamic prompts can also read time information, for example for greetings in different time periods.

However, server time is not necessarily the same as the user's local time, so you should specify which time zone to use.

Example: Generating greetings by specified time zone

Example

from

datetime

import

datetime

from

zoneinfo

import

ZoneInfo

from

langchain.

agents

.

middleware

import

dynamic_prompt

,

ModelRequest

@

dynamic_prompt

def

time_aware_prompt

(

request: ModelRequest

)

str

:

   

"""Generate a greeting based on Beijing time."""

    now

=

datetime

.

now

(

ZoneInfo

(

"Asia/Shanghai"

)

)

    hour

=

now.

hour

    greeting

=

"Good morning"

if

hour

<

12

else

"Good afternoon"

if

hour

<

18

else

"Good evening"

   

return

(

        f

"You are a programming learning assistant. Current Beijing time: {now:%Y-%m-%d %H:%M}."

        f

"You can use"{greeting}"naturally as a greeting; keep the answer concise."

   

)

Here it explicitly uses Asia/Shanghai time zone, avoiding reliance on the server operating system's local time zone.

But it is still only Beijing time, not necessarily the user's local time. If the website supports multiple time zones, read the time zone from trusted user settings and validate it.

In addition,@dynamic_prompt executed before each model request; it is recommended to avoid time-consuming database scans, large file processing, or complex network requests directly in the function.


8. The relationship between static and dynamic System Prompts

If both are set:

create_agent(system_prompt=...)



middleware=[dynamic_prompt_function]

then @dynamic_prompt The returned prompt will be used for the current model request.

Therefore, it may replace the original static System Prompt rather than being automatically appended.

Example: Dynamic prompt overriding static prompt

Example

from

langchain.

agents

import

create_agent

from

langchain.

agents

.

middleware

import

dynamic_prompt

,

ModelRequest

@

dynamic_prompt

def

override_prompt

(

request: ModelRequest

)

str

:

   

"""Replace the system prompt for the current model request."""

   

return

"You are a Python teacher; explain concepts in one sentence."

agent

=

create_agent

(

    model

=

"deepseek:deepseek-flash"

,

    tools

=

[

]

,

    system_prompt

=

"You are a general programming assistant; please provide detailed explanations."

,

    middleware

=

[

override_prompt

]

)

result

=

agent.

invoke

(

{

   

"messages"

:

[

{

"role"

:

"user"

,

"content"

:

"What is a variable?"

}

]

}

)

print

(

result

[

"messages"

]

[

1

]

.

content

)

At this point, the model request uses the system prompt returned by the dynamic function.

**Note:** If there are multiple Middleware that modify the system prompt, the final effect is also affected by the execution order and combination logic of the middleware; you cannot simply apply a fixed global priority.


9. Combining static and dynamic prompts

In real projects, you usually want to keep a set of fixed rules while appending personalized content based on user information.

It is recommended to define common rules separately and then combine them in the dynamic prompt.

Example: Common rules + user level

Example

from

langchain.

agents

.

middleware

import

dynamic_prompt

,

ModelRequest

BASE_PROMPT

=

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

@

dynamic_prompt

def

combined_prompt

(

request: ModelRequest

[

UserContext

]

)

str

:

   

"""Combine general rules and user level."""

    level

=

request.

runtime

.

context

.

level

    extra

=

"Please explain with simple examples."

if

level

==

"Beginner"

else

"You can explain technical principles in depth."

   

return

BASE_PROMPT +

"\n"

The UserContext referenced here is the same as in the earlier runtime context example.

If you run this example standalone, you need to define UserContext as well and combined_prompt register it with the Agent.

Reading the current system_prompt

In the current LangChain API, you can also use request.system_prompt to access the system prompt text of the current model request.

Example

from

langchain.

agents

.

middleware

import

dynamic_prompt

,

ModelRequest

@

dynamic_prompt

def

extend_prompt

(

request: ModelRequest

)

str

:

   

"""Add rules on top of the current prompt."""

    base

=

request.

system_prompt

or

"You are a programming learning assistant."

   

return

base +

"\nWhen answering, prioritize giving simple, actionable examples."

This approach is suitable for retaining the current static system prompt and then appending dynamic rules.

However, if multiple dynamic prompt middleware are configured, check whether content may be appended repeatedly. Do not assume every middleware necessarily reads the original, unmodified system prompt.


10. System Prompt and tool calling

The System Prompt can guide the Agent on when to use tools.

For example:

当用户查询课程目录时,使用 search_course 工具。

工具没有返回相关课程时,明确告知用户。

不要编造课程价格或会员信息。

But even with this setting, there is no guarantee the model will choose to call a tool every time.

If a business operation must be executed, such as deducting payment, saving an order, or checking permissions, it should be handled by the program or an explicit workflow, not just by relying on natural-language prompts.

It is recommended to separate responsibilities:

Function Responsible mechanism
Guide the model's answer style System Prompt
Adjust prompts based on the user Dynamic Prompt
Define callable capabilities @tool
Execute tools and loop scheduling create_agent()
Verify identity and permissions Trusted backend business logic

11. Complete example: Personalized programming learning Agent

Below we combine static common rules, runtime context, dynamic prompts, and a course search tool.

Filename:dynamic_prompt_demo.py

Install dependencies:

pip install -U langchain langchain-deepseek python-dotenv

in .env Configure in the file:

DEEPSEEK_API_KEY=your_deepseek_api_key

Complete example

from

dataclasses

import

dataclass

from

dotenv

import

load_dotenv

from

langchain.

agents

import

create_agent

from

langchain.

agents

.

middleware

import

dynamic_prompt

,

ModelRequest

from

langchain.

tools

import

tool

load_dotenv

(

)

@

dataclass

class

UserContext:

    level:

str

=

"Beginner"

    goal:

str

=

"Learn programming"

COURSES

=

{

   

"python"

:

"Python3 Basic Tutorial"

,

   

"html"

:

"HTML Basics Tutorial"

,

   

"java"

:

"Java Basics Tutorial"

}

@

tool

def

search_course

(

keyword

:

str

)

str

:

   

"""Query simulated courses by programming language."""

   

return

COURSES.

get

(

keyword

.

lower

(

)

,

"No matching mock course found"

)

BASE_PROMPT

=

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

@

dynamic_prompt

def

personalized_prompt

(

request: ModelRequest

[

UserContext

]

)

str

:

   

"""Generate a prompt based on user level and learning goal."""

    ctx

=

request.

runtime

.

context

   

if

ctx.

level

==

"Beginner"

:

        extra

=

"The user is a beginner; use fewer terms and explain basic concepts first."

   

elif

ctx.

level

==

"Intermediate"

:

        extra

=

"The user has a programming background; you can introduce project practice and common questions."

   

else

:

        extra

=

"The user is an advanced developer; focus on explaining technical principles and engineering design."

   

return

f

"{BASE_PROMPT}\nLearning goal: {ctx.goal}\n{extra}"

agent

=

create_agent

(

    model

=

"deepseek:deepseek-flash"

,

    tools

=

[

search_course

]

,

    context_schema

=

UserContext

,

    middleware

=

[

personalized_prompt

]

)

def

ask

(

question:

str

,

level:

str

)

:

    result

=

agent.

invoke

(

       

{

"messages"

:

[

{

"role"

:

"user"

,

"content"

: question

}

]

}

,

        context

=

UserContext

(

level

=

level

,

goal

=

"Learn Python"

)

   

)

   

print

(

f

"\n[{level}] {result['messages'][-1].content}"

)

if

name

==

"main"

:

    ask

(

"I want to learn Python; what courses do you recommend?"

,

"Beginner"

)

    ask

(

"I want to learn Python; what courses do you recommend?"

,

"Advanced"

)

In this example, the user asks the same question, but the level in Context differs.

The Agent can dynamically adjust the system prompt for different users.

Beginners may get simpler learning advice, while advanced developers may get more in-depth technical directions.

The course search tool still uses fixed mock data and does not connect to any real website.

**Note:** Each user's learning level should be provided as trusted context by the application; you should not directly treat model-generated role information as a basis for permissions.


12. Frequently asked questions

1. What is the difference between System Prompt and HumanMessage?

The System Prompt mainly sets the model's role and behavior rules, while HumanMessage is used to express the user's current question or request.

2. Does @dynamic_prompt execute every round?

It executes each time the Agent is about to call the model. One Agent run may make multiple model requests due to tool calls, so the dynamic prompt may also execute multiple times.

3. Can a dynamic prompt return a SystemMessage?

Yes. The current @dynamic_prompt supports returning a string or SystemMessage.

4. How to read the user level?

It is recommended to use context_schema to define runtime Context, and then use request.runtime.context .

5. Is Context a dictionary or an object?

It depends on the application's definition. You can use a dictionary, a data structure corresponding to TypedDict, or an object such as a dataclass; the reading method must be consistent.

6. Do dynamic prompts automatically preserve the static prompt?

No, concatenation is not automatically guaranteed. The return value of the dynamic function is used for the current request; it is recommended to explicitly combine the fixed and dynamic parts.

7. Can you get the current System Prompt?

can be used via request.system_prompt Read the system prompt text of the current model request.

8. Why is the number of conversation messages greater than the actual number of turns?

Because the Agent also generates tool-call requests, tool results, and other messages. When counting user turns, filter HumanMessage separately.

9. Is Dynamic Prompt suitable for querying a database?

You can read data as needed by the business, but it is not recommended to perform complex, time-consuming database queries before every model call. It is usually more appropriate to obtain necessary information in the application layer in advance and pass it in through Context.

10. Can the System Prompt guarantee the model will call a tool?

No. It can guide tool use, but tasks that must be enforced should be handed to the application or a deterministic workflow.


Summary

LangChain provides two main ways to configure the system prompt:

For simple applications, you can directly use:

agent = create_agent(

    model="deepseek:deepseek-flash",

    system_prompt="You are a programming learning assistant."

)

For applications needing dynamic control, you can use:

@dynamic_prompt

def my_prompt(request: ModelRequest) -> str:

    return "根据当前任务生成的系统提示词"



agent = create_agent(

    model="deepseek:deepseek-flash",

    middleware=[my_prompt]

)

**Core principle:** Fixed roles and rules go in the base System Prompt, while user-related variations are provided through Dynamic Prompt and trusted Context. Prompts are responsible for guiding the model, while key business constraints should be guaranteed by the program.