[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7ANV23HM01TMQZ7J7VGQ7QB":3,"skill-same:01M7ANV23HM01TMQZ7J7VGQ7QB":59},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":24,"commitSha":25,"skillDirectory":5,"forksCount":13,"repositoryHtmlUrl":26,"repositoryHomepageUrl":6,"ownerHtmlUrl":27,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":28,"install":29,"resources":42},"01M7ANV23HM01TMQZ7J7VGQ7QB","openai-assistants",null,"Complete guide for OpenAI's Assistants API v2: stateful conversational AI with built-in tools\n(Code Interpreter, File Search, Function Calling), vector stores for RAG (up to 10,000 files),\nthread\u002Frun lifecycle management, and streaming patterns. Both Node.js SDK and fetch approaches.\n\n⚠️ DEPRECATION NOTICE: OpenAI plans to sunset Assistants API in H1 2026 in favor of Responses API.\nThis skill remains valuable for existing apps and migration planning.\n\nUse when: building stateful chatbots with OpenAI, implementing RAG with vector stores, executing\nPython code with Code Interpreter, using file search for document Q&A, managing conversation threads,\nstreaming assistant responses, or encountering errors like \"thread already has active run\", vector\nstore indexing delays, run polling timeouts, or file upload issues.\n\nKeywords: openai assistants, assistants api, openai threads, openai runs, code interpreter assistant,\nfile search openai, vector store openai, openai rag, assistant streaming, thread persistence,\nstateful chatbot, thread already has active run, run status polling, vector store error","davidanthonyn\u002Fclaude-skills","davidanthonyn","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F55152980?v=4","01M7AJ4MY8S5C2RJCGX6626J0G","01M7AJ7JE1K98GRPH9Z57Z0R0W",0,"MIT","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fopenai-assistants\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: openai-assistants\ndescription: |\n  Complete guide for OpenAI's Assistants API v2: stateful conversational AI with built-in tools\n  (Code Interpreter, File Search, Function Calling), vector stores for RAG (up to 10,000 files),\n  thread\u002Frun lifecycle management, and streaming patterns. Both Node.js SDK and fetch approaches.\n\n  ⚠️ DEPRECATION NOTICE: OpenAI plans to sunset Assistants API in H1 2026 in favor of Responses API.\n  This skill remains valuable for existing apps and migration planning.\n\n  Use when: building stateful chatbots with OpenAI, implementing RAG with vector stores, executing\n  Python code with Code Interpreter, using file search for document Q&A, managing conversation threads,\n  streaming assistant responses, or encountering errors like \"thread already has active run\", vector\n  store indexing delays, run polling timeouts, or file upload issues.\n\n  Keywords: openai assistants, assistants api, openai threads, openai runs, code interpreter assistant,\n  file search openai, vector store openai, openai rag, assistant streaming, thread persistence,\n  stateful chatbot, thread already has active run, run status polling, vector store error\nlicense: MIT\n---\n\n# OpenAI Assistants API v2\n\n**Status**: Production Ready (Deprecated H1 2026)\n**Package**: openai@6.7.0\n**Last Updated**: 2025-10-25\n**v1 Deprecated**: December 18, 2024\n**v2 Sunset**: H1 2026 (migrate to Responses API)\n\n---\n\n## ⚠️ Important: Deprecation Notice\n\n**OpenAI announced that the Assistants API will be deprecated in favor of the [Responses API](..\u002Fopenai-responses\u002FSKILL.md).**\n\n**Timeline:**\n- ✅ **Dec 18, 2024**: Assistants API v1 deprecated\n- ⏳ **H1 2026**: Planned sunset of Assistants API v2\n- ✅ **Now**: Responses API available (recommended for new projects)\n\n**Should you still use this skill?**\n- ✅ **Yes, if**: You have existing Assistants API code (12-18 month migration window)\n- ✅ **Yes, if**: You need to maintain legacy applications\n- ✅ **Yes, if**: Planning migration from Assistants → Responses\n- ❌ **No, if**: Starting a new project (use openai-responses skill instead)\n\n**Migration Path:**\nSee `references\u002Fmigration-to-responses.md` for complete migration guide.\n\n---\n\n## Table of Contents\n\n1. [Quick Start](#quick-start)\n2. [Core Concepts](#core-concepts)\n3. [Assistants](#assistants)\n4. [Threads](#threads)\n5. [Messages](#messages)\n6. [Runs](#runs)\n7. [Streaming Runs](#streaming-runs)\n8. [Tools](#tools)\n   - [Code Interpreter](#code-interpreter)\n   - [File Search](#file-search)\n   - [Function Calling](#function-calling)\n9. [Vector Stores](#vector-stores)\n10. [File Uploads](#file-uploads)\n11. [Thread Lifecycle Management](#thread-lifecycle-management)\n12. [Error Handling](#error-handling)\n13. [Production Best Practices](#production-best-practices)\n14. [Relationship to Other Skills](#relationship-to-other-skills)\n\n---\n\n## Quick Start\n\n### Installation\n\n```bash\nnpm install openai@6.7.0\n```\n\n### Environment Setup\n\n```bash\nexport OPENAI_API_KEY=\"sk-...\"\n```\n\n### Basic Assistant (Node.js SDK)\n\n```typescript\nimport OpenAI from 'openai';\n\nconst openai = new OpenAI({\n  apiKey: process.env.OPENAI_API_KEY,\n});\n\n\u002F\u002F 1. Create an assistant\nconst assistant = await openai.beta.assistants.create({\n  name: \"Math Tutor\",\n  instructions: \"You are a personal math tutor. Write and run code to answer math questions.\",\n  tools: [{ type: \"code_interpreter\" }],\n  model: \"gpt-4o\",\n});\n\n\u002F\u002F 2. Create a thread\nconst thread = await openai.beta.threads.create();\n\n\u002F\u002F 3. Add a message to the thread\nawait openai.beta.threads.messages.create(thread.id, {\n  role: \"user\",\n  content: \"I need to solve the equation `3x + 11 = 14`. Can you help me?\",\n});\n\n\u002F\u002F 4. Create a run\nconst run = await openai.beta.threads.runs.create(thread.id, {\n  assistant_id: assistant.id,\n});\n\n\u002F\u002F 5. Poll for completion\nlet runStatus = await openai.beta.threads.runs.retrieve(thread.id, run.id);\n\nwhile (runStatus.status !== 'completed') {\n  await new Promise(resolve => setTimeout(resolve, 1000));\n  runStatus = await openai.beta.threads.runs.retrieve(thread.id, run.id);\n}\n\n\u002F\u002F 6. Retrieve messages\nconst messages = await openai.beta.threads.messages.list(thread.id);\nconsole.log(messages.data[0].content[0].text.value);\n```\n\n### Basic Assistant (Fetch - Cloudflare Workers)\n\n```typescript\n\u002F\u002F 1. Create assistant\nconst assistant = await fetch('https:\u002F\u002Fapi.openai.com\u002Fv1\u002Fassistants', {\n  method: 'POST',\n  headers: {\n    'Authorization': `Bearer ${env.OPENAI_API_KEY}`,\n    'Content-Type': 'application\u002Fjson',\n    'OpenAI-Beta': 'assistants=v2',\n  },\n  body: JSON.stringify({\n    name: \"Math Tutor\",\n    instructions: \"You are a helpful math tutor.\",\n    model: \"gpt-4o\",\n  }),\n});\n\nconst assistantData = await assistant.json();\n\n\u002F\u002F 2. Create thread\nconst thread = await fetch('https:\u002F\u002Fapi.openai.com\u002Fv1\u002Fthreads', {\n  method: 'POST',\n  headers: {\n    'Authorization': `Bearer ${env.OPENAI_API_KEY}`,\n    'Content-Type': 'application\u002Fjson',\n    'OpenAI-Beta': 'assistants=v2',\n  },\n});\n\nconst threadData = await thread.json();\n\n\u002F\u002F 3. Add message and create run\nconst run = await fetch(`https:\u002F\u002Fapi.openai.com\u002Fv1\u002Fthreads\u002F${threadData.id}\u002Fruns`, {\n  method: 'POST',\n  headers: {\n    'Authorization': `Bearer ${env.OPENAI_API_KEY}`,\n    'Content-Type': 'application\u002Fjson',\n    'OpenAI-Beta': 'assistants=v2',\n  },\n  body: JSON.stringify({\n    assistant_id: assistantData.id,\n    additional_messages: [{\n      role: \"user\",\n      content: \"What is 3x + 11 = 14?\",\n    }],\n  }),\n});\n\n\u002F\u002F Poll for completion...\n```\n\n---\n\n## Core Concepts\n\nThe Assistants API uses four main objects:\n\n### 1. **Assistants**\nConfigured AI entities with:\n- Instructions (system prompt, max 256k characters)\n- Model (gpt-4o, gpt-5, etc.)\n- Tools (Code Interpreter, File Search, Functions)\n- File attachments\n- Metadata\n\n### 2. **Threads**\nConversation containers that:\n- Store message history\n- Persist across runs\n- Can have metadata\n- Support up to 100,000 messages\n\n### 3. **Messages**\nIndividual messages in a thread:\n- User messages (input)\n- Assistant messages (output)\n- Can include file attachments\n- Support text and image content\n\n### 4. **Runs**\nExecution of an assistant on a thread:\n- Asynchronous processing\n- Multiple states (queued, in_progress, completed, failed, etc.)\n- Can stream results\n- Handle tool calls automatically\n\n---\n\n## Assistants\n\n### Create an Assistant\n\n```typescript\nconst assistant = await openai.beta.assistants.create({\n  name: \"Data Analyst\",\n  instructions: \"You are a data analyst. Use code interpreter to analyze data and create visualizations.\",\n  model: \"gpt-4o\",\n  tools: [\n    { type: \"code_interpreter\" },\n    { type: \"file_search\" },\n  ],\n  tool_resources: {\n    file_search: {\n      vector_store_ids: [\"vs_abc123\"],\n    },\n  },\n  metadata: {\n    department: \"analytics\",\n    version: \"1.0\",\n  },\n});\n```\n\n**Parameters:**\n- `model` (required): Model ID (gpt-4o, gpt-5, gpt-4-turbo)\n- `instructions`: System prompt (max 256k characters in v2, was 32k in v1)\n- `name`: Assistant name (max 256 characters)\n- `description`: Description (max 512 characters)\n- `tools`: Array of tools (max 128 tools)\n- `tool_resources`: Resources for tools (vector stores, files)\n- `temperature`: 0-2 (default 1)\n- `top_p`: 0-1 (default 1)\n- `response_format`: \"auto\", \"json_object\", or JSON schema\n- `metadata`: Key-value pairs (max 16 pairs)\n\n### Retrieve an Assistant\n\n```typescript\nconst assistant = await openai.beta.assistants.retrieve(\"asst_abc123\");\n```\n\n### Update an Assistant\n\n```typescript\nconst updatedAssistant = await openai.beta.assistants.update(\"asst_abc123\", {\n  instructions: \"Updated instructions\",\n  tools: [{ type: \"code_interpreter\" }, { type: \"file_search\" }],\n});\n```\n\n### Delete an Assistant\n\n```typescript\nawait openai.beta.assistants.del(\"asst_abc123\");\n```\n\n### List Assistants\n\n```typescript\nconst assistants = await openai.beta.assistants.list({\n  limit: 20,\n  order: \"desc\",\n});\n```\n\n---\n\n## Threads\n\nThreads store conversation history and persist across runs.\n\n### Create a Thread\n\n```typescript\n\u002F\u002F Empty thread\nconst thread = await openai.beta.threads.create();\n\n\u002F\u002F Thread with initial messages\nconst thread = await openai.beta.threads.create({\n  messages: [\n    {\n      role: \"user\",\n      content: \"Hello! I need help with Python.\",\n      metadata: { source: \"web\" },\n    },\n  ],\n  metadata: {\n    user_id: \"user_123\",\n    session_id: \"session_456\",\n  },\n});\n```\n\n### Retrieve a Thread\n\n```typescript\nconst thread = await openai.beta.threads.retrieve(\"thread_abc123\");\n```\n\n### Update Thread Metadata\n\n```typescript\nconst thread = await openai.beta.threads.update(\"thread_abc123\", {\n  metadata: {\n    user_id: \"user_123\",\n    last_active: new Date().toISOString(),\n  },\n});\n```\n\n### Delete a Thread\n\n```typescript\nawait openai.beta.threads.del(\"thread_abc123\");\n```\n\n**⚠️ Warning**: Deleting a thread also deletes all messages and runs. Cannot be undone.\n\n---\n\n## Messages\n\n### Add a Message to a Thread\n\n```typescript\nconst message = await openai.beta.threads.messages.create(\"thread_abc123\", {\n  role: \"user\",\n  content: \"Can you analyze this data?\",\n  attachments: [\n    {\n      file_id: \"file_abc123\",\n      tools: [{ type: \"code_interpreter\" }],\n    },\n  ],\n  metadata: {\n    timestamp: new Date().toISOString(),\n  },\n});\n```\n\n**Parameters:**\n- `role`: \"user\" only (assistant messages created by runs)\n- `content`: Text or array of content blocks\n- `attachments`: Files with associated tools\n- `metadata`: Key-value pairs\n\n### Retrieve a Message\n\n```typescript\nconst message = await openai.beta.threads.messages.retrieve(\n  \"thread_abc123\",\n  \"msg_abc123\"\n);\n```\n\n### List Messages\n\n```typescript\nconst messages = await openai.beta.threads.messages.list(\"thread_abc123\", {\n  limit: 20,\n  order: \"desc\", \u002F\u002F \"asc\" or \"desc\"\n});\n\n\u002F\u002F Iterate through messages\nfor (const message of messages.data) {\n  console.log(`${message.role}: ${message.content[0].text.value}`);\n}\n```\n\n### Update Message Metadata\n\n```typescript\nconst message = await openai.beta.threads.messages.update(\n  \"thread_abc123\",\n  \"msg_abc123\",\n  {\n    metadata: {\n      edited: \"true\",\n      edit_timestamp: new Date().toISOString(),\n    },\n  }\n);\n```\n\n### Delete a Message\n\n```typescript\nawait openai.beta.threads.messages.del(\"thread_abc123\", \"msg_abc123\");\n```\n\n---\n\n## Runs\n\nRuns execute an assistant on a thread.\n\n### Create a Run\n\n```typescript\nconst run = await openai.beta.threads.runs.create(\"thread_abc123\", {\n  assistant_id: \"asst_abc123\",\n  instructions: \"Please address the user as Jane Doe.\",\n  additional_messages: [\n    {\n      role: \"user\",\n      content: \"Can you help me with this?\",\n    },\n  ],\n});\n```\n\n**Parameters:**\n- `assistant_id` (required): Assistant to use\n- `instructions`: Override assistant instructions\n- `additional_messages`: Add messages before running\n- `tools`: Override assistant tools\n- `metadata`: Key-value pairs\n- `temperature`: Override temperature\n- `top_p`: Override top_p\n- `max_prompt_tokens`: Limit input tokens\n- `max_completion_tokens`: Limit output tokens\n\n### Retrieve a Run\n\n```typescript\nconst run = await openai.beta.threads.runs.retrieve(\n  \"thread_abc123\",\n  \"run_abc123\"\n);\n\nconsole.log(run.status); \u002F\u002F queued, in_progress, requires_action, completed, failed, etc.\n```\n\n### Run States\n\n| State | Description |\n|-------|-------------|\n| `queued` | Run is waiting to start |\n| `in_progress` | Run is executing |\n| `requires_action` | Function calling needs your input |\n| `cancelling` | Cancellation in progress |\n| `cancelled` | Run was cancelled |\n| `failed` | Run failed (check `last_error`) |\n| `completed` | Run finished successfully |\n| `expired` | Run expired (max 10 minutes) |\n\n### Polling Pattern\n\n```typescript\nasync function pollRunCompletion(threadId: string, runId: string) {\n  let run = await openai.beta.threads.runs.retrieve(threadId, runId);\n\n  while (['queued', 'in_progress', 'cancelling'].includes(run.status)) {\n    await new Promise(resolve => setTimeout(resolve, 1000)); \u002F\u002F Wait 1 second\n    run = await openai.beta.threads.runs.retrieve(threadId, runId);\n  }\n\n  if (run.status === 'failed') {\n    throw new Error(`Run failed: ${run.last_error?.message}`);\n  }\n\n  if (run.status === 'requires_action') {\n    \u002F\u002F Handle function calling (see Function Calling section)\n    return run;\n  }\n\n  return run; \u002F\u002F completed\n}\n\nconst run = await openai.beta.threads.runs.create(threadId, { assistant_id: assistantId });\nconst completedRun = await pollRunCompletion(threadId, run.id);\n```\n\n### Cancel a Run\n\n```typescript\nconst run = await openai.beta.threads.runs.cancel(\"thread_abc123\", \"run_abc123\");\n```\n\n**⚠️ Important**: Cancellation is asynchronous. Check `status` becomes `cancelled`.\n\n### List Runs\n\n```typescript\nconst runs = await openai.beta.threads.runs.list(\"thread_abc123\", {\n  limit: 10,\n  order: \"desc\",\n});\n```\n\n---\n\n## Streaming Runs\n\nStream run events in real-time using Server-Sent Events (SSE).\n\n### Basic Streaming\n\n```typescript\nconst stream = await openai.beta.threads.runs.stream(\"thread_abc123\", {\n  assistant_id: \"asst_abc123\",\n});\n\nfor await (const event of stream) {\n  if (event.event === 'thread.message.delta') {\n    const delta = event.data.delta.content?.[0]?.text?.value;\n    if (delta) {\n      process.stdout.write(delta);\n    }\n  }\n}\n```\n\n### Stream Event Types\n\n| Event | Description |\n|-------|-------------|\n| `thread.run.created` | Run was created |\n| `thread.run.in_progress` | Run started |\n| `thread.run.step.created` | Step created (tool call, message creation) |\n| `thread.run.step.delta` | Step progress update |\n| `thread.message.created` | Message created |\n| `thread.message.delta` | Message content streaming |\n| `thread.message.completed` | Message finished |\n| `thread.run.completed` | Run finished |\n| `thread.run.failed` | Run failed |\n| `thread.run.requires_action` | Function calling needed |\n\n### Complete Streaming Example\n\n```typescript\nasync function streamAssistantResponse(threadId: string, assistantId: string) {\n  const stream = await openai.beta.threads.runs.stream(threadId, {\n    assistant_id: assistantId,\n  });\n\n  for await (const event of stream) {\n    switch (event.event) {\n      case 'thread.run.created':\n        console.log('\\\\nRun started...');\n        break;\n\n      case 'thread.message.delta':\n        const delta = event.data.delta.content?.[0];\n        if (delta?.type === 'text' && delta.text?.value) {\n          process.stdout.write(delta.text.value);\n        }\n        break;\n\n      case 'thread.run.step.delta':\n        const toolCall = event.data.delta.step_details;\n        if (toolCall?.type === 'tool_calls') {\n          const codeInterpreter = toolCall.tool_calls?.[0]?.code_interpreter;\n          if (codeInterpreter?.input) {\n            console.log('\\\\nExecuting code:', codeInterpreter.input);\n          }\n        }\n        break;\n\n      case 'thread.run.completed':\n        console.log('\\\\n\\\\nRun completed!');\n        break;\n\n      case 'thread.run.failed':\n        console.error('\\\\nRun failed:', event.data.last_error);\n        break;\n\n      case 'thread.run.requires_action':\n        \u002F\u002F Handle function calling\n        console.log('\\\\nFunction calling required');\n        break;\n    }\n  }\n}\n```\n\n---\n\n## Tools\n\nAssistants API supports three types of tools:\n\n### Code Interpreter\n\nExecutes Python code in a sandboxed environment.\n\n**Capabilities:**\n- Run Python code\n- Generate charts\u002Fgraphs\n- Process files (CSV, JSON, text, images, etc.)\n- Return file outputs (images, data files)\n- Install packages (limited set available)\n\n**Example:**\n\n```typescript\nconst assistant = await openai.beta.assistants.create({\n  name: \"Data Analyst\",\n  instructions: \"You are a data analyst. Use Python to analyze data and create visualizations.\",\n  model: \"gpt-4o\",\n  tools: [{ type: \"code_interpreter\" }],\n});\n\n\u002F\u002F Upload a file\nconst file = await openai.files.create({\n  file: fs.createReadStream(\"sales_data.csv\"),\n  purpose: \"assistants\",\n});\n\n\u002F\u002F Create thread with file\nconst thread = await openai.beta.threads.create({\n  messages: [{\n    role: \"user\",\n    content: \"Analyze this sales data and create a visualization.\",\n    attachments: [{\n      file_id: file.id,\n      tools: [{ type: \"code_interpreter\" }],\n    }],\n  }],\n});\n\n\u002F\u002F Run\nconst run = await openai.beta.threads.runs.create(thread.id, {\n  assistant_id: assistant.id,\n});\n\n\u002F\u002F Poll for completion and retrieve outputs\n```\n\n**Output Files:**\n\nCode Interpreter can generate files (images, CSVs, etc.). Access them via:\n\n```typescript\nconst messages = await openai.beta.threads.messages.list(thread.id);\nconst message = messages.data[0];\n\nfor (const content of message.content) {\n  if (content.type === 'image_file') {\n    const fileId = content.image_file.file_id;\n    const fileContent = await openai.files.content(fileId);\n    \u002F\u002F Save or process file\n  }\n}\n```\n\n### File Search\n\nSemantic search over uploaded documents using vector stores.\n\n**Key Features:**\n- Up to 10,000 files per assistant (500x more than v1)\n- Automatic chunking and embedding\n- Vector + keyword search\n- Parallel queries with multi-threading\n- Advanced reranking\n\n**Pricing:**\n- $0.10\u002FGB\u002Fday for vector storage\n- First 1GB free\n\n**Example:**\n\n```typescript\n\u002F\u002F 1. Create vector store\nconst vectorStore = await openai.beta.vectorStores.create({\n  name: \"Product Documentation\",\n  metadata: { category: \"docs\" },\n});\n\n\u002F\u002F 2. Upload files to vector store\nconst file = await openai.files.create({\n  file: fs.createReadStream(\"product_guide.pdf\"),\n  purpose: \"assistants\",\n});\n\nawait openai.beta.vectorStores.files.create(vectorStore.id, {\n  file_id: file.id,\n});\n\n\u002F\u002F 3. Create assistant with file search\nconst assistant = await openai.beta.assistants.create({\n  name: \"Product Support\",\n  instructions: \"Use file search to answer questions about our products.\",\n  model: \"gpt-4o\",\n  tools: [{ type: \"file_search\" }],\n  tool_resources: {\n    file_search: {\n      vector_store_ids: [vectorStore.id],\n    },\n  },\n});\n\n\u002F\u002F 4. Create thread and run\nconst thread = await openai.beta.threads.create({\n  messages: [{\n    role: \"user\",\n    content: \"How do I install the product?\",\n  }],\n});\n\nconst run = await openai.beta.threads.runs.create(thread.id, {\n  assistant_id: assistant.id,\n});\n```\n\n**Best Practices:**\n- Wait for vector store status to be `completed` before using\n- Use metadata for filtering (coming soon)\n- Chunk large documents appropriately\n- Monitor storage costs\n\n### Function Calling\n\nDefine custom functions for the assistant to call.\n\n**Example:**\n\n```typescript\nconst assistant = await openai.beta.assistants.create({\n  name: \"Weather Assistant\",\n  instructions: \"You help users get weather information.\",\n  model: \"gpt-4o\",\n  tools: [{\n    type: \"function\",\n    function: {\n      name: \"get_weather\",\n      description: \"Get the current weather for a location\",\n      parameters: {\n        type: \"object\",\n        properties: {\n          location: {\n            type: \"string\",\n            description: \"City name, e.g., 'San Francisco'\",\n          },\n          unit: {\n            type: \"string\",\n            enum: [\"celsius\", \"fahrenheit\"],\n            description: \"Temperature unit\",\n          },\n        },\n        required: [\"location\"],\n      },\n    },\n  }],\n});\n\n\u002F\u002F Create thread and run\nconst thread = await openai.beta.threads.create({\n  messages: [{\n    role: \"user\",\n    content: \"What's the weather in San Francisco?\",\n  }],\n});\n\nlet run = await openai.beta.threads.runs.create(thread.id, {\n  assistant_id: assistant.id,\n});\n\n\u002F\u002F Poll until requires_action\nwhile (run.status === 'in_progress' || run.status === 'queued') {\n  await new Promise(resolve => setTimeout(resolve, 1000));\n  run = await openai.beta.threads.runs.retrieve(thread.id, run.id);\n}\n\nif (run.status === 'requires_action') {\n  const toolCalls = run.required_action.submit_tool_outputs.tool_calls;\n\n  const toolOutputs = [];\n  for (const toolCall of toolCalls) {\n    if (toolCall.function.name === 'get_weather') {\n      const args = JSON.parse(toolCall.function.arguments);\n      \u002F\u002F Call your actual weather API\n      const weather = await getWeatherAPI(args.location, args.unit);\n\n      toolOutputs.push({\n        tool_call_id: toolCall.id,\n        output: JSON.stringify(weather),\n      });\n    }\n  }\n\n  \u002F\u002F Submit tool outputs\n  run = await openai.beta.threads.runs.submitToolOutputs(thread.id, run.id, {\n    tool_outputs: toolOutputs,\n  });\n\n  \u002F\u002F Continue polling...\n}\n```\n\n---\n\n## Vector Stores\n\nVector stores enable efficient semantic search over large document collections.\n\n### Create a Vector Store\n\n```typescript\nconst vectorStore = await openai.beta.vectorStores.create({\n  name: \"Legal Documents\",\n  metadata: {\n    department: \"legal\",\n    category: \"contracts\",\n  },\n  expires_after: {\n    anchor: \"last_active_at\",\n    days: 7, \u002F\u002F Auto-delete 7 days after last use\n  },\n});\n```\n\n### Add Files to Vector Store\n\n**Single File:**\n\n```typescript\nconst file = await openai.files.create({\n  file: fs.createReadStream(\"contract.pdf\"),\n  purpose: \"assistants\",\n});\n\nawait openai.beta.vectorStores.files.create(vectorStore.id, {\n  file_id: file.id,\n});\n```\n\n**Batch Upload:**\n\n```typescript\nconst fileBatch = await openai.beta.vectorStores.fileBatches.create(vectorStore.id, {\n  file_ids: [\"file_abc123\", \"file_def456\", \"file_ghi789\"],\n});\n\n\u002F\u002F Poll for batch completion\nlet batch = await openai.beta.vectorStores.fileBatches.retrieve(vectorStore.id, fileBatch.id);\nwhile (batch.status === 'in_progress') {\n  await new Promise(resolve => setTimeout(resolve, 1000));\n  batch = await openai.beta.vectorStores.fileBatches.retrieve(vectorStore.id, fileBatch.id);\n}\n```\n\n### Check Vector Store Status\n\n```typescript\nconst vectorStore = await openai.beta.vectorStores.retrieve(\"vs_abc123\");\n\nconsole.log(vectorStore.status); \u002F\u002F \"in_progress\", \"completed\", \"failed\"\nconsole.log(vectorStore.file_counts); \u002F\u002F { in_progress: 0, completed: 50, failed: 0 }\n```\n\n**⚠️ Important**: Wait for `status: \"completed\"` before using with file search.\n\n### List Vector Stores\n\n```typescript\nconst stores = await openai.beta.vectorStores.list({\n  limit: 20,\n  order: \"desc\",\n});\n```\n\n### Update Vector Store\n\n```typescript\nconst vectorStore = await openai.beta.vectorStores.update(\"vs_abc123\", {\n  name: \"Updated Name\",\n  metadata: { updated: \"true\" },\n});\n```\n\n### Delete Vector Store\n\n```typescript\nawait openai.beta.vectorStores.del(\"vs_abc123\");\n```\n\n---\n\n## File Uploads\n\nUpload files for use with Code Interpreter or File Search.\n\n### Upload a File\n\n```typescript\nimport fs from 'fs';\n\nconst file = await openai.files.create({\n  file: fs.createReadStream(\"document.pdf\"),\n  purpose: \"assistants\",\n});\n\nconsole.log(file.id); \u002F\u002F file_abc123\n```\n\n**Supported Formats:**\n- **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\n- **File Search**: .c, .cpp, .docx, .html, .java, .json, .md, .pdf, .php, .pptx, .py, .rb, .tex, .txt, .css, .js, .ts, .go\n\n**Size Limits:**\n- Code Interpreter: 512 MB per file\n- File Search: 512 MB per file\n- Vector Store: Up to 10,000 files\n\n### Retrieve File Info\n\n```typescript\nconst file = await openai.files.retrieve(\"file_abc123\");\n```\n\n### Download File Content\n\n```typescript\nconst content = await openai.files.content(\"file_abc123\");\n\u002F\u002F Returns binary content\n```\n\n### Delete a File\n\n```typescript\nawait openai.files.del(\"file_abc123\");\n```\n\n### List Files\n\n```typescript\nconst files = await openai.files.list({\n  purpose: \"assistants\",\n});\n```\n\n---\n\n## Thread Lifecycle Management\n\nProper thread lifecycle management prevents common errors.\n\n### Pattern 1: One Thread Per User\n\n```typescript\nasync function getOrCreateUserThread(userId: string): Promise\u003Cstring> {\n  \u002F\u002F Check if thread exists in your database\n  let threadId = await db.getThreadIdForUser(userId);\n\n  if (!threadId) {\n    \u002F\u002F Create new thread\n    const thread = await openai.beta.threads.create({\n      metadata: { user_id: userId },\n    });\n    threadId = thread.id;\n    await db.saveThreadIdForUser(userId, threadId);\n  }\n\n  return threadId;\n}\n```\n\n### Pattern 2: Active Run Check\n\n```typescript\nasync function ensureNoActiveRun(threadId: string) {\n  const runs = await openai.beta.threads.runs.list(threadId, {\n    limit: 1,\n    order: \"desc\",\n  });\n\n  const latestRun = runs.data[0];\n  if (latestRun && ['queued', 'in_progress', 'cancelling'].includes(latestRun.status)) {\n    throw new Error('Thread already has an active run. Wait or cancel first.');\n  }\n}\n\n\u002F\u002F Before creating new run\nawait ensureNoActiveRun(threadId);\nconst run = await openai.beta.threads.runs.create(threadId, { assistant_id });\n```\n\n### Pattern 3: Thread Cleanup\n\n```typescript\nasync function cleanupOldThreads(maxAgeHours = 24) {\n  const threads = await openai.beta.threads.list({ limit: 100 });\n\n  for (const thread of threads.data) {\n    const createdAt = new Date(thread.created_at * 1000);\n    const ageHours = (Date.now() - createdAt.getTime()) \u002F (1000 * 60 * 60);\n\n    if (ageHours > maxAgeHours) {\n      await openai.beta.threads.del(thread.id);\n    }\n  }\n}\n```\n\n---\n\n## Error Handling\n\n### Common Errors and Solutions\n\n**1. Thread Already Has Active Run**\n\n```\nError: 400 Can't add messages to thread_xxx while a run run_xxx is active.\n```\n\n**Solution:**\n```typescript\n\u002F\u002F Wait for run to complete or cancel it\nconst run = await openai.beta.threads.runs.retrieve(threadId, runId);\nif (['queued', 'in_progress'].includes(run.status)) {\n  await openai.beta.threads.runs.cancel(threadId, runId);\n  \u002F\u002F Wait for cancellation\n  while (run.status !== 'cancelled') {\n    await new Promise(resolve => setTimeout(resolve, 500));\n    run = await openai.beta.threads.runs.retrieve(threadId, runId);\n  }\n}\n```\n\n**2. Run Polling Timeout**\n\nLong-running tasks may exceed reasonable polling windows.\n\n**Solution:**\n```typescript\nasync function pollWithTimeout(threadId: string, runId: string, maxSeconds = 300) {\n  const startTime = Date.now();\n\n  while (true) {\n    const run = await openai.beta.threads.runs.retrieve(threadId, runId);\n\n    if (!['queued', 'in_progress'].includes(run.status)) {\n      return run;\n    }\n\n    const elapsed = (Date.now() - startTime) \u002F 1000;\n    if (elapsed > maxSeconds) {\n      await openai.beta.threads.runs.cancel(threadId, runId);\n      throw new Error('Run exceeded timeout');\n    }\n\n    await new Promise(resolve => setTimeout(resolve, 1000));\n  }\n}\n```\n\n**3. Vector Store Not Ready**\n\nUsing vector store before indexing completes.\n\n**Solution:**\n```typescript\nasync function waitForVectorStore(vectorStoreId: string) {\n  let store = await openai.beta.vectorStores.retrieve(vectorStoreId);\n\n  while (store.status === 'in_progress') {\n    await new Promise(resolve => setTimeout(resolve, 2000));\n    store = await openai.beta.vectorStores.retrieve(vectorStoreId);\n  }\n\n  if (store.status === 'failed') {\n    throw new Error('Vector store indexing failed');\n  }\n\n  return store;\n}\n```\n\n**4. File Upload Format Issues**\n\nUnsupported file formats cause errors.\n\n**Solution:**\n```typescript\nconst SUPPORTED_FORMATS = {\n  code_interpreter: ['.csv', '.json', '.pdf', '.txt', '.py', '.js', '.xlsx'],\n  file_search: ['.pdf', '.docx', '.txt', '.md', '.html'],\n};\n\nfunction validateFile(filename: string, tool: string) {\n  const ext = filename.substring(filename.lastIndexOf('.')).toLowerCase();\n  if (!SUPPORTED_FORMATS[tool].includes(ext)) {\n    throw new Error(`Unsupported file format for ${tool}: ${ext}`);\n  }\n}\n```\n\nSee `references\u002Ftop-errors.md` for complete error catalog.\n\n---\n\n## Production Best Practices\n\n### 1. Use Assistant IDs (Don't Recreate)\n\n**❌ Bad:**\n```typescript\n\u002F\u002F Creates new assistant on every request!\nconst assistant = await openai.beta.assistants.create({ ... });\n```\n\n**✅ Good:**\n```typescript\n\u002F\u002F Create once, store ID, reuse\nconst ASSISTANT_ID = process.env.ASSISTANT_ID || await createAssistant();\n\nasync function createAssistant() {\n  const assistant = await openai.beta.assistants.create({ ... });\n  console.log('Save this ID:', assistant.id);\n  return assistant.id;\n}\n```\n\n### 2. Implement Proper Error Handling\n\n```typescript\nasync function createRunWithRetry(threadId: string, assistantId: string, maxRetries = 3) {\n  for (let i = 0; i \u003C maxRetries; i++) {\n    try {\n      return await openai.beta.threads.runs.create(threadId, {\n        assistant_id: assistantId,\n      });\n    } catch (error) {\n      if (error.status === 429) {\n        \u002F\u002F Rate limit - wait and retry\n        await new Promise(resolve => setTimeout(resolve, 2000 * (i + 1)));\n        continue;\n      }\n\n      if (error.message?.includes('active run')) {\n        \u002F\u002F Wait for active run to complete\n        await new Promise(resolve => setTimeout(resolve, 5000));\n        continue;\n      }\n\n      throw error; \u002F\u002F Other errors\n    }\n  }\n\n  throw new Error('Max retries exceeded');\n}\n```\n\n### 3. Monitor Costs\n\n```typescript\n\u002F\u002F Track usage\nconst run = await openai.beta.threads.runs.retrieve(threadId, runId);\nconsole.log('Tokens used:', run.usage);\n\u002F\u002F { prompt_tokens: 150, completion_tokens: 200, total_tokens: 350 }\n\n\u002F\u002F Set limits\nconst run = await openai.beta.threads.runs.create(threadId, {\n  assistant_id: assistantId,\n  max_prompt_tokens: 1000,\n  max_completion_tokens: 500,\n});\n```\n\n### 4. Clean Up Resources\n\n```typescript\n\u002F\u002F Delete old threads\nasync function cleanupUserThread(userId: string) {\n  const threadId = await db.getThreadIdForUser(userId);\n  if (threadId) {\n    await openai.beta.threads.del(threadId);\n    await db.deleteThreadIdForUser(userId);\n  }\n}\n\n\u002F\u002F Delete unused vector stores\nasync function cleanupVectorStores(keepDays = 30) {\n  const stores = await openai.beta.vectorStores.list({ limit: 100 });\n\n  for (const store of stores.data) {\n    const ageSeconds = Date.now() \u002F 1000 - store.created_at;\n    const ageDays = ageSeconds \u002F (60 * 60 * 24);\n\n    if (ageDays > keepDays) {\n      await openai.beta.vectorStores.del(store.id);\n    }\n  }\n}\n```\n\n### 5. Use Streaming for Better UX\n\n```typescript\n\u002F\u002F Show progress in real-time\nasync function streamToUser(threadId: string, assistantId: string) {\n  const stream = await openai.beta.threads.runs.stream(threadId, {\n    assistant_id: assistantId,\n  });\n\n  for await (const event of stream) {\n    if (event.event === 'thread.message.delta') {\n      const delta = event.data.delta.content?.[0]?.text?.value;\n      if (delta) {\n        \u002F\u002F Send to user immediately\n        sendToClient(delta);\n      }\n    }\n  }\n}\n```\n\n---\n\n## Relationship to Other Skills\n\n### vs. openai-api Skill\n\n**openai-api** (Chat Completions):\n- Stateless requests\n- Manual history management\n- Direct responses\n- Use for: Simple text generation, function calling\n\n**openai-assistants**:\n- Stateful conversations (threads)\n- Automatic history management\n- Built-in tools (Code Interpreter, File Search)\n- Use for: Chatbots, data analysis, RAG\n\n### vs. openai-responses Skill\n\n**openai-responses** (Responses API):\n- ✅ **Recommended for new projects**\n- Better reasoning preservation\n- Modern MCP integration\n- Active development\n\n**openai-assistants**:\n- ⚠️ **Deprecated in H1 2026**\n- Use for legacy apps\n- Migration path available\n\n**Migration:** See `references\u002Fmigration-to-responses.md`\n\n---\n\n## Migration from v1 to v2\n\n**v1 deprecated**: December 18, 2024\n\n**Key Changes:**\n1. **Retrieval → File Search**: `retrieval` tool replaced with `file_search`\n2. **Vector Stores**: Files now organized in vector stores (10,000 file limit)\n3. **Instructions Limit**: Increased from 32k to 256k characters\n4. **File Attachments**: Now message-level instead of assistant-level\n\nSee `references\u002Fmigration-from-v1.md` for complete guide.\n\n---\n\n## Next Steps\n\n**Templates:**\n- `templates\u002Fbasic-assistant.ts` - Simple math tutor\n- `templates\u002Fcode-interpreter-assistant.ts` - Data analysis\n- `templates\u002Ffile-search-assistant.ts` - RAG with vector stores\n- `templates\u002Ffunction-calling-assistant.ts` - Custom tools\n- `templates\u002Fstreaming-assistant.ts` - Real-time streaming\n\n**References:**\n- `references\u002Ftop-errors.md` - 12 common errors and solutions\n- `references\u002Fthread-lifecycle.md` - Thread management patterns\n- `references\u002Fvector-stores.md` - Vector store deep dive\n\n**Related Skills:**\n- `openai-responses` - Modern replacement (recommended)\n- `openai-api` - Chat Completions (stateless)\n\n---\n\n**Last Updated**: 2025-10-25\n**Package Version**: openai@6.7.0\n**Status**: Production Ready (Deprecated H1 2026)\n","# OpenAI Assistants API v2\n\n**Status**: Production Ready (Deprecated H1 2026)\n**Package**: openai@6.7.0\n**Last Updated**: 2025-10-25\n**v1 Deprecated**: December 18, 2024\n**v2 Sunset**: H1 2026 (migrate to Responses API)\n\n---\n\n## ⚠️ Important: Deprecation Notice\n\n**OpenAI announced that the Assistants API will be deprecated in favor of the [Responses API](..\u002Fopenai-responses\u002FSKILL.md).**\n\n**Timeline:**\n- ✅ **Dec 18, 2024**: Assistants API v1 deprecated\n- ⏳ **H1 2026**: Planned sunset of Assistants API v2\n- ✅ **Now**: Responses API available (recommended for new projects)\n\n**Should you still use this skill?**\n- ✅ **Yes, if**: You have existing Assistants API code (12-18 month migration window)\n- ✅ **Yes, if**: You need to maintain legacy applications\n- ✅ **Yes, if**: Planning migration from Assistants → Responses\n- ❌ **No, if**: Starting a new project (use openai-responses skill instead)\n\n**Migration Path:**\nSee `references\u002Fmigration-to-responses.md` for complete migration guide.\n\n---\n\n## Table of Contents\n\n1. [Quick Start](#quick-start)\n2. [Core Concepts](#core-concepts)\n3. [Assistants](#assistants)\n4. [Threads](#threads)\n5. [Messages](#messages)\n6. [Runs](#runs)\n7. [Streaming Runs](#streaming-runs)\n8. [Tools](#tools)\n   - [Code Interpreter](#code-interpreter)\n   - [File Search](#file-search)\n   - [Function Calling](#function-calling)\n9. [Vector Stores](#vector-stores)\n10. [File Uploads](#file-uploads)\n11. [Thread Lifecycle Management](#thread-lifecycle-management)\n12. [Error Handling](#error-handling)\n13. [Production Best Practices](#production-best-practices)\n14. [Relationship to Other Skills](#relationship-to-other-skills)\n\n---\n\n## Quick Start\n\n### Installation\n\n```bash\nnpm install openai@6.7.0\n```\n\n### Environment Setup\n\n```bash\nexport OPENAI_API_KEY=\"sk-...\"\n```\n\n### Basic Assistant (Node.js SDK)\n\n```typescript\nimport OpenAI from 'openai';\n\nconst openai = new OpenAI({\n  apiKey: process.env.OPENAI_API_KEY,\n});\n\n\u002F\u002F 1. Create an assistant\nconst assistant = await openai.beta.assistants.create({\n  name: \"Math Tutor\",\n  instructions: \"You are a personal math tutor. Write and run code to answer math questions.\",\n  tools: [{ type: \"code_interpreter\" }],\n  model: \"gpt-4o\",\n});\n\n\u002F\u002F 2. Create a thread\nconst thread = await openai.beta.threads.create();\n\n\u002F\u002F 3. Add a message to the thread\nawait openai.beta.threads.messages.create(thread.id, {\n  role: \"user\",\n  content: \"I need to solve the equation `3x + 11 = 14`. Can you help me?\",\n});\n\n\u002F\u002F 4. Create a run\nconst run = await openai.beta.threads.runs.create(thread.id, {\n  assistant_id: assistant.id,\n});\n\n\u002F\u002F 5. Poll for completion\nlet runStatus = await openai.beta.threads.runs.retrieve(thread.id, run.id);\n\nwhile (runStatus.status !== 'completed') {\n  await new Promise(resolve => setTimeout(resolve, 1000));\n  runStatus = await openai.beta.threads.runs.retrieve(thread.id, run.id);\n}\n\n\u002F\u002F 6. Retrieve messages\nconst messages = await openai.beta.threads.messages.list(thread.id);\nconsole.log(messages.data[0].content[0].text.value);\n```\n\n### Basic Assistant (Fetch - Cloudflare Workers)\n\n```typescript\n\u002F\u002F 1. Create assistant\nconst assistant = await fetch('https:\u002F\u002Fapi.openai.com\u002Fv1\u002Fassistants', {\n  method: 'POST',\n  headers: {\n    'Authorization': `Bearer ${env.OPENAI_API_KEY}`,\n    'Content-Type': 'application\u002Fjson',\n    'OpenAI-Beta': 'assistants=v2',\n  },\n  body: JSON.stringify({\n    name: \"Math Tutor\",\n    instructions: \"You are a helpful math tutor.\",\n    model: \"gpt-4o\",\n  }),\n});\n\nconst assistantData = await assistant.json();\n\n\u002F\u002F 2. Create thread\nconst thread = await fetch('https:\u002F\u002Fapi.openai.com\u002Fv1\u002Fthreads', {\n  method: 'POST',\n  headers: {\n    'Authorization': `Bearer ${env.OPENAI_API_KEY}`,\n    'Content-Type': 'application\u002Fjson',\n    'OpenAI-Beta': 'assistants=v2',\n  },\n});\n\nconst threadData = await thread.json();\n\n\u002F\u002F 3. Add message and create run\nconst run = await fetch(`https:\u002F\u002Fapi.openai.com\u002Fv1\u002Fthreads\u002F${threadData.id}\u002Fruns`, {\n  method: 'POST',\n  headers: {\n    'Authorization': `Bearer ${env.OPENAI_API_KEY}`,\n    'Content-Type': 'application\u002Fjson',\n    'OpenAI-Beta': 'assistants=v2',\n  },\n  body: JSON.stringify({\n    assistant_id: assistantData.id,\n    additional_messages: [{\n      role: \"user\",\n      content: \"What is 3x + 11 = 14?\",\n    }],\n  }),\n});\n\n\u002F\u002F Poll for completion...\n```\n\n---\n\n## Core Concepts\n\nThe Assistants API uses four main objects:\n\n### 1. **Assistants**\nConfigured AI entities with:\n- Instructions (system prompt, max 256k characters)\n- Model (gpt-4o, gpt-5, etc.)\n- Tools (Code Interpreter, File Search, Functions)\n- File attachments\n- Metadata\n\n### 2. **Threads**\nConversation containers that:\n- Store message history\n- Persist across runs\n- Can have metadata\n- Support up to 100,000 messages\n\n### 3. **Messages**\nIndividual messages in a thread:\n- User messages (input)\n- Assistant messages (output)\n- Can include file attachments\n- Support text and image content\n\n### 4. **Runs**\nExecution of an assistant on a thread:\n- Asynchronous processing\n- Multiple states (queued, in_progress, completed, failed, etc.)\n- Can stream results\n- Handle tool calls automatically\n\n---\n\n## Assistants\n\n### Create an Assistant\n\n```typescript\nconst assistant = await openai.beta.assistants.create({\n  name: \"Data Analyst\",\n  instructions: \"You are a data analyst. Use code interpreter to analyze data and create visualizations.\",\n  model: \"gpt-4o\",\n  tools: [\n    { type: \"code_interpreter\" },\n    { type: \"file_search\" },\n  ],\n  tool_resources: {\n    file_search: {\n      vector_store_ids: [\"vs_abc123\"],\n    },\n  },\n  metadata: {\n    department: \"analytics\",\n    version: \"1.0\",\n  },\n});\n```\n\n**Parameters:**\n- `model` (required): Model ID (gpt-4o, gpt-5, gpt-4-turbo)\n- `instructions`: System prompt (max 256k characters in v2, was 32k in v1)\n- `name`: Assistant name (max 256 characters)\n- `description`: Description (max 512 characters)\n- `tools`: Array of tools (max 128 tools)\n- `tool_resources`: Resources for tools (vector stores, files)\n- `temperature`: 0-2 (default 1)\n- `top_p`: 0-1 (default 1)\n- `response_format`: \"auto\", \"json_object\", or JSON schema\n- `metadata`: Key-value pairs (max 16 pairs)\n\n### Retrieve an Assistant\n\n```typescript\nconst assistant = await openai.beta.assistants.retrieve(\"asst_abc123\");\n```\n\n### Update an Assistant\n\n```typescript\nconst updatedAssistant = await openai.beta.assistants.update(\"asst_abc123\", {\n  instructions: \"Updated instructions\",\n  tools: [{ type: \"code_interpreter\" }, { type: \"file_search\" }],\n});\n```\n\n### Delete an Assistant\n\n```typescript\nawait openai.beta.assistants.del(\"asst_abc123\");\n```\n\n### List Assistants\n\n```typescript\nconst assistants = await openai.beta.assistants.list({\n  limit: 20,\n  order: \"desc\",\n});\n```\n\n---\n\n## Threads\n\nThreads store conversation history and persist across runs.\n\n### Create a Thread\n\n```typescript\n\u002F\u002F Empty thread\nconst thread = await openai.beta.threads.create();\n\n\u002F\u002F Thread with initial messages\nconst thread = await openai.beta.threads.create({\n  messages: [\n    {\n      role: \"user\",\n      content: \"Hello! I need help with Python.\",\n      metadata: { source: \"web\" },\n    },\n  ],\n  metadata: {\n    user_id: \"user_123\",\n    session_id: \"session_456\",\n  },\n});\n```\n\n### Retrieve a Thread\n\n```typescript\nconst thread = await openai.beta.threads.retrieve(\"thread_abc123\");\n```\n\n### Update Thread Metadata\n\n```typescript\nconst thread = await openai.beta.threads.update(\"thread_abc123\", {\n  metadata: {\n    user_id: \"user_123\",\n    last_active: new Date().toISOString(),\n  },\n});\n```\n\n### Delete a Thread\n\n```typescript\nawait openai.beta.threads.del(\"thread_abc123\");\n```\n\n**⚠️ Warning**: Deleting a thread also deletes all messages and runs. Cannot be undone.\n\n---\n\n## Messages\n\n### Add a Message to a Thread\n\n```typescript\nconst message = await openai.beta.threads.messages.create(\"thread_abc123\", {\n  role: \"user\",\n  content: \"Can you analyze this data?\",\n  attachments: [\n    {\n      file_id: \"file_abc123\",\n      tools: [{ type: \"code_interpreter\" }],\n    },\n  ],\n  metadata: {\n    timestamp: new Date().toISOString(),\n  },\n});\n```\n\n**Parameters:**\n- `role`: \"user\" only (assistant messages created by runs)\n- `content`: Text or array of content blocks\n- `attachments`: Files with associated tools\n- `metadata`: Key-value pairs\n\n### Retrieve a Message\n\n```typescript\nconst message = await openai.beta.threads.messages.retrieve(\n  \"thread_abc123\",\n  \"msg_abc123\"\n);\n```\n\n### List Messages\n\n```typescript\nconst messages = await openai.beta.threads.messages.list(\"thread_abc123\", {\n  limit: 20,\n  order: \"desc\", \u002F\u002F \"asc\" or \"desc\"\n});\n\n\u002F\u002F Iterate through messages\nfor (const message of messages.data) {\n  console.log(`${message.role}: ${message.content[0].text.value}`);\n}\n```\n\n### Update Message Metadata\n\n```typescript\nconst message = await openai.beta.threads.messages.update(\n  \"thread_abc123\",\n  \"msg_abc123\",\n  {\n    metadata: {\n      edited: \"true\",\n      edit_timestamp: new Date().toISOString(),\n    },\n  }\n);\n```\n\n### Delete a Message\n\n```typescript\nawait openai.beta.threads.messages.del(\"thread_abc123\", \"msg_abc123\");\n```\n\n---\n\n## Runs\n\nRuns execute an assistant on a thread.\n\n### Create a Run\n\n```typescript\nconst run = await openai.beta.threads.runs.create(\"thread_abc123\", {\n  assistant_id: \"asst_abc123\",\n  instructions: \"Please address the user as Jane Doe.\",\n  additional_messages: [\n    {\n      role: \"user\",\n      content: \"Can you help me with this?\",\n    },\n  ],\n});\n```\n\n**Parameters:**\n- `assistant_id` (required): Assistant to use\n- `instructions`: Override assistant instructions\n- `additional_messages`: Add messages before running\n- `tools`: Override assistant tools\n- `metadata`: Key-value pairs\n- `temperature`: Override temperature\n- `top_p`: Override top_p\n- `max_prompt_tokens`: Limit input tokens\n- `max_completion_tokens`: Limit output tokens\n\n### Retrieve a Run\n\n```typescript\nconst run = await openai.beta.threads.runs.retrieve(\n  \"thread_abc123\",\n  \"run_abc123\"\n);\n\nconsole.log(run.status); \u002F\u002F queued, in_progress, requires_action, completed, failed, etc.\n```\n\n### Run States\n\n| State | Description |\n|-------|-------------|\n| `queued` | Run is waiting to start |\n| `in_progress` | Run is executing |\n| `requires_action` | Function calling needs your input |\n| `cancelling` | Cancellation in progress |\n| `cancelled` | Run was cancelled |\n| `failed` | Run failed (check `last_error`) |\n| `completed` | Run finished successfully |\n| `expired` | Run expired (max 10 minutes) |\n\n### Polling Pattern\n\n```typescript\nasync function pollRunCompletion(threadId: string, runId: string) {\n  let run = await openai.beta.threads.runs.retrieve(threadId, runId);\n\n  while (['queued', 'in_progress', 'cancelling'].includes(run.status)) {\n    await new Promise(resolve => setTimeout(resolve, 1000)); \u002F\u002F Wait 1 second\n    run = await openai.beta.threads.runs.retrieve(threadId, runId);\n  }\n\n  if (run.status === 'failed') {\n    throw new Error(`Run failed: ${run.last_error?.message}`);\n  }\n\n  if (run.status === 'requires_action') {\n    \u002F\u002F Handle function calling (see Function Calling section)\n    return run;\n  }\n\n  return run; \u002F\u002F completed\n}\n\nconst run = await openai.beta.threads.runs.create(threadId, { assistant_id: assistantId });\nconst completedRun = await pollRunCompletion(threadId, run.id);\n```\n\n### Cancel a Run\n\n```typescript\nconst run = await openai.beta.threads.runs.cancel(\"thread_abc123\", \"run_abc123\");\n```\n\n**⚠️ Important**: Cancellation is asynchronous. Check `status` becomes `cancelled`.\n\n### List Runs\n\n```typescript\nconst runs = await openai.beta.threads.runs.list(\"thread_abc123\", {\n  limit: 10,\n  order: \"desc\",\n});\n```\n\n---\n\n## Streaming Runs\n\nStream run events in real-time using Server-Sent Events (SSE).\n\n### Basic Streaming\n\n```typescript\nconst stream = await openai.beta.threads.runs.stream(\"thread_abc123\", {\n  assistant_id: \"asst_abc123\",\n});\n\nfor await (const event of stream) {\n  if (event.event === 'thread.message.delta') {\n    const delta = event.data.delta.content?.[0]?.text?.value;\n    if (delta) {\n      process.stdout.write(delta);\n    }\n  }\n}\n```\n\n### Stream Event Types\n\n| Event | Description |\n|-------|-------------|\n| `thread.run.created` | Run was created |\n| `thread.run.in_progress` | Run started |\n| `thread.run.step.created` | Step created (tool call, message creation) |\n| `thread.run.step.delta` | Step progress update |\n| `thread.message.created` | Message created |\n| `thread.message.delta` | Message content streaming |\n| `thread.message.completed` | Message finished |\n| `thread.run.completed` | Run finished |\n| `thread.run.failed` | Run failed |\n| `thread.run.requires_action` | Function calling needed |\n\n### Complete Streaming Example\n\n```typescript\nasync function streamAssistantResponse(threadId: string, assistantId: string) {\n  const stream = await openai.beta.threads.runs.stream(threadId, {\n    assistant_id: assistantId,\n  });\n\n  for await (const event of stream) {\n    switch (event.event) {\n      case 'thread.run.created':\n        console.log('\\\\nRun started...');\n        break;\n\n      case 'thread.message.delta':\n        const delta = event.data.delta.content?.[0];\n        if (delta?.type === 'text' && delta.text?.value) {\n          process.stdout.write(delta.text.value);\n        }\n        break;\n\n      case 'thread.run.step.delta':\n        const toolCall = event.data.delta.step_details;\n        if (toolCall?.type === 'tool_calls') {\n          const codeInterpreter = toolCall.tool_calls?.[0]?.code_interpreter;\n          if (codeInterpreter?.input) {\n            console.log('\\\\nExecuting code:', codeInterpreter.input);\n          }\n        }\n        break;\n\n      case 'thread.run.completed':\n        console.log('\\\\n\\\\nRun completed!');\n        break;\n\n      case 'thread.run.failed':\n        console.error('\\\\nRun failed:', event.data.last_error);\n        break;\n\n      case 'thread.run.requires_action':\n        \u002F\u002F Handle function calling\n        console.log('\\\\nFunction calling required');\n        break;\n    }\n  }\n}\n```\n\n---\n\n## Tools\n\nAssistants API supports three types of tools:\n\n### Code Interpreter\n\nExecutes Python code in a sandboxed environment.\n\n**Capabilities:**\n- Run Python code\n- Generate charts\u002Fgraphs\n- Process files (CSV, JSON, text, images, etc.)\n- Return file outputs (images, data files)\n- Install packages (limited set available)\n\n**Example:**\n\n```typescript\nconst assistant = await openai.beta.assistants.create({\n  name: \"Data Analyst\",\n  instructions: \"You are a data analyst. Use Python to analyze data and create visualizations.\",\n  model: \"gpt-4o\",\n  tools: [{ type: \"code_interpreter\" }],\n});\n\n\u002F\u002F Upload a file\nconst file = await openai.files.create({\n  file: fs.createReadStream(\"sales_data.csv\"),\n  purpose: \"assistants\",\n});\n\n\u002F\u002F Create thread with file\nconst thread = await openai.beta.threads.create({\n  messages: [{\n    role: \"user\",\n    content: \"Analyze this sales data and create a visualization.\",\n    attachments: [{\n      file_id: file.id,\n      tools: [{ type: \"code_interpreter\" }],\n    }],\n  }],\n});\n\n\u002F\u002F Run\nconst run = await openai.beta.threads.runs.create(thread.id, {\n  assistant_id: assistant.id,\n});\n\n\u002F\u002F Poll for completion and retrieve outputs\n```\n\n**Output Files:**\n\nCode Interpreter can generate files (images, CSVs, etc.). Access them via:\n\n```typescript\nconst messages = await openai.beta.threads.messages.list(thread.id);\nconst message = messages.data[0];\n\nfor (const content of message.content) {\n  if (content.type === 'image_file') {\n    const fileId = content.image_file.file_id;\n    const fileContent = await openai.files.content(fileId);\n    \u002F\u002F Save or process file\n  }\n}\n```\n\n### File Search\n\nSemantic search over uploaded documents using vector stores.\n\n**Key Features:**\n- Up to 10,000 files per assistant (500x more than v1)\n- Automatic chunking and embedding\n- Vector + keyword search\n- Parallel queries with multi-threading\n- Advanced reranking\n\n**Pricing:**\n- $0.10\u002FGB\u002Fday for vector storage\n- First 1GB free\n\n**Example:**\n\n```typescript\n\u002F\u002F 1. Create vector store\nconst vectorStore = await openai.beta.vectorStores.create({\n  name: \"Product Documentation\",\n  metadata: { category: \"docs\" },\n});\n\n\u002F\u002F 2. Upload files to vector store\nconst file = await openai.files.create({\n  file: fs.createReadStream(\"product_guide.pdf\"),\n  purpose: \"assistants\",\n});\n\nawait openai.beta.vectorStores.files.create(vectorStore.id, {\n  file_id: file.id,\n});\n\n\u002F\u002F 3. Create assistant with file search\nconst assistant = await openai.beta.assistants.create({\n  name: \"Product Support\",\n  instructions: \"Use file search to answer questions about our products.\",\n  model: \"gpt-4o\",\n  tools: [{ type: \"file_search\" }],\n  tool_resources: {\n    file_search: {\n      vector_store_ids: [vectorStore.id],\n    },\n  },\n});\n\n\u002F\u002F 4. Create thread and run\nconst thread = await openai.beta.threads.create({\n  messages: [{\n    role: \"user\",\n    content: \"How do I install the product?\",\n  }],\n});\n\nconst run = await openai.beta.threads.runs.create(thread.id, {\n  assistant_id: assistant.id,\n});\n```\n\n**Best Practices:**\n- Wait for vector store status to be `completed` before using\n- Use metadata for filtering (coming soon)\n- Chunk large documents appropriately\n- Monitor storage costs\n\n### Function Calling\n\nDefine custom functions for the assistant to call.\n\n**Example:**\n\n```typescript\nconst assistant = await openai.beta.assistants.create({\n  name: \"Weather Assistant\",\n  instructions: \"You help users get weather information.\",\n  model: \"gpt-4o\",\n  tools: [{\n    type: \"function\",\n    function: {\n      name: \"get_weather\",\n      description: \"Get the current weather for a location\",\n      parameters: {\n        type: \"object\",\n        properties: {\n          location: {\n            type: \"string\",\n            description: \"City name, e.g., 'San Francisco'\",\n          },\n          unit: {\n            type: \"string\",\n            enum: [\"celsius\", \"fahrenheit\"],\n            description: \"Temperature unit\",\n          },\n        },\n        required: [\"location\"],\n      },\n    },\n  }],\n});\n\n\u002F\u002F Create thread and run\nconst thread = await openai.beta.threads.create({\n  messages: [{\n    role: \"user\",\n    content: \"What's the weather in San Francisco?\",\n  }],\n});\n\nlet run = await openai.beta.threads.runs.create(thread.id, {\n  assistant_id: assistant.id,\n});\n\n\u002F\u002F Poll until requires_action\nwhile (run.status === 'in_progress' || run.status === 'queued') {\n  await new Promise(resolve => setTimeout(resolve, 1000));\n  run = await openai.beta.threads.runs.retrieve(thread.id, run.id);\n}\n\nif (run.status === 'requires_action') {\n  const toolCalls = run.required_action.submit_tool_outputs.tool_calls;\n\n  const toolOutputs = [];\n  for (const toolCall of toolCalls) {\n    if (toolCall.function.name === 'get_weather') {\n      const args = JSON.parse(toolCall.function.arguments);\n      \u002F\u002F Call your actual weather API\n      const weather = await getWeatherAPI(args.location, args.unit);\n\n      toolOutputs.push({\n        tool_call_id: toolCall.id,\n        output: JSON.stringify(weather),\n      });\n    }\n  }\n\n  \u002F\u002F Submit tool outputs\n  run = await openai.beta.threads.runs.submitToolOutputs(thread.id, run.id, {\n    tool_outputs: toolOutputs,\n  });\n\n  \u002F\u002F Continue polling...\n}\n```\n\n---\n\n## Vector Stores\n\nVector stores enable efficient semantic search over large document collections.\n\n### Create a Vector Store\n\n```typescript\nconst vectorStore = await openai.beta.vectorStores.create({\n  name: \"Legal Documents\",\n  metadata: {\n    department: \"legal\",\n    category: \"contracts\",\n  },\n  expires_after: {\n    anchor: \"last_active_at\",\n    days: 7, \u002F\u002F Auto-delete 7 days after last use\n  },\n});\n```\n\n### Add Files to Vector Store\n\n**Single File:**\n\n```typescript\nconst file = await openai.files.create({\n  file: fs.createReadStream(\"contract.pdf\"),\n  purpose: \"assistants\",\n});\n\nawait openai.beta.vectorStores.files.create(vectorStore.id, {\n  file_id: file.id,\n});\n```\n\n**Batch Upload:**\n\n```typescript\nconst fileBatch = await openai.beta.vectorStores.fileBatches.create(vectorStore.id, {\n  file_ids: [\"file_abc123\", \"file_def456\", \"file_ghi789\"],\n});\n\n\u002F\u002F Poll for batch completion\nlet batch = await openai.beta.vectorStores.fileBatches.retrieve(vectorStore.id, fileBatch.id);\nwhile (batch.status === 'in_progress') {\n  await new Promise(resolve => setTimeout(resolve, 1000));\n  batch = await openai.beta.vectorStores.fileBatches.retrieve(vectorStore.id, fileBatch.id);\n}\n```\n\n### Check Vector Store Status\n\n```typescript\nconst vectorStore = await openai.beta.vectorStores.retrieve(\"vs_abc123\");\n\nconsole.log(vectorStore.status); \u002F\u002F \"in_progress\", \"completed\", \"failed\"\nconsole.log(vectorStore.file_counts); \u002F\u002F { in_progress: 0, completed: 50, failed: 0 }\n```\n\n**⚠️ Important**: Wait for `status: \"completed\"` before using with file search.\n\n### List Vector Stores\n\n```typescript\nconst stores = await openai.beta.vectorStores.list({\n  limit: 20,\n  order: \"desc\",\n});\n```\n\n### Update Vector Store\n\n```typescript\nconst vectorStore = await openai.beta.vectorStores.update(\"vs_abc123\", {\n  name: \"Updated Name\",\n  metadata: { updated: \"true\" },\n});\n```\n\n### Delete Vector Store\n\n```typescript\nawait openai.beta.vectorStores.del(\"vs_abc123\");\n```\n\n---\n\n## File Uploads\n\nUpload files for use with Code Interpreter or File Search.\n\n### Upload a File\n\n```typescript\nimport fs from 'fs';\n\nconst file = await openai.files.create({\n  file: fs.createReadStream(\"document.pdf\"),\n  purpose: \"assistants\",\n});\n\nconsole.log(file.id); \u002F\u002F file_abc123\n```\n\n**Supported Formats:**\n- **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\n- **File Search**: .c, .cpp, .docx, .html, .java, .json, .md, .pdf, .php, .pptx, .py, .rb, .tex, .txt, .css, .js, .ts, .go\n\n**Size Limits:**\n- Code Interpreter: 512 MB per file\n- File Search: 512 MB per file\n- Vector Store: Up to 10,000 files\n\n### Retrieve File Info\n\n```typescript\nconst file = await openai.files.retrieve(\"file_abc123\");\n```\n\n### Download File Content\n\n```typescript\nconst content = await openai.files.content(\"file_abc123\");\n\u002F\u002F Returns binary content\n```\n\n### Delete a File\n\n```typescript\nawait openai.files.del(\"file_abc123\");\n```\n\n### List Files\n\n```typescript\nconst files = await openai.files.list({\n  purpose: \"assistants\",\n});\n```\n\n---\n\n## Thread Lifecycle Management\n\nProper thread lifecycle management prevents common errors.\n\n### Pattern 1: One Thread Per User\n\n```typescript\nasync function getOrCreateUserThread(userId: string): Promise\u003Cstring> {\n  \u002F\u002F Check if thread exists in your database\n  let threadId = await db.getThreadIdForUser(userId);\n\n  if (!threadId) {\n    \u002F\u002F Create new thread\n    const thread = await openai.beta.threads.create({\n      metadata: { user_id: userId },\n    });\n    threadId = thread.id;\n    await db.saveThreadIdForUser(userId, threadId);\n  }\n\n  return threadId;\n}\n```\n\n### Pattern 2: Active Run Check\n\n```typescript\nasync function ensureNoActiveRun(threadId: string) {\n  const runs = await openai.beta.threads.runs.list(threadId, {\n    limit: 1,\n    order: \"desc\",\n  });\n\n  const latestRun = runs.data[0];\n  if (latestRun && ['queued', 'in_progress', 'cancelling'].includes(latestRun.status)) {\n    throw new Error('Thread already has an active run. Wait or cancel first.');\n  }\n}\n\n\u002F\u002F Before creating new run\nawait ensureNoActiveRun(threadId);\nconst run = await openai.beta.threads.runs.create(threadId, { assistant_id });\n```\n\n### Pattern 3: Thread Cleanup\n\n```typescript\nasync function cleanupOldThreads(maxAgeHours = 24) {\n  const threads = await openai.beta.threads.list({ limit: 100 });\n\n  for (const thread of threads.data) {\n    const createdAt = new Date(thread.created_at * 1000);\n    const ageHours = (Date.now() - createdAt.getTime()) \u002F (1000 * 60 * 60);\n\n    if (ageHours > maxAgeHours) {\n      await openai.beta.threads.del(thread.id);\n    }\n  }\n}\n```\n\n---\n\n## Error Handling\n\n### Common Errors and Solutions\n\n**1. Thread Already Has Active Run**\n\n```\nError: 400 Can't add messages to thread_xxx while a run run_xxx is active.\n```\n\n**Solution:**\n```typescript\n\u002F\u002F Wait for run to complete or cancel it\nconst run = await openai.beta.threads.runs.retrieve(threadId, runId);\nif (['queued', 'in_progress'].includes(run.status)) {\n  await openai.beta.threads.runs.cancel(threadId, runId);\n  \u002F\u002F Wait for cancellation\n  while (run.status !== 'cancelled') {\n    await new Promise(resolve => setTimeout(resolve, 500));\n    run = await openai.beta.threads.runs.retrieve(threadId, runId);\n  }\n}\n```\n\n**2. Run Polling Timeout**\n\nLong-running tasks may exceed reasonable polling windows.\n\n**Solution:**\n```typescript\nasync function pollWithTimeout(threadId: string, runId: string, maxSeconds = 300) {\n  const startTime = Date.now();\n\n  while (true) {\n    const run = await openai.beta.threads.runs.retrieve(threadId, runId);\n\n    if (!['queued', 'in_progress'].includes(run.status)) {\n      return run;\n    }\n\n    const elapsed = (Date.now() - startTime) \u002F 1000;\n    if (elapsed > maxSeconds) {\n      await openai.beta.threads.runs.cancel(threadId, runId);\n      throw new Error('Run exceeded timeout');\n    }\n\n    await new Promise(resolve => setTimeout(resolve, 1000));\n  }\n}\n```\n\n**3. Vector Store Not Ready**\n\nUsing vector store before indexing completes.\n\n**Solution:**\n```typescript\nasync function waitForVectorStore(vectorStoreId: string) {\n  let store = await openai.beta.vectorStores.retrieve(vectorStoreId);\n\n  while (store.status === 'in_progress') {\n    await new Promise(resolve => setTimeout(resolve, 2000));\n    store = await openai.beta.vectorStores.retrieve(vectorStoreId);\n  }\n\n  if (store.status === 'failed') {\n    throw new Error('Vector store indexing failed');\n  }\n\n  return store;\n}\n```\n\n**4. File Upload Format Issues**\n\nUnsupported file formats cause errors.\n\n**Solution:**\n```typescript\nconst SUPPORTED_FORMATS = {\n  code_interpreter: ['.csv', '.json', '.pdf', '.txt', '.py', '.js', '.xlsx'],\n  file_search: ['.pdf', '.docx', '.txt', '.md', '.html'],\n};\n\nfunction validateFile(filename: string, tool: string) {\n  const ext = filename.substring(filename.lastIndexOf('.')).toLowerCase();\n  if (!SUPPORTED_FORMATS[tool].includes(ext)) {\n    throw new Error(`Unsupported file format for ${tool}: ${ext}`);\n  }\n}\n```\n\nSee `references\u002Ftop-errors.md` for complete error catalog.\n\n---\n\n## Production Best Practices\n\n### 1. Use Assistant IDs (Don't Recreate)\n\n**❌ Bad:**\n```typescript\n\u002F\u002F Creates new assistant on every request!\nconst assistant = await openai.beta.assistants.create({ ... });\n```\n\n**✅ Good:**\n```typescript\n\u002F\u002F Create once, store ID, reuse\nconst ASSISTANT_ID = process.env.ASSISTANT_ID || await createAssistant();\n\nasync function createAssistant() {\n  const assistant = await openai.beta.assistants.create({ ... });\n  console.log('Save this ID:', assistant.id);\n  return assistant.id;\n}\n```\n\n### 2. Implement Proper Error Handling\n\n```typescript\nasync function createRunWithRetry(threadId: string, assistantId: string, maxRetries = 3) {\n  for (let i = 0; i \u003C maxRetries; i++) {\n    try {\n      return await openai.beta.threads.runs.create(threadId, {\n        assistant_id: assistantId,\n      });\n    } catch (error) {\n      if (error.status === 429) {\n        \u002F\u002F Rate limit - wait and retry\n        await new Promise(resolve => setTimeout(resolve, 2000 * (i + 1)));\n        continue;\n      }\n\n      if (error.message?.includes('active run')) {\n        \u002F\u002F Wait for active run to complete\n        await new Promise(resolve => setTimeout(resolve, 5000));\n        continue;\n      }\n\n      throw error; \u002F\u002F Other errors\n    }\n  }\n\n  throw new Error('Max retries exceeded');\n}\n```\n\n### 3. Monitor Costs\n\n```typescript\n\u002F\u002F Track usage\nconst run = await openai.beta.threads.runs.retrieve(threadId, runId);\nconsole.log('Tokens used:', run.usage);\n\u002F\u002F { prompt_tokens: 150, completion_tokens: 200, total_tokens: 350 }\n\n\u002F\u002F Set limits\nconst run = await openai.beta.threads.runs.create(threadId, {\n  assistant_id: assistantId,\n  max_prompt_tokens: 1000,\n  max_completion_tokens: 500,\n});\n```\n\n### 4. Clean Up Resources\n\n```typescript\n\u002F\u002F Delete old threads\nasync function cleanupUserThread(userId: string) {\n  const threadId = await db.getThreadIdForUser(userId);\n  if (threadId) {\n    await openai.beta.threads.del(threadId);\n    await db.deleteThreadIdForUser(userId);\n  }\n}\n\n\u002F\u002F Delete unused vector stores\nasync function cleanupVectorStores(keepDays = 30) {\n  const stores = await openai.beta.vectorStores.list({ limit: 100 });\n\n  for (const store of stores.data) {\n    const ageSeconds = Date.now() \u002F 1000 - store.created_at;\n    const ageDays = ageSeconds \u002F (60 * 60 * 24);\n\n    if (ageDays > keepDays) {\n      await openai.beta.vectorStores.del(store.id);\n    }\n  }\n}\n```\n\n### 5. Use Streaming for Better UX\n\n```typescript\n\u002F\u002F Show progress in real-time\nasync function streamToUser(threadId: string, assistantId: string) {\n  const stream = await openai.beta.threads.runs.stream(threadId, {\n    assistant_id: assistantId,\n  });\n\n  for await (const event of stream) {\n    if (event.event === 'thread.message.delta') {\n      const delta = event.data.delta.content?.[0]?.text?.value;\n      if (delta) {\n        \u002F\u002F Send to user immediately\n        sendToClient(delta);\n      }\n    }\n  }\n}\n```\n\n---\n\n## Relationship to Other Skills\n\n### vs. openai-api Skill\n\n**openai-api** (Chat Completions):\n- Stateless requests\n- Manual history management\n- Direct responses\n- Use for: Simple text generation, function calling\n\n**openai-assistants**:\n- Stateful conversations (threads)\n- Automatic history management\n- Built-in tools (Code Interpreter, File Search)\n- Use for: Chatbots, data analysis, RAG\n\n### vs. openai-responses Skill\n\n**openai-responses** (Responses API):\n- ✅ **Recommended for new projects**\n- Better reasoning preservation\n- Modern MCP integration\n- Active development\n\n**openai-assistants**:\n- ⚠️ **Deprecated in H1 2026**\n- Use for legacy apps\n- Migration path available\n\n**Migration:** See `references\u002Fmigration-to-responses.md`\n\n---\n\n## Migration from v1 to v2\n\n**v1 deprecated**: December 18, 2024\n\n**Key Changes:**\n1. **Retrieval → File Search**: `retrieval` tool replaced with `file_search`\n2. **Vector Stores**: Files now organized in vector stores (10,000 file limit)\n3. **Instructions Limit**: Increased from 32k to 256k characters\n4. **File Attachments**: Now message-level instead of assistant-level\n\nSee `references\u002Fmigration-from-v1.md` for complete guide.\n\n---\n\n## Next Steps\n\n**Templates:**\n- `templates\u002Fbasic-assistant.ts` - Simple math tutor\n- `templates\u002Fcode-interpreter-assistant.ts` - Data analysis\n- `templates\u002Ffile-search-assistant.ts` - RAG with vector stores\n- `templates\u002Ffunction-calling-assistant.ts` - Custom tools\n- `templates\u002Fstreaming-assistant.ts` - Real-time streaming\n\n**References:**\n- `references\u002Ftop-errors.md` - 12 common errors and solutions\n- `references\u002Fthread-lifecycle.md` - Thread management patterns\n- `references\u002Fvector-stores.md` - Vector store deep dive\n\n**Related Skills:**\n- `openai-responses` - Modern replacement (recommended)\n- `openai-api` - Chat Completions (stateless)\n\n---\n\n**Last Updated**: 2025-10-25\n**Package Version**: openai@6.7.0\n**Status**: Production Ready (Deprecated H1 2026)\n",{"name":5,"license":14,"description":23},"Complete guide for OpenAI's Assistants API v2: stateful conversational AI with built-in tools\n(Code Interpreter, File Search, Function Calling), vector stores for RAG (up to 10,000 files),\nthread\u002Frun lifecycle management, and streaming patterns. Both Node.js SDK and fetch approaches.\n\n⚠️ DEPRECATION NOTICE: OpenAI plans to sunset Assistants API in H1 2026 in favor of Responses API.\nThis skill remains valuable for existing apps and migration planning.\n\nUse when: building stateful chatbots with OpenAI, implementing RAG with vector stores, executing\nPython code with Code Interpreter, using file search for document Q&A, managing conversation threads,\nstreaming assistant responses, or encountering errors like \"thread already has active run\", vector\nstore indexing delays, run polling timeouts, or file upload issues.\n\nKeywords: openai assistants, assistants api, openai threads, openai runs, code interpreter assistant,\nfile search openai, vector store openai, openai rag, assistant streaming, thread persistence,\nstateful chatbot, thread already has active run, run status polling, vector store error\n","main","45d5ac830c3e238eeba6d0b4e6fd7cf6b56bf380","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn","2026-09-09 16:05:56",{"source":8,"skillName":5,"commands":30,"prompt":40,"zipAvailable":41},[31,34,37],{"tool":32,"command":33},"npx","npx skills add davidanthonyn\u002Fclaude-skills --skill openai-assistants",{"tool":35,"command":36},"bunx","bunx skills add davidanthonyn\u002Fclaude-skills --skill openai-assistants",{"tool":38,"command":39},"pnpm","pnpm dlx skills add davidanthonyn\u002Fclaude-skills --skill openai-assistants","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fopenai-assistants\u002FSKILL.md",true,[43,49,53],{"path":44,"resourceType":45,"resourceTypeDesc":46,"sizeBytes":47,"sourceHtmlUrl":48},"README.md","REFERENCE","参考文档",8309,"https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fopenai-assistants\u002FREADME.md",{"path":50,"resourceType":45,"resourceTypeDesc":46,"sizeBytes":51,"sourceHtmlUrl":52},"SKILL.json",35621,"https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fopenai-assistants\u002FSKILL.json",{"path":54,"resourceType":55,"resourceTypeDesc":56,"sizeBytes":57,"sourceHtmlUrl":58},"SKILL.md.backup","OTHER","其他",32372,"https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fopenai-assistants\u002FSKILL.md.backup",[60,67,75,82,89,98],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":18},"01M7AQPHJF528A4MD52YZEZV3R","zustand-state-management","Production-tested setup for Zustand state management in React applications with TypeScript.\nThis skill provides comprehensive patterns for building scalable, type-safe global state.\n\nUse when: setting up global state in React, migrating from Redux or Context API, implementing\nstate persistence with localStorage, configuring TypeScript with Zustand, using slices pattern\nfor modular stores, adding devtools middleware for debugging, handling Next.js SSR hydration,\nor encountering hydration errors, TypeScript inference issues, or persist middleware problems.\n\nPrevents 5 documented issues: Next.js hydration mismatches, TypeScript double parentheses\nsyntax errors, persist middleware export errors, infinite render loops, and slices pattern\ntype inference failures.\n\nKeywords: zustand, state management, React state, TypeScript state, persist middleware,\ndevtools, slices pattern, global state, React hooks, create store, useBoundStore,\nStateCreator, hydration error, text content mismatch, infinite render, localStorage,\nsessionStorage, immer middleware, shallow equality, selector pattern, zustand v5","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fzustand-state-management\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":71,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":18},"01M7AQP2XJRPNYEH323GJ81NN5","zetic-mlange","Help users integrate the ZETIC Melange (MLange) on-device AI SDK into Android (Kotlin\u002FJava) and iOS (Swift) mobile apps. Use this skill whenever the user mentions Zetic, MLange, Melange, ZeticMLangeModel, ZeticMLangeLLMModel, ZeticMLangeHFModel, on-device NPU inference for mobile, or deploying ML models to Android\u002FiOS with NPU acceleration. Also trigger when users ask about running LLMs on-device with GGUF quantization, mobile NPU model deployment, or converting PyTorch\u002FONNX models for mobile inference. Covers general model inference, LLM inference (streaming token generation), and HuggingFace model loading.","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fzetic-mlange\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fzetic-mlange\u002FSKILL.md",[],[],{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":18},"01M7AQNEJHD27NNF5PYQDSW8B9","youtube-downloader","Download videos, audio, playlists, and channels from YouTube and 1000+ websites using yt-dlp. Supports quality selection, format conversion, subtitle download, playlist filtering, metadata extraction, thumbnail download, and batch operations. Use when downloading YouTube videos in any quality (4K, 8K, HDR), extracting audio as MP3\u002FM4A\u002FFLAC, downloading entire playlists\u002Fchannels, getting subtitles in multiple languages, converting to specific formats, downloading live streams, archiving content, or batch processing multiple URLs. Optimized for reliability with automatic retries, rate limiting, and error handling.","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fyoutube-downloader\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":18},"01M7AQJQSD2H04EE2EPNAQ8A3M","wordpress-plugin-core","This skill provides comprehensive knowledge for WordPress plugin development, covering core patterns, security best practices, database interactions, hooks\u002Ffilters, Settings API, custom post types, REST API, and AJAX. This skill should be used when creating WordPress plugins, troubleshooting security issues, implementing custom post types\u002Ftaxonomies, building admin interfaces, or working with the WordPress database.\n\nUse when: Creating new WordPress plugins, implementing nonces\u002Fsanitization\u002Fescaping, working with $wpdb and prepared statements, building Settings API pages, registering custom post types or taxonomies, implementing REST API endpoints, handling AJAX requests, debugging plugin activation\u002Fdeactivation issues, preventing SQL injection\u002FXSS\u002FCSRF vulnerabilities.\n\nKeywords: wordpress plugin development, wordpress security, wordpress hooks, wordpress filters, wordpress database, wpdb prepare, sanitize_text_field, esc_html, wp_nonce, custom post type, register_post_type, settings api, rest api, admin-ajax, wordpress sql injection, wordpress xss, wordpress csrf, plugin header, activation hook, deactivation hook, wordpress coding standards, wordpress plugin architecture","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fwordpress-plugin-core\u002FSKILL.md",[],[],{"skillNo":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":93,"licenseFileUrl":94,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":18},"01M7AQJ91T970QCFMN9R1EHZXV","webapp-testing","Test local web applications with Playwright. Use when asked to verify frontend functionality, debug UI behavior, capture browser screenshots, or inspect browser logs.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fwebapp-testing\u002FSKILL.md",[],[],{"skillNo":99,"name":100,"nameZh":6,"description":101,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":18},"01M7AQJ5E89MS8C5K3GZTY4B48","web-performance-audit","Audit web performance using Chrome DevTools MCP. Use when asked to audit, profile, debug, or optimize page load performance, Lighthouse scores, or site speed.","https:\u002F\u002Fgithub.com\u002Fdavidanthonyn\u002Fclaude-skills\u002Fblob\u002Fmain\u002Fweb-performance-audit\u002FSKILL.md",[],[]]