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

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()

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