Skip to content

templates

Templates define core interfaces and abstract base classes that ensure consistency across the system. They establish patterns that other components must follow while keeping implementation details flexible.

See Design Principles - Templates for more details.

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