1use anyhow::Result;
7use serde::{Deserialize, Serialize};
8use std::collections::HashMap;
9use tracing::{debug, info};
10
11#[derive(Debug, Clone, Serialize, Deserialize)]
13pub struct RefinementSuggestion {
14 pub suggestion_type: RefinementType,
16 pub original: String,
18 pub suggested: String,
20 pub reason: String,
22 pub confidence: f32,
24 pub example: Option<String>,
26}
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
30pub enum RefinementType {
31 AddFilter,
33 AddOrdering,
35 AddLimit,
37 AddAggregation,
39 Simplify,
41 AddConstraints,
43 OptimizePerformance,
45 ClarifyAmbiguity,
47 AddJoin,
49 BetterPredicates,
51}
52
53#[derive(Debug, Clone, Serialize, Deserialize)]
55pub struct QueryAnalysis {
56 pub original_query: String,
58 pub complexity: u8,
60 pub estimated_results: Option<usize>,
62 pub performance_issues: Vec<String>,
64 pub ambiguities: Vec<String>,
66 pub missing_optimizations: Vec<String>,
68}
69
70#[derive(Debug, Clone, Serialize, Deserialize)]
72pub struct RefinementConfig {
73 pub max_suggestions: usize,
75 pub min_confidence: f32,
77 pub suggest_performance: bool,
79 pub suggest_clarity: bool,
81 pub suggest_features: bool,
83}
84
85impl Default for RefinementConfig {
86 fn default() -> Self {
87 Self {
88 max_suggestions: 5,
89 min_confidence: 0.6,
90 suggest_performance: true,
91 suggest_clarity: true,
92 suggest_features: true,
93 }
94 }
95}
96
97pub struct QueryRefiner {
99 config: RefinementConfig,
100 conversation_history: Vec<ConversationTurn>,
102 learned_patterns: HashMap<String, Vec<String>>,
104}
105
106#[derive(Debug, Clone, Serialize, Deserialize)]
108pub struct ConversationTurn {
109 pub query: String,
110 pub refined_query: Option<String>,
111 pub intent: Option<String>,
112 pub entities: Vec<String>,
113 pub timestamp: chrono::DateTime<chrono::Utc>,
114}
115
116impl QueryRefiner {
117 pub fn new(config: RefinementConfig) -> Self {
119 info!("Initialized context-aware query refiner with multi-turn conversation support");
120 Self {
121 config,
122 conversation_history: Vec::new(),
123 learned_patterns: HashMap::new(),
124 }
125 }
126
127 pub fn add_turn(
129 &mut self,
130 query: String,
131 refined_query: Option<String>,
132 intent: Option<String>,
133 entities: Vec<String>,
134 ) {
135 self.conversation_history.push(ConversationTurn {
136 query,
137 refined_query,
138 intent,
139 entities,
140 timestamp: chrono::Utc::now(),
141 });
142
143 if self.conversation_history.len() > 10 {
145 self.conversation_history.remove(0);
146 }
147 }
148
149 fn get_context(&self) -> HashMap<String, String> {
151 let mut context = HashMap::new();
152
153 let recent_entities: Vec<String> = self
155 .conversation_history
156 .iter()
157 .rev()
158 .take(3)
159 .flat_map(|turn| turn.entities.clone())
160 .collect();
161
162 if !recent_entities.is_empty() {
163 context.insert("recent_entities".to_string(), recent_entities.join(", "));
164 }
165
166 if let Some(recent_turn) = self.conversation_history.last() {
168 if let Some(ref intent) = recent_turn.intent {
169 context.insert("recent_intent".to_string(), intent.clone());
170 }
171 }
172
173 context
174 }
175
176 pub fn refine(&self, query: &str) -> Result<Vec<RefinementSuggestion>> {
178 debug!("Analyzing query for refinements: {}", query);
179
180 let context = self.get_context();
181 let analysis = self.analyze_query(query)?;
182 let mut suggestions = Vec::new();
183
184 suggestions.extend(self.suggest_context_aware_refinements(query, &context)?);
186
187 if self.config.suggest_performance {
189 suggestions.extend(self.suggest_performance_improvements(&analysis)?);
190 }
191
192 if self.config.suggest_clarity {
194 suggestions.extend(self.suggest_clarity_improvements(&analysis)?);
195 }
196
197 if self.config.suggest_features {
199 suggestions.extend(self.suggest_feature_additions(&analysis)?);
200 }
201
202 suggestions.retain(|s| s.confidence >= self.config.min_confidence);
204
205 suggestions.sort_by(|a, b| {
207 b.confidence
208 .partial_cmp(&a.confidence)
209 .unwrap_or(std::cmp::Ordering::Equal)
210 });
211
212 suggestions.truncate(self.config.max_suggestions);
214
215 info!("Generated {} refinement suggestions", suggestions.len());
216
217 Ok(suggestions)
218 }
219
220 fn analyze_query(&self, query: &str) -> Result<QueryAnalysis> {
222 let lowercase = query.to_lowercase();
223
224 let mut performance_issues = Vec::new();
225 let mut ambiguities = Vec::new();
226 let mut missing_optimizations = Vec::new();
227
228 if !lowercase.contains("limit") {
230 missing_optimizations
231 .push("No LIMIT clause - query may return too many results".to_string());
232 }
233
234 if (lowercase.contains("list") || lowercase.contains("show"))
236 && !lowercase.contains("order")
237 && !lowercase.contains("sort")
238 {
239 missing_optimizations
240 .push("Results not ordered - consider adding ORDER BY".to_string());
241 }
242
243 if lowercase.contains("thing")
245 || lowercase.contains("stuff")
246 || lowercase.contains("something")
247 {
248 ambiguities.push("Vague terms detected - be more specific".to_string());
249 }
250
251 if lowercase.contains("all") && !lowercase.contains("limit") {
253 performance_issues.push("Requesting 'all' without LIMIT may be slow".to_string());
254 }
255
256 let complexity = self.estimate_complexity(query);
258
259 Ok(QueryAnalysis {
260 original_query: query.to_string(),
261 complexity,
262 estimated_results: None,
263 performance_issues,
264 ambiguities,
265 missing_optimizations,
266 })
267 }
268
269 fn estimate_complexity(&self, query: &str) -> u8 {
271 let mut complexity = 1u8;
272
273 complexity += (query.split_whitespace().count() / 10).min(3) as u8;
275
276 let complex_keywords = [
278 "aggregate",
279 "group",
280 "having",
281 "union",
282 "optional",
283 "filter",
284 "minus",
285 ];
286 for keyword in &complex_keywords {
287 if query.to_lowercase().contains(keyword) {
288 complexity += 1;
289 }
290 }
291
292 complexity.min(10)
293 }
294
295 fn suggest_performance_improvements(
297 &self,
298 analysis: &QueryAnalysis,
299 ) -> Result<Vec<RefinementSuggestion>> {
300 let mut suggestions = Vec::new();
301
302 if !analysis.original_query.to_lowercase().contains("limit") {
304 suggestions.push(RefinementSuggestion {
305 suggestion_type: RefinementType::AddLimit,
306 original: analysis.original_query.clone(),
307 suggested: format!("{} LIMIT 100", analysis.original_query.trim()),
308 reason: "Add LIMIT to prevent returning too many results".to_string(),
309 confidence: 0.9,
310 example: Some("SELECT * WHERE { ?s ?p ?o } LIMIT 100".to_string()),
311 });
312 }
313
314 for issue in &analysis.performance_issues {
316 if issue.contains("slow") {
317 suggestions.push(RefinementSuggestion {
318 suggestion_type: RefinementType::OptimizePerformance,
319 original: analysis.original_query.clone(),
320 suggested: "Consider adding filters to narrow the search".to_string(),
321 reason: issue.clone(),
322 confidence: 0.75,
323 example: Some(
324 "SELECT * WHERE { ?s rdf:type :Movie . ?s :year 2023 } LIMIT 100"
325 .to_string(),
326 ),
327 });
328 }
329 }
330
331 Ok(suggestions)
332 }
333
334 fn suggest_clarity_improvements(
336 &self,
337 analysis: &QueryAnalysis,
338 ) -> Result<Vec<RefinementSuggestion>> {
339 let mut suggestions = Vec::new();
340
341 for ambiguity in &analysis.ambiguities {
342 suggestions.push(RefinementSuggestion {
343 suggestion_type: RefinementType::ClarifyAmbiguity,
344 original: analysis.original_query.clone(),
345 suggested: "Replace vague terms with specific entity types or properties"
346 .to_string(),
347 reason: ambiguity.clone(),
348 confidence: 0.8,
349 example: Some(
350 "Instead of 'show me things', use 'show me movies' or 'show me people'"
351 .to_string(),
352 ),
353 });
354 }
355
356 if analysis.original_query.len() < 20 {
358 suggestions.push(RefinementSuggestion {
359 suggestion_type: RefinementType::ClarifyAmbiguity,
360 original: analysis.original_query.clone(),
361 suggested: "Add more details to your query".to_string(),
362 reason: "Short query may be too vague".to_string(),
363 confidence: 0.65,
364 example: Some("Instead of 'movies', try 'movies released in 2023'".to_string()),
365 });
366 }
367
368 Ok(suggestions)
369 }
370
371 fn suggest_feature_additions(
373 &self,
374 analysis: &QueryAnalysis,
375 ) -> Result<Vec<RefinementSuggestion>> {
376 let mut suggestions = Vec::new();
377 let lowercase = analysis.original_query.to_lowercase();
378
379 if !lowercase.contains("order") && !lowercase.contains("sort") {
381 suggestions.push(RefinementSuggestion {
382 suggestion_type: RefinementType::AddOrdering,
383 original: analysis.original_query.clone(),
384 suggested: "Add ORDER BY to sort results".to_string(),
385 reason: "Ordered results are easier to browse".to_string(),
386 confidence: 0.7,
387 example: Some("SELECT * WHERE { ?s ?p ?o } ORDER BY ?s LIMIT 100".to_string()),
388 });
389 }
390
391 if (lowercase.contains("list") || lowercase.contains("show"))
393 && !lowercase.contains("count")
394 {
395 suggestions.push(RefinementSuggestion {
396 suggestion_type: RefinementType::AddAggregation,
397 original: analysis.original_query.clone(),
398 suggested: "Consider counting results instead of listing all".to_string(),
399 reason: "Aggregation provides quick overview".to_string(),
400 confidence: 0.6,
401 example: Some(
402 "SELECT (COUNT(?s) as ?count) WHERE { ?s rdf:type :Movie }".to_string(),
403 ),
404 });
405 }
406
407 if lowercase.contains("all") || lowercase.contains("everything") {
409 suggestions.push(RefinementSuggestion {
410 suggestion_type: RefinementType::AddFilter,
411 original: analysis.original_query.clone(),
412 suggested: "Add filters to narrow down results".to_string(),
413 reason: "Filtering improves result relevance".to_string(),
414 confidence: 0.75,
415 example: Some("FILTER (?year > 2020)".to_string()),
416 });
417 }
418
419 Ok(suggestions)
420 }
421
422 pub fn apply_suggestion(
424 &self,
425 query: &str,
426 suggestion: &RefinementSuggestion,
427 ) -> Result<String> {
428 match suggestion.suggestion_type {
429 RefinementType::AddLimit => {
430 if !query.to_lowercase().contains("limit") {
431 Ok(format!("{} LIMIT 100", query.trim()))
432 } else {
433 Ok(query.to_string())
434 }
435 }
436 RefinementType::AddOrdering => {
437 if !query.to_lowercase().contains("order by") {
438 if let Some(limit_pos) = query.to_lowercase().find("limit") {
440 let mut refined = query.to_string();
441 refined.insert_str(limit_pos, "ORDER BY ?s ");
442 Ok(refined)
443 } else {
444 Ok(format!("{} ORDER BY ?s", query.trim()))
445 }
446 } else {
447 Ok(query.to_string())
448 }
449 }
450 _ => {
451 Ok(suggestion.suggested.clone())
453 }
454 }
455 }
456
457 pub fn start_refinement_session(&self, initial_query: &str) -> RefinementSession {
459 RefinementSession {
460 original_query: initial_query.to_string(),
461 current_query: initial_query.to_string(),
462 applied_suggestions: Vec::new(),
463 iteration: 0,
464 context: self.get_context(),
465 }
466 }
467
468 fn suggest_context_aware_refinements(
470 &self,
471 query: &str,
472 context: &HashMap<String, String>,
473 ) -> Result<Vec<RefinementSuggestion>> {
474 let mut suggestions = Vec::new();
475
476 if let Some(recent_entities) = context.get("recent_entities") {
478 if !query
479 .to_lowercase()
480 .contains(&recent_entities.to_lowercase())
481 {
482 suggestions.push(RefinementSuggestion {
483 suggestion_type: RefinementType::AddConstraints,
484 original: query.to_string(),
485 suggested: format!("{} related to {}", query, recent_entities),
486 reason: format!("Building on previous context about {}", recent_entities),
487 confidence: 0.75,
488 example: Some(format!(
489 "Continue from previous query about {}",
490 recent_entities
491 )),
492 });
493 }
494 }
495
496 if self.conversation_history.len() >= 2 {
498 let prev_queries: Vec<String> = self
499 .conversation_history
500 .iter()
501 .rev()
502 .take(3)
503 .map(|t| t.query.clone())
504 .collect();
505
506 if prev_queries
507 .iter()
508 .all(|q| q.to_lowercase().contains("count"))
509 && !query.to_lowercase().contains("count")
510 {
511 suggestions.push(RefinementSuggestion {
512 suggestion_type: RefinementType::AddAggregation,
513 original: query.to_string(),
514 suggested: format!("count {}", query),
515 reason: "You've been asking for counts - continue the pattern?".to_string(),
516 confidence: 0.65,
517 example: Some("SELECT (COUNT(?x) as ?count) WHERE ...".to_string()),
518 });
519 }
520 }
521
522 Ok(suggestions)
523 }
524
525 pub fn learn_from_feedback(&mut self, original: String, refined: String, accepted: bool) {
527 if accepted {
528 self.learned_patterns
529 .entry(original.clone())
530 .or_default()
531 .push(refined.clone());
532
533 debug!(
534 "Learned new refinement pattern: {} -> {}",
535 original, refined
536 );
537 }
538 }
539
540 pub fn get_history(&self) -> &[ConversationTurn] {
542 &self.conversation_history
543 }
544
545 pub fn clear_history(&mut self) {
547 self.conversation_history.clear();
548 info!("Cleared conversation history");
549 }
550}
551
552#[derive(Debug, Clone, Serialize, Deserialize)]
554pub struct RefinementSession {
555 pub original_query: String,
557 pub current_query: String,
559 pub applied_suggestions: Vec<RefinementSuggestion>,
561 pub iteration: usize,
563 pub context: HashMap<String, String>,
565}
566
567impl RefinementSession {
568 pub fn apply(&mut self, suggestion: RefinementSuggestion, refined_query: String) {
570 self.current_query = refined_query;
571 self.applied_suggestions.push(suggestion);
572 self.iteration += 1;
573 }
574
575 pub fn summary(&self) -> String {
577 format!(
578 "Refined query in {} iterations, applied {} suggestions",
579 self.iteration,
580 self.applied_suggestions.len()
581 )
582 }
583}
584
585#[cfg(test)]
586mod tests {
587 use super::*;
588
589 #[test]
590 fn test_query_analysis() {
591 let refiner = QueryRefiner::new(RefinementConfig::default());
592 let analysis = refiner
593 .analyze_query("show me all things")
594 .expect("should succeed");
595
596 assert!(!analysis.performance_issues.is_empty());
597 assert!(!analysis.ambiguities.is_empty());
598 }
599
600 #[test]
601 fn test_limit_suggestion() {
602 let refiner = QueryRefiner::new(RefinementConfig::default());
603 let suggestions = refiner
604 .refine("SELECT * WHERE { ?s ?p ?o }")
605 .expect("should succeed");
606
607 assert!(suggestions
608 .iter()
609 .any(|s| s.suggestion_type == RefinementType::AddLimit));
610 }
611
612 #[test]
613 fn test_apply_limit() {
614 let refiner = QueryRefiner::new(RefinementConfig::default());
615 let suggestion = RefinementSuggestion {
616 suggestion_type: RefinementType::AddLimit,
617 original: "SELECT * WHERE { ?s ?p ?o }".to_string(),
618 suggested: "SELECT * WHERE { ?s ?p ?o } LIMIT 100".to_string(),
619 reason: "Add limit".to_string(),
620 confidence: 0.9,
621 example: None,
622 };
623
624 let refined = refiner
625 .apply_suggestion("SELECT * WHERE { ?s ?p ?o }", &suggestion)
626 .expect("should succeed");
627 assert!(refined.contains("LIMIT"));
628 }
629
630 #[test]
631 fn test_refinement_session() {
632 let refiner = QueryRefiner::new(RefinementConfig::default());
633 let mut session = refiner.start_refinement_session("show me movies");
634
635 let suggestion = RefinementSuggestion {
636 suggestion_type: RefinementType::AddLimit,
637 original: "show me movies".to_string(),
638 suggested: "show me movies LIMIT 100".to_string(),
639 reason: "Add limit".to_string(),
640 confidence: 0.9,
641 example: None,
642 };
643
644 session.apply(suggestion, "show me movies LIMIT 100".to_string());
645 assert_eq!(session.iteration, 1);
646 assert_eq!(session.applied_suggestions.len(), 1);
647 }
648}