genkit_google_genai 1.2.0
genkit_google_genai: ^1.2.0 copied to clipboard
Google AI plugin for Genkit Dart.
Google AI plugin for Genkit Dart.
Building with a coding agent? Install the Genkit Dart skill first.
npx skills add genkit-ai/skills --skill developing-genkit-dartIt teaches your agent the current Genkit Dart APIs and common gotchas. Source, manual install and skills for other languages: genkit-ai/skills.
Usage #
import 'package:genkit/genkit.dart';
import 'package:genkit_google_genai/genkit_google_genai.dart';
void main() async {
// Initialize Genkit with the Google AI plugin
final ai = Genkit(plugins: [googleAI()]);
// Generate text
final response = await ai.generate(
model: googleAI.gemini('gemini-flash-latest'),
prompt: 'Tell me a joke about a developer.',
);
print(response.text);
}
Tool Calling #
import 'package:genkit/genkit.dart';
import 'package:genkit_google_genai/genkit_google_genai.dart';
part 'main.g.dart';
@Schema()
abstract class $WeatherToolInput {
String get location;
}
void main() async {
final ai = Genkit(plugins: [googleAI()]);
ai.defineTool(
name: 'getWeather',
description: 'Get the weather for a location',
inputSchema: WeatherToolInput.$schema,
fn: (input, context) async {
return .response('The weather in ${input.location} is 75 and sunny.');
},
);
final response = await ai.generate(
model: googleAI.gemini('gemini-flash-latest'),
prompt: 'What is the weather in Boston?',
toolNames: ['getWeather'],
);
print(response.text);
}
Embeddings #
import 'package:genkit/genkit.dart';
import 'package:genkit_google_genai/genkit_google_genai.dart';
void main() async {
final ai = Genkit(plugins: [googleAI()]);
final embeddings = await ai.embed(
embedder: googleAI.textEmbedding('gemini-embedding-001'),
documents: [
DocumentData(content: [TextPart(text: 'Hello world')]),
DocumentData(content: [TextPart(text: 'Genkit is awesome')]),
],
);
print(embeddings[0].embedding);
}
gemini-embedding-2 also embeds images and videos (as MediaParts).
Built-in tools #
Google Search, code execution, URL context and file search have their own
options; other built-in tools go in tools as maps. Name the tool with its
camelCase key ({'googleMaps': {...}}): that form works on every model,
whichever API it's called through. A map with its own type ({'type': 'google_maps'}) only works on models called through the Interactions API
(see below). For Google Maps, set the user's location with
retrievalConfig:
final response = await ai.generate(
model: googleAI.gemini('gemini-flash-latest'),
prompt: 'Describe some sights near me',
config: GeminiOptions(
tools: [
{
'googleMaps': {'enableWidget': true},
},
],
retrievalConfig: GeminiRetrievalConfig(
latLng: GeminiLatLng(latitude: 43.0896, longitude: -79.0849),
),
),
);
final response = await ai.generate(
model: googleAI.gemini('gemini-flash-latest'),
prompt: 'Summarize https://genkit.dev',
config: GeminiOptions(urlContext: GeminiUrlContext()),
);
Image generation #
final response = await ai.generate(
model: googleAI.geminiImage('gemini-nano-banana-2.1'),
prompt: 'A watercolor painting of a castle in the mountains.',
config: GeminiImageOptions(
imageConfig: GeminiImageConfig(aspectRatio: '16:9', imageSize: '2K'),
),
);
final image = response.media;
Video generation (Gemini Omni) #
final response = await ai.generate(
model: googleAI.geminiVideo('gemini-omni-1.1-flash'),
prompt: 'An origami butterfly flaps its wings and flies out of the window.',
config: GeminiVideoOptions(
videoFormat: GeminiVideoFormat(aspectRatio: '16:9', resolution: '720p'),
),
);
// An MP4 video (video/mp4), returned inline as a data URL.
final video = response.media;
ai.generate()returns the video directly (it isn't a long-running operation).- Images and videos in the prompt are used as inputs (image to video, first and last frame, subject references, editing or extending a video).
videoFormatsetsaspectRatio(16:9, the default, or9:16) andresolution(360p,720p(the default),1080por4k).delivery: 'uri'returns a Files API URI instead of inline data, which is recommended for large videos; it requiresstore: true.videoConfig.task(text_to_video,image_to_video,reference_to_video,edit,extend) tells the model which kind of generation to do; without it, the model infers it from the prompt.- To edit a generated video in a follow-up turn, set
store: trueand pass the previous response's messages. - Tools aren't supported.
Music generation (Lyria) #
final response = await ai.generate(
model: googleAI.lyria('lyria-3-clip-preview'),
prompt: 'A cheerful acoustic folk song with guitar and harmonica.',
);
final music = response.media; // the audio
final lyrics = response.text; // the lyrics or a caption
lyria-3.5 and lyria-3-pro-preview make full-length songs; images in the
prompt are used as inspiration. As with the Gemini models on the
Interactions API, calls aren't stored on the server unless store: true is
set (in LyriaOptions or googleAI(store: true)).
Antigravity agent #
final response = await ai.generate(
model: googleAI.antigravity('antigravity-preview-09-2026'),
prompt: 'Read Hacker News, summarize the top 10 stories.',
// The sandbox the agent works in.
config: AntigravityOptions(environment: 'remote'),
);
- The agent keeps the conversation on the server. Passing
messages: previousResponse.messagescontinues it in the same sandbox (the plugin sends the interaction and environment IDs from the last response). - Without
tools, the agent uses its default tools; withtools: [{'type': 'google_search'}]it uses only those. Your own Genkit tools work too. modelpicks the Gemini model the agent runs on (e.g.gemini-4-argon).storeis only sent when you set it: the agent needs stored interactions, sostore: falseis rejected by the server.- System messages are sent as user messages (the agent has no system instruction).
Interactions API and response.raw #
Newer Gemini models are called through Google's Interactions API
(/v1beta/interactions) instead of the older generateContent API.
Model routing #
Gemini and Gemma models use the Interactions API, including the -latest
aliases and any model not listed below. Only these older models still use
generateContent, until they are retired:
gemini-3.5-flashgemini-3.1-flash-litegemini-3.1-pro-previewgemini-3.1-pro-preview-customtoolsgemini-3-flash-previewgemini-2.5-progemini-2.5-flashgemini-2.5-flash-litegemini-3.1-flash-imagegemini-3-pro-imagegemini-2.5-flash-imagegemini-2.5-flash-preview-ttsgemini-2.5-pro-preview-ttsgemini-3.1-flash-tts-previewgemma-4-26b-a4b-itgemma-4-31b-it
Standard Genkit output vs. response.raw #
response.text, response.reasoning, response.message, response.media,
streaming and tool calling work the same way on both APIs.
If your code reads the provider payload in response.raw, it differs:
generateContent: aGenerateContentResponsewithcandidates[]. Grounding metadata is oncandidates[0].groundingMetadata.- Interactions API: an interaction with
id,statusand asteps[]timeline. Server-side tool calls and results (Google Search, code execution, ...) are explicit steps (google_search_call,code_execution_call, ...), and grounding citations are annotations on the text content of themodel_outputstep.
Differences on the Interactions API #
- Safety settings: sent as the Interactions API's
safety_settings(see Gemini API safety settings).BLOCK_NONEis sent asoff, which means the same there (the Gemini API doesn't acceptblock_none).HARM_CATEGORY_UNSPECIFIEDentries are left out. - Options the Interactions API doesn't use:
topK,presencePenalty,frequencyPenalty,responseMimeType(other thanapplication/json) andthinkingConfig.thinkingBudget(usethinkingLevel) are not sent; each is logged once per model as a warning. This includesthinkingBudget: 0: these models can't turn thinking off, so for the least thinking setthinkingLevelto the model's lowest level (LOW, orMINIMALwhere the model supports it).candidateCountabove 1 is warned about too: one candidate is returned.temperatureandtopPare still sent, although newer models ignore them.responseMimeType: 'application/json'asks for JSON output, as ongenerateContent. - Stateless by default: the plugin sends
store: false, so nothing is kept on Google's servers. To store interactions, setGeminiOptions(store: true)on a request, orgoogleAI(store: true)for every request (a request's ownstore,trueorfalse, wins over the plugin option). A stored interaction's ID is inresponse.message?.metadata?['interactionId']; passingmessages: previousResponse.messageswithstore: truecontinues that interaction and sends only the new messages. SettingpreviousInteractionIdyourself also requiresstore: true(otherwise it throwsINVALID_ARGUMENT). On models that usegenerateContent,storeonly controls whether the server logs the request for your project (viewable in AI Studio's Logs and Datasets): it's sent as is when you set it (request config orgoogleAI(store: ...)), and otherwise your project's logging setting applies. - Service tier:
GeminiOptions(serviceTier: 'flex')(orstandard,priority) works on both APIs. - Text-to-speech: the
gemini-3.8-flash-ttsandgemini-3.8-flash-lite-ttsmodels return a complete WAV file (audio/wav). Streamed, they send raw PCM chunks (audio/l16, 24 kHz, mono, 16-bit), joined into one part in the final response. To choose the format, setGeminiTtsOptions(audioFormat: GeminiAudioFormat(mimeType: 'audio/wav'))(audio/wav,audio/l16,audio/mulaworaudio/alaw); requestaudio/wavwhen streaming to get a playable file at the end. For several speakers, each turn is a separate text part that names its speaker:TextPart(text: '...', metadata: {'speechMetadata': {'speaker': 'Joe'}})(an optionalstylesets how it's spoken). - Built-in tools:
toolsmaps and the tool options are sent as Interactions tools (e.g.{'googleMaps': {}}becomes agoogle_mapstool); a map with its owntypeis sent as is.retrievalConfig.latLngis set on the Google Maps tool (there's no retrieval config on this API); otherretrievalConfigfields are ignored with a warning.audioFormat,videoFormatandvideoConfigonly work on these models (they're ignored with a warning ongenerateContent). The vertexAI-only options (location,labels,vertexRetrieval,payGo,videoFormat.gcsUri) are ignored with a warning on both APIs. - Streaming: text, media and thought summaries stream as they arrive.
A server-side tool step (Google Search, code execution, ...) streams as
one complete part when the step ends, and a function call streams as a
complete tool request when the response ends. With structured output,
chunk.outputis null for chunks it can't parse yet (or that have no JSON text, such as thoughts or tool calls), so check it before use. - Usage:
response.usagehas the token totals (inputTokens,outputTokens,thoughtsTokens, ...). Token counts per modality are inresponse.usage?.custom(e.g.inputTextTokens,inputImageTokens,outputAudioTokens), and tool-use tokens inresponse.usage?.custom?['toolUseTokens'](also ongenerateContent, which still reports the oldertoolUsePromptTokenCountkey too). Grounding tool use is counted there too (e.g.googleSearchCount).