GithubHelp home page GithubHelp logo

vatsalsaglani / claudetools Goto Github PK

View Code? Open in Web Editor NEW
25.0 2.0 4.0 55 KB

Claudetools is a Python library that enables function calling with the Claude 3 family of language models from Anthropic.

License: MIT License

Python 100.00%
anthropic anthropic-claude claude-3 function-call function-calling tools

claudetools's Introduction

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.

claudetools's People

Contributors

fannan avatar vatsalsaglani avatar vatsalsqyrus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

claudetools's Issues

The AnthropicBedrock is not working for Sonnet model

ame\": \"getWeather\", \"parameters\": {\"city\": \"NY\"}} </functioncall>\n        <functioncall> {\"name\": \"getWeather\", \"parameters\": {\"city\": \"LA\"}} </functioncall>\n    </multiplefunctions>\n\nTask: 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.\nThe user can provide multiple actions at once so you've to break those down and call the appropriate functions in the correct sequence.",
    "max_tokens": 1000
}
2024-04-27 16:43:57 - httpx - INFO - HTTP Request: POST https://bedrock-runtime.us-east-1.amazonaws.com/model/anthropic.claude-3-sonnet-20240229/invoke "HTTP/1.1 403 Forbidden"
Traceback (most recent call last):
  File "/Users/anantkan/autoContra/claude.py", line 56, in <module>
    output = tool(model="anthropic.claude-3-sonnet-20240229",
  File "/Users/anantkan/autoContra/myenv/lib/python3.9/site-packages/claudetools/tools/tool.py", line 101, in __call__
    return asyncio.run(
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete
    return future.result()
  File "/Users/anantkan/autoContra/myenv/lib/python3.9/site-packages/claudetools/tools/tool.py", line 61, in tool_call
    output = await self.perform_model_call(model,
  File "/Users/anantkan/autoContra/myenv/lib/python3.9/site-packages/claudetools/tools/tool.py", line 91, in perform_model_call
    return self.complete(model, messages, system=system, **kwargs)
  File "/Users/anantkan/autoContra/myenv/lib/python3.9/site-packages/claudetools/completion/complete.py", line 33, in __call__
    output = self.client.messages.create(model=model,
  File "/Users/anantkan/autoContra/myenv/lib/python3.9/site-packages/anthropic/_utils/_utils.py", line 275, in wrapper
    return func(*args, **kwargs)
  File "/Users/anantkan/autoContra/myenv/lib/python3.9/site-packages/anthropic/resources/messages.py", line 658, in create
    return self._post(
  File "/Users/anantkan/autoContra/myenv/lib/python3.9/site-packages/anthropic/_base_client.py", line 1208, in post
    return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls))
  File "/Users/anantkan/autoContra/myenv/lib/python3.9/site-packages/anthropic/_base_client.py", line 897, in request
    return self._request(
  File "/Users/anantkan/autoContra/myenv/lib/python3.9/site-packages/anthropic/_base_client.py", line 988, in _request
    raise self._make_status_error_from_response(err.response) from None
anthropic.PermissionDeniedError: Error code: 403 - {'message': 'The security token included in the request is invalid.'}
(myenv) anantkan@f84d898fedb6 autoContra % ```

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.