Chapter 1: APIs and Integration
Connecting to AI Services
APIs are the gateway to integrating AI capabilities into your applications. Understanding how to work with AI APIs is essential for building AI-powered products.
Major AI APIs
| Provider | Main API | Key Features |
|---|---|---|
| OpenAI | GPT-4, DALL-E | Most popular, comprehensive |
| Anthropic | Claude | Safety-focused, long context |
| Gemini | Google integration | |
| Hugging Face | Multiple | Open source models |
| Cohere | Command | Enterprise-focused |
OpenAI API Basics
Authentication
from openai import OpenAI
client = OpenAI(api_key="your-api-key")
Basic Chat Completion
response = client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What is machine learning?"}
]
)
print(response.choices[0].message.content)
Key Parameters
| Parameter | Purpose |
|---|---|
| model | Which model to use |
| messages | Conversation history |
| temperature | Creativity (0-2) |
| max_tokens | Response length limit |
Anthropic (Claude) API
Basic Usage
import anthropic
client = anthropic.Anthropic(api_key="your-api-key")
message = client.messages.create(
model="claude-3-sonnet-20240229",
max_tokens=1024,
messages=[
{"role": "user", "content": "Hello, Claude"}
]
)
Rate Limits and Quotas
Understanding Limits
- Requests per minute (RPM): API calls allowed
- Tokens per minute (TPM): Text volume allowed
- Tokens per day (TPD): Daily limits
Handling Rate Limits
import time
from openai import RateLimitError
def call_with_retry(func, max_retries=3):
for attempt in range(max_retries):
try:
return func()
except RateLimitError:
time.sleep(2 ** attempt)
raise Exception("Max retries exceeded")
Pricing Considerations
Token-Based Pricing
| Model | Input | Output |
|---|---|---|
| GPT-4 | $30/1M tokens | $60/1M tokens |
| GPT-3.5 | $0.50/1M | $1.50/1M |
| Claude 3 Sonnet | $3/1M | $15/1M |
Cost Estimation
Tokens per request × Requests per day × Days × Price per token
Security Best Practices
API Key Management
- Never commit keys to code
- Use environment variables
- Rotate keys regularly
- Use different keys per environment
import os
api_key = os.environ.get("OPENAI_API_KEY")
Key Takeaways
✅ APIs enable integration of AI into applications
✅ Different providers have different strengths
✅ Rate limits and costs require planning
✅ Secure key management is essential
Next Steps
Continue to Chapter 2: Building AI-Powered Apps.