Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.
TypeScript agent-harnessagent-harness-engineeringai-engineeringai-observabilityamd-gpuclaude-codeclickhousecodexcoding-agentcoding-agentscursorgenaigpu-monitoringllm-observabilityllmopsnvidia-smiobservabilityopen-sourceopenaiopentelemetry
feat(typescript): add Mem0 (mem0ai) memory-layer auto-instrumentation (#1276)
Manan Bansalce2afe3be709
diff --git a/sdk/typescript/src/instrumentation/__tests__/mem0-trace-comparison.test.ts b/sdk/typescript/src/instrumentation/__tests__/mem0-trace-comparison.test.tsnew file mode 100644index 00000000..038c8516--- /dev/null+++ b/sdk/typescript/src/instrumentation/__tests__/mem0-trace-comparison.test.ts@@ -0,0 +1,238 @@+/**+ * Cross-Language Trace Comparison Tests for the mem0 Integration+ *+ * These verify that the TypeScript mem0 instrumentation emits the same spans /+ * attributes as the Python SDK reference+ * (sdk/python/src/openlit/instrumentation/mem0). mem0 is a memory layer, not an LLM+ * provider: each operation (add / search / get / getAll / update / delete /+ * deleteAll / history) becomes one CLIENT span named `memory <op>` carrying+ * `gen_ai.*` attributes. There are no tokens, model, cost, or metrics. The same+ * wrapper serves both the hosted `MemoryClient` and the OSS `Memory` clients, whose+ * method surfaces are identical.+ */++import { SpanKind } from '@opentelemetry/api';+import { ATTR_SERVICE_NAME, ATTR_TELEMETRY_SDK_NAME } from '@opentelemetry/semantic-conventions';+import Mem0Wrapper from '../mem0/wrapper';+import OpenlitConfig from '../../config';+import OpenLitHelper from '../../helpers';+import SemanticConvention from '../../semantic-convention';++jest.mock('../../config');+jest.mock('../../helpers', () => ({+ __esModule: true,+ default: { handleException: jest.fn() },+ applyCustomSpanAttributes: jest.fn(),+}));++describe('mem0 Cross-Language Trace Comparison', () => {+ let mockSpan: any;+ let mockTracer: any;++ beforeEach(() => {+ mockSpan = {+ setAttribute: jest.fn(),+ setStatus: jest.fn(),+ recordException: jest.fn(),+ end: jest.fn(),+ };+ mockTracer = { startSpan: jest.fn(() => mockSpan) };++ (OpenlitConfig as any).environment = 'openlit-testing';+ (OpenlitConfig as any).applicationName = 'openlit-test';+ (OpenlitConfig as any).captureMessageContent = true;+ });++ afterEach(() => {+ jest.clearAllMocks();+ });++ // Wrap `impl` as the mem0 operation `spanName`, then invoke it with `args`.+ async function runOp(spanName: string, impl: (...a: any[]) => any, args: any[] = []) {+ const wrapped = Mem0Wrapper._patchMemoryOperation(mockTracer, spanName)(impl);+ return wrapped.apply({}, args);+ }++ // Snapshot of all setAttribute(key, value) calls as a plain object.+ function attrs(): Record<string, any> {+ return Object.fromEntries((mockSpan.setAttribute as jest.Mock).mock.calls);+ }++ describe('Core span shape', () => {+ it('opens a CLIENT span named after the Python endpoint string', async () => {+ await runOp('memory add', async () => [{ id: 'm1' }], [[{ role: 'user', content: 'hi' }], {}]);++ expect(mockTracer.startSpan).toHaveBeenCalledWith('memory add', { kind: SpanKind.CLIENT });+ expect(mockSpan.setStatus).toHaveBeenCalledWith({ code: 1 }); // SpanStatusCode.OK+ expect(mockSpan.end).toHaveBeenCalledTimes(1);+ });++ it('sets the same core attributes as the Python SDK', async () => {+ await runOp('memory add', async () => [{ id: 'm1' }], [[{ role: 'user', content: 'hi' }], {}]);+ const a = attrs();++ expect(a[ATTR_TELEMETRY_SDK_NAME]).toBe('openlit');+ // Provider name is stamped on BOTH keys (gen_ai.system + gen_ai.provider.name).+ expect(a[SemanticConvention.GEN_AI_PROVIDER_NAME]).toBe('mem0');+ expect(a[SemanticConvention.GEN_AI_PROVIDER_NAME_OTEL]).toBe('mem0');+ expect(a[SemanticConvention.GEN_AI_ENDPOINT]).toBe('memory add');+ expect(a[SemanticConvention.GEN_AI_OPERATION]).toBe(SemanticConvention.GEN_AI_OPERATION_TYPE_MEMORY);+ expect(a[SemanticConvention.ATTR_DEPLOYMENT_ENVIRONMENT]).toBe('openlit-testing');+ expect(a[ATTR_SERVICE_NAME]).toBe('openlit-test');+ // gen_ai.sdk.version is the mem0ai package version (a string); its exact value+ // comes from the version OTel passes to the patch hook — asserted in the next test.+ expect(typeof a[SemanticConvention.GEN_AI_SDK_VERSION]).toBe('string');+ expect(typeof a[SemanticConvention.GEN_AI_CLIENT_OPERATION_DURATION]).toBe('number');+ });++ it('stamps the mem0ai version OTel hands to the patch hook', async () => {+ const wrapped = Mem0Wrapper._patchMemoryOperation(mockTracer, 'memory add', '3.0.7')(+ async () => [{ id: 'm1' }]+ );+ await wrapped.apply({}, [[{ role: 'user', content: 'hi' }], {}]);+ expect(attrs()[SemanticConvention.GEN_AI_SDK_VERSION]).toBe('3.0.7');+ });++ it('applies custom span attributes on every memory span', async () => {+ const { applyCustomSpanAttributes } = jest.requireMock('../../helpers');+ await runOp('memory get', async () => ({ id: 'm1' }), ['mem-123']);+ expect(applyCustomSpanAttributes).toHaveBeenCalledWith(mockSpan);+ });+ });++ describe('Operation: add', () => {+ it('records message count, infer flag, and input content', async () => {+ const messages = [+ { role: 'user', content: 'I love coffee' },+ { role: 'assistant', content: 'Noted' },+ ];+ await runOp('memory add', async () => ({ results: [{ id: 'm1' }] }), [+ messages,+ { userId: 'alice', infer: false },+ ]);+ const a = attrs();++ expect(a[SemanticConvention.GEN_AI_MEMORY_COUNT]).toBe(2);+ expect(a[SemanticConvention.GEN_AI_MEMORY_INFER]).toBe(false);+ expect(a[SemanticConvention.GEN_AI_USER_ID]).toBe('alice');+ expect(a[SemanticConvention.GEN_AI_INPUT_MESSAGES]).toBe(JSON.stringify(messages));+ });++ it('captures user / agent / run scope from the config object', async () => {+ await runOp('memory add', async () => [{ id: 'm1' }], [+ [{ role: 'user', content: 'hi' }],+ { userId: 'u1', agentId: 'a1', runId: 'r1', metadata: { topic: 'food' } },+ ]);+ const a = attrs();++ expect(a[SemanticConvention.GEN_AI_USER_ID]).toBe('u1');+ expect(a[SemanticConvention.GEN_AI_AGENT_ID]).toBe('a1');+ expect(a[SemanticConvention.GEN_AI_RUN_ID]).toBe('r1');+ expect(a[SemanticConvention.GEN_AI_MEMORY_METADATA]).toBe(JSON.stringify({ topic: 'food' }));+ });+ });++ describe('Operation: search', () => {+ it('records query / limit (topK) / threshold and output content', async () => {+ const response = { results: [{ id: 'm1', memory: 'likes coffee' }, { id: 'm2', memory: 'likes tea' }] };+ await runOp('memory search', async () => response, [+ 'what drinks?',+ { userId: 'alice', topK: 5, threshold: 0.7 },+ ]);+ const a = attrs();++ expect(a[SemanticConvention.GEN_AI_MEMORY_SEARCH_QUERY]).toBe('what drinks?');+ expect(a[SemanticConvention.GEN_AI_MEMORY_SEARCH_LIMIT]).toBe(5);+ expect(a[SemanticConvention.GEN_AI_MEMORY_SEARCH_THRESHOLD]).toBe(0.7);+ expect(a[SemanticConvention.GEN_AI_MEMORY_OPERATION_RESULT_COUNT]).toBe(2);+ expect(a[SemanticConvention.GEN_AI_DATA_SOURCES]).toBe(2);+ expect(a[SemanticConvention.GEN_AI_OUTPUT_MESSAGES]).toBe(JSON.stringify(response));+ });++ it('reads scope from a nested filters object (camel or snake case)', async () => {+ await runOp('memory search', async () => ({ results: [] }), [+ 'q',+ { filters: { user_id: 'snake-user' } },+ ]);+ expect(attrs()[SemanticConvention.GEN_AI_USER_ID]).toBe('snake-user');+ });++ it('reports result_count 0 for an empty results array (not 1)', async () => {+ await runOp('memory search', async () => ({ results: [] }), ['q', { filters: { user_id: 'x' } }]);+ const a = attrs();+ expect(a[SemanticConvention.GEN_AI_MEMORY_OPERATION_RESULT_COUNT]).toBe(0);+ expect(a[SemanticConvention.GEN_AI_DATA_SOURCES]).toBe(0);+ });+ });++ describe('Operations carrying a positional memory id', () => {+ it('get -> db.operation.id', async () => {+ await runOp('memory get', async () => ({ id: 'mem-1' }), ['mem-1']);+ expect(attrs()[SemanticConvention.DB_OPERATION_ID]).toBe('mem-1');+ });++ it('update -> db.update.id', async () => {+ await runOp('memory update', async () => ({ message: 'ok' }), ['mem-2', 'new text']);+ expect(attrs()[SemanticConvention.DB_UPDATE_ID]).toBe('mem-2');+ });++ it('delete -> db.delete.id', async () => {+ await runOp('memory delete', async () => ({ message: 'ok' }), ['mem-3']);+ expect(attrs()[SemanticConvention.DB_DELETE_ID]).toBe('mem-3');+ });+ });++ describe('Operation: getAll / deleteAll', () => {+ it('getAll uses the snake_case span name and reads scope from its first-arg config', async () => {+ await runOp('memory get_all', async () => ({ results: [{ id: 'm1' }, { id: 'm2' }, { id: 'm3' }] }), [+ { userId: 'bob' },+ ]);+ const a = attrs();++ expect(mockTracer.startSpan).toHaveBeenCalledWith('memory get_all', { kind: SpanKind.CLIENT });+ expect(a[SemanticConvention.GEN_AI_USER_ID]).toBe('bob');+ expect(a[SemanticConvention.GEN_AI_MEMORY_OPERATION_RESULT_COUNT]).toBe(3);+ });++ it('deleteAll uses the snake_case span name', async () => {+ await runOp('memory delete_all', async () => ({ message: 'ok' }), [{ userId: 'bob' }]);+ expect(mockTracer.startSpan).toHaveBeenCalledWith('memory delete_all', { kind: SpanKind.CLIENT });+ });++ it('reset uses the Python endpoint span name', async () => {+ await runOp('memory reset', async () => ({ message: 'ok' }), []);+ expect(mockTracer.startSpan).toHaveBeenCalledWith('memory reset', { kind: SpanKind.CLIENT });+ expect(attrs()[SemanticConvention.GEN_AI_ENDPOINT]).toBe('memory reset');+ expect(attrs()[SemanticConvention.GEN_AI_OPERATION]).toBe(SemanticConvention.GEN_AI_OPERATION_TYPE_MEMORY);+ });+ });++ describe('Content capture toggle', () => {+ it('omits input/output content when captureMessageContent is false', async () => {+ (OpenlitConfig as any).captureMessageContent = false;+ await runOp('memory add', async () => ({ results: [] }), [+ [{ role: 'user', content: 'secret' }],+ {},+ ]);+ const keys = (mockSpan.setAttribute as jest.Mock).mock.calls.map(([k]: [string]) => k);+ expect(keys).not.toContain(SemanticConvention.GEN_AI_INPUT_MESSAGES);+ });+ });++ describe('Error path', () => {+ it('records the exception, still ends the span, and rethrows', async () => {+ const boom = new Error('mem0 down');+ await expect(+ runOp('memory search', async () => {+ throw boom;+ }, ['q', { topK: 3 }])+ ).rejects.toThrow('mem0 down');++ expect((OpenLitHelper as any).handleException).toHaveBeenCalledWith(mockSpan, boom);+ expect(mockSpan.end).toHaveBeenCalledTimes(1);+ // Core attributes are still emitted on the error path (best-effort).+ expect(attrs()[SemanticConvention.GEN_AI_PROVIDER_NAME]).toBe('mem0');+ expect(typeof attrs()[SemanticConvention.GEN_AI_CLIENT_OPERATION_DURATION]).toBe('number');+ });+ });+});diff --git a/sdk/typescript/src/instrumentation/index.ts b/sdk/typescript/src/instrumentation/index.tsindex 0cc91d28..ab296c10 100644--- a/sdk/typescript/src/instrumentation/index.ts+++ b/sdk/typescript/src/instrumentation/index.ts@@ -32,6 +32,7 @@ import ClaudeAgentSDKInstrumentation from './claude-agent-sdk';import CursorSDKInstrumentation from './cursor-sdk';import AstraInstrumentation from './astra';import MCPInstrumentation from './mcp';+import Mem0Instrumentation from './mem0';/*** OTel community instrumentations loaded dynamically (like Python SDK).@@ -106,6 +107,7 @@ export default class Instrumentations {'cursor-sdk': new CursorSDKInstrumentation(),'astra': new AstraInstrumentation(),mcp: new MCPInstrumentation(),+ mem0: new Mem0Instrumentation(),};static setup(diff --git a/sdk/typescript/src/instrumentation/mem0/index.ts b/sdk/typescript/src/instrumentation/mem0/index.tsnew file mode 100644index 00000000..311e3138--- /dev/null+++ b/sdk/typescript/src/instrumentation/mem0/index.ts@@ -0,0 +1,135 @@+import {+ InstrumentationBase,+ InstrumentationModuleDefinition,+ InstrumentationNodeModuleDefinition,+ InstrumentationNodeModuleFile,+ isWrapped,+} from '@opentelemetry/instrumentation';+import { InstrumentationConfig } from '@opentelemetry/instrumentation';+import { diag } from '@opentelemetry/api';+import { INSTRUMENTATION_PREFIX } from '../../constant';+import Mem0Wrapper from './wrapper';++export interface Mem0InstrumentationConfig extends InstrumentationConfig {}++/**+ * mem0 method name -> span name. Span names reuse the Python endpoint strings+ * (snake_case `get_all` / `delete_all`) so TS and Python emit identical span names,+ * even though the JS methods are camelCase (`getAll` / `deleteAll`).+ */+const MEM0_METHODS: Array<[string, string]> = [+ ['add', 'memory add'],+ ['search', 'memory search'],+ ['get', 'memory get'],+ ['getAll', 'memory get_all'],+ ['update', 'memory update'],+ ['delete', 'memory delete'],+ ['deleteAll', 'memory delete_all'],+ ['history', 'memory history'],+ ['reset', 'memory reset'],+];++export default class OpenlitMem0Instrumentation extends InstrumentationBase {+ constructor(config: Mem0InstrumentationConfig = {}) {+ super(`${INSTRUMENTATION_PREFIX}/instrumentation-mem0`, '1.0.0', config);+ }++ protected init(): void | InstrumentationModuleDefinition | InstrumentationModuleDefinition[] {+ // mem0ai ships two clients at two specifiers:+ // - `mem0ai` -> hosted MemoryClient (the package entry, patched below)+ // - `mem0ai/oss` -> self-hosted Memory (an internal file)+ // require-in-the-middle reaches internal files via the `files` array, so the OSS+ // entry is registered as InstrumentationNodeModuleFile(s) on the main definition.+ // A few candidate paths are listed to stay robust across build layouts.+ const ossFiles = ['mem0ai/dist/oss/index.js', 'mem0ai/dist/oss/index.cjs', 'mem0ai/oss/index.js'].map(+ (filePath) =>+ new InstrumentationNodeModuleFile(+ filePath,+ ['>=0.1.32'],+ (moduleExports: any, moduleVersion?: string) => {+ this._patchOss(moduleExports, moduleVersion);+ return moduleExports;+ },+ (moduleExports: any) => {+ if (moduleExports !== undefined) this._unpatchOss(moduleExports);+ }+ )+ );++ const module = new InstrumentationNodeModuleDefinition(+ 'mem0ai',+ ['>=0.1.32'],+ (moduleExports: any, moduleVersion?: string) => {+ this._patch(moduleExports, moduleVersion);+ return moduleExports;+ },+ (moduleExports: any) => {+ if (moduleExports !== undefined) this._unpatch(moduleExports);+ },+ ossFiles+ );++ return [module];+ }++ public manualPatch(mem0: any): void {+ // Manual entry point (openlit.init({ instrumentations: { mem0 } })). The caller may+ // pass either the hosted module/class or the OSS one, so try both resolvers — the+ // isWrapped guard in _patchClass keeps it idempotent.+ this._patch(mem0);+ this._patchOss(mem0);+ }++ /** Patch the hosted MemoryClient (default export of `mem0ai`). */+ protected _patch(moduleExports: any, moduleVersion?: string) {+ const ClientClass = moduleExports?.MemoryClient ?? moduleExports?.default ?? moduleExports;+ this._patchClass(ClientClass, moduleVersion);+ }++ /** Patch the self-hosted Memory class (`mem0ai/oss`). */+ protected _patchOss(moduleExports: any, moduleVersion?: string) {+ const MemoryClass = moduleExports?.Memory ?? moduleExports?.default ?? moduleExports;+ this._patchClass(MemoryClass, moduleVersion);+ }++ private _patchClass(target: any, moduleVersion?: string) {+ try {+ const proto = target?.prototype;+ if (!proto) return;++ for (const [method, spanName] of MEM0_METHODS) {+ if (typeof proto[method] !== 'function') continue;+ if (isWrapped(proto[method])) {+ this._unwrap(proto, method);+ }+ this._wrap(proto, method, Mem0Wrapper._patchMemoryOperation(this.tracer, spanName, moduleVersion));+ }+ } catch (e) {+ diag.error('mem0 instrumentation: error in _patch method', e);+ }+ }++ protected _unpatch(moduleExports: any) {+ const ClientClass = moduleExports?.MemoryClient ?? moduleExports?.default ?? moduleExports;+ this._unpatchClass(ClientClass);+ }++ protected _unpatchOss(moduleExports: any) {+ const MemoryClass = moduleExports?.Memory ?? moduleExports?.default ?? moduleExports;+ this._unpatchClass(MemoryClass);+ }++ private _unpatchClass(target: any) {+ try {+ const proto = target?.prototype;+ if (!proto) return;+ for (const [method] of MEM0_METHODS) {+ if (typeof proto[method] === 'function' && isWrapped(proto[method])) {+ this._unwrap(proto, method);+ }+ }+ } catch {+ /* ignore */+ }+ }+}diff --git a/sdk/typescript/src/instrumentation/mem0/wrapper.ts b/sdk/typescript/src/instrumentation/mem0/wrapper.tsnew file mode 100644index 00000000..5838dd66--- /dev/null+++ b/sdk/typescript/src/instrumentation/mem0/wrapper.ts@@ -0,0 +1,269 @@+import { SpanKind, SpanStatusCode, Tracer, context, trace } from '@opentelemetry/api';+import { ATTR_SERVICE_NAME, ATTR_TELEMETRY_SDK_NAME } from '@opentelemetry/semantic-conventions';+import OpenlitConfig from '../../config';+import { SDK_NAME } from '../../constant';+import OpenLitHelper, { applyCustomSpanAttributes } from '../../helpers';+import SemanticConvention from '../../semantic-convention';++// `gen_ai.sdk.version` reports the *instrumented* package version (mem0ai), matching+// the Python SDK (importlib.metadata.version("mem0ai")) rather than OpenLIT's version.+// The reliable source is the version OTel passes to the patch hook, threaded in as the+// `version` arg of _patchMemoryOperation. This module-level require is only a fallback+// for manualPatch — and note mem0ai's "exports" map blocks `mem0ai/package.json`, so it+// resolves to 'unknown' for mem0ai itself; that's fine, the OTel-provided version wins.+let mem0SdkVersion = 'unknown';+try {+ // eslint-disable-next-line @typescript-eslint/no-var-requires+ mem0SdkVersion = require('mem0ai/package.json')?.version || 'unknown';+} catch {+ mem0SdkVersion = 'unknown';+}++/**+ * Wrapper for mem0 memory-layer operations. mem0 exposes the same method surface on+ * the hosted `MemoryClient` (`mem0ai`) and the self-hosted `Memory` (`mem0ai/oss`):+ * add / search / get / getAll / update / delete / deleteAll / history. Every method+ * returns a Promise, so a single async wrapper handles them all. The emitted spans+ * mirror the Python reference (sdk/python/src/openlit/instrumentation/mem0): one+ * CLIENT span per call named `memory <op>`, with `gen_ai.*` attributes. No tokens,+ * model, cost, or metrics are involved (matching Python) so this does not use the+ * chat-oriented BaseWrapper.+ */+class Mem0Wrapper {+ static aiSystem = SemanticConvention.GEN_AI_SYSTEM_MEM0;++ /**+ * Returns a wrapper (over an original Promise-returning method) that emits one+ * `memory <op>` CLIENT span. `spanName` is the Python endpoint string, e.g.+ * `memory add` or `memory get_all`.+ */+ static _patchMemoryOperation(tracer: Tracer, spanName: string, version?: string): any {+ const sdkVersion = version || mem0SdkVersion;+ return (originalMethod: (...args: any[]) => any) => {+ return async function (this: any, ...args: any[]) {+ const span = tracer.startSpan(spanName, { kind: SpanKind.CLIENT });+ const startTime = Date.now();++ return context.with(trace.setSpan(context.active(), span), async () => {+ try {+ const response = await originalMethod.apply(this, args);+ const duration = (Date.now() - startTime) / 1000;++ Mem0Wrapper._setSpanAttributes(span, spanName, args, response, sdkVersion);+ span.setAttribute(SemanticConvention.GEN_AI_CLIENT_OPERATION_DURATION, duration);+ Mem0Wrapper._setContentAttributes(span, spanName, args, response);++ span.setStatus({ code: SpanStatusCode.OK });+ return response;+ } catch (e: any) {+ const duration = (Date.now() - startTime) / 1000;+ span.setAttribute(SemanticConvention.GEN_AI_CLIENT_OPERATION_DURATION, duration);+ try {+ Mem0Wrapper._setSpanAttributes(span, spanName, args, undefined, sdkVersion);+ } catch {+ /* best-effort attributes on the error path */+ }+ OpenLitHelper.handleException(span, e);+ throw e;+ } finally {+ span.end();+ }+ });+ };+ };+ }++ /** Sets every non-content attribute (core + scope + memory + operation + response). */+ static _setSpanAttributes(+ span: any,+ spanName: string,+ args: any[],+ response?: any,+ sdkVersion: string = mem0SdkVersion+ ) {+ const applicationName = OpenlitConfig.applicationName || '';+ const environment = OpenlitConfig.environment || '';++ // Core attributes (set on every memory span).+ span.setAttribute(ATTR_TELEMETRY_SDK_NAME, SDK_NAME);+ // Set both provider-name keys to 'mem0': gen_ai.system (the key Python mem0 uses)+ // and gen_ai.provider.name (the OTel framework convention). Same value either way.+ span.setAttribute(SemanticConvention.GEN_AI_PROVIDER_NAME, Mem0Wrapper.aiSystem);+ span.setAttribute(SemanticConvention.GEN_AI_PROVIDER_NAME_OTEL, Mem0Wrapper.aiSystem);+ span.setAttribute(SemanticConvention.GEN_AI_ENDPOINT, spanName);+ span.setAttribute(SemanticConvention.GEN_AI_OPERATION, SemanticConvention.GEN_AI_OPERATION_TYPE_MEMORY);+ span.setAttribute(SemanticConvention.ATTR_DEPLOYMENT_ENVIRONMENT, environment);+ span.setAttribute(ATTR_SERVICE_NAME, applicationName);+ span.setAttribute(SemanticConvention.GEN_AI_SDK_VERSION, sdkVersion);++ const config = Mem0Wrapper._extractConfig(spanName, args);++ // Session scope — present either at the top level of the config object or inside a+ // nested `filters` object, in camelCase (v3 SDK) or snake_case (filters / hosted API).+ const userId = Mem0Wrapper._scopeValue(config, 'userId', 'user_id');+ const agentId = Mem0Wrapper._scopeValue(config, 'agentId', 'agent_id');+ const runId = Mem0Wrapper._scopeValue(config, 'runId', 'run_id');+ if (userId !== undefined) span.setAttribute(SemanticConvention.GEN_AI_USER_ID, userId);+ if (agentId !== undefined) span.setAttribute(SemanticConvention.GEN_AI_AGENT_ID, agentId);+ if (runId !== undefined) span.setAttribute(SemanticConvention.GEN_AI_RUN_ID, runId);++ // Memory type / metadata.+ const memoryType = config?.memoryType ?? config?.memory_type;+ if (memoryType !== undefined) {+ span.setAttribute(SemanticConvention.GEN_AI_MEMORY_TYPE, memoryType);+ }+ if (config?.metadata !== undefined && config?.metadata !== null) {+ span.setAttribute(+ SemanticConvention.GEN_AI_MEMORY_METADATA,+ Mem0Wrapper._safeStringify(config.metadata)+ );+ }++ Mem0Wrapper._setOperationAttributes(span, spanName, args, config);+ Mem0Wrapper._setResponseAttributes(span, response);++ applyCustomSpanAttributes(span);+ }++ private static _setOperationAttributes(span: any, spanName: string, args: any[], config: any) {+ switch (spanName) {+ case 'memory add': {+ const messages = args[0];+ if (config && Object.prototype.hasOwnProperty.call(config, 'infer')) {+ span.setAttribute(SemanticConvention.GEN_AI_MEMORY_INFER, config.infer);+ }+ if (Mem0Wrapper._hasMessages(messages)) {+ const count = Array.isArray(messages) ? messages.length : 1;+ span.setAttribute(SemanticConvention.GEN_AI_MEMORY_COUNT, count);+ }+ break;+ }+ case 'memory search': {+ const query = args[0];+ if (query !== undefined) {+ span.setAttribute(SemanticConvention.GEN_AI_MEMORY_SEARCH_QUERY, query);+ }+ // v3 SDK uses `topK`; older / hosted shapes use `limit`.+ const limit = config?.topK ?? config?.limit;+ if (limit !== undefined) {+ span.setAttribute(SemanticConvention.GEN_AI_MEMORY_SEARCH_LIMIT, limit);+ }+ if (config?.threshold !== undefined) {+ span.setAttribute(SemanticConvention.GEN_AI_MEMORY_SEARCH_THRESHOLD, config.threshold);+ }+ break;+ }+ case 'memory update': {+ const memoryId = args[0];+ if (memoryId !== undefined) span.setAttribute(SemanticConvention.DB_UPDATE_ID, memoryId);+ break;+ }+ case 'memory delete': {+ const memoryId = args[0];+ if (memoryId !== undefined) span.setAttribute(SemanticConvention.DB_DELETE_ID, memoryId);+ break;+ }+ case 'memory get': {+ const memoryId = args[0];+ if (memoryId !== undefined) span.setAttribute(SemanticConvention.DB_OPERATION_ID, memoryId);+ break;+ }+ default:+ // get_all, delete_all, history: no extra operation-specific id attribute.+ break;+ }+ }++ private static _setResponseAttributes(span: any, response: any) {+ if (!response) return;++ let count: number;+ if (Array.isArray(response)) {+ count = response.length;+ } else if (typeof response === 'object') {+ // A results array reflects the true count — an empty list is 0; a single-object+ // response (e.g. get / update) counts as 1. NOTE: the Python reference reports 1+ // for an empty results list (its `if results` is falsy on []); we intentionally+ // report the accurate 0 here (per a Sourcery review; Python sync tracked separately).+ count = Array.isArray(response.results) ? response.results.length : 1;+ } else {+ count = 1;+ }++ span.setAttribute(SemanticConvention.GEN_AI_MEMORY_OPERATION_RESULT_COUNT, count);+ span.setAttribute(SemanticConvention.GEN_AI_DATA_SOURCES, count);+ }++ /** Captures input (add) / output (search) content when capture is enabled. */+ static _setContentAttributes(span: any, spanName: string, args: any[], response: any) {+ if (!OpenlitConfig.captureMessageContent) return;++ try {+ if (spanName === 'memory add') {+ const messages = args[0];+ if (Mem0Wrapper._hasMessages(messages)) {+ const content =+ typeof messages === 'object' ? Mem0Wrapper._safeStringify(messages) : String(messages);+ span.setAttribute(SemanticConvention.GEN_AI_INPUT_MESSAGES, content);+ }+ }+ if (spanName === 'memory search' && response) {+ const content =+ typeof response === 'object' ? Mem0Wrapper._safeStringify(response) : String(response);+ span.setAttribute(SemanticConvention.GEN_AI_OUTPUT_MESSAGES, content);+ }+ } catch {+ /* best-effort content capture */+ }+ }++ /**+ * Returns the options/config object for an operation, accounting for the fact that+ * its argument position differs by method: add/search take it as the 2nd arg, while+ * getAll/deleteAll take it as the 1st. get/update/history take a positional id and+ * carry no scope config.+ */+ private static _extractConfig(spanName: string, args: any[]): any {+ switch (spanName) {+ case 'memory add':+ case 'memory search':+ case 'memory delete':+ return args[1] && typeof args[1] === 'object' ? args[1] : {};+ case 'memory get_all':+ case 'memory delete_all':+ return args[0] && typeof args[0] === 'object' ? args[0] : {};+ default:+ return {};+ }+ }++ private static _scopeValue(config: any, camelKey: string, snakeKey: string): any {+ if (!config || typeof config !== 'object') return undefined;+ if (config[camelKey] !== undefined) return config[camelKey];+ if (config[snakeKey] !== undefined) return config[snakeKey];+ const filters = config.filters;+ if (filters && typeof filters === 'object') {+ if (filters[camelKey] !== undefined) return filters[camelKey];+ if (filters[snakeKey] !== undefined) return filters[snakeKey];+ }+ return undefined;+ }++ private static _hasMessages(messages: any): boolean {+ if (messages === undefined || messages === null) return false;+ if (Array.isArray(messages)) return messages.length > 0;+ if (typeof messages === 'string') return messages.length > 0;+ return true;+ }++ private static _safeStringify(value: any): string {+ if (typeof value === 'string') return value;+ try {+ return JSON.stringify(value);+ } catch {+ return String(value);+ }+ }+}++export default Mem0Wrapper;diff --git a/sdk/typescript/src/semantic-convention.ts b/sdk/typescript/src/semantic-convention.tsindex c76e3476..c9cf11ff 100644--- a/sdk/typescript/src/semantic-convention.ts+++ b/sdk/typescript/src/semantic-convention.ts@@ -211,7 +211,8 @@ export default class SemanticConvention {static GEN_AI_OPERATION_TYPE_AGENT = 'invoke_agent';static GEN_AI_OPERATION_TYPE_TOOLS = 'execute_tool';static GEN_AI_OPERATION_TYPE_RETRIEVE = 'retrieval';-+ static GEN_AI_OPERATION_TYPE_MEMORY = 'memory';+// GenAI Output Typesstatic GEN_AI_OUTPUT_TYPE_TEXT = 'text';static GEN_AI_OUTPUT_TYPE_JSON = 'json';@@ -245,6 +246,7 @@ export default class SemanticConvention {static GEN_AI_SYSTEM_STRANDS = 'strands_agents';static GEN_AI_SYSTEM_CURSOR = 'cursor';static GEN_AI_SYSTEM_MCP = 'mcp';+ static GEN_AI_SYSTEM_MEM0 = 'mem0';// ----- MCP (Model Context Protocol) -----// Operation types@@ -498,6 +500,20 @@ export default class SemanticConvention {static DB_WITH_PAYLOAD = 'db.with_payload';static DB_OUTPUT_FIELDS = 'db.output_fields';+ // ----- Mem0 (memory layer) instrumentation -----+ // Session scope (mirrors Python semcov; stamped on memory spans when present)+ static GEN_AI_USER_ID = 'gen_ai.user.id';+ static GEN_AI_RUN_ID = 'gen_ai.run.id';+ // Memory operation attributes+ static GEN_AI_MEMORY_TYPE = 'gen_ai.memory.type';+ static GEN_AI_MEMORY_METADATA = 'gen_ai.memory.metadata';+ static GEN_AI_MEMORY_INFER = 'gen_ai.memory.infer';+ static GEN_AI_MEMORY_COUNT = 'gen_ai.memory.count';+ static GEN_AI_MEMORY_SEARCH_QUERY = 'gen_ai.memory.search.query';+ static GEN_AI_MEMORY_SEARCH_LIMIT = 'gen_ai.memory.search.limit';+ static GEN_AI_MEMORY_SEARCH_THRESHOLD = 'gen_ai.memory.search.threshold';+ static GEN_AI_MEMORY_OPERATION_RESULT_COUNT = 'gen_ai.memory.operation.result_count';+// ----- Guard System -----static GUARD_REQUESTS = 'guard.requests';static GUARD_VERDICT = 'guard.verdict';diff --git a/sdk/typescript/src/types.ts b/sdk/typescript/src/types.tsindex be41c711..0c5e9591 100644--- a/sdk/typescript/src/types.ts+++ b/sdk/typescript/src/types.ts@@ -3,7 +3,7 @@ import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';import { metrics } from '@opentelemetry/api';import type { Guard } from './guard/base';-export type InstrumentationType = 'openai' | 'anthropic' | 'cohere' | 'groq' | 'mistral' | 'google-ai' | 'vertexai' | 'together' | 'ollama' | 'vercel-ai' | 'langchain' | 'langgraph' | 'pinecone' | 'bedrock' | 'llamaindex' | 'huggingface' | 'replicate' | 'chroma' | 'qdrant' | 'milvus' | 'astra' | 'azure-ai-inference' | 'openai-agents' | 'strands' | 'google-adk' | 'claude-agent-sdk' | 'cursor-sdk' | 'ai21' | 'gradient' | 'mcp';+export type InstrumentationType = 'openai' | 'anthropic' | 'cohere' | 'groq' | 'mistral' | 'google-ai' | 'vertexai' | 'together' | 'ollama' | 'vercel-ai' | 'langchain' | 'langgraph' | 'pinecone' | 'bedrock' | 'llamaindex' | 'huggingface' | 'replicate' | 'chroma' | 'qdrant' | 'milvus' | 'astra' | 'azure-ai-inference' | 'openai-agents' | 'strands' | 'google-adk' | 'claude-agent-sdk' | 'cursor-sdk' | 'ai21' | 'gradient' | 'mcp' | 'mem0';export type OpenlitInstrumentations = Partial<Record<InstrumentationType, any>>;