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

回传本地工具结果并核对推理与用量

JAVASCRIPTNode.js 24.22.3、Pi CLI 1.5.0、临时笔记、自编本机回环端点。reasoning-tools-loopback.mjs
reasoning-tools-loopback.mjs124 行
import assert from 'node:assert/strict';
import {spawn} from 'node:child_process';
import {once} from 'node:events';
import {mkdir, writeFile} from 'node:fs/promises';
import {createServer} from 'node:http';
import {join, resolve} from 'node:path';

const [, , cliPath, workDir] = process.argv;
if (!cliPath || !workDir) throw new Error('请提供锁定的 Pi CLI 和空临时目录');
const cli = resolve(cliPath);
const cwd = resolve(workDir);
const agent = join(cwd, 'fixture-agent');
await mkdir(agent);
const note = '课程码:LESSON-47\n';
await writeFile(join(cwd, 'course-note.txt'), note, {flag: 'wx'});

const observations = [];
const model = 'course-deepseek-fixture';
const detail = 'fixture-thinking-marker';
const resultText = '已找到课程码。';
const toolId = 'call_read_course_1';
const server = createServer(async (req, res) => {
  if (req.method !== 'POST' || req.url !== '/v1/chat/completions') {
    res.writeHead(404).end();
    return;
  }
  let raw = '';
  for await (const chunk of req) raw += chunk;
  const body = JSON.parse(raw);
  const tool = body.messages.find(message => message.role === 'tool');
  const assistant = body.messages.find(message => message.role === 'assistant' && message.tool_calls);
  observations.push({
    model: body.model, tools: (body.tools ?? []).map(tool => tool.function.name),
    authMatchesFixture: req.headers.authorization === 'Bearer course-test-only',
    thinking: body.thinking?.type, effort: body.reasoning_effort,
    reasoningRetained: assistant?.reasoning_content === detail,
    toolAssociates: tool?.tool_call_id === toolId,
    courseNoteRead: tool?.content === note,
  });
  const frame = (delta, reason = null, usage) => ({
    id: 'course-fixture', object: 'chat.completion.chunk', created: 1, model,
    choices: [{index: 0, delta, finish_reason: reason}], ...(usage && {usage}),
  });
  const send = value => res.write('data: ' + JSON.stringify(value) + '\n\n');
  res.writeHead(200, {'Content-Type': 'text/event-stream'});
  if (tool) {
    send(frame({role: 'assistant', content: resultText}));
    send(frame({}, 'stop', {prompt_tokens: 100, completion_tokens: 20, total_tokens: 120,
      prompt_tokens_details: {cached_tokens: 30}}));
  } else {
    send(frame({role: 'assistant', reasoning_content: detail}));
    send(frame({tool_calls: [{index: 0, id: toolId, type: 'function',
      function: {name: 'read', arguments: JSON.stringify({path: 'course-note.txt'})}}]}));
    send(frame({}, 'tool_calls'));
  }
  res.end('data: [DONE]\n\n');
});
server.listen(0, '127.0.0.1');
await once(server, 'listening');

const env = Object.fromEntries(
  ['PATH', 'SystemRoot', 'WINDIR', 'TEMP', 'TMP', 'USERPROFILE', 'LOCALAPPDATA', 'APPDATA', 'COMSPEC']
    .filter(key => process.env[key]).map(key => [key, process.env[key]]),
);
Object.assign(env, {
  PI_CODING_AGENT_DIR: agent, PI_OFFLINE: '1', PI_SKIP_VERSION_CHECK: '1', PI_TELEMETRY: '0',
  COURSE_LOOPBACK_DEEPSEEK_KEY: 'course-test-only',
});
const cases = [];
function check(name, input, expected, actual) {
  assert.deepStrictEqual(actual, expected, name);
  cases.push({name, input, expected, actual, passed: true});
}
try {
  const baseUrl = 'http://127.0.0.1:' + server.address().port + '/v1';
  await writeFile(join(agent, 'models.json'), JSON.stringify({providers: {deepseek: {
    baseUrl, api: 'openai-completions', apiKey: '$COURSE_LOOPBACK_DEEPSEEK_KEY',
    models: [{id: model, baseUrl, reasoning: true, input: ['text'], contextWindow: 16000, maxTokens: 512,
      cost: {input: 2, output: 4, cacheRead: 0.5, cacheWrite: 0},
      thinkingLevelMap: {minimal: 'low', low: 'low', medium: 'high', high: 'high', xhigh: 'high', max: 'max'},
      compat: {thinkingFormat: 'deepseek', requiresReasoningContentOnAssistantMessages: true}}],
  }}}));
  const flags = ['--mode', 'json', '--no-session', '--no-extensions', '--no-mcp', '--no-context-files',
    '--no-skills', '--no-prompt-templates', '--no-themes', '--tools', 'read', '--no-approve',
    '--model', 'deepseek/' + model + ':xhigh', '读取课程笔记中的课程码'];
  const worker = spawn(process.execPath, [cli, ...flags], {cwd, env, windowsHide: true});
  let stdout = '', stderr = '';
  worker.stdout.setEncoding('utf8').on('data', data => { stdout += data; });
  worker.stderr.setEncoding('utf8').on('data', data => { stderr += data; });
  worker.stdin.end();
  const timer = setTimeout(() => worker.kill(), 15000);
  try {
    const [code] = await once(worker, 'close');
    assert.equal(code, 0, stderr);
  } finally {
    clearTimeout(timer);
  }
  const events = stdout.trim().split('\n').map(JSON.parse);
  const assistantEvents = events.filter(event => event.type === 'message_end' && event.message.role === 'assistant');
  const final = assistantEvents.at(-1).message;
  check('two_http_rounds', {tool: 'read'}, 2, observations.length);
  const [first, second] = observations;
  check('first_local_request', {provider: 'deepseek', protocol: 'openai-completions'},
        {model, tools: ['read'], authMatchesFixture: true},
        {model: first.model, tools: first.tools, authMatchesFixture: first.authMatchesFixture});
  check('mapped_effort_on_both_requests', {level: 'xhigh'}, [['enabled', 'high'], ['enabled', 'high']],
        observations.map(({thinking, effort}) => [thinking, effort]));
  check('tool_result_keeps_reasoning_and_id', {file: 'course-note.txt'},
        {reasoningRetained: true, toolAssociates: true, courseNoteRead: true},
        {reasoningRetained: second.reasoningRetained, toolAssociates: second.toolAssociates, courseNoteRead: second.courseNoteRead});
  check('actual_final_response', {endpointReply: resultText}, resultText,
        final.content.find(item => item.type === 'text').text);
  check('synthetic_usage_channels', {prompt: 100, cached: 30, completion: 20},
        {input: 70, cacheRead: 30, output: 20},
        {input: final.usage.input, cacheRead: final.usage.cacheRead, output: final.usage.output});
  const expectedCost = (70 * 2 + 30 * 0.5 + 20 * 4) / 1000000;
  check('local_cost_estimate', {rates: [2, 0.5, 4], basis: 'per million tokens'},
        expectedCost.toFixed(8), final.usage.cost.total.toFixed(8));
  process.stdout.write(JSON.stringify({version: process.version, cases}) + '\n');
} finally {
  server.closeAllConnections();
  await new Promise(close => server.close(close));
}
本例需在 Node.js 24.22.3、Pi CLI 1.5.0、临时笔记、自编本机回环端点。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Node.js 24.22.3、Pi CLI 1.5.0、临时笔记、自编本机回环端点。

入口文件:projects/pi-agent-deepseek-lab/reasoning-tools-loopback.mjs

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 reasoning-tools-loopback.mjs,或下载右侧课程工程包。
  2. 确认本地已准备 Node.js 24.22.3、Pi CLI 1.5.0、临时笔记、自编本机回环端点。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Pi Agent

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

下载课程关联工程包:Pi Agent

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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