Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How do I define and call custom functions using Claudetools


How do I define and call custom functions using Claudetools


Here is how you can define and call custom functions using the Claudetools library:

The key steps are:

1. Define your functions: Create Pydantic models to define the input parameters for your functions. Then implement the functions that will be called by Claude.

python
from pydantic import BaseModel, Field

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

def add_todo(params: AddTodo):
    todos.append(params.text)
    return f"Added TODO: {params.text}"

2. Create a list of function definitions: Specify the name, description, and parameter schema for each function you want to make available to Claude.

python
functions = [
    {
        "name": "add_todo",
        "description": "Add a new TODO",
        "parameters": AddTodo.schema()
    }
]

3. Call the Claudetools Tool with your functions: Create a Tool instance with your Anthropic API key, and call the tool with the list of functions, user messages, and other required parameters.

python
from claudetools.tools.tool import Tool

tool = Tool(ANTHROPIC_API_KEY)
output = tool(model="claude-3-sonnet-20240229", messages=user_messages, tools=functions, ...)

4. Handle the tool output: The tool call will return the result of the function call, which you can then process and return to the user.

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

The key benefits of using Claudetools are:

- Flexible function definition: Define your functions using Pydantic models for type safety and validation.
- Synchronous and asynchronous support: Choose between synchronous or asynchronous interaction modes.
- Multiple tools support: Call multiple functions within a single prompt.
- Customizable system prompts: Attach custom system prompts for better context and control.

By following this approach, you can easily integrate your own custom functions with the powerful capabilities of the Claude 3 model[1][5].

Citations:
[1] https://github.com/vatsalsaglani/claudetools
[2] https://www.make.com/en/help/functions/custom-functions
[3] https://help.claris.com/archive/help/18/fmp/en/FMP_Help/custom-functions.html
[4] https://mathda.com/en/calculator-usages/calces/custom-functions
[5] https://docs.anthropic.com/en/docs/build-with-claude/tool-use