anthropic-messages.test.ts 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476
  1. import { describe, expect } from "bun:test"
  2. import { Effect } from "effect"
  3. import { HttpClientRequest } from "effect/unstable/http"
  4. import { CacheHint, LLM, AIError, LLMRequest, Message, ToolCallPart, ToolDefinition, Usage } from "../../src/index.js"
  5. import { Auth, LLMClient } from "../../src/route.js"
  6. import { compileRequest } from "../../src/route/client.js"
  7. import * as AnthropicMessages from "../../src/protocols/anthropic-messages.js"
  8. import { continuationRequest, nativeAnthropicMessagesContinuation } from "../continuation-scenarios.js"
  9. import { it } from "../lib/effect.js"
  10. import { dynamicResponse, fixedResponse } from "../lib/http.js"
  11. import { sseEvents } from "../lib/sse.js"
  12. const model = AnthropicMessages.route
  13. .with({ endpoint: { baseURL: "https://api.anthropic.test/v1/" }, auth: Auth.header("x-api-key", "test") })
  14. .model({ id: "claude-sonnet-4-5" })
  15. const opus48 = AnthropicMessages.route
  16. .with({ endpoint: { baseURL: "https://api.anthropic.test/v1/" }, auth: Auth.header("x-api-key", "test") })
  17. .model({ id: "claude-opus-4-8" })
  18. const request = LLM.request({
  19. id: "req_1",
  20. model,
  21. system: { type: "text", text: "You are concise.", cache: new CacheHint({ type: "ephemeral" }) },
  22. prompt: "Say hello.",
  23. // This fixture predates the `cache: "auto"` default; pin the policy off so
  24. // existing wire-shape assertions only see the manual hint on the system part.
  25. cache: "none",
  26. generation: { maxTokens: 20, temperature: 0 },
  27. })
  28. type AnthropicToolResult = Extract<
  29. AnthropicMessages.AnthropicMessagesBody["messages"][number]["content"][number],
  30. { readonly type: "tool_result" }
  31. >
  32. const expectToolResult = (body: AnthropicMessages.AnthropicMessagesBody): AnthropicToolResult => {
  33. const result = body.messages
  34. .flatMap((message) => (message.role === "user" ? message.content : []))
  35. .find((block): block is AnthropicToolResult => block.type === "tool_result")
  36. expect(result).toBeDefined()
  37. return result!
  38. }
  39. describe("Anthropic Messages route", () => {
  40. it.effect("prepares Anthropic Messages target", () =>
  41. Effect.gen(function* () {
  42. const prepared = yield* compileRequest(request)
  43. expect(prepared.body).toEqual({
  44. model: "claude-sonnet-4-5",
  45. system: [{ type: "text", text: "You are concise.", cache_control: { type: "ephemeral" } }],
  46. messages: [{ role: "user", content: [{ type: "text", text: "Say hello." }] }],
  47. stream: true,
  48. max_tokens: 20,
  49. temperature: 0,
  50. })
  51. }),
  52. )
  53. it.effect("lowers adaptive thinking settings with effort", () =>
  54. Effect.gen(function* () {
  55. const prepared = yield* compileRequest(
  56. LLMRequest.update(request, {
  57. providerOptions: {
  58. anthropic: { thinking: { type: "adaptive", display: "summarized" }, effort: "low" },
  59. },
  60. }),
  61. )
  62. expect(prepared.body).toMatchObject({
  63. thinking: { type: "adaptive", display: "summarized" },
  64. output_config: { effort: "low" },
  65. })
  66. }),
  67. )
  68. it.effect("normalizes enabled and disabled thinking settings", () =>
  69. Effect.gen(function* () {
  70. const enabled = yield* compileRequest(
  71. LLMRequest.update(request, {
  72. providerOptions: { anthropic: { thinking: { type: "enabled", budgetTokens: 1_024 } } },
  73. }),
  74. )
  75. const legacy = yield* compileRequest(
  76. LLMRequest.update(request, {
  77. providerOptions: { anthropic: { thinking: { type: "enabled", budget_tokens: 2_048 } } },
  78. }),
  79. )
  80. const disabled = yield* compileRequest(
  81. LLMRequest.update(request, {
  82. providerOptions: { anthropic: { thinking: { type: "disabled" } } },
  83. }),
  84. )
  85. expect(enabled.body.thinking).toEqual({ type: "enabled", budget_tokens: 1_024 })
  86. expect(legacy.body.thinking).toEqual({ type: "enabled", budget_tokens: 2_048 })
  87. expect(disabled.body.thinking).toEqual({ type: "disabled" })
  88. }),
  89. )
  90. it.effect("rejects enabled thinking without a budget", () =>
  91. Effect.gen(function* () {
  92. const error = yield* compileRequest(
  93. LLMRequest.update(request, {
  94. providerOptions: { anthropic: { thinking: { type: "enabled" } } },
  95. }),
  96. ).pipe(Effect.flip)
  97. expect(error.message).toContain("Anthropic thinking provider option requires budgetTokens")
  98. }),
  99. )
  100. it.effect("lowers chronological system updates natively for Claude Opus 4.8 with cache hints", () =>
  101. Effect.gen(function* () {
  102. const prepared = yield* compileRequest(
  103. LLM.request({
  104. model: opus48,
  105. messages: [
  106. Message.user("Before."),
  107. Message.system([{ type: "text", text: "Operator update.", cache: new CacheHint({ type: "ephemeral" }) }]),
  108. Message.assistant("After."),
  109. ],
  110. cache: "none",
  111. }),
  112. )
  113. expect(prepared.body.messages).toEqual([
  114. { role: "user", content: [{ type: "text", text: "Before." }] },
  115. {
  116. role: "system",
  117. content: [{ type: "text", text: "Operator update.", cache_control: { type: "ephemeral" } }],
  118. },
  119. { role: "assistant", content: [{ type: "text", text: "After." }] },
  120. ])
  121. }),
  122. )
  123. it.effect("lowers chronological system updates to wrapped user text for unsupported Anthropic models", () =>
  124. Effect.gen(function* () {
  125. const prepared = yield* compileRequest(
  126. LLM.request({
  127. model,
  128. messages: [
  129. Message.user("Before."),
  130. Message.system("Treat </system-update> literally."),
  131. Message.assistant("After."),
  132. ],
  133. cache: "none",
  134. }),
  135. )
  136. expect(prepared.body.messages).toEqual([
  137. {
  138. role: "user",
  139. content: [
  140. { type: "text", text: "Before." },
  141. { type: "text", text: "<system-update>\nTreat &lt;/system-update&gt; literally.\n</system-update>" },
  142. ],
  143. },
  144. { role: "assistant", content: [{ type: "text", text: "After." }] },
  145. ])
  146. }),
  147. )
  148. it.effect("rejects non-text chronological system update content before send", () =>
  149. Effect.gen(function* () {
  150. const error = yield* compileRequest(
  151. LLM.request({
  152. model: opus48,
  153. messages: [
  154. Message.user("Before."),
  155. Message.make({ role: "system", content: { type: "media", mediaType: "image/png", data: "AAECAw==" } }),
  156. ],
  157. }),
  158. ).pipe(Effect.flip)
  159. expect(error.message).toContain("Anthropic Messages system messages only support text content for now")
  160. }),
  161. )
  162. it.effect("falls back for unsupported native chronological system update placement", () =>
  163. Effect.gen(function* () {
  164. expect(
  165. (yield* compileRequest(
  166. LLM.request({
  167. model: opus48,
  168. messages: [Message.assistant("Plain."), Message.system("After plain assistant.")],
  169. cache: "none",
  170. }),
  171. )).body.messages,
  172. ).toEqual([
  173. { role: "assistant", content: [{ type: "text", text: "Plain." }] },
  174. {
  175. role: "user",
  176. content: [{ type: "text", text: "<system-update>\nAfter plain assistant.\n</system-update>" }],
  177. },
  178. ])
  179. expect(
  180. (yield* compileRequest(LLM.request({ model: opus48, messages: [Message.system("First.")], cache: "none" })))
  181. .body.messages,
  182. ).toEqual([{ role: "user", content: [{ type: "text", text: "<system-update>\nFirst.\n</system-update>" }] }])
  183. expect(
  184. (yield* compileRequest(
  185. LLM.request({
  186. model: opus48,
  187. messages: [Message.user("Before."), Message.system("One."), Message.system("Two.")],
  188. cache: "none",
  189. }),
  190. )).body.messages,
  191. ).toEqual([
  192. {
  193. role: "user",
  194. content: [
  195. { type: "text", text: "Before." },
  196. { type: "text", text: "<system-update>\nOne.\n</system-update>" },
  197. { type: "text", text: "<system-update>\nTwo.\n</system-update>" },
  198. ],
  199. },
  200. ])
  201. }),
  202. )
  203. it.effect("rejects a system update between a local tool call and its result", () =>
  204. Effect.gen(function* () {
  205. const error = yield* compileRequest(
  206. LLM.request({
  207. model: opus48,
  208. messages: [
  209. Message.user("Use the tool."),
  210. Message.assistant([ToolCallPart.make({ id: "call_1", name: "lookup", input: {} })]),
  211. Message.system("Too early."),
  212. Message.tool({ id: "call_1", name: "lookup", result: "Done." }),
  213. ],
  214. cache: "none",
  215. }),
  216. ).pipe(Effect.flip)
  217. expect(error.message).toContain("system updates cannot split a local tool call from its tool result")
  218. }),
  219. )
  220. it.effect("prepares tool call and tool result messages", () =>
  221. Effect.gen(function* () {
  222. const prepared = yield* compileRequest(
  223. LLM.request({
  224. id: "req_tool_result",
  225. model,
  226. messages: [
  227. Message.user("What is the weather?"),
  228. Message.assistant([ToolCallPart.make({ id: "call_1", name: "lookup", input: { query: "weather" } })]),
  229. Message.tool({ id: "call_1", name: "lookup", result: { forecast: "sunny" } }),
  230. ],
  231. cache: "none",
  232. }),
  233. )
  234. expect(prepared.body).toEqual({
  235. model: "claude-sonnet-4-5",
  236. messages: [
  237. { role: "user", content: [{ type: "text", text: "What is the weather?" }] },
  238. {
  239. role: "assistant",
  240. content: [{ type: "tool_use", id: "call_1", name: "lookup", input: { query: "weather" } }],
  241. },
  242. { role: "user", content: [{ type: "tool_result", tool_use_id: "call_1", content: '{"forecast":"sunny"}' }] },
  243. ],
  244. stream: true,
  245. max_tokens: 4096,
  246. })
  247. }),
  248. )
  249. it.effect("batches parallel tool results into one Anthropic user message", () =>
  250. Effect.gen(function* () {
  251. const prepared = yield* compileRequest(
  252. LLM.request({
  253. model,
  254. messages: [
  255. Message.user("Check both cities."),
  256. Message.assistant([
  257. { type: "text", text: "I'll check both." },
  258. ToolCallPart.make({ id: "call_paris", name: "weather", input: { city: "Paris" } }),
  259. ToolCallPart.make({ id: "call_london", name: "weather", input: { city: "London" } }),
  260. ]),
  261. Message.tool({ id: "call_paris", name: "weather", result: { temperature: 22 } }),
  262. Message.tool({ id: "call_london", name: "weather", result: { temperature: 18 } }),
  263. ],
  264. cache: "none",
  265. }),
  266. )
  267. expect(prepared.body.messages).toMatchObject([
  268. { role: "user", content: [{ type: "text", text: "Check both cities." }] },
  269. {
  270. role: "assistant",
  271. content: [
  272. { type: "text", text: "I'll check both." },
  273. { type: "tool_use", id: "call_paris", name: "weather", input: { city: "Paris" } },
  274. { type: "tool_use", id: "call_london", name: "weather", input: { city: "London" } },
  275. ],
  276. },
  277. {
  278. role: "user",
  279. content: [
  280. { type: "tool_result", tool_use_id: "call_paris", content: '{"temperature":22}' },
  281. { type: "tool_result", tool_use_id: "call_london", content: '{"temperature":18}' },
  282. ],
  283. },
  284. ])
  285. expect(prepared.body.messages).toHaveLength(3)
  286. }),
  287. )
  288. it.effect("keeps tools and sends tool_choice none", () =>
  289. Effect.gen(function* () {
  290. const prepared = yield* compileRequest(
  291. LLM.request({
  292. id: "req_tool_choice_none",
  293. model,
  294. tools: [{ name: "lookup", description: "Look things up", inputSchema: { type: "object", properties: {} } }],
  295. messages: [
  296. Message.user("What is the weather?"),
  297. Message.assistant([ToolCallPart.make({ id: "call_1", name: "lookup", input: { query: "weather" } })]),
  298. Message.tool({ id: "call_1", name: "lookup", result: { forecast: "sunny" } }),
  299. ],
  300. toolChoice: "none",
  301. cache: "none",
  302. }),
  303. )
  304. expect(prepared.body.tools).toEqual([
  305. {
  306. name: "lookup",
  307. description: "Look things up",
  308. input_schema: { type: "object", properties: {} },
  309. },
  310. ])
  311. expect(prepared.body.tool_choice).toEqual({ type: "none" })
  312. }),
  313. )
  314. // Regression: read tool results must stay structured so base64 media data is
  315. // not JSON-stringified into `tool_result.content`.
  316. it.effect("lowers media tool-result content as structured blocks", () =>
  317. Effect.gen(function* () {
  318. const prepared = yield* compileRequest(
  319. LLM.request({
  320. id: "req_tool_result_image",
  321. model,
  322. messages: [
  323. Message.user("Show me the screenshot."),
  324. Message.assistant([ToolCallPart.make({ id: "call_1", name: "read", input: { filePath: "shot.png" } })]),
  325. Message.tool({
  326. id: "call_1",
  327. name: "read",
  328. resultType: "content",
  329. result: [
  330. { type: "text", text: "Image read successfully" },
  331. { type: "file", uri: "data:image/png;base64,AAECAw==", mime: "image/png" },
  332. { type: "file", uri: "data:application/pdf;base64,JVBERi0xLjQ=", mime: "application/pdf" },
  333. ],
  334. }),
  335. ],
  336. cache: "none",
  337. }),
  338. )
  339. expect(expectToolResult(prepared.body).content).toEqual([
  340. { type: "text", text: "Image read successfully" },
  341. { type: "image", source: { type: "base64", media_type: "image/png", data: "AAECAw==" } },
  342. { type: "document", source: { type: "base64", media_type: "application/pdf", data: "JVBERi0xLjQ=" } },
  343. ])
  344. }),
  345. )
  346. it.effect("lowers single-image tool-result content as a structured image block", () =>
  347. Effect.gen(function* () {
  348. const prepared = yield* compileRequest(
  349. LLM.request({
  350. id: "req_tool_result_image_only",
  351. model,
  352. messages: [
  353. Message.assistant([ToolCallPart.make({ id: "call_1", name: "screenshot", input: {} })]),
  354. Message.tool({
  355. id: "call_1",
  356. name: "screenshot",
  357. resultType: "content",
  358. result: [{ type: "file", uri: "data:image/jpeg;base64,/9j/AA==", mime: "image/jpeg" }],
  359. }),
  360. ],
  361. cache: "none",
  362. }),
  363. )
  364. expect(expectToolResult(prepared.body).content).toEqual([
  365. { type: "image", source: { type: "base64", media_type: "image/jpeg", data: "/9j/AA==" } },
  366. ])
  367. }),
  368. )
  369. it.effect("rejects unsupported media in tool-result content with a clear error", () =>
  370. Effect.gen(function* () {
  371. const error = yield* compileRequest(
  372. LLM.request({
  373. id: "req_tool_result_unsupported_media",
  374. model,
  375. messages: [
  376. Message.assistant([ToolCallPart.make({ id: "call_1", name: "fetch", input: {} })]),
  377. Message.tool({
  378. id: "call_1",
  379. name: "fetch",
  380. resultType: "content",
  381. result: [{ type: "file", uri: "data:audio/mpeg;base64,AAECAw==", mime: "audio/mpeg" }],
  382. }),
  383. ],
  384. cache: "none",
  385. }),
  386. ).pipe(Effect.flip)
  387. expect(error.message).toContain("Anthropic Messages")
  388. expect(error.message).toContain("audio/mpeg")
  389. }),
  390. )
  391. it.effect("prepares the composed native continuation request", () =>
  392. Effect.gen(function* () {
  393. const prepared = yield* compileRequest(
  394. continuationRequest({
  395. id: "req_native_continuation_anthropic",
  396. model,
  397. features: nativeAnthropicMessagesContinuation,
  398. }),
  399. )
  400. expect(prepared.body).toMatchObject({
  401. system: [{ type: "text", text: "You are concise. Continue from the provided history." }],
  402. messages: [
  403. {
  404. role: "user",
  405. content: [
  406. { type: "text", text: "What is shown here?" },
  407. { type: "image", source: { type: "base64", media_type: "image/png", data: "AAECAw==" } },
  408. ],
  409. },
  410. {
  411. role: "assistant",
  412. content: [
  413. { type: "thinking", thinking: "I inspected the previous turn.", signature: "sig_continuation_1" },
  414. { type: "text", text: "It shows a small test image." },
  415. ],
  416. },
  417. { role: "user", content: [{ type: "text", text: "Check the weather in Paris before continuing." }] },
  418. {
  419. role: "assistant",
  420. content: [{ type: "tool_use", id: "call_weather_1", name: "get_weather", input: { city: "Paris" } }],
  421. },
  422. {
  423. role: "user",
  424. content: [{ type: "tool_result", tool_use_id: "call_weather_1", content: '{"temperature":22}' }],
  425. },
  426. { role: "assistant", content: [{ type: "text", text: "Paris is 22 degrees." }] },
  427. { role: "user", content: [{ type: "text", text: "Continue from this conversation in one short sentence." }] },
  428. ],
  429. })
  430. expect(prepared.body.tools).toEqual([expect.objectContaining({ name: "get_weather" })])
  431. }),
  432. )
  433. it.effect("lowers preserved Anthropic reasoning signature metadata", () =>
  434. Effect.gen(function* () {
  435. const prepared = yield* compileRequest(
  436. LLM.request({
  437. model,
  438. messages: [
  439. Message.assistant([
  440. { type: "reasoning", text: "thinking", providerMetadata: { anthropic: { signature: "sig_1" } } },
  441. ]),
  442. ],
  443. }),
  444. )
  445. expect(prepared.body).toMatchObject({
  446. messages: [{ role: "assistant", content: [{ type: "thinking", thinking: "thinking", signature: "sig_1" }] }],
  447. })
  448. }),
  449. )
  450. it.effect("round-trips redacted thinking as redacted_thinking blocks", () =>
  451. Effect.gen(function* () {
  452. const prepared = yield* compileRequest(
  453. LLM.request({
  454. model,
  455. messages: [
  456. Message.assistant([
  457. { type: "reasoning", text: "", providerMetadata: { anthropic: { redactedData: "opaque_1" } } },
  458. { type: "reasoning", text: "visible", providerMetadata: { anthropic: { signature: "sig_1" } } },
  459. ]),
  460. ],
  461. }),
  462. )
  463. expect(prepared.body).toMatchObject({
  464. messages: [
  465. {
  466. role: "assistant",
  467. content: [
  468. { type: "redacted_thinking", data: "opaque_1" },
  469. { type: "thinking", thinking: "visible", signature: "sig_1" },
  470. ],
  471. },
  472. ],
  473. })
  474. }),
  475. )
  476. it.effect("parses text, reasoning, and usage stream fixtures", () =>
  477. Effect.gen(function* () {
  478. const body = sseEvents(
  479. { type: "message_start", message: { usage: { input_tokens: 5, cache_read_input_tokens: 1 } } },
  480. { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
  481. { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "Hello" } },
  482. { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "!" } },
  483. { type: "content_block_stop", index: 0 },
  484. { type: "content_block_start", index: 1, content_block: { type: "thinking", thinking: "" } },
  485. { type: "content_block_delta", index: 1, delta: { type: "thinking_delta", thinking: "thinking" } },
  486. { type: "content_block_delta", index: 1, delta: { type: "signature_delta", signature: "sig_1" } },
  487. { type: "content_block_stop", index: 1 },
  488. {
  489. type: "message_delta",
  490. delta: { stop_reason: "end_turn", stop_sequence: "\n\nHuman:" },
  491. usage: { output_tokens: 2 },
  492. },
  493. { type: "message_stop" },
  494. )
  495. const response = yield* LLMClient.generate(request).pipe(Effect.provide(fixedResponse(body)))
  496. expect(response.text).toBe("Hello!")
  497. expect(response.reasoning).toBe("thinking")
  498. expect(response.usage).toMatchObject({
  499. inputTokens: 6,
  500. outputTokens: 2,
  501. nonCachedInputTokens: 5,
  502. cacheReadInputTokens: 1,
  503. totalTokens: 8,
  504. })
  505. expect(response.events.find((event) => event.type === "reasoning-end")).toMatchObject({
  506. providerMetadata: { anthropic: { signature: "sig_1" } },
  507. })
  508. expect(response.events.find((event) => event.type === "reasoning-delta" && event.text === "")).toBeUndefined()
  509. expect(response.message.content).toEqual([
  510. { type: "text", text: "Hello!" },
  511. { type: "reasoning", text: "thinking", providerMetadata: { anthropic: { signature: "sig_1" } } },
  512. ])
  513. expect(response.events.at(-1)).toMatchObject({
  514. type: "finish",
  515. reason: { normalized: "stop", raw: "end_turn" },
  516. providerMetadata: { anthropic: { stopSequence: "\n\nHuman:" } },
  517. })
  518. }),
  519. )
  520. it.effect("requires message_stop before completing a streamed message", () =>
  521. Effect.gen(function* () {
  522. const error = yield* LLMClient.generate(request).pipe(
  523. Effect.provide(
  524. fixedResponse(
  525. sseEvents(
  526. { type: "message_start", message: { usage: { input_tokens: 5 } } },
  527. { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
  528. { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "Hello" } },
  529. { type: "content_block_stop", index: 0 },
  530. { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 1 } },
  531. ),
  532. ),
  533. ),
  534. Effect.flip,
  535. )
  536. expect(error.reason).toMatchObject({
  537. _tag: "InvalidProviderOutput",
  538. classification: "incomplete-stream",
  539. message: "The provider response ended unexpectedly.",
  540. })
  541. }),
  542. )
  543. it.effect("maps thinking tokens and preserves unknown Anthropic usage fields", () =>
  544. Effect.gen(function* () {
  545. const response = yield* LLMClient.generate(request).pipe(
  546. Effect.provide(
  547. fixedResponse(
  548. sseEvents(
  549. {
  550. type: "message_start",
  551. message: {
  552. usage: {
  553. input_tokens: 5,
  554. cache_read_input_tokens: 2,
  555. service_tier: "standard",
  556. cache_creation: { ephemeral_5m_input_tokens: 1 },
  557. server_tool_use: { web_search_requests: 1, start_counter: 2 },
  558. output_tokens_details: { thinking_tokens: 3, start_detail: "preserved" },
  559. },
  560. },
  561. },
  562. {
  563. type: "message_delta",
  564. delta: { stop_reason: "end_turn" },
  565. usage: {
  566. output_tokens: 8,
  567. server_tool_use: { web_search_requests: 2, terminal_counter: 3 },
  568. output_tokens_details: { terminal_detail: "preserved" },
  569. future_terminal: { requests: 4 },
  570. },
  571. },
  572. { type: "message_stop" },
  573. ),
  574. ),
  575. ),
  576. )
  577. expect(response.usage).toMatchObject({
  578. inputTokens: 7,
  579. outputTokens: 8,
  580. reasoningTokens: 3,
  581. totalTokens: 15,
  582. providerMetadata: {
  583. anthropic: {
  584. input_tokens: 5,
  585. cache_read_input_tokens: 2,
  586. service_tier: "standard",
  587. cache_creation: { ephemeral_5m_input_tokens: 1 },
  588. server_tool_use: { web_search_requests: 2, start_counter: 2, terminal_counter: 3 },
  589. output_tokens: 8,
  590. output_tokens_details: {
  591. thinking_tokens: 3,
  592. start_detail: "preserved",
  593. terminal_detail: "preserved",
  594. },
  595. future_terminal: { requests: 4 },
  596. },
  597. },
  598. })
  599. }),
  600. )
  601. it.effect("round-trips omitted thinking carried only by a signature delta", () =>
  602. Effect.gen(function* () {
  603. const response = yield* LLMClient.generate(request).pipe(
  604. Effect.provide(
  605. fixedResponse(
  606. sseEvents(
  607. { type: "message_start", message: { usage: { input_tokens: 5 } } },
  608. {
  609. type: "content_block_start",
  610. index: 0,
  611. content_block: { type: "thinking", thinking: "", signature: "" },
  612. },
  613. { type: "content_block_delta", index: 0, delta: { type: "signature_delta", signature: "sig_1" } },
  614. { type: "content_block_stop", index: 0 },
  615. { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 1 } },
  616. { type: "message_stop" },
  617. ),
  618. ),
  619. ),
  620. )
  621. expect(response.message.content).toEqual([
  622. { type: "reasoning", text: "", providerMetadata: { anthropic: { signature: "sig_1" } } },
  623. ])
  624. const prepared = yield* compileRequest(LLM.request({ model, messages: [response.message], cache: "none" }))
  625. expect(prepared.body.messages).toEqual([
  626. { role: "assistant", content: [{ type: "thinking", thinking: "", signature: "sig_1" }] },
  627. ])
  628. }),
  629. )
  630. it.effect("retains a thinking signature supplied in content_block_start", () =>
  631. Effect.gen(function* () {
  632. const response = yield* LLMClient.generate(request).pipe(
  633. Effect.provide(
  634. fixedResponse(
  635. sseEvents(
  636. { type: "message_start", message: { usage: { input_tokens: 5 } } },
  637. {
  638. type: "content_block_start",
  639. index: 0,
  640. content_block: { type: "thinking", thinking: "", signature: "sig_1" },
  641. },
  642. { type: "content_block_stop", index: 0 },
  643. { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 1 } },
  644. { type: "message_stop" },
  645. ),
  646. ),
  647. ),
  648. )
  649. expect(response.message.content).toEqual([
  650. { type: "reasoning", text: "", providerMetadata: { anthropic: { signature: "sig_1" } } },
  651. ])
  652. expect(response.events.find((event) => event.type === "reasoning-end")).toMatchObject({
  653. providerMetadata: { anthropic: { signature: "sig_1" } },
  654. })
  655. }),
  656. )
  657. it.effect("retains complete tool input from content_block_start", () =>
  658. Effect.gen(function* () {
  659. const response = yield* LLMClient.generate(request).pipe(
  660. Effect.provide(
  661. fixedResponse(
  662. sseEvents(
  663. { type: "message_start", message: { usage: { input_tokens: 5 } } },
  664. {
  665. type: "content_block_start",
  666. index: 0,
  667. content_block: { type: "tool_use", id: "call_1", name: "lookup", input: { query: "weather" } },
  668. },
  669. { type: "content_block_stop", index: 0 },
  670. { type: "message_delta", delta: { stop_reason: "tool_use" }, usage: { output_tokens: 1 } },
  671. { type: "message_stop" },
  672. ),
  673. ),
  674. ),
  675. )
  676. expect(response.toolCalls).toMatchObject([{ id: "call_1", name: "lookup", input: { query: "weather" } }])
  677. }),
  678. )
  679. it.effect("retains empty text blocks", () =>
  680. Effect.gen(function* () {
  681. const response = yield* LLMClient.generate(request).pipe(
  682. Effect.provide(
  683. fixedResponse(
  684. sseEvents(
  685. { type: "message_start", message: { usage: { input_tokens: 5 } } },
  686. { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
  687. { type: "content_block_stop", index: 0 },
  688. { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 1 } },
  689. { type: "message_stop" },
  690. ),
  691. ),
  692. ),
  693. )
  694. expect(response.message.content).toEqual([{ type: "text", text: "" }])
  695. }),
  696. )
  697. it.effect("parses redacted thinking into empty reasoning with redactedData metadata", () =>
  698. Effect.gen(function* () {
  699. const body = sseEvents(
  700. { type: "message_start", message: { usage: { input_tokens: 5 } } },
  701. { type: "content_block_start", index: 0, content_block: { type: "redacted_thinking", data: "opaque_1" } },
  702. { type: "content_block_stop", index: 0 },
  703. { type: "content_block_start", index: 1, content_block: { type: "text", text: "" } },
  704. { type: "content_block_delta", index: 1, delta: { type: "text_delta", text: "Hello" } },
  705. { type: "content_block_stop", index: 1 },
  706. { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 2 } },
  707. { type: "message_stop" },
  708. )
  709. const response = yield* LLMClient.generate(request).pipe(Effect.provide(fixedResponse(body)))
  710. expect(response.events.find((event) => event.type === "reasoning-start")).toMatchObject({
  711. providerMetadata: { anthropic: { redactedData: "opaque_1" } },
  712. })
  713. expect(response.message.content).toEqual([
  714. { type: "reasoning", text: "", providerMetadata: { anthropic: { redactedData: "opaque_1" } } },
  715. { type: "text", text: "Hello" },
  716. ])
  717. }),
  718. )
  719. it.effect("round-trips streamed redacted thinking with tool use into a continuation request", () =>
  720. Effect.gen(function* () {
  721. // Anthropic types `redacted_thinking.data` as an opaque string. Its
  722. // contents are provider-owned and must be replayed without inspection.
  723. const redactedData = "cmVkYWN0ZWQtdGhpbmtpbmc="
  724. const response = yield* LLMClient.generate(
  725. LLMRequest.update(request, {
  726. tools: [ToolDefinition.make({ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } })],
  727. }),
  728. ).pipe(
  729. Effect.provide(
  730. fixedResponse(
  731. sseEvents(
  732. { type: "message_start", message: { usage: { input_tokens: 5 } } },
  733. {
  734. type: "content_block_start",
  735. index: 0,
  736. content_block: { type: "redacted_thinking", data: redactedData },
  737. },
  738. { type: "content_block_stop", index: 0 },
  739. {
  740. type: "content_block_start",
  741. index: 1,
  742. content_block: { type: "tool_use", id: "call_1", name: "lookup" },
  743. },
  744. {
  745. type: "content_block_delta",
  746. index: 1,
  747. delta: { type: "input_json_delta", partial_json: '{"query":"weather"}' },
  748. },
  749. { type: "content_block_stop", index: 1 },
  750. { type: "message_delta", delta: { stop_reason: "tool_use" }, usage: { output_tokens: 1 } },
  751. { type: "message_stop" },
  752. ),
  753. ),
  754. ),
  755. )
  756. const prepared = yield* compileRequest(
  757. LLM.request({
  758. model,
  759. messages: [
  760. Message.user("Say hello."),
  761. response.message,
  762. Message.tool({ id: "call_1", name: "lookup", result: "sunny", resultType: "text" }),
  763. ],
  764. tools: [ToolDefinition.make({ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } })],
  765. cache: "none",
  766. }),
  767. )
  768. expect(prepared.body.messages).toEqual([
  769. { role: "user", content: [{ type: "text", text: "Say hello." }] },
  770. {
  771. role: "assistant",
  772. content: [
  773. { type: "redacted_thinking", data: redactedData },
  774. { type: "tool_use", id: "call_1", name: "lookup", input: { query: "weather" } },
  775. ],
  776. },
  777. {
  778. role: "user",
  779. content: [
  780. {
  781. type: "tool_result",
  782. tool_use_id: "call_1",
  783. content: "sunny",
  784. is_error: undefined,
  785. cache_control: undefined,
  786. },
  787. ],
  788. },
  789. ])
  790. }),
  791. )
  792. it.effect("maps context-window truncation to length", () =>
  793. Effect.gen(function* () {
  794. const response = yield* LLMClient.generate(request).pipe(
  795. Effect.provide(
  796. fixedResponse(
  797. sseEvents(
  798. { type: "message_start", message: { usage: { input_tokens: 5 } } },
  799. {
  800. type: "message_delta",
  801. delta: { stop_reason: "model_context_window_exceeded" },
  802. usage: { output_tokens: 1 },
  803. },
  804. { type: "message_stop" },
  805. ),
  806. ),
  807. ),
  808. )
  809. expect(response.finishReason).toEqual({ normalized: "length", raw: "model_context_window_exceeded" })
  810. }),
  811. )
  812. it.effect("preserves pause_turn while normalizing it to stop", () =>
  813. Effect.gen(function* () {
  814. const response = yield* LLMClient.generate(request).pipe(
  815. Effect.provide(
  816. fixedResponse(
  817. sseEvents(
  818. { type: "message_start", message: { usage: { input_tokens: 5 } } },
  819. { type: "message_delta", delta: { stop_reason: "pause_turn" }, usage: { output_tokens: 1 } },
  820. { type: "message_stop" },
  821. ),
  822. ),
  823. ),
  824. )
  825. expect(response.finishReason).toEqual({ normalized: "stop", raw: "pause_turn" })
  826. }),
  827. )
  828. it.effect("assembles streamed tool call input", () =>
  829. Effect.gen(function* () {
  830. const body = sseEvents(
  831. { type: "message_start", message: { usage: { input_tokens: 5 } } },
  832. { type: "content_block_start", index: 0, content_block: { type: "tool_use", id: "call_1", name: "lookup" } },
  833. { type: "content_block_delta", index: 0, delta: { type: "input_json_delta", partial_json: '{"query"' } },
  834. { type: "content_block_delta", index: 0, delta: { type: "input_json_delta", partial_json: ':"weather"}' } },
  835. { type: "content_block_stop", index: 0 },
  836. { type: "message_delta", delta: { stop_reason: "tool_use" }, usage: { output_tokens: 1 } },
  837. { type: "message_stop" },
  838. )
  839. const response = yield* LLMClient.generate(
  840. LLMRequest.update(request, {
  841. tools: [ToolDefinition.make({ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } })],
  842. }),
  843. ).pipe(Effect.provide(fixedResponse(body)))
  844. const usage = new Usage({
  845. inputTokens: 5,
  846. outputTokens: 1,
  847. nonCachedInputTokens: 5,
  848. cacheReadInputTokens: undefined,
  849. cacheWriteInputTokens: undefined,
  850. totalTokens: 6,
  851. providerMetadata: { anthropic: { input_tokens: 5, output_tokens: 1 } },
  852. })
  853. expect(response.toolCalls).toEqual([
  854. {
  855. type: "tool-call",
  856. id: "call_1",
  857. name: "lookup",
  858. input: { query: "weather" },
  859. providerExecuted: undefined,
  860. providerMetadata: undefined,
  861. },
  862. ])
  863. expect(response.events).toEqual([
  864. { type: "step-start", index: 0 },
  865. { type: "tool-input-start", id: "call_1", name: "lookup" },
  866. { type: "tool-input-delta", id: "call_1", name: "lookup", text: '{"query"' },
  867. { type: "tool-input-delta", id: "call_1", name: "lookup", text: ':"weather"}' },
  868. { type: "tool-input-end", id: "call_1", name: "lookup", providerMetadata: undefined },
  869. {
  870. type: "tool-call",
  871. id: "call_1",
  872. name: "lookup",
  873. input: { query: "weather" },
  874. providerExecuted: undefined,
  875. providerMetadata: undefined,
  876. },
  877. {
  878. type: "step-finish",
  879. index: 0,
  880. reason: { normalized: "tool-calls", raw: "tool_use" },
  881. usage,
  882. providerMetadata: undefined,
  883. },
  884. {
  885. type: "finish",
  886. reason: { normalized: "tool-calls", raw: "tool_use" },
  887. providerMetadata: undefined,
  888. usage,
  889. },
  890. ])
  891. }),
  892. )
  893. it.effect("assembles and persists multiple tool calls from one Anthropic response", () =>
  894. Effect.gen(function* () {
  895. const response = yield* LLMClient.generate(request).pipe(
  896. Effect.provide(
  897. fixedResponse(
  898. sseEvents(
  899. { type: "message_start", message: { usage: { input_tokens: 5 } } },
  900. {
  901. type: "content_block_start",
  902. index: 0,
  903. content_block: { type: "tool_use", id: "call_paris", name: "weather", input: {} },
  904. },
  905. {
  906. type: "content_block_delta",
  907. index: 0,
  908. delta: { type: "input_json_delta", partial_json: '{"city":"Paris"}' },
  909. },
  910. { type: "content_block_stop", index: 0 },
  911. {
  912. type: "content_block_start",
  913. index: 1,
  914. content_block: { type: "tool_use", id: "call_london", name: "weather", input: {} },
  915. },
  916. {
  917. type: "content_block_delta",
  918. index: 1,
  919. delta: { type: "input_json_delta", partial_json: '{"city":"London"}' },
  920. },
  921. { type: "content_block_stop", index: 1 },
  922. { type: "message_delta", delta: { stop_reason: "tool_use" }, usage: { output_tokens: 2 } },
  923. { type: "message_stop" },
  924. ),
  925. ),
  926. ),
  927. )
  928. expect(response.toolCalls).toMatchObject([
  929. { id: "call_paris", name: "weather", input: { city: "Paris" } },
  930. { id: "call_london", name: "weather", input: { city: "London" } },
  931. ])
  932. expect(response.message.content).toMatchObject([
  933. { type: "tool-call", id: "call_paris", name: "weather", input: { city: "Paris" } },
  934. { type: "tool-call", id: "call_london", name: "weather", input: { city: "London" } },
  935. ])
  936. expect(response.finishReason).toEqual({ normalized: "tool-calls", raw: "tool_use" })
  937. }),
  938. )
  939. it.effect("keeps malformed server tool input terminal", () =>
  940. Effect.gen(function* () {
  941. const body = sseEvents(
  942. { type: "message_start", message: { usage: { input_tokens: 5 } } },
  943. {
  944. type: "content_block_start",
  945. index: 0,
  946. content_block: { type: "server_tool_use", id: "call_1", name: "web_search" },
  947. },
  948. {
  949. type: "content_block_delta",
  950. index: 0,
  951. delta: { type: "input_json_delta", partial_json: '{"query":"partial' },
  952. },
  953. { type: "content_block_stop", index: 0 },
  954. )
  955. const error = yield* LLMClient.generate(request).pipe(Effect.provide(fixedResponse(body)), Effect.flip)
  956. expect(error).toBeInstanceOf(AIError)
  957. expect(error.message).toContain("Invalid JSON input for anthropic-messages tool call web_search")
  958. }),
  959. )
  960. it.effect("fails with a typed provider error for stream error frames", () =>
  961. Effect.gen(function* () {
  962. const error = yield* LLMClient.generate(request).pipe(
  963. Effect.provide(
  964. fixedResponse(sseEvents({ type: "error", error: { type: "overloaded_error", message: "Overloaded" } })),
  965. ),
  966. Effect.flip,
  967. )
  968. expect(error.reason).toMatchObject({ _tag: "ProviderInternal", message: "overloaded_error: Overloaded" })
  969. }),
  970. )
  971. it.effect("classifies prompt-too-long provider errors", () =>
  972. Effect.gen(function* () {
  973. const error = yield* LLMClient.generate(request).pipe(
  974. Effect.provide(
  975. fixedResponse(
  976. sseEvents({
  977. type: "error",
  978. error: { type: "invalid_request_error", message: "prompt is too long: 210000 tokens" },
  979. }),
  980. ),
  981. ),
  982. Effect.flip,
  983. )
  984. expect(error.reason).toMatchObject({
  985. _tag: "InvalidRequest",
  986. message: "invalid_request_error: prompt is too long: 210000 tokens",
  987. classification: "context-overflow",
  988. })
  989. }),
  990. )
  991. it.effect("falls back to error type when no message is present", () =>
  992. Effect.gen(function* () {
  993. const error = yield* LLMClient.generate(request).pipe(
  994. Effect.provide(fixedResponse(sseEvents({ type: "error", error: { type: "overloaded_error", message: "" } }))),
  995. Effect.flip,
  996. )
  997. expect(error.reason).toMatchObject({ _tag: "ProviderInternal", message: "overloaded_error" })
  998. }),
  999. )
  1000. it.effect("falls back to a stable default when error payload is absent", () =>
  1001. Effect.gen(function* () {
  1002. const error = yield* LLMClient.generate(request).pipe(
  1003. Effect.provide(fixedResponse(sseEvents({ type: "error" }))),
  1004. Effect.flip,
  1005. )
  1006. expect(error.reason).toMatchObject({ _tag: "UnknownProvider", message: "Anthropic Messages stream error" })
  1007. }),
  1008. )
  1009. it.effect("fails HTTP provider errors before stream parsing", () =>
  1010. Effect.gen(function* () {
  1011. const error = yield* LLMClient.generate(request).pipe(
  1012. Effect.provide(
  1013. fixedResponse('{"type":"error","error":{"type":"invalid_request_error","message":"Bad request"}}', {
  1014. status: 400,
  1015. headers: { "content-type": "application/json" },
  1016. }),
  1017. ),
  1018. Effect.flip,
  1019. )
  1020. expect(error).toBeInstanceOf(AIError)
  1021. expect(error.reason).toMatchObject({ _tag: "InvalidRequest", message: "Bad request" })
  1022. }),
  1023. )
  1024. it.effect("decodes server_tool_use + web_search_tool_result as provider-executed events", () =>
  1025. Effect.gen(function* () {
  1026. const body = sseEvents(
  1027. { type: "message_start", message: { usage: { input_tokens: 5 } } },
  1028. {
  1029. type: "content_block_start",
  1030. index: 0,
  1031. content_block: { type: "server_tool_use", id: "srvtoolu_abc", name: "web_search" },
  1032. },
  1033. {
  1034. type: "content_block_delta",
  1035. index: 0,
  1036. delta: { type: "input_json_delta", partial_json: '{"query":"effect 4"}' },
  1037. },
  1038. { type: "content_block_stop", index: 0 },
  1039. {
  1040. type: "content_block_start",
  1041. index: 1,
  1042. content_block: {
  1043. type: "web_search_tool_result",
  1044. tool_use_id: "srvtoolu_abc",
  1045. content: [{ type: "web_search_result", url: "https://example.com", title: "Example" }],
  1046. },
  1047. },
  1048. { type: "content_block_stop", index: 1 },
  1049. { type: "content_block_start", index: 2, content_block: { type: "text", text: "" } },
  1050. { type: "content_block_delta", index: 2, delta: { type: "text_delta", text: "Found it." } },
  1051. { type: "content_block_stop", index: 2 },
  1052. { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 8 } },
  1053. { type: "message_stop" },
  1054. )
  1055. const response = yield* LLMClient.generate(
  1056. LLMRequest.update(request, {
  1057. tools: [
  1058. ToolDefinition.make({ name: "web_search", description: "Web search", inputSchema: { type: "object" } }),
  1059. ],
  1060. }),
  1061. ).pipe(Effect.provide(fixedResponse(body)))
  1062. const toolCall = response.events.find((event) => event.type === "tool-call")
  1063. expect(toolCall).toEqual({
  1064. type: "tool-call",
  1065. id: "srvtoolu_abc",
  1066. name: "web_search",
  1067. input: { query: "effect 4" },
  1068. providerExecuted: true,
  1069. })
  1070. const toolResult = response.events.find((event) => event.type === "tool-result")
  1071. expect(toolResult).toEqual({
  1072. type: "tool-result",
  1073. id: "srvtoolu_abc",
  1074. name: "web_search",
  1075. result: { type: "json", value: [{ type: "web_search_result", url: "https://example.com", title: "Example" }] },
  1076. providerExecuted: true,
  1077. // The complete payload rides in provider metadata as irreducible replay
  1078. // state for later stateless requests.
  1079. providerMetadata: {
  1080. anthropic: {
  1081. blockType: "web_search_tool_result",
  1082. result: [{ type: "web_search_result", url: "https://example.com", title: "Example" }],
  1083. },
  1084. },
  1085. })
  1086. expect(response.text).toBe("Found it.")
  1087. expect(response.events.at(-1)).toMatchObject({
  1088. type: "finish",
  1089. reason: { normalized: "stop", raw: "end_turn" },
  1090. })
  1091. }),
  1092. )
  1093. it.effect("decodes web_search_tool_result_error as provider-executed error result", () =>
  1094. Effect.gen(function* () {
  1095. const body = sseEvents(
  1096. { type: "message_start", message: { usage: { input_tokens: 5 } } },
  1097. {
  1098. type: "content_block_start",
  1099. index: 0,
  1100. content_block: { type: "server_tool_use", id: "srvtoolu_x", name: "web_search" },
  1101. },
  1102. { type: "content_block_delta", index: 0, delta: { type: "input_json_delta", partial_json: '{"query":"q"}' } },
  1103. { type: "content_block_stop", index: 0 },
  1104. {
  1105. type: "content_block_start",
  1106. index: 1,
  1107. content_block: {
  1108. type: "web_search_tool_result",
  1109. tool_use_id: "srvtoolu_x",
  1110. content: { type: "web_search_tool_result_error", error_code: "max_uses_exceeded" },
  1111. },
  1112. },
  1113. { type: "content_block_stop", index: 1 },
  1114. { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 1 } },
  1115. { type: "message_stop" },
  1116. )
  1117. const response = yield* LLMClient.generate(
  1118. LLMRequest.update(request, {
  1119. tools: [
  1120. ToolDefinition.make({ name: "web_search", description: "Web search", inputSchema: { type: "object" } }),
  1121. ],
  1122. }),
  1123. ).pipe(Effect.provide(fixedResponse(body)))
  1124. const toolResult = response.events.find((event) => event.type === "tool-result")
  1125. expect(toolResult).toMatchObject({
  1126. type: "tool-result",
  1127. id: "srvtoolu_x",
  1128. name: "web_search",
  1129. result: { type: "error" },
  1130. providerExecuted: true,
  1131. })
  1132. }),
  1133. )
  1134. it.effect("round-trips provider-executed assistant content into server tool blocks", () =>
  1135. Effect.gen(function* () {
  1136. const prepared = yield* compileRequest(
  1137. LLM.request({
  1138. id: "req_round_trip",
  1139. model,
  1140. messages: [
  1141. Message.user("Search for something."),
  1142. Message.assistant([
  1143. {
  1144. type: "tool-call",
  1145. id: "srvtoolu_abc",
  1146. name: "web_search",
  1147. input: { query: "effect 4" },
  1148. providerExecuted: true,
  1149. },
  1150. {
  1151. type: "tool-result",
  1152. id: "srvtoolu_abc",
  1153. name: "web_search",
  1154. result: { type: "json", value: [{ url: "https://example.com" }] },
  1155. providerExecuted: true,
  1156. },
  1157. { type: "text", text: "Found it." },
  1158. ]),
  1159. Message.user("Thanks."),
  1160. ],
  1161. }),
  1162. )
  1163. expect(prepared.body).toMatchObject({
  1164. messages: [
  1165. { role: "user", content: [{ type: "text", text: "Search for something." }] },
  1166. {
  1167. role: "assistant",
  1168. content: [
  1169. { type: "server_tool_use", id: "srvtoolu_abc", name: "web_search", input: { query: "effect 4" } },
  1170. {
  1171. type: "web_search_tool_result",
  1172. tool_use_id: "srvtoolu_abc",
  1173. content: [{ url: "https://example.com" }],
  1174. },
  1175. { type: "text", text: "Found it." },
  1176. ],
  1177. },
  1178. { role: "user", content: [{ type: "text", text: "Thanks." }] },
  1179. ],
  1180. })
  1181. }),
  1182. )
  1183. it.effect("rejects round-trip for unknown server tool names", () =>
  1184. Effect.gen(function* () {
  1185. const error = yield* compileRequest(
  1186. LLM.request({
  1187. id: "req_unknown_server_tool",
  1188. model,
  1189. messages: [
  1190. Message.assistant([
  1191. {
  1192. type: "tool-result",
  1193. id: "srvtoolu_abc",
  1194. name: "future_server_tool",
  1195. result: { type: "json", value: {} },
  1196. providerExecuted: true,
  1197. },
  1198. ]),
  1199. ],
  1200. }),
  1201. ).pipe(Effect.flip)
  1202. expect(error.message).toContain("future_server_tool")
  1203. }),
  1204. )
  1205. it.effect("continues a conversation with user media content", () =>
  1206. Effect.gen(function* () {
  1207. const response = yield* LLMClient.generate(
  1208. LLM.request({
  1209. id: "req_media",
  1210. model,
  1211. messages: [
  1212. Message.user([
  1213. { type: "text", text: "What is in this image?" },
  1214. { type: "media", mediaType: "image/png", data: "AAECAw==" },
  1215. { type: "media", mediaType: "application/pdf", data: "JVBERi0xLjQ=", filename: "report.pdf" },
  1216. ]),
  1217. ],
  1218. }),
  1219. ).pipe(
  1220. Effect.provide(
  1221. dynamicResponse((input) =>
  1222. Effect.gen(function* () {
  1223. const web = yield* HttpClientRequest.toWeb(input.request).pipe(Effect.orDie)
  1224. expect(yield* Effect.promise(() => web.json())).toMatchObject({
  1225. messages: [
  1226. {
  1227. role: "user",
  1228. content: [
  1229. { type: "text", text: "What is in this image?" },
  1230. { type: "image", source: { type: "base64", media_type: "image/png", data: "AAECAw==" } },
  1231. {
  1232. type: "document",
  1233. source: { type: "base64", media_type: "application/pdf", data: "JVBERi0xLjQ=" },
  1234. },
  1235. ],
  1236. },
  1237. ],
  1238. })
  1239. return input.respond(
  1240. sseEvents(
  1241. { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
  1242. { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "An image." } },
  1243. { type: "content_block_stop", index: 0 },
  1244. { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 3 } },
  1245. { type: "message_stop" },
  1246. ),
  1247. { headers: { "content-type": "text/event-stream" } },
  1248. )
  1249. }),
  1250. ),
  1251. ),
  1252. )
  1253. expect(response.text).toBe("An image.")
  1254. }),
  1255. )
  1256. it.effect("maps ttlSeconds >= 3600 to cache_control ttl: '1h'", () =>
  1257. Effect.gen(function* () {
  1258. const prepared = yield* compileRequest(
  1259. LLM.request({
  1260. model,
  1261. system: { type: "text", text: "system", cache: new CacheHint({ type: "ephemeral", ttlSeconds: 3600 }) },
  1262. prompt: "hi",
  1263. }),
  1264. )
  1265. expect(prepared.body).toMatchObject({
  1266. system: [{ type: "text", text: "system", cache_control: { type: "ephemeral", ttl: "1h" } }],
  1267. })
  1268. }),
  1269. )
  1270. it.effect("emits cache_control on tool definitions and tool-result blocks", () =>
  1271. Effect.gen(function* () {
  1272. const prepared = yield* compileRequest(
  1273. LLM.request({
  1274. model,
  1275. tools: [
  1276. {
  1277. name: "lookup",
  1278. description: "lookup tool",
  1279. inputSchema: { type: "object", properties: {} },
  1280. cache: new CacheHint({ type: "ephemeral" }),
  1281. },
  1282. ],
  1283. messages: [
  1284. Message.user("What's the weather?"),
  1285. Message.assistant([ToolCallPart.make({ id: "call_1", name: "lookup", input: {} })]),
  1286. Message.tool({
  1287. id: "call_1",
  1288. name: "lookup",
  1289. result: { temp: 72 },
  1290. cache: new CacheHint({ type: "ephemeral" }),
  1291. }),
  1292. ],
  1293. }),
  1294. )
  1295. expect(prepared.body).toMatchObject({
  1296. tools: [{ name: "lookup", cache_control: { type: "ephemeral" } }],
  1297. messages: [
  1298. { role: "user", content: [{ type: "text", text: "What's the weather?" }] },
  1299. { role: "assistant", content: [{ type: "tool_use", id: "call_1", name: "lookup" }] },
  1300. {
  1301. role: "user",
  1302. content: [{ type: "tool_result", tool_use_id: "call_1", cache_control: { type: "ephemeral" } }],
  1303. },
  1304. ],
  1305. })
  1306. }),
  1307. )
  1308. it.effect("drops cache_control breakpoints past the 4-per-request cap", () =>
  1309. Effect.gen(function* () {
  1310. const hint = new CacheHint({ type: "ephemeral" })
  1311. const prepared = yield* compileRequest(
  1312. LLM.request({
  1313. model,
  1314. system: [
  1315. { type: "text", text: "a", cache: hint },
  1316. { type: "text", text: "b", cache: hint },
  1317. { type: "text", text: "c", cache: hint },
  1318. { type: "text", text: "d", cache: hint },
  1319. { type: "text", text: "e", cache: hint },
  1320. { type: "text", text: "f", cache: hint },
  1321. ],
  1322. prompt: "hi",
  1323. }),
  1324. )
  1325. const system = (prepared.body as { system: Array<{ cache_control?: unknown }> }).system
  1326. const marked = system.filter((part) => part.cache_control !== undefined)
  1327. expect(marked).toHaveLength(4)
  1328. expect(system[4]?.cache_control).toBeUndefined()
  1329. expect(system[5]?.cache_control).toBeUndefined()
  1330. }),
  1331. )
  1332. it.effect("spends breakpoint budget on tools before system before messages", () =>
  1333. Effect.gen(function* () {
  1334. const hint = new CacheHint({ type: "ephemeral" })
  1335. const prepared = yield* compileRequest(
  1336. LLM.request({
  1337. model,
  1338. tools: [
  1339. {
  1340. name: "t1",
  1341. description: "t1",
  1342. inputSchema: { type: "object", properties: {} },
  1343. cache: hint,
  1344. },
  1345. {
  1346. name: "t2",
  1347. description: "t2",
  1348. inputSchema: { type: "object", properties: {} },
  1349. cache: hint,
  1350. },
  1351. {
  1352. name: "t3",
  1353. description: "t3",
  1354. inputSchema: { type: "object", properties: {} },
  1355. cache: hint,
  1356. },
  1357. {
  1358. name: "t4",
  1359. description: "t4",
  1360. inputSchema: { type: "object", properties: {} },
  1361. cache: hint,
  1362. },
  1363. ],
  1364. system: [{ type: "text", text: "system-tail", cache: hint }],
  1365. messages: [Message.user([{ type: "text", text: "message-tail", cache: hint }])],
  1366. }),
  1367. )
  1368. const body = prepared.body as {
  1369. tools: Array<{ cache_control?: unknown }>
  1370. system: Array<{ cache_control?: unknown }>
  1371. messages: Array<{ content: Array<{ cache_control?: unknown }> }>
  1372. }
  1373. expect(body.tools.every((t) => t.cache_control !== undefined)).toBe(true)
  1374. expect(body.system[0]?.cache_control).toBeUndefined()
  1375. expect(body.messages[0]?.content[0]?.cache_control).toBeUndefined()
  1376. }),
  1377. )
  1378. })