Last reviewed: November 16, 2026.
To use DeepSeek AI with OpenRouter, create an OpenRouter API key, select a DeepSeek model from its catalog, and send a request to the OpenRouter API. OpenRouter acts as a gateway, routing your request to an eligible provider serving that model. You can connect with cURL, the OpenAI Python SDK, or a compatible application.
For the standard setup funded with OpenRouter credits, an OpenRouter key is the credential you need.
This guide uses the documented DeepSeek V4.1 Flash 1017 listing consistently across its examples. Model availability and provider settings can change, so check that listing before running the code.
| Setting | Value for this tutorial |
|---|---|
| API key | An OpenRouter API key stored as OPENROUTER_API_KEY |
| SDK base URL | https://openrouter.ai/api/v1 |
| Full Chat Completions endpoint | https://openrouter.ai/api/v1/chat/completions |
| Model ID | deepseek/deepseek-v4.1-flash-1017 |
| Final text in a normal response | choices[0].message.content |
These examples use Chat Completions. OpenRouter also supports the Responses API, which uses a different request and response structure. Keep the endpoint and payload format matched.
1. Create an OpenRouter API key
Sign in to OpenRouter and open the API Keys page. Create a dedicated key for your project and set a spending limit appropriate for your test. A key limit controls spending; it does not add credits to your account.

For a paid model, check your available OpenRouter credits. If you want a free test, first find a currently listed free variant as explained below. The model used in this tutorial is a paid listing.

macOS or Linux: set the variable in the terminal where you will run the examples.
export OPENROUTER_API_KEY="replace_with_your_openrouter_key"
Windows PowerShell: use this syntax instead.
$env:OPENROUTER_API_KEY = "replace_with_your_openrouter_key"
These assignments apply to the current shell and programs started from it. Configure your hosting platform separately when you deploy. Keep the real key in server-side secrets, and replace it if exposed. OpenRouter documents key handling and credential errors in its authentication guide.
2. Choose the correct DeepSeek model ID
Open the DeepSeek model catalog, select a model, and copy its API ID. Check its available providers, input and output pricing, supported features, and limits.

The ID used here is deepseek/deepseek-v4.1-flash-1017. The deepseek/ prefix identifies the model author in the catalog; it does not guarantee that DeepSeek itself will be the inference provider.

For repeatable application testing, start with a specific release listing. An explicitly documented latest-model alias can change its target over time. Record the model returned by the API if you use an alias.
Check available models programmatically
The models endpoint returns a catalog in data. This Python script uses the standard library and lists DeepSeek text-generation model IDs beginning with deepseek/, along with their advertised parameters.
import json
import os
from urllib.request import Request, urlopen
request = Request(
"https://openrouter.ai/api/v1/models",
headers={
"Authorization": "Bearer " + os.environ["OPENROUTER_API_KEY"]
},
)
with urlopen(request, timeout=30) as response:
catalog = json.load(response)
for model in catalog["data"]:
model_id = model.get("id", "")
if model_id.startswith("deepseek/"):
print(json.dumps({
"id": model_id,
"context_length": model.get("context_length"),
"supported_parameters": model.get("supported_parameters", []),
}))
Use the returned id as the request value. A catalog entry does not guarantee that your account can reach every provider: privacy settings, routing restrictions, and current capacity also affect eligibility. Check the provider details when your application requires a particular feature.
3. Send your first request with cURL
Run this command in a Bash-compatible shell, such as a macOS/Linux terminal or Git Bash. In Windows PowerShell, use the Python example below if you want to avoid differences in shell quoting.
curl --silent --show-error --fail-with-body \
--max-time 90 \
https://openrouter.ai/api/v1/chat/completions \
-H "Authorization: Bearer $OPENROUTER_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "deepseek/deepseek-v4.1-flash-1017",
"messages": [
{
"role": "user",
"content": "Explain what an API gateway does in two short sentences."
}
],
"max_tokens": 512,
"reasoning": {"enabled": false}
}'

The command returns JSON. Look for an answer in choices[0].message.content, then inspect finish_reason and usage. An error object needs attention even if the connection itself succeeded.
Reasoning is disabled deliberately for this short connection test. The selected model currently has optional reasoning enabled by default, according to its live metadata. A small output allowance can otherwise be consumed before a final answer appears.
If a tool asks for a base URL, enter https://openrouter.ai/api/v1. If it asks for the complete HTTP request URL, enter the full /chat/completions endpoint. Supplying the full endpoint to an SDK base-URL field can produce a duplicated path.
Use DeepSeek with the OpenAI Python SDK
The OpenAI Python package can send requests to OpenRouter when you explicitly configure its base URL and key. See the official SDK integration guide. Install the package in your Python environment:
python -m pip install --upgrade openai
Save the following as deepseek_openrouter.py. It makes a single request, checks for an API error or missing answer, and prints metadata you can use to inspect the result.
import json
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["OPENROUTER_API_KEY"],
base_url="https://openrouter.ai/api/v1",
timeout=90.0,
max_retries=0,
)
response = client.chat.completions.create(
model="deepseek/deepseek-v4.1-flash-1017",
messages=[{
"role": "user",
"content": "Explain what an API gateway does in two short sentences.",
}],
max_tokens=512,
extra_body={"reasoning": {"enabled": False}},
)
data = response.model_dump(exclude_none=True)
choice = (data.get("choices") or [{}])[0]
error = data.get("error") or choice.get("error")
if error:
raise RuntimeError(str(error))
content = (choice.get("message") or {}).get("content")
if not content:
raise RuntimeError(
"No final text. Check finish_reason, reasoning, and tool calls."
)
print(content)
print(json.dumps({
"id": data.get("id"),
"model": data.get("model"),
"provider": data.get("provider"),
"finish_reason": choice.get("finish_reason"),
"usage": data.get("usage"),
}, indent=2))
Run the script from the same terminal where you set the environment variable:
python deepseek_openrouter.py

The extra_body argument carries the OpenRouter reasoning setting. Automatic SDK retries are disabled here so an initial test does not silently repeat. Add a deliberate retry policy once you know how your application should handle failures.
Try a useful task after the connection works
Replace the user message with this fictional support note. Check whether the answer preserves the facts and avoids inventing an order number or promising a refund:
Summarize this fictional support ticket for an agent.
Return exactly three labeled lines: Issue, Known facts, Next question.
Use only the information provided. Do not promise a refund.
Ticket: The customer ordered a blue mug but received a green one.
The package arrived yesterday. No order number or photos were included.
This gives you a small quality check before introducing real customer data. A successful API request proves connectivity; your own task examples establish whether the result is useful.
Call DeepSeek from server-side JavaScript
Save this as deepseek_openrouter.mjs and run it in a current Node.js environment with built-in fetch. Keep the account key on the server. A public webpage should call your backend, which holds the secret.
const apiKey = process.env.OPENROUTER_API_KEY;
if (!apiKey) {
throw new Error("Set OPENROUTER_API_KEY before running this script.");
}
const response = await fetch(
"https://openrouter.ai/api/v1/chat/completions",
{
method: "POST",
headers: {
Authorization: "Bearer " + apiKey,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "deepseek/deepseek-v4.1-flash-1017",
messages: [{
role: "user",
content: "Explain what an API gateway does in two short sentences.",
}],
max_tokens: 512,
reasoning: { enabled: false },
}),
signal: AbortSignal.timeout(90000),
}
);
const responseText = await response.text();
let data;
try {
data = JSON.parse(responseText);
} catch {
throw new Error(
"HTTP " + response.status + ": expected a JSON response."
);
}
const choice = data.choices?.[0];
const apiError = data.error ?? choice?.error;
if (!response.ok || apiError) {
throw new Error(
apiError?.message ?? "HTTP error " + response.status
);
}
const content = choice?.message?.content;
if (!content) {
throw new Error("No final text; inspect finish_reason and message fields.");
}
console.log(content);
console.log({
id: data.id,
model: data.model,
provider: data.provider,
finish_reason: choice.finish_reason,
usage: data.usage,
});
node deepseek_openrouter.mjs
The response-body check matters: OpenRouter documents cases where a generation error appears after an HTTP 200 response has started. Its error guide explains both ordinary HTTP failures and errors returned inside a response.
Confirm that the request completed correctly
Before connecting the result to an automated workflow, inspect these fields. Store identifiers and operational metadata needed for debugging, while keeping credentials and unnecessary prompt contents out of logs.
| Check | What it tells you |
|---|---|
model | The model reported in the response; useful when aliases or model fallbacks are involved. |
provider, when present | The serving provider, which can differ from the model author. |
choices[0].message.content | The final text for this tutorial. Tool-enabled requests can return tool calls instead. |
finish_reason | stop normally marks completion; length signals a limit; tool_calls means the application needs to handle tools. |
usage | Token accounting and available cost details. Reasoning and cache-related fields depend on the response. |
Use the response schema and usage-accounting documentation to interpret these fields. Compare the request with your OpenRouter Activity record when investigating cost or provider behavior.

For the plain-text examples above, missing content or finish_reason: "length" means you should investigate before treating the result as complete. Fluent text can still be cut off.
DeepSeek OpenRouter pricing, free access, and limits
How paid usage is calculated
Check the selected model’s provider table for current rates. Providers serving the same model can differ in price and capabilities. Compare input and output rates separately, then account for applicable caching, reasoning, or other charges.

Estimated text inference cost =
(input tokens / 1,000,000 × input price per million)
+ (billed output tokens / 1,000,000 × output price per million)
Use that formula as an estimate for ordinary text usage, then inspect actual usage and charges. The pricing.prompt and pricing.completion values returned by the models API are per-token prices; multiply them by one million before comparing them with a per-million price table.
OpenRouter’s pricing page distinguishes inference charges from plan-dependent fees when you buy credits. Include those fees when comparing OpenRouter with the direct DeepSeek API. A lower advertised token rate alone does not settle the total-cost comparison.
Can you use DeepSeek through OpenRouter for free?
Only if a suitable DeepSeek free listing is currently available and your request qualifies for it. Check the live free-model collection and the exact model ID. Adding :free to a paid model name does not create a free variant.

As reviewed on November 16, 2026, the collection documents limits of 20 requests per minute and 50 per day for :free variants, with a higher daily allowance after qualifying credit purchases. Failed attempts can count toward the allowance. Check the current rules before building a workflow around them.
A model with a zero-dollar displayed rate but no :free suffix can have different funding requirements. Also, openrouter/free selects from eligible free models; it does not promise a DeepSeek response.
Check the key’s available budget
Account credits, a key’s spending cap, and request-rate allowances are different limits. The limits documentation provides a key-status endpoint:
curl --silent --show-error --fail-with-body \
https://openrouter.ai/api/v1/key \
-H "Authorization: Bearer $OPENROUTER_API_KEY"
Inspect the returned budget and usage fields when diagnosing failures. Setting a very large output limit can make a request harder to fund, even when you expect a short answer.
Provider routing and optional features
Provider fallback and model fallback are different
Provider fallback tries another eligible endpoint serving the same model. Model fallback tries a different model from an explicit list. The latter can change output behavior, feature support, and cost; review the model-fallback guide before enabling it.
Once the basic request works, you can add this optional object to a Chat Completions request to prefer price ordering while requiring parameter support:
{
"provider": {
"sort": "price",
"require_parameters": true,
"allow_fallbacks": true
}
}
This is a request fragment to merge with your existing model and messages, not a complete request. In the Python SDK, place it inside extra_body alongside the reasoning setting.
In provider routing, order expresses a preference, while only restricts eligible providers. More restrictions can leave no usable endpoint. Apply controls according to your requirements and account plan.

Enable reasoning when the task benefits from it
For a reasoning task, replace the disabled setting with a supported effort level, such as this fragment for the selected model:
{
"reasoning": {
"effort": "low"
}
}
Allow enough output tokens for both reasoning and the final answer. reasoning.exclude: true hides reasoning from the returned output; it does not switch reasoning off. For multi-turn reasoning or tool workflows, preserve required reasoning_details as described in the reasoning documentation.
Streaming, JSON output, and tools
| Feature | How to approach it |
|---|---|
| Streaming | Set stream: true and process Chat Completions events, including delta.content. Handle errors inside the stream and inspect its final status. See streaming documentation. |
| Structured JSON | Use a supported response_format, such as json_schema, and require an eligible provider. Validate the returned data in your application. See structured outputs. |
| Tool calling | Send supported tool definitions. Your application handles requested actions and returns their results; a model response alone does not execute your code. See tool calling. |
Introduce one feature at a time. This makes it easier to distinguish a connection problem from an unsupported parameter or a mistake in your application’s response handling.
Fix common DeepSeek OpenRouter errors
Read the error message and metadata alongside the HTTP status. Start with the small request above, then reintroduce optional settings individually.
| Symptom | What to check next |
|---|---|
400 | Validate JSON, required fields, and parameter support. Remove optional settings while isolating the cause. |
401 | Check that this process has the OpenRouter key, including its Bearer header. A direct DeepSeek credential will not authenticate this request. |
402 | Check credits, key limits, and output allowance. Inspect error.metadata.limit_source for the specific budget involved. |
403 | Read permission, moderation, guardrail, or configured-budget details. Resolve the applicable restriction. |
404 or “No endpoints found” | Recheck the model ID and provider filters. A valid model can still have no endpoint matching your settings. |
429 | Check your request allowance and provider capacity. Respect retry/reset headers and reduce concurrency. |
502 or 503 | Check provider availability and routing requirements. Use bounded retries for transient failures. |
| Empty or incomplete text | Inspect finish_reason, reasoning, tool calls, and any response-body error before increasing the output limit. |

The relevant references are error handling, authentication, and credit and rate limits.
One useful distinction: a 402 with limit_source: "openrouter_in_flight_budget" can be temporary because other requests have reserved budget. Respect Retry-After when supplied. Repeating an invalid key, unsupported model ID, or exhausted account balance will not fix the underlying problem.
Set a maximum retry count and delay between attempts. For workflows that execute tools, prevent a repeated request from triggering the same external action twice.
Understand where your data goes
Your application sends content to OpenRouter, which routes it to a serving provider. Review both OpenRouter’s data-collection policy and the chosen provider’s policy. Your own application logs are another place where prompts and responses may be stored.
Avoid treating a model name or data_collection: "deny" as a universal promise of zero retention. OpenRouter has separate controls for data policies and retention.
Under the current ZDR documentation, provider.zdr: true follows the account’s Safety Retention choice. For stricter provider retention requirements, review the ZDR only setting, which excludes Safety Retention endpoints and can reduce model availability. The policy also describes safety and legal exceptions. Configure these requirements before submitting sensitive material.
Should you use OpenRouter or the direct DeepSeek API?
OpenRouter is useful when you want one integration across model families or a choice of providers. The direct DeepSeek API is useful when you want to work with DeepSeek’s own service and documented features directly. Compare the actual route your application will use.
| Configuration | OpenRouter | Direct DeepSeek API |
|---|---|---|
| Credential | OpenRouter API key | DeepSeek API key |
| Base URL | https://openrouter.ai/api/v1 | https://api.deepseek.com |
| Example model name | deepseek/deepseek-v4.1-flash-1017 | deepseek-flash |
| Standard billing | OpenRouter credits and applicable plan terms | DeepSeek account and API rates |
| Serving route | An eligible OpenRouter provider endpoint | DeepSeek’s API service |

DeepSeek documents its current model names and connection details in Your First API Call. The key, model name, and balance from one service should not be assumed to work on the other.
OpenRouter also offers Bring Your Own Key for supported providers. That is a separate configuration with its own terms; your application still authenticates to OpenRouter with an OpenRouter credential.
Frequently asked questions
Can I use DeepSeek R1 or V3 instead?
Check whether the exact model and an eligible provider remain available in the current OpenRouter catalog. Copy that entry’s ID and review its features. Do not assume an older tutorial’s model, free variant, or reasoning settings still apply unchanged.
Do I need an OpenAI account to use the Python example?
The example uses the OpenAI package as a client library, but sends its request to OpenRouter with an OpenRouter key. Its model access and billing are handled through the configured OpenRouter route.
Can I connect a chat app without writing code?
If the app supports OpenRouter, choose that provider, enter an OpenRouter key, and select the DeepSeek model. For a custom OpenAI-compatible connection, check whether the app expects a base URL or a full endpoint. Its other feature settings still need to match the model and provider.
Does this run DeepSeek locally on my computer?
No. Your local script sends a request to a hosted service. Running model weights locally is a separate setup. You do not need a local inference GPU for the HTTP examples in this guide.
Why might the same model behave differently across providers?
Providers can differ in serving configuration, supported parameters, performance, and limits. Record the model and provider, use consistent prompts, and compare complete responses when evaluating a route for your application.
