Skip to main content

Overview

The Social Algorithms framework provides a flexible system for defining custom social algorithms that control how agents communicate and interact with each other in multi-agent systems. This framework allows you to upload any arbitrary social algorithm as a callable that defines the sequence of communication between agents.

Installation

Class Definition

Attributes

str
default:"None"
Unique identifier for the algorithm. If None, a UUID will be generated.
str
default:"SocialAlgorithm"
Human-readable name for the algorithm.
str
Description of what the algorithm does.
List[AgentType]
default:"None"
List of agents that will participate in the algorithm. Required: every element must be an Agent instance.
Callable
default:"None"
The callable that defines the communication sequence. Must accept (agents, task, **kwargs) as parameters.
float
default:"300.0"
Maximum time allowed for algorithm execution in seconds.
OutputType
default:"dict"
Shape of final_outputs. "dict" wraps a non-dict result as {"result": ...}, "list" wraps a non-list result as [...], and "str" converts a non-string result with str(). Any other value returns the result unchanged.
bool
default:"False"
Whether to enable verbose logging.
enable_communication_logging, parallel_execution and max_workers were removed. Agent messages are now always recorded, and the two parallel options were stored but never used. Passing them is accepted and ignored.

Instance attributes

Conversation
The transcript of every agent message, kept across runs. Read it with the standard Conversation API, for example social_alg.conversation.get_str().

Constructor Validation

The constructor calls _validate_inputs() before returning, which raises:

Methods

run()

Execute the social algorithm with the given task.
Parameters:
  • task (str): The task to execute using the social algorithm.
  • algorithm_args (Dict[str, Any]): Additional keyword arguments for the algorithm. The dict is never mutated.
  • **kwargs: More keyword arguments for the algorithm. They win over algorithm_args on a name conflict.
The algorithm is called as social_algorithm(agents, task, **algorithm_args, **kwargs). Returns: SocialAlgorithmResult — The result of executing the social algorithm. Raises:
  • InvalidAlgorithmError: If no social algorithm is defined.
  • TimeoutError: If the algorithm execution exceeds max_execution_time.
  • Any exception the algorithm raises, after it is logged.
Process flow:
  1. Records the task as a User message. The conversation is not cleared between runs
  2. Patches each agent’s run and talk_to for the duration of the call, so every agent message is recorded under the agent’s name
  3. Calls the algorithm under the timeout and restores the agents afterwards, even on failure
  4. Records the algorithm’s return value under the algorithm’s name and returns a SocialAlgorithmResult

add_agent()

Add an agent to the social algorithm.
Parameters:
  • agent (Agent): The agent to add.
Raises:
  • ValueError: If agent is not an instance of the Agent class.

remove_agent()

Remove an agent from the social algorithm.
Parameters:
  • agent_name (str): Name of the agent to remove.
Raises:
  • AgentNotFoundError: If no agent with agent_name is found.

get_communication_history()

Get the recorded agent messages, oldest first.
Returns: The conversation messages, each a {"role", "content", ...} dict.

clear_communication_history()

Clear the communication history.

get_algorithm_info()

Get information about the social algorithm.
Returns: Information about the algorithm including ID, name, description, agent count, and configuration.

Data Models

SocialAlgorithmResult

Result of executing a social algorithm.
Only the SocialAlgorithms class itself is exported from the top-level swarms package. SocialAlgorithmResult and the exception classes below must be imported from the submodule:

Exception Classes

  • SocialAlgorithmError — Base exception for social algorithm errors
  • InvalidAlgorithmError — Raised when an invalid algorithm is provided
  • AgentNotFoundError — Raised when a required agent is not found

Usage Examples

Basic Social Algorithm

Research and Development Team

Competitive Evaluation

Negotiation Algorithm

Advanced Features

Communication Logging

Every agent.run() and agent.talk_to() call made while the algorithm runs is recorded into conversation, under the calling agent’s own name. For run, the recorded content is whatever run returns. For talk_to, the outgoing message is recorded with the receiver’s name in the message metadata. This is always on; the algorithm does not have to report anything itself.

Timeout Protection

Algorithms are executed with timeout protection to prevent infinite loops. The default is 300 seconds (5 minutes), customizable via max_execution_time.
The timeout is implemented with signal.SIGALRM, which only works on the main thread of the main interpreter and does not exist on Windows. Calling run() from a worker thread raises ValueError: signal only works in main thread. signal.alarm also truncates to whole seconds, so a sub-second max_execution_time rounds to alarm(0) and disables the timeout entirely.

Error Handling

run raises InvalidAlgorithmError when no algorithm is set and TimeoutError when the limit is hit. Any other exception from the algorithm or an agent is logged and re-raised, so handle agent failures inside your algorithm if you want the run to continue. remove_agent raises AgentNotFoundError for an unknown name.

Tracing

The constructor captures its configuration and each run call is recorded as a SocialAlgorithms.run span when telemetry is on. Agent runs inside the algorithm nest under that span.

Output Formatting

Results can be formatted as "dict" (default), "list", or "str".

Integration

Best Practices

  1. Algorithm Design: Design algorithms to be modular and reusable. Break complex algorithms into smaller, composable functions
  2. Error Handling: Always include proper error handling. Check for required agents and validate inputs
  3. Logging: Use the built-in logging system to track execution and debug issues
  4. Timeout Management: Set appropriate timeouts based on algorithm complexity
  5. Agent Roles: Clearly define roles for each agent to ensure proper communication patterns
  6. Testing: Test with different agent configurations and edge cases
  7. Documentation: Document custom algorithms thoroughly, including expected inputs and outputs

Source Code

View the source code on GitHub