Module ai.google.gemini
ballerinax/ai.google.gemini Ballerina library
Overview
Google Gemini is a family of multimodal large language models that support text generation, reasoning, function calling, and embeddings.
The ai.google.gemini connector plugs Gemini into the ai agent framework. It implements the framework's ModelProvider and EmbeddingProvider interfaces, so any agent built with the ai module can use Gemini for chat, structured generation, and embeddings.
Key features
- Connect and interact with Gemini large language models
- Native tool/function calling
- Structured output via Gemini's native JSON mode (
responseJsonSchema) - Multimodal input — images, PDFs, and Gemini File API references, through
generate - Text and embedding model support (
embed/batchEmbed) - Secure communication using API-key authentication
Scope and limitations
chataccepts text only. Images, PDFs, and other documents are supported throughgenerate(see Multimodal input); passing a non-textai:Documenttochatreturns an error.- Streaming is not available. The
ai:ModelProviderinterface defines onlychatandgenerate, so there is no streaming API to implement. - Gemini Developer API only. Vertex AI endpoints (
{location}-aiplatform.googleapis.com, OAuth bearer credentials,publishers/google/models/...paths) are not supported. - Document URLs are fetched by the connector. Gemini cannot fetch arbitrary web URLs, so an
ai:Urlin a prompt is downloaded locally and sent inline. Onlyhttpandhttpsare accepted, including on every redirect hop. No restriction is placed on the destination host: a URL that resolves to a loopback, private, link-local, or other internal address (including cloud metadata endpoints) is fetched the same as any public one. Applications that accept document URLs from untrusted end users are responsible for validating or restricting those URLs before passing them to this connector, or for enforcing an egress policy at the network layer.
Prerequisites
Before using this module, obtain the configuration required to engage the LLM.
- Create a Google account and sign in to Google AI Studio.
- Generate an API key from Google AI Studio.
Quickstart
To use the ai.google.gemini module in your Ballerina application, update the .bal file as follows:
Step 1: Import the module
import ballerinax/ai.google.gemini;
Step 2: Initialize the Model Provider
import ballerina/ai; import ballerinax/ai.google.gemini; final ai:ModelProvider geminiModel = check new gemini:ModelProvider("<API_KEY>", gemini:GEMINI_3_8_FLASH);
Step 3: Invoke the model
import ballerina/ai; import ballerina/io; import ballerinax/ai.google.gemini; public function main() returns error? { ai:ChatAssistantMessage response = check geminiModel->chat( [{role: ai:USER, content: "Explain Ballerina in one sentence."}], []); io:println(response.content); }
Using the Embedding Provider
import ballerina/ai; import ballerinax/ai.google.gemini; final ai:EmbeddingProvider embeddingModel = check new gemini:EmbeddingProvider("<API_KEY>", gemini:GEMINI_EMBEDDING_2); public function main() returns error? { ai:TextChunk chunk = {content: "Ballerina is a cloud-native language."}; ai:Embedding embedding = check embeddingModel->embed(chunk); }
Multimodal input
Images, PDFs, and files already uploaded to the Gemini File API can be sent through generate:
import ballerina/ai; import ballerinax/ai.google.gemini; public function main() returns error? { ai:ImageDocument image = {content: "https://example.com/chart.png"}; string description = check geminiModel->generate(`Describe this image: ${image}`); }
When a document is supplied as a URL, the connector downloads it and forwards the bytes inline — Gemini does not fetch arbitrary web URLs itself. Two consequences:
- The download is an outbound request from your service to a caller-influenced address. Treat prompt-supplied URLs as untrusted input.
- Documents larger than 20 MiB are rejected, matching Gemini's inline-request ceiling.
To avoid the download entirely, upload via the Gemini File API and pass the resulting ai:FileId.
Model selection
GEMINI_3_8_FLASH is the recommended default. The GEMINI_MODEL_NAMES enum documents the status of every supported model, including announced shutdown dates — GEMINI_3_1_FLASH_LITE retires on 2027-05-07.
GEMINI_2_5_PRO, GEMINI_2_5_FLASH and GEMINI_2_5_FLASH_LITE are deprecated. Google retired these models on 2026-10-16, so requests to them fail. They will be removed in the next major release.
GEMINI_4_ARGON is Google's flagship reasoning model. It is available on the paid tier only (the free tier has no quota for it, and calls fail with a 429), and it is noticeably slower than the Flash models. The default HTTP timeout is 60 seconds, so raise it for non-trivial prompts:
final ai:ModelProvider argon = check new gemini:ModelProvider( "<API_KEY>", gemini:GEMINI_4_ARGON, timeout = 300 );
For embeddings, GEMINI_EMBEDDING_2 is the current model. GEMINI_EMBEDDING_001 remains supported for text-only use cases.
Note: the embedding spaces of the two embedding models are not compatible. Switching between them requires re-embedding all previously stored data.
Generation settings
Thinking tokens and maxTokens
Gemini 3 models and later perform internal reasoning by default, and reasoning tokens are billed against maxOutputTokens. A small token cap can therefore be consumed entirely by reasoning, returning a response with finishReason MAX_TOKENS and no text at all.
maxTokens defaults to 65,536 — the models' own maximum output limit — so this does not happen out of the box. It is a ceiling, not a target: billing follows the tokens actually produced.
Thinking level
thinkingLevel sets how much internal reasoning the model performs before answering: gemini:LOW, gemini:MEDIUM or gemini:HIGH. It is unset by default, so the model's own default (MEDIUM on current models) applies. Higher levels can improve answers on complex tasks at the cost of latency and billed thinking tokens.
final ai:ModelProvider geminiModel = check new gemini:ModelProvider( "<API_KEY>", gemini:GEMINI_3_8_FLASH, thinkingLevel = gemini:LOW );
Gemini's minimal level is not offered, because GEMINI_3_8_FLASH, GEMINI_4_ARGON and GEMINI_3_1_PRO_PREVIEW reject it.
Temperature
temperature is unset by default, so the model's own default applies. Google strongly recommends leaving it at the default of 1.0 for Gemini 3 models — lowering it "may lead to unexpected behavior, such as looping or degraded performance, particularly in complex mathematical or reasoning tasks."
On GEMINI_3_8_FLASH and GEMINI_4_ARGON, Google deprecates temperature in favour of thinkingLevel. Both models still accept a value in the valid range of 0.0–2.0, so setting it does not cause an error, but the connector logs a warning when the provider is created with a temperature for either model. Use thinkingLevel to tune these models.
Schemas
Tool parameters and structured-output schemas are sent through Gemini's standard-JSON-Schema fields (parametersJsonSchema and responseJsonSchema), which accept $ref, $defs, additionalProperties, title, and prefixItems. Only the oneOf and allOf combinators are rewritten, to the documented anyOf.
Authentication
The first argument, apiKey, sets how the connector authenticates with the Gemini API. It keeps its name so that existing code still compiles, but it accepts any of the following. The same options apply to gemini:EmbeddingProvider.
-
API key (
string): sent in thex-goog-api-keyheader. This is the simplest option. -
OAuth 2.0 with a refresh token (
gemini:OAuth2RefreshConfig): the connector exchanges the refresh token for a short-lived access token, sends it in theAuthorization: Bearerheader, and gets a new one before it expires. The first access token is requested when the provider is created, so invalid credentials fail at initialization. Create a desktop OAuth client in your Google Cloud project, then rungcloud auth application-default login --client-id-file=client_secret.json --scopes=https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/generative-language.retriever. The client ID, client secret, and refresh token are stored in~/.config/gcloud/application_default_credentials.json. SetquotaProjectIdto the project to bill, sent in thex-goog-user-projectheader. See Authentication with OAuth.A refresh token stops working when it is revoked or unused for six months. It also expires after 7 days while the OAuth app's publishing status is Testing, and a Google Workspace session length policy can make the user sign in again. For a long-running server, publish the OAuth app (In production) and check your Workspace policy.
final ai:ModelProvider geminiModel = check new gemini:ModelProvider({ clientId: "<client ID>", clientSecret: "<client secret>", refreshToken: "<refresh token>", quotaProjectId: "<Google Cloud project ID>" }, gemini:GEMINI_3_8_FLASH); -
OAuth 2.0 access token (
gemini:BearerTokenConfig): an access token obtained elsewhere, for example withgcloud auth application-default print-access-token, sent in theAuthorization: Bearerheader. SetquotaProjectIdwhen the token was issued to an OAuth client of another project, such as thegclouddefault client, or the Gemini API rejects it. The connector does not refresh the token, so requests fail once it expires (after about an hour).final ai:ModelProvider geminiModel = check new gemini:ModelProvider( {token: "<access token>", quotaProjectId: "<Google Cloud project ID>"}, gemini:GEMINI_3_8_FLASH);
Note: the API key is sent in a custom header, not through
http:ClientAuthConfig, so HTTP trace or access logs record it. They also record OAuth access tokens. Avoid trace logging in production.
Rate limits and retries
Gemini enforces per-model rate limits; exceeding them returns a 429 with status RESOURCE_EXHAUSTED, which the connector surfaces as an error naming that status.
No retry policy is applied by default, because generateContent is a billed, non-idempotent request and silent retries could duplicate a charged generation. To opt in, supply a retryConfig through the connection configuration:
final ai:ModelProvider geminiModel = check new gemini:ModelProvider( "<API_KEY>", gemini:GEMINI_3_8_FLASH, retryConfig = {count: 3, interval: 2, statusCodes: [429, 503]} );
Report issues
To report bugs, request new features, start new discussions, view project roadmaps, and track issues, go to the Ballerina library parent repository.
Useful links
- Chat live with us on our Discord server.
- Post technical questions on Stack Overflow with the #ballerina tag.
- For more information go to the
ai.google.geminipackage.