messageFromJson function

Message messageFromJson(
  1. Map<String, Object?> json
)

A Conversation API JSON object as a Message. Parts of a type it does not know are left out.

Implementation

Message messageFromJson(Map<String, Object?> json) {
  final contents = <Content>[];
  switch (json['content']) {
    case final String text:
      contents.add(Content.text(text));
    case final List<Object?> parts:
      for (final part in parts) {
        if (part case {'type': 'text', 'text': final String text}) {
          contents.add(Content.text(text));
        }
      }
    case null:
      break;
    case final other:
      throw StateError(
        'LiteRT-LM response content is ${other.runtimeType}, not a string '
        'or a list of parts: ${jsonEncode(json)}',
      );
  }
  final calls = switch (json['tool_calls']) {
    final List<Object?> list => _wholeTurn(list),
    _ => const <ToolCall>[],
  };
  final channels = <String, String>{};
  if (json['channels'] case final Map<String, Object?> map) {
    for (final MapEntry(:key, :value) in map.entries) {
      if (value is String) channels[key] = value;
    }
  }
  return Message(
    role: Role._fromWire(json['role']),
    contents: contents,
    toolCalls: calls,
    channels: channels,
  );
}