zzstoatzz commited on
Commit
fbc87be
·
1 Parent(s): 0882194

merge conflict

Browse files

fix

merge conflict

multi

Files changed (3) hide show
  1. .gitignore +1 -1
  2. examples/memory.py +306 -84
  3. uv.lock +1 -1
.gitignore CHANGED
@@ -16,4 +16,4 @@ src/fastmcp/_version.py
16
 
17
  # editors
18
  .cursorrules
19
- .vscode/
 
16
 
17
  # editors
18
  .cursorrules
19
+ .vscode/
examples/memory.py CHANGED
@@ -1,122 +1,344 @@
 
 
 
 
1
  """
2
- filesystem mcp server with basic memory capabilities.
3
- keeps a user profile that can be updated and summarized by an llm.
4
  """
5
 
 
 
6
  import os
7
- from datetime import UTC, datetime
 
8
  from pathlib import Path
9
- from typing import Annotated
10
 
 
 
 
 
11
  from pydantic import BaseModel, Field
12
  from pydantic_ai import Agent
13
 
14
  from fastmcp import FastMCP
15
 
16
- MAX_MEMORIES = 3
 
 
 
17
 
 
 
18
 
19
- class Memory(BaseModel):
20
- """a single memory/observation about the user"""
 
 
 
 
 
 
 
21
 
22
- content: str
23
- timestamp: float
24
- importance: Annotated[int, Field(ge=1, le=5)] = Field(default=3)
 
 
 
25
 
26
 
27
- class Profile(BaseModel):
28
- """user profile built from memories"""
 
 
 
 
29
 
30
- memories: list[Memory] = Field(default_factory=list, max_length=MAX_MEMORIES)
31
- summary: str = Field(default="")
32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
- class MemoryUpdate(BaseModel):
35
- """llm analysis of how to update the profile"""
36
 
37
- keep_indices: list[int] = Field(description="indices of memories to keep")
38
- new_memory: Memory = Field(description="processed version of the new memory")
39
- updated_summary: str = Field(description="brief summary of all memories")
 
40
 
41
 
42
- memory_agent = Agent(
43
- "openai:gpt-4o",
44
- result_type=MemoryUpdate,
45
- system_prompt="""
46
- you help maintain a concise user memory profile. when given a new memory:
47
- 1. analyze its importance relative to existing memories
48
- 2. if we're at max capacity of memories, decide which to keep
49
- 3. provide a brief summary of all memories
50
- focus on keeping the most important and relevant information.
51
- """,
52
- )
53
 
54
- mcp = FastMCP("memory", dependencies=["pydantic-ai-slim[openai]"])
 
55
 
56
- PROFILE_DIR = (
57
- Path.home() / ".fastmcp" / os.environ.get("USER", "anon") / "memory"
58
- ).resolve()
59
- PROFILE_DIR.mkdir(parents=True, exist_ok=True)
60
 
 
 
 
 
 
 
 
 
 
 
61
 
62
- @mcp.tool()
63
- async def remember(
64
- content: Annotated[str, Field(description="new observation/memory to store")],
65
- importance: Annotated[int, Field(ge=1, le=5, description="importance (1-5)")],
66
- ) -> str:
67
- """store a new memory/observation about the user"""
68
- profile_path = PROFILE_DIR / "profile.json"
69
-
70
- if profile_path.exists():
71
- profile = Profile.model_validate_json(profile_path.read_text())
72
- else:
73
- profile = Profile()
74
-
75
- new_memory = Memory(
76
- content=content,
77
- timestamp=datetime.now(UTC).timestamp(),
78
- importance=importance,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  )
 
 
 
 
 
 
 
 
 
 
 
80
 
81
- if len(profile.memories) >= MAX_MEMORIES:
82
- result = await memory_agent.run(
83
- f"""
84
- new memory: {content} (importance: {importance})
85
-
86
- current memories:
87
- {[f"{i}: {m.content} (importance: {m.importance})"
88
- for i, m in enumerate(profile.memories)]}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  """
 
 
 
 
 
 
 
 
 
 
 
90
  )
 
 
 
91
 
92
- profile.memories = [profile.memories[i] for i in result.data.keep_indices]
93
- profile.memories.append(result.data.new_memory)
94
- profile.summary = result.data.updated_summary
95
- else:
96
- profile.memories.append(new_memory)
97
 
98
- profile_path.write_text(profile.model_dump_json(indent=2))
99
- return f"remembered: {content}"
 
 
 
 
 
 
 
 
 
 
 
100
 
101
 
102
  @mcp.tool()
103
  async def read_profile() -> str:
104
- """read and display the current memory profile"""
105
- profile_path = PROFILE_DIR / "profile.json"
106
- if not profile_path.exists():
107
- return "no profile found"
108
-
109
- profile = Profile.model_validate_json(profile_path.read_text())
110
-
111
- output = ["current memories:"]
112
- for i, memory in enumerate(profile.memories):
113
- output.append(
114
- f"{i}. {memory.content} "
115
- f"(importance: {memory.importance}, "
116
- f"timestamp: {datetime.fromtimestamp(memory.timestamp, UTC)})"
117
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
 
119
- if profile.summary:
120
- output.append(f"\nsummary: {profile.summary}")
121
 
122
- return "\n".join(output)
 
 
1
+ # /// script
2
+ # dependencies = ["pydantic-ai-slim[openai]", "asyncpg", "numpy", "pgvector", "fastmcp"]
3
+ # ///
4
+
5
  """
6
+ Recursive memory system inspired by the human brain's clustering of memories.
7
+ Uses OpenAI's 'text-embedding-3-small' model and pgvector for efficient similarity search.
8
  """
9
 
10
+ import asyncio
11
+ import math
12
  import os
13
+ from dataclasses import dataclass
14
+ from datetime import datetime, timezone
15
  from pathlib import Path
16
+ from typing import Annotated, Self
17
 
18
+ import asyncpg
19
+ import numpy as np
20
+ from openai import AsyncOpenAI
21
+ from pgvector.asyncpg import register_vector # Import register_vector
22
  from pydantic import BaseModel, Field
23
  from pydantic_ai import Agent
24
 
25
  from fastmcp import FastMCP
26
 
27
+ MAX_DEPTH = 5
28
+ SIMILARITY_THRESHOLD = 0.7
29
+ DECAY_FACTOR = 0.99
30
+ REINFORCEMENT_FACTOR = 1.1
31
 
32
+ DEFAULT_LLM_MODEL = "openai:gpt-4o"
33
+ DEFAULT_EMBEDDING_MODEL = "text-embedding-3-small"
34
 
35
+ mcp = FastMCP(
36
+ "memory",
37
+ dependencies=[
38
+ "pydantic-ai-slim[openai]",
39
+ "asyncpg",
40
+ "numpy",
41
+ "pgvector",
42
+ ],
43
+ )
44
 
45
+ DB_DSN = "postgresql://postgres:postgres@localhost:54320/memory_db"
46
+ # reset memory with rm ~/.fastmcp/{USER}/memory/*
47
+ PROFILE_DIR = (
48
+ Path.home() / ".fastmcp" / os.environ.get("USER", "anon") / "memory"
49
+ ).resolve()
50
+ PROFILE_DIR.mkdir(parents=True, exist_ok=True)
51
 
52
 
53
+ def cosine_similarity(a: list[float], b: list[float]) -> float:
54
+ a_array = np.array(a, dtype=np.float64)
55
+ b_array = np.array(b, dtype=np.float64)
56
+ return np.dot(a_array, b_array) / (
57
+ np.linalg.norm(a_array) * np.linalg.norm(b_array)
58
+ )
59
 
 
 
60
 
61
+ async def do_ai[T](
62
+ user_prompt: str,
63
+ system_prompt: str,
64
+ result_type: type[T] | Annotated,
65
+ deps=None,
66
+ ) -> T:
67
+ agent = Agent(
68
+ DEFAULT_LLM_MODEL,
69
+ system_prompt=system_prompt,
70
+ result_type=result_type,
71
+ )
72
+ result = await agent.run(user_prompt, deps=deps)
73
+ return result.data
74
 
 
 
75
 
76
+ @dataclass
77
+ class Deps:
78
+ openai: AsyncOpenAI
79
+ pool: asyncpg.Pool
80
 
81
 
82
+ async def get_db_pool() -> asyncpg.Pool:
83
+ async def init(conn):
84
+ await conn.execute("CREATE EXTENSION IF NOT EXISTS vector;")
85
+ await register_vector(conn)
 
 
 
 
 
 
 
86
 
87
+ pool = await asyncpg.create_pool(DB_DSN, init=init)
88
+ return pool
89
 
 
 
 
 
90
 
91
+ class MemoryNode(BaseModel):
92
+ id: int | None = None
93
+ content: str
94
+ summary: str = ""
95
+ importance: float = 1.0
96
+ access_count: int = 0
97
+ timestamp: float = Field(
98
+ default_factory=lambda: datetime.now(timezone.utc).timestamp()
99
+ )
100
+ embedding: list[float]
101
 
102
+ @classmethod
103
+ async def from_content(cls, content: str, deps: Deps):
104
+ embedding = await get_embedding(content, deps)
105
+ return cls(content=content, embedding=embedding)
106
+
107
+ async def save(self, deps: Deps):
108
+ async with deps.pool.acquire() as conn:
109
+ if self.id is None:
110
+ result = await conn.fetchrow(
111
+ """
112
+ INSERT INTO memories (content, summary, importance, access_count, timestamp, embedding)
113
+ VALUES ($1, $2, $3, $4, $5, $6)
114
+ RETURNING id
115
+ """,
116
+ self.content,
117
+ self.summary,
118
+ self.importance,
119
+ self.access_count,
120
+ self.timestamp,
121
+ self.embedding,
122
+ )
123
+ self.id = result["id"]
124
+ else:
125
+ await conn.execute(
126
+ """
127
+ UPDATE memories
128
+ SET content = $1, summary = $2, importance = $3,
129
+ access_count = $4, timestamp = $5, embedding = $6
130
+ WHERE id = $7
131
+ """,
132
+ self.content,
133
+ self.summary,
134
+ self.importance,
135
+ self.access_count,
136
+ self.timestamp,
137
+ self.embedding,
138
+ self.id,
139
+ )
140
+
141
+ async def merge_with(self, other: Self, deps: Deps):
142
+ self.content = await do_ai(
143
+ f"{self.content}\n\n{other.content}",
144
+ "Combine the following two texts into a single, coherent text.",
145
+ str,
146
+ deps,
147
+ )
148
+ self.importance += other.importance
149
+ self.access_count += other.access_count
150
+ self.embedding = [(a + b) / 2 for a, b in zip(self.embedding, other.embedding)]
151
+ self.summary = await do_ai(
152
+ self.content, "Summarize the following text concisely.", str, deps
153
+ )
154
+ await self.save(deps)
155
+ # Delete the merged node from the database
156
+ if other.id is not None:
157
+ await delete_memory(other.id, deps)
158
+
159
+ def get_effective_importance(self):
160
+ return self.importance * (1 + math.log(self.access_count + 1))
161
+
162
+
163
+ async def get_embedding(text: str, deps: Deps) -> list[float]:
164
+ embedding_response = await deps.openai.embeddings.create(
165
+ input=text,
166
+ model=DEFAULT_EMBEDDING_MODEL,
167
  )
168
+ return embedding_response.data[0].embedding
169
+
170
+
171
+ async def delete_memory(memory_id: int, deps: Deps):
172
+ async with deps.pool.acquire() as conn:
173
+ await conn.execute("DELETE FROM memories WHERE id = $1", memory_id)
174
+
175
+
176
+ async def add_memory(content: str, deps: Deps):
177
+ new_memory = await MemoryNode.from_content(content, deps)
178
+ await new_memory.save(deps)
179
 
180
+ similar_memories = await find_similar_memories(new_memory.embedding, deps)
181
+ for memory in similar_memories:
182
+ if memory.id != new_memory.id:
183
+ await new_memory.merge_with(memory, deps)
184
+
185
+ await update_importance(new_memory.embedding, deps)
186
+
187
+ await prune_memories(deps)
188
+
189
+ return f"Remembered: {content}"
190
+
191
+
192
+ async def find_similar_memories(embedding: list[float], deps: Deps) -> list[MemoryNode]:
193
+ async with deps.pool.acquire() as conn:
194
+ rows = await conn.fetch(
195
+ """
196
+ SELECT id, content, summary, importance, access_count, timestamp, embedding
197
+ FROM memories
198
+ ORDER BY embedding <-> $1
199
+ LIMIT 5
200
+ """,
201
+ embedding,
202
+ )
203
+ memories = [
204
+ MemoryNode(
205
+ id=row["id"],
206
+ content=row["content"],
207
+ summary=row["summary"],
208
+ importance=row["importance"],
209
+ access_count=row["access_count"],
210
+ timestamp=row["timestamp"],
211
+ embedding=row["embedding"],
212
+ )
213
+ for row in rows
214
+ ]
215
+ return memories
216
+
217
+
218
+ async def update_importance(user_embedding: list[float], deps: Deps):
219
+ async with deps.pool.acquire() as conn:
220
+ rows = await conn.fetch(
221
+ "SELECT id, importance, access_count, embedding FROM memories"
222
+ )
223
+ for row in rows:
224
+ memory_embedding = row["embedding"]
225
+ similarity = cosine_similarity(user_embedding, memory_embedding)
226
+ if similarity > SIMILARITY_THRESHOLD:
227
+ new_importance = row["importance"] * REINFORCEMENT_FACTOR
228
+ new_access_count = row["access_count"] + 1
229
+ else:
230
+ new_importance = row["importance"] * DECAY_FACTOR
231
+ new_access_count = row["access_count"]
232
+ await conn.execute(
233
+ """
234
+ UPDATE memories
235
+ SET importance = $1, access_count = $2
236
+ WHERE id = $3
237
+ """,
238
+ new_importance,
239
+ new_access_count,
240
+ row["id"],
241
+ )
242
+
243
+
244
+ async def prune_memories(deps: Deps):
245
+ async with deps.pool.acquire() as conn:
246
+ rows = await conn.fetch(
247
+ """
248
+ SELECT id, importance, access_count
249
+ FROM memories
250
+ ORDER BY importance DESC
251
+ OFFSET $1
252
+ """,
253
+ MAX_DEPTH,
254
+ )
255
+ for row in rows:
256
+ await conn.execute("DELETE FROM memories WHERE id = $1", row["id"])
257
+
258
+
259
+ async def display_memory_tree(deps: Deps) -> str:
260
+ async with deps.pool.acquire() as conn:
261
+ rows = await conn.fetch(
262
  """
263
+ SELECT content, summary, importance, access_count
264
+ FROM memories
265
+ ORDER BY importance DESC
266
+ LIMIT $1
267
+ """,
268
+ MAX_DEPTH,
269
+ )
270
+ result = ""
271
+ for row in rows:
272
+ effective_importance = row["importance"] * (
273
+ 1 + math.log(row["access_count"] + 1)
274
  )
275
+ summary = row["summary"] or row["content"]
276
+ result += f"- {summary} (Importance: {effective_importance:.2f})\n"
277
+ return result
278
 
 
 
 
 
 
279
 
280
+ @mcp.tool()
281
+ async def remember(
282
+ contents: list[str] = Field(
283
+ description="List of observations or memories to store"
284
+ ),
285
+ ):
286
+ deps = Deps(openai=AsyncOpenAI(), pool=await get_db_pool())
287
+ try:
288
+ return "\n".join(
289
+ await asyncio.gather(*[add_memory(content, deps) for content in contents])
290
+ )
291
+ finally:
292
+ await deps.pool.close()
293
 
294
 
295
  @mcp.tool()
296
  async def read_profile() -> str:
297
+ deps = Deps(openai=AsyncOpenAI(), pool=await get_db_pool())
298
+ profile = await display_memory_tree(deps)
299
+ await deps.pool.close()
300
+ return profile
301
+
302
+
303
+ async def initialize_database():
304
+ pool = await asyncpg.create_pool(
305
+ "postgresql://postgres:postgres@localhost:54320/postgres"
306
+ )
307
+ try:
308
+ async with pool.acquire() as conn:
309
+ await conn.execute("""
310
+ SELECT pg_terminate_backend(pg_stat_activity.pid)
311
+ FROM pg_stat_activity
312
+ WHERE pg_stat_activity.datname = 'memory_db'
313
+ AND pid <> pg_backend_pid();
314
+ """)
315
+ await conn.execute("DROP DATABASE IF EXISTS memory_db;")
316
+ await conn.execute("CREATE DATABASE memory_db;")
317
+ finally:
318
+ await pool.close()
319
+
320
+ pool = await asyncpg.create_pool(DB_DSN)
321
+ try:
322
+ async with pool.acquire() as conn:
323
+ await conn.execute("CREATE EXTENSION IF NOT EXISTS vector;")
324
+
325
+ await register_vector(conn)
326
+
327
+ await conn.execute("""
328
+ CREATE TABLE IF NOT EXISTS memories (
329
+ id SERIAL PRIMARY KEY,
330
+ content TEXT NOT NULL,
331
+ summary TEXT,
332
+ importance REAL NOT NULL,
333
+ access_count INT NOT NULL,
334
+ timestamp DOUBLE PRECISION NOT NULL,
335
+ embedding vector(1536) NOT NULL
336
+ );
337
+ CREATE INDEX IF NOT EXISTS idx_memories_embedding ON memories USING hnsw (embedding vector_l2_ops);
338
+ """)
339
+ finally:
340
+ await pool.close()
341
 
 
 
342
 
343
+ if __name__ == "__main__":
344
+ asyncio.run(initialize_database())
uv.lock CHANGED
@@ -228,7 +228,7 @@ wheels = [
228
 
229
  [[package]]
230
  name = "fastmcp"
231
- version = "0.3.6.dev5+g6a13ab9.d20241203"
232
  source = { editable = "." }
233
  dependencies = [
234
  { name = "httpx" },
 
228
 
229
  [[package]]
230
  name = "fastmcp"
231
+ version = "0.3.6.dev8+g3b5ae20"
232
  source = { editable = "." }
233
  dependencies = [
234
  { name = "httpx" },