Skip to content

Build and run agents you can see, understand and trust.

fix(memory): fix the case when `Mem0LongTermMemory` uses graphstore (#942)

Osier-Yi233915dee2d1
diff --git a/examples/functionality/long_term_memory/mem0/memory_example.py b/examples/functionality/long_term_memory/mem0/memory_example.py
index f711d0282..5e0529ce6 100644
--- a/examples/functionality/long_term_memory/mem0/memory_example.py
+++ b/examples/functionality/long_term_memory/mem0/memory_example.py
@@ -10,7 +10,6 @@ import os
from dotenv import load_dotenv
from mem0.vector_stores.configs import VectorStoreConfig
-
from agentscope.memory import Mem0LongTermMemory
from agentscope.agent import ReActAgent
from agentscope.embedding import DashScopeTextEmbedding
@@ -50,6 +49,45 @@ async def main() -> None:
),
)
+ # If you want to also use graph memory in mem0,
+ # the following is an example of using Neo4j graph store.
+ # from mem0.configs.base import MemoryConfig
+ # from mem0.graphs.configs import GraphStoreConfig
+ # long_term_memory = Mem0LongTermMemory(
+ # agent_name="Friday",
+ # user_name="user_123",
+ # embedding_model=DashScopeTextEmbedding(
+ # model_name="text-embedding-v3",
+ # api_key=os.environ.get("DASHSCOPE_API_KEY"),
+ # dimensions=1024,
+ # ),
+ # model=DashScopeChatModel(
+ # model_name="qwen-max-latest",
+ # api_key=os.environ.get("DASHSCOPE_API_KEY"),
+ # stream=False,
+ # ),
+ # vector_store_config=VectorStoreConfig(
+ # provider="qdrant",
+ # config={
+ # "on_disk": True,
+ # "path": "../memory/qdrant_data", # Specify custom path
+ # "embedding_model_dims": 1024,
+ # }),
+ # mem0_config=MemoryConfig(
+ # graph_store=GraphStoreConfig(
+ # provider="neo4j",
+ # config={
+ # "url": os.environ.get("NEO4J_URL",
+ # "neo4j://localhost:7687"),
+ # "username": os.environ.get("NEO4J_USER", "neo4j"),
+ # "password": os.environ.get("NEO4J_PASSWORD",
+ # "12345678"),
+ # "database": "neo4j",
+ # },
+ # ),
+ # ),
+ # )
+
print("=== Long Term Memory Examples with mem0 ===\n")
# Example 1: Basic conversation recording
diff --git a/src/agentscope/memory/_mem0_long_term_memory.py b/src/agentscope/memory/_mem0_long_term_memory.py
index b964209c7..c584c9bb8 100644
--- a/src/agentscope/memory/_mem0_long_term_memory.py
+++ b/src/agentscope/memory/_mem0_long_term_memory.py
@@ -424,6 +424,10 @@ class Mem0LongTermMemory(LongTermMemoryBase):
results.extend(
[item["memory"] for item in result["results"]],
)
+ if "relations" in result.keys():
+ results.extend(
+ self._format_relations(result),
+ )
return ToolResponse(
content=[
@@ -490,6 +494,28 @@ class Mem0LongTermMemory(LongTermMemoryBase):
**kwargs,
)
+ def _format_relations(self, result: dict) -> list:
+ """Format relations from search result.
+
+ Args:
+ result (`dict`):
+ The result from the memory search operation.
+
+ Returns:
+ `list`:
+ The formatted relations.
+ Each relation is a string in the format of:
+ "{source} -- {relationship} -- {destination}"
+ """
+ if "relations" not in result:
+ return []
+ return [
+ f"{relation['source']} -- "
+ f"{relation['relationship']} -- "
+ f"{relation['destination']}"
+ for relation in result["relations"]
+ ]
+
async def _mem0_record(
self,
messages: str | list[dict],
@@ -589,5 +615,9 @@ class Mem0LongTermMemory(LongTermMemoryBase):
results.extend(
[memory["memory"] for memory in result["results"]],
)
+ if "relations" in result.keys():
+ results.extend(
+ self._format_relations(result),
+ )
return "\n".join(results)
diff --git a/src/agentscope/memory/_mem0_utils.py b/src/agentscope/memory/_mem0_utils.py
index 72b36048b..2a74af9b1 100644
--- a/src/agentscope/memory/_mem0_utils.py
+++ b/src/agentscope/memory/_mem0_utils.py
@@ -41,13 +41,64 @@ class AgentScopeLLM(LLMBase):
self.agentscope_model = self.config.model
+ def _parse_response(
+ self,
+ model_response: ChatResponse,
+ has_tool: bool,
+ ) -> str | dict:
+ """Parse the model response into a string or
+ a dict to follow the mem0 library's format.
+
+ Args:
+ model_response (`ChatResponse`): The response from the model.
+ has_tool (`bool`): Whether there are tool calls in the response.
+
+ Returns:
+ `str | dict`:
+ The parsed response. If has_tool is True, return a dict
+ with "content" and "tool_calls" keys. Otherwise, return
+ a string.
+ """
+ text_parts: list[str] = []
+ thinking_parts: list[str] = []
+ tool_parts = []
+ for block in model_response.content:
+ # Handle TextBlock
+ if isinstance(block, dict) and block.get("type") == "text":
+ text_parts.append(str(block.get("text", "")))
+
+ # Handle ThinkingBlock
+ elif isinstance(block, dict) and block.get("type") == "thinking":
+ thinking_parts.append(
+ f"[Thinking: {block.get('thinking', '')}]",
+ )
+ # Handle ToolUseBlock
+ elif isinstance(block, dict) and block.get("type") == "tool_use":
+ tool_name = block.get("name")
+ tool_input = block.get("input", {})
+ tool_parts.append(
+ {
+ "name": tool_name,
+ "arguments": tool_input,
+ },
+ )
+ text_part = thinking_parts + text_parts
+ if has_tool:
+ # If there are tool calls, return the content and tool calls
+ return {
+ "content": "\n".join(text_part) if len(text_part) > 0 else "",
+ "tool_calls": tool_parts,
+ }
+ else:
+ return "\n".join(text_part) if len(text_part) > 0 else ""
+
def generate_response(
self,
messages: List[Dict[str, str]],
response_format: Any | None = None,
tools: List[Dict] | None = None,
tool_choice: str = "auto",
- ) -> str:
+ ) -> str | dict:
"""Generate a response based on the given messages using agentscope.
Args:
@@ -61,7 +112,7 @@ class AgentScopeLLM(LLMBase):
Tool choice method. Not used in AgentScope.
Returns:
- `str`:
+ `str | dict`:
The generated response.
"""
# pylint: disable=unused-argument
@@ -92,47 +143,19 @@ class AgentScopeLLM(LLMBase):
)
response = asyncio.run(_async_call())
+ has_tool = tools is not None
# Extract text from the response content blocks
if not response.content:
- return ""
-
- # Collect all text from different block types
- text_parts = []
- thinking_parts = []
- tool_parts = []
-
- for block in response.content:
- # Handle TextBlock
- if isinstance(block, dict) and block.get("type") == "text":
- text_parts.append(block.get("text", ""))
-
- # Handle ThinkingBlock
- elif (
- isinstance(block, dict) and block.get("type") == "thinking"
- ):
- thinking_parts.append(
- f"[Thinking: {block.get('thinking', '')}]",
- )
-
- # Handle ToolUseBlock
- elif (
- isinstance(block, dict) and block.get("type") == "tool_use"
- ):
- tool_name = block.get("name")
- tool_input = block.get("input", {})
- tool_parts.append(
- f"[Tool: {tool_name} - {str(tool_input)}]",
- )
-
- # Combine all parts in order: thinking, text, tools
- all_parts: list[str] = thinking_parts + text_parts + tool_parts
-
- if all_parts:
- return "\n".join(all_parts)
- # If no recognized blocks found, try to convert the entire
- # content to string
- return str(response.content)
+ if has_tool:
+ return {
+ "content": "",
+ "tool_calls": [],
+ }
+ else:
+ return ""
+
+ return self._parse_response(response, has_tool)
except Exception as e:
raise RuntimeError(