Getting started overview
This reference details the process for initiating interaction with the OpenRouter platform, focusing on account creation, API key generation, and executing a foundational API request. The objective is to enable developers to make a successful first call to the OpenRouter API, thereby accessing a range of Large Language Models (LLMs) through a single interface.
OpenRouter functions as an intermediary, standardizing the access layer for various LLM providers. This approach aims to streamline the development workflow by abstracting away the unique API specifications of individual models. Users pay based on their token consumption, with costs varying per model and provider, as detailed on the OpenRouter pricing documentation. OpenRouter's architecture aligns with common API gateway patterns, as discussed in general API design principles by Kong's API Gateway learning center, which often involves unified access and traffic management.
The following table provides a quick reference for the steps involved:
| Step | Action | Location/Tool |
|---|---|---|
| 1 | Create an account | OpenRouter website |
| 2 | Generate an API key | OpenRouter dashboard |
| 3 | Install SDK (optional) | pip (Python) or npm/yarn (JavaScript) |
| 4 | Formulate API request | Code editor or terminal (cURL) |
| 5 | Execute API call | Code editor or terminal |
| 6 | Verify response | Terminal output or application logs |
Create an account and get keys
To begin using OpenRouter, you must first register for an account and generate an API key. This key authenticates your requests and associates them with your usage profile.
- Navigate to the OpenRouter website: Go to openrouter.ai.
- Sign up: Click on the "Sign In" or "Get Started" button. You will typically be prompted to sign in using a third-party identity provider like Google, GitHub, or Discord. Select your preferred method and follow the prompts to complete the registration process.
- Access API Keys: Once logged in, locate the "API Keys" section in your dashboard. This is usually accessible via a user icon or a direct link in the navigation menu.
- Create a new key: Click the button to create a new API key. You may be prompted to name your key for easier management, especially if you plan to use multiple keys for different projects.
- Copy your API key: The generated key will be displayed once. It is crucial to copy this key immediately and store it securely, as it typically will not be shown again for security reasons. Treat your API key like a password; do not expose it in client-side code or public repositories.
The API key is a bearer token used in the Authorization header of your HTTP requests. For instance, an API key starting with sk-or- would be included as Authorization: Bearer sk-or-examplekeyXYZ.
Your first request
After obtaining your API key, you can make your first request to the OpenRouter API. This section provides examples using cURL, Python, and JavaScript to demonstrate a basic chat completion request.
Prerequisites
- An OpenRouter API key.
- For Python, install the
openailibrary (which OpenRouter's API is compatible with):pip install openai. - For JavaScript, Node.js and
npmare recommended:npm install openai. - A terminal for cURL commands.
cURL Example
The cURL command allows direct interaction with the API from your terminal, useful for testing and quick verification.
curl https://openrouter.ai/api/v1/chat/completions \
-H "Authorization: Bearer YOUR_OPENROUTER_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "mistralai/mistral-7b-instruct",
"messages": [
{"role": "user", "content": "What is the capital of France?"}
]
}'
Replace YOUR_OPENROUTER_API_KEY with the key you generated. This example requests a response from the mistralai/mistral-7b-instruct model. The -d flag specifies the JSON payload containing the model identifier and the conversation history.
Python Example
Using the Python openai library simplifies interactions. Remember to set your API key as an environment variable or directly in your script (though environment variables are recommended for security).
import os
from openai import OpenAI
# Set your API key as an environment variable or replace 'os.environ.get("OPENROUTER_API_KEY")'
# It is recommended to use an environment variable for security.
client = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key=os.environ.get("OPENROUTER_API_KEY"),
)
chat_completion = client.chat.completions.create(
model="mistralai/mistral-7b-instruct", # Example model. Refer to OpenRouter docs for others.
messages=[
{"role": "user", "content": "Explain the concept of quantum entanglement."}
]
)
print(chat_completion.choices[0].message.content)
To run this Python script, save it as a .py file, set the OPENROUTER_API_KEY environment variable in your terminal (e.g., export OPENROUTER_API_KEY='sk-or-...' on Linux/macOS or $env:OPENROUTER_API_KEY='sk-or-...' on PowerShell), and then execute it with python your_script_name.py.
JavaScript Example (Node.js)
For JavaScript environments, the openai npm package can also be used, configured to point to the OpenRouter API base URL.
import OpenAI from "openai";
// Ensure your API key is available as an environment variable
// or replace process.env.OPENROUTER_API_KEY with your actual key.
const openai = new OpenAI({
baseURL: "https://openrouter.ai/api/v1",
apiKey: process.env.OPENROUTER_API_KEY,
});
async function getCompletion() {
try {
const chatCompletion = await openai.chat.completions.create({
model: "mistralai/mistral-7b-instruct", // Another example model
messages: [{
role: "user",
content: "Describe the function of a neural network."
}],
});
console.log(chatCompletion.choices[0].message.content);
} catch (error) {
console.error("Error fetching completion:", error);
}
}
getCompletion();
Save this as a .js file, ensure Node.js is installed, and set the OPENROUTER_API_KEY environment variable (e.g., export OPENROUTER_API_KEY='sk-or-...'). Then run with node your_script_name.js.
Common next steps
After successfully making your first API call, consider these next steps to further integrate and optimize your use of OpenRouter:
- Explore available models: OpenRouter supports a wide array of LLMs from different providers. Review the OpenRouter models documentation to discover models that best fit your specific use case concerning performance, cost, and capabilities. This may involve experimenting with models like Llama 3, Claude, or various fine-tuned variants.
- Monitor usage and costs: The OpenRouter dashboard provides tools to track your API usage and associated costs. Regularly consult this information, especially given the model-dependent pricing summary, to manage your budget effectively.
- Implement streaming responses: For real-time applications or conversational interfaces, implementing streaming responses can enhance user experience. The OpenRouter API supports streaming, allowing you to receive partial responses as they are generated, rather than waiting for the entire completion.
- Integrate with a prompt playground: OpenRouter offers a prompt playground on its website where you can test different prompts and models directly. This environment can be invaluable for iterating on prompts and comparing model outputs before coding them into your application.
- Error handling and retry logic: Implement robust error handling in your application, including retry logic for transient network issues or rate limit errors. Understanding common OpenRouter API error codes can help inform your retry strategies. For general best practices on API error handling, consult resources like MDN Web Docs on Fetch API error handling.
- Explore advanced features: Investigate features such as custom routing, which allows you to define rules for which models to use based on specific criteria, and fine-tuning options if supported by a particular underlying model.
Troubleshooting the first call
Encountering issues during your first API call is not uncommon. Here are some common problems and their solutions:
- Authentication error (401 Unauthorized):
- Issue: Your API key is incorrect, expired, or missing from the
Authorizationheader. - Solution: Double-check that you have copied the full and correct API key. Ensure it is included in the
Authorization: Bearer YOUR_OPENROUTER_API_KEYheader. Generate a new key if you suspect the old one is compromised or invalid.
- Issue: Your API key is incorrect, expired, or missing from the
- Invalid request payload (400 Bad Request):
- Issue: The JSON body of your request is malformed, or required parameters are missing or incorrect.
- Solution: Verify that your JSON syntax is valid. Ensure that
modelandmessagesare correctly structured and present, as required by the OpenRouter API reference. Pay close attention to quotation marks, commas, and curly braces.
- Model not found or invalid (404 Not Found or 400 Bad Request):
- Issue: The model identifier you provided (e.g.,
"mistralai/mistral-7b-instruct") is incorrect, misspelled, or the model is temporarily unavailable. - Solution: Consult the list of available models in the OpenRouter documentation to ensure you are using a correct and currently supported model identifier.
- Issue: The model identifier you provided (e.g.,
- Rate limit exceeded (429 Too Many Requests):
- Issue: You have sent too many requests in a short period.
- Solution: Implement exponential backoff or introduce delays between your API calls. Check the OpenRouter rate limit documentation for specific thresholds.
- Network connection issues:
- Issue: Your client cannot reach the OpenRouter API endpoint.
- Solution: Verify your internet connection. Check for any firewall or proxy settings that might be blocking outbound requests to
openrouter.ai. Try using a simple cURL command to another known endpoint (e.g.,curl https://google.com) to diagnose general connectivity.
- Environment variable not loaded:
- Issue: In Python or JavaScript examples,
os.environ.get("OPENROUTER_API_KEY")orprocess.env.OPENROUTER_API_KEYreturnsNoneorundefined. - Solution: Ensure you have correctly set the environment variable in your terminal session before running the script. For persistent settings, add it to your shell's profile configuration (e.g.,
.bashrc,.zshrc,.profile).
- Issue: In Python or JavaScript examples,