Coverage for tools/memory_tools.py: 29%

1 from pydantic import BaseModel, Field

2 from qrclaw.tools.registry import register

3 from qrclaw.memory import LongTermMemory

4 from qrclaw.logger import get_logger

5

6 logger = get_logger("qrclaw.tools.memory")

7

8 class WriteMemoryArgs(BaseModel):

9 content: str = Field(description="要记录的重要信息，使用 Markdown 格式")

10 title: str = Field(description="可选的标题，用于分类和组织记忆", default="")

11

12 class ReadMemoryArgs(BaseModel):

13 pass # 不需要参数，读取全部记忆

14

15@register(description="写入中期记忆，仅用于记录用户偏好、项目配置等需要跨会话复用的信息，任务结果、调研报告等不要写入", args_model=WriteMemoryArgs)

16 def write_memory(content: str, title: str = "") -> str:

17 """

18 写入中期记忆

19

20 Args:

21 content: 要记录的内容（Markdown 格式）

22 title: 可选的标题

23

24 Returns:

25 str: 操作结果

26 """

27 logger.debug(f"写入中期记忆: {title or '无标题'}")

28 try:

29 from qrclaw.agent import get_workspace

30 from qrclaw.workspace import Workspace

31 ws = get_workspace() or Workspace("default")

32 memory = LongTermMemory(ws.memory_file)

33 success = memory.append(content, title if title else None)

34

35 if success:

36 result = f"已写入中期记忆: {title if title else '无标题'}"

37 logger.info(result)

38 return result

39 else:

40 error_msg = "写入中期记忆失败"

41 logger.error(error_msg)

42 return error_msg

43 except Exception as e:

44 error_msg = f"错误：写入中期记忆失败 {e}"

45 logger.error(error_msg, exc_info=True)

46 return error_msg

47

48@register(description="读取中期记忆，查看之前记录的重要信息", args_model=ReadMemoryArgs)

49 def read_memory() -> str:

50 """

51 读取中期记忆

52

53 Returns:

54 str: 记忆内容（Markdown 格式）

55 """

56 logger.debug("读取中期记忆")

57 try:

58 from qrclaw.agent import get_workspace

59 from qrclaw.workspace import Workspace

60 ws = get_workspace() or Workspace("default")

61 memory = LongTermMemory(ws.memory_file)

62 content = memory.load()

63

64 if not content or content.strip() == "# QRClaw 中期记忆":

65 logger.info("中期记忆为空")

66 return "中期记忆为空，还没有记录任何信息"

67

68 logger.info(f"读取中期记忆成功: {len(content)} 字符")

69 return content

70 except Exception as e:

71 error_msg = f"错误：读取中期记忆失败 {e}"

72 logger.error(error_msg, exc_info=True)

73 return error_msg