anthropic-messages.test.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  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.message.content).toEqual([
  369. { type: "text", text: "Hello!" },
  370. { type: "reasoning", text: "thinking", providerMetadata: { anthropic: { signature: "sig_1" } } },
  371. ])
  372. expect(response.events.at(-1)).toMatchObject({
  373. type: "finish",
  374. reason: "stop",
  375. providerMetadata: { anthropic: { stopSequence: "\n\nHuman:" } },
  376. })
  377. }),
  378. )
  379. it.effect("assembles streamed tool call input", () =>
  380. Effect.gen(function* () {
  381. const body = sseEvents(
  382. { type: "message_start", message: { usage: { input_tokens: 5 } } },
  383. { type: "content_block_start", index: 0, content_block: { type: "tool_use", id: "call_1", name: "lookup" } },
  384. { type: "content_block_delta", index: 0, delta: { type: "input_json_delta", partial_json: '{"query"' } },
  385. { type: "content_block_delta", index: 0, delta: { type: "input_json_delta", partial_json: ':"weather"}' } },
  386. { type: "content_block_stop", index: 0 },
  387. { type: "message_delta", delta: { stop_reason: "tool_use" }, usage: { output_tokens: 1 } },
  388. )
  389. const response = yield* LLMClient.generate(
  390. LLM.updateRequest(request, {
  391. tools: [{ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } }],
  392. }),
  393. ).pipe(Effect.provide(fixedResponse(body)))
  394. const usage = new Usage({
  395. inputTokens: 5,
  396. outputTokens: 1,
  397. nonCachedInputTokens: 5,
  398. cacheReadInputTokens: undefined,
  399. cacheWriteInputTokens: undefined,
  400. totalTokens: 6,
  401. providerMetadata: { anthropic: { input_tokens: 5, output_tokens: 1 } },
  402. })
  403. expect(response.toolCalls).toEqual([
  404. {
  405. type: "tool-call",
  406. id: "call_1",
  407. name: "lookup",
  408. input: { query: "weather" },
  409. providerExecuted: undefined,
  410. providerMetadata: undefined,
  411. },
  412. ])
  413. expect(response.events).toEqual([
  414. { type: "step-start", index: 0 },
  415. { type: "tool-input-start", id: "call_1", name: "lookup" },
  416. { type: "tool-input-delta", id: "call_1", name: "lookup", text: '{"query"' },
  417. { type: "tool-input-delta", id: "call_1", name: "lookup", text: ':"weather"}' },
  418. { type: "tool-input-end", id: "call_1", name: "lookup", providerMetadata: undefined },
  419. {
  420. type: "tool-call",
  421. id: "call_1",
  422. name: "lookup",
  423. input: { query: "weather" },
  424. providerExecuted: undefined,
  425. providerMetadata: undefined,
  426. },
  427. { type: "step-finish", index: 0, reason: "tool-calls", usage, providerMetadata: undefined },
  428. {
  429. type: "finish",
  430. reason: "tool-calls",
  431. providerMetadata: undefined,
  432. usage,
  433. },
  434. ])
  435. }),
  436. )
  437. it.effect("emits provider-error events for mid-stream provider errors", () =>
  438. Effect.gen(function* () {
  439. const response = yield* LLMClient.generate(request).pipe(
  440. Effect.provide(
  441. fixedResponse(sseEvents({ type: "error", error: { type: "overloaded_error", message: "Overloaded" } })),
  442. ),
  443. )
  444. // Prefix the error type so consumers can distinguish overloads, rate
  445. // limits, and quota errors without parsing the message string.
  446. expect(response.events).toEqual([{ type: "provider-error", message: "overloaded_error: Overloaded" }])
  447. }),
  448. )
  449. it.effect("classifies prompt-too-long provider errors", () =>
  450. Effect.gen(function* () {
  451. const response = yield* LLMClient.generate(request).pipe(
  452. Effect.provide(
  453. fixedResponse(
  454. sseEvents({
  455. type: "error",
  456. error: { type: "invalid_request_error", message: "prompt is too long: 210000 tokens" },
  457. }),
  458. ),
  459. ),
  460. )
  461. expect(response.events).toEqual([
  462. {
  463. type: "provider-error",
  464. message: "invalid_request_error: prompt is too long: 210000 tokens",
  465. classification: "context-overflow",
  466. },
  467. ])
  468. }),
  469. )
  470. it.effect("falls back to error type when no message is present", () =>
  471. Effect.gen(function* () {
  472. const response = yield* LLMClient.generate(request).pipe(
  473. Effect.provide(fixedResponse(sseEvents({ type: "error", error: { type: "overloaded_error", message: "" } }))),
  474. )
  475. expect(response.events).toEqual([{ type: "provider-error", message: "overloaded_error" }])
  476. }),
  477. )
  478. it.effect("falls back to a stable default when error payload is absent", () =>
  479. Effect.gen(function* () {
  480. const response = yield* LLMClient.generate(request).pipe(
  481. Effect.provide(fixedResponse(sseEvents({ type: "error" }))),
  482. )
  483. expect(response.events).toEqual([{ type: "provider-error", message: "Anthropic Messages stream error" }])
  484. }),
  485. )
  486. it.effect("fails HTTP provider errors before stream parsing", () =>
  487. Effect.gen(function* () {
  488. const error = yield* LLMClient.generate(request).pipe(
  489. Effect.provide(
  490. fixedResponse('{"type":"error","error":{"type":"invalid_request_error","message":"Bad request"}}', {
  491. status: 400,
  492. headers: { "content-type": "application/json" },
  493. }),
  494. ),
  495. Effect.flip,
  496. )
  497. expect(error).toBeInstanceOf(LLMError)
  498. expect(error.reason).toMatchObject({ _tag: "InvalidRequest" })
  499. expect(error.message).toContain("HTTP 400")
  500. }),
  501. )
  502. it.effect("decodes server_tool_use + web_search_tool_result as provider-executed events", () =>
  503. Effect.gen(function* () {
  504. const body = sseEvents(
  505. { type: "message_start", message: { usage: { input_tokens: 5 } } },
  506. {
  507. type: "content_block_start",
  508. index: 0,
  509. content_block: { type: "server_tool_use", id: "srvtoolu_abc", name: "web_search" },
  510. },
  511. {
  512. type: "content_block_delta",
  513. index: 0,
  514. delta: { type: "input_json_delta", partial_json: '{"query":"effect 4"}' },
  515. },
  516. { type: "content_block_stop", index: 0 },
  517. {
  518. type: "content_block_start",
  519. index: 1,
  520. content_block: {
  521. type: "web_search_tool_result",
  522. tool_use_id: "srvtoolu_abc",
  523. content: [{ type: "web_search_result", url: "https://example.com", title: "Example" }],
  524. },
  525. },
  526. { type: "content_block_stop", index: 1 },
  527. { type: "content_block_start", index: 2, content_block: { type: "text", text: "" } },
  528. { type: "content_block_delta", index: 2, delta: { type: "text_delta", text: "Found it." } },
  529. { type: "content_block_stop", index: 2 },
  530. { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 8 } },
  531. )
  532. const response = yield* LLMClient.generate(
  533. LLM.updateRequest(request, {
  534. tools: [{ name: "web_search", description: "Web search", inputSchema: { type: "object" } }],
  535. }),
  536. ).pipe(Effect.provide(fixedResponse(body)))
  537. const toolCall = response.events.find((event) => event.type === "tool-call")
  538. expect(toolCall).toEqual({
  539. type: "tool-call",
  540. id: "srvtoolu_abc",
  541. name: "web_search",
  542. input: { query: "effect 4" },
  543. providerExecuted: true,
  544. })
  545. const toolResult = response.events.find((event) => event.type === "tool-result")
  546. expect(toolResult).toEqual({
  547. type: "tool-result",
  548. id: "srvtoolu_abc",
  549. name: "web_search",
  550. result: { type: "json", value: [{ type: "web_search_result", url: "https://example.com", title: "Example" }] },
  551. providerExecuted: true,
  552. providerMetadata: { anthropic: { blockType: "web_search_tool_result" } },
  553. })
  554. expect(response.text).toBe("Found it.")
  555. expect(response.events.at(-1)).toMatchObject({ type: "finish", reason: "stop" })
  556. }),
  557. )
  558. it.effect("decodes web_search_tool_result_error as provider-executed error result", () =>
  559. Effect.gen(function* () {
  560. const body = sseEvents(
  561. { type: "message_start", message: { usage: { input_tokens: 5 } } },
  562. {
  563. type: "content_block_start",
  564. index: 0,
  565. content_block: { type: "server_tool_use", id: "srvtoolu_x", name: "web_search" },
  566. },
  567. { type: "content_block_delta", index: 0, delta: { type: "input_json_delta", partial_json: '{"query":"q"}' } },
  568. { type: "content_block_stop", index: 0 },
  569. {
  570. type: "content_block_start",
  571. index: 1,
  572. content_block: {
  573. type: "web_search_tool_result",
  574. tool_use_id: "srvtoolu_x",
  575. content: { type: "web_search_tool_result_error", error_code: "max_uses_exceeded" },
  576. },
  577. },
  578. { type: "content_block_stop", index: 1 },
  579. { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 1 } },
  580. )
  581. const response = yield* LLMClient.generate(
  582. LLM.updateRequest(request, {
  583. tools: [{ name: "web_search", description: "Web search", inputSchema: { type: "object" } }],
  584. }),
  585. ).pipe(Effect.provide(fixedResponse(body)))
  586. const toolResult = response.events.find((event) => event.type === "tool-result")
  587. expect(toolResult).toMatchObject({
  588. type: "tool-result",
  589. id: "srvtoolu_x",
  590. name: "web_search",
  591. result: { type: "error" },
  592. providerExecuted: true,
  593. })
  594. }),
  595. )
  596. it.effect("round-trips provider-executed assistant content into server tool blocks", () =>
  597. Effect.gen(function* () {
  598. const prepared = yield* LLMClient.prepare(
  599. LLM.request({
  600. id: "req_round_trip",
  601. model,
  602. messages: [
  603. Message.user("Search for something."),
  604. Message.assistant([
  605. {
  606. type: "tool-call",
  607. id: "srvtoolu_abc",
  608. name: "web_search",
  609. input: { query: "effect 4" },
  610. providerExecuted: true,
  611. },
  612. {
  613. type: "tool-result",
  614. id: "srvtoolu_abc",
  615. name: "web_search",
  616. result: { type: "json", value: [{ url: "https://example.com" }] },
  617. providerExecuted: true,
  618. },
  619. { type: "text", text: "Found it." },
  620. ]),
  621. Message.user("Thanks."),
  622. ],
  623. }),
  624. )
  625. expect(prepared.body).toMatchObject({
  626. messages: [
  627. { role: "user", content: [{ type: "text", text: "Search for something." }] },
  628. {
  629. role: "assistant",
  630. content: [
  631. { type: "server_tool_use", id: "srvtoolu_abc", name: "web_search", input: { query: "effect 4" } },
  632. {
  633. type: "web_search_tool_result",
  634. tool_use_id: "srvtoolu_abc",
  635. content: [{ url: "https://example.com" }],
  636. },
  637. { type: "text", text: "Found it." },
  638. ],
  639. },
  640. { role: "user", content: [{ type: "text", text: "Thanks." }] },
  641. ],
  642. })
  643. }),
  644. )
  645. it.effect("rejects round-trip for unknown server tool names", () =>
  646. Effect.gen(function* () {
  647. const error = yield* LLMClient.prepare(
  648. LLM.request({
  649. id: "req_unknown_server_tool",
  650. model,
  651. messages: [
  652. Message.assistant([
  653. {
  654. type: "tool-result",
  655. id: "srvtoolu_abc",
  656. name: "future_server_tool",
  657. result: { type: "json", value: {} },
  658. providerExecuted: true,
  659. },
  660. ]),
  661. ],
  662. }),
  663. ).pipe(Effect.flip)
  664. expect(error.message).toContain("future_server_tool")
  665. }),
  666. )
  667. it.effect("continues a conversation with user image content", () =>
  668. Effect.gen(function* () {
  669. const response = yield* LLMClient.generate(
  670. LLM.request({
  671. id: "req_media",
  672. model,
  673. messages: [
  674. Message.user([
  675. { type: "text", text: "What is in this image?" },
  676. { type: "media", mediaType: "image/png", data: "AAECAw==" },
  677. ]),
  678. ],
  679. }),
  680. ).pipe(
  681. Effect.provide(
  682. dynamicResponse((input) =>
  683. Effect.gen(function* () {
  684. const web = yield* HttpClientRequest.toWeb(input.request).pipe(Effect.orDie)
  685. expect(yield* Effect.promise(() => web.json())).toMatchObject({
  686. messages: [
  687. {
  688. role: "user",
  689. content: [
  690. { type: "text", text: "What is in this image?" },
  691. { type: "image", source: { type: "base64", media_type: "image/png", data: "AAECAw==" } },
  692. ],
  693. },
  694. ],
  695. })
  696. return input.respond(
  697. sseEvents(
  698. { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
  699. { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "An image." } },
  700. { type: "content_block_stop", index: 0 },
  701. { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 3 } },
  702. { type: "message_stop" },
  703. ),
  704. { headers: { "content-type": "text/event-stream" } },
  705. )
  706. }),
  707. ),
  708. ),
  709. )
  710. expect(response.text).toBe("An image.")
  711. }),
  712. )
  713. it.effect("maps ttlSeconds >= 3600 to cache_control ttl: '1h'", () =>
  714. Effect.gen(function* () {
  715. const prepared = yield* LLMClient.prepare(
  716. LLM.request({
  717. model,
  718. system: { type: "text", text: "system", cache: new CacheHint({ type: "ephemeral", ttlSeconds: 3600 }) },
  719. prompt: "hi",
  720. }),
  721. )
  722. expect(prepared.body).toMatchObject({
  723. system: [{ type: "text", text: "system", cache_control: { type: "ephemeral", ttl: "1h" } }],
  724. })
  725. }),
  726. )
  727. it.effect("emits cache_control on tool definitions and tool-result blocks", () =>
  728. Effect.gen(function* () {
  729. const prepared = yield* LLMClient.prepare(
  730. LLM.request({
  731. model,
  732. tools: [
  733. {
  734. name: "lookup",
  735. description: "lookup tool",
  736. inputSchema: { type: "object", properties: {} },
  737. cache: new CacheHint({ type: "ephemeral" }),
  738. },
  739. ],
  740. messages: [
  741. Message.user("What's the weather?"),
  742. Message.assistant([ToolCallPart.make({ id: "call_1", name: "lookup", input: {} })]),
  743. Message.tool({
  744. id: "call_1",
  745. name: "lookup",
  746. result: { temp: 72 },
  747. cache: new CacheHint({ type: "ephemeral" }),
  748. }),
  749. ],
  750. }),
  751. )
  752. expect(prepared.body).toMatchObject({
  753. tools: [{ name: "lookup", cache_control: { type: "ephemeral" } }],
  754. messages: [
  755. { role: "user", content: [{ type: "text", text: "What's the weather?" }] },
  756. { role: "assistant", content: [{ type: "tool_use", id: "call_1", name: "lookup" }] },
  757. {
  758. role: "user",
  759. content: [{ type: "tool_result", tool_use_id: "call_1", cache_control: { type: "ephemeral" } }],
  760. },
  761. ],
  762. })
  763. }),
  764. )
  765. it.effect("drops cache_control breakpoints past the 4-per-request cap", () =>
  766. Effect.gen(function* () {
  767. const hint = new CacheHint({ type: "ephemeral" })
  768. const prepared = yield* LLMClient.prepare(
  769. LLM.request({
  770. model,
  771. system: [
  772. { type: "text", text: "a", cache: hint },
  773. { type: "text", text: "b", cache: hint },
  774. { type: "text", text: "c", cache: hint },
  775. { type: "text", text: "d", cache: hint },
  776. { type: "text", text: "e", cache: hint },
  777. { type: "text", text: "f", cache: hint },
  778. ],
  779. prompt: "hi",
  780. }),
  781. )
  782. const system = (prepared.body as { system: Array<{ cache_control?: unknown }> }).system
  783. const marked = system.filter((part) => part.cache_control !== undefined)
  784. expect(marked).toHaveLength(4)
  785. expect(system[4]?.cache_control).toBeUndefined()
  786. expect(system[5]?.cache_control).toBeUndefined()
  787. }),
  788. )
  789. it.effect("spends breakpoint budget on tools before system before messages", () =>
  790. Effect.gen(function* () {
  791. const hint = new CacheHint({ type: "ephemeral" })
  792. const prepared = yield* LLMClient.prepare(
  793. LLM.request({
  794. model,
  795. tools: [
  796. {
  797. name: "t1",
  798. description: "t1",
  799. inputSchema: { type: "object", properties: {} },
  800. cache: hint,
  801. },
  802. {
  803. name: "t2",
  804. description: "t2",
  805. inputSchema: { type: "object", properties: {} },
  806. cache: hint,
  807. },
  808. {
  809. name: "t3",
  810. description: "t3",
  811. inputSchema: { type: "object", properties: {} },
  812. cache: hint,
  813. },
  814. {
  815. name: "t4",
  816. description: "t4",
  817. inputSchema: { type: "object", properties: {} },
  818. cache: hint,
  819. },
  820. ],
  821. system: [{ type: "text", text: "system-tail", cache: hint }],
  822. messages: [Message.user([{ type: "text", text: "message-tail", cache: hint }])],
  823. }),
  824. )
  825. const body = prepared.body as {
  826. tools: Array<{ cache_control?: unknown }>
  827. system: Array<{ cache_control?: unknown }>
  828. messages: Array<{ content: Array<{ cache_control?: unknown }> }>
  829. }
  830. expect(body.tools.every((t) => t.cache_control !== undefined)).toBe(true)
  831. expect(body.system[0]?.cache_control).toBeUndefined()
  832. expect(body.messages[0]?.content[0]?.cache_control).toBeUndefined()
  833. }),
  834. )
  835. })