🤯 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(follow-up): allow scene-specific model config for follow-up action extraction (#14797)
Inneic9505f7ea2d4
diff --git a/packages/types/src/followUpAction.ts b/packages/types/src/followUpAction.tsindex d1699661f2b..228df81c0e5 100644--- a/packages/types/src/followUpAction.ts+++ b/packages/types/src/followUpAction.ts@@ -11,8 +11,14 @@ export interface FollowUpChip {export type FollowUpHint = { kind: 'onboarding'; phase: OnboardingPhase } | { kind: 'chat' };+export interface FollowUpModelConfig {+ model: string;+ provider: string;+}+export interface FollowUpExtractInput {hint?: FollowUpHint;+ modelConfig: FollowUpModelConfig;topicId: string;}@@ -32,7 +38,13 @@ export const FollowUpHintSchema = z.union([}),]);+export const FollowUpModelConfigSchema = z.object({+ model: z.string().min(1),+ provider: z.string().min(1),+});+export const FollowUpExtractInputSchema = z.object({hint: FollowUpHintSchema.optional(),+ modelConfig: FollowUpModelConfigSchema,topicId: z.string().min(1),});diff --git a/src/features/Onboarding/Agent/index.tsx b/src/features/Onboarding/Agent/index.tsxindex 53fb61bda2d..4b4f6b078a7 100644--- a/src/features/Onboarding/Agent/index.tsx+++ b/src/features/Onboarding/Agent/index.tsx@@ -13,6 +13,7 @@ import { useTranslation } from 'react-i18next';import { useNavigate } from 'react-router-dom';import Loading from '@/components/Loading/BrandTextLoading';+import { ONBOARDING_PRODUCTION_DEFAULT_MODEL } from '@/const/onboarding';import ModeSwitch from '@/features/Onboarding/components/ModeSwitch';import { useClientDataSWR, useOnlyFetchOnceSWR } from '@/libs/swr';import OnboardingContainer from '@/routes/onboarding/_layout';@@ -21,7 +22,7 @@ import { messageService } from '@/services/message';import { topicService } from '@/services/topic';import { userService } from '@/services/user';import { useAgentStore } from '@/store/agent';-import { builtinAgentSelectors } from '@/store/agent/selectors';+import { agentByIdSelectors, builtinAgentSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { useUserStore } from '@/store/user';@@ -55,6 +56,9 @@ const AgentOnboardingPage = memo(() => {const onboardingAgentId = useAgentStore(builtinAgentSelectors.getBuiltinAgentId(BUILTIN_AGENT_SLUGS.webOnboarding),);+ const onboardingAgentConfig = useAgentStore((s) =>+ onboardingAgentId ? agentByIdSelectors.getAgentConfigById(onboardingAgentId)(s) : undefined,+ );const inboxAgentId = useAgentStore(builtinAgentSelectors.getBuiltinAgentId(BUILTIN_AGENT_SLUGS.inbox),);@@ -123,10 +127,18 @@ const AgentOnboardingPage = memo(() => {() => !messagesForOnboarding || messagesForOnboarding.length === 0,[messagesForOnboarding],);+ const onboardingFollowUpModelConfig = useMemo(+ () => ({+ model: onboardingAgentConfig?.model ?? ONBOARDING_PRODUCTION_DEFAULT_MODEL.model,+ provider: onboardingAgentConfig?.provider ?? ONBOARDING_PRODUCTION_DEFAULT_MODEL.provider,+ }),+ [onboardingAgentConfig?.model, onboardingAgentConfig?.provider],+ );const onboardingFollowUp = useOnboardingFollowUp({enabled: !onboardingFinished && !viewingHistoricalTopic,isGreeting,+ modelConfig: onboardingFollowUpModelConfig,});const { onBeforeSendMessage, triggerExtract } = onboardingFollowUp;diff --git a/src/features/Onboarding/Agent/useOnboardingFollowUp.test.ts b/src/features/Onboarding/Agent/useOnboardingFollowUp.test.tsindex 43b38837612..6fa5c2a199f 100644--- a/src/features/Onboarding/Agent/useOnboardingFollowUp.test.ts+++ b/src/features/Onboarding/Agent/useOnboardingFollowUp.test.ts@@ -5,6 +5,11 @@ import { useFollowUpActionStore } from '@/store/followUpAction';import { useOnboardingFollowUp } from './useOnboardingFollowUp';+const MODEL_CONFIG = {+ model: 'scene-model',+ provider: 'scene-provider',+};+describe('useOnboardingFollowUp', () => {let fetchFor: ReturnType<typeof vi.fn>;let clear: ReturnType<typeof vi.fn>;@@ -24,7 +29,7 @@ describe('useOnboardingFollowUp', () => {it('triggerExtract skips when disabled', async () => {const { result } = renderHook(() =>- useOnboardingFollowUp({ enabled: false, isGreeting: false }),+ useOnboardingFollowUp({ enabled: false, isGreeting: false, modelConfig: MODEL_CONFIG }),);await result.current.triggerExtract('topic-1', 'discovery');expect(fetchFor).not.toHaveBeenCalled();@@ -32,7 +37,7 @@ describe('useOnboardingFollowUp', () => {it('triggerExtract skips when phase is undefined', async () => {const { result } = renderHook(() =>- useOnboardingFollowUp({ enabled: true, isGreeting: false }),+ useOnboardingFollowUp({ enabled: true, isGreeting: false, modelConfig: MODEL_CONFIG }),);await result.current.triggerExtract('topic-1', undefined);expect(fetchFor).not.toHaveBeenCalled();@@ -40,32 +45,37 @@ describe('useOnboardingFollowUp', () => {it('triggerExtract skips when phase is summary', async () => {const { result } = renderHook(() =>- useOnboardingFollowUp({ enabled: true, isGreeting: false }),+ useOnboardingFollowUp({ enabled: true, isGreeting: false, modelConfig: MODEL_CONFIG }),);await result.current.triggerExtract('topic-1', 'summary');expect(fetchFor).not.toHaveBeenCalled();});it('triggerExtract skips when isGreeting is true', async () => {- const { result } = renderHook(() => useOnboardingFollowUp({ enabled: true, isGreeting: true }));+ const { result } = renderHook(() =>+ useOnboardingFollowUp({ enabled: true, isGreeting: true, modelConfig: MODEL_CONFIG }),+ );await result.current.triggerExtract('topic-1', 'agent_identity');expect(fetchFor).not.toHaveBeenCalled();});it('triggerExtract fires fetchFor with onboarding hint on a normal turn', async () => {const { result } = renderHook(() =>- useOnboardingFollowUp({ enabled: true, isGreeting: false }),+ useOnboardingFollowUp({ enabled: true, isGreeting: false, modelConfig: MODEL_CONFIG }),);await result.current.triggerExtract('topic-1', 'discovery');expect(fetchFor).toHaveBeenCalledWith('topic-1', {- kind: 'onboarding',- phase: 'discovery',+ hint: {+ kind: 'onboarding',+ phase: 'discovery',+ },+ modelConfig: MODEL_CONFIG,});});it('onBeforeSendMessage clears when enabled', async () => {const { result } = renderHook(() =>- useOnboardingFollowUp({ enabled: true, isGreeting: false }),+ useOnboardingFollowUp({ enabled: true, isGreeting: false, modelConfig: MODEL_CONFIG }),);await result.current.onBeforeSendMessage();expect(clear).toHaveBeenCalledTimes(1);@@ -73,7 +83,7 @@ describe('useOnboardingFollowUp', () => {it('onBeforeSendMessage does nothing when disabled', async () => {const { result } = renderHook(() =>- useOnboardingFollowUp({ enabled: false, isGreeting: false }),+ useOnboardingFollowUp({ enabled: false, isGreeting: false, modelConfig: MODEL_CONFIG }),);await result.current.onBeforeSendMessage();expect(clear).not.toHaveBeenCalled();diff --git a/src/features/Onboarding/Agent/useOnboardingFollowUp.ts b/src/features/Onboarding/Agent/useOnboardingFollowUp.tsindex f816df44c4b..0337bca1d1d 100644--- a/src/features/Onboarding/Agent/useOnboardingFollowUp.ts+++ b/src/features/Onboarding/Agent/useOnboardingFollowUp.ts@@ -1,3 +1,4 @@+import type { FollowUpModelConfig } from '@lobechat/types';import { useCallback } from 'react';import { useFollowUpActionStore } from '@/store/followUpAction';@@ -6,6 +7,7 @@ import type { OnboardingPhase } from '@/types/user';interface UseOnboardingFollowUpParams {enabled: boolean;isGreeting: boolean;+ modelConfig: FollowUpModelConfig;}interface OnboardingFollowUpHandlers {@@ -16,6 +18,7 @@ interface OnboardingFollowUpHandlers {export const useOnboardingFollowUp = ({enabled,isGreeting,+ modelConfig,}: UseOnboardingFollowUpParams): OnboardingFollowUpHandlers => {const triggerExtract = useCallback(async (topicId: string, phase: OnboardingPhase | undefined) => {@@ -24,9 +27,12 @@ export const useOnboardingFollowUp = ({if (phase === 'summary') return;if (isGreeting) return;- await useFollowUpActionStore.getState().fetchFor(topicId, { kind: 'onboarding', phase });+ await useFollowUpActionStore.getState().fetchFor(topicId, {+ hint: { kind: 'onboarding', phase },+ modelConfig,+ });},- [enabled, isGreeting],+ [enabled, isGreeting, modelConfig],);const onBeforeSendMessage = useCallback(async () => {diff --git a/src/server/services/followUpAction/index.test.ts b/src/server/services/followUpAction/index.test.tsindex 9407eea57c8..a843ed6583f 100644--- a/src/server/services/followUpAction/index.test.ts+++ b/src/server/services/followUpAction/index.test.ts@@ -8,6 +8,10 @@ import { FollowUpActionService } from './index';const TEST_USER = 'user-1';const TEST_TOPIC = 'topic-1';const FOUND_MSG = 'msg-real';+const MODEL_CONFIG = {+ model: 'scene-model',+ provider: 'scene-provider',+};describe('FollowUpActionService.extract', () => {let svc: FollowUpActionService;@@ -37,7 +41,7 @@ describe('FollowUpActionService.extract', () => {it('returns empty (with empty messageId) when no eligible assistant message found', async () => {queryFindFirstSpy.mockResolvedValue(undefined);- const result = await svc.extract({ topicId: TEST_TOPIC });+ const result = await svc.extract({ modelConfig: MODEL_CONFIG, topicId: TEST_TOPIC });expect(result).toEqual({ chips: [], messageId: '' });expect(runtimeMock.generateObject).not.toHaveBeenCalled();});@@ -57,18 +61,46 @@ describe('FollowUpActionService.extract', () => {const result = await svc.extract({topicId: TEST_TOPIC,hint: { kind: 'onboarding', phase: 'agent_identity' },+ modelConfig: MODEL_CONFIG,});expect(result.messageId).toBe(FOUND_MSG);expect(result.chips).toHaveLength(3);expect(result.chips[0].label).toBe('Lumi');});+ it('uses the caller-provided scene model config for extraction', async () => {+ queryFindFirstSpy.mockResolvedValue({+ id: FOUND_MSG,+ content: 'What would you like to call me?',+ });+ runtimeMock.generateObject.mockResolvedValue({ chips: [] });++ await svc.extract({+ topicId: TEST_TOPIC,+ modelConfig: {+ model: 'custom-scene-model',+ provider: 'custom-provider',+ },+ });++ expect(ModelRuntimeModule.initModelRuntimeFromDB).toHaveBeenCalledWith(+ dbMock,+ TEST_USER,+ 'custom-provider',+ );+ expect(runtimeMock.generateObject).toHaveBeenCalledWith(+ expect.objectContaining({+ model: 'custom-scene-model',+ }),+ );+ });+it('truncates more than 4 chips', async () => {queryFindFirstSpy.mockResolvedValue({ id: FOUND_MSG, content: 'choose' });runtimeMock.generateObject.mockResolvedValue({chips: Array.from({ length: 6 }, (_, i) => ({ label: `c${i}`, message: `c${i}` })),});- const result = await svc.extract({ topicId: TEST_TOPIC });+ const result = await svc.extract({ modelConfig: MODEL_CONFIG, topicId: TEST_TOPIC });expect(result.chips).toHaveLength(4);});@@ -80,7 +112,7 @@ describe('FollowUpActionService.extract', () => {{ label: 'ok', message: 'ok' },],});- const result = await svc.extract({ topicId: TEST_TOPIC });+ const result = await svc.extract({ modelConfig: MODEL_CONFIG, topicId: TEST_TOPIC });expect(result.chips).toEqual([{ label: 'ok', message: 'ok' }]);});@@ -93,21 +125,21 @@ describe('FollowUpActionService.extract', () => {{ label: 'bad', message: '' },],});- const result = await svc.extract({ topicId: TEST_TOPIC });+ const result = await svc.extract({ modelConfig: MODEL_CONFIG, topicId: TEST_TOPIC });expect(result.chips).toEqual([{ label: 'ok', message: 'ok' }]);});it('returns empty (with messageId) when LLM throws', async () => {queryFindFirstSpy.mockResolvedValue({ id: FOUND_MSG, content: 'q?' });runtimeMock.generateObject.mockRejectedValue(new Error('boom'));- const result = await svc.extract({ topicId: TEST_TOPIC });+ const result = await svc.extract({ modelConfig: MODEL_CONFIG, topicId: TEST_TOPIC });expect(result).toEqual({ chips: [], messageId: FOUND_MSG });});it('returns empty (with messageId) when LLM response fails schema validation', async () => {queryFindFirstSpy.mockResolvedValue({ id: FOUND_MSG, content: 'q?' });runtimeMock.generateObject.mockResolvedValue({ chips: 'not-an-array' });- const result = await svc.extract({ topicId: TEST_TOPIC });+ const result = await svc.extract({ modelConfig: MODEL_CONFIG, topicId: TEST_TOPIC });expect(result).toEqual({ chips: [], messageId: FOUND_MSG });});@@ -117,6 +149,7 @@ describe('FollowUpActionService.extract', () => {await svc.extract({topicId: TEST_TOPIC,hint: { kind: 'onboarding', phase: 'discovery' },+ modelConfig: MODEL_CONFIG,});const passedMessages = runtimeMock.generateObject.mock.calls[0][0].messages;const sysContent = passedMessages.find((m: any) => m.role === 'system').content;diff --git a/src/server/services/followUpAction/index.ts b/src/server/services/followUpAction/index.tsindex 9cac815a388..b4636b38d30 100644--- a/src/server/services/followUpAction/index.ts+++ b/src/server/services/followUpAction/index.ts@@ -1,8 +1,7 @@-import { DEFAULT_SYSTEM_AGENT_CONFIG } from '@lobechat/const';import type { FollowUpChip, FollowUpExtractInput, FollowUpExtractResult } from '@lobechat/types';import debug from 'debug';-import { type LobeChatDatabase } from '@/database/type';+import type { LobeChatDatabase } from '@/database/type';import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';import { buildSuggestionPrompt } from './prompts';@@ -21,7 +20,11 @@ export class FollowUpActionService {this.userId = userId;}- async extract({ topicId, hint }: FollowUpExtractInput): Promise<FollowUpExtractResult> {+ async extract({+ topicId,+ hint,+ modelConfig,+ }: FollowUpExtractInput): Promise<FollowUpExtractResult> {// Resolve the latest assistant message that actually has user-facing text.// Tool-call-only messages have empty content and must be skipped.const row = await this.db.query.messages.findFirst({@@ -43,7 +46,7 @@ export class FollowUpActionService {if (!text) return EMPTY_RESULT(row.id);const { system, user } = buildSuggestionPrompt({ assistantText: text, hint });- const { model, provider } = this.getModelConfig();+ const { model, provider } = modelConfig;let raw: unknown;try {@@ -79,17 +82,4 @@ export class FollowUpActionService {return { chips, messageId: row.id };}-- private getModelConfig(): { model: string; provider: string } {- const overrideModel = process.env.FOLLOW_UP_ACTION_MODEL;- const overrideProvider = process.env.FOLLOW_UP_ACTION_PROVIDER;- if (overrideModel && overrideProvider) {- return { model: overrideModel, provider: overrideProvider };- }- const fallback = DEFAULT_SYSTEM_AGENT_CONFIG.topic;- return {- model: overrideModel ?? fallback.model,- provider: overrideProvider ?? fallback.provider,- };- }}diff --git a/src/store/followUpAction/action.ts b/src/store/followUpAction/action.tsindex 35cb0fc4cda..3a3e5cb8a5c 100644--- a/src/store/followUpAction/action.ts+++ b/src/store/followUpAction/action.ts@@ -1,4 +1,4 @@-import type { FollowUpChip, FollowUpHint } from '@lobechat/types';+import type { FollowUpChip, FollowUpHint, FollowUpModelConfig } from '@lobechat/types';import { followUpActionService } from '@/services/followUpAction';import { type StoreSetter } from '@/store/types';@@ -11,6 +11,11 @@ const TIMEOUT_MS = 20_000;type Setter = StoreSetter<FollowUpActionStore>;+interface FetchForParams {+ hint?: FollowUpHint;+ modelConfig: FollowUpModelConfig;+}+export const createFollowUpActionSlice = (set: Setter,get: () => FollowUpActionStore,@@ -27,7 +32,7 @@ export class FollowUpActionImpl {this.#get = get;}- fetchFor = async (topicId: string, hint?: FollowUpHint): Promise<void> => {+ fetchFor = async (topicId: string, params: FetchForParams): Promise<void> => {const cur = this.#get();// Dedupe: skip if already loading/ready for the same topicif (cur.pendingTopicId === topicId && cur.status !== 'idle') return;@@ -50,7 +55,7 @@ export class FollowUpActionImpl {'fetchFor:start',);- const result = await followUpActionService.extract({ hint, topicId }, controller.signal);+ const result = await followUpActionService.extract({ ...params, topicId }, controller.signal);clearTimeout(timeoutId);// Discard stale results: if the active controller in state is no longerdiff --git a/src/store/followUpAction/index.test.ts b/src/store/followUpAction/index.test.tsindex e7cf1443977..db805cc47db 100644--- a/src/store/followUpAction/index.test.ts+++ b/src/store/followUpAction/index.test.ts@@ -7,6 +7,8 @@ import { useFollowUpActionStore } from './store';const TOPIC = 'topic-1';const NEW_TOPIC = 'topic-2';const MSG = 'msg-real';+const MODEL_CONFIG = { model: 'scene-model', provider: 'scene-provider' };+const FETCH_PARAMS = { modelConfig: MODEL_CONFIG };describe('useFollowUpActionStore', () => {beforeEach(() => {@@ -24,7 +26,7 @@ describe('useFollowUpActionStore', () => {chips: [{ label: 'a', message: 'a' }],});- const promise = useFollowUpActionStore.getState().fetchFor(TOPIC);+ const promise = useFollowUpActionStore.getState().fetchFor(TOPIC, FETCH_PARAMS);expect(useFollowUpActionStore.getState().status).toBe('loading');await promise;expect(spy).toHaveBeenCalledOnce();@@ -34,9 +36,29 @@ describe('useFollowUpActionStore', () => {expect(useFollowUpActionStore.getState().topicId).toBe(TOPIC);});+ it('fetchFor forwards modelConfig to the service', async () => {+ const spy = vi.spyOn(followUpActionService, 'extract').mockResolvedValue({+ messageId: MSG,+ chips: [{ label: 'a', message: 'a' }],+ });+ await useFollowUpActionStore.getState().fetchFor(TOPIC, {+ hint: { kind: 'onboarding', phase: 'discovery' },+ modelConfig: MODEL_CONFIG,+ });++ expect(spy).toHaveBeenCalledWith(+ {+ hint: { kind: 'onboarding', phase: 'discovery' },+ modelConfig: MODEL_CONFIG,+ topicId: TOPIC,+ },+ expect.any(AbortSignal),+ );+ });+it('fetchFor returns idle when service returns null', async () => {vi.spyOn(followUpActionService, 'extract').mockResolvedValue(null);- await useFollowUpActionStore.getState().fetchFor(TOPIC);+ await useFollowUpActionStore.getState().fetchFor(TOPIC, FETCH_PARAMS);expect(useFollowUpActionStore.getState().status).toBe('idle');expect(useFollowUpActionStore.getState().chips).toHaveLength(0);expect(useFollowUpActionStore.getState().messageId).toBeUndefined();@@ -44,7 +66,7 @@ describe('useFollowUpActionStore', () => {it('fetchFor returns idle when service returns empty messageId', async () => {vi.spyOn(followUpActionService, 'extract').mockResolvedValue({ chips: [], messageId: '' });- await useFollowUpActionStore.getState().fetchFor(TOPIC);+ await useFollowUpActionStore.getState().fetchFor(TOPIC, FETCH_PARAMS);expect(useFollowUpActionStore.getState().status).toBe('idle');expect(useFollowUpActionStore.getState().messageId).toBeUndefined();});@@ -53,8 +75,8 @@ describe('useFollowUpActionStore', () => {const spy = vi.spyOn(followUpActionService, 'extract').mockImplementation(() => new Promise(() => {}));- const p1 = useFollowUpActionStore.getState().fetchFor(TOPIC);- const p2 = useFollowUpActionStore.getState().fetchFor(TOPIC);+ const p1 = useFollowUpActionStore.getState().fetchFor(TOPIC, FETCH_PARAMS);+ const p2 = useFollowUpActionStore.getState().fetchFor(TOPIC, FETCH_PARAMS);void p1;void p2;expect(spy).toHaveBeenCalledTimes(1);@@ -66,17 +88,17 @@ describe('useFollowUpActionStore', () => {if (!firstSignal) firstSignal = signal;return new Promise(() => {});});- const p1 = useFollowUpActionStore.getState().fetchFor(TOPIC);+ const p1 = useFollowUpActionStore.getState().fetchFor(TOPIC, FETCH_PARAMS);void p1;await Promise.resolve();await Promise.resolve();- void useFollowUpActionStore.getState().fetchFor(NEW_TOPIC);+ void useFollowUpActionStore.getState().fetchFor(NEW_TOPIC, FETCH_PARAMS);expect(firstSignal?.aborted).toBe(true);});it('clear() aborts and resets state', async () => {vi.spyOn(followUpActionService, 'extract').mockImplementation(() => new Promise(() => {}));- const p = useFollowUpActionStore.getState().fetchFor(TOPIC);+ const p = useFollowUpActionStore.getState().fetchFor(TOPIC, FETCH_PARAMS);void p;useFollowUpActionStore.getState().clear();expect(useFollowUpActionStore.getState().status).toBe('idle');@@ -90,7 +112,7 @@ describe('useFollowUpActionStore', () => {signal = s;return new Promise(() => {});});- const p = useFollowUpActionStore.getState().fetchFor(TOPIC);+ const p = useFollowUpActionStore.getState().fetchFor(TOPIC, FETCH_PARAMS);void p;await Promise.resolve();vi.advanceTimersByTime(20_000);@@ -124,7 +146,7 @@ describe('useFollowUpActionStore', () => {});// First fetchFor is in flight (does not yet resolve).- const p1 = useFollowUpActionStore.getState().fetchFor(TOPIC);+ const p1 = useFollowUpActionStore.getState().fetchFor(TOPIC, FETCH_PARAMS);void p1;await Promise.resolve();@@ -133,7 +155,7 @@ describe('useFollowUpActionStore', () => {expect(useFollowUpActionStore.getState().status).toBe('idle');// Next turn starts another fetchFor for the SAME topic.- const p2 = useFollowUpActionStore.getState().fetchFor(TOPIC);+ const p2 = useFollowUpActionStore.getState().fetchFor(TOPIC, FETCH_PARAMS);// The first call now resolves with a stale result. It must be discarded// because its controller is no longer the active one — even though the@@ -156,7 +178,7 @@ describe('useFollowUpActionStore', () => {signal = s;return new Promise(() => {});});- const p = useFollowUpActionStore.getState().fetchFor(TOPIC);+ const p = useFollowUpActionStore.getState().fetchFor(TOPIC, FETCH_PARAMS);void p;await Promise.resolve();useFollowUpActionStore.getState().reset();