API

Checking the API

Nenya API

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

https://api.contrastivelabs.dev/v1
Base URL
nonesend any value: SDKs insist on one
API key
nenyathe newest release: nenya-1 today
Model name
16,384 tokensprompt and reply together
Context
text onlyEnglish. For a PDF or a scan, see PDFs and scans
Input and output

Get started

Quick start#

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

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?"}]
  }'
You should see
The capital of France is Paris.

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

The reply
{
  "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.
  • 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.
  • 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.

Get started

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). These are the rules that came out of it.

  1. 1Decode 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. 2Say 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. 3Use 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. 4Extraction: 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. 5Classification: 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. 6Tools: 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. 7In 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).
  8. 8Describe 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. 9Keep 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. 10Check 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. 11Work 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:

JobAsk like thisSettingsIn our tests
Classify into a fixed listOne user message: the question, the text, Options:, Answer with the label only.temperature: 0; structured_outputs: {"choice": [...]}; logprobs for confidence81% 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 documentSystem message: the field list. User message: the document.temperature: 0; response_format with a JSON schema; max_tokens83.5 field F1 on 500 real documents; 0.6% invented values
Call toolstools, and a system message that says what the assistant is forno temperature; tool_choice: "required" when every request should become a call90% right calls with 8 tools when forced, 76% to 87% with a system message, 64% with neither
Free textanythingthe default samplingnot what this model is for: see What to expect

All the recipes below are in one runnable file, 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.

Terminal
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

Get started

The model#

NameNenya 1
Size2.5 billion parameters, of which 0.5 billion are used for each token (a mixture of experts)
Trained fortool calling, extraction and classification
Context16,384 tokens, prompt and reply together
LanguagesEnglish. It was trained on English text only.
Input and outputtext only
Thinking modenone: it answers directly
Weights and licenceOpen under Apache 2.0: Nenya 1 on Hugging Face. So is the base model it was trained from, Nenya-2.5B-A0.5B-Base.

Names#

NameWhat it is
Nenya 1the model, as it is called in public
nenyathe name to send. It always means the newest release.
nenya-1the exact checkpoint of Nenya 1. Replies carry it in their model field and in the x-nenya-model header.
nenya-sft-50171a 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-Basethe 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#

DateCheckpointWhat changed
2 December 2026nenya-1The 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). 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). A request that names the retired nenya-sft-50171 gets 404.
1 December 2026nenya-1Nenya 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).
29 November 2026nenya-sft-50171The API opened, with a preview checkpoint.

Get started

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.

Terminal
# 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.

Then send the same requests to your own address:

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?"}]
  }'

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); 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). 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 (context_length_exceeded, unsupported_schema).
  • The reply headers listed under Reply headers are the public API’s own. Your server does not send them.

Guides

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
<|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
<|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:

JobWhat a system message does
Tool callingA 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.
ExtractionIt is the best place for the field list: 83.5 F1 there, against 79.4 with everything in the user message. See Extraction.
ClassificationKeep 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). Do not rely on what it says about itself either: asked who made it, it may name another company.

Guides

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.

JobWhere it goesTemplate
Classify, one labelone user message{question} {Heading}: {text} Options: - {label} - {label} Answer with the label only.
… when nothing may fitadded to the last lineAnswer with the label only. If none of the options fits, answer "none".
… with the labels explainedthe option lines- {label}: {what it covers}
… with long optionsthe option lines and the last lineA) {option} B) {option} Answer with the letter of the correct option only.
Classify, several labelsthe last lineAnswer with a JSON object: {"labels": [...]}. Use an empty list if none apply.
Classify, as JSONthe last lineAnswer with a JSON object: {"label": ...}.
Extract (best)system messageYou extract structured data from {kind}s. For each document the user sends, give these fields. Fields: - {name} ({type}): {description} 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 messageone user messageExtract these fields from the {kind} below. {document} Fields: - {name} ({type}): {description} Answer with one JSON object with exactly these keys. Use null for a field the text does not give.
Extract, as a tool callone user message, one toolPlease 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. {document} 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 callingsystem and user messagesno 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).

Guides

Classification#

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

The recipe#

# 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"]}
  }'
What it prints
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 list78.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 enum82.7%
The same without the schema80.0%
A tool call with the labels as the enum of a parameter70.5%
The question and the options in the system message, the text as the user message60.9%
Four worked examples as earlier turns, then the recipe73.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 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
        }
      }
    }
  }'
The content of the reply
{"label": "Billing"}

How sure it is#

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

ConfidenceShare of the answersRight
0.99 and over28%97%
0.90 to 0.9936%89%
0.70 to 0.9020%73%
0.50 to 0.7012%52%
under 0.506%36%
Act only when the confidence is at leastAnswers you keepRight among them
0.7083%88%
0.8075%90%
0.9063%93%
0.9551%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 offeredVoice commands (60 intents), unseenVehicle complaints (31 components), unseenCLINC150 (150 intents), trained on it
590.8%88.8%99.6%
1086.0%82.8%97.9%
2080.4%68.8%94.5%
4070.4%91.6%
60 to 8062.8%62.0% (all 31)87.4%
15075.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: rightRight label offered: wrongly said “none”Right label not offered: said “none”
Four tasks it never saw77.9%3.9%39%
CLINC150, which it was trained on93.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:

Prompt
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):

Prompt
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?”):

Prompt
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"]}):

Prompt
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.

Guides

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 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
        }
      }
    }
  }'

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

What it prints
{
  "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 F1Whole record rightInvented valuesFields filled that the document does not give
The recipe above: field list in the system message, document as the user message83.539.8%0.6%4.8%
One user message: the field list, then the document80.233.0%0.6%2.7%
One user message: the document, then the field list (the layout it was trained on)79.429.6%0.9%9.5%
A tool call whose parameters are the fields67.6 to 72.69% to 17%1.5% to 10%19% to 57%
A tool call with every field marked required72.87.0%9.2%75%
The recipe above, fields without descriptions67.020.4%0.7%10.5%
response_format alone: no field list in the prompt44.73.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): 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 tokensField list in the system messageField list after the document
under 50084.981.8
500 to 1,00084.585.0
1,000 to 2,00081.071.8
2,000 to 4,000 (14 documents)69.054.9

Past about 2,000 tokens, split the document. See 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. 1Split it into parts of 1,000 to 1,500 tokens, at paragraph or section breaks, with a few sentences of overlap.
  2. 2Run the same extraction on every part. Fields the part does not have come back null.
  3. 3Merge: 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.

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. 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.

Terminal
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.

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.

Sample prompts#

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

System message
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
{
  "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:

System message
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
{
  "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:

Prompt
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.

Guides

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. 1Send the conversation and the tools.
  2. 2If the reply has tool_calls, run each one in your own code. The model never runs anything.
  3. 3Append the model’s message as it came, then one tool message for each call, with the call’s id.
  4. 4Send the conversation again. Repeat until the reply has no calls. Put a limit on the number of turns.
  5. 5When 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).

A support agent with three tools:

# 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"
  }'
What it prints
-> 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.

Three things in this example come out of our tests (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
{
  "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
{
  "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
[
  {"name": "get_weather", "arguments": {"city": "Paris"}},
  {"name": "get_weather", "arguments": {"city": "Tokyo"}}
]

Choosing whether it calls#

tool_choiceWhat 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 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 offeredRight callAnswered in words insteadRight call with tool_choice: "required"
189.5%3.8%92.2%
287.0%6.2%92.0%
473.2%20.2%91.5%
863.8%28.8%90.2%
1679.2%8.8%87.0%
3283.2%2.5%84.8%
6478.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 offeredA tool fits: right callNo tool fits: makes no call
Nothing set63.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 rules86.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 tool90.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:
System message
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:

{
  "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"]
    }
  }
}
The call each command becomes
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). 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 writtenRight
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 JavaScript98.2% and 98.8%
as a printed Python dict: str(result) (single quotes, True, None)98.6%
as one sentence98.2%
as Python writes it, with the keys in the opposite order98.2%
as Python writes it, sent a second time98.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 withOld ruleRule as printed now
one refund of the order’s total79%100%
words and no call, most often “I’ll process a refund for the damaged item”6%0
a refund of 06%0
“I can’t find order 48213 in our system”, after the order had come back5%0
a question back to the customer4%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): 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 withThe model says soIt makes the call again
{"error": "no such order"}3%96%
{"status": 404, "message": "Order not found"}3%96%
{"found": false}33%62%
null39%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: 0100%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 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 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
'<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 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). 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). 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).
  • 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".

Guides

JSON output#

response_format holds the reply to JSON:

response_formatThe 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) ends such a reply early, with finish_reason: "repetition".

What a schema may use#

Works
Typesstring, integer, number, boolean, null, lists of types such as ["string", "null"]
Structurenested objects, arrays, arrays of objects, $defs and $ref, anyOf, oneOf
Objectsproperties, 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
Valuesenum, const
Numbersminimum, maximum, exclusiveMinimum
StringsminLength, maxLength, pattern, and format: date, time, date-time, duration, email, hostname, ipv4, ipv6, uuid, uri
ArraysminItems, 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
{
  "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 enums and limits (Choosing whether it calls).

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:

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

Guides

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 -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
  }'
You should see, a few words at a time
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.

Guides

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 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
  }'
You should see
 Paris, and the capital of the United

Reference

Endpoints#

EndpointWhat it does
POST /v1/chat/completionsChat, with tools, JSON output and streaming
POST /v1/completionsRaw text completion, with logprobs and echo
GET /v1/modelsThe model names
GET /health200 when the model is ready, 503 while it starts

Nothing else is served.

Reference

Request parameters#

modelstringrequired
Send nenya. The id of a retired checkpoint gets 404; any other name is answered by the checkpoint that is served (Names).
messagesarrayrequired
Roles: system, developer, user, assistant, tool. Content is a string or a list of text parts.
toolsarraydefault: none
See Tool calling.
tool_choicestring or objectdefault: "auto"
"auto", "required", "none", or one named function.
parallel_tool_callsbooleandefault: true
false keeps a reply to one call.
response_formatobjectdefault: none
See JSON output.
temperaturenumberdefault: 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_tokensintegerdefault: 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.
stopstring or arraydefault: none
Text that ends the reply.
seedintegerdefault: none
Makes sampling repeatable.
logprobs, top_logprobsboolean, integerdefault: off
The probability of each token of the reply and of its nearest alternatives. See How sure it is.
stream, stream_optionsboolean, objectdefault: false
See Streaming.
nintegerdefault: 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.

ParameterWhat 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_texttrue adds prompt_text to the reply: the prompt as the model read it.
top_k, min_p, repetition_penaltymore sampling controls
min_tokens, stop_token_ids, ignore_eoscontrols over where a reply ends
prompt_logprobs, echoprobabilities of the prompt’s own tokens (echo on /v1/completions)
continue_final_message, add_generation_promptcontinue 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#

RequestDecoding
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 endpointtemperature 0
Every other requesttemperature 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). 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) 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).

Reference

finish_reason#

ValueMeaningWhat to do
stopThe model ended its reply, or one of your stop strings came up.Use the reply.
lengthThe 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_callsThe reply holds tool calls.Run them. With a function forced by name the value is stop: look at message.tool_calls.
repetitionOnly 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.

Reference

Reply headers#

HeaderWhat it tells you
x-nenya-modelThe exact checkpoint that answered
x-nenya-queue-msHow long the request waited for a free slot, in milliseconds
x-nenya-ignoredRequest fields that were not passed on
x-request-idThe request’s id. Quote it when you report a problem or ask for a deletion (Getting help).
retry-afterWith a 429, a 502 or a 503: how many seconds to wait

Reference

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.

Reference

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
{
  "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
  }
}
StatuscodeWhat happenedWhat to do
400noneThe request is malformed. message says what is wrong, and param names the field when there is one.Fix the request
400batch_too_largeOne request asks for more replies than a request may haveSend smaller batches
400context_length_exceededThe prompt does not fit the contextShorten it, or split the document
400unsupported_schemaThe JSON schema uses a keyword the server cannot enforce. message names it.Take the keyword out (What a schema may use)
404model_not_foundThe request names a checkpoint that is retiredSend nenya (Names)
404not_foundThere is no such endpointUse one of the four
413request_too_largeThe body is over 1 MBIt could not fit the context anyway
429server_busyThe request waited 45 seconds for a free slotRetry after the Retry-After seconds
429queue_fullToo many of your requests are already waitingSend fewer at once
502upstream_unavailableThe model is restartingRetry in a moment
503model_loadingThe model is starting upRetry after the Retry-After seconds
504upstream_unavailableThe request ran for 2 hoursAsk for less, or stream

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

400 Bad Request
{
  "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.

The other 400s 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
{
  "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.

Reference

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. 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.

Reference

OpenAI compatibility#

FeatureStatus
Chat completionsSupported
Tool calling, several calls in one reply includedSupported
StreamingSupported
JSON mode and JSON schemaSupported, with the keyword list under JSON output
LogprobsSupported
Text completionsSupported
Images, audio and filesNot supported: text only
EmbeddingsNot served
Responses APINot served
functions and function_callRetired: use tools
API keysNot needed: any value is accepted

More

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:

Terminal
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.

More

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 calling75.4 on the 13 single-turn categories of BFCL v4
Extraction91.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
Classification80.3% across 14 public datasets; 81% to 83% on four tasks it never saw, asked as on this page
Chains of callsweak: 13.9 on BFCL’s multi-turn categories
Knowledge, maths, code, writingwhat 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.

  • 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

More

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.

DataScored by
Classification1,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
Extraction500 documents from 2026 US public records: NTSB accident reports, FDA warning letters, NHTSA complaints, openFDA recall notices. 2,321 fields.Field F1
Tool callingThe 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 temperatureSampled, 1 DecemberSince 2 DecemberWith temperature: 0 set, 1 December
Classification, the recipe (a choice list)not measured81.6%81.2%
Classification, a JSON schema with the labels as an enum78.3%82.5%82.7%
Extraction, the recipe (field list in the system message, a JSON schema)82.2 F183.5 F183.4 F1
Extraction, the document then the field list, a JSON schema77.6 F179.6 F179.6 F1
Classification, JSON asked for in the prompt only (no response_format)74.8%73.8%: still sampled80.0%
Extraction, the recipe without response_format81.3 and 81.9 F181.5 F1: still sampled83.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), with about 50,000 requests:

DataRight is
How a result is written360 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 exampleThe 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 nothing114 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.

More

Getting help#

Write to 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.

More

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. The weights are free under Apache 2.0: Nenya 1 on Hugging Face.

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 the id.

In full: the Terms of Service and the Privacy Policy.

More

For coding assistants#

This page is also plain Markdown at /docs.md. Give that address to a coding assistant and it has everything here.

Every request on this page was sent to the API on 2 December 2026, and the replies shown are the ones that came back, from nenya-1.

Loading…

Need fine-tuning, on-prem deployment, your own evals or support?

Nenya 1 is free to call here and free to download. Book a call for a fine-tuned model or an on-prem deployment.