Building a Coding Assistant with the DeepSeek API
The gap between a chatbot that can write a function and a coding assistant you actually keep open all day is not the model. It is the scaffolding around it: how you feed it context, when you escalate to a stronger model, and whether it can look at your files instead of guessing at them. This guide builds that scaffolding using the DeepSeek API through the OpenAI SDK you already know.
Everything below runs against one base URL and two model names. Use deepseek-v4-flash for nearly everything, and reach for deepseek-v4-pro only when a task genuinely needs more reasoning. No wrapper libraries, no bespoke client, no lock-in beyond the model choice itself.
What a usable assistant actually needs
Streaming output, so responses feel instant instead of arriving in one lump.
Conversation memory that survives more than one turn without growing without bound.
A cheap default model plus a deliberate escalation path for hard problems.
Read-only tool access to the repository, so answers reference real code.
A hard stop on tool loops, because a confused model will happily read files forever.
Step 1: A streaming REPL loop
Install the SDK, point it at AiCredits, and the rest is ordinary OpenAI-style code. Only the base URL and the model name change.
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["AICREDITS_API_KEY"],
base_url="https://api.aicreditsapi.com/v1",
)
MODEL = "deepseek-v4-flash"
SYSTEM = (
"You are a senior engineer working inside the user's repository. "
"Return working code, not pseudocode. If you have not seen a file, "
"say so instead of guessing its contents. Prefer the smallest change "
"that fixes the problem."
)
history = [{"role": "system", "content": SYSTEM}]
def ask(user_message: str) -> str:
history.append({"role": "user", "content": user_message})
stream = client.chat.completions.create(
model=MODEL,
messages=history,
stream=True,
temperature=0.2,
)
parts = []
for event in stream:
delta = event.choices[0].delta.content
if delta:
parts.append(delta)
print(delta, end="", flush=True)
print()
reply = "".join(parts)
history.append({"role": "assistant", "content": reply})
return reply
if __name__ == "__main__":
while True:
try:
line = input("\n> ")
except (EOFError, KeyboardInterrupt):
break
if line.strip().lower() in {"exit", "quit"}:
break
if line.strip():
ask(line)
Two details matter more than they look. A low temperature keeps suggestions from drifting between runs on the same prompt, which makes diffing your own output sane. And appending the assistant reply back into history is what makes a follow-up like "now make it async" mean anything at all.
Step 2: Route cheap work to flash, hard work to pro
Cost control in a coding assistant comes almost entirely from routing, not from trimming prompts. Most requests — explain this function, write a regex, fix this import, add a docstring — are well within deepseek-v4-flash. A minority need real reasoning: untangling a race condition, planning a refactor across modules, or debugging a failure that spans five files. Send those to deepseek-v4-pro and leave everything else alone.
Keep the heuristic boring and log which model handled each request. If you cannot explain why a request was escalated, the rule is too clever.
HARD_SIGNALS = (
"refactor",
"architecture",
"deadlock",
"race condition",
"memory leak",
"why does",
"migration plan",
)
def pick_model(task: str) -> str:
"""Cheap by default; escalate only when the task genuinely needs it."""
lowered = task.lower()
if any(signal in lowered for signal in HARD_SIGNALS) or len(task) > 4000:
return "deepseek-v4-pro"
return "deepseek-v4-flash"
def complete(task: str) -> str:
response = client.chat.completions.create(
model=pick_model(task),
messages=[
{"role": "system", "content": SYSTEM},
{"role": "user", "content": task},
],
temperature=0.1,
)
return response.choices[0].message.content or ""
| Task | Model | Why |
|---|---|---|
| Explain a function, fix a small bug | deepseek-v4-flash | Fast and accurate when you hand it the relevant code |
| Generate tests and docstrings | deepseek-v4-flash | High-volume work on a stable, repetitive pattern |
| Plan a multi-module refactor | deepseek-v4-pro | Must hold more dependencies in mind at once |
| Debug a race condition or leak | deepseek-v4-pro | Long chains of cause and effect; flash tends to stop early |
| Port code between languages | deepseek-v4-flash | Mechanical mapping with little reasoning depth |
Step 3: Let it read your files, not write them
The single biggest quality jump comes from replacing pasted code with actual file reads. Give the model a read_file tool, keep it read-only, and cap the loop so a confused assistant cannot spin. The handler below refuses paths outside the project root and truncates large files so one read does not dominate your context window.
import json
import pathlib
ROOT = pathlib.Path.cwd().resolve()
TOOLS = [{
"type": "function",
"function": {
"name": "read_file",
"description": "Read a text file from the project. Paths are relative to the project root.",
"parameters": {
"type": "object",
"properties": {"path": {"type": "string"}},
"required": ["path"],
},
},
}]
def read_file(path: str) -> str:
target = (ROOT / path).resolve()
if target != ROOT and ROOT not in target.parents:
return "Error: path is outside the project root."
if not target.is_file():
return f"Error: {path} is not a readable file."
return target.read_text(encoding="utf-8", errors="replace")[:12000]
def run(task: str, model: str = "deepseek-v4-flash", max_turns: int = 6) -> str:
messages = [
{"role": "system", "content": SYSTEM},
{"role": "user", "content": task},
]
for _ in range(max_turns):
response = client.chat.completions.create(
model=model,
messages=messages,
tools=TOOLS,
temperature=0.1,
)
message = response.choices[0].message
messages.append(message)
if not message.tool_calls:
return message.content or ""
for call in message.tool_calls:
args = json.loads(call.function.arguments or "{}")
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": read_file(args.get("path", "")),
})
return "Stopped after hitting the tool-call limit."
Read-only is deliberate. The moment you add write_file or a shell runner, you need diff previews and per-command approval. That is worth building, but build it after the read path is reliable — otherwise you are debugging two systems at once.
Keeping context under control
Send excerpts, not repositories. Read the file yourself, slice the relevant function, and include a few lines of surrounding context.
Summarize old turns. After roughly a dozen exchanges, replace the oldest messages with a short summary of decisions already made.
Front-load a repo map. A flat list of file paths costs a handful of lines and saves the model from asking for a directory listing every session.
Keep the system prompt stable. Identical prefixes are cache-friendly, and cache hits are billed more cheaply than fresh input.
Trim tool output. A long file read is context you pay for again on every subsequent turn unless you prune it.
How this compares to other routes
OpenAI's API is the obvious alternative and has the most mature tooling ecosystem around it. If you already live in that stack and hold a card that works internationally, there is little friction. OpenRouter is genuinely useful when you want one key across many providers and want to compare models side by side; the trade-off is an extra layer between you and the model when something misbehaves. AiCredits is the narrow option: direct DeepSeek models, card or PayPal at signup, and no Chinese phone number or bank account needed. If DeepSeek is the model you have already chosen, that is the shortest path to a working loop.
| Option | Strength | Trade-off |
|---|---|---|
| OpenAI direct | Broadest catalog and the most mature tooling ecosystem | One vendor sets both model and price; needs an internationally accepted card |
| OpenRouter | One key across many providers, handy for side-by-side comparison | A layer between you and the model when you need to debug a failure |
| AiCredits | Direct DeepSeek models, card or PayPal, no Chinese phone or bank required | DeepSeek models only — a narrower catalog by design |
Signing up without the usual friction
DeepSeek's own platform is excellent, but account creation assumes a Chinese phone number and payment method, which blocks plenty of developers. AiCredits exists for exactly that gap: top up with a card or PayPal, get an API key, and use the same SDK calls shown above. Pricing is usage-based and billed per token, with off-peak requests and cache hits costing less than peak, uncached ones — current rates live at aicreditsapi.com/pricing.
AiCredits also ships code linting tools, which pair well with an assistant. Let the linter catch style and correctness problems mechanically, and spend model tokens on the things a linter cannot see.
Frequently asked questions
Not through AiCredits. You sign up, top up with a card or PayPal, and get a key that works with the OpenAI SDK. No Chinese phone number, bank account, or local ID verification is involved.
Default to deepseek-v4-flash. It handles the overwhelming majority of day-to-day coding requests: explanations, small edits, tests, regexes, ports. Escalate to deepseek-v4-pro only for multi-file reasoning, refactor planning, and hard debugging, since it costs more per request.
Yes. Set base_url to https://api.aicreditsapi.com/v1, pass your AiCredits key as api_key, and set model to deepseek-v4-flash or deepseek-v4-pro. Streaming, tool calls, and multi-turn messages all behave the way you expect.
Cap the loop. The run() function above takes a max_turns argument and returns an explicit message when it is exhausted, which is far better than silently burning tokens on repeated reads of the same file.
Yes, when your prompts share a stable prefix: the same long system prompt, the same repo map, the same conventions block. Cache hits are cheaper than fresh input tokens, so ordering your messages with the stable parts first makes hits more likely.
What to build next
Get the streaming loop and the read-only file tool working end to end before adding anything else. The next three upgrades, in order of payoff, are a repo map injected at session start, a diff-approval flow for writes, and a small test-runner tool so the assistant can verify its own suggestions. Each one is just another tool definition and a handler — the loop itself never changes.
That is the whole trick. A cheap default model, a deliberate escalation path, real file access, and a context budget you actually manage will outperform a fancier model wired up carelessly.