Skip to main content

Downloads

Claudetools

Claudetools is a Python library that provides a convenient way to use Claude 3 family's structured data generation capabilities for function calling. The function calling capabilities are similar to ones available with OpenAI models.

With claudetools one can now use any model from the Claude 3 family of models for function calling.

Key Features

  • Function Calling: Define and call custom functions within your prompts, leveraging the advanced capabilities of Claude 3 models.
  • Synchronous and Asynchronous Clients: Choose between synchronous or asynchronous interaction modes depending on your use case.
  • Flexible Tool Definition: Specify function names, descriptions, and parameters using the Pydantic library for type safety and validation.
  • Multiple Tools Support: Opt to call multiple tools within a single prompt, enabling more complex interactions.
  • Customizable System Prompts: Attach custom system prompts to your conversations for better context and control.
  • Bedrock Client: Use Claude 3 via AWS Bedrock for function calling.

Installation

You can install claudetools from PyPI or directly from the source:

From PyPi

pip install claudetools

Install from source

pip install git+https://github.com/vatsalsaglani/claudetools

Usage

Here's a basic example of how to use claudetools for function calling with the Claude 3 model:

import asyncio
from claudetools.tools.tool import Tool
from pydantic import BaseModel, Field
from typing import List, Dict
import json

# create a tool instance with your Anthropic API Key
tool = Tool(ANTHROPIC_API_KEY)

# define your function parameters
class AddTodo(BaseModel):
    text: str = Field(..., description="Text to add for the TODO to remember.")

class MarkCompleted(BaseModel):
    text: str = Field(..., description="Text of the completed TODO.")


class ReOpen(BaseModel):
    text: str = Field(..., description="Text of the TODO to reopen.")


# specify the functions you want to use
functions = [{
    "name": "AddTodo",
    "description": "Add a TODO with text to remember.",
    "parameters": AddTodo.model_json_schema()
}, {
    "name": "MarkCompleted",
    "description": "Get text of the todo mark it complete",
    "parameters": MarkCompleted.model_json_schema()
}, {
    "name": "ReOpen",
    "description": "Get text of the todo reopen it.",
    "parameters": ReOpen.model_json_schema()
}]

# set up the user messages
user_messages = [{
    "role":
    "user",
    "content":
    """I have to pick up my daughter from school. After which I've to do the laundary. And now I need to cook lunch."""
}]

# dependency prompt to attach to the main system prompt
DEPENDENCY_PROMPT = """You are a helpful assistant that helps a user with their tasks and todos. The user can add a todos, mark todos as completed, or reopen certain todos.
The user can provide multiple actions at once so you've to break those down and call the appropriate functions in the correct sequence."""


# call the tool with the required parameters
output = tool(model="claude-3-sonnet-20240229",
              messages=user_messages,
              tools=functions,
              tool_choice=None,
              multiple_tools=True,
              attach_system=DEPENDENCY_PROMPT,
              max_tokens=3000)

if output:
    print(json.dumps(output, indent=4))
else:
    print("Unable to find a function!")

No default value of max_tokens is assumed hence, please provide max_tokens to avoid getting an error from the Claude APIs.

The parameter explanation is provided below.

  • model: The name of the model from the Claude 3 family.
  • messages: Messages transferred between the user and the assistant.
  • tools: Set of function specification to use.
  • tool_choice: User a particular function. By default the value is None. The model will figure out the function to call and provide the related parameters. If a specific function needs to be called provide {"name": "function name"} in the tool_choice argument.
  • multiple_tools: Defaults to False. Can be set to True to get multiple function calls.
  • attach_system: Defaults to None. Can also accept string which will be attached as part of the system prompt.
  • max_tokens: As mentioned above, no default value of max_tokens is assumed. Hence, please provide max_tokens to avoid getting an error.

Asynchronous Interaction

Just import AsyncTool instead of Tool to and use await with each call.

import asyncio
from claudetools.tools.tool import AsyncTool
from pydantic import BaseModel, Field
from typing import List, Dict
import json

tool = AsyncTool(ANTHROPIC_API_KEY)

class AddTodo(BaseModel):
    text: str = Field(..., description="Text to add for the TODO to remember.")


functions = [{
    "name": "AddTodo",
    "description": "Add a TODO with text to remember.",
    "parameters": AddTodo.model_json_schema()
}, {
    "name": "MarkCompleted",
    "description": "Get text of the todo mark it complete",
    "parameters": MarkCompleted.model_json_schema()
}, {
    "name": "ReOpen",
    "description": "Get text of the todo reopen it.",
    "parameters": ReOpen.model_json_schema()
}]

user_messages = [{
    "role":
    "user",
    "content":
    """I have to pick up my daughter from school. After which I've to do the laundary. And now I need to cook lunch."""
}]

async def main():

    output = await tool(model="claude-3-sonnet-20240229",
                messages=user_messages,
                tools=functions,
                tool_choice=None,
                multiple_tools=True,
                attach_system=None,
                max_tokens=3000)
    if output:
        print(json.dumps(output, indent=4))
    else:
        print("Unable to find a function!")

if __name__ == "__main__":
    asyncio.run(main())

Bedrock Example

Currently, only the sync client supports AWS Bedrock.

import asyncio
from claudetools.tools.tool import Tool
from pydantic import BaseModel, Field
from typing import List, Dict
import json

AWS_ACCESS_KEY=""
AWS_SECRET_KEY=""
AWS_REGION=""
# or
AWS_SESSION_TOKEN=""

# create a tool instance with your aws access and secret keys
tool = Tool(aws_access_key=AWS_ACCESS_KEY,
            aws_secret_key=AWS_SECRET_KEY,
            aws_region=AWS_REGION)
# to use session token from AWS STS use the following
# tool = Tool(aws_session_token=AWS_SESSION_TOKEN, aws_region=AWS_REGION)


# define your function parameters
class AddTodo(BaseModel):
    text: str = Field(..., description="Text to add for the TODO to remember.")

class MarkCompleted(BaseModel):
    text: str = Field(..., description="Text of the completed TODO.")


class ReOpen(BaseModel):
    text: str = Field(..., description="Text of the TODO to reopen.")


# specify the functions you want to use
functions = [{
    "name": "AddTodo",
    "description": "Add a TODO with text to remember.",
    "parameters": AddTodo.model_json_schema()
}, {
    "name": "MarkCompleted",
    "description": "Get text of the todo mark it complete",
    "parameters": MarkCompleted.model_json_schema()
}, {
    "name": "ReOpen",
    "description": "Get text of the todo reopen it.",
    "parameters": ReOpen.model_json_schema()
}]

# set up the user messages
user_messages = [{
    "role":
    "user",
    "content":
    """I have to pick up my daughter from school. After which I've to do the laundary. And now I need to cook lunch."""
}]

# dependency prompt to attach to the main system prompt
DEPENDENCY_PROMPT = """You are a helpful assistant that helps a user with their tasks and todos. The user can add a todos, mark todos as completed, or reopen certain todos.
The user can provide multiple actions at once so you've to break those down and call the appropriate functions in the correct sequence."""


# call the tool with the required parameters
output = tool(model="claude-3-sonnet-20240229",
              messages=user_messages,
              tools=functions,
              tool_choice=None,
              multiple_tools=True,
              attach_system=DEPENDENCY_PROMPT,
              max_tokens=3000)

if output:
    print(json.dumps(output, indent=4))
else:
    print("Unable to find a function!")

Requirements

Python 3.7 or higher.

TODOs

  • Add examples notebook.
  • Enable logging.
  • Add support for AWS Bedrock.
  • Validate outputs in tool_choice.

Contributing

Contributions to claudetools are welcome! If you find any issues or have suggestions for improvements, please open an issue or submit a pull request on this GitHub repository.

Metadata

Release files for claudetools 1.0.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for claudetools 1.0.3
File Size Uploaded
claudetools-1.0.3.tar.gz 12.8 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for claudetools 1.0.3
File Interpreter ABI Platform
claudetools-1.0.3-py3-none-any.whl Python 3 none any Details

Total release size: 29.7 kB

Release files / claudetools-1.0.3.tar.gz

Download URL claudetools-1.0.3.tar.gz
Size 12.8 kB
Tags Source
SHA-256 checksum
How to use checksums
9a1dd47ece661f92b70a742b5682cbdd1a9df6d5b0c152deb9e33898f4a06b16
BLAKE2b-256 checksum
How to use checksums
6b3455b5d31c0258764a31144a3751e990f87ffce5c897a14cf1f526809c591c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.0.1 CPython/3.12.8

Release files / claudetools-1.0.3-py3-none-any.whl

Download URL claudetools-1.0.3-py3-none-any.whl
Size 16.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8bf43f779e9f9f4f26bab2fddcf6b3d6a43cacddfc9f0532506d2e26156cb643
BLAKE2b-256 checksum
How to use checksums
9d1cac6ab4a165a4646b715a4d1d3b504e36b1dc41b87e034e8bdc9440f41d3e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.0.1 CPython/3.12.8

Release history Release notifications | RSS feed

This release

1.0.3 This release

2 release files

1.0.2

2 release files

1.0.1

2 release files

1.0.0

2 release files

0.9.1

2 release files

0.9.0

2 release files

0.8.0

2 release files

0.7.0

2 release files

0.6.0

2 release files

0.5.0

2 release files

0.4.0

2 release files

0.2.0

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page