Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Can I use typing.Literal to constrain values in Claudetools
    claude sonnet


Can I use typing.Literal to constrain values in Claudetools


Yes, you can use `typing.Literal` to constrain the values of function parameters in Claudetools. Here's how you can do it:

1. Define your function parameters using Literal types:

python
from typing import Literal

class AddTodo(BaseModel):
    text: Literal["buy milk", "clean the house", "call mom"]

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

In this example, the `text` parameter of the `AddTodo` model is constrained to only accept the literal string values `"buy milk"`, `"clean the house"`, or `"call mom"`.

2. Create a list of function definitions with the Literal parameter schemas:

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

3. Call the Claudetools Tool with the list of functions:

python
from claudetools.tools.tool import Tool

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

When you call the tool with the `AddTodo` model, Claudetools will automatically validate that the input value matches one of the literal string values defined in the `Literal` type.

This allows you to precisely constrain the allowed values for your function parameters, ensuring that the input data is valid and consistent with your application's requirements.

The key benefits of using `typing.Literal` in Claudetools are:

1. Type safety: Static type checkers can verify that the input values match the expected literal types.
2. Explicit documentation: The Literal types clearly communicate the allowed values to users of your functions.
3. Runtime validation: Claudetools will automatically validate the input data against the Literal types at runtime.

By leveraging `typing.Literal` in your Claudetools functions, you can create a more robust and reliable integration between your Python application and the Claude 3 model.

Citations:
[1] https://typing.readthedocs.io/en/latest/spec/literal.html
[2] https://testdriven.io/tips/c61d55d8-caa7-4ab4-b611-7356bddc0181/
[3] https://github.com/tiangolo/sqlmodel/issues/57
[4] https://github.com/sphinx-doc/sphinx/issues/9195
[5] https://stackoverflow.com/questions/59163553/getting-the-literal-out-of-a-python-literal-type-at-runtime