/ examples / context / 14_agent_context_param.py
14_agent_context_param.py
  1  #!/usr/bin/env python3
  2  """
  3  Agent-Centric Context Management Example
  4  
  5  Demonstrates the recommended way to use context management with the new
  6  `context=` parameter. This is the simplest and most powerful approach.
  7  
  8  The `context=` parameter accepts:
  9  - False (default): Zero overhead, no context management
 10  - True: Enable with safe defaults (auto-compact, smart strategy)
 11  - ManagerConfig: Custom configuration object
 12  - ContextManager: Pre-configured manager instance
 13  
 14  Requires: OPENAI_API_KEY environment variable
 15  """
 16  
 17  import os
 18  from praisonaiagents import Agent
 19  from praisonaiagents.context import ManagerConfig
 20  
 21  
 22  def example_1_simple_enable():
 23      """Simplest usage - just enable context management."""
 24      print("=" * 60)
 25      print("Example 1: Simple Enable (context=True)")
 26      print("=" * 60)
 27      
 28      # Create agent with context management enabled
 29      agent = Agent(
 30          instructions="You are a helpful assistant. Keep responses concise.",
 31          llm="gpt-4o-mini",
 32          context=True,  # Enable with safe defaults
 33      )
 34      
 35      # The agent now automatically:
 36      # - Tracks token usage
 37      # - Optimizes when approaching limits (80% threshold)
 38      # - Uses smart optimization strategy
 39      
 40      print("Agent created with context management enabled")
 41      print(f"Context manager initialized: {agent.context_manager is not None}")
 42      
 43      if agent.context_manager:
 44          print(f"Model: {agent.context_manager.model}")
 45          print(f"Auto-compact: {agent.context_manager.config.auto_compact}")
 46          print(f"Threshold: {agent.context_manager.config.compact_threshold}")
 47          print(f"Strategy: {agent.context_manager.config.strategy}")
 48      
 49      # Make a chat call
 50      if os.environ.get("OPENAI_API_KEY"):
 51          response = agent.chat("What is 2+2?")
 52          print(f"\nResponse: {response}")
 53      else:
 54          print("\nSkipping API call (no OPENAI_API_KEY)")
 55      
 56      print()
 57  
 58  
 59  def example_2_custom_config():
 60      """Custom configuration with ManagerConfig."""
 61      print("=" * 60)
 62      print("Example 2: Custom Configuration (context=ManagerConfig)")
 63      print("=" * 60)
 64      
 65      # Create custom configuration
 66      config = ManagerConfig(
 67          auto_compact=True,
 68          compact_threshold=0.7,  # Trigger at 70% instead of 80%
 69          strategy="smart",
 70          monitor_enabled=True,
 71          monitor_path="./context_debug.txt",
 72          monitor_format="human",
 73          redact_sensitive=True,
 74          output_reserve=8000,
 75      )
 76      
 77      # Create agent with custom config
 78      agent = Agent(
 79          instructions="You are a code assistant.",
 80          llm="gpt-4o-mini",
 81          context=config,
 82      )
 83      
 84      print("Agent created with custom context config")
 85      print(f"Threshold: {agent.context_manager.config.compact_threshold}")
 86      print(f"Monitor enabled: {agent.context_manager.config.monitor_enabled}")
 87      print(f"Monitor path: {agent.context_manager.config.monitor_path}")
 88      
 89      if os.environ.get("OPENAI_API_KEY"):
 90          response = agent.chat("Write a hello world in Python")
 91          print(f"\nResponse: {response[:200]}...")
 92      else:
 93          print("\nSkipping API call (no OPENAI_API_KEY)")
 94      
 95      print()
 96  
 97  
 98  def example_3_disabled():
 99      """Disabled context management - zero overhead."""
100      print("=" * 60)
101      print("Example 3: Disabled (context=False)")
102      print("=" * 60)
103      
104      # Create agent without context management (default)
105      agent = Agent(
106          instructions="You are a simple assistant.",
107          llm="gpt-4o-mini",
108          context=False,  # Explicit disable (same as default)
109      )
110      
111      print("Agent created without context management")
112      print(f"Context manager: {agent.context_manager}")
113      print("Zero overhead: No token tracking, no optimization")
114      
115      if os.environ.get("OPENAI_API_KEY"):
116          response = agent.chat("Hello!")
117          print(f"\nResponse: {response}")
118      else:
119          print("\nSkipping API call (no OPENAI_API_KEY)")
120      
121      print()
122  
123  
124  def example_4_access_stats():
125      """Access context statistics and history."""
126      print("=" * 60)
127      print("Example 4: Access Context Stats")
128      print("=" * 60)
129      
130      agent = Agent(
131          instructions="You are helpful.",
132          llm="gpt-4o-mini",
133          context=True,
134      )
135      
136      manager = agent.context_manager
137      
138      # Access budget info via internal attribute
139      budget = manager._budget
140      print(f"Model limit: {budget.model_limit:,} tokens")
141      print(f"Output reserve: {budget.output_reserve:,} tokens")
142      print(f"Usable budget: {budget.usable:,} tokens")
143      
144      # Access config
145      print("\nConfiguration:")
146      print(f"  Auto-compact: {manager.config.auto_compact}")
147      print(f"  Threshold: {manager.config.compact_threshold}")
148      print(f"  Strategy: {manager.config.strategy}")
149      
150      print()
151  
152  
153  def example_5_multi_agent():
154      """Multi-agent with shared context management."""
155      print("=" * 60)
156      print("Example 5: Multi-Agent Context Management")
157      print("=" * 60)
158      
159      from praisonaiagents import AgentTeam, Task
160      
161      config = ManagerConfig(
162          auto_compact=True,
163          compact_threshold=0.8,
164      )
165      
166      # Create agents
167      researcher = Agent(
168          name="Researcher",
169          instructions="You research topics thoroughly.",
170          llm="gpt-4o-mini",
171      )
172      
173      writer = Agent(
174          name="Writer", 
175          instructions="You write clear summaries.",
176          llm="gpt-4o-mini",
177      )
178      
179      # Create tasks
180      task1 = Task(description="Research AI trends", agent=researcher)
181      task2 = Task(description="Write a summary", agent=writer)
182      
183      # Create multi-agent system with context management
184      agents = AgentTeam(
185          agents=[researcher, writer],
186          tasks=[task1, task2],
187          context=config,  # Shared context config
188      )
189      
190      print("Multi-agent system created")
191      print(f"Context manager: {agents.context_manager is not None}")
192      
193      if agents.context_manager:
194          print("Type: MultiAgentContextManager")
195          print("Provides per-agent isolation with shared config")
196      
197      print()
198  
199  
200  def main():
201      print("\n" + "=" * 60)
202      print("Agent-Centric Context Management Examples")
203      print("=" * 60 + "\n")
204      
205      example_1_simple_enable()
206      example_2_custom_config()
207      example_3_disabled()
208      example_4_access_stats()
209      example_5_multi_agent()
210      
211      print("=" * 60)
212      print("✓ All examples complete!")
213      print("=" * 60)
214  
215  
216  if __name__ == "__main__":
217      main()