aboutsummaryrefslogtreecommitdiff
path: root/apps/docs/integrations/openai.mdx
blob: 66b797c19e5fb917f563f7a55ef86a578f62ba90 (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
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
---
title: "OpenAI SDK"
sidebarTitle: "OpenAI SDK"
description: "Memory tools for OpenAI function calling with Supermemory integration"
icon: "/images/openai.svg"
---

Add memory capabilities to the official OpenAI SDKs using Supermemory. Two approaches available:

1. **`withSupermemory` wrapper** - Automatic memory injection into system prompts (zero-config)
2. **Function calling tools** - Explicit tool calls for search/add memory operations

<Tip>
**New to Supermemory?** Start with `withSupermemory` for the simplest integration. It automatically injects relevant memories into your prompts.
</Tip>

<CardGroup>
<Card title="Supermemory tools on npm" icon="npm" href="https://www.npmjs.com/package/@supermemory/tools">
    Check out the NPM page for more details
</Card>
<Card title="Supermemory AI SDK" icon="python" href="https://pypi.org/project/supermemory-openai-sdk/">
    Check out the PyPI page for more details
</Card>
</CardGroup>

---

## withSupermemory Wrapper

The simplest way to add memory to your OpenAI client. Wraps your client to automatically inject relevant memories into system prompts.

### Installation

```bash
npm install @supermemory/tools openai
```

### Quick Start

```typescript
import OpenAI from "openai"
import { withSupermemory } from "@supermemory/tools/openai"

const openai = new OpenAI()

// Wrap client with memory - memories auto-injected into system prompts
const client = withSupermemory(openai, "user-123", {
  mode: "full",        // "profile" | "query" | "full"
  addMemory: "always", // "always" | "never"
})

// Use normally - memories are automatically included
const response = await client.chat.completions.create({
  model: "gpt-5",
  messages: [
    { role: "system", content: "You are a helpful assistant." },
    { role: "user", content: "What's my favorite programming language?" }
  ]
})
```

### Configuration Options

```typescript
const client = withSupermemory(openai, "user-123", {
  // Memory search mode
  mode: "full",  // "profile" (user profile only), "query" (search only), "full" (both)

  // Auto-save conversations as memories
  addMemory: "always",  // "always" | "never"

  // Group messages into conversations
  conversationId: "conv-456",

  // Enable debug logging
  verbose: true,

  // Custom API endpoint
  baseUrl: "https://custom.api.com"
})
```

### Modes Explained

| Mode | Description | Use Case |
|------|-------------|----------|
| `profile` | Injects user profile (static + dynamic facts) | General personalization |
| `query` | Searches memories based on user message | Question answering |
| `full` | Both profile and query-based search | Best for chatbots |

### Works with Responses API Too

```typescript
const client = withSupermemory(openai, "user-123", { mode: "full" })

// Memories injected into instructions
const response = await client.responses.create({
  model: "gpt-5",
  instructions: "You are a helpful assistant.",
  input: "What do you know about me?"
})
```

### Environment Variables

```bash
SUPERMEMORY_API_KEY=your_supermemory_key
OPENAI_API_KEY=your_openai_key
```

---

## Function Calling Tools

For explicit control over memory operations, use function calling tools. The model decides when to search or add memories.

## Installation

<CodeGroup>

```bash Python
# Using uv (recommended)
uv add supermemory-openai-sdk

# Or with pip
pip install supermemory-openai-sdk
```

```bash JavaScript/TypeScript
npm install @supermemory/tools
```

</CodeGroup>

## Quick Start

<CodeGroup>

```python Python SDK
import asyncio
import openai
from supermemory_openai import SupermemoryTools, execute_memory_tool_calls

async def main():
    # Initialize OpenAI client
    client = openai.AsyncOpenAI(api_key="your-openai-api-key")

    # Initialize Supermemory tools
    tools = SupermemoryTools(
        api_key="your-supermemory-api-key",
        config={"project_id": "my-project"}
    )

    # Chat with memory tools
    response = await client.chat.completions.create(
        model="gpt-5",
        messages=[
            {
                "role": "system",
                "content": "You are a helpful assistant with access to user memories."
            },
            {
                "role": "user",
                "content": "Remember that I prefer tea over coffee"
            }
        ],
        tools=tools.get_tool_definitions()
    )

    # Handle tool calls if present
    if response.choices[0].message.tool_calls:
        tool_results = await execute_memory_tool_calls(
            api_key="your-supermemory-api-key",
            tool_calls=response.choices[0].message.tool_calls,
            config={"project_id": "my-project"}
        )
        print("Tool results:", tool_results)

    print(response.choices[0].message.content)

asyncio.run(main())
```

```typescript JavaScript/TypeScript SDK
import { supermemoryTools, getToolDefinitions, createToolCallExecutor } from "@supermemory/tools/openai"
import OpenAI from "openai"

const client = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY!,
})

// Get tool definitions for OpenAI
const toolDefinitions = getToolDefinitions()

// Create tool executor
const executeToolCall = createToolCallExecutor(process.env.SUPERMEMORY_API_KEY!, {
  projectId: "your-project-id",
})

// Use with OpenAI Chat Completions
const completion = await client.chat.completions.create({
  model: "gpt-5",
  messages: [
    {
      role: "user",
      content: "What do you remember about my preferences?",
    },
  ],
  tools: toolDefinitions,
})

// Execute tool calls if any
if (completion.choices[0]?.message.tool_calls) {
  for (const toolCall of completion.choices[0].message.tool_calls) {
    const result = await executeToolCall(toolCall)
    console.log(result)
  }
}
```

</CodeGroup>

## Configuration

### Memory Tools Configuration

<CodeGroup>

```python Python Configuration
from supermemory_openai import SupermemoryTools

tools = SupermemoryTools(
    api_key="your-supermemory-api-key",
    config={
        "project_id": "my-project",  # or use container_tags
        "base_url": "https://custom-endpoint.com",  # optional
    }
)
```

```typescript JavaScript Configuration
import { supermemoryTools } from "@supermemory/tools/openai"

const tools = supermemoryTools(process.env.SUPERMEMORY_API_KEY!, {
  containerTags: ["your-user-id"],
  baseUrl: "https://custom-endpoint.com", // optional
})
```

</CodeGroup>

## Available Tools

### Search Memories

Search through user memories using semantic search:

<CodeGroup>

```python Python
# Search memories
result = await tools.search_memories(
    information_to_get="user preferences",
    limit=10,
    include_full_docs=True
)
print(f"Found {len(result.memories)} memories")
```

```typescript JavaScript
// Search memories
const searchResult = await tools.searchMemories({
  informationToGet: "user preferences",
  limit: 10,
})
console.log(`Found ${searchResult.memories.length} memories`)
```

</CodeGroup>

### Add Memory

Store new information in memory:

<CodeGroup>

```python Python
# Add memory
result = await tools.add_memory(
    memory="User prefers tea over coffee"
)
print(f"Added memory with ID: {result.memory.id}")
```

```typescript JavaScript
// Add memory
const addResult = await tools.addMemory({
  memory: "User prefers dark roast coffee",
})
console.log(`Added memory with ID: ${addResult.memory.id}`)
```

</CodeGroup>

## Individual Tools

Use tools separately for more granular control:

<CodeGroup>

```python Python Individual Tools
from supermemory_openai import (
    create_search_memories_tool,
    create_add_memory_tool
)

search_tool = create_search_memories_tool("your-api-key")
add_tool = create_add_memory_tool("your-api-key")

# Use individual tools in OpenAI function calling
tools_list = [search_tool, add_tool]
```

```typescript JavaScript Individual Tools
import {
  createSearchMemoriesTool,
  createAddMemoryTool
} from "@supermemory/tools/openai"

const searchTool = createSearchMemoriesTool(process.env.SUPERMEMORY_API_KEY!)
const addTool = createAddMemoryTool(process.env.SUPERMEMORY_API_KEY!)

// Use individual tools
const toolDefinitions = [searchTool.definition, addTool.definition]
```

</CodeGroup>

## Complete Chat Example

Here's a complete example showing a multi-turn conversation with memory:

<CodeGroup>

```python Complete Python Example
import asyncio
import openai
from supermemory_openai import SupermemoryTools, execute_memory_tool_calls

async def chat_with_memory():
    client = openai.AsyncOpenAI()
    tools = SupermemoryTools(
        api_key="your-supermemory-api-key",
        config={"project_id": "chat-example"}
    )

    messages = [
        {
            "role": "system",
            "content": """You are a helpful assistant with memory capabilities.
            When users share personal information, remember it using addMemory.
            When they ask questions, search your memories to provide personalized responses."""
        }
    ]

    while True:
        user_input = input("You: ")
        if user_input.lower() == 'quit':
            break

        messages.append({"role": "user", "content": user_input})

        # Get AI response with tools
        response = await client.chat.completions.create(
            model="gpt-5",
            messages=messages,
            tools=tools.get_tool_definitions()
        )

        # Handle tool calls
        if response.choices[0].message.tool_calls:
            messages.append(response.choices[0].message)

            tool_results = await execute_memory_tool_calls(
                api_key="your-supermemory-api-key",
                tool_calls=response.choices[0].message.tool_calls,
                config={"project_id": "chat-example"}
            )

            messages.extend(tool_results)

            # Get final response after tool execution
            final_response = await client.chat.completions.create(
                model="gpt-5",
                messages=messages
            )

            assistant_message = final_response.choices[0].message.content
        else:
            assistant_message = response.choices[0].message.content
            messages.append({"role": "assistant", "content": assistant_message})

        print(f"Assistant: {assistant_message}")

# Run the chat
asyncio.run(chat_with_memory())
```

```typescript Complete JavaScript Example
import OpenAI from "openai"
import { getToolDefinitions, createToolCallExecutor } from "@supermemory/tools/openai"
import readline from 'readline'

const client = new OpenAI()
const executeToolCall = createToolCallExecutor(process.env.SUPERMEMORY_API_KEY!, {
  projectId: "chat-example",
})

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
})

async function chatWithMemory() {
  const messages: OpenAI.Chat.ChatCompletionMessageParam[] = [
    {
      role: "system",
      content: `You are a helpful assistant with memory capabilities.
      When users share personal information, remember it using addMemory.
      When they ask questions, search your memories to provide personalized responses.`
    }
  ]

  const askQuestion = () => {
    rl.question("You: ", async (userInput) => {
      if (userInput.toLowerCase() === 'quit') {
        rl.close()
        return
      }

      messages.push({ role: "user", content: userInput })

      // Get AI response with tools
      const response = await client.chat.completions.create({
        model: "gpt-5",
        messages,
        tools: getToolDefinitions(),
      })

      const choice = response.choices[0]
      if (choice?.message.tool_calls) {
        messages.push(choice.message)

        // Execute tool calls
        for (const toolCall of choice.message.tool_calls) {
          const result = await executeToolCall(toolCall)
          messages.push({
            role: "tool",
            tool_call_id: toolCall.id,
            content: JSON.stringify(result),
          })
        }

        // Get final response after tool execution
        const finalResponse = await client.chat.completions.create({
          model: "gpt-5",
          messages,
        })

        const assistantMessage = finalResponse.choices[0]?.message.content || "No response"
        console.log(`Assistant: ${assistantMessage}`)
        messages.push({ role: "assistant", content: assistantMessage })
      } else {
        const assistantMessage = choice?.message.content || "No response"
        console.log(`Assistant: ${assistantMessage}`)
        messages.push({ role: "assistant", content: assistantMessage })
      }

      askQuestion()
    })
  }

  console.log("Chat with memory started. Type 'quit' to exit.")
  askQuestion()
}

chatWithMemory()
```

</CodeGroup>

## Error Handling

Handle errors gracefully in your applications:

<CodeGroup>

```python Python Error Handling
from supermemory_openai import SupermemoryTools
import openai

async def safe_chat():
    try:
        client = openai.AsyncOpenAI()
        tools = SupermemoryTools(api_key="your-api-key")

        response = await client.chat.completions.create(
            model="gpt-5",
            messages=[{"role": "user", "content": "Hello"}],
            tools=tools.get_tool_definitions()
        )

    except openai.APIError as e:
        print(f"OpenAI API error: {e}")
    except Exception as e:
        print(f"Unexpected error: {e}")
```

```typescript JavaScript Error Handling
import OpenAI from "openai"
import { getToolDefinitions } from "@supermemory/tools/openai"

async function safeChat() {
  try {
    const client = new OpenAI()

    const response = await client.chat.completions.create({
      model: "gpt-5",
      messages: [{ role: "user", content: "Hello" }],
      tools: getToolDefinitions(),
    })

  } catch (error) {
    if (error instanceof OpenAI.APIError) {
      console.error("OpenAI API error:", error.message)
    } else {
      console.error("Unexpected error:", error)
    }
  }
}
```

</CodeGroup>

## API Reference

### Python SDK

#### `SupermemoryTools`

**Constructor**
```python
SupermemoryTools(
    api_key: str,
    config: Optional[SupermemoryToolsConfig] = None
)
```

**Methods**
- `get_tool_definitions()` - Get OpenAI function definitions
- `search_memories(information_to_get, limit, include_full_docs)` - Search user memories
- `add_memory(memory)` - Add new memory
- `execute_tool_call(tool_call)` - Execute individual tool call

#### `execute_memory_tool_calls`

```python
execute_memory_tool_calls(
    api_key: str,
    tool_calls: List[ToolCall],
    config: Optional[SupermemoryToolsConfig] = None
) -> List[dict]
```

### JavaScript SDK

#### `supermemoryTools`

```typescript
supermemoryTools(
  apiKey: string,
  config?: { projectId?: string; baseUrl?: string }
)
```

#### `createToolCallExecutor`

```typescript
createToolCallExecutor(
  apiKey: string,
  config?: { projectId?: string; baseUrl?: string }
) -> (toolCall: OpenAI.Chat.ChatCompletionMessageToolCall) => Promise<any>
```

## Environment Variables

Set these environment variables:

```bash
SUPERMEMORY_API_KEY=your_supermemory_key
OPENAI_API_KEY=your_openai_key
SUPERMEMORY_BASE_URL=https://custom-endpoint.com  # optional
```

## Development

### Python Setup

```bash
# Install uv
curl -LsSf https://astral.sh/uv/install.sh | sh

# Setup project
git clone <repository-url>
cd packages/openai-sdk-python
uv sync --dev

# Run tests
uv run pytest

# Type checking
uv run mypy src/supermemory_openai

# Formatting
uv run black src/ tests/
uv run isort src/ tests/
```

### JavaScript Setup

```bash
# Install dependencies
npm install

# Run tests
npm test

# Type checking
npm run type-check

# Linting
npm run lint
```

## Next Steps

<CardGroup cols={2}>
  <Card title="AI SDK Integration" icon="triangle" href="/integrations/ai-sdk">
    Use with Vercel AI SDK for streamlined development
  </Card>

  <Card title="Memory API" icon="database" href="/memory-api/overview">
    Direct API access for advanced memory management
  </Card>
</CardGroup>