name: openai-assistants description: OpenAI Assistants API v2 用于具有代码解释器、文件搜索和RAG的状态ful聊天机器人。适用于管理线程、向量存储,或处理活动运行错误、索引延迟。⚠️ 将于2026年8月26日停用。
关键词:openai assistants, assistants api, openai threads, openai runs, code interpreter assistant, file search openai, vector store openai, openai rag, assistant streaming, thread persistence, stateful chatbot, thread already has active run, run status polling, vector store error license: MIT metadata: version: “2.0.0” openai_version: “6.9.1” last_verified: “2025-11-21” api_version: “v2” v1_deprecated: “2024-12-18” v2_sunset: “H1 2026” production_tested: true token_savings: “~60%” errors_prevented: 15 templates_included: 8 references_included: 8
OpenAI Assistants API v2
状态: 生产就绪(预计H1 2026停用) | 包: openai@6.9.1 最后更新: 2025-11-21 | v2停用时间: H1 2026
⚠️ 重要:停用通知
OpenAI宣布Assistants API将停用,推荐使用Responses API。
时间线:
- ✅ 2024年12月18日: Assistants API v1已停用
- ⏳ H1 2026: 计划停用Assistants API v2
- ✅ 现在: Responses API可用(推荐新项目使用)
是否仍应使用此技能?
- ✅ 是,如果: 您有现有的Assistants API代码(12-18个月迁移窗口)
- ✅ 是,如果: 您需要维护遗留应用
- ✅ 是,如果: 计划从Assistants迁移到Responses
- ❌ 否,如果: 开始新项目(使用openai-responses技能代替)
迁移路径: 参见references/migration-to-responses.md获取完整迁移指南。
快速开始(5分钟)
1. 安装
bun add openai@6.7.0 # 推荐
# 或: npm install openai@6.7.0
2. 环境设置
export OPENAI_API_KEY="sk-..."
3. 基础助手
import OpenAI from 'openai'
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY })
// 1. 创建一个助手
const assistant = await openai.beta.assistants.create({
name: "数学导师",
instructions: "你是一个有帮助的数学导师。清晰地回答数学问题。",
model: "gpt-4-1106-preview",
})
// 2. 创建一个线程(对话)
const thread = await openai.beta.threads.create()
// 3. 添加一条消息
await openai.beta.threads.messages.create(thread.id, {
role: "user",
content: "12 * 34 是多少?",
})
// 4. 创建并轮询运行
const run = await openai.beta.threads.runs.createAndPoll(thread.id, {
assistant_id: assistant.id,
})
// 5. 获取消息
if (run.status === 'completed') {
const messages = await openai.beta.threads.messages.list(thread.id)
console.log(messages.data[0].content[0].text.value)
}
关键点:
- 助手是持久的(存储在服务器端)
- 线程是持久的(对话历史)
- 运行在线程上执行助手
- 始终轮询或流式运行(它们是异步的)
- 使用
createAndPoll简化或流式进行实时处理
核心概念
4个关键对象:
- 助手 = AI代理,带有指令和工具
- 线程 = 对话(持久化消息)
- 消息 = 线程中的单条消息(用户或助手)
- 运行 = 在线程上执行助手
生命周期:
助手(创建一次)+ 线程(每次对话)+ 消息(添加用户输入)→ 运行(执行)→ 消息(获取响应)
**加载references/assistants-api-v2.md**获取完整架构、对象、工作流和定价详情。
关键规则
始终执行
✅ 轮询或流式运行 - 运行是异步的,不要假设立即完成
✅ 检查运行状态 - 处理requires_action、failed、cancelled、expired
✅ 处理函数调用 - 当requires_action时提交工具输出
✅ 存储线程ID - 重用线程进行多轮对话
✅ 设置超时 - 向量存储索引可能需数分钟处理大文件
✅ 验证文件上传 - 检查支持的格式和大小限制
✅ 使用结构化指令 - 清晰、具体的助手指令
✅ 处理速率限制 - 实现指数退避
✅ 清理未使用资源 - 删除旧助手/线程以节省成本
✅ 使用最新API版本 - Assistants API v2(v1已于2024年12月停用)
切勿执行
❌ 切勿跳过运行轮询 - 运行不会立即完成
❌ 切勿重用运行ID - 每次交互创建新运行
❌ 切勿假设文件索引是即时的 - 向量存储需要时间
❌ 切勿忽略requires_action状态 - 函数调用需要您的响应
❌ 切勿硬编码助手ID - 使用环境变量
❌ 切勿为每个请求创建新助手 - 重用助手
❌ 切勿超出文件限制 - 每个向量存储10000个文件,每个文件10GB
❌ 切勿在生产中使用代码解释器 - 使用沙盒执行代替
❌ 切勿跳过错误处理 - API调用可能失败
❌ 切勿用Assistants API开始新项目 - 使用Responses API代替
前5大错误预防
此技能预防了15个文档化错误。以下是前5个:
错误 #1: “线程已有活动运行”
错误: 无法创建运行: thread_xyz已有活动运行
预防: 创建新运行前检查活动运行:
// 获取运行并检查状态
const runs = await openai.beta.threads.runs.list(thread.id)
const activeRun = runs.data.find(r => ['in_progress', 'queued'].includes(r.status))
if (activeRun) {
// 取消或等待
await openai.beta.threads.runs.cancel(thread.id, activeRun.id)
}
// 现在创建新运行
const run = await openai.beta.threads.runs.create(thread.id, {...})
参见: references/top-errors.md #1
错误 #2: 向量存储索引超时
错误: 上传后文件搜索立即返回空结果 预防: 等待索引完成:
// 上传文件
const file = await openai.files.create({
file: fs.createReadStream('document.pdf'),
purpose: 'assistants',
})
// 添加到向量存储
await openai.beta.vectorStores.files.create(vectorStore.id, {
file_id: file.id,
})
// 等待索引(轮询file_counts)
let vs = await openai.beta.vectorStores.retrieve(vectorStore.id)
while (vs.file_counts.in_progress > 0) {
await new Promise(resolve => setTimeout(resolve, 1000))
vs = await openai.beta.vectorStores.retrieve(vectorStore.id)
}
参见: references/top-errors.md #2
错误 #3: 运行状态轮询无限循环
错误: 轮询永不终止,永远挂起 预防: 添加超时和终端状态检查:
const maxAttempts = 60 // 60秒
let attempts = 0
while (attempts < maxAttempts) {
const run = await openai.beta.threads.runs.retrieve(thread.id, run.id)
if (['completed', 'failed', 'cancelled', 'expired', 'requires_action'].includes(run.status)) {
break
}
await new Promise(resolve => setTimeout(resolve, 1000))
attempts++
}
if (attempts >= maxAttempts) {
throw new Error('运行轮询超时')
}
参见: references/top-errors.md #3
错误 #4: 函数调用未提交
错误: 运行永远卡在requires_action状态
预防: 当需要时提交工具输出:
const run = await openai.beta.threads.runs.createAndPoll(thread.id, {
assistant_id: assistant.id,
})
if (run.status === 'requires_action') {
const toolCalls = run.required_action.submit_tool_outputs.tool_calls
const toolOutputs = toolCalls.map(call => ({
tool_call_id: call.id,
output: JSON.stringify(executeTool(call.function.name, call.function.arguments)),
}))
await openai.beta.threads.runs.submitToolOutputsAndPoll(thread.id, run.id, {
tool_outputs: toolOutputs,
})
}
参见: references/top-errors.md #4
错误 #5: 文件上传格式不支持
错误: 代码解释器的文件格式无效
预防: 上传前验证文件格式:
const supportedFormats = {
code_interpreter: ['.c', '.cpp', '.csv', '.docx', '.html', '.java', '.json', '.md', '.pdf', '.php', '.pptx', '.py', '.rb', '.tex', '.txt', '.css', '.js', '.sh', '.ts'],
file_search: ['.c', '.cpp', '.docx', '.html', '.java', '.json', '.md', '.pdf', '.php', '.pptx', '.py', '.rb', '.tex', '.txt', '.css', '.js', '.sh', '.ts'],
}
const fileExtension = path.extname(filePath)
if (!supportedFormats.code_interpreter.includes(fileExtension)) {
throw new Error(`不支持的文件格式: ${fileExtension}`)
}
// 现在安全上传
const file = await openai.files.create({
file: fs.createReadStream(filePath),
purpose: 'assistants',
})
参见: references/top-errors.md #5
完整错误目录(所有15个错误):参见references/top-errors.md
常见用例
用例 1: 简单问答聊天机器人
模板: templates/basic-assistant.ts | 时间: 10分钟
const assistant = await openai.beta.assistants.create({
name: "支持机器人",
instructions: "专业地回答客户问题。",
model: "gpt-4-1106-preview",
})
// 每次对话: 创建线程 → 添加消息 → 运行 → 获取响应
用例 2: 文档问答与RAG
模板: templates/file-search-assistant.ts | 时间: 30分钟
参考: 加载references/file-search-rag-guide.md和references/vector-stores.md获取完整实现。
用例 3: 代码执行助手
模板: templates/code-interpreter-assistant.ts | 时间: 20分钟
参考: 加载references/code-interpreter-guide.md获取设置、替代方案和故障排除。
用例 4: 函数调用助手
模板: templates/function-calling-assistant.ts | 时间: 25分钟
用例 5: 流式聊天机器人
模板: templates/streaming-assistant.ts | 时间: 15分钟
何时加载详细参考
加载references/assistants-api-v2.md当:
- 用户需要完整API参考
- 用户询问特定端点或参数
- 用户需要速率限制信息或配额
- 用户想要架构详情
加载references/code-interpreter-guide.md当:
- 用户实现代码执行
- 用户询问代码解释器支持的文件格式
- 用户需要代码解释器替代方案(E2B, Modal)
- 用户遇到代码解释器错误
加载references/file-search-rag-guide.md当:
- 用户构建RAG应用
- 用户询问向量存储设置
- 用户需要文件搜索优化策略
- 用户扩展文档搜索超出基础设置
加载references/migration-from-v1.md当:
- 用户提及Assistants API v1
- 用户从v1升级到v2
- 用户询问破坏性更改(检索 → 文件搜索)
- 用户遇到v1停用错误
加载references/migration-to-responses.md当:
- 用户计划未来迁移到Responses API
- 用户询问Responses API比较
- 用户提及停用时间线
- 用户构建新项目(推荐Responses API)
加载references/thread-lifecycle.md当:
- 用户构建多轮对话
- 用户询问线程持久化模式
- 用户需要对话管理策略
- 用户优化线程使用或清理
加载references/top-errors.md当:
- 用户遇到任何错误(所有15个文档化错误)
- 用户询问故障排除
- 用户想预防已知问题
- 用户调试生产问题
加载references/vector-stores.md当:
- 用户扩展文件搜索超出基础设置
- 用户询问文件限制(10000个文件)
- 用户需要索引优化
- 用户管理向量存储成本($0.10/GB/天)
可用模板
templates/中的生产就绪代码示例:
basic-assistant.ts- 最小助手设置(入门)code-interpreter-assistant.ts- 代码执行(Python代码运行器)file-search-assistant.ts- 文档问答(RAG应用)function-calling-assistant.ts- 外部工具(API集成)streaming-assistant.ts- 实时响应(流式输出)thread-management.ts- 多轮对话(聊天机器人)vector-store-setup.ts- 向量存储配置(文件搜索设置)package.json- 依赖项(项目设置)
依赖项
必需:
- openai@6.7.0 - OpenAI Node.js SDK
可选:
- fs - 文件系统操作(内置)
- path - 路径工具(内置)
官方文档
- Assistants API: https://platform.openai.com/docs/assistants/overview
- API参考: https://platform.openai.com/docs/api-reference/assistants
- Responses API: https://platform.openai.com/docs/guides/responses(推荐新项目使用)
- 迁移指南: https://platform.openai.com/docs/guides/migration
- 社区论坛: https://community.openai.com/
包版本(已验证 2025-10-25)
{
"dependencies": {
"openai": "^6.7.0"
}
}
版本说明:
- OpenAI SDK 6.7.0是最新稳定版
- 支持Assistants API v2
- Assistants API v1已于2024年12月18日停用
- Assistants API v2计划H1 2026停用
生产示例
此技能基于生产使用:
- 令牌节省: 约60% vs 手动实现
- 错误预防: 15个文档化问题
- 设置时间: < 30分钟用于基础聊天机器人
- 验证: ✅ 文件搜索工作, ✅ 流式功能, ✅ 函数调用测试
完整设置清单
- [ ] 已安装
openai@6.7.0 - [ ] 设置
OPENAI_API_KEY环境变量 - [ ] 创建至少一个助手
- [ ] 测试线程创建和消息添加
- [ ] 实现运行轮询或流式
- [ ] 处理
requires_action状态(如果使用函数调用) - [ ] 测试文件上传(如果使用代码解释器或文件搜索)
- [ ] 为所有API调用实现错误处理
- [ ] 存储线程ID以保持对话持久化
- [ ] 计划迁移到Responses API(针对新项目)
- [ ] 设置监控以处理速率限制
- [ ] 实现清理未使用资源
问题?问题?
- 检查官方文档: https://platform.openai.com/docs/assistants/overview
- 回顾
references/top-errors.md获取所有15个文档化错误 - 参见
templates/获取生产就绪代码示例 - 检查
references/migration-to-responses.md以备未来之需 - 加入社区: https://community.openai.com/
⚠️ 提醒: 此API已停用。对于新项目,请使用Responses API代替。参见references/migration-to-responses.md获取迁移指南。