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 [];
  final body = jsonEncode({
    'model': model,
    'input': inputs,
    'encoding_format': 'float',
  });
  final res = await retryRequest(
    send: () => _http
        .post(
          Uri.parse('$_baseUrl/embeddings'),
          headers: {
            'Authorization': 'Bearer $apiKey',
            'Content-Type': 'application/json',
          },
          body: body,
        )
        .timeout(_timeout),
    providerLabel: 'OpenAI',
    isHardFailure: (r) =>
        r.statusCode == 429 && r.body.toLowerCase().contains('quota'),
  );
  final json = jsonDecode(res.body) as Map<String, Object?>;
  final data = json['data'] as List<Object?>?;
  if (data == null || data.isEmpty) {
    throw const AiBrokerException('OpenAI returned no embeddings.');
  }
  // Sort by index defensively; the API documents request order but
  // pinning it locally costs nothing and protects against future churn.
  final sorted = [...data]..sort((a, b) {
      final ai = (a as Map<String, Object?>)['index'] as int? ?? 0;
      final bi = (b as Map<String, Object?>)['index'] as int? ?? 0;
      return ai.compareTo(bi);
    });
  final out = <List<double>>[];
  for (final item in sorted) {
    final m = item as Map<String, Object?>;
    final embedding = m['embedding'] as List<Object?>?;
    if (embedding == null) {
      throw const AiBrokerException('OpenAI embedding missing.');
    }
    out.add(
      embedding.map((v) => (v as num).toDouble()).toList(growable: false),
    );
  }
  if (out.length != inputs.length) {
    throw AiBrokerException(
      'OpenAI returned ${out.length} embeddings for ${inputs.length} inputs.',
    );
  }
  return out;
}