embed method

  1. @override
Future<List<List<double>>> embed({
  1. required String apiKey,
  2. required String model,
  3. required List<String> inputs,
})

Embeds one or more texts into vectors of the model's native dimension. Returns one vector per input, same order as inputs; all vectors share the same length.

Per-call input limits are provider-specific (OpenAI: ≤2048 inputs, ≤8191 tokens each, ≤300k tokens per request; Gemini: ≤100 per call). Callers needing batching above those ceilings should use the higher-level Embedder from lib/src/embed/.

Throws AiBrokerException for transport / response failures.

Implementation

@override
Future<List<List<double>>> embed({
  required String apiKey,
  required String model,
  required List<String> inputs,
}) async {
  if (inputs.isEmpty) return const [];
  // Gemini wants the model name prefixed with `models/` in each request
  // *and* in the URL path.
  final modelPath = model.startsWith('models/') ? model : 'models/$model';
  final body = jsonEncode({
    'requests': [
      for (final text in inputs)
        {
          'model': modelPath,
          'content': {
            'parts': [
              {'text': text},
            ],
          },
        },
    ],
  });
  final uri = Uri.parse('$_baseUrl/$modelPath:batchEmbedContents');
  final res = await retryRequest(
    send: () => _http
        .post(
          uri,
          headers: {
            ..._authHeaders(apiKey),
            'Content-Type': 'application/json',
          },
          body: body,
        )
        .timeout(_timeout),
    providerLabel: 'Gemini',
  );
  final json = jsonDecode(res.body) as Map<String, Object?>;
  final embeddings = json['embeddings'] as List<Object?>?;
  if (embeddings == null || embeddings.isEmpty) {
    throw const AiBrokerException('Gemini returned no embeddings.');
  }
  final out = <List<double>>[];
  for (final item in embeddings) {
    final m = item as Map<String, Object?>;
    final values = m['values'] as List<Object?>?;
    if (values == null) {
      throw const AiBrokerException('Gemini embedding missing values.');
    }
    out.add(
      values.map((v) => (v as num).toDouble()).toList(growable: false),
    );
  }
  if (out.length != inputs.length) {
    throw AiBrokerException(
      'Gemini returned ${out.length} embeddings for ${inputs.length} inputs.',
    );
  }
  return out;
}