### Clone and Install Sage Dependencies Source: https://github.com/zhangzhengeric/sage/blob/main/docs/QUICK_START.md Clones the Sage repository from GitHub and installs the necessary Python dependencies using pip. ```bash git clone https://github.com/ZHangZHengEric/Sage.git cd Sage pip install -r requirements.txt ``` -------------------------------- ### FastAPI + React Web Application Setup (Bash) Source: https://github.com/zhangzhengeric/sage/blob/main/docs/README.md Outlines the steps to set up and run a web application combining FastAPI for the backend and React for the frontend. It involves starting the Python backend in one terminal and then navigating to the frontend directory to install dependencies and start the development server. ```bash cd examples/fastapi_react_demo python start_backend.py # New terminal cd frontend npm install && npm run dev ``` -------------------------------- ### Troubleshooting Source: https://github.com/zhangzhengeric/sage/blob/main/docs/QUICK_START.md Provides solutions for common issues encountered during Sage development and deployment. ```APIDOC ## Troubleshooting ### Description Common issues and their solutions for Sage applications. ### Method N/A (Code examples for troubleshooting) ### Endpoint N/A ### Parameters N/A ### Request Example ```bash # Ensure you're using compatible API endpoints for token tracking export OPENAI_API_VERSION="2024-02-15-preview" ``` ```python # Enable performance monitoring controller.enable_performance_monitoring() perf_stats = controller.get_performance_stats() print("Bottlenecks:", perf_stats['bottlenecks']) # Reset token stats periodically controller.reset_all_token_stats() ``` ### Response N/A (This section describes code examples for troubleshooting.) ``` -------------------------------- ### Run Sage Demos Source: https://github.com/zhangzhengeric/sage/blob/main/docs/QUICK_START.md Provides commands to run the Sage framework's web interface demo using Streamlit and a command-line interface demo for multi-turn conversations. ```bash # Web interface with enhanced features (recommended) streamlit run examples/sage_demo.py -- \ --api_key $OPENAI_API_KEY \ --model mistralai/mistral-small-3.1-24b-instruct:free \ --base_url https://openrouter.ai/api/v1 # Command line interface python examples/multi_turn_demo.py ``` -------------------------------- ### Install Sage Core Dependencies (Bash) Source: https://github.com/zhangzhengeric/sage/blob/main/README_CN.md Clone the Sage repository and install the core Python dependencies using pip. This is the initial setup step for using the Sage framework. ```bash git clone https://github.com/ZHangZHengEric/Sage.git cd Sage # Install core dependencies pip install -r requirements.txt ``` -------------------------------- ### Python Script with Token Tracking Source: https://github.com/zhangzhengeric/sage/blob/main/docs/QUICK_START.md A placeholder for a Python script demonstrating how to integrate token tracking and enhanced monitoring within the Sage framework. ```python ```python # This is a placeholder for a Python script with token tracking. # Actual code will be provided in a full implementation. print("Sage token tracking example") ``` ``` -------------------------------- ### OpenAI API Client Initialization (Python) Source: https://github.com/zhangzhengeric/sage/blob/main/docs/QUICK_START.md Demonstrates initializing the OpenAI client with different API providers and their specific configurations. Supports standard OpenAI, cost-effective OpenRouter, and high-performance DeepSeek. Requires the 'openai' library. ```python # OpenAI (with streaming token tracking) model = OpenAI(api_key="sk-...") # OpenRouter (cost-effective, multiple models) model = OpenAI( api_key="sk-or-v1-வுகளை", base_url="https://openrouter.ai/api/v1" ) # DeepSeek (high performance) model = OpenAI( api_key="sk-வுகளை", base_url="https://api.deepseek.com/v1" ) ``` -------------------------------- ### Token Cost Optimization Source: https://github.com/zhangzhengeric/sage/blob/main/docs/QUICK_START.md Provides functionality to set token usage limits, track costs, and export usage reports. ```APIDOC ## Token Cost Optimization ### Description Monitor and control token usage to optimize costs for your Sage applications. ### Method N/A (Code examples for interacting with the controller) ### Endpoint N/A ### Parameters N/A ### Request Example ```python # Set token usage limits controller.set_token_limits( max_tokens_per_request=4000, max_total_tokens=50000, cost_alert_threshold=1.00 # Alert at $1.00 ) # Track costs across different models cost_tracker = controller.get_cost_tracker() print(f"Current session cost: ${cost_tracker.get_session_cost():.4f}") # Export detailed usage for billing controller.export_token_usage("usage_report.csv") ``` ### Response N/A (This section describes code examples for cost optimization features.) ``` -------------------------------- ### Troubleshooting Token Tracking and Slow Execution (Bash/Python) Source: https://github.com/zhangzhengeric/sage/blob/main/docs/QUICK_START.md Offers solutions for common Sage framework issues, including token tracking showing zero and slow execution times. It suggests setting API versions and enabling performance monitoring. ```bash # Ensure you're using compatible API endpoints export OPENAI_API_VERSION="2024-02-15-preview" ``` ```python # Enable performance monitoring controller.enable_performance_monitoring() perf_stats = controller.get_performance_stats() print("Bottlenecks:", perf_stats['bottlenecks']) ``` ```python # Reset token stats periodically controller.reset_all_token_stats() ``` -------------------------------- ### Real-time Streaming with Token Monitoring (Python) Source: https://github.com/zhangzhengeric/sage/blob/main/docs/QUICK_START.md Shows how to use the controller.run_stream method for real-time execution feedback. It prints message chunks as they arrive and tracks total token usage and elapsed time, providing live monitoring of the agent's progress. Requires an initialized AgentController, ToolManager, and the time module. ```python import time start_time = time.time() total_tokens = 0 print("🔄 Streaming execution with real-time monitoring:") for chunk in controller.run_stream(messages, tool_manager, deep_thinking=True): for message in chunk: print(f"🤖 [{message.get('type', 'unknown')}] {message['role']}: {message.get('show_content', '')[:100]}...") # Track token usage in real-time if 'usage' in message: total_tokens += message['usage'].get('total_tokens', 0) elapsed = time.time() - start_time print(f" 💰 Tokens: {total_tokens} | ⏱️ Time: {elapsed:.1f}s") print(f"\n✅ Streaming completed! Final token count: {total_tokens}") ``` -------------------------------- ### Set Sage Environment Variables Source: https://github.com/zhangzhengeric/sage/blob/main/docs/QUICK_START.md Demonstrates how to set environment variables for Sage configuration, including API keys and debug settings. It also shows how to create a .env file for persistent configuration. ```bash # Option 1: Set environment variables export OPENAI_API_KEY="your-api-key-here" export SAGE_DEBUG=true export SAGE_MAX_LOOP_COUNT=10 # Option 2: Create .env file (recommended) cat > .env << EOF OPENAI_API_KEY=your-api-key-here SAGE_DEBUG=true SAGE_ENVIRONMENT=development SAGE_MAX_LOOP_COUNT=10 SAGE_TOOL_TIMEOUT=30 EOF ``` -------------------------------- ### Token Cost Optimization and Management (Python) Source: https://github.com/zhangzhengeric/sage/blob/main/docs/QUICK_START.md Provides Python code snippets for managing and monitoring token usage within the Sage framework. This includes setting limits, tracking costs, and exporting usage data for billing purposes. ```python # Set token usage limits controller.set_token_limits( max_tokens_per_request=4000, max_total_tokens=50000, cost_alert_threshold=1.00 # Alert at $1.00 ) # Track costs across different models cost_tracker = controller.get_cost_tracker() print(f"Current session cost: ${cost_tracker.get_session_cost():.4f}") # Export detailed usage for billing controller.export_token_usage("usage_report.csv") ``` -------------------------------- ### Sage Agent Initialization and Execution (Python) Source: https://github.com/zhangzhengeric/sage/blob/main/docs/QUICK_START.md Initializes the Sage AgentController with OpenAI (via OpenRouter) and executes a multi-agent task. It prints the final output, execution summary, and token usage statistics. Dependencies include os, time, and Sage's agent and tool modules. ```python import os import time from agents.agent.agent_controller import AgentController from agents.tool.tool_manager import ToolManager from openai import OpenAI def main(): # Initialize components with enhanced configuration api_key = os.getenv('OPENAI_API_KEY') model = OpenAI( api_key=api_key, base_url="https://openrouter.ai/api/v1" # Use OpenRouter for cost-effective access ) tool_manager = ToolManager() # Create agent controller with production settings controller = AgentController( model, { "model": "mistralai/mistral-small-3.1-24b-instruct:free", "temperature": 0.7, "max_tokens": 4096 } ) # Define your task messages = [{ "role": "user", "content": "Explain how multi-agent systems work and their applications in modern AI", "type": "normal" }] print("🚀 Starting Sage Multi-Agent execution...") start_time = time.time() # Execute with full pipeline and monitoring result = controller.run( messages, tool_manager, deep_thinking=True, # Enable comprehensive task analysis summary=True, # Generate detailed summary deep_research=True # Full multi-agent pipeline ) execution_time = time.time() - start_time # Print results with enhanced information print("🎯 Final Output:") print(result['final_output']['content']) print(f"\n📊 Execution Summary:") print(f" • Generated {len(result['new_messages'])} messages") print(f" • Total execution time: {execution_time:.2f}s") # Display comprehensive token statistics print(f"\n💰 Token Usage Statistics:") controller.print_comprehensive_token_stats() # Get detailed statistics for further processing stats = controller.get_comprehensive_token_stats() print(f"\n📈 Cost Analysis:") print(f" • Total tokens: {stats['total_tokens']}") print(f" • Estimated cost: ${stats.get('estimated_cost', 0):.4f}") if __name__ == "__main__": main() ``` -------------------------------- ### Production Configuration Example (Python) Source: https://github.com/zhangzhengeric/sage/blob/main/docs/EXAMPLES.md Demonstrates setting up production-level configurations for an AgentController. It retrieves default settings and defines specific parameters like model, temperature, and timeout for a production environment. This example assumes the existence of 'AgentController', 'Settings', and 'get_settings' from the 'agents.config.settings' module. ```python # Production setup with error handling from agents.config.settings import Settings, get_settings # Get default settings settings = get_settings() # Production configuration production_config = { "model": "gpt-4", "temperature": 0.3, "max_tokens": 8192, "timeout": 120 } controller = AgentController( model=model, model_config=production_config ) ``` -------------------------------- ### Multi-Environment Configuration Setup (Python) Source: https://github.com/zhangzhengeric/sage/blob/main/docs/EXAMPLES.md Illustrates how to configure an application based on the environment variable 'SAGE_ENVIRONMENT'. It sets different model configurations for 'production' and 'development' environments, falling back to 'development' if the variable is not set. This requires the 'os' module. ```python import os # Environment-specific configuration env = os.getenv('SAGE_ENVIRONMENT', 'development') if env == 'production': config = { "model": "gpt-4", "temperature": 0.2, "max_tokens": 8192 } elif env == 'development': config = { "model": "gpt-3.5-turbo", "temperature": 0.7, "max_tokens": 4096 } controller = AgentController(model, config) ``` -------------------------------- ### Weather Analysis Tool Source: https://github.com/zhangzhengeric/sage/blob/main/docs/QUICK_START.md Provides comprehensive weather analysis with forecasts and trends. It includes parameters for city, number of forecast days, and an option to include historical trends. ```APIDOC ## WeatherAnalysisTool ### Description Advanced weather analysis tool with caching and validation. Get comprehensive weather analysis with forecasts and trends. ### Method N/A (This is a tool definition, not an endpoint) ### Endpoint N/A ### Parameters #### Tool Parameters - **city** (string) - Required - Name of the city - **days** (integer) - Optional - Number of forecast days (1-7), default is 3 - **include_trends** (boolean) - Optional - Include historical trends analysis, default is False ### Request Example ```json { "city": "New York", "days": 5, "include_trends": true } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **city** (string) - The city for which the weather data was fetched. - **current_weather** (string) - The current weather conditions. - **forecast** (array) - A list of forecast weather conditions for the specified number of days. - **trends** (object) - (Optional) Contains historical trend analysis if `include_trends` is true. - **metadata** (object) - Contains execution time, data source, and cache information. #### Error Response - **success** (boolean) - Always false in case of an error. - **error** (string) - A message describing the error. - **error_type** (string) - The type of the error that occurred. - **city** (string) - The city that was requested. - **metadata** (object) - Contains execution time. #### Response Example (Success) ```json { "success": true, "city": "New York", "current_weather": "Sunny, 72°F in New York", "forecast": [ "Day 1: Partly cloudy", "Day 2: Partly cloudy", "Day 3: Partly cloudy", "Day 4: Partly cloudy", "Day 5: Partly cloudy" ], "trends": { "trend": "warming", "confidence": 0.85 }, "metadata": { "execution_time": 0.1234, "data_source": "OpenWeatherMap", "cache_used": false } } ``` #### Response Example (Error) ```json { "success": false, "error": "City not found", "error_type": "ValueError", "city": "NonExistentCity", "metadata": { "execution_time": 0.05 } } ``` ``` -------------------------------- ### Sage Configuration Example (.env) Source: https://github.com/zhangzhengeric/sage/blob/main/docs/CONFIGURATION.md An example .env file demonstrating how to set various configuration parameters for the Sage Multi-Agent Framework. This includes API keys, model settings, agent behavior options, development preferences, and tool configurations. ```bash # .env file for Sage configuration # API Configuration OPENAI_API_KEY=sk-your-openai-api-key-here SAGE_BASE_URL=https://api.openai.com/v1 # Model Settings SAGE_MODEL_NAME=gpt-4 SAGE_MAX_TOKENS=8192 SAGE_TEMPERATURE=0.3 # Agent Behavior SAGE_DEEP_THINKING=true SAGE_DEEP_RESEARCH=true SAGE_SUMMARY_MODE=true SAGE_MAX_ITERATIONS=15 # Development Settings SAGE_DEBUG=true SAGE_ENVIRONMENT=development SAGE_LOG_LEVEL=DEBUG # Tool Settings SAGE_TOOLS_PATH=/custom/tools:/default/tools SAGE_TOOL_TIMEOUT=60 ``` -------------------------------- ### Install Sage Core Dependencies Source: https://github.com/zhangzhengeric/sage/blob/main/README.md This command installs the core Python dependencies required to run the Sage framework. It assumes you have already cloned the repository and navigated into the Sage directory. Ensure you have Python 3.10+ installed as per the project requirements. ```bash git clone https://github.com/ZHangZHengEric/Sage.git cd Sage # Install core dependencies pip install -r requirements.txt ``` -------------------------------- ### Integration Testing Full Workflow Source: https://github.com/zhangzhengeric/sage/blob/main/docs/EXAMPLES.md Shows an example of integration testing the complete workflow, requiring an OpenAI API key. ```APIDOC ## Integration Testing Full Workflow ### Description This example demonstrates integration testing for the complete workflow, including setting up the OpenAI model, ToolManager, and AgentController. It requires the `OPENAI_API_KEY` environment variable to be set. ### Method N/A (This is a testing example) ### Endpoint N/A ### Parameters N/A ### Request Example ```python def test_full_workflow(): """Test complete workflow integration""" # This requires actual API key for integration testing if not os.getenv('OPENAI_API_KEY'): pytest.skip("API key not available") model = OpenAI(api_key=os.getenv('OPENAI_API_KEY')) tool_manager = ToolManager() controller = AgentController(model, {"model": "gpt-3.5-turbo"}) messages = [{"role": "user", "content": "What is 2+2?", "type": "normal"}] result = controller.run(messages, tool_manager) assert "4" in result['final_output']['content'] ``` ### Response N/A ``` -------------------------------- ### Sage Agent Execution Modes (Python) Source: https://github.com/zhangzhengeric/sage/blob/main/docs/QUICK_START.md Illustrates different execution modes for the Sage AgentController's run method: Deep Research, Standard, and Rapid. These modes control the depth of task analysis and research, affecting performance and comprehensiveness. Requires an initialized AgentController and ToolManager. ```python # Deep Research Mode (recommended for complex analysis) result = controller.run( messages, tool_manager, deep_thinking=True, # Comprehensive task analysis summary=True, # Detailed summary with insights deep_research=True # Full multi-agent pipeline ) # Standard Mode (balanced performance) result = controller.run( messages, tool_manager, deep_thinking=True, # Task analysis summary=True, # Summary generation deep_research=False # Direct execution after analysis ) # Rapid Mode (maximum speed) result = controller.run( messages, tool_manager, deep_thinking=False, # Skip analysis deep_research=False # Direct execution ) ``` -------------------------------- ### Content Creation Pipeline Workflow (Python) Source: https://github.com/zhangzhengeric/sage/blob/main/docs/EXAMPLES.md Shows a workflow for generating a blog post using the AgentController. It defines user messages with a specific request and then runs the controller with options like deep_thinking, summary, and max_loop_count. The final output's content is then printed. This example relies on a pre-configured 'controller' and 'tool_manager'. ```python # Blog post creation workflow messages = [{"role": "user", "content": "Create a comprehensive blog post about sustainable computing practices. Include an outline, research key points, and write the full article with actionable tips.", "type": "normal" }] # Use full pipeline for comprehensive content result = controller.run( messages, tool_manager, deep_thinking=True, summary=True, max_loop_count=20 ) print("Generated Blog Post:") print(result['final_output']['content']) ``` -------------------------------- ### Install Dependencies for FastAPI React Demo Source: https://github.com/zhangzhengeric/sage/blob/main/README.md Installs all necessary Python packages for the FastAPI React demo application using pip. This command reads package requirements from the specified requirements.txt file. ```bash pip install -r examples/fastapi_react_demo/requirements.txt ``` -------------------------------- ### Usage Example Source: https://github.com/zhangzhengeric/sage/blob/main/docs/EXAMPLES.md Demonstrates how to use the robust_query function to analyze market conditions and handle potential exceptions. ```APIDOC ## Usage Example ### Description This section shows a basic example of how to use the `robust_query` function to analyze market conditions and print the response. ### Method N/A (This is a usage example, not a direct API endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example ```python try: response = robust_query("Analyze current market conditions") print(response) except Exception as e: print(f"Failed after all retries: {e}") ``` ### Response N/A ``` -------------------------------- ### Start FastAPI React Demo Backend (Python) Source: https://github.com/zhangzhengeric/sage/blob/main/README_CN.md Run the FastAPI backend server for the modern web application demo. This command initiates the asynchronous API server that powers the React frontend. ```python cd examples/fastapi_react_demo # Backend setup python start_backend.py ``` -------------------------------- ### Python Setup Script for Tool Packaging Source: https://github.com/zhangzhengeric/sage/blob/main/docs/TOOL_DEVELOPMENT.md This Python script, `setup.py`, is used to package Sage custom tools for distribution. It defines package metadata, dependencies, and entry points for Sage tools, enabling them to be discovered and used within the Sage ecosystem. ```python # setup.py for tool package from setuptools import setup, find_packages setup( name="sage-custom-tools", version="1.0.0", packages=find_packages(), install_requires=[ "sage-multi-agent>=1.0.0", "requests>=2.25.0", # Other dependencies ], entry_points={ "sage.tools": [ "weather = custom_tools.weather:WeatherTool", "database = custom_tools.database:DatabaseTool", ] } ) ``` -------------------------------- ### Weather Analysis Tool with Caching and Validation (Python) Source: https://github.com/zhangzhengeric/sage/blob/main/docs/QUICK_START.md Implements an advanced weather analysis tool that fetches weather data, provides forecasts, and optionally analyzes historical trends. It includes error handling and mock data fetching for demonstration purposes. The tool is designed to be registered with ToolBase. ```python from agents.tool.tool_base import ToolBase from typing import Dict, Any, Optional import requests import time @ToolBase.register_tool class WeatherAnalysisTool(ToolBase): """Advanced weather analysis tool with caching and validation""" def __init__(self): super().__init__( name="weather_analysis", description="Get comprehensive weather analysis with forecasts and trends", parameters={ "city": { "type": "string", "description": "Name of the city", "required": True }, "days": { "type": "integer", "description": "Number of forecast days (1-7)", "minimum": 1, "maximum": 7, "default": 3 }, "include_trends": { "type": "boolean", "description": "Include historical trends analysis", "default": False } } ) def execute(self, city: str, days: int = 3, include_trends: bool = False, **kwargs) -> Dict[str, Any]: """Execute weather analysis with enhanced error handling""" start_time = time.time() try: # Your weather API logic here weather_data = self._fetch_weather_data(city, days) result = { "success": True, "city": city, "current_weather": weather_data["current"], "forecast": weather_data["forecast"][:days], "metadata": { "execution_time": time.time() - start_time, "data_source": "OpenWeatherMap", "cache_used": False } } if include_trends: result["trends"] = self._analyze_trends(city) return result except Exception as e: return { "success": False, "error": str(e), "error_type": type(e).__name__, "city": city, "metadata": { "execution_time": time.time() - start_time } } def _fetch_weather_data(self, city: str, days: int) -> Dict[str, Any]: # Mock implementation - replace with real API return { "current": f"Sunny, 72°F in {city}", "forecast": [f"Day {i+1}: Partly cloudy" for i in range(days)] } def _analyze_trends(self, city: str) -> Dict[str, Any]: # Mock trends analysis return {"trend": "warming", "confidence": 0.85} ``` -------------------------------- ### AgentController.run() Parameters Source: https://github.com/zhangzhengeric/sage/blob/main/docs/EXAMPLES.md Details the parameters accepted by the AgentController.run() method. ```APIDOC ## AgentController.run() Parameters ### Description This section details the parameters available for the `AgentController.run()` method. ### Method N/A (Parameter documentation) ### Endpoint N/A ### Parameters #### Input Parameters - `input_messages` (List[Dict]) - Required - List of message dictionaries. - `tool_manager` (ToolManager) - Optional - ToolManager instance. - `session_id` (str) - Optional - Session identifier. - `deep_thinking` (bool) - Optional - Enable task analysis phase (default: True). - `summary` (bool) - Optional - Enable task summary phase (default: True). - `max_loop_count` (int) - Optional - Maximum planning-execution-observation loops (default: 10). - `deep_research` (bool) - Optional - Enable full agent pipeline vs direct execution (default: True). ### Request Example N/A ### Response N/A ``` -------------------------------- ### Main Configuration File (config/settings.yaml) Source: https://github.com/zhangzhengeric/sage/blob/main/docs/CONFIGURATION_CN.md The main configuration file allows for detailed setup of models, agents, tools, and logging. It defines parameters such as model names, token limits, agent iteration counts, and tool directories. ```APIDOC ## 📁 Configuration Files ### Main Configuration (config/settings.yaml) ```yaml # Sage Multi-agent Framework Configuration model: name: "gpt-4" base_url: "https://api.openai.com/v1" max_tokens: 4096 temperature: 0.7 top_p: 1.0 frequency_penalty: 0.0 presence_penalty: 0.0 timeout: 60 retry_count: 3 agent: max_iterations: 10 deep_thinking: true deep_research: true summary_mode: true streaming: false task_analysis: enabled: true max_depth: 3 planning: enabled: true max_subtasks: 20 execution: parallel_tools: true max_concurrent: 5 observation: enabled: true feedback_threshold: 0.8 tool: directories: - "./agents/tool" - "./custom_tools" timeout: 30 max_concurrent: 5 retry_count: 2 mcp_servers: config_path: "./mcp_servers/mcp_setting.json" auto_connect: true logging: level: "INFO" format: "% (asctime)s - % (name)s - % (levelname)s - % (message)s" file: "./logs/sage.log" rotate: true max_size: "10MB" backup_count: 5 debug: enabled: false profile: false trace_calls: false save_conversations: false ``` ``` -------------------------------- ### Unit Testing AgentController Source: https://github.com/zhangzhengeric/sage/blob/main/docs/EXAMPLES.md Provides an example of unit testing the AgentController class using pytest and unittest.mock. ```APIDOC ## Unit Testing AgentController ### Description This example demonstrates how to perform unit testing on the `AgentController` class using `pytest` and `unittest.mock` to simulate model responses. ### Method N/A (This is a testing example) ### Endpoint N/A ### Parameters N/A ### Request Example ```python import pytest from unittest.mock import Mock def test_agent_controller(): """Test agent controller basic functionality""" mock_model = Mock() mock_model.chat.completions.create.return_value.choices = [ Mock(message=Mock(content="Test response")) ] controller = AgentController(mock_model, {"model": "gpt-4"}) messages = [{"role": "user", "content": "Test query", "type": "normal"}] result = controller.run(messages) assert result is not None assert 'final_output' in result ``` ### Response N/A ``` -------------------------------- ### Basic Query Processing with Sage Agent Controller Source: https://github.com/zhangzhengeric/sage/blob/main/docs/EXAMPLES.md Demonstrates how to initialize the Sage Agent Controller and perform a basic query. It utilizes OpenAI for language modeling and ToolManager for tool integration. The output is the final content of the agent's response. ```python from agents.agent.agent_controller import AgentController from agents.tool.tool_manager import ToolManager from openai import OpenAI # Initialize model = OpenAI(api_key="your-api-key") tool_manager = ToolManager() controller = AgentController(model, {"model": "gpt-4", "temperature": 0.7}) # Simple query messages = [{"role": "user", "content": "What are the benefits of renewable energy?", "type": "normal"}] result = controller.run(messages, tool_manager) print(result['final_output']['content']) ``` -------------------------------- ### Data Analysis Workflow Example (Python) Source: https://github.com/zhangzhengeric/sage/blob/main/docs/EXAMPLES.md Demonstrates a data analysis workflow using the AgentController. It prepares user messages containing data to be analyzed and then executes the controller with deep_thinking, summary, and deep_research enabled for comprehensive analysis and insights. Requires 'controller' and 'tool_manager'. ```python # Analyze data messages = [{"role": "user", "content": "Analyze this data and provide insights on trends and recommendations: [Your data here]", "type": "normal" }] result = controller.run( messages, tool_manager, deep_thinking=True, # Enable task analysis summary=True, # Generate comprehensive summary deep_research=True # Use full agent pipeline ) ``` -------------------------------- ### Performance Monitoring Source: https://github.com/zhangzhengeric/sage/blob/main/docs/EXAMPLES.md Illustrates how to measure the execution performance of a query using the AgentController. ```APIDOC ## Performance Monitoring ### Description This function measures the execution time and other performance metrics for a given query using the `AgentController`. ### Method N/A (This is a performance monitoring utility) ### Endpoint N/A ### Parameters - `query` (str) - Required - The query string to execute. ### Request Example ```python import time from typing import Dict, Any def measure_performance(query: str) -> Dict[str, Any]: """Measure execution performance""" start_time = time.time() messages = [{"role": "user", "content": query, "type": "normal"}] result = controller.run(messages, tool_manager) end_time = time.time() execution_time = end_time - start_time return { "result": result, "execution_time": execution_time, "message_count": len(result.get('new_messages', [])), "success": result.get('final_output') is not None } # Usage performance = measure_performance("Explain quantum computing") print(f"Execution time: {performance['execution_time']:.2f} seconds") print(f"Messages generated: {performance['message_count']}") ``` ### Response - `result` (Dict[str, Any]) - The result from the controller's run method. - `execution_time` (float) - The time taken for execution in seconds. - `message_count` (int) - The number of messages generated. - `success` (bool) - Indicates if the operation was successful. ``` -------------------------------- ### MCP Configuration: STDIO Connection Source: https://github.com/zhangzhengeric/sage/blob/main/README_CN.md Configuration example for establishing an MCP connection using the STDIO protocol. This typically involves specifying the command to execute and its arguments, suitable for local process communication. ```json { "mcpServers": { "file_system": { "command": "python", "args": ["./mcp_servers/file_system/file_system.py"], "connection_type": "stdio" } } } ``` -------------------------------- ### Basic Usage of Sage Framework Source: https://github.com/zhangzhengeric/sage/blob/main/docs/EXAMPLES.md Demonstrates the fundamental usage of the Sage framework by querying market conditions and handling potential exceptions. It requires a `robust_query` function to be defined and accessible. ```python try: response = robust_query("Analyze current market conditions") print(response) except Exception as e: print(f"Failed after all retries: {e}") ``` -------------------------------- ### AgentController.run_stream() Parameters Source: https://github.com/zhangzhengeric/sage/blob/main/docs/EXAMPLES.md Details the parameters accepted by the AgentController.run_stream() method, noting it supports the same parameters as run(). ```APIDOC ## AgentController.run_stream() Parameters ### Description This section details the parameters available for the `AgentController.run_stream()` method. It supports the same parameters as the `run()` method and yields message chunks for real-time processing. ### Method N/A (Parameter documentation) ### Endpoint N/A ### Parameters #### Input Parameters - `input_messages` (List[Dict]) - Required - List of message dictionaries. - `tool_manager` (ToolManager) - Optional - ToolManager instance. - `session_id` (str) - Optional - Session identifier. - `deep_thinking` (bool) - Optional - Enable task analysis phase (default: True). - `summary` (bool) - Optional - Enable task summary phase (default: True). - `max_loop_count` (int) - Optional - Maximum planning-execution-observation loops (default: 10). - `deep_research` (bool) - Optional - Enable full agent pipeline vs direct execution (default: True). ### Request Example N/A ### Response N/A ``` -------------------------------- ### Example Model Names for Sage Source: https://github.com/zhangzhengeric/sage/blob/main/docs/CONFIGURATION_CN.md Lists example model identifiers supported by Sage, categorized by provider. This includes models from OpenAI, OpenRouter, DeepSeek, and local models via Ollama. ```python # OpenAI 模型 "gpt-4" "gpt-4-turbo" "gpt-3.5-turbo" # OpenRouter 模型 "mistralai/mistral-large" "meta-llama/llama-2-70b-chat" "anthropic/claude-3-sonnet" # DeepSeek 模型 "deepseek-chat" "deepseek-coder" # 本地模型(通过 Ollama) "llama2:7b" "mistral:7b" ``` -------------------------------- ### Dockerfile for Sage Tool Deployment Source: https://github.com/zhangzhengeric/sage/blob/main/docs/TOOL_DEVELOPMENT.md This Dockerfile outlines the steps to containerize Sage tools for deployment. It sets up a Python environment, installs dependencies, copies tool code, and configures environment variables before defining the entry point for running the Sage tools server. ```dockerfile # Dockerfile for tool deployment FROM python:3.9-slim WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY custom_tools/ ./custom_tools/ COPY mcp_servers/ ./mcp_servers/ ENV SAGE_TOOLS_PATH=/app/custom_tools ENV MCP_SERVERS_PATH=/app/mcp_servers CMD ["python", "-m", "sage.tools.server"] ``` -------------------------------- ### Python Performance Monitoring and Optimization Source: https://github.com/zhangzhengeric/sage/blob/main/docs/ARCHITECTURE.md Provides advanced performance monitoring and optimization functionalities in Python. It includes methods to collect various performance metrics, generate optimization reports, and export detailed analytics. ```python class PerformanceMonitor: """Advanced performance monitoring and optimization""" def collect_metrics(self): """Collect comprehensive performance data""" return { 'execution_times': self._get_execution_times(), 'memory_usage': self._get_memory_stats(), 'token_efficiency': self._analyze_token_usage(), 'tool_performance': self._get_tool_metrics(), 'bottlenecks': self._identify_bottlenecks() } def generate_optimization_report(self): """Generate actionable optimization recommendations""" def export_performance_data(self, format='json'): """Export detailed performance analytics""" ``` -------------------------------- ### Agent Flow Orchestration in Python Source: https://github.com/zhangzhengeric/sage/blob/main/README_CN.md Python code illustrating how to orchestrate a sequence of custom agents using AgentFlow. This example defines a list of agents, initializes an AgentFlow, and demonstrates streaming execution with system context. ```python from sagents.agent_flow import AgentFlow from sagents.agent.task_analysis_agent import TaskAnalysisAgent from sagents.agent.task_planning_agent import PlanningAgent from sagents.agent.task_executor_agent import ExecutorAgent # 定义自定义智能体序列 custom_agents = [ TaskAnalysisAgent(model, model_config), CustomResearchAgent(model, model_config), PlanningAgent(model, model_config), ExecutorAgent(model, model_config) ] # 创建智能体流程 agent_flow = AgentFlow(custom_agents, workspace="./workspace") # 流式执行 for message_chunks in agent_flow.run_stream( input_messages=messages, tool_manager=tool_manager, session_id="custom-session", system_context={ "project_type": "research", "domain": "AI/ML" } ): # 处理流式结果 for chunk in message_chunks: print(f"{chunk.role}: {chunk.content}") ``` -------------------------------- ### Market Research using Sage Agent Controller Source: https://github.com/zhangzhengeric/sage/blob/main/docs/EXAMPLES.md Illustrates a comprehensive market research task using the Sage Agent Controller. It enables deep thinking, summary generation, and the full agent pipeline for in-depth analysis. The output prints the generated market research results. ```python # Comprehensive market research messages = [{ "role": "user", "content": "Conduct a market analysis for electric vehicles in 2024. Include market size, key players, trends, and future outlook.", "type": "normal" }] result = controller.run( messages, tool_manager, deep_thinking=True, # Enable task analysis summary=True, # Generate comprehensive summary deep_research=True # Use full agent pipeline ) print("Market Research Results:") print(result['final_output']['content']) ``` -------------------------------- ### Test Configuration Loading and Overrides (Python) Source: https://github.com/zhangzhengeric/sage/blob/main/docs/CONFIGURATION.md Provides Python pytest examples for testing configuration loading, default values, and environment variable overrides. It demonstrates how to assert expected settings after loading from files and environment. ```python # test_config.py import pytest from agents.config import Settings, load_config import os def test_default_config(): """Test default configuration values""" settings = Settings() assert settings.model.name == "gpt-3.5-turbo" assert settings.agent.max_iterations == 10 assert settings.tool.timeout == 30 def test_environment_override(): """Test environment variable override""" os.environ['SAGE_MODEL_NAME'] = 'gpt-4' settings = Settings() assert settings.model.name == "gpt-4" # Clean up environment variable del os.environ['SAGE_MODEL_NAME'] def test_config_file_loading(): """Test configuration file loading""" # Assuming a dummy test_config.yaml exists for this test # In a real scenario, you'd create this file or mock it. # For demonstration, let's assume it loads successfully. try: config = load_config("./test_config.yaml") assert config is not None assert 'model' in config except FileNotFoundError: pytest.skip("test_config.yaml not found, skipping file loading test.") ``` -------------------------------- ### Model-Specific Configuration Settings Source: https://github.com/zhangzhengeric/sage/blob/main/docs/CONFIGURATION_CN.md Provides example dictionaries defining model-specific parameters such as `max_tokens`, `temperature`, and `streaming` for different models like GPT-4 and Mistral Large. ```python model_configs = { "gpt-4": { "max_tokens": 8192, "temperature": 0.3, "top_p": 0.9, "streaming": True }, "mistral-large": { "max_tokens": 32000, "temperature": 0.4, "stop_sequences": ["Human:", "Assistant:"] } } ``` -------------------------------- ### Batch Processing Multiple Queries (Python) Source: https://github.com/zhangzhengeric/sage/blob/main/docs/EXAMPLES.md Demonstrates batch processing by iterating through a list of queries. For each query, it constructs messages and runs the AgentController, collecting the results. Finally, it prints the collected results, truncated to 200 characters. Requires 'controller' and 'tool_manager'. ```python # Process multiple queries efficiently queries = [ "Summarize latest AI research papers", "Analyze market trends for electric vehicles", "Create a project timeline for mobile app development" ] results = [] for query in queries: messages = [{"role": "user", "content": query, "type": "normal"}] result = controller.run(messages, tool_manager, deep_thinking=True) results.append(result['final_output']['content']) print("Batch Processing Results:") for i, result in enumerate(results): print(f"\nQuery {i+1}: {queries[i]}") print(f"Result: {result[:200]}...") ``` -------------------------------- ### AgentController Usage with System Context Source: https://github.com/zhangzhengeric/sage/blob/main/docs/README.md Demonstrates how to initialize and use the AgentController in Python. The example showcases the integration of `system_context` for providing project-specific information, constraints, and preferences to the agent, enhancing its decision-making and output. This component is central to orchestrating agent interactions. ```Python from agents.agent.agent_controller import AgentController controller = AgentController(model, model_config) # Enhanced with system_context support result = controller.run( messages, tool_manager, system_context={ "project_info": "AI research", "constraints": ["time: 2h", "budget: $100"], "preferences": {"output_format": "structured"} } ) ``` -------------------------------- ### Configure Hierarchical Settings with Python Source: https://github.com/zhangzhengeric/sage/blob/main/docs/ARCHITECTURE.md Demonstrates a Python class for managing hierarchical configurations with defined schemas. It supports validation against these schemas, including data types, default values, and constraints. This class is central to the configuration system's robustness. ```python class ConfigurationManager: """Enterprise-grade configuration management""" SCHEMA = { 'agents': { 'max_loop_count': {'type': 'int', 'default': 10, 'min': 1, 'max': 50}, 'tool_timeout': {'type': 'int', 'default': 30, 'min': 5, 'max': 300}, 'retry_attempts': {'type': 'int', 'default': 3, 'min': 1, 'max': 10} }, 'performance': { 'enable_monitoring': {'type': 'bool', 'default': True}, 'memory_threshold': {'type': 'int', 'default': 1024, 'min': 256}, 'cache_ttl': {'type': 'int', 'default': 3600, 'min': 60} }, 'costs': { 'budget_alert_threshold': {'type': 'float', 'default': 10.0, 'min': 0.1}, 'cost_tracking_enabled': {'type': 'bool', 'default': True} } } def validate_config(self, config): """Validate configuration against schema""" def hot_reload(self, config_path): """Reload configuration without restart""" ``` -------------------------------- ### Extend Functionality with Python Plugins Source: https://github.com/zhangzhengeric/sage/blob/main/docs/ARCHITECTURE.md Illustrates a Python PluginManager for an extensible system. It provides methods to register various plugin types, including agent implementations, tool implementations, and middleware. It also supports auto-discovering and loading plugins from a specified directory. ```python class PluginManager: """Extensible plugin system for custom functionality""" def register_agent_plugin(self, plugin_class): """Register custom agent implementations""" def register_tool_plugin(self, plugin_class): """Register custom tool implementations""" def register_middleware(self, middleware_class): """Register request/response middleware""" def load_plugins_from_directory(self, directory): """Auto-discover and load plugins""" ``` -------------------------------- ### Custom Agent Development in Python Source: https://github.com/zhangzhengeric/sage/blob/main/README_CN.md Example of creating a custom research agent by inheriting from AgentBase. It demonstrates initializing the agent, defining its description, and implementing a streaming run method to interact with an LLM for research tasks. ```python from sagents.agent.agent_base import AgentBase from sagents.context.session_context import SessionContext from sagents.context.messages.message import MessageChunk, MessageRole, MessageType class CustomResearchAgent(AgentBase): """专门用于研究任务的自定义智能体""" def __init__(self, model, model_config): super().__init__(model, model_config, system_prefix="研究智能体") self.agent_description = "专门用于深度研究和分析的智能体" def run_stream(self, session_context: SessionContext, tool_manager=None, session_id=None): """实现自定义智能体逻辑""" # 访问对话历史 messages = session_context.message_manager.get_messages_for_llm() # 自定义研究逻辑 research_prompt = "对给定主题进行深入研究..." # 流式响应 for chunk in self._call_llm_streaming( messages + [{"role": "user", "content": research_prompt}], session_id=session_id, step_name="research_analysis" ): yield [chunk] ```