Deepseek 多輪對(duì)話

2025-02-05 11:05 更新

本指南將介紹如何使用 DeepSeek /chat/completions API 進(jìn)行多輪對(duì)話。

DeepSeek /chat/completions API 是一個(gè)“無(wú)狀態(tài)” API,即服務(wù)端不記錄用戶請(qǐng)求的上下文,用戶在每次請(qǐng)求時(shí),需將之前所有對(duì)話歷史拼接好后,傳遞給對(duì)話 API。

下面的代碼以 Python 語(yǔ)言,展示了如何進(jìn)行上下文拼接,以實(shí)現(xiàn)多輪對(duì)話。

from openai import OpenAI
client = OpenAI(api_key="<DeepSeek API Key>", base_url="https://api.deepseek.com")

# Round 1
messages = [{"role": "user", "content": "What's the highest mountain in the world?"}]
response = client.chat.completions.create(
model="deepseek-chat",
messages=messages
)

messages.append(response.choices[0].message)
print(f"Messages Round 1: {messages}")

# Round 2
messages.append({"role": "user", "content": "What is the second?"})
response = client.chat.completions.create(
model="deepseek-chat",
messages=messages
)

messages.append(response.choices[0].message)
print(f"Messages Round 2: {messages}")

在第一輪請(qǐng)求時(shí),傳遞給 API 的 messages 為:

[
{"role": "user", "content": "What's the highest mountain in the world?"}
]

在第二輪請(qǐng)求時(shí):

  1. 要將第一輪中模型的輸出添加到 messages 末尾
  2. 將新的提問(wèn)添加到 messages 末尾

最終傳遞給 API 的 messages 為:

[
{"role": "user", "content": "What's the highest mountain in the world?"},
{"role": "assistant", "content": "The highest mountain in the world is Mount Everest."},
{"role": "user", "content": "What is the second?"}
]


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)