如何在多个 Mistral AI api 调用之间发送上下文以像聊天机器人一样保持对话?

问题描述 投票:0回答:1

我想创建一个像使用 Mistral AI api 一样的聊天机器人。但 Api 的响应就像每次调用之间的新开始一样,并且它不保留上下文。这是我的 python 代码(来自文档):

import os
from mistralai import Mistral

api_key = "my api key"

client = Mistral(api_key=api_key)

chat_response = client.agents.complete(
    agent_id="my agent id",
    messages = [
        {
            "role": "user",
            "content": "Hello",
        },
    ]
)
print(chat_response.choices[0].message.content)

如何在每次通话之间发送上下文?

python artificial-intelligence mistral-ai
1个回答
0
投票

询问 Mistrai Ai 本身就解决了我的问题! 我需要以助理角色发送之前的所有消息。这是一个保留上下文的完整工作示例:

import os
from mistralai import Mistral

api_key = "secret api key"

client = Mistral(api_key=api_key)

# Initialiser l'historique des messages
message_history = []

def get_chat_response(user_message):
    # Ajouter le message de l'utilisateur à l'historique
    message_history.append({"role": "user", "content": user_message})

    # Appeler l'API avec l'historique des messages
    chat_response = client.agents.complete(
        agent_id="my agent id",
        messages=message_history
    )

    # Ajouter la réponse de l'agent à l'historique
    agent_message = chat_response.choices[0].message.content
    message_history.append({"role": "assistant", "content": agent_message})

    return agent_message

while True :
    user_message = input(">: ")
    response = get_chat_response(user_message)
    print(response)
© www.soinside.com 2019 - 2024. All rights reserved.