/ examples / agent_centric_api.py
agent_centric_api.py
  1  """
  2  Agent-Centric API Example
  3  
  4  Demonstrates the consolidated feature parameters for PraisonAI Agents.
  5  These params provide a cleaner, more intuitive API with progressive disclosure.
  6  
  7  Precedence Rule: Instance > Config > Array > String > Bool > Default
  8  
  9  Consolidated Params Support:
 10  - memory: bool | str URL | str preset | [preset, overrides] | MemoryConfig | Instance
 11  - knowledge: bool | str path | [sources...] | KnowledgeConfig | Instance
 12  - planning: bool | str LLM | [preset, overrides] | PlanningConfig
 13  - reflection: bool | str preset | [preset, overrides] | ReflectionConfig
 14  - guardrails: bool | callable | str prompt | GuardrailConfig
 15  - web: bool | str provider | [provider, overrides] | WebConfig
 16  - output: str preset | [preset, overrides] | OutputConfig
 17  - execution: str preset | [preset, overrides] | ExecutionConfig
 18  """
 19  
 20  from praisonaiagents import (
 21      Agent,
 22      # Config classes for progressive disclosure
 23      MemoryConfig,
 24      KnowledgeConfig,
 25      PlanningConfig,
 26      ReflectionConfig,
 27      GuardrailConfig,
 28      WebConfig,
 29  )
 30  
 31  
 32  def example_simple_enable():
 33      """Example 1: Simple boolean enable (easiest)"""
 34      print("\n=== Example 1: Simple Boolean Enable ===")
 35      
 36      agent = Agent(
 37          instructions="You are a helpful assistant",
 38          memory=True,      # Enable memory with defaults
 39          reflection=True,  # Enable self-reflection
 40          web=WebConfig(fetch=False),         # Enable web search + fetch
 41      )
 42      print(f"Agent created with memory={agent._memory_instance is not None}")
 43      print(f"  self_reflect={agent.self_reflect}")
 44      print(f"  web_search={agent.web_search}")
 45  
 46  
 47  def example_with_config():
 48      """Example 2: Using config objects (more control)"""
 49      print("\n=== Example 2: Using Config Objects ===")
 50      
 51      agent = Agent(
 52          instructions="You are a research assistant",
 53          memory=MemoryConfig(
 54              backend="file",
 55              user_id="researcher_001",
 56              auto_memory=True,
 57          ),
 58          reflection=ReflectionConfig(
 59              min_iterations=1,
 60              max_iterations=5,
 61              llm="gpt-4o-mini",
 62          ),
 63          web=WebConfig(
 64              search=True,
 65              fetch=False,  # Only search, no full page fetch
 66              max_results=3,
 67          ),
 68      )
 69      print(f"Agent created with user_id={agent.user_id}")
 70      print(f"  {agent.max_reflect}")
 71      print(f"  web_search={agent.web_search}, web_fetch={agent.web_fetch}")
 72  
 73  
 74  def example_guardrails():
 75      """Example 3: Guardrails with callable or config"""
 76      print("\n=== Example 3: Guardrails ===")
 77      
 78      # Option A: Direct callable
 79      def my_validator(output):
 80          """Simple validator that checks response length."""
 81          is_valid = len(output.raw) < 1000
 82          return (is_valid, output if is_valid else "Response too long")
 83      
 84      agent_a = Agent(
 85          instructions="Be concise",
 86          guardrails=my_validator,  # Direct callable
 87      )
 88      print(f"Agent A: guardrail is callable = {callable(agent_a.guardrail)}")
 89      
 90      # Option B: Using GuardrailConfig
 91      agent_b = Agent(
 92          instructions="Be helpful and safe",
 93          guardrails=GuardrailConfig(
 94              llm_validator="Ensure the response is helpful, accurate, and safe",
 95              max_retries=3,
 96          ),
 97      )
 98      print(f"Agent B: guardrail = {agent_b.guardrail}")
 99      print(f"  max_retries = {agent_b.max_guardrail_retries}")
100  
101  
102  def example_planning():
103      """Example 4: Planning mode"""
104      print("\n=== Example 4: Planning Mode ===")
105      
106      agent = Agent(
107          instructions="You are a project planner",
108          planning=PlanningConfig(
109              reasoning=True,
110              read_only=True,  # Plan mode - only read operations
111          ),
112      )
113      print(f"Agent created with planning={agent.planning}")
114      print(f"  plan_mode={agent.plan_mode}")
115      print(f"  planning_reasoning={agent.planning_reasoning}")
116  
117  
118  def example_backward_compatible():
119      """Example 5: Using new consolidated params"""
120      print("\n=== Example 5: Consolidated Params ===")
121      
122      # New consolidated params
123      agent = Agent(
124          instructions="Test agent",
125          reflection=True,
126          web=WebConfig(search=True, fetch=False),
127      )
128      print(f"Consolidated params work: self_reflect={agent.self_reflect}")
129      print(f"  web_search={agent.web_search}, web_fetch={agent.web_fetch}")
130  
131  
132  def example_real_chat():
133      """Example 6: Real chat with new API"""
134      print("\n=== Example 6: Real Chat ===")
135      
136      agent = Agent(
137          instructions="You are a helpful math tutor. Be concise.",
138          reflection=False,
139          web=False,
140      )
141      
142      response = agent.start("What is the square root of 144?")
143      print(f"Response: {response}")
144  
145  
146  def example_string_presets():
147      """Example 7: String presets (NEW - user-friendly shortcuts)"""
148      print("\n=== Example 7: String Presets ===")
149      
150      # Output presets: minimal, normal, verbose, debug, silent
151      agent = Agent(
152          instructions="You are a verbose assistant",
153          output="verbose",      # String preset for output
154          execution="fast",      # String preset for execution
155          web=["tavily", {"fetch": False}],          # String preset with override for web provider
156      )
157      print(f"Output preset 'verbose': verbose={agent.verbose}, metrics={agent.metrics}")
158      print(f"Execution preset 'fast': max_iter={agent.max_iter}")
159      print(f"Web preset 'tavily': web_search={agent.web_search}")
160  
161  
162  def example_array_overrides():
163      """Example 8: Array with overrides (NEW - preset + customization)"""
164      print("\n=== Example 8: Array Overrides ===")
165      
166      # Array format: [preset, {overrides}]
167      agent = Agent(
168          instructions="You are a streaming assistant",
169          output=["verbose", {"stream": True}],      # Verbose preset + enable streaming
170          execution=["fast", {"max_iter": 15}],      # Fast preset + custom max_iter
171      )
172      print(f"Output array override: verbose={agent.verbose}, stream={agent.stream}")
173      print(f"Execution array override: max_iter={agent.max_iter}")
174  
175  
176  def example_url_parsing():
177      """Example 9: URL parsing for memory (NEW - connection strings)"""
178      print("\n=== Example 9: URL Parsing ===")
179      
180      # Memory supports URL connection strings
181      # Supported: postgresql://, redis://, sqlite:///, mongodb://
182      agent = Agent(
183          instructions="You are a database-backed assistant",
184          memory="postgresql://postgres:password@localhost:5432/praisonai",
185      )
186      print("Memory URL parsed: memory enabled")
187      
188      # Also works with presets
189      agent2 = Agent(
190          instructions="You are a redis-backed assistant",
191          memory="redis",  # Preset name
192      )
193      print("Memory preset 'redis': configured")
194  
195  
196  def example_knowledge_sources():
197      """Example 10: Knowledge with sources (list and string)"""
198      print("\n=== Example 10: Knowledge Sources ===")
199      
200      # Single path string
201      agent1 = Agent(
202          instructions="You are a document assistant",
203          knowledge="docs/",  # Single path
204      )
205      print(f"Knowledge single path: knowledge={agent1.knowledge}")
206      
207      # List of sources
208      agent2 = Agent(
209          instructions="You are a multi-source assistant",
210          knowledge=["docs/", "data.pdf", "https://example.com/api"],
211      )
212      print(f"Knowledge list: knowledge={agent2.knowledge}")
213      
214      # With config for advanced settings
215      agent3 = Agent(
216          instructions="You are an advanced RAG assistant",
217          knowledge=KnowledgeConfig(
218              sources=["docs/"],
219              retrieval_k=10,
220              rerank=True,
221          ),
222      )
223      print("Knowledge config: configured with rerank")
224  
225  
226  if __name__ == "__main__":
227      print("=" * 60)
228      print("PraisonAI Agent-Centric API Examples")
229      print("=" * 60)
230      
231      example_simple_enable()
232      example_with_config()
233      example_guardrails()
234      example_planning()
235      example_backward_compatible()
236      example_real_chat()
237      example_string_presets()
238      example_array_overrides()
239      example_url_parsing()
240      example_knowledge_sources()
241      
242      print("\n" + "=" * 60)
243      print("All examples completed!")
244      print("=" * 60)