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.2
to
1.3.3
+272
dist/index-BOj_YK4D.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";
}
/**
* 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
-1
import { SupermemoryToolsConfig } from "./types-B1x7Kbsa.js";
import { OpenAIMiddlewareOptions } from "./index-DSTQstC8.js";
import { OpenAIMiddlewareOptions } from "./index-BOj_YK4D.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-DSTQstC8.js";
import { MemoryAddResult, MemorySearchResult, OpenAIMiddlewareOptions, createAddMemoryFunction, createAddMemoryTool, createSearchMemoriesFunction, createSearchMemoriesTool, createToolCallExecutor, createToolCallsExecutor, getToolDefinitions, memoryToolSchemas, supermemoryTools, withSupermemory } from "../index-BOj_YK4D.js";
export { MemoryAddResult, MemorySearchResult, OpenAIMiddlewareOptions, createAddMemoryFunction, createAddMemoryTool, createSearchMemoriesFunction, createSearchMemoriesTool, createToolCallExecutor, createToolCallsExecutor, getToolDefinitions, memoryToolSchemas, supermemoryTools, withSupermemory };

@@ -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}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 a=e.some(e=>e.role===`system`),o=r===`profile`?``:s(e),l=await c(t,o),u=l.profile.static?.length||0,d=l.profile.dynamic?.length||0;n.info(`Memory search completed`,{containerTag:t,memoryCountStatic:u,memoryCountDynamic:d,queryText:o.substring(0,100)+(o.length>100?`...`:``),mode:r});let f=r===`query`?``:i({profile:{static:l.profile.static?.map(e=>e.memory),dynamic:l.profile.dynamic?.map(e=>e.memory)},searchResults:{results:l.searchResults.results.map(e=>({memory:e.memory}))}}),p=r===`profile`?``:`Search results for user's recent message: \n${l.searchResults.results.map(e=>`- ${e.memory}`).join(`
`)}`,m=`${f}\n${p}`.trim();return m&&n.debug(`Memory content preview`,{content:m,fullLength:m.length}),a?(n.debug(`Added memories to existing system prompt`),e.map(e=>e.role===`system`?{...e,content:`${e.content} \n ${m}`}:e)):(n.debug(`System prompt does not exist, created system prompt with memories`),[{role:`system`,content:m},...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=>{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(`
`),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),i=new o({apiKey:process.env.SUPERMEMORY_API_KEY}),c=e.chat.completions.create,f=async n=>{let a=Array.isArray(n.messages)?n.messages:[];if(addMemory===`always`){let e=s(a);if(e?.trim()){let n=conversationId?u(a):e,o=conversationId?`conversation:${conversationId}`:void 0;d(i,t,n,o,r)}}if(mode!==`profile`&&!s(a))return r.debug(`No user message found, skipping memory search`),c.call(e.chat.completions,n);r.info(`Starting memory search`,{containerTag:t,conversationId,mode});let o=await l(a,t,r,mode);return c.call(e.chat.completions,{...n,messages:o})};return e.chat.completions.create=f,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};
`),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};
{
"name": "@supermemory/tools",
"type": "module",
"version": "1.3.2",
"version": "1.3.3",
"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 the system prompt based on the user's message content.
*
* This middleware searches the supermemory API for relevant memories using the container tag
* and user message, then either appends memories to an existing system prompt or creates
* a new system prompt with the memories.
*
* @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
*
* @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 normally - memories will be automatically injected
* const response = await openaiWithSupermemory.chat.completions.create({
* model: "gpt-4",
* messages: [
* { role: "user", content: "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 };