SDKs overview
OpenRouter provides a unified API endpoint designed to facilitate access to a diverse range of large language models (LLMs) from various providers through a single interface. To streamline integration for developers, OpenRouter offers official software development kits (SDKs) that abstract the direct HTTP API calls into language-native functions and objects. These SDKs are maintained by the OpenRouter team and are intended to provide a stable and idiomatic way to interact with the platform's services, including chat completions, streaming responses, and model metadata retrieval. The primary benefit of using an SDK is reduced boilerplate code and easier management of API requests and responses, allowing developers to focus on application logic rather than low-level networking and serialization concerns.
The OpenRouter platform itself acts as a gateway, routing requests to the specified LLM while standardizing the input and output formats. This approach allows developers to switch between different models with minimal code changes, supporting use cases such as A/B testing models, optimizing costs by selecting the most efficient model for a task, or leveraging specialized models for specific functions. The SDKs are designed to reflect this abstraction, presenting a consistent interface regardless of the underlying LLM selected. This architecture is particularly beneficial for rapid prototyping and deploying applications that require flexibility in their LLM backend (OpenRouter API Documentation).
Official SDKs by language
OpenRouter maintains official SDKs for the most common programming languages used in AI and web development. These SDKs are designed to provide a consistent and reliable interface for interacting with the OpenRouter API. The official SDKs are regularly updated to ensure compatibility with the latest API versions and to incorporate new features or improvements. Developers are encouraged to use these official libraries for their projects to ensure full access to OpenRouter's capabilities and to benefit from ongoing support.
| Language | Package Name | Install Command | Maturity |
|---|---|---|---|
| Python | openrouter |
pip install openrouter |
Stable |
| JavaScript | openrouter |
npm install openrouter or yarn add openrouter |
Stable |
Installation
Installing the OpenRouter SDKs is typically performed using the standard package managers for each respective language environment. This process ensures that all necessary dependencies are resolved and the library is correctly integrated into your project. Before installation, developers should ensure they have a compatible version of Python or Node.js installed on their system.
Python SDK Installation
The Python SDK for OpenRouter can be installed via pip, the standard package installer for Python. It is recommended to install libraries within a virtual environment to manage project-specific dependencies and avoid conflicts with system-wide packages. Virtual environments can be created using tools like venv or conda.
# Create a virtual environment (optional but recommended)
python -m venv openrouter_env
source openrouter_env/bin/activate # On Windows, use `openrouter_env\Scripts\activate`
# Install the OpenRouter Python SDK
pip install openrouter
After installation, the SDK can be imported into Python scripts and used to make API calls to OpenRouter. Ensure that your OpenRouter API key is securely configured, typically through environment variables, to authenticate your requests (OpenRouter Authentication Guide).
JavaScript SDK Installation
The JavaScript SDK is available through npm (Node Package Manager) and yarn, which are package managers for JavaScript runtime environments. Developers can add the openrouter package to their project using either command, depending on their preferred package manager.
# Using npm
npm install openrouter
# Or using yarn
yarn add openrouter
Once installed, the SDK can be imported into Node.js applications or front-end JavaScript projects that use module bundlers like Webpack or Rollup. Similar to the Python SDK, API keys should be handled securely, especially in client-side applications where direct exposure could lead to security vulnerabilities. For server-side Node.js applications, environment variables are the recommended method for API key management (MDN Web Storage API documentation offers context on client-side storage considerations).
Quickstart example
This section provides a basic quickstart example for both the Python and JavaScript SDKs, demonstrating how to make a simple chat completion request using the OpenRouter API. These examples assume that the respective SDKs have been installed and that an OpenRouter API key is available and configured.
Python Quickstart
The following Python code snippet illustrates how to send a chat message to a specified LLM via OpenRouter and receive a response. This example uses a placeholder model and an API key stored as an environment variable.
import os
from openrouter import OpenAI
# Initialize the OpenRouter client with your API key
# It's recommended to set OPENROUTER_API_KEY as an environment variable
client = OpenAI(api_key=os.environ.get("OPENROUTER_API_KEY"))
def get_chat_completion(prompt_message: str, model_name: str = "nousresearch/nous-hermes-2-mixtral-8x7b-dpo"):
try:
response = client.chat.completions.create(
model=model_name,
messages=[
{"role": "user", "content": prompt_message}
],
temperature=0.7,
max_tokens=150
)
return response.choices[0].message.content
except Exception as e:
return f"An error occurred: {e}"
if __name__ == "__main__":
user_prompt = "Explain the concept of quantum entanglement in simple terms."
completion = get_chat_completion(user_prompt)
print(f"User: {user_prompt}")
print(f"OpenRouter ({'nousresearch/nous-hermes-2-mixtral-8x7b-dpo'}): {completion}")
print("\n--- Streaming Example ---")
print(f"User: {user_prompt}")
stream_response = client.chat.completions.create(
model="mistralai/mixtral-8x7b-instruct",
messages=[
{"role": "user", "content": user_prompt}
],
stream=True
)
for chunk in stream_response:
if chunk.choices[0].delta.content is not None:
print(chunk.choices[0].delta.content, end="")
print()
This example demonstrates both a standard completion request and a streaming response, which is useful for real-time applications where partial responses can be displayed as they are generated. The model parameter specifies which LLM to use, and OpenRouter handles the routing and interaction with that specific model (OpenRouter API Reference offers more detail on parameters).
JavaScript Quickstart
The following JavaScript code snippet demonstrates how to achieve a similar chat completion using the OpenRouter JavaScript SDK. This example is suitable for Node.js environments and uses an environment variable for the API key.
import OpenAI from 'openrouter';
// Initialize the OpenRouter client with your API key
// It's recommended to set OPENROUTER_API_KEY as an environment variable
const client = new OpenAI({
apiKey: process.env.OPENROUTER_API_KEY,
});
async function getChatCompletion(promptMessage, modelName = "nousresearch/nous-hermes-2-mixtral-8x7b-dpo") {
try {
const response = await client.chat.completions.create({
model: modelName,
messages: [
{ role: "user", content: promptMessage }
],
temperature: 0.7,
max_tokens: 150,
});
return response.choices[0].message.content;
} catch (error) {
return `An error occurred: ${error.message}`;
}
}
async function main() {
const userPrompt = "What are the key differences between classical and quantum computing?";
const completion = await getChatCompletion(userPrompt);
console.log(`User: ${userPrompt}`);
console.log(`OpenRouter (${'nousresearch/nous-hermes-2-mixtral-8x7b-dpo'}): ${completion}`);
console.log("\n--- Streaming Example ---");
console.log(`User: ${userPrompt}`);
const streamResponse = await client.chat.completions.create({
model: "mistralai/mixtral-8x7b-instruct",
messages: [
{ role: "user", content: userPrompt }
],
stream: true,
});
for await (const chunk of streamResponse) {
if (chunk.choices[0].delta.content !== undefined) {
process.stdout.write(chunk.choices[0].delta.content);
}
}
console.log();
}
main();
This JavaScript example also covers both standard and streaming chat completions, demonstrating the asynchronous nature of API calls in JavaScript using async/await. Developers should ensure their Node.js environment supports ES modules if using import statements, or adjust to require syntax for CommonJS environments (Node.js ES Modules documentation).
Community libraries
While OpenRouter provides official SDKs, the open-source community often develops additional libraries, connectors, and tools that extend functionality or integrate OpenRouter with other platforms and frameworks. These community-contributed projects can offer specialized utilities, integrations with specific web frameworks (e.g., Flask, Express), or client libraries in languages not officially supported by OpenRouter. Community libraries are typically found on platforms like GitHub and PyPI, and their quality, maintenance, and compatibility can vary.
Developers considering using community libraries should evaluate their active development status, community support, and alignment with their project's requirements. Reviewing the source code, issue trackers, and contribution guidelines is recommended to assess the reliability and security of these external tools. While OpenRouter does not officially endorse or maintain these projects, they can sometimes fill specific niches or provide alternative approaches to integration. Examples of such community efforts often involve wrappers for specific application types or integrations into larger AI orchestration frameworks, similar to how other API providers see community contributions for their services (Google API client libraries are an example of a robust ecosystem of official and community-contributed tools).
Currently, the primary community interaction with OpenRouter often revolves around direct API calls via cURL or basic HTTP clients in languages without official SDKs, or through frameworks that abstract API interactions like LangChain or LlamaIndex which can be configured to use any OpenAI-compatible endpoint, including OpenRouter. Specific community-driven wrappers may emerge as the platform gains wider adoption.