BitNet-LLM-Virtual-Coworker-Builder

BitNet_LLM_Virtual_Coworker_Builder Python API

This document provides a comprehensive reference for the BitNet_LLM_Virtual_Coworker_Builder Python API.

Table of Contents

Core API

BitNetVirtualCoworker

The BitNetVirtualCoworker class is the foundation of the framework, providing the interface for creating and running virtual co-workers.

Constructor

BitNetVirtualCoworker(
    model: BitNetModel,
    tools: List[Tool] = None,
    name: str = None,
    description: str = None,
    memory: Memory = None,
    system_prompt: str = None
)

Parameters:

Methods

run
run(task: str) -> str

Runs the virtual co-worker on a task and returns the result.

Parameters:

Returns:

run_batch
run_batch(tasks: List[str]) -> List[str]

Runs the virtual co-worker on multiple tasks and returns the results.

Parameters:

Returns:

add_tool
add_tool(tool: Tool) -> None

Adds a tool to the virtual co-worker.

Parameters:

remove_tool
remove_tool(tool_name: str) -> bool

Removes a tool from the virtual co-worker.

Parameters:

Returns:

get_tool
get_tool(tool_name: str) -> Optional[Tool]

Gets a tool by name.

Parameters:

Returns:

get_tools
get_tools() -> List[Tool]

Gets all tools available to the virtual co-worker.

Returns:

clear_memory
clear_memory() -> None

Clears the virtual co-worker’s memory.

get_memory
get_memory() -> str

Gets the virtual co-worker’s memory as a string.

Returns:

add_to_memory
add_to_memory(content: str) -> None

Adds content to the virtual co-worker’s memory.

Parameters:

Example

from bitnet_vc_builder import BitNetVirtualCoworker, BitNetModel, Tool

# Initialize BitNet model
model = BitNetModel(model_path="models/bitnet-b1.58-2b")

# Create a virtual co-worker
coworker = BitNetVirtualCoworker(
    model=model,
    name="AssistantCoworker",
    description="A helpful virtual co-worker"
)

# Run the virtual co-worker on a task
result = coworker.run("What is the capital of France?")
print(result)

BitNetTeam

The BitNetTeam class enables collaboration between multiple virtual co-workers.

Constructor

BitNetTeam(
    agents: List[BitNetVirtualCoworker],
    name: str = None,
    description: str = None,
    collaboration_mode: CollaborationMode = CollaborationMode.SEQUENTIAL,
    coordinator_agent: str = None,
    memory: Memory = None,
    enable_conflict_resolution: bool = False,
    conflict_resolution_strategy: str = "voting",
    enable_task_prioritization: bool = False,
    enable_performance_tracking: bool = False,
    max_parallel_tasks: int = None
)

Parameters:

Methods

run
run(task: str) -> str

Runs the team on a task and returns the result.

Parameters:

Returns:

add_agent
add_agent(agent: BitNetVirtualCoworker) -> None

Adds a virtual co-worker to the team.

Parameters:

remove_agent
remove_agent(agent_name: str) -> bool

Removes a virtual co-worker from the team.

Parameters:

Returns:

get_agent
get_agent(agent_name: str) -> Optional[BitNetVirtualCoworker]

Gets a virtual co-worker by name.

Parameters:

Returns:

get_agents
get_agents() -> List[BitNetVirtualCoworker]

Gets all virtual co-workers in the team.

Returns:

set_collaboration_mode
set_collaboration_mode(mode: CollaborationMode) -> None

Sets the collaboration mode for the team.

Parameters:

set_coordinator_agent
set_coordinator_agent(agent_name: str) -> None

Sets the coordinator virtual co-worker for hierarchical mode.

Parameters:

Raises:

clear_memory
clear_memory() -> None

Clears the team’s memory.

get_memory
get_memory() -> str

Gets the team’s memory as a string.

Returns:

add_to_memory
add_to_memory(content: str) -> None

Adds content to the team’s memory.

Parameters:

Example

from bitnet_vc_builder import BitNetVirtualCoworker, BitNetModel, BitNetTeam, CollaborationMode

# Initialize BitNet model
model = BitNetModel(model_path="models/bitnet-b1.58-2b")

# Create virtual co-workers
researcher = BitNetVirtualCoworker(
    model=model,
    name="Researcher",
    description="A virtual co-worker that specializes in research"
)

analyst = BitNetVirtualCoworker(
    model=model,
    name="Analyst",
    description="A virtual co-worker that specializes in data analysis"
)

writer = BitNetVirtualCoworker(
    model=model,
    name="Writer",
    description="A virtual co-worker that specializes in writing"
)

# Create a team
team = BitNetTeam(
    agents=[researcher, analyst, writer],
    name="ResearchTeam",
    description="A team that researches topics, analyzes data, and writes reports",
    collaboration_mode=CollaborationMode.HIERARCHICAL,
    coordinator_agent="Researcher"
)

# Run the team on a task
result = team.run("Research climate change and write a report")
print(result)

CollaborationMode

The CollaborationMode enum defines the different modes of collaboration between virtual co-workers in a team.

class CollaborationMode(Enum):
    SEQUENTIAL = "sequential"
    HIERARCHICAL = "hierarchical"
    PARALLEL = "parallel"

Models API

BitNetModel

The BitNetModel class provides a unified interface to BitNet’s 1-bit quantized language models.

Constructor

BitNetModel(
    model_path: str,
    kernel_type: str = "i2_s",
    num_threads: int = 4,
    context_size: int = 2048,
    temperature: float = 0.7,
    top_p: float = 0.9,
    top_k: int = 40,
    repetition_penalty: float = 1.1,
    bitnet_path: str = None
)

Parameters:

Methods

generate
generate(
    prompt: str,
    max_tokens: int = 512,
    temperature: float = None,
    top_p: float = None,
    top_k: int = None,
    repetition_penalty: float = None,
    stop_sequences: List[str] = None
) -> str

Generates text based on the prompt.

Parameters:

Returns:

tokenize
tokenize(text: str) -> List[int]

Tokenizes text into token IDs.

Parameters:

Returns:

detokenize
detokenize(tokens: List[int]) -> str

Converts token IDs back to text.

Parameters:

Returns:

get_token_count
get_token_count(text: str) -> int

Gets the number of tokens in the text.

Parameters:

Returns:

set_parameters
set_parameters(
    temperature: float = None,
    top_p: float = None,
    top_k: int = None,
    repetition_penalty: float = None
) -> None

Sets generation parameters.

Parameters:

Example

from bitnet_vc_builder import BitNetModel

# Initialize BitNet model
model = BitNetModel(
    model_path="models/bitnet-b1.58-2b",
    kernel_type="i2_s",
    num_threads=4,
    context_size=2048,
    temperature=0.7
)

# Generate text
response = model.generate(
    prompt="What is the capital of France?",
    max_tokens=100,
    temperature=0.8
)
print(response)

ModelOptimizer

The ModelOptimizer class provides utilities for optimizing BitNet models for better performance.

Constructor

ModelOptimizer(
    model_path: str,
    output_path: str = None,
    target_device: str = "cpu",
    num_threads: int = 4,
    quantization_level: int = 0,
    enable_fast_math: bool = True,
    enable_caching: bool = True,
    batch_size: int = 1
)

Parameters:

Methods

optimize
optimize() -> Dict[str, Any]

Optimizes the model and returns optimization results.

Returns:

benchmark
benchmark(
    prompt: str = "Hello, world!",
    max_tokens: int = 100,
    num_runs: int = 10
) -> Dict[str, Any]

Benchmarks the optimized model and returns performance metrics.

Parameters:

Returns:

Example

from bitnet_vc_builder.models.optimizers import ModelOptimizer

# Create a model optimizer
optimizer = ModelOptimizer(
    model_path="models/bitnet-b1.58-2b",
    target_device="cpu",
    num_threads=4,
    quantization_level=2,
    enable_fast_math=True,
    enable_caching=True
)

# Optimize the model
result = optimizer.optimize()
print(f"Optimized model saved to: {result['optimized_model_path']}")
print(f"Size reduction: {result['memory_reduction']}%")
print(f"Speed improvement: {result['speedup']}x")

# Benchmark the optimized model
benchmark = optimizer.benchmark()
print(f"Tokens per second: {benchmark['tokens_per_second']}")
print(f"Latency: {benchmark['latency']} ms")
print(f"Memory usage: {benchmark['memory_usage']} MB")

Tools API

Tool

The Tool class is the base class for all tools that can be used by virtual co-workers.

Constructor

Tool(
    name: str,
    description: str,
    function: Callable,
    args_schema: Dict[str, Dict[str, Any]] = None,
    return_direct: bool = False,
    category: str = None
)

Parameters:

Methods

execute
execute(**kwargs) -> Any

Executes the tool with the given arguments.

Parameters:

Returns:

validate_args
validate_args(args: Dict[str, Any]) -> Dict[str, Any]

Validates the arguments against the schema.

Parameters:

Returns:

Raises:

to_dict
to_dict() -> Dict[str, Any]

Converts the tool to a dictionary representation.

Returns:

Example

from bitnet_vc_builder import Tool

def calculator(expression):
    """Simple calculator tool"""
    try:
        return eval(expression)
    except Exception as e:
        return f"Error: {str(e)}"

calculator_tool = Tool(
    name="calculator",
    description="Calculate a mathematical expression",
    function=calculator,
    args_schema={
        "expression": {
            "type": "string",
            "description": "Mathematical expression to calculate"
        }
    }
)

# Execute the tool
result = calculator_tool.execute(expression="2 + 2")
print(result)  # Output: 4

Built-in Tools

The framework includes several built-in tools that can be used by virtual co-workers:

WebSearchTool

A tool for searching the web.

from bitnet_vc_builder.tools.common_tools import WebSearchTool

web_search = WebSearchTool()

CalculatorTool

A tool for performing mathematical calculations.

from bitnet_vc_builder.tools.common_tools import CalculatorTool

calculator = CalculatorTool()

WikipediaTool

A tool for searching Wikipedia.

from bitnet_vc_builder.tools.common_tools import WikipediaTool

wikipedia = WikipediaTool()

WeatherTool

A tool for getting weather information.

from bitnet_vc_builder.tools.common_tools import WeatherTool

weather = WeatherTool(api_key="your_api_key")

CodeGenerationTool

A tool for generating code.

from bitnet_vc_builder.tools.code_tools import CodeGenerationTool

code_generator = CodeGenerationTool()

DataAnalysisTool

A tool for analyzing data.

from bitnet_vc_builder.tools.data_tools import DataAnalysisTool

data_analyzer = DataAnalysisTool()

DocumentProcessingTool

A tool for processing documents.

from bitnet_vc_builder.tools.document_tools import DocumentProcessingTool

document_processor = DocumentProcessingTool()

Memory API

Memory

The Memory class is the base class for all memory systems.

Constructor

Memory(max_items: int = 100)

Parameters:

Methods

add
add(content: str) -> None

Adds content to memory.

Parameters:

get
get() -> List[str]

Gets all items in memory.

Returns:

get_context
get_context() -> str

Gets the memory context as a string.

Returns:

clear
clear() -> None

Clears all items from memory.

Example

from bitnet_vc_builder.memory.memory import Memory

# Create a memory system
memory = Memory(max_items=50)

# Add items to memory
memory.add("This is an important fact.")
memory.add("Remember this for later.")

# Get all items
items = memory.get()
print(items)

# Get memory context
context = memory.get_context()
print(context)

# Clear memory
memory.clear()

ConversationMemory

The ConversationMemory class is a memory system that stores conversation history.

Constructor

ConversationMemory(max_items: int = 100)

Parameters:

Methods

add_user_message
add_user_message(message: str) -> None

Adds a user message to the conversation history.

Parameters:

add_assistant_message
add_assistant_message(message: str) -> None

Adds an assistant message to the conversation history.

Parameters:

get_conversation
get_conversation() -> List[Dict[str, str]]

Gets the conversation history.

Returns:

get_context
get_context() -> str

Gets the conversation history as a string.

Returns:

clear
clear() -> None

Clears the conversation history.

Example

from bitnet_vc_builder.memory.memory import ConversationMemory

# Create a conversation memory
memory = ConversationMemory(max_items=50)

# Add messages to the conversation
memory.add_user_message("Hello, how are you?")
memory.add_assistant_message("I'm doing well, thank you! How can I help you today?")
memory.add_user_message("I need information about climate change.")

# Get the conversation history
conversation = memory.get_conversation()
print(conversation)

# Get the conversation context
context = memory.get_context()
print(context)

# Clear the conversation
memory.clear()

Utilities

Configuration

The framework includes utilities for loading and saving configuration.

load_config

load_config(config_path: str) -> Dict[str, Any]

Loads configuration from a YAML file.

Parameters:

Returns:

save_config

save_config(config: Dict[str, Any], config_path: str) -> None

Saves configuration to a YAML file.

Parameters:

Example

from bitnet_vc_builder.utils.config import load_config, save_config

# Load configuration
config = load_config("config/config.yaml")

# Modify configuration
config["models"]["default_model"] = "bitnet-b1.58-2b"

# Save configuration
save_config(config, "config/config.yaml")

Logging

The framework includes utilities for logging.

setup_logging

setup_logging(
    log_level: str = "INFO",
    log_file: str = None,
    log_format: str = None
) -> None

Sets up logging.

Parameters:

Example

from bitnet_vc_builder.utils.logging import setup_logging, get_logger

# Set up logging
setup_logging(log_level="DEBUG", log_file="logs/app.log")

# Get a logger
logger = get_logger(__name__)

# Log messages
logger.debug("This is a debug message")
logger.info("This is an info message")
logger.warning("This is a warning message")
logger.error("This is an error message")