test-agent-runtime.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { AgentRuntime } from "../src/runtime.js";
  2. import type { AgentRuntimeConfig, AgentRuntimeDeps } from "../src/runtime/types.js";
  3. import { createTestModelSelection } from "./test-model-selection.js";
  4. import { createTestModelFactory } from "./test-runtime-model.js";
  5. type TestRuntimeConfig = Omit<AgentRuntimeConfig, "modelSelection"> &
  6. Partial<Pick<AgentRuntimeConfig, "modelSelection">> & {
  7. /** 测试模型的能力上限,不进入 Selection 或生产 Runtime Config。 */
  8. maxOutputTokens?: number;
  9. };
  10. type TestRuntimeDeps = Omit<AgentRuntimeDeps, "modelFactory"> &
  11. Partial<Pick<AgentRuntimeDeps, "modelFactory">>;
  12. /**
  13. * 低层 Runtime 测试也显式经过 ModelFactory/ModelSelection 契约。
  14. * 与具体模型无关的测试由该 fixture 注入不可联网的测试 Model,不在生产 Runtime 制造 sentinel。
  15. */
  16. export function createTestAgentRuntime(
  17. sessionId: ConstructorParameters<typeof AgentRuntime>[0],
  18. config: TestRuntimeConfig,
  19. deps: TestRuntimeDeps,
  20. ): AgentRuntime {
  21. const { maxOutputTokens, ...runtimeConfig } = config;
  22. const modelSelection =
  23. runtimeConfig.modelSelection ?? createTestModelSelection("test/default-runtime-model");
  24. const modelAdapter = deps.modelAdapter;
  25. const baseModelFactory =
  26. deps.modelFactory ??
  27. (modelAdapter
  28. ? createTestModelFactory({
  29. generateText: (request) => modelAdapter.generateText(request as never),
  30. ...(modelAdapter.streamText
  31. ? { streamText: (request) => modelAdapter.streamText!(request as never) }
  32. : {}),
  33. })
  34. : createTestModelFactory({}));
  35. const modelFactory =
  36. maxOutputTokens === undefined
  37. ? baseModelFactory
  38. : (input: Parameters<typeof baseModelFactory>[0]) => {
  39. const wrap = (
  40. model: ReturnType<typeof baseModelFactory>,
  41. ): ReturnType<typeof baseModelFactory> =>
  42. Object.freeze({
  43. ...model,
  44. optionSpecs: Object.freeze({
  45. ...model.optionSpecs,
  46. maxOutputTokens: Object.freeze({ max: maxOutputTokens }),
  47. }),
  48. bind(options) {
  49. return wrap(model.bind(options));
  50. },
  51. });
  52. return wrap(baseModelFactory(input));
  53. };
  54. return new AgentRuntime(
  55. sessionId,
  56. { ...runtimeConfig, modelSelection },
  57. {
  58. ...deps,
  59. modelFactory,
  60. },
  61. );
  62. }