Skip to main content

openai_protocol/
rerank.rs

1use std::collections::HashMap;
2
3use serde::{Deserialize, Serialize};
4use serde_json::Value;
5use validator::Validate;
6
7use super::common::{default_model, default_true, GenerationRequest, StringOrArray, UsageInfo};
8
9fn default_rerank_object() -> String {
10    "rerank".to_string()
11}
12
13/// TODO: Create timestamp should not be in protocol layer
14fn current_timestamp() -> i64 {
15    std::time::SystemTime::now()
16        .duration_since(std::time::UNIX_EPOCH)
17        .unwrap_or_else(|_| std::time::Duration::from_secs(0))
18        .as_secs() as i64
19}
20
21// ============================================================================
22// Rerank API
23// ============================================================================
24
25#[derive(Debug, Clone, Deserialize, Serialize, Validate)]
26#[validate(schema(function = "validate_rerank_request"))]
27pub struct RerankRequest {
28    /// The query text to rank documents against
29    #[validate(custom(function = "validate_query"))]
30    pub query: String,
31
32    /// List of documents to be ranked
33    #[validate(custom(function = "validate_documents"))]
34    pub documents: Vec<String>,
35
36    /// Model to use for reranking
37    #[serde(default = "default_model")]
38    pub model: String,
39
40    /// Maximum number of documents to return (optional)
41    #[serde(skip_serializing_if = "Option::is_none")]
42    #[validate(range(min = 1))]
43    pub top_k: Option<usize>,
44
45    /// Whether to return documents in addition to scores
46    #[serde(default = "default_true")]
47    pub return_documents: bool,
48
49    // SGLang specific extensions
50    /// Request ID for tracking
51    pub rid: Option<StringOrArray>,
52
53    /// User identifier
54    pub user: Option<String>,
55}
56
57impl GenerationRequest for RerankRequest {
58    fn get_model(&self) -> Option<&str> {
59        Some(&self.model)
60    }
61
62    fn is_stream(&self) -> bool {
63        false // Reranking doesn't support streaming
64    }
65
66    fn extract_text_for_routing(&self) -> String {
67        self.query.clone()
68    }
69}
70
71impl super::validated::Normalizable for RerankRequest {
72    // Use default no-op normalization
73}
74
75// ============================================================================
76// Validation Functions
77// ============================================================================
78
79/// Validates that the query is not empty
80fn validate_query(query: &str) -> Result<(), validator::ValidationError> {
81    if query.trim().is_empty() {
82        return Err(validator::ValidationError::new("query cannot be empty"));
83    }
84    Ok(())
85}
86
87/// Validates that the documents list is not empty
88fn validate_documents(documents: &[String]) -> Result<(), validator::ValidationError> {
89    if documents.is_empty() {
90        return Err(validator::ValidationError::new(
91            "documents list cannot be empty",
92        ));
93    }
94    Ok(())
95}
96
97/// Schema-level validation for cross-field dependencies
98fn validate_rerank_request(req: &RerankRequest) -> Result<(), validator::ValidationError> {
99    // Validate top_k if specified
100    if let Some(k) = req.top_k {
101        if k > req.documents.len() {
102            // This is allowed but we log a warning
103            tracing::warn!(
104                "top_k ({}) is greater than number of documents ({})",
105                k,
106                req.documents.len()
107            );
108        }
109    }
110    Ok(())
111}
112
113impl RerankRequest {
114    /// Get the effective top_k value
115    pub fn effective_top_k(&self) -> usize {
116        self.top_k.unwrap_or(self.documents.len())
117    }
118}
119
120/// Individual rerank result
121#[serde_with::skip_serializing_none]
122#[derive(Debug, Clone, Serialize, Deserialize)]
123pub struct RerankResult {
124    /// Relevance score for the document
125    pub score: f32,
126
127    /// The document text (if return_documents was true)
128    pub document: Option<String>,
129
130    /// Original index of the document in the request
131    pub index: usize,
132
133    /// Additional metadata about the ranking
134    pub meta_info: Option<HashMap<String, Value>>,
135}
136
137/// Rerank response containing sorted results
138#[derive(Debug, Clone, Serialize, Deserialize)]
139pub struct RerankResponse {
140    /// Ranked results sorted by score (highest first)
141    pub results: Vec<RerankResult>,
142
143    /// Model used for reranking
144    pub model: String,
145
146    /// Usage information
147    pub usage: Option<UsageInfo>,
148
149    /// Response object type
150    #[serde(default = "default_rerank_object")]
151    pub object: String,
152
153    /// Response ID
154    pub id: Option<StringOrArray>,
155
156    /// Creation timestamp
157    pub created: i64,
158}
159
160impl RerankResponse {
161    /// Create a new RerankResponse with the given results and model
162    pub fn new(
163        results: Vec<RerankResult>,
164        model: String,
165        request_id: Option<StringOrArray>,
166    ) -> Self {
167        RerankResponse {
168            results,
169            model,
170            usage: None,
171            object: default_rerank_object(),
172            id: request_id,
173            created: current_timestamp(),
174        }
175    }
176
177    /// Apply top_k limit to results
178    pub fn apply_top_k(&mut self, k: usize) {
179        self.results.truncate(k);
180    }
181
182    /// Drop documents from results (when return_documents is false)
183    pub fn drop_documents(&mut self) {
184        for result in &mut self.results {
185            result.document = None;
186        }
187    }
188}
189
190/// V1 API compatibility format for rerank requests
191/// Matches Python's V1RerankReqInput
192#[derive(Debug, Clone, Serialize, Deserialize)]
193pub struct V1RerankReqInput {
194    pub query: String,
195    pub documents: Vec<String>,
196}
197
198/// Convert V1RerankReqInput to RerankRequest
199impl From<V1RerankReqInput> for RerankRequest {
200    fn from(v1: V1RerankReqInput) -> Self {
201        RerankRequest {
202            query: v1.query,
203            documents: v1.documents,
204            model: default_model(),
205            top_k: None,
206            return_documents: true,
207            rid: None,
208            user: None,
209        }
210    }
211}