VectorStoreBuilder

Struct VectorStoreBuilder 

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

Builder for creating a new vector store.

Vector stores are collections of files that can be searched through using semantic similarity. They’re commonly used for RAG applications.

Implementations§

Source§

impl VectorStoreBuilder

Source

pub fn new() -> Self

Create a new vector store builder.

§Examples
use openai_ergonomic::builders::vector_stores::VectorStoreBuilder;

let builder = VectorStoreBuilder::new()
    .name("My Knowledge Base")
    .file_ids(vec!["file-123".to_string(), "file-456".to_string()]);
Examples found in repository?
examples/vector_stores.rs (line 468)
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}
543
544/// Helper function to create enterprise knowledge base structure
545fn create_enterprise_knowledge_base() -> Result<Vec<(String, VectorStoreBuilder)>, Error> {
546    let departments = vec![
547        ("Engineering".to_string(), create_engineering_store()),
548        ("Legal".to_string(), create_legal_store()),
549        ("HR".to_string(), create_hr_store()),
550        ("Marketing".to_string(), create_marketing_store()),
551        ("Finance".to_string(), create_finance_store()),
552        ("Operations".to_string(), create_operations_store()),
553    ];
554
555    Ok(departments)
556}
557
558fn create_engineering_store() -> VectorStoreBuilder {
559    VectorStoreBuilder::new()
560        .name("Engineering Knowledge Base")
561        .add_file("file-architecture-docs-001")
562        .add_file("file-coding-standards-002")
563        .add_file("file-deployment-guides-003")
564        .add_file("file-api-documentation-004")
565        .metadata("department", "engineering")
566        .metadata("access_level", "engineering_team")
567        .metadata("update_frequency", "weekly")
568        .expires_after_days(365)
569}
570
571fn create_legal_store() -> VectorStoreBuilder {
572    VectorStoreBuilder::new()
573        .name("Legal Documentation Store")
574        .add_file("file-contracts-templates-001")
575        .add_file("file-compliance-guides-002")
576        .add_file("file-policy-documents-003")
577        .metadata("department", "legal")
578        .metadata("access_level", "legal_team")
579        .metadata("confidentiality", "high")
580        .expires_after_days(2555) // 7 years for legal retention
581}
582
583fn create_hr_store() -> VectorStoreBuilder {
584    VectorStoreBuilder::new()
585        .name("Human Resources Knowledge Base")
586        .add_file("file-employee-handbook-001")
587        .add_file("file-benefits-guide-002")
588        .add_file("file-performance-templates-003")
589        .metadata("department", "hr")
590        .metadata("access_level", "hr_managers")
591        .metadata("privacy", "employee_data")
592        .expires_after_days(1095) // 3 years
593}
594
595fn create_marketing_store() -> VectorStoreBuilder {
596    VectorStoreBuilder::new()
597        .name("Marketing Materials Store")
598        .add_file("file-brand-guidelines-001")
599        .add_file("file-campaign-templates-002")
600        .add_file("file-market-research-003")
601        .metadata("department", "marketing")
602        .metadata("access_level", "marketing_team")
603        .metadata("content_type", "creative_assets")
604        .expires_after_days(365)
605}
606
607fn create_finance_store() -> VectorStoreBuilder {
608    VectorStoreBuilder::new()
609        .name("Finance Documentation Store")
610        .add_file("file-budget-templates-001")
611        .add_file("file-financial-policies-002")
612        .add_file("file-audit-procedures-003")
613        .metadata("department", "finance")
614        .metadata("access_level", "finance_team")
615        .metadata("compliance", "required")
616        .expires_after_days(2555) // 7 years for financial records
617}
618
619fn create_operations_store() -> VectorStoreBuilder {
620    VectorStoreBuilder::new()
621        .name("Operations Procedures Store")
622        .add_file("file-standard-procedures-001")
623        .add_file("file-incident-response-002")
624        .add_file("file-vendor-management-003")
625        .metadata("department", "operations")
626        .metadata("access_level", "operations_team")
627        .metadata("criticality", "high")
628        .expires_after_days(730) // 2 years
629}
More examples
Hide additional examples
examples/assistants_file_search.rs (line 222)
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 name(self, name: impl Into<String>) -> Self

Set the vector store’s name.

Examples found in repository?
examples/vector_stores.rs (line 469)
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}
543
544/// Helper function to create enterprise knowledge base structure
545fn create_enterprise_knowledge_base() -> Result<Vec<(String, VectorStoreBuilder)>, Error> {
546    let departments = vec![
547        ("Engineering".to_string(), create_engineering_store()),
548        ("Legal".to_string(), create_legal_store()),
549        ("HR".to_string(), create_hr_store()),
550        ("Marketing".to_string(), create_marketing_store()),
551        ("Finance".to_string(), create_finance_store()),
552        ("Operations".to_string(), create_operations_store()),
553    ];
554
555    Ok(departments)
556}
557
558fn create_engineering_store() -> VectorStoreBuilder {
559    VectorStoreBuilder::new()
560        .name("Engineering Knowledge Base")
561        .add_file("file-architecture-docs-001")
562        .add_file("file-coding-standards-002")
563        .add_file("file-deployment-guides-003")
564        .add_file("file-api-documentation-004")
565        .metadata("department", "engineering")
566        .metadata("access_level", "engineering_team")
567        .metadata("update_frequency", "weekly")
568        .expires_after_days(365)
569}
570
571fn create_legal_store() -> VectorStoreBuilder {
572    VectorStoreBuilder::new()
573        .name("Legal Documentation Store")
574        .add_file("file-contracts-templates-001")
575        .add_file("file-compliance-guides-002")
576        .add_file("file-policy-documents-003")
577        .metadata("department", "legal")
578        .metadata("access_level", "legal_team")
579        .metadata("confidentiality", "high")
580        .expires_after_days(2555) // 7 years for legal retention
581}
582
583fn create_hr_store() -> VectorStoreBuilder {
584    VectorStoreBuilder::new()
585        .name("Human Resources Knowledge Base")
586        .add_file("file-employee-handbook-001")
587        .add_file("file-benefits-guide-002")
588        .add_file("file-performance-templates-003")
589        .metadata("department", "hr")
590        .metadata("access_level", "hr_managers")
591        .metadata("privacy", "employee_data")
592        .expires_after_days(1095) // 3 years
593}
594
595fn create_marketing_store() -> VectorStoreBuilder {
596    VectorStoreBuilder::new()
597        .name("Marketing Materials Store")
598        .add_file("file-brand-guidelines-001")
599        .add_file("file-campaign-templates-002")
600        .add_file("file-market-research-003")
601        .metadata("department", "marketing")
602        .metadata("access_level", "marketing_team")
603        .metadata("content_type", "creative_assets")
604        .expires_after_days(365)
605}
606
607fn create_finance_store() -> VectorStoreBuilder {
608    VectorStoreBuilder::new()
609        .name("Finance Documentation Store")
610        .add_file("file-budget-templates-001")
611        .add_file("file-financial-policies-002")
612        .add_file("file-audit-procedures-003")
613        .metadata("department", "finance")
614        .metadata("access_level", "finance_team")
615        .metadata("compliance", "required")
616        .expires_after_days(2555) // 7 years for financial records
617}
618
619fn create_operations_store() -> VectorStoreBuilder {
620    VectorStoreBuilder::new()
621        .name("Operations Procedures Store")
622        .add_file("file-standard-procedures-001")
623        .add_file("file-incident-response-002")
624        .add_file("file-vendor-management-003")
625        .metadata("department", "operations")
626        .metadata("access_level", "operations_team")
627        .metadata("criticality", "high")
628        .expires_after_days(730) // 2 years
629}
More examples
Hide additional examples
examples/assistants_file_search.rs (line 223)
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 file_ids(self, file_ids: Vec<String>) -> Self

Set the file IDs to include in the vector store.

Source

pub fn add_file(self, file_id: impl Into<String>) -> Self

Add a single file ID to the vector store.

Examples found in repository?
examples/vector_stores.rs (line 101)
82fn run_basic_vector_store_example() -> Result<(), Error> {
83    println!(" Example 1: Basic Vector Store Operations");
84    println!("{}", "=".repeat(60));
85
86    // Create a simple vector store
87    let basic_store = simple_vector_store("Getting Started Vector Store")
88        .metadata("purpose", "tutorial")
89        .metadata("created_by", "openai_ergonomic_example");
90
91    println!(" Created basic vector store:");
92    println!("   Name: {}", basic_store.name_ref().unwrap());
93    println!(
94        "   Purpose: {}",
95        basic_store.metadata_ref().get("purpose").unwrap()
96    );
97    println!("   Files: {}", basic_store.file_count());
98
99    // Add files to the vector store
100    let store_with_files = basic_store
101        .add_file("file-welcome-doc-001")
102        .add_file("file-getting-started-002")
103        .add_file("file-basic-examples-003");
104
105    println!("\n Added files to vector store:");
106    for (i, file_id) in store_with_files.file_ids_ref().iter().enumerate() {
107        println!("   {}. {}", i + 1, file_id);
108    }
109    println!("   Total files: {}", store_with_files.file_count());
110
111    // Demonstrate vector store properties
112    println!("\n Vector Store Properties:");
113    println!("   Has files: {}", store_with_files.has_files());
114    println!(
115        "   Metadata entries: {}",
116        store_with_files.metadata_ref().len()
117    );
118    println!(
119        "   Expires: {}",
120        if store_with_files.expires_after_ref().is_some() {
121            "Yes"
122        } else {
123            "No"
124        }
125    );
126
127    println!("\n Basic Operations:");
128    println!("    Create vector store");
129    println!("    Add metadata");
130    println!("    Add files");
131    println!("    Query properties");
132    println!("    Ready for search operations");
133
134    Ok(())
135}
136
137/// Example 2: Document Management and Batch Operations
138fn run_document_management_example() -> Result<(), Error> {
139    println!("\n Example 2: Document Management and Batch Operations");
140    println!("{}", "=".repeat(60));
141
142    // Simulate a large document collection
143    let document_collection = vec![
144        "file-product-docs-001",
145        "file-product-docs-002",
146        "file-api-reference-003",
147        "file-user-guide-004",
148        "file-troubleshooting-005",
149        "file-changelog-006",
150        "file-best-practices-007",
151        "file-integration-guide-008",
152    ];
153
154    // Create vector store with batch file addition
155    let doc_store = vector_store_with_files(
156        "Product Documentation Store",
157        document_collection.iter().map(|s| s.to_string()).collect(),
158    )
159    .metadata("category", "documentation")
160    .metadata("product", "api_platform")
161    .metadata("version", "v2.1")
162    .expires_after_days(180); // 6 months retention
163
164    println!(" Created documentation vector store:");
165    println!("   Name: {}", doc_store.name_ref().unwrap());
166    println!("   Documents: {} files", doc_store.file_count());
167    println!(
168        "   Category: {}",
169        doc_store.metadata_ref().get("category").unwrap()
170    );
171    println!("   Retention: 180 days");
172
173    // Demonstrate individual file operations
174    let individual_file_op = add_file_to_vector_store("doc-store-123", "file-new-feature-009");
175
176    println!("\n Individual File Operations:");
177    println!("   Adding file: {}", individual_file_op.file_id());
178    println!("   To store: {}", individual_file_op.vector_store_id());
179
180    // Simulate file organization strategies
181    println!("\n Document Organization Strategies:");
182
183    let categorized_stores = vec![
184        (
185            "API Documentation",
186            vec!["file-api-ref", "file-endpoints", "file-auth"],
187        ),
188        (
189            "User Guides",
190            vec!["file-quickstart", "file-tutorials", "file-howtos"],
191        ),
192        (
193            "Technical Specs",
194            vec!["file-architecture", "file-protocols", "file-security"],
195        ),
196        (
197            "Release Notes",
198            vec!["file-changelog", "file-migration", "file-breaking-changes"],
199        ),
200    ];
201
202    for (category, files) in &categorized_stores {
203        let category_store = vector_store_with_files(
204            format!("{} Vector Store", category),
205            files.iter().map(|s| s.to_string()).collect(),
206        )
207        .metadata("category", category.to_lowercase().replace(" ", "_"))
208        .metadata("auto_managed", "true");
209
210        println!("    {}: {} files", category, category_store.file_count());
211    }
212
213    println!("\n Document Management Workflow:");
214    println!("   1.  Batch upload documents by category");
215    println!("   2.  Apply consistent metadata tagging");
216    println!("   3. ⏰ Set appropriate retention policies");
217    println!("   4.  Enable automatic organization");
218    println!("   5.  Monitor storage usage and performance");
219
220    Ok(())
221}
222
223/// Example 3: Semantic Search and Similarity Queries
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}
543
544/// Helper function to create enterprise knowledge base structure
545fn create_enterprise_knowledge_base() -> Result<Vec<(String, VectorStoreBuilder)>, Error> {
546    let departments = vec![
547        ("Engineering".to_string(), create_engineering_store()),
548        ("Legal".to_string(), create_legal_store()),
549        ("HR".to_string(), create_hr_store()),
550        ("Marketing".to_string(), create_marketing_store()),
551        ("Finance".to_string(), create_finance_store()),
552        ("Operations".to_string(), create_operations_store()),
553    ];
554
555    Ok(departments)
556}
557
558fn create_engineering_store() -> VectorStoreBuilder {
559    VectorStoreBuilder::new()
560        .name("Engineering Knowledge Base")
561        .add_file("file-architecture-docs-001")
562        .add_file("file-coding-standards-002")
563        .add_file("file-deployment-guides-003")
564        .add_file("file-api-documentation-004")
565        .metadata("department", "engineering")
566        .metadata("access_level", "engineering_team")
567        .metadata("update_frequency", "weekly")
568        .expires_after_days(365)
569}
570
571fn create_legal_store() -> VectorStoreBuilder {
572    VectorStoreBuilder::new()
573        .name("Legal Documentation Store")
574        .add_file("file-contracts-templates-001")
575        .add_file("file-compliance-guides-002")
576        .add_file("file-policy-documents-003")
577        .metadata("department", "legal")
578        .metadata("access_level", "legal_team")
579        .metadata("confidentiality", "high")
580        .expires_after_days(2555) // 7 years for legal retention
581}
582
583fn create_hr_store() -> VectorStoreBuilder {
584    VectorStoreBuilder::new()
585        .name("Human Resources Knowledge Base")
586        .add_file("file-employee-handbook-001")
587        .add_file("file-benefits-guide-002")
588        .add_file("file-performance-templates-003")
589        .metadata("department", "hr")
590        .metadata("access_level", "hr_managers")
591        .metadata("privacy", "employee_data")
592        .expires_after_days(1095) // 3 years
593}
594
595fn create_marketing_store() -> VectorStoreBuilder {
596    VectorStoreBuilder::new()
597        .name("Marketing Materials Store")
598        .add_file("file-brand-guidelines-001")
599        .add_file("file-campaign-templates-002")
600        .add_file("file-market-research-003")
601        .metadata("department", "marketing")
602        .metadata("access_level", "marketing_team")
603        .metadata("content_type", "creative_assets")
604        .expires_after_days(365)
605}
606
607fn create_finance_store() -> VectorStoreBuilder {
608    VectorStoreBuilder::new()
609        .name("Finance Documentation Store")
610        .add_file("file-budget-templates-001")
611        .add_file("file-financial-policies-002")
612        .add_file("file-audit-procedures-003")
613        .metadata("department", "finance")
614        .metadata("access_level", "finance_team")
615        .metadata("compliance", "required")
616        .expires_after_days(2555) // 7 years for financial records
617}
618
619fn create_operations_store() -> VectorStoreBuilder {
620    VectorStoreBuilder::new()
621        .name("Operations Procedures Store")
622        .add_file("file-standard-procedures-001")
623        .add_file("file-incident-response-002")
624        .add_file("file-vendor-management-003")
625        .metadata("department", "operations")
626        .metadata("access_level", "operations_team")
627        .metadata("criticality", "high")
628        .expires_after_days(730) // 2 years
629}
More examples
Hide additional examples
examples/assistants_file_search.rs (line 164)
146fn run_document_qa_example() -> Result<(), Error> {
147    println!("\n Example 2: Document Q&A Assistant");
148    println!("{}", "=".repeat(60));
149
150    // Create specialized document Q&A assistant
151    let _qa_assistant = AssistantBuilder::new("gpt-4-1106-preview")
152        .name("Document Q&A Specialist")
153        .description("Answers questions based on uploaded documents with high accuracy")
154        .instructions(
155            "You are a document Q&A specialist. Answer questions by searching through the provided documents. Always cite your sources, indicate confidence levels, and acknowledge when information is not available in the documents."
156        )
157        .add_tool(tool_file_search());
158
159    println!(" Created Document Q&A assistant:");
160    println!("   Specialty: Precise question answering from documents");
161
162    // Create a temporary vector store for this Q&A session
163    let qa_store = temporary_vector_store("Q&A Session Store", 7) // Expires in 7 days
164        .add_file("file-research-paper-001")
165        .add_file("file-user-manual-002")
166        .add_file("file-technical-spec-003")
167        .metadata("session_id", "qa-session-123")
168        .metadata("user", "researcher-001");
169
170    println!("\n Q&A Document Store:");
171    println!("   Files: {} documents loaded", qa_store.file_count());
172    println!("   Expiration: 7 days (temporary session)");
173    println!("   Session ID: qa-session-123");
174
175    println!("\n Example Q&A Queries:");
176    let queries = vec![
177        "What is the maximum throughput mentioned in the technical specifications?",
178        "How do I configure the authentication system according to the user manual?",
179        "What are the key findings from the research paper regarding performance?",
180        "Are there any known limitations discussed in these documents?",
181    ];
182
183    for (i, query) in queries.iter().enumerate() {
184        println!("   {}. {}", i + 1, query);
185    }
186
187    println!("\n Document Q&A RAG Workflow:");
188    println!("   1.  Process user question");
189    println!("   2.  Generate search queries for vector store");
190    println!("   3.  Retrieve relevant document sections");
191    println!("   4.  Rank and filter results by relevance");
192    println!("   5.  Generate answer from retrieved context");
193    println!("   6.  Add citations and confidence indicators");
194
195    println!("\n Expected Q&A Response Format:");
196    println!("    Direct answer to the question");
197    println!("    Citations: [technical-spec-003.pdf, page 15]");
198    println!("    Confidence: High (90%)");
199    println!("    Related information: See also user-manual-002.pdf, section 4.3");
200    println!("     Limitations: No information found about edge cases");
201
202    Ok(())
203}
204
205/// Example 3: Research Assistant with Advanced RAG
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 add_files<I, S>(self, file_ids: I) -> Self
where I: IntoIterator<Item = S>, S: Into<String>,

Add multiple file IDs to the vector store.

Source

pub fn clear_files(self) -> Self

Clear all file IDs from the vector store.

Source

pub fn expires_after_days(self, days: i32) -> Self

Set expiration policy for the vector store.

Examples found in repository?
examples/assistants_file_search.rs (line 90)
82fn run_knowledge_base_example() -> Result<(), Error> {
83    println!(" Example 1: Building a Knowledge Base Assistant");
84    println!("{}", "=".repeat(60));
85
86    // Create a knowledge base vector store
87    let knowledge_store = simple_vector_store("Company Knowledge Base")
88        .metadata("type", "internal_docs")
89        .metadata("department", "engineering")
90        .expires_after_days(365); // Expire after 1 year
91
92    println!(" Created knowledge base vector store:");
93    println!("   Name: {}", knowledge_store.name_ref().unwrap());
94    println!("   Type: Internal documentation");
95    println!("   Expiration: 365 days");
96
97    // Simulate adding documents to the knowledge base
98    let file_ids = vec![
99        "file-api-docs-123".to_string(),
100        "file-coding-standards-456".to_string(),
101        "file-deployment-guide-789".to_string(),
102        "file-troubleshooting-101".to_string(),
103    ];
104
105    let populated_store = vector_store_with_files("Engineering Knowledge Base", file_ids.clone());
106
107    println!("\n Knowledge Base Contents:");
108    for (i, file_id) in populated_store.file_ids_ref().iter().enumerate() {
109        println!("   {}. {}", i + 1, file_id);
110    }
111    println!("   Total files: {}", populated_store.file_count());
112
113    // Create an assistant with file search capabilities
114    let kb_assistant = assistant_with_instructions(
115        "gpt-4-1106-preview",
116        "Engineering Knowledge Assistant",
117        "You are an engineering knowledge assistant. Help developers find relevant information from our internal documentation, coding standards, and deployment guides. Always provide accurate citations and suggest related resources when appropriate."
118    )
119    .description("Internal knowledge base assistant for engineering teams")
120    .add_tool(tool_file_search());
121
122    println!("\n Created knowledge base assistant:");
123    println!("   Name: {}", kb_assistant.name_ref().unwrap());
124    println!("   Capability: File search through engineering documents");
125
126    println!("\n Example Knowledge Base Query:");
127    println!("   'What are our coding standards for API documentation?'");
128
129    println!("\n RAG Workflow for Knowledge Base:");
130    println!("   1.  Search vector store for relevant documents");
131    println!("   2.  Retrieve matching sections from coding standards");
132    println!("   3.  Generate response based on retrieved content");
133    println!("   4.  Provide citations to specific documents");
134    println!("   5.  Suggest related topics or documents");
135
136    println!("\n Expected Knowledge Base Response:");
137    println!("   • Specific coding standards for API documentation");
138    println!("   • Citations: 'coding-standards-456.md, section 3.2'");
139    println!("   • Examples from deployment guide");
140    println!("   • Related resources: troubleshooting guide");
141
142    Ok(())
143}
More examples
Hide additional examples
examples/vector_stores.rs (line 162)
138fn run_document_management_example() -> Result<(), Error> {
139    println!("\n Example 2: Document Management and Batch Operations");
140    println!("{}", "=".repeat(60));
141
142    // Simulate a large document collection
143    let document_collection = vec![
144        "file-product-docs-001",
145        "file-product-docs-002",
146        "file-api-reference-003",
147        "file-user-guide-004",
148        "file-troubleshooting-005",
149        "file-changelog-006",
150        "file-best-practices-007",
151        "file-integration-guide-008",
152    ];
153
154    // Create vector store with batch file addition
155    let doc_store = vector_store_with_files(
156        "Product Documentation Store",
157        document_collection.iter().map(|s| s.to_string()).collect(),
158    )
159    .metadata("category", "documentation")
160    .metadata("product", "api_platform")
161    .metadata("version", "v2.1")
162    .expires_after_days(180); // 6 months retention
163
164    println!(" Created documentation vector store:");
165    println!("   Name: {}", doc_store.name_ref().unwrap());
166    println!("   Documents: {} files", doc_store.file_count());
167    println!(
168        "   Category: {}",
169        doc_store.metadata_ref().get("category").unwrap()
170    );
171    println!("   Retention: 180 days");
172
173    // Demonstrate individual file operations
174    let individual_file_op = add_file_to_vector_store("doc-store-123", "file-new-feature-009");
175
176    println!("\n Individual File Operations:");
177    println!("   Adding file: {}", individual_file_op.file_id());
178    println!("   To store: {}", individual_file_op.vector_store_id());
179
180    // Simulate file organization strategies
181    println!("\n Document Organization Strategies:");
182
183    let categorized_stores = vec![
184        (
185            "API Documentation",
186            vec!["file-api-ref", "file-endpoints", "file-auth"],
187        ),
188        (
189            "User Guides",
190            vec!["file-quickstart", "file-tutorials", "file-howtos"],
191        ),
192        (
193            "Technical Specs",
194            vec!["file-architecture", "file-protocols", "file-security"],
195        ),
196        (
197            "Release Notes",
198            vec!["file-changelog", "file-migration", "file-breaking-changes"],
199        ),
200    ];
201
202    for (category, files) in &categorized_stores {
203        let category_store = vector_store_with_files(
204            format!("{} Vector Store", category),
205            files.iter().map(|s| s.to_string()).collect(),
206        )
207        .metadata("category", category.to_lowercase().replace(" ", "_"))
208        .metadata("auto_managed", "true");
209
210        println!("    {}: {} files", category, category_store.file_count());
211    }
212
213    println!("\n Document Management Workflow:");
214    println!("   1.  Batch upload documents by category");
215    println!("   2.  Apply consistent metadata tagging");
216    println!("   3. ⏰ Set appropriate retention policies");
217    println!("   4.  Enable automatic organization");
218    println!("   5.  Monitor storage usage and performance");
219
220    Ok(())
221}
222
223/// Example 3: Semantic Search and Similarity Queries
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}
543
544/// Helper function to create enterprise knowledge base structure
545fn create_enterprise_knowledge_base() -> Result<Vec<(String, VectorStoreBuilder)>, Error> {
546    let departments = vec![
547        ("Engineering".to_string(), create_engineering_store()),
548        ("Legal".to_string(), create_legal_store()),
549        ("HR".to_string(), create_hr_store()),
550        ("Marketing".to_string(), create_marketing_store()),
551        ("Finance".to_string(), create_finance_store()),
552        ("Operations".to_string(), create_operations_store()),
553    ];
554
555    Ok(departments)
556}
557
558fn create_engineering_store() -> VectorStoreBuilder {
559    VectorStoreBuilder::new()
560        .name("Engineering Knowledge Base")
561        .add_file("file-architecture-docs-001")
562        .add_file("file-coding-standards-002")
563        .add_file("file-deployment-guides-003")
564        .add_file("file-api-documentation-004")
565        .metadata("department", "engineering")
566        .metadata("access_level", "engineering_team")
567        .metadata("update_frequency", "weekly")
568        .expires_after_days(365)
569}
570
571fn create_legal_store() -> VectorStoreBuilder {
572    VectorStoreBuilder::new()
573        .name("Legal Documentation Store")
574        .add_file("file-contracts-templates-001")
575        .add_file("file-compliance-guides-002")
576        .add_file("file-policy-documents-003")
577        .metadata("department", "legal")
578        .metadata("access_level", "legal_team")
579        .metadata("confidentiality", "high")
580        .expires_after_days(2555) // 7 years for legal retention
581}
582
583fn create_hr_store() -> VectorStoreBuilder {
584    VectorStoreBuilder::new()
585        .name("Human Resources Knowledge Base")
586        .add_file("file-employee-handbook-001")
587        .add_file("file-benefits-guide-002")
588        .add_file("file-performance-templates-003")
589        .metadata("department", "hr")
590        .metadata("access_level", "hr_managers")
591        .metadata("privacy", "employee_data")
592        .expires_after_days(1095) // 3 years
593}
594
595fn create_marketing_store() -> VectorStoreBuilder {
596    VectorStoreBuilder::new()
597        .name("Marketing Materials Store")
598        .add_file("file-brand-guidelines-001")
599        .add_file("file-campaign-templates-002")
600        .add_file("file-market-research-003")
601        .metadata("department", "marketing")
602        .metadata("access_level", "marketing_team")
603        .metadata("content_type", "creative_assets")
604        .expires_after_days(365)
605}
606
607fn create_finance_store() -> VectorStoreBuilder {
608    VectorStoreBuilder::new()
609        .name("Finance Documentation Store")
610        .add_file("file-budget-templates-001")
611        .add_file("file-financial-policies-002")
612        .add_file("file-audit-procedures-003")
613        .metadata("department", "finance")
614        .metadata("access_level", "finance_team")
615        .metadata("compliance", "required")
616        .expires_after_days(2555) // 7 years for financial records
617}
618
619fn create_operations_store() -> VectorStoreBuilder {
620    VectorStoreBuilder::new()
621        .name("Operations Procedures Store")
622        .add_file("file-standard-procedures-001")
623        .add_file("file-incident-response-002")
624        .add_file("file-vendor-management-003")
625        .metadata("department", "operations")
626        .metadata("access_level", "operations_team")
627        .metadata("criticality", "high")
628        .expires_after_days(730) // 2 years
629}
Source

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

Add metadata to the vector store.

Examples found in repository?
examples/vector_stores.rs (line 88)
82fn run_basic_vector_store_example() -> Result<(), Error> {
83    println!(" Example 1: Basic Vector Store Operations");
84    println!("{}", "=".repeat(60));
85
86    // Create a simple vector store
87    let basic_store = simple_vector_store("Getting Started Vector Store")
88        .metadata("purpose", "tutorial")
89        .metadata("created_by", "openai_ergonomic_example");
90
91    println!(" Created basic vector store:");
92    println!("   Name: {}", basic_store.name_ref().unwrap());
93    println!(
94        "   Purpose: {}",
95        basic_store.metadata_ref().get("purpose").unwrap()
96    );
97    println!("   Files: {}", basic_store.file_count());
98
99    // Add files to the vector store
100    let store_with_files = basic_store
101        .add_file("file-welcome-doc-001")
102        .add_file("file-getting-started-002")
103        .add_file("file-basic-examples-003");
104
105    println!("\n Added files to vector store:");
106    for (i, file_id) in store_with_files.file_ids_ref().iter().enumerate() {
107        println!("   {}. {}", i + 1, file_id);
108    }
109    println!("   Total files: {}", store_with_files.file_count());
110
111    // Demonstrate vector store properties
112    println!("\n Vector Store Properties:");
113    println!("   Has files: {}", store_with_files.has_files());
114    println!(
115        "   Metadata entries: {}",
116        store_with_files.metadata_ref().len()
117    );
118    println!(
119        "   Expires: {}",
120        if store_with_files.expires_after_ref().is_some() {
121            "Yes"
122        } else {
123            "No"
124        }
125    );
126
127    println!("\n Basic Operations:");
128    println!("    Create vector store");
129    println!("    Add metadata");
130    println!("    Add files");
131    println!("    Query properties");
132    println!("    Ready for search operations");
133
134    Ok(())
135}
136
137/// Example 2: Document Management and Batch Operations
138fn run_document_management_example() -> Result<(), Error> {
139    println!("\n Example 2: Document Management and Batch Operations");
140    println!("{}", "=".repeat(60));
141
142    // Simulate a large document collection
143    let document_collection = vec![
144        "file-product-docs-001",
145        "file-product-docs-002",
146        "file-api-reference-003",
147        "file-user-guide-004",
148        "file-troubleshooting-005",
149        "file-changelog-006",
150        "file-best-practices-007",
151        "file-integration-guide-008",
152    ];
153
154    // Create vector store with batch file addition
155    let doc_store = vector_store_with_files(
156        "Product Documentation Store",
157        document_collection.iter().map(|s| s.to_string()).collect(),
158    )
159    .metadata("category", "documentation")
160    .metadata("product", "api_platform")
161    .metadata("version", "v2.1")
162    .expires_after_days(180); // 6 months retention
163
164    println!(" Created documentation vector store:");
165    println!("   Name: {}", doc_store.name_ref().unwrap());
166    println!("   Documents: {} files", doc_store.file_count());
167    println!(
168        "   Category: {}",
169        doc_store.metadata_ref().get("category").unwrap()
170    );
171    println!("   Retention: 180 days");
172
173    // Demonstrate individual file operations
174    let individual_file_op = add_file_to_vector_store("doc-store-123", "file-new-feature-009");
175
176    println!("\n Individual File Operations:");
177    println!("   Adding file: {}", individual_file_op.file_id());
178    println!("   To store: {}", individual_file_op.vector_store_id());
179
180    // Simulate file organization strategies
181    println!("\n Document Organization Strategies:");
182
183    let categorized_stores = vec![
184        (
185            "API Documentation",
186            vec!["file-api-ref", "file-endpoints", "file-auth"],
187        ),
188        (
189            "User Guides",
190            vec!["file-quickstart", "file-tutorials", "file-howtos"],
191        ),
192        (
193            "Technical Specs",
194            vec!["file-architecture", "file-protocols", "file-security"],
195        ),
196        (
197            "Release Notes",
198            vec!["file-changelog", "file-migration", "file-breaking-changes"],
199        ),
200    ];
201
202    for (category, files) in &categorized_stores {
203        let category_store = vector_store_with_files(
204            format!("{} Vector Store", category),
205            files.iter().map(|s| s.to_string()).collect(),
206        )
207        .metadata("category", category.to_lowercase().replace(" ", "_"))
208        .metadata("auto_managed", "true");
209
210        println!("    {}: {} files", category, category_store.file_count());
211    }
212
213    println!("\n Document Management Workflow:");
214    println!("   1.  Batch upload documents by category");
215    println!("   2.  Apply consistent metadata tagging");
216    println!("   3. ⏰ Set appropriate retention policies");
217    println!("   4.  Enable automatic organization");
218    println!("   5.  Monitor storage usage and performance");
219
220    Ok(())
221}
222
223/// Example 3: Semantic Search and Similarity Queries
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}
543
544/// Helper function to create enterprise knowledge base structure
545fn create_enterprise_knowledge_base() -> Result<Vec<(String, VectorStoreBuilder)>, Error> {
546    let departments = vec![
547        ("Engineering".to_string(), create_engineering_store()),
548        ("Legal".to_string(), create_legal_store()),
549        ("HR".to_string(), create_hr_store()),
550        ("Marketing".to_string(), create_marketing_store()),
551        ("Finance".to_string(), create_finance_store()),
552        ("Operations".to_string(), create_operations_store()),
553    ];
554
555    Ok(departments)
556}
557
558fn create_engineering_store() -> VectorStoreBuilder {
559    VectorStoreBuilder::new()
560        .name("Engineering Knowledge Base")
561        .add_file("file-architecture-docs-001")
562        .add_file("file-coding-standards-002")
563        .add_file("file-deployment-guides-003")
564        .add_file("file-api-documentation-004")
565        .metadata("department", "engineering")
566        .metadata("access_level", "engineering_team")
567        .metadata("update_frequency", "weekly")
568        .expires_after_days(365)
569}
570
571fn create_legal_store() -> VectorStoreBuilder {
572    VectorStoreBuilder::new()
573        .name("Legal Documentation Store")
574        .add_file("file-contracts-templates-001")
575        .add_file("file-compliance-guides-002")
576        .add_file("file-policy-documents-003")
577        .metadata("department", "legal")
578        .metadata("access_level", "legal_team")
579        .metadata("confidentiality", "high")
580        .expires_after_days(2555) // 7 years for legal retention
581}
582
583fn create_hr_store() -> VectorStoreBuilder {
584    VectorStoreBuilder::new()
585        .name("Human Resources Knowledge Base")
586        .add_file("file-employee-handbook-001")
587        .add_file("file-benefits-guide-002")
588        .add_file("file-performance-templates-003")
589        .metadata("department", "hr")
590        .metadata("access_level", "hr_managers")
591        .metadata("privacy", "employee_data")
592        .expires_after_days(1095) // 3 years
593}
594
595fn create_marketing_store() -> VectorStoreBuilder {
596    VectorStoreBuilder::new()
597        .name("Marketing Materials Store")
598        .add_file("file-brand-guidelines-001")
599        .add_file("file-campaign-templates-002")
600        .add_file("file-market-research-003")
601        .metadata("department", "marketing")
602        .metadata("access_level", "marketing_team")
603        .metadata("content_type", "creative_assets")
604        .expires_after_days(365)
605}
606
607fn create_finance_store() -> VectorStoreBuilder {
608    VectorStoreBuilder::new()
609        .name("Finance Documentation Store")
610        .add_file("file-budget-templates-001")
611        .add_file("file-financial-policies-002")
612        .add_file("file-audit-procedures-003")
613        .metadata("department", "finance")
614        .metadata("access_level", "finance_team")
615        .metadata("compliance", "required")
616        .expires_after_days(2555) // 7 years for financial records
617}
618
619fn create_operations_store() -> VectorStoreBuilder {
620    VectorStoreBuilder::new()
621        .name("Operations Procedures Store")
622        .add_file("file-standard-procedures-001")
623        .add_file("file-incident-response-002")
624        .add_file("file-vendor-management-003")
625        .metadata("department", "operations")
626        .metadata("access_level", "operations_team")
627        .metadata("criticality", "high")
628        .expires_after_days(730) // 2 years
629}
More examples
Hide additional examples
examples/assistants_file_search.rs (line 88)
82fn run_knowledge_base_example() -> Result<(), Error> {
83    println!(" Example 1: Building a Knowledge Base Assistant");
84    println!("{}", "=".repeat(60));
85
86    // Create a knowledge base vector store
87    let knowledge_store = simple_vector_store("Company Knowledge Base")
88        .metadata("type", "internal_docs")
89        .metadata("department", "engineering")
90        .expires_after_days(365); // Expire after 1 year
91
92    println!(" Created knowledge base vector store:");
93    println!("   Name: {}", knowledge_store.name_ref().unwrap());
94    println!("   Type: Internal documentation");
95    println!("   Expiration: 365 days");
96
97    // Simulate adding documents to the knowledge base
98    let file_ids = vec![
99        "file-api-docs-123".to_string(),
100        "file-coding-standards-456".to_string(),
101        "file-deployment-guide-789".to_string(),
102        "file-troubleshooting-101".to_string(),
103    ];
104
105    let populated_store = vector_store_with_files("Engineering Knowledge Base", file_ids.clone());
106
107    println!("\n Knowledge Base Contents:");
108    for (i, file_id) in populated_store.file_ids_ref().iter().enumerate() {
109        println!("   {}. {}", i + 1, file_id);
110    }
111    println!("   Total files: {}", populated_store.file_count());
112
113    // Create an assistant with file search capabilities
114    let kb_assistant = assistant_with_instructions(
115        "gpt-4-1106-preview",
116        "Engineering Knowledge Assistant",
117        "You are an engineering knowledge assistant. Help developers find relevant information from our internal documentation, coding standards, and deployment guides. Always provide accurate citations and suggest related resources when appropriate."
118    )
119    .description("Internal knowledge base assistant for engineering teams")
120    .add_tool(tool_file_search());
121
122    println!("\n Created knowledge base assistant:");
123    println!("   Name: {}", kb_assistant.name_ref().unwrap());
124    println!("   Capability: File search through engineering documents");
125
126    println!("\n Example Knowledge Base Query:");
127    println!("   'What are our coding standards for API documentation?'");
128
129    println!("\n RAG Workflow for Knowledge Base:");
130    println!("   1.  Search vector store for relevant documents");
131    println!("   2.  Retrieve matching sections from coding standards");
132    println!("   3.  Generate response based on retrieved content");
133    println!("   4.  Provide citations to specific documents");
134    println!("   5.  Suggest related topics or documents");
135
136    println!("\n Expected Knowledge Base Response:");
137    println!("   • Specific coding standards for API documentation");
138    println!("   • Citations: 'coding-standards-456.md, section 3.2'");
139    println!("   • Examples from deployment guide");
140    println!("   • Related resources: troubleshooting guide");
141
142    Ok(())
143}
144
145/// Example 2: Document Q&A Assistant
146fn run_document_qa_example() -> Result<(), Error> {
147    println!("\n Example 2: Document Q&A Assistant");
148    println!("{}", "=".repeat(60));
149
150    // Create specialized document Q&A assistant
151    let _qa_assistant = AssistantBuilder::new("gpt-4-1106-preview")
152        .name("Document Q&A Specialist")
153        .description("Answers questions based on uploaded documents with high accuracy")
154        .instructions(
155            "You are a document Q&A specialist. Answer questions by searching through the provided documents. Always cite your sources, indicate confidence levels, and acknowledge when information is not available in the documents."
156        )
157        .add_tool(tool_file_search());
158
159    println!(" Created Document Q&A assistant:");
160    println!("   Specialty: Precise question answering from documents");
161
162    // Create a temporary vector store for this Q&A session
163    let qa_store = temporary_vector_store("Q&A Session Store", 7) // Expires in 7 days
164        .add_file("file-research-paper-001")
165        .add_file("file-user-manual-002")
166        .add_file("file-technical-spec-003")
167        .metadata("session_id", "qa-session-123")
168        .metadata("user", "researcher-001");
169
170    println!("\n Q&A Document Store:");
171    println!("   Files: {} documents loaded", qa_store.file_count());
172    println!("   Expiration: 7 days (temporary session)");
173    println!("   Session ID: qa-session-123");
174
175    println!("\n Example Q&A Queries:");
176    let queries = vec![
177        "What is the maximum throughput mentioned in the technical specifications?",
178        "How do I configure the authentication system according to the user manual?",
179        "What are the key findings from the research paper regarding performance?",
180        "Are there any known limitations discussed in these documents?",
181    ];
182
183    for (i, query) in queries.iter().enumerate() {
184        println!("   {}. {}", i + 1, query);
185    }
186
187    println!("\n Document Q&A RAG Workflow:");
188    println!("   1.  Process user question");
189    println!("   2.  Generate search queries for vector store");
190    println!("   3.  Retrieve relevant document sections");
191    println!("   4.  Rank and filter results by relevance");
192    println!("   5.  Generate answer from retrieved context");
193    println!("   6.  Add citations and confidence indicators");
194
195    println!("\n Expected Q&A Response Format:");
196    println!("    Direct answer to the question");
197    println!("    Citations: [technical-spec-003.pdf, page 15]");
198    println!("    Confidence: High (90%)");
199    println!("    Related information: See also user-manual-002.pdf, section 4.3");
200    println!("     Limitations: No information found about edge cases");
201
202    Ok(())
203}
204
205/// Example 3: Research Assistant with Advanced RAG
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 name_ref(&self) -> Option<&str>

Get the name of this vector store.

Examples found in repository?
examples/vector_stores.rs (line 92)
82fn run_basic_vector_store_example() -> Result<(), Error> {
83    println!(" Example 1: Basic Vector Store Operations");
84    println!("{}", "=".repeat(60));
85
86    // Create a simple vector store
87    let basic_store = simple_vector_store("Getting Started Vector Store")
88        .metadata("purpose", "tutorial")
89        .metadata("created_by", "openai_ergonomic_example");
90
91    println!(" Created basic vector store:");
92    println!("   Name: {}", basic_store.name_ref().unwrap());
93    println!(
94        "   Purpose: {}",
95        basic_store.metadata_ref().get("purpose").unwrap()
96    );
97    println!("   Files: {}", basic_store.file_count());
98
99    // Add files to the vector store
100    let store_with_files = basic_store
101        .add_file("file-welcome-doc-001")
102        .add_file("file-getting-started-002")
103        .add_file("file-basic-examples-003");
104
105    println!("\n Added files to vector store:");
106    for (i, file_id) in store_with_files.file_ids_ref().iter().enumerate() {
107        println!("   {}. {}", i + 1, file_id);
108    }
109    println!("   Total files: {}", store_with_files.file_count());
110
111    // Demonstrate vector store properties
112    println!("\n Vector Store Properties:");
113    println!("   Has files: {}", store_with_files.has_files());
114    println!(
115        "   Metadata entries: {}",
116        store_with_files.metadata_ref().len()
117    );
118    println!(
119        "   Expires: {}",
120        if store_with_files.expires_after_ref().is_some() {
121            "Yes"
122        } else {
123            "No"
124        }
125    );
126
127    println!("\n Basic Operations:");
128    println!("    Create vector store");
129    println!("    Add metadata");
130    println!("    Add files");
131    println!("    Query properties");
132    println!("    Ready for search operations");
133
134    Ok(())
135}
136
137/// Example 2: Document Management and Batch Operations
138fn run_document_management_example() -> Result<(), Error> {
139    println!("\n Example 2: Document Management and Batch Operations");
140    println!("{}", "=".repeat(60));
141
142    // Simulate a large document collection
143    let document_collection = vec![
144        "file-product-docs-001",
145        "file-product-docs-002",
146        "file-api-reference-003",
147        "file-user-guide-004",
148        "file-troubleshooting-005",
149        "file-changelog-006",
150        "file-best-practices-007",
151        "file-integration-guide-008",
152    ];
153
154    // Create vector store with batch file addition
155    let doc_store = vector_store_with_files(
156        "Product Documentation Store",
157        document_collection.iter().map(|s| s.to_string()).collect(),
158    )
159    .metadata("category", "documentation")
160    .metadata("product", "api_platform")
161    .metadata("version", "v2.1")
162    .expires_after_days(180); // 6 months retention
163
164    println!(" Created documentation vector store:");
165    println!("   Name: {}", doc_store.name_ref().unwrap());
166    println!("   Documents: {} files", doc_store.file_count());
167    println!(
168        "   Category: {}",
169        doc_store.metadata_ref().get("category").unwrap()
170    );
171    println!("   Retention: 180 days");
172
173    // Demonstrate individual file operations
174    let individual_file_op = add_file_to_vector_store("doc-store-123", "file-new-feature-009");
175
176    println!("\n Individual File Operations:");
177    println!("   Adding file: {}", individual_file_op.file_id());
178    println!("   To store: {}", individual_file_op.vector_store_id());
179
180    // Simulate file organization strategies
181    println!("\n Document Organization Strategies:");
182
183    let categorized_stores = vec![
184        (
185            "API Documentation",
186            vec!["file-api-ref", "file-endpoints", "file-auth"],
187        ),
188        (
189            "User Guides",
190            vec!["file-quickstart", "file-tutorials", "file-howtos"],
191        ),
192        (
193            "Technical Specs",
194            vec!["file-architecture", "file-protocols", "file-security"],
195        ),
196        (
197            "Release Notes",
198            vec!["file-changelog", "file-migration", "file-breaking-changes"],
199        ),
200    ];
201
202    for (category, files) in &categorized_stores {
203        let category_store = vector_store_with_files(
204            format!("{} Vector Store", category),
205            files.iter().map(|s| s.to_string()).collect(),
206        )
207        .metadata("category", category.to_lowercase().replace(" ", "_"))
208        .metadata("auto_managed", "true");
209
210        println!("    {}: {} files", category, category_store.file_count());
211    }
212
213    println!("\n Document Management Workflow:");
214    println!("   1.  Batch upload documents by category");
215    println!("   2.  Apply consistent metadata tagging");
216    println!("   3. ⏰ Set appropriate retention policies");
217    println!("   4.  Enable automatic organization");
218    println!("   5.  Monitor storage usage and performance");
219
220    Ok(())
221}
222
223/// Example 3: Semantic Search and Similarity Queries
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}
More examples
Hide additional examples
examples/assistants_file_search.rs (line 93)
82fn run_knowledge_base_example() -> Result<(), Error> {
83    println!(" Example 1: Building a Knowledge Base Assistant");
84    println!("{}", "=".repeat(60));
85
86    // Create a knowledge base vector store
87    let knowledge_store = simple_vector_store("Company Knowledge Base")
88        .metadata("type", "internal_docs")
89        .metadata("department", "engineering")
90        .expires_after_days(365); // Expire after 1 year
91
92    println!(" Created knowledge base vector store:");
93    println!("   Name: {}", knowledge_store.name_ref().unwrap());
94    println!("   Type: Internal documentation");
95    println!("   Expiration: 365 days");
96
97    // Simulate adding documents to the knowledge base
98    let file_ids = vec![
99        "file-api-docs-123".to_string(),
100        "file-coding-standards-456".to_string(),
101        "file-deployment-guide-789".to_string(),
102        "file-troubleshooting-101".to_string(),
103    ];
104
105    let populated_store = vector_store_with_files("Engineering Knowledge Base", file_ids.clone());
106
107    println!("\n Knowledge Base Contents:");
108    for (i, file_id) in populated_store.file_ids_ref().iter().enumerate() {
109        println!("   {}. {}", i + 1, file_id);
110    }
111    println!("   Total files: {}", populated_store.file_count());
112
113    // Create an assistant with file search capabilities
114    let kb_assistant = assistant_with_instructions(
115        "gpt-4-1106-preview",
116        "Engineering Knowledge Assistant",
117        "You are an engineering knowledge assistant. Help developers find relevant information from our internal documentation, coding standards, and deployment guides. Always provide accurate citations and suggest related resources when appropriate."
118    )
119    .description("Internal knowledge base assistant for engineering teams")
120    .add_tool(tool_file_search());
121
122    println!("\n Created knowledge base assistant:");
123    println!("   Name: {}", kb_assistant.name_ref().unwrap());
124    println!("   Capability: File search through engineering documents");
125
126    println!("\n Example Knowledge Base Query:");
127    println!("   'What are our coding standards for API documentation?'");
128
129    println!("\n RAG Workflow for Knowledge Base:");
130    println!("   1.  Search vector store for relevant documents");
131    println!("   2.  Retrieve matching sections from coding standards");
132    println!("   3.  Generate response based on retrieved content");
133    println!("   4.  Provide citations to specific documents");
134    println!("   5.  Suggest related topics or documents");
135
136    println!("\n Expected Knowledge Base Response:");
137    println!("   • Specific coding standards for API documentation");
138    println!("   • Citations: 'coding-standards-456.md, section 3.2'");
139    println!("   • Examples from deployment guide");
140    println!("   • Related resources: troubleshooting guide");
141
142    Ok(())
143}
Source

pub fn file_ids_ref(&self) -> &[String]

Get the file IDs for this vector store.

Examples found in repository?
examples/vector_stores.rs (line 106)
82fn run_basic_vector_store_example() -> Result<(), Error> {
83    println!(" Example 1: Basic Vector Store Operations");
84    println!("{}", "=".repeat(60));
85
86    // Create a simple vector store
87    let basic_store = simple_vector_store("Getting Started Vector Store")
88        .metadata("purpose", "tutorial")
89        .metadata("created_by", "openai_ergonomic_example");
90
91    println!(" Created basic vector store:");
92    println!("   Name: {}", basic_store.name_ref().unwrap());
93    println!(
94        "   Purpose: {}",
95        basic_store.metadata_ref().get("purpose").unwrap()
96    );
97    println!("   Files: {}", basic_store.file_count());
98
99    // Add files to the vector store
100    let store_with_files = basic_store
101        .add_file("file-welcome-doc-001")
102        .add_file("file-getting-started-002")
103        .add_file("file-basic-examples-003");
104
105    println!("\n Added files to vector store:");
106    for (i, file_id) in store_with_files.file_ids_ref().iter().enumerate() {
107        println!("   {}. {}", i + 1, file_id);
108    }
109    println!("   Total files: {}", store_with_files.file_count());
110
111    // Demonstrate vector store properties
112    println!("\n Vector Store Properties:");
113    println!("   Has files: {}", store_with_files.has_files());
114    println!(
115        "   Metadata entries: {}",
116        store_with_files.metadata_ref().len()
117    );
118    println!(
119        "   Expires: {}",
120        if store_with_files.expires_after_ref().is_some() {
121            "Yes"
122        } else {
123            "No"
124        }
125    );
126
127    println!("\n Basic Operations:");
128    println!("    Create vector store");
129    println!("    Add metadata");
130    println!("    Add files");
131    println!("    Query properties");
132    println!("    Ready for search operations");
133
134    Ok(())
135}
More examples
Hide additional examples
examples/assistants_file_search.rs (line 108)
82fn run_knowledge_base_example() -> Result<(), Error> {
83    println!(" Example 1: Building a Knowledge Base Assistant");
84    println!("{}", "=".repeat(60));
85
86    // Create a knowledge base vector store
87    let knowledge_store = simple_vector_store("Company Knowledge Base")
88        .metadata("type", "internal_docs")
89        .metadata("department", "engineering")
90        .expires_after_days(365); // Expire after 1 year
91
92    println!(" Created knowledge base vector store:");
93    println!("   Name: {}", knowledge_store.name_ref().unwrap());
94    println!("   Type: Internal documentation");
95    println!("   Expiration: 365 days");
96
97    // Simulate adding documents to the knowledge base
98    let file_ids = vec![
99        "file-api-docs-123".to_string(),
100        "file-coding-standards-456".to_string(),
101        "file-deployment-guide-789".to_string(),
102        "file-troubleshooting-101".to_string(),
103    ];
104
105    let populated_store = vector_store_with_files("Engineering Knowledge Base", file_ids.clone());
106
107    println!("\n Knowledge Base Contents:");
108    for (i, file_id) in populated_store.file_ids_ref().iter().enumerate() {
109        println!("   {}. {}", i + 1, file_id);
110    }
111    println!("   Total files: {}", populated_store.file_count());
112
113    // Create an assistant with file search capabilities
114    let kb_assistant = assistant_with_instructions(
115        "gpt-4-1106-preview",
116        "Engineering Knowledge Assistant",
117        "You are an engineering knowledge assistant. Help developers find relevant information from our internal documentation, coding standards, and deployment guides. Always provide accurate citations and suggest related resources when appropriate."
118    )
119    .description("Internal knowledge base assistant for engineering teams")
120    .add_tool(tool_file_search());
121
122    println!("\n Created knowledge base assistant:");
123    println!("   Name: {}", kb_assistant.name_ref().unwrap());
124    println!("   Capability: File search through engineering documents");
125
126    println!("\n Example Knowledge Base Query:");
127    println!("   'What are our coding standards for API documentation?'");
128
129    println!("\n RAG Workflow for Knowledge Base:");
130    println!("   1.  Search vector store for relevant documents");
131    println!("   2.  Retrieve matching sections from coding standards");
132    println!("   3.  Generate response based on retrieved content");
133    println!("   4.  Provide citations to specific documents");
134    println!("   5.  Suggest related topics or documents");
135
136    println!("\n Expected Knowledge Base Response:");
137    println!("   • Specific coding standards for API documentation");
138    println!("   • Citations: 'coding-standards-456.md, section 3.2'");
139    println!("   • Examples from deployment guide");
140    println!("   • Related resources: troubleshooting guide");
141
142    Ok(())
143}
Source

pub fn expires_after_ref(&self) -> Option<&VectorStoreExpirationPolicy>

Get the expiration policy for this vector store.

Examples found in repository?
examples/vector_stores.rs (line 120)
82fn run_basic_vector_store_example() -> Result<(), Error> {
83    println!(" Example 1: Basic Vector Store Operations");
84    println!("{}", "=".repeat(60));
85
86    // Create a simple vector store
87    let basic_store = simple_vector_store("Getting Started Vector Store")
88        .metadata("purpose", "tutorial")
89        .metadata("created_by", "openai_ergonomic_example");
90
91    println!(" Created basic vector store:");
92    println!("   Name: {}", basic_store.name_ref().unwrap());
93    println!(
94        "   Purpose: {}",
95        basic_store.metadata_ref().get("purpose").unwrap()
96    );
97    println!("   Files: {}", basic_store.file_count());
98
99    // Add files to the vector store
100    let store_with_files = basic_store
101        .add_file("file-welcome-doc-001")
102        .add_file("file-getting-started-002")
103        .add_file("file-basic-examples-003");
104
105    println!("\n Added files to vector store:");
106    for (i, file_id) in store_with_files.file_ids_ref().iter().enumerate() {
107        println!("   {}. {}", i + 1, file_id);
108    }
109    println!("   Total files: {}", store_with_files.file_count());
110
111    // Demonstrate vector store properties
112    println!("\n Vector Store Properties:");
113    println!("   Has files: {}", store_with_files.has_files());
114    println!(
115        "   Metadata entries: {}",
116        store_with_files.metadata_ref().len()
117    );
118    println!(
119        "   Expires: {}",
120        if store_with_files.expires_after_ref().is_some() {
121            "Yes"
122        } else {
123            "No"
124        }
125    );
126
127    println!("\n Basic Operations:");
128    println!("    Create vector store");
129    println!("    Add metadata");
130    println!("    Add files");
131    println!("    Query properties");
132    println!("    Ready for search operations");
133
134    Ok(())
135}
136
137/// Example 2: Document Management and Batch Operations
138fn run_document_management_example() -> Result<(), Error> {
139    println!("\n Example 2: Document Management and Batch Operations");
140    println!("{}", "=".repeat(60));
141
142    // Simulate a large document collection
143    let document_collection = vec![
144        "file-product-docs-001",
145        "file-product-docs-002",
146        "file-api-reference-003",
147        "file-user-guide-004",
148        "file-troubleshooting-005",
149        "file-changelog-006",
150        "file-best-practices-007",
151        "file-integration-guide-008",
152    ];
153
154    // Create vector store with batch file addition
155    let doc_store = vector_store_with_files(
156        "Product Documentation Store",
157        document_collection.iter().map(|s| s.to_string()).collect(),
158    )
159    .metadata("category", "documentation")
160    .metadata("product", "api_platform")
161    .metadata("version", "v2.1")
162    .expires_after_days(180); // 6 months retention
163
164    println!(" Created documentation vector store:");
165    println!("   Name: {}", doc_store.name_ref().unwrap());
166    println!("   Documents: {} files", doc_store.file_count());
167    println!(
168        "   Category: {}",
169        doc_store.metadata_ref().get("category").unwrap()
170    );
171    println!("   Retention: 180 days");
172
173    // Demonstrate individual file operations
174    let individual_file_op = add_file_to_vector_store("doc-store-123", "file-new-feature-009");
175
176    println!("\n Individual File Operations:");
177    println!("   Adding file: {}", individual_file_op.file_id());
178    println!("   To store: {}", individual_file_op.vector_store_id());
179
180    // Simulate file organization strategies
181    println!("\n Document Organization Strategies:");
182
183    let categorized_stores = vec![
184        (
185            "API Documentation",
186            vec!["file-api-ref", "file-endpoints", "file-auth"],
187        ),
188        (
189            "User Guides",
190            vec!["file-quickstart", "file-tutorials", "file-howtos"],
191        ),
192        (
193            "Technical Specs",
194            vec!["file-architecture", "file-protocols", "file-security"],
195        ),
196        (
197            "Release Notes",
198            vec!["file-changelog", "file-migration", "file-breaking-changes"],
199        ),
200    ];
201
202    for (category, files) in &categorized_stores {
203        let category_store = vector_store_with_files(
204            format!("{} Vector Store", category),
205            files.iter().map(|s| s.to_string()).collect(),
206        )
207        .metadata("category", category.to_lowercase().replace(" ", "_"))
208        .metadata("auto_managed", "true");
209
210        println!("    {}: {} files", category, category_store.file_count());
211    }
212
213    println!("\n Document Management Workflow:");
214    println!("   1.  Batch upload documents by category");
215    println!("   2.  Apply consistent metadata tagging");
216    println!("   3. ⏰ Set appropriate retention policies");
217    println!("   4.  Enable automatic organization");
218    println!("   5.  Monitor storage usage and performance");
219
220    Ok(())
221}
222
223/// Example 3: Semantic Search and Similarity Queries
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}
Source

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

Get the metadata for this vector store.

Examples found in repository?
examples/vector_stores.rs (line 95)
82fn run_basic_vector_store_example() -> Result<(), Error> {
83    println!(" Example 1: Basic Vector Store Operations");
84    println!("{}", "=".repeat(60));
85
86    // Create a simple vector store
87    let basic_store = simple_vector_store("Getting Started Vector Store")
88        .metadata("purpose", "tutorial")
89        .metadata("created_by", "openai_ergonomic_example");
90
91    println!(" Created basic vector store:");
92    println!("   Name: {}", basic_store.name_ref().unwrap());
93    println!(
94        "   Purpose: {}",
95        basic_store.metadata_ref().get("purpose").unwrap()
96    );
97    println!("   Files: {}", basic_store.file_count());
98
99    // Add files to the vector store
100    let store_with_files = basic_store
101        .add_file("file-welcome-doc-001")
102        .add_file("file-getting-started-002")
103        .add_file("file-basic-examples-003");
104
105    println!("\n Added files to vector store:");
106    for (i, file_id) in store_with_files.file_ids_ref().iter().enumerate() {
107        println!("   {}. {}", i + 1, file_id);
108    }
109    println!("   Total files: {}", store_with_files.file_count());
110
111    // Demonstrate vector store properties
112    println!("\n Vector Store Properties:");
113    println!("   Has files: {}", store_with_files.has_files());
114    println!(
115        "   Metadata entries: {}",
116        store_with_files.metadata_ref().len()
117    );
118    println!(
119        "   Expires: {}",
120        if store_with_files.expires_after_ref().is_some() {
121            "Yes"
122        } else {
123            "No"
124        }
125    );
126
127    println!("\n Basic Operations:");
128    println!("    Create vector store");
129    println!("    Add metadata");
130    println!("    Add files");
131    println!("    Query properties");
132    println!("    Ready for search operations");
133
134    Ok(())
135}
136
137/// Example 2: Document Management and Batch Operations
138fn run_document_management_example() -> Result<(), Error> {
139    println!("\n Example 2: Document Management and Batch Operations");
140    println!("{}", "=".repeat(60));
141
142    // Simulate a large document collection
143    let document_collection = vec![
144        "file-product-docs-001",
145        "file-product-docs-002",
146        "file-api-reference-003",
147        "file-user-guide-004",
148        "file-troubleshooting-005",
149        "file-changelog-006",
150        "file-best-practices-007",
151        "file-integration-guide-008",
152    ];
153
154    // Create vector store with batch file addition
155    let doc_store = vector_store_with_files(
156        "Product Documentation Store",
157        document_collection.iter().map(|s| s.to_string()).collect(),
158    )
159    .metadata("category", "documentation")
160    .metadata("product", "api_platform")
161    .metadata("version", "v2.1")
162    .expires_after_days(180); // 6 months retention
163
164    println!(" Created documentation vector store:");
165    println!("   Name: {}", doc_store.name_ref().unwrap());
166    println!("   Documents: {} files", doc_store.file_count());
167    println!(
168        "   Category: {}",
169        doc_store.metadata_ref().get("category").unwrap()
170    );
171    println!("   Retention: 180 days");
172
173    // Demonstrate individual file operations
174    let individual_file_op = add_file_to_vector_store("doc-store-123", "file-new-feature-009");
175
176    println!("\n Individual File Operations:");
177    println!("   Adding file: {}", individual_file_op.file_id());
178    println!("   To store: {}", individual_file_op.vector_store_id());
179
180    // Simulate file organization strategies
181    println!("\n Document Organization Strategies:");
182
183    let categorized_stores = vec![
184        (
185            "API Documentation",
186            vec!["file-api-ref", "file-endpoints", "file-auth"],
187        ),
188        (
189            "User Guides",
190            vec!["file-quickstart", "file-tutorials", "file-howtos"],
191        ),
192        (
193            "Technical Specs",
194            vec!["file-architecture", "file-protocols", "file-security"],
195        ),
196        (
197            "Release Notes",
198            vec!["file-changelog", "file-migration", "file-breaking-changes"],
199        ),
200    ];
201
202    for (category, files) in &categorized_stores {
203        let category_store = vector_store_with_files(
204            format!("{} Vector Store", category),
205            files.iter().map(|s| s.to_string()).collect(),
206        )
207        .metadata("category", category.to_lowercase().replace(" ", "_"))
208        .metadata("auto_managed", "true");
209
210        println!("    {}: {} files", category, category_store.file_count());
211    }
212
213    println!("\n Document Management Workflow:");
214    println!("   1.  Batch upload documents by category");
215    println!("   2.  Apply consistent metadata tagging");
216    println!("   3. ⏰ Set appropriate retention policies");
217    println!("   4.  Enable automatic organization");
218    println!("   5.  Monitor storage usage and performance");
219
220    Ok(())
221}
222
223/// Example 3: Semantic Search and Similarity Queries
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}
Source

pub fn has_files(&self) -> bool

Check if the vector store has any files.

Examples found in repository?
examples/vector_stores.rs (line 113)
82fn run_basic_vector_store_example() -> Result<(), Error> {
83    println!(" Example 1: Basic Vector Store Operations");
84    println!("{}", "=".repeat(60));
85
86    // Create a simple vector store
87    let basic_store = simple_vector_store("Getting Started Vector Store")
88        .metadata("purpose", "tutorial")
89        .metadata("created_by", "openai_ergonomic_example");
90
91    println!(" Created basic vector store:");
92    println!("   Name: {}", basic_store.name_ref().unwrap());
93    println!(
94        "   Purpose: {}",
95        basic_store.metadata_ref().get("purpose").unwrap()
96    );
97    println!("   Files: {}", basic_store.file_count());
98
99    // Add files to the vector store
100    let store_with_files = basic_store
101        .add_file("file-welcome-doc-001")
102        .add_file("file-getting-started-002")
103        .add_file("file-basic-examples-003");
104
105    println!("\n Added files to vector store:");
106    for (i, file_id) in store_with_files.file_ids_ref().iter().enumerate() {
107        println!("   {}. {}", i + 1, file_id);
108    }
109    println!("   Total files: {}", store_with_files.file_count());
110
111    // Demonstrate vector store properties
112    println!("\n Vector Store Properties:");
113    println!("   Has files: {}", store_with_files.has_files());
114    println!(
115        "   Metadata entries: {}",
116        store_with_files.metadata_ref().len()
117    );
118    println!(
119        "   Expires: {}",
120        if store_with_files.expires_after_ref().is_some() {
121            "Yes"
122        } else {
123            "No"
124        }
125    );
126
127    println!("\n Basic Operations:");
128    println!("    Create vector store");
129    println!("    Add metadata");
130    println!("    Add files");
131    println!("    Query properties");
132    println!("    Ready for search operations");
133
134    Ok(())
135}
Source

pub fn file_count(&self) -> usize

Get the number of files in the vector store.

Examples found in repository?
examples/vector_stores.rs (line 97)
82fn run_basic_vector_store_example() -> Result<(), Error> {
83    println!(" Example 1: Basic Vector Store Operations");
84    println!("{}", "=".repeat(60));
85
86    // Create a simple vector store
87    let basic_store = simple_vector_store("Getting Started Vector Store")
88        .metadata("purpose", "tutorial")
89        .metadata("created_by", "openai_ergonomic_example");
90
91    println!(" Created basic vector store:");
92    println!("   Name: {}", basic_store.name_ref().unwrap());
93    println!(
94        "   Purpose: {}",
95        basic_store.metadata_ref().get("purpose").unwrap()
96    );
97    println!("   Files: {}", basic_store.file_count());
98
99    // Add files to the vector store
100    let store_with_files = basic_store
101        .add_file("file-welcome-doc-001")
102        .add_file("file-getting-started-002")
103        .add_file("file-basic-examples-003");
104
105    println!("\n Added files to vector store:");
106    for (i, file_id) in store_with_files.file_ids_ref().iter().enumerate() {
107        println!("   {}. {}", i + 1, file_id);
108    }
109    println!("   Total files: {}", store_with_files.file_count());
110
111    // Demonstrate vector store properties
112    println!("\n Vector Store Properties:");
113    println!("   Has files: {}", store_with_files.has_files());
114    println!(
115        "   Metadata entries: {}",
116        store_with_files.metadata_ref().len()
117    );
118    println!(
119        "   Expires: {}",
120        if store_with_files.expires_after_ref().is_some() {
121            "Yes"
122        } else {
123            "No"
124        }
125    );
126
127    println!("\n Basic Operations:");
128    println!("    Create vector store");
129    println!("    Add metadata");
130    println!("    Add files");
131    println!("    Query properties");
132    println!("    Ready for search operations");
133
134    Ok(())
135}
136
137/// Example 2: Document Management and Batch Operations
138fn run_document_management_example() -> Result<(), Error> {
139    println!("\n Example 2: Document Management and Batch Operations");
140    println!("{}", "=".repeat(60));
141
142    // Simulate a large document collection
143    let document_collection = vec![
144        "file-product-docs-001",
145        "file-product-docs-002",
146        "file-api-reference-003",
147        "file-user-guide-004",
148        "file-troubleshooting-005",
149        "file-changelog-006",
150        "file-best-practices-007",
151        "file-integration-guide-008",
152    ];
153
154    // Create vector store with batch file addition
155    let doc_store = vector_store_with_files(
156        "Product Documentation Store",
157        document_collection.iter().map(|s| s.to_string()).collect(),
158    )
159    .metadata("category", "documentation")
160    .metadata("product", "api_platform")
161    .metadata("version", "v2.1")
162    .expires_after_days(180); // 6 months retention
163
164    println!(" Created documentation vector store:");
165    println!("   Name: {}", doc_store.name_ref().unwrap());
166    println!("   Documents: {} files", doc_store.file_count());
167    println!(
168        "   Category: {}",
169        doc_store.metadata_ref().get("category").unwrap()
170    );
171    println!("   Retention: 180 days");
172
173    // Demonstrate individual file operations
174    let individual_file_op = add_file_to_vector_store("doc-store-123", "file-new-feature-009");
175
176    println!("\n Individual File Operations:");
177    println!("   Adding file: {}", individual_file_op.file_id());
178    println!("   To store: {}", individual_file_op.vector_store_id());
179
180    // Simulate file organization strategies
181    println!("\n Document Organization Strategies:");
182
183    let categorized_stores = vec![
184        (
185            "API Documentation",
186            vec!["file-api-ref", "file-endpoints", "file-auth"],
187        ),
188        (
189            "User Guides",
190            vec!["file-quickstart", "file-tutorials", "file-howtos"],
191        ),
192        (
193            "Technical Specs",
194            vec!["file-architecture", "file-protocols", "file-security"],
195        ),
196        (
197            "Release Notes",
198            vec!["file-changelog", "file-migration", "file-breaking-changes"],
199        ),
200    ];
201
202    for (category, files) in &categorized_stores {
203        let category_store = vector_store_with_files(
204            format!("{} Vector Store", category),
205            files.iter().map(|s| s.to_string()).collect(),
206        )
207        .metadata("category", category.to_lowercase().replace(" ", "_"))
208        .metadata("auto_managed", "true");
209
210        println!("    {}: {} files", category, category_store.file_count());
211    }
212
213    println!("\n Document Management Workflow:");
214    println!("   1.  Batch upload documents by category");
215    println!("   2.  Apply consistent metadata tagging");
216    println!("   3. ⏰ Set appropriate retention policies");
217    println!("   4.  Enable automatic organization");
218    println!("   5.  Monitor storage usage and performance");
219
220    Ok(())
221}
222
223/// Example 3: Semantic Search and Similarity Queries
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 111)
82fn run_knowledge_base_example() -> Result<(), Error> {
83    println!(" Example 1: Building a Knowledge Base Assistant");
84    println!("{}", "=".repeat(60));
85
86    // Create a knowledge base vector store
87    let knowledge_store = simple_vector_store("Company Knowledge Base")
88        .metadata("type", "internal_docs")
89        .metadata("department", "engineering")
90        .expires_after_days(365); // Expire after 1 year
91
92    println!(" Created knowledge base vector store:");
93    println!("   Name: {}", knowledge_store.name_ref().unwrap());
94    println!("   Type: Internal documentation");
95    println!("   Expiration: 365 days");
96
97    // Simulate adding documents to the knowledge base
98    let file_ids = vec![
99        "file-api-docs-123".to_string(),
100        "file-coding-standards-456".to_string(),
101        "file-deployment-guide-789".to_string(),
102        "file-troubleshooting-101".to_string(),
103    ];
104
105    let populated_store = vector_store_with_files("Engineering Knowledge Base", file_ids.clone());
106
107    println!("\n Knowledge Base Contents:");
108    for (i, file_id) in populated_store.file_ids_ref().iter().enumerate() {
109        println!("   {}. {}", i + 1, file_id);
110    }
111    println!("   Total files: {}", populated_store.file_count());
112
113    // Create an assistant with file search capabilities
114    let kb_assistant = assistant_with_instructions(
115        "gpt-4-1106-preview",
116        "Engineering Knowledge Assistant",
117        "You are an engineering knowledge assistant. Help developers find relevant information from our internal documentation, coding standards, and deployment guides. Always provide accurate citations and suggest related resources when appropriate."
118    )
119    .description("Internal knowledge base assistant for engineering teams")
120    .add_tool(tool_file_search());
121
122    println!("\n Created knowledge base assistant:");
123    println!("   Name: {}", kb_assistant.name_ref().unwrap());
124    println!("   Capability: File search through engineering documents");
125
126    println!("\n Example Knowledge Base Query:");
127    println!("   'What are our coding standards for API documentation?'");
128
129    println!("\n RAG Workflow for Knowledge Base:");
130    println!("   1.  Search vector store for relevant documents");
131    println!("   2.  Retrieve matching sections from coding standards");
132    println!("   3.  Generate response based on retrieved content");
133    println!("   4.  Provide citations to specific documents");
134    println!("   5.  Suggest related topics or documents");
135
136    println!("\n Expected Knowledge Base Response:");
137    println!("   • Specific coding standards for API documentation");
138    println!("   • Citations: 'coding-standards-456.md, section 3.2'");
139    println!("   • Examples from deployment guide");
140    println!("   • Related resources: troubleshooting guide");
141
142    Ok(())
143}
144
145/// Example 2: Document Q&A Assistant
146fn run_document_qa_example() -> Result<(), Error> {
147    println!("\n Example 2: Document Q&A Assistant");
148    println!("{}", "=".repeat(60));
149
150    // Create specialized document Q&A assistant
151    let _qa_assistant = AssistantBuilder::new("gpt-4-1106-preview")
152        .name("Document Q&A Specialist")
153        .description("Answers questions based on uploaded documents with high accuracy")
154        .instructions(
155            "You are a document Q&A specialist. Answer questions by searching through the provided documents. Always cite your sources, indicate confidence levels, and acknowledge when information is not available in the documents."
156        )
157        .add_tool(tool_file_search());
158
159    println!(" Created Document Q&A assistant:");
160    println!("   Specialty: Precise question answering from documents");
161
162    // Create a temporary vector store for this Q&A session
163    let qa_store = temporary_vector_store("Q&A Session Store", 7) // Expires in 7 days
164        .add_file("file-research-paper-001")
165        .add_file("file-user-manual-002")
166        .add_file("file-technical-spec-003")
167        .metadata("session_id", "qa-session-123")
168        .metadata("user", "researcher-001");
169
170    println!("\n Q&A Document Store:");
171    println!("   Files: {} documents loaded", qa_store.file_count());
172    println!("   Expiration: 7 days (temporary session)");
173    println!("   Session ID: qa-session-123");
174
175    println!("\n Example Q&A Queries:");
176    let queries = vec![
177        "What is the maximum throughput mentioned in the technical specifications?",
178        "How do I configure the authentication system according to the user manual?",
179        "What are the key findings from the research paper regarding performance?",
180        "Are there any known limitations discussed in these documents?",
181    ];
182
183    for (i, query) in queries.iter().enumerate() {
184        println!("   {}. {}", i + 1, query);
185    }
186
187    println!("\n Document Q&A RAG Workflow:");
188    println!("   1.  Process user question");
189    println!("   2.  Generate search queries for vector store");
190    println!("   3.  Retrieve relevant document sections");
191    println!("   4.  Rank and filter results by relevance");
192    println!("   5.  Generate answer from retrieved context");
193    println!("   6.  Add citations and confidence indicators");
194
195    println!("\n Expected Q&A Response Format:");
196    println!("    Direct answer to the question");
197    println!("    Citations: [technical-spec-003.pdf, page 15]");
198    println!("    Confidence: High (90%)");
199    println!("    Related information: See also user-manual-002.pdf, section 4.3");
200    println!("     Limitations: No information found about edge cases");
201
202    Ok(())
203}

Trait Implementations§

Source§

impl Clone for VectorStoreBuilder

Source§

fn clone(&self) -> VectorStoreBuilder

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 VectorStoreBuilder

Source§

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

Formats the value using the given formatter. Read more
Source§

impl Default for VectorStoreBuilder

Source§

fn default() -> Self

Returns the “default value” for a type. 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,