# deepseek-v4 (https://reapi.ai/docs/deepseek-v4)

> The DeepSeek V4 API ships two open-weight models — **`deepseek-v4-flash`**
> (fast, low-cost) and **`deepseek-v4-pro`** (frontier reasoning and agentic
> coding) — exposed through reAPI as a drop-in OpenAI-compatible Chat
> Completions endpoint. Both bring a 1M-token context window, 384K max output,
> thinking mode on by default, vision input, tool use, and context caching.
> Current rates live on the
> [model page](https://reapi.ai/models/deepseek-v4).

## Quick example

### cURL

    ```bash
    curl https://api.reapi.ai/v1/chat/completions \
      -H "Authorization: Bearer YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "model": "deepseek-v4-flash",
        "messages": [
          { "role": "user", "content": "Hello" }
        ],
        "stream": true,
        "max_tokens": 4096,
        "temperature": 0.7
      }'
    ```

### Python (OpenAI SDK)

    ```python
    from openai import OpenAI

    client = OpenAI(
        api_key="YOUR_API_KEY",
        base_url="https://api.reapi.ai/v1",
    )

    stream = client.chat.completions.create(
        model="deepseek-v4-flash",  # or "deepseek-v4-pro"
        messages=[{"role": "user", "content": "Hello"}],
        stream=True,
        max_tokens=4096,
        temperature=0.7,
    )

    for chunk in stream:
        delta = chunk.choices[0].delta.content or ""
        print(delta, end="", flush=True)
    ```

### Node.js

    ```js
    import OpenAI from "openai";

    const client = new OpenAI({
      apiKey: "YOUR_API_KEY",
      baseURL: "https://api.reapi.ai/v1",
    });

    const stream = await client.chat.completions.create({
      model: "deepseek-v4-flash", // or "deepseek-v4-pro"
      messages: [{ role: "user", content: "Hello" }],
      stream: true,
      max_tokens: 4096,
      temperature: 0.7,
    });

    for await (const chunk of stream) {
      process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
    }
    ```

### Go

    ```go
    package main

    import (
        "bytes"
        "encoding/json"
        "fmt"
        "io"
        "net/http"
    )

    func main() {
        body, _ := json.Marshal(map[string]any{
            "model": "deepseek-v4-flash", // or "deepseek-v4-pro"
            "messages": []map[string]string{
                {"role": "user", "content": "Hello"},
            },
            "stream":      true,
            "max_tokens":  4096,
            "temperature": 0.7,
        })
        req, _ := http.NewRequest("POST",
            "https://api.reapi.ai/v1/chat/completions", bytes.NewReader(body))
        req.Header.Set("Authorization", "Bearer YOUR_API_KEY")
        req.Header.Set("Content-Type", "application/json")

        resp, _ := http.DefaultClient.Do(req)
        defer resp.Body.Close()
        out, _ := io.ReadAll(resp.Body)
        fmt.Println(string(out))
    }
    ```

***

## Authentication

Use your reAPI API key — the same key that calls the image, video and audio
endpoints — as a bearer token:

```http
Authorization: Bearer YOUR_API_KEY
```

Create one under **API keys** in your reAPI dashboard. Chat requests are billed
from the same credit balance as every other model on the platform.

***

## Models

The DeepSeek V4 family ships two variants. Both share the same endpoint,
request shape, 1M context window, and 384K max output — pick the variant
with the `model` field.

| `model`             | Best for                                                                                                      | Architecture                  |
| ------------------- | ------------------------------------------------------------------------------------------------------------- | ----------------------------- |
| `deepseek-v4-flash` | Fast, low-cost everyday work — autocomplete, batch analysis, chat backends. Reasoning closely approaches Pro. | 284B total / 13B active (MoE) |
| `deepseek-v4-pro`   | Frontier reasoning, complex debugging, and agentic coding. Rivals top closed-source models.                   | 1.6T total / 49B active (MoE) |

  The legacy ids `deepseek-chat` and `deepseek-reasoner` map to
  `deepseek-v4-flash` in non-thinking and thinking mode respectively. New
  integrations should use the explicit `deepseek-v4-flash` /
  `deepseek-v4-pro` ids.

***

## Endpoint

```http
POST https://api.reapi.ai/v1/chat/completions
```

Drop-in for the OpenAI SDKs — same request shape, same SSE wire format. Set
`base_url` to `https://api.reapi.ai/v1`. DeepSeek V4 also supports the
Anthropic API format natively; this guide documents the OpenAI-compatible
Chat Completions surface.

***

## Request body

### `model` — string, required

`"deepseek-v4-flash"` or `"deepseek-v4-pro"`. Echoed back in the response
envelope.

### `messages` — array, required

Conversation history as an array of message objects. Same shape as the
OpenAI Chat Completions spec, plus content-parts for vision:

```json
{
  "role": "system" | "user" | "assistant" | "tool",
  "content": "string OR content-parts array (text + image_url parts)"
}
```

Multi-turn history is sent in chronological order — the last message is the
one the model responds to. In thinking mode **with `tools`**, keep the returned
assistant messages, including historical `reasoning_content` and `tool_calls`,
when continuing the conversation. **Without `tools`**, historical reasoning is
not required and is ignored if supplied. See DeepSeek's
[thinking-mode guide](https://api-docs.deepseek.com/guides/thinking_mode/).

### `max_tokens` — integer

Upper bound on output tokens for this response, **including the
chain-of-thought when thinking mode is on**. The synchronous API supports up
to 384K output tokens, subject to the remaining context capacity. On this reAPI
endpoint, omission uses the configured model cap of **384,000**; `4096` in the
examples is an explicit request budget, not the default. Set a budget suited to
the task and leave room for both reasoning and the final answer.

### `stream` — boolean, default `false`

When `true`, the response is streamed as server-sent events (SSE) with
`Content-Type: text/event-stream`. Each event is a JSON delta in the OpenAI
format, terminated by a `data: [DONE]` line.

### `reasoning_effort` — string, default `"high"`

How hard the model thinks before answering. Three rungs:

| Level  | Use it for                                                                                                         |
| ------ | ------------------------------------------------------------------------------------------------------------------ |
| `max`  | The hardest reasoning, where correctness outweighs latency and cost.                                               |
| `high` | **The default.** Reasons thoroughly without reaching for the ceiling.                                              |
| `low`  | Short, scoped, latency-sensitive work — and the answer to "the thinking is costing more than the answer is worth". |

`medium` and `xhigh` are accepted as compatibility aliases and both resolve to
`high`, so a request carrying either gets the default rung rather than an
error.

### `temperature` — number, default `1`

Sampling temperature, up to `2`. Lower values produce more deterministic
output. **Ignored while the model is in thinking mode.**

### `top_p` — number, default `1`

Nucleus sampling cutoff, up to `1`. Ignored in thinking mode.

### `frequency_penalty` / `presence_penalty` — deprecated

**No longer supported.** DeepSeek marks both as deprecated: a request carrying
them is accepted, and the value has no effect. Steer repetition with prompting
or the `reasoning_effort` rung instead.

### `stop` — string or array, optional

Up to four stop sequences. Generation ends when one is produced, and the
sequence itself is not returned.

### `logprobs` / `top_logprobs` — optional

`logprobs: true` returns a log probability for each output token.
`top_logprobs` (0–20) additionally returns that many alternatives per
position, and requires `logprobs: true`.

### `tools` / `tool_choice` — optional

Standard OpenAI tool-calling parameters. DeepSeek V4 ships dedicated agentic
optimizations with reliable function calling and JSON output.

### Fields this model does not have

`seed` and `n` are not part of the DeepSeek V4 request surface. Both are
accepted without an error and neither changes the result, so a client that
relies on either gets silence rather than a failure — send neither.

***

## Thinking mode

DeepSeek V4 runs in **thinking mode by default**: before the final answer it
produces a chain of thought, returned in a `reasoning_content` field at the
same level as `content`.

```json
{
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "reasoning_content": "Let me work through this step by step...",
        "content": "The final answer."
      },
      "finish_reason": "stop"
    }
  ]
}
```

Two controls govern it. `reasoning_effort` picks how hard the model thinks
(`low` / `high` / `max`), and the `thinking` object switches the mode outright:

```json
{ "thinking": { "type": "enabled" } }
```

For latency-sensitive or simple calls, drop to `reasoning_effort: "low"` or
turn thinking off for faster, cheaper responses. While thinking is on,
`temperature` and `top_p` have no effect — and `frequency_penalty` /
`presence_penalty` have none in either mode, being deprecated outright.

  **Do not strip reasoning from a tool-calling conversation.** With `tools`
  present in thinking mode, return the historical assistant messages with their
  `reasoning_content`, followed by the tool results. That history counts toward
  the context budget. In a conversation without `tools`, previous reasoning is
  ignored and need not be resent.

***

## Vision input (beta)

Send images alongside text via OpenAI content-parts:

```json
{
  "model": "deepseek-v4-pro",
  "max_tokens": 4096,
  "messages": [
    {
      "role": "user",
      "content": [
        { "type": "text", "text": "What does this chart show?" },
        {
          "type": "image_url",
          "image_url": { "url": "https://example.com/chart.png" }
        }
      ]
    }
  ]
}
```

Each image counts toward the input token budget based on its resolution.

***

## Context caching

DeepSeek V4 caches stable prompt prefixes automatically. When a request hits
the cache, the cached input tokens bill at a small fraction of the standard
input rate — a big saving for agent loops and chatbots that replay long
system prompts and tool schemas. No configuration is required; reuse the same
prefix across calls and the discount applies. The
`usage.prompt_tokens_details.cached_tokens` field reports how many input
tokens were served from cache.

***

## Response shape

### Non-streaming (`stream: false`)

```json
{
  "id": "chatcmpl-018f5a3a1b6e7d9f8c2b4d6e8f0a2c4e",
  "object": "chat.completion",
  "created": 1735000000,
  "model": "deepseek-v4-flash",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Hello! How can I help you today?"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 12,
    "completion_tokens": 9,
    "total_tokens": 21,
    "prompt_tokens_details": {
      "cached_tokens": 0
    }
  }
}
```

When thinking mode is on, `message.reasoning_content` carries the
chain-of-thought alongside `content`.

### Streaming (`stream: true`)

`Content-Type: text/event-stream`. Each `data:` line is a JSON delta in the
OpenAI chunk format; the final event before `[DONE]` carries the
`finish_reason` (`stop` / `length` / `tool_calls` / `content_filter`).

***

## Groups

See the [model page’s live group prices](/models/deepseek-v4#pricing). Flash and Pro list their own groups. Copy the complete model ID shown for the group you want and use it in the normal `model` field. The same reAPI key works across available groups; no separate group key is needed.

The bare `deepseek-v4-flash` and `deepseek-v4-pro` model IDs use the `deepseek` group by default. To choose another available group, use its full model ID from the price table, such as `deepseek-v4-pro:default`. For programmatic discovery and compatibility details, see [LLM groups](/docs/api/llm-groups).

## Pricing

DeepSeek V4 is billed **pay-as-you-go** from your reAPI credit balance
(`1 credit = $0.001`, `$1 = 1,000 credits`). It bills along three dimensions — input tokens (cache miss),
input tokens (cache hit), and output tokens — and `deepseek-v4-pro` costs
more per token than `deepseek-v4-flash`. Current rates live in the pricing card at the top of the
[model page](https://reapi.ai/models/deepseek-v4).

Per-call bill:

```
billable_input  = (prompt_tokens - cached_tokens) × input_rate      / 1,000,000
cache_read_bill = cached_tokens                   × cache_hit_rate   / 1,000,000
output_bill     = completion_tokens               × output_rate      / 1,000,000
```

Output tokens include the chain-of-thought when thinking mode is on. Failed
requests are not charged.

***

## Limits

| Limit               | Value       |
| ------------------- | ----------- |
| Context window      | 1M tokens   |
| Max output per call | 384K tokens |

Streams that hit the output cap finish with `finish_reason: "length"`;
call again with a continuation message if you need more text.

***

## Errors

The error envelope follows the OpenAI shape — HTTP status, plus a JSON body:

```json
{
  "error": {
    "message": "...",
    "type": "invalid_request_error",
    "code": "..."
  }
}
```

Common cases:

| Status | When                                       | Notes                                              |
| ------ | ------------------------------------------ | -------------------------------------------------- |
| `400`  | Bad request shape, unsupported param combo | Check the `messages` array and `model` id          |
| `401`  | Missing / invalid API key                  | Create a key under API keys in the reAPI dashboard |
| `402`  | Insufficient balance                       | Top up your reAPI credits                          |
| `429`  | Rate limit hit                             | Back off and retry                                 |
| `500`  | Upstream / gateway error                   | Safe to retry — failed calls are not charged       |

  reAPI does **not** internally retry chat requests. Every customer
  call maps to exactly one upstream POST. If a network error reaches you, that
  is a one-for-one wire failure and a retry from your side is safe; the gateway
  will not double-bill.

***

## Recipes

### Minimum request

```json
{
  "model": "deepseek-v4-flash",
  "max_tokens": 4096,
  "messages": [
    { "role": "user", "content": "Summarise this in three sentences." }
  ]
}
```

### Tool use (function calling)

```json
{
  "model": "deepseek-v4-pro",
  "max_tokens": 4096,
  "messages": [
    { "role": "user", "content": "What's the weather in Tokyo today?" }
  ],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "Look up the current weather for a city.",
        "parameters": {
          "type": "object",
          "properties": { "city": { "type": "string" } },
          "required": ["city"]
        }
      }
    }
  ],
  "tool_choice": "auto"
}
```

### Long-context analysis

```json
{
  "model": "deepseek-v4-pro",
  "max_tokens": 8192,
  "messages": [
    { "role": "system", "content": "<a long, stable reference document>" },
    { "role": "user", "content": "List every mention of constraint X with line numbers." }
  ]
}
```

Keep the long reference block stable across calls so the cache-hit rate
applies on subsequent requests.

***

## When to pick Flash vs Pro

* **`deepseek-v4-flash`** — latency-sensitive, high-throughput, cost-sensitive
  work: in-IDE autocomplete, inline suggestions, CI code review, bulk
  summarization, chat backends. Reasoning closely approaches Pro at a fraction
  of the price.
* **`deepseek-v4-pro`** — work where reasoning depth dominates: complex
  debugging, architecture planning, math/STEM, and long-horizon agentic
  coding. Both share one key — route per request.

***

## Tips

* **Set `max_tokens` generously when thinking is on.** The chain-of-thought
  counts toward the output budget; a low cap can truncate before the final
  answer.
* **Preserve reasoning in tool loops.** In thinking mode with `tools`, retain
  historical assistant `reasoning_content` and `tool_calls`. Without `tools`,
  previous reasoning is ignored and need not be sent.
* **Stream by default for chat UX.** Streaming cuts perceived latency.
* **Cache stable prefixes.** Reuse the same system prompt and tool schemas
  across calls to bill repeated input at the low cache-hit rate.
* **Route by difficulty.** Send simple, high-volume calls to Flash and
  reserve Pro for the hardest reasoning, all on one key.

***

## Related

* [Authentication](/docs/api/authentication)
* [Quickstart](/docs/api/quickstart)
* [Errors catalog](/docs/api/errors)