Overview
Theswarms.utils module provides essential utilities for file operations, logging, output formatting, token counting, and data processing. These utilities support core agent functionality and framework operations.
Every name in swarms.utils.__all__ is re-exported from the top-level package, so from swarms import count_tokens works. Names outside __all__, such as Formatter and get_supported_models, are imported from their modules.
Logging
initialize_logger
Initialize a Loguru logger with custom formatting and output configuration.str
default:"swarms"
Legacy parameter, kept only for backwards compatibility — it no longer sets the log directory. Logs are always written to
{WORKSPACE_DIR}/logs (via get_log_dir()), regardless of what is passed here.Logger
The shared Loguru logger. Handlers are configured on the first call and reused afterwards
- Colored console output at
INFOlevel - Timestamp formatting
- Function and line number tracking
- Backtrace and diagnostics enabled
- Thread-safe enqueuing
{WORKSPACE_DIR}/logs, or agent_workspace/logs when WORKSPACE_DIR is unset. That directory holds a combined swarms_{YYYY-MM-DD}.log, rotated daily and kept for 10 days, plus one {module}.log per swarms module that logs, rolled to {module}.log.1 past 10 MB. If the directory cannot be created, the logger falls back to console output only.
Formatting & Output
Formatter
Rich-based formatter for beautiful console output with markdown support.Constructor
bool
default:"True"
Enable markdown output rendering
from swarms.utils.formatter import formatter, created with md=False.
Panel body text renders in a neutral grey (grey85), whatever border color or style you choose.
Methods
print_panel
Print content in a styled panel.str
required
Content to display in the panel
str
default:""
Panel title
str
default:"bold blue"
Border style when markdown is enabled. With
md=False, the border gets a random color and style is not usedprint_markdown
Render markdown content with syntax highlighting.str
required
Markdown content to render
str
default:""
Panel title
str
default:"blue"
Border color style
print_streaming_panel
Display real-time streaming response with live updates.Generator
required
Streaming response generator from LLM
str
default:"Agent Streaming Response"
Panel title
str
default:"None"
Border style. A random color is used when
Nonebool
default:"False"
Whether to collect individual chunks
Callable
default:"None"
Callback function for each chunk
str
Complete accumulated response text
print_agent_dashboard
Display a live dashboard showing agent statuses.List[Dict[str, Any]]
required
List of agent information dictionaries with name, status, and output
str
default:"Concurrent Workflow Dashboard"
Dashboard title
bool
default:"False"
Whether this is the final update
Other methods
Data Structure Formatting
format_dict_to_string
Recursively format a dictionary into a readable, multi-line string.dict
required
The dictionary to format
int
default:"0"
Current indentation level for nested structures
bool
default:"True"
If
True, use "key: value" formatting; if False, use "key value"format_data_structure
Format any Python data structure (dict, list, tuple, set, or object) into a readable, indented, multi-line string.any
required
The data structure to format
int
default:"0"
Current indentation level
int
default:"10"
Maximum depth to recurse
exists
Check if a value is notNone.
File Processing
create_file_in_folder
Create a file with content in a specified folder.str
required
Path to the folder (created if doesn’t exist)
str
required
Name of the file to create
Any
required
Content to write to the file
str
Path to the created file
sanitize_file_path
Clean and sanitize file paths for cross-platform compatibility.<, >, :, ", /, \, |, ? and * is replaced with _, so path separators are replaced too.
str
required
File path to sanitize
str
Sanitized file path safe for all platforms
The file helpers in this section log failures and return
None instead of raising. Check the return value before you use it.load_json
Load and parse a JSON string.str
required
JSON string to parse
object
Parsed Python object (dict, list, etc.), or
None if the string is not valid JSONzip_workspace
Zip an entire workspace directory. The archive is written to a new temporary directory, not the current one.str
required
Path to workspace directory to zip
str
required
Name for output zip file. A
.zip extension in it is removed, then added back oncestr
Path to created zip file, or
None on failurezip_folders
Zip two folders into a single archive. Each folder appears under its own base name inside the archive. ReturnsNone.
str
required
Path to first folder
str
required
Path to second folder
str
required
Output archive path without the extension.
.zip is appendedToken Management
count_tokens
Count tokens in text using LiteLLM tokenizer.str
required
Text to count tokens for
str
default:"gpt-5.4"
Model to use for tokenization
str
default:"gpt-5.4"
Fallback encoder used if tokenizing with
model failsint
Number of tokens in the text. Empty or whitespace-only text returns
0ValueError if both the primary model and the fallback encoder fail to tokenize the text.
get_supported_models
Get the list of models supported by LiteLLM.list
List of supported model name strings
Agent Loading
load_agent_from_markdown
Load an agent from a markdown file with YAML frontmatter. Keyword arguments override values from the file. See AgentLoader for the file format.load_agents_from_markdown
Load multiple agents from a directory path or a list of markdown files.Union[str, List[str]]
required
A directory path or a list of markdown file paths
bool
default:"True"
Load files in parallel with a thread pool
float
default:"10.0"
Skip files larger than this size
MarkdownAgentLoader
Class for loading agents from markdown with advanced options.load_agent_from_markdown and load_agents_from_markdown are thin wrappers around it.
int
default:"None"
Accepted but currently ignored. The constructor always sets
max_workers to twice the CPU countContext Window Management
Conversation.dynamic_auto_chunking
Trim the conversation history from the beginning so the remainder fits within the conversation’s token budget, using a binary search over token counts. It returns a single trimmed string (the tail of the history that fits), not a list of chunks.This is a method on
Conversation, not a standalone helper — there is no dynamic_auto_chunking in swarms.utils. The budget and tokenizer come from the Conversation’s own context_length and tokenizer_model_name, so the method itself takes no arguments.str
The conversation history trimmed to fit within
context_length tokens. Returns the full history unchanged if it already fits, or if chunking fails.Conversation constructor parameters:
int
default:"8192"
Maximum number of tokens allowed in the conversation history
str
default:"gpt-5.4"
Model used for token counting
Output History Formatting
history_output_formatter
Format aConversation object’s history into one of several output formats. This is what an agent’s or swarm’s output_type setting runs through.
Conversation
required
A conversation object exposing methods like
return_messages_as_list(), to_dict(), get_str(), etc.HistoryOutputType
default:"list"
Output format. One of:
"list", "dict"/"dictionary", "string"/"str", "final"/"last", "json", "all" (same as "str"), "yaml", "dict-all-except-first", "str-all-except-first", "dict-final", "list-final"ValueError if type is not one of the supported values.
HistoryOutputType is the Literal type listing these values, exported from swarms.utils and swarms for type hints. OutputType in swarms.utils.output_types is an alias of it.
LiteLLM Wrapper
LiteLLM
Wrapper class for LiteLLM with error handling.Agent builds one of these internally; use it directly for single LLM calls outside an agent.
model_name, not model — because LiteLLM.__init__ absorbs unrecognized keywords via **kwargs, passing model= silently fails to set the model instead of raising an error.
Commonly used constructor parameters:
str
default:"gpt-5.4"
Any LiteLLM model string
str
default:"None"
System prompt sent with every call
float
default:"None"
Sampling temperature. When
None it is left out of the request and the provider’s default appliesint
default:"4000"
Maximum output tokens per call
bool
default:"False"
Return a generator of chunks instead of a string
List[dict]
default:"None"
OpenAI-format tool schemas the model may call
str
default:"None"
"low", "medium" or "high" for reasoning modelsint
default:"None"
Extended thinking budget for Anthropic reasoning models
bool
default:"False"
Add provider-side prompt-cache breakpoints (Anthropic models). Tune with
cache_configstr
default:"None"
Custom API endpoint, for local or self-hosted models
str
default:"None"
API key. Falls back to the provider’s environment variable
Callable[[dict], None]
default:"None"
Called with each call’s token counts. For a stream, it fires once the provider’s final usage chunk has been consumed
NetworkConnectionError
Raised byLiteLLM.run() and arun() when the provider cannot be reached. The message includes troubleshooting steps.
LiteLLMException
Exception class for LiteLLM wrapper errors. The wrapper re-raises it if it occurs, but nothing in the framework raises it today. Provider errors such as authentication or bad-request failures reach you as LiteLLM’s own exception types.When the call goes through an
Agent, a model that still fails after retry_attempts (and after any fallback_models) raises AgentLLMError from Agent.run(). See Agent error schemas.Workspace Management
WorkspaceManager
Creates a swarm’s autosave directory once and writes to it on demand. The directory is{WORKSPACE_DIR}/swarms/{ClassName}/{name}-{stamp}, created eagerly so dir is usable straight after construction.
WORKSPACE_DIR is unset, the manager sets it to ./agent_workspace before creating the directory. No method raises: a failed write logs a warning and returns None, so autosave never fails a run.
Any
required
The swarm instance. Its class name and
name attribute pick the directory, and it is the default source for conversation and config datastr
default:"None"
Overrides
owner.name in the pathbool
default:"True"
Timestamp in the directory name when
True, otherwise a short UUIDbool
default:"False"
Log the directory and each successful write
bool
default:"True"
When
False nothing is created or written and dir stays NoneOptional[Sequence[str]]
default:"None"
Path segments joined onto the workspace directory in place of the default
swarms/{ClassName}/{name}-{stamp} layout — e.g. ("agents", "my-agent-a1b2c3d4e5f6")Optional[Dict[str, Any]]
default:"None"
Base fields merged into
_autosave_metadata on every write, in place of the default {class_name, swarm_name, swarm_id}
Each
save_* method returns the written path, or None when the manager is disabled or the write failed. bool(manager) is True only when writes will land somewhere.
WorkspaceManager replaces the old swarms.utils.swarm_autosave module, which has been deleted. Build a WorkspaceManager in your swarm’s __init__ and call its save_* methods from run.Example: Complete Utility Usage
Best Practices
- Use logging extensively: Initialize logger in all modules for debugging
- Sanitize paths: Always sanitize file paths before file operations
- Count tokens: Monitor token usage to stay within model limits
- Format output: Use Formatter for consistent, beautiful CLI output
- Handle errors: Wrap file operations in try-catch blocks
- Chunk large texts: Use
Conversation.dynamic_auto_chunking()to keep long histories inside the context window - Stream responses: Use print_streaming_panel for real-time output