ProviderConfig.fromJson constructor

ProviderConfig.fromJson(
  1. Map<String, Object?> json
)

Restores a config written by toJson. Unknown enum values fall back to the defaults; a missing id or baseUrl, or a field of the wrong type, throws FormatException.

Implementation

factory ProviderConfig.fromJson(Map<String, Object?> json) {
  String? text(String key) => switch (json[key]) {
    null => null,
    final String value => value,
    _ => throw FormatException('ProviderConfig.$key must be a string.'),
  };
  final id = text('id');
  final baseUrl = text('baseUrl');
  if (id == null || id.isEmpty || baseUrl == null) {
    throw const FormatException('ProviderConfig needs id and baseUrl.');
  }
  T pick<T extends Enum>(List<T> values, Object? name, T fallback) =>
      values.where((value) => value.name == name).firstOrNull ?? fallback;
  return ProviderConfig(
    id: id,
    name: text('name') ?? '',
    protocol: pick(
      ProviderProtocol.values,
      json['protocol'],
      ProviderProtocol.openAiCompatible,
    ),
    baseUrl: baseUrl,
    model: text('model') ?? '',
    presetId: text('presetId'),
    structuredOutput: pick(
      StructuredOutputMode.values,
      json['structuredOutput'],
      StructuredOutputMode.jsonSchema,
    ),
    maxTokensField: pick(
      MaxTokensField.values,
      json['maxTokensField'],
      MaxTokensField.maxTokens,
    ),
  );
}