# Nenya API

A free, public, OpenAI-compatible API for Nenya 1. No sign-up, no keys.

- Base URL: `https://api.contrastivelabs.dev/v1`
- API key: `none` (send any value: SDKs insist on one)
- Model name: `nenya` (the newest release: nenya-1 today)
- Context: `16,384 tokens` (prompt and reply together)
- Input and output: `text only` (English. For a PDF or a scan, see [PDFs and scans](https://contrastivelabs.com/docs#pdfs-and-scans))

The page this was made from: https://contrastivelabs.com/docs. A playground that sends these requests from a browser: https://contrastivelabs.com/playground.

## Quick start

curl needs nothing installed. The other two use the OpenAI SDK: `pip install openai` or `npm install openai`.

curl:

```bash
curl https://api.contrastivelabs.dev/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "nenya",
    "messages": [{"role": "user", "content": "What is the capital of France?"}]
  }'
```

Python:

```python
from openai import OpenAI

client = OpenAI(base_url="https://api.contrastivelabs.dev/v1", api_key="none")

response = client.chat.completions.create(
    model="nenya",
    messages=[{"role": "user", "content": "What is the capital of France?"}],
)
print(response.choices[0].message.content)
```

JavaScript:

```javascript
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://api.contrastivelabs.dev/v1", apiKey: "none" });

const response = await client.chat.completions.create({
  model: "nenya",
  messages: [{ role: "user", content: "What is the capital of France?" }],
});
console.log(response.choices[0].message.content);
```

You should see:

```text
The capital of France is Paris.
```

What comes back, with the fields that are null left out:

The reply:

```json
{
  "id": "chatcmpl-53a2bee22c274aaab7afea7be393bc6c",
  "object": "chat.completion",
  "created": 1796243219,
  "model": "nenya-1",
  "choices": [
    {
      "index": 0,
      "message": {"role": "assistant", "content": "The capital of France is Paris."},
      "finish_reason": "stop"
    }
  ],
  "usage": {"prompt_tokens": 55, "total_tokens": 63, "completion_tokens": 8}
}
```

- `model` names the exact checkpoint that answered. `nenya` is only the name you send.
- `finish_reason` says why the reply ended. Check it before you use the reply: see [finish_reason](https://contrastivelabs.com/docs#finish-reason).
- `usage.prompt_tokens` is 55 for a seven-token question. Every chat request carries a built-in system turn of 48 tokens: see [What the model reads](https://contrastivelabs.com/docs#what-the-model-reads).
- A chat reply is sampled unless you set `temperature`, so the wording changes from run to run.

The API can be called from a web page: it answers cross-origin requests from any site.

> **Nothing to install?** The [playground](https://contrastivelabs.com/playground) sends the same requests from your browser.

## Using it well: the short version

Nenya 1 is small: half a billion parameters do the work for each token. It does its three jobs well when it is asked the way it was trained, and much worse when it is not. We measured that on this API, with about 120,000 requests ([Our tests](https://contrastivelabs.com/docs#our-tests)). These are the rules that came out of it.

1. **Decode at temperature 0 whenever there is one right answer.** The server does this by itself in two cases: a request with `tools`, and a request whose reply is held to a shape by `response_format` or `structured_outputs`. Everything else is sampled at temperature 0.9 unless you set `temperature`, and that includes a classification or an extraction asked in plain words. In our tests sampling cost 4 to 5 points of classification accuracy and 1 to 2 points of extraction F1, and three sampled runs of the same 1,000 classification requests agreed on only 710 of the labels. The recipes on this page set `temperature: 0` themselves, so they give the same results on any server.
2. **Say everything in the prompt. The model never sees your `response_format` schema.** The schema holds the reply to a shape. It does not tell the model what the fields mean. Extraction with a schema and no field list in the prompt scored 45 F1, against 83 with the fields listed.
3. **Use the layouts on this page.** Classification in the layout the model was trained on is right 79% to 83% of the time. The same tasks asked as “Classify the following text into one of these categories: …” gave a clean label 6% of the time: the model wrote a paragraph instead.
4. **Extraction: ask for JSON, not for a tool call.** 83.5 F1 as JSON against 68 to 73 as a tool call, on the same 500 documents.
5. **Classification: list the labels in the prompt and hold the reply to them.** 81% to 83%, against 70% when the labels are the `enum` of a tool.
6. **Tools: tell the model when it has to call.** Offered a handful of tools and no system message, it answered in words instead of calling in up to 29% of the requests where a tool fitted. `tool_choice: "required"` or a system message fixes most of that.
7. **In a tool loop: rules that say what to do, limits in your code, and an end to the calls when a function finds nothing.** A rule that left the amount of a refund open lost 1 conversation in 5. A limit written in the system message was not kept once in 110 conversations. After `{"error": "no such order"}` the model made the same call again 96 times in 100. How a result is spelt made no difference ([After a result](https://contrastivelabs.com/docs#after-a-result)).
8. **Describe every field, label and parameter.** Field descriptions are worth 14 to 17 points of extraction F1. Without parameter descriptions, wrong arguments in tool calls double.
9. **Keep lists short.** On a task the model has not seen, each doubling of the label list costs about 8 points. Past 8 tools, each doubling of the tool list costs 3 to 5.
10. **Check `finish_reason` before you parse, and set `max_tokens`.** A reply that reaches the limit is cut off mid-JSON, and there is no limit other than the context unless you set one.
11. **Work dates out yourself.** Given today’s date, the model turned 1 of 13 relative dates (“tomorrow”, “next Thursday”, “in two weeks”) into the right day. Dates written out in the text came out right. Take the words out as they are written and resolve them in your code.

The same as a table:

| Job | Ask like this | Settings | In our tests |
| --- | --- | --- | --- |
| Classify into a fixed list | One user message: the question, the text, `Options:`, `Answer with the label only.` | `temperature: 0`; `structured_outputs: {"choice": [...]}`; `logprobs` for confidence | 81% right on four tasks it never saw; 93% on the 6 in 10 answers it is at least 90% sure of |
| Extract fields from a document | System message: the field list. User message: the document. | `temperature: 0`; `response_format` with a JSON schema; `max_tokens` | 83.5 field F1 on 500 real documents; 0.6% invented values |
| Call tools | `tools`, and a system message that says what the assistant is for | no `temperature`; `tool_choice: "required"` when every request should become a call | 90% right calls with 8 tools when forced, 76% to 87% with a system message, 64% with neither |
| Free text | anything | the default sampling | not what this model is for: see [What to expect](https://contrastivelabs.com/docs#what-to-expect) |

All the recipes below are in one runnable file, [cookbook.py](https://contrastivelabs.com/cookbook.py). Eleven worked use cases on real documents (complaints, accident reports, recall notices, voice commands, a PDF and its scan), each with its data and its checked answers, are in the [cookbooks](https://contrastivelabs.com/cookbook).

```bash
pip install openai
curl -O https://contrastivelabs.com/cookbook.py
python cookbook.py                  # run every recipe and print what comes back
python cookbook.py classify         # only the recipes whose name starts with "classify"
python cookbook.py --json out.json  # also save every request and reply
```

## The model

|   |   |
| --- | --- |
| Name | Nenya 1 |
| Size | 2.5 billion parameters, of which 0.5 billion are used for each token (a mixture of experts) |
| Trained for | tool calling, extraction and classification |
| Context | 16,384 tokens, prompt and reply together |
| Languages | English. It was trained on English text only. |
| Input and output | text only |
| Thinking mode | none: it answers directly |
| Weights and licence | Open under Apache 2.0: [Nenya 1 on Hugging Face](https://huggingface.co/contrastivelabs/Nenya-1). So is the base model it was trained from, [Nenya-2.5B-A0.5B-Base](https://huggingface.co/contrastivelabs/Nenya-2.5B-A0.5B-Base). |

### Names

| Name | What it is |
| --- | --- |
| Nenya 1 | the model, as it is called in public |
| `nenya` | the name to send. It always means the newest release. |
| `nenya-1` | the exact checkpoint of Nenya 1. Replies carry it in their `model` field and in the `x-nenya-model` header. |
| `nenya-sft-50171` | a preview checkpoint the API served from 29 November to 1 December 2026. It is retired: a request that names it gets `404`. |
| Nenya-2.5B-A0.5B-Base | the open base model Nenya 1 was trained from. It is not served here. |

**Pinning a checkpoint.** One checkpoint is served at a time. There are two ways to name it:

- `nenya` always means the newest release. When a new checkpoint is released, the same request starts being answered by the new one.
- An exact id, such as `nenya-1`, means those weights or an error. Once a checkpoint is retired, a request that names it gets `404` with the code `model_not_found`. It is never answered by another checkpoint. Send the id when your results have to be reproducible.

Any other name (`gpt-4o`, or a misspelt id) is answered by the checkpoint that is served, so code written for another model runs unchanged. The reply’s `model` field and the `x-nenya-model` header always say which checkpoint answered. `GET /v1/models` lists the names the server answers to.

### Versions

| Date | Checkpoint | What changed |
| --- | --- | --- |
| 2 December 2026 | `nenya-1` | The same checkpoint; the server changed. A request for one reply with `response_format` or `structured_outputs` is decoded at temperature 0 unless it sets a sampling field ([Sampling when you set nothing](https://contrastivelabs.com/docs#sampling)). Errors that come from the engine carry `type: "invalid_request_error"` and a code where there is one (`context_length_exceeded`, `unsupported_schema`) in place of the number 400 ([Errors](https://contrastivelabs.com/docs#errors)). A request that names the retired `nenya-sft-50171` gets `404`. |
| 1 December 2026 | `nenya-1` | Nenya 1, the release. A new version of the serving engine, with the same outputs. Requests and replies are stored from this day ([Terms and privacy](https://contrastivelabs.com/docs#terms)). |
| 29 November 2026 | `nenya-sft-50171` | The API opened, with a preview checkpoint. |

## Run it locally

Nenya 1 also runs on your own hardware, through vLLM. The server it starts speaks the same API, so everything on this page stays as it is except the address.

You need Linux and an NVIDIA GPU.

```bash
# 1. the engine: vLLM with the Nenya plugin
pip install nenya-vllm
# 2. the server, on port 8000, under the name "nenya". It downloads the weights the first time.
nenya-vllm serve contrastivelabs/Nenya-1
```

The first start is slow: the engine compiles its kernels for your GPU, which takes 20 minutes or more, once for each machine. Later starts take seconds. The options of the command, and the rest, are in the engine’s repository: [nenya-vllm on GitHub](https://github.com/contrastivelabs/nenya-vllm).

Then send the same requests to your own address:

curl:

```bash
curl http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "nenya",
    "messages": [{"role": "user", "content": "What is the capital of France?"}]
  }'
```

Python:

```python
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="none")

response = client.chat.completions.create(
    model="nenya",
    messages=[{"role": "user", "content": "What is the capital of France?"}],
)
print(response.choices[0].message.content)
```

JavaScript:

```javascript
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "http://localhost:8000/v1", apiKey: "none" });

const response = await client.chat.completions.create({
  model: "nenya",
  messages: [{ role: "user", content: "What is the capital of France?" }],
});
console.log(response.choices[0].message.content);
```

### What is different

The public API has a small server of its own in front of the engine. A few things on this page are that server’s, and yours will not do them:

- **Names.** Send the name the server gives the model, `nenya`. The public API answers to any name ([Names](https://contrastivelabs.com/docs#names)); your server answers only to its own.
- **JSON with no `temperature` is sampled.** The public API decodes it at temperature 0 by itself ([Sampling when you set nothing](https://contrastivelabs.com/docs#sampling)). On your server, set `temperature: 0`, as every recipe on this page does. A request with `tools` is decoded at temperature 0 on both.
- **Errors** come as vLLM writes them, without the codes listed under [Errors](https://contrastivelabs.com/docs#errors) (`context_length_exceeded`, `unsupported_schema`).
- **The reply headers** listed under [Reply headers](https://contrastivelabs.com/docs#headers) are the public API’s own. Your server does not send them.

## What the model reads

Every chat request is turned into one text before the model sees it. That text always begins with a system turn the server writes. For the quick start it is:

The quick start, as the model reads it:

```text
<|im_start|>system
You are Nenya, a helpful function-calling AI assistant built by arsalanzafar.ai. You do not currently have access to any functions. <functions></functions><|im_end|>
<|im_start|>user
What is the capital of France?<|im_end|>
<|im_start|>assistant
```

With a system message of your own and tools, the same turn holds three things in this order:

The system turn, with a system message of your own and tools:

```text
<|im_start|>system
You are Nenya, a helpful function-calling AI assistant built by arsalanzafar.ai.

{your system message}

You are provided with function signatures within <functions></functions> XML tags. You may call one or more functions to assist with the user query. Output any function calls within <function_calls></function_calls> XML tags. Don't make assumptions about what values to plug into functions. <functions>[{your tools, as JSON}]</functions><|im_end|>
```

What follows from that:

- **There is always a system turn, and you cannot remove it.** Your system message is added to it, after the first sentence. It does not replace that sentence.
- **Several system messages are joined** into that turn, in order, wherever they stand in the conversation. `developer` messages are treated the same way.
- **It costs tokens.** A request with one user message and no tools carries 48 tokens besides your text. With tools it carries about 95, plus the JSON of the tools: about 60 tokens for a tool with one parameter, 155 on average for the tools in our tests.
- **Tools are read as JSON text.** The names and descriptions you write are the words the model matches against the request.
- **A conversation has to end with a `user` or a `tool` message.** One that ends with an `assistant` message gets a `400`, unless you set `continue_final_message: true` and `add_generation_prompt: false` to have that message continued.
- **To see the exact text**, add `"return_prompt_text": true` to a request. The reply then has a `prompt_text` field with the prompt as the model read it.

### System messages

A system message is the place for who the assistant is, what it is for, and rules that hold for every request. How much it helps depends on the job:

| Job | What a system message does |
| --- | --- |
| Tool calling | A lot. With no system message the model is cautious about calling. One that says what the assistant is for makes it call. See [Make sure it calls](https://contrastivelabs.com/docs#make-sure-it-calls). |
| Extraction | It is the best place for the field list: 83.5 F1 there, against 79.4 with everything in the user message. See [Extraction](https://contrastivelabs.com/docs#extraction). |
| Classification | Keep the question and the options in the user message, next to the text. Moved to the system message they scored 61% against 79%. A short system message beside them does no harm (80.5% against 81.2%). |

The model follows short, plain instructions best. It is a small model: do not count on it to follow a long list of rules, and check on your own examples that it does what your system message says. In a tool loop it follows a rule that says what to do and does not keep a rule that forbids a value: the limit has to be checked in your code ([After a result](https://contrastivelabs.com/docs#after-a-result)). Do not rely on what it says about itself either: asked who made it, it may name another company.

## Prompt templates

The words outside the braces are the ones that scored best in our tests. Nearly all of them are the wording the model was trained on. Keep them, and fill in the braces.

| Job | Where it goes | Template |
| --- | --- | --- |
| Classify, one label | one user message | `{question}`<br><br>`{Heading}:`<br>`{text}`<br><br>`Options:`<br>`- {label}`<br>`- {label}`<br><br>`Answer with the label only.` |
| … when nothing may fit | added to the last line | `Answer with the label only. If none of the options fits, answer "none".` |
| … with the labels explained | the option lines | `- {label}: {what it covers}` |
| … with long options | the option lines and the last line | `A) {option}`<br>`B) {option}`<br><br>`Answer with the letter of the correct option only.` |
| Classify, several labels | the last line | `Answer with a JSON object: {"labels": [...]}. Use an empty list if none apply.` |
| Classify, as JSON | the last line | `Answer with a JSON object: {"label": ...}.` |
| Extract (best) | system message | `You extract structured data from {kind}s. For each document the user sends, give these fields.`<br><br>`Fields:`<br>`- {name} ({type}): {description}`<br><br>`Answer with one JSON object with exactly these keys. Use null for a field the text does not give.` |
|  | user message | `{document}` |
| Extract, in one message | one user message | `Extract these fields from the {kind} below.`<br><br>`{document}`<br><br>`Fields:`<br>`- {name} ({type}): {description}`<br><br>`Answer with one JSON object with exactly these keys. Use null for a field the text does not give.` |
| Extract, as a tool call | one user message, one tool | `Please save the details of the {kind} below using the appropriate tool. Fill in only the fields whose values the {kind} states, and leave out any field it does not state.`<br><br>`{document}`<br><br>with one tool whose parameters are the fields, none of them `required`, and whose description ends `Every parameter is optional: give only the values the {kind} states.` |
| Tool calling | system and user messages | no fixed wording: the tools go in `tools` |

What the braces stand for:

- `{question}`: the task as you would put it to a person. “Which team should handle this support ticket?”
- `{Heading}`: one word for what the text is. `Ticket`, `Review`, `Message`. Two blocks are fine: `Title:` and `Abstract:`.
- `{kind}`: what the document is, in a word or two: `invoice`, `email`, `support ticket`.
- `{type}`: `string`, `integer`, `number`, `boolean`, `list of string`, or `list of {key, key}` for a list of objects. For a field with fixed values, end the line with `(one of: a, b, c)`.

## Classification

Give the model a question, a text and a list of labels. It answers with one of them.

### The recipe

curl:

```bash
# What the recipe sends for the first of its three tickets.
curl https://api.contrastivelabs.dev/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "nenya",
    "messages": [
      {
        "role": "user",
        "content": "Which team should handle this support ticket?\n\nTicket:\nI was charged twice for my November invoice.\n\nOptions:\n- Billing\n- Technical\n- Shipping\n- Account\n\nAnswer with the label only."
      }
    ],
    "temperature": 0,
    "max_tokens": 24,
    "logprobs": true,
    "structured_outputs": {"choice": ["Billing", "Technical", "Shipping", "Account"]}
  }'
```

Python:

```python
import math

from openai import OpenAI

client = OpenAI(base_url="https://api.contrastivelabs.dev/v1", api_key="none")


def classify(question, text, labels, heading="Text", descriptions=None, allow_none=False):
    """(label, confidence)"""
    options = "\n".join(f"- {label}: {descriptions[label]}" if descriptions else f"- {label}" for label in labels)
    prompt = f"{question}\n\n{heading}:\n{text}\n\nOptions:\n{options}\n\nAnswer with the label only."
    if allow_none:
        prompt += ' If none of the options fits, answer "none".'
    reply = client.chat.completions.create(
        model="nenya",
        messages=[{"role": "user", "content": prompt}],
        temperature=0,                      # one right answer: do not sample
        max_tokens=24,
        logprobs=True,                      # for the confidence
        extra_body={"structured_outputs": {"choice": labels + (["none"] if allow_none else [])}},
    )
    choice = reply.choices[0]
    tokens = [t for t in choice.logprobs.content if not t.token.startswith("<|")]
    confidence = math.exp(sum(t.logprob for t in tokens))
    return choice.message.content, confidence


teams = ["Billing", "Technical", "Shipping", "Account"]
for ticket in ["I was charged twice for my November invoice.",
               "Tracking has not updated in five days. Where is my parcel?",
               "I cannot log in, and my card was still charged."]:
    label, confidence = classify("Which team should handle this support ticket?", ticket, teams, heading="Ticket")
    print(f"{label:<10} {confidence:4.0%}  {ticket}")
```

JavaScript:

```javascript
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://api.contrastivelabs.dev/v1", apiKey: "none" });

/** [label, confidence] */
async function classify(question, text, labels, { heading = "Text", descriptions = null, allowNone = false } = {}) {
  const options = labels
    .map((label) => (descriptions ? `- ${label}: ${descriptions[label]}` : `- ${label}`))
    .join("\n");
  let prompt = `${question}\n\n${heading}:\n${text}\n\nOptions:\n${options}\n\nAnswer with the label only.`;
  if (allowNone) prompt += ' If none of the options fits, answer "none".';
  const reply = await client.chat.completions.create({
    model: "nenya",
    messages: [{ role: "user", content: prompt }],
    temperature: 0, // one right answer: do not sample
    max_tokens: 24,
    logprobs: true, // for the confidence
    structured_outputs: { choice: allowNone ? [...labels, "none"] : labels },
  });
  const choice = reply.choices[0];
  const tokens = choice.logprobs.content.filter((t) => !t.token.startsWith("<|"));
  const confidence = Math.exp(tokens.reduce((sum, t) => sum + t.logprob, 0));
  return [choice.message.content, confidence];
}

const teams = ["Billing", "Technical", "Shipping", "Account"];
for (const ticket of [
  "I was charged twice for my November invoice.",
  "Tracking has not updated in five days. Where is my parcel?",
  "I cannot log in, and my card was still charged.",
]) {
  const [label, confidence] = await classify("Which team should handle this support ticket?", ticket, teams, {
    heading: "Ticket",
  });
  console.log(`${label.padEnd(10)} ${`${Math.round(confidence * 100)}%`.padStart(4)}  ${ticket}`);
}
```

What it prints:

```text
Billing    100%  I was charged twice for my November invoice.
Shipping    99%  Tracking has not updated in five days. Where is my parcel?
Billing     50%  I cannot log in, and my card was still charged.
```

The third ticket could go two ways, and the confidence says so. Act on the sure answers and send the rest to a person. At a near tie like this one the answer itself can change from run to run, even at temperature 0: when we ran it again, the same ticket came back as `Technical` at 42%.

What each part does:

- **The layout** is the one the model was trained on: question, a heading and the text, `Options:` with one label to a line, then `Answer with the label only.`
- **`structured_outputs: {"choice": [...]}`** holds the reply to one of your labels, letter for letter. Without it 4% of the replies were not a label: a label with its description repeated after it, or a label the model made up. It is an extension of this API: with the Python SDK it goes in `extra_body`, the JavaScript SDK sends extra keys as they are.
- **`temperature: 0`**: with a choice list the server decodes at temperature 0 by itself. The recipe says so all the same, so that it still holds when you drop the list or run the model somewhere else (rule 1).
- **`logprobs`** gives the probability of each token of the reply. Their product is the model’s own confidence in the label.

### Which form to use

The same 1,000 items, from four tasks the model has no training data for, asked every way:

| How it is asked (`temperature: 0`) | Right |
| --- | --- |
| The recipe above without the choice list | 78.9% |
| **The recipe above** (reply held to the labels) | **81.2%** |
| `Answer with a JSON object: {"label": ...}.` and a JSON schema with the labels as an `enum` | 82.7% |
| The same without the schema | 80.0% |
| A tool call with the labels as the `enum` of a parameter | 70.5% |
| The question and the options in the system message, the text as the user message | 60.9% |
| Four worked examples as earlier turns, then the recipe | 73.1% |
| “Classify the following … into one of these categories: … Category:” | 6.1% clean labels (the right label was somewhere in the reply 48% of the time) |

So: one user message in the trained layout, with the reply held to the labels either by a choice list or by a JSON schema. The two are equally good; the choice list gives you the label alone and the simplest confidence. Do not use a tool call to classify, do not move the options to the system message, and do not add examples: all three made it worse.

As JSON, for when you want an object back:

curl:

```bash
curl https://api.contrastivelabs.dev/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "nenya",
    "messages": [
      {
        "role": "user",
        "content": "Which team should handle this support ticket?\n\nTicket:\nI was charged twice for my November invoice.\n\nOptions:\n- Billing\n- Technical\n- Shipping\n- Account\n\nAnswer with a JSON object: {\"label\": ...}."
      }
    ],
    "temperature": 0,
    "max_tokens": 32,
    "response_format": {
      "type": "json_schema",
      "json_schema": {
        "name": "label",
        "schema": {
          "type": "object",
          "properties": {
            "label": {"type": "string", "enum": ["Billing", "Technical", "Shipping", "Account"]}
          },
          "required": ["label"],
          "additionalProperties": false
        }
      }
    }
  }'
```

Python:

```python
from openai import OpenAI

client = OpenAI(base_url="https://api.contrastivelabs.dev/v1", api_key="none")

prompt = """Which team should handle this support ticket?

Ticket:
I was charged twice for my November invoice.

Options:
- Billing
- Technical
- Shipping
- Account

Answer with a JSON object: {"label": ...}."""

response = client.chat.completions.create(
    model="nenya",
    messages=[{"role": "user", "content": prompt}],
    temperature=0,
    max_tokens=32,
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "label",
            "schema": {
                "type": "object",
                "properties": {
                    "label": {
                        "type": "string",
                        "enum": ["Billing", "Technical", "Shipping", "Account"],
                    },
                },
                "required": ["label"],
                "additionalProperties": False,
            },
        },
    },
)
print(response.choices[0].message.content)
```

JavaScript:

```javascript
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://api.contrastivelabs.dev/v1", apiKey: "none" });

const prompt = `Which team should handle this support ticket?

Ticket:
I was charged twice for my November invoice.

Options:
- Billing
- Technical
- Shipping
- Account

Answer with a JSON object: {"label": ...}.`;

const response = await client.chat.completions.create({
  model: "nenya",
  messages: [{ role: "user", content: prompt }],
  temperature: 0,
  max_tokens: 32,
  response_format: {
    type: "json_schema",
    json_schema: {
      name: "label",
      schema: {
        type: "object",
        properties: {
          label: { type: "string", enum: ["Billing", "Technical", "Shipping", "Account"] },
        },
        required: ["label"],
        additionalProperties: false,
      },
    },
  },
});
console.log(response.choices[0].message.content);
```

The content of the reply:

```json
{"label": "Billing"}
```

### How sure it is

The confidence is worth using. On the same 1,000 items:

| Confidence | Share of the answers | Right |
| --- | --- | --- |
| 0.99 and over | 28% | 97% |
| 0.90 to 0.99 | 36% | 89% |
| 0.70 to 0.90 | 20% | 73% |
| 0.50 to 0.70 | 12% | 52% |
| under 0.50 | 6% | 36% |

| Act only when the confidence is at least | Answers you keep | Right among them |
| --- | --- | --- |
| 0.70 | 83% | 88% |
| 0.80 | 75% | 90% |
| 0.90 | 63% | 93% |
| 0.95 | 51% | 95% |

Pick the threshold from the mistakes you can afford, and send what falls under it to a person or to a larger model.

### How many labels

Accuracy falls as the list grows. On the two tasks the model never saw it lost 5 to 14 points each time the list doubled, about 8 on average. On CLINC150, whose training split it was trained on, it lost 2 to 4 points a doubling up to 80 labels:

| Labels offered | Voice commands (60 intents), unseen | Vehicle complaints (31 components), unseen | CLINC150 (150 intents), trained on it |
| --- | --- | --- | --- |
| 5 | 90.8% | 88.8% | 99.6% |
| 10 | 86.0% | 82.8% | 97.9% |
| 20 | 80.4% | 68.8% | 94.5% |
| 40 | 70.4% |  | 91.6% |
| 60 to 80 | 62.8% | 62.0% (all 31) | 87.4% |
| 150 |  |  | 75.2% |

Keep the list to 20 labels or fewer if you can. With a larger set, classify in two steps: first into a few groups, then into the labels of the group that was chosen. During training the model never saw more than about 25 labels in one prompt.

### When nothing fits

End the prompt with `If none of the options fits, answer "none".` and add `"none"` to the choice list. This is weaker than the rest. We left the right label out of the options for 30% of the items:

|  | Right label offered: right | Right label offered: wrongly said “none” | Right label not offered: said “none” |
| --- | --- | --- | --- |
| Four tasks it never saw | 77.9% | 3.9% | 39% |
| CLINC150, which it was trained on | 93.7% | 2.9% | 89% |

On a task unlike its training, “none” catches four in ten of the texts that belong nowhere. The other six get a label, with a lower confidence than usual: 0.73 at the median, against 0.96 for a right label. So use both: allow “none”, and treat a low confidence as “none” too. With a threshold of 0.8 the two together caught 77% of the texts that belonged nowhere, and with 0.9, 85%.

### Tips

- **Explain labels whose names are not clear**: `- Fraud: transactions the customer does not recognise`. With the reply held to the labels, descriptions raised one task from 68% to 71% to 73%. Without the choice list the model repeats the description after the label.
- **Several labels**: end with `Answer with a JSON object: {"labels": [...]}. Use an empty list if none apply.` and a schema whose `labels` is an array with your labels as the `enum` of its items.
- **A yes/no check** is a classification with two labels, `yes` and `no`.
- **A scale** (`low`, `normal`, `high`, `urgent`) works as it is. Keep the options in their order.
- **Long options**, such as clauses or answers to choose between: letter them `A)`, `B)`, … and end with `Answer with the letter of the correct option only.`
- **Labels that begin with different words** give cleaner confidences.
- **It was trained on tasks like the public ones.** On 14 public classification datasets it scores 80%. On the four tasks here, which it never saw, 79% to 83%. On a task with a habit of its own it can fail: asked whether a summary is supported by its source, it says “supported” almost every time. Try it on 50 of your own examples before you rely on it.

### Sample prompts

A yes/no check:

```text
Does this message ask for a refund?

Message:
Please cancel my order and send my money back.

Options:
- yes
- no

Answer with the label only.
```

Labels that need explaining (reply: `Cards`):

```text
Which queue does this message to an online bank belong in?

Message:
My card was declined abroad even though I told you I was travelling.

Options:
- Cards: lost, blocked, declined or expiring cards
- Fraud: transactions the customer does not recognise
- Payments: transfers, standing orders and direct debits
- General: opening hours, branches and everything else

Answer with the label only.
```

Nothing may fit (replies: `lights` for the first request, `none` for “What is the meaning of life?”):

```text
Which intent does this request express?

Request:
Turn the living room lights down a bit.

Options:
- lights
- heating
- music
- alarm

Answer with the label only. If none of the options fits, answer "none".
```

Several labels (reply: `{"labels": ["cleanliness", "staff", "wifi", "food"]}`):

```text
Which topics does this hotel review mention?

Review:
The room was spotless and the staff were lovely, but the wifi kept dropping and breakfast was cold.

Options:
- cleanliness
- staff
- food
- wifi
- location
- price

Answer with a JSON object: {"labels": [...]}. Use an empty list if none apply.
```

## Extraction

Give the model a document and the fields you want. It gives back one JSON object.

### The recipe

The field list goes in the system message. The document is the user message, alone.

curl:

```bash
curl https://api.contrastivelabs.dev/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "nenya",
    "messages": [
      {
        "role": "system",
        "content": "You extract structured data from invoices. For each document the user sends, give these fields.\n\nFields:\n- vendor (string): Name of the company that issued the invoice\n- invoice_number (string): The invoice number\n- invoice_date (string): The date the invoice was issued, as YYYY-MM-DD\n- due_date (string): The date payment is due, as YYYY-MM-DD\n- customer (string): Name of the customer the invoice is billed to\n- po_number (string): The purchase order number\n- currency (string): Three-letter currency code, such as GBP\n- total (number): The total amount due\n- line_items (list of {description, quantity, unit_price, amount}): One entry for each line of the invoice\n\nAnswer with one JSON object with exactly these keys. Use null for a field the text does not give."
      },
      {
        "role": "user",
        "content": "INVOICE\n\nNorthwind Supply Co.\nInvoice no.: INV-2041\nDate: 3 November 2026\nDue: 3 December 2026\nBill to: Halden Robotics Ltd\n\nDescription                  Qty    Unit    Amount\nM6 hex bolts, box of 500      12   18.40    220.80\nAluminium bracket, 40 mm     250    2.15    537.50\nFreight                        1   64.00     64.00\n\nSubtotal      822.30\nVAT 20%       164.46\nTotal due     GBP 986.76"
      }
    ],
    "temperature": 0,
    "max_tokens": 800,
    "response_format": {
      "type": "json_schema",
      "json_schema": {
        "name": "record",
        "schema": {
          "type": "object",
          "properties": {
            "vendor": {"type": ["string", "null"]},
            "invoice_number": {"type": ["string", "null"]},
            "invoice_date": {"type": ["string", "null"]},
            "due_date": {"type": ["string", "null"]},
            "customer": {"type": ["string", "null"]},
            "po_number": {"type": ["string", "null"]},
            "currency": {"type": ["string", "null"]},
            "total": {"type": ["number", "null"]},
            "line_items": {
              "type": "array",
              "items": {
                "type": "object",
                "properties": {
                  "description": {"type": "string"},
                  "quantity": {"type": "number"},
                  "unit_price": {"type": "number"},
                  "amount": {"type": "number"}
                },
                "required": ["description", "quantity", "unit_price", "amount"],
                "additionalProperties": false
              }
            }
          },
          "required": [
            "vendor",
            "invoice_number",
            "invoice_date",
            "due_date",
            "customer",
            "po_number",
            "currency",
            "total",
            "line_items"
          ],
          "additionalProperties": false
        }
      }
    }
  }'
```

Python:

```python
import json

from openai import OpenAI

client = OpenAI(base_url="https://api.contrastivelabs.dev/v1", api_key="none")


def extract(kind, document, fields, max_tokens=800):
    """{field: value or None}. fields: [{"name", "type", "description"}], plus "schema" for lists and objects."""
    lines = "\n".join(f"- {f['name']} ({f['type']}): {f['description']}" for f in fields)
    system = (f"You extract structured data from {kind}s. For each document the user sends, give these fields.\n\n"
              f"Fields:\n{lines}\n\n"
              "Answer with one JSON object with exactly these keys. Use null for a field the text does not give.")
    properties = {f["name"]: f.get("schema") or {"type": [f["type"], "null"]} for f in fields}
    schema = {"type": "object", "properties": properties, "required": [f["name"] for f in fields],
              "additionalProperties": False}
    reply = client.chat.completions.create(
        model="nenya",
        messages=[{"role": "system", "content": system}, {"role": "user", "content": document}],
        temperature=0,                      # one right answer: do not sample
        max_tokens=max_tokens,
        response_format={"type": "json_schema", "json_schema": {"name": "record", "schema": schema}},
    )
    choice = reply.choices[0]
    if choice.finish_reason != "stop":      # "length": the JSON was cut off and will not parse
        raise RuntimeError(f"the reply was cut off ({choice.finish_reason}): raise max_tokens")
    return json.loads(choice.message.content)


invoice = """INVOICE

Northwind Supply Co.
Invoice no.: INV-2041
Date: 3 November 2026
Due: 3 December 2026
Bill to: Halden Robotics Ltd

Description                  Qty    Unit    Amount
M6 hex bolts, box of 500      12   18.40    220.80
Aluminium bracket, 40 mm     250    2.15    537.50
Freight                        1   64.00     64.00

Subtotal      822.30
VAT 20%       164.46
Total due     GBP 986.76"""

line_item = {"type": "object",
             "properties": {"description": {"type": "string"}, "quantity": {"type": "number"},
                            "unit_price": {"type": "number"}, "amount": {"type": "number"}},
             "required": ["description", "quantity", "unit_price", "amount"], "additionalProperties": False}

record = extract("invoice", invoice, [
    {"name": "vendor", "type": "string", "description": "Name of the company that issued the invoice"},
    {"name": "invoice_number", "type": "string", "description": "The invoice number"},
    {"name": "invoice_date", "type": "string", "description": "The date the invoice was issued, as YYYY-MM-DD"},
    {"name": "due_date", "type": "string", "description": "The date payment is due, as YYYY-MM-DD"},
    {"name": "customer", "type": "string", "description": "Name of the customer the invoice is billed to"},
    {"name": "po_number", "type": "string", "description": "The purchase order number"},
    {"name": "currency", "type": "string", "description": "Three-letter currency code, such as GBP"},
    {"name": "total", "type": "number", "description": "The total amount due"},
    {"name": "line_items", "type": "list of {description, quantity, unit_price, amount}",
     "description": "One entry for each line of the invoice", "schema": {"type": "array", "items": line_item}},
])
print(json.dumps(record, indent=2))
```

JavaScript:

```javascript
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://api.contrastivelabs.dev/v1", apiKey: "none" });

/** {field: value or null}. fields: [{name, type, description}], plus `schema` for lists and objects. */
async function extract(kind, document, fields, maxTokens = 800) {
  const lines = fields.map((f) => `- ${f.name} (${f.type}): ${f.description}`).join("\n");
  const system =
    `You extract structured data from ${kind}s. For each document the user sends, give these fields.\n\n` +
    `Fields:\n${lines}\n\n` +
    "Answer with one JSON object with exactly these keys. Use null for a field the text does not give.";
  const properties = Object.fromEntries(fields.map((f) => [f.name, f.schema ?? { type: [f.type, "null"] }]));
  const schema = {
    type: "object",
    properties,
    required: fields.map((f) => f.name),
    additionalProperties: false,
  };
  const reply = await client.chat.completions.create({
    model: "nenya",
    messages: [
      { role: "system", content: system },
      { role: "user", content: document },
    ],
    temperature: 0, // one right answer: do not sample
    max_tokens: maxTokens,
    response_format: { type: "json_schema", json_schema: { name: "record", schema } },
  });
  const choice = reply.choices[0];
  if (choice.finish_reason !== "stop") {
    // "length": the JSON was cut off and will not parse
    throw new Error(`the reply was cut off (${choice.finish_reason}): raise max_tokens`);
  }
  return JSON.parse(choice.message.content);
}

const invoice = `INVOICE

Northwind Supply Co.
Invoice no.: INV-2041
Date: 3 November 2026
Due: 3 December 2026
Bill to: Halden Robotics Ltd

Description                  Qty    Unit    Amount
M6 hex bolts, box of 500      12   18.40    220.80
Aluminium bracket, 40 mm     250    2.15    537.50
Freight                        1   64.00     64.00

Subtotal      822.30
VAT 20%       164.46
Total due     GBP 986.76`;

const lineItem = {
  type: "object",
  properties: {
    description: { type: "string" },
    quantity: { type: "number" },
    unit_price: { type: "number" },
    amount: { type: "number" },
  },
  required: ["description", "quantity", "unit_price", "amount"],
  additionalProperties: false,
};

const record = await extract("invoice", invoice, [
  { name: "vendor", type: "string", description: "Name of the company that issued the invoice" },
  { name: "invoice_number", type: "string", description: "The invoice number" },
  { name: "invoice_date", type: "string", description: "The date the invoice was issued, as YYYY-MM-DD" },
  { name: "due_date", type: "string", description: "The date payment is due, as YYYY-MM-DD" },
  { name: "customer", type: "string", description: "Name of the customer the invoice is billed to" },
  { name: "po_number", type: "string", description: "The purchase order number" },
  { name: "currency", type: "string", description: "Three-letter currency code, such as GBP" },
  { name: "total", type: "number", description: "The total amount due" },
  {
    name: "line_items",
    type: "list of {description, quantity, unit_price, amount}",
    description: "One entry for each line of the invoice",
    schema: { type: "array", items: lineItem },
  },
]);
console.log(JSON.stringify(record, null, 2));
```

An invoice, with its lines as a list of objects:

What it prints:

```json
{
  "vendor": "Northwind Supply Co.",
  "invoice_number": "INV-2041",
  "invoice_date": "2026-11-03",
  "due_date": "2026-12-03",
  "customer": "Halden Robotics Ltd",
  "po_number": null,
  "currency": "GBP",
  "total": 986.76,
  "line_items": [
    {
      "description": "M6 hex bolts, box of 500",
      "quantity": 12,
      "unit_price": 18.4,
      "amount": 220.8
    },
    {
      "description": "Aluminium bracket, 40 mm",
      "quantity": 250,
      "unit_price": 2.15,
      "amount": 537.5
    },
    {"description": "Freight", "quantity": 1, "unit_price": 64, "amount": 64}
  ]
}
```

The dates came back as `YYYY-MM-DD` because the field descriptions ask for it. The invoice has no purchase order number, so `po_number` is `null`.

What each part does:

- **The system message** names every field, its type and what it means. This is what the model works from.
- **`response_format`** holds the reply to valid JSON with exactly your keys, so it always parses. It does not tell the model anything: leave the field list out of the prompt and the F1 falls from 83 to 45.
- **`temperature: 0`**, as everywhere on this page.
- **`max_tokens` and the `finish_reason` check**: a reply that reaches the limit is cut off in the middle of the JSON.

### Which form to use

500 real documents from 2026, of four kinds the model never saw in training (accident reports, warning letters, vehicle complaints, recall notices), 2,321 fields to find. Field F1 counts a field as right when its value matches, and counts both missed fields and wrong or invented ones against the score.

| How it is asked (`temperature: 0`) | Field F1 | Whole record right | Invented values | Fields filled that the document does not give |
| --- | --- | --- | --- | --- |
| **The recipe above**: field list in the system message, document as the user message | **83.5** | 39.8% | 0.6% | 4.8% |
| One user message: the field list, then the document | 80.2 | 33.0% | 0.6% | 2.7% |
| One user message: the document, then the field list (the layout it was trained on) | 79.4 | 29.6% | 0.9% | 9.5% |
| A tool call whose parameters are the fields | 67.6 to 72.6 | 9% to 17% | 1.5% to 10% | 19% to 57% |
| A tool call with every field marked `required` | 72.8 | 7.0% | 9.2% | 75% |
| The recipe above, fields without descriptions | 67.0 | 20.4% | 0.7% | 10.5% |
| `response_format` alone: no field list in the prompt | 44.7 | 3.0% | 5.3% | 48% (and 72 replies did not parse) |

“Invented values” are values the reply gives that are wrong and stand nowhere in the document.

Three things to take from this:

- **JSON beats a tool call by 11 to 16 points.** As a tool call the model leaves out a third of the fields the document does give. Use a tool call for extraction only when the model also has to choose what to do with the record. If you do, say in the request and in the tool’s description that only stated values are wanted (the wording under [Prompt templates](https://contrastivelabs.com/docs#prompt-templates)): that scored 71 F1, against 68 without it.
- **The system message is the best place for the field list**, and the gap grows with the length of the document (next table). Three different wordings of that message scored 82.9 to 83.5.
- **Descriptions are not optional.** Without them the model has only the field’s name to go on.

By the length of the request:

| Prompt tokens | Field list in the system message | Field list after the document |
| --- | --- | --- |
| under 500 | 84.9 | 81.8 |
| 500 to 1,000 | 84.5 | 85.0 |
| 1,000 to 2,000 | 81.0 | 71.8 |
| 2,000 to 4,000 (14 documents) | 69.0 | 54.9 |

Past about 2,000 tokens, split the document. See [Long documents](https://contrastivelabs.com/docs#long-documents).

### Tips

- **Put the format in the description**: `as YYYY-MM-DD`, `three-letter currency code`, `digits only`. The model follows it.
- **Fixed values**: write `One of: damaged, late, wrong_item, other` in the description and give the field an `enum` in the schema. The schema then holds the value to your list.
- **Missing fields come back as `null`.** In the recipe every key is required and every type allows `null`, so the reply always has every key. The model left 95% of the absent fields empty.
- **Do not mark optional fields as required without allowing `null`.** Forced to give a value, the model gives one: with every field `required` in the tool form, it filled 75% of the fields the document did not have.
- **Dates that need working out are not reliable.** Given “Today is Monday, 30 November 2026”, the model got 1 of 13 relative dates right (“tomorrow”, “next Thursday”, “in two weeks”), and none of three that needed the month or the year filled in (“on the 12th”, “on 5 January”). Told to give a date only if the text has one, it still made one up. Dates written out in the text (“Thursday 3 December”, “December 3rd”) came out right. So ask for the words as they are written (`when_as_written: The day and time, in the email's own words`) and resolve them in your code. We did not test sums or unit conversions: do those in your code too.
- **A schema limit does not make a value true.** A rating field with `maximum: 5` turned “9 out of 10” into `4`. Use limits for the shape of a value, and check the meaning yourself.
- **One document in a request.** For several short records in one text, number them (`Line 1:`, `Line 2:`), write `For each line, give:` above the field list, and end with `Answer with one JSON object whose keys are the line numbers ("1", "2", ...); null for anything not stated.`
- **Check what matters.** 0.6% invented values is low, and it is not zero. For a value you act on, check that it appears in the document.

### Long documents

The limit is 16,384 tokens for the prompt and the reply together, and accuracy starts to fall well before it: from about 85 F1 under 1,000 tokens to 69 between 2,000 and 4,000. For a long document:

1. Split it into parts of 1,000 to 1,500 tokens, at paragraph or section breaks, with a few sentences of overlap.
2. Run the same extraction on every part. Fields the part does not have come back `null`.
3. Merge: for each field take the first value that is not `null`, or keep them all and look at the ones that disagree.

We have not measured this procedure. It follows from the table above: short requests are the ones the model reads best.

To count tokens before you send, see [Counting tokens](https://contrastivelabs.com/docs#counting-tokens).

### PDFs and scans

The API takes text. There is no upload for files on the server yet, so a PDF or a scan is turned into text on your own machine first, and then the extraction recipe runs on that text unchanged.

The tool we recommend for that step is [Docling](https://github.com/docling-project/docling). An MIT licence and fully local execution make it the easy default. Table structure survives its conversion, and scanned pages go through an optional OCR step.

```bash
pip install openai docling
```

```python
from docling.datamodel.base_models import InputFormat
from docling.datamodel.pipeline_options import OcrMode, PdfPipelineOptions
from docling.document_converter import DocumentConverter, PdfFormatOption


def pdf_to_text(path, scanned=False):
    """The text of a PDF as Markdown, tables included. It runs on this machine: nothing is sent anywhere.
    scanned=True reads every page with OCR, for a file that is only pictures of pages."""
    options = PdfPipelineOptions(do_ocr=scanned)            # a PDF that has a text layer needs no OCR
    if scanned:
        options.ocr_options.mode = OcrMode.FULL_PAGE        # read the whole page, not only the pictures in it
    converter = DocumentConverter(format_options={InputFormat.PDF: PdfFormatOption(pipeline_options=options)})
    return converter.convert(path).document.export_to_markdown()


text = pdf_to_text("report.pdf")                        # pdf_to_text("scan.pdf", scanned=True) for a scan
record = extract("aviation accident report", text, FIELDS)      # the recipe above, unchanged
```

- **Switch OCR off for a PDF that has text in it, and on for a scan.** With OCR on, Docling also reads the pictures of a page that already has its text. To tell the two apart, convert with OCR off first: a scan comes back nearly empty.
- **Look at the text before you send it.** Ruled tables come out as Markdown tables, each value in the cell next to its label. A block that the page lays out in columns without rules can come out as loose lines.
- **The conversion runs on your machine.** Docling downloads its models the first time (under 1 GB) and runs them locally. Only the text you pass on goes to the API.
- **A long PDF is a long text.** Convert the pages that hold the facts (`converter.convert(path, page_range=(1, 2))`), or split the text as in [Long documents](https://contrastivelabs.com/docs#long-documents).

In our test, three real accident reports, each as the PDF its agency publishes and as a scan of it, gave 70 of 72 fields right, with the same answers from the scan as from the PDF every time. A two-page file took 5 to 13 seconds to convert on four CPU threads. That was Docling 2.156 on Linux, on clean pages: a skewed photograph or handwriting will do worse. The whole recipe, with the PDF, the scan and the checked answers, is the cookbook [Extract from a PDF or a scan](https://contrastivelabs.com/cookbook/extract-pdfs-and-scans).

### Sample prompts

A meeting from an email. The system message, as the recipe writes it:

```text
You extract structured data from emails. For each document the user sends, give these fields.

Fields:
- organiser (string): Name of the person asking for the meeting
- topic (string): What the meeting is about, in a few words
- when_as_written (string): The day and time of the meeting, in the email's own words
- duration_minutes (integer): Length of the meeting in minutes
- room (string): The room that was booked
- video_link (string): Link for joining by video
- to_bring (string): What the reader is asked to bring

Answer with one JSON object with exactly these keys. Use null for a field the text does not give.
```

The user message is the email (“Can we move the supplier review to next Thursday at 2:30pm? An hour should do. I have booked the Faraday room … Please bring the Q3 defect figures.”). The reply:

The reply:

```json
{
  "organiser": "Priya Nair",
  "topic": "Supplier review",
  "when_as_written": "next Thursday at 2:30pm",
  "duration_minutes": 60,
  "room": "Faraday room",
  "video_link": null,
  "to_bring": "the Q3 defect figures"
}
```

A support ticket into a record with fixed choices:

```text
You extract structured data from support tickets. For each document the user sends, give these fields.

Fields:
- customer_name (string): Name of the customer
- order_id (string): The order number, digits only
- product (string): The product the ticket is about
- problem (string): One of: damaged, late, wrong_item, missing_part, other
- wants (string): One of: refund, replacement, repair, information
- phone (string): The customer's phone number

Answer with one JSON object with exactly these keys. Use null for a field the text does not give.
```

For “Hi, I ordered the standing desk (order 48213) two weeks ago and it arrived with a cracked top. I need it replaced before the 12th, we have an office move. Jo Brandt” the reply is:

The reply:

```json
{
  "customer_name": "Jo Brandt",
  "order_id": "48213",
  "product": "standing desk",
  "problem": "damaged",
  "wants": "replacement",
  "phone": null
}
```

The same extraction in one user message, for a client that cannot send a system message:

```text
Extract these fields from the invoice below.

{the invoice}

Fields:
- vendor (string): Name of the company that issued the invoice
- total (number): The total amount due
- currency (string): Three-letter currency code, such as GBP

Answer with one JSON object with exactly these keys. Use null for a field the text does not give.
```

## Tool calling

Describe your functions. The model decides which to call and with what arguments. Your code runs the call and sends the result back.

### The loop

1. Send the conversation and the tools.
2. If the reply has `tool_calls`, run each one in your own code. The model never runs anything.
3. Append the model’s message as it came, then one `tool` message for each call, with the call’s `id`.
4. Send the conversation again. Repeat until the reply has no calls. Put a limit on the number of turns.
5. When a function has nothing more to try (the order does not exist), it raises `Final` with a sentence for the model. The loop sends the sentence as the result and offers no tools after it, so the model answers in words. Without this the model makes the same call again and again ([After a result](https://contrastivelabs.com/docs#after-a-result)).

A support agent with three tools:

curl:

```bash
# 1. Send the conversation and the tools. The reply holds a call.
curl https://api.contrastivelabs.dev/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "nenya",
    "messages": [
      {
        "role": "system",
        "content": "You are the support assistant of Fernhill, an online furniture shop. You help customers with their orders.\n\nRules:\n- Always look an order up first.\n- Use a tool whenever one fits the request, and pass exactly the values the customer gave.\n- A customer who asks for their money back gets the order'\''s total refunded.\n- If no tool fits, answer in one or two sentences.\n- Keep answers short and plain."
      },
      {
        "role": "user",
        "content": "My standing desk from order 48213 arrived with a cracked top. I would like my money back."
      }
    ],
    "tools": [
      {
        "type": "function",
        "function": {
          "name": "get_order",
          "description": "Look up an order by its number.",
          "parameters": {
            "type": "object",
            "properties": {
              "order_id": {"type": "string", "description": "The order number, digits only"}
            },
            "required": ["order_id"]
          }
        }
      },
      {
        "type": "function",
        "function": {
          "name": "issue_refund",
          "description": "Refund an order, in full or in part.",
          "parameters": {
            "type": "object",
            "properties": {
              "order_id": {"type": "string", "description": "The order number, digits only"},
              "amount": {"type": "number", "description": "Amount to refund, in pounds"},
              "reason": {
                "type": "string",
                "enum": ["damaged", "late", "wrong_item", "other"],
                "description": "Why the customer is refunded"
              }
            },
            "required": ["order_id", "amount", "reason"]
          }
        }
      },
      {
        "type": "function",
        "function": {
          "name": "escalate_to_human",
          "description": "Hand the conversation to a person.",
          "parameters": {
            "type": "object",
            "properties": {
              "summary": {
                "type": "string",
                "description": "What the customer wants, in one sentence"
              }
            },
            "required": ["summary"]
          }
        }
      }
    ],
    "tool_choice": "auto"
  }'

# 3 and 4. Send it again, with the model's message as it came and the result of the call under the call's id.
curl https://api.contrastivelabs.dev/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "nenya",
    "messages": [
      {
        "role": "system",
        "content": "You are the support assistant of Fernhill, an online furniture shop. You help customers with their orders.\n\nRules:\n- Always look an order up first.\n- Use a tool whenever one fits the request, and pass exactly the values the customer gave.\n- A customer who asks for their money back gets the order'\''s total refunded.\n- If no tool fits, answer in one or two sentences.\n- Keep answers short and plain."
      },
      {
        "role": "user",
        "content": "My standing desk from order 48213 arrived with a cracked top. I would like my money back."
      },
      {
        "role": "assistant",
        "content": null,
        "tool_calls": [
          {
            "id": "chatcmpl-tool-855f7d90770cca64",
            "type": "function",
            "function": {"name": "get_order", "arguments": "{\"order_id\": \"48213\"}"}
          }
        ]
      },
      {
        "role": "tool",
        "tool_call_id": "chatcmpl-tool-855f7d90770cca64",
        "content": "{\"order_id\": \"48213\", \"item\": \"Standing desk\", \"status\": \"delivered\", \"total_gbp\": 329.0}"
      }
    ],
    "tools": [
      {
        "type": "function",
        "function": {
          "name": "get_order",
          "description": "Look up an order by its number.",
          "parameters": {
            "type": "object",
            "properties": {
              "order_id": {"type": "string", "description": "The order number, digits only"}
            },
            "required": ["order_id"]
          }
        }
      },
      {
        "type": "function",
        "function": {
          "name": "issue_refund",
          "description": "Refund an order, in full or in part.",
          "parameters": {
            "type": "object",
            "properties": {
              "order_id": {"type": "string", "description": "The order number, digits only"},
              "amount": {"type": "number", "description": "Amount to refund, in pounds"},
              "reason": {
                "type": "string",
                "enum": ["damaged", "late", "wrong_item", "other"],
                "description": "Why the customer is refunded"
              }
            },
            "required": ["order_id", "amount", "reason"]
          }
        }
      },
      {
        "type": "function",
        "function": {
          "name": "escalate_to_human",
          "description": "Hand the conversation to a person.",
          "parameters": {
            "type": "object",
            "properties": {
              "summary": {
                "type": "string",
                "description": "What the customer wants, in one sentence"
              }
            },
            "required": ["summary"]
          }
        }
      }
    ],
    "tool_choice": "auto"
  }'
```

Python:

```python
import json

from openai import OpenAI

client = OpenAI(base_url="https://api.contrastivelabs.dev/v1", api_key="none")


class Final(Exception):
    """A function raises this when there is nothing more to try. Its message goes to the model as the result,
    and no tools are offered after it, so the model answers in words."""


def run_tools(messages, tools, functions, tool_choice="auto", max_turns=6):
    """Run the conversation until the model answers in words. functions: {tool name: Python function}."""
    messages = list(messages)
    for _ in range(max_turns):
        offer = {"tools": tools, "tool_choice": tool_choice} if tools else {"temperature": 0}
        reply = client.chat.completions.create(model="nenya", messages=messages, **offer)
        message = reply.choices[0].message
        if not message.tool_calls:
            return message.content
        messages.append(message.model_dump(exclude_none=True))     # the model's message, as it came
        for call in message.tool_calls:
            arguments = json.loads(call.function.arguments)        # a JSON string: parse it, then check it
            print(f"-> {call.function.name}({arguments})")
            try:
                result = json.dumps(functions[call.function.name](**arguments))
            except Final as final:          # nothing more to try: a sentence for the model, and no more tools
                result, tools = str(final), None
            messages.append({"role": "tool", "tool_call_id": call.id, "content": result})
        tool_choice = "auto"                # a forced first step must not force every later one
    raise RuntimeError("the model kept calling tools: stop and look")


def tool(name, description, properties, required):
    return {"type": "function", "function": {"name": name, "description": description, "parameters": {
        "type": "object", "properties": properties, "required": required}}}


system = """You are the support assistant of Fernhill, an online furniture shop. You help customers with their orders.

Rules:
- Always look an order up first.
- Use a tool whenever one fits the request, and pass exactly the values the customer gave.
- A customer who asks for their money back gets the order's total refunded.
- If no tool fits, answer in one or two sentences.
- Keep answers short and plain."""

tools = [
    tool("get_order", "Look up an order by its number.",
         {"order_id": {"type": "string", "description": "The order number, digits only"}}, ["order_id"]),
    tool("issue_refund", "Refund an order, in full or in part.",
         {"order_id": {"type": "string", "description": "The order number, digits only"},
          "amount": {"type": "number", "description": "Amount to refund, in pounds"},
          "reason": {"type": "string", "enum": ["damaged", "late", "wrong_item", "other"],
                     "description": "Why the customer is refunded"}}, ["order_id", "amount", "reason"]),
    tool("escalate_to_human", "Hand the conversation to a person.",
         {"summary": {"type": "string", "description": "What the customer wants, in one sentence"}}, ["summary"]),
]

ORDERS = {"48213": {"order_id": "48213", "item": "Standing desk", "status": "delivered", "total_gbp": 329.00}}


def get_order(order_id):
    if order_id not in ORDERS:              # found nothing: say so in a sentence, and end the tool calls
        raise Final(f"There is no order {order_id}. Tell the customer, and ask them to check the number.")
    return ORDERS[order_id]


def issue_refund(order_id, amount, reason):
    total = get_order(order_id)["total_gbp"]
    if not 0 < amount <= total:             # a limit belongs here: the model passes on what it is asked for
        return {"error": f"The amount must be more than 0 and at most the order's total of {total:.2f} GBP. "
                         f"Nothing was refunded."}
    return {"refunded_gbp": amount, "order_id": order_id}


functions = {                               # your own code: here, stand-ins
    "get_order": get_order,
    "issue_refund": issue_refund,
    "escalate_to_human": lambda summary: {"ticket": "H-1042"},
}

answer = run_tools(
    [{"role": "system", "content": system},
     {"role": "user", "content": "My standing desk from order 48213 arrived with a cracked top. "
                                 "I would like my money back."}],
    tools, functions)
print(answer)
```

JavaScript:

```javascript
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://api.contrastivelabs.dev/v1", apiKey: "none" });

/**
 * A function throws this when there is nothing more to try. Its message goes to the model as the result,
 * and no tools are offered after it, so the model answers in words.
 */
class Final extends Error {}

/** Run the conversation until the model answers in words. functions: {tool name: JavaScript function}. */
async function runTools(messages, tools, functions, toolChoice = "auto", maxTurns = 6) {
  messages = [...messages];
  for (let turn = 0; turn < maxTurns; turn++) {
    const offer = tools ? { tools, tool_choice: toolChoice } : { temperature: 0 };
    const reply = await client.chat.completions.create({ model: "nenya", messages, ...offer });
    const message = reply.choices[0].message;
    if (!message.tool_calls?.length) return message.content;
    messages.push(message); // the model's message, as it came
    for (const call of message.tool_calls) {
      const args = JSON.parse(call.function.arguments); // a JSON string: parse it, then check it
      console.log(`-> ${call.function.name}(${JSON.stringify(args)})`);
      let result;
      try {
        result = JSON.stringify(functions[call.function.name](args));
      } catch (error) {
        if (!(error instanceof Final)) throw error;
        result = error.message; // nothing more to try: a sentence for the model, and no more tools
        tools = null;
      }
      messages.push({ role: "tool", tool_call_id: call.id, content: result });
    }
    toolChoice = "auto"; // a forced first step must not force every later one
  }
  throw new Error("the model kept calling tools: stop and look");
}

function tool(name, description, properties, required) {
  return {
    type: "function",
    function: { name, description, parameters: { type: "object", properties, required } },
  };
}

const system = `You are the support assistant of Fernhill, an online furniture shop. You help customers with their orders.

Rules:
- Always look an order up first.
- Use a tool whenever one fits the request, and pass exactly the values the customer gave.
- A customer who asks for their money back gets the order's total refunded.
- If no tool fits, answer in one or two sentences.
- Keep answers short and plain.`;

const tools = [
  tool(
    "get_order",
    "Look up an order by its number.",
    { order_id: { type: "string", description: "The order number, digits only" } },
    ["order_id"],
  ),
  tool(
    "issue_refund",
    "Refund an order, in full or in part.",
    {
      order_id: { type: "string", description: "The order number, digits only" },
      amount: { type: "number", description: "Amount to refund, in pounds" },
      reason: {
        type: "string",
        enum: ["damaged", "late", "wrong_item", "other"],
        description: "Why the customer is refunded",
      },
    },
    ["order_id", "amount", "reason"],
  ),
  tool(
    "escalate_to_human",
    "Hand the conversation to a person.",
    { summary: { type: "string", description: "What the customer wants, in one sentence" } },
    ["summary"],
  ),
];

const ORDERS = { "48213": { order_id: "48213", item: "Standing desk", status: "delivered", total_gbp: 329.0 } };

function getOrder({ order_id }) {
  if (!(order_id in ORDERS)) {
    // found nothing: say so in a sentence, and end the tool calls
    throw new Final(`There is no order ${order_id}. Tell the customer, and ask them to check the number.`);
  }
  return ORDERS[order_id];
}

function issueRefund({ order_id, amount, reason }) {
  const total = getOrder({ order_id }).total_gbp;
  if (!(amount > 0 && amount <= total)) {
    // a limit belongs here: the model passes on what it is asked for
    return {
      error: `The amount must be more than 0 and at most the order's total of ${total.toFixed(2)} GBP. Nothing was refunded.`,
    };
  }
  return { refunded_gbp: amount, order_id };
}

// your own code: here, stand-ins
const functions = {
  get_order: getOrder,
  issue_refund: issueRefund,
  escalate_to_human: ({ summary }) => ({ ticket: "H-1042" }),
};

const answer = await runTools(
  [
    { role: "system", content: system },
    {
      role: "user",
      content: "My standing desk from order 48213 arrived with a cracked top. I would like my money back.",
    },
  ],
  tools,
  functions,
);
console.log(answer);
```

What it prints:

```text
-> get_order({'order_id': '48213'})
-> issue_refund({'order_id': '48213', 'amount': 329.0, 'reason': 'damaged'})
Your money back has been processed. The standing desk (order 48213) total £329.00 has been refunded.
```

The JavaScript prints:

```text
-> get_order({"order_id":"48213"})
-> issue_refund({"order_id":"48213","amount":329,"reason":"damaged"})
Your order 48213 has been refunded in full.
```

Three things in this example come out of our tests ([After a result](https://contrastivelabs.com/docs#after-a-result)):

- Every rule says what to do, and the third one says it for the usual case, a customer who names no amount.
- The limit on a refund is in `issue_refund`, not in the rules. The model does not keep a limit that is only written down.
- An order that does not exist ends the tool calls. Asked about order 77120, the model looks it up once and answers “I couldn’t find an order with ID 77120. Could you double-check the order number and share it with me?”.

### What goes over the wire

The model’s message has no text, only the calls. `arguments` is a JSON string, not an object:

The model’s message:

```json
{
  "role": "assistant",
  "content": null,
  "tool_calls": [
    {
      "id": "chatcmpl-tool-855f7d90770cca64",
      "type": "function",
      "function": {"name": "get_order", "arguments": "{\"order_id\": \"48213\"}"}
    }
  ]
}
```

You send that message back as it came, followed by the result:

The result, as the next message:

```json
{
  "role": "tool",
  "tool_call_id": "chatcmpl-tool-855f7d90770cca64",
  "content": "{\"order_id\": \"48213\", \"item\": \"Standing desk\", \"status\": \"delivered\", \"total_gbp\": 329.0}"
}
```

When a request needs more than one call, they come in one reply. Asked for the weather in Paris and in Tokyo, the model returns two calls. Run both and send both results before you ask again. `parallel_tool_calls: false` keeps a reply to one call.

The two calls:

```json
[
  {"name": "get_weather", "arguments": {"city": "Paris"}},
  {"name": "get_weather", "arguments": {"city": "Tokyo"}}
]
```

### Choosing whether it calls

| `tool_choice` | What happens |
| --- | --- |
| `"auto"` | The default. The model calls when it judges that a tool fits, and answers in words when it judges that none does. |
| `"required"` | It has to call: a call always comes back. |
| `{"type": "function", "function": {"name": "get_order"}}` | It has to call that tool. `finish_reason` is then `stop`, not `tool_calls`: look at `message.tool_calls`. |
| `"none"` | Calls are not read. The model still sees the tools and may write a call out as text (`<function_calls>…`), so to stop it calling, leave `tools` out. |

Forcing guarantees that a call comes back. It does not check the values against your schema: an `enum` in a tool’s parameters is a hint, forced or not. We saw `"Brake"` where the list had `"Service brakes"`. Check the arguments before you act on them. To hold a value to a list, use [JSON output](https://contrastivelabs.com/docs#json-output) with a schema.

### Make sure it calls

This is the behaviour to know about before you build on tool calling. We asked 400 questions that each have one right tool, and added unrelated tools to the list:

| Tools offered | Right call | Answered in words instead | Right call with `tool_choice: "required"` |
| --- | --- | --- | --- |
| 1 | 89.5% | 3.8% | 92.2% |
| 2 | 87.0% | 6.2% | 92.0% |
| 4 | 73.2% | 20.2% | 91.5% |
| 8 | 63.8% | 28.8% | 90.2% |
| 16 | 79.2% | 8.8% | 87.0% |
| 32 | 83.2% | 2.5% | 84.8% |
| 64 | 78.0% | 2.2% | 79.5% |

With 4 to 8 tools and nothing else in the request, the model often replies “The provided tools do not include a function for that”, although one of them does. Forced to call, it picks the right tool and fills it correctly nine times in ten. So the tool is found: what goes wrong is the decision to call.

There are three ways to fix it. Which one is right depends on what happens when no tool fits. We tested that too, with 240 questions that none of the tools offered can answer:

| With 8 tools offered | A tool fits: right call | No tool fits: makes no call |
| --- | --- | --- |
| Nothing set | 63.8% | 90.8% |
| A system message that says when to call (below) | 81.5% | 85.0% |
| A system message with a role and a list of house rules | 86.2% to 86.5% | 77.1% to 77.9% |
| `tool_choice: "required"` | 90.2% | 0%: it has to call |
| `tool_choice: "required"` and a `no_matching_tool` tool | 90.2% | 50.0% (it calls `no_matching_tool`) |

- **Every request should become a call** (a command interface, a router, a form filler): set `tool_choice: "required"`. Add a `no_matching_tool` tool so that a request that fits nothing has somewhere to go. When a tool fitted, the model took that way out by mistake once in 400 requests. It catches half to two thirds of the requests that fit nothing, so still check the call.
- **Some requests need a call and some need an answer** (an assistant): give it a system message. Any system message helps, and the more it reads like a real assistant’s instructions, the more the model calls, when it should and when it should not. The one that balanced best in our tests:

```text
You can only act through the tools you are given. For every request that one of the tools covers, you must call that tool: never compute, look up or answer from your own knowledge when a tool covers the request. Only when no tool covers it, reply in one sentence that you cannot help with that.
```

- **A wrong call is costly** (payments, deletions): leave `tool_choice` on `"auto"`, keep the system message short, and accept that some requests get an answer in words. Then ask the user to confirm before the call runs.

The way-out tool:

JSON:

```json
{
  "type": "function",
  "function": {
    "name": "no_matching_tool",
    "description": "Call this when none of the other tools can do what the user asks.",
    "parameters": {
      "type": "object",
      "properties": {
        "reason": {"type": "string", "description": "One sentence on why no tool fits"}
      },
      "required": ["reason"]
    }
  }
}
```

Python:

```python
tool("no_matching_tool", "Call this when none of the other tools can do what the user asks.",
     {"reason": {"type": "string", "description": "One sentence on why no tool fits"}}, ["reason"])
```

JavaScript:

```javascript
tool("no_matching_tool", "Call this when none of the other tools can do what the user asks.",
  { reason: { type: "string", description: "One sentence on why no tool fits" } }, ["reason"])
```

The call each command becomes:

```text
Make it a bit warmer in the bedroom, 21 degrees.   -> set_temperature({"room": "bedroom", "celsius": 21})
Dim the kitchen lights to 30%.                     -> set_lights({"room": "kitchen", "brightness": 30})
Order me a pizza.                                  -> no_matching_tool({"reason": "I don't have a pizza ordering tool available."})
```

### After a result

The second step of the loop is the model reading what your function returned and deciding what comes next: an answer in words, or another call. We tested that step on 360 cases from 30 kinds of application (orders, bookings, invoices, calendars, stock, tickets, payments), and the shop example above on its own ([Our tests](https://contrastivelabs.com/docs#our-tests)). Four things came out of it.

**1. It does not matter how you write a result.** The same 360 results, written in different ways:

| The result is written | Right |
| --- | --- |
| as Python writes it: `json.dumps(result)` | 98.1% |
| as JavaScript writes it: `JSON.stringify(result)` (no spaces, `329` for `329.0`) | 97.6% |
| indented by two spaces, from Python and from JavaScript | 98.2% and 98.8% |
| as a printed Python dict: `str(result)` (single quotes, `True`, `None`) | 98.6% |
| as one sentence | 98.2% |
| as Python writes it, with the keys in the opposite order | 98.2% |
| as Python writes it, sent a second time | 98.3% |

The last two rows are not spellings at all, and they move the number as much as the spellings do. So send what your language writes. Letters outside ASCII can be escaped (`"Z\u00fcrich"`, which is what `json.dumps` writes) or not: 97.9% and 98.8% on the 167 cases that have them, within chance as well. Indentation costs tokens: 31 more than JavaScript’s unspaced JSON for these results, in prompts of about 440. It was also the one spelling that moved the model’s choice at all, shifting the odds of the first token by a factor of about 1.6 towards the right kind of reply. That is too little to show in the table and enough to tip a step that is nearly a tie, which is point 4.

**2. Write a rule as what to do.** When this page was first printed, the shop example had the rule “Refund only what the customer asks for, and never more than the order’s total”. The customer in the example asks for their money back and names no amount, so that rule does not say what to do. We ran that conversation and twelve like it, every step generated, 504 times with the old rule and 336 times with the rule as it is printed now (“A customer who asks for their money back gets the order’s total refunded”):

| The conversation ended with | Old rule | Rule as printed now |
| --- | --- | --- |
| one refund of the order’s total | 79% | 100% |
| words and no call, most often “I’ll process a refund for the damaged item” | 6% | 0 |
| a refund of 0 | 6% | 0 |
| “I can’t find order 48213 in our system”, after the order had come back | 5% | 0 |
| a question back to the customer | 4% | 0 |

A rule that leaves the model to work the value out is followed to the letter (nothing was asked for, so 0), or the model stops to ask, or it loses the thread. A rule that names the usual case is followed.

**3. A limit is not kept. Check it in your code.** With “never refund more than the order’s total” in the system message, in four wordings, a customer who asked for 500 pounds back on an order of 329 was refunded 500 in 110 conversations out of 110. The model passes on what it is asked for. With the limit in the function, as in the example, the function refused the 500 in 170 conversations out of 170, and no customer was told that 500 had been paid. With the rules as printed, the model then told the customer that it could not make that refund and named the order’s total (58 times in 100), or refunded the 329 (42 times in 100). The same holds for an `enum` ([Choosing whether it calls](https://contrastivelabs.com/docs#tool-choice)): what must not happen has to be checked by the code that runs the call.

**4. A look-up that finds nothing has to end the tool calls.** Told that there is no such order, the model does not tell the customer. It makes the call again, with the same number or one digit changed, until the loop reaches its limit: 290 conversations out of 290 with the shop example, whatever the system message said. The same step in 114 cases from 19 kinds of application:

| The function answers a look-up that found nothing with | The model says so | It makes the call again |
| --- | --- | --- |
| `{"error": "no such order"}` | 3% | 96% |
| `{"status": 404, "message": "Order not found"}` | 3% | 96% |
| `{"found": false}` | 33% | 62% |
| `null` | 39% | 52% |
| `{}` | 52% | 36% |
| `There is no order 77120.` | 54% | 45% |
| `There is no order 77120. Tell the user, and ask them to check it.` | 58% | 42% |
| that last sentence, and the next request sent without `tools` and with `temperature: 0` | 100% | 0 |

The word `error` is read as “try again”. A sentence does better, and nothing works reliably while the tools are still on offer: a rule in the system message (“If a tool finds nothing or returns an error, do not call it again”) moved the first row from 96% to 85%, and `tool_choice: "none"` made the model write the call out as text instead (83%). What works is both together: the result is a sentence that says what happened and what to do, and the request that follows has no `tools`. Set `temperature: 0` on that request, because a request without tools is sampled by default, and sampled it was right 91.5% of the time, not 100%. `Final` in [the loop](https://contrastivelabs.com/docs#tool-calling-loop) does all three, and the shop example then answered an unknown order number in 20 conversations out of 20. Keep `{"error": ...}` for a failure the model can do something about: the refusal of the 500 pounds above is one.

#### Close calls

A step where two continuations are almost equally likely can come out as a sentence the model hardly ever means. At temperature 0 the model writes the most likely next token at every step, which is not the same as the most likely reply. With the old refund rule, the first token after the order’s result was an exact tie: the tool call 46.6%, the word “I” 46.6%. The server gives an exact tie to the word. After “I” came “ can” (39%), then “’t” (43%), then “ find” (32%), and the reply was “I can’t find order 48213 in our system. Could you confirm the order number?”. Sent alone, the request gave that reply 12 times out of 12. Sampled at temperature 1, the same request gave the refund 33 times in 60 and a question to the customer 21 times, and the “can’t find” sentence once in 120.

At such a tie the reply is also not the same every time. Sent 48 times while the server was answering other requests, that request came back as the refund 19 times, as “I’ll process a refund” with no call 22 times and as “I can’t find order” 7 times ([Sampling when you set nothing](https://contrastivelabs.com/docs#sampling) says why). With the rule as printed now the call has 85% to 88% at the first token, and all 48 replies were the refund.

You can see a close call before it bites: ask for `logprobs` and read the first token of the reply.

```python
import math

reply = client.chat.completions.create(model="nenya", messages=messages, tools=tools, logprobs=True,
                                       top_logprobs=3)
for alternative in reply.choices[0].logprobs.content[0].top_logprobs:      # the first token of the reply
    print(f"{alternative.token!r:20} {math.exp(alternative.logprob):.0%}")
```

What it prints:

```text
'<function_calls>'   88%
'I'                  9%
'The'                1%
```

`<function_calls>` is the token every tool call begins with. When it and a word are close to each other, the step is a close call: say in the system message what should happen there, or set `tool_choice` for that step when your code knows that a call has to come next. In the 360 cases the two were within a factor of 1.6 of each other in 61% of the refund requests asked with the old rule, in 12% of the requests to book the cheapest of three flights, and in 0.1% of all the others.

### How many tools

With the call forced, what is left is picking the tool and filling its arguments: 92% right with one or two tools, 90% with 8, 87% with 16, 85% with 32, 80% with 64. Wrong picks begin at 16 tools (1%) and reach 8% at 64. The list also costs tokens: 155 for each tool on average in this test, so 64 tools take 10,000 of the 16,384.

Keep the list to the tools the request could need, 16 or fewer if you can. With a large catalogue, choose the candidates first (by keyword, by embedding, or with a [classification](https://contrastivelabs.com/docs#classification) into groups of tools) and offer only those.

### Tips

- **Leave `temperature` unset.** A request with tools is decoded greedily, and that is the best setting: at 0.7 the right calls fell by 3.5 points, at 1.0 by 7.
- **Describe every parameter.** Without parameter descriptions, wrong arguments went from 7.5% to 14.5%. Say the format: `The order number, digits only`, `Amount in pounds`.
- **Mark as `required` what the call cannot do without**, and leave the rest optional. The model leaves an optional parameter out when the user did not mention it.
- **Similar tools are hard too.** With two to four tools from one domain, the right calls were 82.5% (BFCL `multiple`) against 89% for a single tool (BFCL `simple`). Give look-alike tools descriptions that say when to use which.
- **When no tool fits, it sometimes calls anyway**: with one tool that does not fit, it made a call in 18% of the requests (BFCL `irrelevance`). Do not let a call run unchecked.
- **Several independent calls work**: 84% (BFCL `parallel`).
- **Chains of calls are the weak spot.** When each call needs the result of the one before, the model is much less reliable: 13.9% on BFCL’s multi-turn categories, where the five other small models we compared score between 0% and 15%. Keep each step small, and put a limit on the number of turns.
- **Tool results** go back as text, written the way your language writes them: Python’s JSON, JavaScript’s, indented or not made no difference in our tests ([After a result](https://contrastivelabs.com/docs#after-a-result)). Keep them short: they count against the context.
- **Rules say what to do. Limits go into your code. A look-up that finds nothing ends the tool calls** (`Final` in [the loop](https://contrastivelabs.com/docs#tool-calling-loop)). A rule that left a value open ended 1 conversation in 5 without the refund, a limit written in the system message was never kept, and `{"error": "no such order"}` was answered with the same call again 96 times in 100 ([After a result](https://contrastivelabs.com/docs#after-a-result)).
- **A cut-off call**: if a non-streamed reply to a tool request does not parse as a call, the server generates it once more at temperature 0.7 before it answers. A call cut by your own `max_tokens` arrives as text in `content`, beginning `<function_calls>`, with `finish_reason: "length"`.

## JSON output

`response_format` holds the reply to JSON:

| `response_format` | The reply is |
| --- | --- |
| `{"type": "json_object"}` | some valid JSON object. The prompt decides its keys. |
| `{"type": "json_schema", "json_schema": {"name": "...", "schema": {...}}}` | valid JSON that fits your schema |

Four things to know:

- **The model does not see the schema.** Say in the prompt which keys you want and what they mean.
- **It is decoded at temperature 0** unless you set a sampling field (`temperature`, `top_p`, `top_k`, `min_p`) or ask for several replies with `n`. Set a `temperature` when you want variety: ten different made-up records, say.
- **A reply can be cut off**: check `finish_reason`. With `length` the content is JSON broken off part-way, such as `{"invoice_number": "INV-2041", "date": "14 March 2026", "seller": {"name`, and will not parse. Set `max_tokens` with room to spare.
- **A reply can run on into blank space until `max_tokens`.** That happens when the schema forbids what the model wants to write next, because blank space is the one thing JSON always allows. Asked for settings that the text gives as `x_speed is 3`, with every value typed `string`, the reply was `{"x_speed":` and then spaces to the limit. With the type `["string", "number"]` it was `{"x_speed": 3, "x_mode": "fast"}`, and so it was with the type left as `string` and “Write every value as a string, in quotes” added to the prompt. So make the types match how the text writes the values, or say in the prompt how to write them. And let a field be `null` when the text may not have it: a required `string` field for a purchase order number the invoice did not have came back as the text `"null"`, and in one sampled run as a number the model made up. At temperature 0 the same request fails the same way every time: change the prompt or the schema. `repetition_detection` ([Request parameters](https://contrastivelabs.com/docs#parameters)) ends such a reply early, with `finish_reason: "repetition"`.

### What a schema may use

| Works |  |
| --- | --- |
| Types | `string`, `integer`, `number`, `boolean`, `null`, lists of types such as `["string", "null"]` |
| Structure | nested objects, arrays, arrays of objects, `$defs` and `$ref`, `anyOf`, `oneOf` |
| Objects | `properties`, `required` (a key not listed may be left out), `additionalProperties`; `patternProperties` with one pattern, written to match the whole key (`^x_[a-z]+$`, not `^x_`) and used without `properties` |
| Values | `enum`, `const` |
| Numbers | `minimum`, `maximum`, `exclusiveMinimum` |
| Strings | `minLength`, `maxLength`, `pattern`, and `format`: `date`, `time`, `date-time`, `duration`, `email`, `hostname`, `ipv4`, `ipv6`, `uuid`, `uri` |
| Arrays | `minItems`, `maxItems` |

| Refused with a `400` and the code `unsupported_schema` |
| --- |
| `multipleOf` |
| `uniqueItems`, `contains`, `minContains`, `maxContains` |
| `pattern` or `format` together with `minLength` or `maxLength` on one string |
| a `format` the server does not know (`phone`, for example) |
| `allOf` with two or more branches |
| `propertyNames` together with `properties` or `patternProperties` |
| `patternProperties` together with `properties`, or with more than one pattern |

The message of that `400` names each keyword and where it stands in your schema:

400 Bad Request:

```json
{
  "error": {
    "message": "`multipleOf` (at `properties.price`) is not supported in a JSON schema on this server. Take it out, say the rule in the prompt and check the value in your code.",
    "type": "invalid_request_error",
    "param": "response_format",
    "code": "unsupported_schema"
  }
}
```

A keyword in neither table may be accepted and then not enforced: `not`, `if` with `then`, and `dependentRequired` are. Check in your code whatever matters. The parameters of a tool are a different matter: they are never refused, and a call is not held to their `enum`s and limits ([Choosing whether it calls](https://contrastivelabs.com/docs#tool-choice)).

A schema holds the shape of the reply, not its truth. Under `"format": "date"` the reply is a well-formed date, and it can be the wrong one. Under `"maxItems": 2` a list of three cities comes back as two.

### Holding a reply to a list, or to a pattern

`structured_outputs` is an extension of this API for replies that are not JSON:

Python:

```python
extra_body={"structured_outputs": {"choice": ["Billing", "Technical", "Shipping", "Account"]}}   # one of these
extra_body={"structured_outputs": {"regex": "[A-Z]{3}-[0-9]{4}"}}                                 # this pattern
```

JavaScript:

```javascript
structured_outputs: { choice: ["Billing", "Technical", "Shipping", "Account"] },   // one of these
structured_outputs: { regex: "[A-Z]{3}-[0-9]{4}" },                                // this pattern
```

## Streaming

Set `"stream": true`. Tokens arrive as server-sent events as they are generated, ending with `data: [DONE]`. Add `"stream_options": {"include_usage": true}` to get the token counts in a last event.

Streaming is for text a person reads as it arrives. The usual place for it in an agent is the last step: the sentence the model writes from a tool’s result.

curl:

```bash
curl -N https://api.contrastivelabs.dev/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "nenya",
    "messages": [
      {
        "role": "system",
        "content": "You are the support assistant of Fernhill, an online furniture shop. You help customers with their orders.\n\nRules:\n- Always look an order up first.\n- Use a tool whenever one fits the request, and pass exactly the values the customer gave.\n- A customer who asks for their money back gets the order'\''s total refunded.\n- If no tool fits, answer in one or two sentences.\n- Keep answers short and plain."
      },
      {"role": "user", "content": "Where is my order 48213?"},
      {
        "role": "assistant",
        "content": null,
        "tool_calls": [
          {
            "id": "call_1",
            "type": "function",
            "function": {"name": "get_order", "arguments": "{\"order_id\": \"48213\"}"}
          }
        ]
      },
      {
        "role": "tool",
        "tool_call_id": "call_1",
        "content": "{\"order_id\": \"48213\", \"status\": \"in transit\", \"carrier\": \"DHL\", \"expected_delivery\": \"2026-12-04\"}"
      }
    ],
    "tools": [
      {
        "type": "function",
        "function": {
          "name": "get_order",
          "description": "Look up an order by its number.",
          "parameters": {
            "type": "object",
            "properties": {
              "order_id": {"type": "string", "description": "The order number, digits only"}
            },
            "required": ["order_id"]
          }
        }
      },
      {
        "type": "function",
        "function": {
          "name": "issue_refund",
          "description": "Refund an order, in full or in part.",
          "parameters": {
            "type": "object",
            "properties": {
              "order_id": {"type": "string", "description": "The order number, digits only"},
              "amount": {"type": "number", "description": "Amount to refund, in pounds"},
              "reason": {
                "type": "string",
                "enum": ["damaged", "late", "wrong_item", "other"],
                "description": "Why the customer is refunded"
              }
            },
            "required": ["order_id", "amount", "reason"]
          }
        }
      },
      {
        "type": "function",
        "function": {
          "name": "escalate_to_human",
          "description": "Hand the conversation to a person.",
          "parameters": {
            "type": "object",
            "properties": {
              "summary": {
                "type": "string",
                "description": "What the customer wants, in one sentence"
              }
            },
            "required": ["summary"]
          }
        }
      }
    ],
    "stream": true
  }'
```

Python:

```python
from openai import OpenAI

client = OpenAI(base_url="https://api.contrastivelabs.dev/v1", api_key="none")

# system and tools are the support agent's, from "Tool calling" above
stream = client.chat.completions.create(
    model="nenya",
    messages=[
        {"role": "system", "content": system},
        {"role": "user", "content": "Where is my order 48213?"},
        {
            "role": "assistant",
            "content": None,
            "tool_calls": [
                {
                    "id": "call_1",
                    "type": "function",
                    "function": {"name": "get_order", "arguments": "{\"order_id\": \"48213\"}"},
                },
            ],
        },
        {
            "role": "tool",
            "tool_call_id": "call_1",
            "content": "{\"order_id\": \"48213\", \"status\": \"in transit\", \"carrier\": \"DHL\", \"expected_delivery\": \"2026-12-04\"}",
        },
    ],
    tools=tools,
    stream=True,
)
for chunk in stream:
    if not chunk.choices:
        continue
    delta = chunk.choices[0].delta
    if delta.content:
        print(delta.content, end="", flush=True)
    for call in delta.tool_calls or []:
        print(call.function.name, call.function.arguments)
```

JavaScript:

```javascript
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://api.contrastivelabs.dev/v1", apiKey: "none" });

// system and tools are the support agent's, from "Tool calling" above
const stream = await client.chat.completions.create({
  model: "nenya",
  messages: [
    { role: "system", content: system },
    { role: "user", content: "Where is my order 48213?" },
    {
      role: "assistant",
      content: null,
      tool_calls: [
        {
          id: "call_1",
          type: "function",
          function: { name: "get_order", arguments: "{\"order_id\": \"48213\"}" },
        },
      ],
    },
    {
      role: "tool",
      tool_call_id: "call_1",
      content: "{\"order_id\": \"48213\", \"status\": \"in transit\", \"carrier\": \"DHL\", \"expected_delivery\": \"2026-12-04\"}",
    },
  ],
  tools: tools,
  stream: true,
});
for await (const chunk of stream) {
  const delta = chunk.choices[0]?.delta;
  if (delta?.content) process.stdout.write(delta.content);
  for (const call of delta?.tool_calls ?? []) {
    console.log(call.function.name, call.function.arguments);
  }
}
```

You should see, a few words at a time:

```text
Your order 48213 is in transit with DHL and is expected to be delivered on 2026-12-04.
```

- Tool calls stream too. Each call arrives whole, in one event, with its arguments complete.
- The last event of a choice carries its `finish_reason`.
- A stream that breaks off part-way ends with a `data: {"error": …}` event.
- For long replies, stream. A non-streamed request that runs longer than 50 seconds is answered with `200` early and kept open with whitespace until its JSON is ready; standard JSON parsers and the OpenAI SDKs read it normally.

## Text completion

`POST /v1/completions` continues a prompt as raw text, with no chat format and no system turn around it. It takes `logprobs` and `echo`, which makes it the endpoint for scoring text. A list of prompts in one request is answered as a batch.

curl:

```bash
curl https://api.contrastivelabs.dev/v1/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "nenya",
    "prompt": "The capital of France is",
    "max_tokens": 8,
    "temperature": 0
  }'
```

Python:

```python
from openai import OpenAI

client = OpenAI(base_url="https://api.contrastivelabs.dev/v1", api_key="none")

response = client.completions.create(
    model="nenya",
    prompt="The capital of France is",
    max_tokens=8,
    temperature=0,
)
print(response.choices[0].text)
```

JavaScript:

```javascript
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://api.contrastivelabs.dev/v1", apiKey: "none" });

const response = await client.completions.create({
  model: "nenya",
  prompt: "The capital of France is",
  max_tokens: 8,
  temperature: 0,
});
console.log(response.choices[0].text);
```

You should see:

```text
 Paris, and the capital of the United
```

## Endpoints

| Endpoint | What it does |
| --- | --- |
| `POST /v1/chat/completions` | Chat, with tools, JSON output and streaming |
| `POST /v1/completions` | Raw text completion, with `logprobs` and `echo` |
| `GET /v1/models` | The model names |
| `GET /health` | `200` when the model is ready, `503` while it starts |

Nothing else is served.

## Request parameters

- `model` (string; required): Send `nenya`. The id of a retired checkpoint gets `404`; any other name is answered by the checkpoint that is served ([Names](https://contrastivelabs.com/docs#names)).
- `messages` (array; required): Roles: `system`, `developer`, `user`, `assistant`, `tool`. Content is a string or a list of `text` parts.
- `tools` (array; default: none): See [Tool calling](https://contrastivelabs.com/docs#tool-calling).
- `tool_choice` (string or object; default: "auto"): `"auto"`, `"required"`, `"none"`, or one named function.
- `parallel_tool_calls` (boolean; default: true): `false` keeps a reply to one call.
- `response_format` (object; default: none): See [JSON output](https://contrastivelabs.com/docs#json-output).
- `temperature` (number; default: 0.9 with top-k 20; 0 when the request has tools, response_format (JSON) or structured_outputs): Used as you set it, `0` included. Set `0` for anything with one right answer.
- `max_tokens` (integer; default: no limit but the context): The most tokens a reply may have. Set it. `max_completion_tokens` means the same. A value above 16,384 gets a `400`; a value above the room that is left is lowered to it.
- `stop` (string or array; default: none): Text that ends the reply.
- `seed` (integer; default: none): Makes sampling repeatable.
- `logprobs, top_logprobs` (boolean, integer; default: off): The probability of each token of the reply and of its nearest alternatives. See [How sure it is](https://contrastivelabs.com/docs#classification-confidence).
- `stream, stream_options` (boolean, object; default: false): See [Streaming](https://contrastivelabs.com/docs#streaming).
- `n` (integer; default: 1): Several replies to one request, 62 at most. It needs sampling: with `temperature: 0`, or with `tools` and no `temperature`, `n` above 1 gets a `400` (“n must be 1 when using greedy sampling”). Parallel requests are the better way to go fast.

Also accepted from OpenAI’s list: `top_p`, `presence_penalty`, `frequency_penalty`, `logit_bias`.

Beyond OpenAI’s, these are accepted. With the Python SDK pass them in `extra_body`; the JavaScript SDK sends extra keys as they are.

| Parameter | What it does |
| --- | --- |
| `structured_outputs` | `{"choice": [...]}` or `{"regex": "..."}`: holds the reply to a list or a pattern. |
| `repetition_detection` | `{"max_pattern_size": 20, "min_pattern_size": 1, "min_count": 8}` stops a reply that repeats a pattern of up to 20 tokens 8 times in a row. The reply then ends with `finish_reason: "repetition"`. A cheap guard against a loop. |
| `return_prompt_text` | `true` adds `prompt_text` to the reply: the prompt as the model read it. |
| `top_k`, `min_p`, `repetition_penalty` | more sampling controls |
| `min_tokens`, `stop_token_ids`, `ignore_eos` | controls over where a reply ends |
| `prompt_logprobs`, `echo` | probabilities of the prompt’s own tokens (`echo` on `/v1/completions`) |
| `continue_final_message`, `add_generation_prompt` | continue a last `assistant` message instead of starting a new one |

Fields the API does not know are dropped, and the reply’s `x-nenya-ignored` header names them. That covers `user`, a chat template of your own, reasoning settings, and the older `guided_choice` and `guided_json`. The retired `functions` and `function_call` get a `400`: use `tools` and `tool_choice`.

### Sampling when you set nothing

| Request | Decoding |
| --- | --- |
| A request with `tools` (and `tool_choice` not `"none"`) | temperature 0 |
| A request for one reply with `response_format` of type `json_object` or `json_schema`, or with `structured_outputs`, on either endpoint | temperature 0 |
| Every other request | temperature 0.9, top-k 20 |

“Nothing” means none of `temperature`, `top_p`, `top_k` and `min_p`: set one of them and the request is decoded as you say. Three kinds of request that you might expect to be decoded at temperature 0 are sampled all the same:

- a classification or an extraction asked in plain words, with nothing in the request that holds the reply to a shape. The server cannot tell it from a chat. Set `temperature: 0`;
- a JSON request that asks for several replies (`n` above 1). Several replies at temperature 0 would be one reply several times, and the engine refuses them;
- the request of a tool loop that is sent without `tools`, such as the answer after a look-up that found nothing ([After a result](https://contrastivelabs.com/docs#after-a-result)). The loop on this page sets `temperature: 0` on it.

`temperature: 0` gives the same reply to the same request, except at a near tie: requests are computed in batches together with other callers’, which moves the last decimals, and when two answers are almost equally likely the choice can flip. The confidence ([How sure it is](https://contrastivelabs.com/docs#classification-confidence)) tells you when you are there.

How often that happens: we sent 4,318 tool-loop requests twice while the server was busy with other requests. The second reply was worded differently from the first in 14% of the pairs, and it was right where the first was wrong, or the other way round, in 0.7%. Sent one after the other to an idle server, a request gave the same reply every time. The scores behind a reply are kept in half precision, so two tokens can have exactly the same score: that happened at 1 generated token in 100, in 1 reply in 5. The server then takes the token that comes first in its vocabulary, and the token that opens a tool call stands near the end of it: at an exact tie between a call and a word, the reply begins with the word ([Close calls](https://contrastivelabs.com/docs#close-calls)).

## finish_reason

| Value | Meaning | What to do |
| --- | --- | --- |
| `stop` | The model ended its reply, or one of your `stop` strings came up. | Use the reply. |
| `length` | The reply reached `max_tokens` or the end of the context. It is cut off. | Do not parse it as JSON. Raise `max_tokens`, or shorten the prompt. A tool call that was cut off is left as text in `content`. |
| `tool_calls` | The reply holds tool calls. | Run them. With a function forced by name the value is `stop`: look at `message.tool_calls`. |
| `repetition` | Only with `repetition_detection`: a loop was stopped. | Treat the reply as failed. |

Each choice also carries `stop_reason`, an extra of the engine: the `stop` string that ended the reply, a token number, or `null`. You can ignore it.

## Reply headers

| Header | What it tells you |
| --- | --- |
| `x-nenya-model` | The exact checkpoint that answered |
| `x-nenya-queue-ms` | How long the request waited for a free slot, in milliseconds |
| `x-nenya-ignored` | Request fields that were not passed on |
| `x-request-id` | The request’s id. Quote it when you report a problem or ask for a deletion ([Getting help](https://contrastivelabs.com/docs#getting-help)). |
| `retry-after` | With a `429`, a `502` or a `503`: how many seconds to wait |

## Limits

If the API is overloaded, capacity is shared between callers, so you may have to wait a little. We add more capacity as soon as that happens.

## Errors

Errors use OpenAI’s JSON shape (`{"error": {"message", "type", "param", "code"}}`), so SDKs raise their usual exceptions.

Sending an image, for example, gets a `400`:

400 Bad Request:

```json
{
  "error": {
    "message": "`messages[0]` has a content part of type `image_url`. Nenya reads text only: send the content as a string or as `text` parts.",
    "type": "invalid_request_error",
    "param": "messages",
    "code": null
  }
}
```

| Status | `code` | What happened | What to do |
| --- | --- | --- | --- |
| `400` | none | The request is malformed. `message` says what is wrong, and `param` names the field when there is one. | Fix the request |
| `400` | `batch_too_large` | One request asks for more replies than a request may have | Send smaller batches |
| `400` | `context_length_exceeded` | The prompt does not fit the context | Shorten it, or split the document |
| `400` | `unsupported_schema` | The JSON schema uses a keyword the server cannot enforce. `message` names it. | Take the keyword out ([What a schema may use](https://contrastivelabs.com/docs#what-a-schema-may-use)) |
| `404` | `model_not_found` | The request names a checkpoint that is retired | Send `nenya` ([Names](https://contrastivelabs.com/docs#names)) |
| `404` | `not_found` | There is no such endpoint | Use one of the four |
| `413` | `request_too_large` | The body is over 1 MB | It could not fit the context anyway |
| `429` | `server_busy` | The request waited 45 seconds for a free slot | Retry after the `Retry-After` seconds |
| `429` | `queue_full` | Too many of your requests are already waiting | Send fewer at once |
| `502` | `upstream_unavailable` | The model is restarting | Retry in a moment |
| `503` | `model_loading` | The model is starting up | Retry after the `Retry-After` seconds |
| `504` | `upstream_unavailable` | The request ran for 2 hours | Ask for less, or stream |

**A prompt that does not fit** gets the code OpenAI uses for it:

400 Bad Request:

```json
{
  "error": {
    "message": "This model's maximum context length is 16384 tokens. However, your prompt contains at least 16385 input tokens, which exceeds this limit even without any output tokens. Please reduce the length of the input prompt. (parameter=input_tokens, value=16385)",
    "type": "invalid_request_error",
    "param": "input_tokens",
    "code": "context_length_exceeded"
  }
}
```

Catch it by its code:

```python
import openai

try:
    reply = client.chat.completions.create(model="nenya", messages=messages)
except openai.BadRequestError as error:
    if error.code == "context_length_exceeded":
        ...                                 # too long: split the document and try again
    else:
        raise
```

The message does not say how long your prompt is, only that it is over the limit (“at least 16385”). To know before you send, see [Counting tokens](https://contrastivelabs.com/docs#counting-tokens).

**The other `400`s** have the same shape, with `code: null` and the field at fault in `param` where there is one: `max_tokens` above 16,384 (`param: "max_tokens"`), a conversation that ends with an assistant message (`param: "messages"`), a `temperature` out of range (`param: "temperature"`), `n` above 1 at temperature 0, an unknown role.

**A checkpoint that is retired** gets a `404`:

404 Not Found:

```json
{
  "error": {
    "message": "The checkpoint `nenya-sft-50171` is no longer served. Send `nenya` for the newest release (today `nenya-1`).",
    "type": "invalid_request_error",
    "param": "model",
    "code": "model_not_found"
  }
}
```

With the OpenAI SDK that is an `openai.NotFoundError`.

Before 2 December 2026 the errors that come from the engine had `type: "BadRequestError"` and the number 400 as their `code`. If you caught the long prompt by `error.param == "input_tokens"`, that still works.

A stream that breaks off part-way ends with a `data: {"error": …}` event. To report a problem, see [Getting help](https://contrastivelabs.com/docs#getting-help).

## Counting tokens

- **After the fact**: every reply carries `usage` with the prompt and reply counts.
- **Before you send**: the model’s tokenizer gives the same count for plain text as `cl100k_base` in [tiktoken](https://github.com/openai/tiktoken). We compared the two on prose, code, JSON and non-English text and they agreed exactly.

```python
import tiktoken
tokens = len(tiktoken.get_encoding("cl100k_base").encode(document))
```

Add the fixed part of a chat request: 48 tokens without tools, about 95 with tools plus the JSON of the tools.

- **Exactly, for a whole request**: send it with `"max_tokens": 1` and read `usage.prompt_tokens`.
- **A rule of thumb**: 4 characters to a token for English prose, under 3 for JSON.

## OpenAI compatibility

| Feature | Status |
| --- | --- |
| Chat completions | Supported |
| Tool calling, several calls in one reply included | Supported |
| Streaming | Supported |
| JSON mode and JSON schema | Supported, with the keyword list under [JSON output](https://contrastivelabs.com/docs#json-output) |
| Logprobs | Supported |
| Text completions | Supported |
| Images, audio and files | Not supported: text only |
| Embeddings | Not served |
| Responses API | Not served |
| `functions` and `function_call` | Retired: use `tools` |
| API keys | Not needed: any value is accepted |

## Running benchmarks

Any harness that takes an OpenAI base URL works. Send the requests in parallel: the server queues what it cannot run yet.

**Berkeley Function-Calling Leaderboard (BFCL v4).** BFCL only runs models it knows, so `run_bfcl.py` registers the API with BFCL’s own OpenAI handler and runs the official generate and evaluate steps:

```bash
pip install "bfcl-eval==2026.3.23"
curl -O https://contrastivelabs.com/run_bfcl.py
export BFCL_PROJECT_ROOT=$PWD/bfcl_run
python run_bfcl.py --base-url https://api.contrastivelabs.dev/v1 --model nenya --categories single_turn --threads 16
```

The 13 single-turn categories are 3,641 requests and take a few minutes. For numbers that belong to one checkpoint, pass its id (`--model nenya-1`) instead of `nenya`: once that checkpoint is retired every request gets a `404`, so a run cannot score another checkpoint by mistake.

## What to expect from the model

Nenya 1 is a small model trained for three jobs. It is good at them, and it is not a general assistant.

|   |   |
| --- | --- |
| Tool calling | 75.4 on the 13 single-turn categories of BFCL v4 |
| Extraction | 91.0 field F1 on 1,512 held-out documents of the kinds it was trained on; 83.5 on 500 real documents of kinds it never saw, asked as on this page |
| Classification | 80.3% across 14 public datasets; 81% to 83% on four tasks it never saw, asked as on this page |
| Chains of calls | weak: 13.9 on BFCL’s multi-turn categories |
| Knowledge, maths, code, writing | what a small model gives |

The Models page shows 70.8 and 75.0 for the same 500 documents and four tasks. There all 15 models get the same prompt, with no tuning for Nenya 1: [how we measured](https://contrastivelabs.com/methodology).

- It reads and writes text only, in English.
- It answers directly. There is no thinking mode.
- It does not know today’s date, or anything after its training data.
- It does not work out dates (“tomorrow”, “next Thursday”).
- It can be wrong and sound sure. Check the output before you rely on it.

[The benchmarks, beside other open models](https://contrastivelabs.com/#benchmarks)

## Our tests

The numbers on this page that say “in our tests” were measured on this API on 1 December 2026, with the checkpoint `nenya-1`, about 65,000 requests in 150 settings. Every setting saw the same items with the same options, so the comparisons are like for like.

|  | Data | Scored by |
| --- | --- | --- |
| Classification | 1,000 items from four tasks with no training data: vehicle complaints by component, voice commands by intent, 2026 arXiv papers by subject area, 2026 Stack Exchange questions by site. For the number of labels also CLINC150. | The label, exactly |
| Extraction | 500 documents from 2026 US public records: NTSB accident reports, FDA warning letters, NHTSA complaints, openFDA recall notices. 2,321 fields. | Field F1 |
| Tool calling | The 400 questions of BFCL v4’s `simple_python` category, with unrelated tools added to the list; the 240 questions of its `irrelevance` category for “no tool fits”. | BFCL’s own checker |

One standard error is about 1 to 2.5 points on these sizes: read differences smaller than 3 points as no difference. The numbers belong to this checkpoint and will be measured again for the next one.

On 2 December 2026 the server began to decode a JSON request at temperature 0 when the request sets no sampling field. We then sent again, with no `temperature`, the requests that had been sampled the day before:

| Asked with no `temperature` | Sampled, 1 December | Since 2 December | With `temperature: 0` set, 1 December |
| --- | --- | --- | --- |
| Classification, the recipe (a choice list) | not measured | 81.6% | 81.2% |
| Classification, a JSON schema with the labels as an `enum` | 78.3% | 82.5% | 82.7% |
| Extraction, the recipe (field list in the system message, a JSON schema) | 82.2 F1 | 83.5 F1 | 83.4 F1 |
| Extraction, the document then the field list, a JSON schema | 77.6 F1 | 79.6 F1 | 79.6 F1 |
| Classification, JSON asked for in the prompt only (no `response_format`) | 74.8% | 73.8%: still sampled | 80.0% |
| Extraction, the recipe without `response_format` | 81.3 and 81.9 F1 | 81.5 F1: still sampled | 83.5 F1 |

The last two rows are the requests the server cannot recognise: nothing in them holds the reply to a shape. For those, set `temperature: 0` yourself.

Also on 2 December 2026 we measured the second step of a tool loop, what the model does with a function’s result ([After a result](https://contrastivelabs.com/docs#after-a-result)), with about 50,000 requests:

|  | Data | Right is |
| --- | --- | --- |
| How a result is written | 360 cases written for the test, 12 from each of 30 kinds of application. In 192 the result holds the answer to the user’s question. In 168 the next call needs a value out of it. Each case in 12 spellings, each sent twice among the others. | The answer has every fact asked for (a number, a date, a name, a code), or the next call is made with the right values |
| The shop example | The example’s conversation and 12 like it, under 23 wordings of the system message: the step after the order’s result under all of them, the whole conversation with every step generated under 9. And eight neighbouring requests (a partial refund, a refund above the total, an order that does not exist, a question no tool fits). | The conversation ends with one refund of the order’s total, or with what the neighbouring request calls for |
| A look-up that finds nothing | 114 of the 360 cases, the ones whose first call looks one thing up, with the result replaced by “nothing found” in 11 forms, and the next request sent in 5 ways. | The model says that it was not found and makes no call |

The cases are ours and not a public benchmark, so read the numbers as comparisons between ways of doing one thing. Every case, request and reply is in the records of the test.

## Getting help

Write to [arsalan@contrastivelabs.com](mailto:arsalan@contrastivelabs.com). For a problem with a request, quote the `x-request-id` header of the reply, and the `model` field if you have it. For a fine-tuned model, an on-prem deployment, your own evals or support, [book a call](https://calendar.app.google/o2KufcrfAsuyqapR6).

## Terms and privacy

### Terms

Nenya 1 is free to call. There is no sign-up, no key and no quota.

For privacy and the lowest latency, run Nenya 1 on [your own hardware](https://contrastivelabs.com/docs#run-it-locally). The weights are free under Apache 2.0: [Nenya 1 on Hugging Face](https://huggingface.co/contrastivelabs/Nenya-1).

Do not use the API to break the law or to attack people or systems. We may block a caller who does.

We intend to keep Nenya 1 free here. Later models may be commercial.

### Privacy

We keep each request and reply for 30 days, to monitor the API for abuse and to see where the model gets things wrong. We do not train on them. Then they are deleted.

For every request we store a timestamp, number of tokens, time elapsed, address country (according to Cloudflare), client library name and we create an id based on your address to be able to distinguish callers without storing the address. There’s an `x-request-id` header in each response. If you want to delete your request please send [arsalan@contrastivelabs.com](mailto:arsalan@contrastivelabs.com) the id.

In full: the [Terms of Service](https://contrastivelabs.com/terms) and the [Privacy Policy](https://contrastivelabs.com/privacy).

## For coding assistants

This page is also plain Markdown at [/docs.md](https://contrastivelabs.com/docs.md). Give that address to a coding assistant and it has everything here.

---

The replies shown were recorded from the API on 2026-12-02, answered by `nenya-1`.
