VectorStoreSearchBuilder

Struct VectorStoreSearchBuilder 

Source
pub struct VectorStoreSearchBuilder { /* private fields */ }
Expand description

Builder for searching through vector stores.

Implementations§

Source§

impl VectorStoreSearchBuilder

Source

pub fn new(vector_store_id: impl Into<String>, query: impl Into<String>) -> Self

Create a new vector store search builder.

Examples found in repository?
examples/vector_stores.rs (line 493)
463fn run_advanced_search_patterns_example() -> Result<(), Error> {
464    println!("\n Example 6: Advanced Search Patterns and Optimization");
465    println!("{}", "=".repeat(60));
466
467    // Create optimized search store
468    let optimized_store = VectorStoreBuilder::new()
469        .name("Advanced Search Optimization Store")
470        .add_file("file-technical-docs-001")
471        .add_file("file-user-feedback-002")
472        .add_file("file-performance-data-003")
473        .add_file("file-best-practices-004")
474        .metadata("search_optimized", "true")
475        .metadata("indexing", "enhanced")
476        .metadata("caching", "enabled");
477
478    println!(" Created advanced search store:");
479    println!("   Optimization: Enhanced indexing");
480    println!("   Caching: Enabled");
481    println!("   Files: {} documents", optimized_store.file_count());
482
483    // Demonstrate advanced search patterns
484    println!("\n Advanced Search Patterns:");
485
486    // Multi-stage search
487    println!("   1.  Multi-stage Search:");
488    println!("      Stage 1: Broad semantic search (100 results)");
489    println!("      Stage 2: Filtered refinement (20 results)");
490    println!("      Stage 3: Relevance re-ranking (5 top results)");
491
492    let multi_stage_search =
493        VectorStoreSearchBuilder::new("advanced-store-789", "machine learning best practices")
494            .limit(100)
495            .filter("category", "best_practices")
496            .filter("verified", "true");
497
498    println!("      Query: '{}'", multi_stage_search.query());
499    println!(
500        "      Initial limit: {}",
501        multi_stage_search.limit_ref().unwrap()
502    );
503
504    // Contextual search
505    println!("   2.  Contextual Search:");
506    println!("      Context: User role, project phase, domain expertise");
507    println!("      Adaptation: Results tailored to user context");
508
509    let _contextual_search =
510        search_vector_store_with_limit("advanced-store-789", "deployment strategies", 15)
511            .filter("audience", "senior_engineer")
512            .filter("complexity", "advanced")
513            .filter("domain", "cloud_infrastructure");
514
515    println!("      Audience: senior_engineer");
516    println!("      Complexity: advanced");
517    println!("      Domain: cloud_infrastructure");
518
519    // Hybrid search approaches
520    println!("   3.  Hybrid Search Approaches:");
521    println!("      Semantic similarity + keyword matching");
522    println!("      Vector search + traditional full-text search");
523    println!("      AI-enhanced query understanding");
524
525    // Search performance optimization
526    println!("\n Search Performance Optimization:");
527    println!("    Query optimization and caching");
528    println!("    Result pre-computation for common queries");
529    println!("    Incremental index updates");
530    println!("    Load balancing across vector stores");
531    println!("    Machine learning-based relevance tuning");
532
533    // Quality metrics and monitoring
534    println!("\n Search Quality Metrics:");
535    println!("    Relevance scores and user feedback");
536    println!("   ⏱ Query response time analysis");
537    println!("    Search success rate tracking");
538    println!("    Usage pattern analysis");
539    println!("    Continuous improvement recommendations");
540
541    Ok(())
542}
Source

pub fn limit(self, limit: i32) -> Self

Set the maximum number of results to return.

Examples found in repository?
examples/vector_stores.rs (line 494)
463fn run_advanced_search_patterns_example() -> Result<(), Error> {
464    println!("\n Example 6: Advanced Search Patterns and Optimization");
465    println!("{}", "=".repeat(60));
466
467    // Create optimized search store
468    let optimized_store = VectorStoreBuilder::new()
469        .name("Advanced Search Optimization Store")
470        .add_file("file-technical-docs-001")
471        .add_file("file-user-feedback-002")
472        .add_file("file-performance-data-003")
473        .add_file("file-best-practices-004")
474        .metadata("search_optimized", "true")
475        .metadata("indexing", "enhanced")
476        .metadata("caching", "enabled");
477
478    println!(" Created advanced search store:");
479    println!("   Optimization: Enhanced indexing");
480    println!("   Caching: Enabled");
481    println!("   Files: {} documents", optimized_store.file_count());
482
483    // Demonstrate advanced search patterns
484    println!("\n Advanced Search Patterns:");
485
486    // Multi-stage search
487    println!("   1.  Multi-stage Search:");
488    println!("      Stage 1: Broad semantic search (100 results)");
489    println!("      Stage 2: Filtered refinement (20 results)");
490    println!("      Stage 3: Relevance re-ranking (5 top results)");
491
492    let multi_stage_search =
493        VectorStoreSearchBuilder::new("advanced-store-789", "machine learning best practices")
494            .limit(100)
495            .filter("category", "best_practices")
496            .filter("verified", "true");
497
498    println!("      Query: '{}'", multi_stage_search.query());
499    println!(
500        "      Initial limit: {}",
501        multi_stage_search.limit_ref().unwrap()
502    );
503
504    // Contextual search
505    println!("   2.  Contextual Search:");
506    println!("      Context: User role, project phase, domain expertise");
507    println!("      Adaptation: Results tailored to user context");
508
509    let _contextual_search =
510        search_vector_store_with_limit("advanced-store-789", "deployment strategies", 15)
511            .filter("audience", "senior_engineer")
512            .filter("complexity", "advanced")
513            .filter("domain", "cloud_infrastructure");
514
515    println!("      Audience: senior_engineer");
516    println!("      Complexity: advanced");
517    println!("      Domain: cloud_infrastructure");
518
519    // Hybrid search approaches
520    println!("   3.  Hybrid Search Approaches:");
521    println!("      Semantic similarity + keyword matching");
522    println!("      Vector search + traditional full-text search");
523    println!("      AI-enhanced query understanding");
524
525    // Search performance optimization
526    println!("\n Search Performance Optimization:");
527    println!("    Query optimization and caching");
528    println!("    Result pre-computation for common queries");
529    println!("    Incremental index updates");
530    println!("    Load balancing across vector stores");
531    println!("    Machine learning-based relevance tuning");
532
533    // Quality metrics and monitoring
534    println!("\n Search Quality Metrics:");
535    println!("    Relevance scores and user feedback");
536    println!("   ⏱ Query response time analysis");
537    println!("    Search success rate tracking");
538    println!("    Usage pattern analysis");
539    println!("    Continuous improvement recommendations");
540
541    Ok(())
542}
Source

pub fn filter(self, key: impl Into<String>, value: impl Into<String>) -> Self

Add a filter to the search.

Examples found in repository?
examples/vector_stores.rs (line 268)
224fn run_semantic_search_example() -> Result<(), Error> {
225    println!("\n Example 3: Semantic Search and Similarity Queries");
226    println!("{}", "=".repeat(60));
227
228    // Create a search-optimized vector store
229    let search_store = simple_vector_store("Semantic Search Demo Store")
230        .add_file("file-ml-concepts-001")
231        .add_file("file-nlp-techniques-002")
232        .add_file("file-deep-learning-003")
233        .add_file("file-computer-vision-004")
234        .add_file("file-ai-ethics-005")
235        .metadata("domain", "machine_learning")
236        .metadata("search_optimized", "true");
237
238    println!(" Created search-optimized vector store:");
239    println!("   Name: {}", search_store.name_ref().unwrap());
240    println!("   Domain: Machine Learning");
241    println!("   Documents: {} files", search_store.file_count());
242
243    // Demonstrate various search patterns
244    println!("\n Search Query Examples:");
245
246    // Basic semantic search
247    let basic_search = search_vector_store("search-store-123", "neural network architectures");
248    println!("   1. Basic Search:");
249    println!("      Query: '{}'", basic_search.query());
250    println!("      Store: {}", basic_search.vector_store_id());
251
252    // Limited result search
253    let limited_search = search_vector_store_with_limit(
254        "search-store-123",
255        "natural language processing techniques",
256        5,
257    );
258    println!("   2. Limited Results:");
259    println!("      Query: '{}'", limited_search.query());
260    println!(
261        "      Limit: {} results",
262        limited_search.limit_ref().unwrap()
263    );
264
265    // Advanced filtered search
266    let filtered_search =
267        search_vector_store_with_limit("search-store-123", "computer vision applications", 10)
268            .filter("category", "practical_applications")
269            .filter("difficulty", "intermediate");
270
271    println!("   3. Filtered Search:");
272    println!("      Query: '{}'", filtered_search.query());
273    println!(
274        "      Filters: {} applied",
275        filtered_search.filter_ref().len()
276    );
277    for (key, value) in filtered_search.filter_ref() {
278        println!("         {}={}", key, value);
279    }
280
281    // Demonstrate search result processing
282    println!("\n Search Result Processing:");
283    println!("    Semantic similarity ranking");
284    println!("    Document excerpt extraction");
285    println!("    Relevance score calculation");
286    println!("    Source location identification");
287    println!("    Related content suggestions");
288
289    // Show different query types
290    println!("\n Query Type Examples:");
291    let query_examples = vec![
292        (
293            "Conceptual",
294            "What is machine learning?",
295            "Broad conceptual understanding",
296        ),
297        (
298            "Technical",
299            "How to implement backpropagation?",
300            "Specific technical implementation",
301        ),
302        (
303            "Comparative",
304            "LSTM vs Transformer architectures",
305            "Comparative analysis",
306        ),
307        (
308            "Problem-solving",
309            "Overfitting in neural networks",
310            "Problem identification and solutions",
311        ),
312        (
313            "Application",
314            "Computer vision in healthcare",
315            "Domain-specific applications",
316        ),
317    ];
318
319    for (query_type, query, description) in query_examples {
320        println!("    {}: '{}'", query_type, query);
321        println!("      Purpose: {}", description);
322    }
323
324    Ok(())
325}
326
327/// Example 4: Enterprise Knowledge Base
328fn run_enterprise_knowledge_base_example() -> Result<(), Error> {
329    println!("\n Example 4: Enterprise Knowledge Base");
330    println!("{}", "=".repeat(60));
331
332    // Create enterprise-scale vector stores
333    let enterprise_stores = create_enterprise_knowledge_base()?;
334
335    println!(" Enterprise Knowledge Base Architecture:");
336    for (department, store) in enterprise_stores {
337        println!("    {}", department);
338        println!("      Files: {} documents", store.file_count());
339        println!(
340            "      Retention: {} days",
341            store
342                .expires_after_ref()
343                .map_or("permanent".to_string(), |exp| exp.days.to_string())
344                .as_str()
345        );
346
347        // Show metadata structure
348        for (key, value) in store.metadata_ref() {
349            println!("      {}: {}", key, value);
350        }
351        println!();
352    }
353
354    // Demonstrate cross-departmental search
355    println!(" Cross-Departmental Search Examples:");
356
357    let cross_searches = vec![
358        (
359            "Security Compliance",
360            "GDPR data handling procedures",
361            vec!["legal", "engineering", "hr"],
362        ),
363        (
364            "Product Launch",
365            "Q4 release planning and coordination",
366            vec!["product", "engineering", "marketing"],
367        ),
368        (
369            "Budget Planning",
370            "Annual technology investment strategy",
371            vec!["finance", "engineering", "executive"],
372        ),
373        (
374            "Process Improvement",
375            "Remote work productivity guidelines",
376            vec!["hr", "operations", "it"],
377        ),
378    ];
379
380    for (topic, query, departments) in cross_searches {
381        println!("    {}: '{}'", topic, query);
382        println!("      Search scope: {}", departments.join(", "));
383    }
384
385    println!("\n Enterprise Features:");
386    println!("    Role-based access control");
387    println!("    Usage analytics and monitoring");
388    println!("    Automated content lifecycle management");
389    println!("    Search performance optimization");
390    println!("    Backup and disaster recovery");
391    println!("    Compliance and audit trails");
392
393    Ok(())
394}
395
396/// Example 5: Vector Store Lifecycle Management
397fn run_vector_store_lifecycle_example() -> Result<(), Error> {
398    println!("\n Example 5: Vector Store Lifecycle Management");
399    println!("{}", "=".repeat(60));
400
401    // Demonstrate different lifecycle patterns
402    println!("⏰ Vector Store Lifecycle Patterns:");
403
404    // Temporary stores for sessions
405    let session_store = temporary_vector_store("User Session Store", 1)
406        .add_file("file-session-context-001")
407        .metadata("session_id", "sess_12345")
408        .metadata("user_id", "user_67890");
409
410    println!("    Session-based (1 day):");
411    println!("      Purpose: Temporary user context");
412    println!("      Files: {}", session_store.file_count());
413    println!("      Auto-cleanup: ");
414
415    // Project stores
416    let project_store = temporary_vector_store("Project Alpha Documentation", 90)
417        .add_file("file-project-spec-001")
418        .add_file("file-meeting-notes-002")
419        .add_file("file-progress-reports-003")
420        .metadata("project_id", "proj_alpha_2024")
421        .metadata("phase", "development");
422
423    println!("    Project-based (90 days):");
424    println!("      Purpose: Project lifecycle documentation");
425    println!("      Files: {}", project_store.file_count());
426    println!("      Cleanup: After project completion");
427
428    // Long-term knowledge stores
429    let knowledge_store = simple_vector_store("Institutional Knowledge Base")
430        .add_file("file-company-history-001")
431        .add_file("file-best-practices-002")
432        .add_file("file-lessons-learned-003")
433        .metadata("retention", "permanent")
434        .metadata("backup", "enabled")
435        .metadata("compliance", "required");
436
437    println!("    Institutional (permanent):");
438    println!("      Purpose: Long-term organizational knowledge");
439    println!("      Files: {}", knowledge_store.file_count());
440    println!("      Cleanup: Manual review only");
441
442    // Demonstrate lifecycle events
443    println!("\n Lifecycle Event Handling:");
444    println!("    Creation: Automatic indexing and optimization");
445    println!("    Updates: Incremental re-indexing of modified files");
446    println!("    Monitoring: Usage tracking and performance metrics");
447    println!("    Warnings: Expiration notifications and alerts");
448    println!("    Cleanup: Automatic or manual deletion processes");
449    println!("    Archival: Long-term storage for compliance");
450
451    // Show cost optimization strategies
452    println!("\n Cost Optimization Strategies:");
453    println!("    Smart expiration policies based on usage");
454    println!("    Analytics-driven storage optimization");
455    println!("    Automatic compression for archived content");
456    println!("    Tiered storage (hot, warm, cold)");
457    println!("    Usage-based scaling recommendations");
458
459    Ok(())
460}
461
462/// Example 6: Advanced Search Patterns and Optimization
463fn run_advanced_search_patterns_example() -> Result<(), Error> {
464    println!("\n Example 6: Advanced Search Patterns and Optimization");
465    println!("{}", "=".repeat(60));
466
467    // Create optimized search store
468    let optimized_store = VectorStoreBuilder::new()
469        .name("Advanced Search Optimization Store")
470        .add_file("file-technical-docs-001")
471        .add_file("file-user-feedback-002")
472        .add_file("file-performance-data-003")
473        .add_file("file-best-practices-004")
474        .metadata("search_optimized", "true")
475        .metadata("indexing", "enhanced")
476        .metadata("caching", "enabled");
477
478    println!(" Created advanced search store:");
479    println!("   Optimization: Enhanced indexing");
480    println!("   Caching: Enabled");
481    println!("   Files: {} documents", optimized_store.file_count());
482
483    // Demonstrate advanced search patterns
484    println!("\n Advanced Search Patterns:");
485
486    // Multi-stage search
487    println!("   1.  Multi-stage Search:");
488    println!("      Stage 1: Broad semantic search (100 results)");
489    println!("      Stage 2: Filtered refinement (20 results)");
490    println!("      Stage 3: Relevance re-ranking (5 top results)");
491
492    let multi_stage_search =
493        VectorStoreSearchBuilder::new("advanced-store-789", "machine learning best practices")
494            .limit(100)
495            .filter("category", "best_practices")
496            .filter("verified", "true");
497
498    println!("      Query: '{}'", multi_stage_search.query());
499    println!(
500        "      Initial limit: {}",
501        multi_stage_search.limit_ref().unwrap()
502    );
503
504    // Contextual search
505    println!("   2.  Contextual Search:");
506    println!("      Context: User role, project phase, domain expertise");
507    println!("      Adaptation: Results tailored to user context");
508
509    let _contextual_search =
510        search_vector_store_with_limit("advanced-store-789", "deployment strategies", 15)
511            .filter("audience", "senior_engineer")
512            .filter("complexity", "advanced")
513            .filter("domain", "cloud_infrastructure");
514
515    println!("      Audience: senior_engineer");
516    println!("      Complexity: advanced");
517    println!("      Domain: cloud_infrastructure");
518
519    // Hybrid search approaches
520    println!("   3.  Hybrid Search Approaches:");
521    println!("      Semantic similarity + keyword matching");
522    println!("      Vector search + traditional full-text search");
523    println!("      AI-enhanced query understanding");
524
525    // Search performance optimization
526    println!("\n Search Performance Optimization:");
527    println!("    Query optimization and caching");
528    println!("    Result pre-computation for common queries");
529    println!("    Incremental index updates");
530    println!("    Load balancing across vector stores");
531    println!("    Machine learning-based relevance tuning");
532
533    // Quality metrics and monitoring
534    println!("\n Search Quality Metrics:");
535    println!("    Relevance scores and user feedback");
536    println!("   ⏱ Query response time analysis");
537    println!("    Search success rate tracking");
538    println!("    Usage pattern analysis");
539    println!("    Continuous improvement recommendations");
540
541    Ok(())
542}
More examples
Hide additional examples
examples/assistants_file_search.rs (line 256)
206fn run_research_assistant_example() -> Result<(), Error> {
207    println!("\n Example 3: Research Assistant with Advanced RAG");
208    println!("{}", "=".repeat(60));
209
210    // Create research-focused assistant
211    let _research_assistant = assistant_with_instructions(
212        "gpt-4-1106-preview",
213        "Research Assistant",
214        "You are a research assistant specializing in literature review and analysis. Help researchers find relevant information, identify patterns across documents, synthesize findings, and suggest research directions. Always provide comprehensive citations and acknowledge research limitations."
215    )
216    .add_tool(tool_file_search());
217
218    println!(" Created research assistant:");
219    println!("   Focus: Literature review and cross-document analysis");
220
221    // Create a comprehensive research vector store
222    let _research_store = VectorStoreBuilder::new()
223        .name("Research Literature Database")
224        .add_file("file-paper-ai-ethics-001")
225        .add_file("file-paper-ml-bias-002")
226        .add_file("file-paper-fairness-003")
227        .add_file("file-survey-responsible-ai-004")
228        .add_file("file-whitepaper-governance-005")
229        .metadata("domain", "AI Ethics")
230        .metadata("papers_count", "50")
231        .metadata("date_range", "2020-2024");
232
233    println!("\n Research Literature Database:");
234    println!("   Domain: AI Ethics and Responsible AI");
235    println!("   Papers: 5 documents loaded (representing 50 papers)");
236    println!("   Date range: 2020-2024");
237
238    println!("\n Research Query:");
239    println!(
240        "   'What are the current approaches to addressing algorithmic bias in machine learning?'"
241    );
242    println!("   'Please provide a comprehensive overview with citations.'");
243
244    println!("\n Advanced RAG Research Workflow:");
245    println!("   1.  Query analysis and decomposition");
246    println!("   2.  Multi-faceted search across all documents");
247    println!("   3.  Semantic clustering of results");
248    println!("   4.  Cross-reference analysis between papers");
249    println!("   5.  Identify trends and patterns");
250    println!("   6.  Synthesize comprehensive overview");
251    println!("   7.  Provide detailed citations and references");
252
253    // Demonstrate search refinement
254    let refined_search =
255        search_vector_store_with_limit("research-db-123", "algorithmic bias mitigation", 20)
256            .filter("category", "methodology")
257            .filter("confidence", "high");
258
259    println!("\n Search Refinement:");
260    println!("   Query: algorithmic bias mitigation");
261    println!("   Limit: {} results", refined_search.limit_ref().unwrap());
262    println!("   Filters: category=methodology, confidence=high");
263
264    println!("\n Expected Research Response:");
265    println!("    Executive Summary:");
266    println!("      • Overview of current bias mitigation approaches");
267    println!("      • Key methodological categories identified");
268    println!("      • Emerging trends and best practices");
269    println!("   ");
270    println!("    Detailed Analysis:");
271    println!("      • Pre-processing techniques (data augmentation, sampling)");
272    println!("      • In-processing methods (fairness constraints, adversarial training)");
273    println!("      • Post-processing approaches (threshold optimization, calibration)");
274    println!("   ");
275    println!("    Comprehensive Citations:");
276    println!("      • [Smith et al., 2023] - Fairness constraints in ML training");
277    println!("      • [Johnson & Lee, 2024] - Bias detection in neural networks");
278    println!("      • [Research Survey, 2024] - Comprehensive bias mitigation review");
279    println!("   ");
280    println!("    Future Research Directions:");
281    println!("      • Intersectional bias analysis");
282    println!("      • Real-time bias monitoring");
283    println!("      • Domain-specific mitigation strategies");
284
285    Ok(())
286}
287
288/// Example 4: Citation and Source Attribution
289fn run_citation_example() -> Result<(), Error> {
290    println!("\n Example 4: Citation and Source Attribution");
291    println!("{}", "=".repeat(60));
292
293    // Create citation-focused assistant
294    let _citation_assistant = AssistantBuilder::new("gpt-4-1106-preview")
295        .name("Citation Specialist")
296        .description("Provides detailed source attribution and citation management")
297        .instructions(
298            "You are a citation specialist. Always provide accurate, detailed citations for any information retrieved from documents. Use proper academic citation formats, include page numbers when available, and distinguish between direct quotes and paraphrased content."
299        )
300        .add_tool(tool_file_search());
301
302    println!(" Created citation specialist assistant:");
303    println!("   Focus: Accurate source attribution and citation formatting");
304
305    // Create thread for citation-heavy work
306    let _citation_thread = simple_thread()
307        .metadata("citation_style", "APA")
308        .metadata("requirement", "academic_standards")
309        .metadata("verification", "enabled");
310
311    println!("\n Citation Requirements:");
312    println!("   Style: APA format");
313    println!("   Standards: Academic-level accuracy");
314    println!("   Verification: Enabled for all sources");
315
316    println!("\n Citation Query:");
317    println!("   'Provide a summary of the key arguments about privacy in AI systems,'");
318    println!("   'with detailed citations for each point made.'");
319
320    println!("\n Citation-Focused RAG Workflow:");
321    println!("   1.  Search for relevant content across documents");
322    println!("   2.  Extract content with precise location data");
323    println!("   3.  Generate response with inline citations");
324    println!("   4.  Verify citation accuracy and completeness");
325    println!("   5.  Format citations according to specified style");
326    println!("   6.  Cross-check for citation consistency");
327
328    // Demonstrate different citation formats
329    println!("\n Citation Format Examples:");
330    println!("    Direct Quote:");
331    println!(
332        "      \"Privacy-preserving AI requires careful balance between utility and protection\""
333    );
334    println!("      (Johnson, 2024, p. 15)");
335    println!("   ");
336    println!("    Paraphrased Content:");
337    println!("      Recent research indicates that differential privacy methods show promise");
338    println!("      for protecting individual data in ML training (Smith & Lee, 2023).");
339    println!("   ");
340    println!("    Multiple Source Synthesis:");
341    println!("      Several studies have demonstrated the effectiveness of federated learning");
342    println!("      approaches (Chen et al., 2023; Rodriguez, 2024; Brown & Wilson, 2023).");
343
344    println!("\n Expected Citation Response:");
345    println!("    Structured Summary with Citations:");
346    println!("      • Privacy challenges in AI systems (Anderson, 2024, pp. 23-25)");
347    println!("      • Technical solutions: differential privacy (Johnson et al., 2023)");
348    println!("      • Regulatory considerations (Privacy Commission Report, 2024, §3.2)");
349    println!("   ");
350    println!("    Reference List:");
351    println!(
352        "      Anderson, M. (2024). AI Privacy Challenges. Tech Ethics Journal, 15(3), 20-30."
353    );
354    println!("      Johnson, P., Smith, R., & Lee, K. (2023). Differential privacy in practice.");
355    println!("      Privacy Commission. (2024). AI governance guidelines (Report #2024-AI-001).");
356
357    Ok(())
358}
359
360/// Example 5: Multi-Document Analysis and Synthesis
361fn run_multi_document_analysis_example() -> Result<(), Error> {
362    println!("\n Example 5: Multi-Document Analysis and Synthesis");
363    println!("{}", "=".repeat(60));
364
365    // Create multi-document analysis assistant
366    let _analysis_assistant = assistant_with_instructions(
367        "gpt-4-1106-preview",
368        "Document Analysis Specialist",
369        "You are a document analysis expert. Compare and contrast information across multiple documents, identify contradictions or gaps, synthesize information from diverse sources, and provide comprehensive analysis that considers multiple perspectives."
370    )
371    .add_tool(tool_file_search());
372
373    println!(" Created document analysis assistant:");
374    println!("   Specialty: Cross-document comparison and synthesis");
375
376    // Create comprehensive document store for analysis
377    let _analysis_store = VectorStoreBuilder::new()
378        .name("Multi-Document Analysis Store")
379        .add_file("file-policy-proposal-v1")
380        .add_file("file-policy-proposal-v2")
381        .add_file("file-stakeholder-feedback-001")
382        .add_file("file-legal-review-002")
383        .add_file("file-technical-assessment-003")
384        .add_file("file-cost-benefit-analysis-004")
385        .metadata("analysis_type", "policy_comparison")
386        .metadata("documents", "6")
387        .metadata("perspectives", "multiple");
388
389    println!("\n Multi-Document Analysis Setup:");
390    println!("   Documents: 6 files representing different perspectives");
391    println!("   Analysis type: Policy proposal comparison");
392    println!("   Perspectives: Technical, legal, financial, stakeholder");
393
394    println!("\n Multi-Document Analysis Query:");
395    println!("   'Compare the two policy proposals and analyze how stakeholder feedback'");
396    println!("   'has been incorporated. Identify any conflicts between the legal review'");
397    println!("   'and technical assessment.'");
398
399    println!("\n Multi-Document RAG Analysis Workflow:");
400    println!("   1.  Identify key comparison dimensions");
401    println!("   2.  Search each document type systematically");
402    println!("   3.  Create comparison matrix across documents");
403    println!("   4.  Identify conflicts and contradictions");
404    println!("   5.  Find connections and dependencies");
405    println!("   6.  Synthesize comprehensive analysis");
406    println!("   7.  Provide recommendations based on synthesis");
407
408    // Demonstrate advanced search patterns
409    let _comparative_search =
410        search_vector_store_with_limit("analysis-store-456", "risk assessment comparison", 15)
411            .filter("document_type", "technical,legal")
412            .filter("section", "risks");
413
414    println!("\n Advanced Search Pattern:");
415    println!("   Query: risk assessment comparison");
416    println!("   Target documents: technical + legal reviews");
417    println!("   Focus section: risk analysis sections");
418
419    println!("\n Expected Multi-Document Analysis:");
420    println!("    Comparative Analysis:");
421    println!("      Policy Proposal Comparison:");
422    println!("      • V1 focuses on immediate implementation (Technical Assessment)");
423    println!("      • V2 incorporates phased approach (Stakeholder Feedback)");
424    println!("   ");
425    println!("    Identified Conflicts:");
426    println!("      • Legal review flags compliance issues with V1 approach");
427    println!("      • Technical assessment questions feasibility of V2 timeline");
428    println!("      • Cost analysis shows budget misalignment between proposals");
429    println!("   ");
430    println!("    Stakeholder Integration:");
431    println!("      • 73% of feedback incorporated in V2 (Stakeholder Feedback doc)");
432    println!("      • Privacy concerns addressed through technical modifications");
433    println!("      • Cost concerns partially resolved via phased implementation");
434    println!("   ");
435    println!("    Synthesis Recommendations:");
436    println!("      • Hybrid approach combining V1 technical framework with V2 timeline");
437    println!("      • Address legal compliance through additional technical review");
438    println!("      • Require budget revision to align with stakeholder expectations");
439
440    Ok(())
441}
Source

pub fn vector_store_id(&self) -> &str

Get the vector store ID for this search.

Examples found in repository?
examples/vector_stores.rs (line 250)
224fn run_semantic_search_example() -> Result<(), Error> {
225    println!("\n Example 3: Semantic Search and Similarity Queries");
226    println!("{}", "=".repeat(60));
227
228    // Create a search-optimized vector store
229    let search_store = simple_vector_store("Semantic Search Demo Store")
230        .add_file("file-ml-concepts-001")
231        .add_file("file-nlp-techniques-002")
232        .add_file("file-deep-learning-003")
233        .add_file("file-computer-vision-004")
234        .add_file("file-ai-ethics-005")
235        .metadata("domain", "machine_learning")
236        .metadata("search_optimized", "true");
237
238    println!(" Created search-optimized vector store:");
239    println!("   Name: {}", search_store.name_ref().unwrap());
240    println!("   Domain: Machine Learning");
241    println!("   Documents: {} files", search_store.file_count());
242
243    // Demonstrate various search patterns
244    println!("\n Search Query Examples:");
245
246    // Basic semantic search
247    let basic_search = search_vector_store("search-store-123", "neural network architectures");
248    println!("   1. Basic Search:");
249    println!("      Query: '{}'", basic_search.query());
250    println!("      Store: {}", basic_search.vector_store_id());
251
252    // Limited result search
253    let limited_search = search_vector_store_with_limit(
254        "search-store-123",
255        "natural language processing techniques",
256        5,
257    );
258    println!("   2. Limited Results:");
259    println!("      Query: '{}'", limited_search.query());
260    println!(
261        "      Limit: {} results",
262        limited_search.limit_ref().unwrap()
263    );
264
265    // Advanced filtered search
266    let filtered_search =
267        search_vector_store_with_limit("search-store-123", "computer vision applications", 10)
268            .filter("category", "practical_applications")
269            .filter("difficulty", "intermediate");
270
271    println!("   3. Filtered Search:");
272    println!("      Query: '{}'", filtered_search.query());
273    println!(
274        "      Filters: {} applied",
275        filtered_search.filter_ref().len()
276    );
277    for (key, value) in filtered_search.filter_ref() {
278        println!("         {}={}", key, value);
279    }
280
281    // Demonstrate search result processing
282    println!("\n Search Result Processing:");
283    println!("    Semantic similarity ranking");
284    println!("    Document excerpt extraction");
285    println!("    Relevance score calculation");
286    println!("    Source location identification");
287    println!("    Related content suggestions");
288
289    // Show different query types
290    println!("\n Query Type Examples:");
291    let query_examples = vec![
292        (
293            "Conceptual",
294            "What is machine learning?",
295            "Broad conceptual understanding",
296        ),
297        (
298            "Technical",
299            "How to implement backpropagation?",
300            "Specific technical implementation",
301        ),
302        (
303            "Comparative",
304            "LSTM vs Transformer architectures",
305            "Comparative analysis",
306        ),
307        (
308            "Problem-solving",
309            "Overfitting in neural networks",
310            "Problem identification and solutions",
311        ),
312        (
313            "Application",
314            "Computer vision in healthcare",
315            "Domain-specific applications",
316        ),
317    ];
318
319    for (query_type, query, description) in query_examples {
320        println!("    {}: '{}'", query_type, query);
321        println!("      Purpose: {}", description);
322    }
323
324    Ok(())
325}
Source

pub fn query(&self) -> &str

Get the search query.

Examples found in repository?
examples/vector_stores.rs (line 249)
224fn run_semantic_search_example() -> Result<(), Error> {
225    println!("\n Example 3: Semantic Search and Similarity Queries");
226    println!("{}", "=".repeat(60));
227
228    // Create a search-optimized vector store
229    let search_store = simple_vector_store("Semantic Search Demo Store")
230        .add_file("file-ml-concepts-001")
231        .add_file("file-nlp-techniques-002")
232        .add_file("file-deep-learning-003")
233        .add_file("file-computer-vision-004")
234        .add_file("file-ai-ethics-005")
235        .metadata("domain", "machine_learning")
236        .metadata("search_optimized", "true");
237
238    println!(" Created search-optimized vector store:");
239    println!("   Name: {}", search_store.name_ref().unwrap());
240    println!("   Domain: Machine Learning");
241    println!("   Documents: {} files", search_store.file_count());
242
243    // Demonstrate various search patterns
244    println!("\n Search Query Examples:");
245
246    // Basic semantic search
247    let basic_search = search_vector_store("search-store-123", "neural network architectures");
248    println!("   1. Basic Search:");
249    println!("      Query: '{}'", basic_search.query());
250    println!("      Store: {}", basic_search.vector_store_id());
251
252    // Limited result search
253    let limited_search = search_vector_store_with_limit(
254        "search-store-123",
255        "natural language processing techniques",
256        5,
257    );
258    println!("   2. Limited Results:");
259    println!("      Query: '{}'", limited_search.query());
260    println!(
261        "      Limit: {} results",
262        limited_search.limit_ref().unwrap()
263    );
264
265    // Advanced filtered search
266    let filtered_search =
267        search_vector_store_with_limit("search-store-123", "computer vision applications", 10)
268            .filter("category", "practical_applications")
269            .filter("difficulty", "intermediate");
270
271    println!("   3. Filtered Search:");
272    println!("      Query: '{}'", filtered_search.query());
273    println!(
274        "      Filters: {} applied",
275        filtered_search.filter_ref().len()
276    );
277    for (key, value) in filtered_search.filter_ref() {
278        println!("         {}={}", key, value);
279    }
280
281    // Demonstrate search result processing
282    println!("\n Search Result Processing:");
283    println!("    Semantic similarity ranking");
284    println!("    Document excerpt extraction");
285    println!("    Relevance score calculation");
286    println!("    Source location identification");
287    println!("    Related content suggestions");
288
289    // Show different query types
290    println!("\n Query Type Examples:");
291    let query_examples = vec![
292        (
293            "Conceptual",
294            "What is machine learning?",
295            "Broad conceptual understanding",
296        ),
297        (
298            "Technical",
299            "How to implement backpropagation?",
300            "Specific technical implementation",
301        ),
302        (
303            "Comparative",
304            "LSTM vs Transformer architectures",
305            "Comparative analysis",
306        ),
307        (
308            "Problem-solving",
309            "Overfitting in neural networks",
310            "Problem identification and solutions",
311        ),
312        (
313            "Application",
314            "Computer vision in healthcare",
315            "Domain-specific applications",
316        ),
317    ];
318
319    for (query_type, query, description) in query_examples {
320        println!("    {}: '{}'", query_type, query);
321        println!("      Purpose: {}", description);
322    }
323
324    Ok(())
325}
326
327/// Example 4: Enterprise Knowledge Base
328fn run_enterprise_knowledge_base_example() -> Result<(), Error> {
329    println!("\n Example 4: Enterprise Knowledge Base");
330    println!("{}", "=".repeat(60));
331
332    // Create enterprise-scale vector stores
333    let enterprise_stores = create_enterprise_knowledge_base()?;
334
335    println!(" Enterprise Knowledge Base Architecture:");
336    for (department, store) in enterprise_stores {
337        println!("    {}", department);
338        println!("      Files: {} documents", store.file_count());
339        println!(
340            "      Retention: {} days",
341            store
342                .expires_after_ref()
343                .map_or("permanent".to_string(), |exp| exp.days.to_string())
344                .as_str()
345        );
346
347        // Show metadata structure
348        for (key, value) in store.metadata_ref() {
349            println!("      {}: {}", key, value);
350        }
351        println!();
352    }
353
354    // Demonstrate cross-departmental search
355    println!(" Cross-Departmental Search Examples:");
356
357    let cross_searches = vec![
358        (
359            "Security Compliance",
360            "GDPR data handling procedures",
361            vec!["legal", "engineering", "hr"],
362        ),
363        (
364            "Product Launch",
365            "Q4 release planning and coordination",
366            vec!["product", "engineering", "marketing"],
367        ),
368        (
369            "Budget Planning",
370            "Annual technology investment strategy",
371            vec!["finance", "engineering", "executive"],
372        ),
373        (
374            "Process Improvement",
375            "Remote work productivity guidelines",
376            vec!["hr", "operations", "it"],
377        ),
378    ];
379
380    for (topic, query, departments) in cross_searches {
381        println!("    {}: '{}'", topic, query);
382        println!("      Search scope: {}", departments.join(", "));
383    }
384
385    println!("\n Enterprise Features:");
386    println!("    Role-based access control");
387    println!("    Usage analytics and monitoring");
388    println!("    Automated content lifecycle management");
389    println!("    Search performance optimization");
390    println!("    Backup and disaster recovery");
391    println!("    Compliance and audit trails");
392
393    Ok(())
394}
395
396/// Example 5: Vector Store Lifecycle Management
397fn run_vector_store_lifecycle_example() -> Result<(), Error> {
398    println!("\n Example 5: Vector Store Lifecycle Management");
399    println!("{}", "=".repeat(60));
400
401    // Demonstrate different lifecycle patterns
402    println!("⏰ Vector Store Lifecycle Patterns:");
403
404    // Temporary stores for sessions
405    let session_store = temporary_vector_store("User Session Store", 1)
406        .add_file("file-session-context-001")
407        .metadata("session_id", "sess_12345")
408        .metadata("user_id", "user_67890");
409
410    println!("    Session-based (1 day):");
411    println!("      Purpose: Temporary user context");
412    println!("      Files: {}", session_store.file_count());
413    println!("      Auto-cleanup: ");
414
415    // Project stores
416    let project_store = temporary_vector_store("Project Alpha Documentation", 90)
417        .add_file("file-project-spec-001")
418        .add_file("file-meeting-notes-002")
419        .add_file("file-progress-reports-003")
420        .metadata("project_id", "proj_alpha_2024")
421        .metadata("phase", "development");
422
423    println!("    Project-based (90 days):");
424    println!("      Purpose: Project lifecycle documentation");
425    println!("      Files: {}", project_store.file_count());
426    println!("      Cleanup: After project completion");
427
428    // Long-term knowledge stores
429    let knowledge_store = simple_vector_store("Institutional Knowledge Base")
430        .add_file("file-company-history-001")
431        .add_file("file-best-practices-002")
432        .add_file("file-lessons-learned-003")
433        .metadata("retention", "permanent")
434        .metadata("backup", "enabled")
435        .metadata("compliance", "required");
436
437    println!("    Institutional (permanent):");
438    println!("      Purpose: Long-term organizational knowledge");
439    println!("      Files: {}", knowledge_store.file_count());
440    println!("      Cleanup: Manual review only");
441
442    // Demonstrate lifecycle events
443    println!("\n Lifecycle Event Handling:");
444    println!("    Creation: Automatic indexing and optimization");
445    println!("    Updates: Incremental re-indexing of modified files");
446    println!("    Monitoring: Usage tracking and performance metrics");
447    println!("    Warnings: Expiration notifications and alerts");
448    println!("    Cleanup: Automatic or manual deletion processes");
449    println!("    Archival: Long-term storage for compliance");
450
451    // Show cost optimization strategies
452    println!("\n Cost Optimization Strategies:");
453    println!("    Smart expiration policies based on usage");
454    println!("    Analytics-driven storage optimization");
455    println!("    Automatic compression for archived content");
456    println!("    Tiered storage (hot, warm, cold)");
457    println!("    Usage-based scaling recommendations");
458
459    Ok(())
460}
461
462/// Example 6: Advanced Search Patterns and Optimization
463fn run_advanced_search_patterns_example() -> Result<(), Error> {
464    println!("\n Example 6: Advanced Search Patterns and Optimization");
465    println!("{}", "=".repeat(60));
466
467    // Create optimized search store
468    let optimized_store = VectorStoreBuilder::new()
469        .name("Advanced Search Optimization Store")
470        .add_file("file-technical-docs-001")
471        .add_file("file-user-feedback-002")
472        .add_file("file-performance-data-003")
473        .add_file("file-best-practices-004")
474        .metadata("search_optimized", "true")
475        .metadata("indexing", "enhanced")
476        .metadata("caching", "enabled");
477
478    println!(" Created advanced search store:");
479    println!("   Optimization: Enhanced indexing");
480    println!("   Caching: Enabled");
481    println!("   Files: {} documents", optimized_store.file_count());
482
483    // Demonstrate advanced search patterns
484    println!("\n Advanced Search Patterns:");
485
486    // Multi-stage search
487    println!("   1.  Multi-stage Search:");
488    println!("      Stage 1: Broad semantic search (100 results)");
489    println!("      Stage 2: Filtered refinement (20 results)");
490    println!("      Stage 3: Relevance re-ranking (5 top results)");
491
492    let multi_stage_search =
493        VectorStoreSearchBuilder::new("advanced-store-789", "machine learning best practices")
494            .limit(100)
495            .filter("category", "best_practices")
496            .filter("verified", "true");
497
498    println!("      Query: '{}'", multi_stage_search.query());
499    println!(
500        "      Initial limit: {}",
501        multi_stage_search.limit_ref().unwrap()
502    );
503
504    // Contextual search
505    println!("   2.  Contextual Search:");
506    println!("      Context: User role, project phase, domain expertise");
507    println!("      Adaptation: Results tailored to user context");
508
509    let _contextual_search =
510        search_vector_store_with_limit("advanced-store-789", "deployment strategies", 15)
511            .filter("audience", "senior_engineer")
512            .filter("complexity", "advanced")
513            .filter("domain", "cloud_infrastructure");
514
515    println!("      Audience: senior_engineer");
516    println!("      Complexity: advanced");
517    println!("      Domain: cloud_infrastructure");
518
519    // Hybrid search approaches
520    println!("   3.  Hybrid Search Approaches:");
521    println!("      Semantic similarity + keyword matching");
522    println!("      Vector search + traditional full-text search");
523    println!("      AI-enhanced query understanding");
524
525    // Search performance optimization
526    println!("\n Search Performance Optimization:");
527    println!("    Query optimization and caching");
528    println!("    Result pre-computation for common queries");
529    println!("    Incremental index updates");
530    println!("    Load balancing across vector stores");
531    println!("    Machine learning-based relevance tuning");
532
533    // Quality metrics and monitoring
534    println!("\n Search Quality Metrics:");
535    println!("    Relevance scores and user feedback");
536    println!("   ⏱ Query response time analysis");
537    println!("    Search success rate tracking");
538    println!("    Usage pattern analysis");
539    println!("    Continuous improvement recommendations");
540
541    Ok(())
542}
Source

pub fn limit_ref(&self) -> Option<i32>

Get the search limit.

Examples found in repository?
examples/vector_stores.rs (line 262)
224fn run_semantic_search_example() -> Result<(), Error> {
225    println!("\n Example 3: Semantic Search and Similarity Queries");
226    println!("{}", "=".repeat(60));
227
228    // Create a search-optimized vector store
229    let search_store = simple_vector_store("Semantic Search Demo Store")
230        .add_file("file-ml-concepts-001")
231        .add_file("file-nlp-techniques-002")
232        .add_file("file-deep-learning-003")
233        .add_file("file-computer-vision-004")
234        .add_file("file-ai-ethics-005")
235        .metadata("domain", "machine_learning")
236        .metadata("search_optimized", "true");
237
238    println!(" Created search-optimized vector store:");
239    println!("   Name: {}", search_store.name_ref().unwrap());
240    println!("   Domain: Machine Learning");
241    println!("   Documents: {} files", search_store.file_count());
242
243    // Demonstrate various search patterns
244    println!("\n Search Query Examples:");
245
246    // Basic semantic search
247    let basic_search = search_vector_store("search-store-123", "neural network architectures");
248    println!("   1. Basic Search:");
249    println!("      Query: '{}'", basic_search.query());
250    println!("      Store: {}", basic_search.vector_store_id());
251
252    // Limited result search
253    let limited_search = search_vector_store_with_limit(
254        "search-store-123",
255        "natural language processing techniques",
256        5,
257    );
258    println!("   2. Limited Results:");
259    println!("      Query: '{}'", limited_search.query());
260    println!(
261        "      Limit: {} results",
262        limited_search.limit_ref().unwrap()
263    );
264
265    // Advanced filtered search
266    let filtered_search =
267        search_vector_store_with_limit("search-store-123", "computer vision applications", 10)
268            .filter("category", "practical_applications")
269            .filter("difficulty", "intermediate");
270
271    println!("   3. Filtered Search:");
272    println!("      Query: '{}'", filtered_search.query());
273    println!(
274        "      Filters: {} applied",
275        filtered_search.filter_ref().len()
276    );
277    for (key, value) in filtered_search.filter_ref() {
278        println!("         {}={}", key, value);
279    }
280
281    // Demonstrate search result processing
282    println!("\n Search Result Processing:");
283    println!("    Semantic similarity ranking");
284    println!("    Document excerpt extraction");
285    println!("    Relevance score calculation");
286    println!("    Source location identification");
287    println!("    Related content suggestions");
288
289    // Show different query types
290    println!("\n Query Type Examples:");
291    let query_examples = vec![
292        (
293            "Conceptual",
294            "What is machine learning?",
295            "Broad conceptual understanding",
296        ),
297        (
298            "Technical",
299            "How to implement backpropagation?",
300            "Specific technical implementation",
301        ),
302        (
303            "Comparative",
304            "LSTM vs Transformer architectures",
305            "Comparative analysis",
306        ),
307        (
308            "Problem-solving",
309            "Overfitting in neural networks",
310            "Problem identification and solutions",
311        ),
312        (
313            "Application",
314            "Computer vision in healthcare",
315            "Domain-specific applications",
316        ),
317    ];
318
319    for (query_type, query, description) in query_examples {
320        println!("    {}: '{}'", query_type, query);
321        println!("      Purpose: {}", description);
322    }
323
324    Ok(())
325}
326
327/// Example 4: Enterprise Knowledge Base
328fn run_enterprise_knowledge_base_example() -> Result<(), Error> {
329    println!("\n Example 4: Enterprise Knowledge Base");
330    println!("{}", "=".repeat(60));
331
332    // Create enterprise-scale vector stores
333    let enterprise_stores = create_enterprise_knowledge_base()?;
334
335    println!(" Enterprise Knowledge Base Architecture:");
336    for (department, store) in enterprise_stores {
337        println!("    {}", department);
338        println!("      Files: {} documents", store.file_count());
339        println!(
340            "      Retention: {} days",
341            store
342                .expires_after_ref()
343                .map_or("permanent".to_string(), |exp| exp.days.to_string())
344                .as_str()
345        );
346
347        // Show metadata structure
348        for (key, value) in store.metadata_ref() {
349            println!("      {}: {}", key, value);
350        }
351        println!();
352    }
353
354    // Demonstrate cross-departmental search
355    println!(" Cross-Departmental Search Examples:");
356
357    let cross_searches = vec![
358        (
359            "Security Compliance",
360            "GDPR data handling procedures",
361            vec!["legal", "engineering", "hr"],
362        ),
363        (
364            "Product Launch",
365            "Q4 release planning and coordination",
366            vec!["product", "engineering", "marketing"],
367        ),
368        (
369            "Budget Planning",
370            "Annual technology investment strategy",
371            vec!["finance", "engineering", "executive"],
372        ),
373        (
374            "Process Improvement",
375            "Remote work productivity guidelines",
376            vec!["hr", "operations", "it"],
377        ),
378    ];
379
380    for (topic, query, departments) in cross_searches {
381        println!("    {}: '{}'", topic, query);
382        println!("      Search scope: {}", departments.join(", "));
383    }
384
385    println!("\n Enterprise Features:");
386    println!("    Role-based access control");
387    println!("    Usage analytics and monitoring");
388    println!("    Automated content lifecycle management");
389    println!("    Search performance optimization");
390    println!("    Backup and disaster recovery");
391    println!("    Compliance and audit trails");
392
393    Ok(())
394}
395
396/// Example 5: Vector Store Lifecycle Management
397fn run_vector_store_lifecycle_example() -> Result<(), Error> {
398    println!("\n Example 5: Vector Store Lifecycle Management");
399    println!("{}", "=".repeat(60));
400
401    // Demonstrate different lifecycle patterns
402    println!("⏰ Vector Store Lifecycle Patterns:");
403
404    // Temporary stores for sessions
405    let session_store = temporary_vector_store("User Session Store", 1)
406        .add_file("file-session-context-001")
407        .metadata("session_id", "sess_12345")
408        .metadata("user_id", "user_67890");
409
410    println!("    Session-based (1 day):");
411    println!("      Purpose: Temporary user context");
412    println!("      Files: {}", session_store.file_count());
413    println!("      Auto-cleanup: ");
414
415    // Project stores
416    let project_store = temporary_vector_store("Project Alpha Documentation", 90)
417        .add_file("file-project-spec-001")
418        .add_file("file-meeting-notes-002")
419        .add_file("file-progress-reports-003")
420        .metadata("project_id", "proj_alpha_2024")
421        .metadata("phase", "development");
422
423    println!("    Project-based (90 days):");
424    println!("      Purpose: Project lifecycle documentation");
425    println!("      Files: {}", project_store.file_count());
426    println!("      Cleanup: After project completion");
427
428    // Long-term knowledge stores
429    let knowledge_store = simple_vector_store("Institutional Knowledge Base")
430        .add_file("file-company-history-001")
431        .add_file("file-best-practices-002")
432        .add_file("file-lessons-learned-003")
433        .metadata("retention", "permanent")
434        .metadata("backup", "enabled")
435        .metadata("compliance", "required");
436
437    println!("    Institutional (permanent):");
438    println!("      Purpose: Long-term organizational knowledge");
439    println!("      Files: {}", knowledge_store.file_count());
440    println!("      Cleanup: Manual review only");
441
442    // Demonstrate lifecycle events
443    println!("\n Lifecycle Event Handling:");
444    println!("    Creation: Automatic indexing and optimization");
445    println!("    Updates: Incremental re-indexing of modified files");
446    println!("    Monitoring: Usage tracking and performance metrics");
447    println!("    Warnings: Expiration notifications and alerts");
448    println!("    Cleanup: Automatic or manual deletion processes");
449    println!("    Archival: Long-term storage for compliance");
450
451    // Show cost optimization strategies
452    println!("\n Cost Optimization Strategies:");
453    println!("    Smart expiration policies based on usage");
454    println!("    Analytics-driven storage optimization");
455    println!("    Automatic compression for archived content");
456    println!("    Tiered storage (hot, warm, cold)");
457    println!("    Usage-based scaling recommendations");
458
459    Ok(())
460}
461
462/// Example 6: Advanced Search Patterns and Optimization
463fn run_advanced_search_patterns_example() -> Result<(), Error> {
464    println!("\n Example 6: Advanced Search Patterns and Optimization");
465    println!("{}", "=".repeat(60));
466
467    // Create optimized search store
468    let optimized_store = VectorStoreBuilder::new()
469        .name("Advanced Search Optimization Store")
470        .add_file("file-technical-docs-001")
471        .add_file("file-user-feedback-002")
472        .add_file("file-performance-data-003")
473        .add_file("file-best-practices-004")
474        .metadata("search_optimized", "true")
475        .metadata("indexing", "enhanced")
476        .metadata("caching", "enabled");
477
478    println!(" Created advanced search store:");
479    println!("   Optimization: Enhanced indexing");
480    println!("   Caching: Enabled");
481    println!("   Files: {} documents", optimized_store.file_count());
482
483    // Demonstrate advanced search patterns
484    println!("\n Advanced Search Patterns:");
485
486    // Multi-stage search
487    println!("   1.  Multi-stage Search:");
488    println!("      Stage 1: Broad semantic search (100 results)");
489    println!("      Stage 2: Filtered refinement (20 results)");
490    println!("      Stage 3: Relevance re-ranking (5 top results)");
491
492    let multi_stage_search =
493        VectorStoreSearchBuilder::new("advanced-store-789", "machine learning best practices")
494            .limit(100)
495            .filter("category", "best_practices")
496            .filter("verified", "true");
497
498    println!("      Query: '{}'", multi_stage_search.query());
499    println!(
500        "      Initial limit: {}",
501        multi_stage_search.limit_ref().unwrap()
502    );
503
504    // Contextual search
505    println!("   2.  Contextual Search:");
506    println!("      Context: User role, project phase, domain expertise");
507    println!("      Adaptation: Results tailored to user context");
508
509    let _contextual_search =
510        search_vector_store_with_limit("advanced-store-789", "deployment strategies", 15)
511            .filter("audience", "senior_engineer")
512            .filter("complexity", "advanced")
513            .filter("domain", "cloud_infrastructure");
514
515    println!("      Audience: senior_engineer");
516    println!("      Complexity: advanced");
517    println!("      Domain: cloud_infrastructure");
518
519    // Hybrid search approaches
520    println!("   3.  Hybrid Search Approaches:");
521    println!("      Semantic similarity + keyword matching");
522    println!("      Vector search + traditional full-text search");
523    println!("      AI-enhanced query understanding");
524
525    // Search performance optimization
526    println!("\n Search Performance Optimization:");
527    println!("    Query optimization and caching");
528    println!("    Result pre-computation for common queries");
529    println!("    Incremental index updates");
530    println!("    Load balancing across vector stores");
531    println!("    Machine learning-based relevance tuning");
532
533    // Quality metrics and monitoring
534    println!("\n Search Quality Metrics:");
535    println!("    Relevance scores and user feedback");
536    println!("   ⏱ Query response time analysis");
537    println!("    Search success rate tracking");
538    println!("    Usage pattern analysis");
539    println!("    Continuous improvement recommendations");
540
541    Ok(())
542}
More examples
Hide additional examples
examples/assistants_file_search.rs (line 261)
206fn run_research_assistant_example() -> Result<(), Error> {
207    println!("\n Example 3: Research Assistant with Advanced RAG");
208    println!("{}", "=".repeat(60));
209
210    // Create research-focused assistant
211    let _research_assistant = assistant_with_instructions(
212        "gpt-4-1106-preview",
213        "Research Assistant",
214        "You are a research assistant specializing in literature review and analysis. Help researchers find relevant information, identify patterns across documents, synthesize findings, and suggest research directions. Always provide comprehensive citations and acknowledge research limitations."
215    )
216    .add_tool(tool_file_search());
217
218    println!(" Created research assistant:");
219    println!("   Focus: Literature review and cross-document analysis");
220
221    // Create a comprehensive research vector store
222    let _research_store = VectorStoreBuilder::new()
223        .name("Research Literature Database")
224        .add_file("file-paper-ai-ethics-001")
225        .add_file("file-paper-ml-bias-002")
226        .add_file("file-paper-fairness-003")
227        .add_file("file-survey-responsible-ai-004")
228        .add_file("file-whitepaper-governance-005")
229        .metadata("domain", "AI Ethics")
230        .metadata("papers_count", "50")
231        .metadata("date_range", "2020-2024");
232
233    println!("\n Research Literature Database:");
234    println!("   Domain: AI Ethics and Responsible AI");
235    println!("   Papers: 5 documents loaded (representing 50 papers)");
236    println!("   Date range: 2020-2024");
237
238    println!("\n Research Query:");
239    println!(
240        "   'What are the current approaches to addressing algorithmic bias in machine learning?'"
241    );
242    println!("   'Please provide a comprehensive overview with citations.'");
243
244    println!("\n Advanced RAG Research Workflow:");
245    println!("   1.  Query analysis and decomposition");
246    println!("   2.  Multi-faceted search across all documents");
247    println!("   3.  Semantic clustering of results");
248    println!("   4.  Cross-reference analysis between papers");
249    println!("   5.  Identify trends and patterns");
250    println!("   6.  Synthesize comprehensive overview");
251    println!("   7.  Provide detailed citations and references");
252
253    // Demonstrate search refinement
254    let refined_search =
255        search_vector_store_with_limit("research-db-123", "algorithmic bias mitigation", 20)
256            .filter("category", "methodology")
257            .filter("confidence", "high");
258
259    println!("\n Search Refinement:");
260    println!("   Query: algorithmic bias mitigation");
261    println!("   Limit: {} results", refined_search.limit_ref().unwrap());
262    println!("   Filters: category=methodology, confidence=high");
263
264    println!("\n Expected Research Response:");
265    println!("    Executive Summary:");
266    println!("      • Overview of current bias mitigation approaches");
267    println!("      • Key methodological categories identified");
268    println!("      • Emerging trends and best practices");
269    println!("   ");
270    println!("    Detailed Analysis:");
271    println!("      • Pre-processing techniques (data augmentation, sampling)");
272    println!("      • In-processing methods (fairness constraints, adversarial training)");
273    println!("      • Post-processing approaches (threshold optimization, calibration)");
274    println!("   ");
275    println!("    Comprehensive Citations:");
276    println!("      • [Smith et al., 2023] - Fairness constraints in ML training");
277    println!("      • [Johnson & Lee, 2024] - Bias detection in neural networks");
278    println!("      • [Research Survey, 2024] - Comprehensive bias mitigation review");
279    println!("   ");
280    println!("    Future Research Directions:");
281    println!("      • Intersectional bias analysis");
282    println!("      • Real-time bias monitoring");
283    println!("      • Domain-specific mitigation strategies");
284
285    Ok(())
286}
Source

pub fn filter_ref(&self) -> &HashMap<String, String>

Get the search filters.

Examples found in repository?
examples/vector_stores.rs (line 275)
224fn run_semantic_search_example() -> Result<(), Error> {
225    println!("\n Example 3: Semantic Search and Similarity Queries");
226    println!("{}", "=".repeat(60));
227
228    // Create a search-optimized vector store
229    let search_store = simple_vector_store("Semantic Search Demo Store")
230        .add_file("file-ml-concepts-001")
231        .add_file("file-nlp-techniques-002")
232        .add_file("file-deep-learning-003")
233        .add_file("file-computer-vision-004")
234        .add_file("file-ai-ethics-005")
235        .metadata("domain", "machine_learning")
236        .metadata("search_optimized", "true");
237
238    println!(" Created search-optimized vector store:");
239    println!("   Name: {}", search_store.name_ref().unwrap());
240    println!("   Domain: Machine Learning");
241    println!("   Documents: {} files", search_store.file_count());
242
243    // Demonstrate various search patterns
244    println!("\n Search Query Examples:");
245
246    // Basic semantic search
247    let basic_search = search_vector_store("search-store-123", "neural network architectures");
248    println!("   1. Basic Search:");
249    println!("      Query: '{}'", basic_search.query());
250    println!("      Store: {}", basic_search.vector_store_id());
251
252    // Limited result search
253    let limited_search = search_vector_store_with_limit(
254        "search-store-123",
255        "natural language processing techniques",
256        5,
257    );
258    println!("   2. Limited Results:");
259    println!("      Query: '{}'", limited_search.query());
260    println!(
261        "      Limit: {} results",
262        limited_search.limit_ref().unwrap()
263    );
264
265    // Advanced filtered search
266    let filtered_search =
267        search_vector_store_with_limit("search-store-123", "computer vision applications", 10)
268            .filter("category", "practical_applications")
269            .filter("difficulty", "intermediate");
270
271    println!("   3. Filtered Search:");
272    println!("      Query: '{}'", filtered_search.query());
273    println!(
274        "      Filters: {} applied",
275        filtered_search.filter_ref().len()
276    );
277    for (key, value) in filtered_search.filter_ref() {
278        println!("         {}={}", key, value);
279    }
280
281    // Demonstrate search result processing
282    println!("\n Search Result Processing:");
283    println!("    Semantic similarity ranking");
284    println!("    Document excerpt extraction");
285    println!("    Relevance score calculation");
286    println!("    Source location identification");
287    println!("    Related content suggestions");
288
289    // Show different query types
290    println!("\n Query Type Examples:");
291    let query_examples = vec![
292        (
293            "Conceptual",
294            "What is machine learning?",
295            "Broad conceptual understanding",
296        ),
297        (
298            "Technical",
299            "How to implement backpropagation?",
300            "Specific technical implementation",
301        ),
302        (
303            "Comparative",
304            "LSTM vs Transformer architectures",
305            "Comparative analysis",
306        ),
307        (
308            "Problem-solving",
309            "Overfitting in neural networks",
310            "Problem identification and solutions",
311        ),
312        (
313            "Application",
314            "Computer vision in healthcare",
315            "Domain-specific applications",
316        ),
317    ];
318
319    for (query_type, query, description) in query_examples {
320        println!("    {}: '{}'", query_type, query);
321        println!("      Purpose: {}", description);
322    }
323
324    Ok(())
325}

Trait Implementations§

Source§

impl Clone for VectorStoreSearchBuilder

Source§

fn clone(&self) -> VectorStoreSearchBuilder

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for VectorStoreSearchBuilder

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,