Skip to content

atoms

Atoms are the fundamental, indivisible building blocks of SilverLingua. They represent single-purpose, foundational components that can't be broken down further while remaining useful.

See Design Principles - Atoms for more details.

Memory

Bases: BaseModel

A Memory is the smallest unit of storage information, and is the base class for all other storage information like [Notion][silverlingua.core.molecules.notion.Notion].

content instance-attribute

content: str

ChatRole

Bases: Enum

Standardized roles for chat messages.

Warning

Do not instantiate this enum directly. Use [create_chat_role()][silverlingua.core.atoms.role.chat.create_chat_role] instead.

SYSTEM class-attribute instance-attribute

SYSTEM = RoleMember('SYSTEM', 'SYSTEM')

HUMAN class-attribute instance-attribute

HUMAN = RoleMember('HUMAN', 'HUMAN')

AI class-attribute instance-attribute

AI = RoleMember('AI', 'AI')

TOOL_CALL class-attribute instance-attribute

TOOL_CALL = RoleMember('TOOL_CALL', 'TOOL_CALL')

TOOL_RESPONSE class-attribute instance-attribute

TOOL_RESPONSE = RoleMember('TOOL_RESPONSE', 'TOOL_RESPONSE')

ReactRole

Bases: Enum

Standardized roles for ReAct framework to help with chain-of-thought prompting.

See: https://www.promptingguide.ai/techniques/react

Warning

Do not instantiate this enum directly. Use [create_react_role()][silverlingua.core.atoms.role.react.create_react_role] instead.

QUESTION class-attribute instance-attribute

QUESTION = RoleMember('QUESTION', 'QUESTION')

THOUGHT class-attribute instance-attribute

THOUGHT = RoleMember('THOUGHT', 'THOUGHT')

ACTION class-attribute instance-attribute

ACTION = RoleMember('ACTION', 'ACTION')

OBSERVATION class-attribute instance-attribute

OBSERVATION = RoleMember('OBSERVATION', 'OBSERVATION')

ANSWER class-attribute instance-attribute

ANSWER = RoleMember('ANSWER', 'ANSWER')

Tokenizer

Bases: BaseModel

A tokenizer that can encode and decode strings.

encode instance-attribute

encode: Callable[[str], List[int]]

decode instance-attribute

decode: Callable[[List[int]], str]

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

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))

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)

RolePrompt

RolePrompt(role: str, text: str)

{{ role }}: {{ text }}

Source code in src/SilverLingua/core/atoms/prompt.py
@prompt
def RolePrompt(role: str, text: str):  # type: ignore
    """{{ role }}: {{ text }}"""

create_chat_role

create_chat_role(name: str, SYSTEM: str, HUMAN: str, AI: str, TOOL_CALL: str, TOOL_RESPONSE: str) -> Type[ChatRole]

Create a new ChatRole enum with only the values of the RoleMembers changed.

This will ensure that the parent of each member is ChatRole, which means that the members will be equal to the members of ChatRole.

Example
OpenAIChatRole = create_chat_role(
    "OpenAIChatRole",
    SYSTEM="system",
    HUMAN="user",
    AI="assistant",
    TOOL_CALL="function_call",
    TOOL_RESPONSE="function",
)

assert OpenAIChatRole.SYSTEM == ChatRole.SYSTEM # True
Source code in src/SilverLingua/core/atoms/role/chat.py
def create_chat_role(
    name: str, SYSTEM: str, HUMAN: str, AI: str, TOOL_CALL: str, TOOL_RESPONSE: str
) -> Type[ChatRole]:
    """
    Create a new ChatRole enum with only the values of the RoleMembers changed.

    This will ensure that the parent of each member is ChatRole, which means
    that the members will be equal to the members of ChatRole.

    Example:
        ```python
        OpenAIChatRole = create_chat_role(
            "OpenAIChatRole",
            SYSTEM="system",
            HUMAN="user",
            AI="assistant",
            TOOL_CALL="function_call",
            TOOL_RESPONSE="function",
        )

        assert OpenAIChatRole.SYSTEM == ChatRole.SYSTEM # True
        ```
    """
    return Enum(
        name,
        {
            "SYSTEM": RoleMember("SYSTEM", SYSTEM, ChatRole),
            "HUMAN": RoleMember("HUMAN", HUMAN, ChatRole),
            "AI": RoleMember("AI", AI, ChatRole),
            "TOOL_CALL": RoleMember("TOOL_CALL", TOOL_CALL, ChatRole),
            "TOOL_RESPONSE": RoleMember("TOOL_RESPONSE", TOOL_RESPONSE, ChatRole),
        },
    )

create_react_role

create_react_role(name: str, QUESTION: str, THOUGHT: str, ACTION: str, OBSERVATION: str, ANSWER: str) -> Type[ReactRole]
Source code in src/SilverLingua/core/atoms/role/react.py
def create_react_role(
    name: str,
    QUESTION: str,
    THOUGHT: str,
    ACTION: str,
    OBSERVATION: str,
    ANSWER: str,
) -> Type[ReactRole]:
    return Enum(
        name,
        {
            "QUESTION": RoleMember("QUESTION", QUESTION, ReactRole),
            "THOUGHT": RoleMember("THOUGHT", THOUGHT, ReactRole),
            "ACTION": RoleMember("ACTION", ACTION, ReactRole),
            "OBSERVATION": RoleMember("OBSERVATION", OBSERVATION, ReactRole),
            "ANSWER": RoleMember("ANSWER", ANSWER, ReactRole),
        },
    )