+FreeDeepseekAPI runs on your computer and turns your free [chat.deepseek.com](https://chat.deepseek.com) account into a local API. Any app that works with OpenAI or Anthropic can talk to DeepSeek through it: Open WebUI, Claude Code, Codex, Cursor and others. You don't need a paid API key.
-## Start here
+## Get started
-**What it is.** You have a free DeepSeek account on [chat.deepseek.com](https://chat.deepseek.com). FreeDeepseekAPI runs on your computer and turns that account into an API at `http://127.0.0.1:9655`, the same kind of address paid AI services give you. Any app that can talk to OpenAI or Anthropic can then use DeepSeek through it: Open WebUI, Cursor, Claude Code, Codex, your own scripts. No paid API key: your own account, on your own machine.
-
-**You need:** [Node.js](https://nodejs.org) 18 or newer, Git, Google Chrome, and a free DeepSeek account.
-
-### 1. Start it (one minute)
+You need [Node.js](https://nodejs.org) 18 or newer, Git, Google Chrome and a DeepSeek account.
```bash
git clone --branch stable https://github.com/dekrezz/FreeDeepseekAPI.git
@@ -52,884 +34,121 @@ npm run auth
npm run dashboard
```
-- `npm run auth`: choose **Sign in with Chrome**, log in at chat.deepseek.com in the window it opens, send a short message such as `ok`, then go back to the terminal. Your login is saved to `deepseek-auth.json`.
-- `npm run dashboard`: starts the proxy and opens `http://127.0.0.1:9655/dashboard`. You can chat with DeepSeek right there.
+1. `npm run auth` opens Chrome. Pick **Sign in with Chrome**, log in to DeepSeek, send a short message like `ok`, then go back to the terminal.
+2. `npm run dashboard` starts the proxy and opens the dashboard. You can chat right there.
+
+## Connect an app
-### 2. Connect your app
+Put this in your app's settings:
| Setting | Value |
|---|---|
| Base URL | `http://127.0.0.1:9655/v1` |
-| API key | any text (if you started the proxy with `PROXY_API_KEY`, use that key) |
-| Model | `deepseek-v4-flash` answers with web search, `deepseek-v4-flash-thinking` thinks first; add `-nosearch` to either to turn search off |
+| API key | any text |
+| Model | `deepseek-v4-flash` |
-Open WebUI running in Docker: use `http://host.docker.internal:9655/v1`.
+Open WebUI in Docker needs `http://host.docker.internal:9655/v1` instead.
-### 3. Coding agents in one command
+## Set up coding agents
-While the proxy is running:
+Keep the proxy running and run:
```bash
npm run setup:agents
```
-It sets up Claude Code, Codex, OpenCode, Hermes, OpenClaw and Cursor as an extra profile; whatever you use today stays as it is. You can also do it from the dashboard: Settings → Agents. Then start, for example, `claude --settings ~/.claude/freedeepseek.settings.json` or `codex --profile freedeepseek`.
-
-Something wrong? `npm run doctor` checks your setup, and `curl http://127.0.0.1:9655/health` shows whether the proxy is up. Everything else is below.
-
----
-
-FreeDeepseekAPI runs a local API server in front of **DeepSeek Web Chat** ([chat.deepseek.com](https://chat.deepseek.com)). Point Open WebUI, LiteLLM, Hermes, Claude Code, Codex, OpenCode, OpenClaw, Cursor, or any OpenAI-compatible client at it.
-
-The project uses your normal logged-in DeepSeek account. The local server accepts API requests, then continues that saved Web session. There is no paid `api.deepseek.com` key.
-
-One model is on the site today: **DeepSeek-V4.1-Flash**. The native Web Search built into chat.deepseek.com is **on by default**, and that search is what answers live internet questions. `-thinking` turns DeepThink on. `-nosearch` or `"web_search": false` turns search off.
-
-> This is an experimental Web-chat proxy. DeepSeek can change its private Web API at any time. When it does, the project is updated to follow, and this guide may change with it. Keep your copy on the newest version: Settings → Updates in the dashboard, or see [Updates](#updates).
-
----
-
-## Contents
-
-- [Start here](#start-here)
-- [What you get](#what-you-get)
-- [Features](#features)
-- [Quick start](#quick-start)
-- [Windows](#windows)
-- [Linux / Chromium](#linux--chromium)
-- [VPS / headless](#vps--headless)
-- [Rootless Podman](#rootless-podman)
-- [Diagnostics / doctor](#diagnostics--doctor)
-- [Session reuse](#session-reuse)
-- [Multi-account pool](#multi-account-pool)
-- [Dashboard](#dashboard)
-- [Updates](#updates)
-- [Sign-in](#sign-in)
-- [Coding agents](#coding-agents)
-- [Check that it works](#check-that-it-works)
-- [Request examples](#request-examples)
- - [Chat Completions](#chat-completions)
- - [DeepThink](#deepthink)
- - [Native web search](#native-web-search)
- - [Streaming](#streaming)
- - [Anthropic Messages](#anthropic-messages)
- - [OpenAI Responses](#openai-responses)
- - [Tool calling](#tool-calling)
- - [Images](#images)
-- [Models](#models)
-- [Endpoints](#endpoints)
-- [Environment](#environment)
-- [Errors](#errors)
-- [Open WebUI](#open-webui)
-- [Refresh the login](#refresh-the-login)
-- [Tests](#tests)
-- [Project status](#project-status)
-
----
-
-## What you get
-
-- Use DeepSeek Web as a local API endpoint.
-- Connect DeepSeek to Open WebUI and other OpenAI-compatible clients.
-- Get a normal JSON body or a streaming SSE response.
-- Turn DeepThink on with `-thinking` and read `reasoning_content`.
-- Talk to Claude Code through the Anthropic Messages shim.
-- Talk to Codex through the OpenAI Responses shim.
-- Keep a separate Web chat for each agent or `user` id.
-- Let several local tools run in one reply, up to eight.
-- Search the live web with DeepSeek's own search, not with bash or a harness websearch tool.
-
-## Features
-
-- **OpenAI-compatible API:** `POST /v1/chat/completions`
-- **Anthropic-compatible shim:** `POST /v1/messages`
-- **OpenAI Responses shim:** `POST /v1/responses`
-- **Streaming:** SSE chunks, and a normal non-stream JSON body
-- **DeepThink:** `reasoning_content` when `-thinking` is on
-- **Native search:** chat.deepseek.com Web Search, on by default. Off with `-nosearch` or `"web_search": false`
-- **Tool calling:** OpenAI tools, Anthropic tools, and Responses function tools, returned as a batch
-- **Model capabilities:** `GET /v1/model-capabilities`
-- **Agent sessions:** one DeepSeek chat per `x-agent-session` or `user`
-- **Session recovery:** an empty reply, a broken tool call, or a timeout keeps the same chat
-- **Zero dependencies:** Node.js 18+, no npm packages
-- **License:** Apache-2.0
-
----
-
-## Quick start
+It adds DeepSeek to Claude Code, Codex, OpenCode, Hermes, OpenClaw and Cursor as an extra option. Your current setup stays as it is, and you can skip this step in the wizard. The same thing is in the dashboard: Settings → Agents.
-```bash
-git clone --branch stable https://github.com/dekrezz/FreeDeepseekAPI.git
-cd FreeDeepseekAPI
-npm run auth
-npm start
-```
+## FAQ
-`npm run auth` opens the sign-in menu. Choose Chrome sign-in, log in at chat.deepseek.com in the profile it opens, send a short message such as `ok`, then return to the terminal and continue. The saved file is `deepseek-auth.json`, mode `0600`.
+
+Is it really free?
-`npm start` opens the launch menu:
+Yes. It uses the same free account you use on the DeepSeek site.
-- Start proxy
-- Start proxy + open dashboard (also `npm run dashboard`)
-- Sign in with Chrome
-- Import an auth file or a browser cookie export
-- Show the DeepSeek-V4.1-Flash model ids
-- Quit
+
-Headless or CI, with no menu:
-
-```bash
-NON_INTERACTIVE=1 npm start
-# or
-SKIP_ACCOUNT_MENU=1 npm start
-```
-
-The server listens on:
-
-```text
-http://127.0.0.1:9655
-```
+
+Is this an official DeepSeek project?
-By default only this computer can reach it. To publish it on a network, set an address and a proxy key:
+No. It talks to DeepSeek's private web chat, which can change at any time. When that happens, the project gets updated to follow.
-```bash
-HOST=0.0.0.0 PROXY_API_KEY='replace-with-a-long-random-value' npm start
-```
-
-Send that key as `Authorization: Bearer `. Without `PROXY_API_KEY`, the API has no authentication of its own. Do not put that instance on a network.
-
-Browser calls are allowed from loopback origins. If the UI is on another origin, list the exact origins, comma-separated:
-
-```bash
-PROXY_CORS_ORIGINS='https://ui.example.com,http://192.168.1.20:3000'
-```
-
----
-
-## Windows
-
-```powershell
-git clone --branch stable https://github.com/dekrezz/FreeDeepseekAPI.git
-cd FreeDeepseekAPI
-npm run auth
-npm start
-```
-
-If Chrome is not in the usual place:
-
-```powershell
-$env:CHROME_PATH="C:\Program Files\Google\Chrome\Application\chrome.exe"
-npm run auth
-```
-
-When Chrome is missing, `npm run auth` prints the install path for Windows, macOS, or Linux instead of a raw stack trace.
-
----
-
-## Linux / Chromium
-
-```bash
-git clone --branch stable https://github.com/dekrezz/FreeDeepseekAPI.git
-cd FreeDeepseekAPI
-CHROME_PATH=$(which chromium) npm run auth
-npm start
-```
-
-If the binary has another name:
-
-```bash
-CHROME_PATH=$(which chromium-browser) npm run auth
-# or
-CHROME_PATH=$(which google-chrome) npm run auth
-```
-
----
-
-## VPS / headless
-
-The reliable path does not run Chrome on the server.
-
-1. On a machine that has a GUI and Chrome:
-
-```bash
-npm run auth
-```
-
-2. Copy `deepseek-auth.json` to the VPS:
-
-```bash
-scp deepseek-auth.json user@your-vps:/opt/FreeDeepseekAPI/deepseek-auth.json
-```
-
-3. Import it and check the file:
-
-```bash
-cd /opt/FreeDeepseekAPI
-npm run auth:import -- --input ./deepseek-auth.json
-npm run doctor -- --offline
-```
-
-4. Start the proxy with no menu:
-
-```bash
-NON_INTERACTIVE=1 npm start
-```
-
-A browser cookie export works too, if you also have the token:
-
-```bash
-DEEPSEEK_TOKEN="" npm run auth:import -- --input ./cookies.json
-```
+
-`deepseek-auth.json` is access to your DeepSeek Web login. Do not commit it, do not paste it into a chat, and keep it mode `0600`.
+
+Can my account get banned?
-There is no password login command. The proxy never asks for your DeepSeek password and never stores one. Sign-in is Chrome, a saved auth file, or a cookie export plus token.
+It can happen. DeepSeek can block a login for days if two chats send on it at the same time, so the proxy runs one chat per login and makes the next one wait. That lowers the risk but can't remove it. DeepSeek decides what it allows.
----
+
-## Rootless Podman
+
+Where do my login and messages go?
-The container only runs the proxy. Sign in on the host with `npm run auth`. Auth scripts and `deepseek-auth.json` are not copied into the image.
-
-Run Podman as your user, not as root.
-
-1. Build the image:
-
-```bash
-podman build --tag localhost/free-deepseek-api:local --file Containerfile .
-```
-
-2. Store the DeepSeek auth file and a separate proxy key as secrets:
-
-```bash
-podman secret create --replace free-deepseek-auth ./deepseek-auth.json
-
-printf 'Proxy API key: '
-IFS= read -r -s PROXY_API_KEY
-printf '\n'
-printf '%s' "$PROXY_API_KEY" |
- podman secret create --replace free-deepseek-proxy-key -
-```
-
-Use a long random key. The value stays in this shell so you can call the API. It is not baked into the image or the Podman command line.
-
-3. Start the container with the privileges dropped:
-
-```bash
-podman run --detach \
- --name free-deepseek-api \
- --publish 127.0.0.1:9655:9655 \
- --secret free-deepseek-auth,type=mount,target=/run/secrets/deepseek-auth.json,mode=0400 \
- --secret free-deepseek-proxy-key,type=mount,target=/run/secrets/proxy-api-key,mode=0400 \
- --read-only \
- --cap-drop=ALL \
- --security-opt=no-new-privileges \
- localhost/free-deepseek-api:local
-```
-
-Inside the image, `NON_INTERACTIVE=1`, `HOST=0.0.0.0`, and `REQUIRE_PROXY_API_KEY=1` are already set. The container refuses to serve if the proxy-key secret is missing or empty. On the host the port is published only on `127.0.0.1`. Do not drop that address unless you have a firewall in front of it.
-
-4. Check liveness, account readiness, and the protected model list:
-
-```bash
-podman healthcheck run free-deepseek-api
-curl --fail http://127.0.0.1:9655/readyz
-curl --fail \
- -H "Authorization: Bearer $PROXY_API_KEY" \
- http://127.0.0.1:9655/v1/models
-```
-
-The built-in healthcheck hits local `/health` and only tells you the process is up. `/readyz` returns `503` when no DeepSeek login can serve a chat right now.
-
-```bash
-podman logs free-deepseek-api
-podman inspect --format '{{.State.Health.Status}}' free-deepseek-api
-```
-
-Stop the container and remove the secrets:
-
-```bash
-podman stop free-deepseek-api
-podman rm free-deepseek-api
-podman secret rm free-deepseek-auth free-deepseek-proxy-key
-unset PROXY_API_KEY
-```
-
-When you rotate the login or the proxy key, replace the secret and recreate the container.
-
----
-
-## Diagnostics / doctor
-
-```bash
-npm run doctor
-# no network call to DeepSeek:
-npm run doctor -- --offline
-```
-
-`doctor` checks:
-
-- whether `deepseek-auth.json` or `DEEPSEEK_AUTH_DIR` is present;
-- whether the JSON parses;
-- whether `token`, `cookie`, and `wasmUrl` are set;
-- whether the file mode is `0600` on macOS and Linux;
-- on a normal run, whether the DeepSeek PoW endpoint answers.
-
-If you see `data.biz_data is null`, `fetch failed`, `401`, `403`, `429`, or a coding agent that cannot list models, run `npm run doctor` first.
-
----
-
-## Session reuse
-
-FreeDeepseekAPI does not open a new DeepSeek chat on every HTTP request.
-
-- One `x-agent-session`, `session`, or `user` value is one DeepSeek chat.
-- When that chat already exists, the proxy continues it with `parent_message_id`.
-- The standing system prompt and the tool list go upstream **once**. Later turns from OpenCode, Claude Code, and Codex send only the new user or tool turn.
-- A changed system prompt is sent again.
-- An empty reply, a broken tool-call, or a timeout **keeps** the live chat. Those failures used to open a new chat and resend the whole prompt. They do not anymore.
-- A new chat starts when the session is missing, the chain hits 100 messages, the chat is older than 2 hours, DeepSeek says the prompt is too long, or you call `/reset-session`.
-- Long prompts are cut to `DEEPSEEK_MAX_PROMPT_CHARS` (default 80,000 characters) before they are sent. The start of the task, the latest tool results, and the tool reminder stay.
-- If the client already sent a multi-turn history, the proxy does not paste its own recovery history a second time.
-- An empty reply is retried up to `DEEPSEEK_MAX_RETRIES` times (default 2). Each retry uses a smaller slice of context, still on the same chat when that chat is alive.
-
-Set the agent explicitly:
-
-```bash
-curl -X POST http://127.0.0.1:9655/v1/chat/completions \
- -H "Content-Type: application/json" \
- -H "x-agent-session: my-agent" \
- -d '{"model":"deepseek-v4-flash","messages":[{"role":"user","content":"Hello"}]}'
-```
-
-List active sessions:
-
-```bash
-curl http://127.0.0.1:9655/v1/sessions
-```
-
-Reset one session:
-
-```bash
-curl -X POST "http://127.0.0.1:9655/reset-session?agent=my-agent"
-```
-
-Reset every session:
-
-```bash
-curl -X POST "http://127.0.0.1:9655/reset-session?agent=all"
-```
-
-A reset keeps the proxy's copy of the conversation and replays it into the next chat when the client sends only one message. Add `&history=drop` when the client will send its own full transcript, for example after editing an earlier message, so the replaced turns do not come back.
-
-You will still see chats in the DeepSeek website. The proxy uses the Web Chat API, and DeepSeek stores the real chats. Session reuse only stops the proxy from opening a new one when the current chain is still good.
-
-A message whose text is exactly `/new` resets that agent's remote chat instead of sending the text to the model.
-
----
-
-## Multi-account pool
-
-DeepSeek can ban a login for days if two chats send on that same login at the same time. The pool rule is: one in-flight chat per login. A second request for a busy login waits. It does not overlap.
-
-Sticky means the proxy does not hop accounts in the middle of a live chat, except when that login is rate-limited or loses auth. If the login gets `401` or `403`, or DeepSeek rate-limits it, the login goes into cooldown and the old remote session is dropped. A rate-limited request does not fail: it moves right away to another ready login, on a new chat that gets the full transcript. After `401`/`403`, the next request moves.
-
-Directory of auth files:
-
-```bash
-mkdir -p accounts
-npm run auth:import -- --input ~/Downloads/deepseek-auth.json --output ./accounts/worker-2.json
-chmod 600 accounts/*.json deepseek-auth.json
-DEEPSEEK_AUTH_DIR=./accounts NON_INTERACTIVE=1 npm start
-```
-
-Or a comma-separated list:
-
-```bash
-DEEPSEEK_AUTH_PATH="./accounts/main.json,./accounts/backup.json" NON_INTERACTIVE=1 npm start
-```
+Your login stays on your computer in `deepseek-auth.json`. Your messages go to DeepSeek, the same as in the normal chat.
-How the pool behaves:
+
-- a new agent gets a free login, round-robin;
-- that login stays stuck to the session;
-- `401`, `403`, and rate limits put the login in cooldown (`DEEPSEEK_ACCOUNT_COOLDOWN_MS`, default 10 minutes). A rate limit is HTTP `429`, a "too frequent" message in an HTTP `400` or JSON body (for example `Слишком частые сообщения`), or a DeepSeek stream hint with `finish_reason: rate_limit_reached`. `Retry-After` is honored when DeepSeek sends it;
-- the rate-limited request moves to another ready login on a new chat. Only when every login is cooling down does the client get `429 rate_limit`;
-- other `400` errors do not cause a cooldown. The chat is recreated on the same login;
-- two requests and two free logins go to different accounts;
-- the same `x-agent-session` overlapping waits on its login (`DEEPSEEK_ACCOUNT_LOCK_WAIT_MS`, default 120 seconds);
-- when every login is busy, the request waits on the sticky or least-recently-used login;
-- OpenCode's session-title request is answered locally and does not occupy a login;
-- `/health` shows account status without auth-file paths or file names;
-- `/dashboard` shows every login and lets you pause, resume, clear a cooldown, and reload auth files without a restart (see [Dashboard](#dashboard));
-- auth files must be mode `0600`.
+
+Which model should I pick?
-You cannot pin a client to a chosen file. The proxy picks a free login.
+There is one model with two switches:
-```bash
-DEEPSEEK_ACCOUNT_COOLDOWN_MS=600000 npm start
-```
-
----
-
-## Dashboard
-
-Open `http://127.0.0.1:9655/dashboard`. It lists every login with its state (`ready`, `busy`, `cooldown`, `disabled`, `no_credentials`), the cooldown countdown and reason, consecutive and total failures, the last upstream error, and usage. From there you can:
-
-- **Disable / Enable** a login. This is a runtime pause: in-flight work finishes, and a restart forgets it. `"enabled": false` in the auth file is the persistent switch; a login disabled in its file cannot be enabled from the dashboard.
-- **Clear cooldown** to put a cooling login back in rotation now.
-- **Reload accounts** to re-read the auth files. New files are added and deleted files are removed. A kept login keeps its cooldown and counters. A login whose token or cookie changed starts fresh.
-
-To add a login, import it and press Reload:
-
-```bash
-npm run auth:import -- --input ~/Downloads/deepseek-auth.json --output ./accounts/worker-3.json
-```
-
-The page is static and holds no data. It reads the admin API:
-
-| Method | Path | Result |
-|---|---|---|
-| `GET` | `/admin/accounts` | `{ now, pool, accounts }` |
-| `POST` | `/admin/accounts//disable` | `{ account, pool }` |
-| `POST` | `/admin/accounts//enable` | `{ account, pool }`. `409 disabled_in_file` if the file says `"enabled": false` |
-| `POST` | `/admin/accounts//clear-cooldown` | `{ account, pool }` |
-| `POST` | `/admin/accounts/reload` | `{ added, removed, kept, errors, accounts, pool }`. `422 no_accounts_found` leaves the pool unchanged |
-| `POST` | `/admin/accounts/restore` | Body `{ archived_as }` from a `DELETE`. Renames the file back and reloads: `{ restored, errors, accounts, pool }`. `404 archive_not_found`, `409 restore_target_exists` |
-
-Access rules:
-
-- With `PROXY_API_KEY` set, `/admin/*` needs the same bearer as `/v1/*`. The page asks for the key and keeps it in the tab's session storage only.
-- Without a key, `/admin/*` answers only direct loopback clients. A request that carries `X-Forwarded-For`, `Forwarded`, or `X-Real-IP` is refused with `403 admin_forbidden`, even from `127.0.0.1`. So is a non-localhost `Host`, or a browser `Origin` other than the proxy's own (another local web app cannot pause logins). `PROXY_ADMIN_ALLOW_REMOTE=1` lifts only the client address rule. The `Host` must still be loopback, an IP address, or a host listed in `PROXY_CORS_ORIGINS`, and a browser `Origin` must still be the proxy's own. Anyone who can reach the port can still pause logins, so prefer a key on a network bind.
-- Browser POSTs still pass the origin guard. To use the dashboard from a non-loopback address, add that origin to `PROXY_CORS_ORIGINS`.
-- Admin responses never contain tokens, cookies, `hif_*` values, or auth-file names.
-
-The container image ships the dashboard. With `--read-only`, actions that write auth files (add, rename, remove, restore) fail with `500 auth_file_write_failed`; pause, resume, and clear cooldown work.
-
----
-
-## Updates
-
-DeepSeek changes its Web chat from time to time, and FreeDeepseekAPI follows. Keep your copy current.
-
-Two channels, both branches on GitHub:
-
-| Channel | What it gets |
-|---|---|
-| `stable` | A release once it has been checked. The default, and what Quick start clones. |
-| `latest` | Every release as soon as it is out. |
-
-**From the dashboard:** Settings → Updates. Pick a channel, **Check for updates** shows what is new, **Install** asks you to confirm those changes, then moves your copy to it, **Restart now** loads it. The restart is automatic when the proxy runs with `npm start` or `npm run dashboard`; otherwise stop it and start it again. Nothing is installed until that confirmation.
-
-The dashboard only moves your copy forward. It stops and shows the command to run by hand when the folder has uncommitted changes to tracked files or your channel branch has commits of its own. A container image or a downloaded archive has no git history: pull a new image or download the new release.
-
-**By hand:**
-
-```bash
-git fetch origin && git switch stable && git merge --ff-only origin/stable
-```
-
-Then restart the proxy.
-
----
-
-## Sign-in
-
-| Command | What it does |
+| Model | What it does |
|---|---|
-| `npm run auth` | Menu: Chrome sign-in, import, status, delete the local file |
-| `npm run deepseek:auth` | Chrome capture of token and cookies |
-| `npm run auth:import` | Import `deepseek-auth.json` or a browser cookie export |
-| `npm run doctor` | Check the files. Drop `--offline` to also hit PoW |
-
-Chrome extension: load `chrome-extension/` on an open chat.deepseek.com tab. Collect until **Token** is Ready, then save the file. Do not paste that JSON into a chat.
-
-Fields: `token`, `cookie`, `wasmUrl` (an `https://*.deepseek.com` address). Optional: `hif_dliq`, `hif_leim`, `name`, and `enabled` (`false` pauses that login). See [`auth.example.json`](auth.example.json).
-
-The password of the DeepSeek account is not an input. There is no `auth:console` command, and none should store a password on disk.
-
----
-
-## Coding agents
-
-```bash
-npm run setup:agents
-npm run setup:agents -- --all --model deepseek-v4-flash
-npm run setup:agents -- --target claude-code --model deepseek-v4-flash-thinking
-npm run setup:agents -- --target codex --model deepseek-v4-flash
-```
-
-The proxy must already be listening. The default origin is `http://127.0.0.1:9655`. Override it with `--base-url`. If `PROXY_API_KEY` is set, it is copied into the agent config.
-
-Setup adds FreeDeepseekAPI as an opt-in profile. It does not replace Claude, GPT, or whatever you already use.
-
-| Agent | What is written | How you select it |
-|---|---|---|
-| Claude Code | `~/.claude/freedeepseek.settings.json` | `claude --settings ~/.claude/freedeepseek.settings.json` |
-| Codex | `~/.codex/freedeepseek.config.toml` and a model catalog | `codex --profile freedeepseek` |
-| OpenCode | a `freedeepseek` provider, plus autonomy rules in `AGENTS.md` | pick `freedeepseek/` |
-| Hermes | `~/.hermes/freedeepseek.yaml` | that profile file |
-| OpenClaw | a `freedeepseek` provider | pick it explicitly |
-| Cursor | a snippet and launcher under `integrations/cursor/` | editor settings stay as they are |
-
-`--model` is always DeepSeek-V4.1-Flash, with native chat.deepseek.com search on. `-thinking` turns DeepThink on. `-nosearch` turns search off; the agent then keeps its own web tools. An old `-search` id maps to the same id without the suffix.
-
-Codex setup does **not** set `forced_login_method = api`. On Codex CLI that line logs you out of ChatGPT. Normal `codex` stays on ChatGPT. The FreeDeepseek profile talks to this proxy.
-
-Images:
-
-- Claude Code: paste or attach. The Anthropic `image` block is uploaded to DeepSeek Web.
-- Codex: `codex -i screenshot.png`. Repeat `-i` for more files. `/v1/responses` accepts `input_image`.
-- OpenCode: paste or drop an image. The generated config keeps attachments.
-- Other OpenAI clients: send `image_url` as a base64 data URL or a public HTTPS URL.
-
-Restore a previous setup from its backup:
-
-```bash
-node scripts/setup-agents.js --restore ~/.freedeepseek-api/backups/
-```
-
-Two agents at once need two Web logins in `accounts/`. Details: [docs/agents.md](docs/agents.md).
-
----
-
-## Check that it works
-
-```bash
-curl http://127.0.0.1:9655/health
-curl http://127.0.0.1:9655/readyz
-curl http://127.0.0.1:9655/v1/models
-curl http://127.0.0.1:9655/v1/model-capabilities
-```
-
-`/health` is liveness. `/readyz` is `200` only when at least one login can serve. `/v1/models` lists the four DeepSeek-V4.1-Flash ids.
-
----
-
-## Request examples
-
-### Chat Completions
-
-```bash
-curl -X POST http://127.0.0.1:9655/v1/chat/completions \
- -H "Content-Type: application/json" \
- -H "x-agent-session: my-agent" \
- -d '{
- "model": "deepseek-v4-flash",
- "messages": [{"role": "user", "content": "Answer in one sentence."}],
- "stream": false
- }'
-```
-
-### DeepThink
-
-`-thinking` is the DeepThink switch from the chat composer. The model is still DeepSeek-V4.1-Flash. It reasons before the answer.
-
-```bash
-curl -X POST http://127.0.0.1:9655/v1/chat/completions \
- -H "Content-Type: application/json" \
- -d '{
- "model": "deepseek-v4-flash-thinking",
- "messages": [{"role": "user", "content": "Why is the sky blue? Keep it short."}],
- "stream": false
- }'
-```
-
-Where the reasoning shows up:
-
-- non-stream: `choices[0].message.reasoning_content`
-- stream: `choices[0].delta.reasoning_content`
-- usage: `usage.completion_tokens_details.reasoning_tokens`
-
-`reasoning_tokens` is an estimate from the extracted DeepThink text. The Web stream does not report official reasoning-token usage.
+| `deepseek-v4-flash` | Answers with web search |
+| `deepseek-v4-flash-thinking` | Thinks first, then answers |
-A tool-call turn does not attach reasoning to the message. Some agents treat any text next to a tool call as the final answer and stop.
+Add `-nosearch` to either one to turn web search off.
-### Native web search
+
-The native Web Search of chat.deepseek.com is on by default, for every model id. Internet questions go through that search. Do not ask the model to use bash, curl, or a harness `websearch` / `webfetch` tool for the live web.
+
+Can I use several accounts?
-```bash
-curl -X POST http://127.0.0.1:9655/v1/chat/completions \
- -H "Content-Type: application/json" \
- -d '{
- "model": "deepseek-v4-flash",
- "messages": [{"role": "user", "content": "Find a current fact about DeepSeek and answer briefly."}],
- "stream": false
- }'
-```
-
-To answer without search, send `"web_search": false`, or use an id ending in `-nosearch`:
-
-```bash
-curl -X POST http://127.0.0.1:9655/v1/chat/completions \
- -H "Content-Type: application/json" \
- -d '{
- "model": "deepseek-v4-flash-thinking",
- "web_search": false,
- "messages": [{"role": "user", "content": "Explain how a B-tree splits a node."}],
- "stream": false
- }'
-```
-
-`web_search` must be `true` or `false`; any other value returns `400 invalid_request_error`. It overrides the id: `"web_search": true` on a `-nosearch` id turns search back on. The field works on `/v1/chat/completions`, `/v1/messages`, and `/v1/responses`.
-
-With search off, a coding agent keeps its own `websearch` / `webfetch` tools and is not told that native search is on.
-
-### Streaming
-
-```bash
-curl -N -X POST http://127.0.0.1:9655/v1/chat/completions \
- -H "Content-Type: application/json" \
- -d '{
- "model": "deepseek-v4-flash",
- "messages": [{"role": "user", "content": "Tell a short joke."}],
- "stream": true
- }'
-```
-
-The last SSE chunk carries `usage`, then `data: [DONE]`.
-
-### Anthropic Messages
-
-```bash
-curl -X POST http://127.0.0.1:9655/v1/messages \
- -H "Content-Type: application/json" \
- -d '{
- "model": "deepseek-v4-flash",
- "max_tokens": 512,
- "messages": [{"role": "user", "content": "Reply with exactly OK"}],
- "stream": false
- }'
-```
-
-Claude Code, after `npm run setup:agents -- --target claude-code`:
-
-```bash
-claude --settings ~/.claude/freedeepseek.settings.json
-```
-
-Names such as `claude-sonnet-*` and `claude-opus-*` are mapped onto DeepSeek-V4.1-Flash and DeepSeek-V4.1-Flash with DeepThink, so a leftover Claude id still runs.
-
-### OpenAI Responses
-
-```bash
-curl -X POST http://127.0.0.1:9655/v1/responses \
- -H "Content-Type: application/json" \
- -d '{
- "model": "deepseek-v4-flash",
- "input": "Reply with exactly OK",
- "stream": false
- }'
-```
-
-Codex uses this route. After setup:
-
-```bash
-codex --profile freedeepseek
-```
-
-### Tool calling
-
-The proxy accepts OpenAI `tools`, Anthropic `tools`, and Responses function tools.
-
-DeepSeek Web has no native tool-call array. The proxy writes the tool list into the prompt and parses the reply back into OpenAI `tool_calls`. Accepted shapes:
-
-- `{"tool_call":{"name":"...","arguments":{...}}}`
-- `{"tool_calls":[{"name":"...","arguments":{...}}]}` — several independent calls, up to 8
-- `TOOL_CALL:` plus a JSON object
-- a fenced JSON envelope with `tool_call`, `tool_calls`, or `function_call`
-- `...`
-- DeepSeek DSML, including the doubled-bar Web variant
-
-`execute_code` and `web_search` are DeepSeek's own tools. They are not run on your computer. If they appear next to a real local tool such as `read_file`, they are dropped and the local calls are kept. A half-written tool block is not executed. One repair retry asks for strict JSON. If that is still broken, the turn returns `502 malformed_tool_call` and the chat stays open.
-
-While native search is on, harness `websearch`, `webfetch`, and `WebFetch` tools are stripped and the live web is the native chat.deepseek.com search. With search off they reach the agent unchanged.
+Yes. Add them in the dashboard under Settings → Accounts. Running two agents at once needs two logins.
-### Images
+
-PNG, JPEG, WebP, and GIF. Up to 10 images, 20 MiB decoded each. The JSON body defaults to 30 MiB.
+
+It stopped working. What do I do?
-The proxy uploads the image to DeepSeek Web, waits until parsing finishes, then sends the file id. A provider `file_id` is rejected. A URL must be public HTTPS. Redirects into local, private, or link-local addresses are rejected.
+Try these in order:
+1. Update: Settings → Updates in the dashboard.
+2. Log in again: `npm run auth`.
+3. Check your setup: `npm run doctor`.
-OpenAI Chat Completions uses `image_url`. Responses uses `input_image`. Anthropic uses an `image` block with base64. See [docs/api.md](docs/api.md).
+If that doesn't help, DeepSeek has probably changed something. [Open an issue](https://github.com/dekrezz/FreeDeepseekAPI/issues).
----
-
-## Models
-
-`GET /v1/models` lists only DeepSeek-V4.1-Flash.
-
-| ID | DeepThink | Native web search | What it does |
-|---|---|---|---|
-| `deepseek-v4-flash` | off | on | DeepSeek-V4.1-Flash. `deepseek-flash` is the same id |
-| `deepseek-v4-flash-thinking` | on | on | DeepThink, then the answer |
-| `deepseek-v4-flash-nosearch` | off | off | No native search |
-| `deepseek-v4-flash-thinking-nosearch` | on | off | DeepThink without native search |
-
-These suffixes are the two switches in the DeepSeek chat composer. They do not select another model. `"web_search": true|false` in the request body overrides the search switch of any id.
-
-The old `deepseek-v4-flash-search` and `deepseek-v4-flash-thinking-search` ids still work. They mean `deepseek-v4-flash` and `deepseek-v4-flash-thinking` and are no longer listed in `/v1/models`.
-
-Older ids are not registered and return `400 invalid_model`:
-
-`deepseek-chat`, `deepseek-reasoner`, `deepseek-r1`, `deepseek-v3`, `deepseek-instant`, `deepseek-expert`, `deepseek-v4-pro`, `deepseek-chat-search`, and vision.
-
-```bash
-curl http://127.0.0.1:9655/v1/model-capabilities
-```
-
-Full table: [docs/models.md](docs/models.md).
-
----
-
-## Endpoints
-
-| Method | Path | Purpose |
-|---|---|---|
-| `GET` | `/health` | Process is up. Account status if no proxy key, or the bearer matches |
-| `GET` | `/readyz` | `200` only if a login can serve now |
-| `GET` | `/dashboard` | Account dashboard (static page) |
-| `GET` | `/admin/accounts` | Pool and per-login status. See [Dashboard](#dashboard) |
-| `POST` | `/admin/accounts//{disable,enable,clear-cooldown}` | Pause, resume, or un-cool one login |
-| `POST` | `/admin/accounts/reload` | Re-read auth files without a restart |
-| `GET` | `/v1/models` | The four DeepSeek-V4.1-Flash ids |
-| `GET` | `/v1/model-capabilities` | Ids, DeepThink, and native search |
-| `POST` | `/v1/chat/completions` | OpenAI Chat Completions |
-| `POST` | `/v1/messages` | Anthropic Messages |
-| `POST` | `/v1/responses` | OpenAI Responses |
-| `GET` | `/v1/sessions` | Local agent sessions |
-| `POST` | `/reset-session?agent=` | Drop one Web chat |
-| `POST` | `/reset-session?agent=all` | Drop every Web chat |
-
----
-
-## Environment
-
-| Variable | Default | Meaning |
-|---|---|---|
-| `HOST` | `127.0.0.1` | Bind address. A non-loopback bind without a proxy key prints a warning |
-| `PORT` | `9655` | Listen port |
-| `TLS_CERT_FILE` / `TLS_KEY_FILE` | off | PEM certificate and private key. When both are set and readable, the proxy serves HTTPS. Unset keeps HTTP. Loopback does not need TLS. A non-loopback bind without them warns that the login import and the Authorization header are clear text |
-| `PROXY_API_KEY` | off | Bearer required on `/v1/*` and `/admin/*` when set |
-| `REQUIRE_PROXY_API_KEY` | off | Refuse to start if the key is missing. The container sets this |
-| `PROXY_CORS_ORIGINS` | loopback | Extra exact browser origins |
-| `PROXY_ADMIN_ALLOW_REMOTE` | off | If `1`, `/admin/*` answers non-loopback clients even without `PROXY_API_KEY` |
-| `DEEPSEEK_AUTH_PATH` | `./deepseek-auth.json` | One file, or a comma-separated list |
-| `DEEPSEEK_AUTH_DIR` | `./accounts` when that directory exists | Every `*.json` in it |
-| `DEEPSEEK_MAX_PROMPT_CHARS` | `80000` | Cap on what is sent upstream. Minimum 16000 |
-| `DEEPSEEK_MAX_RETRIES` | `2` | Empty-reply retries on the same chat |
-| `DEEPSEEK_REQUEST_DEADLINE_MS` | `120000` | Per-request deadline |
-| `DEEPSEEK_MAX_CONCURRENT` | `24` | Process-wide cap. Real parallelism is the number of idle logins |
-| `DEEPSEEK_ACCOUNT_LOCK_WAIT_MS` | `120000` | How long a second chat waits for a busy login |
-| `DEEPSEEK_ACCOUNT_COOLDOWN_MS` | `600000` | Cooldown after 401, 403, or a rate limit without `Retry-After` |
-| `TRUST_PROXY` | off | If `1`, the client IP is taken from `X-Forwarded-For` |
-| `MAX_REQUEST_BODY_BYTES` | `31457280` | Maximum JSON body, including base64 images |
-| `NON_INTERACTIVE` / `SKIP_ACCOUNT_MENU` | off | Skip the launch menu |
-
----
-
-## Errors
-
-| Status | `error.type` | What to do |
-|---|---|---|
-| 400 | `invalid_model` | Use an id from `GET /v1/models` |
-| 400 | `context_length_exceeded` | The prompt was still too long after compaction |
-| 401 | `authentication_error` | The proxy key does not match |
-| 403 | `admin_forbidden` | `/admin/*` without a key from a non-loopback or proxied client. See [Dashboard](#dashboard) |
-| 429 | `concurrent_chat_blocked` | The wait for a busy login ran out. Add another login or retry |
-| 429 | `rate_limit` | Every login is in cooldown (rate-limited or auth failure). Honor `Retry-After` |
-| 429 | `rate_limit_error` | DeepSeek rate-limited the login and the request ran out of time or the client left before a failover finished. Honor `Retry-After` |
-| 502 | `malformed_tool_call` | Tool markup was still broken after one repair. The chat was kept |
-| 502 | `empty_response` | DeepSeek returned nothing after the retries |
-| 503 | `overloaded` / `no_auth` | Too many in-flight requests, or no auth file |
-| 504 | `request_timeout` | The deadline in `DEEPSEEK_REQUEST_DEADLINE_MS` was hit |
-
----
-
-## Open WebUI
-
-Base URL when Open WebUI runs in Docker on the same machine:
-
-```text
-http://host.docker.internal:9655/v1
-```
-
-Local, no Docker:
-
-```text
-http://127.0.0.1:9655/v1
-```
-
-If `PROXY_API_KEY` is unset, the API key field can be anything. If the key is set, the client must send that exact bearer. The proxy checks it before models, sessions, and completions.
-
-Pick `deepseek-v4-flash` for a normal answer with native chat.deepseek.com search, `deepseek-v4-flash-thinking` for DeepThink, and a `-nosearch` id when you want an answer without search.
-
----
-
-## Refresh the login
-
-```bash
-npm run auth
-npm start
-```
-
-If DeepSeek answers `401` or `403`, or the PoW challenge fails, sign in again and replace `deepseek-auth.json`.
-
-These paths stay out of git:
-
-- `deepseek-auth.json`
-- `accounts/*.json`
-- Chrome profile directories used by the auth script
-- `.env`
-
----
-
-## Tests
-
-Syntax and unit tests, no network:
-
-```bash
-npm test
-```
-
-Live smoke tests against a proxy that is already running:
-
-```bash
-BASE_URL=http://127.0.0.1:9655 MODEL=deepseek-v4-flash npm run test:live
-```
+
-`npm test` runs `node --check` on the entry points and `node --test` on `tests/unit.test.js` and `tests/account-failover.test.js`. It does not call DeepSeek: the failover tests serve every upstream call from an in-process mock.
+
+How do I update?
----
+Open Settings → Updates in the dashboard and press **Check for updates**. `stable` gets a release once it has been checked. `latest` gets every release first.
-## Project status
+
-FreeDeepseekAPI is a local Web-chat proxy. It depends on the current chat.deepseek.com contract. When that contract changes, auth or the request body may need an update.
+
+Can other devices use it?
-If a call stops working:
+By default only your computer can reach it. To share it, set `PROXY_API_KEY` and read [Running it safely](SECURITY.md#running-it-safely) first.
-1. Update to the newest version ([Updates](#updates)).
-2. Refresh the login with `npm run auth`.
-3. Run `npm run doctor`.
-4. Read `GET /v1/model-capabilities` and use a DeepSeek-V4.1-Flash id.
-5. If the same chat keeps failing, `POST /reset-session?agent=` and try once more.
-6. If it still fails, DeepSeek has likely changed the private Web API.
+
-Security reports go to a private GitHub advisory, not a public issue. See [SECURITY.md](SECURITY.md). The maintainer list is [CONTRIBUTORS.md](CONTRIBUTORS.md).
+
+Does it work on Windows, a server or in a container?
-## Documentation
+Yes: [Windows](docs/guide.md#windows), [VPS](docs/guide.md#vps--headless), [Podman](docs/guide.md#rootless-podman).
-- [Authentication](docs/auth.md)
-- [Agent setup](docs/agents.md)
-- [Models](docs/models.md)
-- [HTTP API](docs/api.md)
+
-## Stars
+## More
-
-
-
+- [Full guide](docs/guide.md): everything in detail, with request examples
+- [HTTP API](docs/api.md): endpoints, errors and settings
+- [Models](docs/models.md) · [Accounts and login](docs/auth.md) · [Coding agents](docs/agents.md)
+- [Security](SECURITY.md): how to report a vulnerability
## License
diff --git a/README.ru.md b/README.ru.md
index 1e5703c..78a2f23 100644
--- a/README.ru.md
+++ b/README.ru.md
@@ -5,7 +5,7 @@
FreeDeepseekAPI
- Локальный OpenAI-compatible API proxy для DeepSeek Web Chat
+ Ваш бесплатный аккаунт DeepSeek как API
+FreeDeepseekAPI работает на вашем компьютере и превращает бесплатный аккаунт [chat.deepseek.com](https://chat.deepseek.com) в локальный API. Через него с DeepSeek может говорить любое приложение, которое умеет работать с OpenAI или Anthropic: Open WebUI, Claude Code, Codex, Cursor и другие. Платный ключ не нужен.
-## С чего начать
+## Как начать
-**Что это.** У вас есть бесплатный аккаунт DeepSeek на [chat.deepseek.com](https://chat.deepseek.com). FreeDeepseekAPI работает на вашем компьютере и превращает этот аккаунт в API по адресу `http://127.0.0.1:9655` — такой же адрес выдают платные AI-сервисы. Любая программа, которая умеет работать с OpenAI или Anthropic, сможет через него пользоваться DeepSeek: Open WebUI, Cursor, Claude Code, Codex, ваши скрипты. Платный API-ключ не нужен: ваш аккаунт, на вашем компьютере.
-
-**Понадобится:** [Node.js](https://nodejs.org) 18 или новее, Git, Google Chrome и бесплатный аккаунт DeepSeek.
-
-### 1. Запуск за минуту
+Нужны [Node.js](https://nodejs.org) 18 или новее, Git, Google Chrome и аккаунт DeepSeek.
```bash
git clone --branch stable https://github.com/dekrezz/FreeDeepseekAPI.git
@@ -52,884 +34,121 @@ npm run auth
npm run dashboard
```
-- `npm run auth`: выберите **Войти через Chrome**, войдите на chat.deepseek.com в открывшемся окне, отправьте короткое сообщение, например `ok`, и вернитесь в терминал. Вход сохранится в `deepseek-auth.json`.
-- `npm run dashboard`: запускает прокси и открывает `http://127.0.0.1:9655/dashboard`. Там можно сразу общаться с DeepSeek.
+1. `npm run auth` откроет Chrome. Выберите **Sign in with Chrome**, войдите в DeepSeek, отправьте короткое сообщение, например `ok`, и вернитесь в терминал.
+2. `npm run dashboard` запустит прокси и откроет дашборд. Писать в чат можно прямо там.
+
+## Как подключить приложение
-### 2. Подключите свою программу
+Впишите в настройках приложения:
| Настройка | Значение |
|---|---|
| Base URL | `http://127.0.0.1:9655/v1` |
-| API key | любой текст (если прокси запущен с `PROXY_API_KEY`, укажите этот ключ) |
-| Модель | `deepseek-v4-flash` отвечает с поиском в интернете, `deepseek-v4-flash-thinking` сначала думает; добавьте `-nosearch`, чтобы выключить поиск |
+| API key | любой текст |
+| Модель | `deepseek-v4-flash` |
-Open WebUI в Docker: укажите `http://host.docker.internal:9655/v1`.
+Для Open WebUI в Docker адрес другой: `http://host.docker.internal:9655/v1`.
-### 3. Агенты для кода одной командой
+## Как настроить агентов
-Пока прокси запущен:
+Не останавливайте прокси и выполните:
```bash
npm run setup:agents
```
-Команда настроит Claude Code, Codex, OpenCode, Hermes, OpenClaw и Cursor как дополнительный профиль; то, чем вы пользуетесь сейчас, останется как есть. То же можно сделать в дашборде: Settings → Agents. Потом запускайте, например, `claude --settings ~/.claude/freedeepseek.settings.json` или `codex --profile freedeepseek`.
-
-Что-то не так? `npm run doctor` проверит настройку, а `curl http://127.0.0.1:9655/health` покажет, работает ли прокси. Всё остальное — ниже.
-
----
-
-FreeDeepseekAPI поднимает локальный API-сервер перед **DeepSeek Web Chat** ([chat.deepseek.com](https://chat.deepseek.com)). К нему подключаются Open WebUI, LiteLLM, Hermes, Claude Code, Codex, OpenCode, OpenClaw, Cursor и любой OpenAI-compatible клиент.
-
-Проект работает через ваш обычный залогиненный аккаунт DeepSeek. Локальный сервер принимает API-запросы и продолжает сохранённую Web-сессию. Платный ключ `api.deepseek.com` не нужен.
-
-На сайте сейчас одна модель: **DeepSeek-V4.1-Flash**. Родной Web Search, встроенный в chat.deepseek.com, **включён по умолчанию**, и именно им отвечают на вопросы про живой интернет. `-thinking` включает DeepThink. `-nosearch` или `"web_search": false` выключает поиск.
-
-> Это экспериментальный web-chat proxy. DeepSeek может в любой момент поменять внутренний Web API. Когда это происходит, проект обновляется вслед за ним, и эта документация тоже может меняться. Поэтому советуем всегда держать свою копию на последней версии: Settings → Updates в дашборде или раздел [Обновления](#обновления).
-
----
-
-## Навигация
-
-- [С чего начать](#с-чего-начать)
-- [Что это даёт](#что-это-даёт)
-- [Возможности](#возможности)
-- [Быстрый старт](#быстрый-старт)
-- [Windows](#windows)
-- [Linux / Chromium](#linux--chromium)
-- [VPS / headless](#vps--headless)
-- [Rootless Podman](#rootless-podman)
-- [Diagnostics / doctor](#diagnostics--doctor)
-- [Session reuse](#session-reuse)
-- [Пул аккаунтов](#пул-аккаунтов)
-- [Панель аккаунтов](#панель-аккаунтов)
-- [Обновления](#обновления)
-- [Вход](#вход)
-- [Агенты](#агенты)
-- [Проверка работы](#проверка-работы)
-- [Примеры запросов](#примеры-запросов)
- - [Chat Completions](#chat-completions)
- - [DeepThink](#deepthink)
- - [Родной веб-поиск](#родной-веб-поиск)
- - [Streaming](#streaming)
- - [Anthropic Messages](#anthropic-messages)
- - [OpenAI Responses](#openai-responses)
- - [Tool calling](#tool-calling)
- - [Картинки](#картинки)
-- [Модели](#модели)
-- [Endpoints](#endpoints)
-- [Переменные окружения](#переменные-окружения)
-- [Ошибки](#ошибки)
-- [Open WebUI](#open-webui)
-- [Обновить логин](#обновить-логин)
-- [Тесты](#тесты)
-- [Статус проекта](#статус-проекта)
-
----
-
-## Что это даёт
-
-- Использовать DeepSeek Web как локальный API endpoint.
-- Подключать DeepSeek к Open WebUI и другим OpenAI-compatible клиентам.
-- Получать обычный JSON или streaming SSE.
-- Включать DeepThink суффиксом `-thinking` и читать `reasoning_content`.
-- Говорить с Claude Code через Anthropic Messages.
-- Говорить с Codex через OpenAI Responses.
-- Держать отдельный Web-чат на каждого агента или `user`.
-- Отдавать несколько локальных инструментов за один ответ, до восьми.
-- Искать в интернете родным поиском DeepSeek, а не через bash и не через websearch харнесса.
-
-## Возможности
-
-- **OpenAI-compatible API:** `POST /v1/chat/completions`
-- **Anthropic-compatible shim:** `POST /v1/messages`
-- **OpenAI Responses shim:** `POST /v1/responses`
-- **Streaming:** SSE и обычный JSON без стрима
-- **DeepThink:** `reasoning_content`, когда включён `-thinking`
-- **Родной поиск:** Web Search chat.deepseek.com, включён по умолчанию. Выключается через `-nosearch` или `"web_search": false`
-- **Tool calling:** инструменты OpenAI, Anthropic и Responses, пачкой
-- **Возможности моделей:** `GET /v1/model-capabilities`
-- **Сессии агентов:** один чат DeepSeek на `x-agent-session` или `user`
-- **Восстановление сессии:** пустой ответ, сломанный tool call и таймаут оставляют тот же чат
-- **Без зависимостей:** Node.js 18+, ни одного npm-пакета
-- **Лицензия:** Apache-2.0
-
----
-
-## Быстрый старт
+Команда добавит DeepSeek в Claude Code, Codex, OpenCode, Hermes, OpenClaw и Cursor как дополнительный вариант. Ваши текущие настройки останутся, а шаг можно пропустить прямо в мастере. То же самое есть в дашборде: Settings → Agents.
-```bash
-git clone --branch stable https://github.com/dekrezz/FreeDeepseekAPI.git
-cd FreeDeepseekAPI
-npm run auth
-npm start
-```
+## Частые вопросы
-`npm run auth` открывает меню входа. Выберите вход через Chrome, залогиньтесь на chat.deepseek.com в открывшемся профиле, отправьте короткое сообщение вроде `ok` и вернитесь в терминал. Файл сохранится как `deepseek-auth.json` с правами `0600`.
+
+Это правда бесплатно?
-`npm start` открывает меню запуска:
+Да. Используется тот же бесплатный аккаунт, что и на сайте DeepSeek.
-- запустить proxy
-- запустить proxy и открыть дашборд (или `npm run dashboard`)
-- войти через Chrome
-- импортировать auth-файл или экспорт cookies
-- показать id моделей DeepSeek-V4.1-Flash
-- выйти
+
-Без меню, для headless и CI:
-
-```bash
-NON_INTERACTIVE=1 npm start
-# или
-SKIP_ACCOUNT_MENU=1 npm start
-```
-
-Сервер слушает:
-
-```text
-http://127.0.0.1:9655
-```
+
+Это официальный проект DeepSeek?
-По умолчанию он доступен только с этого компьютера. Чтобы открыть его в сеть, задайте адрес и отдельный ключ proxy:
+Нет. Он работает с закрытым веб-чатом DeepSeek, а тот может измениться в любой момент. Когда это случается, проект обновляется вслед за ним.
-```bash
-HOST=0.0.0.0 PROXY_API_KEY='replace-with-a-long-random-value' npm start
-```
-
-Ключ передаётся как `Authorization: Bearer `. Без `PROXY_API_KEY` у API нет своей авторизации. Такой экземпляр в сеть не выставляйте.
-
-Запросы из браузера разрешены с loopback-origin. Если UI открыт на другом адресе, перечислите точные origin через запятую:
-
-```bash
-PROXY_CORS_ORIGINS='https://ui.example.com,http://192.168.1.20:3000'
-```
-
----
-
-## Windows
-
-```powershell
-git clone --branch stable https://github.com/dekrezz/FreeDeepseekAPI.git
-cd FreeDeepseekAPI
-npm run auth
-npm start
-```
-
-Если Chrome стоит не в обычном месте:
-
-```powershell
-$env:CHROME_PATH="C:\Program Files\Google\Chrome\Application\chrome.exe"
-npm run auth
-```
-
-Если Chrome не найден, `npm run auth` печатает, куда его ставить на Windows, macOS и Linux, а не сырой stack trace.
-
----
-
-## Linux / Chromium
-
-```bash
-git clone --branch stable https://github.com/dekrezz/FreeDeepseekAPI.git
-cd FreeDeepseekAPI
-CHROME_PATH=$(which chromium) npm run auth
-npm start
-```
-
-Если бинарник называется иначе:
-
-```bash
-CHROME_PATH=$(which chromium-browser) npm run auth
-# или
-CHROME_PATH=$(which google-chrome) npm run auth
-```
-
----
-
-## VPS / headless
-
-Надёжный путь не запускает Chrome на сервере.
-
-1. На машине, где есть GUI и Chrome:
-
-```bash
-npm run auth
-```
-
-2. Скопируйте `deepseek-auth.json` на VPS:
-
-```bash
-scp deepseek-auth.json user@your-vps:/opt/FreeDeepseekAPI/deepseek-auth.json
-```
-
-3. Импортируйте файл и проверьте его:
-
-```bash
-cd /opt/FreeDeepseekAPI
-npm run auth:import -- --input ./deepseek-auth.json
-npm run doctor -- --offline
-```
-
-4. Запустите proxy без меню:
-
-```bash
-NON_INTERACTIVE=1 npm start
-```
-
-Подойдёт и экспорт cookies браузера, если вместе с ним есть token:
-
-```bash
-DEEPSEEK_TOKEN="" npm run auth:import -- --input ./cookies.json
-```
+
-`deepseek-auth.json` — это доступ к вашему логину DeepSeek Web. Не коммитьте его, не вставляйте в чат и храните с правами `0600`.
+
+Могут ли забанить аккаунт?
-Команды входа по паролю нет. Прокси не спрашивает пароль DeepSeek и не пишет его на диск. Вход — это Chrome, готовый auth-файл или экспорт cookies плюс token.
+Могут. DeepSeek способен заблокировать логин на несколько дней, если два чата отправляют с него сообщения одновременно. Поэтому прокси держит один чат на логин, а следующий ждёт очереди. Риск от этого ниже, но полностью он не исчезает: правила задаёт DeepSeek.
----
+
-## Rootless Podman
+
+Куда уходят мой логин и сообщения?
-Контейнер только запускает proxy. Вход делайте на хосте командой `npm run auth`. Скрипты авторизации и `deepseek-auth.json` в образ не копируются.
-
-Запускайте Podman своим пользователем, без root.
-
-1. Соберите образ:
-
-```bash
-podman build --tag localhost/free-deepseek-api:local --file Containerfile .
-```
-
-2. Положите auth-файл DeepSeek и отдельный ключ proxy в secrets:
-
-```bash
-podman secret create --replace free-deepseek-auth ./deepseek-auth.json
-
-printf 'Proxy API key: '
-IFS= read -r -s PROXY_API_KEY
-printf '\n'
-printf '%s' "$PROXY_API_KEY" |
- podman secret create --replace free-deepseek-proxy-key -
-```
-
-Ключ должен быть длинным и случайным. Значение останется в этом shell, чтобы вы могли вызвать API. В образ и в командную строку Podman оно не попадает.
-
-3. Запустите контейнер с урезанными привилегиями:
-
-```bash
-podman run --detach \
- --name free-deepseek-api \
- --publish 127.0.0.1:9655:9655 \
- --secret free-deepseek-auth,type=mount,target=/run/secrets/deepseek-auth.json,mode=0400 \
- --secret free-deepseek-proxy-key,type=mount,target=/run/secrets/proxy-api-key,mode=0400 \
- --read-only \
- --cap-drop=ALL \
- --security-opt=no-new-privileges \
- localhost/free-deepseek-api:local
-```
-
-В образе уже стоят `NON_INTERACTIVE=1`, `HOST=0.0.0.0` и `REQUIRE_PROXY_API_KEY=1`. Без secret с ключом контейнер не начнёт обслуживать запросы. На хосте порт публикуется только на `127.0.0.1`. Не убирайте этот адрес, если перед ним нет firewall.
-
-4. Проверьте, что процесс жив, что логин готов и что список моделей закрыт ключом:
-
-```bash
-podman healthcheck run free-deepseek-api
-curl --fail http://127.0.0.1:9655/readyz
-curl --fail \
- -H "Authorization: Bearer $PROXY_API_KEY" \
- http://127.0.0.1:9655/v1/models
-```
-
-Встроенный healthcheck бьёт в локальный `/health` и говорит только то, что процесс поднят. `/readyz` вернёт `503`, если ни один логин DeepSeek сейчас не может взять чат.
-
-```bash
-podman logs free-deepseek-api
-podman inspect --format '{{.State.Health.Status}}' free-deepseek-api
-```
-
-Остановите контейнер и удалите secrets:
-
-```bash
-podman stop free-deepseek-api
-podman rm free-deepseek-api
-podman secret rm free-deepseek-auth free-deepseek-proxy-key
-unset PROXY_API_KEY
-```
-
-Когда меняете логин или ключ proxy, замените secret и пересоздайте контейнер.
-
----
-
-## Diagnostics / doctor
-
-```bash
-npm run doctor
-# без запроса в сеть к DeepSeek:
-npm run doctor -- --offline
-```
-
-`doctor` проверяет:
-
-- есть ли `deepseek-auth.json` или `DEEPSEEK_AUTH_DIR`;
-- парсится ли JSON;
-- заданы ли `token`, `cookie` и `wasmUrl`;
-- стоят ли права `0600` на macOS и Linux;
-- при обычном запуске — отвечает ли endpoint PoW у DeepSeek.
-
-Если видите `data.biz_data is null`, `fetch failed`, `401`, `403`, `429` или агент не видит модели, сначала запустите `npm run doctor`.
-
----
-
-## Session reuse
-
-FreeDeepseekAPI не открывает новый чат DeepSeek на каждый HTTP-запрос.
-
-- Одно значение `x-agent-session`, `session` или `user` — один чат DeepSeek.
-- Если чат уже есть, прокси продолжает его через `parent_message_id`.
-- Постоянный system prompt и список инструментов уходят наверх **один раз**. Дальше OpenCode, Claude Code и Codex шлют только новый ход пользователя или результат инструмента.
-- Изменившийся system prompt отправляется снова.
-- Пустой ответ, сломанный tool call и таймаут **оставляют** живой чат. Раньше из-за этого открывался новый чат и заново уезжал весь промпт. Теперь нет.
-- Новый чат начинается, если сессии нет, цепочка дошла до 100 сообщений, чату больше 2 часов, DeepSeek сказал, что промпт слишком длинный, или вы вызвали `/reset-session`.
-- Длинный промпт перед отправкой режется до `DEEPSEEK_MAX_PROMPT_CHARS` (по умолчанию 80 000 символов). Начало задачи, свежие результаты инструментов и напоминание про инструменты сохраняются.
-- Если клиент уже прислал многоходовую историю, прокси не подклеивает свою recovery-историю второй раз.
-- Пустой ответ повторяется до `DEEPSEEK_MAX_RETRIES` раз (по умолчанию 2). Каждый retry берёт меньший кусок контекста и, если чат жив, остаётся в нём.
-
-Явно задать агента:
-
-```bash
-curl -X POST http://127.0.0.1:9655/v1/chat/completions \
- -H "Content-Type: application/json" \
- -H "x-agent-session: my-agent" \
- -d '{"model":"deepseek-v4-flash","messages":[{"role":"user","content":"Привет"}]}'
-```
-
-Активные сессии:
-
-```bash
-curl http://127.0.0.1:9655/v1/sessions
-```
-
-Сбросить одну:
-
-```bash
-curl -X POST "http://127.0.0.1:9655/reset-session?agent=my-agent"
-```
-
-Сбросить все:
-
-```bash
-curl -X POST "http://127.0.0.1:9655/reset-session?agent=all"
-```
-
-Сброс сохраняет копию переписки на стороне прокси и подставляет её в следующий чат, если клиент присылает только одно сообщение. Добавьте `&history=drop`, если клиент сам пришлёт полную историю, например после правки одного из прошлых сообщений: тогда заменённые реплики не вернутся.
-
-Чаты на сайте DeepSeek всё равно будут видны. Прокси ходит во Web Chat API, а сами чаты хранит DeepSeek. Session reuse только не плодит новый чат, пока текущая цепочка ещё годится.
-
-Сообщение, текст которого ровно `/new`, сбрасывает удалённый чат этого агента и не уходит в модель.
-
----
-
-## Пул аккаунтов
-
-DeepSeek может забанить логин на несколько дней, если два чата отправят запрос с одного и того же логина одновременно. Правило пула: один чат в полёте на логин. Второй запрос на занятый логин ждёт и не накладывается.
-
-Sticky значит, что прокси не прыгает между аккаунтами посреди живого чата, кроме случаев, когда логин упёрся в лимит частоты или потерял авторизацию. Если логин получил `401` или `403` или DeepSeek упёрся в лимит частоты, логин уходит в cooldown, а старая удалённая сессия сбрасывается. Запрос, упёршийся в лимит, не падает: он сразу переходит на другой готовый логин, в новый чат с полной историей. После `401`/`403` переходит следующий запрос.
-
-Каталог auth-файлов:
-
-```bash
-mkdir -p accounts
-npm run auth:import -- --input ~/Downloads/deepseek-auth.json --output ./accounts/worker-2.json
-chmod 600 accounts/*.json deepseek-auth.json
-DEEPSEEK_AUTH_DIR=./accounts NON_INTERACTIVE=1 npm start
-```
-
-Или список через запятую:
-
-```bash
-DEEPSEEK_AUTH_PATH="./accounts/main.json,./accounts/backup.json" NON_INTERACTIVE=1 npm start
-```
+Логин остаётся на вашем компьютере в `deepseek-auth.json`. Сообщения уходят в DeepSeek, как и в обычном чате.
-Как ведёт себя пул:
+
-- новый агент получает свободный логин по кругу;
-- этот логин остаётся приклеен к сессии;
-- `401`, `403` и лимит частоты отправляют логин в cooldown (`DEEPSEEK_ACCOUNT_COOLDOWN_MS`, по умолчанию 10 минут). Лимит частоты — это HTTP `429`, сообщение «слишком частые» в HTTP `400` или JSON-ответе (например, `Слишком частые сообщения`) или подсказка в потоке DeepSeek с `finish_reason: rate_limit_reached`. Если DeepSeek прислал `Retry-After`, он соблюдается;
-- запрос, упёршийся в лимит, переходит на другой готовый логин в новый чат. Клиент получает `429 rate_limit`, только когда в cooldown все логины;
-- остальные ошибки `400` в cooldown не отправляют. Чат пересоздаётся на том же логине;
-- два запроса и два свободных логина уходят на разные аккаунты;
-- тот же `x-agent-session` внахлёст ждёт свой логин (`DEEPSEEK_ACCOUNT_LOCK_WAIT_MS`, по умолчанию 120 секунд);
-- когда заняты все логины, запрос ждёт sticky или тот, которым давно не пользовались;
-- запрос заголовка сессии OpenCode отвечается локально и логин не занимает;
-- `/health` показывает статус аккаунтов без путей к auth-файлам и без имён файлов;
-- `/dashboard` показывает все логины и позволяет приостановить, вернуть, снять cooldown и перечитать auth-файлы без перезапуска (см. [Панель аккаунтов](#панель-аккаунтов));
-- auth-файлы должны быть с правами `0600`.
+
+Какую модель выбрать?
-Привязать клиента к выбранному файлу нельзя. Прокси сам берёт свободный логин.
+Модель одна, у неё два переключателя:
-```bash
-DEEPSEEK_ACCOUNT_COOLDOWN_MS=600000 npm start
-```
-
----
-
-## Панель аккаунтов
-
-Откройте `http://127.0.0.1:9655/dashboard`. Там видны все логины: состояние (`ready`, `busy`, `cooldown`, `disabled`, `no_credentials`), обратный отсчёт cooldown и его причина, подряд идущие и общие ошибки, последняя ошибка DeepSeek и расход. Оттуда можно:
-
-- **Disable / Enable** — приостановить или вернуть логин. Это пауза на время работы процесса: начатые запросы доработают, после перезапуска пауза забывается. Постоянный выключатель — `"enabled": false` в auth-файле; логин, выключенный в файле, из панели не включить.
-- **Clear cooldown** — сразу вернуть остывающий логин в ротацию.
-- **Reload accounts** — перечитать auth-файлы. Новые файлы добавляются, удалённые убираются. Оставшийся логин сохраняет cooldown и счётчики. Логин с новым токеном или cookie начинает с чистого листа.
-
-Чтобы добавить логин, импортируйте его и нажмите Reload:
-
-```bash
-npm run auth:import -- --input ~/Downloads/deepseek-auth.json --output ./accounts/worker-3.json
-```
-
-Страница статическая и данных не хранит. Она читает admin API:
-
-| Метод | Путь | Результат |
-|---|---|---|
-| `GET` | `/admin/accounts` | `{ now, pool, accounts }` |
-| `POST` | `/admin/accounts//disable` | `{ account, pool }` |
-| `POST` | `/admin/accounts//enable` | `{ account, pool }`. `409 disabled_in_file`, если в файле `"enabled": false` |
-| `POST` | `/admin/accounts//clear-cooldown` | `{ account, pool }` |
-| `POST` | `/admin/accounts/reload` | `{ added, removed, kept, errors, accounts, pool }`. `422 no_accounts_found` оставляет пул как был |
-| `POST` | `/admin/accounts/restore` | Тело `{ archived_as }` из ответа `DELETE`. Возвращает файл на место и перечитывает пул: `{ restored, errors, accounts, pool }`. `404 archive_not_found`, `409 restore_target_exists` |
-
-Доступ:
-
-- Если задан `PROXY_API_KEY`, `/admin/*` требует тот же bearer, что и `/v1/*`. Страница спросит ключ и сохранит его только в session storage вкладки.
-- Без ключа `/admin/*` отвечает только прямым клиентам с loopback. Запрос с `X-Forwarded-For`, `Forwarded` или `X-Real-IP` получает `403 admin_forbidden`, даже с `127.0.0.1`. Так же отклоняются `Host` не localhost и браузерный `Origin`, отличный от адреса самого прокси (другое локальное веб-приложение не может ставить логины на паузу). `PROXY_ADMIN_ALLOW_REMOTE=1` снимает только ограничение по адресу клиента. `Host` всё равно должен быть loopback, IP-адресом или хостом из `PROXY_CORS_ORIGINS`, а браузерный `Origin` — адресом самого прокси. Любой, кто достучится до порта, сможет ставить логины на паузу, поэтому на сетевом адресе лучше задать ключ.
-- POST из браузера по-прежнему проходит проверку origin. Чтобы открывать панель не с loopback-адреса, добавьте этот origin в `PROXY_CORS_ORIGINS`.
-- В ответах admin API нет токенов, cookie, значений `hif_*` и имён auth-файлов.
-
-Панель входит в образ контейнера. С `--read-only` действия, которые пишут auth-файлы (добавить, переименовать, удалить, восстановить), падают с `500 auth_file_write_failed`; пауза, возобновление и снятие cooldown работают.
-
----
-
-## Обновления
-
-DeepSeek время от времени меняет свой Web-чат, и FreeDeepseekAPI подстраивается под эти изменения. Держите свою копию свежей.
-
-Два канала, оба — ветки на GitHub:
-
-| Канал | Что приходит |
-|---|---|
-| `stable` | Релиз, после того как его проверили. Канал по умолчанию, его клонирует Quick start. |
-| `latest` | Каждый релиз сразу после выхода. |
-
-**Из дашборда:** Settings → Updates. Выберите канал, **Check for updates** покажет, что нового, **Install** попросит подтвердить эти изменения и только потом переведёт вашу копию на новую версию, **Restart now** её запустит. Перезапуск автоматический, если прокси запущен через `npm start` или `npm run dashboard`; иначе остановите его и запустите снова. Без этого подтверждения установка не начинается.
-
-Дашборд только двигает копию вперёд. Он останавливается и показывает команду для ручного обновления, если в папке есть незакоммиченные правки отслеживаемых файлов или в ветке канала есть свои коммиты. У образа контейнера и скачанного архива нет git-истории: скачайте новый образ или новый релиз.
-
-**Вручную:**
-
-```bash
-git fetch origin && git switch stable && git merge --ff-only origin/stable
-```
-
-Потом перезапустите прокси.
-
----
-
-## Вход
-
-| Команда | Что делает |
+| Модель | Что делает |
|---|---|
-| `npm run auth` | Меню: Chrome, импорт, статус, удалить локальный файл |
-| `npm run deepseek:auth` | Снять token и cookies через Chrome |
-| `npm run auth:import` | Импорт `deepseek-auth.json` или экспорта cookies |
-| `npm run doctor` | Проверить файлы. Без `--offline` ещё и PoW |
-
-Расширение Chrome: загрузите `chrome-extension/` на открытую вкладку chat.deepseek.com. Собирайте, пока **Token** не станет Ready, потом сохраните файл. Этот JSON в чат не вставляйте.
-
-Поля: `token`, `cookie`, `wasmUrl` (адрес `https://*.deepseek.com`). Необязательные: `hif_dliq`, `hif_leim`, `name` и `enabled` (`false` ставит логин на паузу). Пример: [`auth.example.json`](auth.example.json).
-
-Пароль аккаунта DeepSeek сюда не входит. Команды `auth:console` нет, и пароль на диск писать не нужно.
-
----
-
-## Агенты
-
-```bash
-npm run setup:agents
-npm run setup:agents -- --all --model deepseek-v4-flash
-npm run setup:agents -- --target claude-code --model deepseek-v4-flash-thinking
-npm run setup:agents -- --target codex --model deepseek-v4-flash
-```
-
-Прокси уже должен слушать порт. Адрес по умолчанию: `http://127.0.0.1:9655`. Другой задаётся через `--base-url`. Если задан `PROXY_API_KEY`, он копируется в конфиг агента.
-
-Setup добавляет FreeDeepseekAPI как отдельный профиль. Claude, GPT и то, чем вы пользуетесь сейчас, он не подменяет.
-
-| Агент | Что записывается | Как выбрать |
-|---|---|---|
-| Claude Code | `~/.claude/freedeepseek.settings.json` | `claude --settings ~/.claude/freedeepseek.settings.json` |
-| Codex | `~/.codex/freedeepseek.config.toml` и каталог моделей | `codex --profile freedeepseek` |
-| OpenCode | провайдер `freedeepseek` и правила автономности в `AGENTS.md` | выбрать `freedeepseek/` |
-| Hermes | `~/.hermes/freedeepseek.yaml` | этот файл профиля |
-| OpenClaw | провайдер `freedeepseek` | выбрать явно |
-| Cursor | сниппет и launcher в `integrations/cursor/` | настройки редактора не меняются |
-
-`--model` всегда DeepSeek-V4.1-Flash с включённым родным поиском chat.deepseek.com. `-thinking` включает DeepThink. `-nosearch` выключает поиск; тогда у агента остаются его собственные веб-инструменты. Старый id с `-search` отображается на тот же id без суффикса.
-
-Setup Codex **не** пишет `forced_login_method = api`. На Codex CLI эта строка разлогинивает ChatGPT. Обычный `codex` остаётся на ChatGPT. Профиль FreeDeepseek говорит с этим прокси.
-
-Картинки:
-
-- Claude Code: вставьте или прикрепите. Блок Anthropic `image` уходит в DeepSeek Web.
-- Codex: `codex -i screenshot.png`. Повторите `-i` для нескольких файлов. `/v1/responses` принимает `input_image`.
-- OpenCode: вставьте или перетащите картинку. Сгенерированный конфиг её не выкидывает.
-- Остальные OpenAI-клиенты: `image_url` как base64 data URL или публичный HTTPS URL.
-
-Вернуть прошлый setup из бэкапа:
-
-```bash
-node scripts/setup-agents.js --restore ~/.freedeepseek-api/backups/
-```
-
-Два агента сразу — два Web-логина в `accounts/`. Подробности: [docs/ru/agents.md](docs/ru/agents.md).
-
----
-
-## Проверка работы
-
-```bash
-curl http://127.0.0.1:9655/health
-curl http://127.0.0.1:9655/readyz
-curl http://127.0.0.1:9655/v1/models
-curl http://127.0.0.1:9655/v1/model-capabilities
-```
-
-`/health` говорит, что процесс жив. `/readyz` равен `200`, только если хотя бы один логин может обслужить запрос. `/v1/models` отдаёт четыре id DeepSeek-V4.1-Flash.
-
----
-
-## Примеры запросов
-
-### Chat Completions
-
-```bash
-curl -X POST http://127.0.0.1:9655/v1/chat/completions \
- -H "Content-Type: application/json" \
- -H "x-agent-session: my-agent" \
- -d '{
- "model": "deepseek-v4-flash",
- "messages": [{"role": "user", "content": "Ответь одним предложением."}],
- "stream": false
- }'
-```
-
-### DeepThink
-
-`-thinking` — это переключатель DeepThink из композера чата. Модель всё та же, DeepSeek-V4.1-Flash. Она рассуждает перед ответом.
-
-```bash
-curl -X POST http://127.0.0.1:9655/v1/chat/completions \
- -H "Content-Type: application/json" \
- -d '{
- "model": "deepseek-v4-flash-thinking",
- "messages": [{"role": "user", "content": "Почему небо голубое? Коротко."}],
- "stream": false
- }'
-```
-
-Где лежит рассуждение:
-
-- без стрима: `choices[0].message.reasoning_content`
-- стрим: `choices[0].delta.reasoning_content`
-- usage: `usage.completion_tokens_details.reasoning_tokens`
-
-`reasoning_tokens` — оценка по извлечённому тексту DeepThink. Web-стрим официальный расход reasoning-токенов не отдаёт.
+| `deepseek-v4-flash` | Отвечает с поиском в интернете |
+| `deepseek-v4-flash-thinking` | Сначала думает, потом отвечает |
-Ход с вызовом инструмента не приклеивает рассуждение к сообщению. Часть агентов считает любой текст рядом с tool call окончательным ответом и останавливается.
+Чтобы отключить поиск, допишите к любой из них `-nosearch`.
-### Родной веб-поиск
+
-Родной Web Search chat.deepseek.com включён по умолчанию для любого id модели. Вопросы про интернет идут через этот поиск. Не просите модель пользоваться bash, curl или инструментом харнесса `websearch` / `webfetch`.
+
+Можно несколько аккаунтов?
-```bash
-curl -X POST http://127.0.0.1:9655/v1/chat/completions \
- -H "Content-Type: application/json" \
- -d '{
- "model": "deepseek-v4-flash",
- "messages": [{"role": "user", "content": "Найди свежий факт про DeepSeek и ответь коротко."}],
- "stream": false
- }'
-```
-
-Чтобы ответить без поиска, передайте `"web_search": false` или возьмите id с окончанием `-nosearch`:
-
-```bash
-curl -X POST http://127.0.0.1:9655/v1/chat/completions \
- -H "Content-Type: application/json" \
- -d '{
- "model": "deepseek-v4-flash-thinking",
- "web_search": false,
- "messages": [{"role": "user", "content": "Объясни, как B-дерево разделяет узел."}],
- "stream": false
- }'
-```
-
-`web_search` должен быть `true` или `false`; любое другое значение возвращает `400 invalid_request_error`. Поле главнее id: `"web_search": true` на id с `-nosearch` снова включает поиск. Поле работает на `/v1/chat/completions`, `/v1/messages` и `/v1/responses`.
-
-При выключенном поиске кодирующий агент сохраняет свои инструменты `websearch` / `webfetch`, и ему не сообщают, что включён родной поиск.
-
-### Streaming
-
-```bash
-curl -N -X POST http://127.0.0.1:9655/v1/chat/completions \
- -H "Content-Type: application/json" \
- -d '{
- "model": "deepseek-v4-flash",
- "messages": [{"role": "user", "content": "Расскажи короткий анекдот."}],
- "stream": true
- }'
-```
-
-Последний SSE-чанк несёт `usage`, затем `data: [DONE]`.
-
-### Anthropic Messages
-
-```bash
-curl -X POST http://127.0.0.1:9655/v1/messages \
- -H "Content-Type: application/json" \
- -d '{
- "model": "deepseek-v4-flash",
- "max_tokens": 512,
- "messages": [{"role": "user", "content": "Ответь ровно OK"}],
- "stream": false
- }'
-```
-
-Claude Code после `npm run setup:agents -- --target claude-code`:
-
-```bash
-claude --settings ~/.claude/freedeepseek.settings.json
-```
-
-Имена вроде `claude-sonnet-*` и `claude-opus-*` отображаются на DeepSeek-V4.1-Flash и DeepSeek-V4.1-Flash с DeepThink, поэтому старый Claude id всё ещё выполняется.
-
-### OpenAI Responses
-
-```bash
-curl -X POST http://127.0.0.1:9655/v1/responses \
- -H "Content-Type: application/json" \
- -d '{
- "model": "deepseek-v4-flash",
- "input": "Ответь ровно OK",
- "stream": false
- }'
-```
-
-Codex ходит этим маршрутом. После setup:
-
-```bash
-codex --profile freedeepseek
-```
-
-### Tool calling
-
-Прокси принимает OpenAI `tools`, Anthropic `tools` и function tools из Responses.
-
-У DeepSeek Web нет настоящего массива tool calls. Прокси вписывает список инструментов в промпт и разбирает ответ обратно в OpenAI `tool_calls`. Принимаются такие формы:
-
-- `{"tool_call":{"name":"...","arguments":{...}}}`
-- `{"tool_calls":[{"name":"...","arguments":{...}}]}` — несколько независимых вызовов, до 8
-- `TOOL_CALL:` и следом JSON-объект
-- JSON в ограде с конвертом `tool_call`, `tool_calls` или `function_call`
-- `...`
-- DeepSeek DSML, включая Web-вариант с удвоенными чертами
-
-`execute_code` и `web_search` — собственные инструменты DeepSeek. На вашем компьютере они не запускаются. Если они стоят рядом с настоящим локальным инструментом вроде `read_file`, они отбрасываются, а локальные вызовы остаются. Недописанный блок инструмента не выполняется. Один повтор просит строгий JSON. Если и он сломан, ход возвращает `502 malformed_tool_call`, а чат остаётся открытым.
-
-Пока родной поиск включён, инструменты харнесса `websearch`, `webfetch` и `WebFetch` вырезаются, а живой интернет — это родной поиск chat.deepseek.com. При выключенном поиске они доходят до агента без изменений.
+Да. Добавьте их в дашборде: Settings → Accounts. Чтобы два агента работали одновременно, нужно два логина.
-### Картинки
+
-PNG, JPEG, WebP и GIF. До 10 картинок, по 20 МиБ в раскодированном виде. Тело JSON по умолчанию до 30 МиБ.
+
+Перестало работать. Что делать?
-Прокси загружает картинку в DeepSeek Web, ждёт конца разбора и потом шлёт id файла. Чужой `file_id` отклоняется. URL должен быть публичным HTTPS. Редиректы на локальные, частные и link-local адреса отклоняются.
+Попробуйте по порядку:
+1. Обновитесь: Settings → Updates в дашборде.
+2. Войдите заново: `npm run auth`.
+3. Проверьте настройку: `npm run doctor`.
-OpenAI Chat Completions использует `image_url`. Responses использует `input_image`. Anthropic использует блок `image` с base64. См. [docs/api.md](docs/api.md).
+Если не помогло, скорее всего, DeepSeek что-то изменил. [Напишите нам в issue](https://github.com/dekrezz/FreeDeepseekAPI/issues).
----
-
-## Модели
-
-`GET /v1/models` отдаёт только DeepSeek-V4.1-Flash.
-
-| ID | DeepThink | Родной веб-поиск | Что делает |
-|---|---|---|---|
-| `deepseek-v4-flash` | выкл | вкл | DeepSeek-V4.1-Flash. `deepseek-flash` — тот же id |
-| `deepseek-v4-flash-thinking` | вкл | вкл | Сначала DeepThink, потом ответ |
-| `deepseek-v4-flash-nosearch` | выкл | выкл | Без родного поиска |
-| `deepseek-v4-flash-thinking-nosearch` | вкл | выкл | DeepThink без родного поиска |
-
-Эти суффиксы — два переключателя в чате DeepSeek. Другую модель они не выбирают. `"web_search": true|false` в теле запроса переопределяет переключатель поиска у любого id.
-
-Старые id `deepseek-v4-flash-search` и `deepseek-v4-flash-thinking-search` по-прежнему работают. Они означают `deepseek-v4-flash` и `deepseek-v4-flash-thinking` и больше не перечислены в `/v1/models`.
-
-Старые id не зарегистрированы и отвечают `400 invalid_model`:
-
-`deepseek-chat`, `deepseek-reasoner`, `deepseek-r1`, `deepseek-v3`, `deepseek-instant`, `deepseek-expert`, `deepseek-v4-pro`, `deepseek-chat-search` и vision.
-
-```bash
-curl http://127.0.0.1:9655/v1/model-capabilities
-```
-
-Полная таблица: [docs/ru/models.md](docs/ru/models.md).
-
----
-
-## Endpoints
-
-| Метод | Путь | Назначение |
-|---|---|---|
-| `GET` | `/health` | Процесс жив. Статус аккаунтов, если ключа proxy нет или bearer совпал |
-| `GET` | `/readyz` | `200`, только если логин может обслужить запрос |
-| `GET` | `/dashboard` | Панель аккаунтов (статическая страница) |
-| `GET` | `/admin/accounts` | Пул и статус каждого логина. См. [Панель аккаунтов](#панель-аккаунтов) |
-| `POST` | `/admin/accounts//{disable,enable,clear-cooldown}` | Приостановить, вернуть или снять cooldown с логина |
-| `POST` | `/admin/accounts/reload` | Перечитать auth-файлы без перезапуска |
-| `GET` | `/v1/models` | Четыре id DeepSeek-V4.1-Flash |
-| `GET` | `/v1/model-capabilities` | Id, DeepThink и родной поиск |
-| `POST` | `/v1/chat/completions` | OpenAI Chat Completions |
-| `POST` | `/v1/messages` | Anthropic Messages |
-| `POST` | `/v1/responses` | OpenAI Responses |
-| `GET` | `/v1/sessions` | Локальные сессии агентов |
-| `POST` | `/reset-session?agent=` | Закрыть один Web-чат |
-| `POST` | `/reset-session?agent=all` | Закрыть все Web-чаты |
-
----
-
-## Переменные окружения
-
-| Переменная | По умолчанию | Смысл |
-|---|---|---|
-| `HOST` | `127.0.0.1` | Адрес. Привязка не к loopback без ключа proxy печатает предупреждение |
-| `PORT` | `9655` | Порт |
-| `TLS_CERT_FILE` / `TLS_KEY_FILE` | выкл | PEM-сертификат и закрытый ключ. Если заданы оба и их можно прочитать, прокси отвечает по HTTPS. Если не заданы, остаётся HTTP. На loopback TLS не нужен. Привязка не к loopback без них предупреждает, что импорт логина и заголовок Authorization идут открытым текстом |
-| `PROXY_API_KEY` | выкл | Bearer обязателен на `/v1/*` и `/admin/*`, если задан |
-| `REQUIRE_PROXY_API_KEY` | выкл | Не стартовать без ключа. В контейнере это включено |
-| `PROXY_CORS_ORIGINS` | loopback | Дополнительные точные origin браузера |
-| `PROXY_ADMIN_ALLOW_REMOTE` | off | Если `1`, `/admin/*` отвечает не-loopback клиентам даже без `PROXY_API_KEY` |
-| `DEEPSEEK_AUTH_PATH` | `./deepseek-auth.json` | Один файл или список через запятую |
-| `DEEPSEEK_AUTH_DIR` | `./accounts`, если каталог есть | Все `*.json` в нём |
-| `DEEPSEEK_MAX_PROMPT_CHARS` | `80000` | Потолок того, что уходит наверх. Минимум 16000 |
-| `DEEPSEEK_MAX_RETRIES` | `2` | Повторы пустого ответа в том же чате |
-| `DEEPSEEK_REQUEST_DEADLINE_MS` | `120000` | Лимит времени на запрос |
-| `DEEPSEEK_MAX_CONCURRENT` | `24` | Потолок процесса. Настоящий параллелизм — число свободных логинов |
-| `DEEPSEEK_ACCOUNT_LOCK_WAIT_MS` | `120000` | Сколько второй чат ждёт занятый логин |
-| `DEEPSEEK_ACCOUNT_COOLDOWN_MS` | `600000` | Cooldown после 401, 403 или лимита частоты без `Retry-After` |
-| `TRUST_PROXY` | выкл | Если `1`, IP клиента берётся из `X-Forwarded-For` |
-| `MAX_REQUEST_BODY_BYTES` | `31457280` | Максимум тела JSON, вместе с base64-картинками |
-| `NON_INTERACTIVE` / `SKIP_ACCOUNT_MENU` | выкл | Пропустить меню запуска |
-
----
-
-## Ошибки
-
-| Статус | `error.type` | Что делать |
-|---|---|---|
-| 400 | `invalid_model` | Возьмите id из `GET /v1/models` |
-| 400 | `context_length_exceeded` | Промпт остался слишком длинным после уплотнения |
-| 401 | `authentication_error` | Ключ proxy не совпал |
-| 403 | `admin_forbidden` | `/admin/*` без ключа с не-loopback или проксированного клиента. См. [Панель аккаунтов](#панель-аккаунтов) |
-| 429 | `concurrent_chat_blocked` | Ожидание занятого логина истекло. Добавьте логин или повторите |
-| 429 | `rate_limit` | Все логины в cooldown (лимит частоты или ошибка входа). Уважайте `Retry-After` |
-| 429 | `rate_limit_error` | DeepSeek ограничил логин, а время запроса вышло или клиент ушёл раньше, чем закончился переход на другой логин. Уважайте `Retry-After` |
-| 502 | `malformed_tool_call` | Разметка инструмента осталась сломанной после одной починки. Чат сохранён |
-| 502 | `empty_response` | DeepSeek ничего не вернул после повторов |
-| 503 | `overloaded` / `no_auth` | Слишком много запросов в полёте или нет auth-файла |
-| 504 | `request_timeout` | Вышел срок из `DEEPSEEK_REQUEST_DEADLINE_MS` |
-
----
-
-## Open WebUI
-
-Base URL, если Open WebUI в Docker на той же машине:
-
-```text
-http://host.docker.internal:9655/v1
-```
-
-Локально, без Docker:
-
-```text
-http://127.0.0.1:9655/v1
-```
-
-Если `PROXY_API_KEY` не задан, в поле API key можно поставить что угодно. Если ключ задан, клиент должен прислать именно его. Прокси проверяет bearer до моделей, сессий и completions.
-
-Берите `deepseek-v4-flash` для обычного ответа с родным поиском chat.deepseek.com, `deepseek-v4-flash-thinking` для DeepThink и id с `-nosearch`, когда нужен ответ без поиска.
-
----
-
-## Обновить логин
-
-```bash
-npm run auth
-npm start
-```
-
-Если DeepSeek отвечает `401` или `403`, или падает PoW, войдите снова и замените `deepseek-auth.json`.
-
-В git не попадают:
-
-- `deepseek-auth.json`
-- `accounts/*.json`
-- каталоги профиля Chrome, которыми пользуется скрипт входа
-- `.env`
-
----
-
-## Тесты
-
-Синтаксис и модульные тесты, без сети:
-
-```bash
-npm test
-```
-
-Живые smoke-тесты против уже запущенного proxy:
-
-```bash
-BASE_URL=http://127.0.0.1:9655 MODEL=deepseek-v4-flash npm run test:live
-```
+
-`npm test` гоняет `node --check` по точкам входа и `node --test` по `tests/unit.test.js` и `tests/account-failover.test.js`. В DeepSeek он не ходит: тесты переключения аккаунтов отвечают на все запросы к DeepSeek встроенной заглушкой.
+
+Как обновиться?
----
+Откройте Settings → Updates в дашборде и нажмите **Check for updates**. На канал `stable` релиз приходит после проверки, на `latest` сразу.
-## Статус проекта
+
-FreeDeepseekAPI — локальный web-chat proxy. Он зависит от текущего контракта chat.deepseek.com. Когда контракт меняется, может понадобиться поправить auth или тело запроса.
+
+Можно подключаться с других устройств?
-Если вызов перестал работать:
+По умолчанию доступ есть только с вашего компьютера. Чтобы открыть его, задайте `PROXY_API_KEY` и сначала прочитайте раздел [Running it safely](SECURITY.md#running-it-safely).
-1. Обновитесь до последней версии ([Обновления](#обновления)).
-2. Обновите логин через `npm run auth`.
-3. Запустите `npm run doctor`.
-4. Прочитайте `GET /v1/model-capabilities` и возьмите id DeepSeek-V4.1-Flash.
-5. Если тот же чат продолжает падать, вызовите `POST /reset-session?agent=` и попробуйте ещё раз.
-6. Если и это не помогло, DeepSeek, скорее всего, изменил внутренний Web API.
+
-Сообщения об уязвимостях идут в закрытый GitHub advisory, не в публичный issue. См. [SECURITY.md](SECURITY.md). Список мейнтейнеров: [CONTRIBUTORS.md](CONTRIBUTORS.md).
+
+Работает на Windows, сервере или в контейнере?
-## Документация
+Да: [Windows](docs/ru/guide.md#windows), [VPS](docs/ru/guide.md#vps--headless), [Podman](docs/ru/guide.md#rootless-podman).
-- [Авторизация](docs/ru/auth.md)
-- [Агенты](docs/ru/agents.md)
-- [Модели](docs/ru/models.md)
-- [HTTP API](docs/api.md)
+
-## Звёзды
+## Что ещё почитать
-
-
-
+- [Полное руководство](docs/ru/guide.md): всё подробно, с примерами запросов
+- [HTTP API](docs/api.md): эндпоинты, ошибки и настройки (на английском)
+- [Модели](docs/ru/models.md) · [Аккаунты и вход](docs/ru/auth.md) · [Агенты](docs/ru/agents.md)
+- [Безопасность](SECURITY.md): как сообщить об уязвимости
## Лицензия
diff --git a/README.zh.md b/README.zh.md
index 64af18f..45cf934 100644
--- a/README.zh.md
+++ b/README.zh.md
@@ -5,7 +5,7 @@
FreeDeepseekAPI
- 面向 DeepSeek Web Chat 的本地 OpenAI 兼容 API 代理
+ 把免费的 DeepSeek 账号变成 API