Skip to content

tool

Tool

Tool(function: Callable)

Bases: BaseModel

A wrapper class for functions that allows them to be both directly callable and serializable to JSON for use with an LLM.

Attributes:

Name Type Description
function Callable

The function to be wrapped.

description FunctionJSONSchema

A TypedDict that describes the function according to JSON schema standards.

name str

The name of the function, extracted from the FunctionJSONSchema.

See also
  • [Agent][silverlingua.core.templates.agent.Agent]
  • [Model][silverlingua.core.templates.model.Model]
Example
def my_function(x, y):
    return x + y

# Create a Tool instance
tool_instance = Tool(my_function)

# Directly call the wrapped function
result = tool_instance(1, 2)  # Output will be 3

# Serialize to JSON
serialized = str(tool_instance)

####
# Alternatively, you can use the decorator to turn a function into a Tool.
####

@tool
def my_function(x, y):
    return x + y

# Now the function itself is already a Tool.
result = my_function(1, 2)  # Output will be 3

Parameters:

Name Type Description Default
function Callable

The function to be turned into a Tool.

required
Source code in src/SilverLingua/core/atoms/tool/tool.py
def __init__(self, function: Callable):
    """
    Args:
        function (Callable): The function to be turned into a Tool.
    """
    description = generate_function_json(function)
    name = description.name
    super().__init__(function=function, description=description, name=name)

function class-attribute instance-attribute

function: Callable = Field(exclude=True)

description class-attribute instance-attribute

description: FunctionJSONSchema = Field(validate_default=True)

name class-attribute instance-attribute

name: str = Field(validate_default=True)

use_function_call

use_function_call(function_call: ToolCallFunction)

Uses a FunctionCall to call the function.

Source code in src/SilverLingua/core/atoms/tool/tool.py
def use_function_call(self, function_call: ToolCallFunction):
    """
    Uses a FunctionCall to call the function.
    """
    arguments_dict = function_call.arguments
    if arguments_dict == "":
        return json.dumps(self.function())

    try:
        arguments_dict = json.loads(function_call.arguments)
    except json.JSONDecodeError:
        raise ValueError(
            "ToolCall.arguments must be a JSON string.\n"
            + f"function_call.arguments: {function_call.arguments}\n"
            + f"json.loads result: {arguments_dict}"
        ) from None

    return json.dumps(self.function(**arguments_dict))

FunctionJSONSchema

Bases: BaseModel

A function according to JSON schema standards.

This is also passed in to OpenAI ChatCompletion API functions list so the AI understands how to call a function.

Attributes:

Name Type Description
name str

The name of the function

description str

A description of the function

parameters Parameters

A dictionary of parameters and their types (Optional)

Example:

{
    "name": "roll_dice",
    "description": "Rolls a number of dice with a given number of sides, optionally
        with a modifier and/or advantage/disadvantage.
        Returns `{result: int, rolls: int[]}`",
    "parameters": {
        "type": "object",
        "properties": {
            "sides": {
              "description": "The number of sides on each die",
              "type": "integer"
            },
            "dice": {
              "description": "The number of dice to roll (default 1)",
              "type": "integer"
            },
            "modifier": {
              "description": "The modifier to add to the roll total (default 0)",
              "type": "integer"
            },
            "advantage": {
              "description": "Whether to roll with advantage (default False)",
              "type": "boolean"
            },
            "disadvantage": {
              "description": "Whether to roll with disadvantage (default False)",
              "type": "boolean"
            }
        }
    }
}

name instance-attribute

name: str

description instance-attribute

description: str

parameters instance-attribute

parameters: Parameters

ToolCall

Bases: BaseModel

model_config class-attribute instance-attribute

model_config = ConfigDict(extra='allow', ignored_types=(type(None)))

function instance-attribute

function: ToolCallFunction

id class-attribute instance-attribute

id: str = Field(default_factory=lambda: str(uuid4()))

index class-attribute instance-attribute

index: Optional[int] = None

string_if_none

string_if_none(v)
Source code in src/SilverLingua/core/atoms/tool/util.py
@field_validator("id", mode="before")
def string_if_none(cls, v):
    return v if v is not None else str(uuid4())

concat

concat(other: ToolCall) -> ToolCall

Concatenates two tool calls and returns the result.

If the IDs are different, prioritize the ID of 'self'. For 'function', merge the 'name' and 'arguments' fields.

We will prefer the id of self over other for 2 reasons: 1. We assume that self is the older of the two 2. The newer may be stream chunked, in which case the id of other may have been None and generated using UUID, but the older ID likely was generated by an API and thus this newer ID is not the true ID.

Source code in src/SilverLingua/core/atoms/tool/util.py
def concat(self, other: "ToolCall") -> "ToolCall":
    """
    Concatenates two tool calls and returns the result.

    If the IDs are different, prioritize the ID of 'self'.
    For 'function', merge the 'name' and 'arguments' fields.

    We will prefer the `id` of self over other for 2 reasons:
    1. We assume that self is the older of the two
    2. The newer may be stream chunked, in which case
    the `id` of `other` may have been `None` and generated
    using UUID, but the older ID likely was generated
    by an API and thus this newer ID is not the true ID.
    """
    merged_function = {
        "name": self.function.name or other.function.name,
        "arguments": (self.function.arguments or "")
        + (other.function.arguments or ""),
    }
    merged_function = ToolCallFunction(**merged_function)

    self_extra = self.__pydantic_extra__
    other_extra = other.__pydantic_extra__

    index = self.index if self.index is not None else other.index

    # Compare the two extra fields
    if self_extra != other_extra:
        if not self_extra or not other_extra:
            return ToolCall(
                id=(self.id) or other.id,
                function=merged_function,
                index=index,
                **(self_extra or {}),
                **(other_extra or {}),
            )
        # If they are different, merge them
        merged_extra = {}
        for key in set(self_extra.keys()) | set(other_extra.keys()):
            if key in self_extra and key in other_extra:
                # If one is None, use the other
                # Else, concatenate them
                if self_extra[key] == other_extra[key]:
                    merged_extra[key] = self_extra[key]
                else:
                    if self_extra[key] is None or other_extra[key] is None:
                        merged_extra[key] = self_extra[key] or other_extra[key]
                    else:
                        merged_extra[key] = self_extra[key] + other_extra[key]
            elif key in self_extra:
                merged_extra[key] = self_extra[key]
            elif key in other_extra:
                merged_extra[key] = other_extra[key]
        #
        return ToolCall(
            id=self.id or other.id,
            function=merged_function,
            index=index,
            **merged_extra,
        )

    return ToolCall(
        id=self.id or other.id,
        function=merged_function,
        index=index,
        **(self_extra or {}),
    )

ToolCallFunction

Bases: BaseModel

name class-attribute instance-attribute

name: str = Field(default='')

arguments class-attribute instance-attribute

arguments: str = Field(default='')

string_if_none

string_if_none(v)
Source code in src/SilverLingua/core/atoms/tool/util.py
@field_validator("*", mode="before")
def string_if_none(cls, v):
    return v if v is not None else ""

ToolCallResponse

Bases: BaseModel

The response property of a tool call.

tool_call_id instance-attribute

tool_call_id: str

name instance-attribute

name: str

content instance-attribute

content: str

from_tool_call classmethod

from_tool_call(tool_call: ToolCall, response: str) -> ToolCallResponse
Source code in src/SilverLingua/core/atoms/tool/util.py
@classmethod
def from_tool_call(cls, tool_call: "ToolCall", response: str) -> "ToolCallResponse":
    return cls(
        tool_call_id=tool_call.id,
        name=tool_call.function.name,
        content=response,
    )

ToolCalls

Bases: BaseModel

A list of tool calls.

list class-attribute instance-attribute

list: List[ToolCall] = Field(default_factory=list, frozen=True)

concat

concat(other: ToolCalls) -> ToolCalls

Concatenates two tool calls lists and returns the result.

Source code in src/SilverLingua/core/atoms/tool/util.py
def concat(self, other: "ToolCalls") -> "ToolCalls":
    """
    Concatenates two tool calls lists and returns the result.
    """
    new: List[ToolCall] = self.list.copy()
    for tool_call in other.list:
        found = False
        # Find the tool call with the same ID
        for i, self_tool_call in enumerate(new):
            if (
                self_tool_call.id == tool_call.id
                or self_tool_call.index == tool_call.index
            ):
                new[i] = self_tool_call.concat(tool_call)
                found = True
        if not found:
            new.append(tool_call)
    return ToolCalls(list=new)