Skip to main content

Swarms - TGSC

Project description

Swarms Utils

A utility package hosting complex logic for the Swarms ecosystem. This package provides essential tools for JSON formatting, swarm matching, and logits processing in multi-agent systems.

Features

  • JSON Formatter: Structured JSON generation with schema validation
  • Swarm Matcher: Intelligent task-to-swarm type matching using embeddings
  • Logits Processor: Advanced token filtering and stopping criteria for language models

Installation

pip install swarms-utils

Or install from source:

git clone https://github.com/The-Swarm-Corporation/swarms-utils.git
cd swarms-utils
pip install -e .

Quick Start

JSON Formatter

Generate structured JSON output using language models with schema validation:

from swarms_utils import Jsonformer
import transformers

# Initialize model and tokenizer
model = transformers.AutoModelForCausalLM.from_pretrained("gpt2")
tokenizer = transformers.AutoTokenizer.from_pretrained("gpt2")

# Define JSON schema
schema = {
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "age": {"type": "number"},
        "is_active": {"type": "boolean"}
    }
}

# Create formatter
formatter = Jsonformer(
    model=model,
    tokenizer=tokenizer,
    json_schema=schema,
    prompt="Generate a user profile"
)

# Generate structured output
result = formatter()
print(result)
# Output: {"name": "John Doe", "age": 30, "is_active": true}

Swarm Matcher

Intelligently match tasks to appropriate swarm types using semantic similarity:

from swarms_utils import SwarmMatcher, SwarmMatcherConfig, SwarmType

# Configure the matcher
config = SwarmMatcherConfig()
matcher = SwarmMatcher(config)

# Add custom swarm types
custom_swarm = SwarmType(
    name="DataAnalysisSwarm",
    description="Specialized in data analysis, visualization, and statistical modeling"
)
matcher.add_swarm_type(custom_swarm)

# Match a task to the best swarm type
task = "Analyze sales data and create visualizations"
best_match, confidence = matcher.find_best_match(task)
print(f"Best match: {best_match} (confidence: {confidence:.2f})")

Logits Processor

Control language model output with custom stopping criteria and token filtering:

from swarms_utils import StringStoppingCriteria, NumberStoppingCriteria, OutputNumbersTokens

# String stopping criteria - stops at quotes
string_criteria = StringStoppingCriteria(tokenizer, prompt_length=10)

# Number stopping criteria - stops at appropriate number precision
number_criteria = NumberStoppingCriteria(tokenizer, prompt_length=10, precision=2)

# Output only number tokens
number_warper = OutputNumbersTokens(tokenizer, prompt)

API Reference

Jsonformer

The main class for structured JSON generation.

Parameters:

  • model: Pre-trained language model
  • tokenizer: Tokenizer for the model
  • json_schema: JSON schema definition
  • prompt: Input prompt for generation
  • debug: Enable debug mode (default: False)
  • max_array_length: Maximum array length (default: 10)
  • max_number_tokens: Maximum tokens for numbers (default: 6)
  • temperature: Generation temperature (default: 1.0)
  • max_string_token_length: Maximum string token length (default: 10)

Methods:

  • generate_number(): Generate a number value
  • generate_boolean(): Generate a boolean value
  • generate_string(): Generate a string value
  • generate_object(): Generate an object with properties
  • generate_array(): Generate an array of items
  • __call__(): Generate complete JSON object

SwarmMatcher

Intelligent task-to-swarm matching using semantic embeddings.

Parameters:

  • config: SwarmMatcherConfig instance

Methods:

  • add_swarm_type(swarm_type): Add a new swarm type
  • find_best_match(task): Find best matching swarm type
  • auto_select_swarm(task): Automatically select swarm type
  • save_swarm_types(filename): Save swarm types to JSON
  • load_swarm_types(filename): Load swarm types from JSON

SwarmType

Pydantic model for defining swarm types.

Fields:

  • name: Swarm type name
  • description: Detailed description for matching
  • embedding: Optional pre-computed embedding

Logits Processors

StringStoppingCriteria: Stops generation at string delimiters NumberStoppingCriteria: Stops generation at appropriate number precision OutputNumbersTokens: Filters logits to only allow number tokens

Use Cases

  • Multi-Agent Systems: Match tasks to specialized agent swarms
  • Structured Output: Generate JSON responses from language models
  • Content Generation: Control model output with custom stopping criteria
  • Workflow Optimization: Automatically select appropriate processing workflows

Configuration

The package supports various configuration options:

from swarms_utils import SwarmMatcherConfig

config = SwarmMatcherConfig(
    model_name="sentence-transformers/all-MiniLM-L6-v2",
    embedding_dim=512
)

Contributing

We welcome contributions! Please see our contributing guidelines for details.

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Submit a pull request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Links

Support

For support and questions:

  • Open an issue on GitHub
  • Join our Discord community
  • Check the documentation

Made by the Swarms Team

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

swarms_utils-0.1.0.tar.gz (17.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

swarms_utils-0.1.0-py3-none-any.whl (17.4 kB view details)

Uploaded Python 3

File details

Details for the file swarms_utils-0.1.0.tar.gz.

File metadata

  • Download URL: swarms_utils-0.1.0.tar.gz
  • Upload date:
  • Size: 17.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.3 CPython/3.12.3 Darwin/24.5.0

File hashes

Hashes for swarms_utils-0.1.0.tar.gz
Algorithm Hash digest
SHA256 d0b43d1dd56198cd6c94bfa4990f26dbae5f82296d55dc74be09e7b4c799f582
MD5 da0189530117ef266108d1a9e73480ba
BLAKE2b-256 abdf7aa607ed9a9299199f57d49a05e12a52cf689cd7afcaac17ef2e95aec181

See more details on using hashes here.

File details

Details for the file swarms_utils-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: swarms_utils-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 17.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.3 CPython/3.12.3 Darwin/24.5.0

File hashes

Hashes for swarms_utils-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 77af42b4b696c613bbc2c948800115ba286e2d6d7919c4fd67a3e55c65015420
MD5 f59ce5e8f99bb1a015c1268548351ccf
BLAKE2b-256 3479d5903a3f35a8dc479db39df32eb446cf961a272f8d7b4c60cacc4ce43c1b

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page