关于 openai-assistants
面向维护或迁移 OpenAI Assistants API v2 应用的技能指南,涵盖助手、对话线程、运行、流式处理及工具用法。该 API 计划于 2026 年 8 月 26 日停止服务,并提供迁移至 Responses API 的参考。
主要功能
- 01助手、线程与运行的 API 模式
- 02流式处理与函数调用
- 03Code Interpreter 与文件搜索
- 04向量存储及文件处理指南
- 05v1 至 v2 和 Responses API 迁移
适用场景
- 01维护现有 Assistants API 应用
- 02将旧版代码迁移至 Responses API
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ jezweb/ claude-skills --skill openai-assistants安装后在 Claude Code 中输入/openai-assistants确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
README.md.claude-plugin/plugin.jsonreferences/assistants-api-v2.mdcode-interpreter-guide.mdfile-search-rag-guide.mdmigration-from-v1.mdthread-lifecycle.mdtop-errors.mdvector-stores.mdrules/openai-assistants.mdscripts/check-versions.shtemplates/basic-assistant.tscode-interpreter-assistant.tsfile-search-assistant.tsfunction-calling-assistant.tspackage.jsonstreaming-assistant.tsthread-management.tsvector-store-setup.ts详细介绍
OpenAI Assistants API v2
状态:已可用于生产环境(⚠️ 已弃用——将于 2026 年 8 月 26 日停止服务) 软件包:[email protected] 最后更新:2026-01-21 v1 弃用日期:2024 年 12 月 18 日 v2 停止服务日期:2026 年 8 月 26 日(迁移至 Responses API)
⚠️ 弃用通知
OpenAI 正在弃用 Assistants API,转而使用 Responses API。
时间表:v1 于 2024 年 12 月 18 日弃用 | v2 将于 2026 年 8 月 26 日停止服务
适用情况:维护旧版应用或迁移现有代码(有 12–18 个月的时间窗口)
不适用情况:启动新项目(请改用 openai-responses 技能)
迁移:请参阅 references/migration-to-responses.md
快速开始
npm install [email protected]
import OpenAI from 'openai';
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
// 1. Create assistant
const assistant = await openai.beta.assistants.create({
name: "Math Tutor",
instructions: "You are a math tutor. Use code interpreter for calculations.",
tools: [{ type: "code_interpreter" }],
model: "gpt-5",
});
// 2. Create thread
const thread = await openai.beta.threads.create();
// 3. Add message
await openai.beta.threads.messages.create(thread.id, {
role: "user",
content: "Solve: 3x + 11 = 14",
});
// 4. Run assistant
const run = await openai.beta.threads.runs.create(thread.id, {
assistant_id: assistant.id,
});
// 5. Poll for completion
let status = await openai.beta.threads.runs.retrieve(thread.id, run.id);
while (status.status !== 'completed') {
await new Promise(r => setTimeout(r, 1000));
status = await openai.beta.threads.runs.retrieve(thread.id, run.id);
}
// 6. Get response
const messages = await openai.beta.threads.messages.list(thread.id);
console.log(messages.data[0].content[0].text.value);
核心概念
四种主要对象:
- Assistants:配置好的 AI,包含指令(v2 最多 256k 个字符,v1 为 32k)、模型、工具和元数据
- Threads:对话容器,包含持久化的消息历史记录(最多 100k 条消息)
- Messages:用户/助手消息,可选附加文件
- Runs:异步执行,包含各种状态(queued、in_progress、requires_action、completed、failed、expired)
主要 API 模式
Assistants
const assistant = await openai.beta.assistants.create({
model: "gpt-5",
instructions: "System prompt (max 256k chars in v2)",
tools: [{ type: "code_interpreter" }, { type: "file_search" }],
tool_resources: { file_search: { vector_store_ids: ["vs_123"] } },
});
主要限制:指令最多 256k 个字符(v2),最多 128 个工具,最多 16 组元数据
Threads 与 Messages
// Create thread with messages
const thread = await openai.beta.threads.create({
messages: [{ role: "user", content: "Hello" }],
});
// Add message with attachments
await openai.beta.threads.messages.create(thread.id, {
role: "user",
content: "Analyze this",
attachments: [{ file_id: "file_123", tools: [{ type: "code_interpreter" }] }],
});
// List messages
const msgs = await openai.beta.threads.messages.list(thread.id);
主要限制:每个 thread 最多 100k 条消息
Runs
// Create run with optional overrides
const run = await openai.beta.threads.runs.create(thread.id, {
assistant_id: "asst_123",
additional_messages: [{ role: "user", content: "Question" }],
max_prompt_tokens: 1000,
max_completion_tokens: 500,
});
// Poll until complete
let status = await openai.beta.threads.runs.retrieve(thread.id, run.id);
while (['queued', 'in_progress'].includes(status.status)) {
await new Promise(r => setTimeout(r, 1000));
status = await openai.beta.threads.runs.retrieve(thread.id, run.id);
}
Run 状态:queued → in_progress → requires_action(函数调用)/ completed / failed / cancelled / expired(最长 10 分钟)
流式传输
const stream = await openai.beta.threads.runs.stream(thread.id, { assistant_id });
for await (const event of stream) {
if (event.event === 'thread.message.delta') {
process.stdout.write(event.data.delta.content?.[0]?.text?.value || '');
}
}
主要事件:thread.run.created、thread.message.delta(流式内容)、thread.run.step.delta(工具进度)、thread.run.completed、thread.run.requires_action(函数调用)
工具
Code Interpreter
在沙盒中运行 Python 代码。生成图表,处理文件(CSV、JSON、PDF、图像)。每个文件最大 512MB。
// Attach file to message
attachments: [{ file_id: "file_123", tools: [{ type: "code_interpreter" }] }]
// Access generated files
for (const content of message.content) {
if (content.type === 'image_file') {
const fileContent = await openai.files.content(content.image_file.file_id);
}
}
File Search(RAG)
使用向量存储进行语义搜索。最多 10,000 个文件(v2;v1 为 20 个)。定价:$0.10/GB/天(1GB 免费)。
// Create vector store
const vs = await openai.beta.vectorStores.create({ name: "Docs" });
await openai.beta.vectorStores.files.create(vs.id, { file_id: "file_123" });
// Wait for indexing
let store = await openai.beta.vectorStores.retrieve(vs.id);
while (store.status === 'in_progress') {
await new Promise(r => setTimeout(r, 2000));
store = await openai.beta.vectorStores.retrieve(vs.id);
}
// Use in assistant
tool_resources: { file_search: { vector_store_ids: [vs.id] } }
⚠️ 使用前请等待 status: 'completed'
函数调用
当 run.status === 'requires_action' 时提交工具输出:
if (run.status === 'requires_action') {
const toolCalls = run.required_action.submit_tool_outputs.tool_calls;
const outputs = toolCalls.map(tc => ({
tool_call_id: tc.id,
output: JSON.stringify(yourFunction(JSON.parse(tc.function.arguments))),
}));
run = await openai.beta.threads.runs.submitToolOutputs(thread.id, run.id, {
tool_outputs: outputs,
});
}
文件格式
Code Interpreter:.c、.cpp、.csv、.docx、.html、.java、.json、.md、.pdf、.php、.pptx、.py、.rb、.tex、.txt、.css、.jpeg、.jpg、.js、.gif、.png、.tar、.ts、.xlsx、.xml、.zip(最大 512MB)
File Search:.c、.cpp、.docx、.html、.java、.json、.md、.pdf、.php、.pptx、.py、.rb、.tex、.txt、.css、.js、.ts、.go(最大 512MB)
已知问题
1. 线程已有正在运行的任务
Error: 400 Can't add messages to thread_xxx while a run run_xxx is active.
修复方法:先取消正在运行的任务:await openai.beta.threads.runs.cancel(threadId, runId)
2. 任务轮询超时 / 状态未完成
Error: OpenAIError: Final run has not been received
原因:长时间运行的任务可能超出轮询时间窗口,或以 incomplete 状态结束。
预防措施:妥善处理未完成的任务
try {
const stream = await openai.beta.threads.runs.stream(thread.id, { assistant_id });
for await (const event of stream) {
if (event.event === 'thread.message.delta') {
process.stdout.write(event.data.delta.content?.[0]?.text?.value || '');
}
}
} catch (error) {
if (error.message?.includes('Final run has not been received')) {
// Run ended with 'incomplete' status - thread can continue
const run = await openai.beta.threads.runs.retrieve(thread.id, runId);
if (run.status === 'incomplete') {
// Handle: prompt user to continue, reduce max_completion_tokens, etc.
}
}
}
来源:GitHub Issues #945、#1306、#1439
3. 向量存储尚未就绪
索引完成前使用向量存储。
修复方法:轮询 vectorStores.retrieve(),直到 status === 'completed'(参见“文件搜索”部分)
4. 文件上传格式问题 不受支持的文件格式会导致静默失败。 修复方法:上传前验证文件扩展名(参见“文件格式”部分)
5. 向量存储上传文档有误
Error: No 'files' provided to process
原因:官方文档展示了错误的 uploadAndPoll 用法。
预防措施:将文件流封装在 { files: [...] } 对象中
// ✅ Correct
await openai.beta.vectorStores.fileBatches.uploadAndPoll(vectorStoreId, {
files: fileStreams
});
// ❌ Wrong (shown in official docs)
await openai.beta.vectorStores.fileBatches.uploadAndPoll(vectorStoreId, fileStreams);
6. 推理模型拒绝 temperature 参数
Error: Unsupported parameter: 'temperature' is not supported with this model
原因:将助手更新为 o3-mini/o1-preview/o1-mini 时,旧的 temperature 设置仍会保留。
预防措施:明确将 temperature 设为 null
await openai.beta.assistants.update(assistantId, {
model: 'o3-mini',
reasoning_effort: 'medium',
temperature: null, // ✅ Must explicitly clear
top_p: null
});
7. uploadAndPoll 返回向量存储 ID,而非批次 ID
Error: Invalid 'batch_id': 'vs_...'. Expected an ID that begins with 'vsfb_'.
原因:uploadAndPoll 返回的是向量存储对象,而不是批次对象。
预防措施:使用其他方法获取批次 ID
// Option 1: Use createAndPoll after separate upload
const batch = await openai.vectorStores.fileBatches.createAndPoll(
vectorStoreId,
{ file_ids: uploadedFileIds }
);
// Option 2: List batches to find correct ID
const batches = await openai.vectorStores.fileBatches.list(vectorStoreId);
const batchId = batches.data[0].id; // starts with 'vsfb_'
8. 删除向量存储文件会影响所有存储 警告:从一个向量存储中删除文件,会将其从所有向量存储中移除
// ❌ This deletes file from VS_A, VS_B, AND VS_C
await openai.vectorStores.files.delete('VS_A', 'file-xxx');
原因:SDK 或 API 错误——删除操作会产生全局影响。 预防措施:如需选择性删除,请避免在多个向量存储间共享文件 来源:GitHub Issue #1710
9. 上传大文件时发生内存泄漏(社区提供)
来源:GitHub Issue #1052 | 状态:开放
影响:在长时间运行的服务中,每上传一个 22MB 文件,约有 44MB 内存泄漏。
原因:使用 vectorStores.fileBatches.uploadAndPoll 从流(如 S3)上传大文件时,上传完成后内存可能不会释放。
已验证:维护者已确认;该问题在 v4.58.1 中有所减轻,但未彻底解决。
变通方法:监控长时间运行的服务中的内存使用情况;定期重启,或使用独立的工作进程
10. 线程已有正在运行的任务——竞态条件(社区提供) 对问题 #1 的补充:取消正在运行的任务时,如果任务在取消操作前已完成,可能会发生竞态条件
async function createRunSafely(threadId: string, assistantId: string) {
// Check for active runs first
const runs = await openai.beta.threads.runs.list(threadId, { limit: 1 });
const activeRun = runs.data.find(r =>
['queued', 'in_progress', 'requires_action'].includes(r.status)
);
if (activeRun) {
try {
await openai.beta.threads.runs.cancel(threadId, activeRun.id);
// Wait for cancellation to complete
let run = await openai.beta.threads.runs.retrieve(threadId, activeRun.id);
while (run.status === 'cancelling') {
await new Promise(r => setTimeout(r, 500));
run = await openai.beta.threads.runs.retrieve(threadId, activeRun.id);
}
} catch (error) {
// Ignore "already completed" errors - run finished naturally
if (!error.message?.includes('completed')) throw error;
}
}
return openai.beta.threads.runs.create(threadId, { assistant_id: assistantId });
}
完整列表请参见 references/top-errors.md。
与其他技能的关系
openai-api(Chat Completions):无状态、需手动维护历史记录、直接返回响应。适用于简单生成。
openai-responses(Responses API):✅ 新项目推荐使用。推理能力更强,MCP 集成更现代,并且仍在积极开发。
openai-assistants:⚠️ 计划于 2026 年上半年弃用。仅用于旧版应用。迁移指南:references/migration-to-responses.md
v1 到 v2 迁移
v1 弃用日期:2024 年 12 月 18 日
主要变更:retrieval → file_search、向量存储区(10k 个文件,而非 20 个)、256k 条指令(而非 32k)、消息级文件附件
参见 references/migration-from-v1.md
模板:templates/basic-assistant.ts、code-interpreter-assistant.ts、file-search-assistant.ts、function-calling-assistant.ts、streaming-assistant.ts
参考资料:references/top-errors.md、thread-lifecycle.md、vector-stores.md、migration-to-responses.md、migration-from-v1.md
相关技能:openai-responses(推荐)、openai-api
最后更新:2026-01-21 软件包:[email protected] 状态:已准备好用于生产环境(⚠️ 已弃用——将于 2026 年 8 月 26 日停止支持) 变更:新增 6 个已知问题(向量存储区上传错误、o3-mini 温度参数、内存泄漏),增强流式错误处理