aboutsummaryrefslogtreecommitdiff
path: root/packages/tools/test/claude-memory-examples.ts
blob: 6921d15188cea21265f6a893a795ef4d8748e12d (plain) (blame)
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
/**
 * Claude Memory Tool Examples
 *
 * This file contains examples showing how to use the Claude Memory Tool with:
 * 1. Direct TypeScript/fetch integration
 * 2. Anthropic SDK integration
 */

import { createClaudeMemoryTool, type MemoryCommand } from "./claude-memory"

// =====================================================
// Example 1: Direct TypeScript/fetch Integration
// =====================================================

/**
 * Example: Direct usage with fetch calls
 */
export async function directFetchExample() {
	console.log("šŸš€ Direct Fetch Example - Claude Memory Tool")
	console.log("=".repeat(50))

	// Initialize the memory tool
	const memoryTool = createClaudeMemoryTool(process.env.SUPERMEMORY_API_KEY!, {
		projectId: "claude-memory-demo",
		memoryContainerTag: "claude_memory_demo",
	})

	// Example memory commands that Claude might send
	const commands: MemoryCommand[] = [
		{
			command: "create",
			path: "/memories/project-notes.md",
			file_text:
				"# Project Notes\n\n## Meeting with Client\n- Discussed requirements\n- Set deadline for next week\n- Need to follow up on budget\n\n## Technical Notes\n- Use React for frontend\n- Node.js backend\n- PostgreSQL database",
		},
		{
			command: "view",
			path: "/memories/",
		},
		{
			command: "view",
			path: "/memories/project-notes.md",
			view_range: [1, 5],
		},
		{
			command: "str_replace",
			path: "/memories/project-notes.md",
			old_str: "next week",
			new_str: "Friday",
		},
		{
			command: "insert",
			path: "/memories/project-notes.md",
			insert_line: 7,
			insert_text: "- Client prefers TypeScript",
		},
		{
			command: "create",
			path: "/memories/todo.txt",
			file_text:
				"TODO List:\n1. Set up development environment\n2. Create project structure\n3. Implement authentication\n4. Build user dashboard",
		},
		{
			command: "view",
			path: "/memories/",
		},
	]

	// Execute each command
	for (let i = 0; i < commands.length; i++) {
		const command = commands[i]
		console.log(
			`\nšŸ“ Step ${i + 1}: ${command.command.toUpperCase()} ${command.path}`,
		)

		try {
			const result = await memoryTool.handleCommand(command)

			if (result.success) {
				console.log("āœ… Success")
				if (result.content) {
					console.log("šŸ“„ Response:")
					console.log(result.content)
				}
			} else {
				console.log("āŒ Failed")
				console.log("Error:", result.error)
			}
		} catch (error) {
			console.log("šŸ’„ Exception:", error)
		}
	}
}

// =====================================================
// Example 2: Anthropic SDK Integration
// =====================================================

/**
 * Mock Anthropic SDK integration example
 * In a real implementation, you'd install @anthropic-ai/sdk
 */
export async function anthropicSdkExample() {
	console.log("šŸ¤– Anthropic SDK Example - Claude Memory Tool")
	console.log("=".repeat(50))

	// Initialize memory tool
	const memoryTool = createClaudeMemoryTool(process.env.SUPERMEMORY_API_KEY!, {
		projectId: "claude-chat-session",
		memoryContainerTag: "claude_memory_chat",
	})

	// Simulate Claude's memory tool usage in a conversation
	console.log("šŸ—£ļø  Simulating Claude conversation with memory tool access...")

	// Scenario: User asks Claude to remember something
	console.log(
		"\nUser: 'Remember that I prefer React over Vue for frontend development'",
	)

	const rememberResult = await memoryTool.handleCommand({
		command: "create",
		path: "/memories/user-preferences.md",
		file_text:
			"# User Preferences\n\n## Frontend Development\n- Prefers React over Vue\n- Likes TypeScript for type safety",
	})

	console.log("šŸ¤– Claude: 'I'll remember that preference for you.'")
	console.log(
		"Memory operation result:",
		rememberResult.success ? "āœ… Stored" : "āŒ Failed",
	)

	// Scenario: User asks about their preferences later
	console.log("\nUser: 'What frontend framework do I prefer?'")
	console.log(
		"šŸ¤– Claude: 'Let me check what I remember about your preferences...'",
	)

	const recallResult = await memoryTool.handleCommand({
		command: "view",
		path: "/memories/user-preferences.md",
	})

	if (recallResult.success) {
		console.log("šŸ“š Claude retrieved from memory:")
		console.log(recallResult.content)
		console.log(
			"\nšŸ¤– Claude: 'Based on what I remember, you prefer React over Vue for frontend development!'",
		)
	}

	// Scenario: User provides additional context
	console.log(
		"\nUser: 'Actually, also add that I like using Tailwind CSS for styling'",
	)

	await memoryTool.handleCommand({
		command: "str_replace",
		path: "/memories/user-preferences.md",
		old_str: "- Likes TypeScript for type safety",
		new_str:
			"- Likes TypeScript for type safety\n- Prefers Tailwind CSS for styling",
	})

	console.log(
		"šŸ¤– Claude: 'I've updated my memory with your Tailwind CSS preference!'",
	)

	// Scenario: Show current memory directory
	console.log("\nšŸ¤– Claude: 'Here's what I currently remember about you:'")
	const directoryResult = await memoryTool.handleCommand({
		command: "view",
		path: "/memories/",
	})

	if (directoryResult.success) {
		console.log(directoryResult.content)
	}
}

// =====================================================
// Example 3: Real Anthropic SDK Integration Template
// =====================================================

/**
 * This is what the actual integration would look like with @anthropic-ai/sdk
 */
export const anthropicIntegrationTemplate = `
// Install: npm install @anthropic-ai/sdk @supermemory/tools

import Anthropic from '@anthropic-ai/sdk';
import { createClaudeMemoryTool } from '@supermemory/tools/claude-memory';

const anthropic = new Anthropic({
  apiKey: process.env.ANTHROPIC_API_KEY,
});

const memoryTool = createClaudeMemoryTool(process.env.SUPERMEMORY_API_KEY!, {
  projectId: 'my-chat-app',
  memoryContainerTag: 'claude_memory'
});

// Memory tool definition for Claude
const memoryToolDefinition = {
  type: 'memory_20250818' as const,
  name: 'memory'
};

async function chatWithMemory(userMessage: string) {
  const response = await anthropic.beta.messages.create({
    model: 'claude-sonnet-4-5',
    max_tokens: 2048,
    messages: [{ role: 'user', content: userMessage }],
    tools: [memoryToolDefinition],
    betas: ['context-management-2025-06-27']
  });

  // Handle tool calls if Claude wants to use memory
  if (response.content.some(block => block.type === 'tool_use')) {
    for (const block of response.content) {
      if (block.type === 'tool_use' && block.name === 'memory') {
        const memoryCommand = block.input as any;
        const result = await memoryTool.handleCommand(memoryCommand);

        // You would typically send this result back to Claude
        console.log('Memory operation result:', result);
      }
    }
  }

  return response;
}

// Example usage:
// await chatWithMemory("Remember that I'm working on a React project with TypeScript");
// await chatWithMemory("What programming languages am I using in my current project?");
`

// =====================================================
// Example 4: cURL Commands for Testing
// =====================================================

export const curlExamples = `
# Test the memory tool using cURL commands against your supermemory API

# 1. Create a memory file
curl -X POST "https://api.supermemory.ai/v3/documents" \\
  -H "Authorization: Bearer YOUR_API_KEY" \\
  -H "Content-Type: application/json" \\
  -d '{
    "content": "# My Notes\\n\\nThis is a test note for Claude memory tool.",
    "customId": "/memories/test-note.md",
    "containerTags": ["claude_memory", "sm_project_test"],
    "metadata": {
      "claude_memory_type": "file",
      "file_path": "/memories/test-note.md",
      "line_count": 3,
      "created_by": "claude_memory_tool"
    }
  }'

# 2. Search/read the memory file
curl -X POST "https://api.supermemory.ai/v3/search" \\
  -H "Authorization: Bearer YOUR_API_KEY" \\
  -H "Content-Type: application/json" \\
  -d '{
    "q": "/memories/test-note.md",
    "containerTags": ["claude_memory", "sm_project_test"],
    "limit": 1,
    "includeFullDocs": true
  }'

# 3. List all memory files (directory listing)
curl -X POST "https://api.supermemory.ai/v3/search" \\
  -H "Authorization: Bearer YOUR_API_KEY" \\
  -H "Content-Type: application/json" \\
  -d '{
    "q": "*",
    "containerTags": ["claude_memory", "sm_project_test"],
    "limit": 100,
    "includeFullDocs": false
  }'

# 4. Update a memory file (str_replace operation)
curl -X PATCH "https://api.supermemory.ai/v3/documents/DOCUMENT_ID" \\
  -H "Authorization: Bearer YOUR_API_KEY" \\
  -H "Content-Type: application/json" \\
  -d '{
    "content": "# My Updated Notes\\n\\nThis note has been updated using str_replace.",
    "metadata": {
      "claude_memory_type": "file",
      "file_path": "/memories/test-note.md",
      "line_count": 3,
      "last_modified": "2025-01-15T10:30:00Z"
    }
  }'

# 5. Delete a memory file
curl -X DELETE "https://api.supermemory.ai/v3/documents/DOCUMENT_ID" \\
  -H "Authorization: Bearer YOUR_API_KEY"
`

// =====================================================
// Main runner function
// =====================================================

export async function runAllExamples() {
	if (!process.env.SUPERMEMORY_API_KEY) {
		console.error("āŒ SUPERMEMORY_API_KEY environment variable is required")
		console.log("Set your API key in .env file or environment variable")
		return
	}

	try {
		await directFetchExample()
		console.log("\\n" + "=".repeat(70) + "\\n")
		await anthropicSdkExample()

		console.log("\\n" + "=".repeat(70))
		console.log("šŸ“‹ Real Anthropic SDK Integration Template:")
		console.log(anthropicIntegrationTemplate)

		console.log("\\n" + "=".repeat(70))
		console.log("šŸ”§ cURL Examples for Direct API Testing:")
		console.log(curlExamples)
	} catch (error) {
		console.error("šŸ’„ Error running examples:", error)
	}
}

// Run examples if this file is executed directly
if (import.meta.main) {
	runAllExamples()
}