Switch the OpenAI JS/TS SDK to use OpenRouter.
Apply with the Grit CLI
grit apply openrouter
Basic OpenAI Node SDK
BEFORE
import OpenAI from 'openai'; const openai = new OpenAI({ apiKey: OPENROUTER_API_KEY, }); async function main() { const completion = await openai.chat.completions.create({ messages: [{ role: 'user', content: 'Say this is a test' }], model: 'gpt-3.5-turbo', }); console.log(completion.choices); // Streaming responses const stream = await openai.chat.completions.create({ model: 'gpt-4', messages: [{ role: 'user', content: 'Say this is a test' }], stream: true, }); for await (const part of stream) { process.stdout.write(part.choices[0]?.delta?.content || ''); } } main();
AFTER
import OpenAI from "openai"; const openai = new OpenAI({ apiKey: OPENROUTER_API_KEY, baseURL: "https://openrouter.ai/api/v1", defaultHeaders: { "HTTP-Referer": YOUR_SITE_URL, "X-Title": YOUR_SITE_NAME, // Optional. Shows on openrouter.ai }, }); async function main() { const completion = await openai.chat.completions.create({ messages: [{ role: "user", content: "Say this is a test" }], model: "openai/gpt-3.5-turbo", }); console.log(completion.choices); // Streaming responses const stream = await openai.chat.completions.create({ model: "openai/gpt-4", messages: [{ role: "user", content: "Say this is a test" }], stream: true, }); for await (const part of stream) { process.stdout.write(part.choices[0]?.delta?.content || ""); } } main();
Merges headers
BEFORE
import OpenAI from 'openai'; const openai = new OpenAI({ apiKey: OPENROUTER_API_KEY, defaultHeaders: { 'X-Custom-Header': 'hello', }, });
AFTER
import OpenAI from "openai"; const openai = new OpenAI({ apiKey: OPENROUTER_API_KEY, defaultHeaders: { "X-Custom-Header": "hello", "HTTP-Referer": YOUR_SITE_URL, "X-Title": YOUR_SITE_NAME, }, baseURL: "https://openrouter.ai/api/v1", });