fix(llm): embedding requests within the model's token budget (#582)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Dashboard (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Agent (push) Successful in 6m15s

This commit was merged in pull request #582.
This commit is contained in:
sharang committed 2026-10-30 07:22:30 +00:00
1 parent 330d492578
commit 1135b65b9e
1 file changed
+78 -3
+78 -3
View File
@@ -29,6 +29,53 @@ 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 {
@@ -37,14 +84,15 @@ impl LlmClient {
}
/// Generate embeddings for a batch of texts, chunking into backend-sized
/// requests and preserving input order across chunks.
/// 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 chunk in texts.chunks(EMBED_BATCH_SIZE) {
out.extend(self.embed_batch(chunk.to_vec()).await?);
for range in plan_batches(&texts) {
out.extend(self.embed_batch(texts[range].to_vec()).await?);
}
Ok(out)
}
@@ -119,6 +167,33 @@ mod tests {
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();