Sub topic 2
How Provider APIs Differ
This chapter compares what the major chat APIs ask for and what they return. Every later chapter in this tutorial depends on these differences, because the adapters and neutral types exist to hide them. It assumes you can read Python and JSON, know basic HTTP, and have called at least one hosted chat completion API.
The examples use two APIs that are widely used and differ in instructive ways: OpenAI's Chat Completions API and Anthropic's Messages API. A third, Google's Gemini generateContent API, appears in the tables where it adds a further variation. Check each provider's current documentation before you rely on a detail here. Field names and limits change between versions.
What stays the same
All three APIs share one idea. You send a model name, a list of conversation turns, and some generation settings. You get back generated text and a count of the tokens used. Because of this overlap, a single interface is possible.
The differences are in the details of that exchange. Each one is small, but each one can break code that assumes the other provider's shape.
How requests differ
Endpoint, authentication, and versioning
Each provider uses a different URL, a different way to pass the key, and a different versioning scheme.
| Aspect | OpenAI Chat Completions | Anthropic Messages | Gemini generateContent |
|---|---|---|---|
| Path | `/v1/chat/completions` | `/v1/messages` | `/v1beta/models/{model}:generateContent` |
| Auth | `Authorization: Bearer <key>` header | `x-api-key` header | API key header or query parameter, or OAuth |
| Version | Part of the path | Required `anthropic-version` header | Part of the path |
| Model name | In the body | In the body | In the URL |
Anthropic rejects a request without the anthropic-version header. Gemini puts the model in the URL, so a "model" is not purely body data there.
System prompts and roles
OpenAI treats the system prompt as a message with role system inside the messages list. Anthropic has no system role in messages. It takes the system prompt as a separate top-level system field. Gemini uses a top-level systemInstruction field and calls the assistant role model.
Required and renamed parameters
max_tokens is optional for OpenAI but required for Anthropic. If your neutral request leaves it out, an Anthropic adapter must supply a default or the call fails with a 400 error. OpenAI has also introduced max_completion_tokens for newer reasoning models, and those models may reject max_tokens. Gemini calls the setting maxOutputTokens and nests it inside generationConfig.
Temperature ranges differ too. OpenAI accepts 0 to 2. Anthropic accepts 0 to 1. A temperature of 1.5 is valid for one provider and an error for the other.
Here is the same request, "Say hello in French," for each of the first two providers.
{
"model": "gpt-4o-mini",
"messages": [
{"role": "system", "content": "You are terse."},
{"role": "user", "content": "Say hello in French."}
],
"temperature": 0.7
}{
"model": "claude-sonnet-4-5",
"system": "You are terse.",
"messages": [
{"role": "user", "content": "Say hello in French."}
],
"max_tokens": 256,
"temperature": 0.7
}The model names above are examples. Use identifiers that your account can access.
How responses differ
Where the text lives
OpenAI returns a list called choices. The text is in choices[0].message.content, which is a string, or null when the model made a tool call instead. Anthropic returns a content list of typed blocks. The text is in blocks with "type": "text", and one response can hold several blocks, such as text followed by a tool use.
Token usage and finish reasons
Token counts have different field names. The finish reason also has different names and values.
| Concept | OpenAI | Anthropic |
|---|---|---|
| Input tokens | `usage.prompt_tokens` | `usage.input_tokens` |
| Output tokens | `usage.completion_tokens` | `usage.output_tokens` |
| Finished normally | `finish_reason: "stop"` | `stop_reason: "end_turn"` |
| Hit the token limit | `"length"` | `"max_tokens"` |
| Wants to call a tool | `"tool_calls"` | `"tool_use"` |
The following script reads both response shapes into one tuple. It needs no network access, so you can run it as written.
openai_body = {
"model": "gpt-4o-mini",
"choices": [
{
"message": {"role": "assistant", "content": "Bonjour."},
"finish_reason": "stop",
}
],
"usage": {"prompt_tokens": 18, "completion_tokens": 3},
}
anthropic_body = {
"model": "claude-sonnet-4-5",
"content": [{"type": "text", "text": "Bonjour."}],
"stop_reason": "end_turn",
"usage": {"input_tokens": 18, "output_tokens": 3},
}
FINISH_REASONS = {
"stop": "stop",
"end_turn": "stop",
"length": "length",
"max_tokens": "length",
"tool_calls": "tool",
"tool_use": "tool",
}
def read_openai(body):
choice = body["choices"][0]
text = choice["message"]["content"] or ""
usage = body["usage"]
return (
text,
FINISH_REASONS.get(choice["finish_reason"], "other"),
usage["prompt_tokens"],
usage["completion_tokens"],
)
def read_anthropic(body):
text = "".join(b["text"] for b in body["content"] if b["type"] == "text")
usage = body["usage"]
return (
text,
FINISH_REASONS.get(body["stop_reason"], "other"),
usage["input_tokens"],
usage["output_tokens"],
)
assert read_openai(openai_body) == read_anthropic(anthropic_body)
print(read_openai(openai_body))Notice the or "" in the OpenAI reader and the filter on block type in the Anthropic reader. Without them, a tool-call response crashes the first reader and leaks non-text blocks into the second.
How streaming differs
Both providers stream over server-sent events (SSE), a plain HTTP response that delivers lines beginning with data:. The payloads inside differ a lot.
OpenAI sends a flat series of chunks. Each carries a small delta such as choices[0].delta.content, and the stream ends with the literal line data: [DONE]. Usage is sent only if you ask for it with a stream option.
Anthropic sends named events in a fixed order. A message_start event comes first. Then each content block gets a content_block_start, one or more content_block_delta events, and a content_block_stop. The stream ends with message_delta, which carries the stop reason and final usage, and then message_stop.
A consumer that expects text in every chunk works against OpenAI and fails on Anthropic's bookkeeping events. A later chapter covers how to normalize this.
How tool calls differ
Both providers let the model request a function call, but the data is shaped differently.
- OpenAI puts calls in
message.tool_calls. Each has anidand afunctionwith anameandarguments. Theargumentsvalue is a JSON string that you must parse. - Anthropic puts calls in
tool_usecontent blocks. Theinputis already a parsed object. - To return a result, OpenAI wants a message with role
tooland atool_call_id. Anthropic wants ausermessage holding atool_resultblock that refers to thetool_use_id. - Tool definitions differ as well. OpenAI wraps a JSON Schema under
function.parameters. Anthropic usesinput_schemaat the top level of the tool.
An adapter has to translate in both directions, and the conversation history matters as well as the single call. A history built for one provider is invalid for the other.
How errors and limits differ
All providers use HTTP status codes, but the body and the details are not the same.
| Situation | Typical status | OpenAI error | Anthropic error |
|---|---|---|---|
| Bad request | 400 | `error.type: "invalid_request_error"` | `error.type: "invalid_request_error"` |
| Bad key | 401 | `error.code: "invalid_api_key"` | `error.type: "authentication_error"` |
| Rate limited | 429 | `error.type` and `error.code` describe the limit | `error.type: "rate_limit_error"` |
| Provider overloaded | 503 or 529 | Varies by service state | `error.type: "overloaded_error"` (HTTP 529) |
The envelope differs. OpenAI wraps the details as {"error": {...}}. Anthropic adds a top-level "type": "error" beside the error object. Rate-limit headers also have different names and formats, so a generic "retry after N seconds" reader needs per-provider code.
Differences that cause quiet bugs
Some differences do not raise errors. They change behavior instead.
- Context window and output limits. Each model has its own limit on input and on output. A prompt that fits one model can fail on another.
- Tokenization. The same text produces different token counts on different providers, so cost and length estimates do not transfer.
- Content filtering. A provider may refuse a prompt or end a response early under its own policy. The finish reason for this differs and may not map to any of your values.
- Consecutive same-role messages. Some providers merge them, some reject them. Test this rather than assume.
- Unknown fields. Some APIs ignore fields they do not recognize, and some reject them. Sending an OpenAI-only field to another provider may or may not fail.
What this means for the interface
The differences fall into three groups, and each group calls for a different treatment.
- Pure translation. Field names, role placement, and response nesting. An adapter can handle these fully.
- Values that need a decision. Required
max_tokens, temperature ranges, and finish reason mapping. The adapter must apply a default, clamp a value, or raise a clear error. - Behavior that cannot be hidden. Quality, context size, filtering, and tokenization. The interface can expose these, but it cannot make two models behave the same.
The next chapters build neutral types that cover the first group, and add rules for the second. The final chapters return to the third.
Exercise
You send the same neutral request, with no max_tokens set and a temperature of 1.5, to both an OpenAI model and an Anthropic model. Name two things that can go wrong, and say where in the system each should be handled.
Show answer
First, Anthropic requires max_tokens, so the call fails with a 400 error unless the Anthropic adapter supplies a default. Second, Anthropic accepts temperatures only from 0 to 1, so 1.5 is invalid there. The adapter should clamp the value or raise a clear error. Both belong in the adapter, because they are provider-specific rules and the calling code should not know about them.
Exercise
A response arrives with stop_reason: "max_tokens" from one provider and finish_reason: "length" from another. What does your code gain by mapping both to one value, and what could it lose?
Show answer
Calling code can check one value, such as "length", to detect a truncated answer regardless of provider. The risk is that provider-specific reasons with no equivalent, such as a content-filter stop, get collapsed into a generic "other" and lose information. Keep the raw reason alongside the mapped one if you may need to debug it.