openpay/ (+3 crates)
op-bnpl/ Affirm + Klarna + Afterpay/Clearpay rails. Full lifecycle
typestate (Initiated→Approved→Captured→Settled→Refunded).
Per-provider sandbox+production base URLs, regions (NA/EU/OC
for Klarna; US/AuNz/Gb/Ca/Eu for Afterpay). HMAC-SHA256
webhook verification with constant-time compare. 61 tests.
op-batch/ NACHA ACH (94-char records, PPD/CCD/WEB/TEL/CTX, R01-R99
return codes, Same-Day ACH cutoffs); SEPA pain.001.001.09
(CT) + pain.008.001.08 (DD) with SCT-Inst flagging; Fedwire
MT103/MT202/CHIPS + pacs.008.001.12 / pacs.009.001.10 +
UETR; Bacs Standard 18. Per-rail cutoff scheduler. Exception
taxonomy unified across rails. 51 tests.
op-screening/ OFAC SDN + EU consolidated + UN consolidated + HMT UK
consolidated + Australia DFAT + Canada SEMA + Japan MOF.
Levenshtein + Jaro-Winkler + Soundex + Metaphone + token
Jaccard scoring. Unicode NFKD normalisation + Cyrillic /
Arabic transliteration. Ed25519-signed BLAKE3-chained
audit log. BSA helpers: CTR + SAR pattern detection
(structuring, round-dollar, rapid-in-out). 43 tests.
smart-byte/smart-byte-rs/ (+3 crates)
smart-byte-bbs/ BBS+ signatures (IETF draft-irtf-cfrg-bbs-signatures-08).
BLS12-381 keys, signatures, disclosure proofs with
cryptographic unlinkability. bbs-2023 Data Integrity
cryptosuite. AnonCreds-shaped link secrets +
predicate proofs. SecretKey zeroize-on-drop. 49 tests.
smart-byte-didcomm/ DIDComm v2 messaging per DIF spec. Pack-encrypted
(ECDH-1PU + ECDH-ES via X25519), pack-signed (JWS),
pack-plaintext. Aries protocols: issue-credential v3,
present-proof v3, basic-message, trust-ping, discover-
features, out-of-band, coordinate-mediation, message-
pickup. Mediator role with pluggable storage. 23 tests.
smart-byte-mdl/ ISO/IEC 18013-5 mobile driver's licence + 18013-7
online presentment. mDoc + MSO with salted-hash
selective disclosure (per item; SHA-256 digest tree).
org.iso.18013.5.1 namespace + AAMVA add-on. ES256
device-auth + issuer-auth. QR-code device-engagement
scaffolding. 28 tests.
eoc/eoc-rs/ (+3 crates)
eoc-local/ Local-inference backends behind one NeuralBackend:
llama.cpp (GGUF, Q4/Q5/Q6/Q8/F16/F32 quantisation),
MLX (Apple Silicon, feature-gated), MLC-LLM (TVM, feature-
gated marker), ONNX Runtime. GGUF file-format reader.
HuggingFace tokenizers. Greedy / top-k / top-p / temperature /
Mirostat samplers. Model registry scanning ~/.eoc/models/.
Joule attribution via eoc-meter. 39 tests.
eoc-rerank/ BM25 sparse + HNSW dense + RRF + min-max hybrid fusion.
Cohere v3.5 + Voyage v2 + bge-reranker v2-m3 + ms-marco
MiniLM + ColBERT v2 rerankers. Two-stage pipeline:
retrieve top-K hybrid → cross-encoder rerank → top-N.
KV-stage recovery shim into the cascade. 31 tests.
eoc-eval/ 15 canonical eval harnesses: MMLU, MMLU-Pro, GPQA,
HumanEval (pass@1 with python3 sandbox), BBH, IFEval (25
verifiable constraints), AlpacaEval, AGIEval, HellaSwag,
ARC (Easy + Challenge), TruthfulQA (MC1+MC2), BoolQ,
GSM8K, MATH (boxed-answer equivalence), Winogrande. Real
questions in BuiltinSamples. EvalRunner emits joules-per-
correct alongside accuracy. 49 tests.
Quality:
- cargo check across all three workspaces: clean
- cargo clippy --all-targets -- -D warnings on every new crate: clean
- 374 new tests, all passing
- #![forbid(unsafe_code)] across every new crate
- No unwrap/expect outside #[cfg(test)]
Rust 1.95.0 edition 2024 (inherited via root rust-toolchain.toml).
205 lines
6.1 KiB
Rust
205 lines
6.1 KiB
Rust
//! Voyage AI re-rank API client.
|
|
//!
|
|
//! Implements [`Reranker`] for:
|
|
//!
|
|
//! * `rerank-2`
|
|
//! * `rerank-2-lite`
|
|
//!
|
|
//! Endpoint: `POST https://api.voyageai.com/v1/rerank`.
|
|
//!
|
|
//! Voyage's response shape mirrors Cohere's: `data: [{ index, relevance_score }]`.
|
|
|
|
use std::time::Duration;
|
|
|
|
use async_trait::async_trait;
|
|
use eoc_core::JouleCost;
|
|
use serde::Deserialize;
|
|
use serde_json::json;
|
|
use tracing::warn;
|
|
|
|
use crate::error::{RerankError, RerankResult};
|
|
use crate::reranker::{Candidate, Reranker, ScoredCandidate};
|
|
|
|
/// Default endpoint for Voyage rerank v1.
|
|
pub const DEFAULT_ENDPOINT: &str = "https://api.voyageai.com/v1/rerank";
|
|
|
|
/// Voyage rerank client.
|
|
pub struct VoyageReranker {
|
|
api_key: String,
|
|
model: String,
|
|
endpoint: String,
|
|
http: reqwest::Client,
|
|
max_retries: u32,
|
|
microjoules_per_pair: u64,
|
|
}
|
|
|
|
impl VoyageReranker {
|
|
/// Build a new client.
|
|
pub fn new(api_key: impl Into<String>, model: impl Into<String>) -> RerankResult<Self> {
|
|
let model = model.into();
|
|
let microjoules_per_pair = match model.as_str() {
|
|
"rerank-2" => 100,
|
|
"rerank-2-lite" => 45,
|
|
other => return Err(RerankError::ModelNotFound(other.to_string())),
|
|
};
|
|
Ok(Self {
|
|
api_key: api_key.into(),
|
|
model,
|
|
endpoint: DEFAULT_ENDPOINT.to_string(),
|
|
http: reqwest::Client::new(),
|
|
max_retries: 3,
|
|
microjoules_per_pair,
|
|
})
|
|
}
|
|
|
|
/// Override the endpoint (used for tests).
|
|
pub fn with_endpoint(mut self, endpoint: impl Into<String>) -> Self {
|
|
self.endpoint = endpoint.into();
|
|
self
|
|
}
|
|
|
|
/// Override the retry budget.
|
|
pub fn with_max_retries(mut self, n: u32) -> Self {
|
|
self.max_retries = n;
|
|
self
|
|
}
|
|
|
|
/// Build the JSON request body.
|
|
pub fn build_body(&self, query: &str, candidates: &[Candidate]) -> serde_json::Value {
|
|
let docs: Vec<&str> = candidates.iter().map(|c| c.text.as_str()).collect();
|
|
json!({
|
|
"model": self.model,
|
|
"query": query,
|
|
"documents": docs,
|
|
"top_k": docs.len(),
|
|
})
|
|
}
|
|
|
|
/// Estimate energy for re-ranking `pairs` candidates.
|
|
pub fn joule_estimate(&self, pairs: usize) -> JouleCost {
|
|
JouleCost::estimated((pairs as u64).saturating_mul(self.microjoules_per_pair))
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
struct ApiResponse {
|
|
data: Vec<ApiResult>,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
struct ApiResult {
|
|
index: usize,
|
|
relevance_score: f32,
|
|
}
|
|
|
|
#[async_trait]
|
|
impl Reranker for VoyageReranker {
|
|
async fn rerank(
|
|
&self,
|
|
query: &str,
|
|
candidates: &[Candidate],
|
|
) -> RerankResult<Vec<ScoredCandidate>> {
|
|
if candidates.is_empty() {
|
|
return Ok(Vec::new());
|
|
}
|
|
if candidates.len() > self.max_pairs() {
|
|
return Err(RerankError::BatchTooLarge(format!(
|
|
"{} candidates exceeds Voyage v1 limit {}",
|
|
candidates.len(),
|
|
self.max_pairs()
|
|
)));
|
|
}
|
|
let body = self.build_body(query, candidates);
|
|
let mut attempt = 0u32;
|
|
loop {
|
|
let resp = self
|
|
.http
|
|
.post(&self.endpoint)
|
|
.bearer_auth(&self.api_key)
|
|
.json(&body)
|
|
.send()
|
|
.await?;
|
|
let status = resp.status();
|
|
if status.is_success() {
|
|
let parsed: ApiResponse = resp.json().await?;
|
|
let mut out: Vec<ScoredCandidate> = parsed
|
|
.data
|
|
.into_iter()
|
|
.filter_map(|r| {
|
|
candidates.get(r.index).map(|c| ScoredCandidate {
|
|
candidate: c.clone(),
|
|
score: r.relevance_score,
|
|
rank: 0,
|
|
})
|
|
})
|
|
.collect();
|
|
out.sort_by(|a, b| {
|
|
b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal)
|
|
});
|
|
for (i, c) in out.iter_mut().enumerate() {
|
|
c.rank = i + 1;
|
|
}
|
|
return Ok(out);
|
|
}
|
|
if status.as_u16() == 401 || status.as_u16() == 403 {
|
|
return Err(RerankError::InvalidApiKey);
|
|
}
|
|
if status.as_u16() == 429 {
|
|
let retry_after = resp
|
|
.headers()
|
|
.get("retry-after")
|
|
.and_then(|v| v.to_str().ok())
|
|
.and_then(|s| s.parse::<u64>().ok());
|
|
if attempt >= self.max_retries {
|
|
return Err(RerankError::RateLimited {
|
|
retry_after_secs: retry_after,
|
|
});
|
|
}
|
|
let wait = retry_after.unwrap_or(1u64 << attempt.min(4));
|
|
warn!(attempt, wait, "voyage rerank 429; backing off");
|
|
tokio::time::sleep(Duration::from_secs(wait)).await;
|
|
attempt += 1;
|
|
continue;
|
|
}
|
|
let body = resp.text().await.unwrap_or_default();
|
|
let truncated: String = body.chars().take(256).collect();
|
|
return Err(RerankError::Unexpected {
|
|
status: status.as_u16(),
|
|
body: truncated,
|
|
});
|
|
}
|
|
}
|
|
|
|
fn model_name(&self) -> &str {
|
|
&self.model
|
|
}
|
|
|
|
fn max_pairs(&self) -> usize {
|
|
// Voyage v1 caps at 1000.
|
|
1000
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn known_models() {
|
|
assert!(VoyageReranker::new("k", "rerank-2").is_ok());
|
|
assert!(VoyageReranker::new("k", "rerank-2-lite").is_ok());
|
|
assert!(matches!(
|
|
VoyageReranker::new("k", "rerank-99"),
|
|
Err(RerankError::ModelNotFound(_))
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn body_shape() {
|
|
let v = VoyageReranker::new("k", "rerank-2").expect("ok");
|
|
let body = v.build_body("q", &[Candidate::new("a", "alpha")]);
|
|
assert_eq!(body["model"], "rerank-2");
|
|
assert_eq!(body["documents"][0], "alpha");
|
|
assert_eq!(body["top_k"], 1);
|
|
}
|
|
}
|