OpenAI API Guide
Integrate OpenAI's GPT models into your applications.
Setup
Installation
pip install openaiAuthentication
from openai import OpenAI
client = OpenAI(api_key="sk-...")
# Or set OPENAI_API_KEY environment variable
client = OpenAI()Chat Completions
Basic Usage
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"}
]
)
print(response.choices[0].message.content)Streaming
stream = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Write a story"}],
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="")Function Calling
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather for a location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City name"
}
},
"required": ["location"]
}
}
}]
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Weather in Tokyo?"}],
tools=tools
)
# Handle tool call
tool_call = response.choices[0].message.tool_calls[0]Vision (GPT-4o)
import base64
def encode_image(path):
with open(path, "rb") as f:
return base64.standard_b64encode(f.read()).decode("utf-8")
response = client.chat.completions.create(
model="gpt-4o",
messages=[{
"role": "user",
"content": [
{"type": "text", "text": "What's in this image?"},
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{encode_image('photo.jpg')}"
}
}
]
}]
)Embeddings
response = client.embeddings.create(
model="text-embedding-3-small",
input="Hello world"
)
embedding = response.data[0].embeddingBest Practices
| Practice | Recommendation |
|---|---|
| Model selection | gpt-4o for quality, gpt-4o-mini for speed |
| Temperature | 0 for deterministic, 0.7-1 for creative |
| Max tokens | Set to control costs |
| Error handling | Handle rate limits with retries |
| Streaming | Use for long responses |
Pricing Considerations
| Model | Input | Output |
|---|---|---|
| gpt-4o | $2.50/1M | $10/1M |
| gpt-4o-mini | $0.15/1M | $0.60/1M |
| text-embedding-3-small | $0.02/1M | - |
intermediateTools & APIsUpdated 2024-12-18
Related Guides
Claude: Capabilities & Best Practices
Master Claude's unique strengths, context window, and optimal use cases.
LangChain: Building LLM Applications
Chain prompts, tools, and memory together with LangChain for powerful AI applications.
Prompt Engineering Fundamentals
Essential techniques for crafting effective prompts that get better results from AI models.
- openai
- gpt-4
- gpt api
- chatgpt api
- openai python