聊天角色與 system 訊息

Working with the OpenAI API

James Chapman

Curriculum Manager, DataCamp

Chat Completions

 

單回合任務

  • 文字生成
  • 文字轉換
  • 分類

單回合任務:一個提示與一個回覆。

Working with the OpenAI API

Chat Completions

 

單回合任務

  • 文字生成
  • 文字轉換
  • 分類

 

多回合對話

→ 基於先前的提示與回覆逐步累積

多回合任務:多個提示與回覆。

Working with the OpenAI API

角色

 

  • System:控制助理的_行為_
  • User:_指示_助理
  • Assistant:對使用者指示給出_回應_
    • 也可由開發者撰寫範例

聊天互動中的三個角色:system、user、assistant。

Working with the OpenAI API

請求設定

response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": prompt}]
)
Working with the 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?"}]
Working with the 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)
Working with the OpenAI API

回應

可變物件在建立後可以被更改;不可變物件一旦建立就不能再修改。
Working with the OpenAI API

降低誤用風險

 

  • System 訊息:可加入防護欄
    • 限制模型輸出

guardrails.jpg

理財家教聊天機器人與理財顧問聊天機器人。

Working with the OpenAI API

用 system 訊息降低誤用

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.
"""
Working with the OpenAI API

用 system 訊息降低誤用

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.
Working with the OpenAI API

一起來練習吧!

Working with the OpenAI API

Preparing Video For Download...