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

# Arize AX

> Using OpenRouter with Arize AX

## Using Arize AX

[Arize AX](https://arize.com/) provides observability and tracing for LLM applications. Since OpenRouter uses the OpenAI API schema, you can use Arize's OpenInference auto-instrumentation with the OpenAI SDK to automatically trace and monitor your OpenRouter API calls.

### Installation

```bash lines theme={null}
pip install openinference-instrumentation-openai openai arize-otel
```

### Prerequisites

* OpenRouter account and API key
* Arize account with Space ID and API Key

### Why OpenRouter Works with Arize AX

Arize's OpenInference auto-instrumentation works with OpenRouter because:

1. **OpenRouter provides a fully OpenAI-API-compatible endpoint** - The `/v1` endpoint mirrors OpenAI's schema, including the [Responses API](https://openrouter.ai/docs/api_reference/responses/overview.md)
2. **Reuse official OpenAI SDKs** - Point the OpenAI client's `base_url` to OpenRouter
3. **Automatic instrumentation** - OpenInference hooks into OpenAI SDK calls seamlessly

### Configuration

Set up your environment variables:

```python title="Environment Setup" lines theme={null}
import os

# Set your OpenRouter API key
os.environ["OPENAI_API_KEY"] = "<OPENROUTER_API_KEY>"
```

```bash title="cURL" lines theme={null}
# Environment Setup
# Set your OpenRouter API key
export OPENAI_API_KEY="$OPENROUTER_API_KEY"
```

```bash title="cURL" lines theme={null}
# Set your OpenRouter API key
export OPENAI_API_KEY="$OPENROUTER_API_KEY"
```

### Simple LLM Call

The Python example configures Arize AX and instruments the OpenAI SDK to trace OpenRouter calls. The other tabs make equivalent API requests without sending traces to Arize.

```python title="Basic Integration" expandable lines theme={null}
from arize.otel import register
from openinference.instrumentation.openai import OpenAIInstrumentor
import openai

# Initialize Arize and register the tracer provider
tracer_provider = register(
    space_id="your-space-id",
    api_key="your-arize-api-key",
    project_name="your-project-name",
)

# Instrument OpenAI SDK
OpenAIInstrumentor().instrument(tracer_provider=tracer_provider)

# Configure OpenAI client for OpenRouter
client = openai.OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key="your_openrouter_api_key",
    default_headers={
        "HTTP-Referer": "<YOUR_SITE_URL>",  # Optional: Your site URL
        "X-OpenRouter-Title": "<YOUR_SITE_NAME>",      # Optional: Your site name
    }
)

# Make a traced Responses API request
response = client.responses.create(
    model="meta-llama/llama-3.1-8b-instruct:free",
    input="Write a haiku about observability.",
)

# Print the assistant's reply
print(response.output_text)
```

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

// Configure OpenAI client for OpenRouter
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 an untraced Responses API request
const response = await client.responses.create({
  model: 'openai/gpt-4o-mini',
  input: 'Write a haiku about observability.',
});

// Print the assistant's reply
console.log(response.output_text);

```

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

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

// Note: OpenInference auto-instrumentation is not available for Go.
// Export spans to Arize with the OpenTelemetry Go SDK if you need tracing.
func main() {
	body, _ := json.Marshal(map[string]any{
		"model": "openai/gpt-4o-mini",
		"input": "Write a haiku about observability.",
	})

	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

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		b, _ := io.ReadAll(resp.Body)
		log.Fatalf("request failed: %s: %s", resp.Status, b)
	}

	var result struct {
		Output []struct {
			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)
	}

	// Print the assistant's reply
	for _, item := range result.Output {
		for _, c := range item.Content {
			if c.Type == "output_text" {
				fmt.Print(c.Text)
			}
		}
	}
	fmt.Println()
}

```

```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" \
  -H "HTTP-Referer: <YOUR_SITE_URL>" \
  -H "X-OpenRouter-Title: <YOUR_SITE_NAME>" \
  -d '{
    "model": "meta-llama/llama-3.1-8b-instruct",
    "input": "Write a haiku about observability."
  }' | jq -r '.output[] | select(.type == "message") | .content[] | select(.type == "output_text") | .text'
```

```text title="Output" theme={null}
Data flows like streams,  
Insights bloom in silent depths,  
Truth revealed in light.
```

### What Gets Traced

All OpenRouter model calls are automatically traced and include:

* Request/response data and timing
* Model name and provider information
* Token usage and cost data (when supported)
* Error handling and debugging information

### JavaScript/TypeScript Support

OpenInference also provides instrumentation for the OpenAI JavaScript/TypeScript SDK, which works with OpenRouter. For setup and examples, please refer to the [OpenInference JavaScript examples for OpenAI](https://github.com/Arize-ai/openinference/tree/main/js).

### Common Issues

* **API Key**: Use your OpenRouter API key, not OpenAI's
* **Model Names**: Use exact model names from [OpenRouter's model list](https://openrouter.ai/models)
* **Rate Limits**: Check your OpenRouter dashboard for usage limits

### Learn More

* **Arize AX OpenRouter Integration**: [https://arize.com/docs/ax/integrations/llm-providers/openrouter/openrouter-tracing](https://arize.com/docs/ax/integrations/llm-providers/openrouter/openrouter-tracing)
* **OpenRouter Quick Start Guide**: [https://openrouter.ai/docs/quickstart](https://openrouter.ai/docs/quickstart.md)
* **OpenInference OpenAI Instrumentation**: [https://github.com/Arize-ai/openinference/tree/main/python/instrumentation/openinference-instrumentation-openai](https://github.com/Arize-ai/openinference/tree/main/python/instrumentation/openinference-instrumentation-openai)
