/ examples / rag / basic_retrieval.py
basic_retrieval.py
  1  """
  2  Basic RAG: Retrieve and Generate
  3  
  4  This example demonstrates the fundamental RAG pattern in PraisonAI:
  5  1. Provide context to an agent
  6  2. Agent uses context to answer questions accurately
  7  3. Generate grounded answers using the provided context
  8  
  9  RAG Concept: The core retrieve-then-generate pattern that grounds LLM responses
 10  in factual content, reducing hallucinations.
 11  """
 12  
 13  from praisonaiagents import Agent
 14  
 15  # Sample knowledge base: Technology company profiles as text strings
 16  COMPANY_PROFILES = [
 17      """NovaTech Solutions specializes in cloud infrastructure and DevOps automation.
 18      Founded in 2018, they serve over 500 enterprise clients globally.
 19      Key products: CloudSync (infrastructure orchestration), DevPipeline (CI/CD platform).
 20      Headquarters: Austin, Texas. Employees: 1,200.""",
 21      
 22      """GreenLeaf Analytics provides environmental monitoring and sustainability reporting.
 23      Established in 2015, they work with governments and corporations on climate data.
 24      Key products: EcoTrack (emissions monitoring), SustainReport (ESG reporting).
 25      Headquarters: Seattle, Washington. Employees: 450.""",
 26      
 27      """QuantumBridge Financial offers algorithmic trading and risk management solutions.
 28      Started in 2012, they manage over $50 billion in assets for institutional clients.
 29      Key products: AlgoTrader Pro (trading platform), RiskShield (portfolio analytics).
 30      Headquarters: New York City. Employees: 800.""",
 31      
 32      """MediCore Health develops AI-powered diagnostic tools for healthcare providers.
 33      Founded in 2019, they partner with 200+ hospitals across North America.
 34      Key products: DiagnosAI (medical imaging analysis), PatientFlow (care coordination).
 35      Headquarters: Boston, Massachusetts. Employees: 350."""
 36  ]
 37  
 38  
 39  def basic_rag_example():
 40      """Demonstrate basic RAG with context injection."""
 41      
 42      # Build context from knowledge base
 43      context = "\n\n".join(COMPANY_PROFILES)
 44      
 45      # Create an agent with instructions
 46      agent = Agent(
 47          name="Company Analyst",
 48          instructions=f"""You are a business analyst who answers questions about companies.
 49          Use only the following company information to answer questions accurately.
 50          If the information isn't available, say so clearly.
 51          
 52          COMPANY DATABASE:
 53          {context}""",
 54      )
 55      
 56      # Test queries
 57      queries = [
 58          "What products does NovaTech Solutions offer?",
 59          "Which company focuses on environmental monitoring?",
 60          "How many employees does QuantumBridge Financial have?",
 61          "What is MediCore Health's main focus area?"
 62      ]
 63      
 64      print("=" * 60)
 65      print("BASIC RAG EXAMPLE: Company Knowledge Base")
 66      print("=" * 60)
 67      
 68      for query in queries:
 69          print(f"\nšŸ“ Query: {query}")
 70          response = agent.chat(query)
 71          print(f"šŸ’” Answer: {response}")
 72          print("-" * 40)
 73  
 74  
 75  def rag_with_query_context():
 76      """Demonstrate per-query context injection for RAG."""
 77      
 78      # Create a general agent
 79      agent = Agent(
 80          name="Research Assistant",
 81          instructions="You answer questions based on the context provided in each query.",
 82          output="silent"
 83      )
 84      
 85      # Simulate retrieved context (in real RAG, this comes from vector search)
 86      retrieved_context = """
 87      The Pacific Ocean is the largest and deepest ocean on Earth.
 88      It covers approximately 165.25 million square kilometers.
 89      The Mariana Trench, located in the Pacific, is the deepest known point at 10,994 meters.
 90      The Pacific Ocean was named by explorer Ferdinand Magellan in 1520.
 91      """
 92      
 93      query = "What is the deepest point in the Pacific Ocean?"
 94      
 95      # Build prompt with context (RAG pattern)
 96      prompt_with_context = f"""Use the following context to answer the question.
 97  
 98  Context:
 99  {retrieved_context}
100  
101  Question: {query}
102  
103  Answer based only on the context provided:"""
104      
105      print("\n" + "=" * 60)
106      print("RAG WITH PER-QUERY CONTEXT INJECTION")
107      print("=" * 60)
108      
109      print(f"\nšŸ“š Context: {retrieved_context[:100]}...")
110      print(f"\nšŸ“ Query: {query}")
111      
112      response = agent.chat(prompt_with_context)
113      print(f"\nšŸ’” Answer: {response}")
114  
115  
116  def main():
117      """Run all basic RAG examples."""
118      print("\nšŸš€ PraisonAI Basic RAG Examples\n")
119      
120      # Example 1: Basic RAG with knowledge base
121      basic_rag_example()
122      
123      # Example 2: Per-query context injection
124      rag_with_query_context()
125      
126      print("\nāœ… Basic RAG examples completed!")
127  
128  
129  if __name__ == "__main__":
130      main()