DeepSeek Harness StreamChunk 协议与错误处理
跟踪完整分片序列、传输失败和中断时的资源清理。
学完这一章,你能够
- 跟踪完整分片序列、传输失败和中断时的资源清理。
从增量到完整内容块
适配器按异步流逐片交付内容。完整文本块以 block-start 开始,用同一 index 发送一个或多个 text-delta,再用 block-end 交付最终文本。本章用两个文本增量拼出标签预览,再发送独立的合成工具调用块。
工具调用增量携带调用 ID,首片可带工具名,argumentsDelta 是原始 JSON 字符串的片段。先拼接再按需解析,不能逐片当作完整 JSON。旧文中的 CallId 在固定版本中应写作 ToolCallId,最终的 block-end 包含同一 ID、名称和完整参数字符串。实验只观察分片和组装。
顺序与终止原因
完整序列应从索引 0 依次组织内容块。同块的开始、增量和结束共用索引。若取得用量,在末尾 finish 之前发送 usage。合成样本分别以 stop 和 tool-calls 结束,后者请求上层处理工具调用。没有用量的路径仍发出及时终止,禁止编造 token 数。
适配器应遵守顺序并发送完整块。固定版本的 BlockAssembler 同时容忍只收到增量的输入,关闭后到达的增量会被丢弃。中断时可提取文本或推理内容前缀,避免把未完成工具调用当作可执行结果。实验分别检查了这些分支。
传输失败、归属头和取消
将 attributionHeaders() 合并进提供方请求头,并把调用方的 AbortSignal 继续传给 fetch 或 SDK。把 HTTP 失败转换为结构化失败。固定 TypeScript 构造签名接受内置 code,自定义 code 通过 LlmError.fromFailure({message, code, status}) 交付。上层可按稳定 code 判断,无需解析描述。
本例的内存传输使用标准 Response 对象返回 503。实际 LlmRuntime 把失败归一成 kind 为 error 的 finish,保留自定义 code 和状态。普通 Error 也可被归一,但本例只得到 UNKNOWN。模拟请求收到取消后进入 aborted 分支,生成器的 finally 完成清理。消费方提前 break 也会关闭迭代器。真实 HTTP 连接和产品循环待实测。
拒绝不支持的请求选项
适配器应明确拒绝无法支持的请求选项。实验传入 stop 后,在接触传输前返回专用错误码。推理强度沿用确切模型元数据所列的有序 ID,例如提供方给出的 off,不自建统一枚举。未提供 reasoning 代表该模型没有推理强度选项。第 24 章离线适配器已观察到显式未知强度在进入 stream 前被拒绝。
分片输出给适配器作者的约定
| 规则 | 实际含义 |
|---|---|
| 内容块的边界 | 完整适配器输出配对 start 与 end。BlockAssembler 可从仅含增量的输入恢复部分内容。 |
| 索引 | 为全序列的块从 0 顺序分配索引,同一块的增量和结束沿用该索引。 |
| 工具参数增量 | 按到达顺序拼接原始 JSON 文本,完整后再解析。 |
| 终止分片 | finish 表示终止,适配器随后结束迭代。 |
| 用量分片 | 取得用量时放在 finish 前,缺失时保留未知。 |
观察流式分片及取消清理
import { registerHooks, createRequire } from 'node:module'
import fs from 'node:fs'
import path from 'node:path'
import assert from 'node:assert/strict'
import { createHash } from 'node:crypto'
import { pathToFileURL, fileURLToPath } from 'node:url'
const repo = path.resolve(process.argv[2])
const base = pathToFileURL(repo + '/').href
const req = createRequire(import.meta.url)
const ts = req(path.join(repo, 'node_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/typescript.js'))
const spec = path.join(repo, 'node_modules/.pnpm/@standard-schema+spec@1.1.0/node_modules/@standard-schema/spec/dist/index.js')
const aliases = {
'@deepseek-ai/dsh-typert-protocol': 'packages/typert/protocol/src/index.ts',
'@deepseek-ai/dsh-brand': 'packages/util/brand/src/index.ts',
'@deepseek-ai/dsh-util-crypto': 'packages/util/crypto/src/index.ts',
'@deepseek-ai/dsh-timeout': 'packages/util/timeout/src/index.ts',
'@deepseek-ai/cordis': 'vendor/cordis/src/index.ts',
'@deepseek-ai/cosmokit': 'vendor/cosmokit/src/index.ts',
'@deepseek-ai/schemastery': 'vendor/schemastery/src/index.ts',
'@deepseek-ai/dsh-scope': 'packages/core/scope/src/index.ts',
'@deepseek-ai/dsh-util-values': 'packages/util/values/src/index.ts',
'@deepseek-ai/dsh-error': 'packages/util/error/src/index.ts',
'@deepseek-ai/dsh-llm': 'packages/llm/llm/src/error.ts',
}
registerHooks({
resolve(s, c, n) {
if (aliases[s]) return n(base + aliases[s], c)
if (s === '@standard-schema/spec') return n(pathToFileURL(spec).href, c)
return n(s, c)
},
load(u, c, n) {
if (u.startsWith(base) && u.endsWith('.ts')) return { format: 'module', source: ts.transpile(fs.readFileSync(fileURLToPath(u), 'utf8'), { compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 } }), shortCircuit: true }
return n(u, c)
},
})
const { Context } = await import('@deepseek-ai/cordis')
const { BlockAssembler, LlmAdapter, LlmRuntime, LlmError, ToolCallId, attributionHeaders } =
await import(base + 'packages/llm/llm/src/index.ts')
const cases = []
function check(name,input,expected,actual) {
assert.deepEqual(actual,expected,name)
cases.push({name,input,expected,actual,passed:true})
}
async function collect(iterable) {
const chunks = []
for await (const value of iterable) chunks.push(value)
return chunks
}
function assemble(chunks) {
const assembler = new BlockAssembler()
for (const chunk of chunks) assembler.push(chunk)
return assembler
}
const id = ToolCallId('lesson-label-one')
const args = ['{"label":', '"蓝天"}']
const requestedTool = {type:'tool-call',id,name:'label_preview',arguments:args.join('')}
class FixtureTransportAdapter extends LlmAdapter {
constructor(send) {
super()
this.send = send
this.closed = 0
}
async *stream(options) {
try {
if (options.stop?.length) {
throw LlmError.fromFailure({ message:'Stop sequences are outside this fixture', code:'LESSON_UNSUPPORTED_STOP' })
}
const response = await this.send({
headers: { 'content-type':'application/json', ...attributionHeaders() },
body: JSON.stringify({ model: options.model, messages: options.messages }),
signal: options.signal,
})
if (!response.ok) {
throw LlmError.fromFailure({ message:'Fixture returned HTTP ' + response.status,
code:'LESSON_HTTP_ERROR', status:response.status })
}
const {useTool,usage} = await response.json()
yield {type:'block-start',index:0,blockType:'text'}
yield {type:'text-delta',index:0,text:'标签'}
yield {type:'text-delta',index:0,text:'预览'}
yield {type:'block-end',index:0,block:{type:'text',text:'标签预览'}}
if (useTool) {
yield {type:'block-start',index:1,blockType:'tool-call'}
yield {type:'tool-call-delta',index:1,id,name:'label_preview',argumentsDelta:args[0]}
yield {type:'tool-call-delta',index:1,id,argumentsDelta:args[1]}
yield {type:'block-end',index:1,block:requestedTool}
}
if (usage) yield {type:'usage',usage}
yield {type:'finish',reason:{kind:useTool ? 'tool-calls' : 'stop'}}
} finally {
this.closed++
}
}
}
const ctx = new Context()
await ctx.plugin(LlmRuntime)
let sent
let fixture = 'success'
let started = Promise.withResolvers()
let calls = 0
const transport = request => {
sent = request
calls++
if (fixture === 'abort') {
started.resolve()
return new Promise((_,reject) => {
const abort = () => reject(request.signal.reason)
if (request.signal.aborted) abort()
else request.signal.addEventListener('abort',abort,{once:true})
})
}
if (fixture === 'error') return new Response('',{status:503})
if (fixture === 'ordinary-error') throw new Error('fixture failure')
if (fixture === 'no-usage') return Response.json({useTool:false})
return Response.json({useTool:true,usage:{inputTokens:7,outputTokens:3}})
}
const adapter = new FixtureTransportAdapter(transport)
const options = {provider:'lesson-stream',model:'fixture-model',messages:[]}
try {
ctx.llm.registerAdapter([options.provider],adapter)
const signal = new AbortController().signal
const chunks = await collect(ctx.llm.stream({...options,signal}))
check('request_attribution_payload_and_signal',options,
{attribution:attributionHeaders()['user-agent'],model:options.model,signal:true},
{attribution:sent.headers['user-agent'],model:JSON.parse(sent.body).model,signal:sent.signal===signal})
check('start_delta_end_usage_finish','text plus synthetic label call',
['block-start','text-delta','text-delta','block-end','block-start','tool-call-delta','tool-call-delta','block-end','usage','finish'],
chunks.map(chunk=>chunk.type))
const merged = assemble(chunks)
check('assembled_text_and_tool_json','canonical blocks',
[{type:'text',text:'标签预览'},requestedTool],merged.blocks())
const toolBeforeClose = assemble(chunks.slice(0,7)).blocks()[1]
check('raw_json_slices_join_before_block_end',args,{label:'蓝天'},JSON.parse(toolBeforeClose.arguments))
check('usage_before_terminal',chunks.map(chunk=>chunk.type),
{usage:{inputTokens:7,outputTokens:3},reason:'tool-calls'},
{usage:merged.usage,reason:merged.finish.kind})
const late = chunks.slice(0,4).concat({type:'text-delta',index:0,text:'迟到'},chunks.slice(4))
check('closed_block_ignores_late_delta','late text after block end','标签预览',assemble(late).blocks()[0].text)
check('assembler_accepts_delta_only','one text delta at index 7',
[{type:'text',text:'独立增量'}],assemble([{type:'text-delta',index:7,text:'独立增量'}]).blocks())
check('interrupted_prefix_has_only_visible_text','open text and partial tool',
[{type:'text',text:'标签预览'}],assemble(chunks.slice(0,7)).interruptedBlocks())
fixture = 'no-usage'
const without = await collect(ctx.llm.stream(options))
check('usage_can_be_absent_in_fixtures','no usage from transport',
{usagePresent:false,finish:'stop'},{usagePresent:assemble(without).usage!==undefined,finish:assemble(without).finish.kind})
fixture = 'error'
const error = (await collect(ctx.llm.stream(options)))[0]
check('http_status_and_stable_code_retained',{status:503},
{kind:'error',code:'LESSON_HTTP_ERROR',status:503},
{kind:error.reason.kind,code:error.reason.failure.code,status:error.reason.failure.status})
fixture = 'ordinary-error'
const ordinary = (await collect(ctx.llm.stream(options)))[0]
check('ordinary_error_normalises_to_generic_code','plain Error',
{kind:'error',code:'UNKNOWN'},{kind:ordinary.reason.kind,code:ordinary.reason.failure.code})
const callsBefore = calls
const unsupported = (await collect(ctx.llm.stream({...options,stop:['END']})))[0]
check('unsupported_option_rejected_before_transport',{stop:['END']},
{code:'LESSON_UNSUPPORTED_STOP',calls:0},
{code:unsupported.reason.failure.code,calls:calls-callsBefore})
fixture = 'abort'
const controller = new AbortController()
const closedBefore = adapter.closed
const run = collect(ctx.llm.stream({...options,signal:controller.signal}))
await started.promise
controller.abort()
const aborted = (await run)[0]
check('abort_ends_iterator_and_closes_adapter','cancel while transport pending',
{kind:'aborted',closed:1},{kind:aborted.reason.kind,closed:adapter.closed-closedBefore})
fixture = 'success'
const before = adapter.closed
for await (const _first of ctx.llm.stream(options)) break
check('consumer_break_calls_adapter_return','break after first chunk',1,adapter.closed-before)
} finally {
await ctx.fiber.dispose()
}
const hash = bytes => createHash('sha256').update(bytes).digest('hex')
const sources = [...Object.values(aliases),...['index','types','assembler','adapter-failure','attribution','brand']
.map(file=>'packages/llm/llm/src/'+file+'.ts'),'docs/user/develop/practice/llm-adapter.zh.md']
console.log(JSON.stringify({
cases,node:process.version,typescript:ts.version,code_sha256:hash(fs.readFileSync(fileURLToPath(import.meta.url))),
source_hashes:Object.fromEntries(sources.map(name=>[name,hash(fs.readFileSync(path.join(repo,name)))])),
transport:'in-process Response fixture',provider_http_called:false,tool_dispatched:false,agent_loop_tested:false,
},null,2))
- 组装文本与工具参数,检查用量、错误码、取消、提前退出和迭代清理。
所需环境:Node.js 24.22.3、TypeScript 6.0.3、固定版本源码。
当前源码 SHA256:4e94b073ca64685c307180f3c475dca8a2f01dfb6d69f4c900d6c89821924fe4
本地复跑
解压后按 README 运行实验并核对实际分片和清理结果。
所需环境:Node.js 24.22.3、TypeScript 6.0.3、固定版本源码。
ZIP SHA256:4ceb195988a276aa4fe03f66f117dcebabb2d8e51c311e547a8f5311df3e4249
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
能逐片解析 argumentsDelta 吗?
展开参考解答
应先按顺序拼接为完整 JSON 文本再解析。