聊天角色與 system 訊息

使用 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

降低誤用風險

 

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

道路邊的防護欄。

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

使用 Python 操作 DeepSeek

用 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 only:

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

用 system 訊息降低誤用

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...