### Running ProactiveAgent Examples Source: https://github.com/leomariga/proactiveagent/blob/main/docs/examples.md Instructions for cloning the repository, installing dependencies, setting the API key, and running a minimal chat example. Essential for setting up and testing the agent. ```bash git clone https://github.com/leomariga/ProactiveAgent.git cd ProactiveAgent uv sync export OPENAI_API_KEY='your-api-key-here' uv run python examples/minimal_chat.py ``` -------------------------------- ### Install uv dependency manager Source: https://github.com/leomariga/proactiveagent/blob/main/CONTRIBUTING.md Install uv using pip. This is a prerequisite for setting up the development environment. ```bash pip install uv ``` -------------------------------- ### Basic ProactiveAgent Usage Source: https://github.com/leomariga/proactiveagent/blob/main/docs/index.md Set up a basic proactive agent with OpenAI provider, a system prompt, and a decision configuration for chat pace. This example demonstrates how to start the agent, send messages, and receive responses. ```python import time from proactiveagent import ProactiveAgent, OpenAIProvider # Create a proactive agent agent = ProactiveAgent( provider = OpenAIProvider(model="gpt-5-nano",), system_prompt = "You are a casual bored teenager. Answer like you're texting a friend", decision_config = { 'wake_up_pattern': "Use the pace of a normal text chat", } ) # Add response callback agent.add_callback(lambda response: print(f"AI: {response}")) agent.start() # Chat with your proactive agent while True: message = input("You: ").strip() if message.lower() == 'quit': break agent.send_message(message) time.sleep(1) agent.stop() ``` -------------------------------- ### Install project dependencies with uv Source: https://github.com/leomariga/proactiveagent/blob/main/CONTRIBUTING.md Install all project dependencies, including development tools, using uv sync --dev. This command automatically creates a virtual environment and installs packages from uv.lock. ```bash uv sync --dev ``` -------------------------------- ### Install ProactiveAgent Source: https://github.com/leomariga/proactiveagent/blob/main/docs/index.md Install the ProactiveAgent library using pip. ```bash pip install proactiveagent ``` -------------------------------- ### List installed dependencies with uv Source: https://github.com/leomariga/proactiveagent/blob/main/CONTRIBUTING.md View all installed dependencies, including development tools, by running uv pip list. ```bash uv pip list ``` -------------------------------- ### ProactiveAgent Initialization and Usage Source: https://context7.com/leomariga/proactiveagent/llms.txt Demonstrates how to initialize the ProactiveAgent with a provider and decision configuration, register callbacks, and use it as a context manager for automatic start and stop. It shows the main loop for user interaction. ```APIDOC ## ProactiveAgent The main orchestrator class that starts a background thread running an asyncio event loop. It connects a provider, a decision engine, and a scheduler; manages conversation history; and dispatches callbacks when it responds, makes a decision, or recalculates sleep time. ```python import time from proactiveagent import ProactiveAgent, OpenAIProvider provider = OpenAIProvider(model="gpt-4o-mini") agent = ProactiveAgent( provider=provider, system_prompt="You are a friendly support agent. Proactively check in when the user goes quiet.", decision_config={ "min_response_interval": 30, # never respond sooner than 30 s "max_response_interval": 300, # always respond within 5 min "engagement_threshold": 0.5, # combined score must exceed this "context_relevance_weight": 0.4, "time_weight": 0.3, "probability_weight": 0.3, "wake_up_pattern": "Check every 1-2 minutes when the user is active", "min_sleep_time": 20, "max_sleep_time": 180, }, log_level="INFO", ) # Register callbacks agent.add_callback(lambda r: print(f"🤖 {r}")) agent.add_decision_callback(lambda ok, reason: print(f"{ '✅' if ok else '⏳'} {reason}")) agent.add_sleep_time_callback(lambda t, reason: print(f"⏰ sleep {t}s – {reason}")) # Use as a context manager for automatic start/stop with agent: while True: msg = input("You: ").strip() if msg.lower() == "quit": break agent.send_message(msg) time.sleep(1) ``` ``` -------------------------------- ### Minimal Chat Implementation Source: https://github.com/leomariga/proactiveagent/blob/main/docs/examples.md Demonstrates core agent initialization, message handling, and default AI-based decision making. This is a good starting point for understanding basic agent functionality. ```python from proactive_agent import ProactiveAgent agent = ProactiveAgent() agent.run() ``` -------------------------------- ### Minimal ProactiveAgent Example Source: https://github.com/leomariga/proactiveagent/blob/main/docs/getting-started.md Create a basic conversational agent that responds autonomously based on a system prompt and decision configuration. ```python import time from proactiveagent import ProactiveAgent, OpenAIProvider agent = ProactiveAgent( provider=OpenAIProvider(model="gpt-5-nano"), system_prompt="ou are a casual bored teenager. Answer like you're texting a friend.", decision_config={ 'wake_up_pattern': "Use the pace of a normal text chat", }, ) agent.add_callback(lambda response: print(f"🤖 AI: {response}")) agent.start() print("Chat started! Type your messages:") while True: message = input("You: ").strip() if message.lower() == 'quit': break agent.send_message(message) time.sleep(3) agent.stop() print("Chat ended!") ``` -------------------------------- ### Run examples or tests with uv Source: https://github.com/leomariga/proactiveagent/blob/main/CONTRIBUTING.md Execute Python scripts or tests using uv run. Alternatively, activate the virtual environment and run scripts directly. ```bash # Run any script using uv uv run python examples/minimal_chat.py # Or activate the virtual environment source .venv/bin/activate # On Windows: .venv\Scripts\activate python examples/minimal_chat.py ``` -------------------------------- ### Static Sleep Calculator Example Source: https://github.com/leomariga/proactiveagent/blob/main/docs/devto_proactiveagent.md Demonstrates using StaticSleepCalculator for fixed 2-minute intervals between agent wake cycles. Callbacks are included for AI responses and sleep time calculations. ```python """ Minimal example using StaticSleepCalculator """ import time from proactiveagent import ProactiveAgent, OpenAIProvider from proactiveagent.sleep_time_calculators import StaticSleepCalculator def on_ai_response(response: str): print(f"🤖 AI: {response}") def on_sleep_time_calculated(sleep_time: int, reasoning: str): print(f"⏰ Sleep: {sleep_time}s - {reasoning}") def main(): provider = OpenAIProvider(model="gpt-5-nano") # Use static sleep calculator with fixed 2-minute intervals sleep_calculator = StaticSleepCalculator(120, "Fixed 2-minute intervals") agent = ProactiveAgent( provider=provider, system_prompt="You are a helpful AI assistant.", decision_config={ 'min_sleep_time': 60, 'max_sleep_time': 300, } ) # Override the default sleep calculator agent.scheduler.sleep_calculator = sleep_calculator agent.add_callback(on_ai_response) agent.add_sleep_time_callback(on_sleep_time_calculated) agent.start() print("=== Static Sleep Calculator ===") print("Always sleeps for 2 minutes between checks.") print("Type 'quit' to exit.\n") while True: message = input("You: ").strip() if message.lower() == 'quit': break agent.send_message(message) time.sleep(1) agent.stop() if __name__ == "__main__": main() ``` -------------------------------- ### Project Dependency Management with uv Source: https://github.com/leomariga/proactiveagent/blob/main/README.md Install project dependencies, including development tools, using the uv package manager. This command synchronizes the development environment. ```bash pip install uv uv sync --dev # Install dependencies including dev tools ``` -------------------------------- ### Custom Provider Implementation Source: https://github.com/leomariga/proactiveagent/blob/main/docs/api-reference.md Example of how to create a custom LLM provider by extending the BaseProvider class and implementing the generate_response method. ```APIDOC ## Custom Provider Implementation ### Description Extend the `BaseProvider` class and implement the `generate_response` method to create a custom LLM provider. ### Method Signature ```python async def generate_response(self, messages: list[dict], system_prompt: str = None) -> str: ``` ### Parameters #### Arguments - **messages** (list[dict]) - Required - List of message dicts with 'role' and 'content'. - **system_prompt** (str) - Optional - System prompt to guide the LLM. ### Returns - **str** - The generated response string from the LLM. ### Example Usage ```python from proactiveagent.providers import BaseProvider class CustomProvider(BaseProvider): def __init__(self, model: str, api_key: str = None): self.model = model self.api_key = api_key async def generate_response( self, messages: list[dict], system_prompt: str = None ) -> str: """ Generate a response from your LLM. Args: messages: List of message dicts with 'role' and 'content' system_prompt: Optional system prompt Returns: Generated response string """ # Your implementation here response = await your_llm_api_call(messages, system_prompt) return response # Use your custom provider agent = ProactiveAgent( provider=CustomProvider(model="your-model"), system_prompt="You are a helpful assistant." ) ``` ``` -------------------------------- ### Test ProactiveAgent Installation from TestPyPI Source: https://github.com/leomariga/proactiveagent/blob/main/BUILD.md Install the ProactiveAgent package from TestPyPI to verify its functionality before publishing to the main PyPI. This requires pip and an internet connection. ```bash pip install --index-url https://test.pypi.org/simple/ proactiveagent ``` ```python python -c "import proactiveagent; print('Installation successful!')" ``` -------------------------------- ### Basic ProactiveAgent Usage Source: https://github.com/leomariga/proactiveagent/blob/main/README.md Demonstrates the basic usage of ProactiveAgent. It shows how to initialize an agent with an OpenAI provider, system prompt, and decision configuration. The agent is then started, and messages are sent to it in a loop until 'quit' is entered. A callback function is used to print the AI's responses. ```python import time from proactiveagent import ProactiveAgent, OpenAIProvider # Create a proactive agent: Define in natural language the frequency of response agent = ProactiveAgent( provider = OpenAIProvider(model="gpt-5-nano",), system_prompt = "You are a casual bored teenager. Answer like you're texting a friend", decision_config = { 'wake_up_pattern': "Use the pace of a normal text chat", } ) # Add response callback and start agent thread def on_response(response: str): print(f"🤖 AI: {response}") agent.add_callback(on_response) agent.start() while True: message = input("You: ").strip() if message.lower() == 'quit': break agent.send_message(message) time.sleep(3) agent.stop() ``` -------------------------------- ### Custom TimeOfDaySleepCalculator Example Source: https://context7.com/leomariga/proactiveagent/llms.txt Extends SleepTimeCalculator to implement custom sleep logic based on the time of day and user engagement. This example checks more frequently during business hours. Ensure 'min_sleep_time' and 'max_sleep_time' are configured. ```python import time as _time from proactiveagent import ProactiveAgent, OpenAIProvider from proactiveagent.sleep_time_calculators import SleepTimeCalculator class TimeOfDaySleepCalculator(SleepTimeCalculator): """Checks more frequently during business hours.""" async def calculate_sleep_time(self, config: dict, context: dict): hour = _time.localtime().tm_hour min_s = config.get("min_sleep_time", 30) max_s = config.get("max_sleep_time", 600) engagement = context.get("user_engagement", "low") if 9 <= hour < 18: base = 30 if engagement == "high" else 60 reason = f"Business hours ({hour}:xx), engagement={engagement}" else: base = 300 reason = f"Off hours ({hour}:xx) – checking less often" sleep_time = max(min_s, min(base, max_s)) return sleep_time, reason import time agent = ProactiveAgent( provider=OpenAIProvider(model="gpt-4o-mini"), decision_config={"min_sleep_time": 20, "max_sleep_time": 300}, ) agent.scheduler.sleep_calculator = TimeOfDaySleepCalculator() agent.add_callback(lambda r: print(f"AI: {r}")) agent.add_sleep_time_callback(lambda t, r: print(f"⏰ {t}s – {r}")) agent.start() agent.send_message("Hello!") time.sleep(20) agent.stop() ``` -------------------------------- ### PatternBasedSleepCalculator Example Source: https://context7.com/leomariga/proactiveagent/llms.txt Configures the agent to use PatternBasedSleepCalculator, mapping keywords in 'wake_up_pattern' to specific sleep durations. When multiple keywords match, the shortest sleep time is used. Ensure 'wake_up_pattern' and 'min_sleep_time'/'max_sleep_time' are set in decision_config. ```python import time from proactiveagent import ProactiveAgent, OpenAIProvider from proactiveagent.sleep_time_calculators import PatternBasedSleepCalculator agent = ProactiveAgent( provider=OpenAIProvider(model="gpt-4o-mini"), decision_config={ "wake_up_pattern": "urgent support queue – check frequently", "min_sleep_time": 10, "max_sleep_time": 600, }, ) agent.scheduler.sleep_calculator = PatternBasedSleepCalculator(pattern_mappings={ "urgent": 15, "frequent": 30, "active": 60, "normal": 180, "slow": 300, "default": 120, }) agent.add_callback(lambda r: print(f"AI: {r}")) agent.add_sleep_time_callback(lambda t, r: print(f"⏰ {t}s – {r}")) agent.start() agent.send_message("New ticket just opened.") time.sleep(30) agent.stop() ``` -------------------------------- ### agent.start() / agent.stop() / agent.is_active() Source: https://context7.com/leomariga/proactiveagent/llms.txt Methods to control the agent's lifecycle. `start()` launches the agent's background thread and event loop, `stop()` gracefully shuts it down, and `is_active()` checks its current running state. ```APIDOC ## agent.start() / agent.stop() `start()` launches the agent's background thread and asyncio event loop; `stop()` signals the scheduler to exit and joins the thread with a 5-second timeout. `is_active()` returns the current running state. ```python from proactiveagent import ProactiveAgent, OpenAIProvider agent = ProactiveAgent(provider=OpenAIProvider(model="gpt-4o-mini")) agent.add_callback(lambda r: print(f"AI: {r}")) agent.start() print("Running:", agent.is_active()) # True agent.send_message("Hello!") time.sleep(10) agent.stop() print("Running:", agent.is_active()) # False ``` ``` -------------------------------- ### Start, Stop, and Check Agent Status Source: https://context7.com/leomariga/proactiveagent/llms.txt Illustrates how to manually start and stop the ProactiveAgent's background thread and event loop. The `is_active()` method can be used to check the current running state of the agent. ```python from proactiveagent import ProactiveAgent, OpenAIProvider agent = ProactiveAgent(provider=OpenAIProvider(model="gpt-4o-mini")) agent.add_callback(lambda r: print(f"AI: {r}")) agent.start() print("Running:", agent.is_active()) # True agent.send_message("Hello!") time.sleep(10) agent.stop() print("Running:", agent.is_active()) # False ``` -------------------------------- ### Implement Custom LLM Provider with Anthropic Source: https://context7.com/leomariga/proactiveagent/llms.txt Extend BaseProvider to connect ProactiveAgent to the Anthropic LLM API. Requires installation of the anthropic SDK. ```python import asyncio from proactiveagent.providers import BaseProvider from proactiveagent import ProactiveAgent import anthropic # example third-party SDK class AnthropicProvider(BaseProvider): def __init__(self, model: str = "claude-3-5-haiku-20241022"): super().__init__(model) self.client = anthropic.Anthropic() async def generate_response(self, messages, system_prompt=None, **kwargs) -> str: def _call(): result = self.client.messages.create( model=self.model, max_tokens=1024, system=system_prompt or "You are a helpful assistant.", messages=messages, ) return result.content[0].text loop = asyncio.get_event_loop() return await loop.run_in_executor(None, _call) import time provider = AnthropicProvider() agent = ProactiveAgent( provider=provider, system_prompt="You are a proactive assistant powered by Claude.", decision_config={"wake_up_pattern": "Check every 2 minutes"}, ) agent.add_callback(lambda r: print(f"AI: {r}")) agent.start() agent.send_message("Hi there!") time.sleep(20) agent.stop() ``` -------------------------------- ### Create a Proactive WhatsApp Chatbot Source: https://github.com/leomariga/proactiveagent/blob/main/docs/devto_proactiveagent.md Initialize and start a ProactiveAgent configured for a casual WhatsApp chat. It uses OpenAI for responses and includes a callback to print AI messages. The agent will periodically check for opportunities to respond, maintaining a conversational flow. ```python import time from proactiveagent import ProactiveAgent, OpenAIProvider agent = ProactiveAgent( provider=OpenAIProvider(model="gpt-5-nano"), system_prompt="You are a casual young person which are bored and wants to talk in a WhatsApp chat. Use informal language, emojis, abbreviations, and speak like you're texting a friend. Keep responses short just a few words and conversational like real WhatsApp messages.", decision_config={ 'wake_up_pattern': "This is a normal whatsapp conversation, adapt your response frequency to the user's conversation.", }, ) agent.add_callback(lambda response: print(f"🤖 AI: {response}")) agent.start() print("Chat started! Type your messages:") while True: message = input("You: ").strip() if message.lower() == 'quit': break agent.send_message(message) time.sleep(3) agent.stop() print("Chat ended!") ``` -------------------------------- ### FunctionBasedDecisionEngine Example Source: https://context7.com/leomariga/proactiveagent/llms.txt Wraps a Python function to act as a decision engine. The function should accept specific arguments and return a boolean indicating whether to respond and a string with the reasoning. Configure with `min_response_interval` and `max_response_interval`. ```python import time from proactiveagent import ProactiveAgent, OpenAIProvider from proactiveagent.decision_engines import FunctionBasedDecisionEngine def business_hours_decision(messages, last_time, context, config, triggered_by_user): import time as _time hour = _time.localtime().tm_hour elapsed = int(_time.time() - last_time) if triggered_by_user: return True, "Direct response to user" if not (9 <= hour < 18): return False, f"Outside business hours ({hour}:xx)" if elapsed < config.get("min_response_interval", 30): return False, f"Too soon ({elapsed}s)" if elapsed > 120: return True, f"Quiet for {elapsed}s during business hours" return False, "Waiting for better timing" agent = ProactiveAgent( provider=OpenAIProvider(model="gpt-4o-mini"), decision_engine=FunctionBasedDecisionEngine(business_hours_decision), decision_config={"min_response_interval": 30, "max_response_interval": 300}, ) agent.add_callback(lambda r: print(f"AI: {r}")) agent.add_decision_callback(lambda ok, r: print(f"{ '✅' if ok else '⏳'} {r}")) agent.start() agent.send_message("Is anyone available?") time.sleep(20) agent.stop() ``` -------------------------------- ### StaticSleepCalculator Example Source: https://context7.com/leomariga/proactiveagent/llms.txt Provides a fixed sleep interval, ignoring conversation context. This is useful for predictable costs and simple polling. Set the `sleep_seconds` and optionally provide a `reasoning` string. ```python import time from proactiveagent import ProactiveAgent, OpenAIProvider from proactiveagent.sleep_time_calculators import StaticSleepCalculator agent = ProactiveAgent( provider=OpenAIProvider(model="gpt-4o-mini"), decision_config={"min_sleep_time": 10, "max_sleep_time": 600}, ) # Override the default AI-based calculator with a fixed 60-second interval agent.scheduler.sleep_calculator = StaticSleepCalculator( sleep_seconds=60, reasoning="Fixed 60-second polling interval", ) agent.add_callback(lambda r: print(f"AI: {r}")) agent.add_sleep_time_callback(lambda t, r: print(f"⏰ {t}s – {r}")) agent.start() agent.send_message("Run a routine check every minute.") time.sleep(90) agent.stop() ``` -------------------------------- ### Simple Decision Engine (Always Respond) Source: https://github.com/leomariga/proactiveagent/blob/main/docs/examples.md An always-respond implementation useful for testing and debugging agent responses. Ensures the agent always attempts to reply, simplifying initial setup and troubleshooting. ```python from proactive_agent import ProactiveAgent from proactive_agent.decision_engines import SimpleDecisionEngine agent = ProactiveAgent( decision_engine=SimpleDecisionEngine() ) agent.run() ``` -------------------------------- ### Custom Sleep Time Calculator Logic Source: https://github.com/leomariga/proactiveagent/blob/main/README.md Implement custom logic for calculating agent sleep times based on context. This example shows how to adjust sleep duration based on user engagement levels. ```python static_calc = StaticSleepCalculator(sleep_time=120) # Every 2 minutes class SmartCalculator(SleepTimeCalculator): async def calculate_sleep_time(self, config, context): engagement = context.get('user_engagement', 'medium') if engagement == 'high': return 30, "High engagement - checking frequently" elif engagement == 'low': return 300, "Low engagement - checking less often" return 120, "Medium engagement - standard interval" agent.scheduler.set_sleep_time_calculator(SmartCalculator()) ``` -------------------------------- ### Use StaticSleepCalculator for Fixed Intervals Source: https://github.com/leomariga/proactiveagent/blob/main/docs/getting-started.md Configure the agent to use `StaticSleepCalculator` for consistent sleep durations between checks. This example demonstrates overriding the default sleep calculator and setting up callbacks for AI responses and sleep time calculations. ```python import time from proactiveagent import ProactiveAgent, OpenAIProvider from proactiveagent.sleep_time_calculators import StaticSleepCalculator def on_ai_response(response: str): print(f"🤖 AI: {response}") def on_sleep_time_calculated(sleep_time: int, reasoning: str): print(f"⏰ Sleep: {sleep_time}s - {reasoning}") def main(): provider = OpenAIProvider(model="gpt-5-nano") # Use static sleep calculator with fixed 2-minute intervals sleep_calculator = StaticSleepCalculator(120, "Fixed 2-minute intervals") agent = ProactiveAgent( provider=provider, system_prompt="You are a helpful AI assistant.", decision_config={ 'min_sleep_time': 60, 'max_sleep_time': 300, } ) # Override the default sleep calculator agent.scheduler.sleep_calculator = sleep_calculator agent.add_callback(on_ai_response) agent.add_sleep_time_callback(on_sleep_time_calculated) agent.start() print("=== Static Sleep Calculator ===") print("Always sleeps for 2 minutes between checks.") print("Type 'quit' to exit.\n") while True: message = input("You: ").strip() if message.lower() == 'quit': break agent.send_message(message) time.sleep(1) agent.stop() if __name__ == "__main__": main() ``` -------------------------------- ### All Configuration Parameters Reference Source: https://github.com/leomariga/proactiveagent/blob/main/docs/examples.md A comprehensive reference documenting all available configuration parameters with inline explanations and default values. Use this to understand and customize agent behavior. ```python from proactive_agent import ProactiveAgent # Configuration parameters documentation # agent_name: Name of the agent (default: "ProactiveAgent") # max_tokens: Maximum tokens for LLM responses (default: 150) # temperature: LLM response temperature (default: 0.7) # model_name: LLM model to use (default: "gpt-3.5-turbo") # ... and many more agent = ProactiveAgent( agent_name="MyCustomAgent", max_tokens=200, temperature=0.8, model_name="gpt-4" ) agent.run() ``` -------------------------------- ### ProactiveAgent Initialization with All Parameters Source: https://github.com/leomariga/proactiveagent/blob/main/docs/api-reference.md Demonstrates initializing the ProactiveAgent with a comprehensive set of decision configuration parameters. ```APIDOC ## ProactiveAgent Initialization with All Parameters ### Description This example shows how to initialize the `ProactiveAgent` with a full suite of `decision_config` parameters, covering response timing, engagement thresholds, decision weights, and sleep calculation. ### Code Example ```python from proactiveagent import ProactiveAgent from proactiveagent.providers import OpenAIProvider agent = ProactiveAgent( provider=OpenAIProvider(model="gpt-5-nano"), system_prompt="You are a helpful AI assistant.", decision_config={ # Response timing parameters "min_response_interval": 30, # Prevents spam "max_response_interval": 600, # Prevents abandonment # Engagement thresholds "engagement_threshold": 0.5, # Decision threshold (0.0-1.0) "engagement_high_threshold": 10, # Messages/hour for high engagement "engagement_medium_threshold": 3, # Messages/hour for medium engagement # Decision weights (must sum to 1.0) "context_relevance_weight": 0.4, # Weight for context factors "time_weight": 0.3, # Weight for time-based factor "probability_weight": 0.3, # Weight for AI decision # Sleep calculation parameters "wake_up_pattern": "Check every 2-3 minutes when active", "min_sleep_time": 30, # Prevents excessive checking "max_sleep_time": 600, # Prevents long inactivity }, ) ``` ``` -------------------------------- ### Instantiate Various Decision Engines Source: https://github.com/leomariga/proactiveagent/blob/main/proactiveagent/decision_engines/README.md Demonstrates how to instantiate different decision engines, including the default AI-based engine, a simple time-based engine, a threshold-based engine with custom thresholds, and a custom function-based engine. ```python from proactiveagent.decision_engines import ( AIBasedDecisionEngine, SimpleDecisionEngine, ThresholdDecisionEngine, FunctionBasedDecisionEngine ) # Default AI-based engine engine = AIBasedDecisionEngine(provider) # Simple time-based engine engine = SimpleDecisionEngine() # Threshold-based with custom thresholds engine = ThresholdDecisionEngine({ 'urgent': 30, 'high': 120, 'medium': 300, 'normal': 600, 'default': 240 }) # Custom function-based engine def my_decision_logic(messages, last_time, context, config, triggered): # Your custom logic here return should_respond, reason engine = FunctionBasedDecisionEngine(my_decision_logic) ``` -------------------------------- ### Initialize and Run ProactiveAgent Source: https://context7.com/leomariga/proactiveagent/llms.txt Demonstrates the initialization of ProactiveAgent with an OpenAI provider and a detailed decision configuration. It registers callbacks for responses, decisions, and sleep times, then runs the agent within a context manager, allowing user input to drive the conversation. ```python import time from proactiveagent import ProactiveAgent, OpenAIProvider provider = OpenAIProvider(model="gpt-4o-mini") agent = ProactiveAgent( provider=provider, system_prompt="You are a friendly support agent. Proactively check in when the user goes quiet.", decision_config={ "min_response_interval": 30, # never respond sooner than 30 s "max_response_interval": 300, # always respond within 5 min "engagement_threshold": 0.5, # combined score must exceed this "context_relevance_weight": 0.4, "time_weight": 0.3, "probability_weight": 0.3, "wake_up_pattern": "Check every 1-2 minutes when the user is active", "min_sleep_time": 20, "max_sleep_time": 180, }, log_level="INFO", ) # Register callbacks agent.add_callback(lambda r: print(f"🤖 {r}")) agent.add_decision_callback(lambda ok, reason: print(f"{ '✅' if ok else '⏳'} {reason}")) agent.add_sleep_time_callback(lambda t, reason: print(f"⏰ sleep {t}s – {reason}")) # Use as a context manager for automatic start/stop with agent: while True: msg = input("You: ").strip() if msg.lower() == "quit": break agent.send_message(msg) time.sleep(1) ``` -------------------------------- ### Complete ProactiveAgent Build and Publish Workflow Source: https://github.com/leomariga/proactiveagent/blob/main/BUILD.md A consolidated workflow for updating the version, building the package, and publishing to PyPI. Assumes successful testing. ```bash uv version --bump minor uv build uv publish ``` -------------------------------- ### Setting and Getting Conversation Context Source: https://context7.com/leomariga/proactiveagent/llms.txt Store and retrieve arbitrary key-value pairs in the agent's conversation context. This context influences decision-making and response urgency. ```python import time from proactiveagent import ProactiveAgent, OpenAIProvider agent = ProactiveAgent(provider=OpenAIProvider(model="gpt-4o-mini")) agent.add_callback(lambda r: print(f"AI: {r}")) agent.start() # Inject external signals as context agent.set_context("user_mood", "frustrated") agent.set_context("topic_urgency", "high") agent.send_message("My order still hasn't arrived!") mood = agent.get_context("user_mood") # "frustrated" urgency = agent.get_context("topic__urgency") # "high" print(f"Mood: {mood}, Urgency: {urgency}") time.sleep(15) agent.stop() ``` -------------------------------- ### ProactiveAgent Initialization with All Parameters Source: https://github.com/leomariga/proactiveagent/blob/main/docs/api-reference.md Initialize ProactiveAgent with a comprehensive set of decision configuration parameters for fine-grained control over agent behavior, response timing, and engagement levels. ```python agent = ProactiveAgent( provider=OpenAIProvider(model="gpt-5-nano"), system_prompt="You are a helpful AI assistant.", decision_config={ # Response timing parameters "min_response_interval": 30, # Prevents spam "max_response_interval": 600, # Prevents abandonment # Engagement thresholds "engagement_threshold": 0.5, # Decision threshold (0.0-1.0) "engagement_high_threshold": 10, # Messages/hour for high engagement "engagement_medium_threshold": 3, # Messages/hour for medium engagement # Decision weights (must sum to 1.0) "context_relevance_weight": 0.4, # Weight for context factors "time_weight": 0.3, # Weight for time-based factor "probability_weight": 0.3, # Weight for AI decision # Sleep calculation parameters "wake_up_pattern": "Check every 2-3 minutes when active", "min_sleep_time": 30, # Prevents excessive checking "max_sleep_time": 600, # Prevents long inactivity }, ) ``` -------------------------------- ### Setting and Getting Conversation Context Source: https://github.com/leomariga/proactiveagent/blob/main/README.md Manage conversation context by setting specific keys and values, which can then be used to influence agent decisions. Retrieve context values using the get_context method. ```python # Set conversation context agent.set_context('user_mood', 'excited') agent.set_context('topic_urgency', 'high') # Context automatically influences decisions mood = agent.get_context('user_mood') ``` -------------------------------- ### Initialize Sleep Time Calculators Source: https://github.com/leomariga/proactiveagent/blob/main/proactiveagent/sleep_time_calculators/README.md Demonstrates how to instantiate different types of sleep time calculators, including AI-based, static, pattern-based, and function-based options. ```python from proactiveagent.sleep_time_calculators import ( AIBasedSleepCalculator, StaticSleepCalculator, PatternBasedSleepCalculator, FunctionBasedSleepCalculator ) # Default AI-based calculator calc = AIBasedSleepCalculator(provider) # Static calculator - always sleep for 3 minutes calc = StaticSleepCalculator(180, "Fixed 3-minute intervals") # Pattern-based with custom mappings calc = PatternBasedSleepCalculator({ 'urgent': 30, # 30 seconds for urgent patterns 'frequent': 60, # 1 minute for frequent checks 'normal': 180, # 3 minutes for normal patterns 'patient': 300, # 5 minutes for patient patterns 'default': 120 # 2 minutes default }) # Custom function-based calculator def my_sleep_logic(config, context): # Your custom logic here return sleep_seconds, reasoning calc = FunctionBasedSleepCalculator(my_sleep_logic) ``` -------------------------------- ### Standalone OpenAIProvider Usage Source: https://context7.com/leomariga/proactiveagent/llms.txt Demonstrates direct usage of OpenAIProvider's async methods for generating responses, determining proactive response likelihood, and calculating sleep times. ```python import asyncio from proactiveagent import OpenAIProvider provider = OpenAIProvider(model="gpt-4o-mini") # api_key can be passed as kwarg # Standalone usage (the agent calls these internally) messages = [ {"role": "user", "content": "What time is it roughly?"}, ] async def demo(): # Generate a chat response response = await provider.generate_response( messages, system_prompt="You are a helpful assistant.", triggered_by_user_message=True, ) print("Response:", response) # Ask the AI whether it should proactively respond should = await provider.should_respond( messages, elapsed_time=45, context={"user_engagement": "medium"} ) print("Should respond:", should) # Ask the AI how long to sleep sleep_secs, reasoning = await provider.calculate_sleep_time( wake_up_pattern="Check every 2 minutes when the user is active", min_sleep_time=30, max_sleep_time=300, context={"user_engagement": "high"}, ) print(f"Sleep {sleep_secs}s – {reasoning}") asyncio.run(demo()) ``` -------------------------------- ### Build ProactiveAgent Package Source: https://github.com/leomariga/proactiveagent/blob/main/BUILD.md Execute uv build to create distribution files (wheel and source distribution) for the ProactiveAgent library. These files are placed in the dist/ directory. ```bash uv build ``` -------------------------------- ### Custom SentimentDecisionEngine Source: https://context7.com/leomariga/proactiveagent/llms.txt Extends the abstract `DecisionEngine` class for custom logic. Implement `async def should_respond` to access the full conversation state. This example prioritizes responding to negative or urgent user messages. ```python import time from proactiveagent import ProactiveAgent, OpenAIProvider from proactiveagent.decision_engines import DecisionEngine class SentimentDecisionEngine(DecisionEngine): """Responds faster when the user seems negative or urgent.""" NEGATIVE_WORDS = {"problem", "broken", "error", "help", "urgent", "fail"} async def should_respond(self, messages, last_user_message_time, context, config, triggered_by_user_message): elapsed = int(time.time() - last_user_message_time) min_iv = config.get("min_response_interval", 30) if triggered_by_user_message: last_content = (messages[-1].get("content", "") if messages else "").lower() is_negative = any(w in last_content for w in self.NEGATIVE_WORDS) if is_negative: return True, "Negative/urgent sentiment – responding immediately" if elapsed < min_iv: return False, f"Too soon ({elapsed}s < {min_iv}s)" if elapsed > config.get("max_response_interval", 600): return True, "Max interval exceeded" return elapsed > 90, f"Standard timing check ({elapsed}s)" agent = ProactiveAgent( provider=OpenAIProvider(model="gpt-4o-mini"), decision_engine=SentimentDecisionEngine(), decision_config={"min_response_interval": 20, "max_response_interval": 300}, ) agent.add_callback(lambda r: print(f"AI: {r}")) agent.start() agent.send_message("I have a broken error and need urgent help!") time.sleep(10) agent.stop() ``` -------------------------------- ### Access Configuration and Context Source: https://github.com/leomariga/proactiveagent/blob/main/proactiveagent/sleep_time_calculators/README.md Illustrates how sleep time calculators can access configuration parameters and context information to determine sleep duration. ```python wake_up_pattern = config.get('wake_up_pattern', 'default pattern') max_sleep_time = config.get('max_sleep_time', 600) # 10 minutes default user_activity = context.get('user_engagement', 'medium') ``` -------------------------------- ### Implement a Custom Decision Engine Source: https://github.com/leomariga/proactiveagent/blob/main/proactiveagent/decision_engines/README.md Shows how to create a custom decision engine by inheriting from the base `DecisionEngine` class and implementing the `should_respond` asynchronous method. This allows for custom decision logic. ```python from proactiveagent.decision_engines.base import DecisionEngine class MyCustomEngine(DecisionEngine): async def should_respond(self, messages, last_user_message_time, context, config, triggered_by_user_message=False): # Your decision logic here return should_respond, reason ``` -------------------------------- ### Custom Decision Engine Implementation Source: https://github.com/leomariga/proactiveagent/blob/main/README.md Shows how to implement a custom decision engine by subclassing `DecisionEngine`. The `should_respond` method should contain the custom logic for determining if the agent should respond. An agent is then initialized with this custom engine. ```python from proactiveagent import DecisionEngine # Your custom logic class MyDecisionEngine(DecisionEngine): async def should_respond(self, messages, last_time, context, config, triggered_by_user): # Your custom decision logic here return should_respond, "reasoning" agent = ProactiveAgent(provider=provider, decision_engine=MyDecisionEngine()) ``` -------------------------------- ### ProactiveAgent Configuration Options Source: https://github.com/leomariga/proactiveagent/blob/main/docs/devto_proactiveagent.md Illustrates setting various configuration parameters for ProactiveAgent, including response timing, decision-making weights, and sleep calculation settings. ```python agent = ProactiveAgent( provider=provider, system_prompt="You are a helpful AI assistant.", decision_config={ # Response timing parameters "min_response_interval": 30, "max_response_interval": 600, # Decision-making weights and thresholds "engagement_threshold": 0.5, "engagement_high_threshold": 10, "engagement_medium_threshold": 3, "context_relevance_weight": 0.4, "time_weight": 0.3, "probability_weight": 0.3, # Sleep calculation parameters "wake_up_pattern": "Check every 2-3 minutes when active", "min_sleep_time": 30, "max_sleep_time": 600, }, ) ``` -------------------------------- ### Sleep Time Calculator Options Source: https://github.com/leomariga/proactiveagent/blob/main/README.md Illustrates options for controlling agent wake-up times. It shows how to instantiate `AIBasedSleepCalculator` which uses AI to interpret natural language patterns for timing, and `StaticSleepCalculator` for fixed intervals. ```python from proactiveagent import AIBasedSleepCalculator, StaticSleepCalculator # Option 1 - AI interprets natural language patterns (default) ai_calc = AIBasedSleepCalculator(provider) ``` -------------------------------- ### Verify Package Build Source: https://github.com/leomariga/proactiveagent/blob/main/BUILD.md Check the contents of the dist/ directory after building. Optionally, use twine to check the package for common issues. ```bash ls -la dist/ ``` ```bash twine check dist/* ``` -------------------------------- ### Publish ProactiveAgent to Main PyPI Source: https://github.com/leomariga/proactiveagent/blob/main/BUILD.md Use the uv publish command to upload the built distribution files to the main PyPI repository. Ensure the package has been thoroughly tested. ```bash uv publish ``` -------------------------------- ### Registering Real-Time Callbacks Source: https://github.com/leomariga/proactiveagent/blob/main/README.md Set up callbacks to monitor agent behavior, including responses, decisions, and sleep times. These functions are executed when specific agent events occur. ```python def on_response(response: str): print(f"Response: {response}") def on_decision(should_respond: bool, reasoning: str): status = "RESPOND" if should_respond else "WAIT" print(f"Decision: {status} - {reasoning}") def on_sleep_time(sleep_time: int, reasoning: str): print(f"Sleeping {sleep_time}s - {reasoning}") # Register callbacks agent.add_callback(on_response) agent.add_decision_callback(on_decision) agent.add_sleep_time_callback(on_sleep_time) ``` -------------------------------- ### Minimal Callback Implementation Source: https://github.com/leomariga/proactiveagent/blob/main/docs/examples.md Shows a complete callback implementation for monitoring agent behavior, including response, sleep time, and decision callbacks. Essential for debugging and understanding agent state transitions. ```python from proactive_agent import ProactiveAgent def on_response(response): print(f"Agent responded: {response}") def on_sleep(sleep_time): print(f"Agent sleeping for: {sleep_time} seconds") def on_decision(decision): print(f"Agent decided: {decision}") agent = ProactiveAgent( on_response=on_response, on_sleep=on_sleep, on_decision=on_decision ) agent.run() ``` -------------------------------- ### Manage Dependencies with uv Source: https://github.com/leomariga/proactiveagent/blob/main/BUILD.md Commands for checking outdated dependencies, upgrading them, and viewing the dependency tree. Useful for maintaining project health. ```bash uv tree --outdated ``` ```bash uv sync --upgrade ``` ```bash uv tree ``` -------------------------------- ### Configuring ProactiveAgent Source: https://github.com/leomariga/proactiveagent/blob/main/README.md Initialize the ProactiveAgent with various configuration options to control response timing, decision-making weights, and sleep intervals. ```python agent = ProactiveAgent( provider=provider, decision_config={ # Response timing bounds 'min_response_interval': 30, # Minimum seconds between responses 'max_response_interval': 600, # Maximum seconds before forced response 'probability_weight': 0.3, # AI decision weight # Sleep calculation 'wake_up_pattern': "Check around 2-3 minutes when user is active", 'min_sleep_time': 30, # Minimum sleep seconds 'max_sleep_time': 600, # Maximum sleep seconds } ) ``` -------------------------------- ### Access Configuration in Decision Engines Source: https://github.com/leomariga/proactiveagent/blob/main/proactiveagent/decision_engines/README.md Illustrates how decision engines can access configuration values directly from the provided configuration dictionary. This ensures flexibility in how engines are parameterized. ```python min_interval = config.get('min_response_interval', 30) max_interval = config.get('max_response_interval', 3600) threshold = config.get('engagement_threshold', 0.5) ``` -------------------------------- ### Validate ProactiveAgent Package Before Publishing Source: https://github.com/leomariga/proactiveagent/blob/main/BUILD.md Use the 'build' package to check for common issues in the distribution files before publishing to PyPI. This helps catch potential problems early. ```bash python -m build --check ``` -------------------------------- ### Observe Agent's Decision Process with Callbacks Source: https://github.com/leomariga/proactiveagent/blob/main/docs/devto_proactiveagent.md Add callbacks to monitor AI responses, calculated sleep times, and decision-making logic in real-time. This helps in understanding the agent's internal reasoning and behavior during a conversation. ```python import time from proactiveagent import ProactiveAgent, OpenAIProvider def on_response(response: str): """Called when AI sends a response""" print(f"🤖 AI: {response}") def on_sleep(sleep_time: int, reasoning: str): """Called when AI calculates sleep time""" print(f"⏰ Sleep: {sleep_time}s - {reasoning}") def on_decision(should_respond: bool, reasoning: str): """Called when AI makes a decision about whether to respond""" status = "RESPOND" if should_respond else "WAIT" print(f"🧠 {status} - {reasoning}") agent = ProactiveAgent( provider=OpenAIProvider(model="gpt-5-nano"), system_prompt="You are a casual young person which are bored and wants to talk in a WhatsApp chat. Use informal language, emojis, abbreviations, and speak like you're texting a friend. Keep responses short just a few words and conversational like real WhatsApp messages.", decision_config={ 'wake_up_pattern': "This is a normal whatsapp conversation, adapt your response frequency to the user's conversation.", }, ) agent.add_callback(on_response) agent.add_sleep_time_callback(on_sleep) agent.add_decision_callback(on_decision) agent.start() print("Chat started! Type your messages:") while True: message = input("You: ").strip() if message.lower() == 'quit': break agent.send_message(message) time.sleep(3) agent.stop() print("Chat ended!") ``` -------------------------------- ### OpenAIProvider Source: https://github.com/leomariga/proactiveagent/blob/main/docs/api/providers.md The OpenAIProvider class is a concrete implementation of the BaseProvider for OpenAI's LLM APIs. ```APIDOC ## OpenAIProvider ::: proactiveagent.providers.openai_provider.OpenAIProvider options: show_root_heading: true show_source: false heading_level: 3 ``` -------------------------------- ### ProactiveAgent Configuration Reference Source: https://context7.com/leomariga/proactiveagent/llms.txt Demonstrates the comprehensive `decision_config` dictionary for controlling agent behavior, including timing, decision weights, engagement thresholds, and custom parameters. Extra keys are forwarded to custom engines and calculators. ```python from proactiveagent import ProactiveAgent, OpenAIProvider agent = ProactiveAgent( provider=OpenAIProvider(model="gpt-4o-mini"), system_prompt="You are a proactive customer-support agent.", decision_config={ # --- Timing hard limits --- "min_response_interval": 30, # Never respond sooner than 30 s "max_response_interval": 600, # Always respond within 10 min # --- Decision score weights (should sum to 1.0) --- "context_relevance_weight": 0.4, # Questions / urgency / follow-up "time_weight": 0.3, # Elapsed-time factor "probability_weight": 0.3, # AI provider vote # --- Engagement level thresholds --- "engagement_threshold": 0.5, # Minimum combined score to respond "engagement_high_threshold": 10, # ≥10 user msgs/hr → "high" "engagement_medium_threshold": 3, # ≥3 user msgs/hr → "medium" # --- Sleep / wake-cycle bounds --- "wake_up_pattern": "Check every 1-2 min when user is active, every 5 min otherwise", "min_sleep_time": 20, "max_sleep_time": 300, # --- Custom keys for your own engines/calculators --- "priority_mode": True, "custom_check_interval": 45, }, ) agent.add_callback(lambda r: print(f"AI: {r}")) agent.start() import time agent.send_message("I need help with my account.") time.sleep(60) agent.stop() ``` -------------------------------- ### Check ProactiveAgent Package Contents Source: https://github.com/leomariga/proactiveagent/blob/main/BUILD.md Inspect the files included in the distribution archives. This command lists the contents of the source distribution (.tar.gz) file. ```bash uv build --sdist --wheel ``` ```bash tar -tzf dist/proactiveagent-*.tar.gz | head -20 ```