🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(memory-user-memory): support to extract memories from LoCoMo dataset (#10925)
Nekoc7c7d6f3c800
diff --git a/packages/memory-user-memory/benchmarks/locomo/run.ts b/packages/memory-user-memory/benchmarks/locomo/run.tsnew file mode 100644index 00000000000..979bba42eb2--- /dev/null+++ b/packages/memory-user-memory/benchmarks/locomo/run.ts@@ -0,0 +1,81 @@+import { MemorySourceType } from '@lobechat/types';+import { convertLocomoFile } from '../../src/converters/locomo';+import { exit } from 'node:process';++const baseUrl = process.env.MEMORY_USER_MEMORY_LOBEHUB_BASE_URL;+const benchmarkLoCoMoFile = process.env.MEMORY_USER_MEMORY_BENCHMARKS_LOCOMO_DATASETS;++const post = async (path: string, body: unknown) => {+ const res = await fetch(new URL(path, baseUrl).toString(), {+ body: JSON.stringify(body),+ headers: { 'Content-Type': 'application/json' },+ method: 'POST',+ });++ if (!res.ok) {+ const text = await res.text();+ throw new Error(`Request failed ${res.status}: ${text}`);+ }++ return res.json();+};++async function main() {+ if (!baseUrl || !benchmarkLoCoMoFile) {+ console.error(+ '[@lobechat/memory-user-memory/benchmarks/locomo] Missing required envs. Set MEMORY_USER_MEMORY_LOBEHUB_BASE_URL and MEMORY_USER_MEMORY_BENCHMARKS_LOCOMO_DATASETS.',+ );++ exit(1);+ }++ console.log(`[@lobechat/memory-user-memory/benchmarks/locomo] loading ${benchmarkLoCoMoFile}`);++ const payloads = convertLocomoFile(benchmarkLoCoMoFile, {+ includeImageCaptions: true,+ source: MemorySourceType.BenchmarkLocomo,+ speakerRoles: { defaultRole: 'user', speakerA: 'user', speakerB: 'assistant' },+ topicIdPrefix: 'sample',+ }).map((p, idx) => ({+ ...p,+ sampleId: `${idx + 1}`,+ topicId: `sample_${idx + 1}`,+ }));++ console.log(+ `[@lobechat/memory-user-memory/benchmarks/locomo] ingesting ${payloads.length} samples to ${baseUrl} (one user per sample)`,+ );++ const usedUserIds = new Set<string>();++ for (const payload of payloads) {+ const userId = `locomo-user-${payload.sampleId}`;+ usedUserIds.add(userId);++ const body = {+ ...payload,+ force: true,+ layers: [], // empty = all layers+ userId,+ };+ try {+ const res = await post('/api/webhooks/memory-extraction/benchmark-locomo', body);+ console.log(`[@lobechat/memory-user-memory/benchmarks/locomo] ingested sample ${payload.sampleId} -> insertedParts=${res.insertedParts ?? 'n/a'} memories=${res.extraction?.memoryIds?.length ?? 0} traceId=${res.extraction?.traceId ?? 'n/a'}`);+ } catch (err) {+ console.error(`[@lobechat/memory-user-memory/benchmarks/locomo] failed sample ${payload.sampleId}`, err);+ break;+ }+ }++ console.log(+ `[@lobechat/memory-user-memory/benchmarks/locomo] users used (${usedUserIds.size}): ${[+ ...usedUserIds,+ ].join(', ')}`,+ );+}++// eslint-disable-next-line unicorn/prefer-top-level-await+main().catch((e) => {+ console.error(e);+ exit(1);+});diff --git a/src/app/(backend)/api/webhooks/memory-extraction/benchmark-locomo/route.ts b/src/app/(backend)/api/webhooks/memory-extraction/benchmark-locomo/route.tsnew file mode 100644index 00000000000..8078802ab92--- /dev/null+++ b/src/app/(backend)/api/webhooks/memory-extraction/benchmark-locomo/route.ts@@ -0,0 +1,144 @@+import { NextResponse } from 'next/server';+import { z } from 'zod';++import { MemorySourceType } from '@lobechat/types';+import { BenchmarkLocomoContextProvider } from '@lobechat/memory-user-memory';+import { UserMemorySourceBenchmarkLoCoMoModel } from '@/database/models/userMemory/sources/benchmarkLoCoMo';+import { MemoryExtractionExecutor } from '@/server/services/memory/userMemory/extract';+import { LayersEnum } from '@/types/userMemory';+import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';++const turnSchema = z.object({+ createdAt: z.string().optional(),+ diaId: z.string().optional(),+ imageCaption: z.string().optional(),+ imageUrls: z.array(z.string()).optional(),+ role: z.string().optional(),+ speaker: z.string(),+ text: z.string(),+});++const sessionSchema = z.object({+ sessionId: z.string(),+ timestamp: z.string().optional(),+ turns: z.array(turnSchema),+});++const ingestSchema = z.object({+ force: z.boolean().optional(),+ layers: z.array(z.string()).optional(),+ sampleId: z.string(),+ sessions: z.array(sessionSchema),+ source: z.nativeEnum(MemorySourceType).optional(),+ sourceId: z.string().optional(),+ userId: z.string(),+});++const parseDate = (value?: string) => {+ if (!value) return new Date();+ const parsed = new Date(value);+ return Number.isNaN(parsed.getTime()) ? new Date() : parsed;+};++const normalizeLayers = (layers?: string[]) => {+ if (!layers?.length) return [] as LayersEnum[];++ const set = new Set<LayersEnum>();+ layers.forEach((layer) => {+ const normalized = layer.toLowerCase() as LayersEnum;+ if (Object.values(LayersEnum).includes(normalized)) {+ set.add(normalized);+ }+ });++ return Array.from(set);+};++export const POST = async (req: Request) => {+ try {+ const { webhookHeaders } = parseMemoryExtractionConfig();++ if (webhookHeaders && Object.keys(webhookHeaders).length > 0) {+ for (const [key, value] of Object.entries(webhookHeaders)) {+ const headerValue = req.headers.get(key);+ if (headerValue !== value) {+ return NextResponse.json(+ { error: `Unauthorized: Missing or invalid header '${key}'` },+ { status: 403 },+ );+ }+ }+ }++ const json = await req.json();+ const parsed = ingestSchema.parse(json);++ const sourceModel = new UserMemorySourceBenchmarkLoCoMoModel(parsed.userId);++ const sourceId = parsed.sourceId || `sample_${parsed.sampleId}`;+ await sourceModel.upsertSource({+ id: sourceId,+ metadata: { ingestAt: new Date().toISOString() },+ sampleId: parsed.sampleId,+ sourceType: (parsed.source ?? MemorySourceType.BenchmarkLocomo) as string,+ });++ let partCounter = 0;+ const parts = parsed.sessions.flatMap((session) => {+ return session.turns.map((turn) => {+ const createdAt = parseDate(turn.createdAt || session.timestamp);+ const metadata: Record<string, unknown> = {+ diaId: turn.diaId,+ imageCaption: turn.imageCaption,+ imageUrls: turn.imageUrls,+ sessionId: session.sessionId,+ };++ const part = {+ content: turn.text,+ createdAt,+ metadata,+ partIndex: partCounter,+ sessionId: session.sessionId,+ speaker: turn.speaker,+ };+ partCounter += 1;+ return part;+ });+ });++ await sourceModel.replaceParts(sourceId, parts);++ const contextProvider = new BenchmarkLocomoContextProvider({+ parts,+ sampleId: parsed.sampleId,+ sourceId,+ userId: parsed.userId,+ });++ const executor = await MemoryExtractionExecutor.create();+ const layers = normalizeLayers(parsed.layers);+ const extraction = await executor.extractBenchmarkSource({+ contextProvider,+ forceAll: parsed.force ?? true,+ layers,+ parts,+ source: parsed.source ?? MemorySourceType.BenchmarkLocomo,+ sourceId,+ userId: parsed.userId,+ });++ return NextResponse.json(+ {+ extraction,+ insertedParts: parts.length,+ sourceId,+ userId: parsed.userId,+ },+ { status: 200 },+ );+ } catch (error) {+ console.error('[locomo-ingest-webhook] failed', error);+ return NextResponse.json({ error: (error as Error).message }, { status: 500 });+ }+};diff --git a/src/server/services/memory/userMemory/extract.ts b/src/server/services/memory/userMemory/extract.tsindex f5895bdd47e..413d16cc265 100644--- a/src/server/services/memory/userMemory/extract.ts+++ b/src/server/services/memory/userMemory/extract.ts@@ -18,7 +18,7 @@ import type {BenchmarkLocomoPart,PersistedMemoryResult,} from '@lobechat/memory-user-memory';-import { UserMemorySourceModel } from '@/database/models/userMemory/source';+import { UserMemorySourceBenchmarkLoCoMoModel } from '@/database/models/userMemory/sources/benchmarkLoCoMo';import { ModelRuntime } from '@lobechat/model-runtime';import type {Embeddings,@@ -1298,7 +1298,7 @@ export class MemoryExtractionExecutor {}for (const userId of payload.userIds) {- const sourceModel = new UserMemorySourceModel(userId);+ const sourceModel = new UserMemorySourceBenchmarkLoCoMoModel(userId);for (const sourceId of benchmarkSourceIds) {const parts = await sourceModel.listParts(sourceId);if (!parts.length) {