Decorators#
Public decorators for extending or integrating with the framework.
This module contains decorators that are part of the public API and intended for end users to apply to their own functions or classes.
- contextgem.public.decorators.register_tool(func, /)[source]#
Registers a function as a tool for LLM chat with tools.
The function defines the tool: its name is the name of the tool, its docstring describes the tool to the LLM, and its parameters, with their type hints and default values, define the parameters of the tool. The descriptions of the parameters are taken from the docstring, or from
Annotatedtype hints, which can also set constraints, e.g.Annotated[int, Field(description="...", ge=1)].Pass the decorated function to
toolsof the LLM. To use an object of your application in a tool, e.g. a database connection, define the tool as a function that uses it, e.g. a closure: a bound method or afunctools.partialcannot be registered.An async function runs in the event loop of the chat, and a sync function in a worker thread, without an event loop, so that it does not block the loop and can use libraries that refuse to run where one is running, e.g. the ORM of Django. Such a function does not see what the calling code keeps for its own thread, e.g. an open database transaction.
To tell the LLM why a call failed, e.g. that a record does not exist, the function raises
ToolCallError, whose message is sent to the LLM, which can call the tool again. Any other exception that it raises stops the chat, and is raised fromchat()as it is.- Parameters:
func (
collections.abc.Callable[...,str] |collections.abc.Callable[...,collections.abc.Coroutine[typing.Any,typing.Any,str]]) – A function to be used as a tool. Can be sync or async, and must return a non-empty string.- Returns:
The same function, marked as a registered tool.
- Return type:
collections.abc.Callable[...,str] |collections.abc.Callable[...,collections.abc.Coroutine[typing.Any,typing.Any,str]]- Raises:
TypeError – If the provided object is not callable, if it is a bound method or a
functools.partial, or if a parameter of the function has no type hint.ValueError – If the signature cannot be inspected, if the function has positional-only parameters or accepts
*argsor**kwargs, if it has no docstring, or if the function name is empty.