### Install and Set Up AgentMap Development Environment Source: https://github.com/jwwelbor/agentmap/blob/main/README_for_contributors.md Steps to clone the repository, install dependencies using Poetry, activate the development shell, and verify the AgentMap installation. ```bash # 1. Fork and clone the repository git clone https://github.com/jwwelbor/AgentMap.git cd AgentMap # 2. Install Poetry (if not already installed) curl -sSL https://install.python-poetry.org | python3 - # 3. Install dependencies and AgentMap in development mode poetry install --with dev # 4. Activate the Poetry shell (optional) poetry shell # 5. Verify installation poetry run python -c "import agentmap; print(f'AgentMap {agentmap.__version__} ready!')" ``` -------------------------------- ### TestPyPI Publishing and Installation Source: https://github.com/jwwelbor/agentmap/blob/main/README_for_contributors.md Steps to configure and publish to TestPyPI, and then test installation from TestPyPI. ```bash # Configure TestPyPI poetry config repositories.testpypi https://test.pypi.org/legacy/ poetry config pypi-token.testpypi YOUR_TEST_PYPI_TOKEN # Publish to TestPyPI poetry publish -r testpypi # Test installation from TestPyPI pip install --index-url https://test.pypi.org/simple/ agentmap ``` -------------------------------- ### Configure API Keys via Environment Variables Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/getting-started/installation.md Sets environment variables for API keys required by different LLM providers like OpenAI, Anthropic, and Google. This is a quick setup method. ```bash # OpenAI export OPENAI_API_KEY="sk-your-openai-key-here" # Anthropic (Claude) export ANTHROPIC_API_KEY="sk-ant-your-anthropic-key-here" # Google (Gemini) export GOOGLE_API_KEY="your-google-api-key-here" ``` -------------------------------- ### Python Method Documentation Example Source: https://github.com/jwwelbor/agentmap/blob/main/DEVELOPMENT.md Provides an example of documenting a Python method, detailing its arguments, return value, potential exceptions, and illustrating its usage with a doctest-compatible example. ```python def build_graph(self, spec: Dict[str, Any]) -> Graph: """Build a graph from specification. Args: spec: Graph specification dictionary containing nodes, edges, and configuration. Must include 'name' and 'nodes' keys. Returns: Graph: Executable graph object Raises: ValidationError: If specification is invalid ConfigurationError: If required agents are not available BuildError: If graph construction fails Example: >>> spec = { ... "name": "test_graph", ... "nodes": [{"name": "start", "agent_type": "echo"}] ... } >>> graph = service.build_graph(spec) >>> graph.name 'test_graph' """ ``` -------------------------------- ### Start AgentMap Docs Development Server Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/README.md Starts the local development server for the AgentMap Docusaurus site, allowing for live previews of changes. Run this command from the 'docs-docusaurus' directory. ```bash npm start ``` -------------------------------- ### Install AgentMap via Pip Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/getting-started/installation.md Installs the AgentMap Python package using pip. Supports installing with specific LLM providers (e.g., anthropic, google, openai) or installing all features at once. ```bash pip install agentmap # Install with specific providers pip install agentmap[anthropic] pip install agentmap[google] pip install agentmap[openai] # Install all features pip install agentmap[all] ``` -------------------------------- ### Test AgentMap CLI Commands and Workflows Source: https://github.com/jwwelbor/agentmap/blob/main/README_for_contributors.md Examples of how to interact with the AgentMap command-line interface for help, running workflows, and executing example scripts. ```bash # Test CLI commands poetry run agentmap --help poetry run agentmap run --graph TestGraph --csv examples/simple.csv # Test specific workflows poetry run python examples/run_example.py ``` -------------------------------- ### Install LLM Dependencies (Bash) Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/getting-started/installation.md Installs necessary Python packages for LLM providers supported by AgentMap. It shows commands to install all providers or specific ones like OpenAI, Anthropic, and Google GenAI. ```bash # Install all providers pip install agentmap[llm] # Or install individually pip install langchain-openai langchain-anthropic langchain-google-genai ``` -------------------------------- ### Starting the AgentMap FastAPI Server Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/reference/api.md Instructions on how to install and start the AgentMap FastAPI server. This server allows for the integration of AgentMap workflows into host applications. The installation can be done via pip, and the server can be launched using the command line or as a Python module. ```bash # Install AgentMap (FastAPI included in base install) pip install agentmap # Start the server agentmap-server --host 0.0.0.0 --port 8000 # Or using Python module python -m agentmap.server_cli ``` -------------------------------- ### Python Class Documentation Example Source: https://github.com/jwwelbor/agentmap/blob/main/DEVELOPMENT.md Demonstrates comprehensive docstring documentation for a Python class, including its purpose, attributes, initialization method arguments, and potential exceptions. Includes a usage example. ```python class GraphBuilderService: """Service responsible for building and validating graph specifications. This service takes graph specifications and converts them into executable graph objects. It handles validation, dependency resolution, and error handling for graph construction. Attributes: di_container: Dependency injection container for service resolution validator: Graph validation service registry: Agent registry for component discovery Example: >>> service = GraphBuilderService(di_container) >>> graph = service.build_graph(graph_spec) >>> print(graph.name) 'my_graph' """ def __init__(self, di_container: CoreContainer): """Initialize the graph builder service. Args: di_container: Dependency injection container Raises: ConfigurationError: If required services are not available """ self.di_container = di_container self.validator = di_container.graph_validation_service() self.registry = di_container.agent_registry_service() ``` -------------------------------- ### Troubleshoot AgentMap Installation Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/getting-started/quick-start.md Fixes 'Module not found' errors by reinstalling AgentMap with verbose output and running a diagnostic command. ```bash # Reinstall with verbose output pip install --upgrade agentmap agentmap diagnose ``` -------------------------------- ### Verify PyPI Release Installation Source: https://github.com/jwwelbor/agentmap/blob/main/README_for_contributors.md Commands to test the installation of the agentmap package at a specific version from PyPI and with all optional dependencies. ```bash # Wait a few minutes, then test pip install agentmap==0.3.0 pip install "agentmap[all]==0.3.0" ``` -------------------------------- ### Run AgentMap Workflows and Serve API (Bash) Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/getting-started/installation.md These Bash commands demonstrate how to execute AgentMap workflows directly using a CSV file and graph, and how to run AgentMap as a local API server. Requires the AgentMap CLI to be installed. ```bash # Run workflows directly agentmap run --csv workflow.csv --graph MyGraph # Run as API server agentmap serve --host 0.0.0.0 --port 8000 ``` -------------------------------- ### Build and Test AgentMap Package Locally Source: https://github.com/jwwelbor/agentmap/blob/main/README_for_contributors.md Instructions for cleaning previous builds, packaging the AgentMap project using Poetry, installing the built package, and testing optional dependencies. ```bash # Clean old builds rm -rf dist/ src/agentmap.egg-info/ # Build the package poetry build # Test the built package pip install dist/agentmap-*.whl python -c "import agentmap; print('Success!')" # Test optional dependencies pip install "agentmap[llm]" --find-links dist/ pip install "agentmap[storage]" --find-links dist/ ``` -------------------------------- ### Install AgentMap and Scaffold Workflow Source: https://github.com/jwwelbor/agentmap/blob/main/README.md This bash command demonstrates the initial setup for using AgentMap. It first installs the agentmap package using pip and then uses the `agentmap scaffold` command to generate a basic workflow CSV file. This is the starting point for creating new AgentMap workflows. ```bash pip install agentmapagentmap scaffold --csv your_workflow.csv ``` -------------------------------- ### Clean AgentMap Installation (Bash) Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/getting-started/installation.md Troubleshoots module import errors by performing a clean uninstall, purging the pip cache, and reinstalling AgentMap. It also includes a command to verify the installation integrity. ```bash # Clean installation pip uninstall agentmap pip cache purge pip install agentmap # Verify installation agentmap diagnose ``` -------------------------------- ### Clone AgentMap Repository and Install Dependencies Source: https://github.com/jwwelbor/agentmap/blob/main/DEVELOPMENT.md Clones the AgentMap project from GitHub and installs development dependencies using Poetry. This sets up the local development environment for the project. ```bash # Clone and setup git clone https://github.com/jwwelbor/AgentMap.git cd AgentMap # Install dependencies poetry install --with dev # Setup pre-commit pre-commit install # Verify setup poetry run pytest ``` -------------------------------- ### Install Dependencies for AgentMap Docs Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/README.md Installs the necessary Node.js dependencies for the Docusaurus documentation site. This command should be run from the 'docs-docusaurus' directory. ```bash cd docs-docusaurus npm install ``` -------------------------------- ### Run and Compile Workflow Commands (Bash) Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/getting-started/installation.md Commands to execute and prepare the AgentMap workflow for deployment. 'agentmap run' tests the specified graph with given input state, while 'agentmap compile' prepares the workflow for production. ```bash # Test the workflow agentmap run --graph SmartBot --state '{"user_query": "What is machine learning?"}' # Compile for production agentmap compile --graph SmartBot ``` -------------------------------- ### AgentMap CLI for Development and Testing Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/deployment/index.md This example shows the steps to install AgentMap, create a simple workflow CSV file, and run it using the CLI. This is a common pattern for local development and testing workflows. ```bash # Install AgentMap pip install agentmap # Create a simple workflow echo "TestGraph,start,InputAgent,Get input,input,result" > test.csv # Run immediately agentmap run --graph TestGraph --csv test.csv --state '{"input": "hello"}' ``` -------------------------------- ### Verify Development Setup Source: https://github.com/jwwelbor/agentmap/blob/main/CONTRIBUTING.md Verifies the development environment setup by running tests and checking code quality. This ensures the environment is configured correctly. Requires pytest and flake8/black to be installed. ```bash # Run tests poetry run pytest # Check code quality poetry run flake8 src/ tests/ poetry run black --check src/ tests/ ``` -------------------------------- ### Basic AgentMap Configuration (YAML) Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/getting-started/installation.md Defines core application settings for logging and execution tracking. Ensures proper logging to a specified file path and level, and enables tracking of agent execution outputs and timing. ```yaml logging: file_path: "/var/log/agentmap/app.log" level: INFO execution: tracking: enabled: true track_outputs: true track_timing: true performance: connection_pooling: true cache_enabled: true max_concurrent_requests: 10 ``` -------------------------------- ### Docker Deployment for AgentMap (Dockerfile) Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/getting-started/installation.md This Dockerfile sets up a Python 3.11 environment, installs dependencies, copies the application code, exposes port 8000, and defines the command to run the AgentMap API server. Suitable for containerized deployments. ```dockerfile FROM python:3.11-slim WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY . . EXPOSE 8000 CMD ["agentmap", "serve", "--host", "0.0.0.0", "--port", "8000"] ``` -------------------------------- ### Running and Accessing FastAPI Service Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/deployment/02-fastapi-standalone.md These bash commands illustrate how to install necessary dependencies, start the FastAPI service, and access its API documentation. It includes installing the agentmap[fastapi] package and using Uvicorn to run the application, providing endpoints for Swagger UI, ReDoc, and OpenAPI JSON. ```bash # Install FastAPI dependencies pip install agentmap[fastapi] # Start the service python main.py # Or use uvicorn directly uvicorn main:app --host 0.0.0.0 --port 8000 --reload ``` -------------------------------- ### Production AgentMap YAML Configuration Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/getting-started/installation.md Configures AgentMap for a production environment, specifying separate CSV and storage configuration paths, advanced routing with cost optimization, and enabling LangSmith for monitoring. ```yaml # Production-ready configuration csv_path: "workflows/production.csv" storage_config_path: "agentmap_storage.yaml" # Advanced routing with cost optimization routing: enabled: true routing_matrix: anthropic: low: "claude-3-haiku-20240307" medium: "claude-3-5-sonnet-20241022" high: "claude-3-opus-20240229" openai: low: "gpt-3.5-turbo" medium: "gpt-4-turbo" high: "gpt-4" cost_optimization: enabled: true max_cost_tier: "high" # LangSmith monitoring tracing: enabled: true mode: "langsmith" project: "production-workflows" langsmith_api_key: "env:LANGSMITH_API_KEY" ``` -------------------------------- ### Basic FastAPI Service Setup Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/deployment/02-fastapi-standalone.md This Python code snippet demonstrates the basic setup for an AgentMap FastAPI service. It initializes the AgentMapAPI with workflow definitions and runs the service using Uvicorn. This serves as a starting point for creating a web API for AgentMap workflows. ```python # main.py from agentmap.services.fastapi import AgentMapAPI # Create standalone service app = AgentMapAPI( csv_file="workflows.csv", title="My Workflow API", description="AgentMap workflows exposed as HTTP API", version="1.0.0" ) if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000) ``` -------------------------------- ### Install and Configure Poetry and Pre-commit Hooks Source: https://github.com/jwwelbor/agentmap/blob/main/DEVELOPMENT.md Installs Poetry, a dependency manager for Python, and sets up pre-commit hooks for maintaining code quality. Poetry is recommended for managing project dependencies and virtual environments. Pre-commit hooks automate checks before each commit. ```bash # Python 3.11+ python --version # Poetry (recommended) curl -sSL https://install.python-poetry.org | python3 - # Pre-commit hooks pip install pre-commit pre-commit install ``` -------------------------------- ### Basic AgentMap YAML Configuration Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/getting-started/installation.md Defines a basic AgentMap configuration file (`agentmap_config.yaml`) specifying the CSV path, autocompile setting, and a single LLM provider with its API key and model details. ```yaml # Basic configuration csv_path: "workflows/main.csv" autocompile: true # Single LLM provider llm: openai: api_key: "env:OPENAI_API_KEY" model: "gpt-4-turbo" temperature: 0.7 ``` -------------------------------- ### Configure API Keys in .env File Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/getting-started/installation.md Creates a `.env` file to persistently store API keys for LLM providers and monitoring services like LangSmith. This is useful for managing credentials across sessions. ```bash # OpenAI OPENAI_API_KEY=sk-your-openai-key-here # Anthropic ANTHROPIC_API_KEY=sk-ant-your-anthropic-key-here # Google GOOGLE_API_KEY=your-google-api-key-here # Optional: LangSmith for monitoring LANGSMITH_API_KEY=your-langsmith-key-here LANGCHAIN_PROJECT="your-project-name" ``` -------------------------------- ### Multi-Provider AgentMap YAML Configuration Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/getting-started/installation.md Sets up AgentMap to use multiple LLM providers (OpenAI, Anthropic, Google) with intelligent routing based on cost and capability tiers. Includes memory configuration for stateful conversations. ```yaml # Multi-provider setup with intelligent routing csv_path: "workflows/main.csv" autocompile: true # Multiple LLM providers llm: openai: api_key: "env:OPENAI_API_KEY" model: "gpt-4-turbo" temperature: 0.7 anthropic: api_key: "env:ANTHROPIC_API_KEY" model: "claude-3-5-sonnet-20241022" temperature: 0.7 google: api_key: "env:GOOGLE_API_KEY" model: "gemini-1.5-pro" temperature: 0.7 # Intelligent routing routing: enabled: true cost_optimization: enabled: true prefer_cost_effective: true routing_matrix: anthropic: low: "claude-3-haiku-20240307" medium: "claude-3-5-sonnet-20241022" high: "claude-3-opus-20240229" openai: low: "gpt-3.5-turbo" medium: "gpt-4-turbo" high: "gpt-4" google: low: "gemini-1.5-flash" medium: "gemini-1.5-pro" high: "gemini-1.5-pro" # Memory for stateful conversations memory: enabled: true default_type: "buffer_window" buffer_window_size: 5 ``` -------------------------------- ### Scaffold Agent Command (Bash) Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/getting-started/installation.md Generates agent code based on a defined workflow graph. This command automatically detects required services (LLM, storage) and creates corresponding Python files for each agent. ```bash # Scaffold agents with automatic service detection agentmap scaffold --graph SmartBot ``` -------------------------------- ### AgentMap Quick Start CLI Usage (Bash) Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/configuration/examples.md Command-line instructions for running a basic AgentMap workflow after setting up the minimal configuration and environment variables. It demonstrates saving configuration, setting the API key, and executing a graph with initial state. ```bash # 1. Save the configuration files # 2. Set your OpenAI API key in .env # 3. Run your first workflow agentmap run --graph HelloWorld --state '{"input": "Hello, AgentMap!"}' ``` -------------------------------- ### Run Example Script (Bash) Source: https://github.com/jwwelbor/agentmap/blob/main/examples/host_integration/README.md Executes the main Python script that demonstrates the AgentMap host integration. This command navigates to the example directory and runs the integration script. ```bash cd examples/host_integration python integration_example.py ``` -------------------------------- ### Generated Data Analyzer Agent (Python) Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/getting-started/installation.md Example of a Python agent generated by AgentMap scaffolding. This agent, 'DataAnalyzerAgent', inherits from BaseAgent and includes capabilities for LLM and storage services, demonstrating how to integrate and use these services within an agent's process method. ```python # Generated: data_analyzer_agent.py from agentmap.agents.base_agent import BaseAgent from agentmap.services.protocols import LLMCapableAgent, StorageCapableAgent from typing import Dict, Any class DataAnalyzerAgent(BaseAgent, LLMCapableAgent, StorageCapableAgent): """ Analyze this query: {user_query} with LLM and storage capabilities Available Services: - self.llm_service: LLM service for calling language models - self.storage_service: Generic storage service (supports all storage types) """ def process(self, inputs: Dict[str, Any]) -> Any: user_query_value = inputs.get("user_query") # LLM SERVICE: (ready to customize) if hasattr(self, 'llm_service') and self.llm_service: response = self.llm_service.call_llm( provider="openai", # or "anthropic", "google" messages=[{"role": "user", "content": user_query_value}], model="gpt-4" ) analysis_result = response.get("content") # STORAGE SERVICE: (ready to customize) if hasattr(self, 'storage_service') and self.storage_service: # Save analysis for future reference self.storage_service.write("json", "query_analysis.json", { "query": user_query_value, "analysis": analysis_result }) return analysis_result ``` -------------------------------- ### Mock Factory for Test Utilities Source: https://github.com/jwwelbor/agentmap/blob/main/DEVELOPMENT.md Provides utility classes for creating mock objects used in testing. The `MockFactory` includes methods to create mock services and DI containers, simplifying the setup of test environments. ```python # tests/utils/mock_factory.py class MockFactory: @staticmethod def create_mock_service(): mock = Mock() mock.method.return_value = {"success": True} return mock @staticmethod def create_mock_di_container(): container = Mock() container.service.return_value = MockFactory.create_mock_service() return container ``` -------------------------------- ### Set AI Provider API Keys Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/getting-started/quick-start.md Sets environment variables for your chosen AI provider's API key. Supports OpenAI, Anthropic, and Google. Ensure you replace 'your-api-key-here' with your actual key. ```bash # Option A: OpenAI (recommended for beginners) export OPENAI_API_KEY="your-api-key-here" # Option B: Anthropic (Claude) export ANTHROPIC_API_KEY="your-api-key-here" # Option C: Google (Gemini) export GOOGLE_API_KEY="your-api-key-here" ``` -------------------------------- ### Conventional Commit Message Examples Source: https://github.com/jwwelbor/agentmap/blob/main/README_for_contributors.md Examples illustrating the conventional commit message format for various types of changes. ```git feat: add new vector storage agent fix: resolve memory leak in graph execution docs: update installation instructions test: add coverage for CSV parsing ``` -------------------------------- ### Create AgentMap Workflow CSV Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/getting-started/quick-start.md Defines a simple 'Hello World' workflow for AgentMap using CSV format. This workflow takes a name as input and greets the user. ```csv graph_name,node_name,agent_type,next_node,on_failure,prompt,input_fields,output_field HelloWorld,Start,input,PrintResult,HandleError,"Hello! What is your name?",,name HelloWorld,PrintResult,echo,,,,"Hello {name}. Welcome to AgentMap!",name,result HelloWorld,HandleError,echo,,,Error occurred ``` -------------------------------- ### Python Protocol Discovery in Application Bootstrap Source: https://github.com/jwwelbor/agentmap/blob/main/examples/host_integration/host_protocol_example.txt Demonstrates the protocol discovery process within `ApplicationBootstrapService.bootstrap_application()`. This involves checking host application support, getting protocol folders, scanning for Protocol classes in Python files, and registering discovered protocols with the `HostServiceRegistry`. The output is a print statement detailing the flow. ```Python def demonstrate_protocol_discovery(): """ This demonstrates what happens during ApplicationBootstrapService.bootstrap_application() """ # When bootstrap_application() is called, it will: # 1. Check if host application support is enabled # if app_config.is_host_application_enabled(): # 2. Get configured protocol folders # protocol_folders = app_config.get_host_protocol_folders() # e.g., [Path("host_services/protocols"), Path("custom_protocols")] # 3. Scan each folder for Python files containing Protocol classes # For each .py file in the folders: # - Import the module dynamically # - Find all classes that: # * End with 'Protocol' or contain 'Protocol' in the name # * Are defined in that module (not imported) # * Look like Protocol classes (inherit from Protocol, have abstract methods, etc.) # 4. Register discovered protocols with HostServiceRegistry # For each discovered protocol: # - Generate a snake_case name (DatabaseServiceProtocol -> database_service) # - Register as a "discovered_protocol" with metadata # - This creates a placeholder that can be filled with an implementation later # 5. Log summary of discovered protocols # The host application can then query what protocols were discovered # and register implementations for them print(""" Protocol Discovery Flow: 1. ApplicationBootstrapService.bootstrap_application() 2. ├─> discover_and_register_host_protocols() 3. │ ├─> Check if host support enabled 4. │ ├─> Get protocol folders from config 5. │ ├─> _discover_protocol_classes(folders) 6. │ │ ├─> Scan each folder for .py files 7. │ │ ├─> Import modules dynamically 8. │ │ ├─> Find Protocol classes 9. │ │ └─> Return [(name, class), ...] 10.│ └─> _register_discovered_protocols(protocols) 11.│ ├─> Register each with HostServiceRegistry 12.│ └─> Log discovered protocols summary 13.└─> Continue with rest of bootstrap """) if __name__ == "__main__": # This example shows the complete flow demonstrate_protocol_discovery() print("\n" + "="*60 + "\n") ``` -------------------------------- ### Resolving Poetry Installation Issues Source: https://github.com/jwwelbor/agentmap/blob/main/README_for_contributors.md Commands to address common issues encountered during Poetry installation, such as the command not being found or dependency conflicts. ```bash # If Poetry command not found export PATH="$HOME/.local/bin:$PATH" # If dependencies conflict poetry lock --no-update poetry install ``` -------------------------------- ### Get AgentMap Cache Statistics (curl) Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/deployment/06-http-api-reference.md Example using curl to get cache statistics from the AgentMap API. The request must include the `X-API-Key` header. ```bash curl -X GET "http://127.0.0.1:8000/admin/cache" \ -H "X-API-Key: your-api-key" ``` -------------------------------- ### Setting up AgentMap Development Environment Source: https://github.com/jwwelbor/agentmap/blob/main/PROJECT_RULES.md This snippet details the steps required to clone the AgentMap repository, install development dependencies using Poetry, run tests, and format the code using Black and isort. ```bash # Clone and setup git clone https://github.com/jwwelbor/AgentMap.git cd AgentMap # Install dependencies poetry install --with dev # Run tests poetry run pytest # Format code poetry run black src/ tests/ poetry run isort src/ tests/ ``` -------------------------------- ### Configuration Management Examples Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/deployment/04-cli-commands.md Demonstrates how to manage AgentMap configurations, including viewing the current settings, running workflows with custom configuration files, and initializing storage configuration for cloud-based solutions. ```bash # View current configuration agentmap diagnose # Expected output: # 🔍 AgentMap System Diagnosis # ✅ Configuration: Valid # ✅ CSV Path: ./workflows/ # ✅ Custom Agents: ./custom_agents/ # ✅ Storage: Local file system # ✅ Dependencies: All available # Use custom config file agentmap run --config ./configs/production.yaml --graph ProductionFlow # Initialize storage configuration agentmap storage-config --init # Expected output: # ✅ Storage configuration initialized # ✅ Created: agentmap_storage_config.yaml # ℹ️ Edit the file to configure cloud storage ``` -------------------------------- ### Install AgentMap with All Features Source: https://github.com/jwwelbor/agentmap/blob/main/README.md Installs AgentMap with all available features and dependencies, including LLM support and all storage integrations. This provides the most comprehensive setup for complex workflow development. ```bash pip install "agentmap[all]" ``` -------------------------------- ### AgentMap Runtime API Initialization Examples (Python) Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/reference/api.md Provides examples of initializing the AgentMap runtime API with different configurations. It demonstrates basic initialization, initialization with a custom configuration file, and forcing a refresh of the provider cache. These examples are crucial for setting up the AgentMap environment correctly. ```python from agentmap import runtime_api # Basic initialization runtime_api.ensure_initialized() # Initialize with custom config runtime_api.ensure_initialized(config_file="./config/production.yaml") # Force refresh of provider cache runtime_api.ensure_initialized(refresh=True) ``` -------------------------------- ### GET /dashboard/metrics Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/deployment/03-fastapi-integration.md Retrieves real-time metrics for the dashboard. Requires an AnalyticsService. ```APIDOC ## GET /dashboard/metrics ### Description Retrieves real-time metrics for the dashboard. ### Method GET ### Endpoint /dashboard/metrics ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **metrics** (dict) - Real-time analytics metrics. #### Response Example ```json { "active_users": 150, "pending_tasks": 25, "success_rate": 0.95 } ``` ``` -------------------------------- ### Setup Directory Structure (Bash) Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/learning/04-orchestration.md A bash command to create a nested directory structure for the agentmap-learning project, including a 'data' subdirectory. ```bash mkdir -p agentmap-learning/data cd agentmap-learning ``` -------------------------------- ### Create Project and Data Directories Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/learning/01-basic-agents.md Creates a new directory for AgentMap learning projects and a subdirectory named 'data' to store CSV output files. This is a standard setup step for organizing workflow data. ```bash mkdir agentmap-learning cd agentmap-learning mkdir data ``` -------------------------------- ### Build AgentMap Docs for Production Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/README.md Builds a production-ready version of the AgentMap Docusaurus site, optimized for deployment. This command is typically run before deploying the site. ```bash npm run build ``` -------------------------------- ### HTTP GET Request for System Metrics Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/deployment/02-fastapi-standalone.md An HTTP GET request to the /metrics endpoint to retrieve system-wide performance metrics, including uptime, execution counts, error rates, and workflow-specific statistics. Includes an example JSON response. ```http GET /metrics ``` -------------------------------- ### HTTP GET Request to List Available Workflows Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/deployment/02-fastapi-standalone.md Shows an HTTP GET request to the /workflows endpoint to retrieve a list of all available workflows, including their names, descriptions, node counts, and estimated execution times. Includes an example JSON response. ```http GET /workflows ``` -------------------------------- ### Service Configuration Examples (Python) Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/reference/services/index.md Demonstrates how to configure AgentMap services using environment variables and a YAML configuration file. This includes settings for LLM providers, storage, and execution tracking. ```python # Environment variables AGENTMAP_LLM_OPENAI_API_KEY=your_api_key AGENTMAP_LLM_ANTHROPIC_API_KEY=your_api_key AGENTMAP_STORAGE_CSV_PATH=./data AGENTMAP_EXECUTION_TRACKING_ENABLED=true # Configuration file (agentmap.yaml) llm: default_provider: anthropic providers: openai: model: gpt-4 temperature: 0.7 anthropic: model: claude-3-5-sonnet-20241022 temperature: 0.7 storage: csv: default_provider: local providers: local: base_path: ./data execution: tracking: enabled: true detail_level: normal ``` -------------------------------- ### Validate YAML Configuration Syntax Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/configuration/troubleshooting.md This snippet demonstrates how to validate YAML configuration files using Python. It checks for basic syntax correctness, which is crucial for AgentMap's configuration loading. Ensure the `PyYAML` library is installed (`pip install PyYAML`). ```bash python -c "import yaml; yaml.safe_load(open('agentmap_config.yaml'))" ``` -------------------------------- ### Run AgentMap Workflow Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/getting-started/quick-start.md Executes an AgentMap workflow defined in a CSV file. It shows both the new simplified syntax and the traditional syntax, along with how to override the graph name. ```bash # ✨ New Simplified Syntax (Recommended): agentmap run --csv hello_world.csv # Traditional Syntax (Still Supported): agentmap run --csv hello_world.csv --graph HelloWorld # Custom Graph Names: # Override graph name using :: syntax agentmap run --csv hello_world.csv::MyCustomBot ``` -------------------------------- ### Workflow Storage Context Example (CSV) Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/configuration/storage-config.md An example demonstrating how to define workflow storage contexts using CSV format. This maps graph names, node names, context details, agent types, input fields, and output fields for data flow. ```csv graph_name,node_name,context,agent_type,input_fields,output_field DataFlow,LoadUsers,"{'collection': 'users', 'format': 'records'}",csv_reader,user_query,users DataFlow,ProcessUsers,"{'collection': 'processed_users'}",json_writer,processed_data,result ``` -------------------------------- ### Verify API Key (Bash & Python) Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/getting-started/installation.md Provides methods to verify if an API key is correctly set and functional for services like OpenAI. It includes checking the environment variable and running a direct Python command to test the API connection. ```bash # Verify key is set echo $OPENAI_API_KEY # Test key directly python -c "import openai; client = openai.OpenAI(); print('API key works!')" ``` -------------------------------- ### Get AgentMap Version Information (curl) Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/deployment/06-http-api-reference.md Example using curl to fetch AgentMap version information. This request is unauthenticated. ```bash curl -X GET "http://127.0.0.1:8000/admin/version" ``` -------------------------------- ### Clone AgentMap Repository Source: https://github.com/jwwelbor/agentmap/blob/main/CONTRIBUTING.md Clones the AgentMap repository to your local machine. This is the first step to start contributing to the project. Requires Git to be installed. ```bash git clone https://github.com/YOUR_USERNAME/AgentMap.git cd AgentMap ``` -------------------------------- ### Activating Poetry Environment Source: https://github.com/jwwelbor/agentmap/blob/main/README_for_contributors.md Command to activate the virtual environment managed by Poetry, ensuring the correct interpreter and installed packages are used. ```bash poetry shell ``` -------------------------------- ### Business Goals AI Prompt Example Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/learning/01-basic-agents.md An example of a modified LLMAgent prompt designed to analyze a goal from a business perspective. It requests an analysis of market potential, required resources, and success metrics. ```string You are a business advisor. Analyze this goal for: 1) Market potential 2) Required resources 3) Success metrics. Goal: {goal} ``` -------------------------------- ### HTTP GET Request to Retrieve Workflow Details Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/deployment/02-fastapi-standalone.md Illustrates an HTTP GET request to the /workflows/{workflow_name} endpoint to fetch detailed information about a specific workflow, including its nodes, agent types, required inputs, outputs, and execution statistics. Provides an example JSON response. ```http GET /workflows/{workflow_name} ``` -------------------------------- ### Troubleshoot Missing LLM Providers Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/getting-started/quick-start.md Diagnoses and resolves the 'No LLM providers available' error by checking and setting the API key environment variable. ```bash # Check if your key is set echo $OPENAI_API_KEY # If empty, set it properly: export OPENAI_API_KEY="your-actual-key-here" ``` -------------------------------- ### Fix AgentMap Memory Type Configuration (YAML) Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/configuration/troubleshooting.md Shows how to configure the 'memory' settings in AgentMap's YAML. The incorrect example uses an invalid memory type 'invalid_buffer'. The correct example specifies a valid 'default_type' from the available options: 'buffer', 'buffer_window', 'summary', 'token_buffer'. ```yaml # ❌ Invalid memory type memory: default_type: "invalid_buffer" # ✅ Valid memory types memory: default_type: "buffer" # buffer, buffer_window, summary, token_buffer ``` -------------------------------- ### Python Configuration Management Example Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/reference/services/service-reference.md Illustrates how to retrieve application configuration settings, such as file paths and LLM configurations, using the configuration service. ```python # Get configuration config = container.app_config_service() csv_path = config.get_csv_path() llm_config = config.get_llm_config("openai") ``` -------------------------------- ### Fix AgentMap Routing Matrix Format (YAML) Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/configuration/troubleshooting.md Demonstrates the correct format for the 'routing_matrix' in YAML configuration files. The incorrect example shows a missing complexity level for the 'openai' provider, while the correct example includes 'low', 'medium', and 'high' complexity levels with their corresponding model names. ```yaml # ❌ Incorrect routing matrix routing_matrix: openai: "gpt-4" # Missing complexity levels # ✅ Correct routing matrix routing_matrix: openai: low: "gpt-3.5-turbo" medium: "gpt-4-turbo" high: "gpt-4" ``` -------------------------------- ### Create Working Directory Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/learning/05-human-summary.md Command to create a working directory for the human-AI collaboration project, including a subdirectory for data. ```bash mkdir -p human-ai-collaboration/data cd human-ai-collaboration ``` -------------------------------- ### AgentMap Configuration Loading Examples Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/deployment/04-cli-commands.md Demonstrates how AgentMap loads configuration files with explicit flags, auto-discovery from the current directory, and system defaults. It also shows logging output for configuration source identification. ```bash agentmap run --config /path/to/custom.yaml # If agentmap_config.yaml exists in current directory, automatically used agentmap run # If no config file found, uses built-in defaults agentmap run [2024-08-06 10:30:15] INFO: Using configuration from: explicit config: /path/to/config.yaml [2024-08-06 10:30:15] INFO: Using configuration from: auto-discovered: /current/dir/agentmap_config.yaml [2024-08-06 10:30:15] INFO: Using configuration from: system defaults ``` -------------------------------- ### Test a Custom Agent Source: https://github.com/jwwelbor/agentmap/blob/main/README_for_contributors.md Example Python code for writing unit tests for a custom agent, ensuring its process method returns the expected output. ```python # tests/agents/test_my_custom_agent.py def test_my_custom_agent(): agent = MyCustomAgent() result = agent.process({"input": "test"}) assert result["result"] == "processed" ``` -------------------------------- ### Validate AgentMap Task Types Configuration (YAML) Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/configuration/troubleshooting.md Illustrates the correct structure for defining 'task_types' in AgentMap's YAML configuration. The incorrect example shows an empty definition for the 'general' task type, missing essential fields. The correct example includes 'provider_preference' and 'default_complexity' for the 'general' task type. ```yaml # ❌ Missing required fields task_types: general: {} # ✅ Complete task type definition task_types: general: provider_preference: ["openai"] default_complexity: "medium" ``` -------------------------------- ### Run Tests (Bash) Source: https://github.com/jwwelbor/agentmap/blob/main/examples/host_integration/README.md Executes the test suites for verifying the host integration. Provides options for quick verification or running a comprehensive test suite. ```bash # Quick verification python test_basic_integration.py # Full test suite python test_host_integration.py ``` -------------------------------- ### Get AgentMap System Diagnostics (curl) Source: https://github.com/jwwelbor/agentmap/blob/main/docs-docusaurus/docs/deployment/06-http-api-reference.md Example using curl to fetch system diagnostics from the AgentMap API. This requires including an `X-API-Key` header for authentication. ```bash curl -X GET "http://127.0.0.1:8000/admin/diagnostics" \ -H "X-API-Key: your-api-key" ``` -------------------------------- ### Python Unit Test Structure Example Source: https://github.com/jwwelbor/agentmap/blob/main/PROJECT_RULES.md Illustrates a basic structure for writing unit tests in Python using pytest, including setup, action, and assertion phases. ```python import pytest from unittest.mock import Mock, patch class TestGraphBuilderService: def test_build_graph_success(self, mock_di_container): # Arrange service = GraphBuilderService(mock_di_container) # Act result = service.build_graph("test_graph") # Assert assert result is not None assert result.name == "test_graph" ``` -------------------------------- ### Example CLI Command Tests in Python Source: https://github.com/jwwelbor/agentmap/blob/main/tests/fresh_suite/cli/test_template.py.txt Demonstrates how to use the `SimpleCLITestBase` to test a specific CLI command ('your-command'). Includes tests for help output, basic functionality verification, and error handling by simulating a service failure. These tests rely on the setup provided by the base class. ```python class TestYourCommand(SimpleCLITestBase): """Test your-command CLI command.""" def test_help_output(self): """Test --help shows usage information.""" result = self.run_command(["your-command", "--help"]) self.assert_success(result) self.assertIn("your-command", result.stdout) def test_basic_functionality(self): """Test basic command functionality.""" result = self.run_command(["your-command", "--option", "value"]) self.assert_success(result) # Verify service was called self.mock_service.some_method.assert_called_once() def test_error_handling(self): """Test command error handling.""" # Configure service to fail self.mock_service.some_method.side_effect = Exception("Service error") result = self.run_command(["your-command"]) self.assert_failure(result) if __name__ == '__main__': unittest.main() ```