@effect-uai/google 0.18.0 → 0.19.0-dev-20261110065930
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/codec.d.mts +28 -7
- package/dist/codec.d.mts.map +1 -1
- package/dist/codec.mjs +52 -10
- package/dist/codec.mjs.map +1 -1
- package/dist/codec.test.d.mts +1 -0
- package/dist/codec.test.mjs +61 -0
- package/dist/codec.test.mjs.map +1 -0
- package/dist/geminiTools.test.mjs +1 -0
- package/dist/geminiTools.test.mjs.map +1 -1
- package/dist/realtimeSession.mjs +2 -2
- package/dist/realtimeSession.mjs.map +1 -1
- package/dist/realtimeSession.test.mjs +67 -36
- package/dist/realtimeSession.test.mjs.map +1 -1
- package/package.json +4 -4
- package/src/codec.test.ts +54 -0
- package/src/codec.ts +90 -21
- package/src/geminiTools.test.ts +1 -0
- package/src/realtimeSession.test.ts +5 -5
- package/src/realtimeSession.ts +2 -2
package/README.md
CHANGED
package/dist/codec.d.mts
CHANGED
|
@@ -4,9 +4,9 @@ import { CommonRequest } from "@effect-uai/core/LanguageModel";
|
|
|
4
4
|
import { ToolDescriptor } from "@effect-uai/core/Tool";
|
|
5
5
|
import { Turn } from "@effect-uai/core/Turn";
|
|
6
6
|
import { ImageSource } from "@effect-uai/core/Image";
|
|
7
|
-
import { Annotation, HistoryItem } from "@effect-uai/core/Items";
|
|
7
|
+
import { Annotation, HistoryItem, ToolCallOutput } from "@effect-uai/core/Items";
|
|
8
8
|
declare namespace codec_d_exports {
|
|
9
|
-
export { AccumulatedFunctionCall, Accumulator, ChunkPart, ChunkResult, GenerationConfig, GroundingMetadata, ImageConfig, RequestBody, RequestTool, ThinkingConfig, WireChunk, accumulatorToTurn, buildRequestBody, emptyAccumulator, groundingToAnnotations, hasUrlImageSource, httpStatusError, ingestChunk,
|
|
9
|
+
export { AccumulatedFunctionCall, Accumulator, ChunkPart, ChunkResult, FunctionResponseBody, GenerationConfig, GroundingMetadata, ImageConfig, RequestBody, RequestTool, ThinkingConfig, WireChunk, accumulatorToTurn, buildRequestBody, emptyAccumulator, functionResponseBody, groundingToAnnotations, hasUrlImageSource, httpStatusError, ingestChunk, toolDescriptorsToTools, transportFailure };
|
|
10
10
|
}
|
|
11
11
|
declare const GroundingMetadata: Schema.Struct<{
|
|
12
12
|
readonly groundingChunks: Schema.optional<Schema.NullOr<Schema.$Array<Schema.Struct<{
|
|
@@ -80,10 +80,9 @@ type RequestPart = {
|
|
|
80
80
|
};
|
|
81
81
|
readonly thoughtSignature?: string;
|
|
82
82
|
} | {
|
|
83
|
-
readonly functionResponse: {
|
|
83
|
+
readonly functionResponse: FunctionResponseBody & {
|
|
84
84
|
readonly id?: string;
|
|
85
85
|
readonly name: string;
|
|
86
|
-
readonly response: Record<string, unknown>;
|
|
87
86
|
};
|
|
88
87
|
};
|
|
89
88
|
type RequestContent = {
|
|
@@ -148,8 +147,30 @@ type RequestBody = {
|
|
|
148
147
|
readonly tools?: ReadonlyArray<RequestTool>;
|
|
149
148
|
readonly toolConfig?: RequestToolConfig;
|
|
150
149
|
};
|
|
151
|
-
|
|
152
|
-
|
|
150
|
+
type MediaPart = {
|
|
151
|
+
readonly inlineData: {
|
|
152
|
+
readonly mimeType: string;
|
|
153
|
+
readonly data: string;
|
|
154
|
+
readonly displayName?: string;
|
|
155
|
+
};
|
|
156
|
+
} | {
|
|
157
|
+
readonly fileData: {
|
|
158
|
+
readonly fileUri: string;
|
|
159
|
+
readonly mimeType?: string;
|
|
160
|
+
readonly displayName?: string;
|
|
161
|
+
};
|
|
162
|
+
};
|
|
163
|
+
/** Gemini's `functionResponse` body for a tool output, without `id` / `name`. */
|
|
164
|
+
type FunctionResponseBody = {
|
|
165
|
+
readonly response: Record<string, unknown>;
|
|
166
|
+
readonly parts?: ReadonlyArray<MediaPart>;
|
|
167
|
+
};
|
|
168
|
+
/**
|
|
169
|
+
* Text and JSON go into `response.output` (or `response.error` when the call
|
|
170
|
+
* failed) as values, never stringified: one value as itself, several as an
|
|
171
|
+
* array. Media goes into `parts`.
|
|
172
|
+
*/
|
|
173
|
+
declare const functionResponseBody: (output: ToolCallOutput) => FunctionResponseBody;
|
|
153
174
|
declare const toolDescriptorsToTools: (tools: ReadonlyArray<ToolDescriptor>) => ReadonlyArray<RequestTool>;
|
|
154
175
|
/** `provider` names the surface that failed, so errors read `gemini` or `lyria`. */
|
|
155
176
|
declare const transportFailure: (provider: string) => (cause: unknown) => AiError.AiError;
|
|
@@ -225,5 +246,5 @@ type ChunkResult = {
|
|
|
225
246
|
declare const ingestChunk: (acc: Accumulator, chunk: WireChunk) => ChunkResult;
|
|
226
247
|
declare const accumulatorToTurn: (acc: Accumulator) => Turn;
|
|
227
248
|
//#endregion
|
|
228
|
-
export { AccumulatedFunctionCall, Accumulator, ChunkPart, ChunkResult, GenerationConfig, GroundingMetadata, ImageConfig, RequestBody, RequestTool, ThinkingConfig, WireChunk, accumulatorToTurn, buildRequestBody, emptyAccumulator, groundingToAnnotations, hasUrlImageSource, httpStatusError, ingestChunk,
|
|
249
|
+
export { AccumulatedFunctionCall, Accumulator, ChunkPart, ChunkResult, FunctionResponseBody, GenerationConfig, GroundingMetadata, ImageConfig, RequestBody, RequestTool, ThinkingConfig, WireChunk, accumulatorToTurn, buildRequestBody, emptyAccumulator, functionResponseBody, groundingToAnnotations, hasUrlImageSource, httpStatusError, ingestChunk, codec_d_exports as t, toolDescriptorsToTools, transportFailure };
|
|
229
250
|
//# sourceMappingURL=codec.d.mts.map
|
package/dist/codec.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codec.d.mts","names":[],"sources":["../src/codec.ts"],"mappings":";;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"codec.d.mts","names":[],"sources":["../src/codec.ts"],"mappings":";;;;;;;;;;cA0Fa,mBAAiB,OAAA;;;;;;;;KAGlB,2BAA2B,kBAAkB;cAU5C,4BAAsB,OACvB,cAAc,0CACvB,cAAc;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AQ;;WAEhC;WACA,IAAI,OAAO;WACX,WAAW,OAAO;WAClB;WACA;;KAGH;WACD,aAAa;WACb,OAAO,cAAc;WACrB;;cA6HE,cAAW,KAAS,aAAW,OAAS,cAAY;cA8DpD,oBAAiB,KAAS,gBAAc"}
|
package/dist/codec.mjs
CHANGED
|
@@ -10,11 +10,11 @@ var codec_exports = /* @__PURE__ */ __exportAll({
|
|
|
10
10
|
accumulatorToTurn: () => accumulatorToTurn,
|
|
11
11
|
buildRequestBody: () => buildRequestBody,
|
|
12
12
|
emptyAccumulator: () => emptyAccumulator,
|
|
13
|
+
functionResponseBody: () => functionResponseBody,
|
|
13
14
|
groundingToAnnotations: () => groundingToAnnotations,
|
|
14
15
|
hasUrlImageSource: () => hasUrlImageSource,
|
|
15
16
|
httpStatusError: () => httpStatusError,
|
|
16
17
|
ingestChunk: () => ingestChunk,
|
|
17
|
-
parsedResponse: () => parsedResponse,
|
|
18
18
|
toolDescriptorsToTools: () => toolDescriptorsToTools,
|
|
19
19
|
transportFailure: () => transportFailure
|
|
20
20
|
});
|
|
@@ -138,13 +138,55 @@ const systemMessageText = (message) => {
|
|
|
138
138
|
const allMessages = (history) => pipe(history, Array$1.filterMap((item) => item.type === "message" ? Result.succeed(item) : Result.failVoid));
|
|
139
139
|
const JsonObject = Schema.Record(Schema.String, Schema.Unknown);
|
|
140
140
|
const decodeJsonObject = Schema.decodeResult(Schema.fromJsonString(JsonObject));
|
|
141
|
-
const
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
141
|
+
const parsedArgs = (encoded) => pipe(decodeJsonObject(encoded), Result.getOrElse(() => ({})));
|
|
142
|
+
const mediaPart = (source, displayName) => {
|
|
143
|
+
const named = displayName === void 0 ? {} : { displayName };
|
|
144
|
+
return Match.value(source).pipe(Match.tagsExhaustive({
|
|
145
|
+
url: (s) => ({ fileData: {
|
|
146
|
+
fileUri: s.url,
|
|
147
|
+
...s.mimeType !== void 0 && { mimeType: s.mimeType },
|
|
148
|
+
...named
|
|
149
|
+
} }),
|
|
150
|
+
base64: (s) => ({ inlineData: {
|
|
151
|
+
mimeType: s.mimeType,
|
|
152
|
+
data: s.base64,
|
|
153
|
+
...named
|
|
154
|
+
} }),
|
|
155
|
+
bytes: (s) => ({ inlineData: {
|
|
156
|
+
mimeType: s.mimeType,
|
|
157
|
+
data: Base64.encode(s.bytes),
|
|
158
|
+
...named
|
|
159
|
+
} })
|
|
160
|
+
}));
|
|
161
|
+
};
|
|
162
|
+
/**
|
|
163
|
+
* Text and JSON go into `response.output` (or `response.error` when the call
|
|
164
|
+
* failed) as values, never stringified: one value as itself, several as an
|
|
165
|
+
* array. Media goes into `parts`.
|
|
166
|
+
*/
|
|
167
|
+
const functionResponseBody = (output) => {
|
|
168
|
+
const values = Array$1.filterMap(output.output, Match.type().pipe(Match.discriminatorsExhaustive("type")({
|
|
169
|
+
input_text: (p) => Result.succeed(p.text),
|
|
170
|
+
input_json: (p) => Result.succeed(p.value),
|
|
171
|
+
input_image: () => Result.failVoid,
|
|
172
|
+
input_file: () => Result.failVoid
|
|
173
|
+
})));
|
|
174
|
+
const media = Array$1.filterMap(output.output, Match.type().pipe(Match.discriminatorsExhaustive("type")({
|
|
175
|
+
input_text: () => Result.failVoid,
|
|
176
|
+
input_json: () => Result.failVoid,
|
|
177
|
+
input_image: (p) => Result.succeed(mediaPart(p.source, void 0)),
|
|
178
|
+
input_file: (p) => Result.succeed(mediaPart(p.source, p.filename))
|
|
179
|
+
})));
|
|
180
|
+
const key = output.isError === true ? "error" : "output";
|
|
181
|
+
const response = Array$1.match(values, {
|
|
182
|
+
onEmpty: () => ({}),
|
|
183
|
+
onNonEmpty: (all) => ({ [key]: all.length === 1 ? Array$1.headNonEmpty(all) : all })
|
|
184
|
+
});
|
|
185
|
+
return media.length === 0 ? { response } : {
|
|
186
|
+
response,
|
|
187
|
+
parts: media
|
|
188
|
+
};
|
|
189
|
+
};
|
|
148
190
|
/**
|
|
149
191
|
* `ToolCallOutput` only carries `call_id`; Gemini's `functionResponse`
|
|
150
192
|
* requires the declared function `name`. Resolve the name by scanning prior
|
|
@@ -198,7 +240,7 @@ const itemToContent = (history) => (item) => Match.value(item).pipe(Match.discri
|
|
|
198
240
|
onNone: () => ({})
|
|
199
241
|
}),
|
|
200
242
|
name: Option.getOrElse(nameForCallId(history, o.call_id), () => o.call_id),
|
|
201
|
-
|
|
243
|
+
...functionResponseBody(o)
|
|
202
244
|
} }]
|
|
203
245
|
}),
|
|
204
246
|
reasoning: () => Result.failVoid
|
|
@@ -412,6 +454,6 @@ const accumulatorToTurn = (acc) => ({
|
|
|
412
454
|
]
|
|
413
455
|
});
|
|
414
456
|
//#endregion
|
|
415
|
-
export { GroundingMetadata, WireChunk, accumulatorToTurn, buildRequestBody, emptyAccumulator, groundingToAnnotations, hasUrlImageSource, httpStatusError, ingestChunk,
|
|
457
|
+
export { GroundingMetadata, WireChunk, accumulatorToTurn, buildRequestBody, emptyAccumulator, functionResponseBody, groundingToAnnotations, hasUrlImageSource, httpStatusError, ingestChunk, codec_exports as t, toolDescriptorsToTools, transportFailure };
|
|
416
458
|
|
|
417
459
|
//# sourceMappingURL=codec.mjs.map
|
package/dist/codec.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codec.mjs","names":["Arr"],"sources":["../src/codec.ts"],"sourcesContent":["import { Array as Arr, Match, Option, Result, Schema, pipe } from \"effect\"\nimport { Base64 } from \"effect/encoding\"\nimport * as AiError from \"@effect-uai/core/AiError\"\nimport type { ImageSource } from \"@effect-uai/core/Image\"\nimport { imageBase64 } from \"@effect-uai/core/Image\"\nimport type {\n ContentBlock,\n ToolCall,\n InputImage,\n HistoryItem,\n Message,\n Annotation,\n} from \"@effect-uai/core/Items\"\nimport type { ToolDescriptor } from \"@effect-uai/core/Tool\"\nimport type { Turn } from \"@effect-uai/core/Turn\"\nimport type { CommonRequest } from \"@effect-uai/core/LanguageModel\"\n\n// ---------------------------------------------------------------------------\n// Wire schemas - the subset of Gemini's streamGenerateContent payload we\n// consume. Reference: https://ai.google.dev/api/generate-content\n// ---------------------------------------------------------------------------\n\nconst TextPart = Schema.Struct({\n text: Schema.String,\n /**\n * Gemini's flag for chain-of-thought parts. When `true`, the part is\n * reasoning trace, not the model's user-facing answer. Maps onto\n * `reasoning_delta { kind: \"trace\" }` in the canonical view.\n */\n thought: Schema.optional(Schema.Boolean),\n})\n\n/**\n * Gemini function-call part. Args are delivered as a whole JSON *object*\n * in a single chunk (Gemini does not stream tool-call args). On Gemini 3\n * the response also carries an `id` per call, which we echo back on the\n * corresponding `functionResponse`.\n */\nconst FunctionCallPart = Schema.Struct({\n functionCall: Schema.Struct({\n id: Schema.optional(Schema.String),\n name: Schema.String,\n args: Schema.optional(Schema.Unknown),\n }),\n // Gemini 3 thinking models attach an opaque signature to each function-call\n // part that must be replayed on the next request, or the call is rejected.\n thoughtSignature: Schema.optional(Schema.String),\n})\n\n/**\n * An image the model drew, as a part of its own turn. Only image models\n * emit these, and only when the request asked for the IMAGE modality.\n * `thought: true` marks an interim image drawn while planning, which is\n * not the answer and is dropped the same way thought text is.\n */\nconst InlineDataPart = Schema.Struct({\n inlineData: Schema.Struct({\n mimeType: Schema.optional(Schema.String),\n data: Schema.String,\n }),\n thought: Schema.optional(Schema.Boolean),\n})\n\nconst Part = Schema.Union([TextPart, FunctionCallPart, InlineDataPart])\ntype WireFunctionCallPart = typeof FunctionCallPart.Type\ntype WireInlineDataPart = typeof InlineDataPart.Type\n\nconst Content = Schema.Struct({\n role: Schema.optional(Schema.String),\n parts: Schema.optional(Schema.Array(Part)),\n})\n\n// Google grounding metadata. On a grounded response the candidate carries\n// `groundingChunks[].web.{uri,title}` - the structured form of the inline `[n]`\n// / trailing `**Sources:**` list the model renders into the answer text.\n// Decoded defensively (every field optional) as it is absent on ungrounded\n// turns. Shared with the Interactions deep-research surface via `codec.ts`.\nconst GroundingChunk = Schema.Struct({\n web: Schema.optional(\n Schema.NullOr(\n Schema.Struct({\n uri: Schema.optional(Schema.NullOr(Schema.String)),\n title: Schema.optional(Schema.NullOr(Schema.String)),\n }),\n ),\n ),\n})\nexport const GroundingMetadata = Schema.Struct({\n groundingChunks: Schema.optional(Schema.NullOr(Schema.Array(GroundingChunk))),\n})\nexport type GroundingMetadata = typeof GroundingMetadata.Type\n\n// Two citations are the same source when they point at the same url.\nconst sameUrlCitation = (a: Annotation, b: Annotation): boolean =>\n a.type === \"url_citation\" && b.type === \"url_citation\" && a.url === b.url\n\n// Grounding chunks → `url_citation` annotations, de-duped by url across every\n// metadata block passed. `web.uri` is a `grounding-api-redirect` URL and\n// `web.title` the bare domain; both are kept as-is (the redirect resolves to\n// the real page).\nexport const groundingToAnnotations = (\n ...metas: ReadonlyArray<GroundingMetadata | null | undefined>\n): ReadonlyArray<Annotation> =>\n pipe(\n metas,\n Arr.flatMap((meta) => meta?.groundingChunks ?? []),\n Arr.filterMap((chunk) =>\n chunk.web?.uri == null\n ? Result.failVoid\n : Result.succeed<Annotation>({\n type: \"url_citation\",\n url: chunk.web.uri,\n title: chunk.web.title ?? chunk.web.uri,\n }),\n ),\n Arr.dedupeWith(sameUrlCitation),\n )\n\nconst Candidate = Schema.Struct({\n content: Schema.optional(Content),\n groundingMetadata: Schema.optional(GroundingMetadata),\n finishReason: Schema.optional(Schema.String),\n index: Schema.optional(Schema.Number),\n})\n\nconst UsageMetadata = Schema.Struct({\n promptTokenCount: Schema.optional(Schema.Number),\n candidatesTokenCount: Schema.optional(Schema.Number),\n totalTokenCount: Schema.optional(Schema.Number),\n cachedContentTokenCount: Schema.optional(Schema.Number),\n thoughtsTokenCount: Schema.optional(Schema.Number),\n})\n\nexport const WireChunk = Schema.Struct({\n candidates: Schema.optional(Schema.Array(Candidate)),\n usageMetadata: Schema.optional(UsageMetadata),\n})\nexport type WireChunk = typeof WireChunk.Type\n\n// ---------------------------------------------------------------------------\n// History → request body\n// ---------------------------------------------------------------------------\n\ntype RequestPart =\n | { readonly text: string }\n | { readonly inlineData: { readonly mimeType: string; readonly data: string } }\n | {\n readonly functionCall: {\n readonly id?: string\n readonly name: string\n readonly args: unknown\n }\n readonly thoughtSignature?: string\n }\n | {\n readonly functionResponse: {\n readonly id?: string\n readonly name: string\n readonly response: Record<string, unknown>\n }\n }\n\ntype RequestContent = {\n readonly role: \"user\" | \"model\"\n readonly parts: ReadonlyArray<RequestPart>\n}\n\ntype RequestSystemInstruction = {\n readonly parts: ReadonlyArray<{ readonly text: string }>\n}\n\n/**\n * Gemini's tool declaration. A `tools[]` entry is either a function-declaration\n * block (translated from `ToolDescriptor`s) or one of the native hosted-tool\n * entries. The native entries are empty objects keyed camelCase per the REST\n * v1beta `Tool` object, and sit as siblings of the declarations in the same\n * `tools` array.\n */\nexport type RequestTool =\n | {\n readonly functionDeclarations: ReadonlyArray<{\n readonly name: string\n readonly description: string\n readonly parameters: Record<string, unknown>\n }>\n }\n | { readonly googleSearch: {} }\n | { readonly urlContext: {} }\n | { readonly codeExecution: {} }\n\ntype RequestToolConfig = {\n readonly functionCallingConfig: {\n readonly mode: \"AUTO\" | \"ANY\" | \"NONE\"\n readonly allowedFunctionNames?: ReadonlyArray<string>\n }\n}\n\nexport type ThinkingConfig = {\n readonly thinkingBudget: number\n}\n\nexport type ImageConfig = {\n readonly aspectRatio?: string\n readonly imageSize?: string\n}\n\nexport type GenerationConfig = {\n readonly temperature?: number\n readonly maxOutputTokens?: number\n readonly topP?: number\n readonly thinkingConfig?: ThinkingConfig\n /** Image models need `[\"TEXT\", \"IMAGE\"]` or they answer in prose only. */\n readonly responseModalities?: ReadonlyArray<\"TEXT\" | \"IMAGE\">\n readonly imageConfig?: ImageConfig\n /** Set together with `responseJsonSchema` to constrain output to JSON. */\n readonly responseMimeType?: string\n /** JSON Schema constraint on the output. */\n readonly responseJsonSchema?: Record<string, unknown>\n}\n\nexport type RequestBody = {\n readonly contents: ReadonlyArray<RequestContent>\n readonly systemInstruction?: RequestSystemInstruction\n readonly generationConfig?: GenerationConfig\n readonly tools?: ReadonlyArray<RequestTool>\n readonly toolConfig?: RequestToolConfig\n}\n\nconst blockText = Match.type<ContentBlock>().pipe(\n Match.discriminatorsExhaustive(\"type\")({\n input_text: (b) => b.text,\n input_image: () => \"\",\n output_text: (b) => b.text,\n output_image: () => \"\",\n refusal: (b) => b.text,\n }),\n)\n\nconst messageText = (message: Message): string => message.content.map(blockText).join(\"\")\n\n/**\n * Gemini's `inlineData` form expects a base64 payload. URL-form images\n * would need to go through Gemini's Files API (upload then `fileData`\n * with the returned URI); pre-uploading isn't free, so we skip those for\n * now and document as a follow-up.\n */\nconst imageSourceToParts = Match.type<InputImage[\"source\"]>().pipe(\n Match.tag(\"url\", (): ReadonlyArray<RequestPart> => []),\n Match.tag(\"base64\", (s): ReadonlyArray<RequestPart> => [\n { inlineData: { mimeType: s.mimeType, data: s.base64 } },\n ]),\n Match.tag(\"bytes\", (s): ReadonlyArray<RequestPart> => [\n { inlineData: { mimeType: s.mimeType, data: Base64.encode(s.bytes) } },\n ]),\n Match.exhaustive,\n)\n\nconst blockToParts = Match.type<ContentBlock>().pipe(\n Match.discriminatorsExhaustive(\"type\")({\n input_text: (b): ReadonlyArray<RequestPart> => (b.text.length === 0 ? [] : [{ text: b.text }]),\n input_image: (b): ReadonlyArray<RequestPart> => imageSourceToParts(b.source),\n output_text: (b): ReadonlyArray<RequestPart> => (b.text.length === 0 ? [] : [{ text: b.text }]),\n // An image the model drew goes back as a model-role `inlineData` part,\n // which is how a multi-turn edit keeps its subject.\n output_image: (b): ReadonlyArray<RequestPart> => imageSourceToParts(b.source),\n // Refusals are assistant-side content; they don't round-trip into Gemini's\n // request body as parts. Skip.\n refusal: (): ReadonlyArray<RequestPart> => [],\n }),\n)\n\nconst messageToContent = (message: Message): Result.Result<RequestContent, void> => {\n const parts = pipe(message.content, Arr.flatMap(blockToParts))\n if (parts.length === 0) return Result.failVoid\n return Match.value(message.role).pipe(\n Match.when(\"user\", () => Result.succeed({ role: \"user\" as const, parts })),\n Match.when(\"assistant\", () => Result.succeed({ role: \"model\" as const, parts })),\n Match.when(\"system\", () => Result.failVoid),\n Match.exhaustive,\n )\n}\n\nconst systemMessageText = (message: Message): Result.Result<string, void> => {\n if (message.role !== \"system\") return Result.failVoid\n const text = messageText(message)\n return text.length === 0 ? Result.failVoid : Result.succeed(text)\n}\n\nconst allMessages = (history: ReadonlyArray<HistoryItem>): ReadonlyArray<Message> =>\n pipe(\n history,\n Arr.filterMap((item) => (item.type === \"message\" ? Result.succeed(item) : Result.failVoid)),\n )\n\n// ---------------------------------------------------------------------------\n// Function-call round-trip\n//\n// `ToolCall.arguments` and `ToolCallOutput.output` are JSON-encoded\n// strings; Gemini's `functionCall.args` and `functionResponse.response`\n// expect parsed JSON *objects*. Decode via Schema:\n// - object payload → use as-is\n// - scalar / array / malformed → wrap as `{ output: <raw string> }` so the\n// model still sees *some* response without crashing the request.\n// ---------------------------------------------------------------------------\n\nconst JsonObject = Schema.Record(Schema.String, Schema.Unknown)\nconst decodeJsonObject = Schema.decodeResult(Schema.fromJsonString(JsonObject))\n\nconst parsedJsonObject =\n (fallback: (raw: string) => Record<string, unknown>) =>\n (encoded: string): Record<string, unknown> =>\n pipe(\n decodeJsonObject(encoded),\n Result.match({\n onSuccess: (v) => v,\n onFailure: () => fallback(encoded),\n }),\n )\n\nconst parsedArgs = parsedJsonObject(() => ({}))\n/** A `ToolCallOutput.output` string as the object `functionResponse` wants. */\nexport const parsedResponse = parsedJsonObject((raw) => ({ output: raw }))\n\n/**\n * `ToolCallOutput` only carries `call_id`; Gemini's `functionResponse`\n * requires the declared function `name`. Resolve the name by scanning prior\n * `function_call` items in the history for a matching `call_id`. If we\n * cannot resolve, fall back to `call_id` as the name - imperfect but\n * preserves stream shape so the model sees *some* response.\n */\nconst isFunctionCallItem = (item: HistoryItem): item is ToolCall => item.type === \"function_call\"\n\nconst nameForCallId = (\n history: ReadonlyArray<HistoryItem>,\n call_id: string,\n): Option.Option<string> =>\n pipe(\n history,\n Arr.findFirst((item): item is ToolCall => isFunctionCallItem(item) && item.call_id === call_id),\n Option.map((f) => f.name),\n )\n\n/**\n * Extract the Gemini-3 wire id and thought signature we stashed in\n * `providerData` on the way out. Schema-driven so the shape lives in one\n * place; failure or absence → `Option.none()`.\n */\nconst ProviderDataGemini = Schema.Struct({\n gemini: Schema.Struct({\n id: Schema.optional(Schema.String),\n thoughtSignature: Schema.optional(Schema.String),\n }),\n})\nconst decodeGemini = Schema.decodeUnknownResult(ProviderDataGemini)\n\nconst geminiField = (\n item: ToolCall,\n pick: (g: {\n readonly id?: string | undefined\n readonly thoughtSignature?: string | undefined\n }) => string | undefined,\n): Option.Option<string> =>\n pipe(\n decodeGemini(item.providerData),\n Result.match({\n onSuccess: (d) => Option.fromNullishOr(pick(d.gemini)),\n onFailure: () => Option.none<string>(),\n }),\n )\n\nconst providerIdFor = (item: ToolCall): Option.Option<string> => geminiField(item, (g) => g.id)\n\n// The originating call's Gemini id, looked up from history by our `call_id`.\n// Gemini 3 maps a `functionResponse` back to its call by this id, so parallel\n// calls to the same function are mis-paired if we drop it.\nconst providerIdForCallId = (\n history: ReadonlyArray<HistoryItem>,\n call_id: string,\n): Option.Option<string> =>\n pipe(\n history,\n Arr.findFirst((item): item is ToolCall => isFunctionCallItem(item) && item.call_id === call_id),\n Option.flatMap(providerIdFor),\n )\n\nconst signatureFor = (item: ToolCall): Option.Option<string> =>\n geminiField(item, (g) => g.thoughtSignature)\n\nconst itemToContent =\n (history: ReadonlyArray<HistoryItem>) =>\n (item: HistoryItem): Result.Result<RequestContent, void> =>\n Match.value(item).pipe(\n Match.discriminatorsExhaustive(\"type\")({\n message: messageToContent,\n function_call: (f) =>\n Result.succeed({\n role: \"model\" as const,\n parts: [\n {\n ...Option.match(signatureFor(f), {\n onSome: (thoughtSignature) => ({ thoughtSignature }),\n onNone: () => ({}),\n }),\n functionCall: {\n ...Option.match(providerIdFor(f), {\n onSome: (id) => ({ id }),\n onNone: () => ({}),\n }),\n name: f.name,\n args: parsedArgs(f.arguments),\n },\n },\n ],\n }),\n function_call_output: (o) =>\n Result.succeed({\n role: \"user\" as const,\n parts: [\n {\n functionResponse: {\n ...Option.match(providerIdForCallId(history, o.call_id), {\n onSome: (id) => ({ id }),\n onNone: () => ({}),\n }),\n name: Option.getOrElse(nameForCallId(history, o.call_id), () => o.call_id),\n response: parsedResponse(o.output),\n },\n },\n ],\n }),\n reasoning: () => Result.failVoid,\n }),\n )\n\n// ---------------------------------------------------------------------------\n// Tool descriptors → Gemini `functionDeclarations`. Gemini accepts only a\n// strict OpenAPI 3.0 subset for `parameters`; strip JSON-Schema keys it\n// rejects (`$schema`, `$ref`, `additionalProperties`, `oneOf`,\n// `definitions`).\n// ---------------------------------------------------------------------------\n\nconst UNSUPPORTED_SCHEMA_KEYS: ReadonlySet<string> = new Set([\n \"$schema\",\n \"$ref\",\n \"$defs\",\n \"definitions\",\n \"additionalProperties\",\n \"oneOf\",\n])\n\nconst sanitizeSchema = (schema: unknown): unknown => {\n if (Array.isArray(schema)) return schema.map(sanitizeSchema)\n if (schema === null || typeof schema !== \"object\") return schema\n return pipe(\n Object.entries(schema as Record<string, unknown>),\n Arr.filterMap(([k, v]) =>\n UNSUPPORTED_SCHEMA_KEYS.has(k)\n ? Result.failVoid\n : Result.succeed([k, sanitizeSchema(v)] as const),\n ),\n Object.fromEntries,\n )\n}\n\nexport const toolDescriptorsToTools = (\n tools: ReadonlyArray<ToolDescriptor>,\n): ReadonlyArray<RequestTool> =>\n tools.length === 0\n ? []\n : [\n {\n functionDeclarations: tools.map((t) => ({\n name: t.name,\n description: t.description,\n parameters: sanitizeSchema(t.inputSchema) as Record<string, unknown>,\n })),\n },\n ]\n\n/**\n * Map our cross-provider `toolChoice` onto Gemini's `functionCallingConfig`.\n * Gemini honours the same three modes plus a function allow-list, so the\n * choice is mapped, not dropped. `undefined` keeps the API default (`AUTO`).\n */\nconst toolChoiceToFunctionCallingConfig = (\n toolChoice: CommonRequest[\"toolChoice\"],\n): RequestToolConfig[\"functionCallingConfig\"] =>\n Match.value(toolChoice ?? \"auto\").pipe(\n Match.when(\"auto\", () => ({ mode: \"AUTO\" as const })),\n Match.when(\"required\", () => ({ mode: \"ANY\" as const })),\n Match.when(\"none\", () => ({ mode: \"NONE\" as const })),\n Match.orElse((tc) => ({ mode: \"ANY\" as const, allowedFunctionNames: [tc.name] })),\n )\n\n// ---------------------------------------------------------------------------\n// HTTP failure mapping, shared by every Google surface\n// ---------------------------------------------------------------------------\n\n/** `provider` names the surface that failed, so errors read `gemini` or `lyria`. */\nexport const transportFailure =\n (provider: string) =>\n (cause: unknown): AiError.AiError =>\n new AiError.Unavailable({ provider, raw: cause })\n\n/** 413 is the inline-payload cap, which is a context limit on every surface. */\nexport const httpStatusError =\n (provider: string) =>\n (status: number, body: string): AiError.AiError =>\n Match.value(status).pipe(\n Match.when(429, (): AiError.AiError => new AiError.RateLimited({ provider, raw: body })),\n Match.whenOr(408, 504, (): AiError.AiError => new AiError.Timeout({ provider, raw: body })),\n Match.when(\n 401,\n (): AiError.AiError => new AiError.AuthFailed({ provider, subtype: \"auth\", raw: body }),\n ),\n Match.when(\n 403,\n (): AiError.AiError =>\n new AiError.AuthFailed({ provider, subtype: \"permission\", raw: body }),\n ),\n Match.when(\n 402,\n (): AiError.AiError => new AiError.AuthFailed({ provider, subtype: \"billing\", raw: body }),\n ),\n Match.when(\n 413,\n (): AiError.AiError => new AiError.ContextLengthExceeded({ provider, raw: body }),\n ),\n Match.when(\n (n) => n >= 500,\n (n): AiError.AiError => new AiError.Unavailable({ provider, status: n, raw: body }),\n ),\n Match.orElse((): AiError.AiError => new AiError.InvalidRequest({ provider, raw: body })),\n )\n\n/**\n * URL-form images need Gemini's Files API (upload, then `fileData`); we\n * don't pre-upload, so such a part would otherwise vanish from the request.\n * The caller fails the request with `Unsupported` instead of silently\n * dropping the image.\n */\nexport const hasUrlImageSource = (history: ReadonlyArray<HistoryItem>): boolean =>\n history.some(\n (item) =>\n item.type === \"message\" &&\n item.content.some((b) => b.type === \"input_image\" && b.source._tag === \"url\"),\n )\n\nexport const buildRequestBody = (\n history: ReadonlyArray<HistoryItem>,\n generationConfig: Option.Option<GenerationConfig>,\n tools: ReadonlyArray<ToolDescriptor> = [],\n providerToolEntries: ReadonlyArray<RequestTool> = [],\n toolChoice: CommonRequest[\"toolChoice\"] = undefined,\n): RequestBody => {\n const systemTexts = pipe(allMessages(history), Arr.filterMap(systemMessageText))\n const contents = pipe(history, Arr.filterMap(itemToContent(history)))\n const functionTools = toolDescriptorsToTools(tools)\n const requestTools = [...functionTools, ...providerToolEntries]\n return {\n contents,\n ...(systemTexts.length > 0 && {\n systemInstruction: { parts: [{ text: systemTexts.join(\"\\n\") }] },\n }),\n ...Option.match(generationConfig, {\n onNone: () => ({}),\n onSome: (cfg) => ({ generationConfig: cfg }),\n }),\n ...(requestTools.length > 0 && { tools: requestTools }),\n // Only force a function-calling mode when there are function declarations;\n // a grounding-only request must keep the API default.\n ...(functionTools.length > 0 && {\n toolConfig: { functionCallingConfig: toolChoiceToFunctionCallingConfig(toolChoice) },\n }),\n }\n}\n\n// ---------------------------------------------------------------------------\n// Stream-level state - accumulate chunk text + final usage/finish.\n//\n// `Accumulator` is immutable; `ingestChunk` returns a fresh one per chunk.\n// Drive it via `Stream.mapAccum` in the consumer.\n// ---------------------------------------------------------------------------\n\nconst finishReasonToStop = (reason: Option.Option<string>): Turn[\"stop_reason\"] =>\n Option.match(reason, {\n onNone: () => \"stop\" as const,\n onSome: (r) => (r === \"MAX_TOKENS\" ? (\"max_tokens\" as const) : (\"stop\" as const)),\n })\n\nexport type AccumulatedFunctionCall = {\n /** Synthesized id-or-name we surface as `call_id` on the canonical item. */\n readonly callId: string\n readonly name: string\n /** Wire id from Gemini 3, when present - echoed back on `functionResponse`. */\n readonly providerId: Option.Option<string>\n /** Thought signature from Gemini 3, replayed on the next request's part. */\n readonly signature: Option.Option<string>\n /** Args as JSON-encoded string, mirroring `Items.ToolCall.arguments`. */\n readonly arguments: string\n}\n\nexport type Accumulator = {\n readonly text: string\n readonly reasoning: string\n /** Images the model drew, in emission order. Image models only. */\n readonly images: ReadonlyArray<ImageSource>\n readonly functionCalls: ReadonlyArray<AccumulatedFunctionCall>\n /** Grounding citations, accumulated (de-duped by url) across chunks. */\n readonly annotations: ReadonlyArray<Annotation>\n readonly finishReason: Option.Option<string>\n readonly usage: {\n readonly input_tokens?: number\n readonly output_tokens?: number\n readonly total_tokens?: number\n readonly input_tokens_details?: { readonly cached_tokens?: number }\n readonly output_tokens_details?: { readonly reasoning_tokens?: number }\n }\n}\n\nexport const emptyAccumulator: Accumulator = {\n text: \"\",\n reasoning: \"\",\n images: [],\n functionCalls: [],\n annotations: [],\n finishReason: Option.none(),\n usage: {},\n}\n\n/**\n * One part's worth of streamable output. `text` and `reasoning` are\n * incremental string deltas; `function_call` arrives whole-in-one-chunk\n * (Gemini does not stream tool-call args).\n */\nexport type ChunkPart =\n | { readonly kind: \"text\"; readonly text: string }\n | { readonly kind: \"reasoning\"; readonly text: string }\n | { readonly kind: \"image\"; readonly source: ImageSource }\n | {\n readonly kind: \"function_call\"\n readonly id: Option.Option<string>\n readonly signature: Option.Option<string>\n readonly name: string\n readonly args: unknown\n }\n\nexport type ChunkResult = {\n readonly accumulator: Accumulator\n readonly parts: ReadonlyArray<ChunkPart>\n readonly finished: boolean\n}\n\nconst textToChunkParts = (p: typeof TextPart.Type): ReadonlyArray<ChunkPart> =>\n p.text.length === 0 ? [] : [{ kind: p.thought === true ? \"reasoning\" : \"text\", text: p.text }]\n\n/** Interim images drawn while planning are dropped, as thought text is. */\nconst inlineDataToChunkParts = (p: WireInlineDataPart): ReadonlyArray<ChunkPart> =>\n p.thought === true\n ? []\n : [\n {\n kind: \"image\",\n source: imageBase64(p.inlineData.data, p.inlineData.mimeType ?? \"image/png\"),\n },\n ]\n\nconst functionCallToChunkParts = (p: WireFunctionCallPart): ReadonlyArray<ChunkPart> => [\n {\n kind: \"function_call\",\n id: Option.fromNullishOr(p.functionCall.id),\n signature: Option.fromNullishOr(p.thoughtSignature),\n name: p.functionCall.name,\n args: p.functionCall.args ?? {},\n },\n]\n\n/** Parts are distinguished by which key they carry, not by a discriminator. */\nconst partToChunkParts: (p: typeof Part.Type) => ReadonlyArray<ChunkPart> = Match.type<\n typeof Part.Type\n>().pipe(\n Match.when({ text: Match.string }, textToChunkParts),\n Match.when({ inlineData: Match.defined }, inlineDataToChunkParts),\n Match.when({ functionCall: Match.defined }, functionCallToChunkParts),\n Match.exhaustive,\n)\n\nconst chunkParts = (chunk: WireChunk): ReadonlyArray<ChunkPart> =>\n pipe(chunk.candidates?.[0]?.content?.parts ?? [], Arr.flatMap(partToChunkParts))\n\nconst sumStrings = (parts: ReadonlyArray<ChunkPart>, kind: \"text\" | \"reasoning\"): string =>\n pipe(\n parts,\n Arr.filterMap((p) => (p.kind === kind ? Result.succeed(p.text) : Result.failVoid)),\n ).join(\"\")\n\nconst collectImages = (parts: ReadonlyArray<ChunkPart>): ReadonlyArray<ImageSource> =>\n pipe(\n parts,\n Arr.filterMap((p) => (p.kind === \"image\" ? Result.succeed(p.source) : Result.failVoid)),\n )\n\nconst collectFunctionCalls = (\n parts: ReadonlyArray<ChunkPart>,\n): ReadonlyArray<Extract<ChunkPart, { kind: \"function_call\" }>> =>\n pipe(\n parts,\n Arr.filterMap((p) => (p.kind === \"function_call\" ? Result.succeed(p) : Result.failVoid)),\n )\n\nconst mergeUsage = (\n prev: Accumulator[\"usage\"],\n next: WireChunk[\"usageMetadata\"],\n): Accumulator[\"usage\"] =>\n next === undefined\n ? prev\n : {\n ...prev,\n ...(next.promptTokenCount !== undefined && { input_tokens: next.promptTokenCount }),\n ...(next.candidatesTokenCount !== undefined && {\n output_tokens: next.candidatesTokenCount,\n }),\n ...(next.totalTokenCount !== undefined && { total_tokens: next.totalTokenCount }),\n ...(next.cachedContentTokenCount !== undefined && {\n input_tokens_details: { cached_tokens: next.cachedContentTokenCount },\n }),\n ...(next.thoughtsTokenCount !== undefined && {\n output_tokens_details: { reasoning_tokens: next.thoughtsTokenCount },\n }),\n }\n\n/**\n * Synthesize a stable `call_id` for a function call. Gemini 3 provides one\n * via `functionCall.id`; older models do not, so we fall back to\n * `<name>_<index>` based on prior calls' position in the accumulator.\n */\nconst synthesizeCallId = (\n call: Extract<ChunkPart, { kind: \"function_call\" }>,\n priorCalls: ReadonlyArray<AccumulatedFunctionCall>,\n): string =>\n Option.match(call.id, {\n onSome: (id) => id,\n onNone: () => `${call.name}_${priorCalls.length}`,\n })\n\nconst chunkCallToAccumulated = (\n prior: ReadonlyArray<AccumulatedFunctionCall>,\n call: Extract<ChunkPart, { kind: \"function_call\" }>,\n): AccumulatedFunctionCall => ({\n callId: synthesizeCallId(call, prior),\n name: call.name,\n providerId: call.id,\n signature: call.signature,\n // `functionCallToChunkParts` already replaced null/undefined with `{}`,\n // so `call.args` is always a JSON-encodable value here.\n arguments: JSON.stringify(call.args),\n})\n\nconst appendFunctionCalls = (\n prior: ReadonlyArray<AccumulatedFunctionCall>,\n fromChunk: ReadonlyArray<Extract<ChunkPart, { kind: \"function_call\" }>>,\n): ReadonlyArray<AccumulatedFunctionCall> =>\n fromChunk.reduce<ReadonlyArray<AccumulatedFunctionCall>>(\n (acc, call) => [...acc, chunkCallToAccumulated(acc, call)],\n prior,\n )\n\n// Grounding usually arrives on the final chunk, but merge across chunks and\n// de-dupe by url so a mid-stream metadata block is not lost or double-counted.\nconst mergeAnnotations = (\n prev: ReadonlyArray<Annotation>,\n next: ReadonlyArray<Annotation>,\n): ReadonlyArray<Annotation> =>\n next.length === 0 ? prev : Arr.dedupeWith(Arr.appendAll(prev, next), sameUrlCitation)\n\nexport const ingestChunk = (acc: Accumulator, chunk: WireChunk): ChunkResult => {\n const parts = chunkParts(chunk)\n const finishReason = Option.fromNullishOr(chunk.candidates?.[0]?.finishReason)\n return {\n parts,\n finished: Option.isSome(finishReason),\n accumulator: {\n text: acc.text + sumStrings(parts, \"text\"),\n reasoning: acc.reasoning + sumStrings(parts, \"reasoning\"),\n images: Arr.appendAll(acc.images, collectImages(parts)),\n functionCalls: appendFunctionCalls(acc.functionCalls, collectFunctionCalls(parts)),\n annotations: mergeAnnotations(\n acc.annotations,\n groundingToAnnotations(chunk.candidates?.[0]?.groundingMetadata),\n ),\n finishReason: Option.orElse(finishReason, () => acc.finishReason),\n usage: mergeUsage(acc.usage, chunk.usageMetadata),\n },\n }\n}\n\nconst reasoningItems = (acc: Accumulator): ReadonlyArray<HistoryItem> =>\n acc.reasoning.length > 0 ? [{ type: \"reasoning\", summary: acc.reasoning }] : []\n\n/**\n * Image models interleave text and image parts, and often answer with an\n * image and no prose at all, so the message exists when either is present.\n */\nconst assistantMessageItems = (acc: Accumulator): ReadonlyArray<HistoryItem> => {\n const content: ReadonlyArray<ContentBlock> = [\n ...(acc.text.length === 0\n ? []\n : [\n {\n type: \"output_text\" as const,\n text: acc.text,\n ...(acc.annotations.length > 0 && { annotations: acc.annotations }),\n },\n ]),\n ...acc.images.map((source) => ({ type: \"output_image\" as const, source })),\n ]\n return content.length === 0 ? [] : [{ type: \"message\", role: \"assistant\", content }]\n}\n\nconst functionCallItems = (acc: Accumulator): ReadonlyArray<HistoryItem> =>\n pipe(\n acc.functionCalls,\n Arr.map((c) => {\n const gemini = {\n ...(Option.isSome(c.providerId) && { id: c.providerId.value }),\n ...(Option.isSome(c.signature) && { thoughtSignature: c.signature.value }),\n }\n return {\n type: \"function_call\" as const,\n call_id: c.callId,\n name: c.name,\n arguments: c.arguments,\n ...(Object.keys(gemini).length > 0 && { providerData: { gemini } }),\n }\n }),\n )\n\nexport const accumulatorToTurn = (acc: Accumulator): Turn => ({\n stop_reason:\n acc.functionCalls.length > 0 ? (\"tool_calls\" as const) : finishReasonToStop(acc.finishReason),\n usage: { ...acc.usage },\n items: [...reasoningItems(acc), ...assistantMessageItems(acc), ...functionCallItems(acc)],\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAsBA,MAAM,WAAW,OAA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match, Option, Result, Schema, pipe } from \"effect\"\nimport { Base64 } from \"effect/encoding\"\nimport * as AiError from \"@effect-uai/core/AiError\"\nimport type { ImageSource } from \"@effect-uai/core/Image\"\nimport { imageBase64 } from \"@effect-uai/core/Image\"\nimport type { FileSource } from \"@effect-uai/core/File\"\nimport type {\n ContentBlock,\n ToolCall,\n ToolCallOutput,\n ToolOutputContent,\n InputImage,\n HistoryItem,\n Message,\n Annotation,\n} from \"@effect-uai/core/Items\"\nimport type { ToolDescriptor } from \"@effect-uai/core/Tool\"\nimport type { Turn } from \"@effect-uai/core/Turn\"\nimport type { CommonRequest } from \"@effect-uai/core/LanguageModel\"\n\n// ---------------------------------------------------------------------------\n// Wire schemas - the subset of Gemini's streamGenerateContent payload we\n// consume. Reference: https://ai.google.dev/api/generate-content\n// ---------------------------------------------------------------------------\n\nconst TextPart = Schema.Struct({\n text: Schema.String,\n /**\n * Gemini's flag for chain-of-thought parts. When `true`, the part is\n * reasoning trace, not the model's user-facing answer. Maps onto\n * `reasoning_delta { kind: \"trace\" }` in the canonical view.\n */\n thought: Schema.optional(Schema.Boolean),\n})\n\n/**\n * Gemini function-call part. Args are delivered as a whole JSON *object*\n * in a single chunk (Gemini does not stream tool-call args). On Gemini 3\n * the response also carries an `id` per call, which we echo back on the\n * corresponding `functionResponse`.\n */\nconst FunctionCallPart = Schema.Struct({\n functionCall: Schema.Struct({\n id: Schema.optional(Schema.String),\n name: Schema.String,\n args: Schema.optional(Schema.Unknown),\n }),\n // Gemini 3 thinking models attach an opaque signature to each function-call\n // part that must be replayed on the next request, or the call is rejected.\n thoughtSignature: Schema.optional(Schema.String),\n})\n\n/**\n * An image the model drew, as a part of its own turn. Only image models\n * emit these, and only when the request asked for the IMAGE modality.\n * `thought: true` marks an interim image drawn while planning, which is\n * not the answer and is dropped the same way thought text is.\n */\nconst InlineDataPart = Schema.Struct({\n inlineData: Schema.Struct({\n mimeType: Schema.optional(Schema.String),\n data: Schema.String,\n }),\n thought: Schema.optional(Schema.Boolean),\n})\n\nconst Part = Schema.Union([TextPart, FunctionCallPart, InlineDataPart])\ntype WireFunctionCallPart = typeof FunctionCallPart.Type\ntype WireInlineDataPart = typeof InlineDataPart.Type\n\nconst Content = Schema.Struct({\n role: Schema.optional(Schema.String),\n parts: Schema.optional(Schema.Array(Part)),\n})\n\n// Google grounding metadata. On a grounded response the candidate carries\n// `groundingChunks[].web.{uri,title}` - the structured form of the inline `[n]`\n// / trailing `**Sources:**` list the model renders into the answer text.\n// Decoded defensively (every field optional) as it is absent on ungrounded\n// turns. Shared with the Interactions deep-research surface via `codec.ts`.\nconst GroundingChunk = Schema.Struct({\n web: Schema.optional(\n Schema.NullOr(\n Schema.Struct({\n uri: Schema.optional(Schema.NullOr(Schema.String)),\n title: Schema.optional(Schema.NullOr(Schema.String)),\n }),\n ),\n ),\n})\nexport const GroundingMetadata = Schema.Struct({\n groundingChunks: Schema.optional(Schema.NullOr(Schema.Array(GroundingChunk))),\n})\nexport type GroundingMetadata = typeof GroundingMetadata.Type\n\n// Two citations are the same source when they point at the same url.\nconst sameUrlCitation = (a: Annotation, b: Annotation): boolean =>\n a.type === \"url_citation\" && b.type === \"url_citation\" && a.url === b.url\n\n// Grounding chunks → `url_citation` annotations, de-duped by url across every\n// metadata block passed. `web.uri` is a `grounding-api-redirect` URL and\n// `web.title` the bare domain; both are kept as-is (the redirect resolves to\n// the real page).\nexport const groundingToAnnotations = (\n ...metas: ReadonlyArray<GroundingMetadata | null | undefined>\n): ReadonlyArray<Annotation> =>\n pipe(\n metas,\n Arr.flatMap((meta) => meta?.groundingChunks ?? []),\n Arr.filterMap((chunk) =>\n chunk.web?.uri == null\n ? Result.failVoid\n : Result.succeed<Annotation>({\n type: \"url_citation\",\n url: chunk.web.uri,\n title: chunk.web.title ?? chunk.web.uri,\n }),\n ),\n Arr.dedupeWith(sameUrlCitation),\n )\n\nconst Candidate = Schema.Struct({\n content: Schema.optional(Content),\n groundingMetadata: Schema.optional(GroundingMetadata),\n finishReason: Schema.optional(Schema.String),\n index: Schema.optional(Schema.Number),\n})\n\nconst UsageMetadata = Schema.Struct({\n promptTokenCount: Schema.optional(Schema.Number),\n candidatesTokenCount: Schema.optional(Schema.Number),\n totalTokenCount: Schema.optional(Schema.Number),\n cachedContentTokenCount: Schema.optional(Schema.Number),\n thoughtsTokenCount: Schema.optional(Schema.Number),\n})\n\nexport const WireChunk = Schema.Struct({\n candidates: Schema.optional(Schema.Array(Candidate)),\n usageMetadata: Schema.optional(UsageMetadata),\n})\nexport type WireChunk = typeof WireChunk.Type\n\n// ---------------------------------------------------------------------------\n// History → request body\n// ---------------------------------------------------------------------------\n\ntype RequestPart =\n | { readonly text: string }\n | { readonly inlineData: { readonly mimeType: string; readonly data: string } }\n | {\n readonly functionCall: {\n readonly id?: string\n readonly name: string\n readonly args: unknown\n }\n readonly thoughtSignature?: string\n }\n | {\n readonly functionResponse: FunctionResponseBody & {\n readonly id?: string\n readonly name: string\n }\n }\n\ntype RequestContent = {\n readonly role: \"user\" | \"model\"\n readonly parts: ReadonlyArray<RequestPart>\n}\n\ntype RequestSystemInstruction = {\n readonly parts: ReadonlyArray<{ readonly text: string }>\n}\n\n/**\n * Gemini's tool declaration. A `tools[]` entry is either a function-declaration\n * block (translated from `ToolDescriptor`s) or one of the native hosted-tool\n * entries. The native entries are empty objects keyed camelCase per the REST\n * v1beta `Tool` object, and sit as siblings of the declarations in the same\n * `tools` array.\n */\nexport type RequestTool =\n | {\n readonly functionDeclarations: ReadonlyArray<{\n readonly name: string\n readonly description: string\n readonly parameters: Record<string, unknown>\n }>\n }\n | { readonly googleSearch: {} }\n | { readonly urlContext: {} }\n | { readonly codeExecution: {} }\n\ntype RequestToolConfig = {\n readonly functionCallingConfig: {\n readonly mode: \"AUTO\" | \"ANY\" | \"NONE\"\n readonly allowedFunctionNames?: ReadonlyArray<string>\n }\n}\n\nexport type ThinkingConfig = {\n readonly thinkingBudget: number\n}\n\nexport type ImageConfig = {\n readonly aspectRatio?: string\n readonly imageSize?: string\n}\n\nexport type GenerationConfig = {\n readonly temperature?: number\n readonly maxOutputTokens?: number\n readonly topP?: number\n readonly thinkingConfig?: ThinkingConfig\n /** Image models need `[\"TEXT\", \"IMAGE\"]` or they answer in prose only. */\n readonly responseModalities?: ReadonlyArray<\"TEXT\" | \"IMAGE\">\n readonly imageConfig?: ImageConfig\n /** Set together with `responseJsonSchema` to constrain output to JSON. */\n readonly responseMimeType?: string\n /** JSON Schema constraint on the output. */\n readonly responseJsonSchema?: Record<string, unknown>\n}\n\nexport type RequestBody = {\n readonly contents: ReadonlyArray<RequestContent>\n readonly systemInstruction?: RequestSystemInstruction\n readonly generationConfig?: GenerationConfig\n readonly tools?: ReadonlyArray<RequestTool>\n readonly toolConfig?: RequestToolConfig\n}\n\nconst blockText = Match.type<ContentBlock>().pipe(\n Match.discriminatorsExhaustive(\"type\")({\n input_text: (b) => b.text,\n input_image: () => \"\",\n output_text: (b) => b.text,\n output_image: () => \"\",\n refusal: (b) => b.text,\n }),\n)\n\nconst messageText = (message: Message): string => message.content.map(blockText).join(\"\")\n\n/**\n * Gemini's `inlineData` form expects a base64 payload. URL-form images\n * would need to go through Gemini's Files API (upload then `fileData`\n * with the returned URI); pre-uploading isn't free, so we skip those for\n * now and document as a follow-up.\n */\nconst imageSourceToParts = Match.type<InputImage[\"source\"]>().pipe(\n Match.tag(\"url\", (): ReadonlyArray<RequestPart> => []),\n Match.tag(\"base64\", (s): ReadonlyArray<RequestPart> => [\n { inlineData: { mimeType: s.mimeType, data: s.base64 } },\n ]),\n Match.tag(\"bytes\", (s): ReadonlyArray<RequestPart> => [\n { inlineData: { mimeType: s.mimeType, data: Base64.encode(s.bytes) } },\n ]),\n Match.exhaustive,\n)\n\nconst blockToParts = Match.type<ContentBlock>().pipe(\n Match.discriminatorsExhaustive(\"type\")({\n input_text: (b): ReadonlyArray<RequestPart> => (b.text.length === 0 ? [] : [{ text: b.text }]),\n input_image: (b): ReadonlyArray<RequestPart> => imageSourceToParts(b.source),\n output_text: (b): ReadonlyArray<RequestPart> => (b.text.length === 0 ? [] : [{ text: b.text }]),\n // An image the model drew goes back as a model-role `inlineData` part,\n // which is how a multi-turn edit keeps its subject.\n output_image: (b): ReadonlyArray<RequestPart> => imageSourceToParts(b.source),\n // Refusals are assistant-side content; they don't round-trip into Gemini's\n // request body as parts. Skip.\n refusal: (): ReadonlyArray<RequestPart> => [],\n }),\n)\n\nconst messageToContent = (message: Message): Result.Result<RequestContent, void> => {\n const parts = pipe(message.content, Arr.flatMap(blockToParts))\n if (parts.length === 0) return Result.failVoid\n return Match.value(message.role).pipe(\n Match.when(\"user\", () => Result.succeed({ role: \"user\" as const, parts })),\n Match.when(\"assistant\", () => Result.succeed({ role: \"model\" as const, parts })),\n Match.when(\"system\", () => Result.failVoid),\n Match.exhaustive,\n )\n}\n\nconst systemMessageText = (message: Message): Result.Result<string, void> => {\n if (message.role !== \"system\") return Result.failVoid\n const text = messageText(message)\n return text.length === 0 ? Result.failVoid : Result.succeed(text)\n}\n\nconst allMessages = (history: ReadonlyArray<HistoryItem>): ReadonlyArray<Message> =>\n pipe(\n history,\n Arr.filterMap((item) => (item.type === \"message\" ? Result.succeed(item) : Result.failVoid)),\n )\n\n// ---------------------------------------------------------------------------\n// Function-call round-trip\n//\n// `ToolCall.arguments` is a JSON string; Gemini's `functionCall.args` wants\n// an object (malformed or non-object arguments become `{}`).\n// ---------------------------------------------------------------------------\n\nconst JsonObject = Schema.Record(Schema.String, Schema.Unknown)\nconst decodeJsonObject = Schema.decodeResult(Schema.fromJsonString(JsonObject))\n\nconst parsedArgs = (encoded: string): Record<string, unknown> =>\n pipe(\n decodeJsonObject(encoded),\n Result.getOrElse(() => ({})),\n )\n\ntype MediaPart =\n | {\n readonly inlineData: {\n readonly mimeType: string\n readonly data: string\n readonly displayName?: string\n }\n }\n | {\n readonly fileData: {\n readonly fileUri: string\n readonly mimeType?: string\n readonly displayName?: string\n }\n }\n\nconst mediaPart = (\n source: ImageSource | FileSource,\n displayName: string | undefined,\n): MediaPart => {\n const named = displayName === undefined ? {} : { displayName }\n return Match.value(source).pipe(\n Match.tagsExhaustive({\n url: (s) => ({\n fileData: {\n fileUri: s.url,\n ...(s.mimeType !== undefined && { mimeType: s.mimeType }),\n ...named,\n },\n }),\n base64: (s) => ({ inlineData: { mimeType: s.mimeType, data: s.base64, ...named } }),\n bytes: (s) => ({\n inlineData: { mimeType: s.mimeType, data: Base64.encode(s.bytes), ...named },\n }),\n }),\n )\n}\n\n/** Gemini's `functionResponse` body for a tool output, without `id` / `name`. */\nexport type FunctionResponseBody = {\n readonly response: Record<string, unknown>\n readonly parts?: ReadonlyArray<MediaPart>\n}\n\n/**\n * Text and JSON go into `response.output` (or `response.error` when the call\n * failed) as values, never stringified: one value as itself, several as an\n * array. Media goes into `parts`.\n */\nexport const functionResponseBody = (output: ToolCallOutput): FunctionResponseBody => {\n const values = Arr.filterMap(\n output.output,\n Match.type<ToolOutputContent>().pipe(\n Match.discriminatorsExhaustive(\"type\")({\n input_text: (p) => Result.succeed<unknown>(p.text),\n input_json: (p) => Result.succeed<unknown>(p.value),\n input_image: () => Result.failVoid,\n input_file: () => Result.failVoid,\n }),\n ),\n )\n const media = Arr.filterMap(\n output.output,\n Match.type<ToolOutputContent>().pipe(\n Match.discriminatorsExhaustive(\"type\")({\n input_text: () => Result.failVoid,\n input_json: () => Result.failVoid,\n input_image: (p) => Result.succeed(mediaPart(p.source, undefined)),\n input_file: (p) => Result.succeed(mediaPart(p.source, p.filename)),\n }),\n ),\n )\n const key = output.isError === true ? \"error\" : \"output\"\n const response = Arr.match(values, {\n onEmpty: () => ({}),\n onNonEmpty: (all) => ({ [key]: all.length === 1 ? Arr.headNonEmpty(all) : all }),\n })\n return media.length === 0 ? { response } : { response, parts: media }\n}\n\n/**\n * `ToolCallOutput` only carries `call_id`; Gemini's `functionResponse`\n * requires the declared function `name`. Resolve the name by scanning prior\n * `function_call` items in the history for a matching `call_id`. If we\n * cannot resolve, fall back to `call_id` as the name - imperfect but\n * preserves stream shape so the model sees *some* response.\n */\nconst isFunctionCallItem = (item: HistoryItem): item is ToolCall => item.type === \"function_call\"\n\nconst nameForCallId = (\n history: ReadonlyArray<HistoryItem>,\n call_id: string,\n): Option.Option<string> =>\n pipe(\n history,\n Arr.findFirst((item): item is ToolCall => isFunctionCallItem(item) && item.call_id === call_id),\n Option.map((f) => f.name),\n )\n\n/**\n * Extract the Gemini-3 wire id and thought signature we stashed in\n * `providerData` on the way out. Schema-driven so the shape lives in one\n * place; failure or absence → `Option.none()`.\n */\nconst ProviderDataGemini = Schema.Struct({\n gemini: Schema.Struct({\n id: Schema.optional(Schema.String),\n thoughtSignature: Schema.optional(Schema.String),\n }),\n})\nconst decodeGemini = Schema.decodeUnknownResult(ProviderDataGemini)\n\nconst geminiField = (\n item: ToolCall,\n pick: (g: {\n readonly id?: string | undefined\n readonly thoughtSignature?: string | undefined\n }) => string | undefined,\n): Option.Option<string> =>\n pipe(\n decodeGemini(item.providerData),\n Result.match({\n onSuccess: (d) => Option.fromNullishOr(pick(d.gemini)),\n onFailure: () => Option.none<string>(),\n }),\n )\n\nconst providerIdFor = (item: ToolCall): Option.Option<string> => geminiField(item, (g) => g.id)\n\n// The originating call's Gemini id, looked up from history by our `call_id`.\n// Gemini 3 maps a `functionResponse` back to its call by this id, so parallel\n// calls to the same function are mis-paired if we drop it.\nconst providerIdForCallId = (\n history: ReadonlyArray<HistoryItem>,\n call_id: string,\n): Option.Option<string> =>\n pipe(\n history,\n Arr.findFirst((item): item is ToolCall => isFunctionCallItem(item) && item.call_id === call_id),\n Option.flatMap(providerIdFor),\n )\n\nconst signatureFor = (item: ToolCall): Option.Option<string> =>\n geminiField(item, (g) => g.thoughtSignature)\n\nconst itemToContent =\n (history: ReadonlyArray<HistoryItem>) =>\n (item: HistoryItem): Result.Result<RequestContent, void> =>\n Match.value(item).pipe(\n Match.discriminatorsExhaustive(\"type\")({\n message: messageToContent,\n function_call: (f) =>\n Result.succeed({\n role: \"model\" as const,\n parts: [\n {\n ...Option.match(signatureFor(f), {\n onSome: (thoughtSignature) => ({ thoughtSignature }),\n onNone: () => ({}),\n }),\n functionCall: {\n ...Option.match(providerIdFor(f), {\n onSome: (id) => ({ id }),\n onNone: () => ({}),\n }),\n name: f.name,\n args: parsedArgs(f.arguments),\n },\n },\n ],\n }),\n function_call_output: (o) =>\n Result.succeed({\n role: \"user\" as const,\n parts: [\n {\n functionResponse: {\n ...Option.match(providerIdForCallId(history, o.call_id), {\n onSome: (id) => ({ id }),\n onNone: () => ({}),\n }),\n name: Option.getOrElse(nameForCallId(history, o.call_id), () => o.call_id),\n ...functionResponseBody(o),\n },\n },\n ],\n }),\n reasoning: () => Result.failVoid,\n }),\n )\n\n// ---------------------------------------------------------------------------\n// Tool descriptors → Gemini `functionDeclarations`. Gemini accepts only a\n// strict OpenAPI 3.0 subset for `parameters`; strip JSON-Schema keys it\n// rejects (`$schema`, `$ref`, `additionalProperties`, `oneOf`,\n// `definitions`).\n// ---------------------------------------------------------------------------\n\nconst UNSUPPORTED_SCHEMA_KEYS: ReadonlySet<string> = new Set([\n \"$schema\",\n \"$ref\",\n \"$defs\",\n \"definitions\",\n \"additionalProperties\",\n \"oneOf\",\n])\n\nconst sanitizeSchema = (schema: unknown): unknown => {\n if (Array.isArray(schema)) return schema.map(sanitizeSchema)\n if (schema === null || typeof schema !== \"object\") return schema\n return pipe(\n Object.entries(schema as Record<string, unknown>),\n Arr.filterMap(([k, v]) =>\n UNSUPPORTED_SCHEMA_KEYS.has(k)\n ? Result.failVoid\n : Result.succeed([k, sanitizeSchema(v)] as const),\n ),\n Object.fromEntries,\n )\n}\n\nexport const toolDescriptorsToTools = (\n tools: ReadonlyArray<ToolDescriptor>,\n): ReadonlyArray<RequestTool> =>\n tools.length === 0\n ? []\n : [\n {\n functionDeclarations: tools.map((t) => ({\n name: t.name,\n description: t.description,\n parameters: sanitizeSchema(t.inputSchema) as Record<string, unknown>,\n })),\n },\n ]\n\n/**\n * Map our cross-provider `toolChoice` onto Gemini's `functionCallingConfig`.\n * Gemini honours the same three modes plus a function allow-list, so the\n * choice is mapped, not dropped. `undefined` keeps the API default (`AUTO`).\n */\nconst toolChoiceToFunctionCallingConfig = (\n toolChoice: CommonRequest[\"toolChoice\"],\n): RequestToolConfig[\"functionCallingConfig\"] =>\n Match.value(toolChoice ?? \"auto\").pipe(\n Match.when(\"auto\", () => ({ mode: \"AUTO\" as const })),\n Match.when(\"required\", () => ({ mode: \"ANY\" as const })),\n Match.when(\"none\", () => ({ mode: \"NONE\" as const })),\n Match.orElse((tc) => ({ mode: \"ANY\" as const, allowedFunctionNames: [tc.name] })),\n )\n\n// ---------------------------------------------------------------------------\n// HTTP failure mapping, shared by every Google surface\n// ---------------------------------------------------------------------------\n\n/** `provider` names the surface that failed, so errors read `gemini` or `lyria`. */\nexport const transportFailure =\n (provider: string) =>\n (cause: unknown): AiError.AiError =>\n new AiError.Unavailable({ provider, raw: cause })\n\n/** 413 is the inline-payload cap, which is a context limit on every surface. */\nexport const httpStatusError =\n (provider: string) =>\n (status: number, body: string): AiError.AiError =>\n Match.value(status).pipe(\n Match.when(429, (): AiError.AiError => new AiError.RateLimited({ provider, raw: body })),\n Match.whenOr(408, 504, (): AiError.AiError => new AiError.Timeout({ provider, raw: body })),\n Match.when(\n 401,\n (): AiError.AiError => new AiError.AuthFailed({ provider, subtype: \"auth\", raw: body }),\n ),\n Match.when(\n 403,\n (): AiError.AiError =>\n new AiError.AuthFailed({ provider, subtype: \"permission\", raw: body }),\n ),\n Match.when(\n 402,\n (): AiError.AiError => new AiError.AuthFailed({ provider, subtype: \"billing\", raw: body }),\n ),\n Match.when(\n 413,\n (): AiError.AiError => new AiError.ContextLengthExceeded({ provider, raw: body }),\n ),\n Match.when(\n (n) => n >= 500,\n (n): AiError.AiError => new AiError.Unavailable({ provider, status: n, raw: body }),\n ),\n Match.orElse((): AiError.AiError => new AiError.InvalidRequest({ provider, raw: body })),\n )\n\n/**\n * URL-form images need Gemini's Files API (upload, then `fileData`); we\n * don't pre-upload, so such a part would otherwise vanish from the request.\n * The caller fails the request with `Unsupported` instead of silently\n * dropping the image.\n */\nexport const hasUrlImageSource = (history: ReadonlyArray<HistoryItem>): boolean =>\n history.some(\n (item) =>\n item.type === \"message\" &&\n item.content.some((b) => b.type === \"input_image\" && b.source._tag === \"url\"),\n )\n\nexport const buildRequestBody = (\n history: ReadonlyArray<HistoryItem>,\n generationConfig: Option.Option<GenerationConfig>,\n tools: ReadonlyArray<ToolDescriptor> = [],\n providerToolEntries: ReadonlyArray<RequestTool> = [],\n toolChoice: CommonRequest[\"toolChoice\"] = undefined,\n): RequestBody => {\n const systemTexts = pipe(allMessages(history), Arr.filterMap(systemMessageText))\n const contents = pipe(history, Arr.filterMap(itemToContent(history)))\n const functionTools = toolDescriptorsToTools(tools)\n const requestTools = [...functionTools, ...providerToolEntries]\n return {\n contents,\n ...(systemTexts.length > 0 && {\n systemInstruction: { parts: [{ text: systemTexts.join(\"\\n\") }] },\n }),\n ...Option.match(generationConfig, {\n onNone: () => ({}),\n onSome: (cfg) => ({ generationConfig: cfg }),\n }),\n ...(requestTools.length > 0 && { tools: requestTools }),\n // Only force a function-calling mode when there are function declarations;\n // a grounding-only request must keep the API default.\n ...(functionTools.length > 0 && {\n toolConfig: { functionCallingConfig: toolChoiceToFunctionCallingConfig(toolChoice) },\n }),\n }\n}\n\n// ---------------------------------------------------------------------------\n// Stream-level state - accumulate chunk text + final usage/finish.\n//\n// `Accumulator` is immutable; `ingestChunk` returns a fresh one per chunk.\n// Drive it via `Stream.mapAccum` in the consumer.\n// ---------------------------------------------------------------------------\n\nconst finishReasonToStop = (reason: Option.Option<string>): Turn[\"stop_reason\"] =>\n Option.match(reason, {\n onNone: () => \"stop\" as const,\n onSome: (r) => (r === \"MAX_TOKENS\" ? (\"max_tokens\" as const) : (\"stop\" as const)),\n })\n\nexport type AccumulatedFunctionCall = {\n /** Synthesized id-or-name we surface as `call_id` on the canonical item. */\n readonly callId: string\n readonly name: string\n /** Wire id from Gemini 3, when present - echoed back on `functionResponse`. */\n readonly providerId: Option.Option<string>\n /** Thought signature from Gemini 3, replayed on the next request's part. */\n readonly signature: Option.Option<string>\n /** Args as JSON-encoded string, mirroring `Items.ToolCall.arguments`. */\n readonly arguments: string\n}\n\nexport type Accumulator = {\n readonly text: string\n readonly reasoning: string\n /** Images the model drew, in emission order. Image models only. */\n readonly images: ReadonlyArray<ImageSource>\n readonly functionCalls: ReadonlyArray<AccumulatedFunctionCall>\n /** Grounding citations, accumulated (de-duped by url) across chunks. */\n readonly annotations: ReadonlyArray<Annotation>\n readonly finishReason: Option.Option<string>\n readonly usage: {\n readonly input_tokens?: number\n readonly output_tokens?: number\n readonly total_tokens?: number\n readonly input_tokens_details?: { readonly cached_tokens?: number }\n readonly output_tokens_details?: { readonly reasoning_tokens?: number }\n }\n}\n\nexport const emptyAccumulator: Accumulator = {\n text: \"\",\n reasoning: \"\",\n images: [],\n functionCalls: [],\n annotations: [],\n finishReason: Option.none(),\n usage: {},\n}\n\n/**\n * One part's worth of streamable output. `text` and `reasoning` are\n * incremental string deltas; `function_call` arrives whole-in-one-chunk\n * (Gemini does not stream tool-call args).\n */\nexport type ChunkPart =\n | { readonly kind: \"text\"; readonly text: string }\n | { readonly kind: \"reasoning\"; readonly text: string }\n | { readonly kind: \"image\"; readonly source: ImageSource }\n | {\n readonly kind: \"function_call\"\n readonly id: Option.Option<string>\n readonly signature: Option.Option<string>\n readonly name: string\n readonly args: unknown\n }\n\nexport type ChunkResult = {\n readonly accumulator: Accumulator\n readonly parts: ReadonlyArray<ChunkPart>\n readonly finished: boolean\n}\n\nconst textToChunkParts = (p: typeof TextPart.Type): ReadonlyArray<ChunkPart> =>\n p.text.length === 0 ? [] : [{ kind: p.thought === true ? \"reasoning\" : \"text\", text: p.text }]\n\n/** Interim images drawn while planning are dropped, as thought text is. */\nconst inlineDataToChunkParts = (p: WireInlineDataPart): ReadonlyArray<ChunkPart> =>\n p.thought === true\n ? []\n : [\n {\n kind: \"image\",\n source: imageBase64(p.inlineData.data, p.inlineData.mimeType ?? \"image/png\"),\n },\n ]\n\nconst functionCallToChunkParts = (p: WireFunctionCallPart): ReadonlyArray<ChunkPart> => [\n {\n kind: \"function_call\",\n id: Option.fromNullishOr(p.functionCall.id),\n signature: Option.fromNullishOr(p.thoughtSignature),\n name: p.functionCall.name,\n args: p.functionCall.args ?? {},\n },\n]\n\n/** Parts are distinguished by which key they carry, not by a discriminator. */\nconst partToChunkParts: (p: typeof Part.Type) => ReadonlyArray<ChunkPart> = Match.type<\n typeof Part.Type\n>().pipe(\n Match.when({ text: Match.string }, textToChunkParts),\n Match.when({ inlineData: Match.defined }, inlineDataToChunkParts),\n Match.when({ functionCall: Match.defined }, functionCallToChunkParts),\n Match.exhaustive,\n)\n\nconst chunkParts = (chunk: WireChunk): ReadonlyArray<ChunkPart> =>\n pipe(chunk.candidates?.[0]?.content?.parts ?? [], Arr.flatMap(partToChunkParts))\n\nconst sumStrings = (parts: ReadonlyArray<ChunkPart>, kind: \"text\" | \"reasoning\"): string =>\n pipe(\n parts,\n Arr.filterMap((p) => (p.kind === kind ? Result.succeed(p.text) : Result.failVoid)),\n ).join(\"\")\n\nconst collectImages = (parts: ReadonlyArray<ChunkPart>): ReadonlyArray<ImageSource> =>\n pipe(\n parts,\n Arr.filterMap((p) => (p.kind === \"image\" ? Result.succeed(p.source) : Result.failVoid)),\n )\n\nconst collectFunctionCalls = (\n parts: ReadonlyArray<ChunkPart>,\n): ReadonlyArray<Extract<ChunkPart, { kind: \"function_call\" }>> =>\n pipe(\n parts,\n Arr.filterMap((p) => (p.kind === \"function_call\" ? Result.succeed(p) : Result.failVoid)),\n )\n\nconst mergeUsage = (\n prev: Accumulator[\"usage\"],\n next: WireChunk[\"usageMetadata\"],\n): Accumulator[\"usage\"] =>\n next === undefined\n ? prev\n : {\n ...prev,\n ...(next.promptTokenCount !== undefined && { input_tokens: next.promptTokenCount }),\n ...(next.candidatesTokenCount !== undefined && {\n output_tokens: next.candidatesTokenCount,\n }),\n ...(next.totalTokenCount !== undefined && { total_tokens: next.totalTokenCount }),\n ...(next.cachedContentTokenCount !== undefined && {\n input_tokens_details: { cached_tokens: next.cachedContentTokenCount },\n }),\n ...(next.thoughtsTokenCount !== undefined && {\n output_tokens_details: { reasoning_tokens: next.thoughtsTokenCount },\n }),\n }\n\n/**\n * Synthesize a stable `call_id` for a function call. Gemini 3 provides one\n * via `functionCall.id`; older models do not, so we fall back to\n * `<name>_<index>` based on prior calls' position in the accumulator.\n */\nconst synthesizeCallId = (\n call: Extract<ChunkPart, { kind: \"function_call\" }>,\n priorCalls: ReadonlyArray<AccumulatedFunctionCall>,\n): string =>\n Option.match(call.id, {\n onSome: (id) => id,\n onNone: () => `${call.name}_${priorCalls.length}`,\n })\n\nconst chunkCallToAccumulated = (\n prior: ReadonlyArray<AccumulatedFunctionCall>,\n call: Extract<ChunkPart, { kind: \"function_call\" }>,\n): AccumulatedFunctionCall => ({\n callId: synthesizeCallId(call, prior),\n name: call.name,\n providerId: call.id,\n signature: call.signature,\n // `functionCallToChunkParts` already replaced null/undefined with `{}`,\n // so `call.args` is always a JSON-encodable value here.\n arguments: JSON.stringify(call.args),\n})\n\nconst appendFunctionCalls = (\n prior: ReadonlyArray<AccumulatedFunctionCall>,\n fromChunk: ReadonlyArray<Extract<ChunkPart, { kind: \"function_call\" }>>,\n): ReadonlyArray<AccumulatedFunctionCall> =>\n fromChunk.reduce<ReadonlyArray<AccumulatedFunctionCall>>(\n (acc, call) => [...acc, chunkCallToAccumulated(acc, call)],\n prior,\n )\n\n// Grounding usually arrives on the final chunk, but merge across chunks and\n// de-dupe by url so a mid-stream metadata block is not lost or double-counted.\nconst mergeAnnotations = (\n prev: ReadonlyArray<Annotation>,\n next: ReadonlyArray<Annotation>,\n): ReadonlyArray<Annotation> =>\n next.length === 0 ? prev : Arr.dedupeWith(Arr.appendAll(prev, next), sameUrlCitation)\n\nexport const ingestChunk = (acc: Accumulator, chunk: WireChunk): ChunkResult => {\n const parts = chunkParts(chunk)\n const finishReason = Option.fromNullishOr(chunk.candidates?.[0]?.finishReason)\n return {\n parts,\n finished: Option.isSome(finishReason),\n accumulator: {\n text: acc.text + sumStrings(parts, \"text\"),\n reasoning: acc.reasoning + sumStrings(parts, \"reasoning\"),\n images: Arr.appendAll(acc.images, collectImages(parts)),\n functionCalls: appendFunctionCalls(acc.functionCalls, collectFunctionCalls(parts)),\n annotations: mergeAnnotations(\n acc.annotations,\n groundingToAnnotations(chunk.candidates?.[0]?.groundingMetadata),\n ),\n finishReason: Option.orElse(finishReason, () => acc.finishReason),\n usage: mergeUsage(acc.usage, chunk.usageMetadata),\n },\n }\n}\n\nconst reasoningItems = (acc: Accumulator): ReadonlyArray<HistoryItem> =>\n acc.reasoning.length > 0 ? [{ type: \"reasoning\", summary: acc.reasoning }] : []\n\n/**\n * Image models interleave text and image parts, and often answer with an\n * image and no prose at all, so the message exists when either is present.\n */\nconst assistantMessageItems = (acc: Accumulator): ReadonlyArray<HistoryItem> => {\n const content: ReadonlyArray<ContentBlock> = [\n ...(acc.text.length === 0\n ? []\n : [\n {\n type: \"output_text\" as const,\n text: acc.text,\n ...(acc.annotations.length > 0 && { annotations: acc.annotations }),\n },\n ]),\n ...acc.images.map((source) => ({ type: \"output_image\" as const, source })),\n ]\n return content.length === 0 ? [] : [{ type: \"message\", role: \"assistant\", content }]\n}\n\nconst functionCallItems = (acc: Accumulator): ReadonlyArray<HistoryItem> =>\n pipe(\n acc.functionCalls,\n Arr.map((c) => {\n const gemini = {\n ...(Option.isSome(c.providerId) && { id: c.providerId.value }),\n ...(Option.isSome(c.signature) && { thoughtSignature: c.signature.value }),\n }\n return {\n type: \"function_call\" as const,\n call_id: c.callId,\n name: c.name,\n arguments: c.arguments,\n ...(Object.keys(gemini).length > 0 && { providerData: { gemini } }),\n }\n }),\n )\n\nexport const accumulatorToTurn = (acc: Accumulator): Turn => ({\n stop_reason:\n acc.functionCalls.length > 0 ? (\"tool_calls\" as const) : finishReasonToStop(acc.finishReason),\n usage: { ...acc.usage },\n items: [...reasoningItems(acc), ...assistantMessageItems(acc), ...functionCallItems(acc)],\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAyBA,MAAM,WAAW,OAAO,OAAO;CAC7B,MAAM,OAAO;;;;;;CAMb,SAAS,OAAO,SAAS,OAAO,OAAO;AACzC,CAAC;;;;;;;AAQD,MAAM,mBAAmB,OAAO,OAAO;CACrC,cAAc,OAAO,OAAO;EAC1B,IAAI,OAAO,SAAS,OAAO,MAAM;EACjC,MAAM,OAAO;EACb,MAAM,OAAO,SAAS,OAAO,OAAO;CACtC,CAAC;CAGD,kBAAkB,OAAO,SAAS,OAAO,MAAM;AACjD,CAAC;;;;;;;AAQD,MAAM,iBAAiB,OAAO,OAAO;CACnC,YAAY,OAAO,OAAO;EACxB,UAAU,OAAO,SAAS,OAAO,MAAM;EACvC,MAAM,OAAO;CACf,CAAC;CACD,SAAS,OAAO,SAAS,OAAO,OAAO;AACzC,CAAC;AAED,MAAM,OAAO,OAAO,MAAM;CAAC;CAAU;CAAkB;AAAc,CAAC;AAItE,MAAM,UAAU,OAAO,OAAO;CAC5B,MAAM,OAAO,SAAS,OAAO,MAAM;CACnC,OAAO,OAAO,SAAS,OAAO,MAAM,IAAI,CAAC;AAC3C,CAAC;AAOD,MAAM,iBAAiB,OAAO,OAAO,EACnC,KAAK,OAAO,SACV,OAAO,OACL,OAAO,OAAO;CACZ,KAAK,OAAO,SAAS,OAAO,OAAO,OAAO,MAAM,CAAC;CACjD,OAAO,OAAO,SAAS,OAAO,OAAO,OAAO,MAAM,CAAC;AACrD,CAAC,CACH,CACF,EACF,CAAC;AACD,MAAa,oBAAoB,OAAO,OAAO,EAC7C,iBAAiB,OAAO,SAAS,OAAO,OAAO,OAAO,MAAM,cAAc,CAAC,CAAC,EAC9E,CAAC;AAID,MAAM,mBAAmB,GAAe,MACtC,EAAE,SAAS,kBAAkB,EAAE,SAAS,kBAAkB,EAAE,QAAQ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AAsB,GAAG;EAAG,GAAG,kBAAkB,GAAG;CAAC;AAC1F"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { functionResponseBody } from "./codec.mjs";
|
|
2
|
+
import { c as it, n as globalExpect, s as describe } from "./index.C4tKZ0yW-DjxCdpW_.mjs";
|
|
3
|
+
import { imageBytes } from "@effect-uai/core/Image";
|
|
4
|
+
import * as Items from "@effect-uai/core/Items";
|
|
5
|
+
import { fileUrl } from "@effect-uai/core/File";
|
|
6
|
+
//#region src/codec.test.ts
|
|
7
|
+
const body = (output, isError) => functionResponseBody({
|
|
8
|
+
type: "function_call_output",
|
|
9
|
+
call_id: "c1",
|
|
10
|
+
output,
|
|
11
|
+
...isError !== void 0 && { isError }
|
|
12
|
+
});
|
|
13
|
+
describe("functionResponseBody", () => {
|
|
14
|
+
it("puts one JSON value under output as an object, never a string", () => {
|
|
15
|
+
globalExpect(body([Items.json({
|
|
16
|
+
city: "Lisbon",
|
|
17
|
+
temp: 18
|
|
18
|
+
})])).toEqual({ response: { output: {
|
|
19
|
+
city: "Lisbon",
|
|
20
|
+
temp: 18
|
|
21
|
+
} } });
|
|
22
|
+
});
|
|
23
|
+
it("puts a failure under error", () => {
|
|
24
|
+
globalExpect(body([Items.json({
|
|
25
|
+
_tag: "CityNotFound",
|
|
26
|
+
city: "Atlantis"
|
|
27
|
+
})], true)).toEqual({ response: { error: {
|
|
28
|
+
_tag: "CityNotFound",
|
|
29
|
+
city: "Atlantis"
|
|
30
|
+
} } });
|
|
31
|
+
});
|
|
32
|
+
it("keeps several values as an array and moves media to parts", () => {
|
|
33
|
+
globalExpect(body([
|
|
34
|
+
Items.text("Home"),
|
|
35
|
+
Items.json({ hits: 2 }),
|
|
36
|
+
Items.image(imageBytes(new Uint8Array([
|
|
37
|
+
1,
|
|
38
|
+
2,
|
|
39
|
+
3
|
|
40
|
+
]), "image/png")),
|
|
41
|
+
Items.file(fileUrl("gs://bucket/a.pdf", "application/pdf"), "a.pdf")
|
|
42
|
+
])).toEqual({
|
|
43
|
+
response: { output: ["Home", { hits: 2 }] },
|
|
44
|
+
parts: [{ inlineData: {
|
|
45
|
+
mimeType: "image/png",
|
|
46
|
+
data: "AQID"
|
|
47
|
+
} }, { fileData: {
|
|
48
|
+
fileUri: "gs://bucket/a.pdf",
|
|
49
|
+
mimeType: "application/pdf",
|
|
50
|
+
displayName: "a.pdf"
|
|
51
|
+
} }]
|
|
52
|
+
});
|
|
53
|
+
});
|
|
54
|
+
it("sends an empty response for media-only output", () => {
|
|
55
|
+
globalExpect(body([Items.image(imageBytes(new Uint8Array([1]), "image/png"))]).response).toEqual({});
|
|
56
|
+
});
|
|
57
|
+
});
|
|
58
|
+
//#endregion
|
|
59
|
+
export {};
|
|
60
|
+
|
|
61
|
+
//# sourceMappingURL=codec.test.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"codec.test.mjs","names":[],"sources":["../src/codec.test.ts"],"sourcesContent":["import { fileUrl } from \"@effect-uai/core/File\"\nimport { imageBytes } from \"@effect-uai/core/Image\"\nimport * as Items from \"@effect-uai/core/Items\"\nimport { describe, expect, it } from \"vitest\"\nimport { functionResponseBody } from \"./codec.js\"\n\nconst body = (output: Items.ToolCallOutput[\"output\"], isError?: boolean) =>\n functionResponseBody({\n type: \"function_call_output\",\n call_id: \"c1\",\n output,\n ...(isError !== undefined && { isError }),\n })\n\ndescribe(\"functionResponseBody\", () => {\n it(\"puts one JSON value under output as an object, never a string\", () => {\n expect(body([Items.json({ city: \"Lisbon\", temp: 18 })])).toEqual({\n response: { output: { city: \"Lisbon\", temp: 18 } },\n })\n })\n\n it(\"puts a failure under error\", () => {\n expect(body([Items.json({ _tag: \"CityNotFound\", city: \"Atlantis\" })], true)).toEqual({\n response: { error: { _tag: \"CityNotFound\", city: \"Atlantis\" } },\n })\n })\n\n it(\"keeps several values as an array and moves media to parts\", () => {\n expect(\n body([\n Items.text(\"Home\"),\n Items.json({ hits: 2 }),\n Items.image(imageBytes(new Uint8Array([1, 2, 3]), \"image/png\")),\n Items.file(fileUrl(\"gs://bucket/a.pdf\", \"application/pdf\"), \"a.pdf\"),\n ]),\n ).toEqual({\n response: { output: [\"Home\", { hits: 2 }] },\n parts: [\n { inlineData: { mimeType: \"image/png\", data: \"AQID\" } },\n {\n fileData: {\n fileUri: \"gs://bucket/a.pdf\",\n mimeType: \"application/pdf\",\n displayName: \"a.pdf\",\n },\n },\n ],\n })\n })\n\n it(\"sends an empty response for media-only output\", () => {\n expect(body([Items.image(imageBytes(new Uint8Array([1]), \"image/png\"))]).response).toEqual({})\n })\n})\n"],"mappings":";;;;;;AAMA,MAAM,QAAQ,QAAwC,YACpD,qBAAqB;CACnB,MAAM;CACN,SAAS;CACT;CACA,GAAI,YAAY,KAAA,KAAa,EAAE,QAAQ;AACzC,CAAC;AAEH,SAAS,8BAA8B;CACrC,GAAG,uEAAuE;EACxE,aAAO,KAAK,CAAC,MAAM,KAAK;GAAE,MAAM;GAAU,MAAM;EAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,EAC/D,UAAU,EAAE,QAAQ;GAAE,MAAM;GAAU,MAAM;EAAG,EAAE,EACnD,CAAC;CACH,CAAC;CAED,GAAG,oCAAoC;EACrC,aAAO,KAAK,CAAC,MAAM,KAAK;GAAE,MAAM;GAAgB,MAAM;EAAW,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,QAAQ,EACnF,UAAU,EAAE,OAAO;GAAE,MAAM;GAAgB,MAAM;EAAW,EAAE,EAChE,CAAC;CACH,CAAC;CAED,GAAG,mEAAmE;EACpE,aACE,KAAK;GACH,MAAM,KAAK,MAAM;GACjB,MAAM,KAAK,EAAE,MAAM,EAAE,CAAC;GACtB,MAAM,MAAM,WAAW,IAAI,WAAW;IAAC;IAAG;IAAG;GAAC,CAAC,GAAG,WAAW,CAAC;GAC9D,MAAM,KAAK,QAAQ,qBAAqB,iBAAiB,GAAG,OAAO;EACrE,CAAC,CACH,CAAC,CAAC,QAAQ;GACR,UAAU,EAAE,QAAQ,CAAC,QAAQ,EAAE,MAAM,EAAE,CAAC,EAAE;GAC1C,OAAO,CACL,EAAE,YAAY;IAAE,UAAU;IAAa,MAAM;GAAO,EAAE,GACtD,EACE,UAAU;IACR,SAAS;IACT,UAAU;IACV,aAAa;GACf,EACF,CACF;EACF,CAAC;CACH,CAAC;CAED,GAAG,uDAAuD;EACxD,aAAO,KAAK,CAAC,MAAM,MAAM,WAAW,IAAI,WAAW,CAAC,CAAC,CAAC,GAAG,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,QAAQ,CAAC,CAAC;CAC/F,CAAC;AACH,CAAC"}
|
|
@@ -10,6 +10,7 @@ const localTool = Tool.make({
|
|
|
10
10
|
name: "get_weather",
|
|
11
11
|
description: "Look up the weather.",
|
|
12
12
|
inputSchema: Tool.fromEffectSchema(Schema.Struct({ city: Schema.String })),
|
|
13
|
+
outputSchema: Schema.String,
|
|
13
14
|
run: ({ city }) => Effect.succeed(`sunny in ${city}`)
|
|
14
15
|
});
|
|
15
16
|
const build = (toolkit) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"geminiTools.test.mjs","names":["expect","Turn"],"sources":["../src/geminiTools.test.ts"],"sourcesContent":["import { Effect, Option, Result, Schema } from \"effect\"\nimport * as Tool from \"@effect-uai/core/Tool\"\nimport { descriptorsOf, providerToolsOf } from \"@effect-uai/core/Tool\"\nimport * as Turn from \"@effect-uai/core/Turn\"\nimport { describe, expect, it } from \"vitest\"\nimport {\n WireChunk,\n accumulatorToTurn,\n buildRequestBody,\n emptyAccumulator,\n ingestChunk,\n} from \"./codec.js\"\nimport { codeExecutionTool, googleSearchTool, renderProviderTools } from \"./GeminiTools.js\"\n\nconst localTool = Tool.make({\n name: \"get_weather\",\n description: \"Look up the weather.\",\n inputSchema: Tool.fromEffectSchema(Schema.Struct({ city: Schema.String })),\n run: ({ city }) => Effect.succeed(`sunny in ${city}`),\n})\n\nconst build = (toolkit: Record<string, Tool.AnyTool>) => {\n const entries = Result.getOrThrow(renderProviderTools(providerToolsOf(toolkit)))\n return buildRequestBody([], Option.none(), descriptorsOf(toolkit), entries)\n}\n\ndescribe(\"Gemini provider tools\", () => {\n it(\"renders google_search to the native googleSearch entry\", () => {\n const body = build({ google_search: googleSearchTool })\n expect(body.tools).toEqual([{ googleSearch: {} }])\n })\n\n it(\"renders a mixed toolkit to both a functionDeclarations entry and the native entry\", () => {\n const body = build({ get_weather: localTool, code_execution: codeExecutionTool })\n expect(body.tools).toEqual([\n {\n functionDeclarations: [\n expect.objectContaining({ name: \"get_weather\", description: \"Look up the weather.\" }),\n ],\n },\n { codeExecution: {} },\n ])\n })\n\n it(\"omits toolConfig for a grounding-only request (no forced function-calling mode)\", () => {\n const body = build({ google_search: googleSearchTool })\n expect(body.toolConfig).toBeUndefined()\n })\n\n it(\"sets toolConfig when a function declaration is present\", () => {\n const body = build({ get_weather: localTool, google_search: googleSearchTool })\n expect(body.toolConfig).toEqual({ functionCallingConfig: { mode: \"AUTO\" } })\n })\n\n it(\"fails on a foreign provider tool\", () => {\n const foreign = Tool.provider({\n name: \"web_search\",\n description: \"Anthropic web search.\",\n inputSchema: Tool.noInput,\n provider: \"anthropic\",\n config: { type: \"web_search_20250305\" },\n })\n const result = renderProviderTools(providerToolsOf({ web_search: foreign }))\n expect(Result.isFailure(result)).toBe(true)\n })\n\n it(\"fails on an unrecognized config kind\", () => {\n const bogus = Tool.provider({\n name: \"mystery\",\n description: \"Unknown Gemini tool.\",\n inputSchema: Tool.noInput,\n provider: \"gemini\",\n config: { kind: \"telepathy\" },\n })\n const result = renderProviderTools(providerToolsOf({ mystery: bogus }))\n expect(Result.isFailure(result)).toBe(true)\n })\n\n it(\"maps groundingMetadata chunks to url_citation annotations on the turn\", () => {\n const grounded = {\n candidates: [\n {\n content: { role: \"model\", parts: [{ text: \"Grounded answer.\" }] },\n groundingMetadata: {\n webSearchQueries: [\"effect ts\"],\n groundingChunks: [\n { web: { uri: \"https://example.com\", title: \"Example\" } },\n // Duplicate uri (de-duped) and a bare-domain title fallback.\n { web: { uri: \"https://example.com\", title: \"Example\" } },\n { web: { uri: \"https://effect.website\" } },\n ],\n },\n finishReason: \"STOP\",\n },\n ],\n }\n const chunk = Schema.decodeUnknownSync(WireChunk)(grounded)\n expect(chunk.candidates?.[0]?.content?.parts?.[0]).toEqual({ text: \"Grounded answer.\" })\n\n const turn = accumulatorToTurn(ingestChunk(emptyAccumulator, chunk).accumulator)\n expect(Turn.citations(turn)).toEqual([\n { type: \"url_citation\", url: \"https://example.com\", title: \"Example\" },\n { type: \"url_citation\", url: \"https://effect.website\", title: \"https://effect.website\" },\n ])\n })\n})\n"],"mappings":";;;;;;;;AAcA,MAAM,YAAY,KAAK,KAAK;CAC1B,MAAM;CACN,aAAa;CACb,aAAa,KAAK,iBAAiB,OAAO,OAAO,EAAE,MAAM,OAAO,OAAO,CAAC,CAAC;CACzE,MAAM,EAAE,WAAW,OAAO,QAAQ,YAAY,MAAM;AACtD,CAAC;AAED,MAAM,SAAS,YAA0C;CACvD,MAAM,UAAU,OAAO,WAAW,oBAAoB,gBAAgB,OAAO,CAAC,CAAC;CAC/E,OAAO,iBAAiB,CAAC,GAAG,OAAO,KAAK,GAAG,cAAc,OAAO,GAAG,OAAO;AAC5E;AAEA,SAAS,+BAA+B;CACtC,GAAG,gEAAgE;EACjE,MAAM,OAAO,MAAM,EAAE,eAAe,iBAAiB,CAAC;EACtD,aAAO,KAAK,KAAK,CAAC,CAAC,QAAQ,CAAC,EAAE,cAAc,CAAC,EAAE,CAAC,CAAC;CACnD,CAAC;CAED,GAAG,2FAA2F;EAC5F,MAAM,OAAO,MAAM;GAAE,aAAa;GAAW,gBAAgB;EAAkB,CAAC;EAChF,aAAO,KAAK,KAAK,CAAC,CAAC,QAAQ,CACzB,EACE,sBAAsB,CACpBA,aAAO,iBAAiB;GAA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uB,OAAO;KAAU,EAAE;KAExD,EAAE,KAAK;MAAE,KAAK;MAAuB,OAAO;KAAU,EAAE;KACxD,EAAE,KAAK,EAAE,KAAK,yBAAyB,EAAE;IAC3C;GACF;GACA,cAAc;EAChB,CACF,EAEuD,CAAC;EAC1D,aAAO,MAAM,aAAa,EAAE,EAAE,SAAS,QAAQ,EAAE,CAAC,CAAC,QAAQ,EAAE,MAAM,mBAAmB,CAAC;EAEvF,MAAM,OAAO,kBAAkB,YAAY,kBAAkB,KAAK,CAAC,CAAC,WAAW;EAC/E,aAAOC,OAAK,UAAU,IAAI,CAAC,CAAC,CAAC,QAAQ,CACnC;GAAE,MAAM;GAAgB,KAAK;GAAuB,OAAO;EAAU,GACrE;GAAE,MAAM;GAAgB,KAAK;GAA0B,OAAO;EAAyB,CACzF,CAAC;CACH,CAAC;AACH,CAAC"}
|
|
1
|
+
{"version":3,"file":"geminiTools.test.mjs","names":["expect","Turn"],"sources":["../src/geminiTools.test.ts"],"sourcesContent":["import { Effect, Option, Result, Schema } from \"effect\"\nimport * as Tool from \"@effect-uai/core/Tool\"\nimport { descriptorsOf, providerToolsOf } from \"@effect-uai/core/Tool\"\nimport * as Turn from \"@effect-uai/core/Turn\"\nimport { describe, expect, it } from \"vitest\"\nimport {\n WireChunk,\n accumulatorToTurn,\n buildRequestBody,\n emptyAccumulator,\n ingestChunk,\n} from \"./codec.js\"\nimport { codeExecutionTool, googleSearchTool, renderProviderTools } from \"./GeminiTools.js\"\n\nconst localTool = Tool.make({\n name: \"get_weather\",\n description: \"Look up the weather.\",\n inputSchema: Tool.fromEffectSchema(Schema.Struct({ city: Schema.String })),\n outputSchema: Schema.String,\n run: ({ city }) => Effect.succeed(`sunny in ${city}`),\n})\n\nconst build = (toolkit: Record<string, Tool.AnyTool>) => {\n const entries = Result.getOrThrow(renderProviderTools(providerToolsOf(toolkit)))\n return buildRequestBody([], Option.none(), descriptorsOf(toolkit), entries)\n}\n\ndescribe(\"Gemini provider tools\", () => {\n it(\"renders google_search to the native googleSearch entry\", () => {\n const body = build({ google_search: googleSearchTool })\n expect(body.tools).toEqual([{ googleSearch: {} }])\n })\n\n it(\"renders a mixed toolkit to both a functionDeclarations entry and the native entry\", () => {\n const body = build({ get_weather: localTool, code_execution: codeExecutionTool })\n expect(body.tools).toEqual([\n {\n functionDeclarations: [\n expect.objectContaining({ name: \"get_weather\", description: \"Look up the weather.\" }),\n ],\n },\n { codeExecution: {} },\n ])\n })\n\n it(\"omits toolConfig for a grounding-only request (no forced function-calling mode)\", () => {\n const body = build({ google_search: googleSearchTool })\n expect(body.toolConfig).toBeUndefined()\n })\n\n it(\"sets toolConfig when a function declaration is present\", () => {\n const body = build({ get_weather: localTool, google_search: googleSearchTool })\n expect(body.toolConfig).toEqual({ functionCallingConfig: { mode: \"AUTO\" } })\n })\n\n it(\"fails on a foreign provider tool\", () => {\n const foreign = Tool.provider({\n name: \"web_search\",\n description: \"Anthropic web search.\",\n inputSchema: Tool.noInput,\n provider: \"anthropic\",\n config: { type: \"web_search_20250305\" },\n })\n const result = renderProviderTools(providerToolsOf({ web_search: foreign }))\n expect(Result.isFailure(result)).toBe(true)\n })\n\n it(\"fails on an unrecognized config kind\", () => {\n const bogus = Tool.provider({\n name: \"mystery\",\n description: \"Unknown Gemini tool.\",\n inputSchema: Tool.noInput,\n provider: \"gemini\",\n config: { kind: \"telepathy\" },\n })\n const result = renderProviderTools(providerToolsOf({ mystery: bogus }))\n expect(Result.isFailure(result)).toBe(true)\n })\n\n it(\"maps groundingMetadata chunks to url_citation annotations on the turn\", () => {\n const grounded = {\n candidates: [\n {\n content: { role: \"model\", parts: [{ text: \"Grounded answer.\" }] },\n groundingMetadata: {\n webSearchQueries: [\"effect ts\"],\n groundingChunks: [\n { web: { uri: \"https://example.com\", title: \"Example\" } },\n // Duplicate uri (de-duped) and a bare-domain title fallback.\n { web: { uri: \"https://example.com\", title: \"Example\" } },\n { web: { uri: \"https://effect.website\" } },\n ],\n },\n finishReason: \"STOP\",\n },\n ],\n }\n const chunk = Schema.decodeUnknownSync(WireChunk)(grounded)\n expect(chunk.candidates?.[0]?.content?.parts?.[0]).toEqual({ text: \"Grounded answer.\" })\n\n const turn = accumulatorToTurn(ingestChunk(emptyAccumulator, chunk).accumulator)\n expect(Turn.citations(turn)).toEqual([\n { type: \"url_citation\", url: \"https://example.com\", title: \"Example\" },\n { type: \"url_citation\", url: \"https://effect.website\", title: \"https://effect.website\" },\n ])\n })\n})\n"],"mappings":";;;;;;;;AAcA,MAAM,YAAY,KAAK,KAAK;CAC1B,MAAM;CACN,aAAa;CACb,aAAa,KAAK,iBAAiB,OAAO,OAAO,EAAE,MAAM,OAAO,OAAO,CAAC,CAAC;CACzE,cAAc,OAAO;CACrB,MAAM,EAAE,WAAW,OAAO,QAAQ,YAAY,MAAM;AACtD,CAAC;AAED,MAAM,SAAS,YAA0C;CACvD,MAAM,UAAU,OAAO,WAAW,oBAAoB,gBAAgB,OAAO,CAAC,CAAC;CAC/E,OAAO,iBAAiB,CAAC,GAAG,OAAO,KAAK,GAAG,cAAc,OAAO,GAAG,OAAO;AAC5E;AAEA,SAAS,+BAA+B;CACtC,GAAG,gEAAgE;EACjE,MAAM,OAAO,MAAM,EAAE,eAAe,iBAAiB,CAAC;EACtD,aAAO,KAAK,KAAK,CAAC,CAAC,QAAQ,CAAC,EAAE,cAAc,CAAC,EAAE,CAAC,CAAC;CACnD,CAAC;CAED,GAAG,2FAA2F;EAC5F,MAAM,OAAO,MAAM;GAAE,aAAa;GAAW,gBAAgB;EAAkB,CAAC;EAChF,aAAO,KAAK,KAAK,CAAC,CAAC,QAAQ,CACzB,EACE,sBAAsB,CACpBA,aAAO,iBAAiB;GAAE,MAAM;GAAe,aAAa;EAAuB,CAAC,CACtF,EACF,GACA,EAAE,eAAe,CAAC,EAAE,CACtB,CAAC;CACH,CAAC;CAED,GAAG,yFAAyF;EAC1F,MAAM,OAAO,MAAM,EAAE,eAAe,iBAAiB,CAAC;EACtD,aAAO,KAAK,UAA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AAa,EAAE,EAAE,SAAS,QAAQ,EAAE,CAAC,CAAC,QAAQ,EAAE,MAAM,mBAAmB,CAAC;EAEvF,MAAM,OAAO,kBAAkB,YAAY,kBAAkB,KAAK,CAAC,CAAC,WAAW;EAC/E,aAAOC,OAAK,UAAU,IAAI,CAAC,CAAC,CAAC,QAAQ,CACnC;GAAE,MAAM;GAAgB,KAAK;GAAuB,OAAO;EAAU,GACrE;GAAE,MAAM;GAAgB,KAAK;GAA0B,OAAO;EAAyB,CACzF,CAAC;CACH,CAAC;AACH,CAAC"}
|
package/dist/realtimeSession.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { functionResponseBody, toolDescriptorsToTools } from "./codec.mjs";
|
|
2
2
|
import { Cause, Duration, Effect, Match, Pull, Queue, Redacted, Ref, Result, Schema, Stream } from "effect";
|
|
3
3
|
import * as AiError from "@effect-uai/core/AiError";
|
|
4
4
|
import { Base64 } from "effect/encoding";
|
|
@@ -328,7 +328,7 @@ const handleInput = (send, state, options, input) => Match.value(input).pipe(Mat
|
|
|
328
328
|
yield* send(JSON.stringify({ toolResponse: { functionResponses: [{
|
|
329
329
|
id: i.output.call_id,
|
|
330
330
|
name,
|
|
331
|
-
|
|
331
|
+
...functionResponseBody(i.output),
|
|
332
332
|
scheduling: options.scheduling
|
|
333
333
|
}] } }));
|
|
334
334
|
})), Match.tag("Interrupt", () => Effect.fail(new AiError.Unsupported({
|