builtin-mcs-search-wire.test.ts 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. import { readFile } from "node:fs/promises";
  2. import { describe, expect, it, vi } from "vitest";
  3. import {
  4. createModelId,
  5. createModelProviderId,
  6. WEBSEARCH_PROVIDER_NATIVE_SPEC,
  7. WEBSEARCH_TOOL_CONTRACT,
  8. } from "@zcode/contracts";
  9. import {
  10. createRegistryModelConfig,
  11. createRegistryProviderConfig,
  12. parseModelConfig,
  13. parseProviderConfig,
  14. parseZCodeBuiltinModelConfigRules,
  15. } from "@zcode/provider";
  16. import { buildProviderRequestMessages } from "../../core/src/runtime/helpers/provider-request-messages.js";
  17. import { AiSdkModelAdapter } from "../src/model/runner.js";
  18. describe("Published MCS and search final Anthropic wire", () => {
  19. it.each([
  20. [
  21. "account:zai-start-plan",
  22. "https://zcode.z.ai/api/v1/zcode-plan/anthropic",
  23. "GLM-5.3-Flash",
  24. true,
  25. true,
  26. ],
  27. [
  28. "account:bigmodel-start-plan",
  29. "https://zcode.z.ai/api/v1/zcode-plan/anthropic",
  30. "GLM-5.3-Flash",
  31. true,
  32. true,
  33. ],
  34. [
  35. "account:zai-offpeak-idle-plan",
  36. "https://zcode.z.ai/api/v1/off-peak/anthropic",
  37. "GLM-5.3-Flash",
  38. true,
  39. false,
  40. ],
  41. [
  42. "account:bigmodel-offpeak-idle-plan",
  43. "https://zcode.z.ai/api/v1/off-peak/anthropic",
  44. "GLM-5.3-Flash",
  45. true,
  46. false,
  47. ],
  48. ["fixture", "https://api.anthropic.com/v1", "claude-sonnet-5", false, true],
  49. ["fixture", "https://proxy.invalid/v1", "vendor/claude-opus-4-8", true, false],
  50. ["personal-off", "https://proxy.invalid/v1", "vendor/claude-opus-4-8", false, false],
  51. ] as const)("%s / %s / %s", async (providerId, baseUrl, modelId, mcs, search) => {
  52. const release = JSON.parse(
  53. await readFile(
  54. new URL("../../../../../config/provider/zcode-builtin.json", import.meta.url),
  55. "utf8",
  56. ),
  57. );
  58. const rules = parseZCodeBuiltinModelConfigRules(release.config.modelConfigRules);
  59. let config = rules.resolve({ providerId, baseUrl, modelId, apiType: "anthropic-messages" });
  60. if (providerId === "personal-off")
  61. config = config.overlay(
  62. parseModelConfig({ properties: { supportsMidConversationSystem: false } }),
  63. );
  64. const modelConfig = createRegistryModelConfig(config);
  65. const providerConfig = createRegistryProviderConfig(
  66. parseProviderConfig({
  67. group: "standard-personal",
  68. access: { type: "api-key", apiKey: "fixture-not-a-real-key" },
  69. api: { type: "anthropic-messages", baseUrl },
  70. }),
  71. );
  72. if (!modelConfig.ok || !providerConfig.ok) throw new Error("Incomplete fixture");
  73. const bodies: Array<{
  74. messages: Array<{ role: string; content: unknown }>;
  75. tools?: unknown[];
  76. }> = [];
  77. vi.stubGlobal("fetch", async (url: RequestInfo | URL, init?: RequestInit) => {
  78. const request = new Request(url, init);
  79. expect(request.url).toBe(`${baseUrl}${baseUrl.endsWith("/v1") ? "" : "/v1"}/messages`);
  80. bodies.push(await request.json());
  81. return Response.json({
  82. id: "fixture",
  83. type: "message",
  84. role: "assistant",
  85. model: modelId,
  86. content: [{ type: "text", text: "ok" }],
  87. stop_reason: "end_turn",
  88. stop_sequence: null,
  89. usage: { input_tokens: 1, output_tokens: 1 },
  90. });
  91. });
  92. try {
  93. const adapter = new AiSdkModelAdapter({
  94. env: {},
  95. retry: { maxAttempts: 1 },
  96. // 本用例验证模型配置与 wire;安全端口注入离线透传,独立安全契约用例覆盖官方版本校验。
  97. requestSecurityState: {
  98. createExecution: () => ({
  99. protectTransport: ({ transport }) => transport,
  100. take: () => [],
  101. }),
  102. },
  103. });
  104. const model = adapter.createModel({
  105. providerId: createModelProviderId(providerId),
  106. modelId: createModelId(modelId),
  107. providerConfig: providerConfig.config,
  108. modelConfig: modelConfig.config,
  109. options: {
  110. maxOutputTokens: 4_000,
  111. reasoningLevel: config.optionSpecs!.reasoningLevel!.values!.at(-1)!,
  112. },
  113. });
  114. expect(model.properties.supportsNativeWebSearch).toBe(search);
  115. await model.generateText({
  116. messages: buildProviderRequestMessages({
  117. useMidConversationSystem: model.properties.supportsMidConversationSystem,
  118. entries: [
  119. { message: { role: "system", content: "stable prefix" } },
  120. { message: { role: "user", content: "hello" }, metadata: { source: "real_user" } },
  121. {
  122. kind: "attachment",
  123. content: "CAPABILITY_REMINDER",
  124. metadata: { source: "output_style" },
  125. },
  126. ],
  127. }).messages,
  128. tools: search
  129. ? [
  130. {
  131. name: "web_search",
  132. capability: "web_search",
  133. description: "fixture search",
  134. executionMode: "providerNative",
  135. inputSchema: WEBSEARCH_TOOL_CONTRACT.inputSchema,
  136. outputSchema: WEBSEARCH_TOOL_CONTRACT.outputSchema,
  137. providerNative: WEBSEARCH_PROVIDER_NATIVE_SPEC,
  138. },
  139. ]
  140. : [],
  141. });
  142. expect(bodies).toHaveLength(1);
  143. const body = bodies[0]!;
  144. const reminder = body.messages.find((message) =>
  145. JSON.stringify(message.content).includes("CAPABILITY_REMINDER"),
  146. );
  147. expect(reminder?.role).toBe(mcs ? "system" : "user");
  148. if (!mcs) expect(JSON.stringify(reminder?.content)).toContain("<system-reminder>");
  149. if (search)
  150. expect(body.tools).toContainEqual(
  151. expect.objectContaining({ name: "web_search", type: "web_search_20260209" }),
  152. );
  153. } finally {
  154. vi.unstubAllGlobals();
  155. }
  156. });
  157. });