聊天角色与系统消息

在 Python 中使用 DeepSeek

James Chapman

AI Curriculum Lead, DataCamp

从单轮到多轮

 

单轮任务

  • 文本生成
  • 文本转换
  • 分类

单轮任务:一个提示对应一个回复。

在 Python 中使用 DeepSeek

从单轮到多轮

 

单轮任务

  • 文本生成
  • 文本转换
  • 分类

 

多轮对话

→ 在先前提示与回复基础上继续

多轮任务:多个提示与回复。

在 Python 中使用 DeepSeek

角色

 

  • System:控制助手的_行为_
  • User:_指示_助手
  • Assistant:对用户指令给出_回复_
    • 也可由开发者编写用于提供示例

聊天交互中的三种角色:system、user、assistant。

在 Python 中使用 DeepSeek

请求设置

response = client.chat.completions.create(
    model="deepseek-ai/DeepSeek-V4.1-Flash",
    messages=[{"role": "user", "content": prompt}]
)
在 Python 中使用 DeepSeek

提示设置

messages=[{"role": "system",
           "content": "You are a Python programming tutor who responds using concise,
                         one-sentence explanations."},
          {"role": "user",
           "content": "What is the difference between mutable and immutable objects?"}]
在 Python 中使用 DeepSeek

发起请求

response = client.chat.completions.create(
  model="deepseek-ai/DeepSeek-V4.1-Flash",
  messages=[{"role": "system",
             "content": "You are a Python programming tutor who responds using concise,
                         one-sentence explanations."},
            {"role": "user",
             "content": "What is the difference between mutable and immutable objects?"}]
)

print(response.choices[0].message.content)
Mutable objects can be changed after creation (like lists), while immutable objects
cannot be modified once created (like tuples or strings).
在 Python 中使用 DeepSeek

降低误用风险

 

  • 系统消息:可包含_护栏_
    • 对模型输出的限制

公路旁的防护栏。

理财导师聊天机器人与理财顾问聊天机器人。

在 Python 中使用 DeepSeek

用系统消息降低误用风险

sys_msg = """
You are finance education assistant that helps students study for exams.

If you are asked for specific, real-world financial advice with risk to their
finances, respond with only:

I'm sorry, I am not allowed to provide financial advice.
"""
在 Python 中使用 DeepSeek

用系统消息降低误用风险

response = client.chat.completions.create(
  model="deepseek-ai/DeepSeek-V4.1-Flash",
  messages=[{"role": "system",
             "content": sys_msg},
            {"role": "user",
             "content": "Which stocks should I invest in?"}]
)

print(response.choices[0].message.content)
I'm sorry, I am not allowed to provide financial advice.
在 Python 中使用 DeepSeek

让我们一起练习吧!

在 Python 中使用 DeepSeek

Preparing Video For Download...