test-runtime-model.ts 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. import {
  2. createModelId,
  3. createModelProviderId,
  4. getCurrentModelInvocationContext,
  5. type Model,
  6. type ModelEvent,
  7. type ModelInputFormat,
  8. type ModelInvocationContext,
  9. type ModelOptions,
  10. type ModelProperties,
  11. type ModelRequest,
  12. type ModelResult,
  13. } from "@zcode/contracts";
  14. import type { RuntimeModelFactory, RuntimeModelFactoryInput } from "../src/runtime/types.js";
  15. export function createTestInputFormat(override: Partial<ModelInputFormat> = {}): ModelInputFormat {
  16. return {
  17. supportsText: true,
  18. supportsImage: true,
  19. supportsVideo: true,
  20. supportsAudio: false,
  21. supportsPdf: true,
  22. ...override,
  23. };
  24. }
  25. export function createTestModelFormatProperties(inputFormat: Partial<ModelInputFormat> = {}) {
  26. return {
  27. inputFormat: createTestInputFormat(inputFormat),
  28. outputFormat: { supportsText: true as const },
  29. };
  30. }
  31. export function createTestRuntimeModel(input: {
  32. contextWindow?: number;
  33. generateText: (request: ModelRequest) => Promise<ModelResult>;
  34. inputFormat?: Partial<ModelInputFormat>;
  35. maxOutputTokens?: number;
  36. modelId?: string;
  37. providerId?: string;
  38. properties?: ModelProperties;
  39. propertyOverrides?: Partial<ModelProperties>;
  40. options?: ModelOptions;
  41. }): Model {
  42. const maxOutputTokens = input.maxOutputTokens ?? 32_000;
  43. const options = {
  44. maxOutputTokens,
  45. reasoningLevel: "disabled",
  46. ...input.options,
  47. };
  48. const model: Model = {
  49. providerId: createModelProviderId(input.providerId ?? "test"),
  50. modelId: createModelId(input.modelId ?? "model"),
  51. properties:
  52. input.properties ??
  53. ({
  54. contextWindow: input.contextWindow ?? 200_000,
  55. ...createTestModelFormatProperties(input.inputFormat),
  56. supportsToolCall: true,
  57. supportsJsonSchemaOutput: true,
  58. supportsNativeWebSearch: false,
  59. supportsMidConversationSystem: true,
  60. ...input.propertyOverrides,
  61. } satisfies ModelProperties),
  62. optionSpecs: {
  63. reasoningLevel: { values: ["disabled"] },
  64. maxOutputTokens: { max: maxOutputTokens },
  65. },
  66. options,
  67. bind(nextOptions) {
  68. return createTestRuntimeModel({ ...input, options: { ...options, ...nextOptions } });
  69. },
  70. generateText: input.generateText,
  71. async *streamText(request) {
  72. const result = await input.generateText(request);
  73. if (result.text) {
  74. yield { id: "test-text", type: "text_start" };
  75. yield { id: "test-text", type: "text_delta", text: result.text };
  76. yield { id: "test-text", type: "text_end" };
  77. }
  78. yield {
  79. type: "finish",
  80. finishReason: result.finishReason,
  81. usage: result.usage,
  82. };
  83. },
  84. };
  85. return model;
  86. }
  87. export interface TestModelExecutionObservation {
  88. factoryInput: RuntimeModelFactoryInput;
  89. invocationContext: ModelInvocationContext | undefined;
  90. model: Pick<Model, "providerId" | "modelId" | "options">;
  91. }
  92. export function createTestModelFactory(implementation: {
  93. generateText?: (
  94. request: ModelRequest,
  95. observation: TestModelExecutionObservation,
  96. ) => Promise<ModelResult>;
  97. onCreate?: (input: RuntimeModelFactoryInput) => void;
  98. maxOutputTokens?: number | ((input: RuntimeModelFactoryInput) => number);
  99. properties?:
  100. | Partial<ModelProperties>
  101. | ((input: RuntimeModelFactoryInput) => Partial<ModelProperties>);
  102. reasoningLevels?: readonly string[] | null;
  103. streamText?: (
  104. request: ModelRequest,
  105. observation: TestModelExecutionObservation,
  106. ) => AsyncIterable<ModelEvent>;
  107. }): RuntimeModelFactory {
  108. return (input) => {
  109. implementation.onCreate?.(input);
  110. const observe = (options: ModelOptions): TestModelExecutionObservation => ({
  111. factoryInput: input,
  112. invocationContext: getCurrentModelInvocationContext(),
  113. model: {
  114. providerId: createModelProviderId(input.selection.providerId),
  115. modelId: createModelId(input.selection.modelId),
  116. options,
  117. },
  118. });
  119. const maxOutputTokens =
  120. typeof implementation.maxOutputTokens === "function"
  121. ? implementation.maxOutputTokens(input)
  122. : (implementation.maxOutputTokens ?? 32_000);
  123. const properties =
  124. typeof implementation.properties === "function"
  125. ? implementation.properties(input)
  126. : implementation.properties;
  127. const createModel = (options: ModelOptions): Model => {
  128. const generateText =
  129. implementation.generateText === undefined
  130. ? async () => {
  131. throw new Error("测试 Model 未实现 generateText");
  132. }
  133. : (request: ModelRequest) => implementation.generateText!(request, observe(options));
  134. const model = createTestRuntimeModel({
  135. generateText,
  136. maxOutputTokens,
  137. modelId: input.selection.modelId,
  138. options,
  139. propertyOverrides: {
  140. supportsMidConversationSystem: false,
  141. ...properties,
  142. },
  143. providerId: input.selection.providerId,
  144. });
  145. const reasoningLevels =
  146. implementation.reasoningLevels === null
  147. ? (["disabled"] as const)
  148. : (implementation.reasoningLevels ?? (["low", "high"] as const));
  149. return Object.freeze({
  150. ...model,
  151. optionSpecs: Object.freeze({
  152. ...model.optionSpecs,
  153. reasoningLevel: Object.freeze({
  154. values: Object.freeze([...reasoningLevels]),
  155. }),
  156. }),
  157. bind(nextOptions) {
  158. return createModel({ ...options, ...nextOptions });
  159. },
  160. ...(implementation.streamText
  161. ? {
  162. streamText: (request: ModelRequest) =>
  163. implementation.streamText!(request, observe(options)),
  164. }
  165. : {}),
  166. });
  167. };
  168. return createModel({
  169. ...input.selection.options,
  170. reasoningLevel:
  171. input.selection.options?.reasoningLevel ??
  172. (implementation.reasoningLevels === null
  173. ? ["disabled"]
  174. : (implementation.reasoningLevels ?? ["low", "high"])
  175. ).at(-1)!,
  176. });
  177. };
  178. }