test-provider-config.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. import type { Model, ModelOptions, ModelProperties, ModelSelection } from "@zcode/contracts";
  2. import {
  3. ApiKeyAccessConfig,
  4. ModelConfig,
  5. ModelInputFormatConfig,
  6. ModelOptionSpecsConfig,
  7. ModelOutputFormatConfig,
  8. ModelPropertiesConfig,
  9. ProviderApiConfig,
  10. ProviderConfig,
  11. ZhipuAccountAccessConfig,
  12. type RegistryModelConfig,
  13. type RegistryProviderConfig,
  14. type ZhipuAccountMode,
  15. } from "@zcode/provider";
  16. import {
  17. AiSdkModelAdapter as ProductionAiSdkModelAdapter,
  18. type AiSdkModelAdapterOptions,
  19. type CreateAiSdkModelOptions,
  20. } from "../src/model/runner.js";
  21. import {
  22. AiSdkModelExecution,
  23. type AiSdkModelExecutionConfig,
  24. type AiSdkModelExecutionOptions,
  25. type AiSdkResolvedModel,
  26. } from "../src/model/model-execution.js";
  27. import { createTestModelProperties } from "./test-model-format.js";
  28. interface LegacyTestProviderConfig {
  29. readonly apiKey?: string;
  30. readonly baseURL?: string;
  31. readonly createLanguageModel?: (modelId: string) => unknown;
  32. readonly accountMode?: ZhipuAccountMode;
  33. readonly headers?: Readonly<Record<string, string>>;
  34. readonly kind: "anthropic" | "custom" | "openai" | "openai-compatible";
  35. readonly name?: string;
  36. readonly providerOptions?: Readonly<Record<string, unknown>>;
  37. }
  38. interface LegacyTestRegistryConfig extends AiSdkModelExecutionConfig {
  39. readonly defaultProvider?: string;
  40. readonly providers: Readonly<Record<string, LegacyTestProviderConfig>>;
  41. }
  42. interface TestCreateModelOptions {
  43. readonly accountMode?: ZhipuAccountMode;
  44. readonly displayName?: string;
  45. readonly providerId: string;
  46. readonly modelId: string;
  47. readonly optionSpecs?: RegistryModelConfig["optionSpecs"];
  48. readonly options?: ModelOptions;
  49. readonly properties?: ModelProperties;
  50. readonly requestDependencies?: CreateAiSdkModelOptions["requestDependencies"];
  51. }
  52. /**
  53. * 仅供旧 Adapter 行为测试组织多组输入数据。
  54. *
  55. * 它不是执行 Registry:每次创建 Model 时都会先解析出一份完整的单 Provider Config,
  56. * 再直接传给生产 Adapter。这样保留网络与请求回归覆盖,同时不会把已删除的查询层带回产品代码。
  57. */
  58. export class TestProviderConfigFixture {
  59. private config: LegacyTestRegistryConfig;
  60. private execution: AiSdkModelExecution;
  61. private readonly executionOptions: AiSdkModelExecutionOptions;
  62. constructor(config: LegacyTestRegistryConfig, options: AiSdkModelExecutionOptions = {}) {
  63. this.config = config;
  64. this.executionOptions = options;
  65. this.execution = new AiSdkModelExecution(this.executionConfig(), this.executionOptions);
  66. }
  67. replaceConfig(config: LegacyTestRegistryConfig): void {
  68. this.config = config;
  69. this.execution = new AiSdkModelExecution(this.executionConfig(), this.executionOptions);
  70. }
  71. resolveConfig(selection: ModelSelection | string, accountMode?: ZhipuAccountMode) {
  72. const resolvedSelection = parseTestSelection(selection, this.config.defaultProvider);
  73. const source = this.config.providers[resolvedSelection.providerId];
  74. if (!source) throw new Error(`Unknown test provider: ${resolvedSelection.providerId}`);
  75. return {
  76. modelId: resolvedSelection.modelId,
  77. providerConfig: toRegistryProviderConfig(resolvedSelection.providerId, source, accountMode),
  78. providerId: resolvedSelection.providerId,
  79. };
  80. }
  81. resolve(
  82. selection: ModelSelection | string,
  83. options: ModelOptions = { maxOutputTokens: 32_000, reasoningLevel: "disabled" },
  84. ): AiSdkResolvedModel {
  85. const resolvedSelection = parseTestSelection(selection, this.config.defaultProvider);
  86. const resolved = this.resolveConfig(resolvedSelection);
  87. const source = this.config.providers[resolvedSelection.providerId];
  88. if (!source) throw new Error(`Unknown test provider: ${resolvedSelection.providerId}`);
  89. const bound = this.execution.bindModel({
  90. ...resolved,
  91. supportsJsonSchemaOutput: false,
  92. optionSpecs: defaultOptionSpecs(resolved.providerConfig.api.type),
  93. });
  94. return bound.resolveRequest({
  95. options: { reasoningLevel: "disabled", ...options },
  96. ...(source.accountMode && source.apiKey ? { requestAuth: { apiKey: source.apiKey } } : {}),
  97. });
  98. }
  99. executionConfig(): AiSdkModelExecutionConfig {
  100. const { providers: _providers, defaultProvider: _defaultProvider, ...execution } = this.config;
  101. return execution;
  102. }
  103. }
  104. export class TestAiSdkModelAdapter extends ProductionAiSdkModelAdapter {
  105. readonly testProviderConfigs?: TestProviderConfigFixture;
  106. constructor(
  107. options: AiSdkModelAdapterOptions & { readonly registry?: TestProviderConfigFixture },
  108. ) {
  109. const { registry, ...productionOptions } = options;
  110. super({ ...productionOptions, ...registry?.executionConfig() });
  111. this.testProviderConfigs = registry;
  112. }
  113. createModel(options: CreateAiSdkModelOptions | TestCreateModelOptions): Model {
  114. if ("providerConfig" in options) return super.createModel(options);
  115. const fixture = this.testProviderConfigs;
  116. if (!fixture) throw new Error("Test Provider Config fixture is required");
  117. const resolved = fixture.resolveConfig(
  118. { providerId: options.providerId, modelId: options.modelId },
  119. options.accountMode ?? (options.requestDependencies?.requestAuth ? "off-peak" : undefined),
  120. );
  121. const requestDependencies =
  122. options.requestDependencies ??
  123. (options.accountMode === "off-peak"
  124. ? {
  125. requestAuth: {
  126. source: { resolve: async () => ({ apiKey: "test-off-peak-key" }) },
  127. },
  128. }
  129. : undefined);
  130. const modelConfig = createRegistryModelConfig(options, resolved.providerConfig.api.type);
  131. const reasoningValues = modelConfig.optionSpecs.reasoningLevel.values;
  132. return super.createModel({
  133. ...resolved,
  134. providerConfig: resolved.providerConfig,
  135. modelConfig,
  136. ...(options.displayName ? { displayName: options.displayName } : {}),
  137. options: {
  138. maxOutputTokens: Math.min(32_000, modelConfig.optionSpecs.maxOutputTokens.max),
  139. reasoningLevel: reasoningValues.at(-1) ?? "disabled",
  140. ...options.options,
  141. },
  142. ...(requestDependencies ? { requestDependencies } : {}),
  143. });
  144. }
  145. }
  146. export function createTestAiSdkModelAdapter(
  147. options: AiSdkModelAdapterOptions & { readonly registry?: TestProviderConfigFixture },
  148. ): TestAiSdkModelAdapter {
  149. return new TestAiSdkModelAdapter(options);
  150. }
  151. function createRegistryModelConfig(
  152. options: TestCreateModelOptions,
  153. apiType: RegistryProviderConfig["api"]["type"],
  154. ): RegistryModelConfig {
  155. const properties = options.properties ?? createTestModelProperties();
  156. const input = properties.inputFormat;
  157. const output = properties.outputFormat;
  158. return new ModelConfig({
  159. enabled: true,
  160. properties: new ModelPropertiesConfig({
  161. requiresMfjsToolSchema: false,
  162. ...properties,
  163. inputFormat: new ModelInputFormatConfig(input),
  164. outputFormat: new ModelOutputFormatConfig(output),
  165. }),
  166. optionSpecs: new ModelOptionSpecsConfig({
  167. maxOutputTokens: {
  168. ...(options.optionSpecs?.maxOutputTokens ?? {
  169. max: 1_000_000,
  170. }),
  171. map: options.optionSpecs?.maxOutputTokens.map ?? maxOutputTokensMap(apiType),
  172. },
  173. reasoningLevel: options.optionSpecs?.reasoningLevel
  174. ? {
  175. ...options.optionSpecs.reasoningLevel,
  176. map:
  177. options.optionSpecs.reasoningLevel.map ??
  178. enumOptionMap(
  179. Object.fromEntries(
  180. options.optionSpecs.reasoningLevel.values.map((value) => [value, {}]),
  181. ),
  182. ),
  183. }
  184. : {
  185. values: ["disabled"],
  186. map: "{}",
  187. },
  188. }),
  189. }) as RegistryModelConfig;
  190. }
  191. function maxOutputTokensMap(apiType: RegistryProviderConfig["api"]["type"]): string {
  192. switch (apiType) {
  193. case "anthropic-messages":
  194. return '{"max_tokens": maxOutputTokens}';
  195. case "openai-chat-completions":
  196. return '{"max_completion_tokens": maxOutputTokens}';
  197. case "openai-responses":
  198. return '{"max_output_tokens": maxOutputTokens}';
  199. }
  200. }
  201. function defaultOptionSpecs(apiType: RegistryProviderConfig["api"]["type"]) {
  202. return {
  203. reasoningLevel: {
  204. values: ["disabled"],
  205. map: "{}",
  206. },
  207. maxOutputTokens: {
  208. map: maxOutputTokensMap(apiType),
  209. },
  210. };
  211. }
  212. function enumOptionMap(mapping: Readonly<Record<string, unknown>>): string {
  213. const entries = Object.entries(mapping);
  214. return entries.reduceRight(
  215. (fallback, [value, parameters]) =>
  216. `reasoningLevel == ${JSON.stringify(value)} ? ${JSON.stringify(parameters)} : ${fallback}`,
  217. "{}",
  218. );
  219. }
  220. function toRegistryProviderConfig(
  221. providerId: string,
  222. source: LegacyTestProviderConfig,
  223. accountMode?: ZhipuAccountMode,
  224. ): RegistryProviderConfig {
  225. const effectiveAccountMode = accountMode ?? source.accountMode;
  226. const apiType =
  227. source.kind === "anthropic"
  228. ? "anthropic-messages"
  229. : source.kind === "openai"
  230. ? "openai-responses"
  231. : "openai-chat-completions";
  232. return new ProviderConfig({
  233. access: effectiveAccountMode
  234. ? new ZhipuAccountAccessConfig({
  235. accountType: "zai",
  236. mode: effectiveAccountMode,
  237. })
  238. : source.apiKey
  239. ? new ApiKeyAccessConfig({ apiKey: source.apiKey })
  240. : new ApiKeyAccessConfig({ apiKey: "test-api-key" }),
  241. api: new ProviderApiConfig({
  242. baseUrl: source.baseURL ?? "https://adapter.test/v1",
  243. headers: source.headers,
  244. type: apiType,
  245. }),
  246. builtinModelIds: [],
  247. enabled: true,
  248. id: providerId,
  249. personalModelIds: [],
  250. name: source.name ?? providerId,
  251. visibility: "visible",
  252. }) as RegistryProviderConfig;
  253. }
  254. function parseTestSelection(selection: ModelSelection | string, defaultProvider?: string) {
  255. if (typeof selection !== "string") {
  256. return { modelId: selection.modelId, providerId: selection.providerId };
  257. }
  258. const value = selection;
  259. const separator = value.indexOf("/");
  260. if (separator < 0) {
  261. if (!defaultProvider) throw new Error(`Test model requires provider id: ${value}`);
  262. return { modelId: value, providerId: defaultProvider };
  263. }
  264. return { modelId: value.slice(separator + 1), providerId: value.slice(0, separator) };
  265. }