|
| 1 | +import os |
| 2 | +from typing import ClassVar |
| 3 | + |
| 4 | +from qwen_agent.agents import Assistant |
| 5 | +from qwen_agent.tools.base import BaseTool, register_tool |
| 6 | +from qwen_agent.utils.output_beautify import typewriter_print |
| 7 | + |
| 8 | +from memmachine import MemMachineClient |
| 9 | + |
| 10 | +_MEMMACHINE_CLIENT = None |
| 11 | +_MEMMACHINE_PROJECT = None |
| 12 | + |
| 13 | + |
| 14 | +def _get_memmachine_project(): |
| 15 | + """Create (or reuse) a MemMachine Project handle (global boundary).""" |
| 16 | + global _MEMMACHINE_CLIENT, _MEMMACHINE_PROJECT |
| 17 | + if _MEMMACHINE_PROJECT is not None: |
| 18 | + return _MEMMACHINE_PROJECT |
| 19 | + |
| 20 | + base_url = os.getenv("MEMMACHINE_BASE_URL") or "http://localhost:8080" |
| 21 | + api_key = os.getenv("MEMMACHINE_API_KEY") or "" |
| 22 | + org_id = os.getenv("MEMMACHINE_ORG_ID") or "default_org" |
| 23 | + project_id = os.getenv("MEMMACHINE_PROJECT_ID") or "qwen_agent_demo" |
| 24 | + |
| 25 | + _MEMMACHINE_CLIENT = MemMachineClient( |
| 26 | + api_key=api_key, base_url=base_url, timeout=30 |
| 27 | + ) |
| 28 | + _MEMMACHINE_PROJECT = _MEMMACHINE_CLIENT.get_or_create_project( |
| 29 | + org_id=org_id, |
| 30 | + project_id=project_id, |
| 31 | + description="qwen-agent tool memory integration", |
| 32 | + ) |
| 33 | + return _MEMMACHINE_PROJECT |
| 34 | + |
| 35 | + |
| 36 | +@register_tool("save_memory") |
| 37 | +class SaveMemory(BaseTool): |
| 38 | + description = "Save a memory entry to MemMachine." |
| 39 | + parameters: ClassVar[list[dict] | dict] = [ |
| 40 | + { |
| 41 | + "name": "content", |
| 42 | + "type": "string", |
| 43 | + "description": "The content to save.", |
| 44 | + "required": True, |
| 45 | + }, |
| 46 | + ] |
| 47 | + |
| 48 | + def call(self, params: str | dict, **kwargs) -> str: |
| 49 | + data = self._verify_json_format_args(params) |
| 50 | + content = data["content"] |
| 51 | + project = _get_memmachine_project() |
| 52 | + mem = project.memory() |
| 53 | + results = mem.add( |
| 54 | + content=content, |
| 55 | + role="assistant", |
| 56 | + metadata={"type": "message"}, |
| 57 | + ) |
| 58 | + uid = results[0].uid if results else "" |
| 59 | + return f"Saved to MemMachine ({uid}): {content}" |
| 60 | + |
| 61 | + |
| 62 | +@register_tool("search_memory") |
| 63 | +class SearchMemory(BaseTool): |
| 64 | + description = "Search memory for information matching the query." |
| 65 | + parameters: ClassVar[list[dict] | dict] = [ |
| 66 | + { |
| 67 | + "name": "query", |
| 68 | + "type": "string", |
| 69 | + "description": "The query to search in memory.", |
| 70 | + "required": True, |
| 71 | + }, |
| 72 | + ] |
| 73 | + |
| 74 | + @staticmethod |
| 75 | + def _format_episodic_bucket(bucket_name: str, bucket: dict) -> list[str]: |
| 76 | + episodes = bucket.get("episodes") |
| 77 | + if not isinstance(episodes, list) or not episodes: |
| 78 | + return [] |
| 79 | + |
| 80 | + lines: list[str] = [f"{bucket_name}:"] |
| 81 | + lines.extend(f"- {ep['content']}" for ep in episodes) |
| 82 | + return lines |
| 83 | + |
| 84 | + @staticmethod |
| 85 | + def _format_episodic_memory(episodic: dict) -> list[str]: |
| 86 | + lines: list[str] = ["episodic_memory:"] |
| 87 | + |
| 88 | + long_term = episodic.get("long_term_memory") |
| 89 | + if isinstance(long_term, dict): |
| 90 | + lines.extend( |
| 91 | + SearchMemory._format_episodic_bucket("long_term_memory", long_term) |
| 92 | + ) |
| 93 | + |
| 94 | + short_term = episodic.get("short_term_memory") |
| 95 | + if isinstance(short_term, dict): |
| 96 | + lines.extend( |
| 97 | + SearchMemory._format_episodic_bucket("short_term_memory", short_term) |
| 98 | + ) |
| 99 | + |
| 100 | + summaries = short_term.get("episode_summary") |
| 101 | + if isinstance(summaries, list) and summaries: |
| 102 | + lines.append("episode_summary:") |
| 103 | + lines.extend(f"- {s}" for s in summaries) |
| 104 | + |
| 105 | + return lines |
| 106 | + |
| 107 | + @staticmethod |
| 108 | + def _format_semantic_memory(semantic: list) -> list[str]: |
| 109 | + lines: list[str] = ["semantic_memory:"] |
| 110 | + for item in semantic: |
| 111 | + if not isinstance(item, dict): |
| 112 | + lines.append(f"- {item!s}") |
| 113 | + continue |
| 114 | + category = item.get("category") |
| 115 | + tag = item.get("tag") |
| 116 | + feature_name = item.get("feature_name") |
| 117 | + value = item.get("value") |
| 118 | + lines.append(f"- [{category}/{tag}] {feature_name} = {value}") |
| 119 | + return lines |
| 120 | + |
| 121 | + @staticmethod |
| 122 | + def _format_search_content(content: dict) -> list[str]: |
| 123 | + lines: list[str] = [] |
| 124 | + |
| 125 | + episodic = content.get("episodic_memory") |
| 126 | + if isinstance(episodic, dict) and episodic: |
| 127 | + lines.extend(SearchMemory._format_episodic_memory(episodic)) |
| 128 | + |
| 129 | + semantic = content.get("semantic_memory") |
| 130 | + if isinstance(semantic, list) and semantic: |
| 131 | + lines.extend(SearchMemory._format_semantic_memory(semantic)) |
| 132 | + |
| 133 | + return lines |
| 134 | + |
| 135 | + def call(self, params: str | dict, **kwargs) -> str: |
| 136 | + data = self._verify_json_format_args(params) |
| 137 | + query = data["query"] |
| 138 | + project = _get_memmachine_project() |
| 139 | + mem = project.memory() |
| 140 | + result = mem.search(query=query, limit=10) |
| 141 | + |
| 142 | + content = result.content |
| 143 | + lines = self._format_search_content(content) |
| 144 | + return "MemMachine search result:\n" + "\n".join(lines) |
| 145 | + |
| 146 | + |
| 147 | +if __name__ == "__main__": |
| 148 | + llm_cfg = {"model": "qwen3-max"} |
| 149 | + system_message = "You are an assistant that can remember information using tools. When asked to remember something, call save_memory. When asked to recall or search information, call search_memory." |
| 150 | + bot = Assistant( |
| 151 | + llm=llm_cfg, |
| 152 | + system_message=system_message, |
| 153 | + function_list=["save_memory", "search_memory"], |
| 154 | + ) |
| 155 | + |
| 156 | + messages = [ |
| 157 | + { |
| 158 | + "role": "user", |
| 159 | + "content": "My name is Alice and my favorite color is blue. Please remember that.", |
| 160 | + } |
| 161 | + ] |
| 162 | + response_plain_text = "" |
| 163 | + for response in bot.run(messages=messages): |
| 164 | + response_plain_text = typewriter_print(response, response_plain_text) |
| 165 | + |
| 166 | + messages = [ |
| 167 | + { |
| 168 | + "role": "user", |
| 169 | + "content": "What is my name and favorite color? Search your memory.", |
| 170 | + } |
| 171 | + ] |
| 172 | + for response in bot.run(messages=messages): |
| 173 | + response_plain_text = typewriter_print(response, response_plain_text) |
0 commit comments