model-provider-restart-config.ts 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. import {
  2. ApiKeyAccessConfig,
  3. ModelConfig,
  4. ModelOptionSpecsConfig,
  5. ModelPropertiesConfig,
  6. ProviderApiConfig,
  7. ProviderConfig,
  8. type ProviderApiType,
  9. } from "@zcode/provider";
  10. import { NodePersonalProviderConfigRepository } from "@zcode/provider-node";
  11. import type { ModelSelection } from "@zcode/shared/model-selection";
  12. const DEFAULT_CONTEXT_WINDOW = 200_000;
  13. const DEFAULT_MAX_OUTPUT_TOKENS = 32_000;
  14. export async function seedPersonalDefaultModelSelection(file: string, selection: ModelSelection) {
  15. const repository = new NodePersonalProviderConfigRepository({
  16. filePath: file,
  17. pollingIntervalMs: false,
  18. });
  19. try {
  20. await repository.update((current) => ({ ...current, defaultModelSelection: selection }));
  21. } finally {
  22. repository.dispose();
  23. }
  24. }
  25. export type SeedReplayProviderModel =
  26. | string
  27. | {
  28. readonly contextWindow?: number;
  29. readonly id: string;
  30. readonly limit?: { readonly output?: number };
  31. readonly maxOutputTokens?: number;
  32. readonly reasoningLevel?: PersonalModelConfigSeed["reasoningLevel"];
  33. };
  34. export interface PersonalModelConfigSeed {
  35. readonly enabled?: boolean;
  36. readonly reasoningLevel?: NonNullable<
  37. ConstructorParameters<typeof ModelOptionSpecsConfig>[0]
  38. >["reasoningLevel"];
  39. readonly contextWindow?: number;
  40. readonly id: string;
  41. readonly inputModalities?: readonly ("text" | "image" | "pdf" | "video")[];
  42. readonly maxOutputTokens?: number;
  43. readonly supportsJsonSchemaOutput?: boolean;
  44. readonly supportsToolCall?: boolean;
  45. readonly supportsMidConversationSystem?: boolean;
  46. }
  47. export interface PersonalProviderConfigSeed {
  48. readonly apiFormat: ProviderApiType;
  49. readonly apiKey: string;
  50. readonly baseURL: string;
  51. readonly enabled?: boolean;
  52. readonly headers?: Readonly<Record<string, string>>;
  53. readonly id: string;
  54. readonly label: string;
  55. readonly models: readonly PersonalModelConfigSeed[];
  56. readonly visibility?: "visible" | "hidden";
  57. /** 模拟用户从 Built-in 模板创建的 Provider;模型成员与默认访问方式由模板提供。 */
  58. readonly templateId?: string;
  59. }
  60. /**
  61. * 为 restart E2E 写入正式 Personal Config。
  62. *
  63. * Seed 直接表达正式 ProviderConfig 与 ModelConfig 字段,不经过旧 Store DTO。
  64. */
  65. export async function seedPersonalProviderConfig(
  66. file: string,
  67. provider: PersonalProviderConfigSeed,
  68. ) {
  69. // 固定 account:* Provider 的 Access 由 ZCode Built-in Config 所有;测试只需把
  70. // endpoint/model 事实切到 replay,不得在 Personal Config 再写 ApiKey Access,
  71. // 否则正式 schema 会拒绝“个人层覆盖计划 Access”的非法组合。
  72. const access = provider.id.startsWith("account:")
  73. ? undefined
  74. : new ApiKeyAccessConfig({
  75. apiKey: provider.apiKey,
  76. });
  77. const providerConfig = new ProviderConfig({
  78. group: "standard-personal",
  79. access,
  80. api: new ProviderApiConfig({
  81. type: provider.apiFormat,
  82. baseUrl: provider.baseURL,
  83. headers: provider.headers,
  84. }),
  85. personalModelIds: provider.models.map((model) => model.id),
  86. visibility: provider.visibility,
  87. });
  88. const repository = new NodePersonalProviderConfigRepository({
  89. filePath: file,
  90. pollingIntervalMs: false,
  91. });
  92. try {
  93. await repository.update((current) => ({
  94. ...current,
  95. providers: current.providers.setRule({
  96. providerId: provider.id,
  97. ...(provider.templateId ? { templateId: provider.templateId } : {}),
  98. providerName: provider.label,
  99. config: providerConfig,
  100. }),
  101. models: provider.models.reduce(
  102. (rules, model) =>
  103. rules.setExact(
  104. provider.id,
  105. model.id,
  106. modelConfigFromSeed(model, provider.apiFormat, provider.enabled ?? true),
  107. ),
  108. current.models.deleteExactForProvider(provider.id),
  109. ),
  110. }));
  111. } finally {
  112. repository.dispose();
  113. }
  114. }
  115. function modelConfigFromSeed(
  116. model: PersonalModelConfigSeed,
  117. apiFormat: ProviderApiType,
  118. enabled: boolean,
  119. ): ModelConfig {
  120. const inputs = new Set(model.inputModalities ?? ["text"]);
  121. const maxOutputTokens = model.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS;
  122. return new ModelConfig({
  123. // SSH 目标保留自己的 Built-in;通用 fixture 必须自行提供完整执行事实,不能靠本机补全。
  124. // 模型禁用必须写正式 enabled;旧 visibility 字段会被 schema 丢弃,让过滤用例误测可用模型。
  125. enabled: enabled && model.enabled !== false,
  126. properties: new ModelPropertiesConfig({
  127. requiresMfjsToolSchema: false,
  128. contextWindow: model.contextWindow ?? DEFAULT_CONTEXT_WINDOW,
  129. inputFormat: {
  130. supportsText: inputs.has("text"),
  131. supportsImage: inputs.has("image"),
  132. supportsVideo: inputs.has("video"),
  133. supportsAudio: inputs.has("audio"),
  134. supportsPdf: inputs.has("pdf"),
  135. },
  136. outputFormat: { supportsText: true },
  137. supportsToolCall: model.supportsToolCall ?? true,
  138. supportsJsonSchemaOutput: model.supportsJsonSchemaOutput ?? false,
  139. supportsNativeWebSearch: false,
  140. supportsMidConversationSystem: model.supportsMidConversationSystem ?? false,
  141. }),
  142. optionSpecs: new ModelOptionSpecsConfig({
  143. reasoningLevel: model.reasoningLevel ?? { values: ["disabled"], map: "{}" },
  144. maxOutputTokens: {
  145. max: maxOutputTokens,
  146. map: maxOutputTokensMap(apiFormat),
  147. },
  148. }),
  149. });
  150. }
  151. function maxOutputTokensMap(apiFormat: ProviderApiType): string {
  152. switch (apiFormat) {
  153. case "anthropic-messages":
  154. return '{"max_tokens":maxOutputTokens}';
  155. case "openai-chat-completions":
  156. return '{"max_completion_tokens":maxOutputTokens}';
  157. case "openai-responses":
  158. return '{"max_output_tokens":maxOutputTokens}';
  159. }
  160. }