Build with OpenAI APIs including GPT-4, GPT-4o, function calling, embeddings, vision, and Assistants. Covers chat completions, structured outputs, streaming, and token optimization. Use when integrating OpenAI models into applications.
Install with Codex or Claude Copy this prompt, paste it into Codex, Claude, or another assistant, and let it review the skill page and install it for you.
A direct command skips the review prompt. Inspect the source before running it.
Build with OpenAI APIs including GPT-4, GPT-4o, function calling, embeddings, vision, and Assistants. Covers chat completions, structured outputs, streaming, and token optimization. Use when integrating OpenAI models into applications.
OpenAI API Skill
Build production-ready applications with OpenAI's GPT-4, GPT-4o, embeddings, vision, and Assistants API.
import json
defexecute_tool(name: str, args: dict) -> str:
"""Execute tool and return result as string."""if name == "get_weather":
# Call actual weather APIreturn json.dumps({"temp": 72, "condition": "sunny"})
elif name == "search_database":
# Query databasereturn json.dumps({"results": ["Product A", "Product B"]})
return json.dumps({"error": "Unknown tool"})
defchat_with_tools(user_message: str) -> str:
messages = [{"role": "user", "content": user_message}]
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=tools,
tool_choice="auto"# or "required" to force tool use
)
message = response.choices[0].message
# Check if model wants to call toolsif message.tool_calls:
messages.append(message) # Add assistant message with tool calls# Execute each tool callfor tool_call in message.tool_calls:
result = execute_tool(
tool_call.function.name,
json.loads(tool_call.function.arguments)
)
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": result
})
# Get final response with tool results
final_response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=tools
)
return final_response.choices[0].message.content
return message.content
Parallel Tool Calls
# Model can call multiple tools in parallel
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "What's the weather in NYC and LA?"}],
tools=tools,
parallel_tool_calls=True# Default is True
)
# Process all tool callsfor tool_call in response.choices[0].message.tool_calls:
print(f"Tool: {tool_call.function.name}")
print(f"Args: {tool_call.function.arguments}")
defget_embedding(text: str, model: str = "text-embedding-3-small") -> list[float]:
response = client.embeddings.create(
input=text,
model=model
)
return response.data[0].embedding
# Single text
embedding = get_embedding("OpenAI makes great APIs")
print(f"Dimensions: {len(embedding)}") # 1536 for small, 3072 for large# Batch embeddings (more efficient)
texts = ["First document", "Second document", "Third document"]
response = client.embeddings.create(
input=texts,
model="text-embedding-3-small"
)
embeddings = [item.embedding for item in response.data]
Reduced Dimensions
# Use dimensions parameter for smaller embeddings
response = client.embeddings.create(
input="Sample text",
model="text-embedding-3-large",
dimensions=256# Reduce from 3072 to 256
)
Semantic Search Example
import numpy as np
from typing importList, Tupledefcosine_similarity(a: List[float], b: List[float]) -> float:
return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
defsemantic_search(query: str, documents: List[str], top_k: int = 3) -> List[Tuple[str, float]]:
query_embedding = get_embedding(query)
doc_embeddings = [get_embedding(doc) for doc in documents]
similarities = [
(doc, cosine_similarity(query_embedding, emb))
for doc, emb inzip(documents, doc_embeddings)
]
returnsorted(similarities, key=lambda x: x[1], reverse=True)[:top_k]
Streaming Responses
Basic Streaming
Python:
stream = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Write a short story"}],
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
TypeScript:
const stream = await openai.chat.completions.create({
model: "gpt-4o",
messages: [{ role: "user", content: "Write a short story" }],
stream: true,
});
forawait (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content;
if (content) process.stdout.write(content);
}
Streaming with Tools
stream = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "What's the weather?"}],
tools=tools,
stream=True
)
tool_calls = []
current_tool = Nonefor chunk in stream:
delta = chunk.choices[0].delta
if delta.tool_calls:
for tc in delta.tool_calls:
if tc.index >= len(tool_calls):
tool_calls.append({
"id": tc.id,
"function": {"name": tc.function.name, "arguments": ""}
})
if tc.function.arguments:
tool_calls[tc.index]["function"]["arguments"] += tc.function.arguments
if delta.content:
print(delta.content, end="", flush=True)
Assistants API
Create an Assistant
assistant = client.beta.assistants.create(
name="Data Analyst",
instructions="You are a data analyst. Analyze data and create visualizations.",
model="gpt-4o",
tools=[
{"type": "code_interpreter"},
{"type": "file_search"}
]
)
Run a Conversation
# Create thread
thread = client.beta.threads.create()
# Add message
client.beta.threads.messages.create(
thread_id=thread.id,
role="user",
content="Analyze this CSV and create a chart"
)
# Run assistant
run = client.beta.threads.runs.create_and_poll(
thread_id=thread.id,
assistant_id=assistant.id
)
if run.status == "completed":
messages = client.beta.threads.messages.list(thread_id=thread.id)
for msg in messages.data:
if msg.role == "assistant":
print(msg.content[0].text.value)
from openai import (
OpenAIError,
APIError,
AuthenticationError,
BadRequestError,
RateLimitError
)
try:
response = client.chat.completions.create(...)
except AuthenticationError:
print("Invalid API key")
except BadRequestError as e:
print(f"Invalid request: {e.message}")
except RateLimitError:
print("Rate limited - implement backoff")
except APIError as e:
print(f"API error: {e.status_code} - {e.message}")
except OpenAIError as e:
print(f"OpenAI error: {e}")
Best Practices
System Prompt Design
SYSTEM_PROMPT = """You are a helpful assistant for {company_name}.
## Your Role
- Answer questions about our products
- Help troubleshoot issues
- Escalate complex problems to human support
## Guidelines
- Be concise and direct
- Use bullet points for lists
- If unsure, say so honestly
- Never make up information
## Tone
- Professional but friendly
- Patient with confused users
- Empathetic to frustrations
"""
Prompt Templates
from string import Template
ANALYSIS_TEMPLATE = Template("""
Analyze the following $content_type:
---
$content
---
Provide:
1. Summary (2-3 sentences)
2. Key points (bullet list)
3. Recommendations (if applicable)
""")
prompt = ANALYSIS_TEMPLATE.substitute(
content_type="customer feedback",
content="The product is great but shipping was slow..."
)
Production Checklist
Category
Recommendation
Security
Never expose API keys; use env vars
Rate Limits
Implement exponential backoff
Costs
Set usage limits; monitor daily spend
Latency
Use streaming for long responses
Reliability
Add fallback models (4o → 4o-mini)
Logging
Log prompts, responses, tokens, costs
Testing
Test with edge cases; mock in tests
Fallback Pattern
MODELS = ["gpt-4o", "gpt-4o-mini", "gpt-3.5-turbo"]
defchat_with_fallback(messages: list) -> str:
for model in MODELS:
try:
response = client.chat.completions.create(
model=model,
messages=messages,
timeout=30
)
return response.choices[0].message.content
except Exception as e:
print(f"{model} failed: {e}")
continueraise Exception("All models failed")