Switch Your OpenAI SDK to Openrouter API in Two Lines: A base_url Migration Guide
Moving an OpenAI SDK application to Openrouter API starts with two configuration changes: the API base URL and the API key.

Moving an OpenAI SDK application to Openrouter API starts with two configuration changes: the API base URL and the API key. For an existing Chat Completions integration, you can usually keep the same request-building and response-handling code, then validate model capabilities, streaming, and failure handling before routing production traffic.
The two-line change
Openrouter API provides one API key and one OpenAI-compatible base URL for 250+ chat, image, video, and audio models:
base_url="https://openrouterapi.ru/v1",
api_key=os.environ["OPENROUTERAPI_API_KEY"],Those settings belong in your OpenAI client constructor. Your application still uses the official SDK; you are changing where it sends requests and which credential it presents.
Keep the scope of this migration clear. Changing the endpoint is not the same as changing the model. If you want to isolate integration problems, first retain your existing model ID—provided it is available through Openrouter API—and change only the connection settings. Evaluate alternative models separately.
Openrouter API uses pay-as-you-go billing in USD. Only successful requests are billed, the minimum top-up is $50, and credits never expire. Check the current pricing and docs before deployment.
What changes, and what stays familiar?
| Integration concern | Migration action | What to validate |
|---|---|---|
| Base URL | Set https://openrouterapi.ru/v1 | Requests reach the intended gateway |
| API key | Supply your Openrouter API key | The application does not accidentally use its previous provider credential |
| Request and response schema | Keep the OpenAI-compatible Chat Completions structure | Your application’s actual fields and response parsing |
| Streaming | Keep your SSE-based streaming path | Chunk handling, completion, cancellation, and disconnects |
| Tools/function calling | Keep the existing flow where supported | Tool schemas, argument parsing, and tool-result messages |
| JSON mode | Retain supported JSON-mode configuration | Valid JSON and application-level schema validation |
| Model selection | Use an available model ID | Capability and parameter support for that model |
| Error handling | Review status handling and retries | Authentication, balance, rate limits, and server failures |
The important qualification is where supported. An OpenAI-compatible interface does not make every model interchangeable. Tool use, JSON output, and optional parameters still need verification for your selected model.
Also, inspect which SDK resource your application calls. The examples below use Chat Completions. Do not assume that every resource exposed by an OpenAI SDK is available merely because the client accepts a different base URL.
Python: keep the SDK, replace the connection settings
Here is a minimal before-and-after using the official openai Python package:
import os
from openai import OpenAI
# Before: default OpenAI connection settings.
before = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
# After: Openrouter API connection settings.
# OPENROUTERAPI_API_KEY contains your $OPENROUTERAPI_API_KEY placeholder value.
after = OpenAI(
base_url="https://openrouterapi.ru/v1",
api_key=os.environ["OPENROUTERAPI_API_KEY"],
)
response = after.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "user", "content": "Reply with one sentence about API testing."}
],
)
print(response.choices[0].message.content)
print(response.usage)The message array and response access remain familiar. You still call chat.completions.create, read the returned choice, and inspect usage.
In a real application, avoid constructing a new client inside every request handler. Initialize the client in your dependency-injection layer or application startup code, then reuse it according to your SDK’s lifecycle guidance.
Keep keys out of source control. Load them from your deployment secret store or environment, and do not print client configuration if it might expose credentials.
Node.js: the same change, different casing
The official JavaScript SDK uses baseURL, while the Python SDK uses base_url. That casing difference is easy to miss when moving examples between languages.
import OpenAI from "openai";
// Before: default OpenAI connection settings.
const before = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
// After: Openrouter API connection settings.
// OPENROUTERAPI_API_KEY contains your $OPENROUTERAPI_API_KEY placeholder value.
const after = new OpenAI({
baseURL: "https://openrouterapi.ru/v1",
apiKey: process.env.OPENROUTERAPI_API_KEY,
});
const response = await after.chat.completions.create({
model: "gpt-4o-mini",
messages: [
{ role: "user", content: "Reply with one sentence about API testing." },
],
});
console.log(response.choices[0].message.content);
console.log(response.usage);Keep this client on the server. A browser bundle is not a safe place for a gateway key; route browser requests through your own backend.
If your application already wraps model calls behind a service function, make the change there rather than editing every call site. Centralized configuration makes testing, credential rotation, and rollback easier.
curl: verify the connection without a framework
A raw HTTP request helps separate SDK problems from endpoint or credential problems. The following example assumes OPENAI_BASE_URL and OPENAI_API_KEY initially contain your existing connection settings.
# Before: use your currently configured provider.
curl "$OPENAI_BASE_URL/chat/completions" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-4o-mini",
"messages": [{"role": "user", "content": "Reply with: migration check"}]
}'
# After: send the same payload to Openrouter API.
curl "https://openrouterapi.ru/v1/chat/completions" \
-H "Authorization: Bearer $OPENROUTERAPI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-4o-mini",
"messages": [{"role": "user", "content": "Reply with: migration check"}]
}'The after request uses the Authorization: Bearer <OPENROUTERAPI_API_KEY> authentication format.
Notice that the SDK base URL ends at /v1, while the complete HTTP endpoint includes /chat/completions. Do not give an SDK the full completion endpoint as its base URL; the client appends its resource path.
Use environment variables for deployment configuration
If your application already constructs OpenAI() without explicit connection arguments, the environment-variable approach can minimize code changes:
# $OPENROUTERAPI_API_KEY is a placeholder for your Openrouter API secret.
export OPENAI_BASE_URL="https://openrouterapi.ru/v1"
export OPENAI_API_KEY="$OPENROUTERAPI_API_KEY"With SDK versions that read these variables, the normal client constructor can use the new settings. Explicit constructor arguments generally take precedence, so search for hard-coded URLs and credentials before assuming an environment change is enough.
Check every process that makes model requests: web servers, background workers, scheduled jobs, evaluation scripts, and local development tools. Updating only the web deployment can leave workers using the old provider.
Also inspect environment inheritance. Containers, process managers, and CI jobs may not receive variables exported in your interactive shell. Validate the effective base URL at startup, but log only the URL—not the secret.
Using OpenAI-named variables does not mean you should keep an OpenAI credential in them. After this change, OPENAI_API_KEY must contain the Openrouter API key for requests going to Openrouter API.
Frameworks: configure the model client
Framework integrations usually expose provider settings somewhere beneath their high-level model abstraction. Put the Openrouter API base URL and credential there, rather than trying to modify generated request URLs afterward.
| Framework | Where to make the change | Practical caution |
|---|---|---|
| LangChain | OpenAI integration’s client/provider configuration; JavaScript integrations commonly expose configuration.baseURL | Ensure chains and agents use the configured model instance |
| LlamaIndex | OpenAI provider or underlying client options | Option names vary by language and version; Python integrations may use api_base |
| Vercel AI SDK | OpenAI provider factory’s baseURL and apiKey | Select the Chat Completions model path for this migration |
For Vercel AI SDK versions supporting this provider interface, the configuration looks like:
import { createOpenAI } from "@ai-sdk/openai";
const openrouterapi = createOpenAI({
baseURL: "https://openrouterapi.ru/v1",
apiKey: process.env.OPENROUTERAPI_API_KEY, // supplied as $OPENROUTERAPI_API_KEY
});
const model = openrouterapi.chat("gpt-4o-mini");For LangChain and LlamaIndex, consult the documentation for your installed integration version. The goal is the same—pass baseURL, or that integration’s equivalent, to the underlying OpenAI-compatible client—but constructor names are not universal.
Afterward, trace one actual request. Frameworks may create separate clients for different tasks or fall back to environment defaults. Configuring one chat model does not automatically migrate every model call in the application.
Pick a model deliberately
Openrouter API’s unified chat interface supports text-generation models, but price, input capacity, and native protocol options differ. These supplied model figures provide a starting point:
| Model | Input price | Output price | Cached input price | Max input |
|---|---|---|---|---|
gpt-5.5 | $4.40 per 1M tokens | $26.40 per 1M tokens | $0.44 per 1M tokens | 922,000 tokens |
gpt-4o | $2.20 per 1M tokens | $8.80 per 1M tokens | $1.10 per 1M tokens | 128,000 tokens |
gpt-4o-mini | $0.132 per 1M tokens | $0.528 per 1M tokens | $0.066 per 1M tokens | 128,000 tokens |
claude-sonnet-4-6 | $2.64 per 1M tokens | $13.20 per 1M tokens | $0.264 per 1M tokens | 1,000,000 tokens |
The three OpenAI models above use the unified chat API interface. claude-sonnet-4-6 also supports the native Anthropic Claude Messages protocol at POST /v1/messages, where Anthropic-style x-api-key authentication is accepted.
Native Anthropic requests are a separate integration choice, not a two-line OpenAI SDK migration. Likewise, native Gemini uses /v1beta/models/{model}:generateContent. Stay with the OpenAI-compatible chat interface when the goal is to preserve your existing chat code.
Treat cached-input pricing separately from ordinary input pricing. Do not estimate savings by assuming every prompt receives the cached rate, and do not interpret maximum input size as an output allowance.
A practical migration test checklist
1. List models and run a smoke prompt
Start by confirming that your credential works and your intended model is listed:
curl --fail-with-body "https://openrouterapi.ru/v1/models" \
-H "Authorization: Bearer $OPENROUTERAPI_API_KEY"Then run a short, non-sensitive prompt through the exact SDK client your application will use. Check that your code can extract the response and tolerate missing or optional fields.
A successful curl request is useful, but it does not prove that your framework configuration is correct.
2. Compare token usage
Run representative prompts through your old and new configurations, retaining the same model and request settings where possible.
Record reported input and output usage, returned content, and application-level results. Investigate discrepancies rather than assuming byte-for-byte identical responses or usage accounting. Generation can vary, and frameworks may alter messages before sending them.
Use sanitized fixtures, not production secrets, for these comparisons.
3. Check streaming, tools, and JSON mode
Test streaming separately from ordinary completion. Verify that your consumer handles incremental chunks, reconstructs the final text, and releases resources when the user cancels or disconnects.
For tools/function calling, test the full loop: receive a tool call, validate its arguments, execute only authorized application logic, and send the tool result back. Do not treat generated arguments as trusted input.
For JSON mode, parse the response and validate it against your application schema. Valid JSON alone does not guarantee the required fields or correct values. Include malformed-output handling in your test suite.
4. Exercise error handling
Your application should distinguish failures instead of retrying everything:
| Status | Meaning to handle | Recommended response |
|---|---|---|
401 | Invalid key | Check credentials; do not repeatedly retry |
402 | Insufficient balance | Surface a billing alert and review available credit |
429 | Rate limit | Reduce concurrency and retry with backoff |
5xx | Server failure | Use bounded retries with exponential backoff and jitter |
If a retry-related header is present, honor it where appropriate. Set a retry budget so nested SDK and application retries do not multiply unexpectedly.
A dropped connection also creates ambiguity: your client may not know whether a request completed. Only successful requests are billed, but client-side failure alone is not proof that processing failed. Avoid blind replay of workflows that could execute tools twice.
Roll back with a configuration flag
Keep provider selection in one place. A feature flag can choose a matched pair of base URL and credential: the original provider configuration or the Openrouter API configuration.
Do not switch only the URL while leaving the wrong key attached. Keep model selection explicit too, since a rollback target may not expose the same model IDs.
Start with internal tests, then a limited traffic segment. Monitor request failures, malformed responses, tool execution, and application outcomes. Define rollback conditions before rollout rather than during an incident.
Rollback should affect new requests. Let active streams finish when practical instead of interrupting users. Keep the previous provider configuration available until the migration has passed your acceptance checks, and remember that changing a flag does not undo completed tool actions.
Key takeaways
- Change the SDK base URL to
https://openrouterapi.ru/v1and supply an Openrouter API key. - Keep Chat Completions code familiar, but verify model-specific streaming, tools, and JSON behavior.
- Test model discovery, usage, error handling, and framework configuration before production rollout.
- Pair URL and credential selection behind a rollback flag.
Create an account and top up from $50 to test your migration.



