-
Notifications
You must be signed in to change notification settings - Fork 276
Feat/memory impl #157
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
wgzesg-bd
wants to merge
2
commits into
volcengine:main
Choose a base branch
from
wgzesg-bd:feat/memory_impl
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Feat/memory impl #157
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,121 @@ | ||
# Copyright 2025 Bytedance Ltd. and/or its affiliates | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
import redis.asyncio as redis | ||
from redis.asyncio.retry import Retry | ||
from redis.backoff import ExponentialBackoff | ||
from redis.exceptions import BusyLoadingError, ConnectionError, TimeoutError | ||
|
||
from arkitect.core.client.base import Client | ||
|
||
|
||
class RedisClient(Client): | ||
""" | ||
Initialize a new Redis client object. | ||
|
||
Parameters: | ||
host (str): The hostname of the Redis server. | ||
username (str): The username for the Redis server. | ||
password (str): The password for the Redis server. | ||
|
||
Returns: | ||
None. | ||
|
||
""" | ||
|
||
def __init__(self, host: str, username: str, password: str): | ||
self.client = redis.Redis( | ||
host=host, | ||
username=username, | ||
password=password, | ||
retry=Retry(ExponentialBackoff(), 3), | ||
retry_on_error=[BusyLoadingError, ConnectionError, TimeoutError], | ||
) | ||
|
||
async def get(self, key: str) -> str: | ||
""" | ||
Get the value of a key from the Redis database. | ||
|
||
Args: | ||
key (str): The key to retrieve from the Redis database. | ||
|
||
Returns: | ||
str: The value of the key, or None if the key does not exist. | ||
|
||
""" | ||
return await self.client.get(key) | ||
|
||
async def set(self, key: str, value: str) -> None: | ||
""" | ||
Set the value of a key in the Redis database. | ||
Args: | ||
key (str): The key to set in the Redis database. | ||
value (str): The value to set for the key. | ||
Returns: | ||
None. | ||
""" | ||
await self.client.set(key, value) | ||
|
||
async def get_with_prefix(self, prefix: str) -> tuple[list[str], list[str]]: | ||
""" | ||
Asynchronous method to obtain all keys and values from the | ||
Redis database that match the specified prefix | ||
|
||
:param prefix: The specified prefix | ||
|
||
:return: A list of tuples containing matching keys | ||
and their corresponding values | ||
""" | ||
|
||
cursor = 0 | ||
keys = [] | ||
|
||
while True: | ||
# 使用 SCAN 命令进行迭代查询 | ||
cursor, key_data = await self.client.scan(cursor, match=prefix, count=1000) | ||
|
||
# 将匹配到的 key 添加到列表中 | ||
keys.extend(key_data) | ||
|
||
# 如果游标值为 0,则表示遍历完成 | ||
if cursor == 0 or len(key_data) == 0: | ||
break | ||
|
||
# 使用 MGET 命令获取所有匹配到的 key 的对应 value | ||
values = await self.client.mget(keys) | ||
|
||
return keys, values | ||
|
||
async def mget(self, keys: list[str]) -> list[str]: | ||
""" | ||
Get the values of multiple keys from the Redis database. | ||
|
||
Args: | ||
keys (list): A list of keys to retrieve from the Redis database. | ||
|
||
Returns: | ||
list: A list of values corresponding to the given keys. | ||
|
||
""" | ||
return await self.client.mget(keys) | ||
|
||
async def delete(self, key: str) -> None: | ||
""" | ||
Delete a key from the Redis database. | ||
Args: | ||
key (str): The key to delete from the Redis database. | ||
Returns: | ||
None. | ||
""" | ||
await self.client.delete(key) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
# Copyright 2025 Bytedance Ltd. and/or its affiliates | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
from .base_memory_service import BaseMemoryService | ||
from .in_memory_memory_service import ( | ||
InMemoryMemoryService, | ||
InMemoryMemoryServiceSingleton, | ||
) | ||
|
||
|
||
__all__ = [ | ||
"BaseMemoryService", | ||
"InMemoryMemoryService", | ||
"InMemoryMemoryServiceSingleton", | ||
] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
# Copyright 2025 Bytedance Ltd. and/or its affiliates | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
from abc import ABC, abstractmethod | ||
from typing import Any | ||
|
||
from openai.types.responses import Response | ||
from pydantic import BaseModel | ||
from volcenginesdkarkruntime.types.chat.chat_completion_message import ( | ||
ChatCompletionMessage, | ||
) | ||
|
||
from arkitect.types.llm.model import Message | ||
|
||
|
||
class Memory(BaseModel): | ||
memory_content: str | ||
reference: Any | None = None | ||
metadata: Any | None = None | ||
|
||
|
||
class SearchMemoryResponse(BaseModel): | ||
memories: list[Memory] | ||
|
||
@property | ||
def content(self) -> str: | ||
return "\n".join([m.memory_content for m in self.memories]) | ||
|
||
|
||
class BaseMemoryService(ABC): | ||
@abstractmethod | ||
async def update_memory( | ||
self, | ||
user_id: str, | ||
new_messages: list[Message | dict | Response | ChatCompletionMessage], | ||
**kwargs: Any, | ||
) -> None: | ||
pass | ||
|
||
@abstractmethod | ||
async def search_memory( | ||
self, | ||
user_id: str, | ||
query: str, | ||
**kwargs: Any, | ||
) -> SearchMemoryResponse: | ||
pass |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
add_or_update有点冗长,叫
upsert_memory
呢?然后接口感觉可以扩展成
@abstractmethod async def upsert_memory( self, user_id: str, data: list[Any], source: DataSource = DataSource.CHAT_MESSAGE, # 将来可以扩展更多的入库的数据,不单单局限在对话的message **kwargs: Any, ) -> None: ...
从而将来可以接入更多数据源,而不单单是对话消息
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
嗯嗯 我觉得要不先把new_messages 改为data: list[Any] 吧,其他source 之后需要加了再加上?暂时不放在base 的interface里
不一定强求所有实现都可以支持各种datasource,但来自message的应该是都会支持的
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
好,我其实想留一个 datasource 是想让接口看起来不是专门针对对话消息的,将来可能可以继续扩展出来各种生产资料,比如doc啥的