openai-assistants について
OpenAI Assistants API v2 を使うアプリの保守や移行を支援するスキルガイドです。アシスタント、スレッド、実行、ストリーミング、ツールを扱い、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);
基本概念
主な 4 つのオブジェクト:
- Assistants:指示(v2 では最大 256k 文字、v1 では 32k 文字)、モデル、ツール、メタデータを設定した AI
- 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);
主な制限:スレッドあたり 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);
}
実行状態: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' になるまで待機してください
Function Calling
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. スレッドに実行中の Run がすでに存在する
Error: 400 Can't add messages to thread_xxx while a run run_xxx is active.
修正方法:まず実行中の Run をキャンセルします:await openai.beta.threads.runs.cancel(threadId, runId)
2. Run のポーリングがタイムアウトする/ステータスが未完了になる
Error: OpenAIError: Final run has not been received
発生する理由:長時間実行されるタスクはポーリングの制限時間を超えたり、incomplete ステータスで終了したりすることがあります。
予防策:未完了の Run を適切に処理します。
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 の Issue #945、#1306、#1439
3. ベクトルストアの準備ができていない
インデックス作成が完了する前にベクトルストアを使用しています。
修正方法:status === 'completed' になるまで vectorStores.retrieve() をポーリングします(「ファイル検索」セクションを参照)。
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. ベクトルストアのファイル削除がすべてのストアに影響する 警告:1 つのベクトルストアからファイルを削除すると、すべてのベクトルストアからそのファイルが削除されます。
// ❌ 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. スレッドに実行中の Run がすでに存在する — 競合状態(コミュニティからの情報) Issue #1 の補足:実行中の Run をキャンセルするとき、キャンセル前に Run が完了した場合、競合状態が発生することがあります。
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、ベクトルストア(20件から10,000件のファイルに増加)、指示の文字数(32kから256kに増加)、メッセージ単位のファイル添付
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 の temperature、メモリーリーク)、ストリーミングのエラーハンドリングを強化