Skip to main content

simpletool

Project description

Simpletool

A Python package for creating simple tool class with a base class and data type definitions.

Overview

This package provides a BaseTool class that serves as the foundation for building various tools. It includes functionalities for:

  • Executing tools with input arguments.
  • Handling environment variables.
  • Generating JSON schemas for input models.

The package also defines data types for content, resources, and errors, ensuring consistency and clarity in tool development.

Core Components

BaseTool Class

The BaseTool class is an abstract base class that all tools should inherit from. It provides the following methods:

  • run(arguments): Executes the tool with the given arguments. This method should be overridden by subclasses to implement the tool's logic.
  • execute(arguments): An alternative name for the run method.
  • get_env(arguments, prefix): Retrieves environment variables from arguments, os.environ, and resources, optionally filtering by a prefix.
  • to_json(input_model, schema): Converts an input model to a JSON schema.

Data Types

The types.py file defines the following data types:

  • Content: Base class for content types.
  • TextContent: Represents text content.
  • ImageContent: Represents image content.
  • ResourceContents: Represents the contents of a resource.
  • TextResourceContents: Represents the contents of a text resource.
  • BlobResourceContents: Represents the contents of a blob resource.
  • EmbeddedResource: Represents an embedded resource.
  • ErrorData: Represents error information.

Installation

To install the package, use pip:

pip install simpletool

Usage

To create a new tool, inherit from the BaseTool class and implement the run or execute method. The input schema can be automatically generated from a Pydantic model using the to_json method.

Example 1: Input schema as a dictionary

from simpletool import BaseTool, TextContent
from typing import Dict, Any, List, Union

class MyTool(BaseTool):
    name = "my_tool"
    description = "A simple example tool"
    input_schema = {
        "type": "object",
        "properties": {
            "message": {
                "type": "string",
                "description": "The message to print"
            }
        },
        "required": ["message"]
    }

    async def run(self, arguments: Dict[str, Any]) -> Union[List[TextContent], ErrorData]:
        message = arguments["message"]
        return [TextContent(type="text", text=f"You said: {message}")]

Example 2: Input schema as a Pydantic model

from simpletool import BaseTool, TextContent, NoTitleDescriptionJsonSchema
from typing import Dict, Any, List, Union
from pydantic import BaseModel, Field

class InputModel(BaseModel):
    """Input model for time conversion."""
    date_time_str: str = Field(
        description="The time to convert. Can be 'NOW' or a specific date and time in a format like 'YYYY-MM-DD HH:MM:SS'."
    )
    from_timezone: str = Field(
        default="",
        description="Source timezone (default: local timezone)"
    )
    to_timezone: str = Field(
        default="UTC", 
        description="Target timezone (default: UTC)"
    )
args_schema = InputModel.model_json_schema(schema_generator=NoTitleDescriptionJsonSchema)

class MyTool2(BaseTool):
    name = "my_tool2"
    description = "A second simple example tool"
    input_schema = InputModel2.model_json_schema(schema_generator=NoTitleDescriptionJsonSchema)

class InputModel2(BaseModel):
    """Input model for another tool."""
    name: str = Field(description="The name of the user.")
    age: int = Field(description="The age of the user.")

    async def run(self, arguments: Dict[str, Any]) -> Union[List[TextContent], ErrorData]:
        message = arguments["message"]
        return [TextContent(type="text", text=f"You said: {message}")]

Accessing Tool Information

The BaseTool class provides several ways to access tool information:

  • str(my_tool): Returns a one-line JSON string representation of the tool.
  • my_tool.details: Returns a one-line JSON string representation of the tool.
  • my_tool.to_dict: Returns a dictionary representation of the tool. Note that my_tool.__dict__ is not the same as would return a dictionary containing all attributes of the object, including internal ones.
from simpletool import BaseTool, NoTitleDescriptionJsonSchema
from simpletool.types import TextContent, ImageContent, EmbeddedResource, ErrorData
from pydantic import BaseModel, Field
from typing import List, Union


class InputSchema(BaseModel):
    """Input model for the MyTool"""
    message: str = Field(description="The message to print")


class MyTool(BaseTool):
    name = "my_tool"
    description = "A simple example tool"
    input_schema = InputSchema.model_json_schema(schema_generator=NoTitleDescriptionJsonSchema)

    async def run(self, arguments: dict) -> Union[List[TextContent | ImageContent | EmbeddedResource], ErrorData]:
        """Execute the tool with the given arguments"""
        # Validate input using Pydantic model
        input_model = InputSchema(**arguments)
        message = input_model.message
        return [TextContent(type="text", text=f"You said: {message}")]


my_tool = MyTool()
print("\nString Representation - str(my_tool):")
print(f"Type: {type(str(my_tool))}")
print(str(my_tool))
# output:
#String Representation - str(my_tool):
#Type: <class 'str'>
#{"name": "my_tool", "description": "A simple example tool", "input_schema": {"properties": {"message": {"type": "string"}}, "required": ["message"], "type": "object"}}
print("\nTool Details - my_tool.info:")
print(f"Type: {type(my_tool.info)}")
print(my_tool.info)
# output:
#Tool Details - my_tool.info:
#Type: <class 'str'>
#{
#    "name": "my_tool",
#    "description": "A simple example tool",
#    "input_schema": {
#        "properties": {
#            "message": {
#                "type": "string"
#            }
#        },
#        "required": [
#            "message"
#        ],
#        "type": "object"
#    }
#}
print("\nDictionary Representation - my_tool.to_dict:")
print(f"Type: {type(my_tool.to_dict)}")
print(my_tool.to_dict)
# output:
#Dictionary Representation - my_tool.to_dict:
#Type: <class 'dict'>
#{'name': 'my_tool', 'description': 'A simple example tool', 'input_schema': {'properties': {'message': {'type': 'string'}}, 'required': ['message'], 'type': 'object'}}

Dependencies

  • pydantic>=2.0.0
  • typing-extensions

License

This project is licensed under the MIT License.

Contributing

Contributions are welcome! Please submit a pull request with your changes.

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

simpletool-0.0.2.tar.gz (10.7 kB view details)

Uploaded Source

Built Distribution

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

simpletool-0.0.2-py2.py3-none-any.whl (6.8 kB view details)

Uploaded Python 2Python 3

File details

Details for the file simpletool-0.0.2.tar.gz.

File metadata

  • Download URL: simpletool-0.0.2.tar.gz
  • Upload date:
  • Size: 10.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.0.1 CPython/3.12.8

File hashes

Hashes for simpletool-0.0.2.tar.gz
Algorithm Hash digest
SHA256 55f1c1e31ef73f6354f9c4b024a76d9ccc7f786c1c0caf45cd58da2a8da2088c
MD5 570d61ae09eff8b6151f0fdebbbdc30c
BLAKE2b-256 3a694bc58ec5993fd3f158884c92103d82a30c2e20d482923871f8ab51a191e0

See more details on using hashes here.

Provenance

The following attestation bundles were made for simpletool-0.0.2.tar.gz:

Publisher: publish.yml on nchekwa/simpletool-python

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file simpletool-0.0.2-py2.py3-none-any.whl.

File metadata

  • Download URL: simpletool-0.0.2-py2.py3-none-any.whl
  • Upload date:
  • Size: 6.8 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.0.1 CPython/3.12.8

File hashes

Hashes for simpletool-0.0.2-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 a046c1cce0ad3f75db7868110ed312cc26a3b94bc83243f766eb4e37cf32d613
MD5 ae689762c4dc5576f68415a8bc1f84f3
BLAKE2b-256 68005035364cc02f4dd8da8131150b6e78f3fed4b92e17caa5f1a8b996ba4c32

See more details on using hashes here.

Provenance

The following attestation bundles were made for simpletool-0.0.2-py2.py3-none-any.whl:

Publisher: publish.yml on nchekwa/simpletool-python

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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