Text Streaming
getTextStream()
Stream text content as it’s generated:import { OpenRouter } from '@openrouter/agent';
const openrouter = new OpenRouter({
apiKey: process.env.OPENROUTER_API_KEY,
});
const result = openrouter.callModel({
model: 'openai/gpt-5-nano',
input: 'Write a short poem about the ocean.',
});
for await (const delta of result.getTextStream()) {
process.stdout.write(delta);
}
import asyncio
import os
from openrouter_agent import OpenRouter, call_model
async def main() -> None:
client = OpenRouter(api_key=os.environ["OPENROUTER_API_KEY"])
result = call_model(
client,
{
"model": "openai/gpt-5-nano",
"input": "Write a short poem about the ocean.",
},
)
async for delta in result.get_text_stream():
print(delta, end="", flush=True)
print()
asyncio.run(main())
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
)
func main() {
body, _ := json.Marshal(map[string]any{
"model": "openai/gpt-5-nano",
"input": "Write a short poem about the ocean.",
"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 {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
b, _ := io.ReadAll(resp.Body)
panic(fmt.Sprintf("%s: %s", resp.Status, b))
}
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 string `json:"type"`
Delta string `json:"delta"`
}
if json.Unmarshal([]byte(data), &event) == nil && event.Type == "response.output_text.delta" {
fmt.Print(event.Delta)
}
}
fmt.Println()
}
curl -sN https://openrouter.ai/api/v1/responses \
-H "Authorization: Bearer $OPENROUTER_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "openai/gpt-5-nano",
"input": "Write a short poem about the ocean.",
"stream": true
}' | jq -Rrj --unbuffered 'ltrimstr("data: ") | fromjson? | select(.type == "response.output_text.delta") | .delta'
echo
Output
Ocean, blue breath beneath the wide sky,
pulling the shore toward the pale edge of light.
Waves write white cursive on the sand,
salt-tasted wind hums through the harbor air.
Gulls carve looping songs against the horizon,
and between tides, the world holds its quiet breath.
Reasoning Streaming
getReasoningStream()
For models that support reasoning (like o3 or Claude with thinking), stream the reasoning process:const result = openrouter.callModel({
model: 'openai/o3',
input: 'Solve this step by step: If x + 5 = 12, what is x?',
});
console.log('Reasoning:');
for await (const delta of result.getReasoningStream()) {
process.stdout.write(delta);
}
console.log('\n\nFinal answer:');
const text = await result.getText();
console.log(text);
import asyncio
import os
from openrouter_agent import OpenRouter, call_model
async def main() -> None:
client = OpenRouter(api_key=os.environ["OPENROUTER_API_KEY"])
result = call_model(
client,
{
"model": "openai/o3",
"input": "Solve this step by step: If x + 5 = 12, what is x?",
"reasoning": {"effort": "medium", "summary": "auto"},
},
)
print("Reasoning:")
async for delta in result.get_reasoning_stream():
print(delta, end="", flush=True)
print("\n\nFinal answer:")
text = await result.get_text()
print(text)
asyncio.run(main())
body, _ := json.Marshal(map[string]any{
"model": "openai/o3",
"input": "Solve this step by step: If x + 5 = 12, what is x?",
"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 {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
b, _ := io.ReadAll(resp.Body)
panic(fmt.Sprintf("%s: %s", resp.Status, b))
}
fmt.Println("Reasoning:")
var text strings.Builder
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 string `json:"type"`
Delta string `json:"delta"`
}
if json.Unmarshal([]byte(data), &event) != nil {
continue
}
switch event.Type {
case "response.failed", "error":
panic("stream failed: " + data)
case "response.reasoning_text.delta", "response.reasoning_summary_text.delta":
fmt.Print(event.Delta)
case "response.output_text.delta":
text.WriteString(event.Delta)
}
}
if err := scanner.Err(); err != nil {
panic(err) // the stream ended early: what was printed is incomplete
}
fmt.Println("\n\nFinal answer:")
fmt.Println(text.String())
stream=$(curl -sN https://openrouter.ai/api/v1/responses \
-H "Authorization: Bearer $OPENROUTER_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "openai/o3",
"input": "Solve this step by step: If x + 5 = 12, what is x?",
"reasoning": {"effort": "high", "summary": "detailed"},
"stream": true
}')
echo 'Reasoning:'
jq -Rrj 'ltrimstr("data: ") | fromjson? | select((.type // "") | test("reasoning") and endswith(".delta")) | (.delta | if type == "string" then . else (.text // .content // empty | tostring) end)' <<< "$stream"
printf '\n\nFinal answer:\n'
jq -Rrj 'ltrimstr("data: ") | fromjson? | select(.type == "response.output_text.delta") | .delta' <<< "$stream"
echo
Output
Reasoning:
Final answer:
We want to find the value of x that makes the equation
x + 5 = 12
true.
Step 1: Isolate x.
To do that, remove the +5 that is added to x. The opposite (inverse) of +5 is −5, so subtract 5 from both sides of the equation:
(x + 5) − 5 = 12 − 5
Step 2: Simplify both sides.
On the left, +5 and −5 cancel, leaving just x.
On the right, 12 − 5 equals 7.
x = 7
Answer: x = 7
Items Streaming
getItemsStream()
Stream complete items as they update. This is the recommended way to handle streaming when you need structured access to all output types (messages, tool calls, reasoning, etc.). See Working with Items for the full paradigm explanation.import type { StreamableOutputItem } from '@openrouter/agent';
const result = openrouter.callModel({
model: '~anthropic/claude-sonnet-latest',
input: 'Hello!',
tools: [myTool],
});
for await (const item of result.getItemsStream()) {
switch (item.type) {
case 'message':
console.log('Message:', item.content);
break;
case 'function_call':
console.log('Tool call:', item.name, item.arguments);
break;
case 'reasoning':
console.log('Thinking:', item.summary);
break;
case 'function_call_output':
console.log('Tool result:', item.output);
break;
}
}
import asyncio
import os
from pydantic import BaseModel
from openrouter_agent import OpenRouter, call_model, tool
class WeatherInput(BaseModel):
location: str
class WeatherOutput(BaseModel):
temperature: int
condition: str
location: str
my_tool = tool(
name="get_weather",
description="Get the current weather for a location",
input_schema=WeatherInput,
output_schema=WeatherOutput,
execute=lambda params, ctx: WeatherOutput(
temperature=72, condition="sunny", location=params.location
),
)
async def main() -> None:
client = OpenRouter(api_key=os.environ["OPENROUTER_API_KEY"])
result = call_model(
client,
{
"model": "~anthropic/claude-sonnet-latest",
"input": "Hello!",
"tools": [my_tool],
},
)
async for item in result.get_items_stream():
data = item if isinstance(item, dict) else item.model_dump()
match data["type"]:
case "message":
print("Message:", data.get("content"))
case "function_call":
print("Tool call:", data.get("name"), data.get("arguments"))
case "reasoning":
print("Thinking:", data.get("summary"))
case "function_call_output":
print("Tool result:", data.get("output"))
asyncio.run(main())
body, _ := json.Marshal(map[string]any{
"model": "~anthropic/claude-sonnet-latest",
"input": "Hello!",
"tools": []any{myTool},
"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 {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
b, _ := io.ReadAll(resp.Body)
panic(fmt.Sprintf("%s: %s", resp.Status, b))
}
var text strings.Builder
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 string `json:"type"`
Delta string `json:"delta"`
Item struct {
Type string `json:"type"`
Name string `json:"name"`
Arguments string `json:"arguments"`
Content json.RawMessage `json:"content"`
Summary json.RawMessage `json:"summary"`
} `json:"item"`
}
if json.Unmarshal([]byte(data), &event) != nil {
continue
}
switch event.Type {
case "response.failed", "error":
panic("stream failed: " + data)
case "response.output_item.added":
text.Reset()
case "response.output_text.delta":
text.WriteString(event.Delta)
fmt.Println("Message:", text.String())
case "response.output_item.done":
switch event.Item.Type {
case "message":
fmt.Println("Message:", string(event.Item.Content))
case "function_call":
fmt.Println("Tool call:", event.Item.Name, event.Item.Arguments)
case "reasoning":
fmt.Println("Thinking:", string(event.Item.Summary))
}
}
}
if err := scanner.Err(); err != nil {
panic(err) // the stream ended early: what was printed is incomplete
}
Output
Message: [{'text': "Hello! How can I help you today? I can check the weather for any location if you'd like. I'm also happy to answer questions or help with something else.", 'type': 'output_text', 'annotations': [], 'logprobs': []}]
| Type | Description |
|---|---|
message | Assistant text responses |
function_call | Tool invocations with arguments |
reasoning | Model thinking (extended thinking) |
web_search_call | Web search operations |
file_search_call | File search operations |
image_generation_call | Image generation operations |
function_call_output | Results from executed tools |
Message Streaming (Deprecated)
getNewMessagesStream()
getNewMessagesStream() is deprecated. Use getItemsStream() instead, which includes all item types and follows the items-based paradigm.// Deprecated - use getItemsStream() instead
const result = callModel(openrouter, {
model: 'openai/gpt-5-nano',
input: 'Hello!',
tools: [myTool] as const,
});
for await (const message of result.getNewMessagesStream()) {
if (message.type === 'message') {
console.log('Assistant message:', message.content);
} else if (message.type === 'function_call_output') {
console.log('Tool result:', message.output);
}
}
body, _ := json.Marshal(map[string]any{
"model": "openai/gpt-5-nano",
"input": "Hello!",
"tools": []any{myTool},
"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 {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
b, _ := io.ReadAll(resp.Body)
panic(fmt.Sprintf("%s: %s", resp.Status, b))
}
var text strings.Builder
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 string `json:"type"`
Delta string `json:"delta"`
Item struct {
Type string `json:"type"`
Content json.RawMessage `json:"content"`
} `json:"item"`
}
if json.Unmarshal([]byte(data), &event) != nil {
continue
}
switch event.Type {
case "response.failed", "error":
panic("stream failed: " + data)
case "response.output_item.added":
text.Reset()
case "response.output_text.delta":
// Build a cumulative snapshot of the assistant message
text.WriteString(event.Delta)
snapshot, _ := json.Marshal([]map[string]any{{
"type": "output_text",
"text": text.String(),
"annotations": []any{},
}})
fmt.Println("Assistant message:", string(snapshot))
case "response.output_item.done":
if event.Item.Type == "message" {
fmt.Println("Assistant message:", string(event.Item.Content))
}
}
}
if err := scanner.Err(); err != nil {
panic(err) // the stream ended early: what was printed is incomplete
}
ResponsesOutputMessage- Assistant text/content updatesOpenResponsesFunctionCallOutput- Tool execution results (after tools complete)
Full Event Streaming
getFullResponsesStream()
Stream all response events including tool preliminary results:const result = callModel(openrouter, {
model: 'openai/gpt-5-nano',
input: 'Search for documents about TypeScript generics',
tools: [searchTool] as const, // Generator tool with eventSchema
});
for await (const event of result.getFullResponsesStream()) {
switch (event.type) {
case 'response.output_text.delta':
process.stdout.write(event.delta);
break;
case 'response.function_call_arguments.delta':
console.log('Tool argument delta:', event.delta);
break;
case 'response.completed':
console.log('Response complete');
break;
case 'tool.preliminary_result':
// Intermediate progress from generator tools
console.log('Progress:', event.result);
break;
case 'tool.result':
// Final result when tool execution completes
console.log('Tool completed:', event.toolCallId);
console.log('Result:', event.result);
// Access any preliminary results that were emitted
if (event.preliminaryResults) {
console.log('Preliminary results:', event.preliminaryResults);
}
break;
}
}
async def main():
result = call_model(openrouter, {
"model": "openai/gpt-5-nano",
"input": "Search for documents about TypeScript generics",
"tools": [search_tool], # Generator tool with event_schema
})
async for event in result.get_full_responses_stream():
e = event if isinstance(event, dict) else event.model_dump()
match e.get("type"):
case "response.output_text.delta":
print(e["delta"], end="", flush=True)
case "response.function_call_arguments.delta":
print("Tool argument delta:", e["delta"])
case "response.completed":
print("Response complete")
case "tool.preliminary_result":
# Intermediate progress from generator tools
print("Progress:", e.get("result"))
case "tool.result":
# Final result when tool execution completes
print("Tool completed:", e.get("tool_call_id"))
print("Result:", e.get("result"))
# Access any preliminary results that were emitted
if e.get("preliminary_results"):
print("Preliminary results:", e["preliminary_results"])
asyncio.run(main())
type toolCall struct {
CallID string `json:"call_id"`
Name string `json:"name"`
Arguments string `json:"arguments"`
}
stream := func(input []any) []toolCall {
body, _ := json.Marshal(map[string]any{
"model": "openai/gpt-5-nano",
"input": input,
"tools": []any{searchTool},
"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 {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
b, _ := io.ReadAll(resp.Body)
panic(fmt.Sprintf("%s: %s", resp.Status, b))
}
var calls []toolCall
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 string `json:"type"`
Delta string `json:"delta"`
Item struct {
Type string `json:"type"`
toolCall
} `json:"item"`
}
if json.Unmarshal([]byte(data), &event) != nil {
continue
}
switch event.Type {
case "response.output_text.delta":
fmt.Print(event.Delta)
case "response.function_call_arguments.delta":
fmt.Println("Tool argument delta:", event.Delta)
case "response.completed":
fmt.Println("Response complete")
case "response.output_item.done":
if event.Item.Type == "function_call" {
calls = append(calls, event.Item.toolCall)
}
}
}
return calls
}
input := []any{map[string]any{"role": "user", "content": "Search for documents about TypeScript generics"}}
for calls := stream(input); len(calls) > 0; calls = stream(input) {
for _, call := range calls {
var preliminary []any
// Run the generator tool, reporting intermediate progress
result := searchDocs(call.Arguments, func(progress any) {
fmt.Println("Progress:", progress)
preliminary = append(preliminary, progress)
})
fmt.Println("Tool completed:", call.CallID)
fmt.Println("Result:", result)
if len(preliminary) > 0 {
fmt.Println("Preliminary results:", preliminary)
}
output, _ := json.Marshal(result)
input = append(input,
map[string]any{"type": "function_call", "call_id": call.CallID, "name": call.Name, "arguments": call.Arguments},
map[string]any{"type": "function_call_output", "call_id": call.CallID, "output": string(output)},
)
}
}
Event Types
The full stream includes these event types:| Event Type | Description |
|---|---|
response.created | Response object created |
response.in_progress | Generation started |
response.output_text.delta | Text content chunk |
response.output_text.done | Text content complete |
response.reasoning.delta | Reasoning content chunk |
response.reasoning.done | Reasoning complete |
response.function_call_arguments.delta | Tool call argument chunk |
response.function_call_arguments.done | Tool call arguments complete |
response.completed | Full response complete |
tool.preliminary_result | Progress from generator tools (intermediate yields) |
tool.result | Final result from tool execution |
Tool Call Streaming
getToolCallsStream()
Stream structured tool calls as they complete:// weatherTool is a manual tool (execute: false), so calls are reported, not auto-executed
const result = callModel(openrouter, {
model: 'openai/gpt-5-nano',
input: 'What is the weather in Paris and Tokyo?',
tools: [weatherTool] as const,
});
for await (const toolCall of result.getToolCallsStream()) {
console.log(`Tool: ${toolCall.name}`);
console.log(`Arguments:`, toolCall.arguments);
console.log(`ID: ${toolCall.id}`);
}
# weather_tool is a manual tool (execute=False), so calls are reported, not auto-executed
async def main():
result = call_model(openrouter, {
"model": "openai/gpt-5-nano",
"input": "What is the weather in Paris and Tokyo?",
"tools": [weather_tool],
})
async for tool_call in result.get_tool_calls_stream():
print(f"Tool: {tool_call.name}")
print("Arguments:", tool_call.arguments)
print(f"ID: {tool_call.id}")
asyncio.run(main())
// weatherTool is a manual tool: calls are reported as they complete, not executed
body, _ := json.Marshal(map[string]any{
"model": "openai/gpt-5-nano",
"input": "What is the weather in Paris and Tokyo?",
"tools": []any{weatherTool},
"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 {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
b, _ := io.ReadAll(resp.Body)
panic(fmt.Sprintf("%s: %s", resp.Status, b))
}
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 string `json:"type"`
Item struct {
Type string `json:"type"`
CallID string `json:"call_id"`
Name string `json:"name"`
Arguments string `json:"arguments"`
} `json:"item"`
}
if json.Unmarshal([]byte(data), &event) != nil {
continue
}
if event.Type == "response.output_item.done" && event.Item.Type == "function_call" {
fmt.Println("Tool:", event.Item.Name)
fmt.Println("Arguments:", event.Item.Arguments)
fmt.Println("ID:", event.Item.CallID)
}
}
getToolStream()
Stream tool deltas and preliminary results:const result = callModel(openrouter, {
model: 'openai/gpt-5-nano',
input: 'Search for TypeScript tutorials',
tools: [searchTool] as const, // Generator tool
});
for await (const event of result.getToolStream()) {
if (event.type === 'delta') {
// Raw argument deltas
process.stdout.write(event.content);
} else if (event.type === 'preliminary_result') {
// Progress from generator tools
console.log(`\nProgress (${event.toolCallId}):`, event.result);
}
}
# search_tool is a generator tool that yields progress events before its final output
async def main():
result = call_model(openrouter, {
"model": "openai/gpt-5-nano",
"input": "Search for TypeScript tutorials",
"tools": [search_tool],
})
async for event in result.get_tool_stream():
if event["type"] == "delta":
# Raw argument deltas
print(event["content"], end="", flush=True)
elif event["type"] == "preliminary_result":
# Progress from generator tools (a Pydantic model matching event_schema)
progress = event["result"]
if hasattr(progress, "model_dump"):
progress = progress.model_dump()
print(f"\nProgress ({event['tool_call_id']}):", progress)
asyncio.run(main())
stream := func(input []any) []toolCall {
body, _ := json.Marshal(map[string]any{
"model": "openai/gpt-5-nano",
"input": input,
"tools": []any{searchTool}, // Generator tool
"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 {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
b, _ := io.ReadAll(resp.Body)
panic(fmt.Sprintf("%s: %s", resp.Status, b))
}
var calls []toolCall
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 string `json:"type"`
Delta string `json:"delta"`
Item struct {
Type string `json:"type"`
toolCall
} `json:"item"`
}
if json.Unmarshal([]byte(data), &event) != nil {
continue
}
switch event.Type {
case "response.function_call_arguments.delta":
// Raw argument deltas (only tool events are streamed here)
fmt.Print(event.Delta)
case "response.failed", "error":
panic(data)
case "response.output_item.done":
if event.Item.Type == "function_call" {
calls = append(calls, event.Item.toolCall)
}
}
}
return calls
}
input := []any{map[string]any{"role": "user", "content": "Search for TypeScript tutorials"}}
for calls := stream(input); len(calls) > 0; calls = stream(input) {
for _, call := range calls {
// Preliminary results (progress) from the generator tool
result := runSearch(call.Arguments, func(progress any) {
p, _ := json.MarshalIndent(progress, "", " ")
fmt.Printf("\nProgress (%s): %s\n", call.CallID, p)
})
output, _ := json.Marshal(result)
input = append(input,
map[string]any{"type": "function_call", "call_id": call.CallID, "name": call.Name, "arguments": call.Arguments},
map[string]any{"type": "function_call_output", "call_id": call.CallID, "output": string(output)},
)
}
}
Concurrent Consumers
Multiple consumers can read from the same result: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: 'Write a story.',
});
// Start both consumers concurrently
const [text, response] = await Promise.all([
// Consumer 1: Collect text
(async () => {
let text = '';
for await (const delta of result.getTextStream()) {
text += delta;
}
return text;
})(),
// Consumer 2: Get full response
result.getResponse(),
]);
console.log('Text length:', text.length);
console.log('Token usage:', response.usage);
import asyncio
import os
from openrouter_agent import OpenRouter, call_model
async def main():
openrouter = OpenRouter(api_key=os.environ["OPENROUTER_API_KEY"])
result = call_model(openrouter, {
"model": "openai/gpt-5-nano",
"input": "Write a story.",
})
# Consumer 1: Collect text
async def collect_text():
text = ""
async for delta in result.get_text_stream():
text += delta
return text
# Start both consumers concurrently (Consumer 2: Get full response)
text, response = await asyncio.gather(collect_text(), result.get_response())
print("Text length:", len(text))
print("Token usage:", response.usage)
asyncio.run(main())
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"sync"
)
type event struct {
Type string `json:"type"`
Delta string `json:"delta"`
Response struct {
Usage json.RawMessage `json:"usage"`
} `json:"response"`
}
func main() {
body, _ := json.Marshal(map[string]any{
"model": "openai/gpt-5-nano",
"input": "Write a story.",
"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 {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
b, _ := io.ReadAll(resp.Body)
panic(fmt.Sprintf("%s: %s", resp.Status, b))
}
// Fan the single stream out to both consumers
textCh, respCh := make(chan event), make(chan event)
go func() {
defer close(textCh)
defer close(respCh)
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 e event
if json.Unmarshal([]byte(data), &e) != nil {
continue
}
if e.Type == "response.failed" || e.Type == "error" {
panic(data)
}
textCh <- e
respCh <- e
}
}()
// Start both consumers concurrently
var text string
var usage json.RawMessage
var wg sync.WaitGroup
wg.Add(2)
// Consumer 1: Collect text
go func() {
defer wg.Done()
for e := range textCh {
if e.Type == "response.output_text.delta" {
text += e.Delta
}
}
}()
// Consumer 2: Get full response
go func() {
defer wg.Done()
for e := range respCh {
if e.Type == "response.completed" {
usage = e.Response.Usage
}
}
}()
wg.Wait()
var pretty bytes.Buffer
json.Indent(&pretty, usage, "", " ")
fmt.Println("Text length:", len(text))
fmt.Println("Token usage:", pretty.String())
}
Output
Text length: 17648
Token usage: {
inputTokens: 10,
inputTokensDetails: {
cachedTokens: 0,
},
outputTokens: 6383,
outputTokensDetails: {
reasoningTokens: 2496,
},
totalTokens: 6393,
cost: 0.0025537,
costDetails: {
upstreamInferenceCost: 0.0025537,
upstreamInferenceInputCost: 5e-7,
upstreamInferenceOutputCost: 0.0025532,
},
isByok: false,
}
ReusableReadableStream ensures each consumer receives all events.
Cancellation
Cancel a stream to stop generation: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: 'Write a very long essay...',
});
// Start streaming
const streamPromise = (async () => {
let charCount = 0;
for await (const delta of result.getTextStream()) {
process.stdout.write(delta);
charCount += delta.length;
// Cancel after 500 characters
if (charCount > 500) {
await result.cancel();
break;
}
}
})();
await streamPromise;
console.log('\nCancelled!');
import asyncio
import os
from openrouter_agent import OpenRouter, call_model
async def main():
openrouter = OpenRouter(api_key=os.environ["OPENROUTER_API_KEY"])
result = call_model(openrouter, {
"model": "openai/gpt-5-nano",
"input": "Write a very long essay...",
})
# Start streaming
char_count = 0
async for delta in result.get_text_stream():
print(delta, end="", flush=True)
char_count += len(delta)
# Cancel after 500 characters
if char_count > 500:
result.cancel()
break
print("\nCancelled!")
asyncio.run(main())
package main
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
body, _ := json.Marshal(map[string]any{
"model": "openai/gpt-5-nano",
"input": "Write a very long essay...",
"stream": true,
})
req, _ := http.NewRequestWithContext(ctx, "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")
// Start streaming
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
b, _ := io.ReadAll(resp.Body)
panic(fmt.Sprintf("%s: %s", resp.Status, b))
}
charCount := 0
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 e struct {
Type string `json:"type"`
Delta string `json:"delta"`
}
if json.Unmarshal([]byte(data), &e) != nil {
continue
}
if e.Type == "response.failed" || e.Type == "error" {
panic(data)
}
if e.Type != "response.output_text.delta" {
continue
}
fmt.Print(e.Delta)
charCount += len(e.Delta)
// Cancel after 500 characters
if charCount > 500 {
cancel()
break
}
}
fmt.Println("\nCancelled!")
}
Output
I can write a very long essay, but I’ll need a topic and some details to tailor it to you. Here are a few quick questions, followed by topic ideas you can pick from. Once you choose, I’ll draft a long essay (with sections, transitions, and a clear thesis) and can deliver it in chunks if you’d like.
Key questions for you:
- Topic: What should the essay be about?
- Length: How many words do you want? (e.g., 2,000–4,000 words, 5,000+, etc.)
- Audience: Who is it for (general readers, academics, students
Cancelled!
Streaming with UI Frameworks
React Example
import { OpenRouter } from '@openrouter/sdk';
import { callModel } from '@openrouter/agent';
// The same pattern a React component uses: append each delta to UI state,
// flip an isStreaming flag when done, and cancel the stream on cleanup.
// In React, call `onText` from setText, `onDone` from setIsStreaming(false),
// and return `cancel` from your useEffect cleanup.
function streamChatResponse(
prompt: string,
onText: (text: string) => void,
onDone: () => void,
) {
const openrouter = new OpenRouter({ apiKey: process.env.OPENROUTER_API_KEY });
const result = callModel(openrouter, {
model: 'openai/gpt-5-nano',
input: prompt,
});
let text = '';
const done = (async () => {
for await (const delta of result.getTextStream()) {
text += delta;
onText(text);
}
onDone();
})();
return {
done,
cancel: () => result.cancel(),
};
}
let rendered = '';
const { done } = streamChatResponse(
'Write a short haiku about streaming text.',
(text) => {
// "Render" only the newly arrived part
process.stdout.write(text.slice(rendered.length));
rendered = text;
},
() => console.log('\n[stream complete]'),
);
await done;
import asyncio
import os
from openrouter_agent import OpenRouter, call_model
# The same pattern a React component uses: append each delta to UI state,
# flip an is_streaming flag when done, and cancel the stream on cleanup.
# In React, call `on_text` from setText, `on_done` from setIsStreaming(false),
# and return `cancel` from your useEffect cleanup.
def stream_chat_response(prompt, on_text, on_done):
openrouter = OpenRouter(api_key=os.environ["OPENROUTER_API_KEY"])
result = call_model(openrouter, {
"model": "openai/gpt-5-nano",
"input": prompt,
})
async def run():
text = ""
async for delta in result.get_text_stream():
text += delta
on_text(text)
on_done()
return asyncio.create_task(run()), result.cancel
async def main():
rendered = ""
def on_text(text):
# "Render" only the newly arrived part
nonlocal rendered
print(text[len(rendered):], end="", flush=True)
rendered = text
done, cancel = stream_chat_response(
"Write a short haiku about streaming text.",
on_text,
lambda: print("\n[stream complete]"),
)
await done
asyncio.run(main())
package main
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
)
// The same pattern a React component uses: append each delta to UI state,
// flip an isStreaming flag when done, and cancel the stream on cleanup.
// In React, call `onText` from setText, `onDone` from setIsStreaming(false),
// and return `cancel` from your useEffect cleanup.
// Failures reach the caller through `onError` instead of ending the process.
func streamChatResponse(prompt string, onText func(string), onDone func(), onError func(error)) (<-chan struct{}, context.CancelFunc) {
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
body, _ := json.Marshal(map[string]any{
"model": "openai/gpt-5-nano",
"input": prompt,
"stream": true,
})
req, _ := http.NewRequestWithContext(ctx, "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")
go func() {
defer close(done)
resp, err := http.DefaultClient.Do(req)
if err != nil {
if ctx.Err() != nil {
return
}
onError(err)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
b, _ := io.ReadAll(resp.Body)
onError(fmt.Errorf("%s: %s", resp.Status, b))
return
}
text := ""
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 e struct {
Type string `json:"type"`
Delta string `json:"delta"`
}
if json.Unmarshal([]byte(data), &e) != nil {
continue
}
if e.Type == "response.failed" || e.Type == "error" {
onError(fmt.Errorf("stream failed: %s", data))
return
}
if e.Type == "response.output_text.delta" {
text += e.Delta
onText(text)
}
}
// A cancelled or failed read ends the loop early: that is not a completed stream
if ctx.Err() != nil {
return
}
if err := scanner.Err(); err != nil {
onError(err)
return
}
onDone()
}()
return done, cancel
}
func main() {
rendered := ""
done, cancel := streamChatResponse(
"Write a short haiku about streaming text.",
func(text string) {
// "Render" only the newly arrived part
fmt.Print(text[len(rendered):])
rendered = text
},
func() { fmt.Println("\n[stream complete]") },
func(err error) { fmt.Fprintln(os.Stderr, "\nstream failed:", err) },
)
defer cancel()
<-done
}
#!/bin/bash
# Fail the script when curl or jq fails, so an error never prints the success marker
set -eo pipefail
# Stream the response and "render" each text delta as it arrives
curl -sSfN https://openrouter.ai/api/v1/responses \
-H "Authorization: Bearer $OPENROUTER_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "openai/gpt-5-nano",
"input": "Write a short haiku about streaming text.",
"stream": true
}' | jq -Rj --unbuffered '
select(startswith("data: ")) | .[6:] | (fromjson? // empty)
| if .type == "response.failed" or .type == "error" then error(tostring)
elif .type == "response.output_text.delta" then .delta
else empty end'
printf '\n[stream complete]\n'
Output
Text streams in the glow
A cursor glides through the feed
Stories stream alive
[stream complete]
Server-Sent Events (SSE)
import { OpenRouter } from '@openrouter/sdk';
import { callModel } from '@openrouter/agent';
import { Hono } from 'hono';
import { streamSSE } from 'hono/streaming';
const openrouter = new OpenRouter({ apiKey: process.env.OPENROUTER_API_KEY });
const app = new Hono();
app.get('/stream', (c) => {
return streamSSE(c, async (stream) => {
const result = callModel(openrouter, {
model: 'openai/gpt-5-nano',
input: c.req.query('prompt') || 'Hello!',
});
for await (const delta of result.getTextStream()) {
await stream.writeSSE({
data: JSON.stringify({ delta }),
event: 'delta',
});
}
await stream.writeSSE({
data: JSON.stringify({ done: true }),
event: 'done',
});
});
});
// Try the endpoint in-process and print the SSE events as they arrive
const res = await app.request(
'/stream?prompt=' + encodeURIComponent('Write a short haiku about streaming text.'),
);
const reader = res.body!.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
process.stdout.write(decoder.decode(value, { stream: true }));
}
import asyncio
import json
import os
from urllib.parse import parse_qs
import httpx
from openrouter_agent import OpenRouter, call_model
openrouter = OpenRouter(api_key=os.environ["OPENROUTER_API_KEY"])
# A minimal ASGI app serving GET /stream as Server-Sent Events
async def app(scope, receive, send):
query = parse_qs(scope["query_string"].decode())
prompt = query.get("prompt", ["Hello!"])[0]
await send({
"type": "http.response.start",
"status": 200,
"headers": [(b"content-type", b"text/event-stream")],
})
async def write_sse(event, data):
body = f"event: {event}\ndata: {json.dumps(data, separators=(',', ':'))}\n\n"
await send({"type": "http.response.body", "body": body.encode(), "more_body": True})
result = call_model(openrouter, {
"model": "openai/gpt-5-nano",
"input": prompt,
})
async for delta in result.get_text_stream():
await write_sse("delta", {"delta": delta})
await write_sse("done", {"done": True})
await send({"type": "http.response.body", "body": b""})
# Try the endpoint in-process and print the SSE events as they arrive
async def main():
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url="http://local") as client:
params = {"prompt": "Write a short haiku about streaming text."}
async with client.stream("GET", "/stream", params=params) as res:
async for chunk in res.aiter_text():
print(chunk, end="", flush=True)
asyncio.run(main())
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"os"
"strings"
)
func streamHandler(w http.ResponseWriter, r *http.Request) {
prompt := r.URL.Query().Get("prompt")
if prompt == "" {
prompt = "Hello!"
}
body, _ := json.Marshal(map[string]any{
"model": "openai/gpt-5-nano",
"input": prompt,
"stream": true,
})
req, _ := http.NewRequestWithContext(r.Context(), "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 {
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
b, _ := io.ReadAll(resp.Body)
http.Error(w, resp.Status+": "+string(b), http.StatusBadGateway)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
flusher := w.(http.Flusher)
writeSSE := func(event string, data any) {
b, _ := json.Marshal(data)
fmt.Fprintf(w, "event: %s\ndata: %s\n\n", event, b)
flusher.Flush()
}
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 e struct {
Type string `json:"type"`
Delta string `json:"delta"`
}
if json.Unmarshal([]byte(data), &e) != nil {
continue
}
if e.Type == "response.failed" || e.Type == "error" {
writeSSE("error", json.RawMessage(data))
return
}
if e.Type == "response.output_text.delta" {
writeSSE("delta", map[string]string{"delta": e.Delta})
}
}
// A read error means the upstream stream was cut short: report it instead of done
if err := scanner.Err(); err != nil {
writeSSE("error", map[string]string{"message": err.Error()})
return
}
writeSSE("done", map[string]bool{"done": true})
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/stream", streamHandler)
// Try the endpoint in-process and print the SSE events as they arrive
srv := httptest.NewServer(mux)
defer srv.Close()
resp, err := http.Get(srv.URL + "/stream?prompt=" + url.QueryEscape("Write a short haiku about streaming text."))
if err != nil {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
b, _ := io.ReadAll(resp.Body)
panic(fmt.Sprintf("%s: %s", resp.Status, b))
}
io.Copy(os.Stdout, resp.Body)
}
#!/bin/bash
# Stop before emitting done if the request or the JSON processing fails
set -euo pipefail
# Re-emit the upstream stream as your own SSE events (delta, then done)
curl -sSfN https://openrouter.ai/api/v1/responses \
-H "Authorization: Bearer $OPENROUTER_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "openai/gpt-5-nano",
"input": "Write a short haiku about streaming text.",
"stream": true
}' | jq -Rj --unbuffered '
select(startswith("data: ")) | .[6:] | (fromjson? // empty)
| if .type == "response.failed" or .type == "error" then error(tostring)
elif .type == "response.output_text.delta" then
"event: delta\ndata: \({delta: .delta} | tojson)\n\n"
else empty end'
printf 'event: done\ndata: {"done":true}\n\n'
Output
event: delta
data: {"delta":"Streaming"}
event: delta
data: {"delta":" text"}
event: delta
data: {"delta":" flows"}
event: delta
data: {"delta":" by"}
event: delta
data: {"delta":"\n"}
event: delta
data: {"delta":"Cursor"}
event: delta
data: {"delta":" blinking"}
event: delta
data: {"delta":" in"}
event: delta
data: {"delta":" the"}
event: delta
data: {"delta":" chat"}
event: delta
data: {"delta":"\n"}
event: delta
data: {"delta":"Letters"}
event: delta
data: {"delta":" pour"}
event: delta
Next Steps
- Working with Items - Understand the items-based streaming paradigm
- Tools - Create tools and multi-turn streaming with tools