You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在多次Mistral AI API调用间传递上下文实现对话机器人

解决Mistral AI Agent对话上下文保留问题

要在Mistral AI Agent的API调用间保留对话上下文,核心是维护完整的对话历史列表,每次调用client.agents.complete时,将包含所有过往用户消息和AI回复的历史列表传入messages参数,而不是仅传入当前用户消息。

具体实现步骤

  1. 初始化一个空列表用于存储对话历史
  2. 每次用户发送新消息时,将用户消息追加到对话历史
  3. 调用API时,把完整的对话历史作为messages参数传递
  4. 接收AI的回复后,将AI的回复也追加到对话历史,供下一轮调用使用

修改后的代码示例

import os
from mistralai import Mistral

api_key = "your_api_key"
agent_id = "your_agent_id"

client = Mistral(api_key=api_key)

# 初始化对话历史列表
conversation_history = []

def send_message(user_input):
    # 将用户新消息添加到对话历史
    conversation_history.append({
        "role": "user",
        "content": user_input
    })
    
    # 携带完整对话历史调用API
    chat_response = client.agents.complete(
        agent_id=agent_id,
        messages=conversation_history
    )
    
    # 提取AI的回复并添加到对话历史
    ai_response = chat_response.choices[0].message
    conversation_history.append(ai_response)
    
    return ai_response.content

# 模拟多轮对话
print(send_message("Hello"))
print(send_message("What's the capital of France?"))
print(send_message("Can you tell me more about its history?"))

注意事项

  • Token限制:对话历史会占用模型的上下文窗口,当历史过长时,需要根据模型的token上限进行截断(比如只保留最近N轮对话),避免触发API报错。
  • 角色正确性:确保对话历史中的消息role只能是user或assistant(AI回复的角色由API返回的message.role提供,无需手动指定)。

内容的提问来源于stack exchange,提问作者Brandonn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 01:52:03