openai-sdk
Integrate OpenAI APIs into applications. Use when a user asks to add GPT or ChatGPT to an app, generate text with OpenAI, build a chatbot, use GPT-4 or o1 models, generate embeddings, use function calling, stream chat completions, build AI features, moderate content, generate images with DALL-E, transcribe audio with Whisper API, or integrate any OpenAI model. Covers Chat Completions, Assistants API, function calling, embeddings, streaming, vision, DALL-E, Whisper, and moderation.
What this skill does
# OpenAI SDK
## Overview
The OpenAI SDK provides access to GPT-4o, o1, DALL-E 3, Whisper, and embedding models. This skill covers the Chat Completions API (text generation, conversation, function calling), streaming responses, vision (image understanding), embeddings, the Assistants API (stateful agents), DALL-E image generation, Whisper transcription, and content moderation. Examples in both TypeScript/Node.js and Python.
## Instructions
### Step 1: Installation and Setup
```bash
# Node.js
npm install openai
# Python
pip install openai
```
```typescript
// lib/openai.ts — Client initialization
import OpenAI from 'openai'
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY, // or set OPENAI_API_KEY env var
})
```
### Step 2: Chat Completions
```typescript
// chat.ts — Basic chat completion and conversation
import OpenAI from 'openai'
const openai = new OpenAI()
// Single message
const response = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [
{ role: 'system', content: 'You are a helpful coding assistant.' },
{ role: 'user', content: 'Write a Python function to merge two sorted lists.' },
],
temperature: 0.7, // 0 = deterministic, 2 = creative
max_tokens: 1000,
})
console.log(response.choices[0].message.content)
// Multi-turn conversation (maintain message history)
const messages: OpenAI.ChatCompletionMessageParam[] = [
{ role: 'system', content: 'You are a data analysis assistant.' },
]
async function chat(userMessage: string) {
messages.push({ role: 'user', content: userMessage })
const response = await openai.chat.completions.create({
model: 'gpt-4o',
messages,
})
const assistantMessage = response.choices[0].message
messages.push(assistantMessage)
return assistantMessage.content
}
```
### Step 3: Streaming Responses
```typescript
// stream.ts — Stream chat completions for real-time UI
const stream = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Explain quantum computing in simple terms.' }],
stream: true,
})
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content || ''
process.stdout.write(content) // stream to terminal/UI
}
```
```typescript
// Next.js streaming API route
// app/api/chat/route.ts — Server-sent events for streaming to frontend
import { OpenAIStream, StreamingTextResponse } from 'ai' // Vercel AI SDK helper
export async function POST(req: Request) {
const { messages } = await req.json()
const response = await openai.chat.completions.create({
model: 'gpt-4o',
messages,
stream: true,
})
const stream = OpenAIStream(response)
return new StreamingTextResponse(stream)
}
```
### Step 4: Function Calling (Tool Use)
```typescript
// function_calling.ts — Let GPT call your functions
const tools: OpenAI.ChatCompletionTool[] = [
{
type: 'function',
function: {
name: 'get_weather',
description: 'Get current weather for a city',
parameters: {
type: 'object',
properties: {
city: { type: 'string', description: 'City name' },
units: { type: 'string', enum: ['celsius', 'fahrenheit'] },
},
required: ['city'],
},
},
},
{
type: 'function',
function: {
name: 'search_database',
description: 'Search the product database',
parameters: {
type: 'object',
properties: {
query: { type: 'string' },
category: { type: 'string' },
max_price: { type: 'number' },
},
required: ['query'],
},
},
},
]
const response = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: 'What is the weather in Tokyo?' }],
tools,
tool_choice: 'auto',
})
// Handle function call
const toolCall = response.choices[0].message.tool_calls?.[0]
if (toolCall) {
const args = JSON.parse(toolCall.function.arguments)
// Execute the actual function
const result = await getWeather(args.city, args.units)
// Send result back to GPT
const finalResponse = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [
{ role: 'user', content: 'What is the weather in Tokyo?' },
response.choices[0].message,
{ role: 'tool', tool_call_id: toolCall.id, content: JSON.stringify(result) },
],
tools,
})
}
```
### Step 5: Embeddings
```typescript
// embeddings.ts — Generate embeddings for semantic search
const response = await openai.embeddings.create({
model: 'text-embedding-3-small', // 1536 dimensions, cheapest
input: 'How to deploy a Node.js app to production',
})
const embedding = response.data[0].embedding // number[] of length 1536
// Batch embeddings
const batchResponse = await openai.embeddings.create({
model: 'text-embedding-3-small',
input: [
'First document text',
'Second document text',
'Third document text',
],
})
// batchResponse.data[0].embedding, batchResponse.data[1].embedding, etc.
```
### Step 6: Vision (Image Understanding)
```typescript
// vision.ts — Analyze images with GPT-4o
const response = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [{
role: 'user',
content: [
{ type: 'text', text: 'What is in this image? Describe in detail.' },
{ type: 'image_url', image_url: { url: 'https://example.com/photo.jpg' } },
],
}],
})
// Base64 image (from file upload)
const base64Image = fs.readFileSync('photo.jpg').toString('base64')
const response2 = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [{
role: 'user',
content: [
{ type: 'text', text: 'Extract all text from this receipt.' },
{ type: 'image_url', image_url: { url: `data:image/jpeg;base64,${base64Image}` } },
],
}],
})
```
### Step 7: Structured Outputs
```typescript
// structured.ts — Get JSON output matching a schema
const response = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Extract info from: John Smith, 35, Software Engineer at Google, lives in SF' }],
response_format: {
type: 'json_schema',
json_schema: {
name: 'person_info',
schema: {
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'number' },
job_title: { type: 'string' },
company: { type: 'string' },
city: { type: 'string' },
},
required: ['name', 'age', 'job_title', 'company', 'city'],
},
},
},
})
// Guaranteed to match the schema
const person = JSON.parse(response.choices[0].message.content!)
```
## Examples
### Example 1: Build a customer support chatbot with function calling
**User prompt:** "Build a chatbot for our e-commerce site that can check order status, search products, and answer FAQs using our knowledge base."
The agent will:
1. Define tools for `check_order_status`, `search_products`, and `search_knowledge_base`.
2. Create a chat endpoint with streaming for real-time responses.
3. Implement the tool execution loop (GPT calls tool → execute → send result back).
4. Add conversation history management for multi-turn interactions.
### Example 2: Build a document analysis pipeline
**User prompt:** "Users upload contracts (PDF/images). Extract key terms, dates, and parties, then generate a structured summary."
The agent will:
1. Use vision API to extract text from document images.
2. Use structured outputs to extract entities into a typed JSON schema.
3. Generate a plain-language summary with a system prompt tuned for legal documents.
## Guidelines
- Use `gpt-4o` for most tasks — it's the best balance of quality, speed, and cost. Use `gpt-4o-mini` for simple tasks where cost matters.
- Always set a `system` message to define the assistant's behavior, constraints, and output format.
- Use structured outputs (`response_format: json_schema`) when yRelated in Image & Video
watch
IncludedWatch a video (URL or local path). Downloads with yt-dlp, extracts auto-scaled frames with ffmpeg, pulls the transcript from captions (or Whisper API fallback), and hands the result to Claude so it can answer questions about what's in the video.
physical-ai-defect-image-generation
IncludedUse when the user wants to orchestrate defect image generation, run associated setup, or handle outputs on OSMO. The Day 0 path handles cold-start with USD-to-ROI, image-edit augmentation, and AnomalyGen to create initial PCBA datasets. The Day 1 path performs inference and labeling on real images. This skill helps with first-time asset setup, creation of finetuning checkpoints, and configuring deployment. Trigger keywords: defect image generation, dig workflow, dig pipeline, defect image detection workflow, aoi pipeline, aoi anomalygen, usd2roi anomalygen, day 0 pcba, day 1 pcba, day 1 real-photo alignment, day 1 manual roi, metal surface anomaly, glass defect, anomalygen finetune, setup_pcb, setup_metal, setup_glass, setup_pretrained, dig setup, dig datasets, dig pretrained checkpoint, dig image-edit endpoint.
accelint-react-best-practices
IncludedReact performance optimization and best practices. ALWAYS use this skill when working with any React code - writing components, hooks, JSX; refactoring; optimizing re-renders, memoization, state management; reviewing for performance; fixing hydration mismatches; debugging infinite re-renders, stale closures, input focus loss, animations restarting; preventing remounting; implementing transitions, lazy initialization, effect dependencies. Even simple React tasks benefit from these patterns. Covers React 19+ (useEffectEvent, Activity, ref props). Triggers - useEffect, useState, useMemo, useCallback, memo, inline components, nested components, components inside components, re-render, performance, hydration, SSR, Next.js, useDeferredValue, combined hooks.
elevenlabs-agents
IncludedBuild conversational AI voice agents with ElevenLabs Platform using React, JavaScript, React Native, or Swift SDKs. Configure agents, tools (client/server/MCP), RAG knowledge bases, multi-voice, and Scribe real-time STT. Use when: building voice chat interfaces, implementing AI phone agents with Twilio, configuring agent workflows or tools, adding RAG knowledge bases, testing with CLI "agents as code", or troubleshooting deprecated @11labs packages, Android audio cutoff, CSP violations, dynamic variables, or WebRTC config. Keywords: ElevenLabs Agents, ElevenLabs voice agents, AI voice agents, conversational AI, @elevenlabs/react, @elevenlabs/client, @elevenlabs/react-native, @elevenlabs/elevenlabs-js, @elevenlabs/agents-cli, elevenlabs SDK, voice AI, TTS, text-to-speech, ASR, speech recognition, turn-taking model, WebRTC voice, WebSocket voice, ElevenLabs conversation, agent system prompt, agent tools, agent knowledge base, RAG voice agents, multi-voice agents, pronunciation dictionary, voice speed control, elevenlabs scribe, @11labs deprecated, Android audio cutoff, CSP violation elevenlabs, dynamic variables elevenlabs, case-sensitive tool names, webhook authentication
humanizer
IncludedHumanize AI-generated text by detecting and removing patterns typical of LLM output. Rewrites text to sound natural, specific, and human. Uses 28 pattern detectors, 560+ AI vocabulary terms across 3 tiers, and statistical analysis (burstiness, type-token ratio, readability) for comprehensive detection. Use when asked to humanize text, de-AI writing, make content sound more natural/human, review writing for AI patterns, score text for AI detection, or improve AI-generated drafts. Covers content, language, style, communication, and filler categories.
generating-mermaid-diagrams
IncludedSalesforce architecture diagrams using Mermaid with ASCII fallback. Use this skill when generating text-based diagrams for Salesforce architecture, OAuth flows, ERDs, integration sequences, or Agentforce structure. TRIGGER when: user says "diagram", "visualize", "ERD", or asks for sequence diagrams, flowcharts, class diagrams, or architecture visualizations in Mermaid. DO NOT TRIGGER when: user wants PNG/SVG image output (use generating-visual-diagrams), or asks about non-Salesforce systems.