The DeepSeek API speaks the OpenAI wire format, which means you can drive it from Node.js with the SDK you already have installed. No new client library, no custom protocol, no community wrapper maintained by one person on weekends.
This starter covers the parts that actually matter in a JavaScript project: the first call, streaming tokens into a terminal or an HTTP response, forcing structured JSON out of the model, keeping conversation history under control, and knowing when to reach for deepseek-v4-pro instead of the default deepseek-v4-flash. Every snippet below runs as written — save them as .mjs files, or set "type": "module" in your package.json so top-level await is legal.
Why Node.js is a natural fit
Node's async model lines up almost exactly with how these APIs behave. A streamed completion is an async iterable, so for await gives you tokens as they arrive without a callback pyramid. That maps cleanly onto Server-Sent Events if you are piping the output to a browser, and onto a plain terminal spinner if you are building a CLI.
Two practical details save time later. First, keep the key in an environment variable rather than in source — process.env.AICREDITS_API_KEY — because the client reads it once at construction. Second, keep the client instance in a module you import, not re-created per request; the SDK reuses connections underneath and re-instantiating it per call throws that away.
Set up the client and make your first call
Install the SDK and export your key:
npm install openai then export AICREDITS_API_KEY="your-key". That is the whole setup. The only thing that changes versus talking to OpenAI directly is the baseURL line.
// npm install openai
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.AICREDITS_API_KEY,
baseURL: "https://api.aicreditsapi.com/v1",
});
const res = await client.chat.completions.create({
model: "deepseek-v4-flash",
messages: [
{ role: "system", content: "You are a concise Node.js debugging assistant." },
{ role: "user", content: "Why does fs.readFile return a Buffer instead of a string?" },
],
});
console.log(res.choices[0].message.content);
console.log(res.usage); // keep an eye on prompt/completion accounting
Stream tokens instead of waiting for the whole answer
For anything interactive, streaming is not a nice-to-have. It changes perceived responsiveness dramatically, because the user sees the first words while the model is still working. With the OpenAI SDK it is one flag plus an async loop.
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.AICREDITS_API_KEY,
baseURL: "https://api.aicreditsapi.com/v1",
});
const stream = await client.chat.completions.create({
model: "deepseek-v4-flash",
messages: [{ role: "user", content: "Explain Node's event loop in three short paragraphs." }],
stream: true,
});
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta?.content;
if (delta) process.stdout.write(delta);
}
process.stdout.write("\n");
The optional chaining matters: the final chunks carry a finish reason rather than content, and some providers send role-only deltas first. Writing chunk.choices[0].delta.content directly is the most common crash in streamed Node integrations.
Getting JSON you can actually trust
Models do not guarantee raw JSON, even when you ask politely. They wrap output in markdown fences, add a friendly preamble, or both. If you want this production-safe, do three things: instruct explicitly, strip fences defensively, and validate the parsed object against a schema before it touches your database.
The snippet below handles the middle step, using temperature: 0 to reduce variation, and is safe to run as-is.
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.AICREDITS_API_KEY,
baseURL: "https://api.aicreditsapi.com/v1",
});
function parseModelJson(text) {
const cleaned = text
.trim()
.replace(/^```(?:json)?/i, "")
.replace(/```$/, "")
.trim();
return JSON.parse(cleaned);
}
const res = await client.chat.completions.create({
model: "deepseek-v4-flash",
temperature: 0,
messages: [
{ role: "system", content: "Return raw JSON only. No markdown fences, no commentary." },
{
role: "user",
content:
'Extract as {"name": string, "version": string, "breaking": boolean}: ' +
'"express 5.0.0 drops callback-style error handling"',
},
],
});
const data = parseModelJson(res.choices[0].message.content);
console.log(data); // typically { name: 'express', version: '5.0.0', breaking: true }
Keep a conversation alive without drowning the context
A chat loop is just an array you keep appending to. The trap is that the array grows forever: every turn resends the full history, so long sessions get slower and more expensive while adding nothing. The fix is a sliding window that always keeps the system prompt and drops the oldest exchanges.
Character count is a rough proxy for tokens, not an exact measure, but it is good enough as a guard rail and it costs nothing to compute before every request.
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.AICREDITS_API_KEY,
baseURL: "https://api.aicreditsapi.com/v1",
});
const MAX_CHARS = 12000;
const history = [
{ role: "system", content: "You are a terse pair-programming partner. Answer in under 150 words." },
];
function trimHistory(messages) {
const system = messages[0]?.role === "system" ? messages[0] : null;
const rest = system ? messages.slice(1) : messages.slice();
const kept = [];
let total = 0;
for (let i = rest.length - 1; i >= 0; i--) {
const len = String(rest[i].content ?? "").length;
if (total + len > MAX_CHARS) break;
kept.unshift(rest[i]);
total += len;
}
// never start the window on an assistant turn
while (kept.length && kept[0].role !== "user") kept.shift();
return system ? [system, ...kept] : kept;
}
async function ask(userText) {
history.push({ role: "user", content: userText });
const res = await client.chat.completions.create({
model: "deepseek-v4-flash",
messages: trimHistory(history),
});
const reply = res.choices[0].message.content;
history.push({ role: "assistant", content: reply });
return reply;
}
console.log(await ask("One-line Node snippet to read a file as UTF-8."));
console.log(await ask("Now make it fail loudly if the file is missing."));
deepseek-v4-flash vs deepseek-v4-pro
The temptation is to start on the strongest model and never think about it again. In practice that wastes money and often makes latency worse for no quality gain. Start on flash and treat pro as an escalation you have to justify.
| Dimension | deepseek-v4-flash | deepseek-v4-pro |
|---|---|---|
| Speed feel | Snappy — good for chat, autocomplete, UI feedback | Slower, better suited to background jobs |
| Cost | The cheaper default for most traffic | Costs more per request than flash |
| Best at | Extraction, classification, summarisation, rewriting, routine code fixes | Multi-step reasoning, ambiguous specs, tricky refactors |
| Default choice? | Yes — start every new feature here | Only after flash demonstrably fails |
Escalate to deepseek-v4-pro only when you can point at a specific prompt where flash failed twice. Otherwise you are paying more for what is usually a prompt problem.
Retries, rate limits, and the errors you will actually hit
Two failure modes dominate: rate limiting and transient network errors. Both are worth retrying; neither is worth retrying immediately, because hammering a throttled endpoint just extends the throttle. Exponential backoff with a ceiling is the standard answer and takes about fifteen lines.
Check err.status rather than parsing error strings — the SDK surfaces the HTTP status for you. Anything in the 4xx range other than rate limiting means your request is wrong, and retrying will not fix it.
async function chatWithRetry(params, attempts = 4) {
for (let i = 0; i < attempts; i++) {
try {
return await client.chat.completions.create(params);
} catch (err) {
const status = err?.status;
const retryable =
status === 429 || (status >= 500 && status < 600) || status === undefined;
if (!retryable || i === attempts - 1) throw err;
const wait = Math.min(2 ** i * 500, 8000);
await new Promise((resolve) => setTimeout(resolve, wait));
}
}
}
const res = await chatWithRetry({
model: "deepseek-v4-flash",
messages: [{ role: "user", content: "Summarise this stack trace in one sentence: ..." }],
});
console.log(res.choices[0].message.content);
Where AiCredits fits in
AiCredits is an OpenAI-compatible gateway for DeepSeek models built for developers outside mainland China. The practical difference is onboarding: sign up with an email, pay with a card or PayPal, and you get a key. No Chinese phone number, no Chinese bank account, no waiting on a reseller in a chat group.
Because the endpoint mirrors the OpenAI shape, nothing above changes. Point baseURL at https://api.aicreditsapi.com/v1, set model to deepseek-v4-flash, and your messages, streaming loop, and retry wrapper keep working untouched. The same account also gives you access to the code linting tools, which are useful when the model is generating the code and you want a second pass before it lands in a pull request.
Billing is usage-based and depends on which model you call and when. Off-peak requests cost less, cache hits cost less, and pro costs more than flash — the current rates are listed at aicreditsapi.com/pricing.
Production checklist
Construct the client once, in its own module. Do not build it per request.
Read the key from the environment; never commit it.
Always use optional chaining on
chunk.choices[0]?.delta?.contentwhen streaming.Validate parsed JSON against a schema before it reaches your database.
Trim conversation history on a character or token budget before each call.
Retry 429 and 5xx responses with backoff and a ceiling; fail fast on other 4xx.
Log
res.usageso you can see which features are quietly expensive.Pin your default to
deepseek-v4-flashand makedeepseek-v4-proan explicit opt-in per feature.
FAQ
Not through AiCredits. You sign up with an email, pay by card or PayPal, and receive an API key for the OpenAI-compatible endpoint at https://api.aicreditsapi.com/v1. No Chinese phone number or bank account is involved at any step.
Yes, and you should. Pass your AiCredits key as apiKey and set baseURL to the AiCredits endpoint. Messages, streaming, tool calls, and usage reporting all behave the way you already expect, so existing code needs one line changed.
Start on deepseek-v4-flash. It is faster and cheaper and handles the large majority of extraction, summarisation, chat, and routine code tasks well. Move a specific feature to deepseek-v4-pro only when you can show flash failing on that feature repeatedly.
Because the last chunk usually carries a finish reason instead of content, and the first chunk may contain only a role. Use chunk.choices[0]?.delta?.content and skip chunks where it is undefined.
It is usage-based and qualitative rather than flat: off-peak requests cost less than peak, cache hits cost less than fresh input, and deepseek-v4-pro costs more than deepseek-v4-flash. Check aicreditsapi.com/pricing for the current rates rather than relying on a figure from a blog post.
The short version: install the OpenAI SDK, change the base URL, default to deepseek-v4-flash, stream everything user-facing, and guard your context window before it guards you. That combination gets you from an empty folder to a working Node.js integration in an afternoon, and it is the same code you will ship to production — just with better error handling around it.