aboutsummaryrefslogtreecommitdiff
path: root/packages/tools/test/anthropic-example.ts
blob: 039f87acc05f979eff3b487710fc3d71d194a15e (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
#!/usr/bin/env bun
/**
 * Anthropic SDK Example with Claude Memory Tool
 * Shows how to use the memory tool with the official Anthropic SDK
 */

import Anthropic from '@anthropic-ai/sdk'
import { createClaudeMemoryTool } from './claude-memory'
import 'dotenv/config'

/**
 * Handle Claude's memory tool calls using the Anthropic SDK
 */
async function chatWithMemoryTool() {
  console.log('๐Ÿค– Anthropic SDK Example - Claude with Memory Tool')
  console.log('=' .repeat(50))

  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 required API keys:')
    console.error('- ANTHROPIC_API_KEY')
    console.error('- SUPERMEMORY_API_KEY')
    return
  }

  // Initialize Anthropic client
  const anthropic = new Anthropic({
    apiKey: ANTHROPIC_API_KEY,
  })

  // Initialize memory tool
  const memoryTool = createClaudeMemoryTool(SUPERMEMORY_API_KEY, {
    projectId: 'anthropic-sdk-demo',
    memoryContainerTag: 'claude_memory_anthropic',
  })

  // Conversation messages
  const messages: Anthropic.Messages.MessageParam[] = [
    {
      role: 'user',
      content: "Hi Claude! I'm working on a new React project using TypeScript and I want you to remember my preferences. Can you help me debug some code later?",
    },
  ]

  console.log('๐Ÿ’ฌ User:', messages[0].content)
  console.log('\n๐Ÿ”„ Sending to Claude with memory tool...')

  try {
    // Make initial request to Claude with memory tool
    const response = await anthropic.beta.messages.create({
      model: 'claude-sonnet-4-5',
      max_tokens: 2048,
      messages: messages,
      tools: [
        {
          type: 'memory_20250818',
          name: 'memory',
        },
      ],
      betas: ['context-management-2025-06-27'],
    })

    console.log('๐Ÿ“ฅ Claude responded:')

    // Process the response
    let toolResults: Anthropic.Messages.ToolResultBlockParam[] = []

    for (const block of response.content) {
      if (block.type === 'text') {
        console.log('๐Ÿ’ญ', block.text)
      } else if (block.type === 'tool_use' && block.name === 'memory') {
        console.log('๐Ÿ”ง Claude is using memory tool:')
        console.log('   Command:', block.input.command)
        console.log('   Path:', block.input.path)

        // Handle the memory tool call
        const memoryResult = await memoryTool.handleCommand(block.input as any)

        const toolResult: Anthropic.Messages.ToolResultBlockParam = {
          type: 'tool_result',
          tool_use_id: block.id,
          content: memoryResult.success
            ? memoryResult.content || 'Operation completed successfully'
            : `Error: ${memoryResult.error}`,
          is_error: !memoryResult.success,
        }

        toolResults.push(toolResult)

        console.log('๐Ÿ“Š Memory operation result:', memoryResult.success ? 'โœ… Success' : 'โŒ Failed')
        if (memoryResult.content) {
          console.log('๐Ÿ“„ Content preview:', memoryResult.content.substring(0, 100) + '...')
        }
      }
    }

    // If Claude used memory tools, send the results back
    if (toolResults.length > 0) {
      console.log('\n๐Ÿ”„ Sending tool results back to Claude...')

      // Add Claude's response to conversation
      messages.push({
        role: 'assistant',
        content: response.content,
      })

      // Add tool results
      messages.push({
        role: 'user',
        content: toolResults,
      })

      const finalResponse = await anthropic.beta.messages.create({
        model: 'claude-sonnet-4-5',
        max_tokens: 2048,
        messages: messages,
        tools: [
          {
            type: 'memory_20250818',
            name: 'memory',
          },
        ],
        betas: ['context-management-2025-06-27'],
      })

      console.log('๐Ÿ“ฅ Claude\'s final response:')

      for (const block of finalResponse.content) {
        if (block.type === 'text') {
          console.log('๐Ÿ’ญ', block.text)
        } else if (block.type === 'tool_use' && block.name === 'memory') {
          console.log('๐Ÿ”ง Claude is using memory tool again:')
          console.log('   Command:', block.input.command)
          console.log('   Path:', block.input.path)

          // Handle additional memory tool calls
          const memoryResult = await memoryTool.handleCommand(block.input as any)
          console.log('๐Ÿ“Š Memory operation result:', memoryResult.success ? 'โœ… Success' : 'โŒ Failed')
        }
      }
    }

    console.log('\nโœจ Conversation completed!')
    console.log('\n๐Ÿ“‹ Usage statistics:')
    console.log('- Input tokens:', response.usage.input_tokens)
    console.log('- Output tokens:', response.usage.output_tokens)
    console.log('- Memory operations:', toolResults.length)

  } catch (error) {
    console.error('โŒ Error:', error)
  }
}

/**
 * Test memory tool operations directly
 */
async function testMemoryOperations() {
  console.log('\n๐Ÿงช Testing Memory Operations Directly')
  console.log('=' .repeat(50))

  if (!process.env.SUPERMEMORY_API_KEY) {
    console.error('โŒ SUPERMEMORY_API_KEY is required')
    return
  }

  const memoryTool = createClaudeMemoryTool(process.env.SUPERMEMORY_API_KEY, {
    projectId: 'direct-test',
    memoryContainerTag: 'claude_memory_direct',
  })

  const testCases = [
    {
      name: 'View empty memory directory',
      command: { command: 'view' as const, path: '/memories' },
    },
    {
      name: 'Create user preferences file',
      command: {
        command: 'create' as const,
        path: '/memories/user-preferences.md',
        file_text: '# User Preferences\n\n- Prefers React with TypeScript\n- Likes clean, readable code\n- Uses functional programming style\n- Prefers ESLint and Prettier for code formatting',
      },
    },
    {
      name: 'Create project notes',
      command: {
        command: 'create' as const,
        path: '/memories/project-notes.txt',
        file_text: 'Current Project: React TypeScript App\n\nFeatures to implement:\n1. User authentication\n2. Dashboard with widgets\n3. Data visualization\n4. Export functionality\n\nTech stack:\n- React 18\n- TypeScript\n- Vite\n- Tailwind CSS',
      },
    },
    {
      name: 'List directory contents',
      command: { command: 'view' as const, path: '/memories/' },
    },
    {
      name: 'Read user preferences',
      command: { command: 'view' as const, path: '/memories/user-preferences.md' },
    },
    {
      name: 'Update preferences (add VS Code)',
      command: {
        command: 'str_replace' as const,
        path: '/memories/user-preferences.md',
        old_str: '- Prefers ESLint and Prettier for code formatting',
        new_str: '- Prefers ESLint and Prettier for code formatting\n- Uses VS Code as primary editor\n- Likes GitHub Copilot for code completion',
      },
    },
    {
      name: 'Insert new task in project notes',
      command: {
        command: 'insert' as const,
        path: '/memories/project-notes.txt',
        insert_line: 6,
        insert_text: '5. Unit testing with Jest and React Testing Library',
      },
    },
    {
      name: 'Read updated project notes',
      command: { command: 'view' as const, path: '/memories/project-notes.txt', view_range: [4, 8] },
    },
  ]

  for (const testCase of testCases) {
    console.log(`\n๐Ÿ” ${testCase.name}`)
    try {
      const result = await memoryTool.handleCommand(testCase.command)

      if (result.success) {
        console.log('โœ… Success')
        if (result.content && result.content.length <= 200) {
          console.log('๐Ÿ“„ Result:', result.content)
        } else if (result.content) {
          console.log('๐Ÿ“„ Result:', result.content.substring(0, 150) + '... (truncated)')
        }
      } else {
        console.log('โŒ Failed')
        console.log('๐Ÿ“„ Error:', result.error)
      }
    } catch (error) {
      console.log('๐Ÿ’ฅ Exception:', error)
    }

    // Small delay to avoid rate limiting
    await new Promise(resolve => setTimeout(resolve, 300))
  }
}

// Run the examples
async function main() {
  await testMemoryOperations()
  console.log('\n' + '=' .repeat(70) + '\n')
  await chatWithMemoryTool()
}

if (import.meta.main) {
  main().catch(console.error)
}