diff --git a/packages/llm/llm-deepseek/README.i18n.yaml b/packages/llm/llm-deepseek/README.i18n.yaml
index f97a878ebb..9383708908 100644
--- a/packages/llm/llm-deepseek/README.i18n.yaml
+++ b/packages/llm/llm-deepseek/README.i18n.yaml
@@ -21,11 +21,11 @@
en: 6850d08bc091ad23
zh: 2906e6cf1dfed6ce
/deepseek-ai-dsh-llm-deepseek/use-this-package/minimal-configuration:
- en: a6b5568e9fb77387
- zh: d11a620457ade13c
+ en: 6a15f2e0efec4c37
+ zh: 7fb5f1e4a92b01ad
/deepseek-ai-dsh-llm-deepseek/use-this-package/endpoint-and-wire-format:
- en: 2a634ead5b47fe97
- zh: 46f199ee79a8c5dc
+ en: 7f291c1fe8b7305c
+ zh: a01267fadad6246f
/deepseek-ai-dsh-llm-deepseek/use-this-package/account-credentials:
en: d3f232309f4963ef
zh: 2e0ccd028de26f3e
@@ -39,8 +39,8 @@
en: f13f24b504dcfb50
zh: 69b0ed9e2adf3394
/deepseek-ai-dsh-llm-deepseek/use-this-package/failures-and-recovery:
- en: dfad0a2c508142bb
- zh: 874de0579fb54c08
+ en: fa4d01530c47422a
+ zh: 88ae8647ad6455e6
/deepseek-ai-dsh-llm-deepseek/understand-the-implementation:
en: 1598ac8a8bb9b6bf
zh: fdd089c5ae7722cd
diff --git a/packages/llm/llm-deepseek/README.md b/packages/llm/llm-deepseek/README.md
index 62551c4efb..1d0bedef65 100644
--- a/packages/llm/llm-deepseek/README.md
+++ b/packages/llm/llm-deepseek/README.md
@@ -57,7 +57,6 @@ A request selects the route with `provider: deepseek-official`; the model id pas
| `baseURL` | `https://api.deepseek.com/anthropic` | Explicit value, then `$DEEPSEEK_BASE_URL`, then the official root |
| `thinking` | `enabled` | Deployment policy; `disabled` locks every request to `off` |
| `reasoningEffort` | `high` | Default effort: `off`, `low`, `high`, or `max` |
-| `safetyCheck` | `false` | `true` sends `safety_check: {"level": "high"}` on every request so DeepSeek reviews input and output with its [content safety](https://api-docs.deepseek.com/guides/safety) policy |
| `maxTokens` | `256,000` | Per-request output cap; a model's own cap and explicit request values win |
| `defaultContextWindow` | `1,000,000` | Capacity fallback for models without an exact value |
| `models` | V4.1 Flash + V4 Pro | Advisory catalog shown by discovery consumers |
@@ -83,7 +82,7 @@ When [proactive compaction](../../compaction/compaction-basic/README.md#use-this
The official root is `https://api.deepseek.com/anthropic`. An explicit `baseURL` or `$DEEPSEEK_BASE_URL` supplies a Messages-compatible root; the `dsh` launcher accepts that variable from the launching environment or `$DSH_HOME/.env`, never from a project `.env` ([app-boot](../../boot/app-boot/README.md)). Model and Files requests append `/v1/messages` and `/v1/files`, except that an exact final `/v1` segment is reused. Trailing slashes do not change these results. A base URL must use HTTP(S) without credentials, query, or fragment.
-Messages sends text, thinking, tool calls, and tool results as content blocks, reasoning effort as `output_config.effort`, and images as Files references or inline base64. Models declaring `systemPromptUpdate: in-history` retain the initial top-level system and send new system snapshots after their corresponding user/tool-result turn; undeclared models use the latest snapshot as the top-level system. Replay metadata preserves the model and thinking signatures. Invalid replay metadata emits a warning and omits signatures while retaining text and tool history. Model entries may declare `toolUpdate: addition-only` or `in-history`; the default `deepseek-flash` entry declares `addition-only`. Projected developer tool updates become system-role `tool_addition` and `tool_removal` blocks referencing declared names, and deferred declarations carry `defer_loading`. Requests containing those blocks send the `mid-conversation-tool-changes-2026-07-01` beta header. Messages omits empty assistant text blocks and skips assistant messages left without content, including saved history from other protocols. The stored Session content remains intact.
+Every request sends `safety_check: {"level": "high"}`, so DeepSeek reviews input and output under its [content safety](https://api-docs.deepseek.com/guides/safety) policy; deployments cannot turn it off. Messages sends text, thinking, tool calls, and tool results as content blocks, reasoning effort as `output_config.effort`, and images as Files references or inline base64. Models declaring `systemPromptUpdate: in-history` retain the initial top-level system and send new system snapshots after their corresponding user/tool-result turn; undeclared models use the latest snapshot as the top-level system. Replay metadata preserves the model and thinking signatures. Invalid replay metadata emits a warning and omits signatures while retaining text and tool history. Model entries may declare `toolUpdate: addition-only` or `in-history`; the default `deepseek-flash` entry declares `addition-only`. Projected developer tool updates become system-role `tool_addition` and `tool_removal` blocks referencing declared names, and deferred declarations carry `defer_loading`. Requests containing those blocks send the `mid-conversation-tool-changes-2026-07-01` beta header. Messages omits empty assistant text blocks and skips assistant messages left without content, including saved history from other protocols. The stored Session content remains intact.
### Account credentials
@@ -120,7 +119,7 @@ Configuration accepts Messages only and has no `protocol` field. If resolution r
Successful Files responses must contain valid JSON. JSON decoding failures from upload, list, retrieve, and delete throw `INVALID_RESPONSE` with the operation and HTTP status in the message, the status in `LlmError.failure`, and the original parser error as `cause`. Body-read transport and cancellation errors retain their identity.
-Non-2xx responses fail with stable codes: `AUTH` (401/403), `QUOTA`, `RATE_LIMIT`, `CONTEXT_WINDOW_EXCEEDED`, `INVALID_REQUEST`, `SERVER`, and `HTTP_` otherwise; pre-response transport failures throw `TRANSPORT`, caller aborts throw `ABORTED`, and stream-idle expiry throws `TIMEOUT`. A request-extension field collision, or a rejected preparation from a directly supplied `prepareExtensions`, fails with `REQUEST_EXTENSION` and appends the cause chain to the message; a post-2xx acceptance failure is logged and the response still streams. A normalized-image rejection names every plausible attachment and its durable position when the provider does not identify a file id. Stale-file rejection removes every named mapping (or every mapping used by the attempt) in one upload-index update and permits one replacement model request. Protocol violations throw `STREAM_CLOSED` or `MALFORMED_RESPONSE`, and a terminal `stop` with no content blocks becomes `EMPTY_RESPONSE`, which the default retry policy retries. A `refusal` stop reason, which the safety check or server-side web tools can return, fails with `CONTENT_REFUSED` plus any provider explanation, such as blocked images, and is not retried; text streamed before it stays out of the conversation history. An input rejected before streaming arrives as HTTP 400 and fails with `INVALID_REQUEST`. A request on the official route without an API key fails with `MISSING_CREDENTIAL`, and a malformed credential fails with `INVALID_CREDENTIAL` naming the reference to fix — never any part of the key.
+Non-2xx responses fail with stable codes: `AUTH` (401/403), `QUOTA`, `RATE_LIMIT`, `CONTEXT_WINDOW_EXCEEDED`, `INVALID_REQUEST`, `SERVER`, and `HTTP_` otherwise; pre-response transport failures throw `TRANSPORT`, caller aborts throw `ABORTED`, and stream-idle expiry throws `TIMEOUT`. A request-extension field collision, or a rejected preparation from a directly supplied `prepareExtensions`, fails with `REQUEST_EXTENSION` and appends the cause chain to the message; a post-2xx acceptance failure is logged and the response still streams. A normalized-image rejection names every plausible attachment and its durable position when the provider does not identify a file id. Stale-file rejection removes every named mapping (or every mapping used by the attempt) in one upload-index update and permits one replacement model request. Protocol violations throw `STREAM_CLOSED` or `MALFORMED_RESPONSE`, and a terminal `stop` with no content blocks becomes `EMPTY_RESPONSE`, which the default retry policy retries. A `refusal` stop reason, which the safety check or server-side web tools can return, reports the billed usage, then fails with `CONTENT_REFUSED` plus any provider explanation, such as blocked images; the default retry policy does not retry it, and text streamed before it stays out of the conversation history. An input rejected before streaming arrives as HTTP 400 and fails with `INVALID_REQUEST`. A request on the official route without an API key fails with `MISSING_CREDENTIAL`, and a malformed credential fails with `INVALID_CREDENTIAL` naming the reference to fix — never any part of the key.
Provider plugins own catalog availability. While its API key resolves, the API-key route serves its configured `models`, or the official model listing while `models` is the built-in catalog on the official endpoint; the account route serves its account listing while signed in (see the [API-key](../llm-deepseek-api-key/README.md) and [account](../llm-deepseek-account/README.md) providers). The transport supplies the bundled catalog, the catalog-entry field schemas, and capability resolution, plus the listing machinery both routes share: `requestModelListing`, the credential-scoped `ModelListingCache` (owned by `createModelListingCache` for automatic refresh, notifications, and plugin cleanup), and `resolveListedCatalog` with its client-version gate, listed badges, and `refuseListedModel`; `catalogModelInfo` attaches a listed badge to the advertised entry. Badge text rejects controls, Unicode line separators, bidi controls, and strings made only of whitespace or default-ignorable characters; joined emoji remain valid. A provider may also supply `connect(signal)`, which resolves the connection for exact-model lookups and prepared calls after provider-owned work such as a catalog load, and `admit(connection, model)`, which refuses a model before network I/O.
diff --git a/packages/llm/llm-deepseek/README.zh.md b/packages/llm/llm-deepseek/README.zh.md
index fa9e55bc1d..79b3b4147c 100644
--- a/packages/llm/llm-deepseek/README.zh.md
+++ b/packages/llm/llm-deepseek/README.zh.md
@@ -57,7 +57,6 @@ kind: "package-reference"
| `baseURL` | `https://api.deepseek.com/anthropic` | 显式值优先,其次为 `$DEEPSEEK_BASE_URL`,最后为官方根地址 |
| `thinking` | `enabled` | 部署策略;`disabled` 把所有请求锁定为 `off` |
| `reasoningEffort` | `high` | 默认强度:`off`、`low`、`high` 或 `max` |
-| `safetyCheck` | `false` | `true` 时每个请求发送 `safety_check: {"level": "high"}`,由 DeepSeek 按其[模型内容安全](https://api-docs.deepseek.com/guides/safety)策略审核输入与输出 |
| `maxTokens` | `256,000` | 单次请求输出上限;模型自身上限与显式请求值优先 |
| `defaultContextWindow` | `1,000,000` | 无精确值模型的容量回退 |
| `models` | V4.1 Flash + V4 Pro | 供发现消费方查看的建议性目录 |
@@ -83,7 +82,7 @@ kind: "package-reference"
官方根地址为 `https://api.deepseek.com/anthropic`。显式 `baseURL` 或 `$DEEPSEEK_BASE_URL` 提供兼容 Messages 的根地址;`dsh` 启动器从启动环境或 `$DSH_HOME/.env` 接受该变量,绝不从项目 `.env` 接受([app-boot](../../boot/app-boot/README.zh.md))。模型与 Files 请求分别追加 `/v1/messages` 和 `/v1/files`,但末尾严格匹配的 `/v1` 路径段会直接复用。末尾斜线不改变这些结果。基址必须使用 HTTP(S),且不含凭据、查询或片段。
-Messages 以内容块发送文本、思考、工具调用和工具结果,以 `output_config.effort` 发送推理强度,并以 Files 引用或内联 base64 发送图片。声明 `systemPromptUpdate: in-history` 的模型保留初始顶层 system,在对应 user/tool-result 轮次之后发送新的 system 快照;未声明能力时,使用最新快照作为顶层 system。回放元数据保留模型与思考签名。无效的回放元数据产生警告并省略签名,不丢弃文本或工具历史。 模型条目可声明 `toolUpdate: addition-only` 或 `in-history`;默认 `deepseek-flash` 条目声明 `addition-only`。投影后的 developer 工具更新转换为 system 角色的 `tool_addition` 和 `tool_removal` 块,引用已声明名称,延迟声明携带 `defer_loading`。包含这些块的请求发送 `mid-conversation-tool-changes-2026-07-01` beta 请求头。 Messages 会省略 assistant 的空文本块,并跳过转换后没有内容的 assistant 消息,包括其他协议保存的历史。已存储的 Session 内容保持原样。
+每个请求都发送 `safety_check: {"level": "high"}`,由 DeepSeek 按其[模型内容安全](https://api-docs.deepseek.com/guides/safety)策略审核输入与输出;部署无法关闭。Messages 以内容块发送文本、思考、工具调用和工具结果,以 `output_config.effort` 发送推理强度,并以 Files 引用或内联 base64 发送图片。声明 `systemPromptUpdate: in-history` 的模型保留初始顶层 system,在对应 user/tool-result 轮次之后发送新的 system 快照;未声明能力时,使用最新快照作为顶层 system。回放元数据保留模型与思考签名。无效的回放元数据产生警告并省略签名,不丢弃文本或工具历史。 模型条目可声明 `toolUpdate: addition-only` 或 `in-history`;默认 `deepseek-flash` 条目声明 `addition-only`。投影后的 developer 工具更新转换为 system 角色的 `tool_addition` 和 `tool_removal` 块,引用已声明名称,延迟声明携带 `defer_loading`。包含这些块的请求发送 `mid-conversation-tool-changes-2026-07-01` beta 请求头。 Messages 会省略 assistant 的空文本块,并跳过转换后没有内容的 assistant 消息,包括其他协议保存的历史。已存储的 Session 内容保持原样。
### 账号凭据
@@ -120,7 +119,7 @@ Files 模式通过 `maxRequestFilesBytes` 与 `maxImagesPerRequest` 限制保留
成功的 Files 响应必须包含有效 JSON。上传、列举、获取和删除操作的 JSON 解码失败抛出 `INVALID_RESPONSE`,消息包含操作名称与 HTTP 状态,`LlmError.failure` 保留该状态,`cause` 保留原始解析错误。读取响应体时的传输和取消错误保留其原有身份。
-非 2xx 响应以稳定 code 失败:`AUTH`(401/403)、`QUOTA`、`RATE_LIMIT`、`CONTEXT_WINDOW_EXCEEDED`、`INVALID_REQUEST`、`SERVER` 以及其他情况的 `HTTP_`;响应前传输失败抛出 `TRANSPORT`,调用方中止抛出 `ABORTED`,流空闲超时抛出 `TIMEOUT`。请求扩展字段冲突,或直接提供的 `prepareExtensions` 拒绝准备时,使用 `REQUEST_EXTENSION` 失败,并在消息中附上原因链;2xx 后接受失败只记录告警,响应仍会继续流式返回。当提供方未指出 file id 时,规范化图片拒绝会列出所有可能附件及其持久位置。陈旧文件拒绝会在一次上传索引更新中删除全部点名映射(或该次尝试使用的全部映射),并允许一次替换模型请求。协议违规抛出 `STREAM_CLOSED` 或 `MALFORMED_RESPONSE`;不带内容块的终止 `stop` 变成 `EMPTY_RESPONSE`,默认重试策略会重试它。安全审核或服务端联网工具返回的 `refusal` 停止原因以 `CONTENT_REFUSED` 失败并附带提供方说明(如被拦截的图片),且不重试;此前已流式输出的文本不进入对话历史。流式输出前被拒绝的输入以 HTTP 400 返回,并以 `INVALID_REQUEST` 失败。官方路由缺少 API Key 的请求以 `MISSING_CREDENTIAL` 失败;格式错误的凭据以 `INVALID_CREDENTIAL` 失败,并点名需要修复的引用——绝不包含密钥的任何部分。
+非 2xx 响应以稳定 code 失败:`AUTH`(401/403)、`QUOTA`、`RATE_LIMIT`、`CONTEXT_WINDOW_EXCEEDED`、`INVALID_REQUEST`、`SERVER` 以及其他情况的 `HTTP_`;响应前传输失败抛出 `TRANSPORT`,调用方中止抛出 `ABORTED`,流空闲超时抛出 `TIMEOUT`。请求扩展字段冲突,或直接提供的 `prepareExtensions` 拒绝准备时,使用 `REQUEST_EXTENSION` 失败,并在消息中附上原因链;2xx 后接受失败只记录告警,响应仍会继续流式返回。当提供方未指出 file id 时,规范化图片拒绝会列出所有可能附件及其持久位置。陈旧文件拒绝会在一次上传索引更新中删除全部点名映射(或该次尝试使用的全部映射),并允许一次替换模型请求。协议违规抛出 `STREAM_CLOSED` 或 `MALFORMED_RESPONSE`;不带内容块的终止 `stop` 变成 `EMPTY_RESPONSE`,默认重试策略会重试它。安全审核或服务端联网工具返回的 `refusal` 停止原因先报告已计费用量,再以 `CONTENT_REFUSED` 失败并附带提供方说明(如被拦截的图片);默认重试策略不重试它,此前已流式输出的文本不进入对话历史。流式输出前被拒绝的输入以 HTTP 400 返回,并以 `INVALID_REQUEST` 失败。官方路由缺少 API Key 的请求以 `MISSING_CREDENTIAL` 失败;格式错误的凭据以 `INVALID_CREDENTIAL` 失败,并点名需要修复的引用——绝不包含密钥的任何部分。
提供方插件负责目录可用性:API key 路由在能解析到 API key 时提供配置中的 `models`,在官方端点上且 `models` 为内置目录时改为提供官方模型列表;账号路由在登录时提供账号的模型列表(见 [API key](../llm-deepseek-api-key/README.zh.md) 与[账号](../llm-deepseek-account/README.zh.md)提供方)。传输层提供内置目录、目录条目字段的 schema 和能力解析,以及两条路由共用的列表机制:`requestModelListing`、按凭据区分的 `ModelListingCache`(由 `createModelListingCache` 持有,负责自动刷新、通知与插件清理),以及带客户端版本门控和列表角标的 `resolveListedCatalog` 与 `refuseListedModel`;`catalogModelInfo` 把列表角标附到公布的条目上。角标文字拒绝控制字符、Unicode 行分隔符、双向控制符及仅由空白或默认可忽略字符组成的字符串,组合 emoji 仍有效。提供方还可以提供 `connect(signal)`:在提供方自己的工作(例如加载目录)完成后,为精确模型查询和预备调用解析连接;以及 `admit(connection, model)`:在网络请求之前拒绝某个模型。
diff --git a/packages/llm/llm-deepseek/src/config.ts b/packages/llm/llm-deepseek/src/config.ts
index dbd6f89b00..630ccea010 100644
--- a/packages/llm/llm-deepseek/src/config.ts
+++ b/packages/llm/llm-deepseek/src/config.ts
@@ -23,8 +23,6 @@ export interface Config {
thinking: Volatile<'enabled' | 'disabled' | undefined>
/** Default thinking effort (default `high`); `off` disables thinking per request. */
reasoningEffort: Volatile<'off' | 'low' | 'high' | 'max' | undefined>
- /** Whether requests enable the provider's high-level content safety check (default `false`). */
- safetyCheck: Volatile
/** Default per-request output cap (default 256,000); a model's own cap and explicit request values win. */
maxTokens: Volatile
/** Positive context capacity used when the selected model has no exact value (default 1,000,000). */
@@ -95,7 +93,6 @@ export const deepSeekConfigFields = {
baseURL: z.string().volatile(),
thinking: z.union(['enabled', 'disabled']).volatile(),
reasoningEffort: z.union(['off', 'low', 'high', 'max']).volatile(),
- safetyCheck: z.boolean().default(false).volatile(),
maxTokens: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER).default(DEFAULT_MAX_TOKENS).volatile(),
defaultContextWindow: z.number().step(1).min(1).default(DEFAULT_CONTEXT_WINDOW).volatile(),
models: z.array(catalogModel).default(DEFAULT_MODELS).volatile(),
@@ -235,9 +232,6 @@ export function resolveAdapterOptions(config: Options, environment?: LaunchEnvir
&& config.reasoningEffort !== 'off') {
throw new Error('llm-deepseek: only reasoningEffort "off" can be configured when thinking is disabled')
}
- if (config.safetyCheck !== undefined && typeof config.safetyCheck !== 'boolean') {
- throw new Error('llm-deepseek: safetyCheck must be a boolean')
- }
if (config.defaultContextWindow !== undefined
&& (!Number.isInteger(config.defaultContextWindow) || config.defaultContextWindow <= 0)) {
throw new Error('llm-deepseek: defaultContextWindow must be a positive integer')
@@ -325,7 +319,6 @@ export function resolveAdapterOptions(config: Options, environment?: LaunchEnvir
thinking: config.thinking,
reasoningEffort: config.reasoningEffort,
},
- safetyCheck: config.safetyCheck ?? false,
maxTokens: config.maxTokens ?? DEFAULT_MAX_TOKENS,
defaultContextWindow: config.defaultContextWindow ?? DEFAULT_CONTEXT_WINDOW,
models: resolveModels(config.models),
diff --git a/packages/llm/llm-deepseek/src/serialize.ts b/packages/llm/llm-deepseek/src/serialize.ts
index 31f921f986..fd39408bfa 100644
--- a/packages/llm/llm-deepseek/src/serialize.ts
+++ b/packages/llm/llm-deepseek/src/serialize.ts
@@ -155,7 +155,7 @@ export function serialize(
thinking: { type: effort === 'off' ? 'disabled' : 'enabled' },
...effort === 'off' ? {} : { output_config: { effort: effort as 'low' | 'high' | 'max' } },
...system.length === 0 ? {} : { system },
- ...connection.safetyCheck ? { safety_check: { level: 'high' as const } } : {},
+ safety_check: { level: 'high' },
...options.temperature === undefined ? {} : { temperature: options.temperature },
...options.stop === undefined ? {} : { stop_sequences: options.stop },
...options.tools === undefined ? {} : {
diff --git a/packages/llm/llm-deepseek/src/translate.ts b/packages/llm/llm-deepseek/src/translate.ts
index 607f8d15cd..0d9d0b673d 100644
--- a/packages/llm/llm-deepseek/src/translate.ts
+++ b/packages/llm/llm-deepseek/src/translate.ts
@@ -87,15 +87,17 @@ function deltaChunk(block: Block, raw: unknown): StreamChunk | undefined {
return malformed(`unsupported delta ${String(delta.type)} for ${content.type}`)
}
-function stopReason(raw: unknown, details: unknown): FinishReason {
+/** Build the failure for a `refusal` stop, keeping the provider's explanation such as blocked images. */
+function refusal(details: unknown): LlmError {
+ const explanation = typeof details === 'object' && details !== null && 'explanation' in details ? details.explanation : undefined
+ return new LlmError(`DeepSeek refused to answer under its content safety review${typeof explanation === 'string' && explanation ? `: ${explanation}` : ''}`, 'CONTENT_REFUSED')
+}
+
+function stopReason(raw: unknown): FinishReason {
switch (raw) {
case 'end_turn': case 'stop_sequence': return { kind: 'stop' }
case 'tool_use': return { kind: 'tool-calls' }
case 'max_tokens': return { kind: 'max-tokens' }
- case 'refusal': {
- const explanation = typeof details === 'object' && details !== null && 'explanation' in details ? details.explanation : undefined
- throw new LlmError(`DeepSeek refused to answer under its content safety review${typeof explanation === 'string' && explanation ? `: ${explanation}` : ''}`, 'CONTENT_REFUSED')
- }
default: return malformed(`unsupported stop reason ${String(raw)}`)
}
}
@@ -110,6 +112,7 @@ export async function* translate(events: AsyncIterable>,
const usage: TokenUsage = { inputTokens: 0, outputTokens: 0 }
let started = false
let reason: FinishReason | undefined
+ let refused: LlmError | undefined
for await (const event of events) {
if (event.type === 'message_start') {
if (started) return malformed('duplicate message_start')
@@ -146,9 +149,16 @@ export async function* translate(events: AsyncIterable>,
}
} else if (event.type === 'message_delta') {
const delta = object(event.delta)
- if (delta.stop_reason != null) reason = stopReason(delta.stop_reason, delta.stop_details)
+ if (delta.stop_reason === 'refusal') refused = refusal(delta.stop_details)
+ else if (delta.stop_reason != null) reason = stopReason(delta.stop_reason)
if (event.usage !== undefined) updateUsage(usage, event.usage)
} else {
+ usage.totalTokens = usage.inputTokens + usage.outputTokens + (usage.cacheReadTokens ?? 0) + (usage.cacheWriteTokens ?? 0)
+ if (refused !== undefined) {
+ // Tokens consumed before a refusal are billed, so report them before failing.
+ yield { type: 'usage', usage }
+ throw refused
+ }
if (reason === undefined || [...blocks.values()].some(block => !block.closed)) return malformed('message_stop without settled blocks and stop reason')
if (blocks.size === 0 && reason.kind === 'stop') throw new LlmError('DeepSeek Messages returned no content', 'EMPTY_RESPONSE')
// Truncated tool JSON is retained in the stream, then pruned by the shared assembler.
@@ -160,7 +170,6 @@ export async function* translate(events: AsyncIterable>,
object(parsed)
}
}
- usage.totalTokens = usage.inputTokens + usage.outputTokens + (usage.cacheReadTokens ?? 0) + (usage.cacheWriteTokens ?? 0)
yield { type: 'usage', usage }
yield { type: 'finish', reason, replayState: replayState(model, [...blocks.values()].map(block => block.replay)) }
return
diff --git a/packages/llm/llm-deepseek/src/types.ts b/packages/llm/llm-deepseek/src/types.ts
index e3d3ab797f..c682bba792 100644
--- a/packages/llm/llm-deepseek/src/types.ts
+++ b/packages/llm/llm-deepseek/src/types.ts
@@ -53,8 +53,6 @@ export interface DeepSeekConnectionOptions {
baseURL: string
/** Request defaults applied to every call (thinking mode, effort). */
defaults: RequestDefaults
- /** Send `safety_check: { level: 'high' }` so the provider reviews request input and model output. */
- safetyCheck: boolean
/** Default per-request output cap; explicit request values win. */
maxTokens: number
/** Positive context capacity used when the selected model has no exact value. */
diff --git a/packages/llm/llm-deepseek/src/wire-types.ts b/packages/llm/llm-deepseek/src/wire-types.ts
index 57a02dc026..8c3065059a 100644
--- a/packages/llm/llm-deepseek/src/wire-types.ts
+++ b/packages/llm/llm-deepseek/src/wire-types.ts
@@ -29,8 +29,8 @@ export type WireRequest = {
system?: string
thinking: { type: 'enabled' | 'disabled' }
output_config?: { effort: 'low' | 'high' | 'max' }
- /** Provider content safety review of the input and output. */
- safety_check?: { level: 'high' }
+ /** Provider content safety review of the input and output; always `high`. */
+ safety_check: { level: 'high' }
temperature?: number
stop_sequences?: string[]
tools?: {
diff --git a/packages/llm/llm-deepseek/tests/loader-composition.spec.ts b/packages/llm/llm-deepseek/tests/loader-composition.spec.ts
index ca673080d7..ff9b02ee99 100644
--- a/packages/llm/llm-deepseek/tests/loader-composition.spec.ts
+++ b/packages/llm/llm-deepseek/tests/loader-composition.spec.ts
@@ -313,17 +313,14 @@ describe('llm-deepseek real dynamic composition', () => {
expect(serverB.headers[0]?.['x-api-key']).toBe('rotated-key')
})
- it('sends the safety check after the settings switch turns it on and fails a refused response', async () => {
+ it('requests the content safety check and fails a refused response', async () => {
vi.stubEnv('DEEPSEEK_API_KEY', '')
const refusal = textEvents.map(event => event.replace('"end_turn"', '"refusal"'))
- const server = await mockServer([{ kind: 'sse', events: textEvents }, { kind: 'sse', events: refusal }])
+ const server = await mockServer([{ kind: 'sse', events: refusal }])
const { ctx } = await loadComposition({ withDynamic: true, baseURL: server.url })
- await assemble(ctx, { model: 'deepseek-v4-flash', messages: [] })
- expect(server.requests[0]).not.toHaveProperty('safety_check')
- await ctx.settings.mutate(NS, [{ op: 'set', path: ['safetyCheck'], value: true }])
const refused = await assemble(ctx, { model: 'deepseek-v4-flash', messages: [] })
- expect(server.requests[1]).toMatchObject({ safety_check: { level: 'high' } })
+ expect(server.requests[0]).toMatchObject({ safety_check: { level: 'high' } })
expect(refused.finish).toMatchObject({ kind: 'error', failure: { code: 'CONTENT_REFUSED' } })
})
diff --git a/packages/llm/llm-deepseek/tests/serialize.spec.ts b/packages/llm/llm-deepseek/tests/serialize.spec.ts
index 4e9b55b1ad..7da6a2d412 100644
--- a/packages/llm/llm-deepseek/tests/serialize.spec.ts
+++ b/packages/llm/llm-deepseek/tests/serialize.spec.ts
@@ -333,12 +333,8 @@ describe('Messages request conversion', () => {
expect(request.output_config).toEqual(effort === 'off' ? undefined : { effort })
})
- it('sends the high safety check only when enabled and rejects a non-boolean switch', () => {
- expect(body([user()]).safety_check).toBeUndefined()
- const messages = [user()]
- const request = serialize(options({ messages }), resolveAdapterOptions({ safetyCheck: true }), messages, new Map(), () => undefined)
- expect(request.safety_check).toEqual({ level: 'high' })
- expect(() => resolveAdapterOptions(JSON.parse('{"safetyCheck":"high"}') as Config)).toThrow(/safetyCheck must be a boolean/)
+ it('always requests the high content safety check', () => {
+ expect(body([user()]).safety_check).toEqual({ level: 'high' })
})
it('disables thinking for the off effort, passes temperature with thinking and refuses unsupported effort', () => {
diff --git a/packages/llm/llm-deepseek/tests/stream.spec.ts b/packages/llm/llm-deepseek/tests/stream.spec.ts
index 423485bc3b..187e978d13 100644
--- a/packages/llm/llm-deepseek/tests/stream.spec.ts
+++ b/packages/llm/llm-deepseek/tests/stream.spec.ts
@@ -39,11 +39,13 @@ describe('Messages stream', () => {
expect(result.at(-1)).toMatchObject({ reason: { kind: 'stop' } })
})
- it('fails a refused response with CONTENT_REFUSED after streamed text', async () => {
- await expect(chunks(translate(events([...textEvents.slice(0, 4), ...end('refusal')]), MODEL)))
- .rejects.toMatchObject({ code: 'CONTENT_REFUSED' })
+ it('reports billed usage, then fails a refused response with CONTENT_REFUSED', async () => {
+ const output: unknown[] = []
+ const consume = async () => { for await (const chunk of translate(events([...textEvents.slice(0, 4), ...end('refusal')]), MODEL)) output.push(chunk) }
+ await expect(consume()).rejects.toMatchObject({ code: 'CONTENT_REFUSED' })
+ expect(output.at(-1)).toEqual({ type: 'usage', usage: { inputTokens: 12, outputTokens: 5, totalTokens: 17 } })
const blocked = { type: 'message_delta', delta: { stop_reason: 'refusal', stop_details: { type: 'refusal', explanation: 'blocked: messages.1.content.0' } } }
- await expect(chunks(translate(events([start, blocked]), MODEL)))
+ await expect(chunks(translate(events([start, blocked, { type: 'message_stop' }]), MODEL)))
.rejects.toMatchObject({ code: 'CONTENT_REFUSED', message: expect.stringContaining('blocked: messages.1.content.0') as string })
})