strict-tool-schema.test.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. // ============================================================
  2. // Anthropic strict 工具 schema:资格判定 + 子集折叠
  3. // ============================================================
  4. import { describe, expect, it } from "vitest";
  5. import type { ModelToolContract } from "@zcode/contracts";
  6. import { toAiSdkTools } from "../src/model/index.js";
  7. import {
  8. isAnthropicFirstPartyModelId,
  9. toStrictToolSchema,
  10. } from "../src/model/strict-tool-schema.js";
  11. /** dwf 合成器会发射的一份典型 mono 子代理 schema(外层 `{ result }` 由 contracts 包起来)。 */
  12. const REVIEW_SCHEMA = {
  13. type: "object",
  14. properties: {
  15. result: {
  16. type: "object",
  17. description: "The structured result for this ask.",
  18. properties: {
  19. findings: {
  20. type: "array",
  21. items: {
  22. type: "object",
  23. properties: {
  24. file: { type: "string", description: "Where it is." },
  25. line: { type: "number", minimum: 1 },
  26. severity: { enum: ["low", "high"] },
  27. evidence: { type: "string", minLength: 3, maxLength: 200 },
  28. },
  29. required: ["file", "line", "severity"],
  30. additionalProperties: false,
  31. },
  32. },
  33. adequate: { type: "boolean" },
  34. notes: { anyOf: [{ type: "null" }, { type: "string", pattern: "^[a-z]+$" }] },
  35. when: { type: "string", format: "date-time" },
  36. slug: { type: "string", format: "kebab-case" },
  37. },
  38. required: ["findings", "adequate", "notes"],
  39. additionalProperties: false,
  40. },
  41. },
  42. required: ["result"],
  43. additionalProperties: false,
  44. };
  45. function submitContract(inputSchema: Record<string, unknown>, strict = true): ModelToolContract {
  46. return {
  47. name: "submit_result",
  48. capability: "submit",
  49. description: "Submit the structured result for the current ask.",
  50. inputSchema,
  51. outputSchema: { type: "object" },
  52. ...(strict ? { strict: true } : {}),
  53. };
  54. }
  55. function schemaOf(toolValue: unknown): Record<string, unknown> {
  56. return (toolValue as { inputSchema: { jsonSchema: Record<string, unknown> } }).inputSchema
  57. .jsonSchema;
  58. }
  59. function at(schema: Record<string, unknown>, path: string[]): Record<string, unknown> {
  60. let node: Record<string, unknown> = schema;
  61. for (const segment of path) node = node[segment] as Record<string, unknown>;
  62. return node;
  63. }
  64. describe("toStrictToolSchema — folding", () => {
  65. it("removes the keywords strict cannot take and folds them into descriptions", () => {
  66. const strict = toStrictToolSchema(REVIEW_SCHEMA);
  67. expect(strict).toBeDefined();
  68. const finding = at(strict!, [
  69. "properties",
  70. "result",
  71. "properties",
  72. "findings",
  73. "items",
  74. "properties",
  75. ]);
  76. expect(finding.line).toEqual({ type: "number", description: "minimum 1" });
  77. expect(finding.evidence).toEqual({
  78. type: "string",
  79. description: "at least 3 characters; at most 200 characters",
  80. });
  81. // 既有 description 保留在前,折叠的约束跟在括号里。
  82. expect(finding.file).toEqual({ type: "string", description: "Where it is." });
  83. const result = at(strict!, ["properties", "result", "properties"]);
  84. expect((result.notes as { anyOf: unknown[] }).anyOf[1]).toEqual({
  85. type: "string",
  86. description: "must match /^[a-z]+$/",
  87. });
  88. // strict 认识的 format 保留;不认识的折进 description。
  89. expect(result.when).toEqual({ type: "string", format: "date-time" });
  90. expect(result.slug).toEqual({ type: "string", description: "format kebab-case" });
  91. });
  92. it("leaves an already-strict schema byte-identical and never mutates its input", () => {
  93. const input = {
  94. type: "object",
  95. properties: { ok: { type: "boolean" }, tags: { type: "array", items: { enum: ["a", "b"] } } },
  96. required: ["ok"],
  97. additionalProperties: false,
  98. };
  99. const snapshot = JSON.stringify(input);
  100. expect(toStrictToolSchema(input)).toEqual(input);
  101. expect(JSON.stringify(input)).toBe(snapshot);
  102. });
  103. it("closes objects that forgot additionalProperties and gives them an empty properties map", () => {
  104. expect(toStrictToolSchema({ type: "object", required: [] })).toEqual({
  105. type: "object",
  106. required: [],
  107. properties: {},
  108. additionalProperties: false,
  109. });
  110. });
  111. it("appends folded constraints to an existing description in parentheses", () => {
  112. expect(
  113. toStrictToolSchema({ type: "integer", description: "Age.", minimum: 0, maximum: 150 }),
  114. ).toEqual({
  115. type: "integer",
  116. description: "Age. (minimum 0; maximum 150)",
  117. });
  118. });
  119. });
  120. describe("toStrictToolSchema — ineligible shapes", () => {
  121. it.each([
  122. ["Record<string, T>", { type: "object", additionalProperties: { type: "string" } }],
  123. [
  124. "unknown ({})",
  125. { type: "object", properties: { any: {} }, required: ["any"], additionalProperties: false },
  126. ],
  127. [
  128. "recursive $ref",
  129. { type: "object", properties: { next: { $ref: "#/$defs/Node" } }, $defs: { Node: {} } },
  130. ],
  131. ["tuple", { type: "array", prefixItems: [{ type: "string" }], minItems: 1, maxItems: 1 }],
  132. [
  133. "nested Record inside anyOf",
  134. { anyOf: [{ type: "null" }, { type: "object", additionalProperties: { type: "number" } }] },
  135. ],
  136. ])("returns undefined for %s", (_label, schema) => {
  137. expect(toStrictToolSchema(schema as Record<string, unknown>)).toBeUndefined();
  138. });
  139. });
  140. describe("isAnthropicFirstPartyModelId", () => {
  141. it.each(["claude-opus-5"])("accepts %s", (id) => {
  142. expect(isAnthropicFirstPartyModelId(id)).toBe(true);
  143. });
  144. it.each(["glm-5.3", "anthropic/claude-opus-5", undefined])("rejects %s", (id) => {
  145. expect(isAnthropicFirstPartyModelId(id)).toBe(false);
  146. });
  147. });
  148. describe("toAiSdkTools — strict forwarding", () => {
  149. it("forwards strict with the folded schema for an eligible contract on a first-party Claude model", () => {
  150. const tools = toAiSdkTools([submitContract(REVIEW_SCHEMA)], {
  151. providerKind: "anthropic",
  152. modelId: "claude-opus-5",
  153. });
  154. const tool = tools?.submit_result as { strict?: boolean } | undefined;
  155. expect(tool?.strict).toBe(true);
  156. const line = at(schemaOf(tool), [
  157. "properties",
  158. "result",
  159. "properties",
  160. "findings",
  161. "items",
  162. "properties",
  163. "line",
  164. ]);
  165. expect(line).toEqual({ type: "number", description: "minimum 1" });
  166. });
  167. it("sends the original schema without strict when the model is not first-party Claude", () => {
  168. const tools = toAiSdkTools([submitContract(REVIEW_SCHEMA)], {
  169. providerKind: "anthropic",
  170. modelId: "glm-5.3",
  171. });
  172. const tool = tools?.submit_result as { strict?: boolean } | undefined;
  173. expect(tool?.strict).toBeUndefined();
  174. expect(schemaOf(tool)).toEqual(REVIEW_SCHEMA);
  175. });
  176. it("sends the original schema without strict on non-Anthropic providers", () => {
  177. const tools = toAiSdkTools([submitContract(REVIEW_SCHEMA)], {
  178. providerKind: "openai-compatible",
  179. modelId: "claude-opus-5",
  180. });
  181. const tool = tools?.submit_result as { strict?: boolean } | undefined;
  182. expect(tool?.strict).toBeUndefined();
  183. expect(schemaOf(tool)).toEqual(REVIEW_SCHEMA);
  184. });
  185. it("ignores strict for a contract that never declared eligibility", () => {
  186. const tools = toAiSdkTools([submitContract(REVIEW_SCHEMA, false)], {
  187. providerKind: "anthropic",
  188. modelId: "claude-opus-5",
  189. });
  190. expect((tools?.submit_result as { strict?: boolean } | undefined)?.strict).toBeUndefined();
  191. });
  192. it("falls back to the full schema without strict when the shape is not expressible", () => {
  193. const recordSchema = {
  194. type: "object",
  195. properties: { result: { type: "object", additionalProperties: { type: "string" } } },
  196. required: ["result"],
  197. additionalProperties: false,
  198. };
  199. const tools = toAiSdkTools([submitContract(recordSchema)], {
  200. providerKind: "anthropic",
  201. modelId: "claude-opus-5",
  202. });
  203. const tool = tools?.submit_result as { strict?: boolean } | undefined;
  204. expect(tool?.strict).toBeUndefined();
  205. expect(schemaOf(tool)).toEqual(recordSchema);
  206. });
  207. });