205 lines
6.9 KiB
Rust
205 lines
6.9 KiB
Rust
use serde::{Deserialize, Serialize};
|
|
|
|
use super::client::LlmClient;
|
|
use crate::error::AgentError;
|
|
|
|
// ── Embedding types ────────────────────────────────────────────
|
|
|
|
#[derive(Serialize)]
|
|
struct EmbeddingRequest {
|
|
model: String,
|
|
input: Vec<String>,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
struct EmbeddingResponse {
|
|
data: Vec<EmbeddingData>,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
struct EmbeddingData {
|
|
embedding: Vec<f64>,
|
|
index: usize,
|
|
}
|
|
|
|
/// Max inputs per embedding request. The bge/OpenAI-like backends cap the input
|
|
/// array (bge-multilingual-gemma2 rejects >25 with "batch size overflow"), so we
|
|
/// chunk larger corpora — a whole control catalog (~1.8k) would otherwise 500.
|
|
const EMBED_BATCH_SIZE: usize = 16;
|
|
// The bge backend takes at most 25 inputs per request.
|
|
const _: () = assert!(EMBED_BATCH_SIZE <= 25);
|
|
|
|
/// Token budget of one embedding request. bge-multilingual-gemma2 takes 8192
|
|
/// tokens; on prod a batch of 16 code chunks came to ~51k and was refused, so a
|
|
/// request now carries only as many inputs as fit, and one input never more.
|
|
const EMBED_MAX_REQUEST_TOKENS: usize = 7000;
|
|
|
|
/// Conservative bytes per token: code tokenizes denser than prose (the chunker's
|
|
/// own estimate of 4 chars per token undercounts it).
|
|
const EMBED_BYTES_PER_TOKEN: usize = 3;
|
|
|
|
fn estimated_tokens(text: &str) -> usize {
|
|
text.len().div_ceil(EMBED_BYTES_PER_TOKEN)
|
|
}
|
|
|
|
/// Shorten `text` (at a char boundary) so it fits a request on its own. The
|
|
/// head of a chunk carries its context header and signature, which is what
|
|
/// retrieval needs.
|
|
fn fit_text(mut text: String) -> String {
|
|
let max_bytes = EMBED_MAX_REQUEST_TOKENS * EMBED_BYTES_PER_TOKEN;
|
|
if text.len() > max_bytes {
|
|
let mut cut = max_bytes;
|
|
while !text.is_char_boundary(cut) {
|
|
cut -= 1;
|
|
}
|
|
text.truncate(cut);
|
|
}
|
|
text
|
|
}
|
|
|
|
/// Split `texts` into consecutive batches of at most [`EMBED_BATCH_SIZE`]
|
|
/// inputs and [`EMBED_MAX_REQUEST_TOKENS`] estimated tokens, keeping order.
|
|
fn plan_batches(texts: &[String]) -> Vec<std::ops::Range<usize>> {
|
|
let mut out = Vec::new();
|
|
let (mut start, mut tokens) = (0, 0);
|
|
for (i, t) in texts.iter().enumerate() {
|
|
let n = estimated_tokens(t);
|
|
if i > start && (i - start == EMBED_BATCH_SIZE || tokens + n > EMBED_MAX_REQUEST_TOKENS) {
|
|
out.push(start..i);
|
|
(start, tokens) = (i, 0);
|
|
}
|
|
tokens += n;
|
|
}
|
|
if start < texts.len() {
|
|
out.push(start..texts.len());
|
|
}
|
|
out
|
|
}
|
|
|
|
// ── Embedding implementation ───────────────────────────────────
|
|
|
|
impl LlmClient {
|
|
pub fn embed_model(&self) -> &str {
|
|
&self.embed_model
|
|
}
|
|
|
|
/// Generate embeddings for a batch of texts, chunking into backend-sized
|
|
/// requests (input count and token budget) and preserving input order.
|
|
pub async fn embed(&self, texts: Vec<String>) -> Result<Vec<Vec<f64>>, AgentError> {
|
|
if texts.is_empty() {
|
|
return Ok(Vec::new());
|
|
}
|
|
let texts: Vec<String> = texts.into_iter().map(fit_text).collect();
|
|
let mut out = Vec::with_capacity(texts.len());
|
|
for range in plan_batches(&texts) {
|
|
out.extend(self.embed_batch(texts[range].to_vec()).await?);
|
|
}
|
|
Ok(out)
|
|
}
|
|
|
|
/// Embed one backend-sized batch (≤ [`EMBED_BATCH_SIZE`]) in a single request.
|
|
async fn embed_batch(&self, texts: Vec<String>) -> Result<Vec<Vec<f64>>, AgentError> {
|
|
if self.embed_model.is_empty() {
|
|
return Err(AgentError::Other(
|
|
"embeddings off: LITELLM_EMBED_MODEL is not set".to_string(),
|
|
));
|
|
}
|
|
let url = format!("{}/v1/embeddings", self.base_url.trim_end_matches('/'));
|
|
|
|
let request_body = EmbeddingRequest {
|
|
model: self.embed_model.clone(),
|
|
input: texts,
|
|
};
|
|
|
|
let mut req = self
|
|
.http
|
|
.post(&url)
|
|
.header("content-type", "application/json")
|
|
.json(&request_body);
|
|
|
|
if let Some(auth) = self.auth_header() {
|
|
req = req.header("Authorization", auth);
|
|
}
|
|
|
|
let resp = req
|
|
.send()
|
|
.await
|
|
.map_err(|e| AgentError::Other(format!("Embedding request failed: {e}")))?;
|
|
|
|
if !resp.status().is_success() {
|
|
let status = resp.status();
|
|
let body = resp.text().await.unwrap_or_default();
|
|
return Err(AgentError::Other(format!(
|
|
"Embedding API returned {status}: {body}"
|
|
)));
|
|
}
|
|
|
|
let body: EmbeddingResponse = resp
|
|
.json()
|
|
.await
|
|
.map_err(|e| AgentError::Other(format!("Failed to parse embedding response: {e}")))?;
|
|
|
|
let mut data = body.data;
|
|
data.sort_by_key(|d| d.index);
|
|
|
|
Ok(data.into_iter().map(|d| d.embedding).collect())
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use secrecy::SecretString;
|
|
|
|
fn client() -> LlmClient {
|
|
LlmClient::new(
|
|
"http://unused".into(),
|
|
SecretString::from(String::new()),
|
|
"m".into(),
|
|
"e".into(),
|
|
)
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn empty_input_makes_no_request() {
|
|
// Must short-circuit before any HTTP call (base_url is unroutable).
|
|
let out = client().embed(Vec::new()).await.unwrap();
|
|
assert!(out.is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn batches_respect_count_and_token_budget() {
|
|
// 40 short texts: count-bound, 16 + 16 + 8
|
|
let short: Vec<String> = (0..40).map(|i| format!("fn f{i}() {{}}")).collect();
|
|
let b = plan_batches(&short);
|
|
assert_eq!(b, vec![0..16, 16..32, 32..40]);
|
|
|
|
// 8 KiB code chunks (~2731 tokens each): two per request, never three
|
|
let big: Vec<String> = (0..5).map(|_| "x".repeat(8192)).collect();
|
|
let b = plan_batches(&big);
|
|
assert_eq!(b, vec![0..2, 2..4, 4..5]);
|
|
for r in &b {
|
|
let tokens: usize = big[r.clone()].iter().map(|t| estimated_tokens(t)).sum();
|
|
assert!(tokens <= EMBED_MAX_REQUEST_TOKENS, "{r:?}: {tokens}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn oversized_text_is_cut_to_fit_alone_at_a_char_boundary() {
|
|
let long = "ä".repeat(30_000); // 60 000 bytes, 2 bytes per char
|
|
let cut = fit_text(long);
|
|
assert!(estimated_tokens(&cut) <= EMBED_MAX_REQUEST_TOKENS);
|
|
assert!(cut.chars().all(|c| c == 'ä'));
|
|
assert_eq!(plan_batches(&[cut.clone(), "y".into()]), vec![0..1, 1..2]);
|
|
assert_eq!(fit_text("short".into()), "short");
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn no_embed_model_makes_no_request() {
|
|
let mut llm = client();
|
|
llm.embed_model = String::new();
|
|
let err = llm.embed(vec!["x".into()]).await.unwrap_err();
|
|
assert!(err.to_string().contains("LITELLM_EMBED_MODEL"), "{err}");
|
|
}
|
|
}
|