Skip to content

Commit e1a6208

Browse files
authored
feat: Add MemMachine Integration Guide for crewai. (MemMachine#875)
1 parent cb76064 commit e1a6208

File tree

6 files changed

+1036
-14
lines changed

6 files changed

+1036
-14
lines changed

integrations/crewai/README.md

Lines changed: 240 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,240 @@
1+
# CrewAI Integration with MemMachine
2+
3+
This directory contains tools for integrating MemMachine with CrewAI agents.
4+
5+
## Overview
6+
7+
MemMachine provides memory tools that can be integrated into CrewAI agents to enable persistent memory capabilities. This allows agents to remember past interactions, user preferences, and context across multiple sessions.
8+
9+
## Installation
10+
11+
```bash
12+
# Install CrewAI and crewai-tools
13+
pip install crewai crewai-tools
14+
15+
# Install MemMachine client
16+
pip install memmachine-client
17+
```
18+
19+
## Configuration
20+
21+
The integration can be configured via environment variables:
22+
23+
| Variable | Description | Default |
24+
|----------|-------------|---------|
25+
| `MEMORY_BACKEND_URL` | URL of the MemMachine backend service | `http://localhost:8080` |
26+
| `CREWAI_ORG_ID` | Organization identifier | `crewai_org` |
27+
| `CREWAI_PROJECT_ID` | Project identifier | `crewai_project` |
28+
| `CREWAI_GROUP_ID` | Group identifier (optional) | `None` |
29+
| `CREWAI_AGENT_ID` | Agent identifier (optional) | `None` |
30+
| `CREWAI_USER_ID` | User identifier (optional) | `None` |
31+
| `CREWAI_SESSION_ID` | Session identifier (optional) | `None` |
32+
33+
## Quick Start
34+
35+
### 1. Basic Usage
36+
37+
```python
38+
from crewai import Agent, Crew, Task
39+
from integrations.crewai.tool import create_memmachine_tools
40+
41+
# Create MemMachine tools
42+
memmachine_tools = create_memmachine_tools(
43+
base_url="http://localhost:8080",
44+
org_id="my_org",
45+
project_id="my_project",
46+
user_id="user123",
47+
)
48+
49+
# Create an agent with memory tools
50+
researcher = Agent(
51+
role="Researcher",
52+
goal="Research topics and remember important information",
53+
backstory="You are a helpful research assistant with memory capabilities.",
54+
tools=memmachine_tools,
55+
verbose=True,
56+
)
57+
58+
# Create a task
59+
task = Task(
60+
description="Research AI trends and remember key findings",
61+
agent=researcher,
62+
)
63+
64+
# Create and run the crew
65+
crew = Crew(
66+
agents=[researcher],
67+
tasks=[task],
68+
)
69+
70+
result = crew.kickoff(inputs={"topic": "Latest AI trends"})
71+
```
72+
73+
### 2. Advanced Usage with Multiple Agents
74+
75+
```python
76+
from crewai import Agent, Crew, Task
77+
from integrations.crewai.tool import create_memmachine_tools
78+
79+
# Create shared memory tools
80+
memmachine_tools = create_memmachine_tools(
81+
base_url="http://localhost:8080",
82+
org_id="my_org",
83+
project_id="my_project",
84+
group_id="research_team",
85+
)
86+
87+
# Create multiple agents with memory
88+
researcher = Agent(
89+
role="Researcher",
90+
goal="Research and store findings in memory",
91+
backstory="You research topics and remember important information.",
92+
tools=memmachine_tools,
93+
verbose=True,
94+
)
95+
96+
writer = Agent(
97+
role="Writer",
98+
goal="Write content based on research and recall past work",
99+
backstory="You write articles and can recall previous research.",
100+
tools=memmachine_tools,
101+
verbose=True,
102+
)
103+
104+
# Create tasks
105+
research_task = Task(
106+
description="Research AI trends and store findings in memory",
107+
agent=researcher,
108+
)
109+
110+
writing_task = Task(
111+
description="Search memory for previous research and write an article",
112+
agent=writer,
113+
)
114+
115+
# Create and run the crew
116+
crew = Crew(
117+
agents=[researcher, writer],
118+
tasks=[research_task, writing_task],
119+
)
120+
121+
result = crew.kickoff(inputs={"topic": "AI in healthcare"})
122+
```
123+
124+
### 3. Using MemMachineTools Directly
125+
126+
```python
127+
from integrations.crewai.tool import MemMachineTools
128+
129+
# Initialize tools
130+
tools = MemMachineTools(
131+
base_url="http://localhost:8080",
132+
org_id="my_org",
133+
project_id="my_project",
134+
user_id="user123",
135+
)
136+
137+
# Add memory
138+
from memmachine.common.api import EpisodeType
139+
140+
result = tools.add_memory(
141+
content="User prefers Python over JavaScript",
142+
role="user",
143+
episode_type=EpisodeType.MESSAGE, # Optional: defaults to EpisodeType.MESSAGE
144+
)
145+
print(result)
146+
147+
# Search memory
148+
results = tools.search_memory(
149+
query="What programming languages does the user prefer?",
150+
limit=5,
151+
)
152+
print(results["summary"])
153+
```
154+
155+
## Tool Descriptions
156+
157+
### Add Memory Tool
158+
159+
Stores important information, facts, preferences, or conversation context in MemMachine memory. Use this automatically whenever the user shares new information that should be remembered.
160+
161+
**Parameters:**
162+
- `content`: The content to store in memory (required)
163+
- `role`: Message role - "user", "assistant", or "system" (default: "user")
164+
165+
### Search Memory Tool
166+
167+
Retrieves relevant context, past conversations, or user preferences from MemMachine memory. Use this when you need to recall information from previous interactions.
168+
169+
**Parameters:**
170+
- `query`: Search query string describing what you're looking for (required)
171+
- `limit`: Maximum number of results to return (default: 5)
172+
173+
## Example: Research Agent with Memory
174+
175+
```python
176+
from crewai import Agent, Crew, Task
177+
from integrations.crewai.tool import create_memmachine_tools
178+
import os
179+
180+
# Get configuration from environment
181+
base_url = os.getenv("MEMORY_BACKEND_URL", "http://localhost:8080")
182+
org_id = os.getenv("CREWAI_ORG_ID", "research_org")
183+
project_id = os.getenv("CREWAI_PROJECT_ID", "research_project")
184+
185+
# Create memory tools
186+
memmachine_tools = create_memmachine_tools(
187+
base_url=base_url,
188+
org_id=org_id,
189+
project_id=project_id,
190+
user_id="researcher_001",
191+
)
192+
193+
# Create agent with memory
194+
researcher = Agent(
195+
role="Research Assistant",
196+
goal="Research topics thoroughly and remember key findings",
197+
backstory="""You are an expert researcher with excellent memory.
198+
You always store important findings in memory so you can recall them later.
199+
When researching, you search memory first to see if you've researched this topic before.""",
200+
tools=memmachine_tools,
201+
verbose=True,
202+
allow_delegation=False,
203+
)
204+
205+
# Create task
206+
task = Task(
207+
description="""Research the topic: {topic}
208+
209+
1. First, search memory to see if you've researched this topic before
210+
2. Research the topic thoroughly
211+
3. Store key findings in memory for future reference
212+
4. Provide a comprehensive summary""",
213+
agent=researcher,
214+
)
215+
216+
# Create and run crew
217+
crew = Crew(
218+
agents=[researcher],
219+
tasks=[task],
220+
)
221+
222+
result = crew.kickoff(inputs={"topic": "Quantum Computing"})
223+
print(result)
224+
```
225+
226+
## Requirements
227+
228+
- MemMachine server running (default: http://localhost:8080)
229+
- Python 3.10+
230+
- CrewAI
231+
- crewai-tools
232+
233+
## Notes
234+
235+
- Memory tools are shared across all agents in a crew by default
236+
- Each agent can have its own `agent_id` in metadata for tracking
237+
- Use `user_id` to scope memories to specific users
238+
- Use `session_id` to scope memories to specific sessions
239+
- Memories persist across crew runs, enabling long-term context
240+

integrations/crewai/__init__.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
"""CrewAI integration for MemMachine memory operations."""
2+
3+
from .tool import MemMachineTools, create_memmachine_tools
4+
5+
__all__ = ["MemMachineTools", "create_memmachine_tools"]

integrations/crewai/example.py

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
#!/usr/bin/env python3
2+
# ruff: noqa: T201
3+
"""
4+
Example CrewAI integration with MemMachine.
5+
6+
This example demonstrates how to use MemMachine memory tools with CrewAI agents.
7+
"""
8+
9+
import os
10+
11+
from crewai import Agent, Crew, Task
12+
from integrations.crewai.tool import create_memmachine_tools
13+
14+
# Configuration
15+
MEMORY_BACKEND_URL = os.getenv("MEMORY_BACKEND_URL", "http://localhost:8080")
16+
ORG_ID = os.getenv("CREWAI_ORG_ID", "example_org")
17+
PROJECT_ID = os.getenv("CREWAI_PROJECT_ID", "example_project")
18+
USER_ID = os.getenv("CREWAI_USER_ID", "user_001")
19+
20+
# Qwen LLM Configuration
21+
QWEN_API_KEY = os.getenv("QWEN_API_KEY", "sk-xxxxxxxxx")
22+
QWEN_BASE_URL = os.getenv(
23+
"QWEN_BASE_URL", "https://dashscope.aliyuncs.com/compatible-mode/v1"
24+
)
25+
QWEN_MODEL = os.getenv("QWEN_MODEL", "qwen-turbo")
26+
27+
# Set environment variables for CrewAI to use Qwen
28+
# CrewAI uses OPENAI_API_KEY, OPENAI_BASE_URL, and OPENAI_MODEL_NAME or OPENAI_MODEL
29+
os.environ["OPENAI_API_KEY"] = QWEN_API_KEY
30+
os.environ["OPENAI_BASE_URL"] = QWEN_BASE_URL
31+
# Try both possible environment variable names
32+
os.environ["OPENAI_MODEL_NAME"] = QWEN_MODEL
33+
os.environ["OPENAI_MODEL"] = QWEN_MODEL
34+
35+
36+
def main() -> None:
37+
"""Run a simple CrewAI example with MemMachine memory."""
38+
print("=" * 60)
39+
print("CrewAI + MemMachine Integration Example")
40+
print("=" * 60)
41+
print()
42+
43+
# Create MemMachine tools
44+
print("Creating MemMachine tools...")
45+
memmachine_tools = create_memmachine_tools(
46+
base_url=MEMORY_BACKEND_URL,
47+
org_id=ORG_ID,
48+
project_id=PROJECT_ID,
49+
user_id=USER_ID,
50+
)
51+
print(f"✓ Created {len(memmachine_tools)} tools")
52+
print()
53+
54+
# Create an agent with memory capabilities
55+
print("Creating research agent...")
56+
researcher = Agent(
57+
role="Research Assistant",
58+
goal="Research topics thoroughly and remember key findings for future reference",
59+
backstory="""You are an expert researcher with excellent memory capabilities.
60+
You always search memory first to see if you've researched a topic before.
61+
When you find new information, you store it in memory so you can recall it later.
62+
You provide comprehensive, well-researched summaries.""",
63+
tools=memmachine_tools,
64+
verbose=True,
65+
allow_delegation=False,
66+
)
67+
print("✓ Agent created")
68+
print()
69+
70+
# Create a task
71+
print("Creating research task...")
72+
task = Task(
73+
description="""Research the topic: {topic}
74+
75+
Steps:
76+
1. First, search your memory to see if you've researched this topic before
77+
2. If you find previous research, build upon it
78+
3. Research the topic thoroughly using your available tools
79+
4. Store key findings and important information in memory
80+
5. Provide a comprehensive summary of your research
81+
82+
Remember to use the search_memory tool first, then add_memory tool to store findings.""",
83+
agent=researcher,
84+
expected_output="A comprehensive research summary with key findings stored in memory",
85+
)
86+
print("✓ Task created")
87+
print()
88+
89+
# Create and run the crew
90+
print("Creating crew...")
91+
crew = Crew(
92+
agents=[researcher],
93+
tasks=[task],
94+
verbose=True,
95+
)
96+
print("✓ Crew created")
97+
print()
98+
99+
# Run the crew
100+
print("Running crew...")
101+
print("-" * 60)
102+
result = crew.kickoff(inputs={"topic": "Artificial Intelligence in Healthcare"})
103+
print("-" * 60)
104+
print()
105+
106+
print("=" * 60)
107+
print("Result:")
108+
print("=" * 60)
109+
print(result)
110+
print()
111+
112+
# Demonstrate memory recall
113+
print("=" * 60)
114+
print("Testing Memory Recall")
115+
print("=" * 60)
116+
print()
117+
118+
# Run again with a related topic to demonstrate memory
119+
print("Running crew again with related topic to demonstrate memory...")
120+
print("-" * 60)
121+
result2 = crew.kickoff(inputs={"topic": "AI applications in medical diagnosis"})
122+
print("-" * 60)
123+
print()
124+
125+
print("=" * 60)
126+
print("Second Result (should reference previous research):")
127+
print("=" * 60)
128+
print(result2)
129+
130+
131+
if __name__ == "__main__":
132+
main()

0 commit comments

Comments
 (0)