gemini.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. import { describe, expect } from "bun:test"
  2. import { Effect } from "effect"
  3. import { LLM, LLMError, Message, ToolCallPart, Usage } from "../../src"
  4. import { Auth, LLMClient } from "../../src/route"
  5. import * as Gemini from "../../src/protocols/gemini"
  6. import { it } from "../lib/effect"
  7. import { fixedResponse } from "../lib/http"
  8. import { sseEvents, sseRaw } from "../lib/sse"
  9. const model = Gemini.route
  10. .with({
  11. endpoint: { baseURL: "https://generativelanguage.test/v1beta/" },
  12. auth: Auth.header("x-goog-api-key", "test"),
  13. })
  14. .model({ id: "gemini-2.5-flash" })
  15. const request = LLM.request({
  16. id: "req_1",
  17. model,
  18. system: "You are concise.",
  19. prompt: "Say hello.",
  20. generation: { maxTokens: 20, temperature: 0 },
  21. })
  22. describe("Gemini route", () => {
  23. it.effect("prepares Gemini target", () =>
  24. Effect.gen(function* () {
  25. const prepared = yield* LLMClient.prepare(request)
  26. expect(prepared.body).toEqual({
  27. contents: [{ role: "user", parts: [{ text: "Say hello." }] }],
  28. systemInstruction: { parts: [{ text: "You are concise." }] },
  29. generationConfig: { maxOutputTokens: 20, temperature: 0 },
  30. })
  31. }),
  32. )
  33. it.effect("lowers chronological system updates to wrapped user text in order", () =>
  34. Effect.gen(function* () {
  35. const prepared = yield* LLMClient.prepare<Gemini.GeminiBody>(
  36. LLM.request({
  37. model,
  38. messages: [Message.user("Before."), Message.system("Update."), Message.assistant("After.")],
  39. }),
  40. )
  41. expect(prepared.body.contents).toEqual([
  42. { role: "user", parts: [{ text: "Before." }, { text: "<system-update>\nUpdate.\n</system-update>" }] },
  43. { role: "model", parts: [{ text: "After." }] },
  44. ])
  45. }),
  46. )
  47. it.effect("prepares multimodal user input and tool history", () =>
  48. Effect.gen(function* () {
  49. const prepared = yield* LLMClient.prepare(
  50. LLM.request({
  51. id: "req_tool_result",
  52. model,
  53. tools: [
  54. {
  55. name: "lookup",
  56. description: "Lookup data",
  57. inputSchema: { type: "object", properties: { query: { type: "string" } } },
  58. },
  59. ],
  60. toolChoice: { type: "tool", name: "lookup" },
  61. messages: [
  62. Message.user([
  63. { type: "text", text: "What is in this image?" },
  64. { type: "media", mediaType: "image/png", data: "AAECAw==" },
  65. ]),
  66. Message.assistant([ToolCallPart.make({ id: "call_1", name: "lookup", input: { query: "weather" } })]),
  67. Message.tool({ id: "call_1", name: "lookup", result: { forecast: "sunny" } }),
  68. ],
  69. }),
  70. )
  71. expect(prepared.body).toEqual({
  72. contents: [
  73. {
  74. role: "user",
  75. parts: [{ text: "What is in this image?" }, { inlineData: { mimeType: "image/png", data: "AAECAw==" } }],
  76. },
  77. {
  78. role: "model",
  79. parts: [{ functionCall: { name: "lookup", args: { query: "weather" } } }],
  80. },
  81. {
  82. role: "user",
  83. parts: [
  84. { functionResponse: { name: "lookup", response: { name: "lookup", content: '{"forecast":"sunny"}' } } },
  85. ],
  86. },
  87. ],
  88. tools: [
  89. {
  90. functionDeclarations: [
  91. {
  92. name: "lookup",
  93. description: "Lookup data",
  94. parameters: { type: "object", properties: { query: { type: "string" } } },
  95. },
  96. ],
  97. },
  98. ],
  99. toolConfig: { functionCallingConfig: { mode: "ANY", allowedFunctionNames: ["lookup"] } },
  100. })
  101. }),
  102. )
  103. it.effect("omits tools when tool choice is none", () =>
  104. Effect.gen(function* () {
  105. const prepared = yield* LLMClient.prepare(
  106. LLM.request({
  107. id: "req_no_tools",
  108. model,
  109. prompt: "Say hello.",
  110. tools: [{ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } }],
  111. toolChoice: { type: "none" },
  112. }),
  113. )
  114. expect(prepared.body).toEqual({
  115. contents: [{ role: "user", parts: [{ text: "Say hello." }] }],
  116. })
  117. }),
  118. )
  119. it.effect("sanitizes integer enums, dangling required, untyped arrays, and scalar object keys", () =>
  120. Effect.gen(function* () {
  121. const prepared = yield* LLMClient.prepare(
  122. LLM.request({
  123. id: "req_schema_patch",
  124. model,
  125. prompt: "Use the tool.",
  126. tools: [
  127. {
  128. name: "lookup",
  129. description: "Lookup data",
  130. inputSchema: {
  131. type: "object",
  132. required: ["status", "missing"],
  133. properties: {
  134. status: { type: "integer", enum: [1, 2] },
  135. tags: { type: "array" },
  136. name: { type: "string", properties: { ignored: { type: "string" } }, required: ["ignored"] },
  137. },
  138. },
  139. },
  140. ],
  141. }),
  142. )
  143. expect(prepared.body).toMatchObject({
  144. tools: [
  145. {
  146. functionDeclarations: [
  147. {
  148. parameters: {
  149. type: "object",
  150. required: ["status"],
  151. properties: {
  152. status: { type: "string", enum: ["1", "2"] },
  153. tags: { type: "array", items: { type: "string" } },
  154. name: { type: "string" },
  155. },
  156. },
  157. },
  158. ],
  159. },
  160. ],
  161. })
  162. }),
  163. )
  164. it.effect("parses text, reasoning, and usage stream fixtures", () =>
  165. Effect.gen(function* () {
  166. const body = sseEvents(
  167. {
  168. candidates: [
  169. {
  170. content: { role: "model", parts: [{ text: "thinking", thought: true }] },
  171. },
  172. ],
  173. },
  174. {
  175. candidates: [
  176. {
  177. content: { role: "model", parts: [{ text: "Hello" }] },
  178. },
  179. ],
  180. },
  181. {
  182. candidates: [
  183. {
  184. content: { role: "model", parts: [{ text: "!" }] },
  185. finishReason: "STOP",
  186. },
  187. ],
  188. },
  189. {
  190. usageMetadata: {
  191. promptTokenCount: 5,
  192. candidatesTokenCount: 2,
  193. totalTokenCount: 7,
  194. thoughtsTokenCount: 1,
  195. cachedContentTokenCount: 1,
  196. },
  197. },
  198. )
  199. const response = yield* LLMClient.generate(request).pipe(Effect.provide(fixedResponse(body)))
  200. expect(response.text).toBe("Hello!")
  201. expect(response.reasoning).toBe("thinking")
  202. expect(response.usage).toMatchObject({
  203. inputTokens: 5,
  204. outputTokens: 3,
  205. nonCachedInputTokens: 4,
  206. cacheReadInputTokens: 1,
  207. reasoningTokens: 1,
  208. totalTokens: 7,
  209. })
  210. const usage = new Usage({
  211. inputTokens: 5,
  212. outputTokens: 3,
  213. nonCachedInputTokens: 4,
  214. cacheReadInputTokens: 1,
  215. reasoningTokens: 1,
  216. totalTokens: 7,
  217. providerMetadata: {
  218. google: {
  219. promptTokenCount: 5,
  220. candidatesTokenCount: 2,
  221. totalTokenCount: 7,
  222. thoughtsTokenCount: 1,
  223. cachedContentTokenCount: 1,
  224. },
  225. },
  226. })
  227. expect(response.events).toEqual([
  228. { type: "step-start", index: 0 },
  229. { type: "reasoning-start", id: "reasoning-0" },
  230. { type: "reasoning-delta", id: "reasoning-0", text: "thinking" },
  231. { type: "text-start", id: "text-0" },
  232. { type: "text-delta", id: "text-0", text: "Hello" },
  233. { type: "text-delta", id: "text-0", text: "!" },
  234. { type: "reasoning-end", id: "reasoning-0" },
  235. { type: "text-end", id: "text-0" },
  236. { type: "step-finish", index: 0, reason: "stop", usage, providerMetadata: undefined },
  237. {
  238. type: "finish",
  239. reason: "stop",
  240. usage,
  241. },
  242. ])
  243. }),
  244. )
  245. it.effect("preserves thoughtSignature for reasoning and tool-call continuation", () =>
  246. Effect.gen(function* () {
  247. const body = sseEvents({
  248. candidates: [
  249. {
  250. content: {
  251. role: "model",
  252. parts: [
  253. { text: "thinking", thought: true },
  254. { text: "", thought: true, thoughtSignature: "thought_sig" },
  255. { functionCall: { name: "lookup", args: { query: "weather" } }, thoughtSignature: "tool_sig" },
  256. ],
  257. },
  258. finishReason: "STOP",
  259. },
  260. ],
  261. })
  262. const response = yield* LLMClient.generate(
  263. LLM.updateRequest(request, {
  264. tools: [{ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } }],
  265. }),
  266. ).pipe(Effect.provide(fixedResponse(body)))
  267. const reasoning = response.events.find((event) => event.type === "reasoning-start")
  268. const reasoningEnd = response.events.find((event) => event.type === "reasoning-end")
  269. const toolCall = response.events.find((event) => event.type === "tool-call")
  270. expect(reasoning).toEqual({
  271. type: "reasoning-start",
  272. id: "reasoning-0",
  273. providerMetadata: undefined,
  274. })
  275. expect(reasoningEnd).toEqual({
  276. type: "reasoning-end",
  277. id: "reasoning-0",
  278. providerMetadata: { google: { thoughtSignature: "thought_sig" } },
  279. })
  280. expect(toolCall).toMatchObject({ providerMetadata: { google: { thoughtSignature: "tool_sig" } } })
  281. const prepared = yield* LLMClient.prepare<Gemini.GeminiBody>(
  282. LLM.request({
  283. model,
  284. messages: [
  285. Message.assistant([
  286. { type: "reasoning", text: "thinking", providerMetadata: reasoningEnd?.providerMetadata },
  287. ToolCallPart.make({
  288. id: "tool_0",
  289. name: "lookup",
  290. input: { query: "weather" },
  291. providerMetadata: toolCall?.providerMetadata,
  292. }),
  293. ]),
  294. ],
  295. }),
  296. )
  297. expect(prepared.body.contents).toEqual([
  298. {
  299. role: "model",
  300. parts: [
  301. { text: "thinking", thought: true, thoughtSignature: "thought_sig" },
  302. { functionCall: { name: "lookup", args: { query: "weather" } }, thoughtSignature: "tool_sig" },
  303. ],
  304. },
  305. ])
  306. }),
  307. )
  308. it.effect("emits streamed tool calls and maps finish reason", () =>
  309. Effect.gen(function* () {
  310. const body = sseEvents({
  311. candidates: [
  312. {
  313. content: {
  314. role: "model",
  315. parts: [{ functionCall: { name: "lookup", args: { query: "weather" } } }],
  316. },
  317. finishReason: "STOP",
  318. },
  319. ],
  320. usageMetadata: { promptTokenCount: 5, candidatesTokenCount: 1 },
  321. })
  322. const response = yield* LLMClient.generate(
  323. LLM.updateRequest(request, {
  324. tools: [{ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } }],
  325. }),
  326. ).pipe(Effect.provide(fixedResponse(body)))
  327. const usage = new Usage({
  328. inputTokens: 5,
  329. outputTokens: 1,
  330. nonCachedInputTokens: 5,
  331. cacheReadInputTokens: undefined,
  332. reasoningTokens: undefined,
  333. totalTokens: 6,
  334. providerMetadata: { google: { promptTokenCount: 5, candidatesTokenCount: 1 } },
  335. })
  336. expect(response.toolCalls).toEqual([
  337. {
  338. type: "tool-call",
  339. id: "tool_0",
  340. name: "lookup",
  341. input: { query: "weather" },
  342. providerExecuted: undefined,
  343. providerMetadata: undefined,
  344. },
  345. ])
  346. expect(response.events).toEqual([
  347. { type: "step-start", index: 0 },
  348. {
  349. type: "tool-call",
  350. id: "tool_0",
  351. name: "lookup",
  352. input: { query: "weather" },
  353. providerExecuted: undefined,
  354. providerMetadata: undefined,
  355. },
  356. { type: "step-finish", index: 0, reason: "tool-calls", usage, providerMetadata: undefined },
  357. {
  358. type: "finish",
  359. reason: "tool-calls",
  360. usage,
  361. },
  362. ])
  363. }),
  364. )
  365. it.effect("assigns unique ids to multiple streamed tool calls", () =>
  366. Effect.gen(function* () {
  367. const body = sseEvents({
  368. candidates: [
  369. {
  370. content: {
  371. role: "model",
  372. parts: [
  373. { functionCall: { name: "lookup", args: { query: "weather" } } },
  374. { functionCall: { name: "lookup", args: { query: "news" } } },
  375. ],
  376. },
  377. finishReason: "STOP",
  378. },
  379. ],
  380. })
  381. const response = yield* LLMClient.generate(
  382. LLM.updateRequest(request, {
  383. tools: [{ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } }],
  384. }),
  385. ).pipe(Effect.provide(fixedResponse(body)))
  386. expect(response.toolCalls).toEqual([
  387. { type: "tool-call", id: "tool_0", name: "lookup", input: { query: "weather" } },
  388. { type: "tool-call", id: "tool_1", name: "lookup", input: { query: "news" } },
  389. ])
  390. expect(response.events.at(-1)).toMatchObject({ type: "finish", reason: "tool-calls" })
  391. }),
  392. )
  393. it.effect("maps length and content-filter finish reasons", () =>
  394. Effect.gen(function* () {
  395. const length = yield* LLMClient.generate(request).pipe(
  396. Effect.provide(
  397. fixedResponse(
  398. sseEvents({ candidates: [{ content: { role: "model", parts: [] }, finishReason: "MAX_TOKENS" }] }),
  399. ),
  400. ),
  401. )
  402. const filtered = yield* LLMClient.generate(request).pipe(
  403. Effect.provide(
  404. fixedResponse(sseEvents({ candidates: [{ content: { role: "model", parts: [] }, finishReason: "SAFETY" }] })),
  405. ),
  406. )
  407. expect(length.events.map((event) => event.type)).toEqual(["step-start", "step-finish", "finish"])
  408. expect(length.events.at(-1)).toMatchObject({ type: "finish", reason: "length" })
  409. expect(filtered.events.map((event) => event.type)).toEqual(["step-start", "step-finish", "finish"])
  410. expect(filtered.events.at(-1)).toMatchObject({ type: "finish", reason: "content-filter" })
  411. }),
  412. )
  413. it.effect("leaves total usage undefined when component counts are missing", () =>
  414. Effect.gen(function* () {
  415. const response = yield* LLMClient.generate(request).pipe(
  416. Effect.provide(fixedResponse(sseEvents({ usageMetadata: { thoughtsTokenCount: 1 } }))),
  417. )
  418. expect(response.usage).toMatchObject({ reasoningTokens: 1 })
  419. expect(response.usage?.totalTokens).toBeUndefined()
  420. }),
  421. )
  422. it.effect("fails invalid stream events", () =>
  423. Effect.gen(function* () {
  424. const error = yield* LLMClient.generate(request).pipe(
  425. Effect.provide(fixedResponse(sseRaw("data: {not json}"))),
  426. Effect.flip,
  427. )
  428. expect(error).toBeInstanceOf(LLMError)
  429. expect(error.reason).toMatchObject({ _tag: "InvalidProviderOutput" })
  430. expect(error.message).toContain("Invalid google/gemini stream event")
  431. }),
  432. )
  433. it.effect("rejects unsupported assistant media content", () =>
  434. Effect.gen(function* () {
  435. const error = yield* LLMClient.prepare(
  436. LLM.request({
  437. id: "req_media",
  438. model,
  439. messages: [Message.assistant({ type: "media", mediaType: "image/png", data: "AAECAw==" })],
  440. }),
  441. ).pipe(Effect.flip)
  442. expect(error.message).toContain(
  443. "Gemini assistant messages only support text, reasoning, and tool-call content for now",
  444. )
  445. }),
  446. )
  447. })