Skip to content
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/genkit_google_genai/lib/genkit_google_genai.dart
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ class GoogleGenAiPluginHandle {
return modelRef('googleai/$name', customOptions: GeminiOptions.$schema);
}

ModelRef<GemmaOptions> gemma(String name) {
return modelRef('googleai/$name', customOptions: GemmaOptions.$schema);
}

EmbedderRef<TextEmbedderOptions> textEmbedding(String name) {
return embedderRef(
'googleai/$name',
Expand Down
38 changes: 32 additions & 6 deletions packages/genkit_google_genai/lib/src/common_plugin.dart
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import 'package:schemantic/schemantic.dart';

import 'aggregation.dart';
import 'api_client.dart';
import 'gemma.dart';
import 'generated/generativelanguage.dart' as gcl;
import 'model.dart';

Expand All @@ -40,11 +41,16 @@ final commonModelInfo = ModelInfo(
abstract class CommonGoogleGenPlugin extends GenkitPlugin {
Future<GenerativeLanguageBaseClient> getApiClient([String? requestApiKey]);

Model createModel(String modelName, SchemanticType customOptions) {
Model createModel(
String modelName,
SchemanticType customOptions, {
ModelInfo? modelInfo,
}) {
final isGemma = isGemmaModelName(modelName);
return Model(
name: '$name/$modelName',
customOptions: customOptions,
metadata: {'model': commonModelInfo.toJson()},
metadata: {'model': (modelInfo ?? commonModelInfo).toJson()},
fn: (req, ctx) async {
gcl.GenerationConfig generationConfig;
List<gcl.SafetySetting>? safetySettings;
Expand Down Expand Up @@ -74,9 +80,17 @@ abstract class CommonGoogleGenPlugin extends GenkitPlugin {
);
toolConfig = toGeminiToolConfig(options.functionCallingConfig);
} else {
final options = req.config == null
? GeminiOptions()
: GeminiOptions.$schema.parse(req.config!);
final GeminiOptions options;
if (isGemma) {
final gemmaOptions = req.config == null
? GemmaOptions()
: GemmaOptions.$schema.parse(req.config!);
options = gemmaToGeminiOptions(gemmaOptions);
} else {
options = req.config == null
? GeminiOptions()
: GeminiOptions.$schema.parse(req.config!);
}
Comment thread
CorieW marked this conversation as resolved.
Outdated
apiKey = options.apiKey;
generationConfig = toGeminiSettings(
options,
Expand All @@ -98,9 +112,12 @@ abstract class CommonGoogleGenPlugin extends GenkitPlugin {
final systemMessage = req.messages
.where((m) => m.role == Role.system)
.firstOrNull;
final messages = req.messages
final nonSystemMessages = req.messages
.where((m) => m.role != Role.system)
.toList();
final messages = isGemma
? stripReasoningParts(nonSystemMessages)
: nonSystemMessages;
Comment thread
CorieW marked this conversation as resolved.
Comment on lines +110 to +112

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

While stripReasoningParts is applied to nonSystemMessages, the systemMessage (extracted at line 104) is passed directly to toGeminiPart at line 132 without filtering. If the Gemma API rejects reasoning parts in the system instruction as well, they should be stripped from the system message content to ensure consistency and avoid potential API errors.


final generateRequest = gcl.GenerateContentRequest(
contents: toGeminiContent(messages),
Expand Down Expand Up @@ -189,6 +206,15 @@ abstract class CommonGoogleGenPlugin extends GenkitPlugin {
return createEmbedder(name);
}
if (actionType == 'model') {
if (isGemmaModelName(name)) {
return createModel(
name,
GemmaOptions.$schema,
modelInfo: isGemma3ModelName(name)
? gemma3ModelInfo
: commonGemmaModelInfo,
);
}
if (name.contains('-tts')) {
return createModel(name, GeminiTtsOptions.$schema);
}
Expand Down
88 changes: 88 additions & 0 deletions packages/genkit_google_genai/lib/src/gemma.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
// 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.

import 'package:genkit/plugin.dart';

import 'model.dart';

final commonGemmaModelInfo = ModelInfo(
supports: {
'multiturn': true,
'media': true,
'tools': true,
'toolChoice': true,
'systemRole': true,
'constrained': 'no-tools',
},
);

final gemma3ModelInfo = ModelInfo(
supports: {...?commonGemmaModelInfo.supports, 'systemRole': false},
);

bool isGemmaModelName(String name) => name.startsWith('gemma-');

bool isGemma3ModelName(String name) =>
name.startsWith('gemma-3-') || name.startsWith('gemma-3n-');

/// Strips parts that the Gemma API rejects in history: reasoning parts
/// and any text/tool parts whose metadata carries a `thoughtSignature`.
/// Messages that become empty after filtering are dropped.
List<Message> stripReasoningParts(List<Message> messages) {
return messages
.map(
(m) => Message(
role: m.role,
content: m.content
.where(
(p) =>
!p.isReasoning && p.metadata?['thoughtSignature'] == null,
)
.toList(),
metadata: m.metadata,
),
)
.where((m) => m.content.isNotEmpty)
.toList();
}

/// Maps a [GemmaOptions] config to its [GeminiOptions] equivalent so the
/// shared `toGeminiSettings`/`toGeminiTools`/etc. helpers can be reused.
/// Every Gemma field has an identical Gemini twin; the only schema-level
/// difference is the tighter `temperature` cap on Gemma.
GeminiOptions gemmaToGeminiOptions(GemmaOptions o) {
return GeminiOptions(
apiKey: o.apiKey,
safetySettings: o.safetySettings,
codeExecution: o.codeExecution,
functionCallingConfig: o.functionCallingConfig,
thinkingConfig: o.thinkingConfig,
responseModalities: o.responseModalities,
googleSearch: o.googleSearch,
fileSearch: o.fileSearch,
temperature: o.temperature,
topP: o.topP,
topK: o.topK,
candidateCount: o.candidateCount,
stopSequences: o.stopSequences,
maxOutputTokens: o.maxOutputTokens,
responseMimeType: o.responseMimeType,
responseLogprobs: o.responseLogprobs,
logprobs: o.logprobs,
presencePenalty: o.presencePenalty,
frequencyPenalty: o.frequencyPenalty,
seed: o.seed,
speechConfig: o.speechConfig,
);
}
18 changes: 15 additions & 3 deletions packages/genkit_google_genai/lib/src/google_api_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import 'package:meta/meta.dart';

import 'api_client.dart';
import 'common_plugin.dart';
import 'gemma.dart';
import 'generated/generativelanguage.dart' as gcl;
import 'model.dart';

Expand Down Expand Up @@ -54,12 +55,23 @@ class GoogleGenAiPluginImpl extends CommonGoogleGenPlugin {
final models = (modelsResponse.models ?? [])
.where((model) {
return model.name != null &&
model.name!.startsWith('models/gemini-');
(model.name!.startsWith('models/gemini-') ||
model.name!.startsWith('models/gemma-'));
})
.map((model) {
final isTts = model.name!.contains('-tts');
final short = model.name!.split('/').last;
if (isGemmaModelName(short)) {
return modelMetadata(
'$name/$short',
customOptions: GemmaOptions.$schema,
modelInfo: isGemma3ModelName(short)
? gemma3ModelInfo
: commonGemmaModelInfo,
);
}
final isTts = short.contains('-tts');
return modelMetadata(
'$name/${model.name!.split('/').last}',
'$name/$short',
customOptions: isTts
? GeminiTtsOptions.$schema
: GeminiOptions.$schema,
Expand Down
36 changes: 36 additions & 0 deletions packages/genkit_google_genai/lib/src/model.dart
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,42 @@ abstract class $GeminiOptions {
$SpeechConfig? get speechConfig;
}

@Schema()
abstract class $GemmaOptions {
String? get apiKey;

List<$SafetySettings>? get safetySettings;

bool? get codeExecution;
$FunctionCallingConfig? get functionCallingConfig;
$ThinkingConfig? get thinkingConfig;
List<String>? get responseModalities;

// Retrieval
$GoogleSearch? get googleSearch;
$FileSearch? get fileSearch;

@DoubleField(minimum: 0.0, maximum: 1.0)
double? get temperature;

@DoubleField(minimum: 0.0, maximum: 1.0)
double? get topP;

int? get topK;
int? get candidateCount;
List<String>? get stopSequences;
int? get maxOutputTokens;

String? get responseMimeType;
bool? get responseLogprobs;
int? get logprobs;
double? get presencePenalty;
double? get frequencyPenalty;
int? get seed;

$SpeechConfig? get speechConfig;
}

@Schema()
abstract class $SafetySettings {
@StringField(
Expand Down
Loading
Loading