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

Cohere API chat_stream方法报错:不支持'messages'参数,请求排查

问题排查:Cohere chat_stream 报意外关键字参数 'messages'

问题描述

正在学习使用Cohere API,跟着《Building a chatbot》课程学习。根据官方API文档,chat_stream方法支持传入messages参数,但调用时触发错误:

BaseCohere.chat_stream() got an unexpected keyword argument 'messages'

出错代码如下:

# Create a conversation ID
conversation_id = str(uuid.uuid4())

# system message
system_message = "you are a coach of tennis"

print('Starting the chat. Type "quit" to end.\n')

while True:

    # User message
    user_message = input("User: ")

    bot_messages=[
        {'role':'system', 'content': system_message},
        {'role':'user', 'content': user_message}
        ]

    # Typing "quit" ends the conversation
    if user_message.lower() == 'quit':
        print("Ending chat.")
        break

    # Chatbot response
    stream = co.chat_stream(
                            model="command-r-plus",
                            messages=bot_messages,
                            conversation_id=conversation_id
                            )

    print("Chatbot: ", end='')

    for event in stream:
        if event.event_type == "text-generation":
            print(event.text, end='')
        if event.event_type == "stream-end":
            chat_history = event.response.chat_history

    print(f"\n{'-'*100}\n")

问题原因

核心原因是使用的Cohere SDK版本与官方文档版本不匹配:

  • 新版SDK(v4及以上)才支持messages数组参数,用来传递多轮对话历史或系统消息
  • 旧版本SDK的chat_stream方法仅支持message(单条用户消息字符串)、system_prompt(系统提示字符串)这类参数,不兼容messages数组。

解决方案

方案1:升级Cohere SDK到最新版本

执行命令升级SDK:

pip install --upgrade cohere

升级后现有代码可直接正常运行,新版SDK已兼容messages参数。

方案2:适配旧版本SDK的参数格式

若暂时无法升级,可修改代码使用旧版本支持的参数:

# 修改chat_stream调用部分
stream = co.chat_stream(
    model="command-r-plus",
    message=user_message,  # 传入单条用户消息
    system_prompt=system_message,  # 传入系统提示
    conversation_id=conversation_id
)

注:旧版本SDK会基于conversation_id自动维护对话历史,无需每次传入完整消息数组。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 18:05:05