-
Notifications
You must be signed in to change notification settings - Fork 34
Add agent-memory provider #23
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
g1itchbot8888-del
wants to merge
1
commit into
supermemoryai:main
Choose a base branch
from
g1itchbot8888-del:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,133 @@ | ||
| import type { | ||
| Provider, | ||
| ProviderConfig, | ||
| IngestOptions, | ||
| IngestResult, | ||
| SearchOptions, | ||
| IndexingProgressCallback, | ||
| } from "../../types/provider" | ||
| import type { UnifiedSession } from "../../types/unified" | ||
| import { logger } from "../../utils/logger" | ||
| import { AGENT_MEMORY_PROMPTS } from "./prompts" | ||
|
|
||
| /** | ||
| * agent-memory provider for MemoryBench. | ||
| * | ||
| * Connects to a local agent-memory bench server (Python HTTP wrapper). | ||
| * The server manages per-container SQLite databases with semantic embeddings | ||
| * and graph-based memory relationships. | ||
| * | ||
| * Start the server: python -m agent_memory.bench_server --port 9876 | ||
| */ | ||
| export class AgentMemoryProvider implements Provider { | ||
| name = "agent-memory" | ||
| prompts = AGENT_MEMORY_PROMPTS | ||
| concurrency = { | ||
| default: 10, // Local, so moderate concurrency | ||
| } | ||
| private baseUrl: string = "http://127.0.0.1:9876" | ||
|
|
||
| async initialize(config: ProviderConfig): Promise<void> { | ||
| if (config.baseUrl) { | ||
| this.baseUrl = config.baseUrl | ||
| } | ||
|
|
||
| // Health check | ||
| try { | ||
| const res = await fetch(`${this.baseUrl}/health`) | ||
| if (!res.ok) throw new Error(`HTTP ${res.status}`) | ||
| const data = await res.json() as { status: string } | ||
| logger.info(`Connected to agent-memory bench server: ${data.status}`) | ||
| } catch (e) { | ||
| throw new Error( | ||
| `Cannot connect to agent-memory bench server at ${this.baseUrl}. ` + | ||
| `Start it with: python -m agent_memory.bench_server --port 9876\n` + | ||
| `Error: ${e}` | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| async ingest(sessions: UnifiedSession[], options: IngestOptions): Promise<IngestResult> { | ||
| // Send sessions in batches to avoid overwhelming the server | ||
| const batchSize = 5 | ||
| const allDocIds: string[] = [] | ||
|
|
||
| for (let i = 0; i < sessions.length; i += batchSize) { | ||
| const batch = sessions.slice(i, i + batchSize) | ||
|
|
||
| const res = await fetch(`${this.baseUrl}/ingest`, { | ||
| method: "POST", | ||
| headers: { "Content-Type": "application/json" }, | ||
| body: JSON.stringify({ | ||
| containerTag: options.containerTag, | ||
| sessions: batch, | ||
| }), | ||
| }) | ||
|
|
||
| if (!res.ok) { | ||
| const text = await res.text() | ||
| throw new Error(`Ingest failed: ${text}`) | ||
| } | ||
|
|
||
| const data = await res.json() as { documentIds: string[], count: number } | ||
| allDocIds.push(...data.documentIds) | ||
|
|
||
| if (i % 20 === 0 && i > 0) { | ||
| logger.info(`Ingested ${i}/${sessions.length} sessions (${allDocIds.length} memories)`) | ||
| } | ||
| } | ||
|
|
||
| logger.info(`Ingested ${sessions.length} sessions → ${allDocIds.length} memories`) | ||
| return { documentIds: allDocIds } | ||
| } | ||
|
|
||
| async awaitIndexing( | ||
| result: IngestResult, | ||
| _containerTag: string, | ||
| onProgress?: IndexingProgressCallback | ||
| ): Promise<void> { | ||
| // agent-memory indexes synchronously on ingest, no waiting needed | ||
| const total = result.documentIds.length | ||
| onProgress?.({ | ||
| completedIds: result.documentIds, | ||
| failedIds: [], | ||
| total, | ||
| }) | ||
| } | ||
|
|
||
| async search(query: string, options: SearchOptions): Promise<unknown[]> { | ||
| const res = await fetch(`${this.baseUrl}/search`, { | ||
| method: "POST", | ||
| headers: { "Content-Type": "application/json" }, | ||
| body: JSON.stringify({ | ||
| containerTag: options.containerTag, | ||
| query, | ||
| limit: options.limit || 30, | ||
| }), | ||
| }) | ||
|
|
||
| if (!res.ok) { | ||
| const text = await res.text() | ||
| throw new Error(`Search failed: ${text}`) | ||
| } | ||
|
|
||
| const data = await res.json() as { results: unknown[] } | ||
| return data.results ?? [] | ||
| } | ||
|
|
||
| async clear(containerTag: string): Promise<void> { | ||
| const res = await fetch(`${this.baseUrl}/clear`, { | ||
| method: "POST", | ||
| headers: { "Content-Type": "application/json" }, | ||
| body: JSON.stringify({ containerTag }), | ||
| }) | ||
|
|
||
| if (!res.ok) { | ||
| logger.warn(`Clear failed for ${containerTag}`) | ||
| } else { | ||
| logger.info(`Cleared memories for: ${containerTag}`) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| export default AgentMemoryProvider |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| import type { ProviderPrompts } from "../../types/prompts" | ||
|
|
||
| export const AGENT_MEMORY_PROMPTS: ProviderPrompts = { | ||
| answerPrompt: (question: string, context: unknown[], questionDate?: string) => { | ||
| const memories = (context as Array<{ memory?: string; score?: number }>) | ||
| .map((r, i) => { | ||
| const memory = r.memory || JSON.stringify(r) | ||
| const score = r.score ? ` (relevance: ${r.score.toFixed(2)})` : "" | ||
| return `${i + 1}. ${memory}${score}` | ||
| }) | ||
| .join("\n") | ||
|
|
||
| return `You are answering questions based on memories from past conversations. | ||
|
|
||
| ${questionDate ? `Current date context: ${questionDate}\n` : ""} | ||
| Retrieved memories: | ||
| ${memories || "(no relevant memories found)"} | ||
|
|
||
| Question: ${question} | ||
|
|
||
| Instructions: | ||
| - Answer ONLY based on the retrieved memories above | ||
| - If the memories don't contain enough information, say so | ||
| - Be specific and cite details from the memories | ||
| - For temporal questions, pay attention to dates and sequence of events | ||
| - If memories contradict each other, prefer the most recent one | ||
|
|
||
| Answer:` | ||
| }, | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Bug: The truthiness check on
r.scoreis unsafe. It will cause a crash if the score is non-numeric and will incorrectly hide a valid score of0.Severity: MEDIUM
Suggested Fix
Replace the truthiness check with an explicit type check to ensure
r.scoreis a number before calling.toFixed(2). For example:const score = typeof r.score === "number" ? ", (relevance: " + r.score.toFixed(2) + ")" : "". This handles non-numeric values gracefully and correctly formats a score of0.Prompt for AI Agent
Did we get this right? 👍 / 👎 to inform future reviews.