API Reference
Complete API documentation for the MARSYS framework with detailed class references, method signatures, and usage examples.
API Organization
The MARSYS API is organized into several key modules:
Orchestra API
High-level coordination API for multi-agent workflows
Agent Classes
Agent base classes and implementations
Model System
Language model configurations and providers
Topology API
Topology definition and pattern configurations
Execution API
Branch execution and step processing
Configuration API
Execution, status, and error handling configs
Memory API
Agent conversation history and memory management
Communication API
User interaction and communication channels
Validation API
Response validation and routing system
Tools API
Tool system for agent function execution
State API
State persistence and checkpointing
Rules API
Rules engine for execution constraints
Orchestra API
from marsys.coordination import Orchestraresult = await Orchestra.run(task, topology)
Agent Classes
from marsys.agents import Agent, BaseAgentagent = Agent(model_config, name="Helper")
Model System
from marsys.models import ModelConfigconfig = ModelConfig(type="api", provider="openrouter")
Topology API
from marsys.coordination.topology import Topologyfrom marsys.coordination.topology.patterns import PatternConfig
Core Classes
Coordination Layer
| Class | Module | Description |
|---|---|---|
| Orchestra | src.coordination | Main orchestration API |
| OrchestraResult | src.coordination.orchestra | Execution result object |
| ExecutionConfig | src.coordination.config | Execution configuration |
| StatusConfig | src.coordination.config | Status output configuration |
Agent Layer
| Class | Module | Description |
|---|---|---|
| BaseAgent | src.agents | Abstract base agent class |
| Agent | src.agents | Standard agent implementation |
| BrowserAgent | src.agents | Web automation agent |
| LearnableAgent | src.agents | Fine-tunable agent |
| AgentPool | src.agents.agent_pool | Agent pool for parallelism |
Model Layer
| Class | Module | Description |
|---|---|---|
| ModelConfig | src.models | Model configuration |
| BaseAPIModel | src.models | API model base class |
| BaseLocalModel | src.models | Unified local model interface |
| LocalProviderAdapter | src.models.adapters | Local adapter base class |
| HuggingFaceLLMAdapter | src.models.adapters | HuggingFace LLM adapter |
| VLLMAdapter | src.models.adapters | vLLM production adapter |
Topology Layer
| Class | Module | Description |
|---|---|---|
| Topology | src.coordination.topology | Topology definition |
| Node | src.coordination.topology | Graph node |
| Edge | src.coordination.topology | Graph edge |
| PatternConfig | src.coordination.topology.patterns | Pre-defined patterns |
Quick Reference
Creating Agents
from marsys.agents import Agentfrom marsys.models import ModelConfig# Basic agentagent = Agent(model_config=ModelConfig(type="api",name="anthropic/claude-haiku-4.5",provider="openrouter",max_tokens=12000),name="Assistant",goal="A helpful assistant")# Agent with toolsagent = Agent(model_config=config,name="Researcher",tools=[search_tool, analyze_tool])# Browser agentfrom marsys.agents import BrowserAgentbrowser = BrowserAgent(model_config=config,name="WebScraper",headless=True)
Defining Topologies
from marsys.coordination.topology import Topologyfrom marsys.coordination.topology.patterns import PatternConfig# Simple topologytopology = {"agents": ["A", "B", "C"],"flows": ["A -> B", "B -> C"]}# Pattern-basedtopology = PatternConfig.hub_and_spoke(hub="Coordinator",spokes=["Worker1", "Worker2"],parallel_spokes=True)# Object-basedtopology = Topology(nodes=[Node("A"), Node("B")],edges=[Edge("A", "B")],rules=[TimeoutRule(300)])
Running Workflows
from marsys.coordination import Orchestra# Simple executionresult = await Orchestra.run(task="Analyze this data",topology=topology)# With configurationfrom marsys.coordination.config import ExecutionConfigresult = await Orchestra.run(task=task,topology=topology,execution_config=ExecutionConfig(convergence_timeout=300,status=StatusConfig.from_verbosity(1)))# With state managementfrom marsys.coordination.state import StateManagerresult = await Orchestra.run(task=task,topology=topology,state_manager=StateManager(storage))
Method Signatures
Orchestra.run()
@classmethodasync def run(cls,task: Union[str, Dict[str, Any]],topology: Union[Dict, Topology, PatternConfig],agent_registry: Optional[AgentRegistry] = None,context: Optional[Dict[str, Any]] = None,execution_config: Optional[ExecutionConfig] = None,state_manager: Optional[StateManager] = None,max_steps: int = 100,allow_follow_ups: bool = False,**kwargs) -> OrchestraResult
Agent.run()
async def run(self,prompt: Union[str, Dict],context: Optional[Dict[str, Any]] = None,stream: bool = False,**kwargs) -> Message
AgentPool.acquire()
async def acquire(self,branch_id: str,timeout: Optional[float] = None) -> Agent
Response Formats
Agent Response Format
Sequential Invocation
{"next_action": "invoke_agent","action_input": "AgentName"}
Parallel Invocation
{"next_action": "parallel_invoke","agents": ["Agent1", "Agent2"],"agent_requests": {"Agent1": "Task 1","Agent2": "Task 2"}}
Tool Call
{"next_action": "call_tool","tool_calls": [{"id": "call_123","type": "function","function": {"name": "search","arguments": "{"query": "AI"}"}}]}
Final Response
{"next_action": "final_response","content": "Result..."}
OrchestraResult Structure
@dataclassclass OrchestraResult:success: boolfinal_response: Anybranch_results: List[BranchResult]total_steps: inttotal_duration: floatmetadata: Dict[str, Any]error: Optional[str] = None
Common Patterns
Pattern: Research Team
# Create specialized agentsresearcher = Agent(config, name="Researcher")analyst = Agent(config, name="Analyst")writer = Agent(config, name="Writer")# Define topologytopology = PatternConfig.hub_and_spoke(hub="Coordinator",spokes=["Researcher", "Analyst", "Writer"],parallel_spokes=True)# Executeresult = await Orchestra.run(task="Research AI trends",topology=topology)
Pattern: Error Recovery
topology = {"agents": ["User", "Processor", "ErrorHandler"],"flows": ["User -> Processor","Processor -> User", # Success"Processor -> ErrorHandler", # Error"ErrorHandler -> User"]}config = ErrorHandlingConfig(enable_error_routing=True,preserve_error_context=True)result = await Orchestra.run(task=task,topology=topology)
Pattern: Stateful Workflow
from marsys.coordination.state import StateManager, FileStorageBackend# Initialize state managementstorage = FileStorageBackend("./state")state_manager = StateManager(storage)# Run with stateresult = await Orchestra.run(task="Long-running analysis",topology=topology,state_manager=state_manager)# Pause if neededawait state_manager.pause_execution(session_id, state)# Resume laterstate = await state_manager.resume_execution(session_id)
Module Index
Core Modules
src.coordination- Orchestration and coordinationsrc.agents- Agent implementationssrc.models- Language model integrationssrc.environment- Tools and browser automationsrc.utils- Utility functions
Coordination Submodules
src.coordination.orchestra- Orchestra implementationsrc.coordination.topology- Topology systemsrc.coordination.execution- Execution enginesrc.coordination.validation- Response validationsrc.coordination.routing- Request routingsrc.coordination.state- State managementsrc.coordination.rules- Rules enginesrc.coordination.communication- User interaction
Agent Submodules
src.agents.agents- Core agent classessrc.agents.memory- Memory managementsrc.agents.agent_pool- Pool implementationsrc.agents.registry- Agent registrysrc.agents.browser_agent- Browser automation
Type Definitions
Common Types
from typing import Union, Dict, Any, List, Optionalfrom dataclasses import dataclassfrom enum import Enum# Task typeTask = Union[str, Dict[str, Any]]# Context typeContext = Dict[str, Any]# Configuration typesclass VerbosityLevel(IntEnum):QUIET = 0NORMAL = 1VERBOSE = 2class NodeType(Enum):USER = "user"AGENT = "agent"SYSTEM = "system"TOOL = "tool"class EdgeType(Enum):INVOKE = "invoke"NOTIFY = "notify"QUERY = "query"STREAM = "stream"class BranchStatus(Enum):PENDING = "pending"RUNNING = "running"WAITING = "waiting"COMPLETED = "completed"FAILED = "failed"
Error Handling
Exception Hierarchy
# Base exceptionclass MARSYSException(Exception):pass# Specific exceptionsclass AgentException(MARSYSException):passclass TopologyException(MARSYSException):passclass ValidationException(MARSYSException):passclass TimeoutException(MARSYSException):passclass ConfigurationException(MARSYSException):pass
Error Handling Example
try:result = await Orchestra.run(task, topology)except TimeoutException as e:logger.error(f"Execution timed out: {e}")# Handle timeoutexcept AgentException as e:logger.error(f"Agent error: {e}")# Handle agent errorexcept MARSYSException as e:logger.error(f"Framework error: {e}")# Handle general error
Next Steps
Dive deeper into specific APIs:
Orchestra API
High-level coordination API for multi-agent workflows
Agent Classes
Agent base classes and implementations
Model System
Language model configurations and providers
Topology API
Topology definition and pattern configurations
Execution API
Branch execution and step processing
Configuration API
Execution, status, and error handling configs
Memory API
Agent conversation history and memory management
Communication API
User interaction and communication channels
Validation API
Response validation and routing system
Tools API
Tool system for agent function execution
State API
State persistence and checkpointing
Rules API
Rules engine for execution constraints
API Stability
All documented APIs are in beta. We aim to maintain backward compatibility for all public methods and classes in future releases.