Skip to main content
Glama

chat_with_memory

Enhance AI responses by automatically retrieving and incorporating relevant stored memories to provide contextual answers to user queries.

Instructions

Chat with memory-enhanced responses.

Use this for questions where stored memories might provide context. The response will incorporate relevant memories automatically.

Args: query: User's question or message top_k: Number of memories to use as context (default: 5)

Returns: AI response enhanced with relevant memories

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes
top_kNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • MCP tool handler for chat_with_memory - decorated with @self.mcp.tool() and calls the core chat method
    @self.mcp.tool()
    async def chat_with_memory(query: str, top_k: int = 5) -> str:
        """Chat with memory-enhanced responses.
    
        Use this for questions where stored memories might provide context.
        The response will incorporate relevant memories automatically.
    
        Args:
            query: User's question or message
            top_k: Number of memories to use as context (default: 5)
    
        Returns:
            AI response enhanced with relevant memories
        """
        try:
            response = self.vault.chat(query, top_k=top_k)
            return response
        except Exception as e:
            logger.error(f"Error in chat: {e}")
            return f"Error generating response: {str(e)}"
  • Core implementation of chat logic - searches for relevant memories, builds context into system prompt, generates LLM response, and maintains chat history
    def chat(
        self,
        query: str,
        top_k: int = 5,
        system_prompt: str | None = None,
        include_history: bool = True,
    ) -> str:
        """Chat with memory-enhanced responses.
    
        Searches for relevant memories and uses them as context for the LLM.
    
        Args:
            query: User's query.
            top_k: Number of memories to include as context.
            system_prompt: Optional custom system prompt (can include {memories_section}).
            include_history: Whether to include chat history.
    
        Returns:
            Assistant's response.
    
        Example:
            >>> response = mem.chat("What language should I use for my backend?")
            >>> print(response)
        """
        # Search for relevant memories
        memories = self._cube.search(query, top_k)
    
        # Build memories section
        if memories:
            memory_lines = [f"- {mem.memory}" for mem in memories]
            memories_section = "## Relevant Memories:\n" + "\n".join(memory_lines)
        else:
            memories_section = ""
    
        # Build system prompt
        if system_prompt:
            system_content = system_prompt.format(memories_section=memories_section)
        else:
            system_content = CHAT_SYSTEM_PROMPT.format(memories_section=memories_section)
    
        # Build messages
        messages = [{"role": "system", "content": system_content}]
    
        if include_history:
            messages.extend(self._chat_history.get_messages())
    
        messages.append({"role": "user", "content": query})
    
        # Generate response
        response = self._llm.generate(messages)
    
        # Update chat history
        self._chat_history.add_user_message(query)
        self._chat_history.add_assistant_message(response)
    
        logger.debug(f"Chat response generated with {len(memories)} memories as context")
        return response
  • System prompt template used by the chat function - includes placeholder for memories_section to inject relevant memories
    CHAT_SYSTEM_PROMPT = """You are a knowledgeable and helpful AI assistant with access to personal memories.
    You have stored memories that help you provide personalized responses.
    Use these memories to understand the user's context, preferences, and past interactions.
    Reference memories naturally when relevant, but don't explicitly mention having a memory system.
    
    {memories_section}"""
  • Tool registration setup call in __init__ that triggers registration of chat_with_memory and other tools
    self._setup_tools()
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden. It mentions that responses are 'enhanced with relevant memories automatically,' but lacks details on behavioral traits such as how memories are selected, whether this requires specific permissions, rate limits, or what happens if no memories are found. The description is minimal and doesn't adequately disclose operational behavior.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately sized and front-loaded: it starts with the core purpose, followed by usage guidelines, then parameter explanations, and return value. Every sentence adds value without redundancy, making it efficient and well-structured.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's moderate complexity (2 parameters, no annotations, but with an output schema), the description is somewhat complete but has gaps. It explains the purpose, usage, and parameters, but lacks behavioral details and doesn't fully leverage the output schema (which exists but isn't referenced). For a memory-enhanced chat tool, more context on how memories are integrated would be helpful.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The description includes an 'Args' section that explains 'query' as the user's question and 'top_k' as the number of memories to use as context with a default. Since schema description coverage is 0%, this adds meaningful semantics beyond the bare schema, but it doesn't fully compensate for the coverage gap (e.g., no details on 'top_k' constraints or 'query' format).

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Chat with memory-enhanced responses' and 'The response will incorporate relevant memories automatically.' It specifies the verb (chat) and resource (memory-enhanced responses), but doesn't explicitly distinguish it from sibling tools like 'search_memories' or 'get_memory' which might also retrieve memories.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear context for when to use this tool: 'Use this for questions where stored memories might provide context.' However, it doesn't explicitly state when NOT to use it or name alternatives among the sibling tools (e.g., when to use 'search_memories' vs. this tool).

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Blvckjs96/MemoVault'

If you have feedback or need assistance with the MCP directory API, please join our Discord server