学习Agent开发5 ai-mock

14 阅读1分钟

提供一个模拟ai server的程序

// src/ai-mock.ts  
import { writeFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { LLMock } from '@copilotkit/aimock'

const LOG_PATH = resolve('src/log.json')

const mock = new LLMock({
  port: 4010,
  requestTransform: (req) => {
    writeFileSync(LOG_PATH, JSON.stringify(req, null, 2), 'utf-8')
    return req
  },
})

// mock.on(
//   {
//     predicate: (req) =>
//       !req.messages.some((m) => m.tool_calls?.some((t) => t.function.name === 'ExitPlanMode')),
//   },
//   {
//     toolCalls: [{ name: 'ExitPlanMode', arguments: {} }],
//     reasoning: 'tool-use-thinking',
//   },
//   { streamingProfile: { tps: 60 } },
// )

mock.on({}, { content: 'a short text', reasoning: 'thinking' }, { streamingProfile: { tps: 60 } })

await mock.start()

console.log(`Anthropic: ANTHROPIC_BASE_URL=${mock.url}  → POST /v1/messages`)
console.log(`OpenAI:    OPENAI_BASE_URL=${mock.url}/v1  → POST /v1/chat/completions`)

export { mock }

node22+可以直接node --watch src/ai-mock.ts 原生的ts执行和watch能力 不需要tsx/esbuild

需要注意的是 mock.on定义的是“一次请求”的结果 = reasoning + tool_call数组/文本 所以“思考+tool调用+text”的常规输出 实际是两次网络请求的结果