DeepSeek Coder Python: Same Code, New Base URL
If your DeepSeek Coder Python script already uses the OpenAI SDK, moving it to this endpoint is a two-line change. Below are working snippets for chat, streaming, tools and JSON output.
Updated

Key points
- Install the openai package, set base_url and api_key, and use the model name uncensored.
- Streaming, tool calling and JSON mode use the standard OpenAI parameters.
- Keep the key in an environment variable and cap parallel workers at 8.
- This is an independent service with its own open-weight model, not DeepSeek's official API.
Setup in under a minute
Most deepseek coder python examples online use the openai package with a custom base URL, which is the same pattern used here. Install the package, then read the key from the environment so it never lands in version control.
pip install --upgrade openai
export CODER_API_KEY="YOUR_KEY"
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.deepseekcoder.top/v1",
api_key=os.environ["CODER_API_KEY"],
)
r = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Write a Python function that merges overlapping intervals."}],
)
print(r.choices[0].message.content)
print(r.usage)
Two things to know. The model is called uncensored, and it is a general open-weight chat model run by an independent provider. It is not DeepSeek's own hosted API, so do not expect a model name from another vendor to work. Get a key on the API key page; new accounts can claim $0.50 of trial credit there without a card.
Repointing an existing client
If you already have code that talks to a DeepSeek-style endpoint, avoid editing every call site. Put the three variable values in one factory function and change them in one place.
import os
from openai import OpenAI
def make_client():
return OpenAI(
base_url=os.getenv("LLM_BASE_URL", "https://api.deepseekcoder.top/v1"),
api_key=os.environ["LLM_API_KEY"],
)
MODEL = os.getenv("LLM_MODEL", "uncensored")
Now a different environment can switch providers without a code change, which also makes side-by-side comparisons easy. Run the same prompt file through two sets of environment variables and diff the outputs. The earlier page on DeepSeek API troubleshooting lists the errors people meet most often after such a change.
Streaming a code answer
Long code answers feel faster when you print tokens as they arrive. Set stream=True and iterate over the chunks. Ask for usage at the end if you track cost.
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Explain Python's GIL and show a multiprocessing example."}],
stream=True,
stream_options={"include_usage": True},
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
if chunk.usage:
print("\n\ntokens:", chunk.usage.total_tokens)
A streamed request occupies one of your concurrency slots until the last chunk arrives. If you forget to read the stream to the end, for example by breaking out of the loop early, the slot stays busy until the connection closes. Close the stream explicitly or use a context manager when you stop early.
Tool calling for a code agent
Tool calling lets the model ask your program to run something, such as a test suite, and then read the result. The format is the standard one: you describe functions in tools, the model returns tool_calls, and you answer with a message whose role is tool.
import json, subprocess
tools = [{
"type": "function",
"function": {
"name": "run_tests",
"description": "Run pytest on a path and return the output",
"parameters": {
"type": "object",
"properties": {"path": {"type": "string"}},
"required": ["path"],
},
},
}]
msgs = [{"role": "user", "content": "Run the tests in tests/unit and tell me which fail."}]
r = client.chat.completions.create(model="uncensored", messages=msgs, tools=tools)
msg = r.choices[0].message
if msg.tool_calls:
msgs.append(msg)
for call in msg.tool_calls:
args = json.loads(call.function.arguments)
out = subprocess.run(["pytest", args["path"], "-q"], capture_output=True, text=True).stdout
msgs.append({"role": "tool", "tool_call_id": call.id, "content": out[-4000:]})
final = client.chat.completions.create(model="uncensored", messages=msgs, tools=tools)
print(final.choices[0].message.content)
Trim tool output before sending it back. The last 4,000 characters of a test log usually hold the failures, and shorter results cost fewer input tokens. Never run model-chosen shell commands without an allow-list; here the command is fixed and only the path comes from the model.
Structured output with JSON mode
When another script consumes the answer, ask for JSON. The setting is response_format, and the prompt should still say what keys you expect.
import json
r = client.chat.completions.create(
model="uncensored",
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": "Return JSON with keys: summary (string), risks (array of strings)."},
{"role": "user", "content": "Review this diff:\n\n" + open("change.diff").read()},
],
temperature=0,
)
data = json.loads(r.choices[0].message.content)
print(data["summary"], len(data["risks"]))
Wrap json.loads in a try block anyway. If a response is cut off by a limit you set with max_tokens, the JSON may be incomplete. Leaving max_tokens unset lets the completion use the rest of the 100,000-token window.
Async version for web backends
If your Python code runs inside FastAPI or another async framework, a blocking call will freeze the event loop. Use AsyncOpenAI with the same arguments, and bound the number of in-flight calls with a semaphore so a traffic spike cannot push you past the concurrency limit.
import asyncio, os
from openai import AsyncOpenAI
client = AsyncOpenAI(
base_url="https://api.deepseekcoder.top/v1",
api_key=os.environ["CODER_API_KEY"],
)
gate = asyncio.Semaphore(8)
async def explain(snippet: str) -> str:
async with gate:
r = await client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Explain this code in two sentences:\n" + snippet}],
)
return r.choices[0].message.content
async def main():
out = await asyncio.gather(*(explain(s) for s in ["x = [i*i for i in range(10)]", "print(sum(range(5)))"]))
print(out)
asyncio.run(main())
The semaphore is the part people skip. Without it, a burst of 30 simultaneous users produces 22 immediate 429 responses with the code concurrency. With it, the extra requests wait in your process for a few seconds, and the user sees a slower answer instead of an error.
Reading errors and headers
When a call fails, the OpenAI SDK raises a typed exception, and the response headers tell you more than the message does. Three headers are worth logging on every request: X-Request-Id for support questions, X-Balance-USD for remaining credit, and X-RateLimit-Limit-Requests to confirm which tier your key is on.
- 401. The key is missing or wrong. Check that the environment variable is set in the shell that launches Python, since an IDE often starts with a different environment.
- 404 or a model error. The model name is wrong. Use
uncensored, or callGET /v1/modelsto see what the endpoint lists. - 429 with
rate_limited. You passed the per-minute cap. Slow the loop down. - 429 with
concurrency. Too many requests are in flight at once. Lower your worker count. - Request too large. The body limit is 8 MB, and the context window is 100,000 tokens for prompt plus completion. Split big repositories into files or summaries.
Failed requests are not charged, so retries while you debug do not eat your trial credit. The SDK exposes the raw response through with_raw_response on the completions object, and the .headers attribute of that result holds the values above. A short wrapper that writes them to your log line costs nothing and saves hours when a batch job misbehaves at night. Pair it with the model's usage field and you can reconstruct the exact cost of every call after the fact.
Parallel requests and cost control
For a batch job, such as adding docstrings to 500 files, use a thread pool sized to your limit. Full keys allow 8 concurrent requests and 300 per minute; trial keys allow 2 and 60.
from concurrent.futures import ThreadPoolExecutor
def docstring_for(src):
r = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Add Google-style docstrings. Return only code.\n\n" + src}],
temperature=0.1,
)
return r.choices[0].message.content
with ThreadPoolExecutor(max_workers=8) as pool:
results = list(pool.map(docstring_for, sources))
Estimate the bill before you start. If each file is about 1,500 tokens in and 1,700 tokens out (the code plus new docstrings), a file costs 1,500 x $0.15 / 1M = $0.000225 for input and 1,700 x $0.50 / 1M = $0.00085 for output, so $0.001075. Five hundred files come to $0.5375, roughly 54 cents. Check the pricing page for top-up sizes, or read the docs for the full parameter list. The older note on DeepSeek Coder V2 API pricing is useful if you are comparing per-token rates.
More guides
Questions and answers
Which Python package do I need?
The official openai package is enough. Set base_url to https://api.deepseekcoder.top/v1, pass your key, and use the model name uncensored.
Does the model run locally?
No. It is hosted. Your script sends requests over HTTPS and pays per token from prepaid credit.
How do I avoid 429 errors in a batch script?
Limit workers to 8 on a full key or 2 on a trial key, and wait at least 5 seconds when the response includes Retry-After. A 429 with the code concurrency means too many requests at once.
Can I use async code?
Yes. The AsyncOpenAI class works with the same base URL and key. The same concurrency limits apply.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.