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.

♻️ refactor: createAgent uses `agentModel.create` directly (#13871)

Arvin Xu4203e32dc792
diff --git a/packages/database/src/models/session.ts b/packages/database/src/models/session.ts
index 259b001af20..f263c182a35 100644
--- a/packages/database/src/models/session.ts
+++ b/packages/database/src/models/session.ts
@@ -212,6 +212,10 @@ export class SessionModel {
// **************** Create *************** //
+ /**
+ * @deprecated Use AgentModel.create for creating agents directly.
+ * This method creates both a session and an agent, which is the legacy pattern.
+ */
create = async ({
id = idGenerator('sessions'),
type = 'agent',
diff --git a/packages/database/src/schemas/agent.ts b/packages/database/src/schemas/agent.ts
index 462df68cd81..c4f09f85bca 100644
--- a/packages/database/src/schemas/agent.ts
+++ b/packages/database/src/schemas/agent.ts
@@ -83,6 +83,7 @@ export const agents = pgTable(
],
);
+/** @deprecated Use CreateAgentSchema from @lobechat/types instead */
export const insertAgentSchema = createInsertSchema(agents, {
agencyConfig: z.custom<LobeAgentAgencyConfig>().nullable().optional(),
// Override chatConfig type to use the proper schema
diff --git a/packages/types/src/agent/item.ts b/packages/types/src/agent/item.ts
index 47064231b01..20a209ba1ab 100644
--- a/packages/types/src/agent/item.ts
+++ b/packages/types/src/agent/item.ts
@@ -1,10 +1,11 @@
import type { LLMParams } from 'model-bank';
+import { z } from 'zod';
import type { FileItem } from '../files';
import type { KnowledgeBaseItem } from '../knowledgeBase';
import type { FewShots } from '../llm';
import type { LobeAgentAgencyConfig } from './agencyConfig';
-import type { LobeAgentChatConfig } from './chatConfig';
+import { AgentChatConfigSchema, type LobeAgentChatConfig } from './chatConfig';
import type { LobeAgentTTSConfig } from './tts';
export interface LobeAgentConfig {
@@ -85,6 +86,35 @@ export type LobeAgentConfigKeys =
| keyof LobeAgentConfig
| ['params', keyof LobeAgentConfig['params']];
+/**
+ * Zod schema for creating a new agent.
+ * Covers all user-configurable fields; system fields (id, userId, timestamps) are excluded.
+ */
+export const CreateAgentSchema = z.object({
+ agencyConfig: z.custom<LobeAgentAgencyConfig>().optional(),
+ avatar: z.string().nullable().optional(),
+ backgroundColor: z.string().nullable().optional(),
+ chatConfig: AgentChatConfigSchema.optional(),
+ description: z.string().nullable().optional(),
+ editorData: z.unknown().optional(),
+ fewShots: z.unknown().optional(),
+ marketIdentifier: z.string().nullable().optional(),
+ model: z.string().nullable().optional(),
+ openingMessage: z.string().nullable().optional(),
+ openingQuestions: z.array(z.string()).optional(),
+ params: z.record(z.unknown()).optional(),
+ plugins: z.array(z.string()).optional(),
+ provider: z.string().nullable().optional(),
+ sessionGroupId: z.string().nullable().optional(),
+ systemRole: z.string().nullable().optional(),
+ tags: z.array(z.string()).optional(),
+ title: z.string().nullable().optional(),
+ tts: z.custom<LobeAgentTTSConfig>().optional(),
+ virtual: z.boolean().nullable().optional(),
+});
+
+export type CreateAgentConfig = z.infer<typeof CreateAgentSchema>;
+
// Agent database item type (independent from schema)
export interface AgentItem {
agencyConfig?: LobeAgentAgencyConfig | null;
diff --git a/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/AddAgent.tsx b/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/AddAgent.tsx
index 4aab728c99c..1bbb7e6e38e 100644
--- a/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/AddAgent.tsx
+++ b/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/AddAgent.tsx
@@ -100,7 +100,7 @@ const AddAgent = memo<{ mobile?: boolean }>(({ mobile }) => {
try {
const result = await createAgentWithMarketIdentifier(true);
message.success(t('assistants.addAgentSuccess'));
- navigate(SESSION_CHAT_URL(result!.agentId || result!.sessionId, mobile));
+ navigate(SESSION_CHAT_URL(result!.agentId, mobile));
} finally {
setIsLoading(false);
}
diff --git a/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/ForkAndChat.tsx b/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/ForkAndChat.tsx
index f7295891d7f..694514cc357 100644
--- a/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/ForkAndChat.tsx
+++ b/src/routes/(main)/community/(detail)/agent/features/Sidebar/ActionButton/ForkAndChat.tsx
@@ -118,7 +118,7 @@ const ForkAndChat = memo<{ mobile?: boolean }>(({ mobile }) => {
message.success(t('fork.success'));
// Step 6: Navigate to chat
- navigate(SESSION_CHAT_URL(result!.agentId || result!.sessionId, mobile));
+ navigate(SESSION_CHAT_URL(result!.agentId, mobile));
} catch (error: any) {
console.error('Fork failed:', error);
message.error(t('fork.failed'));
diff --git a/src/server/routers/lambda/agent.ts b/src/server/routers/lambda/agent.ts
index 0ad5cad4d7d..67f8f47c0c8 100644
--- a/src/server/routers/lambda/agent.ts
+++ b/src/server/routers/lambda/agent.ts
@@ -1,5 +1,5 @@
import { DEFAULT_AGENT_CONFIG, INBOX_SESSION_ID } from '@lobechat/const';
-import { type KnowledgeItem } from '@lobechat/types';
+import { CreateAgentSchema, type KnowledgeItem } from '@lobechat/types';
import { KnowledgeType } from '@lobechat/types';
import { z } from 'zod';
@@ -9,7 +9,6 @@ import { FileModel } from '@/database/models/file';
import { KnowledgeBaseModel } from '@/database/models/knowledgeBase';
import { SessionModel } from '@/database/models/session';
import { UserModel } from '@/database/models/user';
-import { insertAgentSchema } from '@/database/schemas';
import { authedProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { AgentService } from '@/server/services/agent';
@@ -50,35 +49,17 @@ export const agentRouter = router({
createAgent: agentProcedure
.input(
z.object({
- config: insertAgentSchema
- .omit({
- chatConfig: true,
- openingMessage: true,
- openingQuestions: true,
- tags: true,
- tts: true,
- })
- .passthrough()
- .partial()
- .optional(),
+ config: CreateAgentSchema.optional(),
groupId: z.string().optional(),
}),
)
.mutation(async ({ input, ctx }) => {
- const session = await ctx.sessionModel.create({
- config: input.config as any,
- session: { groupId: input.groupId },
- type: 'agent',
+ const agent = await ctx.agentModel.create({
+ ...input.config,
+ sessionGroupId: input.groupId,
});
- // Get the agent ID from the created session
- const sessionWithAgent = await ctx.sessionModel.findByIdOrSlug(session.id);
- const agentId = sessionWithAgent?.agent?.id;
-
- return {
- agentId,
- sessionId: session.id,
- };
+ return { agentId: agent.id };
}),
createAgentFiles: agentProcedure
diff --git a/src/server/routers/lambda/session.ts b/src/server/routers/lambda/session.ts
index 87b66696530..76c35825a68 100644
--- a/src/server/routers/lambda/session.ts
+++ b/src/server/routers/lambda/session.ts
@@ -23,7 +23,14 @@ const sessionProcedure = authedProcedure.use(serverDatabase).use(async (opts) =>
});
});
+/**
+ * @deprecated Session router is legacy. Use agent router for agent CRUD operations.
+ * Session-based agent creation (createSession, batchCreateSessions) should migrate
+ * to agent.createAgent which uses agentModel.create directly.
+ * Session query/update methods are still used by mobile but should be migrated.
+ */
export const sessionRouter = router({
+ /** @deprecated Use agent.createAgent instead */
batchCreateSessions: sessionProcedure
.input(
z.array(
@@ -72,6 +79,7 @@ export const sessionRouter = router({
return ctx.sessionModel.count(input);
}),
+ /** @deprecated Use agent.createAgent instead */
createSession: sessionProcedure
.input(
z.object({
diff --git a/src/services/agent.ts b/src/services/agent.ts
index 8a9027eec6e..d2645ee538d 100644
--- a/src/services/agent.ts
+++ b/src/services/agent.ts
@@ -54,8 +54,7 @@ export interface CreateAgentParams {
}
export interface CreateAgentResult {
- agentId?: string;
- sessionId: string;
+ agentId: string;
}
export interface CreateAgentOnlyParams {
diff --git a/src/services/session/index.ts b/src/services/session/index.ts
index 73a6f36d3ef..9b0ece4f30f 100644
--- a/src/services/session/index.ts
+++ b/src/services/session/index.ts
@@ -13,12 +13,17 @@ import {
type UpdateSessionParams,
} from '@/types/session';
+/**
+ * @deprecated Session service is legacy. Use agentService for agent CRUD operations.
+ * Mobile still uses this, but should migrate to agentService.
+ */
export class SessionService {
hasSessions = async (): Promise<boolean> => {
const result = await this.countSessions();
return result === 0;
};
+ /** @deprecated Use agentService.createAgent instead */
createSession = async (
type: LobeSessionType,
data: Partial<LobeAgentSession>,
diff --git a/src/store/agent/slices/agent/action.ts b/src/store/agent/slices/agent/action.ts
index dbcb8d891b2..ed027ffaec6 100644
--- a/src/store/agent/slices/agent/action.ts
+++ b/src/store/agent/slices/agent/action.ts
@@ -93,7 +93,6 @@ export class AgentSliceActionImpl {
agent_id: result.agentId,
assistant_name: params.config?.title || 'Untitled Agent',
assistant_tags: params.config?.tags || [],
- session_id: result.sessionId,
user_id: userId || 'anonymous',
},
});
diff --git a/src/store/session/slices/session/action.ts b/src/store/session/slices/session/action.ts
index d5db99da85d..1460187acae 100644
--- a/src/store/session/slices/session/action.ts
+++ b/src/store/session/slices/session/action.ts
@@ -59,6 +59,7 @@ export class SessionActionImpl {
this.#set({ allAgentsDrawerOpen: false }, false, n('closeAllAgentsDrawer'));
};
+ /** @deprecated Use agentStore.createAgent instead */
createSession = async (
agent?: PartialDeep<LobeAgentSession>,
isSwitchSession: boolean = true,