Skip to content

🤯 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.

🐛 fix(memory): accept an empty extraction answer and fall back from retired LobeHub memory models (#23088)

Arvin Xu88263122a3e3
diff --git a/apps/server/src/services/memory/userMemory/__tests__/extract.retiredModels.test.ts b/apps/server/src/services/memory/userMemory/__tests__/extract.retiredModels.test.ts
new file mode 100644
index 00000000000..0576907627d
--- /dev/null
+++ b/apps/server/src/services/memory/userMemory/__tests__/extract.retiredModels.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({ isAvailable: vi.fn() }));
+
+vi.mock('@lobechat/business-const', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ BRANDING_PROVIDER: 'lobehub',
+}));
+vi.mock('@lobechat/business-model-bank/model-config', () => ({
+ isLobeHubModelAvailable: mocks.isAvailable,
+}));
+vi.mock('@lobechat/business-model-runtime', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ resolveBusinessModelMapping: async (_provider: string, model: string) => ({
+ resolvedModelId: model,
+ }),
+}));
+
+const { withoutRetiredLobeHubMemoryModels } = await import('../extract/runtime');
+
+describe('withoutRetiredLobeHubMemoryModels', () => {
+ it('drops a memory model choice that names a retired LobeHub model', async () => {
+ mocks.isAvailable.mockImplementation(async (model: string) => model !== 'retired-model');
+
+ const result = await withoutRetiredLobeHubMemoryModels(
+ {
+ memoryAnalysisAgentConfig: { model: 'retired-model', provider: 'lobehub' },
+ userMemoryEmbedding: { model: 'embed-model', provider: 'lobehub' },
+ } as never,
+ );
+
+ expect(result).toEqual({ userMemoryEmbedding: { model: 'embed-model', provider: 'lobehub' } });
+ expect(mocks.isAvailable).toHaveBeenCalledWith('retired-model', 'chat', {
+ userEmail: '[email protected]',
+ });
+ });
+
+ it('keeps choices on other providers without checking them', async () => {
+ mocks.isAvailable.mockReset();
+ const systemAgent = {
+ memoryAnalysisAgentConfig: { model: 'gone-from-openrouter', provider: 'openrouter' },
+ };
+
+ expect(await withoutRetiredLobeHubMemoryModels(systemAgent as never)).toBe(systemAgent);
+ expect(mocks.isAvailable).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/memory/userMemory/extract/extractTopic.ts b/apps/server/src/services/memory/userMemory/extract/extractTopic.ts
index 817d31ebebb..e92aa84972d 100644
--- a/apps/server/src/services/memory/userMemory/extract/extractTopic.ts
+++ b/apps/server/src/services/memory/userMemory/extract/extractTopic.ts
@@ -42,6 +42,7 @@ import {
MemoryExtractionAggregateError,
serializeError,
} from './errors';
+import { withoutRetiredLobeHubMemoryModels } from './runtime';
import type { TopicExtractionJob } from './types';
const isTopicExtracted = (metadata?: ChatTopicMetadata | null): boolean => {
@@ -180,7 +181,10 @@ export async function extractTopic(ctx: MemoryExtractionExecutorContext, job: To
ctx.getAiProviderRuntimeState(job.userId, job.workspaceId),
]);
const memoryServiceConfig = ctx.resolveUserMemoryServiceConfig(
- userState.settings?.systemAgent as Partial<UserServiceModelConfig> | undefined,
+ await withoutRetiredLobeHubMemoryModels(
+ userState.settings?.systemAgent as Partial<UserServiceModelConfig> | undefined,
+ userState.email,
+ ),
);
const keyVaults = await ctx.resolveRuntimeKeyVaults(
aiProviderRuntimeState,
diff --git a/apps/server/src/services/memory/userMemory/extract/runtime.ts b/apps/server/src/services/memory/userMemory/extract/runtime.ts
index c7359fd932e..d24c60ed936 100644
--- a/apps/server/src/services/memory/userMemory/extract/runtime.ts
+++ b/apps/server/src/services/memory/userMemory/extract/runtime.ts
@@ -1,3 +1,6 @@
+import { BRANDING_PROVIDER } from '@lobechat/business-const';
+import { isLobeHubModelAvailable } from '@lobechat/business-model-bank/model-config';
+import { resolveBusinessModelMapping } from '@lobechat/business-model-runtime';
import type { ModelRuntimeHooks } from '@lobechat/model-runtime';
import { ModelRuntime } from '@lobechat/model-runtime';
import type { AiProviderRuntimeState, UserServiceModelConfig } from '@lobechat/types';
@@ -150,6 +153,34 @@ const debugRuntimeInit = (
});
};
+const MEMORY_MODEL_SETTINGS = [
+ ['memoryAnalysisAgentConfig', 'chat'],
+ ['userMemoryEmbedding', 'embedding'],
+ ['userMemoryPersonaWriter', 'chat'],
+] as const;
+
+/**
+ * Drops a user's memory model choice when it names a LobeHub model that is no longer served, so
+ * extraction falls back to the platform default instead of failing every run with
+ * `LobeHubModelDeprecated`. Choices on other providers are the user's to fix and stay as set.
+ */
+export async function withoutRetiredLobeHubMemoryModels(
+ systemAgent: Partial<UserServiceModelConfig> | undefined,
+ userEmail?: string | null,
+): Promise<Partial<UserServiceModelConfig> | undefined> {
+ if (!systemAgent) return systemAgent;
+ let result = systemAgent;
+ for (const [key, type] of MEMORY_MODEL_SETTINGS) {
+ const item = systemAgent[key];
+ if (item?.provider !== BRANDING_PROVIDER || !item.model) continue;
+ const { resolvedModelId } = await resolveBusinessModelMapping(item.provider, item.model);
+ if (await isLobeHubModelAvailable(resolvedModelId, type, { userEmail })) continue;
+ const { [key]: _retired, ...rest } = result;
+ result = rest;
+ }
+ return result;
+}
+
export function resolveUserMemoryAgent(
systemAgent: Partial<UserServiceModelConfig> | undefined,
key: keyof Pick<
diff --git a/packages/memory-user-memory/src/utils/__tests__/lenientParse.test.ts b/packages/memory-user-memory/src/utils/__tests__/lenientParse.test.ts
index 922a070a319..e22ef2ef9cb 100644
--- a/packages/memory-user-memory/src/utils/__tests__/lenientParse.test.ts
+++ b/packages/memory-user-memory/src/utils/__tests__/lenientParse.test.ts
@@ -28,6 +28,32 @@ const identity = (withIdentity: Record<string, unknown>, extra: Record<string, u
});
describe('parseLenient', () => {
+ it('reads a list the model left out as empty instead of failing the topic', () => {
+ const { data, repairs } = parseLenient(ContextMemorySchema, {});
+
+ expect(data).toEqual({ memories: [] });
+ expect(repairs).toEqual(['memories: missing list read as empty']);
+ });
+
+ it('drops an entry whose missing list cannot be read as empty, keeping the others', () => {
+ const schema = z.object({
+ memories: z.array(z.object({ tags: z.array(z.string()), title: z.string() })),
+ });
+
+ const { data } = parseLenient(schema, {
+ memories: [
+ { tags: ['work'], title: 'kept' },
+ { title: 'malformed', unexpected: true },
+ ],
+ });
+
+ expect(data.memories).toEqual([{ tags: ['work'], title: 'kept' }]);
+ });
+
+ it('still fails when a missing list comes with keys outside the schema', () => {
+ expect(() => parseLenient(ContextMemorySchema, { contexts: [{ title: 'x' }] })).toThrow();
+ });
+
it('returns valid output untouched, with no repairs', () => {
const schema = z.object({ items: z.array(z.object({ a: z.string() })) });
diff --git a/packages/memory-user-memory/src/utils/lenientParse.ts b/packages/memory-user-memory/src/utils/lenientParse.ts
index ae73ca65f8a..6f290caf7c7 100644
--- a/packages/memory-user-memory/src/utils/lenientParse.ts
+++ b/packages/memory-user-memory/src/utils/lenientParse.ts
@@ -43,6 +43,15 @@ const schemaAt = (schema: z.ZodType | undefined, path: Path): z.ZodType | undefi
return current;
};
+/** Whether the original object holding `path` carries keys its schema does not know. */
+const hasForeignKeys = (schema: z.ZodType, original: unknown, path: Path): boolean => {
+ const parentPath = path.slice(0, -1);
+ const parent = at(original, parentPath);
+ const shape = objectShape(schemaAt(schema, parentPath));
+ if (!isRecord(parent) || !shape) return true;
+ return Object.keys(parent).some((key) => !(key in shape));
+};
+
const coerce = (expected: string | undefined, value: unknown): { value: unknown } | undefined => {
if (expected === 'number' && typeof value === 'string' && value.trim() !== '') {
const number = Number(value);
@@ -86,6 +95,8 @@ export const parseLenient = <T>(
let changed = false;
/** Entries to drop, per list, applied after the other repairs so indexes stay valid. */
const drops = new Map<unknown[], { indexes: Set<number>; path: Path }>();
+ /** Required lists the output left out; filled only as a last resort, see below. */
+ const missingLists: Path[] = [];
const drop = (path: Path) => {
const index = path.findLastIndex((key) => typeof key === 'number');
@@ -161,6 +172,17 @@ export const parseLenient = <T>(
set(path, coerced.value, `read as ${issue.expected}`);
continue;
}
+ if (
+ issue.expected === 'array' &&
+ actual === undefined &&
+ isRecord(at(current, path.slice(0, -1)))
+ ) {
+ missingLists.push(path);
+ // Also queued for dropping: if the list cannot be read as empty below (the answer
+ // carries keys outside the schema), its entry is dropped as before.
+ drop(path);
+ continue;
+ }
// Null for a field that does not take it: treat it as left out (a default may fill it).
if (actual === null && isRecord(at(current, path.slice(0, -1)))) {
set(path, undefined, 'null left out');
@@ -174,6 +196,14 @@ export const parseLenient = <T>(
// A repair can settle issues reported next to it (a moved field fills the gap it left), so
// entries are dropped only once a pass has nothing else to repair.
if (changed) continue;
+ // A required list left out of an otherwise clean answer means no entries: models omit
+ // `memories` when there is nothing to keep. Keys outside the schema in the original output
+ // mean the model answered something else, which stays a failure.
+ const emptyLists = missingLists.filter((path) => !hasForeignKeys(schema, value, path));
+ if (emptyLists.length > 0) {
+ for (const path of emptyLists) set(path, [], 'missing list read as empty');
+ continue;
+ }
for (const [list, { indexes, path }] of drops) {
for (const index of [...indexes].sort((a, b) => b - a)) {
list.splice(index, 1);