Skip to main content

Instant integration of external tools into LLM applications via automatic function calling.

Project description

LLM Tools Hub

LLM Tools Hub allows developers to instantly integrate external tools and services into their LLM AI applications. This project excels at handling function calling by automatically generating JSON schemas from Python type annotations and seamlessly bridging LLMs with external APIs.

Features

  • Decorator-based tool registration: Simply decorate your functions to register them as tools.
  • Automatic JSON schema generation: Extracts function parameter types and descriptions from Python type hints and docstrings.
  • Flexible integration with LLM function calling: The library only processes function calls—developers remain in full control of invoking the OpenAI API.
  • Reusable conversation history: Continue conversations across multiple interactions by providing your own message history.
  • Batch registration of tools: Use register_tools() to register a list of functions at once.

Installation

Install via pip (once published to PyPI):

pip install llm-tools-hub

Alternatively, clone the repository and install locally:

git clone https://github.com/yourusername/llm-tools-hub.git
cd llm-tools-hub
pip install .

Usage Example

Below is a complete example demonstrating how to register two tools—a function to calculate the sum of two numbers and another to retrieve an exchange rate—and then process function calls from an LLM response.

from llm_tools_hub import ToolRegistry, run_llm_functions_calls, action
from typing import Annotated
import openai
import json

@action(toolname="calculate_sum", requires=["math"])
def calculate_sum(
    a: Annotated[int, "First number"],
    b: Annotated[int, "Second number"]
) -> int:
    """
    Calculate the sum of two numbers.
    """
    return a + b

@action(toolname="get_exchange_rate", requires=[])
def get_exchange_rate(
    base_currency: Annotated[str, "Base currency. e.g. USD"],
    target_currency: Annotated[str, "Target currency. e.g. JPY"],
    date: Annotated[str, "Date in YYYY-MM-DD format"] = "latest"
) -> float:
    """
    Get the exchange rate between two currencies.
    """
    import requests
    url = f"https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@{date}/v1/currencies/{base_currency.lower()}.json"
    response = requests.get(url)
    if response.status_code == 200:
        data = response.json()
        return data.get(base_currency.lower(), {}).get(target_currency.lower(), None)
    else:
        raise Exception(f"Error fetching exchange rate: {response.status_code}")

# Create the registry (using the name 'tools' for professionalism)
tools = ToolRegistry()
tools.register_tools([calculate_sum, get_exchange_rate])

# Define your conversation history (can be extended/reused)
messages = [
    {"role": "user", "content": "How much is 1 USD in JPY? And what is 50 + 75?"}
]

# Developer calls OpenAI as needed, including the function schemas:
openai.api_key = '<your key>'
response = openai.ChatCompletion.create(
    model="gpt-4o-mini",
    messages=messages,
    functions=tools.get_openai_functions(),
    function_call="auto",
)

# Process the LLM response to execute function calls and get their outputs:
tool_messages = tools.run_llm_functions_calls(response=response)

# Developer integrates the tool responses into the conversation:
messages.extend(tool_messages)

# The developer can now call OpenAI again with the updated conversation history:
second_response = openai.ChatCompletion.create(
    model="gpt-4o-mini",
    messages=messages
)
print("Final LLM response:", second_response["choices"][0]["message"].get("content", ""))

API Overview

  • ToolRegistry

    • register_tool(func: Callable): Registers a single function as a tool.
    • register_tools(funcs: List[Callable]): Batch-register multiple functions.
    • get_openai_functions() -> List[Dict[str, Any]]: Returns the list of registered tools in the OpenAI function calling format (with JSON schema generated automatically).
    • call_tool(tool_name: str, arguments: Dict[str, Any]) -> str: Calls the registered tool with the provided arguments and returns its result as a string.
    • run_llm_functions_calls(response: Dict[str, Any]) -> List[Dict[str, Any]]: Processes an LLM response to execute any tool calls, returning a list of function messages (with role "function") that can be added to the conversation history.
  • @action decorator
    Decorates a function to register it as a tool, automatically extracting its name, description (from the docstring), and generating a JSON schema for its parameters using Python type hints.

  • run_llm_functions_calls(response: Dict[str, Any])
    Processes the response from an LLM (that uses function calling) by executing any function calls and returning the results as a list of messages. This gives the developer full control over how and when to invoke the OpenAI API.

Contributing

Contributions are welcome! Please follow these steps:

  1. Fork the repository.
  2. Create a new branch for your changes.
  3. Make your changes with clear commit messages.
  4. Open a pull request describing your changes.

License

This project is licensed under the MIT License.

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

llm_tools_hub-1.0.1.tar.gz (5.4 kB view details)

Uploaded Source

Built Distribution

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

llm_tools_hub-1.0.1-py3-none-any.whl (5.4 kB view details)

Uploaded Python 3

File details

Details for the file llm_tools_hub-1.0.1.tar.gz.

File metadata

  • Download URL: llm_tools_hub-1.0.1.tar.gz
  • Upload date:
  • Size: 5.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.0

File hashes

Hashes for llm_tools_hub-1.0.1.tar.gz
Algorithm Hash digest
SHA256 8e66d1c276597aab3a7266a37b1cac6ab6fd0d3ca2af4f202e4ff720b65364ac
MD5 fe978d6c9d6f2a5562f93b717afe405e
BLAKE2b-256 e17439911bca519afa1c97251717650bd2904b6df701765bf95052575e880bfe

See more details on using hashes here.

File details

Details for the file llm_tools_hub-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: llm_tools_hub-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 5.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.0

File hashes

Hashes for llm_tools_hub-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 18ed3bd898cdb90caa64cae77ab05f3c7cf9330a556b61f0060dc344a62cc17d
MD5 1b2e8c0671d05ba16831ae8d936cf8e0
BLAKE2b-256 ac7c1da4ecfc7f4fa51747542ea2aa3bfc9814554bfe8a8276f508309f341e79

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