structured-output.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. import { describe, expect, test } from "bun:test"
  2. import { MessageV2 } from "../../src/session/message-v2"
  3. import { SessionPrompt } from "../../src/session/prompt"
  4. import { SessionID, MessageID } from "../../src/session/schema"
  5. describe("structured-output.OutputFormat", () => {
  6. test("parses text format", () => {
  7. const result = MessageV2.Format.zod.safeParse({ type: "text" })
  8. expect(result.success).toBe(true)
  9. if (result.success) {
  10. expect(result.data.type).toBe("text")
  11. }
  12. })
  13. test("parses json_schema format with defaults", () => {
  14. const result = MessageV2.Format.zod.safeParse({
  15. type: "json_schema",
  16. schema: { type: "object", properties: { name: { type: "string" } } },
  17. })
  18. expect(result.success).toBe(true)
  19. if (result.success) {
  20. expect(result.data.type).toBe("json_schema")
  21. if (result.data.type === "json_schema") {
  22. expect(result.data.retryCount).toBe(2) // default value
  23. }
  24. }
  25. })
  26. test("parses json_schema format with custom retryCount", () => {
  27. const result = MessageV2.Format.zod.safeParse({
  28. type: "json_schema",
  29. schema: { type: "object" },
  30. retryCount: 5,
  31. })
  32. expect(result.success).toBe(true)
  33. if (result.success && result.data.type === "json_schema") {
  34. expect(result.data.retryCount).toBe(5)
  35. }
  36. })
  37. test("rejects invalid type", () => {
  38. const result = MessageV2.Format.zod.safeParse({ type: "invalid" })
  39. expect(result.success).toBe(false)
  40. })
  41. test("rejects json_schema without schema", () => {
  42. const result = MessageV2.Format.zod.safeParse({ type: "json_schema" })
  43. expect(result.success).toBe(false)
  44. })
  45. test("rejects negative retryCount", () => {
  46. const result = MessageV2.Format.zod.safeParse({
  47. type: "json_schema",
  48. schema: { type: "object" },
  49. retryCount: -1,
  50. })
  51. expect(result.success).toBe(false)
  52. })
  53. })
  54. describe("structured-output.StructuredOutputError", () => {
  55. test("creates error with message and retries", () => {
  56. const error = new MessageV2.StructuredOutputError({
  57. message: "Failed to validate",
  58. retries: 3,
  59. })
  60. expect(error.name).toBe("StructuredOutputError")
  61. expect(error.data.message).toBe("Failed to validate")
  62. expect(error.data.retries).toBe(3)
  63. })
  64. test("converts to object correctly", () => {
  65. const error = new MessageV2.StructuredOutputError({
  66. message: "Test error",
  67. retries: 2,
  68. })
  69. const obj = error.toObject()
  70. expect(obj.name).toBe("StructuredOutputError")
  71. expect(obj.data.message).toBe("Test error")
  72. expect(obj.data.retries).toBe(2)
  73. })
  74. test("isInstance correctly identifies error", () => {
  75. const error = new MessageV2.StructuredOutputError({
  76. message: "Test",
  77. retries: 1,
  78. })
  79. expect(MessageV2.StructuredOutputError.isInstance(error)).toBe(true)
  80. expect(MessageV2.StructuredOutputError.isInstance({ name: "other" })).toBe(false)
  81. })
  82. })
  83. describe("structured-output.UserMessage", () => {
  84. test("user message accepts outputFormat", () => {
  85. const result = MessageV2.User.zod.safeParse({
  86. id: MessageID.ascending(),
  87. sessionID: SessionID.descending(),
  88. role: "user",
  89. time: { created: Date.now() },
  90. agent: "default",
  91. model: { providerID: "anthropic", modelID: "claude-3" },
  92. outputFormat: {
  93. type: "json_schema",
  94. schema: { type: "object" },
  95. },
  96. })
  97. expect(result.success).toBe(true)
  98. })
  99. test("user message works without outputFormat (optional)", () => {
  100. const result = MessageV2.User.zod.safeParse({
  101. id: MessageID.ascending(),
  102. sessionID: SessionID.descending(),
  103. role: "user",
  104. time: { created: Date.now() },
  105. agent: "default",
  106. model: { providerID: "anthropic", modelID: "claude-3" },
  107. })
  108. expect(result.success).toBe(true)
  109. })
  110. })
  111. describe("structured-output.AssistantMessage", () => {
  112. const baseAssistantMessage = {
  113. id: MessageID.ascending(),
  114. sessionID: SessionID.descending(),
  115. role: "assistant" as const,
  116. parentID: MessageID.ascending(),
  117. modelID: "claude-3",
  118. providerID: "anthropic",
  119. mode: "default",
  120. agent: "default",
  121. path: { cwd: "/test", root: "/test" },
  122. cost: 0.001,
  123. tokens: { input: 100, output: 50, reasoning: 0, cache: { read: 0, write: 0 } },
  124. time: { created: Date.now() },
  125. }
  126. test("assistant message accepts structured", () => {
  127. const result = MessageV2.Assistant.zod.safeParse({
  128. ...baseAssistantMessage,
  129. structured: { company: "Anthropic", founded: 2021 },
  130. })
  131. expect(result.success).toBe(true)
  132. if (result.success) {
  133. expect(result.data.structured).toEqual({ company: "Anthropic", founded: 2021 })
  134. }
  135. })
  136. test("assistant message works without structured_output (optional)", () => {
  137. const result = MessageV2.Assistant.zod.safeParse(baseAssistantMessage)
  138. expect(result.success).toBe(true)
  139. })
  140. })
  141. describe("structured-output.createStructuredOutputTool", () => {
  142. test("creates tool with description", () => {
  143. const tool = SessionPrompt.createStructuredOutputTool({
  144. schema: { type: "object" },
  145. onSuccess: () => {},
  146. })
  147. expect(tool.description).toContain("structured format")
  148. })
  149. test("creates tool with schema as inputSchema", () => {
  150. const schema = {
  151. type: "object",
  152. properties: {
  153. company: { type: "string" },
  154. founded: { type: "number" },
  155. },
  156. required: ["company"],
  157. }
  158. const tool = SessionPrompt.createStructuredOutputTool({
  159. schema,
  160. onSuccess: () => {},
  161. })
  162. // AI SDK wraps schema in { jsonSchema: {...} }
  163. expect(tool.inputSchema).toBeDefined()
  164. const inputSchema = tool.inputSchema as any
  165. expect(inputSchema.jsonSchema?.properties?.company).toBeDefined()
  166. expect(inputSchema.jsonSchema?.properties?.founded).toBeDefined()
  167. })
  168. test("strips $schema property from inputSchema", () => {
  169. const schema = {
  170. $schema: "http://json-schema.org/draft-07/schema#",
  171. type: "object",
  172. properties: { name: { type: "string" } },
  173. }
  174. const tool = SessionPrompt.createStructuredOutputTool({
  175. schema,
  176. onSuccess: () => {},
  177. })
  178. // AI SDK wraps schema in { jsonSchema: {...} }
  179. const inputSchema = tool.inputSchema as any
  180. expect(inputSchema.jsonSchema?.$schema).toBeUndefined()
  181. })
  182. test("execute calls onSuccess with valid args", async () => {
  183. let capturedOutput: unknown
  184. const tool = SessionPrompt.createStructuredOutputTool({
  185. schema: { type: "object", properties: { name: { type: "string" } } },
  186. onSuccess: (output) => {
  187. capturedOutput = output
  188. },
  189. })
  190. expect(tool.execute).toBeDefined()
  191. const testArgs = { name: "Test Company" }
  192. const result = await tool.execute!(testArgs, {
  193. toolCallId: "test-call-id",
  194. messages: [],
  195. abortSignal: undefined as any,
  196. })
  197. expect(capturedOutput).toEqual(testArgs)
  198. expect(result.output).toBe("Structured output captured successfully.")
  199. expect(result.metadata.valid).toBe(true)
  200. })
  201. test("AI SDK validates schema before execute - missing required field", async () => {
  202. // Note: The AI SDK validates the input against the schema BEFORE calling execute()
  203. // So invalid inputs never reach the tool's execute function
  204. // This test documents the expected schema behavior
  205. const tool = SessionPrompt.createStructuredOutputTool({
  206. schema: {
  207. type: "object",
  208. properties: {
  209. name: { type: "string" },
  210. age: { type: "number" },
  211. },
  212. required: ["name", "age"],
  213. },
  214. onSuccess: () => {},
  215. })
  216. // The schema requires both 'name' and 'age'
  217. expect(tool.inputSchema).toBeDefined()
  218. const inputSchema = tool.inputSchema as any
  219. expect(inputSchema.jsonSchema?.required).toContain("name")
  220. expect(inputSchema.jsonSchema?.required).toContain("age")
  221. })
  222. test("AI SDK validates schema types before execute - wrong type", async () => {
  223. // Note: The AI SDK validates the input against the schema BEFORE calling execute()
  224. // So invalid inputs never reach the tool's execute function
  225. // This test documents the expected schema behavior
  226. const tool = SessionPrompt.createStructuredOutputTool({
  227. schema: {
  228. type: "object",
  229. properties: {
  230. count: { type: "number" },
  231. },
  232. required: ["count"],
  233. },
  234. onSuccess: () => {},
  235. })
  236. // The schema defines 'count' as a number
  237. expect(tool.inputSchema).toBeDefined()
  238. const inputSchema = tool.inputSchema as any
  239. expect(inputSchema.jsonSchema?.properties?.count?.type).toBe("number")
  240. })
  241. test("execute handles nested objects", async () => {
  242. let capturedOutput: unknown
  243. const tool = SessionPrompt.createStructuredOutputTool({
  244. schema: {
  245. type: "object",
  246. properties: {
  247. user: {
  248. type: "object",
  249. properties: {
  250. name: { type: "string" },
  251. email: { type: "string" },
  252. },
  253. required: ["name"],
  254. },
  255. },
  256. required: ["user"],
  257. },
  258. onSuccess: (output) => {
  259. capturedOutput = output
  260. },
  261. })
  262. // Valid nested object - AI SDK validates before calling execute()
  263. const validResult = await tool.execute!(
  264. { user: { name: "John", email: "john@test.com" } },
  265. {
  266. toolCallId: "test-call-id",
  267. messages: [],
  268. abortSignal: undefined as any,
  269. },
  270. )
  271. expect(capturedOutput).toEqual({ user: { name: "John", email: "john@test.com" } })
  272. expect(validResult.metadata.valid).toBe(true)
  273. // Verify schema has correct nested structure
  274. const inputSchema = tool.inputSchema as any
  275. expect(inputSchema.jsonSchema?.properties?.user?.type).toBe("object")
  276. expect(inputSchema.jsonSchema?.properties?.user?.properties?.name?.type).toBe("string")
  277. expect(inputSchema.jsonSchema?.properties?.user?.required).toContain("name")
  278. })
  279. test("execute handles arrays", async () => {
  280. let capturedOutput: unknown
  281. const tool = SessionPrompt.createStructuredOutputTool({
  282. schema: {
  283. type: "object",
  284. properties: {
  285. tags: {
  286. type: "array",
  287. items: { type: "string" },
  288. },
  289. },
  290. required: ["tags"],
  291. },
  292. onSuccess: (output) => {
  293. capturedOutput = output
  294. },
  295. })
  296. // Valid array - AI SDK validates before calling execute()
  297. const validResult = await tool.execute!(
  298. { tags: ["a", "b", "c"] },
  299. {
  300. toolCallId: "test-call-id",
  301. messages: [],
  302. abortSignal: undefined as any,
  303. },
  304. )
  305. expect(capturedOutput).toEqual({ tags: ["a", "b", "c"] })
  306. expect(validResult.metadata.valid).toBe(true)
  307. // Verify schema has correct array structure
  308. const inputSchema = tool.inputSchema as any
  309. expect(inputSchema.jsonSchema?.properties?.tags?.type).toBe("array")
  310. expect(inputSchema.jsonSchema?.properties?.tags?.items?.type).toBe("string")
  311. })
  312. test("toModelOutput returns text value", async () => {
  313. const tool = SessionPrompt.createStructuredOutputTool({
  314. schema: { type: "object" },
  315. onSuccess: () => {},
  316. })
  317. expect(tool.toModelOutput).toBeDefined()
  318. const modelOutput = await Promise.resolve(
  319. tool.toModelOutput!({
  320. toolCallId: "test-call-id",
  321. input: {},
  322. output: {
  323. output: "Test output",
  324. },
  325. }),
  326. )
  327. expect(modelOutput.type).toBe("text")
  328. if (modelOutput.type !== "text") throw new Error("expected text model output")
  329. expect(modelOutput.value).toBe("Test output")
  330. })
  331. // Note: Retry behavior is handled by the AI SDK and the prompt loop, not the tool itself
  332. // The tool simply calls onSuccess when execute() is called with valid args
  333. // See prompt.ts loop() for actual retry logic
  334. })