aboutsummaryrefslogtreecommitdiff
path: root/packages/tools/test/claude-memory-real-example.ts
blob: 06ebb54684000455248c1a863083de84c716f1cb (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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
/**
 * Real Claude Memory Tool Integration Examples
 *
 * This shows actual tool call handling based on real Claude API responses
 */

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

// =====================================================
// Real Claude API Integration
// =====================================================

/**
 * Handle actual Claude memory tool calls from the API response
 */
export async function handleClaudeMemoryToolCall(
	toolUseBlock: {
		type: "tool_use"
		id: string
		name: "memory"
		input: MemoryCommand
	},
	supermemoryApiKey: string,
	config?: {
		projectId?: string
		memoryContainerTag?: string
		baseUrl?: string
	},
) {
	console.log(
		`๐Ÿ”ง Handling Claude memory tool call: ${toolUseBlock.input.command}`,
	)
	console.log(`๐Ÿ“ Path: ${toolUseBlock.input.path}`)

	// Initialize memory tool
	const memoryTool = createClaudeMemoryTool(supermemoryApiKey, {
		projectId: config?.projectId || "claude-chat",
		memoryContainerTag: config?.memoryContainerTag || "claude_memory",
		baseUrl: config?.baseUrl,
	})

	// Execute the memory command
	const result = await memoryTool.handleCommand(toolUseBlock.input)

	// Format response for Claude
	const toolResult = {
		type: "tool_result" as const,
		tool_use_id: toolUseBlock.id,
		content: result.success
			? result.content || "Operation completed successfully"
			: `Error: ${result.error}`,
		is_error: !result.success,
	}

	console.log(
		`${result.success ? "โœ…" : "โŒ"} Result:`,
		result.content || result.error,
	)

	return toolResult
}

/**
 * Complete example with real Claude API call and memory tool handling
 */
export async function realClaudeMemoryExample() {
	console.log("๐Ÿค– Real Claude Memory Tool Integration")
	console.log("=".repeat(50))

	// Your API keys
	const ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY
	const SUPERMEMORY_API_KEY = process.env.SUPERMEMORY_API_KEY

	if (!ANTHROPIC_API_KEY || !SUPERMEMORY_API_KEY) {
		console.error("โŒ Missing API keys:")
		console.error("- Set ANTHROPIC_API_KEY for Claude")
		console.error("- Set SUPERMEMORY_API_KEY for Supermemory")
		return
	}

	// Step 1: Make initial request to Claude
	console.log("๐Ÿ“ค Making request to Claude API...")

	const initialRequest = {
		model: "claude-sonnet-4-5",
		max_tokens: 2048,
		messages: [
			{
				role: "user" as const,
				content:
					"I'm working on a Python web scraper that keeps crashing with a timeout error. Here's the problematic function:\\n\\n```python\\ndef fetch_page(url, retries=3):\\n    for i in range(retries):\\n        try:\\n            response = requests.get(url, timeout=5)\\n            return response.text\\n        except requests.exceptions.Timeout:\\n            if i == retries - 1:\\n                raise\\n            time.sleep(1)\\n```\\n\\nPlease help me debug this.",
			},
		],
		tools: [
			{
				type: "memory_20250818" as const,
				name: "memory",
			},
		],
	}

	// Make the API call
	const claudeResponse = await fetch("https://api.anthropic.com/v1/messages", {
		method: "POST",
		headers: {
			"x-api-key": ANTHROPIC_API_KEY,
			"anthropic-version": "2023-06-01",
			"content-type": "application/json",
			"anthropic-beta": "context-management-2025-06-27",
		},
		body: JSON.stringify(initialRequest),
	})

	const responseData = await claudeResponse.json()
	console.log("๐Ÿ“ฅ Claude's response:")
	console.log(JSON.stringify(responseData, null, 2))

	// Step 2: Handle any tool calls
	const toolResults = []

	if (responseData.content) {
		for (const block of responseData.content) {
			if (block.type === "tool_use" && block.name === "memory") {
				console.log("\\n๐Ÿ”ง Processing memory tool call:")
				console.log(`Command: ${block.input.command}`)
				console.log(`Path: ${block.input.path}`)

				// Handle the memory tool call
				const toolResult = await handleClaudeMemoryToolCall(
					block,
					SUPERMEMORY_API_KEY,
					{
						projectId: "python-scraper-help",
						memoryContainerTag: "claude_memory_debug",
					},
				)

				toolResults.push(toolResult)
			}
		}
	}

	// Step 3: Send tool results back to Claude if there were any
	if (toolResults.length > 0) {
		console.log("\\n๐Ÿ“ค Sending tool results back to Claude...")

		const followUpRequest = {
			model: "claude-sonnet-4-5",
			max_tokens: 2048,
			messages: [
				...initialRequest.messages,
				{
					role: "assistant" as const,
					content: responseData.content,
				},
				{
					role: "user" as const,
					content: toolResults,
				},
			],
			tools: initialRequest.tools,
		}

		const followUpResponse = await fetch(
			"https://api.anthropic.com/v1/messages",
			{
				method: "POST",
				headers: {
					"x-api-key": ANTHROPIC_API_KEY,
					"anthropic-version": "2023-06-01",
					"content-type": "application/json",
					"anthropic-beta": "context-management-2025-06-27",
				},
				body: JSON.stringify(followUpRequest),
			},
		)

		const followUpData = await followUpResponse.json()
		console.log("๐Ÿ“ฅ Claude's final response:")
		console.log(JSON.stringify(followUpData, null, 2))
	}
}

/**
 * Simplified function to process Claude tool calls
 */
export async function processClaudeResponse(
	claudeResponseData: any,
	supermemoryApiKey: string,
	config?: {
		projectId?: string
		memoryContainerTag?: string
		baseUrl?: string
	},
): Promise<any[]> {
	const toolResults = []

	if (claudeResponseData.content) {
		for (const block of claudeResponseData.content) {
			if (block.type === "tool_use" && block.name === "memory") {
				const toolResult = await handleClaudeMemoryToolCall(
					block,
					supermemoryApiKey,
					config,
				)
				toolResults.push(toolResult)
			}
		}
	}

	return toolResults
}

// =====================================================
// Express.js / Web Framework Integration Example
// =====================================================

export const webIntegrationExample = `
// Example: Express.js endpoint that handles Claude memory tool calls

import express from 'express';
import { processClaudeResponse } from './claude-memory-real-example';

const app = express();
app.use(express.json());

app.post('/chat-with-memory', async (req, res) => {
  const { message, conversationId } = req.body;

  try {
    // 1. Send message to Claude
    const claudeResponse = await fetch('https://api.anthropic.com/v1/messages', {
      method: 'POST',
      headers: {
        'x-api-key': process.env.ANTHROPIC_API_KEY,
        'anthropic-version': '2023-06-01',
        'content-type': 'application/json',
        'anthropic-beta': 'context-management-2025-06-27'
      },
      body: JSON.stringify({
        model: 'claude-sonnet-4-5',
        max_tokens: 2048,
        messages: [{ role: 'user', content: message }],
        tools: [{ type: 'memory_20250818', name: 'memory' }]
      })
    });

    const claudeData = await claudeResponse.json();

    // 2. Handle any memory tool calls
    const toolResults = await processClaudeResponse(
      claudeData,
      process.env.SUPERMEMORY_API_KEY!,
      {
        projectId: conversationId || 'default-chat',
        memoryContainerTag: 'claude_memory_chat'
      }
    );

    // 3. Send tool results back to Claude if needed
    if (toolResults.length > 0) {
      const followUpResponse = await fetch('https://api.anthropic.com/v1/messages', {
        // ... send tool results back to Claude
      });
      const finalData = await followUpResponse.json();
      res.json({ response: finalData, memoryOperations: toolResults.length });
    } else {
      res.json({ response: claudeData, memoryOperations: 0 });
    }

  } catch (error) {
    res.status(500).json({ error: 'Failed to process chat with memory' });
  }
});
`

// =====================================================
// Test with actual tool call from your example
// =====================================================

export async function testWithRealToolCall() {
	console.log("๐Ÿงช Testing with Real Tool Call from Your Example")
	console.log("=".repeat(50))

	// This is the actual tool call Claude made in your example
	const realToolCall = {
		type: "tool_use" as const,
		id: "toolu_01BjWuUZXUfie6ey5Vz3xvth",
		name: "memory" as const,
		input: {
			command: "view" as const,
			path: "/memories",
		},
	}

	console.log("๐Ÿ” Tool call from Claude:")
	console.log(JSON.stringify(realToolCall, null, 2))

	if (!process.env.SUPERMEMORY_API_KEY) {
		console.error("โŒ SUPERMEMORY_API_KEY required for testing")
		return
	}

	// Process the tool call
	const result = await handleClaudeMemoryToolCall(
		realToolCall,
		process.env.SUPERMEMORY_API_KEY,
		{
			projectId: "python-scraper-debug",
			memoryContainerTag: "claude_memory_test",
		},
	)

	console.log("\\n๐Ÿ“‹ Tool Result to send back to Claude:")
	console.log(JSON.stringify(result, null, 2))
}

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

export async function runRealExamples() {
	console.log("๐Ÿš€ Running Real Claude Memory Tool Examples")
	console.log("=".repeat(70))

	// Test with the actual tool call first
	await testWithRealToolCall()

	console.log("\\n" + "=".repeat(70) + "\\n")

	// Show web integration example
	console.log("๐ŸŒ Web Framework Integration Example:")
	console.log(webIntegrationExample)

	// Only run full API example if both keys are present
	if (process.env.ANTHROPIC_API_KEY && process.env.SUPERMEMORY_API_KEY) {
		console.log("\\n" + "=".repeat(70) + "\\n")
		await realClaudeMemoryExample()
	} else {
		console.log(
			"\\nโš ๏ธ  Set ANTHROPIC_API_KEY and SUPERMEMORY_API_KEY to run full API example",
		)
	}
}

// Run if executed directly
if (import.meta.main) {
	runRealExamples()
}