Big News: Socket raises $60M Series C at a $1B valuation to secure software supply chains for AI-driven development.Announcement
Sign In

@supermemory/tools

Package Overview
Dependencies
Maintainers
1
Versions
45
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@supermemory/tools - npm Package Compare versions

Comparing version
1.3.13
to
1.3.14
+273
dist/index-CSb8j3hw.d.ts
import { SupermemoryToolsConfig } from "./types-B1x7Kbsa.js";
import Supermemory from "supermemory";
import OpenAI from "openai";
//#region src/openai/middleware.d.ts
interface OpenAIMiddlewareOptions {
conversationId?: string;
verbose?: boolean;
mode?: "profile" | "query" | "full";
addMemory?: "always" | "never";
baseUrl?: string;
}
/**
* Creates SuperMemory middleware for OpenAI clients.
*
* This function creates middleware that automatically injects relevant memories
* into OpenAI chat completions and optionally saves new memories. The middleware
* can wrap existing OpenAI clients or create new ones with SuperMemory capabilities.
*
* @param containerTag - The container tag/identifier for memory search (e.g., user ID, project ID)
* @param options - Optional configuration options for the middleware
* @param options.conversationId - Optional conversation ID to group messages for contextual memory generation
* @param options.verbose - Enable detailed logging of memory operations (default: false)
* @param options.mode - Memory search mode: "profile" (all memories), "query" (search-based), or "full" (both) (default: "profile")
* @param options.addMemory - Automatic memory storage mode: "always" or "never" (default: "never")
* @returns Object with `wrapClient` and `createClient` methods
* @throws {Error} When SUPERMEMORY_API_KEY environment variable is not set
*
* @example
* ```typescript
* const openaiWithSupermemory = createOpenAIMiddleware(openai, "user-123", {
* conversationId: "conversation-456",
* mode: "full",
* addMemory: "always",
* verbose: true
* })
*
* ```
*/
//#endregion
//#region src/openai/tools.d.ts
/**
* Result types for memory operations
*/
interface MemorySearchResult {
success: boolean;
results?: Awaited<ReturnType<Supermemory["search"]["execute"]>>["results"];
count?: number;
error?: string;
}
interface MemoryAddResult {
success: boolean;
memory?: Awaited<ReturnType<Supermemory["memories"]["add"]>>;
error?: string;
}
/**
* Function schemas for OpenAI function calling
*/
declare const memoryToolSchemas: {
readonly searchMemories: {
name: string;
description: "Search (recall) memories/details/information about the user or other facts or entities. Run when explicitly asked or when context about user's past choices would be helpful.";
parameters: {
type: string;
properties: {
informationToGet: {
type: string;
description: "Terms to search for in the user's memories";
};
includeFullDocs: {
type: string;
description: "Whether to include the full document content in the response. Defaults to true for better AI context.";
default: true;
};
limit: {
type: string;
description: "Maximum number of results to return";
default: 10;
};
};
required: string[];
};
};
readonly addMemory: {
name: string;
description: "Add (remember) memories/details/information about the user or other facts or entities. Run when explicitly asked or when the user mentions any information generalizable beyond the context of the current conversation.";
parameters: {
type: string;
properties: {
memory: {
type: string;
description: "The text content of the memory to add. This should be a single sentence or a short paragraph.";
};
};
required: string[];
};
};
};
/**
* Search memories function
*/
declare function createSearchMemoriesFunction(apiKey: string, config?: SupermemoryToolsConfig): ({
informationToGet,
includeFullDocs,
limit
}: {
informationToGet: string;
includeFullDocs?: boolean;
limit?: number;
}) => Promise<MemorySearchResult>;
/**
* Add memory function
*/
declare function createAddMemoryFunction(apiKey: string, config?: SupermemoryToolsConfig): ({
memory
}: {
memory: string;
}) => Promise<MemoryAddResult>;
/**
* Create all memory tools functions
*/
declare function supermemoryTools(apiKey: string, config?: SupermemoryToolsConfig): {
searchMemories: ({
informationToGet,
includeFullDocs,
limit
}: {
informationToGet: string;
includeFullDocs?: boolean;
limit?: number;
}) => Promise<MemorySearchResult>;
addMemory: ({
memory
}: {
memory: string;
}) => Promise<MemoryAddResult>;
};
/**
* Get OpenAI function definitions for all memory tools
*/
declare function getToolDefinitions(): OpenAI.Chat.Completions.ChatCompletionTool[];
/**
* Execute a tool call based on the function name and arguments
*/
declare function createToolCallExecutor(apiKey: string, config?: SupermemoryToolsConfig): (toolCall: OpenAI.Chat.Completions.ChatCompletionMessageToolCall) => Promise<string>;
/**
* Execute tool calls from OpenAI function calling
*/
declare function createToolCallsExecutor(apiKey: string, config?: SupermemoryToolsConfig): (toolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => Promise<OpenAI.Chat.Completions.ChatCompletionToolMessageParam[]>;
/**
* Individual tool creators for more granular control
*/
declare function createSearchMemoriesTool(apiKey: string, config?: SupermemoryToolsConfig): {
definition: {
type: "function";
function: {
name: string;
description: "Search (recall) memories/details/information about the user or other facts or entities. Run when explicitly asked or when context about user's past choices would be helpful.";
parameters: {
type: string;
properties: {
informationToGet: {
type: string;
description: "Terms to search for in the user's memories";
};
includeFullDocs: {
type: string;
description: "Whether to include the full document content in the response. Defaults to true for better AI context.";
default: true;
};
limit: {
type: string;
description: "Maximum number of results to return";
default: 10;
};
};
required: string[];
};
};
};
execute: ({
informationToGet,
includeFullDocs,
limit
}: {
informationToGet: string;
includeFullDocs?: boolean;
limit?: number;
}) => Promise<MemorySearchResult>;
};
declare function createAddMemoryTool(apiKey: string, config?: SupermemoryToolsConfig): {
definition: {
type: "function";
function: {
name: string;
description: "Add (remember) memories/details/information about the user or other facts or entities. Run when explicitly asked or when the user mentions any information generalizable beyond the context of the current conversation.";
parameters: {
type: string;
properties: {
memory: {
type: string;
description: "The text content of the memory to add. This should be a single sentence or a short paragraph.";
};
};
required: string[];
};
};
};
execute: ({
memory
}: {
memory: string;
}) => Promise<MemoryAddResult>;
};
//#endregion
//#region src/openai/index.d.ts
/**
* Wraps an OpenAI client with SuperMemory middleware to automatically inject relevant memories
* into both Chat Completions and Responses APIs based on the user's input content.
*
* For Chat Completions API: Searches for memories using the user message content and injects
* them into the system prompt (appends to existing or creates new system prompt).
*
* For Responses API: Searches for memories using the input parameter and injects them into
* the instructions parameter (appends to existing or creates new instructions).
*
* @param openaiClient - The OpenAI client to wrap with SuperMemory middleware
* @param containerTag - The container tag/identifier for memory search (e.g., user ID, project ID)
* @param options - Optional configuration options for the middleware
* @param options.conversationId - Optional conversation ID to group messages into a single document for contextual memory generation
* @param options.verbose - Optional flag to enable detailed logging of memory search and injection process (default: false)
* @param options.mode - Optional mode for memory search: "profile" (default), "query", or "full"
* @param options.addMemory - Optional mode for memory addition: "always", "never" (default)
*
* @returns An OpenAI client with SuperMemory middleware injected for both Chat Completions and Responses APIs
*
* @example
* ```typescript
* import { withSupermemory } from "@supermemory/tools/openai"
* import OpenAI from "openai"
*
* // Create OpenAI client with supermemory middleware
* const openai = new OpenAI({
* apiKey: process.env.OPENAI_API_KEY,
* })
* const openaiWithSupermemory = withSupermemory(openai, "user-123", {
* conversationId: "conversation-456",
* mode: "full",
* addMemory: "always"
* })
*
* // Use with Chat Completions API - memories injected into system prompt
* const chatResponse = await openaiWithSupermemory.chat.completions.create({
* model: "gpt-4",
* messages: [
* { role: "user", content: "What's my favorite programming language?" }
* ]
* })
*
* // Use with Responses API - memories injected into instructions
* const response = await openaiWithSupermemory.responses.create({
* model: "gpt-4o",
* instructions: "You are a helpful coding assistant",
* input: "What's my favorite programming language?"
* })
* ```
*
* @throws {Error} When SUPERMEMORY_API_KEY environment variable is not set
* @throws {Error} When supermemory API request fails
*/
declare function withSupermemory(openaiClient: OpenAI, containerTag: string, options?: OpenAIMiddlewareOptions): OpenAI;
//#endregion
export { type MemoryAddResult, type MemorySearchResult, type OpenAIMiddlewareOptions, createAddMemoryFunction, createAddMemoryTool, createSearchMemoriesFunction, createSearchMemoriesTool, createToolCallExecutor, createToolCallsExecutor, getToolDefinitions, memoryToolSchemas, supermemoryTools, withSupermemory };
+1
-0

@@ -13,2 +13,3 @@ import { SupermemoryToolsConfig } from "./types-B1x7Kbsa.js";

apiKey?: string;
baseUrl?: string;
}

@@ -15,0 +16,0 @@ /**

+3
-3

@@ -1,4 +0,4 @@

import{DEFAULT_VALUES as e,PARAMETER_DESCRIPTIONS as t,TOOL_DESCRIPTIONS as n,getContainerTags as r}from"./shared-CttEw8ws.js";import{convertProfileToMarkdown as i,createLogger as a,filterOutSupermemories as o,getLastUserMessage as s}from"./util-D4fsPgmW.js";import c from"supermemory";import{tool as l,wrapLanguageModel as u}from"ai";import{z as d}from"zod";const f=async(e,t)=>{let n=t?JSON.stringify({q:t,containerTag:e}):JSON.stringify({containerTag:e});try{let e=await fetch(`https://api.supermemory.ai/v4/profile`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${process.env.SUPERMEMORY_API_KEY}`},body:n});if(!e.ok){let t=await e.text().catch(()=>`Unknown error`);throw Error(`Supermemory profile search failed: ${e.status} ${e.statusText}. ${t}`)}return await e.json()}catch(e){throw e instanceof Error?e:Error(`Supermemory API request failed: ${e}`)}},p=async(e,t,n,r)=>{let a=e.prompt.some(e=>e.role===`system`),o=r===`profile`?``:e.prompt.slice().reverse().find(e=>e.role===`user`)?.content?.filter(e=>e.type===`text`)?.map(e=>e.type===`text`?e.text:``)?.join(` `)||``,s=await f(t,o),c=s.profile.static?.length||0,l=s.profile.dynamic?.length||0;n.info(`Memory search completed`,{containerTag:t,memoryCountStatic:c,memoryCountDynamic:l,queryText:o.substring(0,100)+(o.length>100?`...`:``),mode:r});let u=r===`query`?``:i(s),d=r===`profile`?``:`Search results for user's recent message: \n${s.searchResults.results.map(e=>`- ${e.memory}`).join(`
`)}`,p=`User Supermemories: \n${u}\n${d}`.trim();return p&&n.debug(`Memory content preview`,{content:p,fullLength:p.length}),a?(n.debug(`Added memories to existing system prompt`),{...e,prompt:e.prompt.map(e=>e.role===`system`?{...e,content:`${e.content} \n ${p}`}:e)}):(n.debug(`System prompt does not exist, created system prompt with memories`),{...e,prompt:[{role:`system`,content:p},...e.prompt]})},m=e=>e.prompt.filter(e=>e.role!==`system`&&e.role!==`tool`).map(e=>{let t=e.role===`user`?`User`:`Assistant`;if(typeof e.content==`string`)return`${t}: ${o(e.content)}`;let n=e.content.filter(e=>e.type===`text`).map(e=>e.type===`text`?o(e.text):``).join(` `);return`${t}: ${n}`}).join(`
import{DEFAULT_VALUES as e,PARAMETER_DESCRIPTIONS as t,TOOL_DESCRIPTIONS as n,getContainerTags as r}from"./shared-CttEw8ws.js";import{convertProfileToMarkdown as i,createLogger as a,filterOutSupermemories as o,getLastUserMessage as s}from"./util-D4fsPgmW.js";import c from"supermemory";import{tool as l,wrapLanguageModel as u}from"ai";import{z as d}from"zod";const f=e=>e?e.endsWith(`/`)?e.slice(0,-1):e:`https://api.supermemory.ai`,p=async(e,t,n)=>{let r=t?JSON.stringify({q:t,containerTag:e}):JSON.stringify({containerTag:e});try{let e=await fetch(`${n}/v4/profile`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${process.env.SUPERMEMORY_API_KEY}`},body:r});if(!e.ok){let t=await e.text().catch(()=>`Unknown error`);throw Error(`Supermemory profile search failed: ${e.status} ${e.statusText}. ${t}`)}return await e.json()}catch(e){throw e instanceof Error?e:Error(`Supermemory API request failed: ${e}`)}},m=async(e,t,n,r,a)=>{let o=e.prompt.some(e=>e.role===`system`),s=r===`profile`?``:e.prompt.slice().reverse().find(e=>e.role===`user`)?.content?.filter(e=>e.type===`text`)?.map(e=>e.type===`text`?e.text:``)?.join(` `)||``,c=await p(t,s,a),l=c.profile.static?.length||0,u=c.profile.dynamic?.length||0;n.info(`Memory search completed`,{containerTag:t,memoryCountStatic:l,memoryCountDynamic:u,queryText:s.substring(0,100)+(s.length>100?`...`:``),mode:r});let d=r===`query`?``:i(c),f=r===`profile`?``:`Search results for user's recent message: \n${c.searchResults.results.map(e=>`- ${e.memory}`).join(`
`)}`,m=`User Supermemories: \n${d}\n${f}`.trim();return m&&n.debug(`Memory content preview`,{content:m,fullLength:m.length}),o?(n.debug(`Added memories to existing system prompt`),{...e,prompt:e.prompt.map(e=>e.role===`system`?{...e,content:`${e.content} \n ${m}`}:e)}):(n.debug(`System prompt does not exist, created system prompt with memories`),{...e,prompt:[{role:`system`,content:m},...e.prompt]})},h=e=>e.prompt.filter(e=>e.role!==`system`&&e.role!==`tool`).map(e=>{let t=e.role===`user`?`User`:`Assistant`;if(typeof e.content==`string`)return`${t}: ${o(e.content)}`;let n=e.content.filter(e=>e.type===`text`).map(e=>e.type===`text`?o(e.text):``).join(` `);return`${t}: ${n}`}).join(`
`),h=async(e,t,n,r,i,a)=>{let o=s(i),c=n?`${m(i)} \n\n Assistant: ${r}`:`User: ${o} \n\n Assistant: ${r}`,l=n?`conversation:${n}`:void 0;try{let n=await e.memories.add({content:c,containerTags:[t],customId:l});a.info(`Memory saved successfully`,{containerTag:t,customId:l,content:c,contentLength:c.length,memoryId:n.id})}catch(e){a.error(`Error saving memory`,{error:e instanceof Error?e.message:`Unknown error`})}},g=(e,t,n,r=!1,i=`profile`,o=`never`)=>{let l=a(r),u=new c({apiKey:t});return{transformParams:async({params:t})=>{let r=s(t);return i!==`profile`&&!r?(l.debug(`No user message found, skipping memory search`),t):(l.info(`Starting memory search`,{containerTag:e,conversationId:n,mode:i}),await p(t,e,l,i))},wrapGenerate:async({doGenerate:t,params:r})=>{let i=s(r);try{let a=await t(),s=a.content.map(e=>e.type===`text`?e.text:``).join(``);return o===`always`&&i&&i.trim()&&h(u,e,n,s,r,l),a}catch(e){throw l.error(`Error generating response`,{error:e instanceof Error?e.message:`Unknown error`}),e}},wrapStream:async({doStream:t,params:r})=>{let i=s(r),a=``;try{let{stream:s,...c}=await t(),d=new TransformStream({transform(e,t){e.type===`text-delta`&&(a+=e.delta),t.enqueue(e)},flush:async()=>{a&&[].push({type:`text`,text:a}),o===`always`&&i&&i.trim()&&h(u,e,n,a,r,l)}});return{stream:s.pipeThrough(d),...c}}catch(e){throw l.error(`Error streaming response`,{error:e instanceof Error?e.message:`Unknown error`}),e}}}},_=(e,t,n)=>{let r=n?.apiKey??process.env.SUPERMEMORY_API_KEY;if(!r)throw Error("SUPERMEMORY_API_KEY is not set — provide it via `options.apiKey` or set `process.env.SUPERMEMORY_API_KEY`");let i=n?.conversationId,a=n?.verbose??!1,o=n?.mode??`profile`,s=n?.addMemory??`never`;return u({model:e,middleware:g(t,r,i,a,o,s)})},v=(i,a)=>{let o=new c({apiKey:i,...a?.baseUrl?{baseURL:a.baseUrl}:{}}),s=r(a);return l({description:n.searchMemories,inputSchema:d.object({informationToGet:d.string().describe(t.informationToGet),includeFullDocs:d.boolean().optional().default(e.includeFullDocs).describe(t.includeFullDocs),limit:d.number().optional().default(e.limit).describe(t.limit)}),execute:async({informationToGet:t,includeFullDocs:n=e.includeFullDocs,limit:r=e.limit})=>{try{let i=await o.search.execute({q:t,containerTags:s,limit:r,chunkThreshold:e.chunkThreshold,includeFullDocs:n});return{success:!0,results:i.results,count:i.results?.length||0}}catch(e){return{success:!1,error:e instanceof Error?e.message:`Unknown error`}}}})},y=(e,i)=>{let a=new c({apiKey:e,...i?.baseUrl?{baseURL:i.baseUrl}:{}}),o=r(i);return l({description:n.addMemory,inputSchema:d.object({memory:d.string().describe(t.memory)}),execute:async({memory:e})=>{try{let t={};return{success:!0,memory:await a.memories.add({content:e,containerTags:o,...Object.keys(t).length>0&&{metadata:t}})}}catch(e){return{success:!1,error:e instanceof Error?e.message:`Unknown error`}}}})};function b(e,t){return{searchMemories:v(e,t),addMemory:y(e,t)}}export{y as addMemoryTool,v as searchMemoriesTool,b as supermemoryTools,_ as withSupermemory};
`),g=async(e,t,n,r,i,a)=>{let o=s(i),c=n?`${h(i)} \n\n Assistant: ${r}`:`User: ${o} \n\n Assistant: ${r}`,l=n?`conversation:${n}`:void 0;try{let n=await e.memories.add({content:c,containerTags:[t],customId:l});a.info(`Memory saved successfully`,{containerTag:t,customId:l,content:c,contentLength:c.length,memoryId:n.id})}catch(e){a.error(`Error saving memory`,{error:e instanceof Error?e.message:`Unknown error`})}},_=(e,t,n,r=!1,i=`profile`,o=`never`,l=`https://api.supermemory.ai`)=>{let u=a(r),d=f(l),p=new c({apiKey:t,...d===`https://api.supermemory.ai`?{}:{baseURL:d}});return{transformParams:async({params:t})=>{let r=s(t);return i!==`profile`&&!r?(u.debug(`No user message found, skipping memory search`),t):(u.info(`Starting memory search`,{containerTag:e,conversationId:n,mode:i}),await m(t,e,u,i,d))},wrapGenerate:async({doGenerate:t,params:r})=>{let i=s(r);try{let a=await t(),s=a.content.map(e=>e.type===`text`?e.text:``).join(``);return o===`always`&&i&&i.trim()&&g(p,e,n,s,r,u),a}catch(e){throw u.error(`Error generating response`,{error:e instanceof Error?e.message:`Unknown error`}),e}},wrapStream:async({doStream:t,params:r})=>{let i=s(r),a=``;try{let{stream:s,...c}=await t(),l=new TransformStream({transform(e,t){e.type===`text-delta`&&(a+=e.delta),t.enqueue(e)},flush:async()=>{a&&[].push({type:`text`,text:a}),o===`always`&&i&&i.trim()&&g(p,e,n,a,r,u)}});return{stream:s.pipeThrough(l),...c}}catch(e){throw u.error(`Error streaming response`,{error:e instanceof Error?e.message:`Unknown error`}),e}}}},v=(e,t,n)=>{let r=n?.apiKey??process.env.SUPERMEMORY_API_KEY;if(!r)throw Error("SUPERMEMORY_API_KEY is not set — provide it via `options.apiKey` or set `process.env.SUPERMEMORY_API_KEY`");let i=n?.conversationId,a=n?.verbose??!1,o=n?.mode??`profile`,s=n?.addMemory??`never`,c=n?.baseUrl;return u({model:e,middleware:_(t,r,i,a,o,s,c)})},y=(i,a)=>{let o=new c({apiKey:i,...a?.baseUrl?{baseURL:a.baseUrl}:{}}),s=r(a);return l({description:n.searchMemories,inputSchema:d.object({informationToGet:d.string().describe(t.informationToGet),includeFullDocs:d.boolean().optional().default(e.includeFullDocs).describe(t.includeFullDocs),limit:d.number().optional().default(e.limit).describe(t.limit)}),execute:async({informationToGet:t,includeFullDocs:n=e.includeFullDocs,limit:r=e.limit})=>{try{let i=await o.search.execute({q:t,containerTags:s,limit:r,chunkThreshold:e.chunkThreshold,includeFullDocs:n});return{success:!0,results:i.results,count:i.results?.length||0}}catch(e){return{success:!1,error:e instanceof Error?e.message:`Unknown error`}}}})},b=(e,i)=>{let a=new c({apiKey:e,...i?.baseUrl?{baseURL:i.baseUrl}:{}}),o=r(i);return l({description:n.addMemory,inputSchema:d.object({memory:d.string().describe(t.memory)}),execute:async({memory:e})=>{try{let t={};return{success:!0,memory:await a.memories.add({content:e,containerTags:o,...Object.keys(t).length>0&&{metadata:t}})}}catch(e){return{success:!1,error:e instanceof Error?e.message:`Unknown error`}}}})};function x(e,t){return{searchMemories:y(e,t),addMemory:b(e,t)}}export{b as addMemoryTool,y as searchMemoriesTool,x as supermemoryTools,v as withSupermemory};
import { SupermemoryToolsConfig } from "./types-B1x7Kbsa.js";
import { OpenAIMiddlewareOptions } from "./index-BOj_YK4D.js";
import { OpenAIMiddlewareOptions } from "./index-CSb8j3hw.js";
export { type OpenAIMiddlewareOptions, type SupermemoryToolsConfig };
import "../types-B1x7Kbsa.js";
import { MemoryAddResult, MemorySearchResult, OpenAIMiddlewareOptions, createAddMemoryFunction, createAddMemoryTool, createSearchMemoriesFunction, createSearchMemoriesTool, createToolCallExecutor, createToolCallsExecutor, getToolDefinitions, memoryToolSchemas, supermemoryTools, withSupermemory } from "../index-BOj_YK4D.js";
import { MemoryAddResult, MemorySearchResult, OpenAIMiddlewareOptions, createAddMemoryFunction, createAddMemoryTool, createSearchMemoriesFunction, createSearchMemoriesTool, createToolCallExecutor, createToolCallsExecutor, getToolDefinitions, memoryToolSchemas, supermemoryTools, withSupermemory } from "../index-CSb8j3hw.js";
export { MemoryAddResult, MemorySearchResult, OpenAIMiddlewareOptions, createAddMemoryFunction, createAddMemoryTool, createSearchMemoriesFunction, createSearchMemoriesTool, createToolCallExecutor, createToolCallsExecutor, getToolDefinitions, memoryToolSchemas, supermemoryTools, withSupermemory };

@@ -1,4 +0,5 @@

import{DEFAULT_VALUES as e,PARAMETER_DESCRIPTIONS as t,TOOL_DESCRIPTIONS as n,getContainerTags as r}from"../shared-CttEw8ws.js";import{convertProfileToMarkdown as i,createLogger as a}from"../util-D4fsPgmW.js";import o from"supermemory";const s=e=>{let t=e.slice().reverse().find(e=>e.role===`user`);return typeof t?.content==`string`?t.content:``},c=async(e,t)=>{let n=t?JSON.stringify({q:t,containerTag:e}):JSON.stringify({containerTag:e});try{let e=await fetch(`https://api.supermemory.ai/v4/profile`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${process.env.SUPERMEMORY_API_KEY}`},body:n});if(!e.ok){let t=await e.text().catch(()=>`Unknown error`);throw Error(`Supermemory profile search failed: ${e.status} ${e.statusText}. ${t}`)}return await e.json()}catch(e){throw e instanceof Error?e:Error(`Supermemory API request failed: ${e}`)}},l=async(e,t,n,r)=>{let i=e.some(e=>e.role===`system`),a=r===`profile`?``:s(e),o=await searchAndFormatMemories(a,t,n,r,`chat`);return i?(n.debug(`Added memories to existing system prompt`),e.map(e=>e.role===`system`?{...e,content:`${e.content} \n ${o}`}:e)):(n.debug(`System prompt does not exist, created system prompt with memories`),[{role:`system`,content:o},...e])},u=e=>e.map(e=>{let t=e.role===`user`?`User`:`Assistant`,n=typeof e.content==`string`?e.content:``;return`${t}: ${n}`}).join(`
import{DEFAULT_VALUES as e,PARAMETER_DESCRIPTIONS as t,TOOL_DESCRIPTIONS as n,getContainerTags as r}from"../shared-CttEw8ws.js";import{convertProfileToMarkdown as i,createLogger as a}from"../util-D4fsPgmW.js";import o from"supermemory";const s=e=>e?e.endsWith(`/`)?e.slice(0,-1):e:`https://api.supermemory.ai`,c=e=>{let t=e.slice().reverse().find(e=>e.role===`user`);return typeof t?.content==`string`?t.content:``},l=async(e,t,n)=>{let r=t?JSON.stringify({q:t,containerTag:e}):JSON.stringify({containerTag:e});try{let e=await fetch(`${n}/v4/profile`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${process.env.SUPERMEMORY_API_KEY}`},body:r});if(!e.ok){let t=await e.text().catch(()=>`Unknown error`);throw Error(`Supermemory profile search failed: ${e.status} ${e.statusText}. ${t}`)}return await e.json()}catch(e){throw e instanceof Error?e:Error(`Supermemory API request failed: ${e}`)}},u=async(e,t,n,r,a)=>{let o=e.some(e=>e.role===`system`),s=r===`profile`?``:c(e),u=await l(t,s,a),d=u.profile.static?.length||0,f=u.profile.dynamic?.length||0;n.info(`Memory search completed for chat API`,{containerTag:t,memoryCountStatic:d,memoryCountDynamic:f,queryText:s.substring(0,100)+(s.length>100?`...`:``),mode:r});let p=r===`query`?``:i({profile:{static:u.profile.static?.map(e=>e.memory),dynamic:u.profile.dynamic?.map(e=>e.memory)},searchResults:{results:u.searchResults.results.map(e=>({memory:e.memory}))}}),m=r===`profile`?``:`Search results for user's recent message: \n${u.searchResults.results.map(e=>`- ${e.memory}`).join(`
`)}`,h=`${p}\n${m}`.trim();return h&&n.debug(`Memory content preview for chat API`,{content:h,fullLength:h.length}),o?(n.debug(`Added memories to existing system prompt`),e.map(e=>e.role===`system`?{...e,content:`${e.content} \n ${h}`}:e)):(n.debug(`System prompt does not exist, created system prompt with memories`),[{role:`system`,content:h},...e])},d=e=>e.map(e=>{let t=e.role===`user`?`User`:`Assistant`,n=typeof e.content==`string`?e.content:``;return`${t}: ${n}`}).join(`
`),d=async(e,t,n,r,i)=>{try{let a=await e.memories.add({content:n,containerTags:[t],customId:r});i.info(`Memory saved successfully`,{containerTag:t,customId:r,contentLength:n.length,memoryId:a.id})}catch(e){i.error(`Error saving memory`,{error:e instanceof Error?e.message:`Unknown error`})}};function f(e,t,n){let r=a(n?.verbose??!1),f=new o({apiKey:process.env.SUPERMEMORY_API_KEY}),p=n?.conversationId,m=n?.mode??`profile`,h=n?.addMemory??`never`,g=e.chat.completions.create,_=e.responses?.create,v=async(e,t,n,r,a)=>{let o=await c(t,e),s=o.profile.static?.length||0,l=o.profile.dynamic?.length||0;n.info(`Memory search completed for ${a} API`,{containerTag:t,memoryCountStatic:s,memoryCountDynamic:l,queryText:e.substring(0,100)+(e.length>100?`...`:``),mode:r});let u=r===`query`?``:i({profile:{static:o.profile.static?.map(e=>e.memory),dynamic:o.profile.dynamic?.map(e=>e.memory)},searchResults:{results:o.searchResults.results.map(e=>({memory:e.memory}))}}),d=r===`profile`?``:`Search results for user's ${a===`chat`?`recent message`:`input`}: \n${o.searchResults.results.map(e=>`- ${e.memory}`).join(`
`)}`,f=`${u}\n${d}`.trim();return f&&n.debug(`Memory content preview for ${a} API`,{content:f,fullLength:f.length}),f},y=async n=>{if(!_)throw Error(`Responses API is not available in this OpenAI client version`);let i=typeof n.input==`string`?n.input:``;if(m!==`profile`&&!i)return r.debug(`No input found for Responses API, skipping memory search`),_.call(e.responses,n);r.info(`Starting memory search for Responses API`,{containerTag:t,conversationId:p,mode:m});let a=[];if(h===`always`&&i?.trim()){let e=p?`Input: ${i}`:i,n=p?`conversation:${p}`:void 0;a.push(d(f,t,e,n,r))}let o=m===`profile`?``:i;a.push(v(o,t,r,m,`responses`));let s=await Promise.all(a),c=s[s.length-1],l=c?`${n.instructions||``}\n\n${c}`.trim():n.instructions;return _.call(e.responses,{...n,instructions:l})},b=async n=>{let i=Array.isArray(n.messages)?n.messages:[];if(m!==`profile`&&!s(i))return r.debug(`No user message found, skipping memory search`),g.call(e.chat.completions,n);r.info(`Starting memory search`,{containerTag:t,conversationId:p,mode:m});let a=[];if(h===`always`){let e=s(i);if(e?.trim()){let n=p?u(i):e,o=p?`conversation:${p}`:void 0;a.push(d(f,t,n,o,r))}}a.push(l(i,t,r,m));let o=await Promise.all(a),c=o[o.length-1];return g.call(e.chat.completions,{...n,messages:c})};return e.chat.completions.create=b,_&&(e.responses.create=y),e}const p={searchMemories:{name:`searchMemories`,description:n.searchMemories,parameters:{type:`object`,properties:{informationToGet:{type:`string`,description:t.informationToGet},includeFullDocs:{type:`boolean`,description:t.includeFullDocs,default:e.includeFullDocs},limit:{type:`number`,description:t.limit,default:e.limit}},required:[`informationToGet`]}},addMemory:{name:`addMemory`,description:n.addMemory,parameters:{type:`object`,properties:{memory:{type:`string`,description:t.memory}},required:[`memory`]}}};function m(e,t){let n=new o({apiKey:e,...t?.baseUrl&&{baseURL:t.baseUrl}}),i=r(t);return{client:n,containerTags:i}}function h(t,n){let{client:r,containerTags:i}=m(t,n);return async function({informationToGet:t,includeFullDocs:n=e.includeFullDocs,limit:a=e.limit}){try{let o=await r.search.execute({q:t,containerTags:i,limit:a,chunkThreshold:e.chunkThreshold,includeFullDocs:n});return{success:!0,results:o.results,count:o.results?.length||0}}catch(e){return{success:!1,error:e instanceof Error?e.message:`Unknown error`}}}}function g(e,t){let{client:n,containerTags:r}=m(e,t);return async function({memory:e}){try{let t={};return{success:!0,memory:await n.memories.add({content:e,containerTags:r,...Object.keys(t).length>0&&{metadata:t}})}}catch(e){return{success:!1,error:e instanceof Error?e.message:`Unknown error`}}}}function _(e,t){let n=h(e,t),r=g(e,t);return{searchMemories:n,addMemory:r}}function v(){return[{type:`function`,function:p.searchMemories},{type:`function`,function:p.addMemory}]}function y(e,t){let n=_(e,t);return async function(e){let t=e.function.name,r=JSON.parse(e.function.arguments);switch(t){case`searchMemories`:return JSON.stringify(await n.searchMemories(r));case`addMemory`:return JSON.stringify(await n.addMemory(r));default:return JSON.stringify({success:!1,error:`Unknown function: ${t}`})}}}function b(e,t){let n=y(e,t);return async function(e){return await Promise.all(e.map(async e=>{let t=await n(e);return{tool_call_id:e.id,role:`tool`,content:t}}))}}function x(e,t){let n=h(e,t);return{definition:{type:`function`,function:p.searchMemories},execute:n}}function S(e,t){let n=g(e,t);return{definition:{type:`function`,function:p.addMemory},execute:n}}function C(e,t,n){if(!process.env.SUPERMEMORY_API_KEY)throw Error(`SUPERMEMORY_API_KEY is not set`);let r=n?.conversationId,i=n?.verbose??!1,a=n?.mode??`profile`,o=n?.addMemory??`never`;return f(e,t,{conversationId:r,verbose:i,mode:a,addMemory:o})}export{g as createAddMemoryFunction,S as createAddMemoryTool,h as createSearchMemoriesFunction,x as createSearchMemoriesTool,y as createToolCallExecutor,b as createToolCallsExecutor,v as getToolDefinitions,p as memoryToolSchemas,_ as supermemoryTools,C as withSupermemory};
`),f=async(e,t,n,r,i)=>{try{let a=await e.memories.add({content:n,containerTags:[t],customId:r});i.info(`Memory saved successfully`,{containerTag:t,customId:r,contentLength:n.length,memoryId:a.id})}catch(e){i.error(`Error saving memory`,{error:e instanceof Error?e.message:`Unknown error`})}};function p(e,t,n){let r=a(n?.verbose??!1),p=s(n?.baseUrl),m=new o({apiKey:process.env.SUPERMEMORY_API_KEY,...p===`https://api.supermemory.ai`?{}:{baseURL:p}}),h=n?.conversationId,g=n?.mode??`profile`,_=n?.addMemory??`never`,v=e.chat.completions.create,y=e.responses?.create,b=async(e,t,n,r,a)=>{let o=await l(t,e,p),s=o.profile.static?.length||0,c=o.profile.dynamic?.length||0;n.info(`Memory search completed for ${a} API`,{containerTag:t,memoryCountStatic:s,memoryCountDynamic:c,queryText:e.substring(0,100)+(e.length>100?`...`:``),mode:r});let u=r===`query`?``:i({profile:{static:o.profile.static?.map(e=>e.memory),dynamic:o.profile.dynamic?.map(e=>e.memory)},searchResults:{results:o.searchResults.results.map(e=>({memory:e.memory}))}}),d=r===`profile`?``:`Search results for user's ${a===`chat`?`recent message`:`input`}: \n${o.searchResults.results.map(e=>`- ${e.memory}`).join(`
`)}`,f=`${u}\n${d}`.trim();return f&&n.debug(`Memory content preview for ${a} API`,{content:f,fullLength:f.length}),f},x=async n=>{if(!y)throw Error(`Responses API is not available in this OpenAI client version`);let i=typeof n.input==`string`?n.input:``;if(g!==`profile`&&!i)return r.debug(`No input found for Responses API, skipping memory search`),y.call(e.responses,n);r.info(`Starting memory search for Responses API`,{containerTag:t,conversationId:h,mode:g});let a=[];if(_===`always`&&i?.trim()){let e=h?`Input: ${i}`:i,n=h?`conversation:${h}`:void 0;a.push(f(m,t,e,n,r))}let o=g===`profile`?``:i;a.push(b(o,t,r,g,`responses`));let s=await Promise.all(a),c=s[s.length-1],l=c?`${n.instructions||``}\n\n${c}`.trim():n.instructions;return y.call(e.responses,{...n,instructions:l})},S=async n=>{let i=Array.isArray(n.messages)?n.messages:[];if(g!==`profile`&&!c(i))return r.debug(`No user message found, skipping memory search`),v.call(e.chat.completions,n);r.info(`Starting memory search`,{containerTag:t,conversationId:h,mode:g});let a=[];if(_===`always`){let e=c(i);if(e?.trim()){let n=h?d(i):e,o=h?`conversation:${h}`:void 0;a.push(f(m,t,n,o,r))}}a.push(u(i,t,r,g,p));let o=await Promise.all(a),s=o[o.length-1];return v.call(e.chat.completions,{...n,messages:s})};return e.chat.completions.create=S,y&&(e.responses.create=x),e}const m={searchMemories:{name:`searchMemories`,description:n.searchMemories,parameters:{type:`object`,properties:{informationToGet:{type:`string`,description:t.informationToGet},includeFullDocs:{type:`boolean`,description:t.includeFullDocs,default:e.includeFullDocs},limit:{type:`number`,description:t.limit,default:e.limit}},required:[`informationToGet`]}},addMemory:{name:`addMemory`,description:n.addMemory,parameters:{type:`object`,properties:{memory:{type:`string`,description:t.memory}},required:[`memory`]}}};function h(e,t){let n=new o({apiKey:e,...t?.baseUrl&&{baseURL:t.baseUrl}}),i=r(t);return{client:n,containerTags:i}}function g(t,n){let{client:r,containerTags:i}=h(t,n);return async function({informationToGet:t,includeFullDocs:n=e.includeFullDocs,limit:a=e.limit}){try{let o=await r.search.execute({q:t,containerTags:i,limit:a,chunkThreshold:e.chunkThreshold,includeFullDocs:n});return{success:!0,results:o.results,count:o.results?.length||0}}catch(e){return{success:!1,error:e instanceof Error?e.message:`Unknown error`}}}}function _(e,t){let{client:n,containerTags:r}=h(e,t);return async function({memory:e}){try{let t={};return{success:!0,memory:await n.memories.add({content:e,containerTags:r,...Object.keys(t).length>0&&{metadata:t}})}}catch(e){return{success:!1,error:e instanceof Error?e.message:`Unknown error`}}}}function v(e,t){let n=g(e,t),r=_(e,t);return{searchMemories:n,addMemory:r}}function y(){return[{type:`function`,function:m.searchMemories},{type:`function`,function:m.addMemory}]}function b(e,t){let n=v(e,t);return async function(e){let t=e.function.name,r=JSON.parse(e.function.arguments);switch(t){case`searchMemories`:return JSON.stringify(await n.searchMemories(r));case`addMemory`:return JSON.stringify(await n.addMemory(r));default:return JSON.stringify({success:!1,error:`Unknown function: ${t}`})}}}function x(e,t){let n=b(e,t);return async function(e){return await Promise.all(e.map(async e=>{let t=await n(e);return{tool_call_id:e.id,role:`tool`,content:t}}))}}function S(e,t){let n=g(e,t);return{definition:{type:`function`,function:m.searchMemories},execute:n}}function C(e,t){let n=_(e,t);return{definition:{type:`function`,function:m.addMemory},execute:n}}function w(e,t,n){if(!process.env.SUPERMEMORY_API_KEY)throw Error(`SUPERMEMORY_API_KEY is not set`);let r=n?.conversationId,i=n?.verbose??!1,a=n?.mode??`profile`,o=n?.addMemory??`never`,s=n?.baseUrl;return p(e,t,{conversationId:r,verbose:i,mode:a,addMemory:o,baseUrl:s})}export{_ as createAddMemoryFunction,C as createAddMemoryTool,g as createSearchMemoriesFunction,S as createSearchMemoriesTool,b as createToolCallExecutor,x as createToolCallsExecutor,y as getToolDefinitions,m as memoryToolSchemas,v as supermemoryTools,w as withSupermemory};
{
"name": "@supermemory/tools",
"type": "module",
"version": "1.3.13",
"version": "1.3.14",
"description": "Memory tools for AI SDK and OpenAI function calling with supermemory",

@@ -6,0 +6,0 @@ "scripts": {

import { SupermemoryToolsConfig } from "./types-B1x7Kbsa.js";
import Supermemory from "supermemory";
import OpenAI from "openai";
//#region src/openai/middleware.d.ts
interface OpenAIMiddlewareOptions {
conversationId?: string;
verbose?: boolean;
mode?: "profile" | "query" | "full";
addMemory?: "always" | "never";
}
/**
* Creates SuperMemory middleware for OpenAI clients.
*
* This function creates middleware that automatically injects relevant memories
* into OpenAI chat completions and optionally saves new memories. The middleware
* can wrap existing OpenAI clients or create new ones with SuperMemory capabilities.
*
* @param containerTag - The container tag/identifier for memory search (e.g., user ID, project ID)
* @param options - Optional configuration options for the middleware
* @param options.conversationId - Optional conversation ID to group messages for contextual memory generation
* @param options.verbose - Enable detailed logging of memory operations (default: false)
* @param options.mode - Memory search mode: "profile" (all memories), "query" (search-based), or "full" (both) (default: "profile")
* @param options.addMemory - Automatic memory storage mode: "always" or "never" (default: "never")
* @returns Object with `wrapClient` and `createClient` methods
* @throws {Error} When SUPERMEMORY_API_KEY environment variable is not set
*
* @example
* ```typescript
* const openaiWithSupermemory = createOpenAIMiddleware(openai, "user-123", {
* conversationId: "conversation-456",
* mode: "full",
* addMemory: "always",
* verbose: true
* })
*
* ```
*/
//#endregion
//#region src/openai/tools.d.ts
/**
* Result types for memory operations
*/
interface MemorySearchResult {
success: boolean;
results?: Awaited<ReturnType<Supermemory["search"]["execute"]>>["results"];
count?: number;
error?: string;
}
interface MemoryAddResult {
success: boolean;
memory?: Awaited<ReturnType<Supermemory["memories"]["add"]>>;
error?: string;
}
/**
* Function schemas for OpenAI function calling
*/
declare const memoryToolSchemas: {
readonly searchMemories: {
name: string;
description: "Search (recall) memories/details/information about the user or other facts or entities. Run when explicitly asked or when context about user's past choices would be helpful.";
parameters: {
type: string;
properties: {
informationToGet: {
type: string;
description: "Terms to search for in the user's memories";
};
includeFullDocs: {
type: string;
description: "Whether to include the full document content in the response. Defaults to true for better AI context.";
default: true;
};
limit: {
type: string;
description: "Maximum number of results to return";
default: 10;
};
};
required: string[];
};
};
readonly addMemory: {
name: string;
description: "Add (remember) memories/details/information about the user or other facts or entities. Run when explicitly asked or when the user mentions any information generalizable beyond the context of the current conversation.";
parameters: {
type: string;
properties: {
memory: {
type: string;
description: "The text content of the memory to add. This should be a single sentence or a short paragraph.";
};
};
required: string[];
};
};
};
/**
* Search memories function
*/
declare function createSearchMemoriesFunction(apiKey: string, config?: SupermemoryToolsConfig): ({
informationToGet,
includeFullDocs,
limit
}: {
informationToGet: string;
includeFullDocs?: boolean;
limit?: number;
}) => Promise<MemorySearchResult>;
/**
* Add memory function
*/
declare function createAddMemoryFunction(apiKey: string, config?: SupermemoryToolsConfig): ({
memory
}: {
memory: string;
}) => Promise<MemoryAddResult>;
/**
* Create all memory tools functions
*/
declare function supermemoryTools(apiKey: string, config?: SupermemoryToolsConfig): {
searchMemories: ({
informationToGet,
includeFullDocs,
limit
}: {
informationToGet: string;
includeFullDocs?: boolean;
limit?: number;
}) => Promise<MemorySearchResult>;
addMemory: ({
memory
}: {
memory: string;
}) => Promise<MemoryAddResult>;
};
/**
* Get OpenAI function definitions for all memory tools
*/
declare function getToolDefinitions(): OpenAI.Chat.Completions.ChatCompletionTool[];
/**
* Execute a tool call based on the function name and arguments
*/
declare function createToolCallExecutor(apiKey: string, config?: SupermemoryToolsConfig): (toolCall: OpenAI.Chat.Completions.ChatCompletionMessageToolCall) => Promise<string>;
/**
* Execute tool calls from OpenAI function calling
*/
declare function createToolCallsExecutor(apiKey: string, config?: SupermemoryToolsConfig): (toolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => Promise<OpenAI.Chat.Completions.ChatCompletionToolMessageParam[]>;
/**
* Individual tool creators for more granular control
*/
declare function createSearchMemoriesTool(apiKey: string, config?: SupermemoryToolsConfig): {
definition: {
type: "function";
function: {
name: string;
description: "Search (recall) memories/details/information about the user or other facts or entities. Run when explicitly asked or when context about user's past choices would be helpful.";
parameters: {
type: string;
properties: {
informationToGet: {
type: string;
description: "Terms to search for in the user's memories";
};
includeFullDocs: {
type: string;
description: "Whether to include the full document content in the response. Defaults to true for better AI context.";
default: true;
};
limit: {
type: string;
description: "Maximum number of results to return";
default: 10;
};
};
required: string[];
};
};
};
execute: ({
informationToGet,
includeFullDocs,
limit
}: {
informationToGet: string;
includeFullDocs?: boolean;
limit?: number;
}) => Promise<MemorySearchResult>;
};
declare function createAddMemoryTool(apiKey: string, config?: SupermemoryToolsConfig): {
definition: {
type: "function";
function: {
name: string;
description: "Add (remember) memories/details/information about the user or other facts or entities. Run when explicitly asked or when the user mentions any information generalizable beyond the context of the current conversation.";
parameters: {
type: string;
properties: {
memory: {
type: string;
description: "The text content of the memory to add. This should be a single sentence or a short paragraph.";
};
};
required: string[];
};
};
};
execute: ({
memory
}: {
memory: string;
}) => Promise<MemoryAddResult>;
};
//#endregion
//#region src/openai/index.d.ts
/**
* Wraps an OpenAI client with SuperMemory middleware to automatically inject relevant memories
* into both Chat Completions and Responses APIs based on the user's input content.
*
* For Chat Completions API: Searches for memories using the user message content and injects
* them into the system prompt (appends to existing or creates new system prompt).
*
* For Responses API: Searches for memories using the input parameter and injects them into
* the instructions parameter (appends to existing or creates new instructions).
*
* @param openaiClient - The OpenAI client to wrap with SuperMemory middleware
* @param containerTag - The container tag/identifier for memory search (e.g., user ID, project ID)
* @param options - Optional configuration options for the middleware
* @param options.conversationId - Optional conversation ID to group messages into a single document for contextual memory generation
* @param options.verbose - Optional flag to enable detailed logging of memory search and injection process (default: false)
* @param options.mode - Optional mode for memory search: "profile" (default), "query", or "full"
* @param options.addMemory - Optional mode for memory addition: "always", "never" (default)
*
* @returns An OpenAI client with SuperMemory middleware injected for both Chat Completions and Responses APIs
*
* @example
* ```typescript
* import { withSupermemory } from "@supermemory/tools/openai"
* import OpenAI from "openai"
*
* // Create OpenAI client with supermemory middleware
* const openai = new OpenAI({
* apiKey: process.env.OPENAI_API_KEY,
* })
* const openaiWithSupermemory = withSupermemory(openai, "user-123", {
* conversationId: "conversation-456",
* mode: "full",
* addMemory: "always"
* })
*
* // Use with Chat Completions API - memories injected into system prompt
* const chatResponse = await openaiWithSupermemory.chat.completions.create({
* model: "gpt-4",
* messages: [
* { role: "user", content: "What's my favorite programming language?" }
* ]
* })
*
* // Use with Responses API - memories injected into instructions
* const response = await openaiWithSupermemory.responses.create({
* model: "gpt-4o",
* instructions: "You are a helpful coding assistant",
* input: "What's my favorite programming language?"
* })
* ```
*
* @throws {Error} When SUPERMEMORY_API_KEY environment variable is not set
* @throws {Error} When supermemory API request fails
*/
declare function withSupermemory(openaiClient: OpenAI, containerTag: string, options?: OpenAIMiddlewareOptions): OpenAI;
//#endregion
export { type MemoryAddResult, type MemorySearchResult, type OpenAIMiddlewareOptions, createAddMemoryFunction, createAddMemoryTool, createSearchMemoriesFunction, createSearchMemoriesTool, createToolCallExecutor, createToolCallsExecutor, getToolDefinitions, memoryToolSchemas, supermemoryTools, withSupermemory };