diff --git a/.github/workflows/star-chart.yml b/.github/workflows/star-chart.yml deleted file mode 100644 index bb73571..0000000 --- a/.github/workflows/star-chart.yml +++ /dev/null @@ -1,48 +0,0 @@ -name: star-chart - -on: - schedule: - - cron: "27 3 * * *" - watch: - types: [started] - workflow_dispatch: - -permissions: - contents: write - -jobs: - render: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - with: - node-version: "20" - - name: Fetch stargazers and draw chart - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - GITHUB_REPOSITORY: ${{ github.repository }} - run: node scripts/render-stars-chart.js - - name: Rasterize SVG to PNG - run: | - sudo apt-get update - sudo apt-get install -y librsvg2-bin - rsvg-convert -w 800 docs/assets/stars.svg -o docs/assets/stars.png - - name: Commit chart if it changed - run: | - git add docs/assets/stars.svg docs/assets/stars.png - if git diff --cached --quiet; then - echo "star chart unchanged" - exit 0 - fi - git config user.name "github-actions[bot]" - git config user.email "41898282+github-actions[bot]@users.noreply.github.com" - git commit -m "$(cat <<'EOF' - Docs - - Changes: - - - Refresh the committed GitHub star chart from stargazer timestamps - EOF - )" - git push diff --git a/.github/workflows/unit.yml b/.github/workflows/unit.yml index 041b51f..11bcbbc 100644 --- a/.github/workflows/unit.yml +++ b/.github/workflows/unit.yml @@ -22,12 +22,10 @@ concurrency: jobs: test: - # PRs always. Main only for direct commits — skip PR merges and the star-chart bot. + # PRs always. Main only for direct commits, not PR merges. if: > - github.event_name == 'pull_request' || ( - !contains(github.event.head_commit.message, 'Merge pull request') && - !contains(github.event.head_commit.message, 'Refresh the committed GitHub star chart') - ) + github.event_name == 'pull_request' || + !contains(github.event.head_commit.message, 'Merge pull request') runs-on: ubuntu-latest timeout-minutes: 5 steps: diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index ac5c5de..9b7a4b1 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -14,6 +14,4 @@ Open a pull request that lands on `main`. Code, docs, and translations all count If you used AI, follow [AI_POLICY.md](AI_POLICY.md): say which tool and model you used (for example, "Used Claude Code with Claude Opus 5.5"), and make sure you understand the change. -The GitHub Actions job that redraws the star chart is not a contributor. It commits as `github-actions[bot]`. - If your login is missing after a merged pull request, say so on that pull request and it will be added here. diff --git a/README.md b/README.md index 79640f2..6de26b8 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@

FreeDeepseekAPI

- Local OpenAI-compatible API proxy for DeepSeek Web Chat + Use your free DeepSeek account as an API

@@ -13,7 +13,6 @@ Node.js 18 plus No npm dependencies OpenAI compatible - DeepSeek V4.1 Flash

@@ -22,28 +21,11 @@ 简体中文

-

- Start here • - Quick start • - What you get • - Examples • - Models • - Endpoints • - Open WebUI • - Coding agents -

- -

- FreeDeepseekAPI dashboard: built-in chat on top of DeepSeek Web -

+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 - - Star history - +- [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

@@ -13,7 +13,6 @@ Node.js 18 plus No npm dependencies OpenAI compatible - DeepSeek V4.1 Flash

@@ -22,28 +21,11 @@ 简体中文

-

- С чего начать • - Быстрый старт • - Что это даёт • - Примеры • - Модели • - Endpoints • - Open WebUI • - Агенты -

- -

- Дашборд FreeDeepseekAPI: встроенный чат поверх DeepSeek Web -

+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

@@ -13,7 +13,6 @@ Node.js 18 plus No npm dependencies OpenAI compatible - DeepSeek V4.1 Flash

@@ -22,28 +21,11 @@ 简体中文

-

- 从这里开始 • - 快速开始 • - 能做什么 • - 示例 • - 模型 • - Endpoints • - Open WebUI • - 编程代理 -

- -

- FreeDeepseekAPI 控制面板:基于 DeepSeek Web 的内置聊天 -

+FreeDeepseekAPI 运行在你的电脑上,把免费的 [chat.deepseek.com](https://chat.deepseek.com) 账号变成本地 API。凡是支持 OpenAI 或 Anthropic 的应用,都能通过它使用 DeepSeek,比如 Open WebUI、Claude Code、Codex、Cursor。不需要付费密钥。 -## 从这里开始 +## 快速上手 -**这是什么。** 你在 [chat.deepseek.com](https://chat.deepseek.com) 有一个免费的 DeepSeek 账号。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,885 +34,122 @@ 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` | -在 Docker 中运行的 Open WebUI:使用 `http://host.docker.internal:9655/v1`。 +在 Docker 里运行的 Open WebUI 要改用 `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 兼容客户端都可以连上来。 - -它使用你已经登录的 DeepSeek 账号。本地服务接收 API 请求,再沿着保存好的 Web 会话继续聊。不需要 `api.deepseek.com` 的付费密钥。 - -网站上现在只有一个模型:**DeepSeek-V4.1-Flash**。chat.deepseek.com 自带的网页搜索**默认打开**,上网查资料走的就是这个搜索。`-thinking` 打开 DeepThink。`-nosearch` 或 `"web_search": false` 关闭搜索。 - -> 这是实验性的网页聊天代理。DeepSeek 随时可能修改内部 Web API。一旦变化,项目会跟着更新,本文档也可能随之调整。建议始终使用最新版本:在面板的 Settings → Updates 中更新,或参见[更新](#更新)。 - ---- - -## 目录 - -- [从这里开始](#从这里开始) -- [能做什么](#能做什么) -- [功能](#功能) -- [快速开始](#快速开始) -- [Windows](#windows) -- [Linux / Chromium](#linux--chromium) -- [VPS / 无界面](#vps--无界面) -- [Rootless Podman](#rootless-podman) -- [Diagnostics / doctor](#diagnostics--doctor) -- [会话复用](#会话复用) -- [多账号池](#多账号池) -- [账号面板](#账号面板) -- [更新](#更新) -- [登录](#登录) -- [编程代理](#编程代理) -- [检查是否正常](#检查是否正常) -- [请求示例](#请求示例) - - [Chat Completions](#chat-completions) - - [DeepThink](#deepthink) - - [自带网页搜索](#自带网页搜索) - - [Streaming](#streaming) - - [Anthropic Messages](#anthropic-messages) - - [OpenAI Responses](#openai-responses) - - [工具调用](#工具调用) - - [图片](#图片) -- [模型](#模型) -- [Endpoints](#endpoints) -- [环境变量](#环境变量) -- [错误](#错误) -- [Open WebUI](#open-webui) -- [重新登录](#重新登录) -- [测试](#测试) -- [项目状态](#项目状态) - ---- - -## 能做什么 - -- 把 DeepSeek Web 当成一个本地 API。 -- 接到 Open WebUI 和其他 OpenAI 兼容客户端。 -- 返回普通 JSON,或者 SSE 流。 -- 用 `-thinking` 打开 DeepThink,并从 `reasoning_content` 读出推理。 -- 用 Anthropic Messages 接 Claude Code。 -- 用 OpenAI Responses 接 Codex。 -- 每个代理或 `user` 各用一个独立的 Web 会话。 -- 一次回复里交出最多八个本地工具调用。 -- 上网用 DeepSeek 自己的搜索,不用 bash,也不用 harness 的 websearch。 - -## 功能 - -- **OpenAI 兼容 API:** `POST /v1/chat/completions` -- **Anthropic 兼容垫片:** `POST /v1/messages` -- **OpenAI Responses 垫片:** `POST /v1/responses` -- **流式输出:** SSE,以及非流式 JSON -- **DeepThink:** 选了 `-thinking` 时返回 `reasoning_content` -- **自带搜索:** chat.deepseek.com 的 Web Search,默认打开。用 `-nosearch` 或 `"web_search": false` 关闭 -- **工具调用:** OpenAI、Anthropic 和 Responses 的工具,可以一批一起返回 -- **模型能力:** `GET /v1/model-capabilities` -- **代理会话:** 一个 `x-agent-session` 或 `user` 对应一个 DeepSeek 聊天 -- **会话恢复:** 空回复、坏掉的工具调用和超时都留在原来的聊天里 -- **零依赖:** 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 网站上的免费账号。 -- 启动代理 -- 启动代理并打开控制台(或 `npm run dashboard`) -- 用 Chrome 登录 -- 导入 auth 文件或浏览器 cookie 导出 -- 列出 DeepSeek-V4.1-Flash 的模型 id -- 退出 +
-无菜单,适合无界面和 CI: - -```bash -NON_INTERACTIVE=1 npm start -# 或 -SKIP_ACCOUNT_MENU=1 npm start -``` - -服务监听: - -```text -http://127.0.0.1:9655 -``` +
+这是 DeepSeek 官方项目吗? -默认只接受本机连接。要暴露到网络,必须同时指定地址和单独的代理密钥: +不是。它对接的是 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。界面开在别的地址时,把精确 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 上该装到哪里,而不是一长串原始堆栈。 - ---- - -## 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 / 无界面 - -更稳的做法是不在服务器上开 Chrome。 - -1. 在有图形界面和 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. 不带菜单启动代理: - -```bash -NON_INTERACTIVE=1 npm start -``` - -浏览器导出的 cookie 也可以,但必须同时带上 token: - -```bash -DEEPSEEK_TOKEN="" npm run auth:import -- --input ./cookies.json -``` +
-`deepseek-auth.json` 就是你的 DeepSeek Web 登录。不要提交,不要贴进聊天,权限保持 `0600`。 +
+账号会被封吗? -没有密码登录命令。代理不问 DeepSeek 密码,也不会把密码写到磁盘。登录方式只有 Chrome、现成的 auth 文件,或者 cookie 导出加上 token。 +有可能。如果同一个登录同时有两个聊天在发送,DeepSeek 可能封禁它几天。所以代理让每个登录同一时间只跑一个聊天,其余的排队。这样风险更低,但无法完全消除,规则由 DeepSeek 决定。 ---- +
-## Rootless Podman +
+我的登录信息和消息会去哪里? -容器只负责跑代理。登录在宿主机上用 `npm run auth` 完成。登录脚本和 `deepseek-auth.json` 不会打进镜像。 - -用普通用户跑 Podman,不要 root。 - -1. 构建镜像: - -```bash -podman build --tag localhost/free-deepseek-api:local --file Containerfile . -``` - -2. 把 DeepSeek 登录和单独的代理密钥放进 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`。前面没有防火墙时,不要拿掉这个地址。 - -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` 在没有任何 DeepSeek 登录能接聊天时返回 `503`。 - -```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 -``` - -轮换登录或代理密钥时,换掉对应 secret,再重建容器。 - ---- - -## Diagnostics / doctor - -```bash -npm run doctor -# 不向 DeepSeek 发网络请求: -npm run doctor -- --offline -``` - -`doctor` 检查: - -- 是否存在 `deepseek-auth.json` 或 `DEEPSEEK_AUTH_DIR`; -- JSON 是否能解析; -- 是否有 `token`、`cookie` 和 `wasmUrl`; -- macOS 和 Linux 上权限是否为 `0600`; -- 普通运行时,DeepSeek 的 PoW 端点是否还能用。 - -看到 `data.biz_data is null`、`fetch failed`、`401`、`403`、`429`,或者代理看不到模型时,先跑 `npm run doctor`。 - ---- - -## 会话复用 - -FreeDeepseekAPI 不会为每一个 HTTP 请求新开一个 DeepSeek 聊天。 - -- 同一个 `x-agent-session`、`session` 或 `user` 对应同一个 DeepSeek 聊天。 -- 已经有会话时,代理用 `parent_message_id` 接着往下写。 -- 固定的 system prompt 和工具列表只向上游发 **一次**。之后 OpenCode、Claude Code 和 Codex 只发新的用户回合或工具结果。 -- system prompt 变了会再发一次。 -- 空回复、坏掉的工具调用和超时 **留在** 当前聊天。以前这种情况会新开一个聊天,再把整段提示重新发出去。现在不会。 -- 只有这些情况才开新聊天:还没有会话、链到了 100 条消息、聊天超过 2 小时、DeepSeek 说提示太长,或者你调用了 `/reset-session`。 -- 发出去之前,长提示会被裁到 `DEEPSEEK_MAX_PROMPT_CHARS`(默认 80 000 个字符)。任务开头、最新的工具结果和工具提醒会留下来。 -- 客户端已经带了多轮历史时,代理不会再把自己的恢复历史贴一遍。 -- 空回复最多重试 `DEEPSEEK_MAX_RETRIES` 次(默认 2)。每次重试都用更短的上下文;聊天还在的话,就继续留在里面。 - -显式指定代理: - -```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 那边。会话复用只是在当前链还能用的时候,不再另开一个。 - -正文恰好是 `/new` 的消息会重置这个代理的远程聊天,并且不会发给模型。 - ---- - -## 多账号池 - -同一个登录上如果有两个聊天同时发出请求,DeepSeek 可能会把这个登录封几天。池的规则是:每个登录同一时刻只跑一个聊天。第二个请求会等,不会叠上去。 - -Sticky 的意思是:活着的聊天中间,代理不会换账号,除非该登录被限流或失去授权。登录收到 `401`、`403`,或被 DeepSeek 限流时,会进入冷却,旧的远程会话会被清掉。被限流的请求不会失败:它会立刻换到另一个可用登录,在新聊天里带上完整对话记录。`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` 和限流让登录进入冷却(`DEEPSEEK_ACCOUNT_COOLDOWN_MS`,默认 10 分钟)。限流包括 HTTP `429`、HTTP `400` 或 JSON 响应里的"请求过于频繁"类消息(例如 `Слишком частые сообщения`),以及 DeepSeek 流里 `finish_reason: rate_limit_reached` 的提示。DeepSeek 给了 `Retry-After` 时会遵守; -- 被限流的请求换到另一个可用登录,开新聊天。只有所有登录都在冷却时,客户端才会收到 `429 rate_limit`; -- 其他 `400` 错误不会触发冷却,聊天在同一个登录上重建; -- 两个请求、两个空闲登录时,会分到不同账号; -- 同一个 `x-agent-session` 重叠时,会等自己的登录(`DEEPSEEK_ACCOUNT_LOCK_WAIT_MS`,默认 120 秒); -- 所有登录都忙时,请求等待 sticky 的那个,或者最久没用的那个; -- OpenCode 的会话头请求在本地回答,不占用登录; -- `/health` 展示账号状态,但不给出 auth 文件路径和文件名; -- `/dashboard` 列出所有登录,可以暂停、恢复、清除冷却,以及不重启就重新读取 auth 文件(见[账号面板](#账号面板)); -- auth 文件权限应为 `0600`。 +
+该选哪个模型? -不能把某个客户端钉死到某个文件。代理自己挑空闲登录。 +只有一个模型,两个开关: -```bash -DEEPSEEK_ACCOUNT_COOLDOWN_MS=600000 npm start -``` - ---- - -## 账号面板 - -打开 `http://127.0.0.1:9655/dashboard`。这里列出每个登录的状态(`ready`、`busy`、`cooldown`、`disabled`、`no_credentials`)、冷却倒计时和原因、连续失败次数与总失败次数、最近一次上游错误以及用量。可以在这里: - -- **Disable / Enable**:暂停或恢复一个登录。这是运行时暂停:进行中的请求会做完,重启后失效。持久开关是 auth 文件里的 `"enabled": false`;文件里禁用的登录不能在面板里启用。 -- **Clear cooldown**:让冷却中的登录立刻回到轮转。 -- **Reload accounts**:重新读取 auth 文件。新文件会加入,删掉的文件会移除。保留下来的登录保持冷却和计数。token 或 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 }`。文件里是 `"enabled": false` 时返回 `409 disabled_in_file` | -| `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/*` 需要和 `/v1/*` 相同的 bearer。页面会询问密钥,只保存在当前标签页的 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 响应里不会有 token、cookie、`hif_*` 值或 auth 文件名。 - -容器镜像包含面板。使用 `--read-only` 时,需要写 auth 文件的操作(添加、重命名、删除、恢复)会返回 `500 auth_file_write_failed`;暂停、恢复和清除冷却照常可用。 - ---- - -## 更新 - -DeepSeek 会不时调整网页聊天,FreeDeepseekAPI 会跟着更新。请让你的副本保持最新。 - -两个渠道,都是 GitHub 上的分支: - -| 渠道 | 内容 | -|---|---| -| `stable` | 经过检查后的版本。默认渠道,快速开始克隆的就是它。 | -| `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` | 用 Chrome 抓取 token 和 cookies | -| `npm run auth:import` | 导入 `deepseek-auth.json` 或 cookie 导出 | -| `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`,它会被写进代理配置。 - -安装只是把 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 | `integrations/cursor/` 里的片段和启动脚本 | 不改编辑器设置 | - -`--model` 始终是 DeepSeek-V4.1-Flash,并打开 chat.deepseek.com 的自带搜索。`-thinking` 打开 DeepThink。`-nosearch` 关闭搜索,这时编程代理会保留自己的联网工具。旧的 `-search` id 等同于去掉这个后缀的 id。 - -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。 - -从备份恢复: - -```bash -node scripts/setup-agents.js --restore ~/.freedeepseek-api/backups/ -``` - -两个代理同时跑,需要 `accounts/` 里有两个 Web 登录。细节见 [docs/zh/agents.md](docs/zh/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` 返回四个 DeepSeek-V4.1-Flash id。 - ---- - -## 请求示例 - -### 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.completion_tokens_details.reasoning_tokens` - -`reasoning_tokens` 是按抽出来的 DeepThink 文本估算的。网页流不会单独给出官方的推理 token 用量。 +| `deepseek-v4-flash` | 联网搜索后回答 | +| `deepseek-v4-flash-thinking` | 先思考,再回答 | -带工具调用的回合不会把推理贴到那条消息上。有些代理把工具调用旁边的任何文字都当成最终答案,然后停下来。 +在任意一个后面加上 `-nosearch` 就会关闭联网搜索。 -### 自带网页搜索 +
-chat.deepseek.com 的原生 Web Search 默认打开,所有模型 id 都一样。网上的问题走这个搜索。不要让模型去用 bash、curl,或者 harness 的 `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`,或者用以 `-nosearch` 结尾的 id: - -```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:在 `-nosearch` id 上发送 `"web_search": true` 会重新打开搜索。这个字段适用于 `/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,以及带 DeepThink 的 DeepSeek-V4.1-Flash,所以旧的 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 走的就是这条路由。安装之后: - -```bash -codex --profile freedeepseek -``` - -### 工具调用 - -代理接受 OpenAI 的 `tools`、Anthropic 的 `tools`,以及 Responses 的 function tools。 - -DeepSeek Web 没有真正的 tool call 数组。代理把工具列表写进提示,再把模型回复解析回 OpenAI 的 `tool_calls`。这些形式都能认: - -- `{"tool_call":{"name":"...","arguments":{...}}}` -- `{"tool_calls":[{"name":"...","arguments":{...}}]}`,一次最多 8 个互不依赖的调用 -- `TOOL_CALL:` 后面跟一个 JSON 对象 -- 围栏里的 JSON,带 `tool_call`、`tool_calls` 或 `function_call` 信封 -- `...` -- DeepSeek DSML,包括带双竖线的网页变体 - -`execute_code` 和 `web_search` 是 DeepSeek 自己的工具。它们不会在你的电脑上执行。如果它们和真正的本地工具(比如 `read_file`)写在一起,它们会被丢掉,本地调用会留下来。没写完的工具块不会执行。代理会再要一次严格 JSON。还是坏的话,这一回合返回 `502 malformed_tool_call`,聊天保持打开。 - -自带搜索打开时,harness 的 `websearch`、`webfetch` 和 `WebFetch` 会被拿掉,要查网上的事,用 chat.deepseek.com 自带的搜索。搜索关闭时,这些工具会原样交给编程代理。 +可以。在控制台的 Settings → Accounts 里添加。两个代理同时工作需要两个登录。 -### 图片 +
-支持 PNG、JPEG、WebP 和 GIF。最多 10 张,解码后每张 20 MiB。JSON 正文默认上限 30 MiB。 +
+突然用不了了怎么办? -代理把图片上传到 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 用带 base64 的 `image` 块。见 [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 的搜索开关。 - -旧的 `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/zh/models.md](docs/zh/models.md)。 - ---- - -## Endpoints - -| 方法 | 路径 | 作用 | -|---|---|---| -| `GET` | `/health` | 进程是否活着。没有代理密钥,或 bearer 匹配时,还会带账号状态 | -| `GET` | `/readyz` | 只有登录能接请求时才是 `200` | -| `GET` | `/dashboard` | 账号面板(静态页面) | -| `GET` | `/admin/accounts` | 账号池和每个登录的状态。见[账号面板](#账号面板) | -| `POST` | `/admin/accounts//{disable,enable,clear-cooldown}` | 暂停、恢复或清除某个登录的冷却 | -| `POST` | `/admin/accounts/reload` | 不重启重新读取 auth 文件 | -| `GET` | `/v1/models` | 四个 DeepSeek-V4.1-Flash id | -| `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 又没有代理密钥时会打印警告 | -| `PORT` | `9655` | 端口 | -| `TLS_CERT_FILE` / `TLS_KEY_FILE` | 关闭 | PEM 证书和私钥。两者都设置且可读时,代理以 HTTPS 提供服务;未设置则保持 HTTP。loopback 不需要 TLS。绑到非 loopback 又没设置它们时,会警告登录导入和 Authorization 头是明文 | -| `PROXY_API_KEY` | 关闭 | 设置后,`/v1/*` 和 `/admin/*` 必须带 bearer | -| `REQUIRE_PROXY_API_KEY` | 关闭 | 没有密钥就拒绝启动。容器里是打开的 | -| `PROXY_CORS_ORIGINS` | loopback | 额外允许的精确浏览器 origin | -| `PROXY_ADMIN_ALLOW_REMOTE` | 关闭 | 设为 `1` 时,即使没有 `PROXY_API_KEY`,`/admin/*` 也接受非 loopback 客户端 | -| `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` | 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` | 用 `GET /v1/models` 里的 id | -| 400 | `context_length_exceeded` | 压缩之后提示仍然太长 | -| 401 | `authentication_error` | 代理密钥不对 | -| 403 | `admin_forbidden` | 没有密钥时,从非 loopback 或经过代理的客户端访问 `/admin/*`。见[账号面板](#账号面板) | -| 429 | `concurrent_chat_blocked` | 等待忙碌登录超时。再加一个登录,或稍后重试 | -| 429 | `rate_limit` | 所有登录都在冷却(限流或登录失效)。遵守 `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 - -同一台机器上、Docker 里的 Open WebUI,Base URL 用: - -```text -http://host.docker.internal:9655/v1 -``` - -本机、不用 Docker: - -```text -http://127.0.0.1:9655/v1 -``` - -没设 `PROXY_API_KEY` 时,API key 随便填。设了的话,客户端必须发这个密钥。代理会在模型、会话和补全之前检查 bearer。 - -普通回答用 `deepseek-v4-flash`,它带 chat.deepseek.com 的自带搜索;要 DeepThink 用 `deepseek-v4-flash-thinking`;想要不带搜索的回答时用 `-nosearch` id。 - ---- - -## 重新登录 - -```bash -npm run auth -npm start -``` - -DeepSeek 返回 `401` 或 `403`,或者 PoW 失败时,重新登录并替换 `deepseek-auth.json`。 - -这些不会进 git: - -- `deepseek-auth.json` -- `accounts/*.json` -- 登录脚本使用的 Chrome 配置目录 -- `.env` - ---- - -## 测试 - -语法和单元测试,不联网: - -```bash -npm test -``` - -对已经跑起来的代理做在线冒烟测试: - -```bash -BASE_URL=http://127.0.0.1:9655 MODEL=deepseek-v4-flash npm run test:live -``` +
-`npm test` 对入口跑 `node --check`,再对 `tests/unit.test.js` 和 `tests/account-failover.test.js` 跑 `node --test`。它不会请求 DeepSeek:账号切换测试的所有上游请求都由进程内的模拟服务应答。 +
+怎么更新? ---- +打开控制台的 Settings → Updates,点 **Check for updates**。`stable` 渠道的版本经过检查后才发布,`latest` 渠道最先收到每个版本。 -## 项目状态 +
-FreeDeepseekAPI 是本地网页聊天代理。它依赖 chat.deepseek.com 当前的协议。协议一变,登录或请求体就可能要跟着改。 +
+其他设备能用吗? -调用突然不行时: +默认只有你的电脑能访问。要共享的话,请设置 `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`,改用 DeepSeek-V4.1-Flash 的 id。 -5. 同一个聊天还是失败,就调用 `POST /reset-session?agent=` 再试。 -6. 还是不行,多半是 DeepSeek 改了内部 Web API。 +
-安全问题请走非公开的 GitHub advisory,不要开公开 issue。见 [SECURITY.md](SECURITY.md)。维护者名单见 [CONTRIBUTORS.md](CONTRIBUTORS.md)。 +
+支持 Windows、服务器或容器吗? -## 文档 +支持:[Windows](docs/zh/guide.md#windows)、[VPS](docs/zh/guide.md#vps--无界面)、[Podman](docs/zh/guide.md#rootless-podman)。 -- [登录](docs/zh/auth.md) -- [编程代理](docs/zh/agents.md) -- [模型](docs/zh/models.md) -- [HTTP API](docs/api.md) +
-## Star +## 更多内容 - - Star 历史 - +- [完整指南](docs/zh/guide.md):详细说明和请求示例 +- [HTTP API](docs/api.md):接口、错误和设置(英文) +- [模型](docs/zh/models.md) · [账号与登录](docs/zh/auth.md) · [编程代理](docs/zh/agents.md) +- [安全](SECURITY.md):如何报告漏洞 ## 许可证 -Apache-2.0。Copyright 2026 dekrezz。 +Apache-2.0. Copyright 2026 dekrezz. diff --git a/docs/README.md b/docs/README.md index 3b8f4e0..0cfc7e5 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,5 +1,6 @@ # Docs +- [Full guide](guide.md) — setup, sessions, the pool, request examples, errors - [Models](models.md) — DeepSeek-V4.1-Flash. native chat.deepseek.com search is on by default, `-thinking` is DeepThink, `-nosearch` turns search off - [One-click agents](agents.md) — Claude Code, Codex, Hermes, OpenClaw, Cursor - [Auth](auth.md) — 1–3 Web logins diff --git a/docs/assets/stars.png b/docs/assets/stars.png deleted file mode 100644 index ff4a9cb..0000000 Binary files a/docs/assets/stars.png and /dev/null differ diff --git a/docs/assets/stars.svg b/docs/assets/stars.svg deleted file mode 100644 index f10bcf8..0000000 --- a/docs/assets/stars.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - GitHub stars - 5 - - - - - 2026-08-31 - 2026-09-22 - diff --git a/docs/guide.md b/docs/guide.md new file mode 100644 index 0000000..8485f0f --- /dev/null +++ b/docs/guide.md @@ -0,0 +1,838 @@ +# Full guide + +The short version is in the [README](../README.md). + +## Contents + +- [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 + +```bash +git clone --branch stable https://github.com/dekrezz/FreeDeepseekAPI.git +cd FreeDeepseekAPI +npm run auth +npm start +``` + +`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`. + +`npm start` opens the launch menu: + +- 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 +``` + +By default only this computer can reach it. To publish it on a network, set an address and a proxy key: + +```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`. + +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. + +--- + +## Rootless Podman + +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 +``` + +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`. + +You cannot pin a client to a chosen file. The proxy picks a free login. + +```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 | +|---|---| +| `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](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. + +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. + +### 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. + +```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. + +### Images + +PNG, JPEG, WebP, and GIF. Up to 10 images, 20 MiB decoded each. The JSON body defaults to 30 MiB. + +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. + +OpenAI Chat Completions uses `image_url`. Responses uses `input_image`. Anthropic uses an `image` block with base64. See [docs/api.md](api.md). + +--- + +## 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](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. + +--- + +## 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. + +If a call stops working: + +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). + +## Documentation + +- [Authentication](auth.md) +- [Agent setup](agents.md) +- [Models](models.md) +- [HTTP API](api.md) diff --git a/docs/ru/README.md b/docs/ru/README.md index fbf0056..a77dde4 100644 --- a/docs/ru/README.md +++ b/docs/ru/README.md @@ -1,5 +1,6 @@ # Документация +- [Полное руководство](guide.md) — установка, сессии, пул, примеры запросов, ошибки - [Модели](models.md) — DeepSeek-V4.1-Flash. Родной поиск chat.deepseek.com включён по умолчанию, `-thinking` это DeepThink, `-nosearch` выключает поиск - [Агенты одним нажатием](agents.md) - [Авторизация](auth.md) — несколько Web-логинов diff --git a/docs/ru/guide.md b/docs/ru/guide.md new file mode 100644 index 0000000..5b84ba1 --- /dev/null +++ b/docs/ru/guide.md @@ -0,0 +1,838 @@ +# Полное руководство + +Короткая версия в [README](../../README.ru.md). + +## Навигация + +- [Что это даёт](#что-это-даёт) +- [Возможности](#возможности) +- [Быстрый старт](#быстрый-старт) +- [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 + +--- + +## Быстрый старт + +```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` открывает меню запуска: + +- запустить 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 +``` + +По умолчанию он доступен только с этого компьютера. Чтобы открыть его в сеть, задайте адрес и отдельный ключ proxy: + +```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. + +--- + +## 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 +``` + +Как ведёт себя пул: + +- новый агент получает свободный логин по кругу; +- этот логин остаётся приклеен к сессии; +- `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](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-токенов не отдаёт. + +Ход с вызовом инструмента не приклеивает рассуждение к сообщению. Часть агентов считает любой текст рядом с tool call окончательным ответом и останавливается. + +### Родной веб-поиск + +Родной 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. При выключенном поиске они доходят до агента без изменений. + +### Картинки + +PNG, JPEG, WebP и GIF. До 10 картинок, по 20 МиБ в раскодированном виде. Тело JSON по умолчанию до 30 МиБ. + +Прокси загружает картинку в DeepSeek Web, ждёт конца разбора и потом шлёт id файла. Чужой `file_id` отклоняется. URL должен быть публичным HTTPS. Редиректы на локальные, частные и link-local адреса отклоняются. + +OpenAI Chat Completions использует `image_url`. Responses использует `input_image`. Anthropic использует блок `image` с base64. См. [docs/api.md](../api.md). + +--- + +## Модели + +`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](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 встроенной заглушкой. + +--- + +## Статус проекта + +FreeDeepseekAPI — локальный web-chat proxy. Он зависит от текущего контракта chat.deepseek.com. Когда контракт меняется, может понадобиться поправить auth или тело запроса. + +Если вызов перестал работать: + +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). + +## Документация + +- [Авторизация](auth.md) +- [Агенты](agents.md) +- [Модели](models.md) +- [HTTP API](../api.md) diff --git a/docs/zh/README.md b/docs/zh/README.md index b12b8f3..6d06b07 100644 --- a/docs/zh/README.md +++ b/docs/zh/README.md @@ -1,5 +1,6 @@ # 文档 +- [完整指南](guide.md) — 安装、会话、账号池、请求示例、错误 - [模型](models.md) — DeepSeek-V4.1-Flash。chat.deepseek.com 的原生搜索默认打开,`-thinking` 是 DeepThink,`-nosearch` 关闭搜索 - [一键接入 Agent](agents.md) - [鉴权](auth.md) — 多个 Web 登录 diff --git a/docs/zh/guide.md b/docs/zh/guide.md new file mode 100644 index 0000000..6b11681 --- /dev/null +++ b/docs/zh/guide.md @@ -0,0 +1,838 @@ +# 完整指南 + +简短版本见 [README](../../README.zh.md)。 + +## 目录 + +- [能做什么](#能做什么) +- [功能](#功能) +- [快速开始](#快速开始) +- [Windows](#windows) +- [Linux / Chromium](#linux--chromium) +- [VPS / 无界面](#vps--无界面) +- [Rootless Podman](#rootless-podman) +- [Diagnostics / doctor](#diagnostics--doctor) +- [会话复用](#会话复用) +- [多账号池](#多账号池) +- [账号面板](#账号面板) +- [更新](#更新) +- [登录](#登录) +- [编程代理](#编程代理) +- [检查是否正常](#检查是否正常) +- [请求示例](#请求示例) + - [Chat Completions](#chat-completions) + - [DeepThink](#deepthink) + - [自带网页搜索](#自带网页搜索) + - [Streaming](#streaming) + - [Anthropic Messages](#anthropic-messages) + - [OpenAI Responses](#openai-responses) + - [工具调用](#工具调用) + - [图片](#图片) +- [模型](#模型) +- [Endpoints](#endpoints) +- [环境变量](#环境变量) +- [错误](#错误) +- [Open WebUI](#open-webui) +- [重新登录](#重新登录) +- [测试](#测试) +- [项目状态](#项目状态) + +--- + +## 能做什么 + +- 把 DeepSeek Web 当成一个本地 API。 +- 接到 Open WebUI 和其他 OpenAI 兼容客户端。 +- 返回普通 JSON,或者 SSE 流。 +- 用 `-thinking` 打开 DeepThink,并从 `reasoning_content` 读出推理。 +- 用 Anthropic Messages 接 Claude Code。 +- 用 OpenAI Responses 接 Codex。 +- 每个代理或 `user` 各用一个独立的 Web 会话。 +- 一次回复里交出最多八个本地工具调用。 +- 上网用 DeepSeek 自己的搜索,不用 bash,也不用 harness 的 websearch。 + +## 功能 + +- **OpenAI 兼容 API:** `POST /v1/chat/completions` +- **Anthropic 兼容垫片:** `POST /v1/messages` +- **OpenAI Responses 垫片:** `POST /v1/responses` +- **流式输出:** SSE,以及非流式 JSON +- **DeepThink:** 选了 `-thinking` 时返回 `reasoning_content` +- **自带搜索:** chat.deepseek.com 的 Web Search,默认打开。用 `-nosearch` 或 `"web_search": false` 关闭 +- **工具调用:** OpenAI、Anthropic 和 Responses 的工具,可以一批一起返回 +- **模型能力:** `GET /v1/model-capabilities` +- **代理会话:** 一个 `x-agent-session` 或 `user` 对应一个 DeepSeek 聊天 +- **会话恢复:** 空回复、坏掉的工具调用和超时都留在原来的聊天里 +- **零依赖:** Node.js 18+,没有 npm 包 +- **许可证:** Apache-2.0 + +--- + +## 快速开始 + +```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` 打开启动菜单: + +- 启动代理 +- 启动代理并打开控制台(或 `npm run dashboard`) +- 用 Chrome 登录 +- 导入 auth 文件或浏览器 cookie 导出 +- 列出 DeepSeek-V4.1-Flash 的模型 id +- 退出 + +无菜单,适合无界面和 CI: + +```bash +NON_INTERACTIVE=1 npm start +# 或 +SKIP_ACCOUNT_MENU=1 npm start +``` + +服务监听: + +```text +http://127.0.0.1:9655 +``` + +默认只接受本机连接。要暴露到网络,必须同时指定地址和单独的代理密钥: + +```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。界面开在别的地址时,把精确 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 上该装到哪里,而不是一长串原始堆栈。 + +--- + +## 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 / 无界面 + +更稳的做法是不在服务器上开 Chrome。 + +1. 在有图形界面和 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. 不带菜单启动代理: + +```bash +NON_INTERACTIVE=1 npm start +``` + +浏览器导出的 cookie 也可以,但必须同时带上 token: + +```bash +DEEPSEEK_TOKEN="" npm run auth:import -- --input ./cookies.json +``` + +`deepseek-auth.json` 就是你的 DeepSeek Web 登录。不要提交,不要贴进聊天,权限保持 `0600`。 + +没有密码登录命令。代理不问 DeepSeek 密码,也不会把密码写到磁盘。登录方式只有 Chrome、现成的 auth 文件,或者 cookie 导出加上 token。 + +--- + +## Rootless Podman + +容器只负责跑代理。登录在宿主机上用 `npm run auth` 完成。登录脚本和 `deepseek-auth.json` 不会打进镜像。 + +用普通用户跑 Podman,不要 root。 + +1. 构建镜像: + +```bash +podman build --tag localhost/free-deepseek-api:local --file Containerfile . +``` + +2. 把 DeepSeek 登录和单独的代理密钥放进 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`。前面没有防火墙时,不要拿掉这个地址。 + +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` 在没有任何 DeepSeek 登录能接聊天时返回 `503`。 + +```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 +``` + +轮换登录或代理密钥时,换掉对应 secret,再重建容器。 + +--- + +## Diagnostics / doctor + +```bash +npm run doctor +# 不向 DeepSeek 发网络请求: +npm run doctor -- --offline +``` + +`doctor` 检查: + +- 是否存在 `deepseek-auth.json` 或 `DEEPSEEK_AUTH_DIR`; +- JSON 是否能解析; +- 是否有 `token`、`cookie` 和 `wasmUrl`; +- macOS 和 Linux 上权限是否为 `0600`; +- 普通运行时,DeepSeek 的 PoW 端点是否还能用。 + +看到 `data.biz_data is null`、`fetch failed`、`401`、`403`、`429`,或者代理看不到模型时,先跑 `npm run doctor`。 + +--- + +## 会话复用 + +FreeDeepseekAPI 不会为每一个 HTTP 请求新开一个 DeepSeek 聊天。 + +- 同一个 `x-agent-session`、`session` 或 `user` 对应同一个 DeepSeek 聊天。 +- 已经有会话时,代理用 `parent_message_id` 接着往下写。 +- 固定的 system prompt 和工具列表只向上游发 **一次**。之后 OpenCode、Claude Code 和 Codex 只发新的用户回合或工具结果。 +- system prompt 变了会再发一次。 +- 空回复、坏掉的工具调用和超时 **留在** 当前聊天。以前这种情况会新开一个聊天,再把整段提示重新发出去。现在不会。 +- 只有这些情况才开新聊天:还没有会话、链到了 100 条消息、聊天超过 2 小时、DeepSeek 说提示太长,或者你调用了 `/reset-session`。 +- 发出去之前,长提示会被裁到 `DEEPSEEK_MAX_PROMPT_CHARS`(默认 80 000 个字符)。任务开头、最新的工具结果和工具提醒会留下来。 +- 客户端已经带了多轮历史时,代理不会再把自己的恢复历史贴一遍。 +- 空回复最多重试 `DEEPSEEK_MAX_RETRIES` 次(默认 2)。每次重试都用更短的上下文;聊天还在的话,就继续留在里面。 + +显式指定代理: + +```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 那边。会话复用只是在当前链还能用的时候,不再另开一个。 + +正文恰好是 `/new` 的消息会重置这个代理的远程聊天,并且不会发给模型。 + +--- + +## 多账号池 + +同一个登录上如果有两个聊天同时发出请求,DeepSeek 可能会把这个登录封几天。池的规则是:每个登录同一时刻只跑一个聊天。第二个请求会等,不会叠上去。 + +Sticky 的意思是:活着的聊天中间,代理不会换账号,除非该登录被限流或失去授权。登录收到 `401`、`403`,或被 DeepSeek 限流时,会进入冷却,旧的远程会话会被清掉。被限流的请求不会失败:它会立刻换到另一个可用登录,在新聊天里带上完整对话记录。`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 +``` + +池怎么工作: + +- 新代理按轮转拿到一个空闲登录; +- 这个登录会粘在该会话上; +- `401`、`403` 和限流让登录进入冷却(`DEEPSEEK_ACCOUNT_COOLDOWN_MS`,默认 10 分钟)。限流包括 HTTP `429`、HTTP `400` 或 JSON 响应里的"请求过于频繁"类消息(例如 `Слишком частые сообщения`),以及 DeepSeek 流里 `finish_reason: rate_limit_reached` 的提示。DeepSeek 给了 `Retry-After` 时会遵守; +- 被限流的请求换到另一个可用登录,开新聊天。只有所有登录都在冷却时,客户端才会收到 `429 rate_limit`; +- 其他 `400` 错误不会触发冷却,聊天在同一个登录上重建; +- 两个请求、两个空闲登录时,会分到不同账号; +- 同一个 `x-agent-session` 重叠时,会等自己的登录(`DEEPSEEK_ACCOUNT_LOCK_WAIT_MS`,默认 120 秒); +- 所有登录都忙时,请求等待 sticky 的那个,或者最久没用的那个; +- OpenCode 的会话头请求在本地回答,不占用登录; +- `/health` 展示账号状态,但不给出 auth 文件路径和文件名; +- `/dashboard` 列出所有登录,可以暂停、恢复、清除冷却,以及不重启就重新读取 auth 文件(见[账号面板](#账号面板)); +- auth 文件权限应为 `0600`。 + +不能把某个客户端钉死到某个文件。代理自己挑空闲登录。 + +```bash +DEEPSEEK_ACCOUNT_COOLDOWN_MS=600000 npm start +``` + +--- + +## 账号面板 + +打开 `http://127.0.0.1:9655/dashboard`。这里列出每个登录的状态(`ready`、`busy`、`cooldown`、`disabled`、`no_credentials`)、冷却倒计时和原因、连续失败次数与总失败次数、最近一次上游错误以及用量。可以在这里: + +- **Disable / Enable**:暂停或恢复一个登录。这是运行时暂停:进行中的请求会做完,重启后失效。持久开关是 auth 文件里的 `"enabled": false`;文件里禁用的登录不能在面板里启用。 +- **Clear cooldown**:让冷却中的登录立刻回到轮转。 +- **Reload accounts**:重新读取 auth 文件。新文件会加入,删掉的文件会移除。保留下来的登录保持冷却和计数。token 或 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 }`。文件里是 `"enabled": false` 时返回 `409 disabled_in_file` | +| `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/*` 需要和 `/v1/*` 相同的 bearer。页面会询问密钥,只保存在当前标签页的 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 响应里不会有 token、cookie、`hif_*` 值或 auth 文件名。 + +容器镜像包含面板。使用 `--read-only` 时,需要写 auth 文件的操作(添加、重命名、删除、恢复)会返回 `500 auth_file_write_failed`;暂停、恢复和清除冷却照常可用。 + +--- + +## 更新 + +DeepSeek 会不时调整网页聊天,FreeDeepseekAPI 会跟着更新。请让你的副本保持最新。 + +两个渠道,都是 GitHub 上的分支: + +| 渠道 | 内容 | +|---|---| +| `stable` | 经过检查后的版本。默认渠道,快速开始克隆的就是它。 | +| `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` | 用 Chrome 抓取 token 和 cookies | +| `npm run auth:import` | 导入 `deepseek-auth.json` 或 cookie 导出 | +| `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`,它会被写进代理配置。 + +安装只是把 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 | `integrations/cursor/` 里的片段和启动脚本 | 不改编辑器设置 | + +`--model` 始终是 DeepSeek-V4.1-Flash,并打开 chat.deepseek.com 的自带搜索。`-thinking` 打开 DeepThink。`-nosearch` 关闭搜索,这时编程代理会保留自己的联网工具。旧的 `-search` id 等同于去掉这个后缀的 id。 + +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。 + +从备份恢复: + +```bash +node scripts/setup-agents.js --restore ~/.freedeepseek-api/backups/ +``` + +两个代理同时跑,需要 `accounts/` 里有两个 Web 登录。细节见 [docs/zh/agents.md](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` 返回四个 DeepSeek-V4.1-Flash id。 + +--- + +## 请求示例 + +### 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.completion_tokens_details.reasoning_tokens` + +`reasoning_tokens` 是按抽出来的 DeepThink 文本估算的。网页流不会单独给出官方的推理 token 用量。 + +带工具调用的回合不会把推理贴到那条消息上。有些代理把工具调用旁边的任何文字都当成最终答案,然后停下来。 + +### 自带网页搜索 + +chat.deepseek.com 的原生 Web Search 默认打开,所有模型 id 都一样。网上的问题走这个搜索。不要让模型去用 bash、curl,或者 harness 的 `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`,或者用以 `-nosearch` 结尾的 id: + +```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:在 `-nosearch` id 上发送 `"web_search": true` 会重新打开搜索。这个字段适用于 `/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,以及带 DeepThink 的 DeepSeek-V4.1-Flash,所以旧的 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 走的就是这条路由。安装之后: + +```bash +codex --profile freedeepseek +``` + +### 工具调用 + +代理接受 OpenAI 的 `tools`、Anthropic 的 `tools`,以及 Responses 的 function tools。 + +DeepSeek Web 没有真正的 tool call 数组。代理把工具列表写进提示,再把模型回复解析回 OpenAI 的 `tool_calls`。这些形式都能认: + +- `{"tool_call":{"name":"...","arguments":{...}}}` +- `{"tool_calls":[{"name":"...","arguments":{...}}]}`,一次最多 8 个互不依赖的调用 +- `TOOL_CALL:` 后面跟一个 JSON 对象 +- 围栏里的 JSON,带 `tool_call`、`tool_calls` 或 `function_call` 信封 +- `...` +- DeepSeek DSML,包括带双竖线的网页变体 + +`execute_code` 和 `web_search` 是 DeepSeek 自己的工具。它们不会在你的电脑上执行。如果它们和真正的本地工具(比如 `read_file`)写在一起,它们会被丢掉,本地调用会留下来。没写完的工具块不会执行。代理会再要一次严格 JSON。还是坏的话,这一回合返回 `502 malformed_tool_call`,聊天保持打开。 + +自带搜索打开时,harness 的 `websearch`、`webfetch` 和 `WebFetch` 会被拿掉,要查网上的事,用 chat.deepseek.com 自带的搜索。搜索关闭时,这些工具会原样交给编程代理。 + +### 图片 + +支持 PNG、JPEG、WebP 和 GIF。最多 10 张,解码后每张 20 MiB。JSON 正文默认上限 30 MiB。 + +代理把图片上传到 DeepSeek Web,等解析结束,再发送文件 id。别人的 `file_id` 会被拒绝。URL 必须是公开的 HTTPS。跳转到本机、私网或 link-local 地址会被拒绝。 + +OpenAI Chat Completions 用 `image_url`。Responses 用 `input_image`。Anthropic 用带 base64 的 `image` 块。见 [docs/api.md](../api.md)。 + +--- + +## 模型 + +`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 的搜索开关。 + +旧的 `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/zh/models.md](models.md)。 + +--- + +## Endpoints + +| 方法 | 路径 | 作用 | +|---|---|---| +| `GET` | `/health` | 进程是否活着。没有代理密钥,或 bearer 匹配时,还会带账号状态 | +| `GET` | `/readyz` | 只有登录能接请求时才是 `200` | +| `GET` | `/dashboard` | 账号面板(静态页面) | +| `GET` | `/admin/accounts` | 账号池和每个登录的状态。见[账号面板](#账号面板) | +| `POST` | `/admin/accounts//{disable,enable,clear-cooldown}` | 暂停、恢复或清除某个登录的冷却 | +| `POST` | `/admin/accounts/reload` | 不重启重新读取 auth 文件 | +| `GET` | `/v1/models` | 四个 DeepSeek-V4.1-Flash id | +| `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 又没有代理密钥时会打印警告 | +| `PORT` | `9655` | 端口 | +| `TLS_CERT_FILE` / `TLS_KEY_FILE` | 关闭 | PEM 证书和私钥。两者都设置且可读时,代理以 HTTPS 提供服务;未设置则保持 HTTP。loopback 不需要 TLS。绑到非 loopback 又没设置它们时,会警告登录导入和 Authorization 头是明文 | +| `PROXY_API_KEY` | 关闭 | 设置后,`/v1/*` 和 `/admin/*` 必须带 bearer | +| `REQUIRE_PROXY_API_KEY` | 关闭 | 没有密钥就拒绝启动。容器里是打开的 | +| `PROXY_CORS_ORIGINS` | loopback | 额外允许的精确浏览器 origin | +| `PROXY_ADMIN_ALLOW_REMOTE` | 关闭 | 设为 `1` 时,即使没有 `PROXY_API_KEY`,`/admin/*` 也接受非 loopback 客户端 | +| `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` | 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` | 用 `GET /v1/models` 里的 id | +| 400 | `context_length_exceeded` | 压缩之后提示仍然太长 | +| 401 | `authentication_error` | 代理密钥不对 | +| 403 | `admin_forbidden` | 没有密钥时,从非 loopback 或经过代理的客户端访问 `/admin/*`。见[账号面板](#账号面板) | +| 429 | `concurrent_chat_blocked` | 等待忙碌登录超时。再加一个登录,或稍后重试 | +| 429 | `rate_limit` | 所有登录都在冷却(限流或登录失效)。遵守 `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 + +同一台机器上、Docker 里的 Open WebUI,Base URL 用: + +```text +http://host.docker.internal:9655/v1 +``` + +本机、不用 Docker: + +```text +http://127.0.0.1:9655/v1 +``` + +没设 `PROXY_API_KEY` 时,API key 随便填。设了的话,客户端必须发这个密钥。代理会在模型、会话和补全之前检查 bearer。 + +普通回答用 `deepseek-v4-flash`,它带 chat.deepseek.com 的自带搜索;要 DeepThink 用 `deepseek-v4-flash-thinking`;想要不带搜索的回答时用 `-nosearch` id。 + +--- + +## 重新登录 + +```bash +npm run auth +npm start +``` + +DeepSeek 返回 `401` 或 `403`,或者 PoW 失败时,重新登录并替换 `deepseek-auth.json`。 + +这些不会进 git: + +- `deepseek-auth.json` +- `accounts/*.json` +- 登录脚本使用的 Chrome 配置目录 +- `.env` + +--- + +## 测试 + +语法和单元测试,不联网: + +```bash +npm test +``` + +对已经跑起来的代理做在线冒烟测试: + +```bash +BASE_URL=http://127.0.0.1:9655 MODEL=deepseek-v4-flash npm run test:live +``` + +`npm test` 对入口跑 `node --check`,再对 `tests/unit.test.js` 和 `tests/account-failover.test.js` 跑 `node --test`。它不会请求 DeepSeek:账号切换测试的所有上游请求都由进程内的模拟服务应答。 + +--- + +## 项目状态 + +FreeDeepseekAPI 是本地网页聊天代理。它依赖 chat.deepseek.com 当前的协议。协议一变,登录或请求体就可能要跟着改。 + +调用突然不行时: + +1. 先更新到最新版本(见[更新](#更新))。 +2. 用 `npm run auth` 重新登录。 +3. 跑 `npm run doctor`。 +4. 看 `GET /v1/model-capabilities`,改用 DeepSeek-V4.1-Flash 的 id。 +5. 同一个聊天还是失败,就调用 `POST /reset-session?agent=` 再试。 +6. 还是不行,多半是 DeepSeek 改了内部 Web API。 + +安全问题请走非公开的 GitHub advisory,不要开公开 issue。见 [SECURITY.md](../../SECURITY.md)。维护者名单见 [CONTRIBUTORS.md](../../CONTRIBUTORS.md)。 + +## 文档 + +- [登录](auth.md) +- [编程代理](agents.md) +- [模型](models.md) +- [HTTP API](../api.md) diff --git a/package.json b/package.json index 801f302..efa337b 100644 --- a/package.json +++ b/package.json @@ -14,7 +14,7 @@ "doctor": "node scripts/doctor.js", "deepseek:auth": "node scripts/deepseek_chrome_auth.js", "setup:agents": "node scripts/setup-agents.js", - "test:syntax": "node --check server.js && node --check lib/pow.js && node --check lib/updater.js && node --check scripts/start.js && node --check scripts/auth.js && node --check scripts/lib/tui-menu.js && node --check scripts/lib/chrome-setup.js && node --check scripts/auth_import.js && node --check scripts/doctor.js && node --check scripts/deepseek_chrome_auth.js && node --check scripts/probe_deepseek_models.js && node --check scripts/setup-agents.js && node --check scripts/render-stars-chart.js && node --check scripts/live_agentic_smoke_tests.mjs && node --check public/dashboard/i18n.js && node --check public/dashboard/core.js && node --check public/dashboard/charts.js && node --check public/dashboard/markdown.js && node --check public/dashboard/status.js && node --check public/dashboard/accounts.js && node --check public/dashboard/usage.js && node --check public/dashboard/requests.js && node --check public/dashboard/settings.js && node --check public/dashboard/glyphfield.js && node --check public/dashboard/chat.js && node --check public/dashboard/agents.js && node --check public/dashboard/app.js", + "test:syntax": "node --check server.js && node --check lib/pow.js && node --check lib/updater.js && node --check scripts/start.js && node --check scripts/auth.js && node --check scripts/lib/tui-menu.js && node --check scripts/lib/chrome-setup.js && node --check scripts/auth_import.js && node --check scripts/doctor.js && node --check scripts/deepseek_chrome_auth.js && node --check scripts/probe_deepseek_models.js && node --check scripts/setup-agents.js && node --check scripts/live_agentic_smoke_tests.mjs && node --check public/dashboard/i18n.js && node --check public/dashboard/core.js && node --check public/dashboard/charts.js && node --check public/dashboard/markdown.js && node --check public/dashboard/status.js && node --check public/dashboard/accounts.js && node --check public/dashboard/usage.js && node --check public/dashboard/requests.js && node --check public/dashboard/settings.js && node --check public/dashboard/glyphfield.js && node --check public/dashboard/chat.js && node --check public/dashboard/agents.js && node --check public/dashboard/app.js", "test:unit": "node --test tests/unit.test.js tests/account-failover.test.js tests/no_tools_regression.test.js tests/parser_delimiter_repair.test.js tests/parser_recovery_boundary.test.js tests/parser_fullwidth_tool_call.test.js tests/parser_bare_call.test.js tests/remote-guard.test.js tests/parser_garbled_dsml.test.js tests/glyph-field.test.js tests/chrome-setup.test.js tests/updater.test.js tests/update-api.test.js tests/agents-api.test.js tests/audit-auth.test.js tests/audit-tooling.test.js tests/audit-dashboard.test.js tests/ipv6-image-guard.test.js tests/wasm-host.test.js", diff --git a/scripts/render-stars-chart.js b/scripts/render-stars-chart.js deleted file mode 100644 index 4a0cbd7..0000000 --- a/scripts/render-stars-chart.js +++ /dev/null @@ -1,121 +0,0 @@ -#!/usr/bin/env node -'use strict'; - -const fs = require('node:fs'); -const path = require('node:path'); - -const ROOT = path.resolve(__dirname, '..'); -const OUT_SVG = path.join(ROOT, 'docs/assets/stars.svg'); -const REPO = process.env.GITHUB_REPOSITORY || 'dekrezz/FreeDeepseekAPI'; -const TOKEN = process.env.GITHUB_TOKEN || process.env.GH_TOKEN || ''; - -function fail(message) { - throw new Error(message); -} - -async function githubJson(url) { - const res = await fetch(url, { - headers: { - Accept: 'application/vnd.github.star+json', - 'User-Agent': 'free-deepseek-api-star-chart', - ...(TOKEN ? { Authorization: `Bearer ${TOKEN}` } : {}), - }, - }); - if (!res.ok) fail(`GitHub ${res.status} ${url}: ${await res.text()}`); - return res.json(); -} - -async function starredAtList() { - const out = []; - for (let page = 1; page <= 100; page += 1) { - const batch = await githubJson( - `https://api.github.com/repos/${REPO}/stargazers?per_page=100&page=${page}`, - ); - if (!Array.isArray(batch) || batch.length === 0) break; - for (const row of batch) { - if (!row.starred_at) fail('stargazers response missing starred_at; Accept header was ignored'); - out.push(row.starred_at); - } - if (batch.length < 100) break; - } - return out.sort(); -} - -function dayKey(iso) { - return iso.slice(0, 10); -} - -function series(createdAt, starredAt) { - const start = dayKey(createdAt); - const end = dayKey(new Date().toISOString()); - const counts = new Map(); - let running = 0; - for (const at of starredAt) { - running += 1; - counts.set(dayKey(at), running); - } - const days = []; - for (let d = new Date(`${start}T00:00:00Z`); d <= new Date(`${end}T00:00:00Z`); d.setUTCDate(d.getUTCDate() + 1)) { - days.push(d.toISOString().slice(0, 10)); - } - if (days.length === 0) days.push(end); - let last = 0; - return days.map((day) => { - if (counts.has(day)) last = counts.get(day); - return { day, count: last }; - }); -} - -function svgChart(points, total) { - const w = 800; - const h = 280; - const padL = 56; - const padR = 24; - const padT = 48; - const padB = 40; - const plotW = w - padL - padR; - const plotH = h - padT - padB; - const maxY = Math.max(1, ...points.map((p) => p.count)); - const xy = (i, count) => { - const x = padL + (points.length === 1 ? plotW : (i / (points.length - 1)) * plotW); - const y = padT + plotH - (count / maxY) * plotH; - return [x, y]; - }; - const d = points - .map((p, i) => { - const [x, y] = xy(i, p.count); - return `${i ? 'L' : 'M'}${x.toFixed(1)},${y.toFixed(1)}`; - }) - .join(' '); - const [lx, ly] = xy(points.length - 1, points[points.length - 1].count); - const start = points[0].day; - const end = points[points.length - 1].day; - return ` - - - GitHub stars - ${total} - - - - - ${start} - ${end} - -`; -} - -async function main() { - const repo = await githubJson(`https://api.github.com/repos/${REPO}`); - const starredAt = await starredAtList(); - const points = series(repo.created_at, starredAt); - const svg = svgChart(points, repo.stargazers_count); - fs.mkdirSync(path.dirname(OUT_SVG), { recursive: true }); - fs.writeFileSync(OUT_SVG, svg); - process.stdout.write(`wrote ${OUT_SVG} (${repo.stargazers_count} stars, ${points.length} days)\n`); -} - -main().catch((err) => { - process.stderr.write(`${err.message}\n`); - process.exit(1); -}); diff --git a/tests/unit.test.js b/tests/unit.test.js index e2733e6..96aa6d6 100644 --- a/tests/unit.test.js +++ b/tests/unit.test.js @@ -462,7 +462,7 @@ test('proxy API key can be loaded from a mounted secret and required explicitly' test('Containerfile keeps the rootless Podman runtime minimal and fail-closed', () => { const containerfile = fs.readFileSync(path.join(ROOT, 'Containerfile'), 'utf8'); const containerignore = fs.readFileSync(path.join(ROOT, '.containerignore'), 'utf8'); - const readme = fs.readFileSync(path.join(ROOT, 'README.md'), 'utf8'); + const guide = fs.readFileSync(path.join(ROOT, 'docs', 'guide.md'), 'utf8'); const copyLines = containerfile .split(/\r?\n/) .map(line => line.trim()) @@ -487,12 +487,12 @@ test('Containerfile keeps the rootless Podman runtime minimal and fail-closed', assert.match(containerignore, /^\*$/m); assert.doesNotMatch(containerignore, /^!.*(?:auth|secret|\.env)/mi); - assert.match(readme, /--publish 127\.0\.0\.1:9655:9655/); - assert.match(readme, /--secret free-deepseek-auth[^\n]*mode=0400/); - assert.match(readme, /--secret free-deepseek-proxy-key[^\n]*mode=0400/); - assert.match(readme, /--read-only/); - assert.match(readme, /--cap-drop=ALL/); - assert.match(readme, /--security-opt=no-new-privileges/); + assert.match(guide, /--publish 127\.0\.0\.1:9655:9655/); + assert.match(guide, /--secret free-deepseek-auth[^\n]*mode=0400/); + assert.match(guide, /--secret free-deepseek-proxy-key[^\n]*mode=0400/); + assert.match(guide, /--read-only/); + assert.match(guide, /--cap-drop=ALL/); + assert.match(guide, /--security-opt=no-new-privileges/); }); test('the files the Containerfile copies are enough to load the server and the dashboard', (t) => {