DeepSeek Integration Guide

Technology: deepseek · Category: ai · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/deepseek

Insight:

DeepSeek is the budget, open-weights tier. One model ID, deepseek-flash (now DeepSeek-V4.1-Flash-1017, with text and image input), covers almost everything. deepseek-v4-pro stays available for the hardest calls. Both have a 1M-token context, 384K max output, and thinking turned on by default: send reasoning_effort: "none" for cheap bulk calls. The API speaks OpenAI Chat Completions, OpenAI Responses and Anthropic Messages, so wiring it in only means changing the baseURL. Data is processed in the PRC, so codeAmani routes only non-sensitive US traffic here. Sensitive data goes to Claude, or to the MIT-licensed weights self-hosted in the US.

██████╗ ███████╗███████╗██████╗ ███████╗███████╗███████╗██╗  ██╗
██╔══██╗██╔════╝██╔════╝██╔══██╗██╔════╝██╔════╝██╔════╝██║ ██╔╝
██║  ██║█████╗  █████╗  ██████╔╝███████╗█████╗  █████╗  █████╔╝
██║  ██║██╔══╝  ██╔══╝  ██╔═══╝ ╚════██║██╔══╝  ██╔══╝  ██╔═██╗
██████╔╝███████╗███████╗██║     ███████║███████╗███████╗██║  ██╗
╚═════╝ ╚══════╝╚══════╝╚═╝     ╚══════╝╚══════╝╚══════╝╚═╝  ╚═╝

DeepSeek Integration Guide

Focus: cost-effective inference and chain-of-thought reasoning with deepseek-flash (V4.1) and deepseek-v4-pro, through the openai SDK, the Vercel AI SDK 7 (@ai-sdk/deepseek), or the Anthropic-compatible endpoint. Also covers the data-residency rules codeAmani applies for US customers.

Overview

As of 2026-10-20 the hosted API serves two model IDs:

Both models have a 1M-token context and a 384K max output. Both support thinking mode, which is ON by default (effort high). They also support tool calls, JSON output, chat-prefix completion (beta) and FIM completion (beta, non-thinking only). Three wire formats reach the same models:

Surface Base URL Use with
OpenAI Chat Completions https://api.deepseek.com openai SDK, @ai-sdk/deepseek, most tools
OpenAI Responses API https://api.deepseek.com (/responses) openai SDK responses.create, Codex
Anthropic Messages https://api.deepseek.com/anthropic @anthropic-ai/sdk, Claude Code
Beta features (FIM, prefix, strict tools) https://api.deepseek.com/beta openai SDK
flowchart LR
  A["Your server code"] --> B{"SDK"}
  B -->|"openai"| C["api.deepseek.com"]
  B -->|"@ai-sdk/deepseek"| C
  B -->|"@anthropic-ai/sdk"| D["api.deepseek.com/anthropic"]
  C --> E{"model"}
  D --> E
  E -->|"deepseek-flash"| F["V4.1-Flash-1017<br/>text + image"]
  E -->|"deepseek-v4-pro"| G["V4-Pro-0813<br/>text only"]
  F --> H{"reasoning_effort"}
  G --> H
  H -->|"none"| I["content only"]
  H -->|"low · high · max"| J["reasoning_content<br/>then content"]

Model history (why old IDs still work)

Date Change
2026-04-24 V4 Preview: deepseek-v4-pro / deepseek-v4-flash launch with 1M context and the thinking toggle.
2026-07-24 deepseek-chat (V3.x) and deepseek-reasoner (R1 line) retired. They no longer work.
2026-08-13 V4-Pro GA (-0813). Effort levels low/high/max added, plus native Responses API and peak/off-peak pricing.
2026-08-21 deepseek-v4-flash-vision-exp launched, along with the Files API.
2026-09-10 V4.1-Flash launched as deepseek-flash. V4-Flash and Vision-Exp retired; their IDs now alias to V4.1-Flash at Flash prices. Prices cut.
2026-10-17 deepseek-flash upgraded to V4.1-Flash-1017 with no price change. Search & Fetch APIs opened to everyone.

Migration: replace deepseek-v4-flash and deepseek-v4-flash-vision-exp with deepseek-flash. The legacy names still resolve, but DeepSeek calls them temporary. Code that still uses deepseek-chat / deepseek-reasoner is already broken.

Official Documentation

Resource URL
API docs (quick start) https://api-docs.deepseek.com/
Models & pricing https://api-docs.deepseek.com/quick_start/pricing
Change log https://api-docs.deepseek.com/updates
Chat Completions reference https://api-docs.deepseek.com/api/create-chat-completion
Thinking mode https://api-docs.deepseek.com/guides/thinking_mode
Tool calls (incl. strict mode) https://api-docs.deepseek.com/guides/tool_calls
JSON output https://api-docs.deepseek.com/guides/json_mode
FIM completion (beta) https://api-docs.deepseek.com/guides/fim_completion
Anthropic API compatibility https://api-docs.deepseek.com/guides/anthropic_api
Responses API https://api-docs.deepseek.com/guides/responses_api
Vision / Files API https://api-docs.deepseek.com/guides/vision
Rate limit & isolation https://api-docs.deepseek.com/quick_start/rate_limit
AI SDK provider https://ai-sdk.dev/providers/ai-sdk-providers/deepseek
Open weights https://huggingface.co/deepseek-ai

SDK Setup

Versions verified on 2026-10-20 with npm view and type-checked under tsc --strict:

Package Version Role
openai 7.39.0 Chat Completions / Responses / FIM client
ai 7.0.146 Vercel AI SDK 7 core
@ai-sdk/deepseek 3.0.69 AI SDK 7 provider (peer zod ^3.25.76 || ^4.1.8)
@anthropic-ai/sdk 0.135.0 Anthropic-format client (also the Claude fallback)
zod 4.6.7 Tool / output schemas
npm install openai@7.39.0
# or, for the AI SDK path:
npm install ai@7.0.146 @ai-sdk/deepseek@3.0.69 zod@4.6.7
// lib/deepseek.ts — server-only
import OpenAI from "openai";

const apiKey = process.env.DEEPSEEK_API_KEY;
if (!apiKey) throw new Error("DEEPSEEK_API_KEY is not set");

export const deepseek = new OpenAI({
  apiKey,
  baseURL: "https://api.deepseek.com",
  timeout: 120_000, // the server holds queued requests up to 10 min; fail over sooner
});

Models & limits

deepseek-flash deepseek-v4-pro
Serves DeepSeek-V4.1-Flash-1017 DeepSeek-V4-Pro-0813
Context 1M tokens 1M tokens
Max output 384K (393,216) 384K
Default max_tokens 8K non-thinking · 64K thinking · 128K at max same
Thinking on by default; none/low/high/max on by default; none/low/high/max
Image input yes (JPEG/PNG/GIF/WebP) no
JSON output · tool calls · Responses · Anthropic API yes yes
FIM (beta) non-thinking only non-thinking only
Concurrency limit (per account) 2,500 500

GET /models returns live metadata (context window, max output, modalities, supported effort levels). Read it at startup instead of hard-coding these numbers.


Core Patterns

Standard chat (thinking off, for cheap bulk work)

Thinking is on by default, so turn it off explicitly for summaries, classification and extraction. reasoning_effort is typed in the openai SDK, so this needs no @ts-expect-error:

const res = await deepseek.chat.completions.create({
  model: "deepseek-flash",
  reasoning_effort: "none", // thinking OFF — cheaper, faster, temperature works
  messages: [
    { role: "system", content: "You are a helpful assistant for codeAmani Labs." },
    { role: "user", content: "Summarize this support ticket in one sentence: ..." },
  ],
  max_tokens: 1024,
});

const text = res.choices[0]?.message.content ?? "";

Thinking mode (reasoning)

Control OpenAI format Anthropic format Responses format
On/off reasoning_effort: "none" (off) or thinking: { type: "enabled" | "disabled" } thinking (budget_tokens ignored) reasoning: { effort: "none" }
Effort reasoning_effort: "low" | "high" | "max" output_config: { effort } reasoning: { effort }

The server maps compatibility values: minimal becomes low, medium and xhigh become high, and ultra becomes max.

import type OpenAI from "openai";

type DeepSeekMessage = OpenAI.Chat.ChatCompletionMessage & {
  reasoning_content?: string | null; // DeepSeek-only field
};

const res = await deepseek.chat.completions.create({
  model: "deepseek-v4-pro",
  reasoning_effort: "high",
  messages: [{ role: "user", content: "Why is my Supabase RLS policy blocking authenticated users?" }],
  max_tokens: 16_384, // caps reasoning + answer together
});

const msg = res.choices[0]?.message as DeepSeekMessage | undefined;
console.log("CoT:", msg?.reasoning_content);
console.log("Answer:", msg?.content);
console.log("Reasoning tokens:", res.usage?.completion_tokens_details?.reasoning_tokens);

Rules (from the thinking-mode guide):

Tool calling

The tool format is standard OpenAI tools / tool_calls. The easiest way to stay correct in thinking mode is to append the returned message object to history unchanged:

const res = await deepseek.chat.completions.create({
  model: "deepseek-flash",
  messages,
  tools,
  tool_choice: "auto",
  reasoning_effort: "high",
});
const message = res.choices[0]!.message;
// Keeps reasoning_content, which is required on later requests that carry `tools`
messages.push(message as OpenAI.Chat.ChatCompletionAssistantMessageParam);
for (const call of message.tool_calls ?? []) {
  if (call.type !== "function") continue;
  messages.push({ role: "tool", tool_call_id: call.id, content: await runTool(call) });
}

The full loop is in examples/tool-loop.ts. Strict mode (beta) uses base URL https://api.deepseek.com/beta, and every function must set strict: true. Each object must list all its properties as required and set additionalProperties: false. Supported types are object, string (pattern, format: email/hostname/ipv4/ipv6/uuid), number/integer (min/max/multipleOf), array (no min/maxItems), enum, anyOf, $ref/$def. Inserting tool calls the model never made into the middle of a conversation works only on the Anthropic and Responses surfaces, not on Chat Completions.

JSON output

const res = await deepseek.chat.completions.create({
  model: "deepseek-flash",
  reasoning_effort: "none",
  response_format: { type: "json_object" }, // only text | json_object — no json_schema
  messages: [
    { role: "system", content: 'Return JSON like {"name": string|null, "amountUsd": number|null}.' },
    { role: "user", content: "Extract from: 'Dana paid $42.50 for order ORD-123'" },
  ],
  max_tokens: 1024,
});
const raw = res.choices[0]?.message.content ?? "";
if (!raw.trim()) throw new Error("empty JSON response — retry"); // documented edge case
const data = JSON.parse(raw) as { name: string | null; amountUsd: number | null };

The prompt must contain the word "json" and should include an example shape. Without them the model can stream whitespace until it hits max_tokens. DeepSeek has no json_schema response format. For schema-validated output, use strict tool calls or the AI SDK's Output.object with zod validation.

FIM (fill-in-the-middle, beta)

const beta = new OpenAI({ apiKey, baseURL: "https://api.deepseek.com/beta" });
const res = await beta.completions.create({
  model: "deepseek-flash",
  prompt: "function fib(n: number): number {\n",
  suffix: "\n}\n",
  max_tokens: 256, // FIM max is 4K
});
console.log(res.choices[0]?.text);

FIM runs in non-thinking mode only, on the legacy /completions endpoint.

Streaming

const stream = await deepseek.chat.completions.create({
  model: "deepseek-flash",
  reasoning_effort: "none",
  stream: true,
  messages: [{ role: "user", content: prompt }],
});
for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}

In thinking mode, delta.reasoning_content chunks arrive before delta.content chunks (see examples/reasoner.ts). While a request waits in the queue, the server sends blank lines (non-streaming) or : keep-alive SSE comments (streaming). The SDK skips them, but a hand-rolled parser must skip them too. If inference has not started after 10 minutes, the server closes the connection.

Vercel AI SDK 7 (@ai-sdk/deepseek)

The provider reads DEEPSEEK_API_KEY by default. It exports deepSeek (canonical) and deepseek (alias). It also sends reasoning_content back between tool steps automatically, which DeepSeek requires.

import { deepSeek, type DeepSeekLanguageModelChatOptions } from "@ai-sdk/deepseek";
import { generateText, isStepCount, tool } from "ai";
import { z } from "zod";

const { text } = await generateText({
  model: deepSeek("deepseek-flash"),
  instructions: "You are an order-support assistant.",
  tools: {
    getOrderStatus: tool({
      description: "Look up an order's status by id.",
      inputSchema: z.object({ orderId: z.string() }),
      execute: async ({ orderId }) => ({ orderId, status: "shipped" as const }),
    }),
  },
  stopWhen: isStepCount(5),
  prompt: "Where is order ORD-123?",
  providerOptions: {
    deepseek: {
      thinking: { type: "enabled" },
      reasoningEffort: "high", // 'low' | 'high' | 'max'
      userId: "tenant_42-user_7", // opaque, no PII
    } satisfies DeepSeekLanguageModelChatOptions,
  },
});

Anthropic-compatible endpoint

import Anthropic from "@anthropic-ai/sdk";

const ds = new Anthropic({
  apiKey: process.env.DEEPSEEK_API_KEY, // a DeepSeek key, not an Anthropic key
  baseURL: "https://api.deepseek.com/anthropic",
});

const msg = await ds.messages.create({
  model: "deepseek-flash",
  max_tokens: 1024,
  system: "You are a helpful assistant.",
  messages: [{ role: "user", content: "Hi, how are you?" }],
});

Model-name mapping: claude-opus* maps to deepseek-v4-pro (billed at Pro rates), and every other claude* name maps to deepseek-flash. Other unknown names return 400. Ignored fields: anthropic-version, cache_control, top_k, mcp_servers, container, service_tier, and thinking.budget_tokens. output_config supports only effort. Document blocks, redacted_thinking, and MCP/code-execution result blocks are not supported. This endpoint is how Claude Code, Claude Desktop developer mode and similar tools run on DeepSeek. Do not point codeAmani's own Claude Code sessions at it (see codeAmani notes).

Responses API, Vision, Files, Search & Fetch


AI Routing: when to use DeepSeek

DeepSeek is a cost-optimisation tier under Anthropic Claude (primary). It is not the default for everything:

flowchart TD
  A["Incoming task"] --> B{"Contains PII, PHI,<br/>payment or customer secrets?"}
  B -->|"yes"| C["Anthropic Claude<br/>(or self-hosted DeepSeek weights in US)"]
  B -->|"no"| D{"Complex agent work<br/>or highest quality?"}
  D -->|"yes"| E["Anthropic<br/>claude-sonnet-5-5"]
  D -->|"no"| F{"Long, repeated prefix<br/>(cache-heavy) or bulk?"}
  F -->|"yes"| G["DeepSeek<br/>deepseek-flash, thinking off"]
  F -->|"no"| H["Anthropic<br/>claude-haiku-5-5"]
Task Recommended
Complex reasoning, agents, anything customer-sensitive claude-sonnet-5-5 (see anthropic/)
Bulk summarise / classify / extract on public or synthetic data deepseek-flash, reasoning_effort: "none"
Cache-heavy long-context jobs (same 100K+ prefix reused) deepseek-flash: cache hits cost $0.003–0.006/M
Step-by-step math / logic on non-sensitive data deepseek-flash at high or max first; deepseek-v4-pro only if an eval shows it wins
Fast classification of customer data claude-haiku-5-5
Strict JSON-schema output OpenAI structured outputs (open-ai/) or DeepSeek strict tools (beta)

Price reality check (2026-10): the anthropic/ guide lists claude-haiku-5-5 at $0.10 / $0.50 per M tokens for prompts up to 100K. That is at or below deepseek-flash cache-miss pricing. DeepSeek's remaining cost edge is cache-hit input ($0.003/M off-peak), very long contexts, and open weights. Benchmark cost per task on your own workload before you route volume to it.


Error handling, retries & fallback

Code Meaning Class Action
400 Invalid request body (also: missing reasoning_content with tools, required tool_choice in thinking mode) terminal Fix the request
401 Wrong API key terminal Fix DEEPSEEK_API_KEY
402 Insufficient balance terminal Top up; fall back immediately
422 Invalid parameters terminal Fix params
429 Concurrency / QPS limit reached (2,500 Flash, 500 Pro per account) transient Back off, then fall back
500 Server error transient Retry after a brief wait
503 Server overloaded transient Retry after a brief wait

finish_reason can also be insufficient_system_resource, which counts as transient. DeepSeek's own advice on 429 is to "temporarily switch to alternative LLM providers".

// lib/ai-resilient.ts
import OpenAI from "openai";
import Anthropic from "@anthropic-ai/sdk";

const deepseek = new OpenAI({
  apiKey: process.env.DEEPSEEK_API_KEY,
  baseURL: "https://api.deepseek.com",
  timeout: 60_000,
  maxRetries: 0, // we own the retry policy below
});
const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });

const RETRYABLE = new Set([429, 500, 503]);
const MAX_RETRIES = 3;
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

/** DeepSeek with jittered backoff on transient errors, then Claude. Non-sensitive input only. */
export async function completeWithFallback(prompt: string): Promise<string> {
  for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
    try {
      const res = await deepseek.chat.completions.create({
        model: "deepseek-flash",
        reasoning_effort: "none",
        messages: [{ role: "user", content: prompt }],
        max_tokens: 2048,
      });
      const choice = res.choices[0];
      // DeepSeek-only finish_reason, not in the OpenAI union, hence the widening cast
      if (choice && (choice.finish_reason as string) !== "insufficient_system_resource") {
        return choice.message.content ?? "";
      }
    } catch (err) {
      const status = err instanceof OpenAI.APIError ? err.status : undefined;
      if (!status || !RETRYABLE.has(status)) break; // terminal or network/timeout -> fallback
    }
    if (attempt === MAX_RETRIES) break;
    const base = 500 * 2 ** attempt;
    await sleep(base + Math.random() * base);
  }

  const msg = await anthropic.messages.create({
    model: "claude-haiku-5-5",
    max_tokens: 2048,
    messages: [{ role: "user", content: prompt }],
  });
  return msg.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("");
}

Cost reference

USD per 1M tokens from the pricing page, checked 2026-10-20, shown as off-peak / peak. Peak hours are 01:00–04:00 and 06:00–10:00 UTC, Monday–Friday, excluding Chinese public holidays. All other hours, including weekends and Chinese holidays, bill at the off-peak rate, which is 50% of peak.

Model Input (cache hit) Input (cache miss) Output
deepseek-flash (V4.1-Flash-1017) $0.003 / $0.006 $0.15 / $0.30 $0.60 / $1.20
deepseek-v4-pro (V4-Pro-0813) $0.022 / $0.044 $0.66 / $1.32 $1.98 / $3.96
Search API · Fetch API $0.75 per 1,000 successful requests (each)

Open weights & licence

Repo (Hugging Face deepseek-ai/) Licence Notes
DeepSeek-V4.1-Flash-1017 MIT Weights for the model behind deepseek-flash today
DeepSeek-V4.1-Flash MIT 2026-09-10 release, with tech report
DeepSeek-V4-Pro MIT 1.6T total / 49B active
DeepSeek-V4-Flash MIT 284B total / 13B active (retired from the API)

DeepSeek describes V4.1-Flash as a 552B-parameter MoE with a causal encoder–decoder design: 8B active parameters for input and 16B for output. The repo's safetensors metadata counts about 763B parameters (see NOTES.md). The weights are MIT-licensed, so commercial use, fine-tuning and redistribution are allowed as long as the copyright notice is kept. Serving them takes multi-GPU, data-centre-class hardware. Self-hosting in a US region (or using a US-hosted inference provider that serves these weights) gives you DeepSeek quality without sending data to the PRC.


Data residency & compliance (US customers)


Environment Variables

The only secret is the API key:

DEEPSEEK_API_KEY=sk-...

Non-secret settings go in code or config, not in the secrets vault:

Setting Value
OpenAI-format base URL https://api.deepseek.com
Anthropic-format base URL https://api.deepseek.com/anthropic
Beta base URL (FIM, prefix, strict tools) https://api.deepseek.com/beta
Default model deepseek-flash
Escalation model deepseek-v4-pro

Troubleshooting

Issue Fix
model not found / 400 on deepseek-chat / deepseek-reasoner Retired 2026-07-24. Use deepseek-flash.
Unexpectedly high bill or slow responses Thinking is on by default. Send reasoning_effort: "none" for bulk calls.
temperature has no effect Ignored in thinking mode. Turn thinking off first.
400 on the second tool-loop request You dropped reasoning_content. Append the full assistant message.
400 with tool_choice: "required" Not allowed in thinking mode. Use "auto" or turn thinking off.
JSON mode returns whitespace / empty Put "json" and an example shape in the prompt, set max_tokens, and retry on empty.
Image input rejected on deepseek-v4-pro Pro is text-only. Use deepseek-flash.
FIM / strict tools fail Use baseURL: "https://api.deepseek.com/beta". FIM is non-thinking only.
429 under load Account concurrency is 2,500 (Flash) / 500 (Pro). Back off, fall back, or request expansion (free).
reasoning_content is a TS error It is not in the OpenAI types. Intersect ChatCompletionMessage & { reasoning_content?: string | null }.

codeAmani notes

Official docs: