Two request shapes, one codebase: writing a thin model adapter

Anyone building a product on language models eventually meets two request formats. Anthropic's Messages API is what you use to call Claude natively. The OpenAI chat completions format has become a de facto standard that many other providers, routers and local runners also accept. Developers shipping small services, such as a FastAPI app that rewrites business text in a formal register, or an editor extension built on an agent SDK, have to decide which format their code speaks and how hard it will be to switch later.
This article compares the two formats field by field, shows a compact adapter that lets the rest of your code ignore the difference and offers a rule of thumb for which to target first. The free endpoint on this site speaks only the OpenAI chat format. It is an independent service, not affiliated with Anthropic, and Anthropic's official API reference is the authority on its own format.
Frequently asked questions
What is the Messages API?
Anthropic's native HTTP API for Claude. You send a model name, a maximum token count, an optional top-level system prompt and a list of user and assistant messages; the reply contains a list of content blocks.
What is the chat completions format?
The request shape popularised by OpenAI: a model name and a list of messages with roles including system, user and assistant. The reply puts the text under choices[0].message.content. Many providers and local runners accept it.
How does the system prompt differ between them?
In chat completions it is simply the first message with role system. In the Messages API it is a separate top-level system field, and the messages list contains only user and assistant turns.
Which is better to code against first?
If your product will only ever use Claude, the native Messages API gives you every Claude feature. If you want to switch or mix providers, coding to an internal interface with adapters for both formats keeps you flexible.
Is max_tokens required in both?
In the Messages API it is required. In chat completions it is usually optional, with a provider-specific default. Setting it explicitly in both is a good habit.
Can I call Claude with an OpenAI client library?
Anthropic has documented an OpenAI SDK compatibility option intended mainly for testing. Check its official docs for what is supported, since some Claude-specific features need the native API.
What format does the free endpoint here use?
Only OpenAI-style: /v1/chat/completions and /v1/completions, with model free-ai. It does not accept the Messages format, and free-ai is not a Claude model.
Why two formats exist
Both formats solve the same problem: send a conversation to a model and get a reply. They differ because they grew up separately, each shaped by its provider's features and design taste. The chat completions format came first in wide use and became a lingua franca, so many open-source servers and routers adopted it to be compatible with existing client libraries.
Anthropic designed its Messages API around Claude's capabilities, with structured content blocks that accommodate text, images, tool use and other features cleanly. Neither is objectively better; they are different contracts.
In practice, most teams meet both. They prototype with a library that speaks the chat format, then adopt Claude for some tasks and discover that the native API looks different. Or they start on Claude and later want a cheaper model for bulk work. Knowing the differences in advance turns either move into an afternoon's work instead of a week's.
Compatibility is a network effect
Because so many tools accept the chat format, code written for it can talk to a long list of back ends with only a change of base URL. That is why the free endpoint here uses it.
Native APIs expose everything
A provider's own format is where new features appear first. Compatibility layers tend to lag or omit provider-specific options.
Request differences, side by side
The core of a request looks similar in both formats, but the details trip people up when switching. The list below covers the differences you meet first.
None of these differences is hard on its own. The trouble comes when they are scattered across a codebase: a system prompt built one way in one file, another way elsewhere, and response parsing copied into every route. Collecting the format knowledge in one place is the real fix.
Message content can be a list
In the Messages API, a message's content may be a string or a list of typed blocks. Plain text requests can use a string, but code that reads replies must handle blocks.
- Endpoint:
/v1/messageson Anthropic versus/v1/chat/completionsin the chat format - Auth: an
x-api-keyheader plus ananthropic-versionheader, versus a bearer token inAuthorization - System prompt: a top-level
systemfield versus a message with rolesystem - Length cap:
max_tokensis required in Messages, optional in most chat implementations - Roles: Messages lists alternate between user and assistant turns

Response differences
Replies differ more than requests. A chat completions response wraps the answer in a choices list; you read choices[0].message.content and the reason it stopped in finish_reason. Token counts appear in usage.prompt_tokens and usage.completion_tokens.
A Messages response returns a content list of blocks. For text, you join the text of blocks whose type is text. The stop reason is in stop_reason, and usage reports input_tokens and output_tokens. A cost tracker must map both naming schemes to the same fields, as discussed in tracking API spend.
Stop reasons mean similar things
Both report whether the model finished naturally or hit the length limit. Check it: a truncated answer looks like a complete one until you read the end.
Errors have different bodies
Status codes are similar, such as 429 for rate limits, but error JSON is structured differently. Log the raw body until your adapter normalises it.
Streaming in each format
Both formats stream over server-sent events, but the events differ. The chat format sends chunks whose choices[0].delta.content holds the next piece of text and ends the stream with a line reading data: [DONE]. The free endpoint on this site follows that convention exactly.
The Messages API sends typed events, for example one that starts the message, deltas that carry text for a content block and one that ends the message. Official SDKs for both formats hide these details behind an iterator, which is the easiest way to stay correct.
Buffer for structured output
If you expect JSON, collect the whole stream before parsing. Partial JSON cannot be parsed safely, whatever the format.
from openai import OpenAI
client = OpenAI(base_url="https://api.anthropickeyfreeapi.com/v1", api_key="none")
stream = client.chat.completions.create(
model="free-ai",
stream=True,
messages=[{"role": "user", "content": "Explain server-sent events in two sentences."}],
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
print()
A thin adapter that speaks both
The cleanest way to stay flexible is to define one internal function, such as complete(system, messages, max_tokens), that returns plain text and usage, and implement it once per format. Application code calls only that function. Switching or mixing providers becomes configuration.
The adapter below uses requests so the differences are visible. The Anthropic branch reads the model name and key from environment variables; take the model ID from Anthropic's current model list.
Keep the internal shape minimal
Start with text in and text out plus usage. Add tools, images or streaming to the interface only when a feature needs them, and implement them per provider.
import os
import requests
def complete(system, messages, max_tokens=1024, provider="free"):
"""messages: list of {"role": "user"|"assistant", "content": str}"""
if provider == "anthropic":
r = requests.post(
"https://api.anthropic.com/v1/messages",
headers={
"x-api-key": os.environ["ANTHROPIC_API_KEY"],
"anthropic-version": "2023-06-01",
"content-type": "application/json",
},
json={"model": os.environ["ANTHROPIC_MODEL"], "max_tokens": max_tokens,
"system": system, "messages": messages},
timeout=120,
)
r.raise_for_status()
d = r.json()
text = "".join(b["text"] for b in d["content"] if b["type"] == "text")
return text, d["usage"]["input_tokens"], d["usage"]["output_tokens"]
r = requests.post(
"https://api.anthropickeyfreeapi.com/v1/chat/completions",
json={"model": "free-ai", "max_tokens": max_tokens,
"messages": [{"role": "system", "content": system}] + messages},
timeout=120,
)
r.raise_for_status()
d = r.json()
u = d.get("usage") or {}
return d["choices"][0]["message"]["content"], u.get("prompt_tokens"), u.get("completion_tokens")
print(complete("Answer in one sentence.", [{"role": "user", "content": "What is an adapter pattern?"}]))Tools, images and other advanced features
Beyond plain text, the formats diverge further. Tool definitions, tool calls and tool results are represented differently, and so are images and documents. If your product depends heavily on these, the adapter grows, and you may decide that one provider's native format is worth committing to.
The free endpoint here is text only, so image and document features need a multimodal provider. For tool use that works with any text model, a prompt-and-JSON loop, as shown in portable skills and tool loops, avoids format-specific tool APIs entirely.
Feature parity is not guaranteed
A compatibility layer may accept a request yet ignore a field it does not support. Test every feature you rely on against every back end you configure.

Choosing a format for a new service
A small service built around one model, such as a text-formality API on top of Claude, is simplest if it calls that provider's native format directly. You get all its features and the official SDK. Put the call behind one function anyway, because requirements change.
A product that will mix models, fall back between providers or run locally in development is better served by the adapter pattern from day one, with the chat format as the default because so many back ends speak it. The comparison of small vs large models covers why mixing is often worth it.
Prototype on the common format
Building the first version against an OpenAI-compatible endpoint, such as the free one here, lets you develop without keys or billing, then add a native branch for your production provider.
Testing across formats
Write a small contract test for your adapter: send the same prompt to every configured back end and assert that you get non-empty text, sensible usage numbers and a normal stop reason. Run it in CI against the free endpoint, and occasionally against paid providers, to catch breaking changes early.
Respect limits while testing. The endpoint here allows one request per second per IP with bursts of three, two in parallel and 10,000 requests per day, and returns 429 with Retry-After or 503 when busy. A test suite that runs a few dozen calls is well within that.
Use the free endpoint in CI
Because it needs no key, the endpoint can run in pull-request pipelines from forks without exposing secrets. Keep the number of calls small and treat its failures as warnings, since there is no service guarantee.

Migrating existing code
If your code already calls one format directly in many places, migrate gradually. Introduce the adapter, move one call site at a time and keep both paths until the tests pass. Search for every place that reads choices[0] or content[0]; those are the lines that break when the format changes.
Editor extensions and agent tools built on a provider's SDK are a special case: their value often lies in deep integration with that provider. If you want them to support other models, an OpenAI-compatible base URL setting is usually the least invasive addition.
Finally, document the decision. A short note in the repository explaining which format each part of the system uses, and why, saves the next developer from rediscovering it. It also makes the cost of adding another provider visible before anyone promises it.
Mind the model name
Model IDs differ across providers and change over time. Keep them in configuration and validate them at start-up, as described in planning for model retirement.
Send a prompt to the keyless free-ai endpoint from the home page and see how it handles your own task, no signup needed.
Read also
- How to build a minimal MCP server for a proof of concept, step by step
- What should you do when an AI model you rely on is retired?
- How to orchestrate a dozen specialised agents without losing track
- Can you recreate skills and tool use from Claude apps through an API?
- Small fast models vs large ones: which fits high-volume AI work?