gemini.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. import { Effect, Schema } from "effect"
  2. import { Route } from "../route/client"
  3. import { Auth } from "../route/auth"
  4. import { Endpoint } from "../route/endpoint"
  5. import { Framing } from "../route/framing"
  6. import { Protocol } from "../route/protocol"
  7. import {
  8. LLMEvent,
  9. Usage,
  10. type FinishReason,
  11. type LLMRequest,
  12. type MediaPart,
  13. type TextPart,
  14. type ToolCallPart,
  15. type ToolDefinition,
  16. } from "../schema"
  17. import { JsonObject, optionalArray, ProviderShared } from "./shared"
  18. import { GeminiToolSchema } from "./utils/gemini-tool-schema"
  19. import { Lifecycle } from "./utils/lifecycle"
  20. const ADAPTER = "gemini"
  21. export const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta"
  22. // =============================================================================
  23. // Request Body Schema
  24. // =============================================================================
  25. const GeminiTextPart = Schema.Struct({
  26. text: Schema.String,
  27. thought: Schema.optional(Schema.Boolean),
  28. thoughtSignature: Schema.optional(Schema.String),
  29. })
  30. const GeminiInlineDataPart = Schema.Struct({
  31. inlineData: Schema.Struct({
  32. mimeType: Schema.String,
  33. data: Schema.String,
  34. }),
  35. })
  36. const GeminiFunctionCallPart = Schema.Struct({
  37. functionCall: Schema.Struct({
  38. name: Schema.String,
  39. args: Schema.Unknown,
  40. }),
  41. thoughtSignature: Schema.optional(Schema.String),
  42. })
  43. const GeminiFunctionResponsePart = Schema.Struct({
  44. functionResponse: Schema.Struct({
  45. name: Schema.String,
  46. response: Schema.Unknown,
  47. }),
  48. })
  49. const GeminiContentPart = Schema.Union([
  50. GeminiTextPart,
  51. GeminiInlineDataPart,
  52. GeminiFunctionCallPart,
  53. GeminiFunctionResponsePart,
  54. ])
  55. const GeminiContent = Schema.Struct({
  56. role: Schema.Literals(["user", "model"]),
  57. parts: Schema.Array(GeminiContentPart),
  58. })
  59. type GeminiContent = Schema.Schema.Type<typeof GeminiContent>
  60. const GeminiSystemInstruction = Schema.Struct({
  61. parts: Schema.Array(Schema.Struct({ text: Schema.String })),
  62. })
  63. const GeminiFunctionDeclaration = Schema.Struct({
  64. name: Schema.String,
  65. description: Schema.String,
  66. parameters: Schema.optional(JsonObject),
  67. })
  68. const GeminiTool = Schema.Struct({
  69. functionDeclarations: Schema.Array(GeminiFunctionDeclaration),
  70. })
  71. const GeminiToolConfig = Schema.Struct({
  72. functionCallingConfig: Schema.Struct({
  73. mode: Schema.Literals(["AUTO", "NONE", "ANY"]),
  74. allowedFunctionNames: optionalArray(Schema.String),
  75. }),
  76. })
  77. const GeminiThinkingConfig = Schema.Struct({
  78. thinkingBudget: Schema.optional(Schema.Number),
  79. includeThoughts: Schema.optional(Schema.Boolean),
  80. })
  81. const GeminiGenerationConfig = Schema.Struct({
  82. maxOutputTokens: Schema.optional(Schema.Number),
  83. temperature: Schema.optional(Schema.Number),
  84. topP: Schema.optional(Schema.Number),
  85. topK: Schema.optional(Schema.Number),
  86. stopSequences: optionalArray(Schema.String),
  87. thinkingConfig: Schema.optional(GeminiThinkingConfig),
  88. })
  89. const GeminiBodyFields = {
  90. contents: Schema.Array(GeminiContent),
  91. systemInstruction: Schema.optional(GeminiSystemInstruction),
  92. tools: optionalArray(GeminiTool),
  93. toolConfig: Schema.optional(GeminiToolConfig),
  94. generationConfig: Schema.optional(GeminiGenerationConfig),
  95. }
  96. const GeminiBody = Schema.Struct(GeminiBodyFields)
  97. export type GeminiBody = Schema.Schema.Type<typeof GeminiBody>
  98. const GeminiUsage = Schema.Struct({
  99. cachedContentTokenCount: Schema.optional(Schema.Number),
  100. thoughtsTokenCount: Schema.optional(Schema.Number),
  101. promptTokenCount: Schema.optional(Schema.Number),
  102. candidatesTokenCount: Schema.optional(Schema.Number),
  103. totalTokenCount: Schema.optional(Schema.Number),
  104. })
  105. type GeminiUsage = Schema.Schema.Type<typeof GeminiUsage>
  106. const GeminiCandidate = Schema.Struct({
  107. content: Schema.optional(GeminiContent),
  108. finishReason: Schema.optional(Schema.String),
  109. })
  110. const GeminiEvent = Schema.Struct({
  111. candidates: optionalArray(GeminiCandidate),
  112. usageMetadata: Schema.optional(GeminiUsage),
  113. })
  114. type GeminiEvent = Schema.Schema.Type<typeof GeminiEvent>
  115. interface ParserState {
  116. readonly finishReason?: string
  117. readonly hasToolCalls: boolean
  118. readonly nextToolCallId: number
  119. readonly usage?: Usage
  120. readonly lifecycle: Lifecycle.State
  121. }
  122. const mediaData = ProviderShared.mediaBytes
  123. // =============================================================================
  124. // Tool Schema Conversion
  125. // =============================================================================
  126. // Tool-schema conversion has two distinct concerns:
  127. //
  128. // 1. Sanitize — fix common authoring mistakes Gemini rejects: integer/number
  129. // enums (must be strings), `required` entries that don't match a property,
  130. // untyped arrays (`items` must be present), and `properties`/`required`
  131. // keys on non-object scalars. Mirrors OpenCode's historical Gemini rules.
  132. //
  133. // 2. Project — lossy mapping from JSON Schema to Gemini's schema dialect:
  134. // drop empty objects, derive `nullable: true` from `type: [..., "null"]`,
  135. // coerce `const` to `[const]` enum, recurse properties/items, propagate
  136. // only an allowlisted set of keys (description, required, format, type,
  137. // properties, items, allOf, anyOf, oneOf, minLength). Anything outside the
  138. // allowlist (e.g. `additionalProperties`, `$ref`) is silently dropped.
  139. //
  140. // Sanitize runs first, then project. The implementation lives in
  141. // `utils/gemini-tool-schema` so this protocol keeps the same shape as the other
  142. // provider protocols.
  143. // =============================================================================
  144. // Request Lowering
  145. // =============================================================================
  146. const lowerTool = (tool: ToolDefinition) => ({
  147. name: tool.name,
  148. description: tool.description,
  149. parameters: GeminiToolSchema.convert(tool.inputSchema),
  150. })
  151. const lowerToolConfig = (toolChoice: NonNullable<LLMRequest["toolChoice"]>) =>
  152. ProviderShared.matchToolChoice("Gemini", toolChoice, {
  153. auto: () => ({ functionCallingConfig: { mode: "AUTO" as const } }),
  154. none: () => ({ functionCallingConfig: { mode: "NONE" as const } }),
  155. required: () => ({ functionCallingConfig: { mode: "ANY" as const } }),
  156. tool: (name) => ({ functionCallingConfig: { mode: "ANY" as const, allowedFunctionNames: [name] } }),
  157. })
  158. const lowerUserPart = (part: TextPart | MediaPart) =>
  159. part.type === "text" ? { text: part.text } : { inlineData: { mimeType: part.mediaType, data: mediaData(part) } }
  160. const lowerToolCall = (part: ToolCallPart) => ({
  161. functionCall: { name: part.name, args: part.input },
  162. })
  163. const lowerMessages = Effect.fn("Gemini.lowerMessages")(function* (request: LLMRequest) {
  164. const contents: GeminiContent[] = []
  165. for (const message of request.messages) {
  166. if (message.role === "user") {
  167. const parts: Array<Schema.Schema.Type<typeof GeminiContentPart>> = []
  168. for (const part of message.content) {
  169. if (!ProviderShared.supportsContent(part, ["text", "media"]))
  170. return yield* ProviderShared.unsupportedContent("Gemini", "user", ["text", "media"])
  171. parts.push(lowerUserPart(part))
  172. }
  173. contents.push({ role: "user", parts })
  174. continue
  175. }
  176. if (message.role === "assistant") {
  177. const parts: Array<Schema.Schema.Type<typeof GeminiContentPart>> = []
  178. for (const part of message.content) {
  179. if (!ProviderShared.supportsContent(part, ["text", "reasoning", "tool-call"]))
  180. return yield* ProviderShared.unsupportedContent("Gemini", "assistant", ["text", "reasoning", "tool-call"])
  181. if (part.type === "text") {
  182. parts.push({ text: part.text })
  183. continue
  184. }
  185. if (part.type === "reasoning") {
  186. parts.push({ text: part.text, thought: true })
  187. continue
  188. }
  189. if (part.type === "tool-call") {
  190. parts.push(lowerToolCall(part))
  191. continue
  192. }
  193. }
  194. contents.push({ role: "model", parts })
  195. continue
  196. }
  197. const parts: Array<Schema.Schema.Type<typeof GeminiContentPart>> = []
  198. for (const part of message.content) {
  199. if (!ProviderShared.supportsContent(part, ["tool-result"]))
  200. return yield* ProviderShared.unsupportedContent("Gemini", "tool", ["tool-result"])
  201. parts.push({
  202. functionResponse: {
  203. name: part.name,
  204. response: {
  205. name: part.name,
  206. content: ProviderShared.toolResultText(part),
  207. },
  208. },
  209. })
  210. }
  211. contents.push({ role: "user", parts })
  212. }
  213. return contents
  214. })
  215. const geminiOptions = (request: LLMRequest) => request.providerOptions?.gemini
  216. const thinkingConfig = (request: LLMRequest) => {
  217. const value = geminiOptions(request)?.thinkingConfig
  218. if (!ProviderShared.isRecord(value)) return undefined
  219. const result = {
  220. thinkingBudget: typeof value.thinkingBudget === "number" ? value.thinkingBudget : undefined,
  221. includeThoughts: typeof value.includeThoughts === "boolean" ? value.includeThoughts : undefined,
  222. }
  223. return Object.values(result).some((item) => item !== undefined) ? result : undefined
  224. }
  225. const fromRequest = Effect.fn("Gemini.fromRequest")(function* (request: LLMRequest) {
  226. const toolsEnabled = request.tools.length > 0 && request.toolChoice?.type !== "none"
  227. const generation = request.generation
  228. const generationConfig = {
  229. maxOutputTokens: generation?.maxTokens,
  230. temperature: generation?.temperature,
  231. topP: generation?.topP,
  232. topK: generation?.topK,
  233. stopSequences: generation?.stop,
  234. thinkingConfig: thinkingConfig(request),
  235. }
  236. return {
  237. contents: yield* lowerMessages(request),
  238. systemInstruction:
  239. request.system.length === 0 ? undefined : { parts: [{ text: ProviderShared.joinText(request.system) }] },
  240. tools: toolsEnabled ? [{ functionDeclarations: request.tools.map(lowerTool) }] : undefined,
  241. toolConfig: toolsEnabled && request.toolChoice ? yield* lowerToolConfig(request.toolChoice) : undefined,
  242. generationConfig: Object.values(generationConfig).some((value) => value !== undefined)
  243. ? generationConfig
  244. : undefined,
  245. }
  246. })
  247. // =============================================================================
  248. // Stream Parsing
  249. // =============================================================================
  250. // Gemini reports `promptTokenCount` (inclusive total) with a
  251. // `cachedContentTokenCount` subset. `candidatesTokenCount` is *exclusive*
  252. // of `thoughtsTokenCount` — visible-only, not a total — so we sum the two
  253. // to produce the inclusive `outputTokens` the rest of the contract expects.
  254. const mapUsage = (usage: GeminiUsage | undefined) => {
  255. if (!usage) return undefined
  256. const cached = usage.cachedContentTokenCount
  257. const nonCached = ProviderShared.subtractTokens(usage.promptTokenCount, cached)
  258. // `candidatesTokenCount` is visible-only; sum with thoughts to produce the
  259. // inclusive `outputTokens` the contract expects. Only compute the total
  260. // when the visible component is reported — otherwise we'd fabricate an
  261. // inclusive number from a partial breakdown.
  262. const outputTokens =
  263. usage.candidatesTokenCount !== undefined ? usage.candidatesTokenCount + (usage.thoughtsTokenCount ?? 0) : undefined
  264. return new Usage({
  265. inputTokens: usage.promptTokenCount,
  266. outputTokens,
  267. nonCachedInputTokens: nonCached,
  268. cacheReadInputTokens: cached,
  269. reasoningTokens: usage.thoughtsTokenCount,
  270. totalTokens: ProviderShared.totalTokens(usage.promptTokenCount, outputTokens, usage.totalTokenCount),
  271. providerMetadata: { google: usage },
  272. })
  273. }
  274. const mapFinishReason = (finishReason: string | undefined, hasToolCalls: boolean): FinishReason => {
  275. if (finishReason === "STOP") return hasToolCalls ? "tool-calls" : "stop"
  276. if (finishReason === "MAX_TOKENS") return "length"
  277. if (
  278. finishReason === "IMAGE_SAFETY" ||
  279. finishReason === "RECITATION" ||
  280. finishReason === "SAFETY" ||
  281. finishReason === "BLOCKLIST" ||
  282. finishReason === "PROHIBITED_CONTENT" ||
  283. finishReason === "SPII"
  284. )
  285. return "content-filter"
  286. if (finishReason === "MALFORMED_FUNCTION_CALL") return "error"
  287. return "unknown"
  288. }
  289. const finish = (state: ParserState): ReadonlyArray<LLMEvent> =>
  290. state.finishReason || state.usage
  291. ? (() => {
  292. const events: LLMEvent[] = []
  293. Lifecycle.finish(state.lifecycle, events, {
  294. reason: mapFinishReason(state.finishReason, state.hasToolCalls),
  295. usage: state.usage,
  296. })
  297. return events
  298. })()
  299. : []
  300. const step = (state: ParserState, event: GeminiEvent) => {
  301. const nextState = {
  302. ...state,
  303. usage: event.usageMetadata ? (mapUsage(event.usageMetadata) ?? state.usage) : state.usage,
  304. }
  305. const candidate = event.candidates?.[0]
  306. if (!candidate?.content)
  307. return Effect.succeed([
  308. { ...nextState, finishReason: candidate?.finishReason ?? nextState.finishReason },
  309. [],
  310. ] as const)
  311. const events: LLMEvent[] = []
  312. let hasToolCalls = nextState.hasToolCalls
  313. let lifecycle = nextState.lifecycle
  314. let nextToolCallId = nextState.nextToolCallId
  315. for (const part of candidate.content.parts) {
  316. if ("text" in part && part.text.length > 0) {
  317. lifecycle = part.thought
  318. ? Lifecycle.reasoningDelta(lifecycle, events, "reasoning-0", part.text)
  319. : Lifecycle.textDelta(lifecycle, events, "text-0", part.text)
  320. continue
  321. }
  322. if ("functionCall" in part) {
  323. const input = part.functionCall.args
  324. const id = `tool_${nextToolCallId++}`
  325. lifecycle = Lifecycle.stepStart(lifecycle, events)
  326. events.push(LLMEvent.toolCall({ id, name: part.functionCall.name, input }))
  327. hasToolCalls = true
  328. }
  329. }
  330. return Effect.succeed([
  331. {
  332. ...nextState,
  333. hasToolCalls,
  334. lifecycle,
  335. nextToolCallId,
  336. finishReason: candidate.finishReason ?? nextState.finishReason,
  337. },
  338. events,
  339. ] as const)
  340. }
  341. // =============================================================================
  342. // Protocol And Gemini Route
  343. // =============================================================================
  344. /**
  345. * The Gemini protocol — request body construction, body schema, and the
  346. * streaming-event state machine. Used by Google AI Studio Gemini and (once
  347. * registered) Vertex Gemini.
  348. */
  349. export const protocol = Protocol.make({
  350. id: ADAPTER,
  351. body: {
  352. schema: GeminiBody,
  353. from: fromRequest,
  354. },
  355. stream: {
  356. event: Protocol.jsonEvent(GeminiEvent),
  357. initial: () => ({ hasToolCalls: false, nextToolCallId: 0, lifecycle: Lifecycle.initial() }),
  358. step,
  359. onHalt: finish,
  360. },
  361. })
  362. export const route = Route.make({
  363. id: ADAPTER,
  364. protocol,
  365. // Gemini's path embeds the model id and pins SSE framing at the URL level.
  366. endpoint: Endpoint.path(({ request }) => `/models/${request.model.id}:streamGenerateContent?alt=sse`),
  367. auth: Auth.apiKeyHeader("x-goog-api-key"),
  368. framing: Framing.sse,
  369. })
  370. // =============================================================================
  371. // Model Helper
  372. // =============================================================================
  373. export const model = Route.model(route, {
  374. provider: "google",
  375. baseURL: DEFAULT_BASE_URL,
  376. })
  377. export * as Gemini from "./gemini"