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

Python中OpenAI Chat Completions API循环调用异常:仅获首个响应如何解决?

循环调用OpenAI Chat Completions API仅获取第一个响应的问题排查与解决

可能的原因

  • API调用异常中断循环:第一个请求成功后,后续请求遇到错误(比如速率限制、网络波动、密钥权限问题等),导致循环直接终止,未执行后续的追加操作。
  • input_list实际元素数量不足:你认为列表包含多个问题,但实际input_list只有第一个元素,循环仅执行一次。
  • 代码缩进错误:虽然你的示例代码缩进正确,但如果实际代码中output.append(chat_response)不在循环块内,也会只添加第一个结果。

解决方法及修改后的代码

1. 增加异常捕获机制

给每个API调用添加异常处理,确保单个请求失败不会中断整个循环,同时可以记录错误信息:

output = []
# 直接遍历列表元素更直观
for question in input_list:
    try:
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": "You are a chatbot."},
                {"role": "user", "content": question},
            ]
        )
        chat_response = response['choices'][0]['message']['content']
        output.append(chat_response)
    except Exception as e:
        # 记录错误,也可用占位符代替失败的响应
        print(f"处理问题 {question} 时出错: {str(e)}")
        output.append(f"Error: {str(e)}")

2. 验证input_list的有效性

先确认列表的实际长度和内容,排除列表本身的问题:

print(f"input_list长度: {len(input_list)}")
print("input_list内容:", input_list)

如果长度为1,说明你传入的列表本身只有一个问题,需要检查列表的生成逻辑。

3. 处理API速率限制

若触发OpenAI的速率限制,可添加延时降低调用频率:

import time

output = []
for question in input_list:
    try:
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": "You are a chatbot."},
                {"role": "user", "content": question},
            ]
        )
        chat_response = response['choices'][0]['message']['content']
        output.append(chat_response)
        # 添加1秒延时避免速率限制
        time.sleep(1)
    except Exception as e:
        print(f"处理问题 {question} 时出错: {str(e)}")
        output.append(f"Error: {str(e)}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 09:25:16