Документация API

Контекст чата

В этом руководстве будет рассказано о том, как использовать API DeepSeek /chat/completions для многоэтапных бесед.

API DeepSeek /chat/completions не сохраняет контекст запросов пользователя. Поэтому пользователь должен объединить всю предыдущую историю беседы и передать ее в чат API при каждом запросе.

Приведенный ниже код на Python демонстрирует, как объединять контекст для достижения многоэтапной беседы.


from openai import OpenAI
client = OpenAI(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}")



При первом запросе в API передаются следующие сообщения:



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


Во втором запросе добавьте входные данные из первого запроса в конец сообщений.

В конечном итоге сообщения, переданные в API, будут следующие:


[
    {"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?"}
]