OpenMAS API Reference¶
This document provides a reference for the key classes and methods in the OpenMAS SDK.
Agent Module¶
BaseAgent¶
from openmas.agent import BaseAgent
class MyAgent(BaseAgent):
async def setup(self) -> None:
"""Set up the agent."""
pass
async def run(self) -> None:
"""Run the agent."""
pass
async def shutdown(self) -> None:
"""Shut down the agent."""
pass
Key methods:
- __init__(name=None, config=None, communicator_class=None, **kwargs)
: Initialize the agent
- setup()
: Set up the agent (called by start()
)
- run()
: Run the agent (called by start()
)
- shutdown()
: Shut down the agent (called by stop()
)
- start()
: Start the agent (calls setup()
then run()
)
- stop()
: Stop the agent (calls shutdown()
)
- set_communicator(communicator)
: Set the agent's communicator
- get_handler(method)
: Get a handler for the specified method
- register_handler(method, handler)
: Register a handler for the specified method
MCP Agents¶
from openmas.agent import McpAgent, McpServerAgent, McpClientAgent
# Base MCP agent
class MyMcpAgent(McpAgent):
pass
# MCP server agent
class MyServerAgent(McpServerAgent):
pass
# MCP client agent
class MyClientAgent(McpClientAgent):
pass
McpAgent¶
Key methods inherited from BaseAgent, plus:
- _discover_mcp_methods()
: Discover methods decorated with MCP decorators
- register_with_server(server)
: Register the agent's MCP methods with an MCP server
McpServerAgent¶
Key methods:
- setup_communicator()
: Set up the MCP communicator (SSE or stdio)
- start_server()
: Start the MCP server
- stop_server()
: Stop the MCP server
McpClientAgent¶
Key methods:
- connect_to_service(service_name, host, port)
: Connect to an MCP service
- disconnect_from_service(service_name)
: Disconnect from an MCP service
- list_tools(service_name)
: List tools available on a service
- call_tool(service_name, tool_name, params)
: Call a tool on a service
MCP Decorators¶
from openmas.agent import mcp_tool, mcp_prompt, mcp_resource
class MyAgent(McpAgent):
@mcp_tool(name="my_tool", description="My tool")
async def my_tool(self, param1: str) -> dict:
"""Tool documentation."""
return {"result": param1}
@mcp_prompt(name="my_prompt", description="My prompt")
async def my_prompt(self, context: str) -> str:
"""Prompt documentation."""
return f"Context: {context}\n\nResponse:"
@mcp_resource(uri="/resource", name="my_resource", mime_type="application/json")
async def my_resource(self) -> bytes:
"""Resource documentation."""
return b'{"key": "value"}'
Communication Module¶
Base Communicator¶
HTTP Communicator¶
from openmas.communication import HttpCommunicator
communicator = HttpCommunicator(
agent_name="my-agent",
service_urls={"other-service": "http://localhost:8000"},
http_port=8001
)
Key methods:
- start()
: Start the communicator
- stop()
: Stop the communicator
- register_handler(method, handler)
: Register a handler for the specified method
- send_request(target_service, method, params)
: Send a request to a service
- send_notification(target_service, method, params)
: Send a notification to a service
MCP Communicators¶
from openmas.communication.mcp import McpSseCommunicator, McpStdioCommunicator
# SSE-based MCP communicator (HTTP/SSE)
sse_communicator = McpSseCommunicator(
agent_name="my-agent",
service_urls={"mcp-service": "http://localhost:8000"},
server_mode=False,
http_port=8001
)
# Stdio-based MCP communicator (stdin/stdout)
stdio_communicator = McpStdioCommunicator(
agent_name="my-agent",
service_urls={},
server_mode=True
)
Key methods (both communicators):
- start()
: Start the communicator
- stop()
: Stop the communicator
- register_handler(method, handler)
: Register a handler for the specified method
- register_mcp_methods(agent)
: Register the agent's MCP methods with the server
gRPC Communicator¶
from openmas.communication.grpc import GrpcCommunicator
grpc_communicator = GrpcCommunicator(
agent_name="my-agent",
service_urls={"grpc-service": "localhost:50051"},
grpc_port=50052
)
MQTT Communicator¶
from openmas.communication.mqtt import MqttCommunicator
mqtt_communicator = MqttCommunicator(
agent_name="my-agent",
service_urls={},
broker_host="localhost",
broker_port=1883
)
Configuration Module¶
from openmas.config import load_config, AgentConfig
from pydantic import Field
# Load standard configuration
config = load_config(AgentConfig)
# Define custom configuration
class MyAgentConfig(AgentConfig):
api_key: str = Field(..., description="API key for external service")
model_name: str = Field("gpt-4", description="Model name to use")
# Load custom configuration
my_config = load_config(MyAgentConfig)
Key functions:
- load_config(config_class)
: Load configuration from environment, files, etc.
- find_project_root()
: Find the root directory of the OpenMAS project
AgentConfig¶
Key fields:
- name
: Agent name (default: "agent")
- log_level
: Logging level (default: "INFO")
- communicator_type
: Type of communicator (default: "http")
- service_urls
: Dictionary of service URLs (default: {})
- communicator_options
: Dictionary of options for the communicator (default: {})
Testing Module¶
import pytest
from openmas.testing import MockCommunicator, AgentTestHarness
from openmas.agent import BaseAgent
# Create a mock communicator
mock_communicator = MockCommunicator(agent_name="test-agent")
# Create a test harness
test_harness = AgentTestHarness(
agent_class=BaseAgent,
default_config={"name": "test-agent"}
)
MockCommunicator¶
Key methods:
- expect_request(target_service, method, params, response)
: Expect a request and return a response
- expect_request_exception(target_service, method, params, exception)
: Expect a request and raise an exception
- expect_notification(target_service, method, params)
: Expect a notification
- verify()
: Verify that all expectations were met
- trigger_handler(method, params)
: Trigger a handler for testing
AgentTestHarness¶
Key methods:
- create_agent(**kwargs)
: Create an agent instance
- running_agent(agent)
: Context manager for running an agent during tests
- running_agents(*agents)
: Context manager for running multiple agents
- link_agents(*agents)
: Link agents for in-memory communication
- trigger_handler(agent, method, params)
: Trigger a handler on an agent
- wait_for(condition, timeout, check_interval)
: Wait for a condition to be true
- verify_all_communicators()
: Verify all communicators' expectations
Logging Module¶
from openmas.logging import get_logger, configure_logging
# Configure logging
configure_logging(log_level="DEBUG")
# Get a logger
logger = get_logger(__name__)
# Use the logger
logger.debug("Debug message")
logger.info("Info message")
logger.warning("Warning message")
logger.error("Error message")
Key functions:
- get_logger(name)
: Get a logger with the specified name
- configure_logging(log_level, json_format)
: Configure logging for the application
Agent Patterns¶
Orchestrator-Worker pattern helpers for OpenMAS.
This module provides helper classes for implementing the Orchestrator-Worker pattern in a multi-agent system. The pattern consists of:
- An orchestrator agent that coordinates a workflow by delegating tasks to worker agents
- Worker agents that specialize in specific tasks and report results back to the orchestrator
- A communication mechanism for task delegation and result aggregation
This pattern is useful for decomposing complex workflows into modular components that can be executed by specialized agents, potentially in parallel.
BaseOrchestratorAgent
¶
Bases: BaseAgent
Base orchestrator agent for coordinating tasks among worker agents.
The orchestrator is responsible for: 1. Managing the workflow of complex tasks 2. Discovering and tracking available worker agents 3. Delegating subtasks to appropriate worker agents 4. Aggregating results from workers 5. Handling failures and retries
Source code in src/openmas/patterns/orchestrator.py
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 |
|
__init__(*args, **kwargs)
¶
Initialize the orchestrator agent.
Source code in src/openmas/patterns/orchestrator.py
delegate_task(worker_name, task_type, parameters=None, metadata=None, timeout=None, callback=None)
async
¶
Delegate a task to a worker agent.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
worker_name
|
str
|
The name of the worker to delegate to |
required |
task_type
|
str
|
The type of task to delegate |
required |
parameters
|
Optional[Dict[str, Any]]
|
Parameters for the task |
None
|
metadata
|
Optional[Dict[str, Any]]
|
Additional metadata for the task |
None
|
timeout
|
Optional[float]
|
Timeout for the task in seconds |
None
|
callback
|
Optional[Callable[[TaskResult], Any]]
|
Callback function to call when the task completes |
None
|
Returns:
Type | Description |
---|---|
str
|
The ID of the delegated task |
Raises:
Type | Description |
---|---|
ValueError
|
If the worker is not registered |
Source code in src/openmas/patterns/orchestrator.py
discover_workers()
async
¶
Discover available worker agents.
This method broadcasts a discovery message to find workers.
Returns:
Type | Description |
---|---|
List[WorkerInfo]
|
List of discovered worker information |
Source code in src/openmas/patterns/orchestrator.py
find_worker_for_task(task_type)
¶
Find a suitable worker for a given task type.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
task_type
|
str
|
The type of task to find a worker for |
required |
Returns:
Type | Description |
---|---|
Optional[str]
|
The name of a suitable worker, or None if no worker is found |
Source code in src/openmas/patterns/orchestrator.py
get_task_result(task_id, timeout=None)
async
¶
Get the result of a task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
task_id
|
str
|
The ID of the task |
required |
timeout
|
Optional[float]
|
How long to wait for the result in seconds |
None
|
Returns:
Type | Description |
---|---|
Optional[TaskResult]
|
The task result, or None if the task is not found or times out |
Source code in src/openmas/patterns/orchestrator.py
orchestrate_workflow(tasks, parallel=False)
async
¶
Orchestrate a workflow of multiple tasks.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tasks
|
List[Dict[str, Any]]
|
List of task definitions, each containing: - task_type: The type of task - parameters: Parameters for the task (optional) - worker: Specific worker to use (optional) |
required |
parallel
|
bool
|
Whether to execute tasks in parallel |
False
|
Returns:
Type | Description |
---|---|
Dict[int, Dict[str, Any]]
|
Dictionary mapping task positions or IDs to results |
Source code in src/openmas/patterns/orchestrator.py
setup()
async
¶
Set up the orchestrator agent.
Registers handlers for worker registration and task results.
Source code in src/openmas/patterns/orchestrator.py
BaseWorkerAgent
¶
Bases: BaseAgent
Base worker agent for processing specialized tasks.
Workers register with orchestrators, receive task assignments, process them according to their capabilities, and return results.
Source code in src/openmas/patterns/orchestrator.py
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 |
|
__init__(*args, **kwargs)
¶
Initialize the worker agent.
Source code in src/openmas/patterns/orchestrator.py
register_with_orchestrator(orchestrator_name)
async
¶
Register this worker with an orchestrator.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
orchestrator_name
|
str
|
The name of the orchestrator to register with |
required |
Returns:
Type | Description |
---|---|
bool
|
True if registration was successful, False otherwise |
Source code in src/openmas/patterns/orchestrator.py
setup()
async
¶
Set up the worker agent.
Discovers and registers task handlers, registers with orchestrators, and sets up communication handlers.
Source code in src/openmas/patterns/orchestrator.py
TaskHandler
¶
A decorator for registering task handlers in worker agents.
Source code in src/openmas/patterns/orchestrator.py
__call__(func)
¶
Decorate a method as a task handler.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
func
|
Callable
|
The method to decorate |
required |
Returns:
Type | Description |
---|---|
Callable
|
The decorated method |
Source code in src/openmas/patterns/orchestrator.py
__init__(task_type, description='')
¶
Initialize the task handler decorator.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
task_type
|
str
|
The type of task this handler can process |
required |
description
|
str
|
A description of the task handler |
''
|
Source code in src/openmas/patterns/orchestrator.py
TaskRequest
¶
Bases: BaseModel
A task request sent from an orchestrator to a worker.
Source code in src/openmas/patterns/orchestrator.py
TaskResult
¶
Bases: BaseModel
A task result sent from a worker to an orchestrator.
Source code in src/openmas/patterns/orchestrator.py
WorkerInfo
¶
Bases: BaseModel
Information about a worker agent.
Source code in src/openmas/patterns/orchestrator.py
Chaining pattern helpers for OpenMAS.
This module provides helper classes and functions for implementing the Chaining pattern in a multi-agent system. The pattern consists of:
- A sequence of service calls that are executed in order
- Results from earlier calls can be passed to later calls
- Error handling and optional retry mechanisms
This pattern is useful when a workflow needs to execute a series of steps in a defined order, where each step may depend on the result of previous steps.
ServiceChain
¶
A chain of service calls that can be executed sequentially.
The ServiceChain allows defining a sequence of API calls to different services, with the ability to pass data between steps, transform inputs/outputs, apply conditions, retry logic, and error handling.
Source code in src/openmas/patterns/chaining.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 |
|
__init__(communicator, name='service_chain')
¶
Initialize the ServiceChain.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
communicator
|
Any
|
The communicator to use for service calls |
required |
name
|
str
|
Name of this chain for logging purposes |
'service_chain'
|
Source code in src/openmas/patterns/chaining.py
add_step(target_service, method, parameters=None, name=None, retry_count=0, retry_delay=1.0, timeout=None, condition=None, transform_input=None, transform_output=None, error_handler=None)
¶
Add a step to the chain.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
target_service
|
str
|
The target service for this step |
required |
method
|
str
|
The method to call on the service |
required |
parameters
|
Optional[Dict[str, Any]]
|
Parameters to pass to the method |
None
|
name
|
Optional[str]
|
Optional name for this step |
None
|
retry_count
|
int
|
Number of times to retry on failure |
0
|
retry_delay
|
float
|
Delay between retries in seconds |
1.0
|
timeout
|
Optional[float]
|
Timeout for this step in seconds |
None
|
condition
|
Optional[Callable[[Dict[str, Any]], bool]]
|
Optional condition function to determine if this step should execute |
None
|
transform_input
|
Optional[Callable[[Dict[str, Any]], Dict[str, Any]]]
|
Optional function to transform input parameters |
None
|
transform_output
|
Optional[Callable[[Any], Any]]
|
Optional function to transform the output |
None
|
error_handler
|
Optional[Callable[[Exception, Dict[str, Any]], Any]]
|
Optional function to handle errors |
None
|
Returns:
Type | Description |
---|---|
ServiceChain
|
The chain instance for method chaining |
Source code in src/openmas/patterns/chaining.py
execute(initial_context=None)
async
¶
Execute the chain of service calls.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
initial_context
|
Optional[Dict[str, Any]]
|
Optional initial context data |
None
|
Returns:
Type | Description |
---|---|
ChainResult
|
Result of the chain execution |
Source code in src/openmas/patterns/chaining.py
ChainBuilder
¶
A builder for creating and executing service chains.
This builder provides a fluent interface for constructing service chains.
Source code in src/openmas/patterns/chaining.py
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 |
|
__init__(communicator, name='service_chain')
¶
Initialize the ChainBuilder.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
communicator
|
Any
|
The communicator to use for service calls |
required |
name
|
str
|
Name of this chain for logging purposes |
'service_chain'
|
Source code in src/openmas/patterns/chaining.py
add_step(target_service, method, parameters=None, name=None, retry_count=0, retry_delay=1.0, timeout=None, condition=None, transform_input=None, transform_output=None, error_handler=None)
¶
Add a step to the chain.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
target_service
|
str
|
The target service for this step |
required |
method
|
str
|
The method to call on the service |
required |
parameters
|
Optional[Dict[str, Any]]
|
Parameters to pass to the method |
None
|
name
|
Optional[str]
|
Optional name for this step |
None
|
retry_count
|
int
|
Number of times to retry on failure |
0
|
retry_delay
|
float
|
Delay between retries in seconds |
1.0
|
timeout
|
Optional[float]
|
Timeout for this step in seconds |
None
|
condition
|
Optional[Callable[[Dict[str, Any]], bool]]
|
Optional condition function to determine if this step should execute |
None
|
transform_input
|
Optional[Callable[[Dict[str, Any]], Dict[str, Any]]]
|
Optional function to transform input parameters |
None
|
transform_output
|
Optional[Callable[[Any], Any]]
|
Optional function to transform the output |
None
|
error_handler
|
Optional[Callable[[Exception, Dict[str, Any]], Any]]
|
Optional function to handle errors |
None
|
Returns:
Type | Description |
---|---|
ChainBuilder
|
The builder instance for method chaining |
Source code in src/openmas/patterns/chaining.py
build()
¶
Build and return the service chain.
Returns:
Type | Description |
---|---|
ServiceChain
|
The constructed service chain |
execute(initial_context=None)
async
¶
Build and execute the service chain.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
initial_context
|
Optional[Dict[str, Any]]
|
Optional initial context data |
None
|
Returns:
Type | Description |
---|---|
ChainResult
|
Result of the chain execution |
Source code in src/openmas/patterns/chaining.py
create_chain(communicator, name='service_chain')
¶
Create a new service chain builder.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
communicator
|
Any
|
The communicator to use for service calls |
required |
name
|
str
|
Name of this chain for logging purposes |
'service_chain'
|
Returns:
Type | Description |
---|---|
ChainBuilder
|
A new chain builder |
Source code in src/openmas/patterns/chaining.py
execute_chain(communicator, steps, initial_context=None, name='service_chain')
async
¶
Execute a chain of service calls defined by steps.
This is a convenience function for creating and executing a chain in a single call.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
communicator
|
Any
|
The communicator to use for service calls |
required |
steps
|
List[Dict[str, Any]]
|
List of step definitions, each a dict with parameters for add_step |
required |
initial_context
|
Optional[Dict[str, Any]]
|
Optional initial context data |
None
|
name
|
str
|
Name of this chain for logging purposes |
'service_chain'
|
Returns:
Type | Description |
---|---|
ChainResult
|
Result of the chain execution |