test-agent-runtime.ts 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. // ============================================================
  2. // bootstrap 测试的 Model / AgentRuntime 夹具(照 core/tests 的同名夹具)
  3. // ============================================================
  4. // provider 重构后 AgentRuntime 只经 ModelFactory/ModelSelection 造 Model,没有「直接注入
  5. // adapter」的兼容路径。dwf 的 driver / run service 测试仍以脚本化 adapter 表达 actor 的应答,
  6. // 这里把它包成测试 ModelFactory,并给 runtime 一个缺省的 selection——与 core 的夹具同形,
  7. // bootstrap 不能跨包引用 core 的 tests/ 目录,所以复制一份。
  8. import {
  9. createModelId,
  10. createModelProviderId,
  11. getCurrentModelInvocationContext,
  12. type Model,
  13. type ModelEvent,
  14. type ModelInputFormat,
  15. type ModelInvocationContext,
  16. type ModelOptions,
  17. type ModelProperties,
  18. type ModelRequest,
  19. type ModelResult,
  20. type ModelSelection,
  21. } from "@zcode/contracts";
  22. import { AgentRuntime, type AgentRuntimeConfig, type AgentRuntimeDeps } from "@zcode/core";
  23. type RuntimeModelFactory = NonNullable<AgentRuntimeDeps["modelFactory"]>;
  24. type RuntimeModelFactoryInput = Parameters<RuntimeModelFactory>[0];
  25. export function createTestInputFormat(override: Partial<ModelInputFormat> = {}): ModelInputFormat {
  26. return {
  27. supportsText: true,
  28. supportsImage: true,
  29. supportsVideo: true,
  30. supportsAudio: false,
  31. supportsPdf: true,
  32. ...override,
  33. };
  34. }
  35. export function createTestModelFormatProperties(inputFormat: Partial<ModelInputFormat> = {}) {
  36. return {
  37. inputFormat: createTestInputFormat(inputFormat),
  38. outputFormat: { supportsText: true as const },
  39. };
  40. }
  41. export function createTestRuntimeModel(input: {
  42. contextWindow?: number;
  43. generateText: (request: ModelRequest) => Promise<ModelResult>;
  44. inputFormat?: Partial<ModelInputFormat>;
  45. maxOutputTokens?: number;
  46. modelId?: string;
  47. providerId?: string;
  48. properties?: ModelProperties;
  49. propertyOverrides?: Partial<ModelProperties>;
  50. options?: ModelOptions;
  51. }): Model {
  52. const maxOutputTokens = input.maxOutputTokens ?? 32_000;
  53. const options = {
  54. maxOutputTokens,
  55. reasoningLevel: "disabled",
  56. ...input.options,
  57. };
  58. const model: Model = {
  59. providerId: createModelProviderId(input.providerId ?? "test"),
  60. modelId: createModelId(input.modelId ?? "model"),
  61. properties:
  62. input.properties ??
  63. ({
  64. contextWindow: input.contextWindow ?? 200_000,
  65. ...createTestModelFormatProperties(input.inputFormat),
  66. supportsToolCall: true,
  67. supportsJsonSchemaOutput: true,
  68. supportsNativeWebSearch: false,
  69. supportsMidConversationSystem: true,
  70. ...input.propertyOverrides,
  71. } satisfies ModelProperties),
  72. optionSpecs: {
  73. reasoningLevel: { values: ["disabled"] },
  74. maxOutputTokens: { max: maxOutputTokens },
  75. },
  76. options,
  77. bind(nextOptions) {
  78. return createTestRuntimeModel({ ...input, options: { ...options, ...nextOptions } });
  79. },
  80. generateText: input.generateText,
  81. async *streamText(request) {
  82. const result = await input.generateText(request);
  83. if (result.text) {
  84. yield { id: "test-text", type: "text_start" };
  85. yield { id: "test-text", type: "text_delta", text: result.text };
  86. yield { id: "test-text", type: "text_end" };
  87. }
  88. yield {
  89. type: "finish",
  90. finishReason: result.finishReason,
  91. usage: result.usage,
  92. };
  93. },
  94. };
  95. return model;
  96. }
  97. export interface TestModelExecutionObservation {
  98. factoryInput: RuntimeModelFactoryInput;
  99. invocationContext: ModelInvocationContext | undefined;
  100. model: Pick<Model, "providerId" | "modelId" | "options">;
  101. }
  102. export function createTestModelFactory(implementation: {
  103. generateText?: (
  104. request: ModelRequest,
  105. observation: TestModelExecutionObservation,
  106. ) => Promise<ModelResult>;
  107. onCreate?: (input: RuntimeModelFactoryInput) => void;
  108. maxOutputTokens?: number | ((input: RuntimeModelFactoryInput) => number);
  109. properties?: Partial<ModelProperties>;
  110. reasoningLevels?: readonly string[] | null;
  111. streamText?: (
  112. request: ModelRequest,
  113. observation: TestModelExecutionObservation,
  114. ) => AsyncIterable<ModelEvent>;
  115. }): RuntimeModelFactory {
  116. return (input) => {
  117. implementation.onCreate?.(input);
  118. const observe = (options: ModelOptions): TestModelExecutionObservation => ({
  119. factoryInput: input,
  120. invocationContext: getCurrentModelInvocationContext(),
  121. model: {
  122. providerId: createModelProviderId(input.selection.providerId),
  123. modelId: createModelId(input.selection.modelId),
  124. options,
  125. },
  126. });
  127. const maxOutputTokens =
  128. typeof implementation.maxOutputTokens === "function"
  129. ? implementation.maxOutputTokens(input)
  130. : (implementation.maxOutputTokens ?? 32_000);
  131. const createModel = (options: ModelOptions): Model => {
  132. const generateText =
  133. implementation.generateText === undefined
  134. ? async () => {
  135. throw new Error("测试 Model 未实现 generateText");
  136. }
  137. : (request: ModelRequest) => implementation.generateText!(request, observe(options));
  138. const model = createTestRuntimeModel({
  139. generateText,
  140. maxOutputTokens,
  141. modelId: input.selection.modelId,
  142. options,
  143. propertyOverrides: {
  144. supportsMidConversationSystem: false,
  145. ...implementation.properties,
  146. },
  147. providerId: input.selection.providerId,
  148. });
  149. const reasoningLevels =
  150. implementation.reasoningLevels === null
  151. ? (["disabled"] as const)
  152. : (implementation.reasoningLevels ?? (["low", "high"] as const));
  153. return Object.freeze({
  154. ...model,
  155. optionSpecs: Object.freeze({
  156. ...model.optionSpecs,
  157. reasoningLevel: Object.freeze({
  158. values: Object.freeze([...reasoningLevels]),
  159. }),
  160. }),
  161. bind(nextOptions) {
  162. return createModel({ ...options, ...nextOptions });
  163. },
  164. ...(implementation.streamText
  165. ? {
  166. streamText: (request: ModelRequest) =>
  167. implementation.streamText!(request, observe(options)),
  168. }
  169. : {}),
  170. });
  171. };
  172. return createModel({
  173. ...input.selection.options,
  174. reasoningLevel:
  175. input.selection.options?.reasoningLevel ??
  176. (implementation.reasoningLevels === null
  177. ? ["disabled"]
  178. : (implementation.reasoningLevels ?? ["low", "high"])
  179. ).at(-1)!,
  180. });
  181. };
  182. }
  183. type TestModelAdapter = {
  184. generateText: (request: ModelRequest) => Promise<ModelResult>;
  185. streamText?: (request: ModelRequest) => AsyncIterable<ModelEvent>;
  186. };
  187. type TestRuntimeConfig = Omit<AgentRuntimeConfig, "modelSelection"> &
  188. Partial<Pick<AgentRuntimeConfig, "modelSelection">>;
  189. type TestRuntimeDeps = Omit<AgentRuntimeDeps, "modelFactory"> &
  190. Partial<Pick<AgentRuntimeDeps, "modelFactory">> & {
  191. /** 脚本化 adapter:包成测试 ModelFactory;给了 modelFactory 时忽略。 */
  192. modelAdapter?: TestModelAdapter;
  193. };
  194. export function createTestModelSelection(
  195. input: string | ModelSelection,
  196. options?: ModelSelection["options"],
  197. ): ModelSelection {
  198. if (typeof input !== "string") {
  199. return {
  200. providerId: input.providerId,
  201. modelId: input.modelId,
  202. ...(input.options ? { options: { ...input.options } } : {}),
  203. };
  204. }
  205. const separator = input.indexOf("/");
  206. if (separator <= 0 || separator === input.length - 1) {
  207. throw new Error(`Test model selection must be provider-qualified: ${input}`);
  208. }
  209. return {
  210. providerId: input.slice(0, separator),
  211. modelId: input.slice(separator + 1),
  212. ...(options ? { options: { ...options } } : {}),
  213. };
  214. }
  215. /** 把脚本化 adapter 包成测试 ModelFactory(与 createTestAgentRuntime 同一条换算)。 */
  216. export function createTestModelFactoryFromAdapter(modelAdapter: TestModelAdapter): RuntimeModelFactory {
  217. return createTestModelFactory({
  218. generateText: (request) => modelAdapter.generateText(request),
  219. ...(modelAdapter.streamText
  220. ? { streamText: (request) => modelAdapter.streamText!(request) }
  221. : {}),
  222. });
  223. }
  224. /**
  225. * 低层 Runtime 测试也显式经过 ModelFactory/ModelSelection 契约:
  226. * 缺省 selection 为 `test/default-runtime-model`,缺省 Model 不联网。
  227. */
  228. export function createTestAgentRuntime(
  229. sessionId: ConstructorParameters<typeof AgentRuntime>[0],
  230. config: TestRuntimeConfig,
  231. deps: TestRuntimeDeps,
  232. ): AgentRuntime {
  233. const modelSelection =
  234. config.modelSelection ?? createTestModelSelection("test/default-runtime-model");
  235. const { modelAdapter, ...runtimeDeps } = deps;
  236. const modelFactory =
  237. deps.modelFactory ??
  238. (modelAdapter ? createTestModelFactoryFromAdapter(modelAdapter) : createTestModelFactory({}));
  239. return new AgentRuntime(sessionId, { ...config, modelSelection }, { ...runtimeDeps, modelFactory });
  240. }