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:"logs"
Name of the folder for log storage
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

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

Data Conversion

csv_to_text

Convert CSV data to formatted text.

json_to_text

Convert JSON data to formatted text.

data_to_text

Universal data-to-text converter supporting multiple formats.

pdf_to_text

Extract text from PDF files.
str
required
Path to PDF file
str
Extracted text content

Token Management

count_tokens

Count tokens in text using LiteLLM tokenizer.
str
required
Text to count tokens for
str
default:"gpt-3.5-turbo"
Model to use for tokenization
int
Number of tokens in the text

check_all_model_max_tokens

Check maximum token limits for available models.

Code Processing

extract_code_from_markdown

Extract code blocks from markdown text.
""" code = extract_code_from_markdown(markdown) print(code)

Output: def hello():\n print(“Hello”)

load_agents_from_markdown

Load multiple agents from markdown files.

MarkdownAgentLoader

Class for loading agents from markdown with advanced options.

Context Window Management

dynamic_auto_chunking

Automatically chunk text based on context window limits.
str
required
Text to chunk
int
default:"4000"
Maximum tokens per chunk
str
default:"gpt-3.5-turbo"
Model to use for token counting
List[str]
List of text chunks

Output History Formatting

history_output_formatter

Format agent conversation history for display.

LiteLLM Wrapper

LiteLLM

Wrapper class for LiteLLM with error handling.

NetworkConnectionError

Exception raised for network connection issues.

LiteLLMException

General exception for LiteLLM errors.

Example: Complete Utility Usage

"""

Extract code

code = extract_code_from_markdown(markdown_content) logger.info(f”Extracted code: “)

Count tokens

tokens = count_tokens(code, model=“gpt-4”) formatter.print_panel( f”Code has tokens”, title=“Token Count”, style=“bold cyan” )

Save to file

safe_path = sanitize_file_path(”./reports/analysis_results.txt”) file_path = create_file_in_folder( folder_path=”./reports”, file_name=“analysis_results.txt”, content=markdown_content ) logger.info(f”Saved to: “)

Display markdown

formatter.print_markdown( markdown_content, title=“Analysis Report”, border_style=“green” )