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 body = jsonEncode(_buildPayload(model, request, stream: false));
final res = await retryRequest(
send: () => _http
.post(
Uri.parse('$_baseUrl/messages'),
headers: _headers(apiKey),
body: body,
)
.timeout(_timeout),
providerLabel: 'Anthropic',
);
final json = jsonDecode(res.body) as Map<String, Object?>;
final content = json['content'] as List<Object?>?;
if (content == null || content.isEmpty) {
throw const AiBrokerException('Anthropic returned no content.');
}
final buf = StringBuffer();
for (final block in content) {
if (block is! Map<String, Object?>) continue;
if (block['type'] != 'text') continue;
buf.write(block['text'] as String? ?? '');
}
final out = buf.toString().trim();
if (out.isEmpty) {
throw const AiBrokerException('Anthropic returned empty text.');
}
final rawFinishReason = json['stop_reason'] as String?;
final usage = json['usage'] as Map<String, Object?>?;
return AiCompletion(
text: out,
rawFinishReason: rawFinishReason,
finishReason:
rawFinishReason == null ? null : _finishReasonOf(rawFinishReason),
inputTokens: usage?['input_tokens'] as int?,
outputTokens: usage?['output_tokens'] as int?,
);
}