# null Source: https://docs.pilottai.com/core/base-agent # Base Agent The `BaseAgent` class is the foundation for all PilottAI agents. It provides the core functionality for job execution, tool management, and memory integration. ## Overview The `BaseAgent` is responsible for: * Executing jobs using LLMs * Managing specialized tools * Maintaining job context * Tracking execution status * Storing and retrieving memory ## Class Definition ```python theme={null} class BaseAgent: def __init__( self, config: AgentConfig, llm_config: Optional[LLMConfig] = None, tools: Optional[List[Tool]] = None, memory_enabled: bool = True ): # Core configuration self.config = config self.id = str(uuid.uuid4()) # State management self.status = AgentStatus.IDLE self.current_job: Optional[Job] = None self._job_lock = asyncio.Lock() # Components self.tools = {tool.name: tool for tool in (tools or [])} self.memory = Memory() if memory_enabled else None self.llm = LLMHandler(llm_config) if llm_config else None # Setup logging self.logger = self._setup_logger() ``` ## Configuration The `BaseAgent` is configured using the `AgentConfig` class: ```python theme={null} from pilottai.core import AgentConfig, AgentType config = AgentConfig( title="researcher", # Agent's title/type agent_type=AgentType.WORKER, # Agent classification goal="Find accurate information", # Main objective description="Research assistant", # Brief description backstory=None, # Optional background story tools=["web_search", "text_analyzer"], # Available tools required_capabilities=[], # Required capabilities max_iterations=20, # Maximum execution iterations memory_enabled=True, # Enable memory verbose=False # Verbose logging ) ``` ## Key Methods ### Job Execution ```python theme={null} async def execute_job(self, job: Union[Dict, Job]) -> Optional[JobResult]: """Execute a job with proper handling and monitoring.""" # Implementation details... ``` The job execution process involves: 1. Planning execution steps using LLM 2. Executing each step with proper error handling 3. Monitoring execution status and timeout 4. Recording execution in memory 5. Returning structured results ### Job Suitability Evaluation ```python theme={null} async def evaluate_job_suitability(self, job: Dict) -> float: """Evaluate how suitable this agent is for a job""" # Implementation details... ``` This method determines how well an agent can handle a specific job by: * Checking required capabilities * Matching job type with agent specializations * Considering current agent load * Analyzing job complexity ### Lifecycle Management ```python theme={null} async def start(self): """Start the agent""" # Implementation details... async def stop(self): """Stop the agent""" # Implementation details... ``` These methods handle the agent's lifecycle, including: * Initializing components * Setting up connections * Updating status * Cleaning up resources ## Job Execution Pipeline The `BaseAgent` follows a structured approach to job execution: 1. **Job Formatting**: Prepare job with context 2. **Execution Planning**: Generate a plan using LLM 3. **Step Execution**: Execute each step in the plan 4. **Tool Invocation**: Use tools as required 5. **Result Summarization**: Summarize and format results ```mermaid theme={null} sequenceDiagram participant A as Agent participant L as LLM participant T as Tools participant M as Memory A->>A: Format job A->>L: Request execution plan L-->>A: Return plan A->>M: Store plan loop For each step A->>T: Execute tool if needed T-->>A: Return tool result A->>L: Process step result L-->>A: Return processed result A->>M: Store step result end A->>L: Request summary L-->>A: Return summary A->>M: Store final result ``` ## System Prompts The `BaseAgent` uses system prompts to guide LLM behavior. The base system prompt follows this template: ``` You are an AI agent with: Title: {title} Goal: {goal} Backstory: {backstory or 'No specific backstory.'} Make decisions and take actions based on your title and goal. ``` ## Error Handling The `BaseAgent` implements robust error handling: * Job timeouts * LLM errors * Tool execution failures * Context validation ## Memory Integration Agents maintain their own memory instance for: * Job history tracking * Context preservation * Knowledge storage * Pattern recognition ```python theme={null} # Store job in memory await self.memory.store_job_start( job_id=job.id, description=job.description, agent_id=self.id ) # Store result in memory await self.memory.store_job_result( job_id=job.id, result=result, success=True, execution_time=execution_time, agent_id=self.id ) ``` ## Extending BaseAgent To create a specialized agent, extend the `BaseAgent` class: ```python theme={null} from pilottai.core import BaseAgent, AgentConfig class ResearchAgent(BaseAgent): def __init__(self, config: AgentConfig, **kwargs): super().__init__(config, **kwargs) self.specializations = ["research", "information_gathering"] async def evaluate_job_suitability(self, job: Dict) -> float: # Custom suitability logic base_score = await super().evaluate_job_suitability(job) if job.get("type") == "research": return min(1.0, base_score + 0.3) return base_score ``` ## Examples ### Creating a Basic Agent ```python theme={null} from pilottai.core import BaseAgent, AgentConfig, LLMConfig # Configure LLM llm_config = LLMConfig( model_name="gpt-4", provider="openai", api_key="your-api-key" ) # Configure agent config = AgentConfig( title="assistant", goal="Help with various jobs", description="General assistant agent" ) # Create agent agent = BaseAgent(config=config, llm_config=llm_config) ``` ### Executing a Job ```python theme={null} # Create job job = { "description": "Summarize the following text", "context": { "text": "PilottAI is a Python framework for building autonomous multi-agent systems..." } } # Execute job result = await agent.execute_job(job) print(f"Job result: {result.output}") ``` ## API Reference For a complete reference of all `BaseAgent` methods and attributes, see the [Agent API](../../api/agent.md) documentation. # null Source: https://docs.pilottai.com/core/examples/customer-service # PilottAI Agent Examples This directory contains example implementations showing how to create and use different types of agents with the PilottAI framework. ## Overview The examples demonstrate how to: * Set up multiple specialized agents * Create and configure tools * Execute jobs across different agents * Use the PilottAI Serve orchestrator ## Installation 1. Install PilottAI: ```bash theme={null} pip install pilott ``` 2. Set up your OpenAI API key: ```bash theme={null} export OPENAI_API_KEY="your-api-key" ``` ## Included Examples ### Agents * **Customer Service Agent**: Handles customer inquiries and support requests * **Document Processor**: Processes and analyzes documents * **Research Analyst**: Conducts research and provides insights ### Tools * **Email Sender**: Tool for sending emails to customers * **Document Processor**: Tool for document analysis and processing ## Usage Run the examples: ```python theme={null} from examples.agents import main # Run the example import asyncio asyncio.run(main()) ``` ## Example Output ``` Job: Handle refund request Result: Customer refund request processed successfully Job: Analyze quarterly report Result: Document analysis complete: 3 key insights found Job: Research competitor pricing Result: Market research analysis completed ``` ## Creating Your Own Agents 1. Configure the agent: ```python theme={null} agent_config = AgentConfig( title="your_agent_title", goal="your_agent_goal", tools=["tool1", "tool2"] ) ``` 2. Add to PilottAI: ```python theme={null} agent = await pilott.add_agent( title=agent_config.title, goal=agent_config.goal, tools=agent_config.tools, llm_config=llm_config ) ``` ## Best Practices 1. **Agent Design** * Give each agent a clear, focused title * Provide specific goals and tools * Use appropriate LLM configurations 2. **Tool Management** * Create reusable tools * Define clear tool interfaces * Handle tool errors gracefully 3. **Job Execution** * Group related jobs * Set appropriate priorities * Monitor execution results ## Configuration Options ### LLM Configuration ```python theme={null} llm_config = LLMConfig( model_name="gpt-4", # or other models provider="openai", # or other providers temperature=0.7 # adjust based on needs ) ``` ### Tool Configuration ```python theme={null} tool = Tool( name="tool_name", description="tool_description", function=your_function, parameters={ "param1": "type1", "param2": "type2" } ) ``` ## Error Handling The examples include basic error handling. In production, you should: * Add comprehensive error handling * Implement retries for failed jobs * Log errors appropriately * Handle API rate limits ## Contributing Feel free to: * Add new agent examples * Create additional tools * Improve documentation * Report issues * Submit pull requests ## Code Ready to use code [customer\_service.py](../../pilott/agents/customer_service.py) # null Source: https://docs.pilottai.com/core/examples/document-processor # Document Processing Agent Example This example demonstrates how to set up and use a document processing agent with the PilottAI framework. ## Features * Text extraction from various document formats * Content analysis capabilities * Document summarization * Configurable processing tools ## Setup 1. Install required dependencies: ```bash theme={null} pip install pilott ``` 2. Configure your environment: ```bash theme={null} export OPENAI_API_KEY="your-api-key" ``` ## Tools Included ### Text Extractor Extracts text content from documents: ```python theme={null} text_extractor = Tool( name="text_extractor", parameters={ "file_path": "str", "format": "str" } ) ``` ### Content Analyzer Analyzes document content: ```python theme={null} content_analyzer = Tool( name="content_analyzer", parameters={ "text": "str", "analysis_type": "str" } ) ``` ### Summarizer Generates document summaries: ```python theme={null} summarizer = Tool( name="summarizer", parameters={ "text": "str", "max_length": "int" } ) ``` ## Quick Start ```python theme={null} from pilottai import Serve from pilottai.core import AgentConfig, LLMConfig # Initialize and run async def main(): pilott = Serve(name="DocumentProcessor") # Add document processing agent doc_processor = await pilott.add_agent( title="document_processor", goal="Process documents efficiently", tools=["text_extractor", "content_analyzer", "summarizer"] ) # Process a document job = { "type": "document_analysis", "document": { "path": "document.pdf", "type": "pdf" } } result = await pilott.execute([job]) ``` ## Supported Document Types * PDF files * Text documents * Word documents (docx) * HTML files ## Common Use Cases 1. **Document Analysis** ```python theme={null} job = { "type": "document_analysis", "description": "Analyze quarterly report" } ``` 2. **Text Extraction** ```python theme={null} job = { "type": "text_extraction", "document": {"path": "file.pdf"} } ``` 3. **Content Summarization** ```python theme={null} job = { "type": "summarization", "document": {"path": "article.txt"} } ``` ## Configuration Options Customize agent behavior: ```python theme={null} config = AgentConfig( title="document_processor", goal="Process documents efficiently", max_concurrent_jobs=5, job_timeout=300 ) ``` ## Best Practices 1. **Document Handling** * Validate document formats before processing * Handle large documents in chunks * Implement proper error handling 2. **Performance** * Configure appropriate timeouts * Use concurrent processing when possible * Monitor memory usage for large documents 3. **Error Handling** * Validate input documents * Handle unsupported formats gracefully * Implement retry logic for failed operations ## Troubleshooting Common issues and solutions: 1. **File Access Errors** * Ensure proper file permissions * Verify file paths are correct * Check file format compatibility 2. **Processing Timeouts** * Adjust job\_timeout in configuration * Process large documents in smaller chunks * Monitor system resources ## Example Output ```python theme={null} # Example result { 'success': True, 'output': { 'summary': 'Document summary...', 'analysis': 'Content analysis...', 'metadata': { 'pages': 5, 'format': 'pdf', 'processing_time': '2.3s' } } } ``` ## Code Ready to use code [document\_processor.py](../../pilott/agents/document_processing.py) # null Source: https://docs.pilottai.com/core/examples/email-agent # Email Agent Example Simple example showing how to set up an email handling agent with PilottAI framework. ## Setup ```bash theme={null} pip install pilott ``` ## Example Usage ```python theme={null} from pilottai import Serve from pilottai.core import AgentConfig, LLMConfig # Initialize pilott = Serve(name="EmailAgent") # Create agent email_agent = await pilott.add_agent( title="email_manager", goal="Handle email communications", tools=["email_sender", "email_analyzer"] ) # Send email job = { "type": "send_email", "template": "welcome", "recipient": "user@example.com" } result = await pilott.execute([job]) ``` ## Tools * email\_sender: Send emails with attachments * email\_analyzer: Analyze email content and intent * template\_manager: Handle email templates ## Features * Email sending and analysis * Template management * Sentiment analysis * Priority handling ## Code Ready to use code [email\_agent.py](../../pilott/agents/email_agent.py) # null Source: https://docs.pilottai.com/core/examples/learning-agent # Learning Agent Example Simple example showing how to set up a learning agent with PilottAI framework. ## Setup ```bash theme={null} pip install pilott ``` ## Example Usage ```python theme={null} from pilottai import Serve from pilottai.core import AgentConfig, LLMConfig # Initialize pilott = Serve(name="LearningAgent") # Create agent learning_agent = await pilott.add_agent( title="learner", goal="Acquire and organize knowledge", tools=["knowledge_base", "pattern_recognizer"] ) # Learn new topic job = { "type": "learn_topic", "content": "Machine Learning Basics", "store_results": True } result = await pilott.execute([job]) ``` ## Tools * knowledge\_base: Store and retrieve knowledge * pattern\_recognizer: Identify patterns in data ## Features * Knowledge acquisition * Pattern recognition * Data organization * Learning tracking ## Code Ready to use code [learning\_agent.py](../../pilott/agents/learning_agent.py) # null Source: https://docs.pilottai.com/core/examples/marketing-expert # Marketing Expert Agent Example Simple example showing how to set up a marketing expert agent with PilottAI framework. ## Setup ```bash theme={null} pip install pilott ``` ## Example Usage ```python theme={null} from pilottai import Serve from pilottai.core import AgentConfig, LLMConfig # Initialize pilott = Serve(name="MarketingExpert") # Create agent marketing_agent = await pilott.add_agent( title="marketing_expert", goal="Create and optimize marketing campaigns", tools=["content_creator", "campaign_analyzer"] ) # Create content job = { "type": "create_content", "content_type": "social_post", "target_audience": "tech professionals" } result = await pilott.execute([job]) ``` ## Tools * content\_creator: Create marketing content * campaign\_analyzer: Analyze campaign performance ## Features * Content creation * Campaign analysis * Performance tracking * Audience targeting ## Code Ready to use code [marketing\_expert.py](../../pilott/agents/marketing_expert.py) # null Source: https://docs.pilottai.com/core/examples/research-analyst # Research Analyst Agent Example Simple example showing how to set up a research analyst agent with PilottAI framework. ## Setup ```bash theme={null} pip install pilott ``` ## Example Usage ```python theme={null} from pilottai import Serve from pilottai.core import AgentConfig, LLMConfig # Initialize pilott = Serve(name="ResearchAnalyst") # Create agent research_agent = await pilott.add_agent( title="research_analyst", goal="Conduct thorough research and provide insights", tools=["data_analyzer", "research_synthesizer"] ) # Analyze data job = { "type": "analyze_data", "data_source": "market_survey_2024", "analysis_type": "trend_analysis" } result = await pilott.execute([job]) ``` ## Tools * data\_analyzer: Analyze research data * research\_synthesizer: Synthesize research findings ## Features * Data analysis * Research synthesis * Trend identification * Insight generation ## Code Ready to use code [research\_analyst.py](../../pilott/agents/research_analyst.py) # null Source: https://docs.pilottai.com/core/examples/sales-rep # Sales Representative Agent Example Simple example showing how to set up a sales representative agent with PilottAI framework. ## Setup ```bash theme={null} pip install pilottai ``` ## Example Usage ```python theme={null} from pilottai import Serve from pilottai.core import AgentConfig, LLMConfig # Initialize pilott = Serve(name="SalesRepresentative") # Create agent sales_agent = await pilott.add_agent( title="sales_representative", goal="Manage leads and close sales effectively", tools=["lead_manager", "proposal_generator"] ) # Manage lead job = { "type": "manage_lead", "lead_id": "LEAD123", "action": "qualify", "details": { "company": "TechCorp", "budget": "100k" } } result = await pilott.execute([job]) ``` ## Tools * lead\_manager: Manage sales leads * proposal\_generator: Generate sales proposals ## Features * Lead qualification * Proposal generation * Sales process automation * Client relationship management ## Code Ready to use code [sales\_rep.py](../../pilott/agents/sales_rep.py) # null Source: https://docs.pilottai.com/core/examples/social-media-agent # Social Media Agent Example Simple example showing how to set up a social media management agent with PilottAI framework. ## Setup ```bash theme={null} pip install pilott ``` ## Example Usage ```python theme={null} from pilottai import Serve from pilottai.core import AgentConfig, LLMConfig # Initialize pilott = Serve(name="SocialMediaManager") # Create agent social_agent = await pilott.add_agent( title="social_media_manager", goal="Manage social media presence and engagement", tools=["content_scheduler", "engagement_analyzer"] ) # Schedule content job = { "type": "schedule_content", "platform": "twitter", "content": "Exciting announcement coming!", "schedule_time": "2024-03-15T10:00:00Z" } result = await pilott.execute([job]) ``` ## Tools * content\_scheduler: Schedule social media content * engagement\_analyzer: Analyze post engagement ## Features * Content scheduling * Engagement analysis * Performance tracking * Multi-platform support ## Code Ready to use code [social\_media\_agent.py](../../pilott/agents/social_media_agent.py) # null Source: https://docs.pilottai.com/core/examples/web-search # Web Search Agent Example Simple example showing how to set up a web search agent with PilottAI framework. ## Setup ```bash theme={null} pip install pilott ``` ## Example Usage ```python theme={null} from pilottai import Serve from pilottai.core import AgentConfig, LLMConfig # Initialize pilott = Serve(name="WebSearchAgent") # Create agent search_agent = await pilott.add_agent( title="web_searcher", goal="Execute and analyze web searches effectively", tools=["search_executor", "result_analyzer"] ) # Execute search job = { "type": "web_search", "query": "latest AI developments 2024", "search_type": "news", "filters": { "date_range": "last_month" } } result = await pilott.execute([job]) ``` ## Tools * search\_executor: Execute web searches * result\_analyzer: Analyze search results ## Features * Web searching * Result analysis * Filter management * Source credibility checking ## Code Ready to use code [web\_search.py](../../pilott/agents/web_search.py) # null Source: https://docs.pilottai.com/core/memory/overview # Memory System The PilottAI Memory System provides robust storage and retrieval capabilities for agents, enabling context preservation, knowledge persistence, and job history tracking. ## Overview The Memory System is designed to: * Maintain job execution history * Store and retrieve semantic information * Track agent interactions * Provide context for future jobs * Support search and similarity matching ## Memory Architecture PilottAI implements a layered memory architecture: ```mermaid theme={null} graph TD A[Agent Memory] --> B[Core Memory System] B --> C[Job Memory] B --> D[Semantic Memory] B --> E[Interaction Memory] B --> F[Pattern Memory] C --> G[Job History] C --> H[Job Context] C --> I[Job Results] D --> J[Knowledge Store] D --> K[Semantic Search] D --> L[Similarity Matching] E --> M[Agent Interactions] E --> N[Conversation History] F --> O[Pattern Recognition] F --> P[Temporal Patterns] ``` ## Basic Memory Usage ### Initializing Memory ```python theme={null} from pilottai.core import Memory # Create a memory instance memory = Memory() ``` ### Storing Job Information ```python theme={null} # Store job start await memory.store_job_start( job_id="job-123", description="Analyze sales data", agent_id="agent-456", context={"data_source": "sales_2023.csv"} ) # Store job result await memory.store_job_result( job_id="job-123", result={"insights": ["Sales increased by 20%", "Q4 was strongest"]}, success=True, execution_time=2.5, agent_id="agent-456" ) # Store job context await memory.store_job_context( job_id="job-123", context={"additional_data": "competitor_analysis.csv"}, context_type="data_source", agent_id="agent-456" ) ``` ### Retrieving Job History ```python theme={null} # Get complete history for a job job_history = await memory.get_job_history( job_id="job-123", include_context=True ) # Get job result job_result = await memory.get_job_result( job_id="job-123" ) ``` ### Storing Semantic Information ```python theme={null} # Store semantic information with tags await memory.store_semantic( text="Sales increased by 20% in Q4 2023 compared to Q4 2022", metadata={"topic": "sales", "period": "Q4 2023"}, tags={"sales", "analysis", "quarterly"} ) ``` ### Searching Memory ```python theme={null} # Search by text and tags results = await memory.search( query="sales increase", tags={"analysis"}, limit=5 ) # Get recent entries with tags recent_entries = await memory.get_recent( tags={"sales"}, limit=10 ) ``` ## Enhanced Memory PilottAI also provides an `EnhancedMemory` class for advanced memory capabilities: ```python theme={null} from pilottai.memory import EnhancedMemory # Create enhanced memory enhanced_memory = EnhancedMemory() # Store semantic information with priority and TTL await enhanced_memory.store_semantic( text="Important sales insight: Q4 showed unexpected growth", metadata={"importance": "high"}, tags={"sales", "priority"}, priority=2, ttl=86400 # 24 hours ) # Search with priority filter results = await enhanced_memory.semantic_search( query="sales growth", tags={"sales"}, min_priority=2, limit=5 ) ``` ## Job Memory Job memory stores the complete history of job execution: ```python theme={null} # Build comprehensive job context job_context = await memory.build_job_context( job_description="Analyze Q1 2024 sales data", agent_id="agent-456" ) # Find similar jobs similar_jobs = await memory.get_similar_jobs( job_description="Analyze sales performance", limit=3 ) ``` ## Memory Maintenance PilottAI automatically manages memory with cleanup functionality: ```python theme={null} # Cleanup old entries await memory.cleanup_old_entries(max_age_days=30) # Clear all memory await memory.clear() ``` ## Memory Architecture Details ### Memory Entry Each memory entry contains: ```python theme={null} class MemoryEntry(BaseModel): text: str entry_type: str # 'job', 'context', 'result', etc. metadata: Dict[str, Any] timestamp: datetime tags: Set[str] priority: int job_id: Optional[str] agent_id: Optional[str] ``` ### Memory Indices The memory system maintains several indices for efficient retrieval: * **Job Index**: Maps job IDs to related entries * **Agent Index**: Maps agent IDs to related entries * **Tag Index**: Maps tags to related entries * **Timestamp Index**: Organizes entries chronologically * **Priority Index**: Groups entries by priority level ### Memory Persistence By default, memory is stored in-memory, but PilottAI supports persistence options: ```python theme={null} # Create memory with persistence from pilottai.core import Memory memory = Memory( persistence_enabled=True, persistence_path="./memory_store", persistence_interval=300 # Save every 5 minutes ) ``` ## Advanced Memory Features ### Pattern Recognition The enhanced memory system can identify patterns in stored information: ```python theme={null} # Store pattern await enhanced_memory.store_pattern( name="sales_cycle", data={ "pattern_type": "temporal", "period": "quarterly", "peak_months": ["March", "June", "September", "December"] }, ttl=2592000 # 30 days ) # Retrieve pattern sales_pattern = await enhanced_memory.get_pattern("sales_cycle") ``` ### Agent Interaction History Track interactions between agents: ```python theme={null} # Store interaction await enhanced_memory.store_interaction( agent_id="agent-123", interaction_type="delegation", data={ "target_agent": "agent-456", "job_id": "job-789", "result": "success" } ) ``` ### Job Context Building Build rich context for new jobs based on history: ```python theme={null} # Build job context with similar jobs and agent history context = await memory.build_job_context( job_description="Analyze customer churn for Q1 2024", agent_id="agent-123" ) ``` ## Best Practices 1. **Use Tags Consistently**: Develop a consistent tagging schema for easy retrieval 2. **Prioritize Important Information**: Set higher priority for critical data 3. **Cleanup Regularly**: Implement regular cleanup for optimal performance 4. **Use TTL for Temporal Data**: Set time-to-live for information that expires 5. **Store Structured Metadata**: Use structured metadata for better searchability ## Example Workflow Here's a complete example of memory usage in a multi-agent system: ```python theme={null} import asyncio from pilottai import Serve from pilottai.core import AgentConfig, LLMConfig from pilottai.memory import EnhancedMemory async def memory_example(): # Initialize PilottAI pilott = Serve(name="MemoryDemo") # Configure LLM llm_config = LLMConfig( model_name="gpt-4", provider="openai", api_key="your-api-key" ) # Start the system await pilott.start() try: # Add agents researcher = await pilott.add_agent( title="researcher", goal="Gather information", llm_config=llm_config ) analyst = await pilott.add_agent( title="analyst", goal="Analyze information", llm_config=llm_config ) # Store information in researcher's memory await researcher.memory.store_semantic( text="US GDP grew by 2.5% in 2023", metadata={"topic": "economics", "region": "US", "year": 2023}, tags={"economics", "gdp", "us"} ) # Execute research job research_result = await pilott.execute([{ "type": "research", "description": "Research US economic growth", "agent": "researcher" }]) # Store analysis in analyst's memory await analyst.memory.store_semantic( text="Analysis shows strong correlation between GDP growth and employment rates", metadata={"analysis_type": "correlation", "variables": ["gdp", "employment"]}, tags={"analysis", "economics", "correlation"} ) # Execute analysis job using context from previous research analysis_result = await pilott.execute([{ "type": "analyze", "description": "Analyze impact of GDP growth on employment", "context": {"research_result": research_result[0].output}, "agent": "analyst" }]) # Retrieve similar analyses from memory similar_analyses = await analyst.memory.search( query="GDP employment correlation", tags={"analysis"}, limit=3 ) print(f"Analysis result: {analysis_result[0].output}") print(f"Similar analyses: {similar_analyses}") finally: # Always stop the system properly await pilott.stop() if __name__ == "__main__": asyncio.run(memory_example()) ``` ## API Reference For a complete reference of all Memory System methods and attributes, see the [Memory API](../../api/memory.md) documentation. # null Source: https://docs.pilottai.com/getting-started/concepts # Basic Concepts This guide introduces the core concepts of the PilottAI framework. ## Framework Architecture PilottAI is designed around a modular, hierarchical architecture: ```mermaid theme={null} classDiagram class Serve { +agents: Dict[str, BaseAgent] +jobs: Dict[str, Job] +memory: Memory +add_agent() +create_job() +execute() +start() +stop() } class BaseAgent { +id: str +config: AgentConfig +status: AgentStatus +tools: Dict[str, Tool] +memory: Memory +llm: LLMHandler +execute_job() +evaluate_job_suitability() +start() +stop() } class Memory { +store_job_start() +store_job_result() +store_job_context() +get_job_history() +get_similar_jobs() +search() } class JobRouter { +route_job() +_calculate_agent_scores() +_find_best_agent() +_analyze_agent_loads() } Serve *-- BaseAgent : manages Serve *-- Memory : uses BaseAgent *-- Memory : has Serve *-- JobRouter : routes jobs ``` ### Core Components 1. **Serve**: The main orchestrator that manages agents, routes jobs, and coordinates execution. 2. **Agents**: Autonomous entities that perform specific jobs using LLMs and tools. 3. **Jobs**: Units of work that are routed to appropriate agents for execution. 4. **Memory**: Storage system for context, job history, and knowledge. 5. **Tools**: Integrations and capabilities that agents can use to accomplish jobs. 6. **Orchestration**: Systems for scaling, load balancing, and fault tolerance. ## Agents Agents are the primary actors in the PilottAI framework. Each agent: * Has a specific title and goal * Can use tools to interact with external systems * Utilizes LLMs for decision-making and job execution * Maintains its own memory and context ### Agent Types PilottAI supports different agent types: * **Orchestrator**: Manages and delegates jobs to worker agents * **Worker**: Executes specific jobs using specialized capabilities * **Hybrid**: Combines orchestration and execution capabilities ### Agent Configuration Agents are configured using the `AgentConfig` class: ```python theme={null} from pilottai.core import AgentConfig, AgentType config = AgentConfig( title="document_processor", # Agent's title/type agent_type=AgentType.WORKER, # Agent classification goal="Process documents efficiently", # Main objective description="Document processing worker", # Brief description backstory=None, # Optional background story knowledge_sources=[], # Available knowledge sources tools=["text_extractor"], # Available tools required_capabilities=[], # Required capabilities max_iterations=20, # Maximum execution iterations max_rpm=None, # Rate limits memory_enabled=True, # Enable memory verbose=False # Verbose logging ) ``` ## Jobs Jobs represent units of work that agents perform. Each job: * Has a description and context * May be assigned to a specific agent or automatically routed * Has a priority level * Tracks execution status and results ### Job Lifecycle ```mermaid theme={null} stateDiagram-v2 [*] --> PENDING: Created PENDING --> IN_PROGRESS: Started IN_PROGRESS --> COMPLETED: Success IN_PROGRESS --> FAILED: Error/Timeout COMPLETED --> [*] FAILED --> PENDING: Retry FAILED --> [*]: Max retries ``` ### Job Creation ```python theme={null} from pilottai.core import Job, JobPriority job = Job( description="Extract key information from document", priority=JobPriority.HIGH, context={"file_path": "document.pdf"} ) ``` ## Memory System PilottAI includes a sophisticated memory system that: * Stores job execution history * Maintains agent context * Enables semantic search and retrieval * Supports knowledge persistence ### Memory Components 1. **Job Memory**: Records job execution details 2. **Semantic Memory**: Stores knowledge and context 3. **Enhanced Memory**: Advanced memory with pattern recognition ### Using Memory ```python theme={null} # Store information in semantic memory await agent.memory.store_semantic( text="Important information about topic X", metadata={"topic": "X", "importance": "high"}, tags={"research", "topic_x"} ) # Search memory results = await agent.memory.search( query="topic X", tags={"research"} ) ``` ## LLM Integration PilottAI uses Large Language Models for agent intelligence. Key concepts: 1. **LLM Configuration**: Settings for model, provider, and parameters 2. **LLM Handler**: Manages LLM interactions with proper error handling 3. **Function Calling**: Structured LLM output for tool use ### LLM Configuration ```python theme={null} from pilottai.core import LLMConfig llm_config = LLMConfig( model_name="gpt-4", provider="openai", api_key="your-api-key", temperature=0.7, max_tokens=2000 ) ``` ## Tools Tools extend agent capabilities by providing: * External system integrations * Specialized functionality * Job-specific utilities ### Tool Creation ```python theme={null} from pilottai.tools import Tool email_tool = Tool( name="email_sender", description="Send emails to recipients", function=lambda **kwargs: send_email(**kwargs), parameters={ "to": "str", "subject": "str", "body": "str" } ) ``` ## Orchestration PilottAI includes advanced orchestration features: ### Dynamic Scaling Automatically adjusts the number of agents based on system load: ```python theme={null} await pilott.enable_dynamic_scaling( config={ "min_agents": 2, "max_agents": 10, "scale_up_threshold": 0.8, "scale_down_threshold": 0.3 } ) ``` ### Load Balancing Distributes jobs across agents to optimize performance: ```python theme={null} await pilott.enable_load_balancing( config={ "check_interval": 30, "overload_threshold": 0.7 } ) ``` ### Fault Tolerance Handles agent failures and ensures system reliability: ```python theme={null} await pilott.enable_fault_tolerance( config={ "health_check_interval": 30, "max_recovery_attempts": 3 } ) ``` ## Next Steps Now that you understand the basic concepts of PilottAI, you can: * Explore specialized [Agents](../core/agents/base-agent.md) * Learn about [Memory Systems](../core/memory/overview.md) * Dive into [Orchestration](../orchestration/overview.md) features * See [Examples](../examples/basic.md) of PilottAI in action # null Source: https://docs.pilottai.com/getting-started/installation # Installation This guide covers the installation process for the PilottAI framework. ## Requirements PilottAI requires the following: * Python 3.10 or higher * Supported operating systems: Linux, macOS, Windows * Optional: An API key for your LLM provider (OpenAI, Anthropic, etc.) ## Installation Methods ### Using pip (Recommended) The simplest way to install PilottAI is using pip: ```bash theme={null} pip install pilott ``` ### Installing with Optional Dependencies PilottAI offers optional dependency sets for various use cases: ```bash theme={null} # Install with document processing dependencies pip install "pilott[docs]" # Install with development dependencies pip install "pilott[dev]" # Install with all dependencies pip install "pilott[all]" ``` ### Installing from Source To install the latest development version: ```bash theme={null} git clone https://github.com/pygig/pilottai.git cd pilottai pip install -e . ``` ## Verifying Installation Verify your installation with: ```bash theme={null} python -c "import pilott; print(pilott.__version__)" ``` This should display the current version of PilottAI. ## Installing LLM Provider SDKs PilottAI supports multiple LLM providers. Depending on which provider you choose, you may need to install additional packages: ```bash theme={null} # For OpenAI pip install openai # For Anthropic pip install anthropic # For Google VertexAI pip install google-cloud-aiplatform ``` ## Configuration After installation, you'll need to configure your LLM provider API keys. There are several ways to do this: ### Environment Variables Set your API key as an environment variable: ```bash theme={null} # For OpenAI export OPENAI_API_KEY="your-api-key" # For Anthropic export ANTHROPIC_API_KEY="your-api-key" ``` ### Configuration File You can also create a configuration file `~/.pilottai/config.yaml` with your API keys: ```yaml theme={null} llm: provider: openai api_key: your-api-key model_name: gpt-4 ``` ### Runtime Configuration Alternatively, you can provide your API key at runtime: ```python theme={null} from pilottai import Serve from pilottai.core import LLMConfig llm_config = LLMConfig( provider="openai", api_key="your-api-key", model_name="gpt-4" ) pilott = Serve(llm_config=llm_config) ``` ## Troubleshooting ### Common Issues **ImportError: No module named 'pilott'** * Make sure you've installed the package correctly * Check that your Python environment matches the one where you installed the package **ModuleNotFoundError: No module named 'openai'** * Install the required provider SDK: `pip install openai` **API key error** * Ensure your API key is correctly set and valid * Check that you're using the right environment variable name ### Getting Help If you encounter any issues during installation: * Check our [FAQ](../faq.md) page * Look for similar issues on our [GitHub repository](https://github.com/pygig/pilottai/issues) * Join our [Discord community](https://discord.gg/pilottai) for real-time support // TODO: Correct link ## Next Steps Now that you have PilottAI installed, continue to the [Quick Start](quickstart.md) guide to create your first multi-agent system. # null Source: https://docs.pilottai.com/getting-started/quickstart # Quick Start Guide This guide will help you create a simple multi-agent system with PilottAI. ## Creating Your First Agent Let's create a simple document processing agent that can extract and analyze text from documents. ```python theme={null} import asyncio from pilottai import Serve from pilottai.core import AgentConfig, LLMConfig, AgentType async def main(): # Configure LLM llm_config = LLMConfig( model_name="gpt-4", provider="openai", api_key="your-api-key" # Replace with your actual API key ) # Initialize PilottAI pilott = Serve(name="QuickStart") # Start the system await pilott.start() try: # Add a document processing agent doc_agent = await pilott.add_agent( title="document_processor", goal="Process and analyze documents efficiently", tools=["text_extractor"], llm_config=llm_config ) # Create a simple job result = await pilott.execute([{ "type": "process_text", "description": "Summarize the following text", "content": "PilottAI is a Python framework for building autonomous multi-agent systems with advanced orchestration capabilities. It provides enterprise-ready features for building scalable AI applications." }]) # Print the result print(f"Job result: {result[0].output}") finally: # Always stop the system properly await pilott.stop() if __name__ == "__main__": asyncio.run(main()) ``` ## Building a Multi-Agent System Now, let's create a more complex system with multiple agents that collaborate: ```python theme={null} import asyncio from pilottai import Serve from pilottai.core import AgentConfig, LLMConfig, AgentType from pilottai.tools import Tool async def main(): # Configure LLM llm_config = LLMConfig( model_name="gpt-4", provider="openai", api_key="your-api-key" # Replace with your actual API key ) # Initialize PilottAI pilott = Serve(name="MultiAgentSystem") # Start the system await pilott.start() try: # Create custom tools search_tool = Tool( name="web_search", description="Search the web for information", function=lambda **kwargs: f"Search results for: {kwargs.get('query')}", parameters={"query": "str"} ) analyze_tool = Tool( name="text_analyzer", description="Analyze text content", function=lambda **kwargs: f"Analysis of: {kwargs.get('content')}", parameters={"content": "str", "type": "str"} ) # Add a research agent research_agent = await pilott.add_agent( title="researcher", goal="Find and collect relevant information", tools=["web_search"], llm_config=llm_config ) # Add an analyst agent analyst_agent = await pilott.add_agent( title="analyst", goal="Analyze and synthesize information", tools=["text_analyzer"], llm_config=llm_config ) # Execute a research job research_result = await pilott.execute([{ "type": "research", "description": "Research information about AI orchestration", "agent": "researcher" }]) # Execute an analysis job using the research result analysis_result = await pilott.execute([{ "type": "analyze", "description": "Analyze the research findings", "content": research_result[0].output, "agent": "analyst" }]) # Print the final result print(f"Research: {research_result[0].output}") print(f"Analysis: {analysis_result[0].output}") finally: # Always stop the system properly await pilott.stop() if __name__ == "__main__": asyncio.run(main()) ``` ## Handling Document Processing PilottAI excels at document processing jobs. Here's how to set up a document processing pipeline: ```python theme={null} import asyncio from pilottai import Serve from pilottai.core import AgentConfig, LLMConfig, AgentType from pilottai.tools import Tool async def process_document(): # Initialize PilottAI pilott = Serve(name="DocumentProcessor") # Configure LLM llm_config = LLMConfig( model_name="gpt-4", provider="openai", api_key="your-api-key" # Replace with your actual API key ) # Start the system await pilott.start() try: # Add a document processing agent doc_processor = await pilott.add_agent( title="document_processor", goal="Process and analyze documents efficiently", tools=["text_extractor", "content_analyzer"], llm_config=llm_config ) # Process a document result = await pilott.execute([{ "type": "process_document", "description": "Extract key information from the document", "file_path": "document.pdf", "extract_metadata": True }]) # Print the result print(f"Document processing result: {result[0].output}") finally: # Always stop the system properly await pilott.stop() if __name__ == "__main__": asyncio.run(process_document()) ``` ## Using Orchestration Features PilottAI provides advanced orchestration capabilities for scaling your agent system: ```python theme={null} import asyncio from pilottai import Serve from pilottai.core import AgentConfig, LLMConfig from pilottai.orchestration import DynamicScaling, LoadBalancer async def main(): # Initialize PilottAI with orchestration features pilott = Serve(name="OrchestrationDemo") # Configure LLM llm_config = LLMConfig( model_name="gpt-4", provider="openai", api_key="your-api-key" # Replace with your actual API key ) # Configure dynamic scaling scaling_config = { "min_agents": 2, "max_agents": 5, "scale_up_threshold": 0.8, "scale_down_threshold": 0.3 } # Configure load balancer lb_config = { "check_interval": 30, "overload_threshold": 0.7 } # Start the system await pilott.start() try: # Enable dynamic scaling await pilott.enable_dynamic_scaling(config=scaling_config) # Enable load balancing await pilott.enable_load_balancing(config=lb_config) # Add base worker agents for i in range(2): await pilott.add_agent( title=f"worker_{i}", goal="Process jobs efficiently", llm_config=llm_config ) # Generate a series of jobs to test scaling jobs = [] for i in range(10): jobs.append({ "type": "process", "description": f"Process job {i}", "data": f"Sample data {i}" }) # Execute jobs in parallel results = await pilott.execute(jobs) # Print system metrics after execution metrics = pilott.get_metrics() print(f"System metrics: {metrics}") finally: # Always stop the system properly await pilott.stop() if __name__ == "__main__": asyncio.run(main()) ``` ## Next Steps Now that you've created your first PilottAI agents, continue to the [Basic Concepts](concepts.mdx) guide to learn more about: * Agent architecture and capabilities * Job routing and execution * Memory systems * Orchestration features * Tool integration For more advanced examples, check the [Examples](../examples/basic.md) section. # null Source: https://docs.pilottai.com/index # PilottAI Framework Build scalable multi-agent systems with powerful orchestration, LLM integration, and job processing capabilities.
## What is PilottAI? PilottAI is a Python framework for building autonomous multi-agent systems with advanced orchestration capabilities. It provides enterprise-ready features for building scalable AI applications powered by large language models.Ticket and support management
Document analysis and extraction
Email handling and templates
Knowledge acquisition and patterns
Campaign and content creation
Data analysis and synthesis
Lead management and proposals
Content scheduling and engagement
Search operations and analysis