anthropic-messages.test.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  1. import { describe, expect } from "bun:test"
  2. import { Effect } from "effect"
  3. import { HttpClientRequest } from "effect/unstable/http"
  4. import { CacheHint, LLM, LLMError, Message, ToolCallPart, Usage } from "../../src"
  5. import { Auth, LLMClient } from "../../src/route"
  6. import * as AnthropicMessages from "../../src/protocols/anthropic-messages"
  7. import { continuationRequest, nativeAnthropicMessagesContinuation } from "../continuation-scenarios"
  8. import { it } from "../lib/effect"
  9. import { dynamicResponse, fixedResponse } from "../lib/http"
  10. import { sseEvents } from "../lib/sse"
  11. const model = AnthropicMessages.route
  12. .with({ endpoint: { baseURL: "https://api.anthropic.test/v1/" }, auth: Auth.header("x-api-key", "test") })
  13. .model({ id: "claude-sonnet-4-5" })
  14. const opus48 = AnthropicMessages.route
  15. .with({ endpoint: { baseURL: "https://api.anthropic.test/v1/" }, auth: Auth.header("x-api-key", "test") })
  16. .model({ id: "claude-opus-4-8" })
  17. const request = LLM.request({
  18. id: "req_1",
  19. model,
  20. system: { type: "text", text: "You are concise.", cache: new CacheHint({ type: "ephemeral" }) },
  21. prompt: "Say hello.",
  22. // This fixture predates the `cache: "auto"` default; pin the policy off so
  23. // existing wire-shape assertions only see the manual hint on the system part.
  24. cache: "none",
  25. generation: { maxTokens: 20, temperature: 0 },
  26. })
  27. type AnthropicToolResult = Extract<
  28. AnthropicMessages.AnthropicMessagesBody["messages"][number]["content"][number],
  29. { readonly type: "tool_result" }
  30. >
  31. const expectToolResult = (body: AnthropicMessages.AnthropicMessagesBody): AnthropicToolResult => {
  32. const result = body.messages
  33. .flatMap((message) => (message.role === "user" ? message.content : []))
  34. .find((block): block is AnthropicToolResult => block.type === "tool_result")
  35. expect(result).toBeDefined()
  36. return result!
  37. }
  38. describe("Anthropic Messages route", () => {
  39. it.effect("prepares Anthropic Messages target", () =>
  40. Effect.gen(function* () {
  41. const prepared = yield* LLMClient.prepare(request)
  42. expect(prepared.body).toEqual({
  43. model: "claude-sonnet-4-5",
  44. system: [{ type: "text", text: "You are concise.", cache_control: { type: "ephemeral" } }],
  45. messages: [{ role: "user", content: [{ type: "text", text: "Say hello." }] }],
  46. stream: true,
  47. max_tokens: 20,
  48. temperature: 0,
  49. })
  50. }),
  51. )
  52. it.effect("lowers chronological system updates natively for Claude Opus 4.8 with cache hints", () =>
  53. Effect.gen(function* () {
  54. const prepared = yield* LLMClient.prepare<AnthropicMessages.AnthropicMessagesBody>(
  55. LLM.request({
  56. model: opus48,
  57. messages: [
  58. Message.user("Before."),
  59. Message.system([{ type: "text", text: "Operator update.", cache: new CacheHint({ type: "ephemeral" }) }]),
  60. Message.assistant("After."),
  61. ],
  62. cache: "none",
  63. }),
  64. )
  65. expect(prepared.body.messages).toEqual([
  66. { role: "user", content: [{ type: "text", text: "Before." }] },
  67. {
  68. role: "system",
  69. content: [{ type: "text", text: "Operator update.", cache_control: { type: "ephemeral" } }],
  70. },
  71. { role: "assistant", content: [{ type: "text", text: "After." }] },
  72. ])
  73. }),
  74. )
  75. it.effect("lowers chronological system updates to wrapped user text for unsupported Anthropic models", () =>
  76. Effect.gen(function* () {
  77. const prepared = yield* LLMClient.prepare<AnthropicMessages.AnthropicMessagesBody>(
  78. LLM.request({
  79. model,
  80. messages: [
  81. Message.user("Before."),
  82. Message.system("Treat </system-update> literally."),
  83. Message.assistant("After."),
  84. ],
  85. cache: "none",
  86. }),
  87. )
  88. expect(prepared.body.messages).toEqual([
  89. {
  90. role: "user",
  91. content: [
  92. { type: "text", text: "Before." },
  93. { type: "text", text: "<system-update>\nTreat &lt;/system-update&gt; literally.\n</system-update>" },
  94. ],
  95. },
  96. { role: "assistant", content: [{ type: "text", text: "After." }] },
  97. ])
  98. }),
  99. )
  100. it.effect("rejects non-text chronological system update content before send", () =>
  101. Effect.gen(function* () {
  102. const error = yield* LLMClient.prepare(
  103. LLM.request({
  104. model: opus48,
  105. messages: [
  106. Message.user("Before."),
  107. Message.make({ role: "system", content: { type: "media", mediaType: "image/png", data: "AAECAw==" } }),
  108. ],
  109. }),
  110. ).pipe(Effect.flip)
  111. expect(error.message).toContain("Anthropic Messages system messages only support text content for now")
  112. }),
  113. )
  114. it.effect("falls back for unsupported native chronological system update placement", () =>
  115. Effect.gen(function* () {
  116. expect(
  117. (yield* LLMClient.prepare<AnthropicMessages.AnthropicMessagesBody>(
  118. LLM.request({
  119. model: opus48,
  120. messages: [Message.assistant("Plain."), Message.system("After plain assistant.")],
  121. cache: "none",
  122. }),
  123. )).body.messages,
  124. ).toEqual([
  125. { role: "assistant", content: [{ type: "text", text: "Plain." }] },
  126. {
  127. role: "user",
  128. content: [{ type: "text", text: "<system-update>\nAfter plain assistant.\n</system-update>" }],
  129. },
  130. ])
  131. expect(
  132. (yield* LLMClient.prepare<AnthropicMessages.AnthropicMessagesBody>(
  133. LLM.request({ model: opus48, messages: [Message.system("First.")], cache: "none" }),
  134. )).body.messages,
  135. ).toEqual([{ role: "user", content: [{ type: "text", text: "<system-update>\nFirst.\n</system-update>" }] }])
  136. expect(
  137. (yield* LLMClient.prepare<AnthropicMessages.AnthropicMessagesBody>(
  138. LLM.request({
  139. model: opus48,
  140. messages: [Message.user("Before."), Message.system("One."), Message.system("Two.")],
  141. cache: "none",
  142. }),
  143. )).body.messages,
  144. ).toEqual([
  145. {
  146. role: "user",
  147. content: [
  148. { type: "text", text: "Before." },
  149. { type: "text", text: "<system-update>\nOne.\n</system-update>" },
  150. { type: "text", text: "<system-update>\nTwo.\n</system-update>" },
  151. ],
  152. },
  153. ])
  154. }),
  155. )
  156. it.effect("rejects a system update between a local tool call and its result", () =>
  157. Effect.gen(function* () {
  158. const error = yield* LLMClient.prepare(
  159. LLM.request({
  160. model: opus48,
  161. messages: [
  162. Message.user("Use the tool."),
  163. Message.assistant([ToolCallPart.make({ id: "call_1", name: "lookup", input: {} })]),
  164. Message.system("Too early."),
  165. Message.tool({ id: "call_1", name: "lookup", result: "Done." }),
  166. ],
  167. cache: "none",
  168. }),
  169. ).pipe(Effect.flip)
  170. expect(error.message).toContain("system updates cannot split a local tool call from its tool result")
  171. }),
  172. )
  173. it.effect("prepares tool call and tool result messages", () =>
  174. Effect.gen(function* () {
  175. const prepared = yield* LLMClient.prepare<AnthropicMessages.AnthropicMessagesBody>(
  176. LLM.request({
  177. id: "req_tool_result",
  178. model,
  179. messages: [
  180. Message.user("What is the weather?"),
  181. Message.assistant([ToolCallPart.make({ id: "call_1", name: "lookup", input: { query: "weather" } })]),
  182. Message.tool({ id: "call_1", name: "lookup", result: { forecast: "sunny" } }),
  183. ],
  184. cache: "none",
  185. }),
  186. )
  187. expect(prepared.body).toEqual({
  188. model: "claude-sonnet-4-5",
  189. messages: [
  190. { role: "user", content: [{ type: "text", text: "What is the weather?" }] },
  191. {
  192. role: "assistant",
  193. content: [{ type: "tool_use", id: "call_1", name: "lookup", input: { query: "weather" } }],
  194. },
  195. { role: "user", content: [{ type: "tool_result", tool_use_id: "call_1", content: '{"forecast":"sunny"}' }] },
  196. ],
  197. stream: true,
  198. max_tokens: 4096,
  199. })
  200. }),
  201. )
  202. // Regression: screenshot/read tool results must stay structured so base64
  203. // image data is not JSON-stringified into `tool_result.content`.
  204. it.effect("lowers image tool-result content as structured image blocks", () =>
  205. Effect.gen(function* () {
  206. const prepared = yield* LLMClient.prepare<AnthropicMessages.AnthropicMessagesBody>(
  207. LLM.request({
  208. id: "req_tool_result_image",
  209. model,
  210. messages: [
  211. Message.user("Show me the screenshot."),
  212. Message.assistant([ToolCallPart.make({ id: "call_1", name: "read", input: { filePath: "shot.png" } })]),
  213. Message.tool({
  214. id: "call_1",
  215. name: "read",
  216. resultType: "content",
  217. result: [
  218. { type: "text", text: "Image read successfully" },
  219. { type: "file", uri: "data:image/png;base64,AAECAw==", mime: "image/png" },
  220. ],
  221. }),
  222. ],
  223. cache: "none",
  224. }),
  225. )
  226. expect(expectToolResult(prepared.body).content).toEqual([
  227. { type: "text", text: "Image read successfully" },
  228. { type: "image", source: { type: "base64", media_type: "image/png", data: "AAECAw==" } },
  229. ])
  230. }),
  231. )
  232. it.effect("lowers single-image tool-result content as a structured image block", () =>
  233. Effect.gen(function* () {
  234. const prepared = yield* LLMClient.prepare<AnthropicMessages.AnthropicMessagesBody>(
  235. LLM.request({
  236. id: "req_tool_result_image_only",
  237. model,
  238. messages: [
  239. Message.assistant([ToolCallPart.make({ id: "call_1", name: "screenshot", input: {} })]),
  240. Message.tool({
  241. id: "call_1",
  242. name: "screenshot",
  243. resultType: "content",
  244. result: [{ type: "file", uri: "data:image/jpeg;base64,/9j/AA==", mime: "image/jpeg" }],
  245. }),
  246. ],
  247. cache: "none",
  248. }),
  249. )
  250. expect(expectToolResult(prepared.body).content).toEqual([
  251. { type: "image", source: { type: "base64", media_type: "image/jpeg", data: "/9j/AA==" } },
  252. ])
  253. }),
  254. )
  255. it.effect("rejects non-image media in tool-result content with a clear error", () =>
  256. Effect.gen(function* () {
  257. const error = yield* LLMClient.prepare(
  258. LLM.request({
  259. id: "req_tool_result_unsupported_media",
  260. model,
  261. messages: [
  262. Message.assistant([ToolCallPart.make({ id: "call_1", name: "fetch", input: {} })]),
  263. Message.tool({
  264. id: "call_1",
  265. name: "fetch",
  266. resultType: "content",
  267. result: [{ type: "file", uri: "data:audio/mpeg;base64,AAECAw==", mime: "audio/mpeg" }],
  268. }),
  269. ],
  270. cache: "none",
  271. }),
  272. ).pipe(Effect.flip)
  273. expect(error.message).toContain("Anthropic Messages")
  274. expect(error.message).toContain("audio/mpeg")
  275. }),
  276. )
  277. it.effect("prepares the composed native continuation request", () =>
  278. Effect.gen(function* () {
  279. const prepared = yield* LLMClient.prepare<AnthropicMessages.AnthropicMessagesBody>(
  280. continuationRequest({
  281. id: "req_native_continuation_anthropic",
  282. model,
  283. features: nativeAnthropicMessagesContinuation,
  284. }),
  285. )
  286. expect(prepared.body).toMatchObject({
  287. system: [{ type: "text", text: "You are concise. Continue from the provided history." }],
  288. messages: [
  289. {
  290. role: "user",
  291. content: [
  292. { type: "text", text: "What is shown here?" },
  293. { type: "image", source: { type: "base64", media_type: "image/png", data: "AAECAw==" } },
  294. ],
  295. },
  296. {
  297. role: "assistant",
  298. content: [
  299. { type: "thinking", thinking: "I inspected the previous turn.", signature: "sig_continuation_1" },
  300. { type: "text", text: "It shows a small test image." },
  301. ],
  302. },
  303. { role: "user", content: [{ type: "text", text: "Check the weather in Paris before continuing." }] },
  304. {
  305. role: "assistant",
  306. content: [{ type: "tool_use", id: "call_weather_1", name: "get_weather", input: { city: "Paris" } }],
  307. },
  308. {
  309. role: "user",
  310. content: [{ type: "tool_result", tool_use_id: "call_weather_1", content: '{"temperature":22}' }],
  311. },
  312. { role: "assistant", content: [{ type: "text", text: "Paris is 22 degrees." }] },
  313. { role: "user", content: [{ type: "text", text: "Continue from this conversation in one short sentence." }] },
  314. ],
  315. })
  316. expect(prepared.body.tools).toEqual([expect.objectContaining({ name: "get_weather" })])
  317. }),
  318. )
  319. it.effect("lowers preserved Anthropic reasoning signature metadata", () =>
  320. Effect.gen(function* () {
  321. const prepared = yield* LLMClient.prepare(
  322. LLM.request({
  323. model,
  324. messages: [
  325. Message.assistant([
  326. { type: "reasoning", text: "thinking", providerMetadata: { anthropic: { signature: "sig_1" } } },
  327. ]),
  328. ],
  329. }),
  330. )
  331. expect(prepared.body).toMatchObject({
  332. messages: [{ role: "assistant", content: [{ type: "thinking", thinking: "thinking", signature: "sig_1" }] }],
  333. })
  334. }),
  335. )
  336. it.effect("parses text, reasoning, and usage stream fixtures", () =>
  337. Effect.gen(function* () {
  338. const body = sseEvents(
  339. { type: "message_start", message: { usage: { input_tokens: 5, cache_read_input_tokens: 1 } } },
  340. { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
  341. { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "Hello" } },
  342. { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "!" } },
  343. { type: "content_block_stop", index: 0 },
  344. { type: "content_block_start", index: 1, content_block: { type: "thinking", thinking: "" } },
  345. { type: "content_block_delta", index: 1, delta: { type: "thinking_delta", thinking: "thinking" } },
  346. { type: "content_block_delta", index: 1, delta: { type: "signature_delta", signature: "sig_1" } },
  347. { type: "content_block_stop", index: 1 },
  348. {
  349. type: "message_delta",
  350. delta: { stop_reason: "end_turn", stop_sequence: "\n\nHuman:" },
  351. usage: { output_tokens: 2 },
  352. },
  353. { type: "message_stop" },
  354. )
  355. const response = yield* LLMClient.generate(request).pipe(Effect.provide(fixedResponse(body)))
  356. expect(response.text).toBe("Hello!")
  357. expect(response.reasoning).toBe("thinking")
  358. expect(response.usage).toMatchObject({
  359. inputTokens: 6,
  360. outputTokens: 2,
  361. nonCachedInputTokens: 5,
  362. cacheReadInputTokens: 1,
  363. totalTokens: 8,
  364. })
  365. expect(response.events.find((event) => event.type === "reasoning-end")).toMatchObject({
  366. providerMetadata: { anthropic: { signature: "sig_1" } },
  367. })
  368. expect(response.events.at(-1)).toMatchObject({
  369. type: "finish",
  370. reason: "stop",
  371. providerMetadata: { anthropic: { stopSequence: "\n\nHuman:" } },
  372. })
  373. }),
  374. )
  375. it.effect("assembles streamed tool call input", () =>
  376. Effect.gen(function* () {
  377. const body = sseEvents(
  378. { type: "message_start", message: { usage: { input_tokens: 5 } } },
  379. { type: "content_block_start", index: 0, content_block: { type: "tool_use", id: "call_1", name: "lookup" } },
  380. { type: "content_block_delta", index: 0, delta: { type: "input_json_delta", partial_json: '{"query"' } },
  381. { type: "content_block_delta", index: 0, delta: { type: "input_json_delta", partial_json: ':"weather"}' } },
  382. { type: "content_block_stop", index: 0 },
  383. { type: "message_delta", delta: { stop_reason: "tool_use" }, usage: { output_tokens: 1 } },
  384. )
  385. const response = yield* LLMClient.generate(
  386. LLM.updateRequest(request, {
  387. tools: [{ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } }],
  388. }),
  389. ).pipe(Effect.provide(fixedResponse(body)))
  390. const usage = new Usage({
  391. inputTokens: 5,
  392. outputTokens: 1,
  393. nonCachedInputTokens: 5,
  394. cacheReadInputTokens: undefined,
  395. cacheWriteInputTokens: undefined,
  396. totalTokens: 6,
  397. providerMetadata: { anthropic: { input_tokens: 5, output_tokens: 1 } },
  398. })
  399. expect(response.toolCalls).toEqual([
  400. {
  401. type: "tool-call",
  402. id: "call_1",
  403. name: "lookup",
  404. input: { query: "weather" },
  405. providerExecuted: undefined,
  406. providerMetadata: undefined,
  407. },
  408. ])
  409. expect(response.events).toEqual([
  410. { type: "step-start", index: 0 },
  411. { type: "tool-input-start", id: "call_1", name: "lookup" },
  412. { type: "tool-input-delta", id: "call_1", name: "lookup", text: '{"query"' },
  413. { type: "tool-input-delta", id: "call_1", name: "lookup", text: ':"weather"}' },
  414. { type: "tool-input-end", id: "call_1", name: "lookup", providerMetadata: undefined },
  415. {
  416. type: "tool-call",
  417. id: "call_1",
  418. name: "lookup",
  419. input: { query: "weather" },
  420. providerExecuted: undefined,
  421. providerMetadata: undefined,
  422. },
  423. { type: "step-finish", index: 0, reason: "tool-calls", usage, providerMetadata: undefined },
  424. {
  425. type: "finish",
  426. reason: "tool-calls",
  427. providerMetadata: undefined,
  428. usage,
  429. },
  430. ])
  431. }),
  432. )
  433. it.effect("emits provider-error events for mid-stream provider errors", () =>
  434. Effect.gen(function* () {
  435. const response = yield* LLMClient.generate(request).pipe(
  436. Effect.provide(
  437. fixedResponse(sseEvents({ type: "error", error: { type: "overloaded_error", message: "Overloaded" } })),
  438. ),
  439. )
  440. // Prefix the error type so consumers can distinguish overloads, rate
  441. // limits, and quota errors without parsing the message string.
  442. expect(response.events).toEqual([{ type: "provider-error", message: "overloaded_error: Overloaded" }])
  443. }),
  444. )
  445. it.effect("classifies prompt-too-long provider errors", () =>
  446. Effect.gen(function* () {
  447. const response = yield* LLMClient.generate(request).pipe(
  448. Effect.provide(
  449. fixedResponse(
  450. sseEvents({
  451. type: "error",
  452. error: { type: "invalid_request_error", message: "prompt is too long: 210000 tokens" },
  453. }),
  454. ),
  455. ),
  456. )
  457. expect(response.events).toEqual([
  458. {
  459. type: "provider-error",
  460. message: "invalid_request_error: prompt is too long: 210000 tokens",
  461. classification: "context-overflow",
  462. },
  463. ])
  464. }),
  465. )
  466. it.effect("falls back to error type when no message is present", () =>
  467. Effect.gen(function* () {
  468. const response = yield* LLMClient.generate(request).pipe(
  469. Effect.provide(fixedResponse(sseEvents({ type: "error", error: { type: "overloaded_error", message: "" } }))),
  470. )
  471. expect(response.events).toEqual([{ type: "provider-error", message: "overloaded_error" }])
  472. }),
  473. )
  474. it.effect("falls back to a stable default when error payload is absent", () =>
  475. Effect.gen(function* () {
  476. const response = yield* LLMClient.generate(request).pipe(
  477. Effect.provide(fixedResponse(sseEvents({ type: "error" }))),
  478. )
  479. expect(response.events).toEqual([{ type: "provider-error", message: "Anthropic Messages stream error" }])
  480. }),
  481. )
  482. it.effect("fails HTTP provider errors before stream parsing", () =>
  483. Effect.gen(function* () {
  484. const error = yield* LLMClient.generate(request).pipe(
  485. Effect.provide(
  486. fixedResponse('{"type":"error","error":{"type":"invalid_request_error","message":"Bad request"}}', {
  487. status: 400,
  488. headers: { "content-type": "application/json" },
  489. }),
  490. ),
  491. Effect.flip,
  492. )
  493. expect(error).toBeInstanceOf(LLMError)
  494. expect(error.reason).toMatchObject({ _tag: "InvalidRequest" })
  495. expect(error.message).toContain("HTTP 400")
  496. }),
  497. )
  498. it.effect("decodes server_tool_use + web_search_tool_result as provider-executed events", () =>
  499. Effect.gen(function* () {
  500. const body = sseEvents(
  501. { type: "message_start", message: { usage: { input_tokens: 5 } } },
  502. {
  503. type: "content_block_start",
  504. index: 0,
  505. content_block: { type: "server_tool_use", id: "srvtoolu_abc", name: "web_search" },
  506. },
  507. {
  508. type: "content_block_delta",
  509. index: 0,
  510. delta: { type: "input_json_delta", partial_json: '{"query":"effect 4"}' },
  511. },
  512. { type: "content_block_stop", index: 0 },
  513. {
  514. type: "content_block_start",
  515. index: 1,
  516. content_block: {
  517. type: "web_search_tool_result",
  518. tool_use_id: "srvtoolu_abc",
  519. content: [{ type: "web_search_result", url: "https://example.com", title: "Example" }],
  520. },
  521. },
  522. { type: "content_block_stop", index: 1 },
  523. { type: "content_block_start", index: 2, content_block: { type: "text", text: "" } },
  524. { type: "content_block_delta", index: 2, delta: { type: "text_delta", text: "Found it." } },
  525. { type: "content_block_stop", index: 2 },
  526. { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 8 } },
  527. )
  528. const response = yield* LLMClient.generate(
  529. LLM.updateRequest(request, {
  530. tools: [{ name: "web_search", description: "Web search", inputSchema: { type: "object" } }],
  531. }),
  532. ).pipe(Effect.provide(fixedResponse(body)))
  533. const toolCall = response.events.find((event) => event.type === "tool-call")
  534. expect(toolCall).toEqual({
  535. type: "tool-call",
  536. id: "srvtoolu_abc",
  537. name: "web_search",
  538. input: { query: "effect 4" },
  539. providerExecuted: true,
  540. })
  541. const toolResult = response.events.find((event) => event.type === "tool-result")
  542. expect(toolResult).toEqual({
  543. type: "tool-result",
  544. id: "srvtoolu_abc",
  545. name: "web_search",
  546. result: { type: "json", value: [{ type: "web_search_result", url: "https://example.com", title: "Example" }] },
  547. providerExecuted: true,
  548. providerMetadata: { anthropic: { blockType: "web_search_tool_result" } },
  549. })
  550. expect(response.text).toBe("Found it.")
  551. expect(response.events.at(-1)).toMatchObject({ type: "finish", reason: "stop" })
  552. }),
  553. )
  554. it.effect("decodes web_search_tool_result_error as provider-executed error result", () =>
  555. Effect.gen(function* () {
  556. const body = sseEvents(
  557. { type: "message_start", message: { usage: { input_tokens: 5 } } },
  558. {
  559. type: "content_block_start",
  560. index: 0,
  561. content_block: { type: "server_tool_use", id: "srvtoolu_x", name: "web_search" },
  562. },
  563. { type: "content_block_delta", index: 0, delta: { type: "input_json_delta", partial_json: '{"query":"q"}' } },
  564. { type: "content_block_stop", index: 0 },
  565. {
  566. type: "content_block_start",
  567. index: 1,
  568. content_block: {
  569. type: "web_search_tool_result",
  570. tool_use_id: "srvtoolu_x",
  571. content: { type: "web_search_tool_result_error", error_code: "max_uses_exceeded" },
  572. },
  573. },
  574. { type: "content_block_stop", index: 1 },
  575. { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 1 } },
  576. )
  577. const response = yield* LLMClient.generate(
  578. LLM.updateRequest(request, {
  579. tools: [{ name: "web_search", description: "Web search", inputSchema: { type: "object" } }],
  580. }),
  581. ).pipe(Effect.provide(fixedResponse(body)))
  582. const toolResult = response.events.find((event) => event.type === "tool-result")
  583. expect(toolResult).toMatchObject({
  584. type: "tool-result",
  585. id: "srvtoolu_x",
  586. name: "web_search",
  587. result: { type: "error" },
  588. providerExecuted: true,
  589. })
  590. }),
  591. )
  592. it.effect("round-trips provider-executed assistant content into server tool blocks", () =>
  593. Effect.gen(function* () {
  594. const prepared = yield* LLMClient.prepare(
  595. LLM.request({
  596. id: "req_round_trip",
  597. model,
  598. messages: [
  599. Message.user("Search for something."),
  600. Message.assistant([
  601. {
  602. type: "tool-call",
  603. id: "srvtoolu_abc",
  604. name: "web_search",
  605. input: { query: "effect 4" },
  606. providerExecuted: true,
  607. },
  608. {
  609. type: "tool-result",
  610. id: "srvtoolu_abc",
  611. name: "web_search",
  612. result: { type: "json", value: [{ url: "https://example.com" }] },
  613. providerExecuted: true,
  614. },
  615. { type: "text", text: "Found it." },
  616. ]),
  617. Message.user("Thanks."),
  618. ],
  619. }),
  620. )
  621. expect(prepared.body).toMatchObject({
  622. messages: [
  623. { role: "user", content: [{ type: "text", text: "Search for something." }] },
  624. {
  625. role: "assistant",
  626. content: [
  627. { type: "server_tool_use", id: "srvtoolu_abc", name: "web_search", input: { query: "effect 4" } },
  628. {
  629. type: "web_search_tool_result",
  630. tool_use_id: "srvtoolu_abc",
  631. content: [{ url: "https://example.com" }],
  632. },
  633. { type: "text", text: "Found it." },
  634. ],
  635. },
  636. { role: "user", content: [{ type: "text", text: "Thanks." }] },
  637. ],
  638. })
  639. }),
  640. )
  641. it.effect("rejects round-trip for unknown server tool names", () =>
  642. Effect.gen(function* () {
  643. const error = yield* LLMClient.prepare(
  644. LLM.request({
  645. id: "req_unknown_server_tool",
  646. model,
  647. messages: [
  648. Message.assistant([
  649. {
  650. type: "tool-result",
  651. id: "srvtoolu_abc",
  652. name: "future_server_tool",
  653. result: { type: "json", value: {} },
  654. providerExecuted: true,
  655. },
  656. ]),
  657. ],
  658. }),
  659. ).pipe(Effect.flip)
  660. expect(error.message).toContain("future_server_tool")
  661. }),
  662. )
  663. it.effect("continues a conversation with user image content", () =>
  664. Effect.gen(function* () {
  665. const response = yield* LLMClient.generate(
  666. LLM.request({
  667. id: "req_media",
  668. model,
  669. messages: [
  670. Message.user([
  671. { type: "text", text: "What is in this image?" },
  672. { type: "media", mediaType: "image/png", data: "AAECAw==" },
  673. ]),
  674. ],
  675. }),
  676. ).pipe(
  677. Effect.provide(
  678. dynamicResponse((input) =>
  679. Effect.gen(function* () {
  680. const web = yield* HttpClientRequest.toWeb(input.request).pipe(Effect.orDie)
  681. expect(yield* Effect.promise(() => web.json())).toMatchObject({
  682. messages: [
  683. {
  684. role: "user",
  685. content: [
  686. { type: "text", text: "What is in this image?" },
  687. { type: "image", source: { type: "base64", media_type: "image/png", data: "AAECAw==" } },
  688. ],
  689. },
  690. ],
  691. })
  692. return input.respond(
  693. sseEvents(
  694. { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
  695. { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "An image." } },
  696. { type: "content_block_stop", index: 0 },
  697. { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 3 } },
  698. { type: "message_stop" },
  699. ),
  700. { headers: { "content-type": "text/event-stream" } },
  701. )
  702. }),
  703. ),
  704. ),
  705. )
  706. expect(response.text).toBe("An image.")
  707. }),
  708. )
  709. it.effect("maps ttlSeconds >= 3600 to cache_control ttl: '1h'", () =>
  710. Effect.gen(function* () {
  711. const prepared = yield* LLMClient.prepare(
  712. LLM.request({
  713. model,
  714. system: { type: "text", text: "system", cache: new CacheHint({ type: "ephemeral", ttlSeconds: 3600 }) },
  715. prompt: "hi",
  716. }),
  717. )
  718. expect(prepared.body).toMatchObject({
  719. system: [{ type: "text", text: "system", cache_control: { type: "ephemeral", ttl: "1h" } }],
  720. })
  721. }),
  722. )
  723. it.effect("emits cache_control on tool definitions and tool-result blocks", () =>
  724. Effect.gen(function* () {
  725. const prepared = yield* LLMClient.prepare(
  726. LLM.request({
  727. model,
  728. tools: [
  729. {
  730. name: "lookup",
  731. description: "lookup tool",
  732. inputSchema: { type: "object", properties: {} },
  733. cache: new CacheHint({ type: "ephemeral" }),
  734. },
  735. ],
  736. messages: [
  737. Message.user("What's the weather?"),
  738. Message.assistant([ToolCallPart.make({ id: "call_1", name: "lookup", input: {} })]),
  739. Message.tool({
  740. id: "call_1",
  741. name: "lookup",
  742. result: { temp: 72 },
  743. cache: new CacheHint({ type: "ephemeral" }),
  744. }),
  745. ],
  746. }),
  747. )
  748. expect(prepared.body).toMatchObject({
  749. tools: [{ name: "lookup", cache_control: { type: "ephemeral" } }],
  750. messages: [
  751. { role: "user", content: [{ type: "text", text: "What's the weather?" }] },
  752. { role: "assistant", content: [{ type: "tool_use", id: "call_1", name: "lookup" }] },
  753. {
  754. role: "user",
  755. content: [{ type: "tool_result", tool_use_id: "call_1", cache_control: { type: "ephemeral" } }],
  756. },
  757. ],
  758. })
  759. }),
  760. )
  761. it.effect("drops cache_control breakpoints past the 4-per-request cap", () =>
  762. Effect.gen(function* () {
  763. const hint = new CacheHint({ type: "ephemeral" })
  764. const prepared = yield* LLMClient.prepare(
  765. LLM.request({
  766. model,
  767. system: [
  768. { type: "text", text: "a", cache: hint },
  769. { type: "text", text: "b", cache: hint },
  770. { type: "text", text: "c", cache: hint },
  771. { type: "text", text: "d", cache: hint },
  772. { type: "text", text: "e", cache: hint },
  773. { type: "text", text: "f", cache: hint },
  774. ],
  775. prompt: "hi",
  776. }),
  777. )
  778. const system = (prepared.body as { system: Array<{ cache_control?: unknown }> }).system
  779. const marked = system.filter((part) => part.cache_control !== undefined)
  780. expect(marked).toHaveLength(4)
  781. expect(system[4]?.cache_control).toBeUndefined()
  782. expect(system[5]?.cache_control).toBeUndefined()
  783. }),
  784. )
  785. it.effect("spends breakpoint budget on tools before system before messages", () =>
  786. Effect.gen(function* () {
  787. const hint = new CacheHint({ type: "ephemeral" })
  788. const prepared = yield* LLMClient.prepare(
  789. LLM.request({
  790. model,
  791. tools: [
  792. {
  793. name: "t1",
  794. description: "t1",
  795. inputSchema: { type: "object", properties: {} },
  796. cache: hint,
  797. },
  798. {
  799. name: "t2",
  800. description: "t2",
  801. inputSchema: { type: "object", properties: {} },
  802. cache: hint,
  803. },
  804. {
  805. name: "t3",
  806. description: "t3",
  807. inputSchema: { type: "object", properties: {} },
  808. cache: hint,
  809. },
  810. {
  811. name: "t4",
  812. description: "t4",
  813. inputSchema: { type: "object", properties: {} },
  814. cache: hint,
  815. },
  816. ],
  817. system: [{ type: "text", text: "system-tail", cache: hint }],
  818. messages: [Message.user([{ type: "text", text: "message-tail", cache: hint }])],
  819. }),
  820. )
  821. const body = prepared.body as {
  822. tools: Array<{ cache_control?: unknown }>
  823. system: Array<{ cache_control?: unknown }>
  824. messages: Array<{ content: Array<{ cache_control?: unknown }> }>
  825. }
  826. expect(body.tools.every((t) => t.cache_control !== undefined)).toBe(true)
  827. expect(body.system[0]?.cache_control).toBeUndefined()
  828. expect(body.messages[0]?.content[0]?.cache_control).toBeUndefined()
  829. }),
  830. )
  831. })