tool-parse


Nametool-parse JSON
Version 1.1.3 PyPI version JSON
download
home_pagehttps://github.com/synacktraa/tool-parse
SummaryMaking LLM Tool-Calling Simpler.
upload_time2024-10-03 10:24:03
maintainerNone
docs_urlNone
authorHarsh Verma
requires_python<3.13,>=3.8
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            <p align="center">Making LLM Tool-Calling Simpler.</p>

---

<p align="center">
    <a href="https://img.shields.io/github/v/release/synacktraa/tool-parse">
        <img src="https://img.shields.io/github/v/release/synacktraa/tool-parse" alt="tool-parse version">
    </a>
    <a href="https://img.shields.io/github/actions/workflow/status/synacktraa/tool-parse/master.yml?branch=master">
        <img src="https://img.shields.io/github/actions/workflow/status/synacktraa/tool-parse/master.yml?branch=master" alt="tool-parse build status">
    </a>
    <a href="https://codecov.io/gh/synacktraa/tool-parse">
        <img src="https://codecov.io/gh/synacktraa/tool-parse/branch/master/graph/badge.svg" alt="tool-parse codecov">
    </a>
    <a href="https://img.shields.io/github/license/synacktraa/tool-parse">
        <img src="https://img.shields.io/github/license/synacktraa/tool-parse" alt="tool-parse license">
    </a>
</p>

## 🚀 Installation

```sh
pip install tool-parse
```

- with `pydantic` support

  ```sh
  pip install "tool-parse[pydantic]"
  ```

- with `langchain` based integration
  ```sh
  pip install "tool-parse[langchain]"
  ```

## 🌟 Key Features

1. **Versatile Tool Management:**

   - Support for functions (both synchronous and asynchronous)
   - Compatible with `pydantic.BaseModel`, `typing.TypedDict`, and `typing.NamedTuple`
   - Supports any docstring format recognized by the `docstring_parser` library
   - `@tool` decorator for creating independent, standalone tools
   - `ToolRegistry` class for managing multiple tools
     - Multiple registration methods:
       - Decorators (`@tr.register`)
       - Direct passing (`tr.register(func)`)
       - Key-value pairs (`tr[key] = func`)
       - Bulk registration (`register_multiple`)
     - Customizable tool naming and description

2. **Extensive Parameter Type Support:**

   - Handles a wide range of parameter types:
     `str`, `int`, `float`, `bool`, `set`, `list`, `dict`, `pathlib.Path`,
     `typing.Set`, `typing.List`, `typing.Dict`, `typing.NamedTuple`,
     `typing.TypedDict`, `pydantic.BaseModel`, `typing.Literal`, `enum.Enum`
   - Supports optional parameters:
     `typing.Optional[<type>]`, `typing.Union[<type>, None]`, `<type> | None`
   - Handles forward references and complex nested types

3. **Robust Schema Generation:**

   - Generates schemas in both 'base' and 'claude' formats
   - Extracts and includes parameter descriptions from docstrings
   - Handles recursive type definitions gracefully

4. **Flexible Tool Invocation:**

   - Supports tool invocation from call expressions or metadata
   - Handles argument parsing and type conversion
   - Manages both positional and keyword arguments

5. **Error Handling and Validation:**
   - Comprehensive error checking for type mismatches, invalid arguments, and unsupported types
   - Validates enum and literal values against allowed options
   - Handles recursive parameter exceptions

## Cookbooks

- [GorillaLLM Integration](./cookbooks/gorillaLLM-integration.ipynb)
- [Langgraph+Ollama Example](./cookbooks//langgraph-ollama-example.ipynb)

## Usage 🤗

### Creating independent tools

```python
from tool_parse import tool
from typing import Optional

@tool
def search_web(query: str, max_results: Optional[int]):
    """
    Search the web for given query
    :param query: The search query string
    :param max_results: Maximum number of results to return
    """
    print(f"{query=}, {max_results=}")
    ...

# Get tool schema
schema = search_web.marshal('base') # `base` and `claude` schema are available

# Invoke tool from LLM generated arguments
output = search_web.compile(arguments={"query": "Transformers"})
```

### Creating a tool registry

```python
from tool_parse import ToolRegistry

tr = ToolRegistry()
```

#### Defining tools and registering them

There are multiple ways of registering tools:

> Adding a docstring is optional, but it's good practice to include descriptions for parameters. The library supports any format recognized by the `docstring_parser` library, with sphinx format being a personal preference.

1. Decorating the object:

```python
from typing import TypedDict

@tr.register
class UserInfo(TypedDict):
    """
    User information schema
    :param name: The user's full name
    :param age: The user's age in years
    """
    name: str
    age: int

# Override name and description
@tr.register(name="search_web", description="Performs a web search")
def search_function(query: str, max_results: int = 10):
    """
    Search the web for given query
    :param query: The search query string
    :param max_results: Maximum number of results to return
    """
    ...
```

2. Passing the object directly:

```python
from typing import NamedTuple

class ProductInfo(NamedTuple):
    """
    Product information
    :param name: The product name
    :param price: The product price
    :param in_stock: Whether the product is in stock
    """
    name: str
    price: float
    in_stock: bool

tr.register(ProductInfo)

async def fetch_data(url: str, timeout: int = 30):
    """
    Fetch data from a given URL
    :param url: The URL to fetch data from
    :param timeout: Timeout in seconds
    """
    ...

tr.register(fetch_data, name="fetch_api_data", description="Fetches data from an API")
```

3. Using key-value pair:

> Note: This method doesn't allow overriding the description.

```python
from pydantic import BaseModel

class OrderModel(BaseModel):
    """
    Order information
    :param order_id: Unique identifier for the order
    :param items: List of items in the order
    :param total: Total cost of the order
    """
    order_id: str
    items: list[str]
    total: float

tr['create_order'] = OrderModel
```

4. Registering multiple tools at once:

> Note: This method doesn't allow overriding the name and description

```python
tr.register_multiple(UserInfo, search_function, ProductInfo)
```

#### Check if a name has already been registered

```python
'search_web' in tr  # Returns True if 'search_web' is registered, False otherwise
```

#### Get registered tools as schema

> `base` and `claude` formats are available. The default `base` format works with almost all providers.

- As a list of dictionaries:

  ```python
  tools = tr.marshal('base')  # list[dict]
  ```

- As a JSON string:

  ```python
  tools = tr.marshal(as_json=True)  # str
  ```

- Saving as a JSON file:

  ```python
  tools = tr.marshal('claude', persist_at='/path/to/tools_schema.json')  # list[dict]
  ```

- Get a single tool schema:
  ```python
  tool = tr['search_web']  # dict
  ```

#### Invoking a tool

- From a call expression:

  ```python
  result = tr.compile('search_web("Python programming", max_results=5)')
  ```

- From call metadata:

  ```python
  result = tr.compile(name='fetch_api_data', arguments={'url': 'https://api.example.com', 'timeout': 60})
  ```

> Important: The `tool-parse` library does not interact directly with LLM-specific APIs. It cannot make requests to any LLM directly. Its primary functions are generating schemas and invoking expressions or metadata generated from LLMs. This design provides developers with more flexibility to integrate or adapt various tools and libraries according to their project needs.

#### Combining two registries

> Note: A single `ToolRegistry` instance can hold as many tools as you need. Creating a new `ToolRegistry` instance is beneficial only when you require a distinct set of tools. This approach is particularly effective when deploying agents to utilize tools designed for specific tasks.

```python
new_registry = ToolRegistry()

@new_registry.register
def calculate_discount(
    original_price: float,
    discount_percentage: float = 10
):
    """
    Calculate the discounted price of an item
    :param original_price: The original price of the item
    :param discount_percentage: The discount percentage to apply
    """
    ...

combined_registry = tr + new_registry
```

## Third Party Integrations

### Langchain

Define the tools

```python
from tool_parse.integrations.langchain import ExtendedStructuredTool

async def search_web(query: str, safe_search: bool = True):
    """
    Search the web.
    :param query: Query to search for.
    :param safe_search: If True, enable safe search.
    """
    return "not found"

class UserInfo(NamedTuple):
    """User information"""
    name: str
    age: int
    role: Literal['admin', 'tester'] = 'tester'

tools = [
    ExtendedStructuredTool(func=search_web),
    ExtendedStructuredTool(func=UserInfo, name="user_info", schema_spec='claude'),
]
# OR
tools = ExtendedStructuredTool.from_objects(search_web, UserInfo, schema_spec='base')
```

Patch the chat model

```python
from langchain_ollama.chat_models import ChatOllama

from tool_parse.integrations.langchain import patch_chat_model

model = patch_chat_model(ChatOllama(model="llama3-groq-tool-use")) # Patch the instance
# OR
model = patch_chat_model(ChatOllama)(model="llama3-groq-tool-use") # Patch the class and then instantiate it
```

Bind the tools

```python
model.bind_tools(tools=tools)
```

> For langgraph agent usage, refer [Langgraph+Ollama Example](./cookbooks//langgraph-ollama-example.ipynb) cookbook

## 🤝 Contributing

Contributions, issues, and feature requests are welcome! Feel free to check the [issues page](https://github.com/synacktraa/tool-parse/issues).

---

Made with ❤️ by [synacktra](https://github.com/synacktraa)

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/synacktraa/tool-parse",
    "name": "tool-parse",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<3.13,>=3.8",
    "maintainer_email": null,
    "keywords": null,
    "author": "Harsh Verma",
    "author_email": "synacktra.work@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/1c/3b/31db8693bc29706c240487d7cc3b1805300d792132ab02fcf1206a3aeb7e/tool_parse-1.1.3.tar.gz",
    "platform": null,
    "description": "<p align=\"center\">Making LLM Tool-Calling Simpler.</p>\n\n---\n\n<p align=\"center\">\n    <a href=\"https://img.shields.io/github/v/release/synacktraa/tool-parse\">\n        <img src=\"https://img.shields.io/github/v/release/synacktraa/tool-parse\" alt=\"tool-parse version\">\n    </a>\n    <a href=\"https://img.shields.io/github/actions/workflow/status/synacktraa/tool-parse/master.yml?branch=master\">\n        <img src=\"https://img.shields.io/github/actions/workflow/status/synacktraa/tool-parse/master.yml?branch=master\" alt=\"tool-parse build status\">\n    </a>\n    <a href=\"https://codecov.io/gh/synacktraa/tool-parse\">\n        <img src=\"https://codecov.io/gh/synacktraa/tool-parse/branch/master/graph/badge.svg\" alt=\"tool-parse codecov\">\n    </a>\n    <a href=\"https://img.shields.io/github/license/synacktraa/tool-parse\">\n        <img src=\"https://img.shields.io/github/license/synacktraa/tool-parse\" alt=\"tool-parse license\">\n    </a>\n</p>\n\n## \ud83d\ude80 Installation\n\n```sh\npip install tool-parse\n```\n\n- with `pydantic` support\n\n  ```sh\n  pip install \"tool-parse[pydantic]\"\n  ```\n\n- with `langchain` based integration\n  ```sh\n  pip install \"tool-parse[langchain]\"\n  ```\n\n## \ud83c\udf1f Key Features\n\n1. **Versatile Tool Management:**\n\n   - Support for functions (both synchronous and asynchronous)\n   - Compatible with `pydantic.BaseModel`, `typing.TypedDict`, and `typing.NamedTuple`\n   - Supports any docstring format recognized by the `docstring_parser` library\n   - `@tool` decorator for creating independent, standalone tools\n   - `ToolRegistry` class for managing multiple tools\n     - Multiple registration methods:\n       - Decorators (`@tr.register`)\n       - Direct passing (`tr.register(func)`)\n       - Key-value pairs (`tr[key] = func`)\n       - Bulk registration (`register_multiple`)\n     - Customizable tool naming and description\n\n2. **Extensive Parameter Type Support:**\n\n   - Handles a wide range of parameter types:\n     `str`, `int`, `float`, `bool`, `set`, `list`, `dict`, `pathlib.Path`,\n     `typing.Set`, `typing.List`, `typing.Dict`, `typing.NamedTuple`,\n     `typing.TypedDict`, `pydantic.BaseModel`, `typing.Literal`, `enum.Enum`\n   - Supports optional parameters:\n     `typing.Optional[<type>]`, `typing.Union[<type>, None]`, `<type> | None`\n   - Handles forward references and complex nested types\n\n3. **Robust Schema Generation:**\n\n   - Generates schemas in both 'base' and 'claude' formats\n   - Extracts and includes parameter descriptions from docstrings\n   - Handles recursive type definitions gracefully\n\n4. **Flexible Tool Invocation:**\n\n   - Supports tool invocation from call expressions or metadata\n   - Handles argument parsing and type conversion\n   - Manages both positional and keyword arguments\n\n5. **Error Handling and Validation:**\n   - Comprehensive error checking for type mismatches, invalid arguments, and unsupported types\n   - Validates enum and literal values against allowed options\n   - Handles recursive parameter exceptions\n\n## Cookbooks\n\n- [GorillaLLM Integration](./cookbooks/gorillaLLM-integration.ipynb)\n- [Langgraph+Ollama Example](./cookbooks//langgraph-ollama-example.ipynb)\n\n## Usage \ud83e\udd17\n\n### Creating independent tools\n\n```python\nfrom tool_parse import tool\nfrom typing import Optional\n\n@tool\ndef search_web(query: str, max_results: Optional[int]):\n    \"\"\"\n    Search the web for given query\n    :param query: The search query string\n    :param max_results: Maximum number of results to return\n    \"\"\"\n    print(f\"{query=}, {max_results=}\")\n    ...\n\n# Get tool schema\nschema = search_web.marshal('base') # `base` and `claude` schema are available\n\n# Invoke tool from LLM generated arguments\noutput = search_web.compile(arguments={\"query\": \"Transformers\"})\n```\n\n### Creating a tool registry\n\n```python\nfrom tool_parse import ToolRegistry\n\ntr = ToolRegistry()\n```\n\n#### Defining tools and registering them\n\nThere are multiple ways of registering tools:\n\n> Adding a docstring is optional, but it's good practice to include descriptions for parameters. The library supports any format recognized by the `docstring_parser` library, with sphinx format being a personal preference.\n\n1. Decorating the object:\n\n```python\nfrom typing import TypedDict\n\n@tr.register\nclass UserInfo(TypedDict):\n    \"\"\"\n    User information schema\n    :param name: The user's full name\n    :param age: The user's age in years\n    \"\"\"\n    name: str\n    age: int\n\n# Override name and description\n@tr.register(name=\"search_web\", description=\"Performs a web search\")\ndef search_function(query: str, max_results: int = 10):\n    \"\"\"\n    Search the web for given query\n    :param query: The search query string\n    :param max_results: Maximum number of results to return\n    \"\"\"\n    ...\n```\n\n2. Passing the object directly:\n\n```python\nfrom typing import NamedTuple\n\nclass ProductInfo(NamedTuple):\n    \"\"\"\n    Product information\n    :param name: The product name\n    :param price: The product price\n    :param in_stock: Whether the product is in stock\n    \"\"\"\n    name: str\n    price: float\n    in_stock: bool\n\ntr.register(ProductInfo)\n\nasync def fetch_data(url: str, timeout: int = 30):\n    \"\"\"\n    Fetch data from a given URL\n    :param url: The URL to fetch data from\n    :param timeout: Timeout in seconds\n    \"\"\"\n    ...\n\ntr.register(fetch_data, name=\"fetch_api_data\", description=\"Fetches data from an API\")\n```\n\n3. Using key-value pair:\n\n> Note: This method doesn't allow overriding the description.\n\n```python\nfrom pydantic import BaseModel\n\nclass OrderModel(BaseModel):\n    \"\"\"\n    Order information\n    :param order_id: Unique identifier for the order\n    :param items: List of items in the order\n    :param total: Total cost of the order\n    \"\"\"\n    order_id: str\n    items: list[str]\n    total: float\n\ntr['create_order'] = OrderModel\n```\n\n4. Registering multiple tools at once:\n\n> Note: This method doesn't allow overriding the name and description\n\n```python\ntr.register_multiple(UserInfo, search_function, ProductInfo)\n```\n\n#### Check if a name has already been registered\n\n```python\n'search_web' in tr  # Returns True if 'search_web' is registered, False otherwise\n```\n\n#### Get registered tools as schema\n\n> `base` and `claude` formats are available. The default `base` format works with almost all providers.\n\n- As a list of dictionaries:\n\n  ```python\n  tools = tr.marshal('base')  # list[dict]\n  ```\n\n- As a JSON string:\n\n  ```python\n  tools = tr.marshal(as_json=True)  # str\n  ```\n\n- Saving as a JSON file:\n\n  ```python\n  tools = tr.marshal('claude', persist_at='/path/to/tools_schema.json')  # list[dict]\n  ```\n\n- Get a single tool schema:\n  ```python\n  tool = tr['search_web']  # dict\n  ```\n\n#### Invoking a tool\n\n- From a call expression:\n\n  ```python\n  result = tr.compile('search_web(\"Python programming\", max_results=5)')\n  ```\n\n- From call metadata:\n\n  ```python\n  result = tr.compile(name='fetch_api_data', arguments={'url': 'https://api.example.com', 'timeout': 60})\n  ```\n\n> Important: The `tool-parse` library does not interact directly with LLM-specific APIs. It cannot make requests to any LLM directly. Its primary functions are generating schemas and invoking expressions or metadata generated from LLMs. This design provides developers with more flexibility to integrate or adapt various tools and libraries according to their project needs.\n\n#### Combining two registries\n\n> Note: A single `ToolRegistry` instance can hold as many tools as you need. Creating a new `ToolRegistry` instance is beneficial only when you require a distinct set of tools. This approach is particularly effective when deploying agents to utilize tools designed for specific tasks.\n\n```python\nnew_registry = ToolRegistry()\n\n@new_registry.register\ndef calculate_discount(\n    original_price: float,\n    discount_percentage: float = 10\n):\n    \"\"\"\n    Calculate the discounted price of an item\n    :param original_price: The original price of the item\n    :param discount_percentage: The discount percentage to apply\n    \"\"\"\n    ...\n\ncombined_registry = tr + new_registry\n```\n\n## Third Party Integrations\n\n### Langchain\n\nDefine the tools\n\n```python\nfrom tool_parse.integrations.langchain import ExtendedStructuredTool\n\nasync def search_web(query: str, safe_search: bool = True):\n    \"\"\"\n    Search the web.\n    :param query: Query to search for.\n    :param safe_search: If True, enable safe search.\n    \"\"\"\n    return \"not found\"\n\nclass UserInfo(NamedTuple):\n    \"\"\"User information\"\"\"\n    name: str\n    age: int\n    role: Literal['admin', 'tester'] = 'tester'\n\ntools = [\n    ExtendedStructuredTool(func=search_web),\n    ExtendedStructuredTool(func=UserInfo, name=\"user_info\", schema_spec='claude'),\n]\n# OR\ntools = ExtendedStructuredTool.from_objects(search_web, UserInfo, schema_spec='base')\n```\n\nPatch the chat model\n\n```python\nfrom langchain_ollama.chat_models import ChatOllama\n\nfrom tool_parse.integrations.langchain import patch_chat_model\n\nmodel = patch_chat_model(ChatOllama(model=\"llama3-groq-tool-use\")) # Patch the instance\n# OR\nmodel = patch_chat_model(ChatOllama)(model=\"llama3-groq-tool-use\") # Patch the class and then instantiate it\n```\n\nBind the tools\n\n```python\nmodel.bind_tools(tools=tools)\n```\n\n> For langgraph agent usage, refer [Langgraph+Ollama Example](./cookbooks//langgraph-ollama-example.ipynb) cookbook\n\n## \ud83e\udd1d Contributing\n\nContributions, issues, and feature requests are welcome! Feel free to check the [issues page](https://github.com/synacktraa/tool-parse/issues).\n\n---\n\nMade with \u2764\ufe0f by [synacktra](https://github.com/synacktraa)\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Making LLM Tool-Calling Simpler.",
    "version": "1.1.3",
    "project_urls": {
        "Homepage": "https://github.com/synacktraa/tool-parse",
        "Repository": "https://github.com/synacktraa/tool-parse"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "0c32734a57a7ddfbbde6f663f3f121c248c910adda5e7d838e4d18006cb72c2d",
                "md5": "366b1b4e216198e9ff2c5c297cbc4aa1",
                "sha256": "017e102bbb3b80fa2cce9247995f0426f21e4ffa926749a1aa6b596a5565cbfa"
            },
            "downloads": -1,
            "filename": "tool_parse-1.1.3-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "366b1b4e216198e9ff2c5c297cbc4aa1",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<3.13,>=3.8",
            "size": 23167,
            "upload_time": "2024-10-03T10:24:02",
            "upload_time_iso_8601": "2024-10-03T10:24:02.054666Z",
            "url": "https://files.pythonhosted.org/packages/0c/32/734a57a7ddfbbde6f663f3f121c248c910adda5e7d838e4d18006cb72c2d/tool_parse-1.1.3-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "1c3b31db8693bc29706c240487d7cc3b1805300d792132ab02fcf1206a3aeb7e",
                "md5": "bdcba99e5d29d5fedc300687486b4747",
                "sha256": "a5051c0debb7a9cbd4685cd603f6aeeaf1c934377e56bf9465a640b0252d4ef4"
            },
            "downloads": -1,
            "filename": "tool_parse-1.1.3.tar.gz",
            "has_sig": false,
            "md5_digest": "bdcba99e5d29d5fedc300687486b4747",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<3.13,>=3.8",
            "size": 22854,
            "upload_time": "2024-10-03T10:24:03",
            "upload_time_iso_8601": "2024-10-03T10:24:03.417307Z",
            "url": "https://files.pythonhosted.org/packages/1c/3b/31db8693bc29706c240487d7cc3b1805300d792132ab02fcf1206a3aeb7e/tool_parse-1.1.3.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-10-03 10:24:03",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "synacktraa",
    "github_project": "tool-parse",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "tox": true,
    "lcname": "tool-parse"
}
        
Elapsed time: 0.37496s