🤯 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
🐛 fix(server,memory-user-memory): embedding token exceeded, should limit and cut off searched memory query (#14757)
Nekoe8b7fe14e162
diff --git a/src/app/(backend)/api/dev/memory-user-memory/benchmark-locomo/route.ts b/src/app/(backend)/api/dev/memory-user-memory/benchmark-locomo/route.tsindex f12db224923..0a67a63687a 100644--- a/src/app/(backend)/api/dev/memory-user-memory/benchmark-locomo/route.ts+++ b/src/app/(backend)/api/dev/memory-user-memory/benchmark-locomo/route.ts@@ -1,7 +1,4 @@-import {- DEFAULT_USER_MEMORY_EMBEDDING_DIMENSIONS,- DEFAULT_USER_MEMORY_EMBEDDING_MODEL_ITEM,-} from '@lobechat/const';+import { DEFAULT_USER_MEMORY_EMBEDDING_MODEL_ITEM } from '@lobechat/const';import { ModelRuntime } from '@lobechat/model-runtime';import { and, eq, inArray } from 'drizzle-orm';import { NextResponse } from 'next/server';@@ -12,6 +9,7 @@ import { userMemories } from '@/database/schemas';import { getServerDB } from '@/database/server';import { selectNonVectorColumns } from '@/database/utils/columns';import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';+import { embedUserMemoryTexts } from '@/server/services/memory/userMemory/embedding';import { LayersEnum } from '@/types/userMemory';const bodySchema = z.object({@@ -65,12 +63,13 @@ export const POST = async (req: Request) => {},);- const [embedding] =- (await runtime.embeddings({- dimensions: DEFAULT_USER_MEMORY_EMBEDDING_DIMENSIONS,- input: parsed.query,- model: config.embedding.model,- })) || [];+ const [embedding] = await embedUserMemoryTexts({+ input: [parsed.query],+ model: config.embedding.model,+ runtime,+ source: 'dev:locomo.search',+ userId,+ });if (!embedding) {return NextResponse.json(diff --git a/src/server/globalConfig/parseMemoryExtractionConfig.ts b/src/server/globalConfig/parseMemoryExtractionConfig.tsindex 266cd6f5a2c..45e59bb3ad9 100644--- a/src/server/globalConfig/parseMemoryExtractionConfig.ts+++ b/src/server/globalConfig/parseMemoryExtractionConfig.ts@@ -25,6 +25,15 @@ const parseTokenLimitEnv = (value?: string) => {return Math.floor(parsed);};+// NOTICE:+// Memory context limit envs reserve only the dynamic context slice that we trim before requests.+// The final provider request still adds system prompts, user prompt wrappers, JSON schemas, tools,+// and response tokens. Configure layer/persona limits to 65%-75% of the provider context window,+// not the hard model maximum. For example, a 272000-token provider limit should use roughly+// 176800-204000 here so wrappers cannot push the final request over the limit.+// TODO: Move these provider-window assumptions to model-bank once it exposes context-window and+// embedding-input-limit capability metadata for each model.+export type MemoryAgentConfig = MemoryAgentPublicConfig & {apiKey?: string;language?: string;@@ -90,6 +99,7 @@ const parseLayerExtractorAgent = (fallbackModel: string): MemoryLayerExtractorCoconst baseURL = process.env.MEMORY_USER_MEMORY_LAYER_EXTRACTOR_BASE_URL;const model = process.env.MEMORY_USER_MEMORY_LAYER_EXTRACTOR_MODEL || fallbackModel;const provider = process.env.MEMORY_USER_MEMORY_LAYER_EXTRACTOR_PROVIDER || DEFAULT_MINI_PROVIDER;+ // Keep this below the model hard limit; see the headroom notice above.const contextLimit = parseTokenLimitEnv(process.env.MEMORY_USER_MEMORY_LAYER_EXTRACTOR_CONTEXT_LIMIT,);@@ -132,6 +142,8 @@ const parseEmbeddingAgent = (return {apiKey: process.env.MEMORY_USER_MEMORY_EMBEDDING_API_KEY ?? fallbackApiKey,baseURL: process.env.MEMORY_USER_MEMORY_EMBEDDING_BASE_URL,+ // Embedding providers often have a smaller per-input limit than chat models.+ // Keep this below the provider's single-input embedding window.contextLimit: parseTokenLimitEnv(process.env.MEMORY_USER_MEMORY_EMBEDDING_CONTEXT_LIMIT),model,provider,@@ -152,6 +164,7 @@ const parsePersonaWriterAgent = (return {apiKey: process.env.MEMORY_USER_MEMORY_PERSONA_WRITER_API_KEY ?? fallbackApiKey,baseURL: process.env.MEMORY_USER_MEMORY_PERSONA_WRITER_BASE_URL,+ // Keep this below the model hard limit; see the headroom notice above.contextLimit: parseTokenLimitEnv(process.env.MEMORY_USER_MEMORY_PERSONA_WRITER_CONTEXT_LIMIT),model,provider,diff --git a/src/server/routers/lambda/userMemories.ts b/src/server/routers/lambda/userMemories.tsindex 3939cf51325..7928659d14d 100644--- a/src/server/routers/lambda/userMemories.ts+++ b/src/server/routers/lambda/userMemories.ts@@ -1,7 +1,6 @@import { BRANDING_PROVIDER, ENABLE_BUSINESS_FEATURES } from '@lobechat/business-const';import {DEFAULT_SEARCH_USER_MEMORY_TOP_K,- DEFAULT_USER_MEMORY_EMBEDDING_DIMENSIONS,DEFAULT_USER_MEMORY_EMBEDDING_MODEL_ITEM,MEMORY_SEARCH_TOP_K_LIMITS,} from '@lobechat/const';@@ -16,12 +15,7 @@ import {UpdateIdentityActionSchema,} from '@lobechat/memory-user-memory';import type { QueryTaxonomyOptionsResult, SearchMemoryResult } from '@lobechat/types';-import {- LayersEnum,- queryTaxonomyOptionsSchema,- RequestTrigger,- searchMemorySchema,-} from '@lobechat/types';+import { LayersEnum, queryTaxonomyOptionsSchema, searchMemorySchema } from '@lobechat/types';import { type SQL } from 'drizzle-orm';import { and, asc, eq, gte, lte } from 'drizzle-orm';import pMap from 'p-map';@@ -51,6 +45,8 @@ import { authedProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { getServerDefaultFilesConfig } from '@/server/globalConfig';import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';+import type { UserMemoryEmbeddingRuntime } from '@/server/services/memory/userMemory/embedding';+import { embedUserMemoryTexts } from '@/server/services/memory/userMemory/embedding';import { normalizeSearchMemoryParams } from '@/server/services/memory/userMemory/searchParams';const EMPTY_SEARCH_RESULT: SearchMemoryResult = {@@ -133,14 +129,15 @@ const searchUserMemories = async (const queryEmbeddings =normalizedQueries.length > 0- ? await modelRuntime.embeddings(- {- dimensions: DEFAULT_USER_MEMORY_EMBEDDING_DIMENSIONS,+ ? (+ await embedUserMemoryTexts({input: normalizedQueries,model: embeddingModel,- },- { metadata: { trigger: RequestTrigger.Memory }, user: ctx.userId },- )+ runtime: modelRuntime,+ source: 'lambda:userMemories.search',+ userId: ctx.userId,+ })+ ).filter((embedding): embedding is number[] => Boolean(embedding)): [];const effectiveEffort = normalizeMemoryEffort(normalizedInput.effort ?? ctx.memoryEffort);@@ -176,20 +173,23 @@ const getEmbeddingRuntime = async (serverDB: LobeChatDatabase, userId: string) =return { agentRuntime, embeddingModel };};-const createEmbedder = (agentRuntime: any, embeddingModel: string, userId: string) => {+const createEmbedder = (+ agentRuntime: UserMemoryEmbeddingRuntime,+ embeddingModel: string,+ userId: string,+) => {return async (value?: string | null): Promise<number[] | undefined> => {if (!value || value.trim().length === 0) return undefined;- const embeddings = await agentRuntime.embeddings(- {- dimensions: DEFAULT_USER_MEMORY_EMBEDDING_DIMENSIONS,- input: value,- model: embeddingModel,- },- { metadata: { trigger: RequestTrigger.Memory }, user: userId },- );+ const [embedding] = await embedUserMemoryTexts({+ input: [value],+ model: embeddingModel,+ runtime: agentRuntime,+ source: 'lambda:userMemories.tool',+ userId,+ });- return embeddings?.[0];+ return embedding;};};@@ -469,20 +469,23 @@ export const userMemoriesRouter = router({const embedTexts = async (texts: string[]): Promise<number[][]> => {if (texts.length === 0) return [];- const response = await agentRuntime.embeddings(- {- dimensions: DEFAULT_USER_MEMORY_EMBEDDING_DIMENSIONS,- input: texts,- model: embeddingModel,- },- { metadata: { trigger: RequestTrigger.Memory }, user: ctx.userId },- );+ const response = await embedUserMemoryTexts({+ input: texts,+ model: embeddingModel,+ runtime: agentRuntime,+ source: 'lambda:userMemories.reEmbed',+ userId: ctx.userId,+ });- if (!response || response.length !== texts.length) {+ if (response.length !== texts.length) {throw new Error('Embedding response length mismatch');}- return response;+ return response.map((embedding) => {+ if (!embedding) throw new Error('Embedding response length mismatch');++ return embedding;+ });};const results: Partial<Record<ReEmbedTableKey, ReEmbedStats>> = {};diff --git a/src/server/services/memory/userMemory/__tests__/embedding.test.ts b/src/server/services/memory/userMemory/__tests__/embedding.test.tsnew file mode 100644index 00000000000..0a759c9e903--- /dev/null+++ b/src/server/services/memory/userMemory/__tests__/embedding.test.ts@@ -0,0 +1,105 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { UserMemoryEmbeddingRuntime } from '../embedding';+import { embedUserMemoryTexts } from '../embedding';++const mocks = vi.hoisted(() => ({+ contextLimit: 3 as number | undefined,+ encodeAsync: vi.fn(async (text: string) => text.split(/\s+/).filter(Boolean).length),+ trimBasedOnBatchProbe: vi.fn(async (text: string, limit?: number) =>+ text+ .split(/\s+/)+ .filter(Boolean)+ .slice(-(limit ?? 0))+ .join(' '),+ ),+}));++vi.mock('@/server/globalConfig/parseMemoryExtractionConfig', () => ({+ parseMemoryExtractionConfig: () => ({+ embedding: {+ contextLimit: mocks.contextLimit,+ },+ }),+}));++vi.mock('@/utils/chunkers', () => ({+ trimBasedOnBatchProbe: mocks.trimBasedOnBatchProbe,+}));++vi.mock('@/utils/tokenizer', () => ({+ encodeAsync: mocks.encodeAsync,+}));++describe('embedUserMemoryTexts', () => {+ beforeEach(() => {+ mocks.contextLimit = 3;+ vi.clearAllMocks();+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('trims long inputs and preserves output indexes', async () => {+ const runtime = {+ embeddings: vi.fn(async () => [+ [1, 2, 3],+ [4, 5, 6],+ ]),+ } satisfies UserMemoryEmbeddingRuntime;++ const result = await embedUserMemoryTexts({+ input: ['one two three four', '', null, 'short text'],+ model: 'text-embedding-3-large',+ runtime,+ source: 'test:source',+ userId: 'user-test',+ });++ expect(runtime.embeddings).toHaveBeenCalledWith(+ {+ dimensions: 1024,+ input: ['two three four', 'short text'],+ model: 'text-embedding-3-large',+ },+ { metadata: { trigger: 'memory' }, user: 'user-test' },+ );+ expect(result).toEqual([[1, 2, 3], undefined, undefined, [4, 5, 6]]);+ expect(console.warn).toHaveBeenCalledWith('[user-memory] trimmed embedding input', {+ limit: 3,+ model: 'text-embedding-3-large',+ originalTokens: 4,+ source: 'test:source',+ trimmedTokens: 3,+ userId: 'user-test',+ });+ });++ it('skips trimming when no context limit is configured', async () => {+ mocks.contextLimit = undefined;+ const runtime = {+ embeddings: vi.fn(async () => [[1, 2, 3]]),+ } satisfies UserMemoryEmbeddingRuntime;++ const result = await embedUserMemoryTexts({+ input: ['one two three four'],+ model: 'text-embedding-3-large',+ runtime,+ source: 'test:no-limit',+ userId: 'user-test',+ });++ expect(mocks.trimBasedOnBatchProbe).not.toHaveBeenCalled();+ expect(runtime.embeddings).toHaveBeenCalledWith(+ {+ dimensions: 1024,+ input: ['one two three four'],+ model: 'text-embedding-3-large',+ },+ { metadata: { trigger: 'memory' }, user: 'user-test' },+ );+ expect(result).toEqual([[1, 2, 3]]);+ });+});diff --git a/src/server/services/memory/userMemory/embedding.ts b/src/server/services/memory/userMemory/embedding.tsnew file mode 100644index 00000000000..884ebe1889d--- /dev/null+++ b/src/server/services/memory/userMemory/embedding.ts@@ -0,0 +1,122 @@+import { DEFAULT_USER_MEMORY_EMBEDDING_DIMENSIONS } from '@lobechat/const';+import type { ModelRuntime } from '@lobechat/model-runtime';+import { RequestTrigger } from '@lobechat/types';++import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';+import { trimBasedOnBatchProbe } from '@/utils/chunkers';+import { encodeAsync } from '@/utils/tokenizer';++export interface UserMemoryEmbeddingRuntime {+ /**+ * Runtime embedding method used by memory-specific call sites.+ */+ embeddings: ModelRuntime['embeddings'];+}++/**+ * Options for embedding user-memory text with memory-specific trimming.+ */+export interface EmbedUserMemoryTextsParams {+ /**+ * Embedding dimension requested by the memory table schema.+ *+ * @default DEFAULT_USER_MEMORY_EMBEDDING_DIMENSIONS+ */+ dimensions?: number;+ /**+ * User memory texts to embed. Empty values keep their output slot as `undefined`.+ */+ input: Array<string | null | undefined>;+ /**+ * Embedding model name passed to the runtime.+ */+ model: string;+ /**+ * Runtime that performs the provider request.+ */+ runtime: UserMemoryEmbeddingRuntime;+ /**+ * Stable call-site label used for trim diagnostics.+ */+ source: string;+ /**+ * User id passed to runtime billing/tracing metadata.+ */+ userId: string;+}++/**+ * Embeds user-memory text after applying the memory embedding context limit.+ *+ * Use when:+ * - User memory search, tools, or maintenance jobs call an embedding model+ * - Inputs may contain long chat/tool payloads or stored memory text+ *+ * Expects:+ * - `input` order must be meaningful to the caller+ * - `runtime.embeddings` returns vectors in request input order+ *+ * Returns:+ * - An output array with the same length as `input`+ * - `undefined` for empty values or values trimmed to empty text+ */+export const embedUserMemoryTexts = async (+ params: EmbedUserMemoryTextsParams,+): Promise<Array<number[] | undefined>> => {+ const { embedding } = parseMemoryExtractionConfig();+ // TODO: Prefer model-bank capability metadata for the embedding input window when available.+ const tokenLimit = embedding.contextLimit;+ const requests: Array<{ index: number; text: string }> = [];++ for (const [index, value] of params.input.entries()) {+ if (typeof value !== 'string') continue;++ const trimmedValue = value.trim();+ if (!trimmedValue) continue;++ const text = tokenLimit ? await trimBasedOnBatchProbe(trimmedValue, tokenLimit) : trimmedValue;+ const normalizedText = text.trim();+ if (!normalizedText) continue;++ if (tokenLimit) {+ const [originalTokens, trimmedTokens] = await Promise.all([+ encodeAsync(trimmedValue),+ encodeAsync(normalizedText),+ ]);++ if (trimmedTokens < originalTokens) {+ console.warn('[user-memory] trimmed embedding input', {+ limit: tokenLimit,+ model: params.model,+ originalTokens,+ source: params.source,+ trimmedTokens,+ userId: params.userId,+ });+ }+ }++ requests.push({ index, text: normalizedText });+ }++ const outputs = params.input.map<number[] | undefined>(() => undefined);+ if (requests.length === 0) return outputs;++ const embeddings = await params.runtime.embeddings(+ {+ dimensions: params.dimensions ?? DEFAULT_USER_MEMORY_EMBEDDING_DIMENSIONS,+ input: requests.map((item) => item.text),+ model: params.model,+ },+ { metadata: { trigger: RequestTrigger.Memory }, user: params.userId },+ );++ for (const [requestIndex, embeddingVector] of (embeddings ?? []).entries()) {+ const request = requests[requestIndex];+ if (!request || !embeddingVector) continue;++ outputs[request.index] = embeddingVector;+ }++ return outputs;+};diff --git a/src/server/services/toolExecution/serverRuntimes/memory.ts b/src/server/services/toolExecution/serverRuntimes/memory.tsindex b44f4b19cd1..fd90b583417 100644--- a/src/server/services/toolExecution/serverRuntimes/memory.ts+++ b/src/server/services/toolExecution/serverRuntimes/memory.ts@@ -5,7 +5,6 @@ import {} from '@lobechat/builtin-tool-memory/executionRuntime';import { BRANDING_PROVIDER, ENABLE_BUSINESS_FEATURES } from '@lobechat/business-const';import {- DEFAULT_USER_MEMORY_EMBEDDING_DIMENSIONS,DEFAULT_USER_MEMORY_EMBEDDING_MODEL_ITEM,MEMORY_SEARCH_TOP_K_LIMITS,} from '@lobechat/const';@@ -32,7 +31,7 @@ import type {SearchMemoryResult,UpdateIdentityMemoryResult,} from '@lobechat/types';-import { LayersEnum, RequestTrigger } from '@lobechat/types';+import { LayersEnum } from '@lobechat/types';import { eq } from 'drizzle-orm';import type { z } from 'zod';@@ -52,6 +51,8 @@ import {resolveToolOutcomeScope,} from '@/server/services/agentSignal/procedure';import { redisPolicyStateStore } from '@/server/services/agentSignal/store/adapters/redis/policyStateStore';+import type { UserMemoryEmbeddingRuntime } from '@/server/services/memory/userMemory/embedding';+import { embedUserMemoryTexts } from '@/server/services/memory/userMemory/embedding';import { normalizeSearchMemoryParams } from '@/server/services/memory/userMemory/searchParams';import type { ToolExecutionMemoryEmbeddingRuntime } from '../types';@@ -99,20 +100,23 @@ const getEmbeddingRuntime = async (serverDB: LobeChatDatabase, userId: string) =return { agentRuntime, embeddingModel };};-const createEmbedder = (agentRuntime: any, embeddingModel: string, userId: string) => {+const createEmbedder = (+ agentRuntime: UserMemoryEmbeddingRuntime,+ embeddingModel: string,+ userId: string,+) => {return async (value?: string | null): Promise<number[] | undefined> => {if (!value || value.trim().length === 0) return undefined;- const embeddings = await agentRuntime.embeddings(- {- dimensions: DEFAULT_USER_MEMORY_EMBEDDING_DIMENSIONS,- input: value,- model: embeddingModel,- },- { metadata: { trigger: RequestTrigger.Memory }, user: userId },- );+ const [embedding] = await embedUserMemoryTexts({+ input: [value],+ model: embeddingModel,+ runtime: agentRuntime,+ source: 'toolRuntime:userMemory.tool',+ userId,+ });- return embeddings?.[0];+ return embedding;};};@@ -215,14 +219,15 @@ class MemoryServerRuntimeService implements MemoryRuntimeService {const queryEmbeddings =normalizedQueries.length > 0- ? await modelRuntime.embeddings(- {- dimensions: DEFAULT_USER_MEMORY_EMBEDDING_DIMENSIONS,+ ? (+ await embedUserMemoryTexts({input: normalizedQueries,model: embeddingModel,- },- { metadata: { trigger: RequestTrigger.Memory }, user: this.userId },- )+ runtime: modelRuntime,+ source: 'toolRuntime:userMemory.search',+ userId: this.userId,+ })+ ).filter((embedding): embedding is number[] => Boolean(embedding)): [];const effectiveEffort = normalizeMemoryEffort(normalizedParams.effort ?? this.memoryEffort);