supermemory/apps/docs/integrations/openai.mdx
MaheshtheDev 7900bceb81 fix(tools): keep the OpenAI memory tag out of serialized history by default
The supermemory field on returned Chat messages and Responses output items
was enumerable, so history replayed through an unwrapped client or a proxy
carried it, and the Responses API rejects it with
400 "Unknown parameter: 'input[1].supermemory'". The field is now
non-enumerable: the wrapper still reads it from the objects pushed back, but
JSON drops it. serializeMemoryBlocks: true makes it enumerable again for apps
that store history as JSON and replay it only through the wrapper.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
2026-11-26 17:22:29 +00:00

690 lines
19 KiB
Text

---
title: "OpenAI SDK"
sidebarTitle: "OpenAI SDK"
description: "Memory tools for OpenAI function calling with Supermemory integration"
icon: "/images/openai.svg"
---
import MigrateCli from "/snippets/migrate-cli.mdx";
Add memory capabilities to the official OpenAI SDKs using Supermemory. Two approaches available:
1. **`withSupermemory` wrapper** - Automatic memory injection into each user turn (zero-config)
2. **Function calling tools** - Explicit tool calls for search/add memory operations
<MigrateCli legacy="@supermemory/tools 2.x" guideHref="/migration/tools-v3-upgrade" guideLabel="3.0 upgrade guide" />
<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="/icons/hugeicons/package.svg" href="https://www.npmjs.com/package/@supermemory/tools">
Check out the NPM page for more details
</Card>
<Card title="Supermemory AI SDK" icon="/icons/hugeicons/python.svg" 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 add relevant memories to each user turn, leaving your system prompt untouched so provider prompt caching keeps working.
### 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 are added to each user turn
const client = withSupermemory(openai, {
namespace: "user-123", // Required: identifies the user/container
id: "conversation-456", // Required: groups messages into the same document
mode: "full", // "profile" | "query" | "full"
addMemory: "always", // "always" (default) | "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, {
// Required: identifies the user/container
namespace: "user-123",
// Required: Group messages into the same document
id: "conv-456",
// Memory search mode
mode: "full", // "profile" (user profile only), "query" (search only), "full" (both)
// Auto-save conversations as memories (default: "always")
addMemory: "always", // "always" | "never"
// Enable debug logging
verbose: true,
// Custom API endpoint
baseUrl: "https://custom.api.com"
})
```
### Prompt caching
Each user turn gets one recall (profile and search, per `mode`), sent as a separate user message after your latest user message, leaving out memories an earlier restored block already shows; your system prompt, `instructions` and messages are never changed. The returned assistant message (Chat Completions, non-streaming) or first output item (Responses) carries that block, signed, in a non-enumerable `supermemory` field. Push that object into your history as is, and the wrapper puts the block back in front of it, so earlier turns are re-sent byte for byte and tool-call steps reuse it. With `previous_response_id` or a conversation, OpenAI keeps the block in its stored history and nothing is tagged. The wrapper holds nothing between calls, so a new wrapper per request is fine. A block with a missing or bad signature (an HMAC keyed by your Supermemory API key) is ignored, and history without one just gets a fresh recall each turn.
`JSON.stringify` drops the non-enumerable field, so history you store as JSON and replay through another client or provider never carries it, but it also gets a fresh recall each turn instead of its restored blocks. To keep the blocks in stored history, set `serializeMemoryBlocks: true`. The field then survives JSON, so replay that history only through the wrapped client, or delete the field first: the Responses API and strict OpenAI-compatible servers reject it with a 400.
Recall has a 3 second budget with no retries. If it fails or runs out, the model call goes ahead without memories for that turn. When `addMemory` is `"always"`, the finished turn is saved once after the model's final answer, in the background, and system and developer messages are never saved.
### 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, { namespace: "user-123", id: "conv-456", mode: "full" })
// Memories are added to the user input; instructions are left untouched
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!, {
namespace: "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!, {
namespace: "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,
)
print(f"Found {result.get('count', 0)} memories")
```
```typescript JavaScript
// Search memories
const searchResult = await tools.searchMemories({
informationToGet: "user preferences",
limit: 10,
})
console.log(`Found ${searchResult.count} 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"
)
memory = result.get("memory") or {}
print(f"Added memory with ID: {memory.get('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!, {
namespace: "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: 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=10)` - Search user memories. Pass `limit` by keyword: the second positional parameter is the deprecated, ignored `include_full_docs`
- `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]
```
#### `with_supermemory`
```python
from openai import OpenAI
from supermemory_openai import with_supermemory, OpenAIMiddlewareOptions
client = with_supermemory(
OpenAI(),
OpenAIMiddlewareOptions(
container_tag="user-123", # identifies the user
custom_id="conversation-456", # one wrapper per conversation
mode="full", # "profile" (default) | "query" | "full"
add_memory="always", # "always" (default) | "never"
),
)
```
Wraps a sync or async OpenAI client's `chat.completions.create`. The Python wrapper places memories so the provider's prompt cache keeps working. The user's profile is fetched once per conversation and appended to the first system or developer message as a separate block, byte-identical on every later call. Each new user message gets its own search results appended to it, and earlier messages are re-sent with exactly the block they got the first time. Tool-call steps reuse their turn's memories and never search again.
Recall has a 3 second budget with no retries. If it fails or runs out, the model call goes ahead without memories, and a failed profile is fetched again on the next user message. When `add_memory` is `"always"`, each turn is saved once in the background after the model's final reply, and system and developer messages are never saved.
### JavaScript SDK
#### `supermemoryTools`
```typescript
supermemoryTools(
apiKey: string,
config?: { namespace?: string; baseUrl?: string }
)
```
#### `createToolCallExecutor`
```typescript
createToolCallExecutor(
apiKey: string,
config?: { namespace?: string; baseUrl?: string }
) -> (toolCall: OpenAI.Chat.ChatCompletionMessageToolCall) => Promise<string> // JSON-encoded result
```
## 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, Python only; in TypeScript pass baseUrl
```
## 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 check-types
```
## Next steps
<CardGroup cols={2}>
<Card title="AI SDK integration" icon="/icons/hugeicons/triangle.svg" href="/integrations/ai-sdk">
Use with Vercel AI SDK for streamlined development
</Card>
<Card title="Add memories" icon="/icons/hugeicons/database-01.svg" href="/ingestion/add-memories">
Direct API access for advanced memory management
</Card>
</CardGroup>