# Reasoning and prompt caching

> Control how much a model thinks with one reasoning field across providers, keep its thinking intact in tool loops, and cut the cost of repeated prompts with prompt caching.

Thinking models and prompt caching work differently at every provider. Lykia gives you one way to ask for each and translates it to the provider that serves the request.

## Ask a model to think

Send `reasoning` in the [`POST /chat/completions`](https://www.getlykia.com/en/docs/api-reference/chat-completions) body:

**cURL**

```bash
curl -i https://api.getlykia.com/v1/chat/completions \
  -H "Authorization: Bearer $LYKIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "anthropic/claude-sonnet-4.5",
    "messages": [
      { "role": "user", "content": "A train leaves at 09:40 and arrives at 13:05. How long is the trip?" }
    ],
    "reasoning": { "effort": "medium" },
    "max_tokens": 4000
  }'
```

**Python**

```python
import os

from openai import OpenAI

client = OpenAI(base_url="https://api.getlykia.com/v1", api_key=os.environ["LYKIA_API_KEY"])

completion = client.chat.completions.create(
    model="anthropic/claude-sonnet-4.5",
    messages=[{"role": "user", "content": "A train leaves at 09:40 and arrives at 13:05. How long is the trip?"}],
    max_tokens=4000,
    extra_body={"reasoning": {"effort": "medium"}},
)
message = completion.choices[0].message
# Lykia's extra fields are kept on the SDK object; the readable thinking text may be absent.
print(getattr(message, "reasoning", None))
print(message.content)
print("reasoning tokens:", completion.usage.completion_tokens_details.reasoning_tokens)
```

**TypeScript**

```typescript
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://api.getlykia.com/v1", apiKey: process.env.LYKIA_API_KEY });

// Lykia-specific fields are not in the SDK's types, so the request object is widened.
const request = {
  model: "anthropic/claude-sonnet-4.5",
  messages: [{ role: "user" as const, content: "A train leaves at 09:40 and arrives at 13:05. How long is the trip?" }],
  max_tokens: 4000,
  reasoning: { effort: "medium" },
};

const completion = await client.chat.completions.create(request as OpenAI.Chat.ChatCompletionCreateParamsNonStreaming);
const message = completion.choices[0].message as OpenAI.Chat.ChatCompletionMessage & { reasoning?: string };
console.log(message.reasoning ?? "(no thinking text returned)");
console.log(message.content);
console.log("reasoning tokens:", completion.usage?.completion_tokens_details?.reasoning_tokens);
```

- `reasoning.effort` (string) — `low`, `medium` or `high`.
- `reasoning.max_tokens` (integer) — A thinking budget in tokens, for providers that take one.
- `reasoning.enabled` (boolean) — `false` turns thinking off where the model allows it.
- `reasoning.exclude` (boolean) — `true` keeps the thinking text out of the response; the model still thinks and the tokens are still billed.

How it is translated:

| Provider family   | What Lykia sends                                                                                                                                                                                                                                     |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Anthropic         | Newer models: adaptive thinking with the effort level (a budget is turned into an effort). Older models: a thinking budget (effort becomes a budget), kept below `max_tokens`; when it would fall under Anthropic's minimum, thinking is turned off. |
| Google AI Studio  | The model's thinking setting (a budget or a level); `enabled: false` sets the budget to zero.                                                                                                                                                        |
| OpenAI-compatible | `reasoning_effort`. A `max_tokens` budget has no equivalent there and is ignored. DeepSeek gets its own on/off thinking switch.                                                                                                                      |

Thinking tokens are counted in `usage.completion_tokens_details.reasoning_tokens` and billed as output (at the model's reasoning price when it has one). A [preset](https://www.getlykia.com/en/docs/guides/model-presets) can carry a `reasoning` default, so products that call `@reasoning` think without sending the field.

## What comes back

```json
{
  "id": "gen-1795457073-aj6XedNrHjt3Rxe6",
  "object": "chat.completion",
  "created": 1795457073,
  "model": "anthropic/claude-sonnet-4.5",
  "provider": "anthropic",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Order 1042 shipped yesterday; it should arrive on Thursday.",
        "reasoning": "The user asks where the order is. The tool result says it shipped on Monday with a three-day estimate.",
        "reasoning_details": [
          {
            "type": "reasoning.text",
            "text": "The user asks where the order is. The tool result says it shipped on Monday with a three-day estimate.",
            "signature": "EqQBCkYIBxgCKkA…",
            "format": "anthropic",
            "index": 0
          }
        ]
      },
      "finish_reason": "stop",
      "logprobs": null
    }
  ],
  "usage": {
    "prompt_tokens": 1840,
    "completion_tokens": 212,
    "total_tokens": 2052,
    "cost": 0.0087,
    "is_byok": false,
    "cost_details": {
      "upstream_cost": 0.0087,
      "platform_fee": 0,
      "is_byok": false
    },
    "prompt_tokens_details": {
      "cached_tokens": 1536,
      "cache_write_tokens": 0
    },
    "completion_tokens_details": {
      "reasoning_tokens": 148
    }
  }
}
```

- `message.reasoning` (string) — The model's thinking as readable text, when the provider returns it. It can be missing or summarised; OpenAI's Chat Completions API does not return thinking text at all.
- `message.reasoning_details` (array) — The thinking blocks themselves. Each item has `type` (`reasoning.text` or `reasoning.encrypted`), `format` (which provider produced it, such as `anthropic` or `google-ai-studio`), `index` and, depending on the type, `text`, `signature`, `data` or `id`. Treat the content as opaque.

In a stream, the same arrive piece by piece as `delta.reasoning` and `delta.reasoning_details`.

## Keep thinking intact in tool loops

When a thinking model calls tools, its next turn needs the thinking it did before the call. Some providers check this with a signature. The rule is simple:

> **Warning:** In a tool loop, send the assistant message back **unchanged**, `reasoning_details` included. Do not rebuild it from `content` and `tool_calls`, and do not edit, reorder or drop the blocks.

**Python**

```python
import json
import os

from openai import OpenAI

client = OpenAI(base_url="https://api.getlykia.com/v1", api_key=os.environ["LYKIA_API_KEY"])

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_order_status",
            "description": "Shipping status of an order",
            "parameters": {"type": "object", "properties": {"order_id": {"type": "string"}}, "required": ["order_id"]},
        },
    }
]
messages = [{"role": "user", "content": "Where is order 1042?"}]

while True:
    completion = client.chat.completions.create(
        model="anthropic/claude-sonnet-4.5",
        messages=messages,
        tools=tools,
        max_tokens=4000,
        extra_body={"reasoning": {"effort": "low"}},
    )
    message = completion.choices[0].message
    if not message.tool_calls:
        print(message.content)
        break

    # Send the assistant turn back unchanged: model_dump keeps reasoning_details, which the provider
    # needs to continue its signed thinking in the next turn.
    messages.append(message.model_dump(exclude_none=True))
    for call in message.tool_calls:
        args = json.loads(call.function.arguments)
        result = {"order_id": args["order_id"], "status": "shipped", "eta": "Thursday"}
        messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})
```

**TypeScript**

```typescript
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://api.getlykia.com/v1", apiKey: process.env.LYKIA_API_KEY });

const tools: OpenAI.Chat.ChatCompletionTool[] = [
  {
    type: "function",
    function: {
      name: "get_order_status",
      description: "Shipping status of an order",
      parameters: { type: "object", properties: { order_id: { type: "string" } }, required: ["order_id"] },
    },
  },
];
const messages: OpenAI.Chat.ChatCompletionMessageParam[] = [{ role: "user", content: "Where is order 1042?" }];

for (;;) {
  const request = { model: "anthropic/claude-sonnet-4.5", messages, tools, max_tokens: 4000, reasoning: { effort: "low" } };
  const completion = await client.chat.completions.create(request as OpenAI.Chat.ChatCompletionCreateParamsNonStreaming);
  const message = completion.choices[0].message;
  if (!message.tool_calls?.length) {
    console.log(message.content);
    break;
  }

  // Push the assistant message object as it came back: it carries reasoning_details, which the provider
  // needs to continue its signed thinking. Do not rebuild it from content and tool_calls alone.
  messages.push(message);
  for (const call of message.tool_calls) {
    if (call.type !== "function") continue;
    const args = JSON.parse(call.function.arguments);
    messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify({ order_id: args.order_id, status: "shipped", eta: "Thursday" }) });
  }
}
```

Lykia turns the blocks back into the provider's own format (Anthropic's signed thinking blocks, Google's thought signatures, DeepSeek's reasoning content). Blocks belong to the provider that produced them: if the next turn goes to a different provider, for example after a fallback, Lykia drops them silently, because no other provider can read them.

### `X-Lykia-Reasoning: dropped`

Some models refuse a tool-loop request with thinking on when the previous assistant turn arrives without its thinking blocks (older Anthropic models with a thinking budget do). Rather than fail the request, Lykia sends that one request without thinking and adds the response header `X-Lykia-Reasoning: dropped`. If you see it, your code is losing `reasoning_details` somewhere between turns; send the assistant message back unchanged and thinking stays on.

## Prompt caching

When requests repeat a long prefix (a system prompt, a policy, tool definitions, a document), providers can cache it and bill the repeated part at a lower price. Most providers do this on their own; Anthropic needs to be told where the cacheable part ends.

### `cache: "auto"`

The simplest way is to let Lykia handle it:

```bash
# cache: "auto" lets Lykia place the prompt-cache breakpoint for providers that need one (Anthropic).
curl https://api.getlykia.com/v1/chat/completions \
  -H "Authorization: Bearer $LYKIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "anthropic/claude-sonnet-4.5",
    "cache": "auto",
    "messages": [
      { "role": "system", "content": "You are the support assistant for Acme. Follow the policy below. (… a long, unchanging policy text …)" },
      { "role": "user", "content": "Can I get a refund after 20 days?" }
    ]
  }'
```

With `cache: "auto"` and no markers of your own in the request, Lykia asks Anthropic for its automatic caching, which places the breakpoint at the end of the cacheable prefix (tool definitions, system prompt and earlier turns). Very short prompts are not cached, without an error. Other providers cache implicitly, so nothing is sent to them. The default is `off`; a preset can set `cache: "auto"` for every request that uses it.

### `cache_control` markers

For full control, put `cache_control` markers where you want breakpoints: on the system message or its parts, on content parts, on tool definitions and on tool results.

```bash
# An explicit breakpoint: everything up to and including this part is cached for an hour.
curl https://api.getlykia.com/v1/chat/completions \
  -H "Authorization: Bearer $LYKIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "anthropic/claude-sonnet-4.5",
    "messages": [
      {
        "role": "system",
        "content": [
          {
            "type": "text",
            "text": "You are the support assistant for Acme. Follow the policy below. (… a long, unchanging policy text …)",
            "cache_control": { "type": "ephemeral", "ttl": "1h" }
          }
        ]
      },
      { "role": "user", "content": "Can I get a refund after 20 days?" }
    ]
  }'
```

`ttl` is `5m` (default) or `1h`. Markers reach Anthropic as they are, and they always win over `cache: "auto"`. Providers that do not use markers ignore them; that is not an error. For OpenAI, you can also pass `prompt_cache_key` to group requests that share a prefix.

### What caching costs

The response reports cached input in `usage.prompt_tokens_details`: `cached_tokens` (read from the cache) and `cache_write_tokens` (written to it). Reads are billed at the model's `input_cache_read` price and writes at `input_cache_write`; a one-hour write costs more than a five-minute one (1.6 times the five-minute write price when the catalog has no separate price for it). When a model has no cache price, cached tokens are billed at the normal input price. See [Credits and billing](https://www.getlykia.com/en/docs/guides/credits-and-billing#what-a-request-costs).

## Next steps

- [Tool calling](https://www.getlykia.com/en/docs/guides/tool-calling): the tool loop itself.
- [Compatibility](https://www.getlykia.com/en/docs/guides/compatibility): which provider family supports what.
- [Model presets](https://www.getlykia.com/en/docs/guides/model-presets): set `reasoning` and `cache` once for a product.
