-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathpymentisdb-python-client.html
More file actions
668 lines (560 loc) · 24.2 KB
/
Copy pathpymentisdb-python-client.html
File metadata and controls
668 lines (560 loc) · 24.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>pymentisdb — Python Client for MentisDB</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, sans-serif;
line-height: 1.7;
color: #1a1a2e;
background: #fafafa;
max-width: 720px;
margin: 0 auto;
padding: 2rem 1.5rem;
}
h1 { font-size: 1.8rem; margin-bottom: 1rem; }
h2 { font-size: 1.4rem; margin-top: 2rem; margin-bottom: 0.75rem; }
h3 { font-size: 1.15rem; margin-top: 1.5rem; margin-bottom: 0.5rem; }
p { margin-bottom: 1rem; }
a { color: #4361ee; }
code { background: #f0f0f0; padding: 0.15em 0.35em; border-radius: 3px; font-size: 0.9em; }
pre { background: #1a1a2e; color: #e0e0e0; padding: 1rem; border-radius: 5px; overflow-x: auto; margin-bottom: 1rem; }
pre code { background: none; padding: 0; color: inherit; }
table { border-collapse: collapse; width: 100%; margin-bottom: 1rem; font-size: 0.9rem; }
th, td { border: 1px solid #ddd; padding: 0.5rem 0.75rem; text-align: left; }
th { background: #f5f5f5; font-weight: 600; }
ul, ol { margin-bottom: 1rem; padding-left: 1.5rem; }
li { margin-bottom: 0.25rem; }
hr { border: none; border-top: 1px solid #e0e0e0; margin: 2rem 0; }
blockquote { border-left: 3px solid #4361ee; padding-left: 1rem; color: #555; margin-bottom: 1rem; }
strong { font-weight: 600; }
.back { margin-bottom: 2rem; font-size: 0.9rem; }
.meta { color: #888; font-size: 0.85rem; margin-bottom: 1.5rem; }
footer { border-top: 1px solid #e0e0e0; padding-top: 1.5rem; color: #888; font-size: 0.85rem; margin-top: 3rem; }
.highlight { background: #eef2ff; border-left: 3px solid #4361ee; padding: 1rem 1.25rem; margin-bottom: 1.5rem; border-radius: 0 4px 4px 0; }
.highlight p:last-child { margin-bottom: 0; }
.tip { background: #f0fff4; border-left: 3px solid #38a169; padding: 1rem 1.25rem; margin-bottom: 1.5rem; border-radius: 0 4px 4px 0; }
.warning { background: #fffaf0; border-left: 3px solid #dd6b20; padding: 1rem 1.25rem; margin-bottom: 1.5rem; border-radius: 0 4px 4px 0; }
.installed { background: #e6fffa; border-left: 3px solid #319795; padding: 1rem 1.25rem; margin-bottom: 1.5rem; border-radius: 0 4px 4px 0; }
</style>
</head>
<body>
<nav style="margin-bottom:0.75rem;font-size:0.85rem;"><a href="https://mentisdb.com">mentisdb.com</a> · <a href="https://docs.mentisdb.com">docs</a> · <a href="https://github.com/CloudLLM-ai/mentisdb">github</a></nav>
<div class="back"><a href="index.html">← Blog</a></div>
<div class="meta">April 14, 2026</div>
<h1>pymentisdb — Python Client for MentisDB</h1>
<p>
mentisdb ships a first-class Python client called <code>pymentisdb</code>. Whether you're
building a LangChain agent, a custom chatbot, or any Python application that needs durable
semantic memory, pymentisdb gives you a clean interface to store and retrieve thoughts
from MentisDB's append-only hash-chained store.
</p>
<h2 id="installation">Installation</h2>
<p>Install from source or via pip:</p>
<pre><code># Core client only (no LangChain dependency)
pip install pymentisdb
# With LangChain integration
pip install pymentisdb[langchain]</code></pre>
<p>Requires Python 3.10+ and a running mentisdb instance. Start one with:</p>
<pre><code>mentisdb</code></pre>
<p>Or for production with TLS:</p>
<pre><code>MENTISDB_DIR=/path/to/data mentisdb --https --port 9473</code></pre>
<h2 id="basic-client">Basic Client Usage</h2>
<p>The <code>MentisDbClient</code> wraps the MentisDB REST API. It handles connection pooling,
authentication headers, and type conversion automatically.</p>
<h3 id="connecting">Connecting</h3>
<pre><code>from pymentisdb import MentisDbClient
# Connect to local mentisdb (default)
client = MentisDbClient()
# Connect to a remote instance
client = MentisDbClient(base_url="https://my.mentisdb.com:9473")</code></pre>
<h3 id="appending-thoughts">Appending Thoughts</h3>
<p>Thoughts are the atomic memory records in MentisDB. Every append is cryptographically
chained to the previous thought — you can't rewrite history, only extend it.</p>
<pre><code>from pymentisdb import ThoughtType, ThoughtRole
# Record an insight
thought = client.append_thought(
thought_type=ThoughtType.INSIGHT,
content="Rate limiting is the real bottleneck for our API.",
agent_name="assistant",
importance=0.8,
tags=["performance", "api"],
)
print(f"Appended: {thought.id}")
# Record a decision
decision = client.append_thought(
thought_type=ThoughtType.DECISION,
content="We will implement a sliding window rate limiter.",
agent_name="assistant",
importance=0.9,
tags=["architecture", "api"],
concepts=["rate-limiting", "sliding-window"],
)
# Record a lesson learned
lesson = client.append_thought(
thought_type=ThoughtType.LESSON_LEARNED,
content="Never deploy on a Friday afternoon.",
agent_name="assistant",
importance=1.0,
confidence=0.95,
)</code></pre>
<h3 id="semantic-search">Semantic Search</h3>
<p>Ranked search combines lexical matching, vector similarity, and graph traversal into a
single scored result set:</p>
<pre><code># Search by text
results = client.ranked_search(
text="rate limiting",
limit=5,
)
print(f"Found {results.total} results")
for hit in results.results:
print(f" [{hit.score.total:.3f}] {hit.thought.content}")
# Filter by importance
results = client.ranked_search(
text="performance",
min_importance=0.7,
)
# Filter by tags and thought type
results = client.ranked_search(
text="api",
thought_types=[ThoughtType.DECISION, ThoughtType.INSIGHT],
tags_any=["architecture", "performance"],
)</code></pre>
<h3 id="context-bundles">Context Bundles — Retrieval with Supporting Memories</h3>
<p>Context bundles go beyond flat search results. They group each top-scoring "seed" match
with the supporting memories reachable through graph relations — giving you not just the
answer but the trail of evidence that led to it:</p>
<pre><code>response = client.context_bundles(
text="why did we choose PostgreSQL",
limit=3,
)
for bundle in response.bundles:
seed = bundle.seed
print(f"Seed: {seed.thought.content} (score: {seed.lexical_score:.3f})")
for support_hit in bundle.support:
print(f" Supporting: {support_hit.thought.content}")
print(f" Depth: {support_hit.depth}, via: {support_hit.relation_kinds}")</code></pre>
<h2 id="langchain">LangChain Integration</h2>
<p>pymentisdb includes a first-class <code>MentisDbMemory</code> class that implements
LangChain's <code>BaseMemory</code> interface. Drop it into any LangChain agent to give
it persistent, retrievable conversation history.</p>
<h3 id="langchain-example">Full LangChain Example</h3>
<pre><code>from pymentisdb import MentisDbClient, MentisDbMemory, ThoughtType, ThoughtRole
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnableWithMessageHistory
from langchain_community.chat_message_histories import ChatMessageHistory
# 1. Set up memory
memory = MentisDbMemory(
base_url="http://127.0.0.1:9472",
chain_key="my-agent", # persists across sessions
agent_name="assistant",
thought_type=ThoughtType.SUMMARY,
role=ThoughtRole.MEMORY,
)
# 2. Build the chain
llm = ChatOpenAI(model="gpt-4o")
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant with persistent memory."),
("placeholder", "{chat_history}"),
("human", "{question}"),
])
chain = prompt | llm
# 3. Add message history (in-memory for demo, use Redis/SQL in prod)
chain_with_history = chain.with_message_history(
ChatMessageHistory(session_id="user-123"),
)
# 4. Run — memory is automatically loaded and saved
response = chain_with_history.invoke(
{"question": "What did I tell you about my project?"},
config={"configurable": {"session_id": "user-123"}},
)
print(response.content)</code></pre>
<h3 id="how-it-works">How MentisDbMemory Works</h3>
<p><code>MentisDbMemory</code> implements four LangChain lifecycle methods:</p>
<ul>
<li><strong><code>load_memory_variables(inputs)</code></strong> — retrieves recent thoughts from MentisDB
via <code>ranked_search()</code> and formats them as a chat history string for the prompt.</li>
<li><strong><code>add_messages(messages)</code></strong> — converts each LangChain message to a
<code>ThoughtType.SUMMARY</code> thought and appends it via <code>append_thought()</code>.</li>
<li><strong><code>get_messages()</code></strong> — retrieves thoughts and reconstructs them as
<code>HumanMessage</code>/<code>AIMessage</code> objects.</li>
<li><strong><code>clear()</code></strong> — a no-op (MentisDB is append-only; use a different
<code>chain_key</code> to isolate sessions).</li>
</ul>
<div class="tip">
<p><strong>Tip:</strong> Use different <code>chain_key</code> values for different users or
conversation threads. MentisDB's cross-chain search lets you query across all of them when needed.</p>
</div>
<h2 id="thought-types">Thought Types Reference</h2>
<p>MentisDB uses typed thoughts instead of generic key-value pairs. This gives retrieval
semantic meaning — a <code>Decision</code> is scored differently from a
<code>Mistake</code>, and you can filter by type:</p>
<table>
<tr><th>ThoughtType</th><th>When to Use</th></tr>
<tr><td><code>INSIGHT</code></td><td>A non-obvious realization or lesson</td></tr>
<tr><td><code>DECISION</code></td><td>A committed choice affecting future behavior</td></tr>
<tr><td><code>PREFERENCE_UPDATE</code></td><td>A stable user preference discovered or changed</td></tr>
<tr><td><code>MISTAKE</code></td><td>A wrong action taken (distinct from Correction)</td></tr>
<tr><td><code>CORRECTION</code></td><td>A prior assumption was wrong — this replaces it</td></tr>
<tr><td><code>LESSON_LEARNED</code></td><td>A rule distilled from failure or expensive fix</td></tr>
<tr><td><code>FINDING</code></td><td>A fact or data point discovered during work</td></tr>
<tr><td><code>QUESTION</code></td><td>An unresolved issue worth preserving</td></tr>
<tr><td><code>SUMMARY</code></td><td>Compressed state (pair with <code>Checkpoint</code> role)</td></tr>
<tr><td><code>LLM_EXTRACTED</code></td><td>Memories auto-extracted from text via the LLM pipeline</td></tr>
</table>
<h2 id="advanced">Advanced: Typed Relations</h2>
<p>Thoughts can link to each other with typed graph relations. This enables multi-hop
reasoning — "show me what led to this decision":</p>
<pre><code>from pymentisdb import ThoughtRelation, ThoughtRelationKind
# Link a correction to the original mistake
client.append_thought(
thought_type=ThoughtType.CORRECTION,
content="The old assumption about retry logic was flawed.",
relations=[
ThoughtRelation(
kind=ThoughtRelationKind.CORRECTS,
target_id=mistake_thought.id,
)
],
)
# Link evidence to a hypothesis
client.append_thought(
thought_type=ThoughtType.FINDING,
content="Cache invalidation is the real issue.",
relations=[
ThoughtRelation(
kind=ThoughtRelationKind.SUPPORTS,
target_id=hypothesis_thought.id,
)
],
)</code></pre>
<h2 id="complete-api">Complete API Reference</h2>
<p>MentisDbClient exposes all MentisDB server operations. Methods currently implemented in the
Python client are marked with <strong>✓</strong>. Methods not yet wrapped (but available via
the REST API directly) are marked with <em>server-only</em> and can be called using
<code>client._post()</code> or <code>client._get()</code> helpers.</p>
<h3 id="imports">Imports</h3>
<pre><code>from pymentisdb import (
MentisDbClient,
ThoughtType,
ThoughtRole,
ThoughtRelation,
ThoughtRelationKind,
MemoryScope,
Thought,
AgentRecord,
RankedSearchHit,
RankedSearchResponse,
ContextBundle,
ContextBundlesResponse,
ChainSummary,
ListChainsResponse,
)</code></pre>
<h3 id="connection-config">Connection Configuration</h3>
<pre><code># Local instance (default)
client = MentisDbClient()
# Remote instance
client = MentisDbClient(base_url="https://my.mentisdb.com:9473")
# Custom timeout (seconds, default 30)
import requests
client = MentisDbClient()
client._session.timeout = 60 # set timeout on underlying requests session
# Add auth headers for remote instances
client._session.headers["Authorization"] = "Bearer YOUR_API_KEY"</code></pre>
<hr>
<h3 id="api-memory">Memory Operations</h3>
<h4>append_thought <strong>✓</strong></h4>
<pre><code>thought = client.append_thought(
thought_type=ThoughtType.INSIGHT,
content="Rate limiting is the real bottleneck.",
chain_key="my-agent", # uses default if omitted
agent_id="agent-001",
agent_name="assistant",
agent_owner="cloudllm",
role=ThoughtRole.MEMORY, # Memory | WorkingMemory | Summary | Checkpoint | Handoff | Audit | Retrospective
importance=0.8, # 0.0–1.0, default 0.5
confidence=0.95, # optional, 0.0–1.0
tags=["performance", "api"],
concepts=["rate-limiting"],
refs=[5, 12], # indices of referenced prior thoughts
relations=[ # typed graph edges
ThoughtRelation(
kind=ThoughtRelationKind.SUPPORTS,
target_id="thought-uuid-abc",
)
],
scope=MemoryScope.USER, # User | Session | Agent
)
print(thought.id, thought.hash)</code></pre>
<h4>ranked_search <strong>✓</strong></h4>
<pre><code>results = client.ranked_search(
text="rate limiting",
chain_key="my-agent",
limit=10,
offset=0,
thought_types=[ThoughtType.DECISION, ThoughtType.INSIGHT],
roles=[ThoughtRole.MEMORY],
tags_any=["performance", "api"],
concepts_any=["rate-limiting"],
agent_ids=["agent-001"],
agent_names=["assistant"],
agent_owners=["cloudllm"],
min_importance=0.5,
min_confidence=0.6,
since=datetime(2026, 1, 1),
until=datetime(2026, 4, 14),
scope="user",
enable_reranking=True,
rerank_k=20,
entity_type="decision",
)
print(results.total)
for hit in results.results:
print(f"[{hit.score.total:.3f}] {hit.thought.content}")
print(f" lexical={hit.score.lexical:.3f} vector={hit.score.vector:.3f} graph={hit.score.graph:.3f}")
print(f" matched_terms={hit.matched_terms}")</code></pre>
<h4>context_bundles <strong>✓</strong></h4>
<pre><code>resp = client.context_bundles(
text="why PostgreSQL",
limit=5,
thought_types=[ThoughtType.DECISION, ThoughtType.FINDING],
)
print(f"Total bundles: {resp.total_bundles}")
for bundle in resp.bundles:
seed = bundle.seed
print(f"Seed: {seed.thought.content} (score={seed.lexical_score:.3f})")
for support in bundle.support:
print(f" [{support.depth}] {support.thought.content}")
print(f" via: {support.relation_kinds}")</code></pre>
<h4>lexical_search <em>server-only</em></h4>
<pre><code># Use the raw REST helpers until this is wrapped
result = client._post("/v1/lexical-search", {
"text": "rate limiting",
"chain_key": "my-agent",
"limit": 10,
"offset": 0,
})
for hit in result["results"]:
thought = Thought.from_dict(hit["thought"])
print(f"[{hit['score']:.3f}] {thought.content}")</code></pre>
<h4>search / query <em>server-only</em></h4>
<pre><code># Alias for lexical_search on the server
result = client._post("/v1/search", {
"text": "performance optimization",
"chain_key": "my-agent",
"limit": 10,
})</code></pre>
<h4>get_thought <em>server-only</em></h4>
<pre><code># Retrieve a single thought by ID, hash, or index
result = client._get("/v1/thoughts/abc123") # by thought ID
result = client._get("/v1/thoughts/by-hash/xyz789") # by content hash
result = client._get("/v1/thoughts/by-index/42") # by append-order index
result = client._get("/v1/thoughts/head") # latest thought on chain
thought = Thought.from_dict(result["thought"])
print(f"Thought {thought.id} at index {thought.index}")</code></pre>
<h4>traverse_thoughts <em>server-only</em></h4>
<pre><code># Traverse forwards or backwards from an anchor point
result = client._post("/v1/traverse-thoughts", {
"chain_key": "my-agent",
"anchor_id": "abc123", # start from this thought ID
"direction": "forward", # forward | backward
"limit": 20,
"include_anchor": True,
"thought_types": ["Insight", "Decision"],
"roles": ["Memory"],
"tags_any": ["performance"],
"since": "2026-01-01T00:00:00Z",
"until": "2026-04-14T00:00:00Z",
})
for thought_data in result["thoughts"]:
t = Thought.from_dict(thought_data)
print(f"[{t.index}] {t.content[:60]}...")</code></pre>
<h4>recent_context <em>server-only</em></h4>
<pre><code># Render recent context as a prompt snippet for agent handoff
result = client._get("/v1/recent-context?chain_key=my-agent&last_n=10")
print(result["content"])</code></pre>
<h4>head <em>server-only</em></h4>
<pre><code># Get chain tip metadata
result = client._get("/v1/chains/head?chain_key=my-agent")
print(f"Chain length: {result['length']}")
print(f"Latest thought: {result['latest_thought_id']}")
print(f"Head hash: {result['head_hash']}")</code></pre>
<hr>
<h3 id="api-chains">Chain & Agent Management</h3>
<h4>list_chains <strong>✓</strong></h4>
<pre><code>resp = client.list_chains()
print(f"Default chain: {resp.default_chain_key}")
print(f"All chains: {resp.chain_keys}")
for chain in resp.chains:
print(f" {chain.chain_key}: {chain.thought_count} thoughts, {chain.agent_count} agents")
print(f" adapter={chain.storage_adapter} location={chain.storage_location}")</code></pre>
<h4>upsert_agent <strong>✓</strong> (also: get_agent, list_agents)</h4>
<pre><code># Create or update an agent identity
agent = client.upsert_agent(
agent_id="agent-001",
chain_key="my-agent",
display_name="Assistant v3",
agent_owner="cloudllm",
description="Primary assistant agent for user tasks",
status="active",
)
print(f"Agent: {agent.display_name} ({agent.status})")
print(f" first seen: index {agent.first_seen_index}")
print(f" thought count: {agent.thought_count}")
print(f" aliases: {agent.aliases}")
# Get a specific agent's full registry record
agent_result = client._get(f"/v1/agents/agent-001?chain_key=my-agent")
# List all agents on a chain
agents_result = client._get("/v1/agents?chain_key=my-agent")
for agent_data in agents_result["agents"]:
print(agent_data["display_name"])</code></pre>
<hr>
<h3 id="api-skills">Skills</h3>
<h4>upload_skill <em>server-only</em></h4>
<pre><code>result = client._post("/v1/skills/upload", {
"agent_id": "agent-001",
"chain_key": "my-agent",
"skill_id": "my-skill",
"content": "# My Skill\n\nThis skill helps with...",
"format": "markdown",
"signing_key_id": "key-2026",
"skill_signature": [1, 2, 3, 4], # 64 bytes as int list
})
print(f"Uploaded skill ID: {result['skill_id']}")
print(f"Version: {result['version_id']}")</code></pre>
<h4>read_skill <em>server-only</em></h4>
<pre><code>result = client._post("/v1/skills/read", {
"skill_id": "my-skill",
"version_id": "v1.0", # optional, latest if omitted
})
print(result["content"])
print(f"Format: {result['format']}")</code></pre>
<h4>search_skill <em>server-only</em></h4>
<pre><code>result = client._post("/v1/skills/search", {
"text": "debugging workflow",
"limit": 5,
"names": ["my-skill"],
"tags_any": ["debug"],
"statuses": ["active"],
"since": "2026-01-01T00:00:00Z",
})
for skill in result["skills"]:
print(f"{skill['skill_id']}: {skill['latest_version']['description']}")</code></pre>
<h4>list_skills <em>server-only</em></h4>
<pre><code>result = client._get("/v1/skills?chain_key=my-agent")
for skill in result["skills"]:
print(f"{skill['skill_id']} ({skill['status']}) — latest version: {skill['latest_version_id']}")</code></pre>
<hr>
<h3 id="api-webhooks">Webhooks</h3>
<h4>register_webhook <em>server-only</em></h4>
<pre><code>result = client._post("/v1/webhooks/register", {
"chain_key": "my-agent",
"url": "https://my-app.com/mentisdb-hook",
"event_types": ["thought.appended", "chain.branched"],
"description": "Notify my app on new thoughts",
"secret": "my-webhook-secret",
})
print(f"Webhook registered: {result['webhook_id']}")</code></pre>
<h4>list_webhooks <em>server-only</em></h4>
<pre><code>result = client._get("/v1/webhooks?chain_key=my-agent")
for wh in result["webhooks"]:
print(f"{wh['webhook_id']}: {wh['url']} [{', '.join(wh['event_types'])}]")</code></pre>
<h4>delete_webhook <em>server-only</em></h4>
<pre><code>result = client._post("/v1/webhooks/delete", {
"webhook_id": "wh-abc123",
})</code></pre>
<hr>
<h3 id="api-markdown">Memory Markdown Export / Import</h3>
<h4>memory_markdown <em>server-only</em></h4>
<pre><code># Export chain as MEMORY.md formatted string
result = client._post("/v1/memory-markdown", {
"chain_key": "my-agent",
"limit": 50,
"thought_types": ["Insight", "Decision"],
"since": "2026-01-01T00:00:00Z",
})
print(result["markdown"])
# Output format:
# ## [Insight] 2026-04-14T10:30:00
# content here
# Tags: performance, api
# Agent: assistant</code></pre>
<h4>import_memory_markdown <em>server-only</em></h4>
<pre><code># Import a MEMORY.md formatted string back into a chain
result = client._post("/v1/import-memory-markdown", {
"chain_key": "my-agent",
"markdown": """## [Insight] 2026-04-10
Some insight here
Tags: test
## [Decision] 2026-04-11
A decision made
""",
"default_agent_id": "agent-001",
})
print(f"Imported {result['imported_count']} thoughts")
print(f"Imported indices: {result['imported_indices']}")</code></pre>
<hr>
<h2 id="full-example-2">Complete Working Example</h2>
<p>Here's a full example showing the full loop — appending thoughts, searching, and
using context bundles — against a running mentisdb:</p>
<pre><code>#!/usr/bin/env python3
"""Complete pymentisdb example — append, search, and retrieve."""
from pymentisdb import MentisDbClient, ThoughtType, ThoughtRole
client = MentisDbClient(base_url="http://127.0.0.1:9472")
# 1. Seed some memories
client.append_thought(
thought_type=ThoughtType.DECISION,
content="We chose PostgreSQL for the primary database.",
agent_name="architect",
importance=0.9,
tags=["database", "architecture"],
)
client.append_thought(
thought_type=ThoughtType.FINDING,
content="PostgreSQL handles 10k TPS with our current schema.",
agent_name="engineer",
importance=0.7,
tags=["database", "performance"],
)
# 2. Semantic search
results = client.ranked_search(text="database performance", limit=5)
print(f"Search results: {results.total} found")
for hit in results.results:
print(f" [{hit.score.total:.3f}] {hit.thought.thought_type.value}: "
f"{hit.thought.content}")
# 3. Get context with supporting evidence
bundles = client.context_bundles(text="why PostgreSQL", limit=2)
for bundle in bundles.bundles:
print(f"\nSeed: {bundle.seed.thought.content}")
for support in bundle.support:
print(f" Evidence ({support.relation_kinds}): {support.thought.content}")
# 4. List all chains
chains = client.list_chains()
print(f"Default chain: {chains.default_chain_key}")
for chain in chains.chains:
print(f" {chain.chain_key}: {chain.thought_count} thoughts")
# 5. Upsert an agent
agent = client.upsert_agent(
agent_id="agent-001",
display_name="My Assistant",
description="Primary user assistant",
)
print(f"Agent: {agent.display_name} — {agent.thought_count} thoughts recorded")</code></pre>
<h2 id="links">Links</h2>
<ul>
<li><a href="https://github.com/CloudLLM-ai/mentisdb/tree/master/pymentisdb">pymentisdb source</a></li>
<li><a href="https://github.com/CloudLLM-ai/mentisdb/tree/master/examples/langchain_memory_example.py">Full LangChain example</a></li>
<li><a href="https://docs.mentisdb.com">MentisDB documentation</a></li>
<li><a href="mentisdb-third-party-integrations.html">Integrating MentisDB with Claude Desktop, OpenCode, and more</a></li>
</ul>
<footer>
<a href="https://github.com/CloudLLM-ai/mentisdb">GitHub</a> ·
<a href="https://docs.mentisdb.com">Docs</a> ·
<a href="https://mentisdb.com">mentisdb.com</a>
</footer>
</body>
</html>