Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
122 changes: 122 additions & 0 deletions packages/firebase_ai/firebase_ai/lib/src/developer/api.dart
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,20 @@ import '../api.dart'
FinishReason,
GenerateContentResponse,
GenerationConfig,
GroundingChunk,
GroundingMetadata,
GroundingSupport,
HarmBlockThreshold,
HarmCategory,
HarmProbability,
PromptFeedback,
SafetyRating,
SafetySetting,
SearchEntryPoint,
Segment,
SerializationStrategy,
UsageMetadata,
WebGroundingChunk,
createUsageMetadata;
import '../content.dart'
show Content, FunctionCall, InlineDataPart, Part, TextPart;
Expand Down Expand Up @@ -206,6 +212,11 @@ Candidate _parseCandidate(Object? jsonObject) {
{'finishMessage': final String finishMessage} => finishMessage,
_ => null
},
groundingMetadata: switch (jsonObject) {
{'groundingMetadata': final Object groundingMetadata} =>
_parseGroundingMetadata(groundingMetadata),
_ => null
},
);
}

Expand Down Expand Up @@ -299,6 +310,117 @@ Citation _parseCitationSource(Object? jsonObject) {
);
}

GroundingMetadata _parseGroundingMetadata(Object? jsonObject) {
if (jsonObject is! Map) {
throw unhandledFormat('GroundingMetadata', jsonObject);
}

final searchEntryPoint = switch (jsonObject) {
{'searchEntryPoint': final Object? searchEntryPoint} =>
_parseSearchEntryPoint(searchEntryPoint),
_ => null,
};
final groundingChunks = switch (jsonObject) {
{'groundingChunks': final List<Object?> groundingChunks} =>
groundingChunks.map(_parseGroundingChunk).toList(),
_ => null,
} ??
[];
// Filters out null elements, which are returned from _parseGroundingSupport when
// segment is null.
final groundingSupport = switch (jsonObject) {
{'groundingSupport': final List<Object?> groundingSupport} =>
groundingSupport
.map(_parseGroundingSupport)
.whereType<GroundingSupport>()
.toList(),
_ => null,
} ??
[];
final webSearchQueries = switch (jsonObject) {
{'webSearchQueries': final List<String>? webSearchQueries} =>
webSearchQueries,
_ => null,
} ??
[];

return GroundingMetadata(
searchEntryPoint: searchEntryPoint,
groundingChunks: groundingChunks,
groundingSupport: groundingSupport,
webSearchQueries: webSearchQueries);
}

Segment _parseSegment(Object? jsonObject) {
if (jsonObject is! Map) {
throw unhandledFormat('Segment', jsonObject);
}

return Segment(
partIndex: (jsonObject['partIndex'] as int?) ?? 0,
startIndex: (jsonObject['startIndex'] as int?) ?? 0,
endIndex: (jsonObject['endIndex'] as int?) ?? 0,
text: (jsonObject['text'] as String?) ?? '');
}

WebGroundingChunk _parseWebGroundingChunk(Object? jsonObject) {
if (jsonObject is! Map) {
throw unhandledFormat('WebGroundingChunk', jsonObject);
}

return WebGroundingChunk(
uri: jsonObject['uri'] as String?,
title: jsonObject['title'] as String?,
domain: jsonObject['domain'] as String?,
);
}

GroundingChunk _parseGroundingChunk(Object? jsonObject) {
if (jsonObject is! Map) {
throw unhandledFormat('GroundingChunk', jsonObject);
}

return GroundingChunk(
web: jsonObject['web'] != null
? _parseWebGroundingChunk(jsonObject['web'])
: null,
);
}

GroundingSupport? _parseGroundingSupport(Object? jsonObject) {
if (jsonObject is! Map) {
throw unhandledFormat('GroundingSupport', jsonObject);
}

final segment = switch (jsonObject) {
{'segment': final Object? segment} => _parseSegment(segment),
_ => null,
};
if (segment == null) {
return null;
}

return GroundingSupport(
segment: segment,
groundingChunkIndices:
(jsonObject['groundingChunkIndices'] as List<int>?) ?? []);
}

SearchEntryPoint _parseSearchEntryPoint(Object? jsonObject) {
if (jsonObject is! Map) {
throw unhandledFormat('SearchEntryPoint', jsonObject);
}

final renderedContent = jsonObject['renderedContent'] as String?;
if (renderedContent == null) {
throw unhandledFormat('SearchEntryPoint', jsonObject);
}

return SearchEntryPoint(
renderedContent: renderedContent,
);
}

Content _parseGoogleAIContent(Object jsonObject) {
return switch (jsonObject) {
{'parts': final List<Object?> parts} => Content(
Expand Down
53 changes: 51 additions & 2 deletions packages/firebase_ai/firebase_ai/test/api_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@

import 'dart:convert';

import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_ai/src/api.dart';

import 'package:firebase_ai/src/content.dart';
import 'package:firebase_ai/src/error.dart';
import 'package:firebase_ai/src/schema.dart';
import 'package:flutter_test/flutter_test.dart';

// --- Mock/Helper Implementations ---
Expand Down Expand Up @@ -947,6 +948,54 @@ void main() {
throwsA(isA<FirebaseAISdkException>().having(
(e) => e.message, 'message', contains('WebGroundingChunk'))));
});

test(
'parses groundingSupport and filters out entries without a segment',
() {
final jsonResponse = {
'candidates': [
{
'content': {
'parts': [
{'text': 'Test'}
]
},
'finishReason': 'STOP',
'groundingMetadata': {
'groundingSupport': [
// Valid entry
{
'segment': {
'startIndex': 0,
'endIndex': 4,
'text': 'Test'
},
'groundingChunkIndices': [0]
},
// Invalid entry - missing segment
{
'groundingChunkIndices': [1]
},
// Invalid entry - empty object
{}
]
}
}
]
};

final response =
VertexSerialization().parseGenerateContentResponse(jsonResponse);
final groundingMetadata = response.candidates.first.groundingMetadata;

expect(groundingMetadata, isNotNull);
// The invalid entries should be filtered out.
expect(groundingMetadata!.groundingSupport, hasLength(1));

final validSupport = groundingMetadata.groundingSupport.first;
expect(validSupport.segment.text, 'Test');
expect(validSupport.groundingChunkIndices, [0]);
});
});

test('parses JSON with no candidates (empty list)', () {
Expand Down
Loading
Loading