chatWithMeta method
Future<AiCompletion>
chatWithMeta({
- required String apiKey,
- required String model,
- required ChatRequest request,
override
Multi-turn, returning the final turn's reply with why the model stopped and the token counts the provider reported. Every provider call goes through here; chat, complete and completeWithMeta are built on it.
Implementation
@override
Future<AiCompletion> chatWithMeta({
required String apiKey,
required String model,
required ChatRequest request,
}) async {
final uri = Uri.parse('$_baseUrl/models/$model:generateContent');
final body = jsonEncode(_buildPayload(request));
final res = await retryRequest(
send: () => _http
.post(
uri,
headers: {
..._authHeaders(apiKey),
'Content-Type': 'application/json',
},
body: body,
)
.timeout(_timeout),
providerLabel: 'Gemini',
);
final json = jsonDecode(res.body) as Map<String, Object?>;
final candidates = json['candidates'] as List<Object?>? ?? const [];
final rawFinishReason = candidates.isEmpty
? null
: (candidates.first as Map<String, Object?>)['finishReason'] as String?;
final usage = json['usageMetadata'] as Map<String, Object?>?;
final replyTokens = usage?['candidatesTokenCount'] as int?;
final thinkingTokens = usage?['thoughtsTokenCount'] as int?;
return AiCompletion(
text: _extractText(json, finishReason: rawFinishReason),
rawFinishReason: rawFinishReason,
finishReason:
rawFinishReason == null ? null : _finishReasonOf(rawFinishReason),
inputTokens: usage?['promptTokenCount'] as int?,
// Gemini counts thinking apart from the reply; [AiCompletion]
// counts both as output, the way Anthropic and OpenAI do.
outputTokens: replyTokens == null && thinkingTokens == null
? null
: (replyTokens ?? 0) + (thinkingTokens ?? 0),
thinkingTokens: thinkingTokens,
);
}