调用OpenAI Assistants API传入助手ID遇model_not_found错误求助
问题根源与解决方案
你犯了一个核心错误:把自定义助手ID传给了Chat Completions API接口,而这个接口只接受OpenAI官方模型ID(比如gpt-3.5-turbo),不支持自定义助手ID。自定义助手属于Assistants API体系,需要用专属的接口流程来调用,不能直接套Chat Completions的逻辑。
正确的调用流程(Assistants API)
自定义助手的调用需要通过「线程-消息-运行」的流程实现,核心步骤如下:
- 创建一个对话线程(如果是新对话)
- 向线程中添加用户消息
- 运行自定义助手并绑定到该线程
- 轮询获取运行结果
修正后的代码示例
try { const fetch = await import('node-fetch').then(mod => mod.default); const apiKey = '你的API密钥'; const assistantId = '你的自定义助手ID'; const userMessage = '你的用户提问内容'; // 1. 创建对话线程 const threadResponse = await fetch('https://api.openai.com/v1/threads', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}`, 'OpenAI-Beta': 'assistants=v1' } }); const thread = await threadResponse.json(); const threadId = thread.id; // 2. 向线程添加用户消息 await fetch(`https://api.openai.com/v1/threads/${threadId}/messages`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}`, 'OpenAI-Beta': 'assistants=v1' }, body: JSON.stringify({ role: 'user', content: userMessage }) }); // 3. 运行自定义助手 const runResponse = await fetch(`https://api.openai.com/v1/threads/${threadId}/runs`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}`, 'OpenAI-Beta': 'assistants=v1' }, body: JSON.stringify({ assistant_id: assistantId }) }); const run = await runResponse.json(); const runId = run.id; // 4. 轮询等待运行完成并获取结果 let runStatus = run.status; while (runStatus !== 'completed') { await new Promise(resolve => setTimeout(resolve, 1000)); const statusResponse = await fetch(`https://api.openai.com/v1/threads/${threadId}/runs/${runId}`, { headers: { 'Authorization': `Bearer ${apiKey}`, 'OpenAI-Beta': 'assistants=v1' } }); const statusData = await statusResponse.json(); runStatus = statusData.status; } // 获取助手回复的消息 const messagesResponse = await fetch(`https://api.openai.com/v1/threads/${threadId}/messages`, { headers: { 'Authorization': `Bearer ${apiKey}`, 'OpenAI-Beta': 'assistants=v1' } }); const messages = await messagesResponse.json(); const assistantReply = messages.data.find(msg => msg.role === 'assistant').content[0].text.value; console.log(assistantReply); } catch (error) { console.error('调用失败:', error); }
关键注意事项
- 必须在请求头中添加
OpenAI-Beta: assistants=v1,否则无法调用Assistants API - 确认自定义助手ID与API密钥属于同一OpenAI账号
- 检查自定义助手配置的模型(比如是否用了gpt-4),确保你的API密钥有对应模型的访问权限
内容的提问来源于stack exchange,提问作者Alex Holt
相关产品推荐
相关产品推荐

