complete method

  1. @override
Future<AIResponse> complete(
  1. List<AIMessage> messages, {
  2. int? maxTokens,
  3. double? temperature,
  4. List<AITool>? tools,
})

Sends a completion request and returns the full response.

Implementation

@override
Future<AIResponse> complete(
  List<AIMessage> messages, {
  int? maxTokens,
  double? temperature,
  List<AITool>? tools,
}) async {
  final stopwatch = Stopwatch()..start();

  final body = _buildRequestBody(messages, maxTokens, temperature);
  final response = await _post('/messages', body);
  stopwatch.stop();

  final json = jsonDecode(response.body) as Map<String, dynamic>;

  if (response.statusCode != 200) {
    throw _parseError(response.statusCode, json);
  }

  final content = json['content'] as List? ?? [];
  final text = content
      .where((c) => (c as Map<String, dynamic>)['type'] == 'text')
      .map((c) => (c as Map<String, dynamic>)['text'] as String)
      .join();

  final usage = json['usage'] as Map<String, dynamic>? ?? {};

  return AIResponse(
    content: text,
    usage: AIUsage(
      promptTokens: usage['input_tokens'] as int? ?? 0,
      completionTokens: usage['output_tokens'] as int? ?? 0,
      estimatedCostUsd: _estimateCost(
        usage['input_tokens'] as int? ?? 0,
        usage['output_tokens'] as int? ?? 0,
      ),
    ),
    model: json['model'] as String? ?? config.model,
    provider: name,
    latency: stopwatch.elapsed,
    finishReason: json['stop_reason'] as String?,
  );
}