OpenRouter Audit Logging
Overview
Every OpenRouter API call returns a generation ID and metadata that enables comprehensive audit logging. The generation endpoint (GET /api/v1/generation?id=) provides exact cost, token counts, provider used, and latency -- data that the initial response doesn't always include. This skill covers structured logging, cost tracking, PII redaction, and compliance-ready audit trails.
Core: Generation Metadata Retrieval
import os, json, time, hashlib, logging
from datetime import datetime, timezone
from dataclasses import dataclass, asdict
from typing import Optional
import requests
from openai import OpenAI
log = logging.getLogger("openrouter.audit")
@dataclass
class AuditEntry:
timestamp: str
generation_id: str
model_requested: str
model_used: str # Actual model served (may differ with fallbacks)
prompt_tokens: int
completion_tokens: int
total_cost: float
latency_ms: float
status: str # "success" | "error" | "timeout"
user_id: str
prompt_hash: str # SHA-256 of prompt (not raw content)
error_code: Optional[str] = None
client = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key=os.environ["OPENROUTER_API_KEY"],
default_headers={
"HTTP-Referer": "https://my-app.com",
"X-Title": "my-app",
},
)
def audited_completion(
messages: list[dict],
model: str = "anthropic/claude-3.5-sonnet",
user_id: str = "system",
**kwargs,
) -> tuple:
"""Make a completion request with full audit logging."""
prompt_text = json.dumps(messages)
prompt_hash = hashlib.sha256(prompt_text.encode()).hexdigest()[:16]
start = time.monotonic()
status = "success"
error_code = None
try:
response = client.chat.completions.create(
model=model, messages=messages, **kwargs
)
except Exception as e:
status = "error"
error_code = type(e).__name__
raise
finally:
latency = (time.monotonic() - start) * 1000
# Fetch exact cost from generation endpoint
gen_data = {}
try:
gen = requests.get(
f"https://openrouter.ai/api/v1/generation?id={response.id}",
headers={"Authorization": f"Bearer {os.environ['OPENROUTER_API_KEY']}"},
timeout=5,
).json()
gen_data = gen.get("data", {})
except Exception:
log.warning(f"Failed to fetch generation metadata for {response.id}")
entry = AuditEntry(
timestamp=datetime.now(timezone.utc).isoformat(),
generation_id=response.id,
model_requested=model,
model_used=response.model,
prompt_tokens=response.usage.prompt_tokens,
completion_tokens=response.usage.completion_tokens,
total_cost=float(gen_data.get("total_cost", 0)),
latency_ms=round(latency, 1),
status=status,
user_id=user_id,
prompt_hash=prompt_hash,
error_code=error_code,
)
log.info(json.dumps(asdict(entry)))
return response, entry
Structured Log Storage
import sqlite3
def init_audit_db(db_path: str = "openrouter_audit.db"):
"""Create append-only audit table."""
conn = sqlite3.connect(db_path)
conn.execute("""
CREATE TABLE IF NOT EXISTS audit_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TEXT NOT NULL,
generation_id TEXT UNIQUE NOT NULL,
model_requested TEXT NOT NULL,
model_used TEXT NOT NULL,
prompt_tokens INTEGER,
completion_tokens INTEGER,
total_cost REAL,
latency_ms REAL,
status TEXT NOT NULL,
user_id TEXT,
prompt_hash TEXT,
error_code TEXT
)
""")
conn.execute("CREATE INDEX IF NOT EXISTS idx_audit_ts ON audit_log(timestamp)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_audit_user ON audit_log(user_id)")
conn.commit()
return conn
def write_audit(conn: sqlite3.Connection, entry: AuditEntry):
"""Write audit entry to SQLite (append-only)."""
conn.execute(
"""INSERT OR IGNORE INTO audit_log
(timestamp, generation_id, model_requested, model_used,
prompt_tokens, completion_tokens, total_cost, latency_ms,
status, user_id, prompt_hash, error_code)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(entry.timestamp, entry.generation_id, entry.model_requested,
entry.model_used, entry.prompt_tokens, entry.completion_tokens,
entry.total_cost, entry.latency_ms, entry.status, entry.user_id,
entry.prompt_hash, entry.error_code),
)
conn.commit()
PII Redaction Before Logging
import re
PII_PATTERNS = [
(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', '[EMAIL]'),
(r'\b\d{3}[-.]?\d{3}[-.]?\d{4}\b', '[PHONE]'),
(r'\b\d{3}-\d{2}-\d{4}\b', '[SSN]'),
(r'\bsk-or-v1-[a-zA-Z0-9]+\b', '[API_KEY]'),
(r'\b(?:\d{4}[- ]?){3}\d{4}\b', '[CARD]'),
]
def redact_pii(text: str) -> str:
"""Scrub PII from text before logging."""
for pattern, replacement in PII_PATTERNS:
text = re.sub(pattern, replacement, text)
return text
Audit Queries
-- Daily cost by model
SELECT date(timestamp) as day, model_used,
COUNT(*) as requests, SUM(total_cost) as cost
FROM audit_log GROUP BY day, model_used ORDER BY day DESC, cost DESC;
-- Error rate by model (last 24h)
SELECT model_requested, COUNT(*) as total,
SUM(CASE WHEN status = 'error' THEN 1 ELSE 0 END) as errors,
ROUND(100.0 * SUM(CASE WHEN status='error' THEN 1 ELSE 0 END) / COUNT(*), 1) as error_pct
FROM audit_log WHERE timestamp > datetime('now', '-1 day')
GROUP BY model_requested;
-- Top spenders
SELECT user_id, COUNT(*) as requests, SUM(total_cost) as total_cost
FROM audit_log GROUP BY user_id ORDER BY total_cost DESC LIMIT 10;
Error Handling
| Error |
Cause |
Fix |
| Generation endpoint 404 |
Generation ID not found or too old |
Fetch within 30 minutes of request |
| Duplicate generation_id |
Retry wrote same request twice |
Use INSERT OR IGNORE |
Missing total_cost |
Generation still processing |
Retry fetch after 1-2 seconds |
| Auth 401 on generation fetch |
Wrong API key for that generation |
Use same key that made the request |
Enterprise Considerations
- Log to append-only storage (SQLite WAL mode, S3, or centralized logging) to prevent tampering
- Hash prompts rather than logging raw content to satisfy data residency requirements
- Set log retention policies (90 days for operational, 7 years for financial compliance)
- Ship structured JSON logs to SIEM (Splunk, Datadog, ELK) for real-time alerting
- Use
user_id field to enable per-user cost attribution and abuse detection
- Index
generation_id for fast correlation with OpenRouter dashboard
References
1---
2name: openrouter-audit-logging
3description: |
4 Implement audit logging for OpenRouter API calls. Use when building compliance trails, debugging production issues, or tracking model usage. Triggers: 'openrouter audit', 'openrouter logging', 'audit trail openrouter', 'log openrouter requests'.
5allowed-tools: Read, Write, Edit, Bash, Grep
6version: 2.0.0
7license: MIT
8author: Jeremy Longshore <jeremy@intentsolutions.io>
9compatible-with: claude-code, codex, openclaw
10tags: [saas, openrouter, security, logging, compliance]
11metadata:
12 source: https://skillmd.com/skills/aibot88/openrouter-audit-logging
13---
14
15# OpenRouter Audit Logging
16
17## Overview
18
19Every OpenRouter API call returns a generation ID and metadata that enables comprehensive audit logging. The generation endpoint (`GET /api/v1/generation?id=`) provides exact cost, token counts, provider used, and latency -- data that the initial response doesn't always include. This skill covers structured logging, cost tracking, PII redaction, and compliance-ready audit trails.
20
21## Core: Generation Metadata Retrieval
22
23```python
24import os, json, time, hashlib, logging
25from datetime import datetime, timezone
26from dataclasses import dataclass, asdict
27from typing import Optional
28import requests
29from openai import OpenAI
30
31log = logging.getLogger("openrouter.audit")
32
33@dataclass
34class AuditEntry:
35 timestamp: str
36 generation_id: str
37 model_requested: str
38 model_used: str # Actual model served (may differ with fallbacks)
39 prompt_tokens: int
40 completion_tokens: int
41 total_cost: float
42 latency_ms: float
43 status: str # "success" | "error" | "timeout"
44 user_id: str
45 prompt_hash: str # SHA-256 of prompt (not raw content)
46 error_code: Optional[str] = None
47
48client = OpenAI(
49 base_url="https://openrouter.ai/api/v1",
50 api_key=os.environ["OPENROUTER_API_KEY"],
51 default_headers={
52 "HTTP-Referer": "https://my-app.com",
53 "X-Title": "my-app",
54 },
55)
56
57def audited_completion(
58 messages: list[dict],
59 model: str = "anthropic/claude-3.5-sonnet",
60 user_id: str = "system",
61 **kwargs,
62) -> tuple:
63 """Make a completion request with full audit logging."""
64 prompt_text = json.dumps(messages)
65 prompt_hash = hashlib.sha256(prompt_text.encode()).hexdigest()[:16]
66
67 start = time.monotonic()
68 status = "success"
69 error_code = None
70
71 try:
72 response = client.chat.completions.create(
73 model=model, messages=messages, **kwargs
74 )
75 except Exception as e:
76 status = "error"
77 error_code = type(e).__name__
78 raise
79 finally:
80 latency = (time.monotonic() - start) * 1000
81
82 # Fetch exact cost from generation endpoint
83 gen_data = {}
84 try:
85 gen = requests.get(
86 f"https://openrouter.ai/api/v1/generation?id={response.id}",
87 headers={"Authorization": f"Bearer {os.environ['OPENROUTER_API_KEY']}"},
88 timeout=5,
89 ).json()
90 gen_data = gen.get("data", {})
91 except Exception:
92 log.warning(f"Failed to fetch generation metadata for {response.id}")
93
94 entry = AuditEntry(
95 timestamp=datetime.now(timezone.utc).isoformat(),
96 generation_id=response.id,
97 model_requested=model,
98 model_used=response.model,
99 prompt_tokens=response.usage.prompt_tokens,
100 completion_tokens=response.usage.completion_tokens,
101 total_cost=float(gen_data.get("total_cost", 0)),
102 latency_ms=round(latency, 1),
103 status=status,
104 user_id=user_id,
105 prompt_hash=prompt_hash,
106 error_code=error_code,
107 )
108
109 log.info(json.dumps(asdict(entry)))
110 return response, entry
111```
112
113## Structured Log Storage
114
115```python
116import sqlite3
117
118def init_audit_db(db_path: str = "openrouter_audit.db"):
119 """Create append-only audit table."""
120 conn = sqlite3.connect(db_path)
121 conn.execute("""
122 CREATE TABLE IF NOT EXISTS audit_log (
123 id INTEGER PRIMARY KEY AUTOINCREMENT,
124 timestamp TEXT NOT NULL,
125 generation_id TEXT UNIQUE NOT NULL,
126 model_requested TEXT NOT NULL,
127 model_used TEXT NOT NULL,
128 prompt_tokens INTEGER,
129 completion_tokens INTEGER,
130 total_cost REAL,
131 latency_ms REAL,
132 status TEXT NOT NULL,
133 user_id TEXT,
134 prompt_hash TEXT,
135 error_code TEXT
136 )
137 """)
138 conn.execute("CREATE INDEX IF NOT EXISTS idx_audit_ts ON audit_log(timestamp)")
139 conn.execute("CREATE INDEX IF NOT EXISTS idx_audit_user ON audit_log(user_id)")
140 conn.commit()
141 return conn
142
143def write_audit(conn: sqlite3.Connection, entry: AuditEntry):
144 """Write audit entry to SQLite (append-only)."""
145 conn.execute(
146 """INSERT OR IGNORE INTO audit_log
147 (timestamp, generation_id, model_requested, model_used,
148 prompt_tokens, completion_tokens, total_cost, latency_ms,
149 status, user_id, prompt_hash, error_code)
150 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
151 (entry.timestamp, entry.generation_id, entry.model_requested,
152 entry.model_used, entry.prompt_tokens, entry.completion_tokens,
153 entry.total_cost, entry.latency_ms, entry.status, entry.user_id,
154 entry.prompt_hash, entry.error_code),
155 )
156 conn.commit()
157```
158
159## PII Redaction Before Logging
160
161```python
162import re
163
164PII_PATTERNS = [
165 (r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', '[EMAIL]'),
166 (r'\b\d{3}[-.]?\d{3}[-.]?\d{4}\b', '[PHONE]'),
167 (r'\b\d{3}-\d{2}-\d{4}\b', '[SSN]'),
168 (r'\bsk-or-v1-[a-zA-Z0-9]+\b', '[API_KEY]'),
169 (r'\b(?:\d{4}[- ]?){3}\d{4}\b', '[CARD]'),
170]
171
172def redact_pii(text: str) -> str:
173 """Scrub PII from text before logging."""
174 for pattern, replacement in PII_PATTERNS:
175 text = re.sub(pattern, replacement, text)
176 return text
177```
178
179## Audit Queries
180
181```sql
182-- Daily cost by model
183SELECT date(timestamp) as day, model_used,
184 COUNT(*) as requests, SUM(total_cost) as cost
185FROM audit_log GROUP BY day, model_used ORDER BY day DESC, cost DESC;
186
187-- Error rate by model (last 24h)
188SELECT model_requested, COUNT(*) as total,
189 SUM(CASE WHEN status = 'error' THEN 1 ELSE 0 END) as errors,
190 ROUND(100.0 * SUM(CASE WHEN status='error' THEN 1 ELSE 0 END) / COUNT(*), 1) as error_pct
191FROM audit_log WHERE timestamp > datetime('now', '-1 day')
192GROUP BY model_requested;
193
194-- Top spenders
195SELECT user_id, COUNT(*) as requests, SUM(total_cost) as total_cost
196FROM audit_log GROUP BY user_id ORDER BY total_cost DESC LIMIT 10;
197```
198
199## Error Handling
200
201| Error | Cause | Fix |
202|-------|-------|-----|
203| Generation endpoint 404 | Generation ID not found or too old | Fetch within 30 minutes of request |
204| Duplicate generation_id | Retry wrote same request twice | Use `INSERT OR IGNORE` |
205| Missing `total_cost` | Generation still processing | Retry fetch after 1-2 seconds |
206| Auth 401 on generation fetch | Wrong API key for that generation | Use same key that made the request |
207
208## Enterprise Considerations
209
210- Log to append-only storage (SQLite WAL mode, S3, or centralized logging) to prevent tampering
211- Hash prompts rather than logging raw content to satisfy data residency requirements
212- Set log retention policies (90 days for operational, 7 years for financial compliance)
213- Ship structured JSON logs to SIEM (Splunk, Datadog, ELK) for real-time alerting
214- Use `user_id` field to enable per-user cost attribution and abuse detection
215- Index `generation_id` for fast correlation with OpenRouter dashboard
216
217## References
218
219- [Examples](${CLAUDE_SKILL_DIR}/references/examples.md) | [Errors](${CLAUDE_SKILL_DIR}/references/errors.md)
220- [Generation API](https://openrouter.ai/docs/api/api-reference/generation-queries/query-a-generation) | [Auth/Key Info](https://openrouter.ai/docs/api/reference/authentication)