蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

观察流式分片及取消清理

JAVASCRIPTNode.js 24.22.3、TypeScript 6.0.3、固定版本源码。stream-observations.mjs
stream-observations.mjs190 行
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、固定版本源码。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Node.js 24.22.3、TypeScript 6.0.3、固定版本源码。

入口文件:projects/deepseek-harness-stream-chunk/stream-observations.mjs

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 stream-observations.mjs,或下载右侧课程工程包。
  2. 确认本地已准备 Node.js 24.22.3、TypeScript 6.0.3、固定版本源码。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:DeepSeek Harness

课程关联工程包(登记关联33章) · 含当前章节或实例 · mbskycom202612a128.zip

下载课程关联工程包:DeepSeek Harness

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a159.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习