聊天角色与系统消息

使用 OpenAI API

James Chapman

Curriculum Manager, DataCamp

聊天补全

 

单轮任务

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

一个只有一条提示和一条回复的单轮任务。

使用 OpenAI API

聊天补全

 

单轮任务

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

 

多轮对话

→ 基于先前的提示与回复

包含多次提示与回复的多轮任务。

使用 OpenAI API

角色

 

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

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

使用 OpenAI API

请求设置

response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": prompt}]
)
使用 OpenAI API

提示设置

messages=[{"role": "system",
           "content": "You are a Python programming tutor who speaks concisely."},
          {"role": "user",
           "content": "What is the difference between mutable and immutable objects?"}]
使用 OpenAI API

发起请求

response = client.chat.completions.create(
  model="gpt-4o-mini",
  messages=[{"role": "system",
             "content": "You are a Python programming tutor who speaks concisely."},
            {"role": "user",
             "content": "What is the difference between mutable and immutable objects?"}]
)

print(response.choices[0].message.content)
使用 OpenAI API

响应

可变对象在创建后可被修改;不可变对象一旦创建就不能修改。
使用 OpenAI API

降低误用风险

 

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

guardrails.jpg

一个金融导师聊天机器人和一个理财顾问聊天机器人。

使用 OpenAI API

用系统消息降低误用风险

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:

I'm sorry, I am not allowed to provide financial advice.
"""
使用 OpenAI API

用系统消息降低误用风险

response = client.chat.completions.create(
  model="gpt-4o-mini",
  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.
使用 OpenAI API

让我们练习!

使用 OpenAI API

Preparing Video For Download...