EN ▾
Start now

How to Use the OpenRouter API, Then Switch Endpoints

Here is how to use openrouter api in a few minutes with the OpenAI SDK, and then how to point the same code at a different OpenAI-compatible endpoint by changing three values.

Last updated

Railway turntable connecting one incoming track to two outgoing glowing tracks, like switching API endpoints

Summary

  • OpenRouter accepts OpenAI-style requests, so the official SDK works after you change base URL, key and model id.
  • Keep those three values in environment variables and your code can switch providers without edits.
  • Model ids on a router look like vendor/model; on this endpoint the id is simply uncensored.
  • Dolphin-style models are community fine-tunes known for fewer refusals; this API runs a different open-weight model.

The quick version

To learn how to use openrouter api, you only need to know that it speaks the OpenAI request format. You create an account, make a key, choose a model id from its catalogue, and point the OpenAI SDK at OpenRouter's base URL. Your messages, parameters and streaming code stay the same.

That portability is the useful part. Once your code reads its endpoint from the environment, moving to another OpenAI-compatible service takes a minute. The second half of this page shows exactly that, against the endpoint on this site.

Think of any OpenAI-compatible service as three values: where to send requests (the base URL), who you are (the key) and what to run (the model id). Everything else, from message format to streaming chunks, follows the same standard. When a provider differs, it is almost always in one of those three values or in which optional features it supports.

Set up OpenRouter in four steps

  1. Create an account on the OpenRouter website.
  2. Create an API key in your account settings and copy it somewhere safe. Treat it like a password.
  3. Add credit if you plan to use paid models. Check OpenRouter's current pricing and free-model rules, as both change.
  4. Pick a model. Each model page shows an id in the form vendor/model-name. That string goes in the model field.

OpenRouter's base URL is https://openrouter.ai/api/v1. It also accepts optional headers that identify your app (HTTP-Referer and X-Title); see its documentation if you want your traffic attributed.

That is the whole setup. A request with curl then looks like any OpenAI call, with the OpenRouter URL and your OpenRouter key in place.

First-run problems

  • An authentication error. The key is wrong, was copied with a trailing space, or belongs to a different service. Re-copy it and check the environment variable.
  • A model-not-found error. The id is misspelled or the model was removed from the catalogue. Copy the id from the model page.
  • An error about credit or limits. Paid models need credit, and free models have caps. Check your account page and the current documentation.

A client that reads its endpoint from the environment

Instead of hard-coding a provider, read three variables. The defaults below target this site's endpoint; override them to talk to OpenRouter or anyone else.

import os
from openai import OpenAI

BASE_URL = os.environ.get("API_BASE_URL", "https://api.uncensoreddolphinopenrouter.com/v1")
MODEL = os.environ.get("API_MODEL", "uncensored")

client = OpenAI(base_url=BASE_URL, api_key=os.environ["API_KEY"])

def ask(prompt: str) -> str:
    resp = client.chat.completions.create(
        model=MODEL,
        messages=[
            {"role": "system", "content": "You are a concise assistant."},
            {"role": "user", "content": prompt},
        ],
        temperature=0.7,
    )
    return resp.choices[0].message.content

print(ask("List three differences between SSE and WebSockets."))

To run it against OpenRouter, export its base URL, your OpenRouter key and a model id from its catalogue before starting the script. Nothing else changes.

The same code against this endpoint

Here are the values side by side.

SettingOpenRouterThis endpoint
Base URLhttps://openrouter.ai/api/v1https://api.uncensoreddolphinopenrouter.com/v1
KeyFrom your OpenRouter settingsFrom the API key page
Model idvendor/model-nameuncensored
Auth headerAuthorization: BearerAuthorization: Bearer

This endpoint offers POST /v1/chat/completions, POST /v1/responses and GET /v1/models. A quick smoke test:

curl https://api.uncensoreddolphinopenrouter.com/v1/chat/completions \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"uncensored","messages":[{"role":"user","content":"Say hello in one line."}]}'

Streaming, tool calling, JSON mode and the usual sampling parameters (temperature, top_p, stop, seed, penalties) are passed through. See the documentation for the details.

Streaming and tool calling work the same way

Once the client reads its settings from the environment, features carry across. Streaming is the same stream=True flag and the same chunk loop:

stream = client.chat.completions.create(
    model=MODEL,
    messages=[{"role": "user", "content": "Describe a lighthouse keeper's morning in four sentences."}],
    stream=True,
)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
print()

Tool calling also uses the usual tools and tool_choice fields, with results sent back as role: "tool" messages. JSON mode uses response_format. On this endpoint all three are supported. On a router, support for each feature can depend on the specific model you choose, so check the model page before relying on it.

Dolphin-style models, and what this endpoint is

Dolphin is the name of a family of community fine-tunes of open-weight models, popular with people who want assistants that refuse less. Routers and hosts list such models from time to time, and availability changes, so check the catalogue you use.

The model behind this endpoint is a different one: a single open-weight model, run by an independent provider and tuned to answer without content refusals for lawful adult use. It is not a Dolphin model, not an official API of any vendor, and not a router. It is text only, with a 100,000-token context window. Sexual content involving minors is not allowed. If you want a wider look at the field, read our guide to uncensored AI models.

Names alone say little about quality. Two models called Dolphin can differ in size, base model and training data. Judge by testing: run the same ten prompts from your real use case, read the replies, and keep the model that behaves the way your product needs. That advice applies equally to the model on this endpoint, which is why the $0.50 trial exists.

Pitfalls when you switch providers

  • Model ids. A vendor/model id on a router will not work here, and uncensored will not work there. Keep the id in configuration.
  • Feature gaps. Tool calling, JSON mode and parameters are not identical across hosts. Test the features you rely on.
  • Limits. This API allows 8 concurrent requests and 300 per minute on a full key (2 and 60 on trial). A 429 means rate_limited or concurrency; wait for Retry-After and retry.
  • Prompt tuning. A prompt written for one model may need small edits for another. Compare outputs on ten of your real prompts, not one.
  • Billing units. Here the price is $0.15 per 1M input tokens and $0.50 per 1M output tokens, prepaid. Compare per-token prices rather than headline numbers, and see pricing for top-ups.

To test this endpoint without paying, claim the $0.50 trial credit on the key page after sign-up. It needs no payment, is valid for 7 days and is limited to one per person.

Handle secrets properly while you experiment. Keep one environment file per provider, outside version control, and never paste a key into a notebook you plan to share. If a key leaks, revoke it at once; on this site you can reissue a key on the API key page, and accounts that have topped up can hold up to 5 keys with labels, so one can be revoked without breaking the others.

Compare two endpoints on the same prompts

The best use of a portable client is a side-by-side test. This script sends one prompt to two endpoints, with the second taken from environment variables, and prints both answers and token counts:

import os
from openai import OpenAI

targets = [
    ("this endpoint", OpenAI(base_url="https://api.uncensoreddolphinopenrouter.com/v1",
                              api_key=os.environ["API_KEY"]), "uncensored"),
    ("other endpoint", OpenAI(base_url=os.environ["ALT_BASE_URL"],
                               api_key=os.environ["ALT_API_KEY"]), os.environ["ALT_MODEL"]),
]

prompt = "Write a six-line scene where two rivals are stuck in an elevator."
for name, c, model in targets:
    r = c.chat.completions.create(model=model, messages=[{"role": "user", "content": prompt}], temperature=0.8)
    print("==", name, r.usage.prompt_tokens, "in /", r.usage.completion_tokens, "out")
    print(r.choices[0].message.content)

Run ten prompts from your real use case, not just one. Look at refusals, tone, formatting and length. Then use the token counts with each service's current prices to estimate monthly cost. At $0.15 per 1M input tokens and $0.50 per 1M output tokens here, a request with 1,000 input and 300 output tokens costs $0.0003.

Common questions

Does the official OpenAI SDK work with OpenRouter?

Yes, OpenRouter documents an OpenAI-compatible API. Set the SDK's base URL to OpenRouter's, use your OpenRouter key and a model id from its catalogue.

How do I switch from OpenRouter to this API?

Change three values: base URL to https://api.uncensoreddolphinopenrouter.com/v1, the key to one from the API key page, and the model to uncensored.

Is this endpoint a Dolphin model?

No. It runs a different single open-weight model from an independent provider. Dolphin is a separate family of community fine-tunes.

Is it affiliated with OpenRouter?

No. It is an independent service and does not route requests to other vendors.

Get your key now

Sign up, grab the key, update the base URL. That is all there is to it.

Begin with trial credit

Enter email and password; key appears instantly.