Learn how to use xAI Grok-3 and Anthropic Claude-3.5 APIs in Python — chat, tools, streaming, vision, and production tips.
from openai import OpenAI
import os
client = OpenAI(
api_key=os.getenv("XAI_API_KEY"),
base_url="https://api.x.ai/v1",
)
response = client.chat.completions.create(
model="grok-3",
messages=[
{"role": "system", "content": "You are Grok, helpful and maximally truthful."},
{"role": "user", "content": "Explain quantum computing in simple terms."}
],
temperature=0.7,
max_tokens=500,
stream=False
)
print(response.choices[0].message.content)
from anthropic import Anthropic
client = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))
message = client.messages.create(
model="claude-3-5-sonnet-20240620",
max_tokens=1024,
temperature=0.7,
system="You are Claude, helpful, honest, and harmless.",
messages=[
{"role": "user", "content": "Plan a 3-day trip to Dubai in 2026"}
],
tools=[
{
"name": "get_weather",
"description": "Get current weather for a city",
"input_schema": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"]
}
}
]
)
print(message.content[0].text)
# Grok-3 streaming
stream = client.chat.completions.create(
model="grok-3",
messages=[{"role": "user", "content": "Tell a short story"}],
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
# Claude-3.5 Vision
message = client.messages.create(
model="claude-3-5-sonnet-20240620",
max_tokens=1024,
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "Describe this image and suggest improvements."},
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/jpeg",
"data": "base64_encoded_image_here"
}
}
]
}
]
)
print(message.content[0].text)