ChatGPT & Claude API Complete Tutorial
Deep learning of OpenAI GPT-4o and Anthropic Claude 3.5 API calling methods, master conversation generation, streaming output, function calling and other advanced features
Supported Models
GPT-4o
gpt-4oThe most powerful multimodal model, supporting text and images
$5.00 / 1M tokens
Vision UnderstandingFunction CallingJSON ModeStreaming Output
GPT-4o-mini
gpt-4o-miniThe most cost-effective intelligent model
$0.15 / 1M tokens
Fast ResponseCost OptimizationFunction CallingStreaming Output
GPT-3.5 Turbo
gpt-3.5-turboClassic and efficient conversation model
$0.50 / 1M tokens
Fast GenerationStable and ReliableStreaming Output
Claude 3.5 Sonnet
claude-3-5-sonnetAnthropic's latest flagship model with excellent programming capabilities
$3.00 / 1M tokens
Ultra-long ContextCode GenerationVision UnderstandingSafety Alignment
Claude 3.5 Haiku
claude-3-5-haikuLightweight and fast Claude model
$0.25 / 1M tokens
Fast ResponseCost OptimizationLong Text Processing
Code Examples
Basic Conversation
The simplest ChatGPT API call example
import openai
# Set API key and endpoint
openai.api_key = "YOUR_API_KEY"
openai.api_base = "https://api.example.com/v1"
# Send conversation request
response = openai.ChatCompletion.create(
model="gpt-4o", # Options: gpt-4o, gpt-4o-mini, gpt-3.5-turbo
messages=[
{"role": "system", "content": "You are a helpful AI assistant"},
{"role": "user", "content": "Please explain what is machine learning"}
],
temperature=0.7, # Control creativity, between 0-2
max_tokens=1000 # Maximum output length
)
print(response.choices[0].message.content)Best Practices
Optimize Prompt Design
- Use clear and specific instructions
- Provide examples and format specifications
- Set appropriate system prompts
- Use few-shot learning techniques
Token usingOptimize
- Set max_tokens parameter appropriately
- Clean up conversation history in time
- Use summaries to compress long texts
- Choose appropriate model size
Error Handling
- Implement retry mechanism
- Handle Rate Limit errors
- Validate response format
- Set timeout duration
Security Considerations
- Do not expose API keys on the client side
- Implement content filtering mechanisms
- Keep audit logs
- Set usage limits
API Response Format
Standard response format returned by ChatGPT and Claude APIs:
{
"id": "chatcmpl-abc123",
"object": "chat.completion",
"created": 1677858242,
"model": "gpt-4o",
"usage": {
"prompt_tokens": 13,
"completion_tokens": 17,
"total_tokens": 30
},
"choices": [{
"message": {
"role": "assistant",
"content": "This is the AI response content"
},
"finish_reason": "stop",
"index": 0
}]
}