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

from marsys.coordination import Orchestra
result = await Orchestra.run(task, topology)

Agent Classes

from marsys.agents import Agent, BaseAgent
agent = Agent(model_config, name="Helper")

Model System

from marsys.models import ModelConfig
config = ModelConfig(type="api", provider="openrouter")

Topology API

from marsys.coordination.topology import Topology
from marsys.coordination.topology.patterns import PatternConfig

Core Classes

Coordination Layer

ClassModuleDescription
Orchestrasrc.coordinationMain orchestration API
OrchestraResultsrc.coordination.orchestraExecution result object
ExecutionConfigsrc.coordination.configExecution configuration
StatusConfigsrc.coordination.configStatus output configuration

Agent Layer

ClassModuleDescription
BaseAgentsrc.agentsAbstract base agent class
Agentsrc.agentsStandard agent implementation
BrowserAgentsrc.agentsWeb automation agent
LearnableAgentsrc.agentsFine-tunable agent
AgentPoolsrc.agents.agent_poolAgent pool for parallelism

Model Layer

ClassModuleDescription
ModelConfigsrc.modelsModel configuration
BaseAPIModelsrc.modelsAPI model base class
BaseLocalModelsrc.modelsUnified local model interface
LocalProviderAdaptersrc.models.adaptersLocal adapter base class
HuggingFaceLLMAdaptersrc.models.adaptersHuggingFace LLM adapter
VLLMAdaptersrc.models.adaptersvLLM production adapter

Topology Layer

ClassModuleDescription
Topologysrc.coordination.topologyTopology definition
Nodesrc.coordination.topologyGraph node
Edgesrc.coordination.topologyGraph edge
PatternConfigsrc.coordination.topology.patternsPre-defined patterns

Quick Reference

Creating Agents

agent_examples.py
from marsys.agents import Agent
from marsys.models import ModelConfig
# Basic agent
agent = 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 tools
agent = Agent(
model_config=config,
name="Researcher",
tools=[search_tool, analyze_tool]
)
# Browser agent
from marsys.agents import BrowserAgent
browser = BrowserAgent(
model_config=config,
name="WebScraper",
headless=True
)

Defining Topologies

topology_examples.py
from marsys.coordination.topology import Topology
from marsys.coordination.topology.patterns import PatternConfig
# Simple topology
topology = {
"agents": ["A", "B", "C"],
"flows": ["A -> B", "B -> C"]
}
# Pattern-based
topology = PatternConfig.hub_and_spoke(
hub="Coordinator",
spokes=["Worker1", "Worker2"],
parallel_spokes=True
)
# Object-based
topology = Topology(
nodes=[Node("A"), Node("B")],
edges=[Edge("A", "B")],
rules=[TimeoutRule(300)]
)

Running Workflows

workflow_examples.py
from marsys.coordination import Orchestra
# Simple execution
result = await Orchestra.run(
task="Analyze this data",
topology=topology
)
# With configuration
from marsys.coordination.config import ExecutionConfig
result = await Orchestra.run(
task=task,
topology=topology,
execution_config=ExecutionConfig(
convergence_timeout=300,
status=StatusConfig.from_verbosity(1)
)
)
# With state management
from marsys.coordination.state import StateManager
result = await Orchestra.run(
task=task,
topology=topology,
state_manager=StateManager(storage)
)

Method Signatures

Orchestra.run()

@classmethod
async 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

@dataclass
class OrchestraResult:
success: bool
final_response: Any
branch_results: List[BranchResult]
total_steps: int
total_duration: float
metadata: Dict[str, Any]
error: Optional[str] = None

Common Patterns

Pattern: Research Team

research_team.py
# Create specialized agents
researcher = Agent(config, name="Researcher")
analyst = Agent(config, name="Analyst")
writer = Agent(config, name="Writer")
# Define topology
topology = PatternConfig.hub_and_spoke(
hub="Coordinator",
spokes=["Researcher", "Analyst", "Writer"],
parallel_spokes=True
)
# Execute
result = await Orchestra.run(
task="Research AI trends",
topology=topology
)

Pattern: Error Recovery

error_recovery.py
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

stateful_workflow.py
from marsys.coordination.state import StateManager, FileStorageBackend
# Initialize state management
storage = FileStorageBackend("./state")
state_manager = StateManager(storage)
# Run with state
result = await Orchestra.run(
task="Long-running analysis",
topology=topology,
state_manager=state_manager
)
# Pause if needed
await state_manager.pause_execution(session_id, state)
# Resume later
state = await state_manager.resume_execution(session_id)

Module Index

Core Modules

  • src.coordination - Orchestration and coordination
  • src.agents - Agent implementations
  • src.models - Language model integrations
  • src.environment - Tools and browser automation
  • src.utils - Utility functions

Coordination Submodules

  • src.coordination.orchestra - Orchestra implementation
  • src.coordination.topology - Topology system
  • src.coordination.execution - Execution engine
  • src.coordination.validation - Response validation
  • src.coordination.routing - Request routing
  • src.coordination.state - State management
  • src.coordination.rules - Rules engine
  • src.coordination.communication - User interaction

Agent Submodules

  • src.agents.agents - Core agent classes
  • src.agents.memory - Memory management
  • src.agents.agent_pool - Pool implementation
  • src.agents.registry - Agent registry
  • src.agents.browser_agent - Browser automation

Type Definitions

Common Types

types.py
from typing import Union, Dict, Any, List, Optional
from dataclasses import dataclass
from enum import Enum
# Task type
Task = Union[str, Dict[str, Any]]
# Context type
Context = Dict[str, Any]
# Configuration types
class VerbosityLevel(IntEnum):
QUIET = 0
NORMAL = 1
VERBOSE = 2
class 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

exceptions.py
# Base exception
class MARSYSException(Exception):
pass
# Specific exceptions
class AgentException(MARSYSException):
pass
class TopologyException(MARSYSException):
pass
class ValidationException(MARSYSException):
pass
class TimeoutException(MARSYSException):
pass
class ConfigurationException(MARSYSException):
pass

Error Handling Example

error_handling.py
try:
result = await Orchestra.run(task, topology)
except TimeoutException as e:
logger.error(f"Execution timed out: {e}")
# Handle timeout
except AgentException as e:
logger.error(f"Agent error: {e}")
# Handle agent error
except MARSYSException as e:
logger.error(f"Framework error: {e}")
# Handle general error

Next Steps

Dive deeper into specific APIs:

API Stability

All documented APIs are in beta. We aim to maintain backward compatibility for all public methods and classes in future releases.