ChatCompletionStreamResponse.fromJson constructor
ChatCompletionStreamResponse.fromJson(
- Map<String, dynamic> json, {
- String? provider,
})
Implementation
factory ChatCompletionStreamResponse.fromJson(Map<String, dynamic> json, {String? provider}) {
String content = '';
bool isComplete = false;
if (json.containsKey('choices') && json['choices'] is List) {
final choice = (json['choices'] as List).first;
content = choice['delta']?['content'] as String? ?? '';
final finishReason = choice['finish_reason'];
isComplete = finishReason != null && finishReason != 'length';
} else if (json.containsKey('candidates')) {
final candidate = (json['candidates'] as List?)?.first;
content = candidate?['content']?['parts']?[0]?['text'] as String? ?? '';
isComplete =
json['candidates'] != null &&
(json['candidates'] as List).isNotEmpty &&
candidate?['finishReason'] != null;
} else if (json.containsKey('delta')) {
content =
json['delta']?['content'] as String? ??
json['content'] as String? ??
'';
isComplete = json['done'] == true || json['finish_reason'] != null;
} else if (json.containsKey('error')) {
throw AIException(
json['error']?['message'] ?? 'Unknown streaming error',
provider: provider,
);
}
return ChatCompletionStreamResponse(
content: content,
isComplete: isComplete,
model: json['model'] as String?,
provider: provider,
rawResponse: json,
);
}