import { MediaPart, JSONSchema, ModelReference, z, EmbedderReference, StatusName } from 'genkit'; import { GenerateRequest } from 'genkit/model'; import { InteractionStreamResult } from './interaction-types.js'; import { GenerateContentResponse, GenerateContentStreamResult } from './types.js'; /** * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * `Api-Revision` header value for Interactions API requests. It selects the * steps-based schema (`steps` in responses, step list input) that the * Interactions converters read and write; without it the server uses the * older `outputs` / turn list schema. */ declare const INTERACTIONS_API_REVISION = "2026-05-20"; declare function buildTraceMetadataInput(url: string, fetchOptions: RequestInit, traceOptions: { request?: unknown; model?: string; clientOptions?: { timeout?: number; }; }): Record; /** * Safely extracts the error message from the error. * @param e The error * @returns The error message */ declare function extractErrMsg(e: unknown): string; /** * Custom replacer function for JSON.stringify to truncate long string fields. * Truncates strings to the first 100 and last 10 characters * if the original string is longer than 110 characters. * * @param key The key of the property being stringified. * @param value The value of the property being stringified. * @return The transformed value, or the original value if no transformation is needed. */ declare function stringTruncator(key: string, value: unknown): unknown; /** * Gets the un-prefixed model name from a modelReference */ declare function extractVersion(model: ModelReference | EmbedderReference): string; /** * Gets the model name without certain prefixes.. * e.g. for "models/googleai/gemini-2.5-pro" it returns just 'gemini-2.5-pro' * @param name A string containing the model string with possible prefixes * @returns the model string stripped of certain prefixes */ declare function modelName(name?: string): string | undefined; /** * Gets the suffix of a model string. * Throws if the string is empty. * @param name A string containing the model string * @returns the model string stripped of prefixes and guaranteed not empty. */ declare function checkModelName(name?: string): string; declare function extractText(request: GenerateRequest): string; declare function extractMimeType(url?: string): string; declare function checkSupportedMimeType(media: MediaPart['media'], supportedTypes: string[]): void; /** * * @param url The url to show (e.g. in an error message) * @returns The appropriately sized url */ declare function displayUrl(url: string): string; /** * * @param request A generate request to extract from * @param metadataType The media must have metadata matching this type if isDefault is false * @param isDefault 'true' allows missing metadata type to match as well. * @returns */ declare function extractMedia(request: GenerateRequest, params: { metadataType?: string; isDefault?: boolean; }): MediaPart['media'] | undefined; /** * * @param request A generate request to extract from * @param metadataType The media must have metadata matching this type if isDefault is false * @param isDefault 'true' allows missing metadata type to match as well. * @returns */ declare function extractMediaArray(request: GenerateRequest, params: { metadataType?: string; isDefault?: boolean; }): MediaPart[] | undefined; /** * Cleans a JSON schema by removing specific keys and standardizing types. * * @param {JSONSchema} schema The JSON schema to clean. * @returns {JSONSchema} The cleaned JSON schema. */ declare function cleanSchema(schema: JSONSchema): JSONSchema; /** * Reports whether an Interactions API error code is a content-policy block * (safety, recitation, blocklist, etc.). * * @param code The `code` field from an Interactions API error. */ declare function isInteractionContentBlockCode(code: unknown): boolean; /** * Maps an Interactions API error `code` to a Genkit `StatusName`. * * Looks the code up (case-insensitively) in the known Interactions error codes. * Also accepts numeric HTTP codes (e.g. `503` or `"503"`), in case the front * end returns a Google-style error body instead. * * @param code The `code` field from an Interactions API error. * @returns The matching `StatusName`, or `undefined` if it cannot be mapped. */ declare function interactionErrorCodeToGenkitStatus(code: unknown): StatusName | undefined; /** * Builds an error for leftover, unparsed Interactions stream text. When the * model is overloaded (or otherwise fails), the API may return a plain JSON * error body (e.g. `{"error":{"code":"service_unavailable","message":"..."}}`) * instead of SSE `data:` frames. Surfacing a `GenkitError` with the correct * status lets downstream middleware (e.g. retry) react appropriately. * * @param text The leftover text that could not be parsed as an SSE event. * @returns A `GenkitError` if the text is a recognizable API error body, * otherwise a generic `Error`. */ declare function parseInteractionStreamErrorText(text: string): Error; declare function interactionProcessStream(response: Response): InteractionStreamResult; /** * Maps an HTTP status code to the corresponding Genkit `StatusName`. * * @param code The HTTP status code. * @returns The matching `StatusName`, or `'UNKNOWN'` if there is no mapping. */ declare function httpStatusToGenkitStatus(code?: number): StatusName; /** Reports whether every element of an array is a string. */ declare function isStringArray(values: unknown[]): values is string[]; /** * Warns (once per model and field) that a config field isn't supported by the * model and was ignored. */ declare function warnDroppedConfigField(model: string, field: string): void; /** * Reports whether a URL targets the Interactions API, i.e. its path contains * an `interactions` segment. */ declare function isInteractionUrl(url: string): boolean; /** * Builds an error for leftover, unparsed stream text. When the model API is * overloaded (or otherwise fails), it may return HTTP 200 with a plain JSON * error body instead of SSE `data:` frames. In that case we surface a proper * `GenkitError` with the correct status so downstream middleware (e.g. retry) * can react appropriately, rather than a generic parse error. * * @param text The leftover text that could not be parsed as a stream chunk. * @returns A `GenkitError` if the text is a recognizable API error body, * otherwise a generic `Error`. */ declare function parseStreamErrorText(text: string): Error; /** * Processes the streaming body of a Response object. It decodes the stream as * UTF-8 text, parses JSON objects from specially formatted lines (e.g., "data: {}"), * and returns both an async generator for individual responses and a promise * that resolves to the aggregated final response. * * @param response The Response object with a streaming body. * @returns An object containing: * - stream: An AsyncGenerator yielding each GenerateContentResponse. * - response: A Promise resolving to the aggregated GenerateContentResponse. */ declare function processStream(response: Response): GenerateContentStreamResult; declare function aggregateResponses(responses: GenerateContentResponse[]): GenerateContentResponse; declare function getGenkitClientHeader(): string; /** * Copies headers into a plain object, leaving out the named headers in any * letter case. Header names are case-insensitive, but object keys aren't: * without this, a custom `api-revision` would sit next to the plugin's * `Api-Revision` and fetch would send both values. * * @param headers The headers to copy (e.g. user-provided custom headers). * @param names The header names to leave out. */ declare function withoutHeaders(headers: Record | Headers | undefined, names: string[]): Record; declare function isKnownKey(key: string | number | symbol, obj: T): key is keyof T; /** * Parses the value of a `Retry-After` HTTP header into milliseconds. * Supports both delay-seconds (e.g. "60") and HTTP-date formats * (e.g. "Mon, 19 May 2026 12:00:00 GMT") per RFC 7231 ยง7.1.3. * * @param value The raw Retry-After header value. * @returns The delay in milliseconds, or undefined if the value cannot be parsed. */ declare function parseRetryAfterMs(value: string): number | undefined; /** * Converts a string in camelCase to lowercase snake_case. */ declare function camelToSnakeCase(str: string): string; declare function convertObjectKeysToSnakeCase(obj: Array): unknown[]; declare function convertObjectKeysToSnakeCase(obj: Record): Record; declare function convertObjectKeysToSnakeCase(obj: unknown): unknown; declare function toSnakeCaseObj(val: unknown): Record; /** * Inserts raw audio bytes at the end of a WAV file's `data` chunk and updates * the RIFF and `data` sizes. Chunks after `data` (the server sends one) stay * after the audio. Returns `undefined` if `wav` isn't a WAV file with a * `data` chunk. */ declare function appendToWavData(wav: Buffer, audio: Buffer): Buffer | undefined; /** * Returns `bytes` without any ID3v2 tags at the start. A tag is only removed * if its header is valid ("ID3", version 2-4, size bytes below 0x80) and the * whole tag fits in `bytes`; otherwise `bytes` is returned unchanged. */ declare function stripLeadingId3Tags(bytes: Buffer): Buffer; declare const TEST_ONLY: { aggregateResponses: typeof aggregateResponses; }; export { INTERACTIONS_API_REVISION, TEST_ONLY, appendToWavData, buildTraceMetadataInput, camelToSnakeCase, checkModelName, checkSupportedMimeType, cleanSchema, convertObjectKeysToSnakeCase, displayUrl, extractErrMsg, extractMedia, extractMediaArray, extractMimeType, extractText, extractVersion, getGenkitClientHeader, httpStatusToGenkitStatus, interactionErrorCodeToGenkitStatus, interactionProcessStream, isInteractionContentBlockCode, isInteractionUrl, isKnownKey, isStringArray, modelName, parseInteractionStreamErrorText, parseRetryAfterMs, parseStreamErrorText, processStream, stringTruncator, stripLeadingId3Tags, toSnakeCaseObj, warnDroppedConfigField, withoutHeaders };