Skip to main content

LLM Agent Toolkit provides minimal, modular interfaces for core components in LLM-based applications.

Project description

Banner

LLM Agent Toolkit: Modular Components for AI Workflows

LLM Agent Toolkit provides minimal, modular interfaces for core components in LLM-based applications. Simplify workflows with stateless interaction, embedding encoders, memory management, tool integration, and data loaders, designed for compatibility and scalability. It prioritizes simplicity and modularity by proposing minimal wrappers designed to work across common tools, discouraging direct access to underlying technologies. Specific implementations and examples will be documented separately in a Cookbook (GitHub Repo).

PyPI: PyPI Downloads

Attention!!!

Using this toolkit simplifies integration by providing unified and modular interfaces across platforms. Many configurations are intentionally kept at their default settings to prioritize ease of use. However, most of these components are extensible through abstract classes, allowing developers to define their own desired configurations for greater flexibility. While this approach enhances consistency and reduces complexity, advanced customization may require extending the provided abstractions.

For developers requiring full-range customization or access to the latest features, it is recommended to consider using native libraries like ollama, openai and google-genai directly.

Table of Contents

Dependecies

Installation

# Text Generation + Image Generation
pip install llm-agent-toolkit

# Text Generation + Image Generation through Gemini
pip install llm-agent-toolkit[gemini]

# Ollama Support
pip install llm-agent-toolkit[ollama] # >= v0.0.30.3

# transform text to embedding through transformers's API
pip install llm-agent-toolkit[transformer] 

# transform audio to text, only works on Ubuntu
sudo apt install ffmpeg
pip install llm-agent-toolkit[transcriber]

# entire package
sudo apt install ffmpeg
pip install llm-agent-toolkit[all] # entire package

Fundamental Components

Core:

A stateless chat completion interface to interact with the LLM.

Purpose: Serves as the central execution layer that abstracts interaction with the underlying LLM model.

Features:

  • Supports Text-to-Text and Image-to-Text.
  • Enables iterative executions for multi-step workflows.
  • Facilitates tool invocation as part of the workflow.
  • Support models from OpenAI, Ollama, DeepSeek, and Gemini.
  • Support Structured Output.

Example - Ollama

from typing import Any
from llm_agent_toolkit import ChatCompletionConfig
from llm_agent_toolkit.core.local import Text_to_Text

CONNECTION_STRING = "http://localhost:11434"
SYSTEM_PROMPT = "You are a faithful assistant."
PROMPT = "Why is the sky blue?"

config = ChatCompletionConfig(
  name="qwen2.5:7b", temperature=0.7
)
llm = Text_to_Text(
  connection_string=CONNECTION_STRING,
  system_prompt=SYSTEM_PROMPT,
  config=config,
  tools=None
)
responses, token_usage = llm.run(query=PROMPT, context=None)
for response in responses:
    print(response["content"])

Example - OpenAI

from typing import Any
from llm_agent_toolkit import ChatCompletionConfig
from llm_agent_toolkit.core.open_ai import Text_to_Text

SYSTEM_PROMPT = "You are a faithful assistant."
PROMPT = "Why is the sky blue?"

config = ChatCompletionConfig(
  name="gpt-4o-mini", temperature=0.7
)
llm = Text_to_Text(
  system_prompt=SYSTEM_PROMPT,
  config=config,
  tools=None
)
responses, token_usage = llm.run(query=PROMPT, context=None)
for response in responses:
    print(response["content"])

Example - DeepSeek

from typing import Any
from llm_agent_toolkit import ChatCompletionConfig
from llm_agent_toolkit.core.deep_seek import Text_to_Text

SYSTEM_PROMPT = "You are a faithful assistant."
PROMPT = "Why is the sky blue?"

config = ChatCompletionConfig(
  name="deepseek-chat", temperature=1.0
)
llm = Text_to_Text(
  system_prompt=SYSTEM_PROMPT,
  config=config,
  tools=None
)
responses, token_usage = llm.run(query=PROMPT, context=None)
for response in responses:
    print(response["content"])

Example - Gemini

from typing import Any
from llm_agent_toolkit import ChatCompletionConfig
from llm_agent_toolkit.core.gemini import Text_to_Text

SYSTEM_PROMPT = "You are a faithful assistant."
PROMPT = "Why is the sky blue?"

config = ChatCompletionConfig(
  name="deepseek-chat", temperature=1.0
)
llm = Text_to_Text(
  system_prompt=SYSTEM_PROMPT,
  config=config,
  tools=None
)
responses, token_usage = llm.run(query=PROMPT, context=None)
for response in responses:
    print(response["content"])

Example - Tools

from typing import Any
from llm_agent_toolkit import ChatCompletionConfig
from llm_agent_toolkit.core.local import Text_to_Text
# This example is also compatible with llm_agent_toolkit.core.open_ai.Text_to_Text
# This example is also compatible with llm_agent_toolkit.core.deep_seek.Text_to_Text
from llm_agent_toolkit.tool import LazyTool

def adder(a: int, b: int) -> int:
    """Add a with b.

    Args:
        a (int): The first number.
        b (int): The second number.

    Returns:
        int: Results
    """
    return a + b


async def divider(a: int, b: int) -> float:
    """Divide a by b.

    Args:
        a (int): The first number.
        b (int): The second number.

    Returns:
        float: Results

    Raises:
        ValueError: When b is 0
    """
    if b == 0:
        raise ValueError("Division by zero.")
    return a / b


CONNECTION_STRING = "http://localhost:11434"
SYSTEM_PROMPT = "You are a faithful assistant."
PROMPT = "10 + 5 / 5 = ?"

add_tool = LazyTool(adder, is_coroutine_function=False)
div_tool = LazyTool(divider, is_coroutine_function=True)

llm = Text_to_Text(
    connection_string=CONNECTION_STRING,
    system_prompt=SYSTEM_PROMPT,
    config=config,
    tools=[add_tool, div_tool],
)

responses, token_usage = llm.run(query=PROMPT, context=None)
for response in responses:
    print(response["content"])

Example - Structured Output

from pydantic import BaseModel

from llm_agent_toolkit import ChatCompletionConfig, ResponseMode
from llm_agent_toolkit.core.local import Text_to_Text_SO
# Other Core that support Structured Output
### * llm_agent_toolkit.core.local.Image_to_Text_SO
### * llm_agent_toolkit.core.open_ai.OAI_StructuredOutput_Core
### * llm_agent_toolkit.core.deep_seek.Text_to_Text_SO # JSON only
### * llm_agent_toolkit.core.gemini.GMN_StructuredOutput_Core
# These `Core` does not support `Tool` and multi iteration execution.
# If desired, caller can call `llm.run` iteratively with progressively updated `context`.
# File example-chain.py shows steps to achieve chained execution.

# Define the Schema through pydantic BaseModel
class QnA(BaseModel):
    question: str
    answer: str


CONNECTION_STRING = "http://localhost:11434"
SYS_PROMPT = "You are a faithful Assistant."
PROMPT = "Write a blog post about physician-assisted suicide (euthanasia)."
CONFIG = ChatCompletionConfig(
    name="llama3.2:3b", temperature=0.3, max_tokens=2048, max_output_tokens=1024
)
# Structured Output via Pydantic BaseModel
llm = Text_to_Text_SO(
    connection_string=CONNECTION_STRING, system_prompt=SYS_PROMPT, config=CONFIG,
)
response_1, token_usage = llm.run(
    query=PROMPT, context=None, mode=ResponseMode.SO, format=QnA,
)[0]

# Structured Output via JSON Mode
### It's essential to mention the expected JSON structure in the prompt 
### and highlight it to return in JSON format.
SPROMPT = f"""
You are a helpful assistant.

Response Schema:
{
    json.dumps(QnA.model_json_schema())
}

Note:
Always response in JSON format without additional comments or explanation.
"""

llm = Text_to_Text_SO(
    connection_string=CONNECTION_STRING, system_prompt=SPROMPT, config=CONFIG,
)
response_2, token_usage = llm.run(
    query=PROMPT, context=None, mode=ResponseMode.JSON
)

Encoder:

A standardized wrapper for embedding models.

Purpose: Provides a minimal API to transform text into embeddings, usable with any common embedding model.

Features:

  • Abstracts away model-specific details (e.g., dimensionality, framework differences).
  • Allows flexible integration with downstream components like Memory or retrieval mechanisms.
  • Support OpenAI, Ollama, Gemini and Transformers.
  • Support asynchronous operation.

Memory:

Offers essential context retention capabilities.

Purpose: Allows efficient context management without hardcoding database or memory solutions.

Types:

  1. Short-term Memory:
    • Maintains recent interactions for session-based context.
  2. Vector Memory:
    • Combines embedding and storage for retrieval-augmented workflows.
    • Includes optional metadata management for filtering results.
    • Support Faiss and Chroma
  3. Async Vector Memory:
    • Same as Vector Memory with async support.

Tool:

A unified interface for augmenting the LLM's functionality.

Purpose: Provides a lightweight abstraction for tool integration, accommodating both simple and complex tools.

Features:

  • Simple Tools: Lazy wrappers for functions or basic utilities.
  • Complex Tools: Abstract class for external APIs or multi-step operations.

Loader:

Responsible for converting raw data into text.

Purpose: Handles preprocessing and content extraction from diverse formats.

Features:

  • Covering limited type of documents, images, and audio files.

Chunkers:

Utility to split long text into chunks.

Features:

  • Basic:

    • FixedCharacterChunker: Split text into fixed-size character chunks with optional overlapping.
    • FixedGroupChunker: Splits text into K chunks. Supporting two levels, word and character, default is character.
    • SectionChunker: Splits text into chunks by section/paragraph.
    • SentenceChunker: Splits text into chunks by sentence.
  • Semantic:

    • SemanticChunker: Split text into semantically coherent chunks.
    • HybridChunker: Split text into semantically coherent chunks with dynamic splitting policy.

Thinking/Reasoning

Call chat completion API with thinking/reasoning equiped models.

Tested models:

  • OpenAI: o1-mini, o3-mini
  • gemini: gemini-2.5-pro-exp-03-25, gemini-2.0-flash-thinking-exp-01-21
  • DeepSeek: deepseek-reasoner

Text-To-Speech (TTS)

Generate audio from text with tts models.

Supported models:

  • OpenAI: gpt-4o-mini-tts, tts-1, tts-1-hd
  • ElevenLabs: eleven_multiplingual_v2, eleven_flash_v2_5, eleven_flash_v2, eleven_turbo_v2_5, eleven_turbo_v2.

OpenAITTS

from llm_agent_toolkit.tts import OpenAITTS
from llm_agent_toolkit.chunkers import SectionChunker


INPUT_PATH = "sample.md"

oai_tts = OpenAITTS(
    model="gpt-4o-mini-tts",
    voice="nova",
    speed=1.0,
    response_format="mp3",
)

with open(INPUT_PATH, "r", encoding="utf-8") as f:
    content = f.read()
    oai_tts.generate(text=content, output_path=f"generated_audio.mp3")

ElevenLabsTTS

from llm_agent_toolkit.tts import ElevenLabsTTS
from llm_agent_toolkit.chunkers import SectionChunker


INPUT_PATH = "sample.md"
# View supported voices
print(ElevenLabsTTS.SUPPORTED_VOICES)
# Use other voices?
ElevenLabsTTS.SUPPORTED_VOICES["voice-name"] = ("voice-id", "language-code")

# View supported models
print(ElevenLabsTTS.SUPPORTED_MODELS)
# Use other models?
ElevenLabs.TTS.SUPPORTED_MODELS["model-name"] = -1 # maximum input length

elevenlabs_tts = ElevenLabsTTS(
    model="eleven_multilingual_v2",
    voice="alloy",
    speed=1.0,
    response_format="mp3",
    sampling_rate_hz=44100,
    bitrate=128
)

with open(INPUT_PATH, "r", encoding="utf-8") as f:
    content = f.read()
    elevenlabs_tts.generate(text=content, output_path=f"generated_audio.mp3")

License

This project is licensed under the GNU General Public License v3.0 License. See the LICENSE file for details.

Project details


Release history Release notifications | RSS feed

Download files

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

Source Distribution

llm_agent_toolkit-0.0.34.0.tar.gz (123.0 kB view details)

Uploaded Source

Built Distribution

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

llm_agent_toolkit-0.0.34.0-py3-none-any.whl (171.3 kB view details)

Uploaded Python 3

File details

Details for the file llm_agent_toolkit-0.0.34.0.tar.gz.

File metadata

  • Download URL: llm_agent_toolkit-0.0.34.0.tar.gz
  • Upload date:
  • Size: 123.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.10.11

File hashes

Hashes for llm_agent_toolkit-0.0.34.0.tar.gz
Algorithm Hash digest
SHA256 7786d0dbe3818375bc3485481cfdd3f263e6769e4d472614f2ea6032a951086c
MD5 e07016e3256809d06cd92879ad66ff24
BLAKE2b-256 1d775377b3841f607fad5a898f093f08c099db27391e9d7b78d3349767f37eca

See more details on using hashes here.

File details

Details for the file llm_agent_toolkit-0.0.34.0-py3-none-any.whl.

File metadata

File hashes

Hashes for llm_agent_toolkit-0.0.34.0-py3-none-any.whl
Algorithm Hash digest
SHA256 74eb2a15a44a25200b9dde4fa178f8a432d4c9e6972d7e8983611317de78a722
MD5 f367d90e6da466334cd824105c2047f7
BLAKE2b-256 55c119663c2fa0aa75e94cc23756b3d6c6878b22a95066fa4cc910c1bccc5e2b

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