agentscope.memory

The memory module.

class MemoryBase[源代码]

基类:StateModule

The base class for memory in agentscope.

__init__()[源代码]

Initialize the memory base.

返回类型:

None

async update_compressed_summary(summary)[源代码]

Update the compressed summary of the memory.

参数:

summary (str) -- The new compressed summary.

返回类型:

None

abstract async add(memories, marks=None, **kwargs)[源代码]

Add message(s) into the memory storage with the given mark (if provided).

参数:
  • memories (Msg | list[Msg] | None) -- The message(s) to be added.

  • marks (str | list[str] | None, optional) -- The mark(s) to associate with the message(s). If None, no mark is associated.

  • kwargs (Any)

返回类型:

None

abstract async delete(msg_ids, **kwargs)[源代码]

Remove message(s) from the storage by their IDs.

参数:
  • msg_ids (list[str]) -- The list of message IDs to be removed.

  • kwargs (Any)

返回:

The number of messages removed.

返回类型:

int

async delete_by_mark(mark, *args, **kwargs)[源代码]

Remove messages from the memory by their marks.

参数:
  • mark (str | list[str]) -- The mark(s) of the messages to be removed.

  • args (Any)

  • kwargs (Any)

抛出:

TypeError -- If the provided mark is not a string or a list of strings.

返回:

The number of messages removed.

返回类型:

int

abstract async size()[源代码]

Get the number of messages in the storage.

返回:

The number of messages in the storage.

返回类型:

int

abstract async clear()[源代码]

Clear the memory content.

返回类型:

None

abstract async get_memory(mark=None, exclude_mark=None, prepend_summary=True, **kwargs)[源代码]

Get the messages from the memory by mark (if provided). Otherwise, get all messages.

备注

If mark and exclude_mark are both provided, the messages will be filtered by both arguments.

备注

mark and exclude_mark should not overlap.

参数:
  • mark (str | None, optional) -- The mark to filter messages. If None, return all messages.

  • exclude_mark (str | None, optional) -- The mark to exclude messages. If provided, messages with this mark will be excluded from the results.

  • prepend_summary (bool, defaults to True) -- Whether to prepend the compressed summary as a message

  • kwargs (Any)

返回:

The list of messages retrieved from the storage.

返回类型:

list[Msg]

async update_messages_mark(new_mark, old_mark=None, msg_ids=None)[源代码]

A unified method to update marks of messages in the storage (add, remove, or change marks).

  • If msg_ids is provided, the update will be applied to the messages

with the specified IDs.

  • If old_mark is provided, the update will be applied to the

messages with the specified old mark. Otherwise, the new_mark will be added to all messages (or those filtered by msg_ids).

  • If new_mark is None, the mark will be removed from the messages.

参数:
  • new_mark (str | None, optional) -- The new mark to set for the messages. If None, the mark will be removed.

  • old_mark (str | None, optional) -- The old mark to filter messages. If None, this constraint is ignored.

  • msg_ids (list[str] | None, optional) -- The list of message IDs to be updated. If None, this constraint is ignored.

返回:

The number of messages updated.

返回类型:

int

class InMemoryMemory[源代码]

基类:MemoryBase

The in-memory implementation of memory storage.

__init__()[源代码]

Initialize the in-memory storage.

返回类型:

None

async get_memory(mark=None, exclude_mark=None, prepend_summary=True, **kwargs)[源代码]

Get the messages from the memory by mark (if provided). Otherwise, get all messages.

备注

If mark and exclude_mark are both provided, the messages will be filtered by both arguments.

备注

mark and exclude_mark should not overlap.

参数:
  • mark (str | None, optional) -- The mark to filter messages. If None, return all messages.

  • exclude_mark (str | None, optional) -- The mark to exclude messages. If provided, messages with this mark will be excluded from the results.

  • prepend_summary (bool, defaults to True) -- Whether to prepend the compressed summary as a message

  • kwargs (Any)

抛出:

TypeError -- If the provided mark is not a string or None.

返回:

The list of messages retrieved from the storage.

返回类型:

list[Msg]

async add(memories, marks=None, allow_duplicates=False, **kwargs)[源代码]

Add message(s) into the memory storage with the given mark (if provided).

参数:
  • memories (Msg | list[Msg] | None) -- The message(s) to be added.

  • marks (str | list[str] | None, optional) -- The mark(s) to associate with the message(s). If None, no mark is associated.

  • allow_duplicates (bool, defaults to False) -- Whether to allow duplicate messages in the storage.

  • kwargs (Any)

返回类型:

None

async delete(msg_ids, **kwargs)[源代码]

Remove message(s) from the storage by their IDs.

参数:
  • msg_ids (list[str]) -- The list of message IDs to be removed.

  • kwargs (Any)

返回:

The number of messages removed.

返回类型:

int

async delete_by_mark(mark, **kwargs)[源代码]

Remove messages from the memory by their marks.

参数:
  • mark (str | list[str]) -- The mark(s) of the messages to be removed.

  • kwargs (Any)

抛出:

TypeError -- If the provided mark is not a string or a list of strings.

返回:

The number of messages removed.

返回类型:

int

async clear()[源代码]

Clear all messages from the storage.

返回类型:

None

async size()[源代码]

Get the number of messages in the storage.

返回:

The number of messages in the storage.

返回类型:

int

async update_messages_mark(new_mark, old_mark=None, msg_ids=None)[源代码]

A unified method to update marks of messages in the storage (add, remove, or change marks).

  • If msg_ids is provided, the update will be applied to the messages

with the specified IDs.

  • If old_mark is provided, the update will be applied to the

messages with the specified old mark. Otherwise, the new_mark will be added to all messages (or those filtered by msg_ids).

  • If new_mark is None, the mark will be removed from the messages.

参数:
  • new_mark (str | None, optional) -- The new mark to set for the messages. If None, the mark will be removed.

  • old_mark (str | None, optional) -- The old mark to filter messages. If None, this constraint is ignored.

  • msg_ids (list[str] | None, optional) -- The list of message IDs to be updated. If None, this constraint is ignored.

返回:

The number of messages updated.

返回类型:

int

state_dict()[源代码]

Get the state dictionary for serialization.

返回类型:

dict

load_state_dict(state_dict, strict=True)[源代码]

Load the state dictionary for deserialization.

参数:
  • state_dict (dict)

  • strict (bool)

返回类型:

None

class RedisMemory[源代码]

基类:MemoryBase

Redis memory storage implementation, which supports session and user context.

备注

All the operations in this class are within a specific session and user context, identified by session_id and user_id. Cross-session or cross-user operations are not supported. For example, the remove_messages method will only remove messages that belong to the specified session_id and user_id.

备注

All Redis keys used by this class will be prefixed by prefix

(if provided) to support multi-tenant / multi-app isolation.

SESSION_KEY = 'user_id:{user_id}:session:{session_id}:messages'

Redis key pattern (without prefix) for storing message IDs (ordered) for a specific session.

SESSION_PATTERN = 'user_id:{user_id}:session:{session_id}:*'

Redis key pattern (without prefix) for scanning all keys belong to a specific user and session.

MARK_KEY = 'user_id:{user_id}:session:{session_id}:mark:{mark}'

Redis key pattern (without prefix) for storing message IDs that belong to a specific mark.

MESSAGE_KEY = 'user_id:{user_id}:session:{session_id}:msg:{msg_id}'

Redis key pattern (without prefix) for storing message payload data.

__init__(session_id='default_session', user_id='default_user', host='localhost', port=6379, db=0, password=None, connection_pool=None, key_prefix='', key_ttl=None, **kwargs)[源代码]

Initialize the Redis based storage by connecting to the Redis server. You can provide either the connection parameters or an existing connection pool.

参数:
  • session_id (str, default to "default_session") -- The session ID for the storage.

  • user_id (str, default to "default_user") -- The user ID for the storage.

  • host (str, default to "localhost") -- The Redis server host.

  • port (int, default to 6379) -- The Redis server port.

  • db (int, default to 0) -- The Redis database index.

  • password (str | None, optional) -- The password for the Redis server, if required.

  • connection_pool (ConnectionPool | None, optional) -- An optional Redis connection pool. If provided, it will be used instead of creating a new connection.

  • key_prefix (str, default to "") -- Optional Redis key prefix prepended to every key generated by this storage. Useful for isolating keys across apps/environments (e.g. "prod", "staging", "myapp").

  • key_ttl (int | None, default to None) -- The expired time in seconds for each key. If provided, the expiration will be refreshed on every access (sliding TTL). If None, the keys will not expire. Note the ttl will update all session related keys, so it's not recommended to set for large sessions.

  • **kwargs (Any) -- Additional keyword arguments to pass to the Redis client.

返回类型:

None

get_client()[源代码]

Get the underlying Redis client.

返回:

The Redis client instance.

返回类型:

Redis

async get_memory(mark=None, exclude_mark=None, prepend_summary=True, **kwargs)[源代码]

Get the messages from the memory by mark (if provided). Otherwise, get all messages.

备注

If mark and exclude_mark are both provided, the messages will be filtered by both arguments.

备注

mark and exclude_mark should not overlap.

参数:
  • mark (str | None, optional) -- The mark to filter messages. If None, return all messages.

  • exclude_mark (str | None, optional) -- The mark to exclude messages. If provided, messages with this mark will be excluded from the results.

  • prepend_summary (bool, defaults to True) -- Whether to prepend the compressed summary as a message

  • kwargs (Any)

返回:

The list of messages retrieved from the storage.

返回类型:

list[Msg]

async add(memories, marks=None, skip_duplicated=True, **kwargs)[源代码]

Add message into the storage with the given mark (if provided).

参数:
  • memories (Msg | list[Msg]) -- The message(s) to be added.

  • marks (str | list[str] | None, optional) -- The mark(s) to associate with the message(s). If None, no mark is associated.

  • skip_duplicated (bool, defaults to True) -- If True, skip messages with duplicate IDs that already exist in the storage. If False, allow duplicate message IDs to be added to the session list (though the message data will be overwritten).

  • kwargs (Any)

返回类型:

None

async delete(msg_ids, **kwargs)[源代码]

Remove message(s) from the storage by their IDs.

参数:
  • msg_ids (list[str]) -- The list of message IDs to be removed.

  • kwargs (Any)

返回:

The number of messages removed.

返回类型:

int

async delete_by_mark(mark, **kwargs)[源代码]

Remove messages from the storage by their marks.

参数:
  • mark (str | list[str]) -- The mark(s) of the messages to be removed.

  • kwargs (Any)

返回:

The number of messages removed.

返回类型:

int

async clear()[源代码]

Clear all messages belong to this session from the storage.

返回类型:

None

async size()[源代码]

Get the number of messages in the storage.

返回:

The number of messages in the storage.

返回类型:

int

async update_messages_mark(new_mark, old_mark=None, msg_ids=None)[源代码]

A unified method to update marks of messages in the storage (add, remove, or change marks).

  • If msg_ids is provided, the update will be applied to the messages

with the specified IDs.

  • If old_mark is provided, the update will be applied to the

messages with the specified old mark. Otherwise, the new_mark will be added to all messages (or those filtered by msg_ids).

  • If new_mark is None, the mark will be removed from the messages.

参数:
  • new_mark (str | None, optional) -- The new mark to set for the messages. If None, the mark will be removed.

  • old_mark (str | None, optional) -- The old mark to filter messages. If None, this constraint is ignored.

  • msg_ids (list[str] | None, optional) -- The list of message IDs to be updated. If None, this constraint is ignored.

返回:

The number of messages updated.

返回类型:

int

async close(close_connection_pool=None)[源代码]

Close the Redis client connection.

参数:

close_connection_pool (bool | None, optional) -- Decides whether to close the connection pool used by this Redis client, overriding Redis.auto_close_connection_pool. By default, let Redis.auto_close_connection_pool decide whether to close the connection pool

返回类型:

None

class AsyncSQLAlchemyMemory[源代码]

基类:MemoryBase

The SQLAlchemy memory storage class for storing messages in a SQL database using SQLAlchemy ORM, such as SQLite, PostgreSQL, MySQL, etc.

备注

All the operations in this class are within a specific session and user context, identified by session_id and user_id. Cross-session or cross-user operations are not supported. For example, the remove_messages method will only remove messages that belong to the specified session_id and user_id.

class MessageTable[源代码]

基类:Base

The default message table definition.

id

The id column, we use the f"{user_id}-{session_id}-{message_id}" as the primary key to ensure uniqueness across users and sessions.

msg

The message JSON content column

session

The foreign key to the session id relationship

session_id

The foreign key to the session id

index

The index column for ordering messages, so that we can retrieve messages in the order they were added.

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance's class are allowed. These could be, for example, any mapped columns or relationships.

class MessageMarkTable[源代码]

基类:Base

The default message mark table definition.

msg_id

The message id column

mark

The mark column

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance's class are allowed. These could be, for example, any mapped columns or relationships.

class SessionTable[源代码]

基类:Base

The default session table definition.

id

The session id column

user

The foreign key to the user id relationship

user_id

The foreign key to the user id

messages

The relationship to messages

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance's class are allowed. These could be, for example, any mapped columns or relationships.

class UserTable[源代码]

基类:Base

The default user table definition.

id

The user id column

sessions

The relationship to sessions

__init__(**kwargs)

A simple constructor that allows initialization from kwargs.

Sets attributes on the constructed instance using the names and values in kwargs.

Only keys that are present as attributes of the instance's class are allowed. These could be, for example, any mapped columns or relationships.

__init__(engine_or_session, session_id=None, user_id=None)[源代码]

Initialize the SqlAlchemyDBStorage with a SQLAlchemy session.

参数:
  • engine_or_session (AsyncEngine | AsyncSession) -- The SQLAlchemy asynchronous engine or session to use for database operations. If you're using a connection pool, maybe you want to pass in an AsyncSession instance.

  • session_id (str | None, optional) -- The session ID for the messages. If None, a default session ID will be used.

  • user_id (str | None, optional) -- The user ID for the messages. If None, a default user ID will be used.

抛出:

ValueError -- If the engine parameter is not an instance of sqlalchemy.ext.asyncio.AsyncEngine or sqlalchemy. ext.asyncio.AsyncSession.

返回类型:

None

property session: AsyncSession

Get the current database session, creating one if it doesn't exist.

返回:

The current database session.

返回类型:

AsyncSession

备注

  • If an external session was provided, it will be returned as-is

  • If using internal session factory, a new session will be created if the current one is None or inactive, and _initialized flag will be reset to ensure proper re-initialization

async get_memory(mark=None, exclude_mark=None, prepend_summary=True, **kwargs)[源代码]

Get the messages from the memory by mark (if provided). Otherwise, get all messages.

备注

If mark and exclude_mark are both provided, the messages will be filtered by both arguments.

备注

mark and exclude_mark should not overlap.

参数:
  • mark (str | None, optional) -- The mark to filter messages. If None, return all messages.

  • exclude_mark (str | None, optional) -- The mark to exclude messages. If provided, messages with this mark will be excluded from the results.

  • prepend_summary (bool, defaults to True) -- Whether to prepend the compressed summary as a message

  • kwargs (Any)

抛出:

TypeError -- If the provided mark is not a string or None.

返回:

The list of messages retrieved from the storage.

返回类型:

list[Msg]

async add(memories, marks=None, skip_duplicated=True, **kwargs)[源代码]

Add message into the storage with the given mark (if provided).

参数:
  • memories (Msg | list[Msg] | None) -- The message(s) to be added.

  • marks (str | list[str] | None, optional) -- The mark(s) to associate with the message(s). If None, no mark is associated.

  • skip_duplicated (bool, defaults to True) -- If True, skip messages with duplicate IDs that already exist in the storage. If False, raise an IntegrityError when attempting to add a message with an existing ID.

  • kwargs (Any)

抛出:

IntegrityError -- If a message with the same ID already exists in the storage and skip_duplicated is set to False.

返回类型:

None

async size()[源代码]

Get the size of the messages in the storage.

返回类型:

int

async clear()[源代码]

Clear all messages from the storage.

返回类型:

None

async delete_by_mark(mark, **kwargs)[源代码]

Remove messages from the storage by their marks.

参数:
  • mark (str | list[str]) -- The mark(s) of the messages to be removed.

  • kwargs (Any)

返回:

The number of messages removed.

返回类型:

int

async delete(msg_ids, **kwargs)[源代码]

Remove message(s) from the storage by their IDs.

备注

Although MessageMarkTable has CASCADE delete on foreign key, we explicitly delete marks first for reliability across all database engines and configurations. SQLAlchemy's bulk delete bypasses ORM-level cascades, and SQLite requires foreign keys to be explicitly enabled.

参数:
  • msg_ids (list[str]) -- The list of message IDs to be removed.

  • kwargs (Any)

返回:

The number of messages removed.

返回类型:

int

async update_messages_mark(new_mark, old_mark=None, msg_ids=None)[源代码]

A unified method to update marks of messages in the storage (add, remove, or change marks).

  • If msg_ids is provided, the update will be applied to the messages

with the specified IDs.

  • If old_mark is provided, the update will be applied to the

messages with the specified old mark. Otherwise, the new_mark will be added to all messages (or those filtered by msg_ids).

  • If new_mark is None, the mark will be removed from the messages.

参数:
  • new_mark (str | None, optional) -- The new mark to set for the messages. If None, the mark will be removed.

  • old_mark (str | None, optional) -- The old mark to filter messages. If None, this constraint is ignored.

  • msg_ids (list[str] | None, optional) -- The list of message IDs to be updated. If None, this constraint is ignored.

返回:

The number of messages updated.

返回类型:

int

async close()[源代码]

Close the database session.

返回类型:

None

class LongTermMemoryBase[源代码]

基类:StateModule

The long-term memory base class, which should be a time-series memory management system.

The record_to_memory and retrieve_from_memory methods are two tool functions for agent to manage the long-term memory voluntarily. You can choose not to implement these two functions.

The record and retrieve methods are for developers to use. For example, retrieving/recording memory at the beginning of each reply, and adding the retrieved memory to the system prompt.

async record(msgs, **kwargs)[源代码]

A developer-designed method to record information from the given input message(s) to the long-term memory.

参数:
  • msgs (list[Msg | None])

  • kwargs (Any)

返回类型:

None

async retrieve(msg, limit=5, **kwargs)[源代码]

A developer-designed method to retrieve information from the long-term memory based on the given input message(s). The retrieved information will be added to the system prompt of the agent.

参数:
  • msg (Msg | list[Msg] | None)

  • limit (int)

  • kwargs (Any)

返回类型:

str

async record_to_memory(thinking, content, **kwargs)[源代码]

Use this function to record important information that you may need later. The target content should be specific and concise, e.g. who, when, where, do what, why, how, etc.

参数:
  • thinking (str) -- Your thinking and reasoning about what to record

  • content (list[str]) -- The content to remember, which is a list of strings.

  • kwargs (Any)

返回类型:

ToolResponse

async retrieve_from_memory(keywords, limit=5, **kwargs)[源代码]

Retrieve the memory based on the given keywords.

参数:
  • keywords (list[str]) -- The keywords to search for in the memory, which should be specific and concise, e.g. the person's name, the date, the location, etc.

  • limit (int, optional) -- The maximum number of memories to retrieve per search, i.e., the number of memories to retrieve for each keyword. Defaults to 5.

  • kwargs (Any)

返回:

A list of messages that match the keywords.

返回类型:

list[Msg]

class Mem0LongTermMemory[源代码]

基类:LongTermMemoryBase

A class that implements the LongTermMemoryBase interface using mem0.

__init__(agent_name=None, user_name=None, run_name=None, model=None, embedding_model=None, vector_store_config=None, mem0_config=None, default_memory_type=None, **kwargs)[源代码]

Initialize the Mem0LongTermMemory instance

参数:
  • agent_name (str | None, optional) -- The name of the agent. Default is None.

  • user_name (str | None, optional) -- The name of the user. Default is None.

  • run_name (str | None, optional) -- The name of the run/session. Default is None.

  • model (ChatModelBase | None)

  • embedding_model (EmbeddingModelBase | None)

  • vector_store_config (Any | None)

  • mem0_config (Any | None)

  • default_memory_type (str | None)

  • kwargs (Any)

返回类型:

None

备注

  1. At least one of agent_name, user_name, or run_name is required.

  2. During memory recording, these parameters become metadata for the stored memories.

  3. Important: mem0 will extract memories from messages containing role of "user" by default. If you want to extract memories from messages containing role of "assistant", you need to provide agent_name.

  4. During memory retrieval, only memories with matching metadata values will be returned.

model (ChatModelBase | None, optional):

The chat model to use for the long-term memory. If mem0_config is provided, this will override the LLM configuration. If mem0_config is None, this is required.

embedding_model (EmbeddingModelBase | None, optional):

The embedding model to use for the long-term memory. If mem0_config is provided, this will override the embedder configuration. If mem0_config is None, this is required.

vector_store_config (VectorStoreConfig | None, optional):

The vector store config to use for the long-term memory. If mem0_config is provided, this will override the vector store configuration. If mem0_config is None and this is not provided, defaults to Qdrant with on_disk=True.

mem0_config (MemoryConfig | None, optional):

The mem0 config to use for the long-term memory. If provided, individual model/embedding_model/vector_store_config parameters will override the corresponding configurations in mem0_config. If None, a new MemoryConfig will be created using the provided parameters.

default_memory_type (str | None, optional):

The type of memory to use. Default is None, to create a semantic memory.

抛出:

ValueError -- If mem0_config is None and either model or embedding_model is None.

参数:
  • agent_name (str | None)

  • user_name (str | None)

  • run_name (str | None)

  • model (ChatModelBase | None)

  • embedding_model (EmbeddingModelBase | None)

  • vector_store_config (Any | None)

  • mem0_config (Any | None)

  • default_memory_type (str | None)

  • kwargs (Any)

返回类型:

None

async record_to_memory(thinking, content, **kwargs)[源代码]

Use this function to record important information that you may need later. The target content should be specific and concise, e.g. who, when, where, do what, why, how, etc.

参数:
  • thinking (str) -- Your thinking and reasoning about what to record.

  • content (list[str]) -- The content to remember, which is a list of strings.

  • kwargs (Any)

返回类型:

ToolResponse

async retrieve_from_memory(keywords, limit=5, **kwargs)[源代码]

Retrieve the memory based on the given keywords.

参数:
  • keywords (list[str]) -- Short, targeted search phrases (for example, a person's name, a specific date, a location, or a phrase describing something you want to retrieve from the memory). Each keyword is issued as an independent query against the memory store.

  • limit (int, optional) -- The maximum number of memories to retrieve per search, defaults to 5. i.e.,the number of memories to retrieve for each keyword.

  • kwargs (Any)

返回:

A ToolResponse containing the retrieved memories as JSON text.

返回类型:

ToolResponse

async record(msgs, memory_type=None, infer=True, **kwargs)[源代码]

Record the content to the long-term memory.

参数:
  • msgs (list[Msg | None]) -- The messages to record to memory.

  • memory_type (str | None, optional) -- The type of memory to use. Default is None, to create a semantic memory. "procedural_memory" is explicitly used for procedural memories.

  • infer (bool, optional) -- Whether to infer memory from the content. Default is True.

  • **kwargs (Any) -- Additional keyword arguments for the mem0 recording.

返回类型:

None

async retrieve(msg, limit=5, **kwargs)[源代码]

Retrieve the content from the long-term memory.

参数:
  • msg (Msg | list[Msg] | None) -- The message to search for in the memory, which should be specific and concise, e.g. the person's name, the date, the location, etc.

  • limit (int, optional) -- The maximum number of memories to retrieve per search, i.e., the number of memories to retrieve for the message. if the message is a list of messages, the limit will be applied to each message. If the message is a single message, then the limit is the total number of memories to retrieve for the message. Defaults to 5.

  • **kwargs (Any) -- Additional keyword arguments.

返回:

The retrieved memory

返回类型:

str

class ReMePersonalLongTermMemory[源代码]

基类:ReMeLongTermMemoryBase

Personal memory implementation using ReMe library.

async record_to_memory(thinking, content, **kwargs)[源代码]

Record important user information to long-term memory.

Record important user information to long-term memory for future reference.

Use this function to save user's personal information, preferences, habits, and facts that you may need in future conversations. This enables you to provide personalized and contextually relevant responses.

When to record:

  • User shares personal preferences (e.g., "I prefer homestays when traveling")

  • User mentions habits or routines (e.g., "I start work at 9 AM")

  • User states likes/dislikes (e.g., "I enjoy drinking green tea")

  • User provides personal facts (e.g., "I work as a software engineer")

What to record: Be specific and structured. Include who, when, where, what, why, and how when relevant.

参数:
  • thinking (str) -- Your reasoning about why this information is worth recording and how it might be useful later.

  • content (list[str]) -- List of specific facts to remember. Each string should be a clear, standalone piece of information. Examples: ["User prefers homestays in Hangzhou", "User likes visiting West Lake in the morning"].

  • **kwargs (Any) -- Additional keyword arguments for the recording operation.

返回:

Confirmation message indicating successful memory recording.

返回类型:

ToolResponse

async retrieve_from_memory(keywords, limit=5, **kwargs)[源代码]

Search and retrieve relevant information from long-term memory.

备注

You should call this function BEFORE answering questions about the user's preferences, past information, or personal details. This ensures you provide accurate information based on stored memories rather than guessing.

Use this when:

  • User asks "what do I like?", "what are my preferences?", "what do you know about me?"

  • User asks about their past behaviors, habits, or stated preferences

  • User refers to information they shared in previous conversations

  • You need to personalize responses based on user's history

参数:
  • keywords (list[str]) -- Keywords to search for in memory. Be specific and use multiple keywords for better results. Examples: ["travel preferences", "Hangzhou"], ["work habits", "morning routine"], ["food preferences", "tea"].

  • limit (int, optional) -- The maximum number of memories to retrieve per search, i.e., the number of memories to retrieve for each keyword. Defaults to 3.

  • **kwargs (Any) -- Additional keyword arguments for the retrieval operation.

返回:

Retrieved memories matching the keywords. If no memories found, you'll receive a message indicating that.

返回类型:

ToolResponse

async record(msgs, **kwargs)[源代码]

Record the content to the long-term memory.

This method converts AgentScope messages to ReMe's format and records them using the personal memory flow.

参数:
  • msgs (list[Msg | None]) -- The messages to record to memory.

  • **kwargs (Any) -- Additional keyword arguments for the mem0 recording.

返回类型:

None

async retrieve(msg, limit=5, **kwargs)[源代码]

Retrieve the content from the long-term memory.

参数:
  • msg (Msg | list[Msg] | None) -- The message to search for in the memory, which should be specific and concise, e.g. the person's name, the date, the location, etc.

  • limit (int, optional) -- The maximum number of memories to retrieve per search, i.e., the number of memories to retrieve for the message. If the message is a list of messages, the limit applies to each message. If the message is a single message, the limit is the total number of memories to retrieve for that message. Defaults to 5.

  • **kwargs (Any) -- Additional keyword arguments.

返回:

The retrieved memory as a string.

返回类型:

str

class ReMeTaskLongTermMemory[源代码]

基类:ReMeLongTermMemoryBase

Task memory implementation using ReMe library.

Task memory learns from execution trajectories and provides retrieval of relevant task experiences.

async record_to_memory(thinking, content, **kwargs)[源代码]

Record task execution experiences and learnings.

Record task execution experiences and learnings to long-term memory.

Use this function to save valuable task-related knowledge that can help with future similar tasks. This enables learning from experience and improving over time.

When to record:

  • After solving technical problems or completing tasks

  • When discovering useful techniques or approaches

  • After implementing solutions with specific steps

  • When learning best practices or important lessons

What to record: Be detailed and actionable. Include:

  • Task description and context

  • Step-by-step execution details

  • Specific techniques and methods used

  • Results, outcomes, and effectiveness

  • Lessons learned and considerations

参数:
  • thinking (str) -- Your reasoning about why this task experience is valuable and what makes it worth remembering for future reference.

  • content (list[str]) -- List of specific task insights to remember. Each string should be a clear, actionable piece of information. Examples: ["Add indexes on WHERE clause columns to speed up queries", "Use EXPLAIN ANALYZE to identify missing indexes"].

  • **kwargs (Any) -- Additional keyword arguments. Can include 'score' (float) to indicate the quality/success of this approach (default: 1.0).

返回:

Confirmation message indicating successful memory recording.

返回类型:

ToolResponse

async retrieve_from_memory(keywords, limit=5, **kwargs)[源代码]

Search and retrieve relevant task experiences.

Search and retrieve relevant task experiences from long-term memory.

IMPORTANT: You should call this function BEFORE attempting to solve problems or answer technical questions. This ensures you leverage experiences and proven solutions rather than starting from scratch.

Use this when: - Asked to solve a technical problem or implement a solution - Asked for recommendations, best practices, or approaches - Asked "what do you know about...?" or "have you seen this

before?"

  • Dealing with tasks that may be similar to experiences

  • Need to recall specific techniques or methods

Benefits of retrieving first: - Learn from past successes and mistakes - Provide more accurate, battle-tested solutions - Avoid reinventing the wheel - Give consistent, informed recommendations

参数:
  • keywords (list[str]) -- Keywords describing the task or problem domain. Be specific and use technical terms. Examples: ["database optimization", "slow queries"], ["API design", "rate limiting"], ["code refactoring", "Python"].

  • limit (int, optional) -- The maximum number of memories to retrieve per search, i.e., the number of memories to retrieve for each keyword. Defaults to 5.

  • **kwargs (Any) -- Additional keyword arguments. Can include 'top_k' (int) to specify number of experiences to retrieve (default: 3).

返回:

Retrieved task experiences and learnings. If no relevant experiences found, you'll receive a message indicating that.

返回类型:

ToolResponse

async record(msgs, **kwargs)[源代码]

Record the content to the task memory.

This method converts AgentScope messages to ReMe's format and records them as a task execution trajectory.

参数:
  • msgs (list[Msg | None]) -- The messages to record to memory.

  • **kwargs (Any) -- Additional keyword arguments for the recording. Can include 'score' (float) for trajectory scoring (default: 1.0).

返回类型:

None

async retrieve(msg, limit=5, **kwargs)[源代码]

Retrieve relevant task experiences from memory.

参数:
  • msg (Msg | list[Msg] | None) -- The message to search for relevant task experiences.

  • limit (int, optional) -- The maximum number of memories to retrieve per search, i.e., the number of memories to retrieve for the message. If the message is a list of messages, the limit applies to each message. If the message is a single message, the limit is the total number of memories to retrieve for that message. Defaults to 3.

  • **kwargs (Any) -- Additional keyword arguments.

返回:

The retrieved task experiences as a string.

返回类型:

str

class ReMeToolLongTermMemory[源代码]

基类:ReMeLongTermMemoryBase

Tool memory implementation using ReMe library.

Tool memory records tool execution results and generates usage guidelines from the execution history.

async record_to_memory(thinking, content, **kwargs)[源代码]

Record tool execution results to build tool usage patterns.

Record tool execution results to build a knowledge base of tool usage patterns.

Use this function after successfully using tools to capture execution details, results, and performance metrics. Over time, this builds comprehensive usage guidelines and best practices for each tool.

When to record:

  • After successfully executing any tool

  • After tool failures (to learn what doesn't work)

  • When discovering effective parameter combinations

  • After noteworthy tool usage patterns

What to record: Each tool execution should include complete execution details.

参数:
  • thinking (str) -- Your reasoning about why this tool execution is worth recording. Mention what worked well, what could be improved, or lessons learned.

  • content (list[str]) --

    List of JSON strings, each representing a tool execution. Each JSON must have these fields: - create_time: Timestamp in format "YYYY-MM-DD HH:MM:SS" - tool_name: Name of the tool executed - input: Input parameters as a dict - output: Tool's output as a string - token_cost: Token cost (integer) - success: Whether execution succeeded (boolean) - time_cost: Execution time in seconds (float)

    Example: '{"create_time": "2024-01-01 10:00:00", "tool_name": "search", "input": {"query": "Python"}, "output": "Found 10 results", "token_cost": 100, "success": true, "time_cost": 1.2}'

  • **kwargs (Any) -- Additional keyword arguments for the recording operation.

返回:

Confirmation message with number of executions recorded and guidelines generated.

返回类型:

ToolResponse

async retrieve_from_memory(keywords, limit=5, **kwargs)[源代码]

Retrieve usage guidelines and best practices for tools.

Retrieve usage guidelines and best practices for specific tools.

备注

You should call this function BEFORE using a tool, especially if you're uncertain about its proper usage or want to follow established best practices. This retrieves synthesized guidelines based on past tool executions.

Use this when:

  • About to use a tool and want to know the best practices

  • Uncertain about tool parameters or usage patterns

  • Want to learn from past successful/failed tool executions

  • User asks "how should I use this tool?" or "what's the best way to..."

  • Need to understand tool performance characteristics or limitations

Benefits of retrieving first:

  • Learn from accumulated tool usage experience

  • Avoid common mistakes and pitfalls

  • Use optimal parameter combinations

  • Understand tool performance and cost characteristics

  • Follow established best practices

参数:
  • keywords (list[str]) -- List of tool names to retrieve guidelines for. Use the exact tool names. Examples: ["search"], ["database_query", "cache_get"], ["api_call"].

  • limit (int, optional) -- The maximum number of memories to retrieve per search, i.e., the number of memories to retrieve for each keyword. Defaults to 5.

  • **kwargs (Any) -- Additional keyword arguments for the retrieval operation.

返回:

Retrieved usage guidelines and best practices for the specified tools. If no guidelines exist yet, you'll receive a message indicating that.

返回类型:

ToolResponse

async record(msgs, **kwargs)[源代码]

Record the content to the tool memory.

This method extracts content from messages and treats them as JSON strings representing tool_call_results, similar to record_to_memory.

参数:
  • msgs (list[Msg | None]) -- The messages to record to memory. Each message's content should be a JSON string or list of JSON strings representing tool_call_results.

  • **kwargs (Any) -- Additional keyword arguments for the recording.

返回类型:

None

async retrieve(msg, limit=5, **kwargs)[源代码]

Retrieve tool guidelines from memory.

Retrieve tool guidelines from memory based on message content.

参数:
  • msg (Msg | list[Msg] | None) -- The message containing tool names or queries to retrieve guidelines for.

  • limit (int, optional) -- The maximum number of memories to retrieve per search, i.e., the number of memories to retrieve for the message. If the message is a list of messages, the limit applies to each message. If the message is a single message, the limit is the total number of memories to retrieve for that message. Defaults to 5.

  • **kwargs (Any) -- Additional keyword arguments.

返回:

The retrieved tool guidelines as a string.

返回类型:

str