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

# Text Generation

> Generate text with callModel using various input formats and model configurations. Supports multiple consumption patterns including text, streaming, and structured output.

## Basic Usage

The simplest way to generate text:

```typescript lines theme={null}
import { OpenRouter, callModel } from '@openrouter/agent';

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

const result = callModel(openrouter, {
  model: 'openai/gpt-5-nano',
  input: 'Explain quantum computing in one sentence.',
});

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

```

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

from openrouter_agent import OpenRouter, call_model


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

    result = call_model(
        openrouter,
        {
            "model": "openai/gpt-5-nano",
            "input": "Explain quantum computing in one sentence.",
        },
    )

    text = await result.get_text()
    print(text)


asyncio.run(main())

```

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

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

func main() {
	body, _ := json.Marshal(map[string]any{
		"model": "openai/gpt-5-nano",
		"input": "Explain quantum computing in one sentence.",
	})

	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 {
		log.Fatalf("unexpected status: %s", resp.Status)
	}

	var result struct {
		Output []struct {
			Type    string `json:"type"`
			Content []struct {
				Type string `json:"type"`
				Text string `json:"text"`
			} `json:"content"`
		} `json:"output"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		log.Fatal(err)
	}

	text := ""
	for _, item := range result.Output {
		if item.Type != "message" {
			continue
		}
		for _, c := range item.Content {
			if c.Type == "output_text" {
				text += c.Text
			}
		}
	}
	fmt.Println(text)
}

```

```bash title="cURL" lines theme={null}
curl -s https://openrouter.ai/api/v1/responses \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-5-nano",
    "input": "Explain quantum computing in one sentence."
  }' | jq -r '.output[] | select(.type == "message") | .content[] | select(.type == "output_text") | .text'

```

```text title="Output" theme={null}
Quantum computing uses quantum bits (qubits) that can be in superposition and entangled, enabling quantum processors to explore many possibilities simultaneously and solve certain problems more efficiently than classical computers.
```

## Input Formats

callModel accepts several input formats to match your use case.

### String Input

The simplest format - a single string becomes a user message:

```typescript lines theme={null}
const result = callModel(openrouter, {
  model: 'openai/gpt-5-nano',
  input: 'What is the speed of light?',
});
```

```python title="Python" lines theme={null}
result = call_model(
    openrouter,
    {
        "model": "openai/gpt-5-nano",
        "input": "What is the speed of light?",
    },
)

```

```go title="Go" lines theme={null}
body, _ := json.Marshal(map[string]any{
	"model": "openai/gpt-5-nano",
	"input": "What is the speed of light?",
})

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)
```

```bash title="cURL" lines theme={null}
result=$(curl -s https://openrouter.ai/api/v1/responses \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-5-nano",
    "input": "What is the speed of light?"
  }')
```

```bash title="cURL" lines theme={null}
result=$(curl -s https://openrouter.ai/api/v1/responses \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-5-nano",
    "input": "What is the speed of light?"
  }')
```

### Message Array

For multi-turn conversations, pass an array of messages:

```typescript lines theme={null}
import { OpenRouter, callModel } from '@openrouter/agent';

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

const result = callModel(openrouter, {
  model: 'openai/gpt-5-nano',
  input: [
    { role: 'user', content: 'My name is Alice.' },
    { role: 'assistant', content: 'Hello Alice! How can I help you today?' },
    { role: 'user', content: 'What is my name?' },
  ],
});

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

```

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

from openrouter_agent import OpenRouter, call_model


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

    result = call_model(
        openrouter,
        {
            "model": "openai/gpt-5-nano",
            "input": [
                {"role": "user", "content": "My name is Alice."},
                {"role": "assistant", "content": "Hello Alice! How can I help you today?"},
                {"role": "user", "content": "What is my name?"},
            ],
        },
    )

    text = await result.get_text()
    print(text)


asyncio.run(main())

```

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

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

func main() {
	body, _ := json.Marshal(map[string]any{
		"model": "openai/gpt-5-nano",
		"input": []map[string]string{
			{"role": "user", "content": "My name is Alice."},
			{"role": "assistant", "content": "Hello Alice! How can I help you today?"},
			{"role": "user", "content": "What is my name?"},
		},
	})

	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 {
		log.Fatalf("unexpected status: %s", resp.Status)
	}

	var result struct {
		Output []struct {
			Type    string `json:"type"`
			Content []struct {
				Type string `json:"type"`
				Text string `json:"text"`
			} `json:"content"`
		} `json:"output"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		log.Fatal(err)
	}

	text := ""
	for _, item := range result.Output {
		if item.Type != "message" {
			continue
		}
		for _, c := range item.Content {
			if c.Type == "output_text" {
				text += c.Text
			}
		}
	}
	fmt.Println(text)
}

```

```bash title="cURL" lines theme={null}
curl -s https://openrouter.ai/api/v1/responses \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-5-nano",
    "input": [
      { "role": "user", "content": "My name is Alice." },
      { "role": "assistant", "content": "Hello Alice! How can I help you today?" },
      { "role": "user", "content": "What is my name?" }
    ]
  }' | jq -r '.output[] | select(.type == "message") | .content[] | select(.type == "output_text") | .text'

```

```text title="Output" theme={null}
Your name is Alice. Would you like me to call you something else or stick with that?
```

### Multimodal

For rich content including images:

```typescript lines theme={null}
import { OpenRouter, callModel } from '@openrouter/agent';

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

const result = callModel(openrouter, {
  model: 'openai/gpt-5.2',
  input: [
    {
      type: 'message',
      role: 'user',
      content: [
        { type: 'input_text', text: 'What is in this image?' },
        {
          type: 'input_image',
          imageUrl: 'https://openrouter.ai/docs/assets/guides/ori/ori-codex-poster.jpg',
          detail: 'auto',
        },
      ],
    },
  ],
});

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

```

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

from openrouter_agent import OpenRouter, call_model


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

    result = call_model(
        openrouter,
        {
            "model": "openai/gpt-5.2",
            "input": [
                {
                    "type": "message",
                    "role": "user",
                    "content": [
                        {"type": "input_text", "text": "What is in this image?"},
                        {
                            "type": "input_image",
                            "image_url": "https://openrouter.ai/docs/assets/guides/ori/ori-codex-poster.jpg",
                            "detail": "auto",
                        },
                    ],
                },
            ],
        },
    )

    text = await result.get_text()
    print(text)


asyncio.run(main())

```

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

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

func main() {
	body, _ := json.Marshal(map[string]any{
		"model": "openai/gpt-5.2",
		"input": []map[string]any{
			{
				"type": "message",
				"role": "user",
				"content": []map[string]any{
					{"type": "input_text", "text": "What is in this image?"},
					{
						"type":      "input_image",
						"image_url": "https://openrouter.ai/docs/assets/guides/ori/ori-codex-poster.jpg",
						"detail":    "auto",
					},
				},
			},
		},
	})

	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 {
		log.Fatalf("unexpected status: %s", resp.Status)
	}

	var result struct {
		Output []struct {
			Type    string `json:"type"`
			Content []struct {
				Type string `json:"type"`
				Text string `json:"text"`
			} `json:"content"`
		} `json:"output"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		log.Fatal(err)
	}

	text := ""
	for _, item := range result.Output {
		if item.Type != "message" {
			continue
		}
		for _, c := range item.Content {
			if c.Type == "output_text" {
				text += c.Text
			}
		}
	}
	fmt.Println(text)
}

```

```bash title="cURL" lines theme={null}
curl -s https://openrouter.ai/api/v1/responses \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-5.2",
    "input": [
      {
        "type": "message",
        "role": "user",
        "content": [
          { "type": "input_text", "text": "What is in this image?" },
          {
            "type": "input_image",
            "image_url": "https://openrouter.ai/docs/assets/guides/ori/ori-codex-poster.jpg",
            "detail": "auto"
          }
        ]
      }
    ]
  }' | jq -r '.output[] | select(.type == "message") | .content[] | select(.type == "output_text") | .text'

```

```text title="Output" theme={null}
The image is a promotional graphic for **“Ori Codex”** by **openrouter**. It shows the text “Ori Codex” on a dark rounded rectangle, with an install command underneath:

`curl -fsSL https://openrouter.ai/labs/ori/install.sh | bash`
```

## System Instructions

Set the model's behavior with the `instructions` parameter:

```typescript lines theme={null}
import { OpenRouter, callModel } from '@openrouter/agent';

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

const result = callModel(openrouter, {
  model: 'openai/gpt-5-nano',
  instructions: 'You are a helpful coding assistant. Be concise and provide working code examples.',
  input: 'How do I read a file in Node.js?',
});

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

```

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

from openrouter_agent import OpenRouter, call_model


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

    result = call_model(
        openrouter,
        {
            "model": "openai/gpt-5-nano",
            "instructions": "You are a helpful coding assistant. Be concise and provide working code examples.",
            "input": "How do I read a file in Node.js?",
        },
    )

    text = await result.get_text()
    print(text)


asyncio.run(main())

```

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

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

func main() {
	body, _ := json.Marshal(map[string]any{
		"model":        "openai/gpt-5-nano",
		"instructions": "You are a helpful coding assistant. Be concise and provide working code examples.",
		"input":        "How do I read a file in Node.js?",
	})

	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 {
		log.Fatalf("unexpected status: %s", resp.Status)
	}

	var result struct {
		Output []struct {
			Type    string `json:"type"`
			Content []struct {
				Type string `json:"type"`
				Text string `json:"text"`
			} `json:"content"`
		} `json:"output"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		log.Fatal(err)
	}

	text := ""
	for _, item := range result.Output {
		if item.Type != "message" {
			continue
		}
		for _, c := range item.Content {
			if c.Type == "output_text" {
				text += c.Text
			}
		}
	}
	fmt.Println(text)
}

```

```bash title="cURL" lines theme={null}
curl -s https://openrouter.ai/api/v1/responses \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-5-nano",
    "instructions": "You are a helpful coding assistant. Be concise and provide working code examples.",
    "input": "How do I read a file in Node.js?"
  }' | jq -r '.output[] | select(.type == "message") | .content[] | select(.type == "output_text") | .text'

```

```text title="Output" theme={null}
You can read files in Node.js using the built-in fs module. Here are common approaches.

1) Async read with callback (typical in old code)
const fs = require('fs');
const path = require('path');
const filePath = path.join(__dirname, 'example.txt');

fs.readFile(filePath, 'utf8', (err, data) => {
  if (err) {
    console.error('Error reading file:', err);
    return;
  }
  console.log(data);
});

2) Sync read (blocking, not for server code)
try {
  const data = require('fs').readFileSync(filePath, 'utf8');
  console.log(data);
} catch (err) {
  console.error(err);
}

3) Promise-based (modern, async/await)
const { promises: fsPromises } = require('fs');
const path = require('path');
const filePath = path.join(__dirname, 'example.txt');

async function readFileAsync() {
  try {
    const data = await fsPromises.readFile(filePath, 'utf8');
    console.log(data);
  } catch (err) {
    console.error('Error reading file:', err);
  }
}
readFileAsync();

4) Read as binary (Buffer) if you omit encoding
fs.readFile(filePath, (err, data) => {
```

## Model Selection

### Single Model

Specify a model by its OpenRouter ID:

```typescript lines theme={null}
const result = openrouter.callModel({
  model: 'anthropic/claude-sonnet-4.5',
  input: 'Hello!',
});
```

```python title="Python" lines theme={null}
result = call_model(
    openrouter,
    {
        "model": "anthropic/claude-sonnet-4.5",
        "input": "Hello!",
    },
)
```

```go title="Go" lines theme={null}
body, _ := json.Marshal(map[string]any{
	"model": "anthropic/claude-sonnet-4.5",
	"input": "Hello!",
})

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)
```

```bash title="cURL" lines theme={null}
result=$(curl -s https://openrouter.ai/api/v1/responses \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "anthropic/claude-sonnet-4.5",
    "input": "Hello!"
  }')
```

```bash title="cURL" lines theme={null}
result=$(curl -s https://openrouter.ai/api/v1/responses \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "anthropic/claude-sonnet-4.5",
    "input": "Hello!"
  }')
```

### Model Fallback

Provide multiple models for automatic fallback:

```typescript lines theme={null}
const result = callModel(openrouter, {
  models: ['anthropic/claude-sonnet-4.5', 'openai/gpt-5.2'],
  input: 'Hello!',
});
```

```python title="Python" lines theme={null}
result = call_model(
    openrouter,
    {
        "models": ["anthropic/claude-sonnet-4.5", "openai/gpt-5.2"],
        "input": "Hello!",
    },
)
```

```go title="Go" lines theme={null}
body, _ := json.Marshal(map[string]any{
	"models": []string{"anthropic/claude-sonnet-4.5", "openai/gpt-5.2"},
	"input":  "Hello!",
})

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)
```

```bash title="cURL" lines theme={null}
result=$(curl -s https://openrouter.ai/api/v1/responses \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "models": ["anthropic/claude-sonnet-4.5", "openai/gpt-5.2"],
    "input": "Hello!"
  }')
```

```bash title="cURL" lines theme={null}
result=$(curl -s https://openrouter.ai/api/v1/responses \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "models": ["anthropic/claude-sonnet-4.5", "openai/gpt-5.2"],
    "input": "Hello!"
  }')
```

The SDK will try each model in order until one succeeds.

## Response Methods

### getText()

Returns just the text content after tool execution completes:

```typescript lines theme={null}
import { OpenRouter } from '@openrouter/sdk';
import { callModel } from '@openrouter/agent';

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

const result = callModel(openrouter, {
  model: 'openai/gpt-5-nano',
  input: 'What is the speed of light?',
});

const text = await result.getText();
console.log(text); // "The speed of light is approximately 299,792 km/s."

```

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

from openrouter_agent import OpenRouter, call_model


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

    result = call_model(
        openrouter,
        {
            "model": "openai/gpt-5-nano",
            "input": "What is the speed of light?",
        },
    )

    text = await result.get_text()
    print(text)  # "The speed of light is approximately 299,792 km/s."


asyncio.run(main())

```

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

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

func main() {
	body, _ := json.Marshal(map[string]any{
		"model": "openai/gpt-5-nano",
		"input": "What is the speed of light?",
	})

	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 {
		log.Fatalf("unexpected status: %s", resp.Status)
	}

	var result struct {
		Output []struct {
			Type    string `json:"type"`
			Content []struct {
				Type string `json:"type"`
				Text string `json:"text"`
			} `json:"content"`
		} `json:"output"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		log.Fatal(err)
	}

	text := ""
	for _, item := range result.Output {
		if item.Type != "message" {
			continue
		}
		for _, c := range item.Content {
			if c.Type == "output_text" {
				text += c.Text
			}
		}
	}
	fmt.Println(text) // "The speed of light is approximately 299,792 km/s."
}

```

```bash title="cURL" lines theme={null}
curl -s https://openrouter.ai/api/v1/responses \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-5-nano",
    "input": "What is the speed of light?"
  }' | jq -r '.output[] | select(.type == "message") | .content[] | select(.type == "output_text") | .text'

```

```text title="Output" theme={null}
In vacuum, the speed of light is exactly 299,792,458 meters per second (about 3.0 × 10^8 m/s). This is a defined constant, denoted c.

In other media, light travels slower: v = c / n, where n is the refractive index of the material (e.g., in air it's about 0.03% slower, in water roughly 0.75 c). If you’d like, I can give speeds in specific materials.
```

### getResponse()

Returns the full response object including usage data:

```typescript lines theme={null}
const response = await result.getResponse();

console.log(response.output);     // Full output array
console.log(response.usage);      // Token usage information

// Usage includes:
// - inputTokens: tokens in the prompt
// - outputTokens: tokens generated
// - cachedTokens: tokens served from cache (cost savings)
```

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

from openrouter_agent import OpenRouter, call_model


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

    result = call_model(
        openrouter,
        {
            "model": "openai/gpt-5-nano",
            "input": "What is the speed of light?",
        },
    )

    response = await result.get_response()

    print(response.output)  # Full output array
    print(response.usage)  # Token usage information

    # Usage includes:
    # - input_tokens: tokens in the prompt
    # - output_tokens: tokens generated
    # - input_tokens_details.cached_tokens: tokens served from cache (cost savings)


asyncio.run(main())

```

```go title="Go" lines theme={null}
if resp.StatusCode != http.StatusOK {
	log.Fatalf("unexpected status: %s", resp.Status)
}

var response struct {
	Output json.RawMessage `json:"output"`
	Usage  json.RawMessage `json:"usage"`
}
if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
	log.Fatal(err)
}

fmt.Println(string(response.Output)) // Full output array
fmt.Println(string(response.Usage))  // Token usage information

// Usage includes:
// - input_tokens: tokens in the prompt
// - output_tokens: tokens generated
// - input_tokens_details.cached_tokens: tokens served from cache (cost savings)
```

```bash title="cURL" lines theme={null}
echo "$result" | jq '.output'   # Full output array
echo "$result" | jq '.usage'    # Token usage information

# Usage includes:
# - input_tokens: tokens in the prompt
# - output_tokens: tokens generated
# - input_tokens_details.cached_tokens: tokens served from cache (cost savings)
```

```bash title="cURL" lines theme={null}
echo "$result" | jq '.output'  # Full output array
echo "$result" | jq '.usage'   # Token usage information

# Usage includes:
# - input_tokens: tokens in the prompt
# - output_tokens: tokens generated
# - input_tokens_details.cached_tokens: tokens served from cache (cost savings)
```

```text title="Output" theme={null}
[OutputReasoningItem(id='rs_0833bf1a925fc483016afcb8f6465c87d1bbbdf95216daa364', summary=[ReasoningSummaryText(text="**Explaining the speed of light**\n\nI need to respond to the question, “What is the speed of light?” The speed of light in a vacuum is approximately 299,792,458 meters per second (m/s), often denoted as c. In a vacuum, it’s defined exactly as this value, unlike in other media where it's slower.\n\nFor practical purposes, I could mention it's about 3.00 x 10^8 m/s, which is roughly 299,792 km/s or 186,282 mi/s. Importantly, nothing travels faster than c in a vacuum, and this speed is constant across all inertial frames.**Clarifying the speed of light**\n\nThe speed of light in a vacuum, denoted as c, is exactly 299,792,458 meters per second. This value is defined as such. In other media, light travels slower, and the speed depends on the refractive index, following the equation v = c/n.\n\nImportantly, in the realm of relativity, nothing can travel faster than c, making it the universal speed limit. For context, that's about 186,282 miles per second. I’ll keep it concise and straightforward!", type='summary_text')], type='reasoning', content=Unset(), encrypted_content='gAAAAABq_Lj6USbY0uOUx2_4iREHWxGeHsfV7i0h-mIZM1oWsC-y4k2q7GndtB1ZLhN7tCucg394Mta1O5i4bBHfgCnAHJ3FThiJKJf8Eqgq81EzoQTHE9S1-c8X9HArx_aWneJrJVDWEETtAX1citIF3z3heolGbsibEpQ5hBxd_XJuFDe90QqfbSX_G_cwPz7obmeusqTcbOSpU34LlSgV4iTix6rb_yz1EgnnmLbvzCQnzWDhP7H0K7MC6fOthTSLWd8SncFD-IYXvWjO43plm2H9-FLM3k9fzUGSzVz9sGmEdweUnjOZH7ivVK-dd3icOK05chMRm5-IWOEzJd7t_SC032BwdIfwaoDqyQAYXdutsHnuoXZx5-6i1JIilP6QwMU5vlHIIdyOMMTJrIJxWdqEfTIXg_cLIICnT57b_5a6nawitAN8KG7pebwSCawb2RzW7sIZb53madMI3yVwNMlOssT6lp4SsOgHls-Nno_2qzp_8OtijXK0hwtNyaHYoSj1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RX5aNfub4dbWNruTse9Gnd9WSz-GNiPlilA1tpLUuNQmuzAcFm2PRpOMiFlkoTfj1xtcYN7TNBRG5ptf-9UiaaW_S9QRN7XRPHazPiSk3UqllANurvx0z30vBEIPo-_dNKIdKB2KMVMSM1RU-7lckmU-RmthNe5Lpsz5JoF5LHmIutswtREsBIKvx2kNWCN0TlITwIkzPH56Z1ScZwRXeUeppNTFGZbQ02KzIvW74P-qI9QD7sABLnio443lMRdY34kfSC40n6YmM10qPhPPkBS1FFv0r6CgCelZ2xeJ6uf_Jw8t0geoZXAPnxU3nQ1IOflm3On71parFcIXJUvxPlHN8ELvfm6RJQxVd_4l6DEpmwUJG3In6XXcZ3YKTHnq-mLNpqNcSvRW21l3bPlzHhgqzB2UglKlDK_DPzs606B6oFyTNp05dbKkQOCu5S4T0iOyeVcZ52Ck6b1WQIXNGcrcwDPfWuLYEfv6c4JE6ptSoIenTkow8ddctgkz15DWa3jEkvYJh7WPs5x43VHtEB3RInnwYrKWneVcs44vsbmqgM3f_JxZX43VmFvGaC3FBBHrPbvU4qrsg5u1zQy7SnH6-rGI4oPn-pbH-c1NYQ8dfq2HJwZdYet4PI13R6fOkWgbT_b-NEd64Hy-nzg30o2GsAIb37YH3mtMbTk_rGXN9_tsLgu2lcWjUes9P2z8FaUFuMqo-cltTIlFHLcDNhQ3HojX5d39ia5NQ9EkoUOAGjdJW5J7hJ03uenv6XvuB1JqKXgwS7qwz5muQdB9VvAoh60UxasOh8aBsVY_DpYLCYOQCWij13TskRYxQDK0tJRmag8zoRNf_Jtr-buI9Hd7WQACeproaOa0sUDHNZjmfNCGy40e_bDRtVk1ya1xNiI6PXruoLlePBqAKTUiqjLxc9QFxyO2TjrrvKMRZZyBdbMUQv7Z-0bttFlQhwz5faXy7vDWV3TMCLBUopZphncZvI6TyNoR.eyJlbmRwb2ludF9zbHVnIjoib3BlbmFpL2dwdC01LW5hbm8tMjAyNS0wOC0wN3xvcGVuYWkifQ', status='completed', format_='openai-responses-v1', signature=Unset()), OutputMessageItem(content=[ResponseOutputText(text='In vacuum, the speed of light is exactly 299,792,458 meters per second (about 3.00 × 10^8 m/s). It’s the universal speed limit in relativity.\n\nIn other media, light travels slower, with speed v = c/n, where n is the refractive index of the medium.', type='output_text', annotations=[], logprobs=[])], id='msg_tmp_7hd5r4y4htd', role='assistant', type='message', phase=Unset(), status='completed')]
input_tokens=13 input_tokens_details=InputTokensDetails(cached_tokens=0, cache_write_tokens=Unset()) output_tokens=461 output_tokens_details=OutputTokensDetails(reasoning_tokens=384) total_tokens=474 cost=0.00018505 cost_details=UsageCostDetails(upstream_inference_input_cost=6.5e-07, upstream_inference_output_cost=0.0001844, upstream_inference_cost=0.00018505) is_byok=False server_tool_use_details=Unset()
```

## Generation Parameters

Control the generation behavior:

```typescript lines theme={null}
import { OpenRouter } from '@openrouter/sdk';
import { callModel } from '@openrouter/agent';

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

const result = callModel(openrouter, {
  model: 'openai/gpt-4o-mini',
  input: 'Write a creative story.',

  // Temperature: 0 = deterministic, 2 = very creative
  temperature: 0.7,

  // Maximum tokens to generate
  maxOutputTokens: 1000,

  // Top-p sampling
  topP: 0.9,
});

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

```

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

from openrouter_agent import OpenRouter, call_model


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

    result = call_model(
        openrouter,
        {
            "model": "openai/gpt-4o-mini",
            "input": "Write a creative story.",
            # Temperature: 0 = deterministic, 2 = very creative
            "temperature": 0.7,
            # Maximum tokens to generate
            "max_output_tokens": 1000,
            # Top-p sampling
            "top_p": 0.9,
        },
    )

    text = await result.get_text()
    print(text)


asyncio.run(main())

```

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

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

func main() {
	body, _ := json.Marshal(map[string]any{
		"model": "openai/gpt-4o-mini",
		"input": "Write a creative story.",

		// Temperature: 0 = deterministic, 2 = very creative
		"temperature": 0.7,

		// Maximum tokens to generate
		"max_output_tokens": 1000,

		// Top-p sampling
		"top_p": 0.9,
	})

	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 {
		log.Fatalf("unexpected status: %s", resp.Status)
	}

	var result struct {
		Output []struct {
			Type    string `json:"type"`
			Content []struct {
				Type string `json:"type"`
				Text string `json:"text"`
			} `json:"content"`
		} `json:"output"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		log.Fatal(err)
	}

	text := ""
	for _, item := range result.Output {
		if item.Type != "message" {
			continue
		}
		for _, c := range item.Content {
			if c.Type == "output_text" {
				text += c.Text
			}
		}
	}
	fmt.Println(text)
}

```

```bash title="cURL" lines theme={null}
result=$(curl -s https://openrouter.ai/api/v1/responses \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-4o-mini",
    "input": "Write a creative story.",
    "temperature": 0.7,
    "max_output_tokens": 1000,
    "top_p": 0.9
  }')

# temperature: 0 = deterministic, 2 = very creative
# max_output_tokens: maximum tokens to generate
# top_p: top-p sampling

echo "$result" | jq -r '.output[] | select(.type == "message") | .content[] | select(.type == "output_text") | .text'

```

```bash title="cURL" lines theme={null}
curl -s https://openrouter.ai/api/v1/responses \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-4o-mini",
    "input": "Write a creative story.",
    "temperature": 0.7,
    "max_output_tokens": 1000,
    "top_p": 0.9
  }' | jq -r '.output[] | select(.type == "message") | .content[] | select(.type == "output_text") | .text'

```

```text title="Output" theme={null}
**The Whispering Grove**

In a small village nestled between rolling hills and a shimmering lake, there stood a grove of ancient trees known as the Whispering Grove. The villagers believed that the trees could communicate with one another and with those who ventured into their embrace. The leaves rustled with secrets, and the wind carried stories from the past, making the grove a place of wonder and mystery.

Among the villagers was a young girl named Elara. With wild curls that danced in the breeze and eyes that sparkled like the stars above, she was known for her insatiable curiosity. Every day after finishing her chores, Elara would sneak away to the Whispering Grove, eager to uncover its secrets. She would sit beneath the tallest tree, a magnificent oak known as Elden, and listen intently to the whispers that floated through the air.

One sunny afternoon, as Elara nestled against Elden’s gnarled roots, she heard a faint voice among the rustling leaves. “Help us,” it seemed to say, a melody of sorrow woven into the wind. Elara’s heart raced. She had never heard a voice so clear before. “Who’s there?” she called out, her voice trembling with a mix of excitement and trepidation.

“Come closer, dear child,” the voice beckoned, gentle yet urgent. “We are the guardians of this grove, and we need your help.”

Elara’s curiosity overcame her fear, and she moved closer to the trunk of Elden. “What do you need?” she asked, her eyes wide with anticipation.

“The balance of our grove is in peril,” the voice replied, resonating through the leaves like a soft chime. “A darkness has crept into the heart of the forest, and it threatens to consume us. Only a pure heart can mend the rift.”

Elara felt a surge of determination. “What must I do?”

“Follow the path of the silver moonlight,” the voice instructed. “Deep within the grove lies a hidden glade. There, you will find a stone, the Heart of the Grove. It pulses with our life force. You must cleanse it of the darkness that has settled upon it.”

With a nod, Elara set off, her heart pounding with excitement and purpose. She followed the dappled light filtering through the leaves, guided by the whispers of the grove. The deeper she ventured, the more vibrant the colors around her became, as if the trees were encouraging her onward.

After what felt like hours, she stumbled upon the glade. It was a breathtaking sight: flowers of every hue blossomed in harmony, and a gentle stream wound its way through the center. In the middle of it all stood a stone, large and imposing, pulsing with a faint, sickly glow.

Elara approached the stone, feeling the weight of its sorrow. She placed her hands on its surface, and the darkness swirled around her, cold and heavy. With a deep breath, she closed her eyes and thought of all the beauty the grove had shared with her—the laughter of the village children, the warmth of the sun filtering through the leaves, and the stories whispered by Elden.

“Light, love, and hope,” she murmured, channeling her feelings into the stone. “You do not belong here. You are not welcome!”

Suddenly, a bright light erupted from her hands, enveloping the stone in a warm glow. The darkness writhed and twisted, but Elara held her ground, pouring every ounce of her spirit into the cleansing. The light grew brighter, and with a final surge, the darkness was banished, dissipating into the air like smoke.

The stone pulsed with renewed vigor, its glow now a radiant white. The grove responded, the trees swaying gently as if in gratitude. Elara opened her eyes, breathless and triumphant.

“You have done it, dear child,” the voice of Elden whispered, echoing with joy. “You have restored the balance. The grove will thrive once more, and we will forever remember your bravery.”

Elara smiled, her heart swelling with pride. She knew she would return to the grove, not just as a curious girl, but as its protector—a guardian of its whispers and wonders.

From that day on, the villagers spoke of the brave girl who saved the Whispering Grove. And as for Elara, she continued to visit Elden, sharing her own stories with the trees, knowing that they would always listen and that their whispers would guide her, no matter where life led her next.
```

## Response Format

Request structured output:

```typescript lines theme={null}
import { OpenRouter } from '@openrouter/sdk';
import { callModel } from '@openrouter/agent';

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

const result = callModel(openrouter, {
  model: 'openai/gpt-5-nano',
  input: 'List three programming languages as a JSON object.',
  text: {
    format: {
      type: 'json_object',
    },
  },
});

const text = await result.getText();
const data = JSON.parse(text);
console.log(JSON.stringify(data, null, 2));

```

```python title="Python" lines theme={null}
import asyncio
import json
import os

from openrouter_agent import OpenRouter, call_model


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

    result = call_model(
        openrouter,
        {
            "model": "openai/gpt-5-nano",
            "input": "List three programming languages as a JSON object.",
            "text": {
                "format": {
                    "type": "json_object",
                },
            },
        },
    )

    text = await result.get_text()
    data = json.loads(text)
    print(json.dumps(data, indent=2))


asyncio.run(main())

```

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

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

func main() {
	body, _ := json.Marshal(map[string]any{
		"model": "openai/gpt-5-nano",
		"input": "List three programming languages as a JSON object.",
		"text": map[string]any{
			"format": map[string]any{
				"type": "json_object",
			},
		},
	})

	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 {
		log.Fatalf("unexpected status: %s", resp.Status)
	}

	var result struct {
		Output []struct {
			Type    string `json:"type"`
			Content []struct {
				Type string `json:"type"`
				Text string `json:"text"`
			} `json:"content"`
		} `json:"output"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		log.Fatal(err)
	}

	text := ""
	for _, item := range result.Output {
		if item.Type != "message" {
			continue
		}
		for _, c := range item.Content {
			if c.Type == "output_text" {
				text += c.Text
			}
		}
	}

	var data map[string]any
	if err := json.Unmarshal([]byte(text), &data); err != nil {
		log.Fatal(err)
	}

	pretty, _ := json.MarshalIndent(data, "", "  ")
	fmt.Println(string(pretty))
}

```

```bash title="cURL" lines theme={null}
result=$(curl -s https://openrouter.ai/api/v1/responses \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-5-nano",
    "input": "List three programming languages as a JSON object.",
    "text": {
      "format": {
        "type": "json_object"
      }
    }
  }')

text=$(echo "$result" | jq -r '.output[] | select(.type == "message") | .content[] | select(.type == "output_text") | .text')
data=$(echo "$text" | jq '.')

```

```bash title="cURL" lines theme={null}
curl -s https://openrouter.ai/api/v1/responses \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-5-nano",
    "input": "List three programming languages as a JSON object.",
    "text": {
      "format": {
        "type": "json_object"
      }
    }
  }' | jq -r '.output[] | select(.type == "message") | .content[] | select(.type == "output_text") | .text' | jq .

```

```json title="Output" theme={null}
{
  "languages": [
    "Python",
    "JavaScript",
    "C++"
  ]
}
```

## Error Handling

Handle common error cases:

```typescript lines theme={null}
import { OpenRouter } from '@openrouter/sdk';
import { callModel } from '@openrouter/agent';

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

try {
  const result = callModel(openrouter, {
    model: 'openai/gpt-5-nano',
    input: 'Hello!',
  });

  const text = await result.getText();
  console.log(text);
} catch (error) {
  if (error instanceof Error && 'statusCode' in error) {
    if (error.statusCode === 401) {
      console.error('Invalid API key');
    } else if (error.statusCode === 429) {
      console.error('Rate limited - try again later');
    } else if (error.statusCode === 503) {
      console.error('Model unavailable');
    } else {
      console.error('Request failed with status', error.statusCode);
    }
  } else {
    console.error('Unexpected error:', error);
  }
}

```

```python title="Python" lines theme={null}
import asyncio
import os
import sys

from openrouter_agent import OpenRouter, call_model


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

    try:
        result = call_model(
            openrouter,
            {
                "model": "openai/gpt-5-nano",
                "input": "Hello!",
            },
        )

        text = await result.get_text()
        print(text)
    except Exception as error:
        status_code = getattr(error, "status_code", None)
        if status_code is not None:
            if status_code == 401:
                print("Invalid API key", file=sys.stderr)
            elif status_code == 429:
                print("Rate limited - try again later", file=sys.stderr)
            elif status_code == 503:
                print("Model unavailable", file=sys.stderr)
            else:
                print("Request failed with status", status_code, file=sys.stderr)
        else:
            print("Unexpected error:", error, file=sys.stderr)


asyncio.run(main())

```

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

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

func main() {
	body, _ := json.Marshal(map[string]any{
		"model": "openai/gpt-5-nano",
		"input": "Hello!",
	})

	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("Unexpected error: ", err)
	}
	defer resp.Body.Close()

	switch resp.StatusCode {
	case http.StatusOK:
	case http.StatusUnauthorized:
		log.Fatal("Invalid API key")
	case http.StatusTooManyRequests:
		log.Fatal("Rate limited - try again later")
	case http.StatusServiceUnavailable:
		log.Fatal("Model unavailable")
	default:
		log.Fatal("Request failed with status ", resp.Status)
	}

	var result struct {
		Output []struct {
			Type    string `json:"type"`
			Content []struct {
				Type string `json:"type"`
				Text string `json:"text"`
			} `json:"content"`
		} `json:"output"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		log.Fatal("Unexpected error: ", err)
	}

	text := ""
	for _, item := range result.Output {
		if item.Type != "message" {
			continue
		}
		for _, c := range item.Content {
			if c.Type == "output_text" {
				text += c.Text
			}
		}
	}
	fmt.Println(text)
}

```

```bash title="cURL" lines theme={null}
response=$(curl -s -w '\n%{http_code}' https://openrouter.ai/api/v1/responses \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-5-nano",
    "input": "Hello!"
  }')

status=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')

case "$status" in
  200) echo "$body" | jq -r '.output[] | select(.type == "message") | .content[] | select(.type == "output_text") | .text' ;;
  401) echo "Invalid API key" >&2 ;;
  429) echo "Rate limited - try again later" >&2 ;;
  503) echo "Model unavailable" >&2 ;;
  *)   echo "Unexpected error: $body" >&2 ;;
esac
```

```bash title="cURL" lines theme={null}
response=$(curl -s -w '\n%{http_code}' https://openrouter.ai/api/v1/responses \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-5-nano",
    "input": "Hello!"
  }') || { echo "Unexpected error: curl failed" >&2; exit 1; }

status=$(tail -n1 <<< "$response")
body=$(sed '$d' <<< "$response")

case "$status" in
  200) jq -r '.output[] | select(.type == "message") | .content[] | select(.type == "output_text") | .text' <<< "$body" ;;
  401) echo "Invalid API key" >&2 ;;
  429) echo "Rate limited - try again later" >&2 ;;
  503) echo "Model unavailable" >&2 ;;
  *) echo "Request failed with status $status" >&2 ;;
esac

```

```text title="Output" theme={null}
Hi there! How can I help today? I can answer questions, explain concepts, help with writing or editing, code or debug, brainstorm ideas, plan a project, or just chat. What would you like to do?
```

## Concurrent Requests

Each callModel invocation is independent:

```typescript lines theme={null}
import { OpenRouter } from '@openrouter/sdk';
import { callModel } from '@openrouter/agent';

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

const [result1, result2, result3] = await Promise.all([
  callModel(openrouter, { model: 'openai/gpt-5-nano', input: 'Question 1' }).getText(),
  callModel(openrouter, { model: 'openai/gpt-5-nano', input: 'Question 2' }).getText(),
  callModel(openrouter, { model: 'openai/gpt-5-nano', input: 'Question 3' }).getText(),
]);

console.log('Result 1:', result1);
console.log('Result 2:', result2);
console.log('Result 3:', result3);

```

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

from openrouter_agent import OpenRouter, call_model


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

    result1, result2, result3 = await asyncio.gather(
        call_model(openrouter, {"model": "openai/gpt-5-nano", "input": "Question 1"}).get_text(),
        call_model(openrouter, {"model": "openai/gpt-5-nano", "input": "Question 2"}).get_text(),
        call_model(openrouter, {"model": "openai/gpt-5-nano", "input": "Question 3"}).get_text(),
    )

    print("Result 1:", result1)
    print("Result 2:", result2)
    print("Result 3:", result3)


asyncio.run(main())

```

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

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

func getText(input string) (string, error) {
	body, _ := json.Marshal(map[string]any{"model": "openai/gpt-5-nano", "input": input})

	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 {
		return "", err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("unexpected status: %s", resp.Status)
	}

	var result struct {
		Output []struct {
			Type    string `json:"type"`
			Content []struct {
				Type string `json:"type"`
				Text string `json:"text"`
			} `json:"content"`
		} `json:"output"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		return "", err
	}

	text := ""
	for _, item := range result.Output {
		if item.Type != "message" {
			continue
		}
		for _, c := range item.Content {
			if c.Type == "output_text" {
				text += c.Text
			}
		}
	}
	return text, nil
}

func main() {
	inputs := []string{"Question 1", "Question 2", "Question 3"}
	results := make([]string, len(inputs))
	errs := make([]error, len(inputs))

	var wg sync.WaitGroup
	for i, input := range inputs {
		wg.Add(1)
		go func() {
			defer wg.Done()
			results[i], errs[i] = getText(input)
		}()
	}
	wg.Wait()

	for i, result := range results {
		if errs[i] != nil {
			log.Fatal(errs[i])
		}
		fmt.Printf("Result %d: %s\n", i+1, result)
	}
}

```

```bash title="cURL" lines theme={null}
tmp=$(mktemp -d)

for i in 1 2 3; do
  curl -s https://openrouter.ai/api/v1/responses \
    -H "Authorization: Bearer $OPENROUTER_API_KEY" \
    -H "Content-Type: application/json" \
    -d "{\"model\": \"openai/gpt-5-nano\", \"input\": \"Question $i\"}" > "$tmp/result$i.json" &
done
wait

for i in 1 2 3; do
  text=$(jq -r '.output[] | select(.type == "message") | .content[] | select(.type == "output_text") | .text' "$tmp/result$i.json")
  echo "Result $i: $text"
done

```

```text title="Output" theme={null}
Result 1: Sure—please share the full text of Question 1 (or an image of it). Also tell me:
- the subject (math, physics, programming, etc.)
- any given data or formulas
- whether you want a quick answer or a step-by-step solution

If you can’t paste it, even a brief summary of the problem will help me get started.
Result 2: I don’t have Question 2. Please paste the exact problem (text, image, or figures) or tell me the subject and any given data. I’ll provide a step-by-step solution and final answer. If you want, also mention any constraints (time, allowed tools) so I tailor the approach.
Result 3: I’m happy to help, but I don’t have the prompt for Question 3. Please either paste the full text of Question 3 or upload an image of it. If you can’t do that, tell me:

- the subject (e.g., algebra, calculus, physics, statistics, geometry, etc.)
- the given data
- what you’re asked to find
- any work you’ve done so far

With that, I can give you a step-by-step solution or guide you through the approach. Here are quick, generic approaches you can use depending on the topic:

- Algebra: write the equation, collect like terms, isolate the variable, and check back in the original equation.
- Calculus: identify what’s to be optimized or solved for, compute derivatives, find critical points, use a sign chart or second derivative test, and verify your solution.
- Geometry/Trigonometry: apply relevant theorems (Pythagoras, similar triangles, trigonometric identities), set up equations, solve for the unknown, check units/consistency.
- Statistics/Probability: determine the model, apply the appropriate formulas (mean, variance, probabilities), and interpret the result.
- Physics: write down the governing equations (Newton’s laws, energy, kinematics), solve for the unknown with correct units, and check dimensional consistency.

Share the prompt and I’ll provide a clear, worked solution.
```

## Next Steps

* **[Streaming](https://openrouter.ai/docs/agent-sdk/call-model/streaming.md)** - Stream responses in real-time
* **[Tools](https://openrouter.ai/docs/agent-sdk/call-model/tools.md)** - Add tool capabilities to your generation
* **[Message Formats](https://openrouter.ai/docs/agent-sdk/call-model/message-formats.md)** - Convert from OpenAI/Claude formats
