/ examples / context / 10_context_monitoring.py
10_context_monitoring.py
  1  #!/usr/bin/env python3
  2  """
  3  Context Monitoring Example
  4  
  5  Demonstrates how to use context monitoring with Agent via context= param,
  6  and also shows low-level ContextMonitor usage for advanced scenarios.
  7  
  8  Agent-Centric Quick Start:
  9      from praisonaiagents import Agent
 10      from praisonaiagents.context import ManagerConfig
 11      
 12      agent = Agent(
 13          instructions="You are helpful.",
 14          context=ManagerConfig(
 15              monitor_enabled=True,
 16              monitor_path="./debug/context.json",
 17          ),
 18      )
 19  """
 20  
 21  import os
 22  import tempfile
 23  from praisonaiagents import Agent
 24  from praisonaiagents.context import (
 25      ManagerConfig,
 26      ContextMonitor,
 27      ContextLedger,
 28      BudgetAllocation,
 29      format_human_snapshot,
 30      format_json_snapshot,
 31      redact_sensitive,
 32      ContextSnapshot,
 33  )
 34  
 35  
 36  def agent_centric_example():
 37      """Agent-centric usage - recommended approach."""
 38      print("=" * 60)
 39      print("Agent-Centric Context Monitoring")
 40      print("=" * 60)
 41      
 42      with tempfile.TemporaryDirectory() as tmpdir:
 43          monitor_path = os.path.join(tmpdir, "context.json")
 44          
 45          agent = Agent(
 46              instructions="You are a helpful assistant.",
 47              context=ManagerConfig(
 48                  monitor_enabled=True,
 49                  monitor_path=monitor_path,
 50                  monitor_format="json",
 51              ),
 52          )
 53          print(f"Agent with monitoring enabled")
 54          print(f"Monitor path: {monitor_path}")
 55          print(f"Context manager: {agent.context_manager is not None}")
 56  
 57  
 58  def main():
 59      print("=" * 60)
 60      print("Context Monitoring Example")
 61      print("=" * 60)
 62      
 63      # Sample conversation for demonstration
 64      messages = [
 65          {"role": "system", "content": "You are a helpful AI assistant."},
 66          {"role": "user", "content": "What is the weather like today?"},
 67          {"role": "assistant", "content": "I don't have access to real-time weather data."},
 68          {"role": "user", "content": "Can you help me write Python code?"},
 69          {"role": "assistant", "content": "Of course! I'd be happy to help with Python."},
 70      ]
 71      
 72      # Example 1: Basic monitoring setup
 73      print("\n1. Basic Monitor Setup")
 74      print("-" * 40)
 75      
 76      with tempfile.TemporaryDirectory() as tmpdir:
 77          context_path = os.path.join(tmpdir, "context.txt")
 78          
 79          monitor = ContextMonitor(
 80              enabled=True,
 81              path=context_path,
 82              format="human",
 83              frequency="turn",
 84          )
 85          
 86          print(f"Monitor enabled: {monitor.enabled}")
 87          print(f"Output path: {context_path}")
 88          print(f"Format: {monitor.format}")
 89          
 90          # Create sample ledger and budget
 91          ledger = ContextLedger(
 92              system_prompt=500,
 93              history=2500,
 94              tools_schema=300,
 95              tool_outputs=1200,
 96          )
 97          
 98          budget = BudgetAllocation(
 99              model_limit=128000,
100              output_reserve=8000,
101          )
102          
103          # Write snapshot
104          result_path = monitor.snapshot(
105              ledger=ledger,
106              budget=budget,
107              messages=messages,
108              trigger="turn",
109          )
110          
111          print(f"\nāœ“ Snapshot written to: {result_path}")
112          
113          # Read and display
114          with open(context_path) as f:
115              content = f.read()
116          print(f"\nSnapshot preview ({len(content)} chars):")
117          print("-" * 40)
118          print(content[:500] + "..." if len(content) > 500 else content)
119      
120      # Example 2: JSON format
121      print("\n\n2. JSON Format Output")
122      print("-" * 40)
123      
124      with tempfile.TemporaryDirectory() as tmpdir:
125          json_path = os.path.join(tmpdir, "context.json")
126          
127          monitor = ContextMonitor(
128              enabled=True,
129              path=json_path,
130              format="json",
131          )
132          
133          monitor.snapshot(
134              ledger=ledger,
135              budget=budget,
136              messages=messages,
137              trigger="manual",
138          )
139          
140          with open(json_path) as f:
141              content = f.read()
142          
143          print(f"JSON snapshot ({len(content)} chars):")
144          print(content[:300] + "..." if len(content) > 300 else content)
145      
146      # Example 3: Sensitive data redaction
147      print("\n\n3. Sensitive Data Redaction")
148      print("-" * 40)
149      
150      sensitive_text = """
151      Here's my API key: sk-proj-abc123def456ghi789
152      And my password is: supersecret123
153      Database connection: postgresql://user:pass@localhost/db
154      """
155      
156      redacted = redact_sensitive(sensitive_text)
157      print("Original text contains sensitive data:")
158      print(f"  - API key pattern found: {'sk-proj-' in sensitive_text}")
159      print(f"  - Password pattern found: {'password' in sensitive_text.lower()}")
160      print("\nAfter redaction:")
161      print(redacted)
162      
163      # Example 4: Monitor frequency options
164      print("\n4. Monitor Frequency Options")
165      print("-" * 40)
166      
167      frequencies = ["turn", "tool_call", "manual", "overflow"]
168      
169      for freq in frequencies:
170          monitor = ContextMonitor(enabled=True, frequency=freq)
171          
172          # Check what triggers writing
173          triggers = {
174              "turn": monitor.should_write("turn"),
175              "tool_call": monitor.should_write("tool_call"),
176              "manual": monitor.should_write("manual"),
177              "overflow": monitor.should_write("overflow"),
178          }
179          
180          active = [k for k, v in triggers.items() if v]
181          print(f"Frequency '{freq}': writes on {active}")
182      
183      # Example 5: Snapshot data structure
184      print("\n5. Snapshot Data Structure")
185      print("-" * 40)
186      
187      snapshot = ContextSnapshot(
188          timestamp="2025-01-07T19:30:00Z",
189          session_id="example-session-123",
190          agent_name="ExampleAgent",
191          model_name="gpt-4o-mini",
192          budget=budget,
193          ledger=ledger,
194          utilization=0.45,
195          warnings=["Context usage at 45%"],
196      )
197      
198      print(f"Snapshot fields:")
199      print(f"  - timestamp: {snapshot.timestamp}")
200      print(f"  - session_id: {snapshot.session_id}")
201      print(f"  - agent_name: {snapshot.agent_name}")
202      print(f"  - model_name: {snapshot.model_name}")
203      print(f"  - utilization: {snapshot.utilization:.1%}")
204      print(f"  - warnings: {snapshot.warnings}")
205      
206      # Format as human-readable
207      human_output = format_human_snapshot(snapshot)
208      print(f"\nHuman-readable format ({len(human_output)} chars)")
209      
210      # Format as JSON
211      json_output = format_json_snapshot(snapshot)
212      print(f"JSON format ({len(json_output)} chars)")
213      
214      print("\n" + "=" * 60)
215      print("āœ“ Context monitoring examples complete!")
216      print("=" * 60)
217  
218  
219  if __name__ == "__main__":
220      main()