|
| 1 | +""" |
| 2 | +Mem0 toolkit demo using SpoonReactAI. |
| 3 | +This demo requires spoon-toolkit to be installed (pip install spoon-toolkit or local install). |
| 4 | +""" |
| 5 | + |
| 6 | +import asyncio |
| 7 | +from typing import Dict, List, Optional |
| 8 | + |
| 9 | +from pydantic import Field |
| 10 | + |
| 11 | +from spoon_ai.agents.spoon_react import SpoonReactAI |
| 12 | +from spoon_ai.chat import ChatBot |
| 13 | +from spoon_ai.llm.manager import get_llm_manager |
| 14 | +from spoon_ai.memory.utils import extract_memories, extract_first_memory_id |
| 15 | +from spoon_ai.tools.tool_manager import ToolManager |
| 16 | +from spoon_ai.tools.base import ToolResult |
| 17 | +from spoon_toolkits.memory import ( |
| 18 | + AddMemoryTool, |
| 19 | + SearchMemoryTool, |
| 20 | + GetAllMemoryTool, |
| 21 | + UpdateMemoryTool, |
| 22 | + DeleteMemoryTool, |
| 23 | +) |
| 24 | + |
| 25 | + |
| 26 | +USER_ID = "defi_user_005" |
| 27 | + |
| 28 | + |
| 29 | +class DeFiMemoryAgent(SpoonReactAI): |
| 30 | + """Brain from spoon-core + memory tools from spoon-toolkit.""" |
| 31 | + |
| 32 | + mem0_config: Dict[str, any] = Field(default_factory=dict) |
| 33 | + available_tools: ToolManager = Field(default_factory=lambda: ToolManager([])) |
| 34 | + |
| 35 | + def model_post_init(self, __context: any = None) -> None: |
| 36 | + super().model_post_init(__context) |
| 37 | + memory_tools = [ |
| 38 | + AddMemoryTool(mem0_config=self.mem0_config), |
| 39 | + SearchMemoryTool(mem0_config=self.mem0_config), |
| 40 | + GetAllMemoryTool(mem0_config=self.mem0_config), |
| 41 | + UpdateMemoryTool(mem0_config=self.mem0_config), |
| 42 | + DeleteMemoryTool(mem0_config=self.mem0_config), |
| 43 | + ] |
| 44 | + self.available_tools = ToolManager(memory_tools) |
| 45 | + if hasattr(self, "_refresh_prompts"): |
| 46 | + self._refresh_prompts() |
| 47 | + |
| 48 | + |
| 49 | +def build_agent(mem0_cfg: Dict[str, any]) -> DeFiMemoryAgent: |
| 50 | + return DeFiMemoryAgent( |
| 51 | + llm=ChatBot( |
| 52 | + llm_provider="openrouter", |
| 53 | + model_name="anthropic/claude-3.5-sonnet", |
| 54 | + enable_long_term_memory=False, # memory comes from toolkit tools instead |
| 55 | + ), |
| 56 | + mem0_config=mem0_cfg, |
| 57 | + system_prompt=( |
| 58 | + "You are a DeFi investment advisor. Use the provided Mem0 tools to recall " |
| 59 | + "and update user preferences before answering." |
| 60 | + ), |
| 61 | + ) |
| 62 | + |
| 63 | + |
| 64 | +def print_memories(result: ToolResult, label: str) -> None: |
| 65 | + memories = extract_memories(result) |
| 66 | + print(f"[Mem0] {label}:") |
| 67 | + if not memories: |
| 68 | + print(" (none)") |
| 69 | + for m in memories: |
| 70 | + print(f" - {m}") |
| 71 | + |
| 72 | + |
| 73 | +async def phase_capture(agent: DeFiMemoryAgent) -> None: |
| 74 | + print("\n=== Phase 1: Capture high-risk Solana preferences ===") |
| 75 | + await agent.available_tools.execute( |
| 76 | + name="add_memory", |
| 77 | + tool_input={ |
| 78 | + "messages": [ |
| 79 | + { |
| 80 | + "role": "user", |
| 81 | + "content": ( |
| 82 | + "I am a high-risk degen trader. I exclusively trade meme coins on Solana " |
| 83 | + "and dislike Ethereum gas fees." |
| 84 | + ), |
| 85 | + } |
| 86 | + ], |
| 87 | + "user_id": USER_ID, |
| 88 | + "async_mode": False, |
| 89 | + }, |
| 90 | + ) |
| 91 | + # Verify storage immediately after add to avoid read-after-write surprises |
| 92 | + verified: ToolResult = ToolResult() |
| 93 | + for attempt in range(3): |
| 94 | + verified = await agent.available_tools.execute( |
| 95 | + name="get_all_memory", |
| 96 | + tool_input={"user_id": USER_ID, "limit": 5}, |
| 97 | + ) |
| 98 | + if extract_memories(verified): |
| 99 | + break |
| 100 | + await asyncio.sleep(0.5) |
| 101 | + print_memories(verified, "Verification after Phase 1 store") |
| 102 | + |
| 103 | + memories = await agent.available_tools.execute( |
| 104 | + name="search_memory", |
| 105 | + tool_input={"query": "Solana meme coins high risk", "user_id": USER_ID}, |
| 106 | + ) |
| 107 | + print_memories(memories, "After Phase 1 store") |
| 108 | + |
| 109 | + |
| 110 | +async def phase_recall(mem0_cfg: Dict[str, any]) -> None: |
| 111 | + print("\n=== Phase 2: Recall with a fresh agent instance ===") |
| 112 | + agent = build_agent(mem0_cfg) |
| 113 | + memories = await agent.available_tools.execute( |
| 114 | + name="search_memory", |
| 115 | + tool_input={"query": "trading strategy solana meme", "user_id": USER_ID}, |
| 116 | + ) |
| 117 | + print_memories(memories, "Retrieved for Phase 2") |
| 118 | + |
| 119 | + |
| 120 | +async def phase_update(agent: DeFiMemoryAgent, memory_id: Optional[str]) -> None: |
| 121 | + print("\n=== Phase 3: Update preferences to safer Arbitrum yield ===") |
| 122 | + await agent.available_tools.execute( |
| 123 | + name="add_memory", |
| 124 | + tool_input={ |
| 125 | + "messages": [ |
| 126 | + { |
| 127 | + "role": "user", |
| 128 | + "content": ( |
| 129 | + "I lost too much money. I want to pivot to safe stablecoin yield farming on Arbitrum now." |
| 130 | + ), |
| 131 | + } |
| 132 | + ], |
| 133 | + "user_id": USER_ID, |
| 134 | + "async_mode": False, |
| 135 | + }, |
| 136 | + ) |
| 137 | + update_result = await agent.available_tools.execute( |
| 138 | + name="update_memory", |
| 139 | + tool_input={ |
| 140 | + "memory_id": memory_id, |
| 141 | + "text": "User pivoted to safer Arbitrum stablecoin yield farming with low risk.", |
| 142 | + "user_id": USER_ID, |
| 143 | + }, |
| 144 | + ) |
| 145 | + print(f"[Mem0] Update result: {update_result}") |
| 146 | + memories = await agent.available_tools.execute( |
| 147 | + name="search_memory", |
| 148 | + tool_input={"query": "stablecoin yield chain choice", "user_id": USER_ID}, |
| 149 | + ) |
| 150 | + print_memories(memories, "Retrieved after update (Phase 3)") |
| 151 | + |
| 152 | + |
| 153 | +async def phase_cleanup(agent: DeFiMemoryAgent, memory_id: Optional[str]) -> None: |
| 154 | + print("\n=== Phase 4: Clean up a memory entry ===") |
| 155 | + delete_result = await agent.available_tools.execute( |
| 156 | + name="delete_memory", |
| 157 | + tool_input={"memory_id": memory_id, "user_id": USER_ID}, |
| 158 | + ) |
| 159 | + print(f"[Mem0] Delete result: {delete_result}") |
| 160 | + remaining = await agent.available_tools.execute( |
| 161 | + name="get_all_memory", |
| 162 | + tool_input={"limit": 5, "user_id": USER_ID}, |
| 163 | + ) |
| 164 | + print_memories(remaining, "Remaining memories after delete") |
| 165 | + |
| 166 | + |
| 167 | +async def main() -> None: |
| 168 | + mem0_cfg = { |
| 169 | + "user_id": USER_ID, |
| 170 | + "metadata": {"project": "defi-investment-advisor"}, |
| 171 | + "async_mode": False, # synchronous writes so the next search sees new data |
| 172 | + } |
| 173 | + |
| 174 | + try: |
| 175 | + agent = build_agent(mem0_cfg) |
| 176 | + await phase_capture(agent) |
| 177 | + await phase_recall(mem0_cfg) |
| 178 | + |
| 179 | + all_memories = await agent.available_tools.execute( |
| 180 | + name="get_all_memory", tool_input={"limit": 5, "user_id": USER_ID} |
| 181 | + ) |
| 182 | + print_memories(all_memories, "All memories before update/delete") |
| 183 | + first_id = extract_first_memory_id(all_memories) |
| 184 | + |
| 185 | + await phase_update(agent, first_id) |
| 186 | + await phase_cleanup(agent, first_id) |
| 187 | + finally: |
| 188 | + await get_llm_manager().cleanup() |
| 189 | + |
| 190 | + |
| 191 | +if __name__ == "__main__": |
| 192 | + asyncio.run(main()) |
0 commit comments