Documentation Index
Fetch the complete documentation index at: https://docs.swarms.world/llms.txt
Use this file to discover all available pages before exploring further.
Overview
TheAgent class is the core component of the Swarms framework, connecting LLMs with tools, long-term memory, and advanced autonomous capabilities. It provides a production-ready interface for building intelligent agents that can reason, use tools, handle multimodal inputs, and execute complex tasks. The class is designed to handle a variety of document types—including PDFs, text files, Markdown, and JSON—enabling robust document ingestion and processing.
| Feature | Description |
|---|---|
| Conversational Loop | Enables back-and-forth interaction with the model. |
| Feedback Collection | Allows users to provide feedback on generated responses. |
| Stoppable Conversation | Supports custom stopping conditions for the conversation. |
| Retry Mechanism | Implements a retry system for handling issues in response generation. |
| Tool Integration | Supports the integration of various tools for enhanced capabilities. |
| Long-term Memory Management | Incorporates vector databases for efficient information retrieval. |
| Document Ingestion | Processes various document types for information extraction. |
| Interactive Mode | Allows real-time communication with the agent. |
| Sentiment Analysis | Evaluates the sentiment of generated responses. |
| Output Filtering and Cleaning | Ensures generated responses meet specific criteria. |
| Asynchronous and Concurrent Execution | Supports efficient parallelization of tasks. |
| Planning and Reasoning | Implements planning functionality for enhanced decision-making. |
| Autonomous Planning and Execution | When max_loops="auto", automatically creates plans, executes subtasks, and generates summaries. Includes built-in tools for file operations, user communication, and workspace management. |
| Agent Handoffs and Task Delegation | Intelligently routes tasks to specialized agents based on capabilities and task requirements. |
Import
Key Features
- Tool Integration: Native support for function calling and tool execution
- Long-term Memory: RAG-based memory system for context retention
- Autonomous Loops: Dynamic execution with configurable stopping conditions
- Multi-modal Support: Process text, images, and other media
- MCP Support: Integration with Model Context Protocol servers
- Agent Handoffs: Delegate tasks to specialized agents
- Streaming: Real-time token streaming with callbacks
- Fallback Models: Automatic failover to backup models
- State Management: Autosave and state persistence
Initialization
Unique identifier for the agent instance
The name of the agent, used for identification and logging
A description of the agent’s purpose and capabilities. Shown to orchestrators when routing tasks.
The system prompt that defines the agent’s behavior and personality
The language model instance to use. If None, a LiteLLM instance will be created
The LiteLLM-compatible model identifier (e.g.
"gpt-4.1", "claude-sonnet-4-6", "groq/llama-3.3-70b-versatile").Extra keyword arguments forwarded to the underlying LiteLLM client.
Base URL for OpenAI-compatible providers (Ollama, LM Studio, vLLM, etc.).
Override API key for the LLM provider. Falls back to environment variables when unset.
Single fallback model used when the primary model fails.
Maximum number of reasoning loops. Use “auto” for autonomous mode with dynamic planning
List of callable functions that the agent can use as tools
Temperature for LLM sampling (0.0 to 1.0)
Maximum number of tokens in the LLM response
Effective context window in tokens. When
context_compression=True, the agent compresses memory once usage crosses 90% of this limit.Nucleus-sampling parameter. Stripped automatically for Anthropic models when extended thinking is enabled.
Allow the framework to grow/shrink the per-call context budget based on token usage signals.
When
True, the agent runs a ContextCompressor that summarises long histories at 90% of context_length so long sessions never hit the context wall.When
True, read/write MEMORY.md under the workspace so agent state survives process restarts. Set False for stateless tasks.Optional pre/post-processing transforms applied to the conversation history.
Enable basic streaming with formatted panels
Enable detailed token-by-token streaming with metadata (citations, tokens used, etc.)
Callback function to receive streaming tokens in real-time. Use with
agent.run_stream / agent.arun_stream for generator-style consumption.Enable interactive mode (REPL-style) — prompt the user for input between loops.
Enable verbose logging for debugging.
When
False, suppress the agent’s printed output (Rich panels, thinking panel, etc.). Token streams via arun_stream / streaming_callback are unaffected.Output format: ‘str’, ‘string’, ‘list’, ‘json’, ‘dict’, ‘yaml’, ‘xml’
Automatically save agent state during execution
Display agent dashboard on initialization
Long-term memory backend (e.g. vector database) for RAG.
List of fallback models to try in order if the primary model fails.
Number of retry attempts for LLM calls
Interval in seconds between retry attempts
Token that signals the agent to stop execution
Function that returns True when the agent should stop
Alternative stopping function
Enable dynamic temperature adjustment during execution
Enable dynamic loop count adjustment (sets max_loops=“auto”)
Seconds to wait between consecutive loop iterations.
Token the user can type in interactive mode to exit the loop.
When
True, append the framework’s preset stopping marker to the system prompt.Auto-generate a system prompt from the task description when one is not provided.
Name of the user in conversation history
Path to save agent state
Standard operating procedure for the agent
List of standard operating procedures
Rules that govern agent behavior
Prompt for planning phase
Enable planning phase before execution
Enable multi-modal processing (images, etc.).
When multiple images are provided, summarise them into a single context entry before invoking the LLM.
After every tool call, run a brief LLM summary of the tool result and add it to the conversation.
Number of times to retry a failing tool call before giving up.
Display tool inputs/outputs in the agent’s printed output.
Pre-built OpenAI function-calling tool schemas. Use when you want to bypass the auto-generated schema.
Override tool schema used at runtime.
Optional post-processor applied to the agent’s output before returning.
Pydantic models registered for structured-output prompting.
URL or connection object for a single MCP server.
List of MCP server URLs for connecting to multiple servers.
Single MCP connection configuration object.
List of agents to enable task handoffs/delegation
Free-form list of agent capabilities used for routing and documentation.
The agent’s role within a swarm (e.g.
"worker", "director").Tags used to filter or categorise the agent.
Structured list of intended use cases for documentation/marketplace listings.
Execution mode:
interactive (REPL), fast (minimal logging/decoration), or standard.UUID of a prompt from the Swarms marketplace to use as the system prompt.
When
True, publish this agent to the Swarms marketplace on initialization.Path to a directory of Agent Skills (Anthropic
SKILL.md format).Tools to enable for the autonomous looper when
max_loops="auto". Use "all" or a list of tool names.Enable ReAct-style reasoning prompting.
Whether to prepend the framework’s reasoning preamble to the system prompt.
Enable reasoning mode for supported models (e.g. o1, o3, Claude with extended thinking).
Effort level for reasoning models:
"low", "medium", or "high".Maximum extended-thinking budget for Claude reasoning models.
Prepend the framework’s safety preamble to the system prompt.
Randomly select from a pool of models on each call (load-balancing/experimentation).
Optional tokenizer instance used for local token counting.
The workspace directory for the agent. Controlled by the
WORKSPACE_DIR environment variable (defaults to agent_workspace). Each agent gets its own subdirectory at workspace_dir/agents/{agent-name}-{uuid}/.Path from which to load saved agent state on init.
Methods
run
Execute the agent’s main loop for a given task.The task or prompt for the agent to process
Optional image path or data for vision-enabled models
Optional list of image paths for batch processing
Expected correct answer for validation with automatic retries
Callback function to receive streaming tokens in real-time
Agent output formatted according to output_type configuration
| Scenario | Return Type | Description |
|---|---|---|
| Single task | str | Returns the agent’s response |
| Multiple images | List[Any] | Returns a list of results, one for each image |
| Answer validation | str | Returns the correct answer as a string |
| Streaming | str | Returns the complete response after streaming completes |
call
Alternative syntax for running the agent (callsrun internally).
arun
Async version ofrun.
run_batched
Run multiple tasks concurrently in batch mode.List of tasks to run concurrently
List of images to process with each task
List of results from each task execution, in the same order as the input tasks
run_multiple_images
Run the agent with multiple images using concurrent processing.continuous_run_with_answer
Run the agent until the correct answer is provided.run_stream
Run the agent and yield response tokens one-by-one as a sync generator. The full agent loop (multi-step reasoning, tool calls, MCP, autonomous plan/execute/summary) runs in a background daemon thread; tokens are forwarded to the caller the moment the LLM emits them.arun_stream
Async generator version ofrun_stream. The agent loop runs in a thread executor while tokens are forwarded through an asyncio.Queue, so the caller’s event loop is never blocked.
Both
run_stream and arun_stream work for any max_loops value (1, integer > 1 with tools, or "auto"). They stream tokens through every internal loop, including tool-call turns, synthesis turns after a tool returns, and the autonomous plan/execute/summary cycle.run_concurrent
Run a single task concurrently using the agent’s internal executor. Returns the awaited result.run_concurrent_tasks
Run a batch of tasks concurrently via a thread pool.bulk_run
Generate responses for multiple input sets. Each input is a dict of kwargs forwarded torun.
save
Save the agent’s current state to disk.load
Load agent state from a saved file.save_state
Save the current state of the agent to a JSON file.save_to_yaml
Save the agent to a YAML file.to_dict
Convert agent configuration to dictionary.to_json
Convert agent configuration to JSON string.to_yaml
Convert agent configuration to YAML string.to_toml
Convert agent configuration to TOML string.model_dump_json / model_dump_yaml
Save the agent model to a JSON or YAML file in the workspace directory.add_tool / add_tools
Dynamically add a tool (or list of tools) to the agent at runtime.remove_tool / remove_tools
Remove a previously-registered tool (or list of tools).add_memory
Append a message to the agent’s short-term memory.memory_query
Query the long-term memory for relevant information.ingest_docs / ingest_pdf
Ingest documents into the agent’s memory.talk_to
Initiate a conversation with another agent.talk_to_multiple_agents
Talk to multiple agents concurrently.receive_message / send_agent_message
Receive or send messages between agents.handle_handoffs
Handle task delegation to specialized agents when handoffs are configured.reset
Reset the agent’s memory and state.undo_last
Undo the last response and return the previous state.plan
Run only the planning phase for a task without executing.print_dashboard
Display the agent’s configuration dashboard.showcase_config
Display the agent’s configuration in a formatted table.analyze_feedback
Analyze the feedback for issues.update_system_prompt / update_max_loops / update_loop_interval / update_retry_attempts / update_retry_interval
In-place setters for runtime reconfiguration.enable_autosave / disable_autosave / cleanup
Control the agent’s background autosave loop.get_llm_parameters
Returns the parameters of the language model.get_agent_role
Returns the role of the agent.Complete Methods Reference
| Method | Description | Usage Example |
|---|---|---|
run(task, img, imgs, correct_answer, streaming_callback) | Run the autonomous agent loop | agent.run("Generate a report") |
run_batched(tasks, imgs) | Run multiple tasks in batch | agent.run_batched(["Task 1", "Task 2"]) |
run_multiple_images(task, imgs) | Run with multiple images concurrently | agent.run_multiple_images("Describe", ["img1.jpg"]) |
continuous_run_with_answer(task, correct_answer) | Run until correct answer | agent.continuous_run_with_answer("Q", correct_answer="A") |
__call__(task) | Alternative way to call run | agent("Generate a report") |
arun(task, img) | Async version of run | await agent.arun("Task") |
run_stream(task, img) | Sync streaming generator | for t in agent.run_stream("Task"): ... |
arun_stream(task, img) | Async streaming generator | async for t in agent.arun_stream("Task"): ... |
run_concurrent(task) | Run a task concurrently | await agent.run_concurrent("Task") |
run_concurrent_tasks(tasks) | Run multiple tasks concurrently | agent.run_concurrent_tasks(["T1", "T2"]) |
bulk_run(inputs) | Generate responses for multiple inputs | agent.bulk_run([{"task": "T1"}]) |
parse_and_execute_tools(response) | Parse response and execute tools | agent.parse_and_execute_tools(response) |
tool_execution_retry(response, loop_count) | Execute tools with retry logic | agent.tool_execution_retry(response, 1) |
add_memory(message) | Add message to memory | agent.add_memory("Important info") |
memory_query(task) | Query long-term memory | agent.memory_query("Find X") |
plan(task) | Plan task execution | agent.plan("Analyze trends") |
save() | Save agent history | agent.save() |
load(file_path) | Load agent history | agent.load("history.json") |
save_state(file_path) | Save state to JSON | agent.save_state("state.json") |
save_to_yaml(file_path) | Save to YAML | agent.save_to_yaml("config.yaml") |
to_dict() | Convert to dictionary | agent.to_dict() |
to_json(indent) | Convert to JSON string | agent.to_json() |
to_yaml(indent) | Convert to YAML string | agent.to_yaml() |
to_toml() | Convert to TOML string | agent.to_toml() |
model_dump_json() | Save model to JSON file | agent.model_dump_json() |
model_dump_yaml() | Save model to YAML file | agent.model_dump_yaml() |
add_tool(tool) | Add a tool | agent.add_tool(my_tool) |
add_tools(tools) | Add multiple tools | agent.add_tools([t1, t2]) |
remove_tool(tool) | Remove a tool | agent.remove_tool(my_tool) |
remove_tools(tools) | Remove multiple tools | agent.remove_tools([t1, t2]) |
talk_to(agent, task) | Talk to another agent | agent.talk_to(other, "Collaborate") |
talk_to_multiple_agents(agents, task) | Talk to multiple agents | agent.talk_to_multiple_agents([a1], "Task") |
receive_message(name, message) | Receive a message | agent.receive_message("User", "Hello") |
send_agent_message(agent_name, message) | Send a message | agent.send_agent_message("AgentX", "Done") |
handle_handoffs(task) | Delegate to specialized agents | agent.handle_handoffs("Analyze data") |
update_system_prompt(prompt) | Update system prompt | agent.update_system_prompt("New prompt") |
update_max_loops(max_loops) | Update max loops | agent.update_max_loops(5) |
reset() | Reset memory | agent.reset() |
undo_last() | Undo last response | agent.undo_last() |
analyze_feedback() | Analyze feedback | agent.analyze_feedback() |
print_dashboard() | Display dashboard | agent.print_dashboard() |
showcase_config() | Display config table | agent.showcase_config() |
get_llm_parameters() | Get LLM parameters | agent.get_llm_parameters() |
get_agent_role() | Get agent role | agent.get_agent_role() |
ingest_docs(docs) | Ingest documents | agent.ingest_docs(["doc.pdf"]) |
ingest_pdf(pdf) | Ingest a PDF | agent.ingest_pdf("doc.pdf") |
check_available_tokens() | Check available tokens | agent.check_available_tokens() |
enable_autosave(interval) | Enable autosave | agent.enable_autosave(300) |
disable_autosave() | Disable autosave | agent.disable_autosave() |
cleanup() | Cleanup resources | agent.cleanup() |
log_agent_data() | Log data to external API | agent.log_agent_data() |
pretty_print(response, loop_count) | Print formatted response | agent.pretty_print("Done", 1) |
call_llm(task) | Call the language model | agent.call_llm("Generate text") |
execute_tools(response, loop_count) | Execute tools from response | agent.execute_tools(response, 1) |
list_output_types() | List available output types | agent.list_output_types() |
update_loop_interval(interval) | Update loop interval | agent.update_loop_interval(2) |
update_retry_attempts(attempts) | Update retry attempts | agent.update_retry_attempts(3) |
update_retry_interval(interval) | Update retry interval | agent.update_retry_interval(5) |
get_docs_from_doc_folders() | Retrieve and process docs from folder | agent.get_docs_from_doc_folders() |
handle_artifacts(response, output_path, extension) | Save artifacts from execution | agent.handle_artifacts(response, "outputs/", ".txt") |
handle_tool_schema_ops() | Handle tool schema operations | agent.handle_tool_schema_ops() |
handle_sop_ops() | Handle SOP operations | agent.handle_sop_ops() |
mcp_tool_handling(response, current_loop) | Handle MCP tool execution | agent.mcp_tool_handling(response, 1) |
parse_function_call_and_execute(response) | Parse and execute function call | agent.parse_function_call_and_execute(response) |
parse_llm_output(response) | Parse and standardize LLM output | agent.parse_llm_output(llm_output) |
llm_output_parser(response) | Parse output from language model | agent.llm_output_parser(llm_output) |
log_step_metadata(loop, task, response) | Log metadata for each step | agent.log_step_metadata(1, "Task", "Done") |
agent_output_type(responses) | Process output based on output type | agent.agent_output_type(responses) |
check_if_no_prompt_then_autogenerate(task) | Auto-generate prompt if none set | agent.check_if_no_prompt_then_autogenerate("Task") |
sentiment_analysis_handler(response) | Perform sentiment analysis | agent.sentiment_analysis_handler("Great job!") |
sentiment_and_evaluator(response) | Sentiment analysis and evaluation | agent.sentiment_and_evaluator("Response") |
count_and_shorten_context_window(history) | Count tokens and shorten context | agent.count_and_shorten_context_window(history) |
output_cleaner_and_output_type(response) | Clean and format output | agent.output_cleaner_and_output_type(response) |
output_cleaner_op(response) | Apply output cleaning operations | agent.output_cleaner_op(response) |
stream_response(response, delay) | Stream response token by token | agent.stream_response("Response", 0.001) |
dynamic_context_window() | Dynamically adjust context window | agent.dynamic_context_window() |
tokens_checks() | Perform token checks | agent.tokens_checks() |
tokens_operations(input_string) | Token-related operations on string | agent.tokens_operations("Input") |
truncate_string_by_tokens(input_string, limit) | Truncate string to token limit | agent.truncate_string_by_tokens("Long text", 100) |
temp_llm_instance_for_tool_summary() | Create temp LLM for tool summaries | agent.temp_llm_instance_for_tool_summary() |
Advanced Capabilities
Tool Integration
TheAgent class allows seamless integration of external tools by accepting a list of Python functions via the tools parameter. Each tool function must include type annotations and a docstring. The agent automatically converts these functions into an OpenAI-compatible function calling schema.
| Requirement | Description |
|---|---|
| Function | The tool must be a Python function. |
| With types | The function must have type annotations for its parameters. |
| With doc strings | The function must include a docstring describing its behavior. |
| Must return a string | The function must return a string value. |
tools_list_dictionary:
Long-term Memory Management
The agent supports integration with vector databases for long-term memory management:Memory Persistence and Context Compression
The agent ships with two complementary memory controls that work together to manage what is remembered between runs and how the context window is managed during long sessions.Persistent Memory
By default (persistent_memory=True) the agent reads and writes a MEMORY.md file under $WORKSPACE_DIR/agents/{agent_name}/MEMORY.md. Every message is appended to this file, and on the next run the file is loaded back so the agent remembers prior interactions.
Set persistent_memory=False to disable all on-disk state — the agent starts from a blank slate every run.
Context Compression
For long-running agents the conversation history can grow until it fills the context window.context_compression=True (the default) attaches a ContextCompressor that automatically summarises and collapses MEMORY.md whenever token usage crosses 90% of context_length.
Combining Both Controls
Agent Handoffs and Task Delegation
TheAgent class supports intelligent task delegation through the handoffs parameter. When provided with a list of specialized agents, the main agent acts as a router that analyzes incoming tasks and delegates them to the most appropriate specialized agent.
How Handoffs Work:
- Task Analysis: When a task is received, the main agent uses a built-in “boss agent” to analyze the task requirements
- Agent Selection: The boss agent evaluates all available specialized agents and selects the most suitable one(s)
- Task Delegation: The selected agent(s) receive the task and process it
- Response Aggregation: Results from specialized agents are collected and returned
| Feature | Description |
|---|---|
| Intelligent Routing | Uses AI to determine the best agent for each task |
| Multiple Agent Support | Can delegate to multiple agents for complex tasks requiring different expertise |
| Task Modification | Can modify tasks to better suit the selected agent’s capabilities |
| Transparent Reasoning | Provides clear explanations for agent selection decisions |
| Seamless Integration | Works transparently with the existing run() method |
Autonomous Mode
Whenmax_loops="auto" is set, the agent enables automatic planning and execution. The agent creates a structured plan with subtasks, executes them sequentially with dependency management, and generates a comprehensive summary.
Available Tools in Autonomous Mode
Whenmax_loops="auto" and interactive=False, the agent has access to specialized tools:
| Tool | Description | Parameters |
|---|---|---|
respond_to_user | Send messages to the user | message (str), message_type (str) |
create_file | Create a new file | file_path (str), content (str) |
update_file | Update an existing file | file_path (str), content (str), mode (str) |
read_file | Read file contents | file_path (str) |
list_directory | List files and directories | directory_path (str) |
delete_file | Delete a file (with safety checks) | file_path (str) |
run_bash | Execute a bash command | command (str), timeout_seconds (int) |
create_sub_agent | Create specialized sub-agents | agents (array of agent specs) |
assign_task | Assign tasks to sub-agents | assignments (array), wait_for_completion (bool) |
$WORKSPACE_DIR/agents/{agent-name}-{uuid}/).
Sub-Agent Delegation
The autonomous agent can create and manage sub-agents for parallel task execution:| Benefit | Description |
|---|---|
| Parallel Processing | Multiple tasks execute simultaneously for faster completion |
| Specialization | Each sub-agent can focus on a specific domain or capability |
| Scalability | Complex tasks can be broken into manageable pieces |
| Reusability | Sub-agents are cached and can handle multiple assignments |
| Fault Tolerance | One sub-agent failure doesn’t stop others from completing |
Batch Processing
Process multiple tasks efficiently withrun_batched:
Examples
Basic Usage
Minimal Configuration
Agent with Tools
Multi-modal Agent
Multi-Image Processing
Autonomous Agent with Auto Loops
Multiple Loops
Dynamic Loops
Agent with Streaming
Token-by-Token Streaming
Agent with Fallback Models
Agent with MCP Integration
Multiple MCP Connections
MCP with Connection Config
Agent Handoffs
Interactive Mode
Auto Generate Prompt
Reasoning-Enabled Models
Execution Modes
Marketplace Prompt Loading
Publishing to Marketplace
Message Transforms for Context Management
Agent with Capabilities
Saving and Loading State
Autosave
Whenautosave=True, the agent saves its configuration at each loop step to workspace_dir/agents/{agent-name}-{uuid}/config.json. Files are written atomically to prevent corruption.
WORKSPACE_DIR environment variable (defaults to agent_workspace).
Async and Concurrent Execution
Comprehensive Agent Configuration
Various Settings
Output Types
The agent supports multiple output formats via theoutput_type parameter:
"str"or"string": Returns the last response as a string"str-all-except-first": Returns all responses except system prompt as string (default)"list": Returns conversation as a list of messages"json": Returns conversation as JSON string"dict": Returns conversation as dictionary"yaml": Returns conversation as YAML string"xml": Returns conversation as XML string
Error Handling
The Agent class includes comprehensive error handling:- AgentInitializationError: Raised when agent fails to initialize
- AgentRunError: Raised when execution fails
- AgentLLMError: Raised when LLM encounters issues
- AgentToolError: Raised when tool execution fails
- AgentMemoryError: Raised for memory-related issues
New Features and Parameters
Enhanced Run Method Parameters
imgs: Process multiple images simultaneously instead of just onecorrect_answer: Validate responses against expected answers with automatic retriesstreaming_callback: Real-time token streaming for interactive applications
MCP (Model Context Protocol) Integration
| Parameter | Description |
|---|---|
mcp_url | Connect to a single MCP server |
mcp_urls | Connect to multiple MCP servers |
mcp_config | Advanced MCP configuration options for a single server |
Advanced Reasoning and Safety
| Parameter | Description |
|---|---|
react_on | Enable ReAct reasoning for complex problem-solving |
safety_prompt_on | Add safety constraints to agent responses |
reasoning_prompt_on | Enable multi-loop reasoning for complex tasks |
reasoning_enabled | Enable reasoning capabilities for supported models (e.g., o1) |
reasoning_effort | Set reasoning effort level: “low”, “medium”, or “high” |
thinking_tokens | Maximum number of thinking tokens for reasoning models |
Performance and Resource Management
| Parameter | Description |
|---|---|
dynamic_context_window | Automatically adjust context window based on available tokens |
tool_retry_attempts | Configure retry behavior for tool execution |
summarize_multiple_images | Automatically summarize results from multiple image processing |
Advanced Memory and Context
| Parameter | Description |
|---|---|
auto_generate_prompt | Automatically generate system prompts based on tasks |
plan_enabled | Enable planning functionality for complex tasks |
context_compression | Auto-summarize MEMORY.md once token usage crosses 90% of context_length |
persistent_memory | Read/write MEMORY.md across sessions; set False to start fresh each run |
Enhanced Tool Management
| Parameter | Description |
|---|---|
tools_list_dictionary | Provide tool schemas in dictionary format |
tool_call_summary | Enable automatic summarization of tool calls |
show_tool_execution_output | Control visibility of tool execution details |
Advanced LLM Configuration
| Parameter | Description |
|---|---|
llm_args | Pass additional arguments to the LLM |
llm_base_url | Specify custom LLM API endpoint |
llm_api_key | Provide LLM API key directly |
top_p | Control top-p sampling parameter |
Execution Modes and Marketplace
| Parameter | Description |
|---|---|
mode | Execution mode: “interactive”, “fast”, or “standard” |
capabilities | List of agent capabilities for documentation and routing |
publish_to_marketplace | Publish agent prompt to Swarms marketplace |
marketplace_prompt_id | Load prompt from Swarms marketplace by UUID |
Best Practices
| Best Practice | Description |
|---|---|
system_prompt | Always provide a clear and concise system prompt to guide the agent’s behavior. |
tools | Use tools to extend the agent’s capabilities for specific tasks. |
retry_attempts & error handling | Implement error handling and utilize the retry_attempts feature for robust execution. |
long_term_memory | Leverage long_term_memory for tasks that require persistent information. |
interactive & dashboard | Use interactive mode for real-time conversations and dashboard for monitoring. |
autosave, save/load | Utilize autosave and save/load methods for continuity across sessions. |
dynamic_context_window & tokens_checks | Optimize token usage with dynamic_context_window and tokens_checks methods. |
concurrent & async methods | Use concurrent and async methods for performance-critical applications. |
run_batched | Leverage run_batched for efficient processing of multiple related tasks. |
mcp_url or mcp_urls | Use mcp_url or mcp_urls to extend agent capabilities with external tools. |
react_on | Enable react_on for complex reasoning tasks requiring step-by-step analysis. |
tool_retry_attempts | Configure tool_retry_attempts for robust tool execution in production environments. |
handoffs | Use handoffs to create specialized agent teams that can intelligently route tasks. |
Set appropriate max_loops | Use 1 for simple tasks, higher numbers for complex reasoning, or “auto” for autonomous planning. |
Enable verbose during development | Helps debug issues during development and testing. |
Set context_length appropriately | Prevents token limit errors in production. |
Related
- BaseSwarm - Base class for multi-agent systems
- BaseStructure - Foundation for swarm structures
- Tools - Creating and using agent tools
- Memory - Long-term memory systems