MemgraphAI

Integrations

Use Memgraph with popular AI frameworks. All integrations use the REST API under the hood, so they work with both hosted and self-hosted deployments.

LangChain

Use Memgraph as a memory backend and retriever in LangChain chains and agents.

python
from memgraph_sdk import MemgraphClient
from langchain.memory import ConversationBufferMemory
from langchain.schema import BaseMemory

class MemgraphMemory(BaseMemory):
    """LangChain memory backed by Memgraph."""

    client: MemgraphClient
    user_id: str
    memory_key: str = "history"

    @property
    def memory_variables(self):
        return [self.memory_key]

    def load_memory_variables(self, inputs):
        query = inputs.get("input", "recent context")
        result = self.client.search(query=query, user_id=self.user_id)
        lines = [r["content"] for r in result.get("results", [])]
        return {self.memory_key: "\n".join(lines)}

    def save_context(self, inputs, outputs):
        if "input" in inputs:
            self.client.add(text=inputs["input"], user_id=self.user_id)
        if "output" in outputs:
            self.client.add(text=outputs["output"], user_id=self.user_id)

    def clear(self):
        pass  # Memgraph memories are persistent

# Usage
client = MemgraphClient(api_key="mg_...", tenant_id="...")
memory = MemgraphMemory(client=client, user_id="alice")

from langchain.chains import ConversationChain
from langchain_openai import ChatOpenAI

chain = ConversationChain(
    llm=ChatOpenAI(model="gpt-4"),
    memory=memory,
)

LangChain Retriever

python
from langchain.schema import BaseRetriever, Document

class MemgraphRetriever(BaseRetriever):
    """Retrieve memories as LangChain documents."""

    client: MemgraphClient
    user_id: str

    def _get_relevant_documents(self, query: str):
        result = self.client.search(query=query, user_id=self.user_id)
        docs = []
        for r in result.get("results", []):
            docs.append(Document(
                page_content=r["content"],
                metadata={"score": r.get("score", 0), **r.get("metadata", {})},
            ))
        return docs

# Use in a RetrievalQA chain
retriever = MemgraphRetriever(client=client, user_id="alice")
from langchain.chains import RetrievalQA
qa = RetrievalQA.from_chain_type(llm=ChatOpenAI(), retriever=retriever)

CrewAI

Give CrewAI agents the ability to remember and recall information across tasks.

python
from crewai.tools import BaseTool
from memgraph_sdk import MemgraphClient

client = MemgraphClient(api_key="mg_...", tenant_id="...")

class MemgraphSearchTool(BaseTool):
    name: str = "search_memory"
    description: str = "Search the user's memory for relevant context and past interactions."

    def _run(self, query: str) -> str:
        result = client.search(query=query, user_id="crew_user")
        lines = [r["content"] for r in result.get("results", [])]
        return "\n".join(lines) if lines else "No memories found."

class MemgraphRememberTool(BaseTool):
    name: str = "remember"
    description: str = "Store an important fact or preference in the user's memory."

    def _run(self, text: str) -> str:
        client.remember(text=text, user_id="crew_user", category="general")
        return f"Remembered: {text}"

# Use in a CrewAI agent
from crewai import Agent

agent = Agent(
    role="Personal Assistant",
    goal="Help the user with tasks while remembering their preferences",
    tools=[MemgraphSearchTool(), MemgraphRememberTool()],
)

LlamaIndex

Use Memgraph as a retriever or tool in LlamaIndex pipelines.

python
from llama_index.core.retrievers import BaseRetriever
from llama_index.core.schema import NodeWithScore, TextNode, QueryBundle
from memgraph_sdk import MemgraphClient

class MemgraphRetriever(BaseRetriever):
    """LlamaIndex retriever backed by Memgraph memory."""

    def __init__(self, client: MemgraphClient, user_id: str):
        super().__init__()
        self.client = client
        self.user_id = user_id

    def _retrieve(self, query_bundle: QueryBundle):
        result = self.client.search(
            query=query_bundle.query_str,
            user_id=self.user_id,
        )
        nodes = []
        for r in result.get("results", []):
            node = TextNode(text=r["content"])
            score = r.get("score", 0.5)
            nodes.append(NodeWithScore(node=node, score=score))
        return nodes

# Use in a query engine
retriever = MemgraphRetriever(client=client, user_id="alice")
from llama_index.core.query_engine import RetrieverQueryEngine
engine = RetrieverQueryEngine(retriever=retriever)

OpenAI Agents SDK

First-class integration with the openai-agents SDK. Auto-inject memory context and capture decisions with lifecycle hooks.

Quick Start: Memory-Powered Agent

python
from memgraph_sdk import MemgraphClient
from memgraph_sdk.openai_agents import create_memgraph_agent
from agents import Runner

client = MemgraphClient(api_key="mg_your_key")

# Creates an agent with:
# - Dynamic system prompt enriched with user memories
# - Optional search_memory + store_memory tools
agent = create_memgraph_agent(
    client=client,
    user_id="alice",
    name="Support Agent",
    instructions="You are a helpful support agent.",
    agent_id="support-bot",
    include_memory_tools=True,
    token_budget=4000,
)

result = await Runner.run(agent, "How should I deploy to production?")
print(result.final_output)

Decision Capture with Hooks

Capture every agent decision automatically with lifecycle hooks:

python
from memgraph_sdk.openai_agents import MemgraphAgentHooks, MemgraphRunHooks
from agents import Agent, Runner

# Per-agent hooks — capture tool calls and reasoning
agent = Agent(
    name="Research Agent",
    instructions="You research topics thoroughly.",
    hooks=MemgraphAgentHooks(
        client=client,
        user_id="alice",
        agent_id="research-bot",
        auto_learn=True,  # extract learnings from exchanges
    ),
)

# Multi-agent orchestration hooks
run_hooks = MemgraphRunHooks(
    client=client,
    user_id="alice",
    agent_id="orchestrator",
)

result = await Runner.run(agent, "Research deployment options", run_hooks=run_hooks)

# Record the full run as a decision
run_hooks.finalize(output=result.final_output, outcome="SUCCESS")

Dynamic Memory Instructions

python
from memgraph_sdk.openai_agents import memgraph_instructions, memgraph_tools

# Dynamic instructions — refreshes memory on each run
agent = Agent(
    name="Assistant",
    instructions=memgraph_instructions(
        client, user_id="alice",
        base="You are a helpful assistant.",
        token_budget=4000,
    ),
    tools=memgraph_tools(client, user_id="alice"),
)

OpenAI Function Calling (Direct)

If you're using the OpenAI API directly without the Agents SDK:

python
import json
import openai
from memgraph_sdk import MemgraphClient

client = MemgraphClient(api_key="mg_your_key")

tools = [
    {
        "type": "function",
        "function": {
            "name": "search_memory",
            "description": "Search the user's memory for relevant information",
            "parameters": {
                "type": "object",
                "properties": {
                    "query": {"type": "string", "description": "What to search for"},
                },
                "required": ["query"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "remember",
            "description": "Store a fact or preference in the user's memory",
            "parameters": {
                "type": "object",
                "properties": {
                    "text": {"type": "string", "description": "The fact to remember"},
                    "category": {"type": "string", "enum": ["preference", "fact", "decision"]},
                },
                "required": ["text"],
            },
        },
    },
]

def handle_tool_call(name, args):
    if name == "search_memory":
        result = client.search(query=args["query"], user_id="alice")
        lines = [r["content"] for r in result.get("results", [])]
        return "\n".join(lines) if lines else "No memories found."
    elif name == "remember":
        client.remember(text=args["text"], user_id="alice", category=args.get("category", "general"))
        return f"Remembered: {args['text']}"

response = openai.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "What do I prefer for deployment?"}],
    tools=tools,
)

if response.choices[0].message.tool_calls:
    for tc in response.choices[0].message.tool_calls:
        result = handle_tool_call(tc.function.name, json.loads(tc.function.arguments))
        print(result)

Generic REST API

Use Memgraph from any language or framework via the REST API.

bash
# Store a memory (belief)
curl -X POST https://api.memgraph.ai/v1/beliefs \
  -H "X-API-KEY: mg_your_key" \
  -H "Content-Type: application/json" \
  -d '{
    "tenant_id": "your-tenant-uuid",
    "subject_id": "alice",
    "key": "preferred_language",
    "value": "Python 3.12",
    "confidence": 0.95,
    "belief_type": "preference",
    "domain": "settings"
  }'

# Search memories
curl -X POST https://api.memgraph.ai/v2/context \
  -H "X-API-KEY: mg_your_key" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "What language does Alice prefer?",
    "user_id": "alice"
  }'

# List beliefs
curl "https://api.memgraph.ai/v1/beliefs?subject_id=alice&limit=20" \
  -H "X-API-KEY: mg_your_key"

Missing your framework? Memgraph works with any framework that can make HTTP requests. See the API Reference for the full endpoint list.