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

# Reasoning Tokens

For models that support it, the OpenRouter API can return **Reasoning Tokens**, also known as thinking tokens. OpenRouter normalizes the different ways of customizing the amount of reasoning tokens that the model will use, providing a unified interface across different providers.

Reasoning tokens provide a transparent look into the reasoning steps taken by a model. Reasoning tokens are considered output tokens and charged accordingly. On most providers they also count against the request's `max_output_tokens`; see [Reasoning tokens and max\_output\_tokens](#reasoning-tokens-and-max_tokens).

Reasoning tokens are included in the response by default if the model decides to output them. The examples on this page use the [Responses API](https://openrouter.ai/docs/api_reference/responses/overview.md), where reasoning tokens appear as `reasoning` items in the response `output` array. On Chat Completions they appear in the `reasoning` field of each message, and `reasoning.exclude` can omit them.

> [!NOTE]
>
> **Some reasoning models do not return their reasoning tokens**
>
> While most models and providers make reasoning tokens available in the response, some (like the OpenAI o-series) do not.

## Controlling Reasoning Tokens

You can control reasoning tokens in your requests using the `reasoning` parameter. `effort`, `max_tokens`, and `enabled` work the same way on the Responses and Chat Completions APIs; `exclude` is a Chat Completions-only option (see [Excluding Reasoning Tokens](#excluding-reasoning-tokens-chat-completions-only)):

```json lines theme={null}
{
  "model": "your-model",
  "input": "...",
  "reasoning": {
    // One of the following (not both):
    "effort": "high", // Can be "max", "xhigh", "high", "medium", "low", "minimal" or "none" (OpenAI-style)
    "max_tokens": 2000, // Specific token limit (Anthropic-style)

    // Or enable reasoning with the default parameters:
    "enabled": true // Default: inferred from `effort` or `max_tokens`
  }
}
```

The `reasoning` config object consolidates settings for controlling reasoning strength across different models. See the Note for each option below to see which models are supported and how other models will behave.

### Reasoning tokens and max\_output\_tokens

> [!WARNING]
>
> **Reasoning tokens count against `max_output_tokens`**
>
> On most providers, the request's `max_output_tokens` limit applies to reasoning and visible output combined. If the limit is small enough that the model spends all of it reasoning, the response returns `status: "incomplete"` with `incomplete_details.reason: "max_output_tokens"` and no `message` item in `output`, and the reasoning tokens are still billed.

To detect this case, subtract `usage.output_tokens_details.reasoning_tokens` from `usage.output_tokens`. The difference is the number of visible output tokens, and it is 0 or near 0 when reasoning consumed the budget.

To avoid it, set `max_output_tokens` well above the expected reasoning length, or cap reasoning with `reasoning.max_tokens` or a lower `reasoning.effort`. For Anthropic models, `max_output_tokens` must be strictly higher than the reasoning budget; see [Anthropic Models with Reasoning Tokens](#anthropic-models-with-reasoning-tokens).

On Chat Completions (`/api/v1/chat/completions`), the same budget is `max_tokens` (or `max_completion_tokens`, which shares the same budget). If the model spends all of it reasoning, the response returns `finish_reason: "length"` with an empty `content`, and the reasoning tokens are still billed. With `reasoning.exclude: true` the `reasoning` field is omitted as well, so the response carries no text at all and the only signal left is `finish_reason` plus `usage`. To detect this case, subtract `usage.completion_tokens_details.reasoning_tokens` from `usage.completion_tokens`. For example, a request with `max_tokens: 300` that returns `completion_tokens: 302` and `reasoning_tokens: 301` produced a single visible token.

### Discovering per-model reasoning options

Each model in [`GET /api/v1/models`](https://openrouter.ai/docs/api/api-reference/models/list-all-models-and-their-properties) may include a `reasoning` object describing which effort levels it accepts and whether reasoning is mandatory:

```json lines theme={null}
{
  "id": "google/gemini-3.5-flash",
  "reasoning": {
    "supported_efforts": ["high", "medium", "low", "minimal"],
    "default_effort": "medium",
    "default_enabled": true,
    "mandatory": true
  }
}
```

Use this when building client UIs:

* **`supported_efforts`**: Filter effort selectors to these values, returned in descending effort order (highest first). When `null`, all gateway effort values are accepted. When omitted, the model does not expose effort selection.
* **`default_effort`**: Pre-select this effort when enabling reasoning. Maps to `reasoning.effort` in chat requests. If the value is `"none"`, treat it as "reasoning off by default" rather than pre-selecting disable when the user explicitly turns reasoning on.
* **`default_enabled`**: Default on/off state when the user has not set `reasoning.enabled`.
* **`supports_max_tokens`**: When present and `true`, show a token budget control and send `reasoning.max_tokens` instead of (or alongside) `reasoning.effort`. Omitted when the model does not support token-budget reasoning.
* **`mandatory`**: When `true`, hide disable controls and do not send `effort: "none"` — the model rejects it.

Non-reasoning models and dynamic router models (`openrouter/auto`, `openrouter/free`) omit the `reasoning` field.

### Max Tokens for Reasoning

> [!NOTE]
>
> **Supported models**
>
> Currently supported by:
>
> <ul>
>   <li>Gemini thinking models</li>
>
>   <li>
>     Anthropic reasoning models (by using the `reasoning.max_tokens`  parameter)
>   </li>
>
>   <li>Some Alibaba Qwen thinking models (mapped to `thinking_budget`)</li>
> </ul>
>
> For Alibaba, support varies by model — please check the individual model descriptions to confirm whether `reasoning.max_tokens` (via `thinking_budget`) is available.

For models that support reasoning token allocation, you can control it like this:

* `"max_tokens": 2000` - Directly specifies the maximum number of tokens to use for reasoning

For models that only support `reasoning.effort` (see below), the `reasoning.max_tokens` value will be used to determine the effort level.

### Reasoning Effort Level

> [!NOTE]
>
> **Supported models**
>
> Currently supported by OpenAI reasoning models (o1 series, o3 series, GPT-5 series) and Grok models

The percentages below are of the request's output token limit (`max_output_tokens`, or `max_tokens` on Chat Completions):

* `"effort": "max"` - Allocates the largest portion of tokens for reasoning (approximately 95% of the limit)
* `"effort": "xhigh"` - Same allocation as max (approximately 95% of the limit)
* `"effort": "high"` - Allocates a large portion of tokens for reasoning (approximately 80% of the limit)
* `"effort": "medium"` - Allocates a moderate portion of tokens (approximately 50% of the limit)
* `"effort": "low"` - Allocates a smaller portion of tokens (approximately 20% of the limit)
* `"effort": "minimal"` - Allocates an even smaller portion of tokens (approximately 10% of the limit)
* `"effort": "none"` - Disables reasoning entirely

For models that only support `reasoning.max_tokens`, the effort level will be set based on the percentages above.

### Excluding Reasoning Tokens (Chat Completions only)

If you want the model to use reasoning internally but not include it in the response:

* `"exclude": true` - The model will still use reasoning, but it won't be returned in the response. The tokens are still billed and [count against `max_tokens`](#reasoning-tokens-and-max_tokens).

`exclude` is only honored on Chat Completions (`/api/v1/chat/completions`). The Responses API ignores it and always returns `reasoning` items in `output`; filter them out client-side if you do not want them.

### Enable Reasoning with Default Config

To enable reasoning with the default parameters:

* `"enabled": true` - Enables reasoning at the "medium" effort level with no exclusions.

### Examples

#### Basic Usage with Reasoning Tokens

```typescript title="TypeScript SDK" expandable lines theme={null}
import { OpenRouter } from '@openrouter/sdk';

const openRouter = new OpenRouter({
  apiKey: '<OPENROUTER_API_KEY>',
});

const response = await openRouter.responses.send({
  responsesRequest: {
    model: 'openai/o3',
    input: "How would you build the world's tallest skyscraper?",
    reasoning: {
      effort: 'high',
      summary: 'detailed',
    },
    stream: false,
  },
});

if (!('output' in response)) {
  throw new Error('Expected a non-streaming response');
}

const reasoning = [...response.output].reverse().find((item) => item.type === 'reasoning');
const message = [...response.output].reverse().find((item) => item.type === 'message');

// Raw reasoning arrives in `content`; OpenAI models return a summary in `summary` instead.
const reasoningText = [...(reasoning?.content ?? []), ...(reasoning?.summary ?? [])]
  .map((part) => part.text)
  .join('');
console.log('REASONING:', reasoningText);
console.log('CONTENT:', message?.content.find((part) => part.type === 'output_text')?.text);
```

```python title="Python (OpenAI SDK)" expandable lines theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key="<OPENROUTER_API_KEY>",
)

response = client.responses.create(
    model="openai/o3",
    input="How would you build the world's tallest skyscraper?",
    reasoning={
        "effort": "high",
        "summary": "detailed",
    },
)

for item in response.output:
    if item.type == "reasoning":
        # Raw reasoning arrives in `content`; OpenAI models return a summary in `summary` instead.
        parts = [*(item.content or []), *item.summary]
        print("REASONING:", "".join(part.text for part in parts))
print("CONTENT:", response.output_text)
```

```typescript title="TypeScript (OpenAI SDK)" expandable lines theme={null}
import OpenAI from 'openai';

const openai = new OpenAI({
  baseURL: 'https://openrouter.ai/api/v1',
  apiKey: '<OPENROUTER_API_KEY>',
});

async function getResponseWithReasoning() {
  const response = await openai.responses.create({
    model: 'openai/o3',
    input: "How would you build the world's tallest skyscraper?",
    reasoning: {
      effort: 'high',
      summary: 'detailed',
    },
  });

  for (const item of response.output) {
    if (item.type === 'reasoning') {
      // Raw reasoning arrives in `content`; OpenAI models return a summary in `summary` instead.
      const parts = [...(item.content ?? []), ...item.summary];
      console.log('REASONING:', parts.map((part) => part.text).join(''));
    }
  }
  console.log('CONTENT:', response.output_text);
}

getResponseWithReasoning();
```

```go title="Go" lines theme={null}
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"strings"
)

type part struct {
	Type string `json:"type"`
	Text string `json:"text"`
}

type item struct {
	Type    string `json:"type"`
	Content []part `json:"content"`
	Summary []part `json:"summary"`
}

func main() {
	body, _ := json.Marshal(map[string]any{
		"model": "openai/o3",
		"input": "How would you build the world's tallest skyscraper?",
		"reasoning": map[string]any{
			"effort":  "high",
			"summary": "detailed",
		},
		"stream": false,
	})

	req, _ := http.NewRequest("POST", "https://openrouter.ai/api/v1/responses", bytes.NewReader(body))
	req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENROUTER_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	raw, _ := io.ReadAll(resp.Body)
	if resp.StatusCode != http.StatusOK {
		log.Fatalf("HTTP %d: %s", resp.StatusCode, raw)
	}

	var response struct {
		Output []item `json:"output"`
	}
	if err := json.Unmarshal(raw, &response); err != nil {
		log.Fatal(err)
	}

	var reasoning, message *item
	for i := len(response.Output) - 1; i >= 0; i-- {
		it := &response.Output[i]
		if it.Type == "reasoning" && reasoning == nil {
			reasoning = it
		}
		if it.Type == "message" && message == nil {
			message = it
		}
	}

	// Raw reasoning arrives in `content`; OpenAI models return a summary in `summary` instead.
	var reasoningText strings.Builder
	if reasoning != nil {
		for _, p := range append(reasoning.Content, reasoning.Summary...) {
			reasoningText.WriteString(p.Text)
		}
	}
	fmt.Println("REASONING:", reasoningText.String())

	content := ""
	if message != nil {
		for _, p := range message.Content {
			if p.Type == "output_text" {
				content = p.Text
				break
			}
		}
	}
	fmt.Println("CONTENT:", content)
}

```

```bash title="cURL" lines theme={null}
curl -sS https://openrouter.ai/api/v1/responses \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/o3",
    "input": "How would you build the world'\''s tallest skyscraper?",
    "reasoning": { "effort": "high", "summary": "detailed" },
    "stream": false
  }' | jq -r '
  # Raw reasoning arrives in `content`; OpenAI models return a summary in `summary` instead.
  ([.output[] | select(.type == "reasoning")] | last) as $r
  | ([.output[] | select(.type == "message")] | last) as $m
  | "REASONING: " + ((($r.content // []) + ($r.summary // [])) | map(.text) | join("")),
    "CONTENT: " + ([$m.content[]? | select(.type == "output_text") | .text][0] // "")'

```

```text title="Output" theme={null}
REASONING: 
CONTENT: Building the world’s tallest skyscraper is as much a management and finance challenge as it is an engineering one. Below is a high-level, end-to-end roadmap that reflects current best practice (as of 2026) and lessons learned from Burj Khalifa, Merdeka 118, and Jeddah Tower, plus emerging technologies. Every step is iterative: feedback loops between design, analysis, procurement, and construction run from day one until opening day.

─────────────────────────────────
1. Establish the “why”
─────────────────────────────────
• Business case: Mixed-use (offices, hotel, branded residences, observation decks) is the only proven revenue model that can underwrite megatall (≥600 m) projects.  
• Icon value: Governments or developers usually justify the extra height through tourism, global branding, and catalytic urban development.

─────────────────────────────────
2. Select and test the site
─────────────────────────────────
• Geotechnical viability: Deep borehole drilling (≥150 m) to map rock strata, groundwater, and compressibility.  
• Seismicity & wind climate: Install 100 m anemometer mast and use 50-year wind records; run probabilistic seismic hazard analysis (PSHA).  
• Infrastructure: Metro, arterial roads, district cooling, water desalination/recycle plant sized for peak demand.  
• Regulatory baseline: Verify air-traffic envelopes, shadowing, view-corridor, and heritage constraints.

─────────────────────────────────
3. Assemble the A-team
─────────────────────────────────
• Developer/asset owner  
• Equity & debt partners (sovereign fund, pension funds, Islamic finance, green bonds)  
• Integrated design/build joint venture led by:  
  – “Star-architect” + local associate architect  
  – Structural engineer of record (EOR) with supertall portfolio  
  – MEP/FP engineer (district energy, grey-water loops, tri-generation)  
  – Wind/climate consultant & RWDI lab  
  – Vertical-transportation consultant (double-deck, sky-lobbies, express zoned shuttles)  
  – Digital construction & BIM/VDC manager  
  – CM/GC with megaproject experience  
  – Specialist subcontractors: curtain wall, tuned mass damper (TMD), steel fabrication, slip-form core

─────────────────────────────────
4. Concept & schematic design
─────────────────────────────────
4.1 Massing & aerodynamic shaping  
• Target height chosen after financial sensitivity (NPV vs metre).  
• Form options: bundled tube, buttressed core, tapered neo-buttress, composite mega-truss.  
• Early wind-tunnel study (1:500 & 1:250 scale) to avoid vortex lock-in; sculpt setbacks, chamfers, corner softening, spirals.
```

#### Using Max Tokens for Reasoning

For models that support direct token allocation (like Anthropic models), you can specify the exact number of tokens to use for reasoning:

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

client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key="<OPENROUTER_API_KEY>",
)

response = client.responses.create(
    model="~anthropic/claude-sonnet-latest",
    input="What's the most efficient algorithm for sorting a large dataset?",
    extra_body={
        "reasoning": {
            "max_tokens": 2000
        }
    },
)

for item in response.output:
    if item.type == "reasoning":
        print("REASONING:", "".join(part.text for part in item.content or []))
print("CONTENT:", response.output_text)
```

```typescript TypeScript expandable lines theme={null}
import OpenAI from 'openai';

const openai = new OpenAI({
  baseURL: 'https://openrouter.ai/api/v1',
  apiKey: '<OPENROUTER_API_KEY>',
});

async function getResponseWithReasoning() {
  const response = await openai.responses.create({
    model: '~anthropic/claude-sonnet-latest',
    input: "How would you build the world's tallest skyscraper?",
    reasoning: {
      // @ts-expect-error max_tokens is an OpenRouter extension
      max_tokens: 2000,
    },
  });

  for (const item of response.output) {
    if (item.type === 'reasoning') {
      console.log('REASONING:', item.content?.map((part) => part.text).join(''));
    }
  }
  console.log('CONTENT:', response.output_text);
}

getResponseWithReasoning();
```

```go title="Go" lines theme={null}
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"strings"
)

type part struct {
	Type string `json:"type"`
	Text string `json:"text"`
}

type item struct {
	Type    string `json:"type"`
	Content []part `json:"content"`
}

func main() {
	body, _ := json.Marshal(map[string]any{
		"model": "~anthropic/claude-sonnet-latest",
		"input": "How would you build the world's tallest skyscraper?",
		"reasoning": map[string]any{
			"max_tokens": 2000,
		},
	})

	req, _ := http.NewRequest("POST", "https://openrouter.ai/api/v1/responses", bytes.NewReader(body))
	req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENROUTER_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	raw, _ := io.ReadAll(resp.Body)
	if resp.StatusCode != http.StatusOK {
		log.Fatalf("HTTP %d: %s", resp.StatusCode, raw)
	}

	var response struct {
		Output []item `json:"output"`
	}
	if err := json.Unmarshal(raw, &response); err != nil {
		log.Fatal(err)
	}

	var content strings.Builder
	for _, it := range response.Output {
		switch it.Type {
		case "reasoning":
			var text strings.Builder
			for _, p := range it.Content {
				text.WriteString(p.Text)
			}
			fmt.Println("REASONING:", text.String())
		case "message":
			for _, p := range it.Content {
				if p.Type == "output_text" {
					content.WriteString(p.Text)
				}
			}
		}
	}
	fmt.Println("CONTENT:", content.String())
}

```

```bash title="cURL" lines theme={null}
curl -sS https://openrouter.ai/api/v1/responses \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "~anthropic/claude-sonnet-latest",
    "input": "How would you build the world'\''s tallest skyscraper?",
    "reasoning": { "max_tokens": 2000 },
    "stream": false
  }' | jq -r '
  (.output[] | select(.type == "reasoning")
    | "REASONING: " + ((.content // []) | map(.text) | join(""))),
  "CONTENT: " + ([.output[] | select(.type == "message") | .content[]?
    | select(.type == "output_text") | .text] | join(""))'

```

```text title="Output" theme={null}
REASONING: I'm considering how to answer the question of building the world's tallest skyscraper, planning to cover the main engineering challenges like foundations, structure, wind loads, elevators, and logistics, with the Burj Khalifa and the stalled Jeddah Tower as reference points.


CONTENT: # Building the World's Tallest Skyscraper

The record is the Burj Khalifa at 828 m. Jeddah Tower, designed to pass 1,000 m, has been partly built but stalled. Here is how I'd approach going beyond that.

## 1. Start with site and economics
- **Geotechnical conditions:** You need deep, stable soil or bedrock. Poor ground drives costs up dramatically.
- **Business case:** Supertall towers rarely pay for themselves directly. They're justified by real estate value around them, national prestige, or tourism. Cost rises faster than height, and a large share of floor area goes to cores and mechanical space near the top.
- **Climate and seismic risk:** These shape the entire structural strategy.

## 2. Foundation
- Use a thick reinforced concrete **mat** supported by **deep bored piles** (Burj Khalifa used piles around 50 m deep).
- Use high-performance, low-heat concrete to avoid cracking during massive pours.
- Protect against groundwater and corrosion, for example with cathodic protection.

## 3. Structural system
Wind, not gravity, is the main enemy at this scale.
- **Buttressed core:** The Burj Khalifa's Y-shaped plan has a central hexagonal core with three wings that brace each other. I'd start from something similar.
- **Outriggers and belt trusses** tie the core to perimeter columns, making the building act as one giant stiff beam.
- **Concrete lower, steel upper:** High-strength concrete (80+ MPa) is stiff and damps motion in the lower sections. Lighter steel or composite construction is better higher up, where weight matters more.
- **Tapering or setbacks:** Reduce the surface area exposed to wind as you go up.

## 4. Wind engineering
- Run **wind tunnel tests** on many iterations of the form.
- Use an asymmetric, spiraling, or stepped shape to **confuse the wind**, preventing coordinated vortex shedding that causes dangerous oscillation.
- Add **tuned mass dampers** or pendulum dampers to control sway and keep occupants comfortable.

## 5. Vertical transportation
This often limits how tall a building can go.
- **Sky lobbies** with shuttle elevators to transfer floors, so you aren't stacking one huge elevator bank on every floor.
- **Double-deck elevators** to save core space.
- **Ropeless magnetic elevators**, like TK Elevator's MULTI, which can move horizontally too. Steel ropes become impractical beyond about 500 m, and carbon-fiber ropes (UltraRope) help.
- Dedicated **evacuation elevators** and protected refuge floors.

## 6. Building systems
- **Water and pumping:** Pump in stages, with intermediate tanks and pressure-reducing stations.
- **Cooling:** Large central plants, plus thermal storage and condensate recovery.
- **Facade:** Use high-performance glazing for solar control, with design that handles large temperature and pressure differences between the bottom and top.
```

#### Excluding Reasoning Tokens from Response (Chat Completions)

If you want the model to use reasoning internally but not include it in the response, use Chat Completions (`/api/v1/chat/completions`). The Responses API ignores `reasoning.exclude` and always returns `reasoning` items in `output`.

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

client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key="<OPENROUTER_API_KEY>",
)

response = client.chat.completions.create(
    model="deepseek/deepseek-r1-0528",
    messages=[
        {"role": "user", "content": "Explain quantum computing in simple terms."}
    ],
    extra_body={
        "reasoning": {
            "effort": "high",
            "exclude": True
        }
    },
)

print(response.choices[0].message.content)
```

```typescript TypeScript expandable lines theme={null}
import OpenAI from 'openai';

const openai = new OpenAI({
  baseURL: 'https://openrouter.ai/api/v1',
  apiKey: '<OPENROUTER_API_KEY>',
});

async function getResponseWithReasoning() {
  const response = await openai.chat.completions.create({
    model: 'deepseek/deepseek-r1-0528',
    messages: [
      {
        role: 'user',
        content: "How would you build the world's tallest skyscraper?",
      },
    ],
    // @ts-expect-error reasoning is an OpenRouter extension
    reasoning: {
      effort: 'high',
      exclude: true,
    },
  });

  console.log('CONTENT:', response.choices[0].message.content);
}

getResponseWithReasoning();
```

```go title="Go" lines theme={null}
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
)

func main() {
	body, _ := json.Marshal(map[string]any{
		"model": "deepseek/deepseek-r1-0528",
		"messages": []map[string]string{
			{"role": "user", "content": "How would you build the world's tallest skyscraper?"},
		},
		"reasoning": map[string]any{
			"effort":  "high",
			"exclude": true,
		},
	})

	req, _ := http.NewRequest("POST", "https://openrouter.ai/api/v1/chat/completions", bytes.NewReader(body))
	req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENROUTER_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	raw, _ := io.ReadAll(resp.Body)
	if resp.StatusCode != http.StatusOK {
		log.Fatalf("HTTP %d: %s", resp.StatusCode, raw)
	}

	var response struct {
		Choices []struct {
			Message struct {
				Content string `json:"content"`
			} `json:"message"`
		} `json:"choices"`
	}
	if err := json.Unmarshal(raw, &response); err != nil {
		log.Fatal(err)
	}
	if len(response.Choices) == 0 {
		log.Fatalf("no choices in response: %s", raw)
	}

	fmt.Println("CONTENT:", response.Choices[0].Message.Content)
}

```

```bash title="cURL" lines theme={null}
curl -sS https://openrouter.ai/api/v1/chat/completions \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "deepseek/deepseek-r1-0528",
    "messages": [
      { "role": "user", "content": "How would you build the world'\''s tallest skyscraper?" }
    ],
    "reasoning": { "effort": "high", "exclude": true }
  }' | jq -r '"CONTENT: " + .choices[0].message.content'
```

```text title="Output" theme={null}
CONTENT: Building the world's tallest skyscraper is an extraordinary feat of engineering, finance, logistics, and political will. It requires pushing boundaries in almost every discipline. Here's a comprehensive breakdown of the key considerations and steps:

**Core Philosophies:**

1.  **Innovation is Mandatory:** You can't just scale up existing designs. Every system faces unprecedented stresses.
2.  **Holistic Systems Thinking:** Structural stability, vertical circulation (elevators), foundation stability, wind dynamics, energy systems, and human comfort are deeply interconnected.
3.  **The Pursuit of Lightness:** Minimizing mass is paramount for managing gravity loads and seismic/wind forces. This drives material science and structural efficiency.
4.  **Redundancy & Resilience:** Absolutely critical for safety at unprecedented heights. Multiple load paths and backup systems are essential.

**Key Challenges & Solutions:**

1.  **Overcoming Gravity & Material Strength:**
    *   **Challenges:** Columns and core experience immense compressive loads. Material sheer volume adds weight exponentially. Self-weight dominates design.
    *   **Solutions:**
        *   **Structural Form:** Tapering profile (pyramidal, stepped) reduces wind profile and efficiently transfers loads downward. Exo-skeleton, bundled-tube (like Willis Tower, refined), or hybrid core/mega-frame systems.
        *   **Super Core:** Massive reinforced concrete core (potentially with steel bracing/plates) housing elevators, stairs, and MEP. Must be incredibly stiff.
        *   **Mega Columns:** Enormous columns at the perimeter and/or key interior points, using ultra-high-performance concrete (UHPC) or composite steel/concrete.
        *   **Outriggers:** Deep horizontal trusses or walls connecting the core to the perimeter columns (potentially at multiple levels). Transfer lateral loads and resist differential shortening.
        *   **Advanced Materials:** Ultra-High-Performance Concrete (UHPC) with fiber reinforcement (compressive strengths > 25,000 psi). High-Strength Low-Alloy (HSLA) steels (yield strengths > 100 ksi). Exploration of carbon fiber composites for reinforcing/cables where weight savings justify cost.

2.  **Conquering the Wind:**
    *   **Challenges:** Wind forces increase with height, causing dangerous sway (affecting human comfort/potential structural fatigue) and vortex shedding oscillations. Aerodynamics are critical.
    *   **Solutions:**
        *   **Aerodynamic Shaping:** Highly optimized geometry – tapering, twisting, softening corners, sculpting with openings (like Shanghai Tower and One Vanderbilt) to disrupt vortex shedding and reduce lateral loads by 20-40%.
        *   **Mass Dampers:** Multi-story tuned liquid sloshing dampers (TLSDs) and/or massive tuned mass dampers (TMDs), potentially active systems, strategically located near the top to counter sway forces.
        *   **Robust Lateral System:** The structural system conceived to resist wind primarily (gravity governs lower floors). Redundant bracing, diagrids, outriggers, super frames.

3.  **Foundation Supremacy:**
    *   **Challenges:** Transferring colossal, concentrated loads to the ground without settlement differences or collapse.
    *   **Solutions:**
        *   **Deep Geotechnical Investigation:** Extensive boring and testing far deeper than standard.
        *   **Massive Piled Foundation:** Thousands of **very** deep steel-reinforced concrete friction/end-bearing piles (potentially > 100m deep) or drilled shafts reaching bedrock. A thick, heavily reinforced mat/pile cap binds them together.
        *   **Advanced Modeling:** Simulating complex soil-structure interaction over decades.

4.  **Vertical Transportation Revolution:**
    *   **Challenges:** Conventional elevators become inefficient. Shafts occupy prime space. Journey times become prohibitive. Cable weight approaches material limits.
    *   **Solutions:**
        *   **Super-Fast Elevators:** Spe
…[1559 chars clipped]…
arbon Reduction:** High fly ash/slag concrete, mass timber components if feasible within safety/strength/fire codes at that height, optimized steel procurement, material recycling programs.
```

#### Advanced Usage: Reasoning Chain-of-Thought

This example shows how to use reasoning tokens in a more complex workflow. It injects one model's reasoning into another model to improve its response quality:

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

client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key="<OPENROUTER_API_KEY>",
)

question = "Which is bigger: 9.11 or 9.9?"

def do_req(model: str, content: str, reasoning_config: dict | None = None):
    extra_body = {"stop": "</think>"}
    if reasoning_config:
        extra_body.update(reasoning_config)
    return client.responses.create(model=model, input=content, extra_body=extra_body)

def get_reasoning(response) -> str:
    return "".join(
        part.text
        for item in response.output
        if item.type == "reasoning"
        for part in item.content or []
    )

# Get reasoning from a capable model
content = f"{question} Please think this through, but don't output an answer"
reasoning_response = do_req("deepseek/deepseek-r1-0528", content)
reasoning = get_reasoning(reasoning_response)

# Let's test! Here's the naive response:
simple_response = do_req("~openai/gpt-mini-latest", question)
print(simple_response.output_text)

# Here's the response with the reasoning token injected:
content = f"{question}. Here is some context to help you: {reasoning}"
smart_response = do_req("~openai/gpt-mini-latest", content)
print(smart_response.output_text)
```

```typescript TypeScript expandable lines theme={null}
import OpenAI from 'openai';

const openai = new OpenAI({
  baseURL: 'https://openrouter.ai/api/v1',
  apiKey: '<OPENROUTER_API_KEY>',
});

async function doReq(model: string, content: string, reasoningConfig: Record<string, unknown> = {}) {
  const payload = {
    model,
    input: content,
    stop: '</think>',
    ...reasoningConfig,
  };

  return openai.responses.create(payload);
}

async function getResponseWithReasoning() {
  const question = 'Which is bigger: 9.11 or 9.9?';
  const reasoningResponse = await doReq(
    'deepseek/deepseek-r1-0528',
    `${question} Please think this through, but don't output an answer`,
  );
  const reasoning = reasoningResponse.output
    .filter((item) => item.type === 'reasoning')
    .flatMap((item) => item.content ?? [])
    .map((part) => part.text)
    .join('');

  // Let's test! Here's the naive response:
  const simpleResponse = await doReq('~openai/gpt-mini-latest', question);
  console.log('NAIVE:', simpleResponse.output_text);

  // Here's the response with the reasoning token injected:
  const content = `${question}. Here is some context to help you: ${reasoning}`;
  const smartResponse = await doReq('~openai/gpt-mini-latest', content);
  console.log('WITH REASONING:', smartResponse.output_text);
}

getResponseWithReasoning();

```

```go title="Go" lines theme={null}
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"strings"
)

type item struct {
	Type    string
	Content []struct{ Type, Text string }
}

func doReq(model, content string) []item {
	body, _ := json.Marshal(map[string]any{
		"model": model,
		"input": content,
		"stop":  "</think>",
	})
	req, _ := http.NewRequest("POST", "https://openrouter.ai/api/v1/responses", bytes.NewReader(body))
	req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENROUTER_API_KEY"))
	req.Header.Set("Content-Type", "application/json")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	raw, _ := io.ReadAll(resp.Body)
	if resp.StatusCode != http.StatusOK {
		log.Fatalf("HTTP %d: %s", resp.StatusCode, raw)
	}
	var r struct{ Output []item }
	if err := json.Unmarshal(raw, &r); err != nil {
		log.Fatal(err)
	}
	return r.Output
}

// join concatenates the text of parts in items of itemType (partType "" = any part).
func join(items []item, itemType, partType string) string {
	var sb strings.Builder
	for _, it := range items {
		if it.Type != itemType {
			continue
		}
		for _, p := range it.Content {
			if partType == "" || p.Type == partType {
				sb.WriteString(p.Text)
			}
		}
	}
	return sb.String()
}

func main() {
	question := "Which is bigger: 9.11 or 9.9?"
	reasoningResponse := doReq("deepseek/deepseek-r1-0528",
		question+" Please think this through, but don't output an answer")
	reasoning := join(reasoningResponse, "reasoning", "")

	// Let's test! Here's the naive response:
	simpleResponse := doReq("~openai/gpt-mini-latest", question)
	fmt.Println("NAIVE:", join(simpleResponse, "message", "output_text"))

	// Here's the response with the reasoning token injected:
	content := question + ". Here is some context to help you: " + reasoning
	smartResponse := doReq("~openai/gpt-mini-latest", content)
	fmt.Println("WITH REASONING:", join(smartResponse, "message", "output_text"))
}

```

```bash title="cURL" lines theme={null}
Q='Which is bigger: 9.11 or 9.9?'

req() {
  jq -n --arg m "$1" --arg i "$2" '{model: $m, input: $i, stop: "</think>"}' |
    curl -sS https://openrouter.ai/api/v1/responses \
      -H "Authorization: Bearer $OPENROUTER_API_KEY" \
      -H "Content-Type: application/json" \
      -d @-
}

text() {
  jq -r '[.output[]? | select(.type == "message") | .content[]? | select(.type == "output_text") | .text] | join("")'
}

REASONING=$(req deepseek/deepseek-r1-0528 "$Q Please think this through, but don't output an answer" |
  jq -r '[.output[]? | select(.type == "reasoning") | .content[]?.text] | join("")')

# Let's test! Here's the naive response:
echo "NAIVE: $(req '~openai/gpt-mini-latest' "$Q" | text)"

# Here's the response with the reasoning token injected:
echo "WITH REASONING: $(req '~openai/gpt-mini-latest' "$Q. Here is some context to help you: $REASONING" | text)"

```

```text title="Output" theme={null}
NAIVE: 9.9 is bigger.

If you compare them as decimals:
- 9.11 = 9.110
- 9.9 = 9.900

Since 9.900 > 9.110, **9.9 is larger**.
WITH REASONING: 9.9 is bigger.
```

## Preserving Reasoning

### Responses API

To preserve reasoning across turns, send the previous response's `output` items back in the next request's `input`, in the order they were returned, and append your `function_call_output` items after them. Keep each `reasoning` item's `content`, `summary`, `signature`, and `encrypted_content` unchanged:

```json lines theme={null}
{
  "model": "anthropic/claude-sonnet-4.5",
  "reasoning": { "max_tokens": 2000 },
  "tools": [{ "type": "function", "name": "get_weather", "parameters": { "type": "object", "properties": { "city": { "type": "string" } }, "required": ["city"] } }],
  "input": [
    { "role": "user", "content": "What's the weather in Boston?" },
    { "type": "reasoning", "id": "rs_abc123", "summary": [], "content": [{ "type": "reasoning_text", "text": "The user wants the current weather, so I should call get_weather." }], "signature": "..." },
    { "type": "function_call", "id": "fc_abc123", "call_id": "call_abc123", "name": "get_weather", "arguments": "{\"city\":\"Boston\"}" },
    { "type": "function_call_output", "call_id": "call_abc123", "output": "{\"temperature_f\":62,\"conditions\":\"cloudy\"}" }
  ]
}
```

With OpenAI GPT-5.6 and newer you can also control which turns' reasoning the model sees; see [Reasoning Context Mode](#reasoning-context-mode).

### Chat Completions

To preserve reasoning context across multiple turns, you can pass it back to the API in one of two ways:

1. **`message.reasoning`** (string): Pass the plaintext reasoning as a string field on the assistant message
2. **`message.reasoning_details`** (array): Pass the full reasoning\_details block

Use `reasoning_details` when working with models that return special reasoning types (such as encrypted or summarized) - this preserves the full structure needed for those models.

For models that only return raw reasoning strings, you can use the simpler `reasoning` field. You can also use `reasoning_content` as an alias - it functions identically to `reasoning`.

The `reasoning_details` functionality works identically across all supported reasoning models. You can easily switch between OpenAI reasoning models (like `~openai/gpt-sol-latest`) and Anthropic reasoning models (like `~anthropic/claude-sonnet-latest`) without changing your code structure.

Preserving reasoning blocks is useful specifically for tool calling. When models like Claude invoke tools, it is pausing its construction of a response to await external information. When tool results are returned, the model will continue building that existing response. This necessitates preserving reasoning blocks during tool use, for a couple of reasons:

**Reasoning continuity**: The reasoning blocks capture the model's step-by-step reasoning that led to tool requests. When you post tool results, including the original reasoning ensures the model can continue its reasoning from where it left off.

**Context maintenance**: While tool results appear as user messages in the API structure, they're part of a continuous reasoning flow. Preserving reasoning blocks maintains this conceptual flow across multiple API calls.

> [!NOTE]
>
> **Important for Reasoning Models**
>
> When providing reasoning\_details blocks, the entire sequence of consecutive reasoning blocks must match the outputs generated by the model during the original request; you cannot rearrange or modify the sequence of these blocks.

### Example: Preserving Reasoning Blocks with OpenRouter and Claude

The Python and TypeScript tabs use the agent helper `call_model` / `callModel`, which runs the tool loop for you and replays the assistant turn with its reasoning blocks, so you never handle `message.reasoning_details` yourself. To see the replay written out against Chat Completions, use the Go or cURL tab.

```python Python expandable lines theme={null}
import asyncio
import os

from pydantic import BaseModel
from openrouter_agent import OpenRouter, call_model, tool


class WeatherInput(BaseModel):
    location: str


class WeatherOutput(BaseModel):
    location: str
    temperature: int
    condition: str
    humidity: int


# Define tools once and reuse
get_weather = tool(
    name="get_weather",
    description="Get current weather",
    input_schema=WeatherInput,
    output_schema=WeatherOutput,
    execute=lambda params, ctx: WeatherOutput(
        location=params.location,
        temperature=45,
        condition="rainy",
        humidity=85,
    ),
)


async def main() -> None:
    client = OpenRouter(api_key=os.environ["OPENROUTER_API_KEY"])

    # The agent loop runs the tool call and sends the assistant turn back with its
    # reasoning blocks preserved unmodified, so Claude continues reasoning from
    # where it left off.
    # Note: You can use '~openai/gpt-sol-latest' instead of '~anthropic/claude-sonnet-latest' - they're completely interchangeable
    result = call_model(
        client,
        {
            "model": "~anthropic/claude-sonnet-latest",
            "input": "What's the weather like in Boston? Then recommend what to wear.",
            "tools": [get_weather],
            "reasoning": {"max_tokens": 2000},
        },
    )

    print(await result.get_text())


asyncio.run(main())

```

```typescript TypeScript expandable lines theme={null}
import { OpenRouter } from '@openrouter/sdk';
import { callModel, tool } from '@openrouter/agent';
import { z } from 'zod';

const client = new OpenRouter({ apiKey: process.env.OPENROUTER_API_KEY });

// Define tools once and reuse
const getWeather = tool({
  name: 'get_weather',
  description: 'Get current weather',
  inputSchema: z.object({ location: z.string() }),
  execute: async ({ location }) => ({
    location,
    temperature: 45,
    condition: 'rainy',
    humidity: 85,
  }),
});

// The agent loop runs the tool call and sends the assistant turn back with its
// reasoning blocks preserved unmodified, so Claude continues reasoning from
// where it left off.
// Note: You can use '~openai/gpt-sol-latest' instead of '~anthropic/claude-sonnet-latest' - they're completely interchangeable
const result = callModel(client, {
  model: '~anthropic/claude-sonnet-latest',
  input: "What's the weather like in Boston? Then recommend what to wear.",
  tools: [getWeather] as const,
  reasoning: { maxTokens: 2000 },
});

const text = await result.getText();
console.log(text);

```

```go title="Go" lines theme={null}
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
)

type obj = map[string]any

func chat(body obj) obj {
	b, _ := json.Marshal(body)
	req, _ := http.NewRequest("POST", "https://openrouter.ai/api/v1/chat/completions", bytes.NewReader(b))
	req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENROUTER_API_KEY"))
	req.Header.Set("Content-Type", "application/json")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	raw, _ := io.ReadAll(resp.Body)
	if resp.StatusCode != http.StatusOK {
		log.Fatalf("HTTP %d: %s", resp.StatusCode, raw)
	}
	var r struct{ Choices []struct{ Message obj } }
	if err := json.Unmarshal(raw, &r); err != nil || len(r.Choices) == 0 {
		log.Fatalf("bad response: %s", raw)
	}
	return r.Choices[0].Message
}

func main() {
	// Define tools once and reuse
	tools := []any{obj{"type": "function", "function": obj{
		"name":        "get_weather",
		"description": "Get current weather",
		"parameters": obj{
			"type":       "object",
			"properties": obj{"location": obj{"type": "string"}},
			"required":   []string{"location"},
		},
	}}}
	messages := []any{obj{"role": "user", "content": "What's the weather like in Boston? Then recommend what to wear."}}

	// The loop runs the tool call and sends the assistant turn back with its
	// reasoning_details preserved unmodified, so Claude continues reasoning from
	// where it left off.
	// Note: You can use '~openai/gpt-sol-latest' instead of '~anthropic/claude-sonnet-latest' - they're completely interchangeable
	for {
		msg := chat(obj{
			"model":     "~anthropic/claude-sonnet-latest",
			"messages":  messages,
			"tools":     tools,
			"reasoning": obj{"max_tokens": 2000},
		})
		messages = append(messages, msg) // includes reasoning_details as-is
		calls, _ := msg["tool_calls"].([]any)
		if len(calls) == 0 {
			fmt.Println(msg["content"])
			return
		}
		for _, c := range calls {
			call := c.(obj)
			fn := call["function"].(obj)
			var args struct{ Location string }
			json.Unmarshal([]byte(fmt.Sprint(fn["arguments"])), &args)
			out, _ := json.Marshal(obj{"location": args.Location, "temperature": 45, "condition": "rainy", "humidity": 85})
			messages = append(messages, obj{"role": "tool", "tool_call_id": call["id"], "content": string(out)})
		}
	}
}

```

```bash title="cURL" lines theme={null}
# Tool definition, sent with every request
TOOLS='[{"type":"function","function":{"name":"get_weather","description":"Get current weather","parameters":{"type":"object","properties":{"location":{"type":"string"}},"required":["location"]}}}]'

# Note: You can use '~openai/gpt-sol-latest' instead of '~anthropic/claude-sonnet-latest' - they're completely interchangeable
chat() {
  jq -n --argjson msgs "$1" --argjson tools "$TOOLS" \
    '{model: "~anthropic/claude-sonnet-latest", messages: $msgs, tools: $tools, reasoning: {max_tokens: 2000}}' |
    curl -sS https://openrouter.ai/api/v1/chat/completions \
      -H "Authorization: Bearer $OPENROUTER_API_KEY" \
      -H "Content-Type: application/json" \
      -d @-
}

MESSAGES=$(jq -n --arg q "What's the weather like in Boston? Then recommend what to wear." '[{role: "user", content: $q}]')

# Loop until Claude answers without requesting another tool call
while :; do
  ASSISTANT=$(chat "$MESSAGES" | jq '.choices[0].message')

  if [ "$(jq '(.tool_calls // []) | length' <<<"$ASSISTANT")" -eq 0 ]; then
    jq -r '.content' <<<"$ASSISTANT"
    break
  fi

  # Send the assistant turn back unmodified (including reasoning_details) plus the tool results,
  # so Claude continues reasoning from where it left off.
  MESSAGES=$(jq -n --argjson m "$MESSAGES" --argjson a "$ASSISTANT" '$m + [$a] + [$a.tool_calls[] | {
    role: "tool",
    tool_call_id: .id,
    content: ({location: (.function.arguments | fromjson).location, temperature: 45, condition: "rainy", humidity: 85} | tojson)
  }]')
done

```

```text title="Output" theme={null}
**Boston right now:** 45°, rainy, 85% humidity. I'm assuming the temperature is in °F, since the tool didn't give a unit.

**What to wear:**
- **Outer layer:** A waterproof rain jacket, or a water-resistant coat with a hood. An umbrella helps too, but a hood is better if it's windy.
- **Warmth:** A warm mid-layer such as a sweater, fleece, or light hoodie. The damp air will make 45° feel colder.
- **Bottoms:** Long pants that dry quickly. Jeans will stay wet and cold if they soak through.
- **Shoes:** Waterproof boots or shoes, with wool or moisture-wicking socks.
- **Extras:** A light hat or beanie if you're out for long. Gloves are optional.

Dress in layers, because you may be too warm indoors.
```

For more detailed information about thinking encryption, redacted blocks, and advanced use cases, see [Anthropic's documentation on extended thinking](https://docs.anthropic.com/en/docs/build-with-claude/tool-use#extended-thinking).

For more information about OpenAI reasoning models, see [OpenAI's reasoning documentation](https://platform.openai.com/docs/guides/reasoning#keeping-reasoning-items-in-context).

## Reasoning Context Mode

When you echo reasoning items back in your conversation history, you can control which reasoning the model has access to with the `reasoning.context` parameter:

* **`auto`**: The model uses its default context mode. Omitting `reasoning.context` has the same effect.
* **`all_turns`**: The model can reference reasoning from all turns present in the input. Use this for multi-turn conversations where you want the model to build on its previous chain of thought.
* **`current_turn`**: The model only uses reasoning from the current turn. Prior reasoning items in the input are ignored. Use this when you want a fresh reasoning pass without influence from earlier turns.

> [!NOTE]
>
> `reasoning.context` is only supported by OpenAI GPT-5.6 and newer.

When using the Responses API with manual state management (echoing output items back as input), set `reasoning.context`. OpenRouter automatically requests encrypted reasoning content from reasoning-capable providers, so replay the returned `encrypted_content` unchanged; no explicit `include` field is required:

```json theme={null}
{
  "model": "~openai/gpt-sol-latest",
  "input": [
    { "role": "user", "content": "Solve this math problem step by step: ..." },
    {
      "type": "reasoning",
      "id": "rs_abc123",
      "encrypted_content": "...",
      "summary": [{ "type": "summary_text", "text": "Analyzed the equation..." }]
    },
    {
      "type": "message",
      "role": "assistant",
      "content": [{ "type": "output_text", "text": "The answer is 42." }]
    },
    { "role": "user", "content": "Now explain it differently." }
  ],
  "reasoning": {
    "effort": "high",
    "context": "all_turns"
  }
}
```

> [!NOTE]
>
> The default value of `context` may vary by model. Set it explicitly if your use case requires a specific behavior.

## Reasoning Mode

For models that offer a pro reasoning variant, the `reasoning.mode` parameter controls which variant serves your request:

* **`standard`**: The model's standard reasoning behavior. Omitting `reasoning.mode` has the same effect.
* **`pro`**: Routes the request to the model's pro variant, which uses deeper multi-pass reasoning for harder problems.

> [!NOTE]
>
> `reasoning.mode` is only supported by OpenAI GPT-5.6 and newer, when served by OpenAI or Azure. Amazon Bedrock's OpenAI-compatible API accepts the field but silently ignores it, so pro reasoning is not available on Bedrock — OpenRouter only routes pro requests to providers that honor mode selection.

For each supported model, there are two equivalent ways to request pro mode on OpenRouter:

1. Send `reasoning.mode: "pro"` with the standard model — OpenRouter reroutes the request to the matching `*-pro` model.
2. Call the `*-pro` model listing directly.

```json theme={null}
{
  "model": "~openai/gpt-sol-latest",
  "input": "Prove that there are infinitely many primes.",
  "reasoning": {
    "mode": "pro"
  }
}
```

> [!NOTE]
>
> * `mode` is independent of `effort`: you can combine `mode: "pro"` with any supported request-level effort. It cannot be combined with a [mid-conversation effort update](#mid-conversation-effort), which OpenAI does not accept on pro models, so that combination is rejected with a 400.
> * Pro mode bills at the same per-token rates as standard mode, but typically consumes more tokens.

## Reasoning with the Anthropic Messages API

Requests sent through the [Anthropic Messages API](https://openrouter.ai/docs/api/api-reference/anthropic-messages/create-a-message.md) control reasoning with Anthropic's native `thinking` and `output_config.effort` fields. OpenRouter normalizes both into the unified `reasoning` parameter, so they work on every reasoning model, not only Claude.

| Messages API request | Unified `reasoning` equivalent |
| - | - |
| `output_config: { effort }` | `reasoning: { effort }` |
| `thinking: { type: "enabled", budget_tokens }` | `reasoning: { max_tokens: budget_tokens }` |
| `thinking: { type: "adaptive" }` | `reasoning: { enabled: true }` |
| `thinking: { type: "disabled" }` | `reasoning: { enabled: false }` |

`output_config.effort` takes precedence over `thinking.type: "adaptive"`. Sending `thinking: { type: "adaptive" }` together with `output_config: { effort: "high" }` means high effort on every model. Claude receives both fields unchanged, while a model such as GPT-5 or MiniMax receives `reasoning_effort: "high"` in its own vocabulary, translated the same way as request-level `reasoning.effort`.

When `thinking: { type: "enabled", budget_tokens }` and `output_config.effort` are sent together, Claude receives both unchanged. The unified `reasoning` parameter accepts either `effort` or `max_tokens` but not both, so every other model receives `reasoning.effort` and the budget is not forwarded. Send only `thinking.budget_tokens` to control other models by token budget.

`thinking: { type: "adaptive" }` without an `output_config.effort` leaves the effort to the model. Claude runs its native adaptive thinking, and other models use their default reasoning effort, which the models endpoint reports as [`reasoning.default_effort`](#discovering-per-model-reasoning-options).

`thinking: { type: "disabled" }` disables reasoning even when an `output_config.effort` is also present. Claude still receives the `output_config.effort`, since Anthropic applies it to the whole response, and other models receive no reasoning effort.

> [!NOTE]
>
> OpenAI models expose two knobs, `reasoning.effort` and `text.verbosity`, and the Messages API request shape has one. `output_config.effort` maps to `reasoning.effort` only, and it is not sent as `text.verbosity`. Anthropic's `xhigh` and `max` levels stay reasoning efforts and are translated to the model's [supported reasoning efforts](#discovering-per-model-reasoning-options). To set OpenAI response verbosity, use the [`verbosity`](https://openrouter.ai/docs/api_reference/parameters#verbosity) parameter on the Chat Completions or Responses API.

## Changing Effort Mid-Conversation

Request-level effort applies to the whole conversation, so raising it for one hard turn and lowering it again on the next changes the request prefix and invalidates the prompt cache. Some models instead accept an effort change as an item in the conversation history. The change applies from that point onward and stays in effect until the next change, the preceding items are untouched, and the cache stays warm. Keep the item at the same position in every later request.

All three OpenRouter APIs expose this, each in the shape native to that API. The Chat Completions form is an OpenRouter extension, since OpenAI's own Chat Completions API has no per-message equivalent.

```json lines theme={null}
// Responses API
{
  "model": "anthropic/claude-fable-5.2",
  "reasoning": { "effort": "high" },
  "input": [
    { "role": "user", "content": "Plan the migration." },
    { "type": "message", "role": "assistant", "content": [{ "type": "output_text", "text": "Here's the plan: ..." }] },
    { "type": "configuration_update", "reasoning": { "effort": "low" } },
    { "role": "user", "content": "Now rename the config file." }
  ]
}
```

```json lines theme={null}
// Chat Completions
{
  "model": "anthropic/claude-fable-5.2",
  "reasoning": { "effort": "high" },
  "messages": [
    { "role": "user", "content": "Plan the migration." },
    { "role": "assistant", "content": "Here's the plan: ..." },
    { "role": "system", "content": "", "configuration_update": { "reasoning": { "effort": "low" } } },
    { "role": "user", "content": "Now rename the config file." }
  ]
}
```

```json lines theme={null}
// Anthropic Messages API
{
  "model": "anthropic/claude-fable-5.2",
  "max_tokens": 4096,
  "output_config": { "effort": "high" },
  "messages": [
    { "role": "user", "content": "Plan the migration." },
    { "role": "assistant", "content": "Here's the plan: ..." },
    { "role": "system", "content": [], "output_config": { "effort": "low" } },
    { "role": "user", "content": "Now rename the config file." }
  ]
}
```

The three forms are interchangeable: OpenRouter normalizes each into one internal representation and re-emits it in the form the selected provider accepts. A Responses `configuration_update` sent to a Claude model becomes a per-message `output_config`, and a Chat Completions or Messages API update sent to an OpenAI model becomes a Responses `configuration_update` item. The request-level effort (`reasoning.effort` or `output_config.effort`) is independent of the per-item updates and still sets the baseline for turns before the first update.

Effort values are translated to the target model's vocabulary the same way as request-level effort. Claude accepts `low`, `medium`, `high`, `xhigh`, and `max` (`minimal` is sent as `low`, `none` is rejected). OpenAI models accept the efforts listed in their [supported reasoning efforts](#discovering-per-model-reasoning-options), and an update with an effort the model does not support is rejected with a 400.

> [!NOTE]
>
> * Put the update directly before the user turn it should apply to, on a content-less system message (Chat Completions and Messages API) or a `configuration_update` item (Responses API). An update ahead of the first user turn is allowed; on Claude models it stays inline in `messages` while ordinary system text is still sent as the top-level `system` prompt, so a system message that carries both text and an update is split in two.
> * Do not place two updates next to each other. The first would apply to nothing; OpenAI rejects adjacent `configuration_update` items, and OpenRouter applies the same rule on every API so the three forms stay interchangeable.
> * An update after the last user turn is accepted and applies to the response generated by that request. Keep it in the same position in later requests so the cached prefix still matches.
> * Updates cannot be combined with `truncation: "auto"` in the Responses API, and on any API they cannot be combined with `reasoning.mode: "pro"` or sent to a pro model variant such as `openai/gpt-6-astra-pro`.
> * Mid-conversation effort updates are not accepted on the [Batch API](https://openrouter.ai/docs/batch-quickstart.md) and are rejected per line.

> [!NOTE]
>
> Support is per model and OpenRouter enables it as providers roll it out. Models that accept mid-conversation effort changes include Claude Fable 5.2, Claude Fable 5.1, Claude Opus 5, and the standard OpenAI GPT-6 models (Astra, Sol, Luna) and GPT-6.1 models (Sol, Terra; see the [GPT-6 migration guide](https://openrouter.ai/docs/cookbook/evaluate-and-optimize/model-migrations/gpt-6.md#mid-conversation-effort-with-configuration_update) for the pro-mode exclusion). Requests that use an update are routed only to endpoints that accept it, and a request for a model that does not support it is rejected with a 400 instead of being sent with the update silently dropped.

## Reasoning Details API Shape

This section documents the Chat Completions (`/api/v1/chat/completions`) response shape. On the Responses API, reasoning arrives as `reasoning` items in `output` instead; see [Basic Usage with Reasoning Tokens](#basic-usage-with-reasoning-tokens).

When reasoning models generate responses, the reasoning information is structured in a standardized format through the `reasoning_details` array. This section documents the API response structure for reasoning details in both streaming and non-streaming responses.

### reasoning\_details Array Structure

The `reasoning_details` field contains an array of reasoning detail objects. Each object in the array represents a specific piece of reasoning information and follows one of three possible types. The location of this array differs between streaming and non-streaming responses.

* **Non-streaming responses**: `reasoning_details` appears in `choices[].message.reasoning_details`
* **Streaming responses**: `reasoning_details` appears in `choices[].delta.reasoning_details` for each chunk

#### Common Fields

All reasoning detail objects share these common fields:

* `id` (string | null): Unique identifier for the reasoning detail
* `format` (string): The format of the reasoning detail, with possible values:
  * `"unknown"` - Format is not specified
  * `"openai-responses-v1"` - OpenAI responses format version 1
  * `"azure-openai-responses-v1"` - Azure OpenAI responses format version 1
  * `"bedrock-openai-responses-v1"` - Amazon Bedrock OpenAI responses format version 1
  * `"bedrock-xai-responses-v1"` - Amazon Bedrock xAI responses format version 1
  * `"xai-responses-v1"` - SpaceXAI responses format version 1
  * `"meta-responses-v1"` - Meta responses format version 1
  * `"google-vertex-meta-responses-v1"` - Meta on Google Vertex responses format version 1 (requests may still send the retired `"google-vertex-responses-v1"`, which maps to this value)
  * `"google-vertex-xai-responses-v1"` - xAI on Google Vertex responses format version 1
  * `"openrouter-stealth-v1"` - OpenRouter stealth model format version 1
  * `"anthropic-claude-v1"` - Anthropic Claude format version 1 (default)
  * `"google-gemini-v1"` - Google Gemini format version 1
* `index` (number, optional): Sequential index of the reasoning detail

#### Reasoning Detail Types

**1. Summary Type (`reasoning.summary`)**

Contains a high-level summary of the reasoning process:

```json lines theme={null}
{
  "type": "reasoning.summary",
  "summary": "The model analyzed the problem by first identifying key constraints, then evaluating possible solutions...",
  "id": "reasoning-summary-1",
  "format": "anthropic-claude-v1",
  "index": 0
}
```

**2. Encrypted Type (`reasoning.encrypted`)**

Contains encrypted reasoning data that may be redacted or protected:

```json lines theme={null}
{
  "type": "reasoning.encrypted",
  "data": "eyJlbmNyeXB0ZWQiOiJ0cnVlIiwiY29udGVudCI6IltSRURBQ1RFRF0ifQ==",
  "id": "reasoning-encrypted-1",
  "format": "anthropic-claude-v1",
  "index": 1
}
```

**3. Text Type (`reasoning.text`)**

Contains raw text reasoning with optional signature verification:

```json lines theme={null}
{
  "type": "reasoning.text",
  "text": "Let me think through this step by step:\n1. First, I need to understand the user's question...",
  "signature": "sha256:abc123def456...",
  "id": "reasoning-text-1",
  "format": "anthropic-claude-v1",
  "index": 2
}
```

### Response Examples

#### Non-Streaming Response

In non-streaming responses, `reasoning_details` appears in the message:

```json expandable lines theme={null}
{
  "choices": [
    {
      "message": {
        "role": "assistant",
        "content": "Based on my analysis, I recommend the following approach...",
        "reasoning_details": [
          {
            "type": "reasoning.summary",
            "summary": "Analyzed the problem by breaking it into components",
            "id": "reasoning-summary-1",
            "format": "anthropic-claude-v1",
            "index": 0
          },
          {
            "type": "reasoning.text",
            "text": "Let me work through this systematically:\n1. First consideration...\n2. Second consideration...",
            "signature": null,
            "id": "reasoning-text-1",
            "format": "anthropic-claude-v1",
            "index": 1
          }
        ]
      }
    }
  ]
}
```

#### Streaming Response

In streaming responses, `reasoning_details` appears in delta chunks as the reasoning is generated:

```json lines theme={null}
{
  "choices": [
    {
      "delta": {
        "reasoning_details": [
          {
            "type": "reasoning.text",
            "text": "Let me think about this step by step...",
            "signature": null,
            "id": "reasoning-text-1",
            "format": "anthropic-claude-v1",
            "index": 0
          }
        ]
      }
    }
  ]
}
```

**Streaming Behavior Notes:**

* Each reasoning detail chunk is sent as it becomes available
* The `reasoning_details` array in each chunk may contain one or more reasoning objects
* For encrypted reasoning, the content may appear as `[REDACTED]` in streaming responses
* The complete reasoning sequence is built by concatenating all chunks in order

## Legacy Parameters

For backward compatibility, Chat Completions (`/api/v1/chat/completions`) still accepts the following legacy parameters. The Responses API does not accept them:

* `include_reasoning: true` - Equivalent to `reasoning: {}`
* `include_reasoning: false` - Equivalent to `reasoning: { exclude: true }`

However, we recommend using the new unified `reasoning` parameter for better control and future compatibility.

## Provider-Specific Reasoning Implementation

### Anthropic Models with Reasoning Tokens

The latest Claude models, such as [`~anthropic/claude-sonnet-latest`](https://openrouter.ai/~anthropic/claude-sonnet-latest), support working with and returning reasoning tokens.

You can enable reasoning on Anthropic models **only** using the unified `reasoning` parameter with either `effort` or `max_tokens`.

#### Reasoning Max Tokens for Anthropic Models

When using Anthropic models with reasoning:

* When using the `reasoning.max_tokens` parameter, that value is used directly with a minimum of 1024 tokens.
* When using the `reasoning.effort` parameter, the budget\_tokens are calculated based on the request's `max_output_tokens` value (`max_tokens` on Chat Completions).

The reasoning token allocation is capped at 128,000 tokens maximum and 1024 tokens minimum. The formula for calculating the budget\_tokens is: `budget_tokens = max(min(max_output_tokens * {effort_ratio}, 128000), 1024)`

effort\_ratio is 0.95 for max and xhigh effort, 0.8 for high effort, 0.5 for medium effort, 0.2 for low effort, and 0.1 for minimal effort.

**Important**: `max_output_tokens` must be strictly higher than the reasoning budget to ensure there are tokens available for the final response after thinking.

> [!NOTE]
>
> **Token Usage and Billing**
>
> Reasoning tokens are counted as output tokens for billing purposes. Using reasoning tokens will increase your token usage but can significantly improve the quality of model responses.

#### Summarized Thinking

For Claude models that support the `thinking.display` field, OpenRouter defaults to **summarized thinking** (`thinking.display: 'summarized'`), so you don't lose the reasoning trace on newer models where Anthropic omits the thinking by default.

The `display` setting only controls the visible thinking trace in the response. The model consumes the same number of tokens either way, and usage is billed based on the tokens the model actually generates. Because the visible summary is condensed, it may contain fewer tokens than the reasoning token count reported in `usage`.

If you're using the Anthropic Messages API format directly, you can control this with `thinking.display`:

* **`'summarized'`** (default): A condensed summary of the reasoning is returned
* **`'omitted'`**: No thinking trace is returned

#### Example: Streaming with Anthropic Reasoning Tokens

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

client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key="<OPENROUTER_API_KEY>",
)

def response_with_reasoning(input):
    return client.responses.create(
        model="~anthropic/claude-sonnet-latest",
        input=input,
        max_output_tokens=10000,
        extra_body={
            "reasoning": {
                "max_tokens": 8000
            }
        },
        stream=True
    )

for event in response_with_reasoning("What's bigger, 9.9 or 9.11?"):
    if event.type in {
        "response.reasoning_text.delta",
        "response.reasoning_summary_text.delta",
    }:
        print(f"REASONING: {event.delta}")
    elif event.type == "response.output_text.delta":
        print(f"CONTENT: {event.delta}")
```

```typescript TypeScript expandable lines theme={null}
import OpenAI from 'openai';

const openai = new OpenAI({
  baseURL: 'https://openrouter.ai/api/v1',
  apiKey: '<OPENROUTER_API_KEY>',
});

async function responseWithReasoning(input: string) {
  return openai.responses.create({
    model: '~anthropic/claude-sonnet-latest',
    input,
    max_output_tokens: 10000,
    reasoning: {
      // @ts-expect-error max_tokens is an OpenRouter extension
      max_tokens: 8000,
    },
    stream: true,
  });
}

(async () => {
  for await (const event of await responseWithReasoning("What's bigger, 9.9 or 9.11?")) {
    if (
      event.type === 'response.reasoning_text.delta' ||
      event.type === 'response.reasoning_summary_text.delta'
    ) {
      console.log(`REASONING: ${event.delta}`);
    } else if (event.type === 'response.output_text.delta') {
      console.log(`CONTENT: ${event.delta}`);
    }
  }
})();
```

```go title="Go" lines theme={null}
package main

import (
	"bufio"
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"strings"
)

func main() {
	body, _ := json.Marshal(map[string]any{
		"model":             "~anthropic/claude-sonnet-latest",
		"input":             "What's bigger, 9.9 or 9.11?",
		"max_output_tokens": 10000,
		"reasoning":         map[string]any{"max_tokens": 8000},
		"stream":            true,
	})
	req, _ := http.NewRequest("POST", "https://openrouter.ai/api/v1/responses", bytes.NewReader(body))
	req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENROUTER_API_KEY"))
	req.Header.Set("Content-Type", "application/json")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		raw, _ := io.ReadAll(resp.Body)
		log.Fatalf("HTTP %d: %s", resp.StatusCode, raw)
	}

	scanner := bufio.NewScanner(resp.Body)
	scanner.Buffer(make([]byte, 1024*1024), 1024*1024)
	for scanner.Scan() {
		data, ok := strings.CutPrefix(scanner.Text(), "data: ")
		if !ok || data == "[DONE]" {
			continue
		}
		var event struct{ Type, Delta string }
		if json.Unmarshal([]byte(data), &event) != nil {
			continue
		}
		switch event.Type {
		case "response.reasoning_text.delta", "response.reasoning_summary_text.delta":
			fmt.Printf("REASONING: %s\n", event.Delta)
		case "response.output_text.delta":
			fmt.Printf("CONTENT: %s\n", event.Delta)
		}
	}
	if err := scanner.Err(); err != nil {
		log.Fatal(err)
	}
}

```

```bash title="cURL" lines theme={null}
curl -sSN https://openrouter.ai/api/v1/responses \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "~anthropic/claude-sonnet-latest",
    "input": "What'\''s bigger, 9.9 or 9.11?",
    "max_output_tokens": 10000,
    "reasoning": {"max_tokens": 8000},
    "stream": true
  }' |
  jq -rR --unbuffered 'select(startswith("data: ")) | .[6:] | try fromjson catch empty |
    if .type == "response.reasoning_text.delta" or .type == "response.reasoning_summary_text.delta" then "REASONING: \(.delta)"
    elif .type == "response.output_text.delta" then "CONTENT: \(.delta)"
    else empty end'

```

```text title="Output" theme={null}
CONTENT: **9.9 is big
CONTENT: ger than
CONTENT:  9.11.**

To
CONTENT:  compare them,
CONTENT:  give
CONTENT:  both
CONTENT:  numbers the same number
CONTENT:  of decimal places:

-
CONTENT:  9.9 =
CONTENT:  9.90
- 9
CONTENT: .11 = 9.11
CONTENT: 

Since 
CONTENT: 90
CONTENT:  h
CONTENT: undredths is more
CONTENT:  than 11 hundredths
CONTENT: , 9.90
CONTENT:  > 9.11.
CONTENT: 

People
CONTENT:  often get
CONTENT:  this
CONTENT:  wrong because they
CONTENT:  read
CONTENT:  "
CONTENT: 11
CONTENT: " as b
CONTENT: igger than "9",
CONTENT:  as
CONTENT:  if the
CONTENT:  decimals were wh
CONTENT: ole numbers.
```

### Google Gemini 3 Models with Thinking Levels

Gemini 3 models (such as [google/gemini-3.1-pro-preview](https://openrouter.ai/google/gemini-3.1-pro-preview) and [google/gemini-3-flash-preview](https://openrouter.ai/google/gemini-3-flash-preview)) use Google's `thinkingLevel` API instead of the older `thinkingBudget` API used by Gemini 2.5 models.

OpenRouter maps the `reasoning.effort` parameter directly to Google's `thinkingLevel` values:

| OpenRouter `reasoning.effort` | Google `thinkingLevel` |
| - | - |
| `"minimal"` | `"minimal"` |
| `"low"` | `"low"` |
| `"medium"` | `"medium"` |
| `"high"` | `"high"` |
| `"xhigh"` | `"high"` (mapped down) |

> [!NOTE]
>
> **Token Consumption is Determined by Google**
>
> When using `thinkingLevel`, the actual number of reasoning tokens consumed is determined internally by Google. There are no publicly documented token limit breakpoints for each level. For example, setting `effort: "low"` might result in several hundred reasoning tokens depending on the complexity of the task. This is expected behavior and reflects how Google implements thinking levels internally.

If a model doesn't support a specific effort level (for example, if a model only supports `low` and `high`), OpenRouter will map your requested effort to the nearest supported level.

#### Using max\_tokens with Gemini 3

If you specify `reasoning.max_tokens` explicitly, OpenRouter will pass it through as `thinkingBudget` to Google's API. However, for Gemini 3 models, Google internally maps this budget value to a `thinkingLevel`, so you will not get precise token control. The actual token consumption is still determined by Google's thinkingLevel implementation, not by the specific budget value you provide.

#### Example: Using Thinking Levels with Gemini 3

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

client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key="<OPENROUTER_API_KEY>",
)

response = client.responses.create(
    model="google/gemini-3.1-pro-preview",
    input="Explain the implications of quantum entanglement.",
    reasoning={
        "effort": "low"  # Maps to thinkingLevel: "low"
    },
)

for item in response.output:
    if item.type == "reasoning":
        print("REASONING:", "".join(part.text for part in item.content or []))
print("CONTENT:", response.output_text)
```

```typescript TypeScript expandable lines theme={null}
import OpenAI from 'openai';

const openai = new OpenAI({
  baseURL: 'https://openrouter.ai/api/v1',
  apiKey: '<OPENROUTER_API_KEY>',
});

async function getResponseWithThinkingLevel() {
  const response = await openai.responses.create({
    model: 'google/gemini-3.1-pro-preview',
    input: 'Explain the implications of quantum entanglement.',
    reasoning: {
      effort: 'low', // Maps to thinkingLevel: "low"
    },
  });

  for (const item of response.output) {
    if (item.type === 'reasoning') {
      const parts = item.content?.length ? item.content : item.summary;
      console.log('REASONING:', parts?.map((part) => part.text).join(''));
    }
  }
  console.log('CONTENT:', response.output_text);
}

getResponseWithThinkingLevel();

```

```go title="Go" lines theme={null}
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"strings"
)

type part struct{ Type, Text string }

func main() {
	body, _ := json.Marshal(map[string]any{
		"model":     "google/gemini-3.1-pro-preview",
		"input":     "Explain the implications of quantum entanglement.",
		"reasoning": map[string]any{"effort": "low"}, // Maps to thinkingLevel: "low"
	})
	req, _ := http.NewRequest("POST", "https://openrouter.ai/api/v1/responses", bytes.NewReader(body))
	req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENROUTER_API_KEY"))
	req.Header.Set("Content-Type", "application/json")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	raw, _ := io.ReadAll(resp.Body)
	if resp.StatusCode != http.StatusOK {
		log.Fatalf("HTTP %d: %s", resp.StatusCode, raw)
	}

	var response struct {
		Output []struct {
			Type             string
			Content, Summary []part
		}
	}
	if err := json.Unmarshal(raw, &response); err != nil {
		log.Fatal(err)
	}

	var content strings.Builder
	for _, item := range response.Output {
		switch item.Type {
		case "reasoning":
			parts := item.Content
			if len(parts) == 0 {
				parts = item.Summary
			}
			var text strings.Builder
			for _, p := range parts {
				text.WriteString(p.Text)
			}
			fmt.Println("REASONING:", text.String())
		case "message":
			for _, p := range item.Content {
				if p.Type == "output_text" {
					content.WriteString(p.Text)
				}
			}
		}
	}
	fmt.Println("CONTENT:", content.String())
}

```

```bash title="cURL" lines theme={null}
curl -sS https://openrouter.ai/api/v1/responses \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "google/gemini-3.1-pro-preview",
    "input": "Explain the implications of quantum entanglement.",
    "reasoning": {"effort": "low"}
  }' |
  jq -r '(.output[] | select(.type == "reasoning") |
      "REASONING: " + ((.content // []) as $c | (if ($c | length) > 0 then $c else (.summary // []) end) | map(.text) | join(""))),
    "CONTENT: " + ([.output[] | select(.type == "message") | .content[]? | select(.type == "output_text") | .text] | join(""))'

```

```text title="Output" theme={null}
REASONING: **Exploring Entanglement's Impact**

I'm currently delving into the profound implications of quantum entanglement. My focus is on understanding how this phenomenon challenges classical notions of reality and opens doors to revolutionary technologies like quantum computing and secure communication.

**Deepening Entanglement Understanding**

I'm currently refining my grasp on quantum entanglement's philosophical weight, particularly how it dismantles local realism. My attention is shifting towards sketching out the core definitions and analogies that best convey this "spooky action" to an expert audience.

**Formulating Quantum Concepts**

I'm solidifying my explanations of how entanglement dismantles local realism, clarifying its relationship with the speed of light and the non-fundamental nature of space. I'm also starting to detail its potential in quantum computing and QKD.


REASONING: 
CONTENT: Quantum entanglement is one of the most bizarre and fascinating phenomena in physics. Albert Einstein famously called it "spooky action at a distance." It occurs when two or more particles become linked in such a way that the state of one particle instantly determines the state of the other, no matter how far apart they are—even if they are on opposite sides of the universe.

The implications of quantum entanglement stretch across fundamental physics, philosophy, and revolutionary new technologies. Here is a breakdown of what this phenomenon means for our understanding of the universe and our future.

---

### 1. Fundamental Physics and Philosophical Implications

**The Death of "Local Realism"**
For centuries, classical physics relied on two common-sense assumptions:
*   **Locality:** An object is only directly influenced by its immediate surroundings. Information cannot travel faster than the speed of light.
*   **Realism:** Objects have definite properties (like position or spin) even when no one is looking at them.
Quantum entanglement, proven by experiments testing **Bell’s Theorem**, shows that the universe does not obey local realism. Particles do not have a definite state until they are measured, and measuring one instantly dictates the state of its entangled partner. This suggests the universe is fundamentally interconnected in ways we cannot perceive.

**Rethinking Space and Time**
Because entangled particles affect each other instantaneously across vast distances, it challenges our traditional understanding of space. Some modern physicists propose that entanglement might be the fundamental "glue" that creates spacetime itself. A prominent theory in theoretical physics, known as **ER=EPR**, suggests that quantum entanglement and wormholes are essentially the same thing, linking the microscopic quantum world with the macroscopic world of gravity.

**No Faster-Than-Light Communication**
A common misconception is that entanglement allows us to send messages faster than light, which would violate Einstein’s theory of relativity. However, because the outcome of a quantum measurement is random, you cannot control *what* state the particle will take. Therefore, you cannot use it to transmit a Morse code-like message. The correlation is instantaneous, but useful *communication* still requires a classical signal (like a laser or radio wave) traveling at the speed of light.

---

### 2. Technological Implications (The Quantum Revolution)

While the philosophy of entanglement is mind-bending, its practical applications are currently driving a multi-billion-dollar technological revolution known as **Quantum Information Science**.
```
