Agents are the core building blocks of AgenticAI Framework. They are autonomous AI entities that can reason, plan, use tools, and execute complex tasks.
Enterprise-Ready
Part of a 400+ module framework with 237 enterprise modules, 7 memory managers, 7 state managers, and 35+ built-in tools.
importlogginglogger=logging.getLogger(__name__)fromagenticaiframeworkimportAgent,AgentConfig# Create a simple agentconfig=AgentConfig(name="assistant",role="Helpful AI Assistant",goal="Help users with their questions accurately and helpfully")agent=Agent(config=config)# Execute a taskresult=agent.execute("What is the capital of France?")logger.info(result.output)# Output: The capital of France is Paris.
importlogginglogger=logging.getLogger(__name__)fromagenticaiframeworkimportAgent,AgentConfig,MemoryManager# Initialize memorymemory=MemoryManager()# Create agent with memoryagent=Agent(config=AgentConfig(name="remembering_assistant",role="Personal Assistant",goal="Help users while remembering context"),memory=memory)# Agent remembers across interactionsresult1=agent.execute("My name is Alice and I like Python")result2=agent.execute("What's my name and what do I like?")logger.info(result2.output)# Output: Your name is Alice and you like Python.
fromagenticaiframeworkimportAgent,AgentConfigfromagenticaiframework.toolsimportSearchTool,CalculatorTool# Create agent with toolsagent=Agent(config=AgentConfig(name="research_assistant",role="Research Analyst",goal="Research topics and provide accurate analysis",tools=[SearchTool(),CalculatorTool()]))# Agent uses tools to complete tasksresult=agent.execute("What's the population of Tokyo and what's 15% of it?")
fromagenticaiframeworkimportAgentConfigconfig=AgentConfig(# Identityname="research_agent",role="Senior Research Analyst",goal="Conduct thorough research and provide accurate insights",backstory="An expert analyst with 10 years of experience in data research",# LLM Settingsmodel="gpt-4o",temperature=0.7,max_tokens=4096,# Execution Settingsmax_iterations=10,max_execution_time=300,# seconds# Toolstools=["search","calculator","python_repl"],# Behaviorverbose=True,allow_delegation=True,cache_responses=True,# Memorymemory_enabled=True,memory_limit=100,# entries# Guardrailsvalidate_inputs=True,sanitize_outputs=True)
# Good: Specific role and clear goalconfig=AgentConfig(name="code_reviewer",role="Senior Software Engineer specializing in Python code review",goal="Review code for bugs, security issues, and best practices. ""Provide actionable feedback with examples.",backstory="A senior engineer with expertise in Python, security, ""and software architecture. Known for thorough but constructive reviews.")# Better: Include constraints and preferencesconfig=AgentConfig(name="code_reviewer",role="Senior Software Engineer specializing in Python code review",goal="Review code for bugs, security issues, and best practices",constraints=["Focus on actionable feedback","Prioritize security issues","Include code examples in suggestions"],preferences={"style_guide":"PEP 8","max_line_length":88,"prefer_type_hints":True})
fromagenticaiframeworkimportAgentConfig,LLMConfig# Basic model configconfig=AgentConfig(name="assistant",model="gpt-4o-mini")# Advanced model configconfig=AgentConfig(name="assistant",llm=LLMConfig(provider="openai",model="gpt-4o",temperature=0.7,max_tokens=4096,top_p=0.95,frequency_penalty=0.0,presence_penalty=0.0,stop_sequences=["###"],timeout=60))# Using different providersconfig=AgentConfig(name="claude_assistant",llm=LLMConfig(provider="anthropic",model="claude-3-5-sonnet-20241022",max_tokens=4096))
fromagenticaiframework.toolsimportTool,tool# Method 1: Using decorator@tooldefget_weather(location:str)->str:"""Get current weather for a location. Args: location: City name or coordinates Returns: Current weather conditions """# Implementationreturnf"Weather in {location}: Sunny, 72Β°F"# Method 2: Using Tool classclassStockPriceTool(Tool):name="stock_price"description="Get current stock price for a ticker symbol"def_run(self,ticker:str)->dict:# Implementationreturn{"ticker":ticker,"price":150.25}asyncdef_arun(self,ticker:str)->dict:# Async implementationreturnawaitself._fetch_price(ticker)# Add custom tools to agentagent=Agent(config=AgentConfig(name="financial_analyst",tools=[get_weather,StockPriceTool()]))
fromagenticaiframeworkimportAgentConfig,ReasoningStrategy# Chain of Thoughtconfig=AgentConfig(name="analyst",reasoning=ReasoningStrategy.CHAIN_OF_THOUGHT)# ReAct (Reason + Act)config=AgentConfig(name="researcher",reasoning=ReasoningStrategy.REACT)# Plan and Executeconfig=AgentConfig(name="planner",reasoning=ReasoningStrategy.PLAN_AND_EXECUTE)# Reflection (Self-critique)config=AgentConfig(name="writer",reasoning=ReasoningStrategy.REFLECTION)
importlogginglogger=logging.getLogger(__name__)fromagenticaiframeworkimportAgent,AgentConfigclassCustomAgent(Agent):defon_start(self):"""Called when agent starts executing."""logger.info("Agent starting...")self.start_time=time.time()defon_complete(self,result):"""Called when task completes."""duration=time.time()-self.start_timelogger.info(f"Completed in {duration:.2f}s")defon_error(self,error):"""Called when an error occurs."""logger.info(f"Error: {error}")self.log_error(error)defon_tool_use(self,tool_name,input_data):"""Called before tool execution."""logger.info(f"Using tool: {tool_name}")defon_tool_result(self,tool_name,result):"""Called after tool execution."""logger.info(f"Tool result: {result}")agent=CustomAgent(config=config)
# Use agent as context managerasyncwithAgent(config=config)asagent:result=awaitagent.execute("Task 1")result=awaitagent.execute("Task 2")# Agent automatically cleaned up
fromagenticaiframeworkimportAgent,AgentConfig,Messenger# Create agentsresearcher=Agent(config=AgentConfig(name="researcher"))writer=Agent(config=AgentConfig(name="writer"))# Set up messengermessenger=Messenger()researcher.set_messenger(messenger)writer.set_messenger(messenger)# Agent sends messageresearcher.send_message(to="writer",content={"research_data":research_results})# Other agent receivesmessages=writer.receive_messages()
fromagenticaiframeworkimportAgent,AgentConfig# Leader agent that can delegateleader=Agent(config=AgentConfig(name="leader",role="Team Lead",allow_delegation=True,delegate_to=["researcher","writer"]))# Worker agentsresearcher=Agent(config=AgentConfig(name="researcher"))writer=Agent(config=AgentConfig(name="writer"))# Leader delegates sub-tasks automaticallyresult=leader.execute("Research AI trends and write a summary",available_agents=[researcher,writer])
fromagenticaiframeworkimportAgentConfig,FallbackConfigconfig=AgentConfig(name="robust_agent",fallback=FallbackConfig(# Fallback model if primary failsfallback_model="gpt-3.5-turbo",# Fallback tools if primary tool failstool_fallbacks={"web_search":"cached_search","api_call":"mock_api"},# Default response on complete failuredefault_response="I'm unable to complete this task at the moment."))
fromagenticaiframeworkimportAgent,AgentConfigfromagenticaiframework.tracingimportTracingConfigconfig=AgentConfig(name="traced_agent",tracing=TracingConfig(enabled=True,exporter="jaeger",endpoint="http://localhost:14268/api/traces",sample_rate=1.0))agent=Agent(config=config)# All executions are automatically traced
# Good: Specific and focusedconfig=AgentConfig(name="python_expert",role="Python Developer specializing in data processing",goal="Write efficient, clean Python code for data pipelines")# Avoid: Vague and broadconfig=AgentConfig(name="helper",role="Assistant",goal="Help with stuff")
# Only include tools the agent needsconfig=AgentConfig(name="researcher",tools=[SearchTool(),WikipediaTool()]# Research-focused tools)# Don't overload with unnecessary tools