Skip to main content

Overview

The swarms.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.

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
Configured Loguru logger instance
Features:
  • Colored console output
  • Timestamp formatting
  • Function and line number tracking
  • Backtrace and diagnostics enabled
  • Thread-safe enqueuing

Formatting & Output

Formatter

Rich-based formatter for beautiful console output with markdown support.

Constructor

bool
default:"True"
Enable markdown output rendering

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"
Panel style (color and formatting)
print_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"
Panel style (uses random color if None)
bool
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

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 not None.

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.
str
required
File path to sanitize
str
Sanitized file path safe for all platforms

load_json

Load and parse a JSON string.
str
required
JSON string to parse
object
Parsed Python object (dict, list, etc.)

zip_workspace

Zip an entire workspace directory.
str
required
Path to workspace directory to zip
str
required
Name for output zip file (without .zip extension)
str
Path to created zip file

zip_folders

Zip multiple folders into a single archive.
str
required
Path to first folder
str
required
Path to second folder
str
required
Output zip file path

Token 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 fails
int
Number of tokens in the text
Raises: ValueError 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 agent configuration from markdown file.

load_agents_from_markdown

Load multiple agents from markdown files.

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"
Worker count used when loading multiple files concurrently

Context 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.
Relevant 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 a Conversation object’s history into one of several output formats.
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", "yaml", "xml", "dict-all-except-first", "str-all-except-first", "dict-final", "list-final"
Raises: ValueError if type is not one of the supported values.

LiteLLM Wrapper

LiteLLM

Wrapper class for LiteLLM with error handling.
The constructor parameter is 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.

NetworkConnectionError

Exception raised for network connection issues.

LiteLLMException

General exception for LiteLLM errors.

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.
Any
required
The swarm instance. Its class name and name attribute pick the directory, and it is the default source for conversation and config data
str
default:"None"
Overrides owner.name in the path
bool
default:"True"
Timestamp in the directory name when True, otherwise a short UUID
bool
default:"False"
Log the directory and each successful write
bool
default:"True"
When False nothing is created or written and dir stays None
Optional[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}

Example: Complete Utility Usage

Best Practices

  1. Use logging extensively: Initialize logger in all modules for debugging
  2. Sanitize paths: Always sanitize file paths before file operations
  3. Count tokens: Monitor token usage to stay within model limits
  4. Format output: Use Formatter for consistent, beautiful CLI output
  5. Handle errors: Wrap file operations in try-catch blocks
  6. Chunk large texts: Use Conversation.dynamic_auto_chunking() to keep long histories inside the context window
  7. Stream responses: Use print_streaming_panel for real-time output