CLI Commands Reference
AgentMap provides a sophisticated command-line interface (CLI) built on a facade pattern architecture for deploying and managing workflows, with powerful scaffolding capabilities for custom agents and functions. The CLI is ideal for development, testing, automation scripts, and production deployments that don't require web API interfaces.
CLI Architecture Overviewâ
The AgentMap CLI follows a consistent facade pattern as defined in SPEC-DEP-001, ensuring clean separation between presentation layer and business logic.
Facade Pattern Implementationâ
All CLI commands use the runtime_api.py module as a unified facade to the underlying business logic:
# CLI commands follow this pattern
from agentmap.runtime_api import ensure_initialized, specific_function
from agentmap.deployment.cli.utils.cli_presenter import print_json, print_err, map_exception_to_exit_code
def command_function(args):
try:
# Ensure runtime is initialized
ensure_initialized(config_file=args.config)
# Use runtime facade for business logic
result = specific_function(args...)
# Use CLI presenter for consistent output
print_json(result)
except Exception as e:
print_err(str(e))
exit_code = map_exception_to_exit_code(e)
raise typer.Exit(code=exit_code)
Runtime API Functionsâ
The runtime_api.py serves as a facade to split runtime modules:
| Function Category | Functions | Commands Using |
|---|---|---|
| Initialization | ensure_initialized(), get_container() | Most commands |
| Workflow Operations | run_workflow(), resume_workflow(), validate_workflow() | run, resume, validate |
| Bundle Operations | scaffold_agents(), update_bundle() | scaffold, update-bundle |
| System Operations | diagnose_system(), get_config(), refresh_cache() | diagnose, config, refresh |
CLI Presenter Architectureâ
All commands use standardized utilities from cli_presenter.py:
print_json(): Consistent JSON output with custom encoder for AgentMap objectsprint_err(): Standardized stderr outputmap_exception_to_exit_code(): Maps runtime exceptions to process exit codes- Custom JSON Encoder: Handles datetime objects, dataclasses, and AgentMap-specific types
Commands NOT Using Facade Patternâ
Two commands implement business logic directly:
| Command | Module | Reason |
|---|---|---|
| auth | auth_command.py | Standalone authentication management |
| init-config | init_config_command.py | Simple file creation utility |
Complete Command Structureâ
All CLI commands are registered in main_cli.py and follow this structure:
src/agentmap/deployment/cli/
âââ main_cli.py # Entry point - registers all commands
âââ <command>_command.py # Individual command handlers
âââ utils/
â âââ cli_presenter.py # Output formatting and error handling
â âââ cli_utils.py # Common utilities (path resolution, etc.)
âââ auth_command.py # Authentication subcommands
âââ run_command.py # Workflow execution
âââ scaffold_command.py # Agent scaffolding
âââ validate_command.py # Validation commands
âââ diagnose_command.py # System diagnostics
âââ resume_command.py # Workflow resumption
âââ refresh_command.py # Cache management
âââ update_bundle_command.py # Bundle operations
Import Patternsâ
Commands follow consistent import patterns:
Facade-based commands:
from agentmap.runtime_api import ensure_initialized, specific_function
from agentmap.deployment.cli.utils.cli_presenter import print_json, print_err, map_exception_to_exit_code
Utility imports:
from agentmap.deployment.cli.utils.cli_utils import handle_command_error, resolve_csv_path
Error Handling Patternâ
All facade-based commands follow consistent error handling:
try:
result = runtime_function(args...)
if result.get("success", False):
print_json(result)
else:
print_err("Operation failed")
raise typer.Exit(code=1)
except typer.Exit:
raise # Preserve exit codes
except Exception as e:
print_err(str(e))
exit_code = map_exception_to_exit_code(e)
raise typer.Exit(code=exit_code)
Configuration Loadingâ
AgentMap uses a hierarchical configuration system with automatic discovery:
Configuration Precedence Orderâ
-
Explicit
--configflag (Highest Priority)agentmap run --config /path/to/custom.yaml -
agentmap_config.yamlin current directory (Auto-Discovered)# If agentmap_config.yaml exists in current directory, automatically used
agentmap run -
System defaults (Lowest Priority)
# If no config file found, uses built-in defaults
agentmap run
Configuration Discovery Loggingâ
AgentMap shows which configuration source is being used:
[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
Quick Start with Local Configâ
-
Copy configuration template to your working directory:
agentmap init-config -
Edit
agentmap_config.yamlas needed -
Run commands without specifying
--config:agentmap run --csv examples/lesson1.csv
Installationâ
pip install agentmap
Basic Commandsâ
Run a Graphâ
agentmap run --graph graph_name --state '{"input": "value"}'
Options:
--graph,-g: Name of the graph to run--state,-s: Initial state as JSON string--csv: Optional path to CSV file--autocompile,-a: Automatically compile the graph--config,-c: Path to custom config file
View Configurationâ
Note: The
configcommand is currently under development. Useagentmap diagnoseto view system configuration information.
agentmap diagnose
⨠Simplified Graph Naming Syntaxâ
AgentMap supports intelligent default graph naming that eliminates the need to specify graph names for simple workflows.
Smart Defaultsâ
CSV filename automatically becomes the graph name:
# Traditional approach
agentmap run --graph CustomerSupport --csv customer_support.csv --state '{"query": "help"}'
# ⨠New simplified approach
agentmap run --csv customer_support.csv --state '{"query": "help"}'
# Graph name is automatically "customer_support"
:: Override Syntaxâ
Specify custom graph names when needed:
# Override graph name for multi-graph CSV files
agentmap run --csv workflows.csv::ProductSupport --state '{"product": "AgentMap"}'
# Works with all commands
agentmap scaffold --csv complex_workflows.csv::SpecificGraph
agentmap validate --csv production.csv::MainFlow
HTTP API Integrationâ
URL encoding for web APIs:
# HTTP API endpoints support :: syntax with URL encoding
curl -X POST "http://localhost:8000/execution/workflow.csv%3A%3AGraphName" \
-H "Content-Type: application/json" \
-d '{"state": {"input": "value"}}'
# RESTful endpoints for default graph names
curl -X POST "http://localhost:8000/execution/customer_support.csv" \
-H "Content-Type: application/json" \
-d '{"state": {"query": "help"}}'
Migration Examplesâ
Side-by-side comparison:
| Traditional Syntax | New Simplified Syntax | Use Case |
|---|---|---|
--graph MyFlow --csv my_file.csv | --csv my_flow.csv | Single graph per file |
--graph Graph1 --csv multi.csv | --csv multi.csv::Graph1 | Multiple graphs per file |
--graph Test --csv complex.csv | --csv complex.csv::Test | Override default name |
Benefits:
- ⥠Faster Development: Less typing for common workflows
- đ Self-Documenting: File names clearly indicate purpose
- đ URL-Safe: Works seamlessly with HTTP APIs
- đ Backward Compatible: All existing workflows continue working
Scaffolding Commandsâ
AgentMap's service-aware scaffolding system is a sophisticated code generation feature that automatically creates custom agent classes and routing functions from CSV definitions. It analyzes CSV context to detect service requirements and generates complete, working code with automatic service integration.
Core Scaffolding Commandâ
agentmap scaffold [OPTIONS]
Options:
--graph,-g: Graph name to scaffold agents for (optional - defaults to all graphs)--csv: CSV path override (uses config default if not specified)--output,-o: Custom directory for agent output (overrides config)--functions,-f: Custom directory for function output (overrides config)--config,-c: Path to custom config file
Service-Aware Code Generationâ
The scaffolding system automatically detects service requirements from CSV context and generates agents with proper service integration:
Example CSV with Service Context:
GraphName,Node,Edge,Description,AgentType,Success_Next,Failure_Next,Input_Fields,Output_Field,Context
IntelligentWorkflow,ProcessData,,"Analyze data using LLM",DataAnalyzer,FormatOutput,HandleError,data|query,analysis,"{""services"": [""llm"", ""storage""]}"
Generated Agent with Service Integration:
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 data using LLM with storage and LLM capabilities
Node: ProcessData
Expected input fields: data, query
Expected output field: analysis
Available Services:
- self.llm_service: LLM service for calling language models
- self.storage_service: Generic storage service (supports all storage types)
"""
def __init__(self):
super().__init__()
# Service attributes (automatically injected during graph building)
self.llm_service: LLMServiceProtocol = None
self.storage_service: StorageServiceProtocol = None
def process(self, inputs: Dict[str, Any]) -> Any:
"""
Process the inputs and return the analysis result.
Args:
inputs (dict): Contains input values with keys: data, query
Returns:
The analysis result
"""
# Access input fields
data_value = inputs.get("data")
query_value = inputs.get("query")
# LLM SERVICE:
if hasattr(self, 'llm_service') and self.llm_service:
response = self.llm_service.call_llm(
provider="openai", # or "anthropic", "google"
messages=[{"role": "user", "content": query_value}],
model="gpt-4" # optional
)
analysis_result = response.get("content")
# STORAGE SERVICE:
if hasattr(self, 'storage_service') and self.storage_service:
# Save analysis for future reference
self.storage_service.write("json", "analysis_results.json", {
"query": query_value,
"analysis": analysis_result,
"timestamp": "2024-01-01T00:00:00Z"
})
return analysis_result
Supported Service Typesâ
The scaffolding system supports multiple service architectures and automatically chooses the appropriate approach:
Unified Storage Services:
"storage"- Generic storage service supporting all storage types (CSV, JSON, File, Vector, Memory)
Separate Service Protocols:
"llm"- Language model services (OpenAI, Anthropic, Google)"csv"- CSV file operations"json"- JSON file operations"file"- General file operations"vector"- Vector search and embeddings"memory"- In-memory data storage"node_registry"- Access to graph node metadata for dynamic routing
Service Context Configurationâ
Specify service requirements in your CSV using the Context field:
JSON Format:
Context
"{""services"": [""llm"", ""storage""]}"
"{""services"": [""llm"", ""vector"", ""memory""]}"
"{""services"": [""csv"", ""json""]}"
String Format:
Context
"services: llm|storage"
"services: vector|memory|llm"
Service Architecture Auto-Detectionâ
The system automatically chooses the appropriate service architecture:
Unified Architecture (when "storage" is requested):
class Agent(BaseAgent, StorageCapableAgent):
def __init__(self):
self.storage_service: StorageServiceProtocol = None
def process(self, inputs):
# Access any storage type through unified interface
data = self.storage_service.read("csv", "input.csv")
result = self.storage_service.write("json", "output.json", processed_data)
Separate Architecture (when specific types are requested):
class Agent(BaseAgent, CSVCapableAgent, VectorCapableAgent):
def __init__(self):
self.csv_service: Any = None # CSV storage service
self.vector_service: Any = None # Vector storage service
def process(self, inputs):
# Use specific service interfaces
csv_data = self.csv_service.read("data.csv")
similar_docs = self.vector_service.search(collection="docs", query="query")
Agent Registry Integrationâ
The scaffolding system integrates with AgentRegistryService to:
- Avoid conflicts: Only scaffolds agents that aren't already registered
- Smart detection: Checks both built-in and custom agent types
- Efficient workflow: Focuses on creating only needed custom agents
# Example output
$ agentmap scaffold --graph MyWorkflow
â
Scaffolded 3 agents/functions.
đ Service integration: 2 with services, 1 basic agents
đ Created files:
data_analyzer_agent.py
report_generator_agent.py
routing_function.py
# Skipped already registered agents
âšī¸ Skipped 2 built-in agents (InputAgent, OutputAgent)
Advanced Usage Examplesâ
Multi-Service Agent Scaffolding:
# CSV with complex service requirements
GraphName,Node,Context
AIWorkflow,ProcessData,"{""services"": [""llm"", ""vector"", ""storage"", ""memory""]}"
# Generated agent inherits multiple protocols
class ProcessDataAgent(BaseAgent, LLMCapableAgent, VectorCapableAgent, StorageCapableAgent, MemoryCapableAgent):
# Automatic service integration for all requested services
Custom Output Directories:
# Scaffold to custom directories
agentmap scaffold --output ./custom_agents --functions ./custom_functions
# Environment variable override
export AGENTMAP_CUSTOM_AGENTS_PATH="./my_agents"
export AGENTMAP_FUNCTIONS_PATH="./my_functions"
agentmap scaffold
Graph-Specific Scaffolding:
# Scaffold only agents for specific graph
agentmap scaffold --graph ProductionWorkflow
# Scaffold with custom CSV
agentmap scaffold --csv ./workflows/special_workflow.csv
Export and Compile Commandsâ
Note: The
exportandcompilecommands are currently under development and not yet available in the CLI. These features are planned for a future release. Currently, you can run workflows directly using theagentmap runcommand.
Validation Commandsâ
AgentMap provides workflow validation through the validate command:
# Validate a workflow
agentmap validate --csv workflow.csv
# Validate with custom configuration
agentmap validate --csv workflow.csv --config custom_config.yaml
Note: Additional validation commands (
validate-csv,validate-config,validate-all,validate-cache) are planned for future releases. Currently, use thevalidatecommand for workflow validation.
Diagnostic Commandsâ
Use the diagnose command to check system health and dependencies. For detailed information, see the Diagnostic Commands documentation.
# Check system health
agentmap diagnose
Resume Workflowsâ
Resume interrupted workflows with the resume command. For detailed information, see the Workflow Resume Commands documentation.
# Resume a workflow with approval
agentmap resume thread_12345 approve
# Resume with additional data
agentmap resume thread_12345 respond --data '{"user_response": "Yes, proceed"}'
Common Usage Patternsâ
Development Workflowâ
-
Create CSV workflow
# Create your workflow.csv file with your favorite editor
vim customer_workflow.csv -
Validate workflow structure
agentmap validate --csv customer_workflow.csv
# Expected output:
# â Workflow validation successful
# â Found 5 nodes in workflow
# â All required columns present -
Scaffold missing agents
agentmap scaffold --csv customer_workflow.csv
# Expected output:
# â Generated WeatherAgent in custom_agents/weather_agent.py
# â Generated PaymentAgent in custom_agents/payment_agent.py
# âšī¸ Edit generated files to implement your logic -
Implement custom agents
# Edit generated files in custom_agents/
code custom_agents/weather_agent.py -
Test workflow
agentmap run --graph CustomerWorkflow --csv customer_workflow.csv
# Expected output:
# â Graph execution completed successfully
# â Execution time: 2.34s
# â All 5 nodes executed successfully -
Deploy workflow (when ready for production)
# Workflows are executed directly - no compilation step needed
agentmap run --graph CustomerWorkflow --csv customer_workflow.csv
# Expected output:
# â Graph execution completed successfully
# â Execution time: 2.34s
# â Ready for production use via CLI or HTTP API
Configuration Managementâ
# 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
Debugging and Developmentâ
# Run with debug logging
agentmap run --graph TestFlow --log-level DEBUG
# Expected output:
# DEBUG: Loading graph definition from CSV
# DEBUG: Resolving agent dependencies
# DEBUG: [Node: start] Executing with inputs: {...}
# DEBUG: [Node: start] Completed in 0.123s
# â
Graph execution completed
# Run with detailed execution tracking
agentmap run --graph TestFlow --track-detailed
# Expected output:
# â
Graph execution completed
# đ Execution Summary:
# Total time: 2.45s
# Nodes executed: 4
# Success rate: 100%
# Run with custom configuration
agentmap run --graph TestFlow --config custom_config.yaml
# Expected output:
# âšī¸ Using configuration from: custom_config.yaml
# â
Graph execution completed
Environment Variablesâ
AgentMap respects several environment variables for configuration:
AGENTMAP_CONFIG_PATH: Default configuration file pathAGENTMAP_CSV_PATH: Default CSV file pathAGENTMAP_CUSTOM_AGENTS_PATH: Custom agents directoryAGENTMAP_FUNCTIONS_PATH: Functions directoryAGENTMAP_LOG_LEVEL: Logging level (DEBUG, INFO, WARNING, ERROR)
Error Handlingâ
Common CLI Errorsâ
- Graph not found: Verify graph name matches CSV graph_name column
- Missing agents: Run scaffold command to generate missing custom agents
- Configuration errors: Check config file syntax and required fields
- Permission errors: Ensure write access to output directories
Debugging Tipsâ
- Use
--log-level DEBUGfor verbose output - Verify CSV syntax with a CSV validator
- Check that custom agents are in the correct directory
- Ensure all required environment variables are set
Monitoring and Operationsâ
Health Checksâ
# Check system health
agentmap diagnose
# Expected output:
# đ AgentMap System Diagnosis
# â
Configuration: Valid
# â
Dependencies: All available
# â
Storage: Accessible
# â
Custom agents: 3 found
# â
Compiled graphs: 2 found
# Validate specific workflow
agentmap validate --csv production_workflow.csv
# Expected output:
# â
Workflow structure valid
# â
All agent types available
# â
Dependency chain complete
# â ī¸ Warning: Large prompt in node 'process_data'
Performance Monitoringâ
# Run with performance profiling
agentmap run --graph MyWorkflow --profile
# Expected output:
# â
Graph execution completed
# đ Performance Profile:
# Node 'validate_input': 0.045s
# Node 'process_data': 1.234s â ī¸ (slow)
# Node 'generate_output': 0.123s
# Total execution: 1.402s
# Monitor execution over time
agentmap run --graph MyWorkflow --monitor
# Expected output:
# đ Monitoring mode enabled
# â
Execution 1: 1.23s (success)
# â
Execution 2: 1.18s (success)
# â Execution 3: failed (error in process_data)
# đ Average: 1.21s, Success rate: 66.7%
Troubleshooting Commandsâ
# Inspect graph structure
agentmap inspect --graph MyWorkflow
# Expected output:
# đ Graph Structure: MyWorkflow
# Nodes: 5
# next_nodes: 4
# Entry points: 1 (start_node)
# Exit points: 1 (end_node)
#
# Flow diagram:
# start_node â validate_input â process_data â generate_output â end_node
# Check dependencies
agentmap validate-dependencies --graph MyWorkflow
# Expected output:
# â
All required agents available
# â
All custom functions found
# â ī¸ Warning: WeatherAgent uses deprecated API
# âšī¸ Suggestion: Update to use WeatherService v2
# Clear cache and rebuild
agentmap refresh
# Expected output:
# â
Cache cleared
# â
Bundle cache refreshed
# âšī¸ Ready for clean workflow execution
Advanced CLI Featuresâ
Batch Operationsâ
Note: Batch operations for multiple workflows are planned for a future release. Currently, validate and run workflows individually using the respective commands.
Integration with CI/CDâ
# Validate workflow in CI/CD pipeline
agentmap validate --csv workflow.csv
# Exit code 0 if valid, non-zero if validation fails
# Run workflow in CI/CD
agentmap run --csv workflow.csv --state '{"input": "test"}'
# Exit code 0 if successful, non-zero if execution fails
Output Formats and Loggingâ
JSON Output for Automationâ
# Get machine-readable output
agentmap run --graph MyWorkflow --format json
# Output:
# {
# "success": true,
# "execution_time": 1.234,
# "nodes_executed": 5,
# "result": {...},
# "errors": []
# }
# Structured validation output
agentmap validate --csv workflow.csv
# Output includes validation results and any warnings/errors
# Exit code 0 indicates validation success
Logging Configurationâ
# Set log level for detailed debugging
AGENTMAP_LOG_LEVEL=DEBUG agentmap run --graph MyWorkflow
# Log to file
agentmap run --graph MyWorkflow --log-file execution.log
# Structured logging for monitoring systems
agentmap run --graph MyWorkflow --log-format json
Security and Productionâ
Production Deploymentâ
For production deployment, you can use either:
- CLI deployment: Run workflows directly via
agentmap run - HTTP API deployment: Use
agentmap serveto start the HTTP API server
# Start HTTP API server for production
agentmap serve --host 0.0.0.0 --port 8000
# Or run workflows directly in production scripts
agentmap run --csv production_workflow.csv --config production_config.yaml
Related Documentationâ
đ Getting Startedâ
- Quick Start Guide: Build your first workflow in 5 minutes
- Understanding Workflows: Core workflow concepts and patterns
- CSV Schema Reference: Complete CSV workflow format specification
đ§ CLI Tools & Debuggingâ
- CLI Graph Inspector: Advanced graph analysis and debugging
- Interactive Playground: Test workflows in your browser
- Execution Tracking: Performance monitoring and debugging
đ¤ Agent Developmentâ
- Agent Types Reference: Available agent types and configurations
- Advanced Agent Types: Custom agent development
- Agent Development Contract: Agent interface requirements
đī¸ Advanced Operationsâ
- Service Injection Patterns: Dependency injection in agents
- Host Service Integration: Custom service integration
- Testing Patterns: Testing strategies for CLI workflows
đ Tutorials & Examplesâ
- Weather Bot Tutorial: Complete CLI workflow example
- Data Processing Pipeline: ETL workflow with CLI operations
- Example Workflows: Real-world CLI usage patterns