Using a Language Model in Code › The Same Pattern, Different Providers

Michael BrenndoerferJune 27, 20252 min read
AI Agent HandbookAll chapters
Part 2 of 15Language Models - The Brain of the Agent
Chapter 5Using a Language Model in Code › The Same Pattern, Different Providers
Reading section 6 of 15 · The Same Pattern, Different Providers · 2 minSection 6 of 15 · 2 min

Book contents

Section 6 of 15 · 2 min read

Using a Language Model in Code › The Same Pattern, Different ProvidersOne section · Sections in this chapter6 / 15 ↓

The core pattern (send messages, get response) is universal, but each provider has slightly different syntax. Let's see the same basic interaction using Claude and Gemini.

Example (Claude Sonnet 4.5)

In[2]:
Code
import os
from anthropic import Anthropic

## Initialize the client
client = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))

## Ask a question
## Using Claude Sonnet 4.5 for its excellent reasoning capabilities
response = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    system="You are a helpful personal assistant.",
    messages=[{"role": "user", "content": "What is 2 + 2?"}],
)

print(response.content[0].text)

Notice the differences: Claude uses messages.create() instead of chat.completions.create(), requires a max_tokens parameter (the maximum length of the response), and puts the system prompt as a separate parameter rather than in the messages list. But the fundamental pattern is identical.

Claude Sonnet 4.5 (released September 2025) is Anthropic's most advanced model, excelling at real-world agent tasks, coding, and computer use. It offers improved alignment and can handle extended autonomous work sessions. There's also Claude Haiku 4.5 (released October 2025), which is faster and more cost-efficient while matching Sonnet 4's performance in coding tasks.

Example (Gemini 2.5 Pro)

In[4]:
Code
import os
from google import genai

client = genai.Client(
    api_key=os.getenv("GEMINI_API_KEY") or os.getenv("GOOGLE_API_KEY")
)

## Ask a question
response = client.models.generate_content(
    model="gemini-2.5-flash", contents="What is 2 + 2?"
)

print(response.text)

Gemini's API is even simpler for basic use cases. You just call generate_content() with your prompt. The trade-off is less fine-grained control over things like system messages (though you can add them by structuring your prompt differently).

Gemini 2.5 Pro (released October 2025) is Google's latest model. It supports advanced tasks across many applications and competes with Claude Sonnet 4.5 and GPT-5.

Why show multiple providers? Because in real projects, you'll often choose different providers for different tasks. OpenAI might be best for general text generation, Claude for complex reasoning with tools, and Gemini for multimodal inputs. Understanding the pattern helps you switch between them easily.