provider-registry-model-runtime.test.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. import type { CreateAiSdkModelOptions } from "@zcode/adapters/model";
  2. import { ModelErrorCode, ModelProtocolError, type Model } from "@zcode/contracts";
  3. import {
  4. ModelConfig,
  5. ModelOptionSpecsConfig,
  6. ModelPropertiesConfig,
  7. ProviderApiConfig,
  8. ProviderConfig,
  9. ProviderRegistry,
  10. ZhipuAccountAccessConfig,
  11. type Provider,
  12. } from "@zcode/provider";
  13. import { describe, expect, it, vi } from "vitest";
  14. import { ApiProviderModelRuntime } from "../src/app/provider-registry-model-runtime.js";
  15. import {
  16. createAccountProviderConfig,
  17. createApiKeyProviderConfig,
  18. } from "./provider-config-fixtures.js";
  19. const properties = new ModelPropertiesConfig({
  20. requiresMfjsToolSchema: false,
  21. contextWindow: 200_000,
  22. inputFormat: {
  23. supportsText: true,
  24. supportsImage: true,
  25. supportsVideo: true,
  26. supportsAudio: false,
  27. supportsPdf: false,
  28. },
  29. outputFormat: { supportsText: true },
  30. supportsToolCall: true,
  31. supportsJsonSchemaOutput: true,
  32. supportsNativeWebSearch: false,
  33. supportsMidConversationSystem: true,
  34. });
  35. function modelConfig(): ModelConfig {
  36. return new ModelConfig({
  37. enabled: true,
  38. visibility: "visible",
  39. properties,
  40. optionSpecs: new ModelOptionSpecsConfig({
  41. reasoningLevel: {
  42. values: ["low", "high"],
  43. map: '{"reasoning_effort":reasoningLevel}',
  44. },
  45. maxOutputTokens: {
  46. max: 32_000,
  47. map: '{"max_completion_tokens":maxOutputTokens}',
  48. },
  49. }),
  50. });
  51. }
  52. function provider(
  53. providerId = "api-provider",
  54. config = createApiKeyProviderConfig({
  55. apiFormat: "openai-chat-completions",
  56. apiKey: "test-key",
  57. baseURL: "https://api.example.com",
  58. models: ["model-a"],
  59. }),
  60. ): Provider {
  61. return { providerId, config, models: [{ modelId: "model-a", config: modelConfig() }] };
  62. }
  63. function fakeModel(): Model {
  64. return {
  65. providerId: "api-provider" as Model["providerId"],
  66. modelId: "model-a" as Model["modelId"],
  67. properties: properties as Model["properties"],
  68. optionSpecs: modelConfig().optionSpecs as Model["optionSpecs"],
  69. options: { maxOutputTokens: 8_000 },
  70. bind() {
  71. return this;
  72. },
  73. async generateText() {
  74. throw new Error("not used");
  75. },
  76. streamText() {
  77. throw new Error("not used");
  78. },
  79. };
  80. }
  81. function selection(providerId = "api-provider") {
  82. return { providerId, modelId: "model-a", options: { reasoningLevel: "high" } };
  83. }
  84. function captureRuntime(registry: ProviderRegistry) {
  85. const created: CreateAiSdkModelOptions[] = [];
  86. const expected = fakeModel();
  87. const runtime = new ApiProviderModelRuntime({
  88. registry,
  89. modelAdapter: {
  90. createModel(options) {
  91. created.push(options);
  92. return expected;
  93. },
  94. },
  95. });
  96. runtime.start();
  97. return { created, expected, runtime };
  98. }
  99. describe("ApiProviderModelRuntime", () => {
  100. it("把 Registry 的完整 Provider / Model Config 原样交给 Adapter", () => {
  101. const registry = new ProviderRegistry([provider()]);
  102. const { created, expected, runtime } = captureRuntime(registry);
  103. expect(runtime.modelFactory({ selection: selection() })).toBe(expected);
  104. expect(created[0]).toMatchObject({
  105. providerId: "api-provider",
  106. modelId: "model-a",
  107. options: { reasoningLevel: "high" },
  108. });
  109. expect(created[0]?.options).not.toHaveProperty("maxOutputTokens");
  110. expect(created[0]?.providerConfig).toBe(registry.getProvider("api-provider")?.config);
  111. expect(created[0]?.modelConfig).toBe(registry.getModel("api-provider", "model-a")?.config);
  112. });
  113. it("Registry 更新只影响之后创建的 Model", () => {
  114. const first = provider();
  115. const registry = new ProviderRegistry([first]);
  116. const { created, runtime } = captureRuntime(registry);
  117. runtime.modelFactory({ selection: selection() });
  118. const second = provider(
  119. "api-provider",
  120. createApiKeyProviderConfig({
  121. apiFormat: "openai-responses",
  122. apiKey: "second-key",
  123. baseURL: "https://second.example.com",
  124. models: ["model-a"],
  125. }),
  126. );
  127. registry.replace([second], "test update");
  128. runtime.modelFactory({ selection: selection() });
  129. expect(created[0]?.providerConfig).toBe(first.config);
  130. expect(created[1]?.providerConfig).toBe(second.config);
  131. });
  132. it("Account Provider 直接传递账号访问配置", () => {
  133. const account = provider(
  134. "account-provider",
  135. createAccountProviderConfig({
  136. apiFormat: "anthropic-messages",
  137. baseURL: "https://account.example.com",
  138. models: ["model-a"],
  139. }),
  140. );
  141. const { created, runtime } = captureRuntime(new ProviderRegistry([account]));
  142. runtime.modelFactory({ selection: selection("account-provider") });
  143. expect(created[0]?.providerConfig).toBe(account.config);
  144. expect(created[0]?.providerConfig.access).toMatchObject({
  145. type: "zhipu-account",
  146. });
  147. });
  148. it("Off-Peak Provider 绑定调用方提供的请求鉴权 Source", () => {
  149. const requestProvider = provider(
  150. "request-provider",
  151. new ProviderConfig({
  152. access: new ZhipuAccountAccessConfig({ accountType: "zai", mode: "off-peak" }),
  153. api: new ProviderApiConfig({
  154. type: "anthropic-messages",
  155. baseUrl: "https://request.example.com",
  156. }),
  157. builtinModelIds: ["model-a"],
  158. personalModelIds: [],
  159. visibility: "hidden",
  160. }),
  161. );
  162. const source = { resolve: vi.fn() };
  163. const { created, runtime } = captureRuntime(new ProviderRegistry([requestProvider]));
  164. runtime.modelFactory({
  165. selection: selection("request-provider"),
  166. requestDependencies: { requestAuth: { source } },
  167. });
  168. expect(created[0]?.requestDependencies?.requestAuth?.source).toBe(source);
  169. });
  170. it("Highspeed 卡 Provider 同样绑定执行作用域请求鉴权 Source", () => {
  171. // 回归:加速卡的 access.mode 是 "highspeed",与 Off-Peak 共用免签网关但凭据是本轮动态
  172. // 下发的 JWT + 卡 ID header。若这里漏掉 highspeed,source 在创建 Model 时被丢,runner
  173. // 会在发送前抛 model_request_auth_missing(本轮加速请求根本发不出去)。
  174. const highspeedProvider = provider(
  175. "account:bigmodel-highspeed-card",
  176. new ProviderConfig({
  177. access: new ZhipuAccountAccessConfig({ accountType: "bigmodel", mode: "highspeed" }),
  178. api: new ProviderApiConfig({
  179. type: "anthropic-messages",
  180. baseUrl: "https://highspeed.example.com",
  181. }),
  182. builtinModelIds: ["model-a"],
  183. personalModelIds: [],
  184. visibility: "hidden",
  185. }),
  186. );
  187. const source = { resolve: vi.fn() };
  188. const { created, runtime } = captureRuntime(new ProviderRegistry([highspeedProvider]));
  189. runtime.modelFactory({
  190. selection: selection("account:bigmodel-highspeed-card"),
  191. requestDependencies: { requestAuth: { source } },
  192. });
  193. expect(created[0]?.requestDependencies?.requestAuth?.source).toBe(source);
  194. });
  195. it("非 Off-Peak / Highspeed 的账号模式不转发执行作用域 Source", () => {
  196. // 门禁边界:Coding Plan 等静态鉴权模式不消费执行作用域 requestAuth,避免把 source
  197. // 无条件透传给所有账号 Provider(防止门禁被误放宽成永远转发)。
  198. const codingPlanProvider = provider(
  199. "coding-plan-provider",
  200. createAccountProviderConfig({
  201. apiFormat: "anthropic-messages",
  202. baseURL: "https://coding-plan.example.com",
  203. models: ["model-a"],
  204. mode: "individual-coding-plan",
  205. }),
  206. );
  207. const source = { resolve: vi.fn() };
  208. const { created, runtime } = captureRuntime(new ProviderRegistry([codingPlanProvider]));
  209. runtime.modelFactory({
  210. selection: selection("coding-plan-provider"),
  211. requestDependencies: { requestAuth: { source } },
  212. });
  213. expect(created[0]?.requestDependencies).toBeUndefined();
  214. });
  215. it("Registry 拥有 Provider 时,缺失 Model 不回退旧事实源", () => {
  216. const { runtime } = captureRuntime(new ProviderRegistry([provider()]));
  217. expect(() =>
  218. runtime.modelFactory({
  219. selection: { providerId: "api-provider", modelId: "missing" },
  220. }),
  221. ).toThrow("Provider Registry 中不存在 Model");
  222. });
  223. it("缺失 Provider 直接报错", () => {
  224. const { runtime } = captureRuntime(new ProviderRegistry([provider()]));
  225. expect(() => runtime.modelFactory({ selection: selection("missing") })).toThrow(
  226. "Provider Registry 中不存在 Provider: missing",
  227. );
  228. });
  229. it("创建前拒绝不支持的 reasoning level,不进入 Adapter", () => {
  230. const { created, runtime } = captureRuntime(new ProviderRegistry([provider()]));
  231. expect(() =>
  232. runtime.modelFactory({
  233. selection: {
  234. providerId: "api-provider",
  235. modelId: "model-a",
  236. options: { reasoningLevel: "max" },
  237. },
  238. }),
  239. ).toThrowError(
  240. expect.objectContaining<ModelProtocolError>({
  241. code: ModelErrorCode.InvalidModelRequest,
  242. message: 'Reasoning effort "max" is not supported by api-provider/model-a',
  243. }),
  244. );
  245. expect(created).toEqual([]);
  246. });
  247. });