extractTextFromResponse static method
Extract text from a LiteRT-LM JSON response chunk.
Handles two response formats:
- Text:
{"role":"assistant","content":[{"type":"text","text":"hello"}]}→ returns"hello" - Thinking:
{"role":"assistant","channels":{"thought":"reasoning..."}}→ returns<|channel>thought\nreasoning...<channel|>(compatible with ThinkingFilter in extensions.dart)
Implementation
static String extractTextFromResponse(String jsonStr) {
final Map<String, dynamic> json;
try {
json = jsonDecode(jsonStr) as Map<String, dynamic>;
} on FormatException {
// Partial / non-JSON chunks pass through verbatim. This is the only
// shape we want to be permissive about — any other parse error
// (TypeError, RangeError, etc.) signals a real contract change with
// LiteRT-LM and must surface, not be silently swallowed.
return jsonStr;
}
// Check for thinking channels first
final channels = json['channels'] as Map<String, dynamic>?;
if (channels != null) {
final thought = channels['thought'] as String?;
if (thought != null && thought.isNotEmpty) {
return '<|channel>thought\n$thought<channel|>';
}
}
// Regular text content
final content = json['content'] as List<dynamic>?;
if (content == null) return jsonStr;
final buffer = StringBuffer();
for (final item in content) {
if (item is Map<String, dynamic> && item['type'] == 'text') {
buffer.write(item['text'] as String? ?? '');
}
}
return buffer.toString();
}