Frameworks

You can find a few examples of using OpenRouter with other frameworks in this Github repository. Here are some examples:

Using OpenAI SDK

  • Using npm i openai: github.

    • Tip: You can also use Grit to automatically migrate your code. Simply run npx @getgrit/launcher openrouter.
  • Using pip install openai: github.

import OpenAI from "openai"

const openai = new OpenAI({
  baseURL: "https://openrouter.ai/api/v1",
  apiKey: $OPENROUTER_API_KEY,
  defaultHeaders: {
    "HTTP-Referer": $YOUR_SITE_URL, // Optional, for including your app on openrouter.ai rankings.
    "X-Title": $YOUR_SITE_NAME, // Optional. Shows in rankings on openrouter.ai.
  },
})

async function main() {
  const completion = await openai.chat.completions.create({
    model: "openai/gpt-4o",
    messages: [
      { role: "user", content: "Say this is a test" }
    ],
  })

  console.log(completion.choices[0].message)
}

main()

Using LangChain

const chat = new ChatOpenAI({
  modelName: "anthropic/claude-3.5-sonnet",
  temperature: 0.8,
  streaming: true,
  openAIApiKey: $OPENROUTER_API_KEY,
}, {
  basePath: $OPENROUTER_BASE_URL + "/api/v1",
  baseOptions: {
    headers: {
      "HTTP-Referer": "https://yourapp.com/", // Optional, for including your app on openrouter.ai rankings.
      "X-Title": "Langchain.js Testing", // Optional. Shows in rankings on openrouter.ai.
    },
  },
});

Vercel AI SDK

You can use Vercel AI SDK to use OpenRouter with your Next.js app.

const config = new Configuration({
  basePath: $OPENROUTER_BASE_URL + "/api/v1",
  apiKey: $OPENROUTER_API_KEY,
  baseOptions: {
    headers: {
      "HTTP-Referer": "https://yourapp.com/", // Optional, for including your app on openrouter.ai rankings.
      "X-Title": "Vercel Testing", // Optional. Shows in rankings on openrouter.ai.
    }
  }
})

const openrouter = new OpenAIApi(config)