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

OpenAI Assistant仅单个API Key可用,其他Key失效的原因排查

问题排查:OpenAI Assistant在不同API Key下的运行差异

问题描述

我编写了基于GPT-4o模型的OpenAI Assistant代码,使用file_search工具检索本地文本文件内容。该代码在其中一个API Key下可正常运行,返回包含文件引用的助手回复;但切换到另一个API Key时,仅能看到用户提问消息,无助手回复输出。

可能的原因及排查方案

  • API Key权限缺失:异常的API Key可能未开通Assistant API(含beta版的向量存储vector_store和file_search工具),或无GPT-4o模型的使用权限。需登录OpenAI后台,检查该Key的权限配置,确认相关服务已启用。
  • 账户计费/额度问题:对应API Key的账户可能余额不足,或触发了计费限制,导致请求被静默拦截。查看账户账单状态和额度使用情况,确保有足够余额且未超出限制。
  • 区域功能限制:不同API Key可能关联不同区域,部分区域暂不支持Assistant API的file_search或vector_store功能。对比两个Key的所属区域,确认目标区域支持相关功能。
  • 文件上传环节隐性失败:代码中仅打印文件批量上传的状态和计数,但未做错误判断。若异常Key环境下文件上传失败(如文件权限、格式不兼容),会导致后续检索无数据,助手无法生成回复。需在file_batch上传后增加判断:
    if file_batch.status != "succeeded":
        print(f"文件上传失败:{file_batch.status}")
        sys.exit(1)
    
  • 线程运行失败未捕获:当前代码仅在run.status == "completed"时获取消息,若运行进入failed状态则直接跳过。需在循环结束后检查失败状态并输出错误详情:
    if run.status == "failed":
        print(f"运行失败:{run.incomplete_details}")
    elif run.status == "completed":
        results = client.beta.threads.messages.list(thread_id=thread.id)
    

代码示例

import os
import sys
from dotenv import load_dotenv
from openai import OpenAI

path = os.path.abspath(os.path.dirname(sys.argv[0])) 
fn = os.path.join(path, ".env")
load_dotenv(fn)
CHATGPT_API_KEY = os.environ.get("CHATGPT_API_KEY")
client = OpenAI(api_key = CHATGPT_API_KEY)

fn = os.path.join(path, "workText.txt")
vector_store = client.beta.vector_stores.create(name="HTML-File")
file_paths = [fn]
file_streams = [open(path, "rb") for path in file_paths]
file_batch = client.beta.vector_stores.file_batches.upload_and_poll(
  vector_store_id=vector_store.id, files=file_streams
)
print(file_batch.status)
print(file_batch.file_counts)
# exit()

print(f"Preparing assistant")
assistant = client.beta.assistants.create(
  name="HTML Analyse Assistant",
  instructions="You are a machine learning researcher, answer questions about the provided text-file",
  model="gpt-4o",
  tools=[{"type": "file_search"}],
)
assistant = client.beta.assistants.update(
  assistant_id=assistant.id,
  tool_resources={"file_search": {"vector_store_ids": [vector_store.id]}},
)

question = """
What is the name of the location?
"""

print(f"Preparing thread")
thread = client.beta.threads.create()
print(f"Preparing question")
results = client.beta.threads.messages.create(
  thread_id = thread.id,
  role = "user",
  content = question
)
print(f"Running for answer")
run = client.beta.threads.runs.create (
  thread_id = thread.id,
  assistant_id = assistant.id
)
while run.status not in ["completed", "failed"]:
  run = client.beta.threads.runs.retrieve (
    thread_id = thread.id,
    run_id = run.id
  )
if run.status == "completed":
  results = client.beta.threads.messages.list(
      thread_id=thread.id
  )

# resultAnswer = results.data[0].content[0].text.value
fn = os.path.join(path, "result.txt")
with open(fn, "w", encoding="utf-8", errors="ignore") as f:
  lines = f.writelines(str(results))

正常运行输出

SyncCursorPage[Message](data=[Message(id='msg_Z6iImlhDNFDmXoCszSl8hOrp', assistant_id='asst_eYsWBFev7jeZZC3MRyZ9PuJK', attachments=[], completed_at=None, content=[TextContentBlock(text=Text(annotations=[FileCitationAnnotation(end_index=117, file_citation=FileCitation(file_id='file-v3Y3HH9Kd0L2doxuoRVNU6kL'), start_index=99, text='【4:0†workText.txt】', type='file_citation')], value='The name of the location is "Benediktinerabtei Gerleve" which is located in Billerbeck, Deutschland【4:0†workText.txt】.'), type='text')], created_at=1729687317, incomplete_at=None, incomplete_details=None, metadata={}, object='thread.message', role='assistant', run_id='run_6KbPCSO8VqIP0bbqFjuSp4fV', status=None, thread_id='thread_aaRH59cvaPGh5L0J8WIviBBU'), Message(id='msg_GPAug3kAr7GSRSEuIPRUmYvc', assistant_id=None, attachments=[], completed_at=None, content=[TextContentBlock(text=Text(annotations=[], value='\n\nWhat is the name of the location?\n\n'), type='text')], created_at=1729687313, incomplete_at=None, incomplete_details=None, metadata={}, object='thread.message', role='user', run_id=None, status=None, thread_id='thread_aaRH59cvaPGh5L0J8WIviBBU')], object='list', first_id='msg_Z6iImlhDNFDmXoCszSl8hOrp', last_id='msg_GPAug3kAr7GSRSEuIPRUmYvc', has_more=False)

异常运行输出

Message(id='msg_NCxFnnQPXL0gKhsxE2hJhYWh', assistant_id=None, attachments=[], completed_at=None, content=[TextContentBlock(text=Text(annotations=[], value='\nWhat is the name of the location?\n'), type='text')], created_at=1729696968, incomplete_at=None, incomplete_details=None, metadata={}, object='thread.message', role='user', run_id=None, status=None, thread_id='thread_puBTFtaoMvauMBO2D6Wc2ylr')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 02:32:07