feat(integrations): Zapier app for Mem0 (#6518)
Co-authored-by: kartik-mem0 <kartik.labhshetwar@mem0.ai>
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
import type { ZObject, Bundle } from './types';
|
||||
|
||||
// Custom (API key) authentication for Mem0.
|
||||
// The key is sent as "Authorization: Token <apiKey>" (matches Mem0's SDKs).
|
||||
const test = (z: ZObject, _bundle: Bundle) => z.request({ url: '/v1/ping/', method: 'GET' });
|
||||
|
||||
export default {
|
||||
type: 'custom',
|
||||
test,
|
||||
fields: [
|
||||
{
|
||||
key: 'apiKey',
|
||||
label: 'Mem0 API Key',
|
||||
// `password` so Zapier masks the key in the connection UI (it is a secret).
|
||||
type: 'password',
|
||||
required: true,
|
||||
helpText:
|
||||
'Your Mem0 API key (starts with `m0-`). Create one at [app.mem0.ai](https://app.mem0.ai) → Settings → API Keys.',
|
||||
},
|
||||
{
|
||||
key: 'baseUrl',
|
||||
label: 'Base URL',
|
||||
type: 'string',
|
||||
required: false,
|
||||
default: 'https://api.mem0.ai',
|
||||
helpText: 'Override only for self-hosted or non-default deployments.',
|
||||
},
|
||||
],
|
||||
// Shown on the connection label in the Zap editor.
|
||||
connectionLabel: 'Mem0',
|
||||
};
|
||||
@@ -0,0 +1,168 @@
|
||||
import type { ZObject, Bundle, AddResponse, EventResponse } from '../types';
|
||||
import { captureEvent } from '../telemetry';
|
||||
|
||||
const POLL_INTERVAL_MS = 1500;
|
||||
// Bounded so the poll budget stays under Zapier's per-step execution timeout.
|
||||
const MAX_POLL_ATTEMPTS = 12;
|
||||
|
||||
// Polls GET /v1/event/{id}/ until the async memory-addition event resolves.
|
||||
const pollEvent = async (z: ZObject, eventId: string): Promise<EventResponse> => {
|
||||
for (let attempt = 0; attempt < MAX_POLL_ATTEMPTS; attempt++) {
|
||||
const res = await z.request({ url: `/v1/event/${eventId}/`, method: 'GET' });
|
||||
const data = res.data as EventResponse;
|
||||
const status = data && data.status;
|
||||
if (status === 'SUCCEEDED') {
|
||||
return data;
|
||||
}
|
||||
if (status === 'FAILED') {
|
||||
const reason = (data && (data.error || data.message)) || 'unknown error';
|
||||
throw new z.errors.Error(`Mem0 memory event ${eventId} failed: ${reason}`, 'Mem0EventFailed', 400);
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
|
||||
}
|
||||
throw new z.errors.Error(
|
||||
`Timed out waiting for memory event ${eventId}. The add was accepted and is ` +
|
||||
`likely still completing on the server — a timeout here does not mean it failed.`,
|
||||
'Mem0Timeout',
|
||||
408,
|
||||
);
|
||||
};
|
||||
|
||||
const perform = async (z: ZObject, bundle: Bundle): Promise<AddResponse | EventResponse> => {
|
||||
// Zapier boolean fields can arrive as the strings 'true'/'false'; coerce
|
||||
// explicitly so "Infer = No" / "Wait = No" are honored.
|
||||
const infer = String(bundle.inputData.infer) !== 'false';
|
||||
// Waiting is opt-in (the poll path can exceed Zapier's step timeout).
|
||||
const wait = String(bundle.inputData.waitForCompletion) === 'true';
|
||||
|
||||
const body: Record<string, unknown> = {
|
||||
messages: [{ role: bundle.inputData.role || 'user', content: bundle.inputData.content }],
|
||||
infer,
|
||||
};
|
||||
if (bundle.inputData.user_id) body.user_id = bundle.inputData.user_id;
|
||||
if (bundle.inputData.agent_id) body.agent_id = bundle.inputData.agent_id;
|
||||
if (bundle.inputData.run_id) body.run_id = bundle.inputData.run_id;
|
||||
if (bundle.inputData.metadata) {
|
||||
try {
|
||||
body.metadata =
|
||||
typeof bundle.inputData.metadata === 'string'
|
||||
? JSON.parse(bundle.inputData.metadata)
|
||||
: bundle.inputData.metadata;
|
||||
} catch {
|
||||
throw new z.errors.Error('Metadata must be valid JSON.', 'InvalidInput', 400);
|
||||
}
|
||||
}
|
||||
// Custom extraction controls (optional): steer what the API extracts.
|
||||
if (bundle.inputData.custom_instructions) {
|
||||
body.custom_instructions = bundle.inputData.custom_instructions;
|
||||
}
|
||||
if (bundle.inputData.custom_categories) {
|
||||
try {
|
||||
body.custom_categories =
|
||||
typeof bundle.inputData.custom_categories === 'string'
|
||||
? JSON.parse(bundle.inputData.custom_categories)
|
||||
: bundle.inputData.custom_categories;
|
||||
} catch {
|
||||
throw new z.errors.Error('Custom Categories must be valid JSON.', 'InvalidInput', 400);
|
||||
}
|
||||
}
|
||||
if (bundle.inputData.includes) body.includes = bundle.inputData.includes;
|
||||
if (bundle.inputData.excludes) body.excludes = bundle.inputData.excludes;
|
||||
|
||||
captureEvent('zapier.add_memory', bundle.authData?.apiKey, { infer, wait });
|
||||
|
||||
const response = await z.request({
|
||||
url: '/v3/memories/add/',
|
||||
method: 'POST',
|
||||
body,
|
||||
});
|
||||
|
||||
// Default to an empty object so an empty/no-content 2xx body can't crash the
|
||||
// `.status` / `.event_id` reads below.
|
||||
const data = (response.data ?? {}) as AddResponse;
|
||||
|
||||
// Add returns {event_id, status:PENDING|RUNNING}; poll only when opted in.
|
||||
if (wait && data.event_id && data.status !== 'SUCCEEDED' && data.status !== 'FAILED') {
|
||||
return pollEvent(z, data.event_id);
|
||||
}
|
||||
if (data.status === 'FAILED') {
|
||||
const reason = data.error || data.message || 'unknown error';
|
||||
throw new z.errors.Error(`Mem0 memory add failed: ${reason}`, 'Mem0EventFailed', 400);
|
||||
}
|
||||
return data;
|
||||
};
|
||||
|
||||
export default {
|
||||
key: 'add_memory',
|
||||
noun: 'Memory',
|
||||
display: {
|
||||
label: 'Add Memory',
|
||||
description: 'Extract and store memories from a message.',
|
||||
},
|
||||
operation: {
|
||||
perform,
|
||||
inputFields: [
|
||||
{
|
||||
key: 'content',
|
||||
label: 'Content',
|
||||
type: 'text',
|
||||
required: true,
|
||||
helpText: 'The message content to extract memories from.',
|
||||
},
|
||||
{
|
||||
key: 'role',
|
||||
label: 'Role',
|
||||
choices: { user: 'User', assistant: 'Assistant', system: 'System' },
|
||||
default: 'user',
|
||||
},
|
||||
{ key: 'user_id', label: 'User ID', type: 'string' },
|
||||
{ key: 'agent_id', label: 'Agent ID', type: 'string' },
|
||||
{ key: 'run_id', label: 'Run ID', type: 'string' },
|
||||
{ key: 'metadata', label: 'Metadata (JSON)', type: 'string' },
|
||||
{
|
||||
key: 'custom_instructions',
|
||||
label: 'Custom Instructions',
|
||||
type: 'text',
|
||||
helpText: 'Optional instructions that steer what the extractor keeps or ignores.',
|
||||
},
|
||||
{
|
||||
key: 'custom_categories',
|
||||
label: 'Custom Categories (JSON)',
|
||||
type: 'string',
|
||||
helpText:
|
||||
'Optional taxonomy for categorising memories, as a JSON array of {category: description} objects.',
|
||||
},
|
||||
{
|
||||
key: 'includes',
|
||||
label: 'Includes',
|
||||
type: 'text',
|
||||
helpText: 'Optional: only extract memories matching this description.',
|
||||
},
|
||||
{
|
||||
key: 'excludes',
|
||||
label: 'Excludes',
|
||||
type: 'text',
|
||||
helpText: 'Optional: skip memories matching this description.',
|
||||
},
|
||||
{
|
||||
key: 'infer',
|
||||
label: 'Infer',
|
||||
type: 'boolean',
|
||||
default: 'true',
|
||||
helpText: 'Run LLM extraction over the message. Turn off to store it verbatim.',
|
||||
},
|
||||
{
|
||||
key: 'waitForCompletion',
|
||||
label: 'Wait for Completion',
|
||||
type: 'boolean',
|
||||
default: 'false',
|
||||
helpText:
|
||||
'Poll until extraction finishes and return the resulting memories. ' +
|
||||
'Leave off (default) to return immediately with an event ID — extraction can take ' +
|
||||
'longer than Zapier allows this step to run, and a timeout does not mean the add failed.',
|
||||
},
|
||||
],
|
||||
// Default (no-wait) returns the accepted event; the wait path returns the resolved event.
|
||||
sample: { event_id: '00000000-0000-0000-0000-000000000000', status: 'PENDING' },
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { ZObject, Bundle } from '../types';
|
||||
|
||||
const perform = async (z: ZObject, bundle: Bundle) => {
|
||||
// Trailing slash required (Django APPEND_SLASH); id encoded so a stray slash can't mistarget the path.
|
||||
const response = await z.request({
|
||||
url: `/v1/memories/${encodeURIComponent(String(bundle.inputData.memory_id))}/`,
|
||||
method: 'DELETE',
|
||||
});
|
||||
return response.data || { message: 'Deleted', memory_id: bundle.inputData.memory_id };
|
||||
};
|
||||
|
||||
export default {
|
||||
key: 'delete_memory',
|
||||
noun: 'Memory',
|
||||
display: {
|
||||
label: 'Delete Memory',
|
||||
description: 'Delete a single memory by its ID.',
|
||||
},
|
||||
operation: {
|
||||
perform,
|
||||
inputFields: [{ key: 'memory_id', label: 'Memory ID', type: 'string', required: true }],
|
||||
sample: { message: 'Memory deleted successfully' },
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,33 @@
|
||||
import { version as platformVersion } from 'zapier-platform-core';
|
||||
import authentication from './authentication';
|
||||
import { includeApiKey, handleBadResponses } from './middleware';
|
||||
import addMemory from './creates/add_memory';
|
||||
import deleteMemory from './creates/delete_memory';
|
||||
import searchMemories from './searches/search_memories';
|
||||
import getMemories from './searches/get_memories';
|
||||
import pkg from '../package.json';
|
||||
|
||||
const app = {
|
||||
version: pkg.version,
|
||||
platformVersion,
|
||||
|
||||
authentication,
|
||||
|
||||
beforeRequest: [includeApiKey],
|
||||
afterResponse: [handleBadResponses],
|
||||
|
||||
creates: {
|
||||
[addMemory.key]: addMemory,
|
||||
[deleteMemory.key]: deleteMemory,
|
||||
},
|
||||
|
||||
searches: {
|
||||
[searchMemories.key]: searchMemories,
|
||||
[getMemories.key]: getMemories,
|
||||
},
|
||||
|
||||
resources: {},
|
||||
triggers: {},
|
||||
};
|
||||
|
||||
export = app;
|
||||
@@ -0,0 +1,50 @@
|
||||
import type { ZObject, Bundle, MutableRequest, ZResponse } from './types';
|
||||
|
||||
// Prepend the configured base URL and inject the auth header on every request.
|
||||
export const includeApiKey = (
|
||||
request: MutableRequest,
|
||||
_z: ZObject,
|
||||
bundle: Bundle,
|
||||
): MutableRequest => {
|
||||
if (bundle.authData && bundle.authData.apiKey) {
|
||||
request.headers = request.headers || {};
|
||||
request.headers.Authorization = `Token ${bundle.authData.apiKey}`;
|
||||
}
|
||||
// Resolve relative URLs against the configured base URL.
|
||||
if (request.url && request.url.startsWith('/')) {
|
||||
const base = (bundle.authData && bundle.authData.baseUrl) || 'https://api.mem0.ai';
|
||||
request.url = `${base.replace(/\/$/, '')}${request.url}`;
|
||||
}
|
||||
return request;
|
||||
};
|
||||
|
||||
// Surface HTTP failures as errors. z.request does NOT throw on non-2xx by
|
||||
// default, so without this a 4xx/5xx would flow downstream as a fake success
|
||||
// (empty search results / error body returned as a created memory).
|
||||
export const handleBadResponses = (
|
||||
response: ZResponse,
|
||||
z: ZObject,
|
||||
_bundle: Bundle,
|
||||
): ZResponse => {
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
throw new z.errors.Error(
|
||||
'The Mem0 API key you supplied is invalid or lacks access.',
|
||||
'AuthenticationError',
|
||||
response.status,
|
||||
);
|
||||
}
|
||||
if (response.status >= 400) {
|
||||
const data = (response.data as Record<string, unknown>) || {};
|
||||
const raw =
|
||||
data.detail || data.error || data.message || response.content || 'unknown error';
|
||||
// DRF sometimes returns detail as an object/array; stringify so the
|
||||
// thrown message never renders as "[object Object]".
|
||||
const detail = typeof raw === 'string' ? raw : JSON.stringify(raw);
|
||||
throw new z.errors.Error(
|
||||
`Mem0 API request failed (HTTP ${response.status}): ${detail}`,
|
||||
'Mem0ApiError',
|
||||
response.status,
|
||||
);
|
||||
}
|
||||
return response;
|
||||
};
|
||||
@@ -0,0 +1,52 @@
|
||||
import type { ZObject, Bundle, Memory } from '../types';
|
||||
import { captureEvent } from '../telemetry';
|
||||
|
||||
const perform = async (z: ZObject, bundle: Bundle): Promise<Memory[]> => {
|
||||
const body: Record<string, unknown> = {};
|
||||
if (bundle.inputData.user_id) body.filters = { user_id: bundle.inputData.user_id };
|
||||
|
||||
captureEvent('zapier.get_memories', bundle.authData?.apiKey);
|
||||
|
||||
const response = await z.request({
|
||||
url: '/v3/memories/',
|
||||
method: 'POST',
|
||||
params: {
|
||||
page: Math.max(1, Math.floor(Number(bundle.inputData.page) || 1)),
|
||||
page_size: Math.max(1, Math.floor(Number(bundle.inputData.limit) || 50)),
|
||||
},
|
||||
body,
|
||||
});
|
||||
// Guard against a null/empty body; always return an array.
|
||||
const data = response.data as Memory[] | { results?: Memory[] } | null;
|
||||
return Array.isArray(data) ? data : data?.results ?? [];
|
||||
};
|
||||
|
||||
export default {
|
||||
key: 'get_memories',
|
||||
noun: 'Memory',
|
||||
display: {
|
||||
label: 'Get Memories',
|
||||
description: 'List stored memories for a user.',
|
||||
},
|
||||
operation: {
|
||||
perform,
|
||||
inputFields: [
|
||||
{ key: 'user_id', label: 'User ID', type: 'string', required: true },
|
||||
{
|
||||
key: 'limit',
|
||||
label: 'Limit',
|
||||
type: 'integer',
|
||||
default: '50',
|
||||
helpText: 'Max memories per page. Use Page to page through larger result sets.',
|
||||
},
|
||||
{
|
||||
key: 'page',
|
||||
label: 'Page',
|
||||
type: 'integer',
|
||||
default: '1',
|
||||
helpText: 'Which page of results to return (1-based).',
|
||||
},
|
||||
],
|
||||
sample: { id: '00000000-0000-0000-0000-000000000000', memory: 'User loves hiking' },
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { ZObject, Bundle, Memory } from '../types';
|
||||
import { captureEvent } from '../telemetry';
|
||||
|
||||
const perform = async (z: ZObject, bundle: Bundle): Promise<Memory[]> => {
|
||||
const body: Record<string, unknown> = {
|
||||
query: bundle.inputData.query,
|
||||
output_format: 'v1.1',
|
||||
top_k: Math.max(1, Math.floor(Number(bundle.inputData.limit) || 50)),
|
||||
};
|
||||
if (bundle.inputData.user_id) body.filters = { user_id: bundle.inputData.user_id };
|
||||
|
||||
captureEvent('zapier.search_memories', bundle.authData?.apiKey);
|
||||
|
||||
const response = await z.request({
|
||||
url: '/v3/memories/search/',
|
||||
method: 'POST',
|
||||
body,
|
||||
});
|
||||
// Searches must return an array; guard against a null/empty body.
|
||||
const data = response.data as Memory[] | { results?: Memory[] } | null;
|
||||
return Array.isArray(data) ? data : data?.results ?? [];
|
||||
};
|
||||
|
||||
export default {
|
||||
key: 'search_memories',
|
||||
noun: 'Memory',
|
||||
display: {
|
||||
label: 'Search Memories',
|
||||
description: 'Semantic search over stored memories.',
|
||||
},
|
||||
operation: {
|
||||
perform,
|
||||
inputFields: [
|
||||
{ key: 'query', label: 'Query', type: 'string', required: true },
|
||||
{ key: 'user_id', label: 'User ID', type: 'string', required: true },
|
||||
{ key: 'limit', label: 'Limit', type: 'integer', default: '50' },
|
||||
],
|
||||
sample: { id: '00000000-0000-0000-0000-000000000000', memory: 'User loves hiking' },
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,39 @@
|
||||
import { createHash } from 'crypto';
|
||||
|
||||
// Anonymous usage telemetry via PostHog, mirroring the Mem0 CLI / plugins.
|
||||
// Fire-and-forget: never awaited, never throws, so it can neither slow down
|
||||
// nor break an action. Opt out with MEM0_TELEMETRY=false.
|
||||
const POSTHOG_API_KEY = 'phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX';
|
||||
const POSTHOG_HOST = 'https://us.i.posthog.com/i/v0/e/';
|
||||
|
||||
export function captureEvent(
|
||||
event: string,
|
||||
apiKey: string | undefined,
|
||||
properties: Record<string, unknown> = {},
|
||||
): void {
|
||||
if (process.env.MEM0_TELEMETRY === 'false') return;
|
||||
try {
|
||||
// Hash the API key so events are attributable to one account without
|
||||
// ever transmitting the key itself.
|
||||
const distinctId = apiKey ? createHash('md5').update(apiKey).digest('hex') : 'zapier-anon';
|
||||
const payload = {
|
||||
api_key: POSTHOG_API_KEY,
|
||||
event,
|
||||
distinct_id: distinctId,
|
||||
properties: {
|
||||
source: 'ZAPIER',
|
||||
$process_person_profile: false,
|
||||
...properties,
|
||||
},
|
||||
};
|
||||
void fetch(POSTHOG_HOST, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
}).catch(() => {
|
||||
/* swallow — telemetry must never surface to the user */
|
||||
});
|
||||
} catch {
|
||||
/* swallow — telemetry must never break the action */
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { ZObject, Bundle } from 'zapier-platform-core';
|
||||
|
||||
export type { ZObject, Bundle };
|
||||
|
||||
/** Mutable outgoing request, as seen by the beforeRequest middleware. */
|
||||
export interface MutableRequest {
|
||||
url?: string;
|
||||
headers?: Record<string, string>;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
/** Response as seen by the afterResponse middleware. */
|
||||
export interface ZResponse {
|
||||
status: number;
|
||||
data?: Record<string, unknown> | unknown[] | null;
|
||||
content?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
/** Async add response from POST /v3/memories/add/. */
|
||||
export interface AddResponse {
|
||||
event_id?: string;
|
||||
status?: string;
|
||||
error?: string;
|
||||
message?: string;
|
||||
results?: unknown[];
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
/** GET /v1/event/{id}/ response. */
|
||||
export interface EventResponse {
|
||||
status?: string;
|
||||
error?: string;
|
||||
message?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
/** A stored memory object returned by search / list. */
|
||||
export interface Memory {
|
||||
id?: string;
|
||||
memory?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
Reference in New Issue
Block a user