Skip to content

🎬 火宝短剧 - 基于AI的一站式短剧生成平台 《一句话生成完整短剧,从剧本到成片全自动化》 Huobao Drama - An AI-Powered End-to-End Short Drama Generator "One Sentence to Complete Drama: Fully Automated from Script to Final Video"

TypeScript

fix: inject episodeId/dramaId into agent tools via factory pattern

Connorec9f61020b9c
diff --git a/backend/src/agents/index.ts b/backend/src/agents/index.ts
index a21a4a6..132def7 100644
--- a/backend/src/agents/index.ts
+++ b/backend/src/agents/index.ts
@@ -1,72 +1,86 @@
/**
- * Mastra Agent 定义
+ * Mastra Agent 工厂
+ * 每次请求动态创建 agent,注入 episodeId/dramaId 到工具闭包
*/
import { Agent } from '@mastra/core/agent'
-import { Mastra } from '@mastra/core'
import { createOpenAI } from '@ai-sdk/openai'
import { getTextConfig } from '../services/ai.js'
-
-// Tools
-import { readEpisodeScript, rewriteToScreenplay, saveScript } from './tools/script-tools.js'
-import { readScriptForExtraction, saveCharacters, saveScenes } from './tools/extract-tools.js'
-import { readStoryboardContext, saveStoryboards, updateStoryboard } from './tools/storyboard-tools.js'
+import { createScriptTools } from './tools/script-tools.js'
+import { createExtractTools } from './tools/extract-tools.js'
+import { createStoryboardTools } from './tools/storyboard-tools.js'
function getModel() {
const config = getTextConfig()
const provider = createOpenAI({
baseURL: config.baseUrl,
apiKey: config.apiKey,
- compatibility: 'compatible', // 使用 Chat Completions 格式而非 Responses API
+ compatibility: 'compatible',
})
return provider.chat(config.model)
}
-// 剧本改写 Agent
-export const scriptRewriter = new Agent({
- id: 'script_rewriter',
- name: '剧本改写',
- instructions: `你是专业编剧,擅长将小说改编为短剧剧本。
+export const validAgentTypes = ['script_rewriter', 'extractor', 'storyboard_breaker']
+
+/**
+ * 创建 agent 实例(per-request,工具已注入 episodeId/dramaId)
+ */
+export function createAgent(type: string, episodeId: number, dramaId: number): Agent | null {
+ const model = getModel()
+
+ switch (type) {
+ case 'script_rewriter': {
+ const tools = createScriptTools(episodeId)
+ return new Agent({
+ id: 'script_rewriter',
+ name: '剧本改写',
+ instructions: `你是专业编剧,擅长将小说改编为短剧剧本。
工作流程:
1. 调用 read_episode_script 读取原始内容
-2. 根据内容进行改写(使用格式化剧本格式)
-3. 调用 save_script 保存改写结果
+2. 根据读取到的内容,自己进行改写(输出格式化剧本格式)
+3. 调用 save_script 保存改写后的完整剧本
格式化剧本格式:
- 场景头:## S编号 | 内景/外景 · 地点 | 时间段
- 动作描写:自然段落,不包含镜头语言
- 对白:角色名:(状态/表情)台词内容
-- 每个场景 30-60 秒内容`,
- model: getModel(),
- tools: { readEpisodeScript, rewriteToScreenplay, saveScript },
-})
+- 每个场景 30-60 秒内容
+
+注意:你必须自己完成改写工作,不要只返回指令。读取内容后直接输出改写结果并保存。`,
+ model,
+ tools,
+ })
+ }
-// 角色场景提取 Agent
-export const extractor = new Agent({
- id: 'extractor',
- name: '角色场景提取',
- instructions: `你是制片助理,擅长从剧本中提取角色和场景信息。
+ case 'extractor': {
+ const tools = createExtractTools(episodeId, dramaId)
+ return new Agent({
+ id: 'extractor',
+ name: '角色场景提取',
+ instructions: `你是制片助理,擅长从剧本中提取角色和场景信息。
工作流程:
1. 调用 read_script_for_extraction 读取格式化剧本
-2. 分析剧本,提取所有角色(名字、角色定位、外貌描述、性格特征)
+2. 分析剧本内容,提取所有角色信息
3. 调用 save_characters 保存角色列表
-4. 分析剧本,提取所有场景(地点、时间、视觉描述)
+4. 分析剧本内容,提取所有场景信息
5. 调用 save_scenes 保存场景列表
提取要求:
- 角色要包含完整的外貌特征描述(发型、服装、体态等)
- 场景要包含光线、色调、氛围等视觉信息
- 不要遗漏任何有台词或重要动作的角色`,
- model: getModel(),
- tools: { readScriptForExtraction, saveCharacters, saveScenes },
-})
-
-// 分镜拆解 Agent
-export const storyboardBreaker = new Agent({
- id: 'storyboard_breaker',
- name: '分镜拆解',
- instructions: `你是资深影视分镜师,擅长将剧本拆解为分镜方案。
+ model,
+ tools,
+ })
+ }
+
+ case 'storyboard_breaker': {
+ const tools = createStoryboardTools(episodeId, dramaId)
+ return new Agent({
+ id: 'storyboard_breaker',
+ name: '分镜拆解',
+ instructions: `你是资深影视分镜师,擅长将剧本拆解为分镜方案。
工作流程:
1. 调用 read_storyboard_context 读取剧本、角色列表、场景列表
@@ -82,22 +96,13 @@ export const storyboardBreaker = new Agent({
- 用 <n> 分隔不同时间段
示例:
-"0-3秒:<location>咖啡厅</location>,近景,<role>小明</role>低头看手机。<n>3-6秒:全景,<role>小红</role>推门走入。"
-
-分镜要素:shot_number, title, shot_type, location, time, action, dialogue, video_prompt, duration, scene_id(从场景列表匹配)`,
- model: getModel(),
- tools: { readStoryboardContext, saveStoryboards, updateStoryboard },
-})
-
-// Agent 注册表
-export const agents: Record<string, Agent> = {
- script_rewriter: scriptRewriter,
- extractor: extractor,
- storyboard_breaker: storyboardBreaker,
+"0-3秒:<location>咖啡厅</location>,近景,<role>小明</role>低头看手机。<n>3-6秒:全景,<role>小红</role>推门走入。"`,
+ model,
+ tools,
+ })
+ }
+
+ default:
+ return null
+ }
}
-
-export function getAgent(type: string): Agent | undefined {
- return agents[type]
-}
-
-export const validAgentTypes = Object.keys(agents)
diff --git a/backend/src/agents/tools/extract-tools.ts b/backend/src/agents/tools/extract-tools.ts
index 12a3d1b..f4439ba 100644
--- a/backend/src/agents/tools/extract-tools.ts
+++ b/backend/src/agents/tools/extract-tools.ts
@@ -1,5 +1,6 @@
/**
* 角色/场景提取 Agent 工具
+ * 工厂函数模式 — 注入 episodeId + dramaId
*/
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
@@ -7,106 +8,87 @@ import { db, schema } from '../../db/index.js'
import { eq } from 'drizzle-orm'
import { now } from '../../utils/response.js'
-// 读取剧本用于提取
-export const readScriptForExtraction = createTool({
- id: 'read_script_for_extraction',
- description: 'Read the formatted screenplay of an episode for character/scene extraction.',
- inputSchema: z.object({
- episode_id: z.number().describe('Episode ID'),
- }),
- execute: async ({ episode_id }) => {
- const [ep] = db.select().from(schema.episodes)
- .where(eq(schema.episodes.id, episode_id)).all()
- if (!ep) return { error: 'Episode not found' }
+export function createExtractTools(episodeId: number, dramaId: number) {
+ const readScriptForExtraction = createTool({
+ id: 'read_script_for_extraction',
+ description: 'Read the formatted screenplay for character/scene extraction.',
+ inputSchema: z.object({}),
+ execute: async () => {
+ const [ep] = db.select().from(schema.episodes)
+ .where(eq(schema.episodes.id, episodeId)).all()
+ if (!ep) return { error: 'Episode not found' }
+ const content = ep.scriptContent || ep.content
+ if (!content) return { error: 'Episode has no script content' }
+ return { script: content }
+ },
+ })
- const content = ep.scriptContent || ep.content
- if (!content) return { error: 'Episode has no script content' }
-
- // 获取 drama_id
- return { script: content, drama_id: ep.dramaId, episode_id: ep.id }
- },
-})
-
-// 保存提取的角色
-export const saveCharacters = createTool({
- id: 'save_characters',
- description: 'Save extracted characters to the database. Each character has name, role, description, appearance.',
- inputSchema: z.object({
- drama_id: z.number().describe('Drama ID'),
- characters: z.array(z.object({
- name: z.string(),
- role: z.string().optional(),
- description: z.string().optional(),
- appearance: z.string().optional(),
- personality: z.string().optional(),
- })).describe('List of characters to save'),
- }),
- execute: async ({ drama_id, characters }) => {
- const ts = now()
- let count = 0
- for (const char of characters) {
- // 检查是否已存在
- const existing = db.select().from(schema.characters)
- .where(eq(schema.characters.dramaId, drama_id))
- .all()
- .find(c => c.name === char.name)
-
- if (existing) {
- db.update(schema.characters)
- .set({ ...char, updatedAt: ts })
- .where(eq(schema.characters.id, existing.id))
- .run()
- } else {
- db.insert(schema.characters)
- .values({ ...char, dramaId: drama_id, createdAt: ts, updatedAt: ts })
- .run()
+ const saveCharacters = createTool({
+ id: 'save_characters',
+ description: 'Save extracted characters. Each character needs: name, role, description, appearance, personality.',
+ inputSchema: z.object({
+ characters: z.array(z.object({
+ name: z.string(),
+ role: z.string().optional(),
+ description: z.string().optional(),
+ appearance: z.string().optional(),
+ personality: z.string().optional(),
+ })),
+ }),
+ execute: async ({ characters }) => {
+ const ts = now()
+ let count = 0
+ for (const char of characters) {
+ const existing = db.select().from(schema.characters)
+ .where(eq(schema.characters.dramaId, dramaId)).all()
+ .find(c => c.name === char.name)
+ if (existing) {
+ db.update(schema.characters).set({ ...char, updatedAt: ts })
+ .where(eq(schema.characters.id, existing.id)).run()
+ } else {
+ db.insert(schema.characters).values({ ...char, dramaId, createdAt: ts, updatedAt: ts }).run()
+ }
+ count++
}
- count++
- }
- return { message: `Saved ${count} characters`, count }
- },
-})
+ return { message: `Saved ${count} characters`, count }
+ },
+ })
-// 保存提取的场景
-export const saveScenes = createTool({
- id: 'save_scenes',
- description: 'Save extracted scenes/backgrounds to the database. Each scene has location, time, prompt.',
- inputSchema: z.object({
- drama_id: z.number().describe('Drama ID'),
- scenes: z.array(z.object({
- location: z.string(),
- time: z.string().optional(),
- prompt: z.string().optional().describe('Visual description for image generation'),
- })).describe('List of scenes to save'),
- }),
- execute: async ({ drama_id, scenes }) => {
- const ts = now()
- let count = 0
- for (const scene of scenes) {
- const existing = db.select().from(schema.scenes)
- .where(eq(schema.scenes.dramaId, drama_id))
- .all()
- .find(s => s.location === scene.location)
-
- if (existing) {
- db.update(schema.scenes)
- .set({ time: scene.time || existing.time, prompt: scene.prompt || existing.prompt, updatedAt: ts })
- .where(eq(schema.scenes.id, existing.id))
- .run()
- } else {
- db.insert(schema.scenes)
- .values({
- dramaId: drama_id,
- location: scene.location,
- time: scene.time || '',
- prompt: scene.prompt || scene.location,
- createdAt: ts,
+ const saveScenes = createTool({
+ id: 'save_scenes',
+ description: 'Save extracted scenes. Each scene needs: location, time, prompt (visual description).',
+ inputSchema: z.object({
+ scenes: z.array(z.object({
+ location: z.string(),
+ time: z.string().optional(),
+ prompt: z.string().optional(),
+ })),
+ }),
+ execute: async ({ scenes }) => {
+ const ts = now()
+ let count = 0
+ for (const scene of scenes) {
+ const existing = db.select().from(schema.scenes)
+ .where(eq(schema.scenes.dramaId, dramaId)).all()
+ .find(s => s.location === scene.location)
+ if (existing) {
+ db.update(schema.scenes).set({
+ time: scene.time || existing.time,
+ prompt: scene.prompt || existing.prompt,
updatedAt: ts,
- })
- .run()
+ }).where(eq(schema.scenes.id, existing.id)).run()
+ } else {
+ db.insert(schema.scenes).values({
+ dramaId, location: scene.location,
+ time: scene.time || '', prompt: scene.prompt || scene.location,
+ createdAt: ts, updatedAt: ts,
+ }).run()
+ }
+ count++
}
- count++
- }
- return { message: `Saved ${count} scenes`, count }
- },
-})
+ return { message: `Saved ${count} scenes`, count }
+ },
+ })
+
+ return { readScriptForExtraction, saveCharacters, saveScenes }
+}
diff --git a/backend/src/agents/tools/script-tools.ts b/backend/src/agents/tools/script-tools.ts
index 17376c6..8a43bf6 100644
--- a/backend/src/agents/tools/script-tools.ts
+++ b/backend/src/agents/tools/script-tools.ts
@@ -1,52 +1,44 @@
/**
* 剧本改写 Agent 工具
+ * 工厂函数模式 — 注入 episodeId,工具不再需要 LLM 传递 ID
*/
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
import { db, schema } from '../../db/index.js'
import { eq } from 'drizzle-orm'
-import { getTextConfig } from '../../services/ai.js'
import { now } from '../../utils/response.js'
-// 读取剧本内容
-export const readEpisodeScript = createTool({
- id: 'read_episode_script',
- description: 'Read the script content of an episode. Returns the raw story/novel text or formatted screenplay.',
- inputSchema: z.object({
- episode_id: z.number().describe('Episode ID'),
- }),
- execute: async ({ episode_id }) => {
- const [ep] = db.select().from(schema.episodes)
- .where(eq(schema.episodes.id, episode_id)).all()
- if (!ep) return { error: `Episode not found (id=${episode_id})` }
+export function createScriptTools(episodeId: number) {
+ const readEpisodeScript = createTool({
+ id: 'read_episode_script',
+ description: 'Read the script content of the current episode.',
+ inputSchema: z.object({}),
+ execute: async () => {
+ const [ep] = db.select().from(schema.episodes)
+ .where(eq(schema.episodes.id, episodeId)).all()
+ if (!ep) return { error: `Episode not found (id=${episodeId})` }
+ const content = ep.content || ep.scriptContent
+ if (!content) return { error: `Episode has no content (id=${episodeId})` }
+ return { content, word_count: content.length, episode_id: episodeId }
+ },
+ })
- // 优先返回原始内容,回退到格式化剧本
- const content = ep.content || ep.scriptContent
- if (!content) return { error: `Episode has no content (id=${episode_id})` }
- return { content, word_count: content.length }
- },
-})
+ const rewriteToScreenplay = createTool({
+ id: 'rewrite_to_screenplay',
+ description: 'Read the original content for AI rewriting. Returns the source text with formatting instructions.',
+ inputSchema: z.object({
+ instructions: z.string().optional().describe('Additional rewrite instructions'),
+ }),
+ execute: async ({ instructions }) => {
+ const [ep] = db.select().from(schema.episodes)
+ .where(eq(schema.episodes.id, episodeId)).all()
+ if (!ep) return { error: `Episode not found` }
+ const source = ep.content || ep.scriptContent
+ if (!source) return { error: `Episode has no content to rewrite` }
-// AI 改写剧本
-export const rewriteToScreenplay = createTool({
- id: 'rewrite_to_screenplay',
- description: 'Use AI to rewrite novel text into formatted screenplay format. Reads the episode content and rewrites it.',
- inputSchema: z.object({
- episode_id: z.number().describe('Episode ID to rewrite'),
- instructions: z.string().optional().describe('Additional instructions for the rewrite'),
- }),
- execute: async ({ episode_id, instructions }) => {
- const [ep] = db.select().from(schema.episodes)
- .where(eq(schema.episodes.id, episode_id)).all()
- if (!ep) return { error: `Episode not found` }
-
- const source = ep.content || ep.scriptContent
- if (!source) return { error: `Episode has no content to rewrite` }
-
- // 返回内容让 agent LLM 自己改写(工具提供数据,LLM 做改写)
- return {
- source_content: source,
- instruction: `请将以下内容改写为格式化剧本。
+ return {
+ source_content: source,
+ instruction: `请将以下内容改写为格式化剧本。
格式规范:
- 场景头:## S编号 | 内景/外景 · 地点 | 时间段
@@ -58,23 +50,24 @@ ${instructions || ''}
【原始内容】
${source}`,
- }
- },
-})
+ }
+ },
+ })
+
+ const saveScript = createTool({
+ id: 'save_script',
+ description: 'Save the rewritten screenplay content to the current episode.',
+ inputSchema: z.object({
+ content: z.string().describe('The formatted screenplay content to save'),
+ }),
+ execute: async ({ content }) => {
+ db.update(schema.episodes)
+ .set({ scriptContent: content, updatedAt: now() })
+ .where(eq(schema.episodes.id, episodeId))
+ .run()
+ return { message: `Script saved`, word_count: content.length }
+ },
+ })
-// 保存剧本
-export const saveScript = createTool({
- id: 'save_script',
- description: 'Save the rewritten screenplay content to an episode.',
- inputSchema: z.object({
- episode_id: z.number().describe('Episode ID to save to'),
- content: z.string().describe('The formatted screenplay content to save'),
- }),
- execute: async ({ episode_id, content }) => {
- db.update(schema.episodes)
- .set({ scriptContent: content, updatedAt: now() })
- .where(eq(schema.episodes.id, episode_id))
- .run()
- return { message: `Script saved to episode ${episode_id}`, word_count: content.length }
- },
-})
+ return { readEpisodeScript, rewriteToScreenplay, saveScript }
+}
diff --git a/backend/src/agents/tools/storyboard-tools.ts b/backend/src/agents/tools/storyboard-tools.ts
index b0847dc..85b7134 100644
--- a/backend/src/agents/tools/storyboard-tools.ts
+++ b/backend/src/agents/tools/storyboard-tools.ts
@@ -1,5 +1,6 @@
/**
* 分镜拆解 Agent 工具
+ * 工厂函数模式 — 注入 episodeId + dramaId
*/
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
@@ -7,136 +8,106 @@ import { db, schema } from '../../db/index.js'
import { eq } from 'drizzle-orm'
import { now } from '../../utils/response.js'
-// 读取剧本 + 角色 + 场景(为分镜拆解提供完整上下文)
-export const readStoryboardContext = createTool({
- id: 'read_storyboard_context',
- description: 'Read the formatted screenplay, characters, and scenes for storyboard breakdown.',
- inputSchema: z.object({
- episode_id: z.number().describe('Episode ID'),
- }),
- execute: async ({ episode_id }) => {
- const [ep] = db.select().from(schema.episodes)
- .where(eq(schema.episodes.id, episode_id)).all()
- if (!ep) return { error: 'Episode not found' }
+export function createStoryboardTools(episodeId: number, dramaId: number) {
+ const readStoryboardContext = createTool({
+ id: 'read_storyboard_context',
+ description: 'Read the screenplay, characters, and scenes for storyboard breakdown.',
+ inputSchema: z.object({}),
+ execute: async () => {
+ const [ep] = db.select().from(schema.episodes)
+ .where(eq(schema.episodes.id, episodeId)).all()
+ if (!ep) return { error: 'Episode not found' }
+ const script = ep.scriptContent || ep.content
+ if (!script) return { error: 'Episode has no script' }
- const script = ep.scriptContent || ep.content
- if (!script) return { error: 'Episode has no script' }
+ const chars = db.select().from(schema.characters)
+ .where(eq(schema.characters.dramaId, dramaId)).all()
+ const scns = db.select().from(schema.scenes)
+ .where(eq(schema.scenes.dramaId, dramaId)).all()
- const chars = db.select().from(schema.characters)
- .where(eq(schema.characters.dramaId, ep.dramaId)).all()
- const scns = db.select().from(schema.scenes)
- .where(eq(schema.scenes.dramaId, ep.dramaId)).all()
+ return {
+ script,
+ characters: chars.map(c => ({ id: c.id, name: c.name })),
+ scenes: scns.map(s => ({ id: s.id, location: s.location, time: s.time })),
+ }
+ },
+ })
- return {
- script,
- drama_id: ep.dramaId,
- episode_id: ep.id,
- characters: chars.map(c => ({ id: c.id, name: c.name })),
- scenes: scns.map(s => ({ id: s.id, location: s.location, time: s.time })),
- }
- },
-})
+ const saveStoryboards = createTool({
+ id: 'save_storyboards',
+ description: 'Save generated storyboards. Replaces all existing storyboards for this episode.',
+ inputSchema: z.object({
+ storyboards: z.array(z.object({
+ shot_number: z.number(),
+ title: z.string().optional(),
+ shot_type: z.string().optional(),
+ angle: z.string().optional(),
+ movement: z.string().optional(),
+ location: z.string().optional(),
+ time: z.string().optional(),
+ action: z.string().optional(),
+ dialogue: z.string().optional(),
+ description: z.string().optional(),
+ result: z.string().optional(),
+ atmosphere: z.string().optional(),
+ video_prompt: z.string().optional(),
+ duration: z.number().optional(),
+ scene_id: z.number().nullable().optional(),
+ })),
+ }),
+ execute: async ({ storyboards }) => {
+ const ts = now()
+ db.delete(schema.storyboards).where(eq(schema.storyboards.episodeId, episodeId)).run()
-// 保存分镜列表
-export const saveStoryboards = createTool({
- id: 'save_storyboards',
- description: 'Save generated storyboards to the database. Replaces existing storyboards for the episode.',
- inputSchema: z.object({
- episode_id: z.number().describe('Episode ID'),
- storyboards: z.array(z.object({
- shot_number: z.number(),
+ let totalDuration = 0
+ for (const sb of storyboards) {
+ db.insert(schema.storyboards).values({
+ episodeId,
+ storyboardNumber: sb.shot_number,
+ title: sb.title, shotType: sb.shot_type,
+ angle: sb.angle, movement: sb.movement,
+ location: sb.location, time: sb.time,
+ action: sb.action, dialogue: sb.dialogue,
+ description: sb.description, result: sb.result,
+ atmosphere: sb.atmosphere, videoPrompt: sb.video_prompt,
+ sceneId: sb.scene_id, duration: sb.duration || 10,
+ createdAt: ts, updatedAt: ts,
+ }).run()
+ totalDuration += sb.duration || 10
+ }
+
+ db.update(schema.episodes)
+ .set({ duration: Math.ceil(totalDuration / 60), updatedAt: ts })
+ .where(eq(schema.episodes.id, episodeId)).run()
+
+ return { message: `Saved ${storyboards.length} storyboards`, count: storyboards.length, total_duration: totalDuration }
+ },
+ })
+
+ const updateStoryboard = createTool({
+ id: 'update_storyboard',
+ description: 'Update a specific storyboard shot.',
+ inputSchema: z.object({
+ storyboard_id: z.number(),
title: z.string().optional(),
shot_type: z.string().optional(),
- angle: z.string().optional(),
- movement: z.string().optional(),
- location: z.string().optional(),
- time: z.string().optional(),
- action: z.string().optional(),
- dialogue: z.string().optional(),
- description: z.string().optional(),
- result: z.string().optional(),
- atmosphere: z.string().optional(),
video_prompt: z.string().optional(),
+ description: z.string().optional(),
+ dialogue: z.string().optional(),
duration: z.number().optional(),
- scene_id: z.number().nullable().optional(),
- characters: z.array(z.number()).optional(),
- })).describe('List of storyboard shots'),
- }),
- execute: async ({ episode_id, storyboards }) => {
- const ts = now()
-
- // 删除旧分镜
- db.delete(schema.storyboards)
- .where(eq(schema.storyboards.episodeId, episode_id))
- .run()
-
- // 插入新分镜
- let totalDuration = 0
- for (const sb of storyboards) {
- db.insert(schema.storyboards).values({
- episodeId: episode_id,
- storyboardNumber: sb.shot_number,
- title: sb.title,
- shotType: sb.shot_type,
- angle: sb.angle,
- movement: sb.movement,
- location: sb.location,
- time: sb.time,
- action: sb.action,
- dialogue: sb.dialogue,
- description: sb.description,
- result: sb.result,
- atmosphere: sb.atmosphere,
- videoPrompt: sb.video_prompt,
- sceneId: sb.scene_id,
- duration: sb.duration || 10,
- createdAt: ts,
- updatedAt: ts,
- }).run()
- totalDuration += sb.duration || 10
- }
-
- // 更新 episode 时长
- db.update(schema.episodes)
- .set({ duration: Math.ceil(totalDuration / 60), updatedAt: ts })
- .where(eq(schema.episodes.id, episode_id))
- .run()
-
- return {
- message: `Saved ${storyboards.length} storyboards`,
- count: storyboards.length,
- total_duration: totalDuration,
- }
- },
-})
-
-// 更新单个分镜
-export const updateStoryboard = createTool({
- id: 'update_storyboard',
- description: 'Update a specific storyboard shot.',
- inputSchema: z.object({
- storyboard_id: z.number().describe('Storyboard ID'),
- title: z.string().optional(),
- shot_type: z.string().optional(),
- video_prompt: z.string().optional(),
- description: z.string().optional(),
- dialogue: z.string().optional(),
- duration: z.number().optional(),
- }),
- execute: async ({ storyboard_id, ...fields }) => {
- const updates: Record<string, any> = { updatedAt: now() }
- if (fields.title) updates.title = fields.title
- if (fields.shot_type) updates.shotType = fields.shot_type
- if (fields.video_prompt) updates.videoPrompt = fields.video_prompt
- if (fields.description) updates.description = fields.description
- if (fields.dialogue) updates.dialogue = fields.dialogue
- if (fields.duration) updates.duration = fields.duration
-
- db.update(schema.storyboards)
- .set(updates)
- .where(eq(schema.storyboards.id, storyboard_id))
- .run()
+ }),
+ execute: async ({ storyboard_id, ...fields }) => {
+ const updates: Record<string, any> = { updatedAt: now() }
+ if (fields.title) updates.title = fields.title
+ if (fields.shot_type) updates.shotType = fields.shot_type
+ if (fields.video_prompt) updates.videoPrompt = fields.video_prompt
+ if (fields.description) updates.description = fields.description
+ if (fields.dialogue) updates.dialogue = fields.dialogue
+ if (fields.duration) updates.duration = fields.duration
+ db.update(schema.storyboards).set(updates).where(eq(schema.storyboards.id, storyboard_id)).run()
+ return { message: `Storyboard ${storyboard_id} updated` }
+ },
+ })
- return { message: `Storyboard ${storyboard_id} updated` }
- },
-})
+ return { readStoryboardContext, saveStoryboards, updateStoryboard }
+}
diff --git a/backend/src/routes/agent.ts b/backend/src/routes/agent.ts
index 3736337..9ecfdc5 100644
--- a/backend/src/routes/agent.ts
+++ b/backend/src/routes/agent.ts
@@ -3,7 +3,7 @@
*/
import { Hono } from 'hono'
import { streamSSE } from 'hono/streaming'
-import { getAgent, validAgentTypes } from '../agents/index.js'
+import { createAgent, validAgentTypes } from '../agents/index.js'
import { success, badRequest } from '../utils/response.js'
const app = new Hono()
@@ -18,29 +18,29 @@ app.post('/:type/chat', async (c) => {
const body = await c.req.json()
const { message, drama_id, episode_id } = body
- const agent = getAgent(agentType)
+ if (!episode_id || !drama_id) {
+ return badRequest(c, 'drama_id and episode_id are required')
+ }
+
+ // 每次请求创建新 agent(工具已注入 episodeId/dramaId)
+ const agent = createAgent(agentType, episode_id, drama_id)
if (!agent) return badRequest(c, 'Agent not found')
- // 构建消息,注入上下文
- const contextInfo = `[Context: drama_id=${drama_id}, episode_id=${episode_id}]`
- const fullMessage = `${contextInfo}\n\n${message}`
+ console.log(`[Agent] ${agentType} | drama=${drama_id} episode=${episode_id} | "${message}"`)
return streamSSE(c, async (stream) => {
try {
const result = await agent.stream([
- { role: 'user', content: fullMessage },
+ { role: 'user', content: message },
])
- // Stream fullStream for tool calls + text
for await (const chunk of result.fullStream) {
if (chunk.type === 'text-delta') {
await stream.writeSSE({
- data: JSON.stringify({
- type: 'content',
- data: chunk.textDelta,
- }),
+ data: JSON.stringify({ type: 'content', data: chunk.textDelta }),
})
} else if (chunk.type === 'tool-call') {
+ console.log(`[Agent] tool_call: ${chunk.toolName}(${JSON.stringify(chunk.args).slice(0, 200)})`)
await stream.writeSSE({
data: JSON.stringify({
type: 'tool_call',
@@ -49,9 +49,8 @@ app.post('/:type/chat', async (c) => {
}),
})
} else if (chunk.type === 'tool-result') {
- const resultStr = typeof chunk.result === 'string'
- ? chunk.result
- : JSON.stringify(chunk.result)
+ const resultStr = typeof chunk.result === 'string' ? chunk.result : JSON.stringify(chunk.result)
+ console.log(`[Agent] tool_result: ${chunk.toolName} → ${resultStr.slice(0, 100)}`)
await stream.writeSSE({
data: JSON.stringify({
type: 'tool_result',
@@ -62,16 +61,14 @@ app.post('/:type/chat', async (c) => {
}
}
- // Done
+ console.log(`[Agent] ${agentType} done`)
await stream.writeSSE({
data: JSON.stringify({ type: 'done', data: '' }),
})
} catch (err: any) {
+ console.error(`[Agent] ${agentType} error:`, err.message)
await stream.writeSSE({
- data: JSON.stringify({
- type: 'error',
- data: err.message || 'Agent execution failed',
- }),
+ data: JSON.stringify({ type: 'error', data: err.message || 'Agent execution failed' }),
})
}
})
@@ -80,14 +77,8 @@ app.post('/:type/chat', async (c) => {
// GET /agent/:type/debug
app.get('/:type/debug', async (c) => {
const agentType = c.req.param('type')
- const agent = getAgent(agentType)
- if (!agent) return badRequest(c, 'Invalid agent type')
-
- return success(c, {
- agent_type: agentType,
- name: agent.name,
- tools: Object.keys(agent.tools || {}),
- })
+ if (!validAgentTypes.includes(agentType)) return badRequest(c, 'Invalid agent type')
+ return success(c, { agent_type: agentType, valid: true })
})
export default app