test-runtime-model.ts 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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?: Partial<ModelProperties>;
  100. reasoningLevels?: readonly string[] | null;
  101. streamText?: (
  102. request: ModelRequest,
  103. observation: TestModelExecutionObservation,
  104. ) => AsyncIterable<ModelEvent>;
  105. }): RuntimeModelFactory {
  106. return (input) => {
  107. implementation.onCreate?.(input);
  108. const observe = (options: ModelOptions): TestModelExecutionObservation => ({
  109. factoryInput: input,
  110. invocationContext: getCurrentModelInvocationContext(),
  111. model: {
  112. providerId: createModelProviderId(input.selection.providerId),
  113. modelId: createModelId(input.selection.modelId),
  114. options,
  115. },
  116. });
  117. const maxOutputTokens =
  118. typeof implementation.maxOutputTokens === "function"
  119. ? implementation.maxOutputTokens(input)
  120. : (implementation.maxOutputTokens ?? 32_000);
  121. const createModel = (options: ModelOptions): Model => {
  122. const generateText =
  123. implementation.generateText === undefined
  124. ? async () => {
  125. throw new Error("测试 Model 未实现 generateText");
  126. }
  127. : (request: ModelRequest) => implementation.generateText!(request, observe(options));
  128. const model = createTestRuntimeModel({
  129. generateText,
  130. maxOutputTokens,
  131. modelId: input.selection.modelId,
  132. options,
  133. propertyOverrides: {
  134. supportsMidConversationSystem: false,
  135. ...implementation.properties,
  136. },
  137. providerId: input.selection.providerId,
  138. });
  139. const reasoningLevels =
  140. implementation.reasoningLevels === null
  141. ? (["disabled"] as const)
  142. : (implementation.reasoningLevels ?? (["low", "high"] as const));
  143. return Object.freeze({
  144. ...model,
  145. optionSpecs: Object.freeze({
  146. ...model.optionSpecs,
  147. reasoningLevel: Object.freeze({
  148. values: Object.freeze([...reasoningLevels]),
  149. }),
  150. }),
  151. bind(nextOptions) {
  152. return createModel({ ...options, ...nextOptions });
  153. },
  154. ...(implementation.streamText
  155. ? {
  156. streamText: (request: ModelRequest) =>
  157. implementation.streamText!(request, observe(options)),
  158. }
  159. : {}),
  160. });
  161. };
  162. return createModel({
  163. ...input.selection.options,
  164. reasoningLevel:
  165. input.selection.options?.reasoningLevel ??
  166. (implementation.reasoningLevels === null
  167. ? ["disabled"]
  168. : (implementation.reasoningLevels ?? ["low", "high"])
  169. ).at(-1)!,
  170. });
  171. };
  172. }