API Reference¶
SilverLingua
¶
SilverLingua - An AI agent framework
Config
¶
get_chat_role
classmethod
¶
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
get_react_role
classmethod
¶
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
get_tool
classmethod
¶
Attempts to get the tool with the given name. If not, returns None.
add_chat_role
classmethod
¶
Adds a chat role to the config.
add_react_role
classmethod
¶
Adds a react role to the config.
register_module
classmethod
¶
register_module(module: Module) -> None
Registers a module.
Source code in src/SilverLingua/config.py
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
check_chat_roles
¶
Source code in src/SilverLingua/config.py
check_react_roles
¶
Source code in src/SilverLingua/config.py
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.
TOOL_RESPONSE
class-attribute
instance-attribute
¶
TOOL_RESPONSE = RoleMember('TOOL_RESPONSE', 'TOOL_RESPONSE')
Memory
¶
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.
OBSERVATION
class-attribute
instance-attribute
¶
OBSERVATION = RoleMember('OBSERVATION', 'OBSERVATION')
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
description
class-attribute
instance-attribute
¶
description: FunctionJSONSchema = 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
ToolCall
¶
Bases: BaseModel
model_config
class-attribute
instance-attribute
¶
model_config = ConfigDict(extra='allow', ignored_types=(type(None)))
string_if_none
¶
concat
¶
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
ToolCallFunction
¶
Bases: BaseModel
ToolCallResponse
¶
Bases: BaseModel
The response property of a tool call.
from_tool_call
classmethod
¶
from_tool_call(tool_call: ToolCall, response: str) -> ToolCallResponse
ToolCalls
¶
Bases: BaseModel
A list of tool calls.
list
class-attribute
instance-attribute
¶
concat
¶
Concatenates two tool calls lists and returns the result.
Source code in src/SilverLingua/core/atoms/tool/util.py
Link
¶
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).)
Notion
¶
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
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
¶
Source code in src/SilverLingua/core/molecules/notion.py
Idearium
¶
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
tokenized_notions
class-attribute
instance-attribute
¶
persistent_indices
class-attribute
instance-attribute
¶
_non_persistent_indices
property
¶
_non_persistent_indices: set
The indices of non-persistent notions.
validate_notions
¶
validate_notion
classmethod
¶
Source code in src/SilverLingua/core/organisms/idearium.py
index
¶
append
¶
append(notion: Notion)
Appends the given notion to the end of the Idearium.
Source code in src/SilverLingua/core/organisms/idearium.py
extend
¶
Extends the Idearium with the given list of notions.
Source code in src/SilverLingua/core/organisms/idearium.py
insert
¶
Inserts the given notion at the given index.
Source code in src/SilverLingua/core/organisms/idearium.py
pop
¶
Removes and returns the notion at the given index.
Source code in src/SilverLingua/core/organisms/idearium.py
replace
¶
Replaces the notion at the given index with the given notion.
Source code in src/SilverLingua/core/organisms/idearium.py
copy
¶
copy() -> Idearium
Returns a copy of the Idearium.
Source code in src/SilverLingua/core/organisms/idearium.py
_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
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
tools
instance-attribute
¶
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.
model_post_init
¶
_find_tool
¶
_use_tools
¶
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
_bind_tools
¶
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
add_tools
¶
_process_messages
¶
Convert various message types into a list of Notions.
Source code in src/SilverLingua/core/templates/agent.py
_process_generation
¶
Wrapper around shared logic between generate and agenerate.
Source code in src/SilverLingua/core/templates/agent.py
generate
¶
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
agenerate
async
¶
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
_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
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
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
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
-
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) -
Preparing Request ([
_format_request][silverlingua.core.templates.model.Model._format_request]): Converts the pre-processed messages into a format suitable for model input. -
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. -
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. -
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]
max_tokens
abstractmethod
property
¶
max_tokens: int
The maximum number of tokens that can be fed to the model at once.
_process_input
¶
Source code in src/SilverLingua/core/templates/model.py
_convert_role
¶
_preprocess
¶
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
_format_request
abstractmethod
¶
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
_standardize_response
abstractmethod
¶
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
_postprocess
abstractmethod
¶
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
_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
_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
_call
¶
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
_acall
async
¶
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
_common_generate_logic
¶
_common_generate_logic(messages: Messages, is_async=False, **kwargs)
Source code in src/SilverLingua/core/templates/model.py
generate
abstractmethod
¶
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
agenerate
abstractmethod
async
¶
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
_common_stream_logic
¶
_common_stream_logic(messages: Messages)
Source code in src/SilverLingua/core/templates/model.py
stream
abstractmethod
¶
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
astream
abstractmethod
async
¶
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
options: show_root_heading: true show_source: true