Skip to content

API Reference

SilverLingua

SilverLingua - An AI agent framework

Config

modules class-attribute instance-attribute

modules: List[Module] = []

chat_roles class-attribute instance-attribute

chat_roles: List[type[ChatRole]] = [ChatRole]

react_roles class-attribute instance-attribute

react_roles: List[type[ReactRole]] = [ReactRole]

tools class-attribute instance-attribute

tools: List[Tool] = []

get_chat_role classmethod

get_chat_role(role: str) -> Optional[ChatRole]

Attempts to get the standardized ChatRole enum from 'role'. If not, returns None.

This is usually used internally for maintaining consistency in Notions across different LLM backends.

Source code in src/SilverLingua/config.py
@classmethod
def get_chat_role(self, role: str) -> Optional[ChatRole]:
    """
    Attempts to get the standardized ChatRole enum from 'role'.
    If not, returns None.

    This is usually used internally for maintaining
    consistency in Notions across different LLM backends.
    """
    for enum_class in self.chat_roles:
        for enum_member in enum_class:
            if str(enum_member.value).lower() == str(role).lower():
                return ChatRole[enum_member.name]
    return None

get_react_role classmethod

get_react_role(role: str) -> Optional[ReactRole]

Attempts to get the standardized ReactRole enum from 'role'. If not, returns None.

This is usually used internally for maintaining consistency in Notions across different LLM backends.

Source code in src/SilverLingua/config.py
@classmethod
def get_react_role(self, role: str) -> Optional[ReactRole]:
    """
    Attempts to get the standardized ReactRole enum from 'role'.
    If not, returns None.

    This is usually used internally for maintaining
    consistency in Notions across different LLM backends.
    """
    for enum_class in self.react_roles:
        for enum_member in enum_class:
            if enum_member.value == role:
                return ReactRole[enum_member.name]
    return None

get_tool classmethod

get_tool(name: str) -> Optional[Tool]

Attempts to get the tool with the given name. If not, returns None.

Source code in src/SilverLingua/config.py
@classmethod
def get_tool(self, name: str) -> Optional[Tool]:
    """
    Attempts to get the tool with the given name.
    If not, returns None.
    """
    for tool in self.tools:
        if tool.name == name:
            return tool
    return None

add_tool classmethod

add_tool(tool: Tool) -> None

Adds a tool to the config.

Source code in src/SilverLingua/config.py
@classmethod
def add_tool(self, tool: Tool) -> None:
    """
    Adds a tool to the config.
    """
    self.tools.append(tool)

add_chat_role classmethod

add_chat_role(role: Type[Enum]) -> None

Adds a chat role to the config.

Source code in src/SilverLingua/config.py
@classmethod
def add_chat_role(self, role: Type[Enum]) -> None:
    """
    Adds a chat role to the config.
    """
    if not issubclass(role, Enum):
        raise TypeError("Expected an enum")
    self.chat_roles.append(role)

add_react_role classmethod

add_react_role(role: Type[Enum]) -> None

Adds a react role to the config.

Source code in src/SilverLingua/config.py
@classmethod
def add_react_role(self, role: Type[Enum]) -> None:
    """
    Adds a react role to the config.
    """
    if not issubclass(role, Enum):
        raise TypeError("Expected an enum")
    self.react_roles.append(role)

register_module classmethod

register_module(module: Module) -> None

Registers a module.

Source code in src/SilverLingua/config.py
@classmethod
def register_module(self, module: Module) -> None:
    """
    Registers a module.
    """
    self.modules.append(module)
    for tool in module.tools:
        self.add_tool(tool)
    for chat_role in module.chat_roles:
        self.add_chat_role(chat_role)
    for react_role in module.react_roles:
        self.add_react_role(react_role)

    logger.debug(
        f'Registered module {module.name}@{module.version}: "{module.description}"'
    )

Module

Module(name: str, description: str, version: str, tools: List[Tool], chat_roles: List[type[ChatRole]], react_roles: List[type[ReactRole]], **kwargs)

Bases: BaseModel

A module that can be loaded into SilverLingua.

Attributes:

Name Type Description
name str

The name of the module.

description str

A description of the module.

version str

The version of the module.

tools List[Tool]

The tools in the module.

chat_roles List[type[ChatRole]]

The chat roles in the module.

react_roles List[type[ReactRole]]

The react roles in the module.

Source code in src/SilverLingua/config.py
def __init__(
    self,
    name: str,
    description: str,
    version: str,
    tools: List[Tool],
    chat_roles: List[type[ChatRole]],
    react_roles: List[type[ReactRole]],
    **kwargs,
):
    super().__init__(
        name=name,
        description=description,
        version=version,
        tools=tools,
        chat_roles=chat_roles,
        react_roles=react_roles,
        **kwargs,
    )

    Config.register_module(self)

name instance-attribute

name: str

description instance-attribute

description: str

version instance-attribute

version: str

tools instance-attribute

tools: List[Tool]

chat_roles instance-attribute

chat_roles: List[type[ChatRole]]

react_roles instance-attribute

react_roles: List[type[ReactRole]]

check_chat_roles

check_chat_roles(v)
Source code in src/SilverLingua/config.py
@field_validator("chat_roles", mode="plain")
def check_chat_roles(cls, v):
    for role in v:
        if not issubclass(role, Enum):
            raise TypeError("Expected an enum")
        else:
            for member in role:
                if (
                    not ChatRole[member.name]
                    or member.value != ChatRole[member.name].value
                ):
                    raise TypeError("members must match ChatRole members.")
    return v

check_react_roles

check_react_roles(v)
Source code in src/SilverLingua/config.py
@field_validator("react_roles", mode="plain")
def check_react_roles(cls, v):
    for role in v:
        if not issubclass(role, Enum):
            raise TypeError("Expected an enum")
        else:
            for member in role:
                if (
                    not ReactRole[member.name]
                    or member.value != ReactRole[member.name].value
                ):
                    raise TypeError("members must match ReactRole members.")
    return v

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

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

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

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)

Bases: Memory

A memory that can have a parent and children Links, forming a hierarchical structure of interconnected memories.

The content can be either a [Notion][silverlingua.core.molecules.notion.Notion] or a [Memory][silverlingua.core.atoms.memory.Memory]. (You can still use the content as a string via str(link.content).)

content instance-attribute

content: Union[Notion, Memory]

parent class-attribute instance-attribute

parent: Optional[Link] = None

children class-attribute instance-attribute

children: List[Link] = Field(default_factory=list)

path property

path: List[Link]

Returns the path from the root to this Link.

root property

root: Link

Returns the root Link of this Link.

depth property

depth: int

Returns 1 based depth of this Link.

is_root property

is_root: bool

Returns whether this Link is a root Link.

is_leaf property

is_leaf: bool

Returns whether this Link is a leaf Link.

is_branch property

is_branch: bool

Returns whether this Link is a branch Link.

path_string property

path_string: str

Returns the path from the root to this Link as a string.

Example: "root>child>grandchild"

add_child

add_child(child: Link) -> None
Source code in src/SilverLingua/core/molecules/link.py
def add_child(self, child: "Link") -> None:
    self.children.append(child)
    child.parent = self

remove_child

remove_child(child: Link) -> None
Source code in src/SilverLingua/core/molecules/link.py
def remove_child(self, child: "Link") -> None:
    self.children.remove(child)
    child.parent = None

Notion

Notion(content: str, role: Union[ChatRole, ReactRole, str], persistent: bool = False)

Bases: Memory

A memory that stores the role associated with its content. The role is usually a [ChatRole][silverlingua.core.atoms.role.chat.ChatRole] or a [ReactRole][silverlingua.core.atoms.role.react.ReactRole]. (See [atoms/roles][silverlingua.core.atoms.role])

Attributes:

Name Type Description
role str

The role of the notion.

content str

The content of the memory.

persistent bool

Whether the notion should be stored in long-term memory.

Source code in src/SilverLingua/core/molecules/notion.py
def __init__(
    self,
    content: str,
    role: Union[ChatRole, ReactRole, str],
    persistent: bool = False,
):
    super().__init__(content=content, role=role, persistent=persistent)

content instance-attribute

content: str

model_config class-attribute instance-attribute

model_config = ConfigDict(from_attributes=True)

role instance-attribute

role: str

persistent class-attribute instance-attribute

persistent: bool = False

chat_role property

chat_role: ChatRole

Gets the chat based role Enum (e.g. Role.SYSTEM, Role.HUMAN, etc.)

(See config)

react_role property

react_role: ReactRole

Gets the react based role Enum (e.g. Role.THOUGHT, Role.OBSERVATION, etc.)

(See config)

validate_role classmethod

validate_role(v: Union[ChatRole, ReactRole, str])
Source code in src/SilverLingua/core/molecules/notion.py
@field_validator("role", mode="before")
@classmethod
def validate_role(cls, v: Union[ChatRole, ReactRole, str]):
    if isinstance(v, (ChatRole, ReactRole)):
        return v.value.value
    elif isinstance(v, str):
        return v
    raise ValueError(f"Expected a ChatRole, ReactRole, or a string, got {type(v)}")

Idearium

Idearium(tokenizer: Tokenizer, max_tokens: int, notions: List[Notion] = None, **kwargs)

Bases: BaseModel

A collection of [Notions][silverlingua.core.molecules.notion.Notion] that is automatically trimmed to fit within a maximum number of tokens.

Source code in src/SilverLingua/core/organisms/idearium.py
def __init__(
    self,
    tokenizer: Tokenizer,
    max_tokens: int,
    notions: List[Notion] = None,
    **kwargs,
):
    # Initialize with empty notions if None
    notions = notions or []

    # Initialize tokenized_notions
    tokenized_notions = [tokenizer.encode(notion.content) for notion in notions]

    # Call parent init with all values
    super().__init__(
        tokenizer=tokenizer,
        max_tokens=max_tokens,
        notions=notions,
        tokenized_notions=tokenized_notions,
        **kwargs,
    )

model_config class-attribute instance-attribute

model_config = ConfigDict(frozen=True)

tokenizer instance-attribute

tokenizer: Tokenizer

max_tokens instance-attribute

max_tokens: int

notions class-attribute instance-attribute

notions: List[Notion] = Field(default_factory=list)

tokenized_notions class-attribute instance-attribute

tokenized_notions: List[List[int]] = Field(default_factory=list)

persistent_indices class-attribute instance-attribute

persistent_indices: set = Field(default_factory=set)

total_tokens property

total_tokens: int

The total number of tokens in the Idearium.

_non_persistent_indices property

_non_persistent_indices: set

The indices of non-persistent notions.

validate_notions

validate_notions(values)
Source code in src/SilverLingua/core/organisms/idearium.py
@model_validator(mode="after")
def validate_notions(cls, values):
    notions = values.notions
    for notion in notions:
        cls.validate_notion(notion, values.max_tokens, values.tokenizer)
    return values

validate_notion classmethod

validate_notion(notion: Notion, max_tokens: int, tokenizer: Tokenizer)
Source code in src/SilverLingua/core/organisms/idearium.py
@classmethod
def validate_notion(cls, notion: Notion, max_tokens: int, tokenizer: Tokenizer):
    if len(notion.content) == 0:
        raise ValueError("Notion content cannot be empty.")

    tokenized_notion = tokenizer.encode(notion.content)
    if len(tokenized_notion) > max_tokens:
        raise ValueError("Notion exceeds maximum token length")

    return tokenized_notion

index

index(notion: Notion) -> int

Returns the index of the first occurrence of the given notion.

Source code in src/SilverLingua/core/organisms/idearium.py
def index(self, notion: Notion) -> int:
    """Returns the index of the first occurrence of the given notion."""
    return self.notions.index(notion)

append

append(notion: Notion)

Appends the given notion to the end of the Idearium.

Source code in src/SilverLingua/core/organisms/idearium.py
def append(self, notion: Notion):
    """Appends the given notion to the end of the Idearium."""
    logger.debug(f"Appending notion: {notion.content!r}")
    tokenized_notion = self.tokenizer.encode(notion.content)

    if self.notions:
        logger.debug(f"Current last notion: {self.notions[-1].content!r}")

    if (
        self.notions
        and self.notions[-1].role == notion.role
        and self.notions[-1].persistent == notion.persistent
    ):
        combined_content = self.notions[-1].content + notion.content
        combined_notion = Notion(
            content=combined_content,
            role=notion.role,
            persistent=notion.persistent,
        )
        self.replace(len(self.notions) - 1, combined_notion)
        logger.debug(
            f"After replace, about to return combined content: {combined_content!r}"
        )
        return

    logger.debug(f"Hitting append path. Appending new notion: {notion.content!r}")
    self.notions.append(notion)
    self.tokenized_notions.append(tokenized_notion)

    if notion.persistent:
        # Modify the set in place instead of reassigning
        self.persistent_indices.add(len(self.notions) - 1)

    self._trim()

extend

extend(notions: Union[List[Notion], Idearium])

Extends the Idearium with the given list of notions.

Source code in src/SilverLingua/core/organisms/idearium.py
def extend(self, notions: Union[List[Notion], "Idearium"]):
    """Extends the Idearium with the given list of notions."""
    if isinstance(notions, Idearium):
        notions = notions.notions

    for notion in notions:
        self.append(notion)

insert

insert(index: int, notion: Notion)

Inserts the given notion at the given index.

Source code in src/SilverLingua/core/organisms/idearium.py
def insert(self, index: int, notion: Notion):
    """Inserts the given notion at the given index."""
    tokenized_notion = self.tokenizer.encode(notion.content)

    self.notions.insert(index, notion)
    self.tokenized_notions.insert(index, tokenized_notion)

    # Update persistent_indices in place
    new_indices = {i + 1 if i >= index else i for i in self.persistent_indices}
    self.persistent_indices.clear()
    self.persistent_indices.update(new_indices)
    if notion.persistent:
        self.persistent_indices.add(index)

    self._trim()

remove

remove(notion: Notion)

Removes the first occurrence of the given notion.

Source code in src/SilverLingua/core/organisms/idearium.py
def remove(self, notion: Notion):
    """Removes the first occurrence of the given notion."""
    index = self.index(notion)
    self.pop(index)

pop

pop(index: int) -> Notion

Removes and returns the notion at the given index.

Source code in src/SilverLingua/core/organisms/idearium.py
def pop(self, index: int) -> Notion:
    """Removes and returns the notion at the given index."""
    ret = self.notions.pop(index)
    self.tokenized_notions.pop(index)

    # Update persistent_indices
    # Modify the set in place instead of reassigning
    self.persistent_indices.discard(index)
    new_indices = {i - 1 if i > index else i for i in self.persistent_indices}
    self.persistent_indices.clear()
    self.persistent_indices.update(new_indices)

    return ret

replace

replace(index: int, notion: Notion)

Replaces the notion at the given index with the given notion.

Source code in src/SilverLingua/core/organisms/idearium.py
def replace(self, index: int, notion: Notion):
    """Replaces the notion at the given index with the given notion."""
    self.notions[index] = notion
    self.tokenized_notions[index] = self.tokenizer.encode(notion.content)

    # Update persistent_indices based on the replaced notion
    if notion.persistent:
        self.persistent_indices.add(index)
    else:
        self.persistent_indices.discard(index)

    self._trim()

copy

copy() -> Idearium

Returns a copy of the Idearium.

Source code in src/SilverLingua/core/organisms/idearium.py
def copy(self) -> "Idearium":
    """Returns a copy of the Idearium."""
    return Idearium(
        tokenizer=self.tokenizer,
        max_tokens=self.max_tokens,
        notions=self.notions.copy(),
        tokenized_notions=self.tokenized_notions.copy(),
        persistent_indices=self.persistent_indices.copy(),
    )

_trim

_trim()

Trims the Idearium to fit within the maximum number of tokens, called after every modification.

This is the primary point of extension for Idearium subclasses, as it allows for custom trimming behavior.

Source code in src/SilverLingua/core/organisms/idearium.py
def _trim(self):
    """
    Trims the Idearium to fit within the maximum number of tokens, called
    after every modification.

    This is the primary point of extension for Idearium subclasses, as it
    allows for custom trimming behavior.
    """
    while self.total_tokens > self.max_tokens:
        non_persistent_indices = self._non_persistent_indices

        # Check if there's only one non-persistent user message
        if len(non_persistent_indices) == 1:
            single_index = next(iter(non_persistent_indices))
            tokenized_notion = self.tokenized_notions[single_index]

            # Trim the only non-persistent notion to fit within the token limit
            tokenized_notion = tokenized_notion[
                : self.max_tokens - (self.total_tokens - len(tokenized_notion))
            ]
            trimmed_content = self.tokenizer.decode(tokenized_notion)
            trimmed_notion = Notion(
                content=trimmed_content,
                role=self.notions[single_index].role,
                persistent=self.notions[single_index].persistent,
            )
            self.replace(single_index, trimmed_notion)
            return

        # Attempt to remove the first non-persistent notion
        for i in non_persistent_indices:
            self.pop(i)
            break
        else:
            # If all notions are persistent and
            # the max token length is still exceeded
            raise ValueError(
                "Persistent notions exceed max_tokens."
                + " Reduce the content or increase max_tokens."
            )

Agent

Agent(model: Model, idearium: Optional[Idearium] = None, tools: Optional[List[Tool]] = None, auto_append_response: bool = True)

Bases: BaseModel

A wrapper around a [Model][silverlingua.core.templates.model.Model] that utilizes an [Idearium][silverlingua.core.organisms.idearium.Idearium] and a set of [Tool][silverlingua.core.atoms.tool.tool.Tool]s.

This is a base class not meant to be used directly. It is meant to be subclassed by specific model implementations.

However, there is limited boilerplate. The only thing that needs to be redefined in subclasses is the _bind_tools method.

Additionally, the _use_tools method is a common method to redefine.

Initializes the agent.

Parameters:

Name Type Description Default
model Model

The model to use.

required
idearium Idearium

The idearium to use. If None, a new one will be created.

None
tools List[Tool]

The tools to use.

None
Source code in src/SilverLingua/core/templates/agent.py
def __init__(
    self,
    model: Model,
    idearium: Optional[Idearium] = None,
    tools: Optional[List[Tool]] = None,
    auto_append_response: bool = True,
):
    """
    Initializes the agent.

    Args:
        model (Model): The model to use.
        idearium (Idearium, optional): The idearium to use.
            If None, a new one will be created.
        tools (List[Tool], optional): The tools to use.
    """
    super().__init__(
        model=model,
        idearium=idearium
        or Idearium(tokenizer=model.tokenizer, max_tokens=model.max_tokens),
        tools=tools or [],
        auto_append_response=auto_append_response,
    )

model_config class-attribute instance-attribute

model_config = ConfigDict(frozen=True)

model property

model: Model

The model used by the agent.

idearium instance-attribute

idearium: Idearium

The Idearium used by the agent.

tools instance-attribute

tools: List[Tool]

The tools used by the agent.

Warning

Do not modify this list directly. Use add_tool, add_tools, and remove_tool instead.

auto_append_response class-attribute instance-attribute

auto_append_response: bool = True

Whether to automatically append the response to the idearium after generating a response.

role property

role: ChatRole

The ChatRole object for the model.

model_post_init

model_post_init(__content)
Source code in src/SilverLingua/core/templates/agent.py
def model_post_init(self, __content):
    self._bind_tools()

_find_tool

_find_tool(name: str) -> Tool | None

Finds a tool by name.

Source code in src/SilverLingua/core/templates/agent.py
def _find_tool(self, name: str) -> Tool | None:
    """
    Finds a tool by name.
    """
    for t in self.tools:
        if t.name == name:
            return t
    return None

_use_tools

_use_tools(tool_calls: ToolCalls) -> List[Notion]

Uses Tools based on the given ToolCalls, returning Notions containing ToolCallResponses.

Parameters:

Name Type Description Default
tool_calls ToolCalls

The ToolCalls to use.

required

Returns:

Type Description
List[Notion]

List[Notion]: The Notions containing ToolCallResponses. Each Notion will have a role of ChatRole.TOOL_RESPONSE.

Source code in src/SilverLingua/core/templates/agent.py
def _use_tools(self, tool_calls: ToolCalls) -> List[Notion]:
    """
    Uses Tools based on the given ToolCalls, returning Notions
    containing ToolCallResponses.

    Args:
        tool_calls (ToolCalls): The ToolCalls to use.

    Returns:
        List[Notion]: The Notions containing ToolCallResponses.
            Each Notion will have a role of ChatRole.TOOL_RESPONSE.
    """
    responses: List[Notion] = []
    for tool_call in tool_calls.list:
        tool = self._find_tool(tool_call.function.name)
        if tool is not None:
            tc_function_response = {}
            with contextlib.suppress(json.JSONDecodeError):
                tc_function_response = json.loads(tool_call.function.arguments)

            tc_response = ToolCallResponse.from_tool_call(
                tool_call=tool_call, response=tool(**tc_function_response)
            )
            responses.append(
                Notion(
                    content=tc_response.model_dump_json(exclude_none=True),
                    role=str(self.role.TOOL_RESPONSE.value),
                )
            )
        else:
            responses.append(
                Notion(
                    content=json.dumps(
                        {
                            "tool_call_id": tool_call.id,
                            "content": "Tool not found",
                            "name": "error",
                        }
                    ),
                    role=str(self.role.TOOL_RESPONSE.value),
                )
            )
    return responses

_bind_tools

_bind_tools() -> None

Called at the end of init to bind the tools to the model.

This MUST be redefined in subclasses to dictate how the tools are bound to the model.

Example:

# From OpenAIChatAgent
def _bind_tools(self) -> None:
    m_tools: List[ChatCompletionToolParam] = [
        {"type": "function", "function": tool.description}
        for tool in self.tools
    ]

    if len(m_tools) > 0:
        self.model.tools = m_tools

Source code in src/SilverLingua/core/templates/agent.py
def _bind_tools(self) -> None:
    """
    Called at the end of __init__ to bind the tools to the model.

    This MUST be redefined in subclasses to dictate how
    the tools are bound to the model.

    Example:
    ```python
    # From OpenAIChatAgent
    def _bind_tools(self) -> None:
        m_tools: List[ChatCompletionToolParam] = [
            {"type": "function", "function": tool.description}
            for tool in self.tools
        ]

        if len(m_tools) > 0:
            self.model.tools = m_tools
    ```
    """
    pass

add_tool

add_tool(tool: Tool) -> None

Adds a tool to the agent.

Source code in src/SilverLingua/core/templates/agent.py
def add_tool(self, tool: Tool) -> None:
    """
    Adds a tool to the agent.
    """
    self.tools.append(tool)
    self._bind_tools()

add_tools

add_tools(tools: List[Tool]) -> None

Adds a list of tools to the agent.

Source code in src/SilverLingua/core/templates/agent.py
def add_tools(self, tools: List[Tool]) -> None:
    """
    Adds a list of tools to the agent.
    """
    self.tools.extend(tools)
    self._bind_tools()

remove_tool

remove_tool(name: str) -> None

Removes a tool from the agent.

Source code in src/SilverLingua/core/templates/agent.py
def remove_tool(self, name: str) -> None:
    """
    Removes a tool from the agent.
    """
    for i, tool in enumerate(self.tools):
        if tool.name == name:
            self.tools.pop(i)
            break
    self._bind_tools()

_process_messages

_process_messages(messages: Messages) -> List[Notion]

Convert various message types into a list of Notions.

Source code in src/SilverLingua/core/templates/agent.py
def _process_messages(self, messages: Messages) -> List[Notion]:
    """Convert various message types into a list of Notions."""
    if isinstance(messages, str):
        return [Notion(content=messages, role=str(self.role.HUMAN.value))]
    elif isinstance(messages, Notion):
        return [messages]
    elif isinstance(messages, Idearium):
        return messages.notions
    elif isinstance(messages, list):
        return [
            (
                Notion(content=msg, role=str(self.role.HUMAN.value))
                if isinstance(msg, str)
                else msg
            )
            for msg in messages
        ]
    raise ValueError(f"Unsupported message type: {type(messages)}")

_process_generation

_process_generation(responses: List[Notion], is_async=False) -> List[Notion]

Wrapper around shared logic between generate and agenerate.

Source code in src/SilverLingua/core/templates/agent.py
def _process_generation(
    self, responses: List[Notion], is_async=False
) -> List[Notion]:
    """Wrapper around shared logic between generate and agenerate."""
    response = responses[0]
    # logger.debug(f"Response: {response}")
    if response.chat_role == ChatRole.TOOL_CALL:
        # logger.debug("Tool call detected")
        # Add the tool call to the idearium
        self.idearium.append(response)
        # Call generate again with the tool response
        tool_calls = ToolCalls.model_validate_json(
            '{"list": ' + response.content + "}"
        )
        tool_response = self._use_tools(tool_calls)
        # logger.debug(f"Tool response: {tool_response}")
        if is_async:
            return self.agenerate(tool_response)
        else:
            return self.generate(tool_response)
    else:
        return responses

generate

generate(messages: Messages, **kwargs) -> List[Notion]

Generates a response to the given messages by calling the underlying model's generate method and checking/actualizing tool usage.

Parameters:

Name Type Description Default
messages Union[str, Notion, Idearium, List[Union[str, Notion]]]
required

Returns:

Type Description
List[Notion]

List[Notion]: A list of responses to the given messages. (Many times there will only be one response.)

Source code in src/SilverLingua/core/templates/agent.py
def generate(self, messages: Messages, **kwargs) -> List[Notion]:
    """
    Generates a response to the given messages by calling the
    underlying model's generate method and checking/actualizing tool usage.

    Args:
        messages (Union[str, Notion, Idearium, List[Union[str, Notion]]]):
        The messages to respond to.

    Returns:
        List[Notion]: A list of responses to the given messages.
            (Many times there will only be one response.)
    """
    self.idearium.extend(self._process_messages(messages))
    responses = self.model.generate(self.idearium, **kwargs)
    result = self._process_generation(responses)

    if self.auto_append_response:
        self.idearium.extend(result)

    return result

agenerate async

agenerate(messages: Messages, **kwargs) -> List[Notion]

Asynchronously generates a response to the given messages by calling the underlying model's agenerate method and checking/actualizing tool usage.

Parameters:

Name Type Description Default
messages Union[str, Notion, Idearium, List[Union[str, Notion]]]
required

Returns:

Type Description
List[Notion]

List[Notion]: A list of responses to the given messages. (Many times there will only be one response.)

Source code in src/SilverLingua/core/templates/agent.py
async def agenerate(self, messages: Messages, **kwargs) -> List[Notion]:
    """
    Asynchronously generates a response to the given messages by calling the
    underlying model's agenerate method and checking/actualizing tool usage.

    Args:
        messages (Union[str, Notion, Idearium, List[Union[str, Notion]]]):
        The messages to respond to.

    Returns:
        List[Notion]: A list of responses to the given messages.
            (Many times there will only be one response.)
    """
    self.idearium.extend(self._process_messages(messages))
    responses = await self.model.agenerate(self.idearium, **kwargs)
    result = self._process_generation(responses, True)
    r = await result if asyncio.iscoroutine(result) else result

    if self.auto_append_response:
        self.idearium.extend(r)

    return r

_process_tool_calls

_process_tool_calls(tool_calls: ToolCalls)

Processes tool calls and returns the tool response.

Parameters:

Name Type Description Default
tool_calls ToolCalls

The tool calls to process.

required

Returns:

Type Description

Optional[ToolCalls]: The tool response. If None, no tool calls were found.

Source code in src/SilverLingua/core/templates/agent.py
def _process_tool_calls(self, tool_calls: ToolCalls):
    """
    Processes tool calls and returns the tool response.

    Args:
        tool_calls (ToolCalls): The tool calls to process.

    Returns:
        Optional[ToolCalls]: The tool response. If None, no tool calls were found.
    """
    for i, tool_call in enumerate(tool_calls.list):
        if not tool_call.id.startswith("call_"):
            # Something went wrong and this tool call is not valid
            tool_calls.list.pop(i)
            logger.error(
                "Invalid tool call: "
                + f"{tool_call.model_dump_json(exclude_none=True)}"
            )

    tc_dump = tool_calls.model_dump(exclude_none=True)
    if tc_dump.get("list"):
        logger.debug(f"Tool calls: {tc_dump}")

        # Create a new notion from the tool calls
        tc_notion = Notion(
            content=json.dumps(tc_dump.get("list")),
            role=str(ChatRole.TOOL_CALL.value),
        )

        # Add the tool call to the idearium
        self.idearium.append(tc_notion)
        # Call stream again with the tool response
        tool_response = self._use_tools(tool_calls)
        return tool_response
    else:
        logger.error("No tool calls found")
        return None

stream

stream(messages: Messages, **kwargs)

Streams a response to the given prompt by calling the underlying model's stream method and checking/actualizing tool usage.

NOTE: Will raise an exception if the underlying model does not support streaming.

Parameters:

Name Type Description Default
messages Union[str, Notion, Idearium, List[Union[str, Notion]]]
required

Returns:

Type Description

Generator[Notion, Any, None]: A generator of responses to the given messages.

Source code in src/SilverLingua/core/templates/agent.py
def stream(self, messages: Messages, **kwargs):
    """
    Streams a response to the given prompt by calling the
    underlying model's stream method and checking/actualizing tool usage.

    NOTE: Will raise an exception if the underlying model does not support
    streaming.

    Args:
        messages (Union[str, Notion, Idearium, List[Union[str, Notion]]]):
        The messages to respond to.

    Returns:
        Generator[Notion, Any, None]: A generator of responses to the given
            messages.
    """
    self.idearium.extend(self._process_messages(messages))
    response_stream = self.model.stream(self.idearium, **kwargs)

    # Process stream directly
    tool_calls: Optional[ToolCalls] = None

    for r in response_stream:
        if r.chat_role == ChatRole.TOOL_CALL:
            logger.debug(f"Tool call detected: {r.content}")
            tc_chunks = ToolCalls.model_validate_json('{"list": ' + r.content + "}")
            tool_calls = tool_calls and tool_calls.concat(tc_chunks) or tc_chunks
            continue
        elif r.content is not None:
            logger.debug(f"Got chunk in stream: {r.content!r}")
            if self.auto_append_response:
                self.idearium.append(r)
            yield r

    # Handle tool calls if any
    if tool_calls is not None:
        logger.debug("Moving to tool response stream")
        tool_response = self._process_tool_calls(tool_calls)
        if tool_response is not None:
            for r in self.stream(tool_response):
                yield r

astream async

astream(messages: Messages, **kwargs)

Asynchronously streams a response to the given prompt by calling the underlying model's astream method and checking/actualizing tool usage.

NOTE: Will raise an exception if the underlying model does not support streaming.

Parameters:

Name Type Description Default
messages Union[str, Notion, Idearium, List[Union[str, Notion]]]
required

Returns:

Type Description

Generator[Notion, Any, None]: A generator of responses to the given messages.

Source code in src/SilverLingua/core/templates/agent.py
async def astream(self, messages: Messages, **kwargs):
    """
    Asynchronously streams a response to the given prompt by calling the
    underlying model's astream method and checking/actualizing tool usage.

    NOTE: Will raise an exception if the underlying model does not support
    streaming.

    Args:
        messages (Union[str, Notion, Idearium, List[Union[str, Notion]]]):
        The messages to respond to.

    Returns:
        Generator[Notion, Any, None]: A generator of responses to the given
            messages.
    """
    self.idearium.extend(self._process_messages(messages))
    response_stream = self.model.astream(self.idearium, **kwargs)

    # Process stream directly
    tool_calls: Optional[ToolCalls] = None

    async for r in response_stream:
        if r.chat_role == ChatRole.TOOL_CALL:
            logger.debug(f"Tool call detected: {r.content}")
            tc_chunks = ToolCalls.model_validate_json('{"list": ' + r.content + "}")
            tool_calls = tool_calls and tool_calls.concat(tc_chunks) or tc_chunks
            continue
        elif r.content is not None:
            logger.debug(f"Got chunk in astream: {r.content!r}")
            if self.auto_append_response:
                self.idearium.append(r)
            yield r

    # Handle tool calls if any
    if tool_calls is not None:
        logger.debug("Moving to tool response stream")
        tool_response = self._process_tool_calls(tool_calls)
        if tool_response is not None:
            async for r in self.astream(tool_response):
                yield r

Model

Bases: BaseModel, ABC

Abstract class for all Large Language Models.

This class outlines a standardized lifecycle for interacting with LLMs, aimed at ensuring a consistent process for message trimming, pre-processing, preparing requests for the model, invoking the model, standardizing the response, and post-processing. The lifecycle is as follows:

Lifecycle
  1. Pre-processing ([_preprocess][silverlingua.core.templates.model.Model._preprocess]): Performs any necessary transformations or adjustments to the messages prior to trimming or preparing them for model input. (Optional)

  2. Preparing Request ([_format_request][silverlingua.core.templates.model.Model._format_request]): Converts the pre-processed messages into a format suitable for model input.

  3. Model Invocation ([_call][silverlingua.core.templates.model.Model._call] or [_acall][silverlingua.core.templates.model.Model._acall]): Feeds the prepared input to the LLM and retrieves the raw model output. There should be both synchronous and asynchronous versions available.

  4. Standardizing Response ([_standardize_response][silverlingua.core.templates.model.Model._standardize_response]): Transforms the raw model output into a consistent response format suitable for further processing or delivery.

  5. Post-processing ([_postprocess][silverlingua.core.templates.model.Model._postprocess]): Performs any final transformations or adjustments to the standardized responses, making them ready for delivery. (Optional)

Subclasses should implement each of the non-optional lifecycle steps in accordance with the specific requirements and behaviors of the target LLM.

See also
  • [Agent][silverlingua.core.templates.agent.Agent]
  • [Idearium][silverlingua.core.organisms.idearium.Idearium]
  • [Notion][silverlingua.core.molecules.notion.Notion]

model_config class-attribute instance-attribute

model_config = ConfigDict(frozen=True)

max_response class-attribute instance-attribute

max_response: int = Field(default=0)

api_key instance-attribute

api_key: str

name instance-attribute

name: str

role instance-attribute

role: Type[ChatRole]

type instance-attribute

type: ModelType

llm instance-attribute

llm: Callable

llm_async instance-attribute

llm_async: Callable

can_stream instance-attribute

can_stream: bool

tokenizer instance-attribute

tokenizer: Tokenizer

max_tokens abstractmethod property

max_tokens: int

The maximum number of tokens that can be fed to the model at once.

_process_input

_process_input(messages: Messages) -> Idearium
Source code in src/SilverLingua/core/templates/model.py
def _process_input(self, messages: Messages) -> Idearium:
    if isinstance(messages, str):
        notions = [Notion(content=messages, role=self.role.HUMAN)]
    elif isinstance(messages, Notion):
        notions = [messages]
    elif isinstance(messages, Idearium):
        return messages  # Already an Idearium, no need to convert
    elif isinstance(messages, list):
        notions = [
            (
                Notion(content=msg, role=self.role.HUMAN)
                if isinstance(msg, str)
                else msg
            )
            for msg in messages
        ]
    else:
        raise ValueError("Invalid input type for messages")

    return Idearium(self.tokenizer, self.max_tokens, notions)

_convert_role

_convert_role(role: ChatRole) -> str

Converts the standard ChatRole to the model-specific role.

Source code in src/SilverLingua/core/templates/model.py
def _convert_role(self, role: ChatRole) -> str:
    """
    Converts the standard ChatRole to the model-specific role.
    """
    return str(self.role[role.name].value)

_preprocess

_preprocess(messages: List[Notion]) -> List[Notion]

Preprocesses the List of Notions, applying any effects necessary before being prepped for input into an API.

This is a lifecycle method that is called by the generate method.

Source code in src/SilverLingua/core/templates/model.py
def _preprocess(self, messages: List[Notion]) -> List[Notion]:
    """
    Preprocesses the List of `Notions`, applying any effects necessary
    before being prepped for input into an API.

    This is a lifecycle method that is called by the `generate` method.
    """
    return [
        Notion(msg.content, self._convert_role(msg.chat_role), msg.persistent)
        for msg in messages
    ]

_format_request abstractmethod

_format_request(messages: List[Notion], *args, **kwargs) -> Union[str, object]

Formats the List of Notions into a format suitable for model input.

This is a lifecycle method that is called by the generate method.

Source code in src/SilverLingua/core/templates/model.py
@abstractmethod
def _format_request(
    self, messages: List[Notion], *args, **kwargs
) -> Union[str, object]:
    """
    Formats the List of `Notions` into a format suitable for model input.

    This is a lifecycle method that is called by the `generate` method.
    """
    pass

_standardize_response abstractmethod

_standardize_response(response: Union[object, str, List[any]], *args, **kwargs) -> List[Notion]

Standardizes the raw response from the model into a List of Notions.

This is a lifecycle method that is called by the generate method.

Source code in src/SilverLingua/core/templates/model.py
@abstractmethod
def _standardize_response(
    self, response: Union[object, str, List[any]], *args, **kwargs
) -> List[Notion]:
    """
    Standardizes the raw response from the model into a List of Notions.

    This is a lifecycle method that is called by the `generate` method.
    """
    pass

_postprocess abstractmethod

_postprocess(response: List[Notion], *args, **kwargs) -> List[Notion]

Postprocesses the response from the model, applying any final effects before being returned.

This is a lifecycle method that is called by the generate method.

Source code in src/SilverLingua/core/templates/model.py
@abstractmethod
def _postprocess(self, response: List[Notion], *args, **kwargs) -> List[Notion]:
    """
    Postprocesses the response from the model, applying any final effects
    before being returned.

    This is a lifecycle method that is called by the `generate` method.
    """
    pass

_retry_call abstractmethod

_retry_call(input: Union[str, object, List[any]], e: Exception, api_call: Callable, retries: int = 0) -> Union[str, object]

Retry logic for API calls used by _common_call_logic.

Source code in src/SilverLingua/core/templates/model.py
@abstractmethod
def _retry_call(
    self,
    input: Union[str, object, List[any]],
    e: Exception,
    api_call: Callable,
    retries: int = 0,
) -> Union[str, object]:
    """
    Retry logic for API calls used by `_common_call_logic`.
    """
    pass

_common_call_logic

_common_call_logic(input: Union[str, object, List[any]], api_call: Callable, retries: int = 0) -> Union[str, object]
Source code in src/SilverLingua/core/templates/model.py
def _common_call_logic(
    self,
    input: Union[str, object, List[any]],
    api_call: Callable,
    retries: int = 0,
) -> Union[str, object]:
    if input is None:
        raise ValueError("No input provided.")

    try:
        out = api_call(messages=input)
        return out
    except Exception as e:
        logger.error(f"Error calling LLM API: {e}")
        if retries >= 3:
            raise e

        return self._retry_call(input, e, api_call, retries=retries)

_call

_call(input: Union[str, object, List[any]], retries: int = 0, **kwargs) -> object

Calls the model with the given input and returns the raw response.

Should behave exactly as _acall does, but synchronously.

This is a lifecycle method that is called by the generate method.

Source code in src/SilverLingua/core/templates/model.py
def _call(
    self, input: Union[str, object, List[any]], retries: int = 0, **kwargs
) -> object:
    """
    Calls the model with the given input and returns the raw response.

    Should behave exactly as `_acall` does, but synchronously.

    This is a lifecycle method that is called by the `generate` method.
    """

    def api_call(**kwargs_):
        return self.llm(**kwargs_, **kwargs)

    return self._common_call_logic(input, api_call, retries)

_acall async

_acall(input: Union[str, object, List[any]], retries: int = 0, **kwargs) -> object

Calls the model with the given input and returns the raw response asynchronously.

Should behave exactly as _call does, but asynchronously.

This is a lifecycle method that is called by the agenerate method.

Source code in src/SilverLingua/core/templates/model.py
async def _acall(
    self, input: Union[str, object, List[any]], retries: int = 0, **kwargs
) -> object:
    """
    Calls the model with the given input and returns the
    raw response asynchronously.

    Should behave exactly as `_call` does, but asynchronously.

    This is a lifecycle method that is called by the `agenerate` method.
    """

    async def api_call(**kwargs_):
        return await self.llm_async(**kwargs_, **kwargs)

    result = self._common_call_logic(input, api_call, retries)
    if asyncio.iscoroutine(result):
        return await result
    return result

_common_generate_logic

_common_generate_logic(messages: Messages, is_async=False, **kwargs)
Source code in src/SilverLingua/core/templates/model.py
def _common_generate_logic(
    self,
    messages: Messages,
    is_async=False,
    **kwargs,
):
    if messages is None:
        raise ValueError("No messages provided.")

    call_method = self._acall if is_async else self._call

    idearium = self._process_input(messages)
    input = self._format_request(self._preprocess(idearium))

    if is_async:

        async def call():
            response = await call_method(input, **kwargs)
            output = self._standardize_response(response)
            return self._postprocess(output)

        return call()
    else:
        response = call_method(input, **kwargs)
        output = self._standardize_response(response)
        return self._postprocess(output)

generate abstractmethod

generate(messages: Messages, *args, **kwargs) -> List[Notion]

Calls the model with the given messages and returns the response.

Messages can be any of: string, list of strings, Notion, list of Notions, or Idearium.

This is the primary method for generating responses from the model, and is responsible for calling all of the lifecycle methods.

Source code in src/SilverLingua/core/templates/model.py
@abstractmethod
def generate(
    self,
    messages: Messages,
    *args,
    **kwargs,
) -> List[Notion]:
    """
    Calls the model with the given messages and returns the response.

    Messages can be any of:
    string, list of strings, Notion, list of Notions, or Idearium.

    This is the primary method for generating responses from the model,
    and is responsible for calling all of the lifecycle methods.
    """
    pass

agenerate abstractmethod async

agenerate(messages: Messages, *args, **kwargs) -> List[Notion]

Calls the model with the given messages and returns the response asynchronously.

Messages can be any of: string, list of strings, Notion, list of Notions, or Idearium.

This is the primary method for generating async responses from the model, and is responsible for calling all of the lifecycle methods.

Source code in src/SilverLingua/core/templates/model.py
@abstractmethod
async def agenerate(
    self,
    messages: Messages,
    *args,
    **kwargs,
) -> List[Notion]:
    """
    Calls the model with the given messages and returns the response
    asynchronously.

    Messages can be any of:
    string, list of strings, Notion, list of Notions, or Idearium.

    This is the primary method for generating async responses from the model,
    and is responsible for calling all of the lifecycle methods.
    """
    pass

_common_stream_logic

_common_stream_logic(messages: Messages)
Source code in src/SilverLingua/core/templates/model.py
def _common_stream_logic(self, messages: Messages):
    if messages is None:
        raise ValueError("No messages provided.")

    if not self.can_stream:
        raise ValueError(
            "This model does not support streaming. "
            + "Please use the `generate` method instead."
        )

    idearium = self._process_input(messages)
    input = self._format_request(self._preprocess(idearium))
    return input

stream abstractmethod

stream(messages: Messages, *args, **kwargs) -> Generator[Notion, Any, None]

Streams the model with the given messages and returns the response, one token at a time.

Messages can be any of: string, list of strings, Notion, list of Notions, or Idearium.

If the model cannot be streamed, this will raise an exception.

Source code in src/SilverLingua/core/templates/model.py
@abstractmethod
def stream(
    self, messages: Messages, *args, **kwargs
) -> Generator[Notion, Any, None]:
    """
    Streams the model with the given messages and returns the response,
    one token at a time.

    Messages can be any of:
    string, list of strings, Notion, list of Notions, or Idearium.

    If the model cannot be streamed, this will raise an exception.
    """
    pass

astream abstractmethod async

astream(messages: Messages, *args, **kwargs) -> Generator[Notion, Any, None]

Streams the model with the given messages and returns the response, one token at a time, asynchronously.

Messages can be any of: string, list of strings, Notion, list of Notions, or Idearium.

If the model cannot be streamed, this will raise an exception.

Source code in src/SilverLingua/core/templates/model.py
@abstractmethod
async def astream(
    self, messages: Messages, *args, **kwargs
) -> Generator[Notion, Any, None]:
    """
    Streams the model with the given messages and returns the response,
    one token at a time, asynchronously.

    Messages can be any of:
    string, list of strings, Notion, list of Notions, or Idearium.

    If the model cannot be streamed, this will raise an exception.
    """
    pass

options: show_root_heading: true show_source: true