Python + Grok-3 / Claude-3.5 API Integration (2026)

Learn how to use xAI Grok-3 and Anthropic Claude-3.5 APIs in Python — chat, tools, streaming, vision, and production tips.

Prerequisites

1. Grok-3 (xAI) – Basic Chat


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)
        

2. Claude-3.5 (Anthropic) – Chat + Tools


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)
        

3. Streaming Responses (Real-Time)


# 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)
        

4. Vision / Multimodal (Image + Text)


# 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)
        

5. Deployment & Best Practices 2026

  • Use environment variables for API keys
  • Rate limiting & retries (tenacity / backoff)
  • Caching (redis / local) for repeated prompts
  • FastAPI + Uvicorn for API wrapper
  • Monitoring: LangSmith / Phoenix / Prometheus

Ready to build your own AI app?

Explore All Tutorials →