> For the list of every page, fetch /llms.txt. The API contract is the OpenAPI file linked from the API reference.

# Use your existing tools

Meadow speaks the OpenAI and Anthropic wire formats, so most clients work after two changes: the base URL and the key.

Next step: find your tool in the table, set its two variables, and run it.

| Tool | Base URL variable | Value | Key variable |
| --- | --- | --- | --- |
| OpenAI Python and TypeScript SDKs | `OPENAI_BASE_URL` | `$MEADOW_BASE_URL/v1` | `OPENAI_API_KEY` |
| Anthropic Python SDK | `ANTHROPIC_BASE_URL` | `$MEADOW_BASE_URL` (no `/v1`) | `ANTHROPIC_API_KEY` or `ANTHROPIC_AUTH_TOKEN` |
| Claude Code | `ANTHROPIC_BASE_URL` | `$MEADOW_BASE_URL` (no `/v1`) | `ANTHROPIC_AUTH_TOKEN` or `ANTHROPIC_API_KEY` |
| Codex CLI | `base_url` in `config.toml` | `$MEADOW_BASE_URL/v1` | the variable you name in `env_key` |
| curl | none | `$MEADOW_BASE_URL/v1/...` | `Authorization: Bearer` or `x-api-key` header |

The key is always your Meadow API key (`mdw_...`), never a provider key. The OpenAI SDKs add `/chat/completions` to the base URL, so theirs ends in `/v1`. The Anthropic SDK adds `/v1/messages`, so its base URL does not.

Model IDs are Meadow's. Run `GET /v1/models` to see them, and read [Models](/call-models/models#model-ids) before you paste an ID from a provider's docs.

What was run for this page, and with which versions:

| Tool | Version | Result |
| --- | --- | --- |
| OpenAI Python SDK | 3.59.0 | Chat Completions and Responses, blocking and streamed, model list. Served by Google and xAI. |
| OpenAI TypeScript SDK | 7.63.0 on Node 26 | Chat Completions blocking and streamed, Responses blocking. Served by Google and xAI. |
| Anthropic Python SDK | 2.13.0 | Messages, blocking and streamed, with both key variables. Served by Anthropic. |
| Claude Code | 2.1.331 | One-shot prompts and one tool call, in print mode. Served by Anthropic. |
| Codex CLI | 0.158.0 | Worked through OpenRouter. Failed through xAI. Not tried with OpenAI. See below. |

Not proven: any tool with OpenAI direct, Azure, or Bedrock as the provider. Our OpenAI key has no quota, so no call through the beta has been served by OpenAI itself. The paths exist and pass tests against stand-in servers. Run one call with your own key before you rely on them.

## curl

```bash
curl -sS "$MEADOW_BASE_URL/v1/chat/completions" \
  -H "Authorization: Bearer $MEADOW_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "gemini-3.1-flash-lite-preview", "messages": [{"role": "user", "content": "Say hello in five words."}], "max_tokens": 32}'
```

[Models](/call-models/models) has a curl sample for each format.

## OpenAI Python SDK

```bash
export OPENAI_BASE_URL="$MEADOW_BASE_URL/v1"
export OPENAI_API_KEY="$MEADOW_API_KEY"
```

```python
from openai import OpenAI

client = OpenAI()  # reads OPENAI_BASE_URL and OPENAI_API_KEY

# Streaming chat completion
stream = client.chat.completions.create(
    model="gemini-3.1-flash-lite-preview",
    messages=[{"role": "user", "content": "Say hello in five words."}],
    max_tokens=32,
    stream=True,
)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="")
print()

# Responses API
response = client.responses.create(
    model="grok-4.7",
    input="Say hello in five words.",
    max_output_tokens=64,
)
print(response.output_text)

# Responses API, streamed
with client.responses.stream(
    model="grok-4.7",
    input="Say hello in five words.",
    max_output_tokens=64,
) as stream:
    for event in stream:
        if event.type == "response.output_text.delta":
            print(event.delta, end="")
    print()

# Routing fields go in extra_body. Meadow headers come back on the raw response.
raw = client.chat.completions.with_raw_response.create(
    model="gemini-3.1-flash-lite-preview",
    messages=[{"role": "user", "content": "Say hello in five words."}],
    max_tokens=32,
    extra_body={"provider": {"order": ["openrouter", "google"]}},
)
print(raw.headers["x-meadow-provider"], raw.headers["x-meadow-model"], raw.headers["x-meadow-attempts"])
print(raw.parse().choices[0].message.content)

# Models this key can reach
print([m.id for m in client.models.list()][:3])
```

```text
Hello there, how are you?
Hello there, friend, how are you?
Hello, nice to meet you.
google gemini-3.1-flash-lite-preview 2
Hello, it is nice meeting.
['claude-fable-5-2', 'claude-haiku-4-5-20251001', 'claude-haiku-5-5']
```

You can also pass both values in code: `OpenAI(base_url=os.environ["MEADOW_BASE_URL"] + "/v1", api_key=os.environ["MEADOW_API_KEY"])`.

### Tool calls and structured output

Tools, `response_format`, and the SDK's `parse()` helper pass through to the provider like any other field. This ran on `gemini-3.1-flash-lite-preview`, served by Google. It needs `pydantic`.

```python
import json

from openai import OpenAI
from pydantic import BaseModel

client = OpenAI()  # reads OPENAI_BASE_URL and OPENAI_API_KEY
MODEL = "gemini-3.1-flash-lite-preview"

# A tool call, then the tool result sent back
tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get the weather for a city.",
        "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
    },
}]
messages = [{"role": "user", "content": "What is the weather in Paris? Use the tool."}]
first = client.chat.completions.create(model=MODEL, messages=messages, tools=tools, max_tokens=200)
tool_call = first.choices[0].message.tool_calls[0]
print(first.choices[0].finish_reason, tool_call.function.name, tool_call.function.arguments)

messages.append(first.choices[0].message)
messages.append({"role": "tool", "tool_call_id": tool_call.id, "content": json.dumps({"temp_c": 18, "sky": "clear"})})
second = client.chat.completions.create(model=MODEL, messages=messages, tools=tools, max_tokens=200)
print(second.choices[0].message.content)


# Structured output parsed into a Pydantic model
class Capital(BaseModel):
    name: str
    country: str


parsed = client.chat.completions.parse(
    model=MODEL,
    messages=[{"role": "user", "content": "What is the capital of France?"}],
    response_format=Capital,
    max_tokens=100,
)
print(parsed.choices[0].message.parsed)

# JSON mode
reply = client.chat.completions.create(
    model=MODEL,
    messages=[{"role": "user", "content": "Return a JSON object with the keys city and country for Paris."}],
    response_format={"type": "json_object"},
    max_tokens=100,
)
print(json.loads(reply.choices[0].message.content))
```

```text
tool_calls get_weather {"city":"Paris"}
The current weather in Paris is 18°C with clear skies.
name='Paris' country='France'
{'city': 'Paris', 'country': 'France'}
```

Whether a field works depends on the provider that serves the call. We ran these four on Google only. A streamed tool call with `AsyncOpenAI` also completed there. [Run untrusted code](/run-sandboxes/run-untrusted-code) uses a tool call to run model-written code in a sandbox.

### What Meadow does not serve

Meadow serves four calls of the OpenAI API: `chat.completions.create` (and the `parse` and `stream` helpers built on it), `responses.create`, `responses.stream`, and `models.list`. Every other call returns 404:

```python
import openai
from openai import OpenAI

try:
    OpenAI(max_retries=0).embeddings.create(model="text-embedding-3-small", input="hi")
except openai.APIStatusError as e:
    print(type(e).__name__, e.status_code, e.body)
```

```text
NotFoundError 404 {'message': "Meadow does not serve embeddings (/v1/embeddings). Call the vendor's own API for it, with a second client that uses the vendor's address and key. The model routes Meadow serves are POST /v1/chat/completions, POST /v1/responses, POST /v1/messages and GET /v1/models.", 'type': 'invalid_request_error', 'param': None, 'code': 'route_not_found'}
```

The message names the call and lists the routes Meadow serves. `e.code` is `route_not_found` for all of them. The body is OpenAI's own error object, so `e.type`, `e.code` and `e.param` are filled. That output was rebuilt from Meadow's tests after the error format changed on 2026-11-28. It was not run again on the hosted beta.

We saw a 404 for `embeddings.create`, `images.generate`, `audio.speech.create`, `audio.transcriptions.create`, `files.list`, `batches.list`, `moderations.create`, `completions.create`, `models.retrieve`, `responses.retrieve`, `vector_stores.list`, and `fine_tuning.jobs.list`.

Do: if your app also embeds text or uses one of these, keep a second client that points at the provider with the provider's key, and use the Meadow client for chat and responses.

A 404 also comes back when the base URL is wrong. `route not found` on a chat call means the OpenAI base URL is missing `/v1`, or the Anthropic base URL has a `/v1` it should not have. The message says which: `route not found: Meadow's routes start with /v1. Add /v1 to the client's base URL.`, or `route not found: the path has /v1 twice. This client adds /v1 itself, so give it Meadow's address without /v1.`

OpenRouter serves more of these than Meadow. Its API reference (read 2026-11-24) lists embeddings, image generation, speech, transcription, files and batches. It lists no moderations, vector stores, fine-tuning or stored responses.

### Retries and errors

The OpenAI and Anthropic SDKs resend a call twice by default after a 429, a 5xx, or a timeout. Through Meadow that has a cost: each send can be billed by a provider and counts against a key's limits. In this run the SDK sent a call that got a 502 three times:

```python
import openai
from openai import OpenAI

client = OpenAI()
try:
    client.chat.completions.create(
        model="gemini-3.1-flash-lite-preview",
        messages=[{"role": "user", "content": "hi"}],
        max_tokens=8,
        extra_body={"provider": {"only": ["openrouter"]}},
    )
except openai.APIStatusError as e:
    print(type(e).__name__, e.status_code)
    print(e.body)
```

```text
InternalServerError 502
{'message': 'all providers in route failed', 'type': 'server_error', 'param': None, 'code': 'all_providers_failed', 'attempts': [{'detail': 'provider returned HTTP 404', 'duration_ms': 45, 'outcome': 'unsupported', 'provider': 'openrouter'}]}
```

That run is from the hosted beta before its update of 2026-11-28. Since then, a 5xx on a model route carries `x-should-retry: false`, and both SDKs obey that header before their own rule, so the SDK sends such a call once. A 429 for a full server carries `x-should-retry: true`. Read from the server's code and its tests. Not yet run with the SDKs.

Do: until that run exists, set `max_retries=0` on the client (`OpenAI(max_retries=0)`, `Anthropic(max_retries=0)`) when a second send is not acceptable, and retry in your own code on a 429 only. Meadow has already tried every provider in the route before it returns a 502, so resending a 502 repeats the same failures. A 429 means no provider took the call, so that one is safe to send again after `retry-after`.

The SDK maps statuses to its usual exception classes. A Meadow error on these routes is in OpenAI's own envelope, so `e.type`, `e.code` and `e.param` are filled: `e.code` is Meadow's code, such as `all_providers_failed`, and `e.type` is OpenAI's, such as `server_error`. `e.body` holds the `error` object, with `attempts` when Meadow tried a provider, and `e.request_id` holds Meadow's request ID. The body above was rebuilt from Meadow's tests after the format changed on 2026-11-28. See [Errors on model routes](/reference/errors#errors-on-model-routes). On a served call the OpenAI SDK's `response._request_id` is Meadow's ID too, read from `x-request-id`. For a provider error passed through, it holds whatever that provider sent: a list for Google, a plain string for xAI. See [Errors](/reference/errors#provider-errors-on-model-routes).

## OpenAI TypeScript SDK

```bash
export OPENAI_BASE_URL="$MEADOW_BASE_URL/v1"
export OPENAI_API_KEY="$MEADOW_API_KEY"
```

```typescript
import OpenAI from "openai";

const client = new OpenAI(); // reads OPENAI_BASE_URL and OPENAI_API_KEY

const reply = await client.chat.completions.create({
  model: "gemini-3.1-flash-lite-preview",
  messages: [{ role: "user", content: "Say hello in five words." }],
  max_tokens: 32,
});
console.log(reply.choices[0].message.content);

const stream = await client.chat.completions.create({
  model: "gemini-3.1-flash-lite-preview",
  messages: [{ role: "user", content: "Say hello in five words." }],
  max_tokens: 32,
  stream: true,
});
for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}
console.log();

const response = await client.responses.create({
  model: "grok-4.7",
  input: "Say hello in five words.",
  max_output_tokens: 64,
});
console.log(response.output_text);

// Meadow's routing fields are not in the SDK's types, so cast the body.
const body = {
  model: "gemini-3.1-flash-lite-preview",
  messages: [{ role: "user", content: "Say hello in five words." }],
  max_tokens: 32,
  provider: { order: ["openrouter", "google"] },
} as OpenAI.Chat.ChatCompletionCreateParamsNonStreaming;

const { data, response: raw } = await client.chat.completions.create(body).withResponse();
console.log(raw.headers.get("x-meadow-provider"), raw.headers.get("x-meadow-attempts"));
console.log(data.choices[0].message.content);
```

```text
Hello, it is nice meeting.
Hello, it is nice meeting.
Hello, hope you are well.
google 2
Hello, it is nice meeting.
```

Without the cast, the TypeScript compiler rejects `provider` with `'provider' does not exist in type 'ChatCompletionCreateParamsBase'`.

## Anthropic Python SDK

```bash
export ANTHROPIC_BASE_URL="$MEADOW_BASE_URL"
export ANTHROPIC_API_KEY="$MEADOW_API_KEY"
```

```python
import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_BASE_URL and ANTHROPIC_API_KEY

message = client.messages.create(
    model="claude-haiku-5-5",
    max_tokens=64,
    messages=[{"role": "user", "content": "Say hello in five words."}],
)
print(next(b.text for b in message.content if b.type == "text"))
print(message.usage.input_tokens, message.usage.output_tokens)

with client.messages.stream(
    model="claude-haiku-5-5",
    max_tokens=64,
    messages=[{"role": "user", "content": "Say hello in five words."}],
) as stream:
    for text in stream.text_stream:
        print(text, end="")
    print()
    final = stream.get_final_message()
print(final.stop_reason)

# Routing fields go in extra_body. Meadow headers come back on the raw response.
raw = client.messages.with_raw_response.create(
    model="claude-haiku-5-5",
    max_tokens=64,
    messages=[{"role": "user", "content": "Say hello in five words."}],
    extra_body={"provider": {"only": ["anthropic"]}},
)
print(raw.headers["x-meadow-provider"], raw.headers["x-meadow-model"], raw.headers["x-meadow-attempts"])
```

```text
Hello there, friend! How are you?
16 14
Hello there, friend. How are you?
end_turn
anthropic claude-haiku-5-5 1
```

`ANTHROPIC_API_KEY` is sent as `x-api-key` and `ANTHROPIC_AUTH_TOKEN` as `Authorization: Bearer`. Meadow accepts either. Set one, not both with different values.

Errors and request IDs work as they do against Anthropic. A Meadow error on `/v1/messages` is in Anthropic's envelope, so the SDK raises its usual class and fills `e.type` (such as `rate_limit_error`), `e.error_code` (Meadow's code) and `e.request_id`. `message._request_id` is Meadow's request ID, because Meadow sends it in the `request-id` header the SDK reads. The provider's own ID is in `x-meadow-provider-request-id`: read it from the raw response headers (`client.messages.with_raw_response.create(...)`). Shown by Meadow's tests, which run the SDK against these bodies. Not run on the hosted beta. See [Errors on model routes](/reference/errors#errors-on-model-routes).

Two differences from calling Anthropic directly:

- `client.messages.count_tokens()` fails with a 404 `Meadow does not serve token counting`. So do the batch, file, and model-detail calls. Meadow serves `messages.create` and `messages.stream` only.
- The SDK retries twice by default. See [Retries and errors](#retries-and-errors).

## Claude Code

```bash
export ANTHROPIC_BASE_URL="$MEADOW_BASE_URL"
export ANTHROPIC_AUTH_TOKEN="$MEADOW_API_KEY"
claude -p "Say hello in five words."
```

```text
Hello there, nice to meet!
```

With only those two variables, Claude Code 2.1.331 asked for `claude-opus-5-5`, which is on Meadow's list, and Anthropic served it. `ANTHROPIC_API_KEY` works in place of `ANTHROPIC_AUTH_TOKEN`. A prompt that made Claude Code call its Bash tool also completed, in two turns.

To choose the model, set `ANTHROPIC_MODEL`:

```bash
export ANTHROPIC_MODEL="claude-haiku-5-5"
```

A provider alias works too: `ANTHROPIC_MODEL=claude-haiku-4-5` was served in this run. Meadow passes other unlisted `claude-` IDs to Anthropic when you have an Anthropic key. If Claude Code prints `API Error: 400 unknown model`, the ID is not one Meadow can place. Pin the provider: `ANTHROPIC_MODEL=anthropic/<model id>`.

### Claude Code on a key with a token limit

Claude Code asks for a large output token limit on every call, and Meadow reserves the cap before it forwards the call. See [the reservation rule](/call-models/token-and-request-limits#the-reservation-rule). So a key with `max_tokens` must have room for one whole reservation, or the first call is rejected.

With Claude Code 2.1.331 and `claude-haiku-5-5`, on a key with `max_tokens: 1000`:

```text
Failed to authenticate. API Error: 403 api key max_tokens limit would be exceeded: 0 of 1000 tokens used and 0 held by calls in flight on this key, and this request reserves 145004 tokens; lower its output token cap or shrink it
```

About 128,000 of that is the output token limit and about 17,000 is the request itself, which carries Claude Code's system prompt and tools. Set `CLAUDE_CODE_MAX_OUTPUT_TOKENS` to lower the cap:

| `CLAUDE_CODE_MAX_OUTPUT_TOKENS` | Reserved by a one-line prompt |
| --- | --- |
| not set | 145,004 |
| `4096` | 21,099 |
| `2048` | 19,051 |

Do:

- Set `CLAUDE_CODE_MAX_OUTPUT_TOKENS` for any Claude Code run on a token-limited key.
- Size the key for the whole job. Each call is charged what the provider reports, which for Claude Code is at least the 17,000 or so tokens of the request. In our run a 120,000 token key allowed one small edit task and two short prompts.
- Claude Code prints "Failed to authenticate" for every 401 and 403. With a 403 the key is valid, and the cause is a limit, a scope, or a model the key does not allow. A wrong key is a 401: `Failed to authenticate. API Error: 401 invalid api key`.

The numbers are from one version of Claude Code and one model. Run one call on a small key to see yours.

Limits of what was tested: print mode (`claude -p`) only, from a clean configuration. An interactive session, which also makes background calls with a small model, was not tested.

To keep Claude Code on approved providers, give it a key from a project with locked routing ([Projects](/set-up-your-account/projects#lock-a-project)), and do not pin model IDs there.

## Codex CLI

The Codex CLI speaks only the Responses format. Add a provider to `~/.codex/config.toml`, with your real base URL written out:

```toml
model = "openrouter/z-ai/glm-5.3"
model_provider = "meadow"

[model_providers.meadow]
name = "Meadow"
base_url = "https://api.usemeadow.ai/v1"
env_key = "MEADOW_API_KEY"
wire_api = "responses"
```

```bash
codex exec --skip-git-repo-check "Say hello in five words. Do not run any commands."
```

```text
Hello there, wonderful human friend!
```

What this proves and what it does not:

- Through OpenRouter, Codex CLI 0.158.0 completed a plain prompt and a prompt that ran a shell command.
- Through xAI, the same request failed. xAI answered 422 because it does not accept one of the tool types Codex sends. Meadow passed that error through.
- Through OpenAI itself, nothing has been run. This is the setup most Codex users want, and it is unproven on the beta.

Codex warns `Model metadata for ... not found` for IDs it does not know. The calls still ran.

## gemini-cli and the Google GenAI SDKs

These speak Google's own Gemini format, which Meadow serves at `/v1beta/models/{model}:generateContent` and `/v1/models/{model}:generateContent`. Set the client's base URL to `MEADOW_BASE_URL` and its key to a Meadow key. [Gemini clients](/call-models/gemini-clients) has the setup. Not on the hosted beta yet, and not run against Google.

## API reference

Operations on this page: [`createChatCompletion`](/reference/api-reference#createchatcompletion), [`createResponse`](/reference/api-reference#createresponse), [`createMessage`](/reference/api-reference#createmessage), [`listModels`](/reference/api-reference#listmodels).