Looking to auto-instrument without client code? Check out OpenRouter Broadcast to automatically send traces to Langfuse.
Using Langfuse
Langfuse provides observability and analytics for LLM applications. Since OpenRouter uses the OpenAI API schema, you can use Langfuse’s native integration with the OpenAI SDK to automatically trace and monitor your OpenRouter API calls.Installation
pip install langfuse openai
Configuration
Set up your environment variables:import os
# Set your Langfuse API keys
LANGFUSE_SECRET_KEY="sk-lf-..."
LANGFUSE_PUBLIC_KEY="pk-lf-..."
# EU region
LANGFUSE_HOST="https://cloud.langfuse.com"
# US region
# LANGFUSE_HOST="https://us.cloud.langfuse.com"
# Set your OpenRouter API key
os.environ["OPENAI_API_KEY"] = "<OPENROUTER_API_KEY>"
# Set your Langfuse API keys
export LANGFUSE_SECRET_KEY="sk-lf-..."
export LANGFUSE_PUBLIC_KEY="pk-lf-..."
# EU region
export LANGFUSE_HOST="https://cloud.langfuse.com"
# US region
# export LANGFUSE_HOST="https://us.cloud.langfuse.com"
# Set your OpenRouter API key
export OPENAI_API_KEY="$OPENROUTER_API_KEY"
# Set your Langfuse API keys
export LANGFUSE_SECRET_KEY="sk-lf-..."
export LANGFUSE_PUBLIC_KEY="pk-lf-..."
# EU region
export LANGFUSE_HOST="https://cloud.langfuse.com"
# US region
# export LANGFUSE_HOST="https://us.cloud.langfuse.com"
# Set your OpenRouter API key
export OPENAI_API_KEY="$OPENROUTER_API_KEY"
Simple LLM Call
Since OpenRouter provides an OpenAI-compatible API, you can use the Langfuse OpenAI SDK wrapper to automatically log OpenRouter calls as generations in Langfuse:# Import the Langfuse OpenAI SDK wrapper
from langfuse.openai import openai
# Create an OpenAI client with OpenRouter's base URL
client = openai.OpenAI(
base_url="https://openrouter.ai/api/v1",
default_headers={
"HTTP-Referer": "<YOUR_SITE_URL>", # Optional: Your site URL
"X-OpenRouter-Title": "<YOUR_SITE_NAME>", # Optional: Your site name
}
)
# Make a Responses API request
response = client.responses.create(
model="anthropic/claude-sonnet-4.6",
instructions="You are a helpful assistant.",
input="Tell me a fun fact about space.",
name="fun-fact-request" # Optional: Name of the generation in Langfuse
)
# Print the assistant's reply
print(response.output_text)
import OpenAI from 'openai';
// Create an OpenAI client with OpenRouter's base URL
const client = new OpenAI({
baseURL: 'https://openrouter.ai/api/v1',
apiKey: process.env.OPENROUTER_API_KEY,
defaultHeaders: {
'HTTP-Referer': '<YOUR_SITE_URL>', // Optional: Your site URL
'X-OpenRouter-Title': '<YOUR_SITE_NAME>', // Optional: Your site name
},
});
// Make a Responses API request
const response = await client.responses.create({
model: 'anthropic/claude-sonnet-4.6',
instructions: 'You are a helpful assistant.',
input: 'Tell me a fun fact about space.',
});
// Print the assistant's reply
console.log(response.output_text);
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
)
func main() {
body, _ := json.Marshal(map[string]any{
"model": "anthropic/claude-sonnet-4.6",
"instructions": "You are a helpful assistant.",
"input": "Tell me a fun fact about space.",
})
// Make a Responses API request to OpenRouter
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")
req.Header.Set("HTTP-Referer", "<YOUR_SITE_URL>") // Optional: Your site URL
req.Header.Set("X-OpenRouter-Title", "<YOUR_SITE_NAME>") // Optional: Your site name
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
var out struct {
Output []struct {
Content []struct {
Type string `json:"type"`
Text string `json:"text"`
} `json:"content"`
} `json:"output"`
}
if err := json.NewDecoder(res.Body).Decode(&out); err != nil {
log.Fatal(err)
}
// Print the assistant's reply
for _, item := range out.Output {
for _, c := range item.Content {
if c.Type == "output_text" {
fmt.Println(c.Text)
}
}
}
}
curl -s https://openrouter.ai/api/v1/responses \
-H "Authorization: Bearer $OPENROUTER_API_KEY" \
-H "Content-Type: application/json" \
-H "HTTP-Referer: <YOUR_SITE_URL>" \
-H "X-OpenRouter-Title: <YOUR_SITE_NAME>" \
-d '{
"model": "anthropic/claude-sonnet-4.6",
"instructions": "You are a helpful assistant.",
"input": "Tell me a fun fact about space."
}' | jq -r '.output[] | select(.type == "message") | .content[] | select(.type == "output_text") | .text'
Output
Here's a fun fact about space:
**A day on Venus is longer than a year on Venus!** 🪐
Venus rotates so slowly on its axis that it takes about **243 Earth days** to complete one full rotation. But it only takes about **225 Earth days** to orbit the Sun. So a single day on Venus is actually longer than its entire year!
As a bonus, Venus also rotates *backwards* compared to most planets, so if you could see the Sun from Venus's surface, it would rise in the west and set in the east. 🌅
Advanced Tracing with Nested Calls
The Python example uses@observe() to capture a parent trace and its LLM calls. The TypeScript, Go, and cURL tabs show the same two requests without Langfuse instrumentation.
from langfuse import observe
from langfuse.openai import openai
# Create an OpenAI client with OpenRouter's base URL
client = openai.OpenAI(
base_url="https://openrouter.ai/api/v1",
)
@observe() # This decorator enables tracing of the function
def analyze_text(text: str):
# First LLM call: Summarize the text
summary_response = summarize_text(text)
summary = summary_response.output_text
# Second LLM call: Analyze the sentiment of the summary
sentiment_response = analyze_sentiment(summary)
sentiment = sentiment_response.output_text
return {
"summary": summary,
"sentiment": sentiment
}
@observe() # Nested function to be traced
def summarize_text(text: str):
return client.responses.create(
model="openai/gpt-4o-mini",
instructions="You summarize texts in a concise manner.",
input=f"Summarize the following text:\n{text}",
name="summarize-text"
)
@observe() # Nested function to be traced
def analyze_sentiment(summary: str):
return client.responses.create(
model="openai/gpt-4o-mini",
instructions="You analyze the sentiment of texts.",
input=f"Analyze the sentiment of the following summary:\n{summary}",
name="analyze-sentiment"
)
# Example usage
text_to_analyze = "OpenRouter's unified API has significantly advanced the field of AI development, setting new standards for model accessibility."
result = analyze_text(text_to_analyze)
print(result)
import OpenAI from 'openai';
// Create an OpenAI client with OpenRouter's base URL
const client = new OpenAI({
baseURL: 'https://openrouter.ai/api/v1',
apiKey: process.env.OPENROUTER_API_KEY,
});
async function analyzeText(text: string) {
// First LLM call: Summarize the text
const summary = (await summarizeText(text)).output_text;
// Second LLM call: Analyze the sentiment of the summary
const sentiment = (await analyzeSentiment(summary)).output_text;
return { summary, sentiment };
}
function summarizeText(text: string) {
return client.responses.create({
model: 'openai/gpt-4o-mini',
instructions: 'You summarize texts in a concise manner.',
input: `Summarize the following text:\n${text}`,
});
}
function analyzeSentiment(summary: string) {
return client.responses.create({
model: 'openai/gpt-4o-mini',
instructions: 'You analyze the sentiment of texts.',
input: `Analyze the sentiment of the following summary:\n${summary}`,
});
}
// Example usage
const textToAnalyze =
"OpenRouter's unified API has significantly advanced the field of AI development, setting new standards for model accessibility.";
const result = await analyzeText(textToAnalyze);
console.log(result);
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
)
// respond makes a Responses API request to OpenRouter and returns the output text
func respond(instructions, input string) string {
body, _ := json.Marshal(map[string]any{
"model": "openai/gpt-4o-mini",
"instructions": instructions,
"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")
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
var out struct {
Output []struct {
Content []struct {
Type string `json:"type"`
Text string `json:"text"`
} `json:"content"`
} `json:"output"`
}
if err := json.NewDecoder(res.Body).Decode(&out); err != nil {
log.Fatal(err)
}
text := ""
for _, item := range out.Output {
for _, c := range item.Content {
if c.Type == "output_text" {
text += c.Text
}
}
}
return text
}
// Nested function: summarize the text
func summarizeText(text string) string {
return respond("You summarize texts in a concise manner.", "Summarize the following text:\n"+text)
}
// Nested function: analyze the sentiment of the summary
func analyzeSentiment(summary string) string {
return respond("You analyze the sentiment of texts.", "Analyze the sentiment of the following summary:\n"+summary)
}
func analyzeText(text string) map[string]string {
// First LLM call: Summarize the text
summary := summarizeText(text)
// Second LLM call: Analyze the sentiment of the summary
sentiment := analyzeSentiment(summary)
return map[string]string{"summary": summary, "sentiment": sentiment}
}
func main() {
textToAnalyze := "OpenRouter's unified API has significantly advanced the field of AI development, setting new standards for model accessibility."
result := analyzeText(textToAnalyze)
fmt.Println(result)
}
# Nested calls: summarize the text, then analyze the summary's sentiment
respond() {
curl -s https://openrouter.ai/api/v1/responses \
-H "Authorization: Bearer $OPENROUTER_API_KEY" \
-H "Content-Type: application/json" \
-d "$(jq -n --arg instructions "$1" --arg input "$2" \
'{model: "openai/gpt-4o-mini", instructions: $instructions, input: $input}')" \
| jq -r '[.output[] | select(.type == "message") | .content[] | select(.type == "output_text") | .text] | join("")'
}
TEXT="OpenRouter's unified API has significantly advanced the field of AI development, setting new standards for model accessibility."
# First LLM call: Summarize the text
SUMMARY=$(respond "You summarize texts in a concise manner." "Summarize the following text:
$TEXT")
# Second LLM call: Analyze the sentiment of the summary
SENTIMENT=$(respond "You analyze the sentiment of texts." "Analyze the sentiment of the following summary:
$SUMMARY")
jq -n --arg summary "$SUMMARY" --arg sentiment "$SENTIMENT" '{summary: $summary, sentiment: $sentiment}'
Output
{
summary: "OpenRouter's unified API has improved AI development by enhancing model accessibility and establishing new industry standards.",
sentiment: "The sentiment of the summary is positive. It highlights the improvements brought about by OpenRouter's unified API, specifically in the areas of AI development, model accessibility, and the establishment of new industry standards. The language suggests progress and beneficial changes, reflecting an optimistic view of the impact of OpenRouter's initiatives.",
}
Learn More
- Langfuse OpenRouter Integration: https://langfuse.com/docs/integrations/other/openrouter
- OpenRouter Quick Start Guide: https://openrouter.ai/docs/quickstart
- Langfuse
@observe()Decorator: https://langfuse.com/docs/sdk/python/decorators