> ## Documentation Index
> Fetch the complete documentation index at: https://docs.withleaf.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Inference API

> OpenAI-compatible REST reference for Leaf Inference: list models, create chat completions with Leaf Router 1, stream SSE responses, and enable Leaf tools.

Leaf Inference exposes an OpenAI-compatible HTTP API for chat completions with `leaf-router-1` and 25 frontier models, with optional server-side Leaf agronomy tools (`weather`, `soil`, `imagery`, `machine`).

For conceptual background, routing behavior, system prompt guidance, and the full 26-model catalog, see [Leaf Inference Overview](https://docs.withleaf.io/inference/overview.md).

## Base URL

```
https://withleaf.io/inference/v1
```

## Endpoints

| Method | Path | Auth | Description |
| - | - | - | - |
| GET | `/models` | None | [List models](#list-models) |
| POST | `/chat/completions` | Leaf V2 API key or Bearer token | [Create chat completion](#create-chat-completion) |

## Authentication & CORS

Authenticate `POST /chat/completions` **exclusively** using Leaf's **V2 Keycloak realm** (`https://auth.withleaf.io/realms/leaf`). Legacy V1 tokens are not accepted, and all built-in `leaf_tools` calls execute against `https://api-v2.withleaf.io`:

* **Leaf V2 API key (recommended):** Create an API key in [dashboard.withleaf.io](https://dashboard.withleaf.io) (**API Keys → Create API key**) and pass `<client_id>:<client_secret>` in `Authorization: Bearer <client_id>:<client_secret>` (compatible with every OpenAI SDK's `api_key` option) or `X-API-Key: <client_id>:<client_secret>`. Leaf Inference exchanges it with Keycloak (`grant_type=client_credentials`) and caches the short-lived access token automatically.
* **Keycloak OAuth2 Bearer token:** Pass an `access_token` obtained from `POST https://auth.withleaf.io/realms/leaf/protocol/openid-connect/token` in `Authorization: Bearer <access_token>`. Verified cryptographically against Keycloak's RS256 JWKS (`https://auth.withleaf.io/realms/leaf/protocol/openid-connect/certs`).

```
Authorization: Bearer <client_id>:<client_secret>
```

All endpoints return permissive CORS headers for browser and server clients (`OPTIONS` returns `204 No Content`):

* `Access-Control-Allow-Origin: *`
* `Access-Control-Allow-Methods: GET, POST, OPTIONS`
* `Access-Control-Allow-Headers: Authorization, Content-Type, X-API-Key, X-Leaf-Tools, X-Leaf-Project`
* `Access-Control-Max-Age: 86400`

***

## List models

GET `/models`

Returns the public catalog of models available on Leaf Inference, including context lengths, zero-data-retention flags, Leaf pricing (25% below list), and maker list pricing. No authentication is required; responses are cached with `Cache-Control: public, max-age=300`.

### Request

```bash cURL theme={null}
curl https://withleaf.io/inference/v1/models
```

```python Python theme={null}
from openai import OpenAI

client = OpenAI(base_url="https://withleaf.io/inference/v1", api_key="unused")
models = client.models.list()
for m in models.data:
    print(m.id)
```

```javascript JavaScript theme={null}
const res = await fetch('https://withleaf.io/inference/v1/models');
const { data } = await res.json();
console.log(data.map((m) => ({ id: m.id, zdr: m.zero_data_retention, pricing: m.pricing })));
```

### Response

`200 OK`

```json theme={null}
{
  "object": "list",
  "data": [
    {
      "id": "leaf-router-1",
      "object": "model",
      "created": 0,
      "owned_by": "leaf",
      "name": "Leaf Router 1",
      "maker": "Leaf",
      "open_weights": false,
      "context_length": 1048576,
      "description": "Leaf agronomy router (82.9% on v3): routes text, EPA label, extension numeric and field photo queries to the best ZDR model at $2.52 per 1,000 answers.",
      "zero_data_retention": true,
      "pricing": {
        "currency": "USD",
        "per": "1M tokens",
        "input": 1.45,
        "output": 10.67,
        "list_input": 1.93,
        "list_output": 14.22,
        "discount": 0.25
      }
    },
    {
      "id": "gpt-6.2-astra",
      "object": "model",
      "created": 0,
      "owned_by": "leaf",
      "name": "GPT-6.2 Astra",
      "maker": "OpenAI",
      "open_weights": false,
      "context_length": 1050000,
      "description": "Highest-scoring single model on Agronomy Benchmark v3, leading on extension numbers and open-ended field photos.",
      "zero_data_retention": true,
      "pricing": {
        "currency": "USD",
        "per": "1M tokens",
        "input": 6,
        "output": 30,
        "list_input": 8,
        "list_output": 40,
        "discount": 0.25
      }
    }
  ]
}
```

| Field | Type | Description |
| - | - | - |
| `data[].id` | string | Model identifier to pass in `POST /chat/completions`. |
| `data[].name` | string | Human-readable display name. |
| `data[].maker` | string | Model lab or maker (`Leaf`, `OpenAI`, `Google`, `Anthropic`, `Moonshot AI`, `xAI`, `Meta`, `Qwen`, `DeepSeek`). |
| `data[].open_weights` | boolean | `true` for open-weight models, `false` for closed models and routers. |
| `data[].context_length` | integer | Maximum context window in tokens. |
| `data[].zero_data_retention` | boolean | `true` when every request is pinned strictly to zero-data-retention endpoints. |
| `data[].pricing.input` | number | Leaf input price in USD per 1M tokens (25% off list). |
| `data[].pricing.output` | number | Leaf output price in USD per 1M tokens (25% off list). |
| `data[].pricing.list_input` | number | Maker list input price in USD per 1M tokens. |
| `data[].pricing.list_output` | number | Maker list output price in USD per 1M tokens. |
| `data[].pricing.discount` | number | Leaf discount fraction (`0.25`). |

***

## Create chat completion

POST `/chat/completions`

Creates a model response for the given chat conversation. Supports standard text prompts, caller-supplied `system` prompts, multimodal images (`image_url` / `input_image`), streaming Server-Sent Events, caller-defined function calling (`tools`), and Leaf's server-side agronomy data tools (`leaf_tools`).

### Headers

| Header | Required | Default | Description |
| - | - | - | - |
| `Authorization` | Yes (or `X-API-Key`) | — | `Bearer <client_id>:<client_secret>` (Leaf V2 API key from [dashboard.withleaf.io](https://dashboard.withleaf.io)) or `Bearer <KEYCLOAK_ACCESS_TOKEN>` issued by `https://auth.withleaf.io/realms/leaf`. |
| `X-API-Key` | No | — | Alternative to `Authorization` for passing `<client_id>:<client_secret>` directly (ignored if `Authorization: Bearer` is present). |
| `Content-Type` | Yes | — | `application/json`. |
| `X-Leaf-Tools` | No | Disabled | Comma-separated Leaf tool groups (`weather,soil,imagery,machine`) or `on` / `all` / `true` / `1` / `yes`. Ignored if `leaf_tools` is supplied in the JSON body. |
| `X-Leaf-Project` | No | Key default project | Optional API owner username for multi-project V2 API keys (`selected` or `all` scope). Must be 1–255 non-whitespace printable characters. Forwarded to `https://api-v2.withleaf.io`. |

### Body parameters

| Parameter | Type | Default | Description |
| - | - | - | - |
| `model` | string | **Required** | Model ID from `GET /models` (for example, `leaf-router-1`). |
| `messages` | array | **Required** | Non-empty array of OpenAI chat messages (`system`, `user`, `assistant`, `tool`). Supports multimodal content parts (`type: "text"`, `type: "image_url"`, `type: "input_image"`). |
| `max_tokens` | integer | `8192` | Maximum output tokens. Clamped to `1`–`32768` (`1`–`8192` in the public playground). |
| `max_completion_tokens` | integer | `8192` | Preferred OpenAI alias for `max_tokens`; takes precedence over `max_tokens` if both are sent. Same `1`–`32768` bounds. |
| `stream` | boolean | `false` | Stream response tokens as Server-Sent Events (`text/event-stream`). |
| `stream_options` | object | `{ "include_usage": false }` | Set `{ "include_usage": true }` with `stream: true` to receive a trailing usage chunk before `data: [DONE]`. |
| `leaf_tools` | boolean \| string \| string\[] | Disabled | Enables built-in Leaf agronomy tools: `true` / `"all"` / `"on"` / `"yes"` / `"1"` for all four groups, or a subset of `weather`, `soil`, `imagery`, `machine` (array or comma-separated string). |
| `tools` | array | Omitted | Caller-defined OpenAI tool definitions (`type: "function"`). Built-in `leaf_*` tool names are reserved while `leaf_tools` is active. |
| `tool_choice` | string \| object | Model default | `"auto"`, `"none"`, `"required"`, or a specific function selector. |
| `parallel_tool_calls` | boolean | Model default | Allow multiple tool calls in a single assistant turn. |
| `temperature` | number | Model default | Sampling temperature. |
| `top_p` | number | Model default | Nucleus sampling cutoff. |
| `top_k` | integer | Model default | Top-k token filtering (on supporting models). |
| `stop` | string \| string\[] | Omitted | Stop sequence(s). |
| `seed` | integer | Omitted | Best-effort reproducible sampling seed. |
| `presence_penalty` | number | Model default | Token presence penalty. |
| `frequency_penalty` | number | Model default | Token frequency penalty. |
| `repetition_penalty` | number | Model default | Multiplicative repetition penalty (on supporting models). |
| `response_format` | object | Omitted | Structured output specification (`json_object` or `json_schema`). |
| `logit_bias` | object | Omitted | Token ID bias map (on supporting models). |
| `logprobs` | boolean | Model default (`false`) | Include token log probabilities (on supporting models). |
| `top_logprobs` | integer | Omitted | Number of top logprobs per token when `logprobs` is `true`. |
| `reasoning` | object | Model default | Reasoning controls for reasoning models (for example, `{ "effort": "low" }`, `"medium"`, or `"high"`). Defaults to `{ "effort": "low" }` only in the keyless public playground. |
| `reasoning_effort` | string | Model default | Shorthand reasoning effort (`"low"`, `"medium"`, `"high"`). |

> [!NOTE]
>
> **System prompt ordering**: When `leaf_tools` is enabled, Leaf prepends a system message instructing the model how to use the enabled Leaf data groups (`weather`, `soil`, `imagery`, `machine`) ahead of your `messages` array. Your own `role: "system"` message(s) remain intact after it. See [System prompts](https://docs.withleaf.io/inference/overview.md#system-prompts).

### Request examples

```bash cURL (non-streaming with Leaf tools) theme={null}
curl https://withleaf.io/inference/v1/chat/completions \
  -H "Authorization: Bearer $LEAF_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "leaf-router-1",
    "max_completion_tokens": 2048,
    "temperature": 0.2,
    "leaf_tools": ["weather", "soil"],
    "messages": [
      { "role": "system", "content": "Respond in imperial units and cite the dates checked." },
      { "role": "user", "content": "Compare topsoil moisture and the 7-day rain forecast near Champaign, Illinois." }
    ]
  }'
```

```python Python (streaming with usage) theme={null}
import os
from openai import OpenAI

# LEAF_API_KEY = "<client_id>:<client_secret>" from dashboard.withleaf.io -> API Keys
client = OpenAI(
    base_url="https://withleaf.io/inference/v1",
    api_key=os.environ["LEAF_API_KEY"],
)

stream = client.chat.completions.create(
    model="leaf-router-1",
    stream=True,
    stream_options={"include_usage": True},
    extra_body={"leaf_tools": ["weather", "soil"]},
    messages=[
        {"role": "system", "content": "Be concise and cite units."},
        {"role": "user", "content": "Will it rain near Ames, Iowa over the next 7 days?"},
    ],
)

for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
    if chunk.usage:
        print("\nUsage:", chunk.usage)
```

```javascript JavaScript (multimodal field photo) theme={null}
import OpenAI from 'openai';

const client = new OpenAI({
  baseURL: 'https://withleaf.io/inference/v1',
  apiKey: process.env.LEAF_API_KEY,
});

const reply = await client.chat.completions.create({
  model: 'leaf-router-1',
  messages: [
    {
      role: 'user',
      content: [
        { type: 'text', text: 'Identify the foliar disease in this corn leaf photo and list key diagnostic signs.' },
        { type: 'image_url', image_url: { url: 'https://example.com/corn-leaf.jpg' } },
      ],
    },
  ],
});

console.log(reply.choices[0].message.content);
```

```bash cURL (X-API-Key, X-Leaf-Tools, and multi-project X-Leaf-Project) theme={null}
curl https://withleaf.io/inference/v1/chat/completions \
  -H "X-API-Key: $LEAF_API_KEY" \
  -H "Content-Type: application/json" \
  -H "X-Leaf-Tools: weather,machine" \
  -H "X-Leaf-Project: my-project-owner" \
  -d '{
    "model": "leaf-router-1",
    "messages": [
      { "role": "user", "content": "Summarize our most recent planting operation and check if rain is forecast on that field." }
    ]
  }'
```

### Non-streaming response

`200 OK` (`Content-Type: application/json`, `Cache-Control: no-store`)

```json theme={null}
{
  "id": "chatcmpl-leaf-9a4e1c2b7f1d4e8a9c3b6d0e",
  "object": "chat.completion",
  "created": 1796219400,
  "model": "leaf-router-1",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Near Champaign, Illinois (40.12°N, 88.24°W)...",
        "reasoning": "..."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 1420,
    "completion_tokens": 318,
    "total_tokens": 1738
  },
  "leaf_tool_calls": [
    {
      "name": "leaf_soil_conditions",
      "arguments": "{\"lat\":40.1164,\"lon\":-88.2434,\"kind\":\"forecast\",\"units\":\"imperial\"}"
    },
    {
      "name": "leaf_weather_forecast",
      "arguments": "{\"lat\":40.1164,\"lon\":-88.2434,\"granularity\":\"daily\",\"units\":\"imperial\"}"
    }
  ]
}
```

| Field | Type | Description |
| - | - | - |
| `id` | string | Unique completion ID prefixed with `chatcmpl-leaf-`. |
| `model` | string | Always the requested public model ID (for example, `leaf-router-1`). |
| `choices[0].message.content` | string \| null | Final assistant text (`null` when returning caller `tool_calls`). |
| `choices[0].message.reasoning` | string | Optional. Present when the model emits reasoning text. |
| `choices[0].message.tool_calls` | array | Optional. Present when returning caller-defined tool calls (`finish_reason: "tool_calls"`). |
| `choices[0].finish_reason` | string | `"stop"`, `"length"`, `"tool_calls"`, or model finish reason. |
| `usage` | object | Aggregated `prompt_tokens`, `completion_tokens`, and `total_tokens` summed across all server-side Leaf tool rounds. |
| `leaf_tool_calls` | array | Optional. Present when one or more server-side Leaf data tools executed during the request (`name` and raw JSON `arguments`). |

### Streaming response (`stream: true`)

`200 OK` (`Content-Type: text/event-stream; charset=utf-8`, `Cache-Control: no-store`, `X-Accel-Buffering: no`)

Chunks follow the OpenAI `chat.completion.chunk` SSE format. When `leaf_tools` executes server-side, Leaf emits status chunks containing a top-level `leaf_tool` object before continuing to stream the final assistant text. If `stream_options: { "include_usage": true }` is set, a final usage chunk (`choices: []`) is emitted right before `data: [DONE]`.

```text theme={null}
data: {"id":"chatcmpl-leaf-9a4e1c2b7f1d4e8a9c3b6d0e","object":"chat.completion.chunk","created":1796219400,"model":"leaf-router-1","choices":[{"index":0,"delta":{},"finish_reason":null}],"leaf_tool":{"id":"call_1","name":"leaf_weather_forecast","arguments":"{\"lat\":42.03,\"lon\":-93.63,\"granularity\":\"daily\"}","status":"running"}}

data: {"id":"chatcmpl-leaf-9a4e1c2b7f1d4e8a9c3b6d0e","object":"chat.completion.chunk","created":1796219400,"model":"leaf-router-1","choices":[{"index":0,"delta":{},"finish_reason":null}],"leaf_tool":{"id":"call_1","name":"leaf_weather_forecast","status":"done"}}

data: {"id":"chatcmpl-leaf-9a4e1c2b7f1d4e8a9c3b6d0e","object":"chat.completion.chunk","created":1796219400,"model":"leaf-router-1","choices":[{"index":0,"delta":{"role":"assistant","content":"Ames, Iowa is forecast to receive..."},"finish_reason":null}]}

data: {"id":"chatcmpl-leaf-9a4e1c2b7f1d4e8a9c3b6d0e","object":"chat.completion.chunk","created":1796219400,"model":"leaf-router-1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}

data: {"id":"chatcmpl-leaf-9a4e1c2b7f1d4e8a9c3b6d0e","object":"chat.completion.chunk","created":1796219400,"model":"leaf-router-1","choices":[],"usage":{"prompt_tokens":1180,"completion_tokens":194,"total_tokens":1374}}

data: [DONE]
```

* `delta.reasoning` is streamed alongside `delta.content` when reasoning text is produced.
* `leaf_tool.status` transitions from `"running"` (includes `arguments`) to `"done"` or `"error"`.
* Standard OpenAI SDKs ignore the extra `leaf_tool` field safely while custom UIs can render live tool-call indicators.

***

## Errors

Error responses follow the OpenAI JSON error envelope:

```json theme={null}
{
  "error": {
    "message": "Unknown model. Available: leaf-router-1, gpt-6.2-astra, ...",
    "type": "invalid_request_error",
    "code": "model_not_found"
  }
}
```

| Status | `error.type` | Cause |
| - | - | - |
| `400` | `invalid_request_error` | Malformed JSON body, missing or empty `messages`, invalid `X-Leaf-Project` header, or invalid model parameters. |
| `401` | `authentication_error` | Missing, malformed, invalid, or expired Leaf V2 API key (`<client_id>:<client_secret>`) or Keycloak Bearer access token. |
| `404` | `invalid_request_error` | Unknown `model` (`code: "model_not_found"`) or unknown endpoint path (`code: "not_found"`). |
| `405` | `invalid_request_error` | Wrong HTTP method on `/chat/completions` (use `POST`). |
| `413` | `invalid_request_error` | Request body exceeds `2 MB` (or conversation exceeds `16,000` characters in the public playground). |
| `429` | `rate_limit_error` | Rate limit exceeded (`60` requests/minute authenticated, `6` requests/minute public playground) or upstream capacity busy. |
| `500` | `server_error` | Unexpected internal error. |
| `502` | `authentication_error` | Leaf Inference could not reach `auth.withleaf.io` to verify your API key or token. Retry the request. |
| `503` | `server_error` | Leaf Inference is temporarily unavailable. Retry after a short backoff. |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.