/ examples / knowledge / scope_isolation_example.py
scope_isolation_example.py
  1  #!/usr/bin/env python3
  2  """
  3  Example: Multi-Agent Scope Isolation
  4  
  5  This example demonstrates:
  6  1. Agent A ingests knowledge under user_id=U1
  7  2. Agent B queries under user_id=U2 - should NOT find the knowledge
  8  3. Agent B queries under user_id=U1 - should find the knowledge
  9  4. Proves scope isolation works correctly
 10  
 11  Requirements:
 12  - pip install praisonaiagents[knowledge]
 13  - OPENAI_API_KEY environment variable
 14  
 15  Usage:
 16      python scope_isolation_example.py
 17  """
 18  
 19  import os
 20  import tempfile
 21  import shutil
 22  
 23  from praisonaiagents import Agent, Knowledge
 24  
 25  
 26  def main():
 27      temp_dir = tempfile.mkdtemp(prefix='praison_scope_')
 28      
 29      try:
 30          # Create test document with UNIQUE secret
 31          doc = os.path.join(temp_dir, 'secret.txt')
 32          with open(doc, 'w') as f:
 33              f.write("""
 34  Project Codename: PHOENIX
 35  Secret access code: WRENCH-992
 36  Classification: Top Secret
 37  Only authorized personnel with code WRENCH-992 may access this project.
 38              """)
 39          
 40          print("=" * 60)
 41          print("Example: Multi-Agent Scope Isolation")
 42          print("=" * 60)
 43          
 44          # Step 1: Agent A ingests knowledge under user_id=U1
 45          print("\n1. Agent A ingests knowledge under user_id='user_alice'")
 46          print("-" * 40)
 47          
 48          agent_a = Agent(
 49              name="AgentA_Ingester",
 50              instructions="You ingest and store knowledge.",
 51              knowledge=[temp_dir],
 52              user_id="user_alice",  # Scoped to Alice
 53              output="silent",
 54          )
 55          
 56          # Ensure knowledge is processed
 57          agent_a._ensure_knowledge_processed()
 58          print("   Knowledge ingested by Agent A under user_alice scope")
 59          
 60          # Step 2: Agent B queries under user_id=U2 - should NOT find
 61          print("\n2. Agent B queries under user_id='user_bob' (different scope)")
 62          print("-" * 40)
 63          
 64          # Create a separate Knowledge instance for Agent B with different scope
 65          knowledge_b = Knowledge()
 66          search_result = knowledge_b.search("WRENCH-992", user_id="user_bob")
 67          
 68          results = search_result.get('results', []) if isinstance(search_result, dict) else []
 69          
 70          if len(results) == 0:
 71              print("   ✅ CORRECT: Agent B (user_bob) found NO results")
 72              print("   Scope isolation is working!")
 73          else:
 74              # Check if any result actually contains the secret
 75              found_secret = any('wrench-992' in str(r.get('memory', '')).lower() for r in results)
 76              if found_secret:
 77                  print("   ❌ ERROR: Agent B found the secret - scope isolation failed!")
 78              else:
 79                  print("   ✅ CORRECT: Agent B found no matching content")
 80          
 81          # Step 3: Agent B queries under user_id=U1 - should find
 82          print("\n3. Agent B queries under user_id='user_alice' (same scope)")
 83          print("-" * 40)
 84          
 85          search_result = knowledge_b.search("WRENCH-992", user_id="user_alice")
 86          results = search_result.get('results', []) if isinstance(search_result, dict) else []
 87          
 88          if len(results) > 0:
 89              memory = results[0].get('memory', '')
 90              if 'wrench-992' in memory.lower():
 91                  print("   ✅ CORRECT: Agent B (as user_alice) found the secret!")
 92                  print(f"   Retrieved: {memory[:80]}...")
 93              else:
 94                  print(f"   ⚠️ Found results but no secret: {memory[:80]}...")
 95          else:
 96              print("   ❌ ERROR: Agent B should have found results with user_alice scope")
 97          
 98          # Step 4: Full Agent chat test with scope
 99          print("\n4. Full Agent chat test with correct scope")
100          print("-" * 40)
101          
102          agent_b = Agent(
103              name="AgentB_Querier",
104              instructions="Answer questions based on the provided knowledge. If you don't have the information, say so.",
105              knowledge=[temp_dir],
106              user_id="user_alice",  # Same scope as Agent A
107              output="silent",
108          )
109          
110          response = agent_b.chat("What is the secret access code for Project PHOENIX?")
111          print(f"   Question: What is the secret access code?")
112          print(f"   Answer: {response}")
113          
114          if "WRENCH-992" in response.upper():
115              print("\n   ✅ VERIFIED: Agent correctly retrieved the secret code!")
116          else:
117              print("\n   ⚠️ Agent may not have found the code")
118          
119          print("\n" + "=" * 60)
120          print("Summary: Scope Isolation")
121          print("=" * 60)
122          print("""
123  - user_id='user_alice': Can access knowledge ingested by user_alice
124  - user_id='user_bob': Cannot access knowledge ingested by user_alice
125  - This enables multi-tenant knowledge isolation
126          """)
127          
128      finally:
129          shutil.rmtree(temp_dir, ignore_errors=True)
130  
131  
132  if __name__ == "__main__":
133      main()