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(storyboard): 拆解分批保存防输出截断,注入 max_tokens,update_storyboard 过滤 null 垃圾值,约束只传两个参数键

WorkStation66e34f451225
diff --git a/backend/src/agents/index.ts b/backend/src/agents/index.ts
index 04f0200..3ec138b 100644
--- a/backend/src/agents/index.ts
+++ b/backend/src/agents/index.ts
@@ -80,7 +80,12 @@ export const DEFAULT_PROMPTS: Record<string, { name: string; instructions: strin
1. 调用 read_storyboard_context 读取剧本、角色列表、场景列表、道具列表
2. 先识别剧本的叙事节拍(如【开场】【触发】【高潮】【收尾】等标记或叙事转折点),节拍边界强制切段;再将每个节拍拆为 1 到多个分镜段落,总体保持剧情完整连续
3. 为每个段落补全生产字段(拆分时不需要生成 video_prompt,该字段由提示词 Agent 在视频生成阶段生成)
-4. 调用 save_storyboards 保存所有分镜段落
+4. 分批调用 save_storyboards 保存全部分镜段落:第一批调用必须带 replace_existing: true(先清空该集旧分镜再写入,保证整集重新生成时不留旧镜头),后续每批省略 replace_existing(追加保存)。每批最多 8 个段落,shot_number 必须按顺序递增;全部段落保存完成前不要结束(不要只保存部分段落就停止)
+
+硬约束(必须遵守):
+- 不要输出任何规划、分析、推理或解释性文本,不要复述剧本,不要写「我正在…」「首先我需要…」这类话——思考留在模型内部,输出只允许工具调用
+- 每个输出步骤必须是工具调用(或完成后的简短结束语),禁止先输出大段文字再调用工具
+- 若因内容过多需要分多批,直接在连续的工具调用中完成全部批次,中间不要插入文字
每个段落只需要填写以下字段:
- character_ids:当前段落涉及的角色 ID 列表,可以为空,也可以包含多个角色;必须从 characters 中选择
@@ -126,7 +131,7 @@ export const DEFAULT_PROMPTS: Record<string, { name: string; instructions: strin
1. 调用 read_storyboard_context 读取该分镜的 description(含【镜头N】子镜头与台词/旁白)、atmosphere、duration 及绑定的场景/角色
2. 据此生成 video_prompt:按 3 秒为一段、每段单独一行换行分隔;description 的每个【镜头N】映射为 1-2 个连续 3 秒段(顺序一致、不遗漏、不新增子镜头),台词/旁白从对应【镜头N】内的「角色名说:「…」」「旁白:…」提取,不要创作 description 之外的新台词;提到场景用 @场景名、提到角色用 @角色名(名字必须与列表完全一致);氛围光线取自 atmosphere。一个分镜段落内允许切镜(换景别/角度/对象),段与段之间可以是不同镜头,但不跨场景;切镜点对齐分镜 description 的【镜头N】结构
3. 生成时会自动把 @名字 替换为对应参考图片标记(如 @小明 → @图片1小明),因此名字必须精确匹配场景/角色列表,不要缩写或加额外符号
-4. 调用 update_storyboard 仅更新该分镜的 video_prompt 字段,不要改动其他字段,不要重新拆分整集
+4. 调用 update_storyboard 保存时参数只传两个键:storyboard_id 和 video_prompt。不要回传该分镜的其他任何字段(title、description、scene_id 等一律不传)
通用规范:
- 所有提示词只输出中文,单段连贯描述,不要分点,不要混入英文词汇
@@ -200,27 +205,97 @@ function createThinkingOffFetch(providerName: string, baseURL: string): typeof f
}
}
+/**
+ * 在请求体中写入配置的温度
+ *
+ * 背景:部分模型服务端强制固定温度(如 kimi-k2 系只允许 0.6,
+ * 报 "invalid temperature: only 0.6 is allowed for this model"),
+ * 需要在文本服务配置里显式指定并随每个请求下发。
+ * inner 传 thinking-off fetch 时可链式叠加两个补丁。
+ */
+function createTemperatureFetch(providerName: string, temperature: number, inner?: typeof fetch): typeof fetch {
+ const base = inner || fetch
+ return async (input: any, init?: any) => {
+ try {
+ if (init?.body && typeof init.body === 'string') {
+ const body = JSON.parse(init.body)
+ if (providerName === 'gemini' && Array.isArray(body?.contents)) {
+ // Gemini 原生格式
+ body.generationConfig = { ...(body.generationConfig || {}), temperature }
+ init = { ...init, body: JSON.stringify(body) }
+ } else if (Array.isArray(body?.messages)) {
+ // OpenAI 兼容格式
+ body.temperature = temperature
+ init = { ...init, body: JSON.stringify(body) }
+ }
+ }
+ } catch { /* 解析失败则原样透传 */ }
+ return base(input, init)
+ }
+}
+
+/**
+ * 在请求体中注入输出上限
+ *
+ * 背景:Agent 输出可能包含大段规划文本 + 工具调用(尤其分批保存时),
+ * 而服务商默认 max_tokens 很小(如 DeepSeek 默认 4096/8192),
+ * 模型写作到一半被截断、工具调用从未生成,表现为「Agent 正常结束但什么都没保存」。
+ * 这里显式抬高输出上限,给足模型完整生成工具调用的空间。
+ * AI_MAX_TOKENS 可覆盖默认值(如某些中转站限制更严)。
+ */
+const defaultMaxTokens = Number(process.env.AI_MAX_TOKENS || 16384)
+
+function createMaxTokensFetch(providerName: string, inner?: typeof fetch): typeof fetch {
+ const base = inner || fetch
+ return async (input: any, init?: any) => {
+ try {
+ if (init?.body && typeof init.body === 'string') {
+ const body = JSON.parse(init.body)
+ if (providerName === 'gemini' && Array.isArray(body?.contents)) {
+ // Gemini 原生格式
+ body.generationConfig = { ...(body.generationConfig || {}), maxOutputTokens: defaultMaxTokens }
+ init = { ...init, body: JSON.stringify(body) }
+ } else if (Array.isArray(body?.messages)) {
+ // OpenAI 兼容格式
+ body.max_tokens = defaultMaxTokens
+ init = { ...init, body: JSON.stringify(body) }
+ }
+ }
+ } catch { /* 解析失败则原样透传 */ }
+ return base(input, init)
+ }
+}
+
async function getModel(fileModel: string | undefined, modelOverride?: string, textConfigId?: number) {
// 请求可指定文本配置(含其 provider/baseUrl/apiKey),否则回退到当前启用配置
const textConfig = (textConfigId ? await getConfigById(textConfigId) : null) || await getTextConfig()
const modelName = modelOverride || fileModel || textConfig.model
const providerName = textConfig.provider.toLowerCase()
const resolvedBaseURL = getTextProviderBaseUrl(textConfig)
- const endpointKey = `${providerName}|${resolvedBaseURL}|${modelName}`
+ const temperature = textConfig.temperature ?? null
+ const endpointKey = `${providerName}|${resolvedBaseURL}|${modelName}|t=${temperature ?? 'default'}`
if (endpointKey !== lastLoggedTextEndpointKey) {
lastLoggedTextEndpointKey = endpointKey
logTaskProgress('AIConfig', 'text-model-endpoint', {
provider: textConfig.provider,
baseUrl: resolvedBaseURL,
model: modelName,
+ ...(temperature !== null ? { temperature } : {}),
})
}
+ // 叠加请求补丁:thinking-off(非官方端点)+ 配置温度 + 输出上限
+ const thinkingOffFetch = createThinkingOffFetch(providerName, resolvedBaseURL)
+ const tempFetch = temperature !== null
+ ? createTemperatureFetch(providerName, temperature, thinkingOffFetch)
+ : thinkingOffFetch
+ const fetchImpl = createMaxTokensFetch(providerName, tempFetch)
+
if (providerName === 'gemini') {
const googleProvider = createGoogleGenerativeAI({
apiKey: textConfig.apiKey,
baseURL: resolvedBaseURL,
- fetch: createThinkingOffFetch(providerName, resolvedBaseURL),
+ fetch: fetchImpl,
})
return googleProvider(modelName)
}
@@ -228,7 +303,7 @@ async function getModel(fileModel: string | undefined, modelOverride?: string, t
const provider = createOpenAI({
baseURL: resolvedBaseURL,
apiKey: textConfig.apiKey,
- fetch: createThinkingOffFetch(providerName, resolvedBaseURL),
+ fetch: fetchImpl,
} as any)
return provider.chat(modelName)
}
diff --git a/backend/src/agents/tools/storyboard-tools.ts b/backend/src/agents/tools/storyboard-tools.ts
index f52d47d..d1c4271 100644
--- a/backend/src/agents/tools/storyboard-tools.ts
+++ b/backend/src/agents/tools/storyboard-tools.ts
@@ -224,32 +224,35 @@ const readStoryboardContext = createTool({
},
})
+const storyboardFields = 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(),
+ description: z.string().optional(),
+ result: z.string().optional(),
+ atmosphere: z.string().optional(),
+ image_prompt: z.string().optional(),
+ video_prompt: z.string().optional(),
+ bgm_prompt: z.string().optional(),
+ sound_effect: z.string().optional(),
+ duration: z.number().optional(),
+ scene_id: z.number().nullable().optional(),
+ character_ids: z.array(z.number()).optional(),
+ prop_ids: z.array(z.number()).optional(),
+})
+
const saveStoryboards = createTool({
id: 'save_storyboards',
- description: 'Save generated storyboards. Replaces all existing storyboards for this episode.',
+ description: 'Save storyboards for this episode. Call in batches of at most 8 storyboards: the first batch must set replace_existing: true (clears all old storyboards for the episode, then writes), every following batch omits replace_existing (appends). Rows are upserted by shot_number, so overlapping batches and retries never create duplicates.',
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(),
- description: z.string().optional(),
- result: z.string().optional(),
- atmosphere: z.string().optional(),
- image_prompt: z.string().optional(),
- video_prompt: z.string().optional(),
- bgm_prompt: z.string().optional(),
- sound_effect: z.string().optional(),
- duration: z.number().optional(),
- scene_id: z.number().nullable().optional(),
- character_ids: z.array(z.number()).optional(),
- prop_ids: z.array(z.number()).optional(),
- })),
+ replace_existing: z.boolean().optional(),
+ storyboards: z.array(storyboardFields),
}),
- execute: async ({ storyboards }, context) => {
+ execute: async ({ storyboards, replace_existing }, context) => {
const ids = requireIds(context)
if ('error' in ids) return ids
const { episodeId, dramaId } = ids
@@ -257,41 +260,74 @@ const saveStoryboards = createTool({
logTaskProgress('StoryboardTool', 'save-begin', {
episodeId,
dramaId,
+ replaceExisting: replace_existing === true,
count: storyboards.length,
shotNumbers: storyboards.map(sb => sb.shot_number).join(','),
})
- const existingStoryboardRows = await db.select().from(schema.storyboards)
- .where(eq(schema.storyboards.episodeId, episodeId))
- const existingStoryboardIds = existingStoryboardRows.map(sb => sb.id)
- for (const storyboardId of existingStoryboardIds) {
- await db.delete(schema.storyboardCharacters)
- .where(eq(schema.storyboardCharacters.storyboardId, storyboardId))
- await db.delete(schema.storyboardProps)
- .where(eq(schema.storyboardProps.storyboardId, storyboardId))
+ if (replace_existing === true) {
+ const existingStoryboardRows = await db.select().from(schema.storyboards)
+ .where(eq(schema.storyboards.episodeId, episodeId))
+ for (const storyboardId of existingStoryboardRows.map(sb => sb.id)) {
+ await db.delete(schema.storyboardCharacters)
+ .where(eq(schema.storyboardCharacters.storyboardId, storyboardId))
+ await db.delete(schema.storyboardProps)
+ .where(eq(schema.storyboardProps.storyboardId, storyboardId))
+ }
+ await db.delete(schema.storyboards).where(eq(schema.storyboards.episodeId, episodeId))
}
- await db.delete(schema.storyboards).where(eq(schema.storyboards.episodeId, episodeId))
- let totalDuration = 0
+ // shot_number → id 索引(含本次调用内新增的行),保证按分镜号幂等 upsert
+ const existingRows = await db.select().from(schema.storyboards)
+ .where(eq(schema.storyboards.episodeId, episodeId))
+ const shotToId = new Map<number, number>(
+ existingRows.filter(sb => !sb.deletedAt).map(sb => [sb.storyboardNumber, sb.id]),
+ )
+
for (const sb of storyboards) {
await validateStoryboardBindings(episodeId, dramaId, sb.scene_id, sb.character_ids, sb.prop_ids)
- const res = await 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,
- description: sb.description, result: sb.result,
- atmosphere: sb.atmosphere, imagePrompt: sb.image_prompt,
- videoPrompt: sb.video_prompt, bgmPrompt: sb.bgm_prompt,
- soundEffect: sb.sound_effect,
- sceneId: sb.scene_id, duration: sb.duration || 10,
- createdAt: ts, updatedAt: ts,
- })
- await syncStoryboardCharacters(getInsertId(res), sb.character_ids || [])
- await syncStoryboardProps(getInsertId(res), sb.prop_ids || [])
- totalDuration += sb.duration || 10
+ const existingId = shotToId.get(sb.shot_number)
+ if (existingId !== undefined) {
+ await db.update(schema.storyboards).set({
+ title: sb.title, shotType: sb.shot_type,
+ angle: sb.angle, movement: sb.movement,
+ location: sb.location, time: sb.time,
+ description: sb.description, result: sb.result,
+ atmosphere: sb.atmosphere, imagePrompt: sb.image_prompt,
+ videoPrompt: sb.video_prompt, bgmPrompt: sb.bgm_prompt,
+ soundEffect: sb.sound_effect,
+ sceneId: sb.scene_id, duration: sb.duration || 10,
+ updatedAt: ts,
+ }).where(eq(schema.storyboards.id, existingId))
+ await syncStoryboardCharacters(existingId, sb.character_ids || [])
+ await syncStoryboardProps(existingId, sb.prop_ids || [])
+ } else {
+ const res = await 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,
+ description: sb.description, result: sb.result,
+ atmosphere: sb.atmosphere, imagePrompt: sb.image_prompt,
+ videoPrompt: sb.video_prompt, bgmPrompt: sb.bgm_prompt,
+ soundEffect: sb.sound_effect,
+ sceneId: sb.scene_id, duration: sb.duration || 10,
+ createdAt: ts, updatedAt: ts,
+ })
+ const newId = getInsertId(res)
+ shotToId.set(sb.shot_number, newId)
+ await syncStoryboardCharacters(newId, sb.character_ids || [])
+ await syncStoryboardProps(newId, sb.prop_ids || [])
+ }
}
+ // 整集时长 = 当前全部存活分镜时长之和(分批保存时不能再按单批累加)
+ const allRows = await db.select().from(schema.storyboards)
+ .where(eq(schema.storyboards.episodeId, episodeId))
+ const totalDuration = allRows
+ .filter(sb => !sb.deletedAt)
+ .reduce((sum, sb) => sum + (sb.duration || 0), 0)
+
await db.update(schema.episodes)
.set({ duration: Math.ceil(totalDuration / 60), updatedAt: ts })
.where(eq(schema.episodes.id, episodeId))
@@ -334,6 +370,16 @@ const updateStoryboard = createTool({
const { episodeId, dramaId } = ids
const [storyboard] = await db.select().from(schema.storyboards).where(eq(schema.storyboards.id, storyboard_id))
if (!storyboard) return { error: `Storyboard ${storyboard_id} not found` }
+
+ // 过滤模型回传的垃圾值:视频提示词 Agent 常把整行字段回传,
+ // 拿不准的字符串字段写成 "null"/"undefined",直接覆盖会毁掉已有内容
+ for (const key of Object.keys(fields) as (keyof typeof fields)[]) {
+ const v = fields[key]
+ if (typeof v === 'string' && (v === 'null' || v === 'undefined' || v === 'NULL' || v === 'Null')) {
+ delete fields[key]
+ }
+ }
+
logTaskProgress('StoryboardTool', 'update-begin', {
episodeId,
storyboardId: storyboard_id,
diff --git a/backend/src/routes/agent.ts b/backend/src/routes/agent.ts
index fe48a67..73c452e 100644
--- a/backend/src/routes/agent.ts
+++ b/backend/src/routes/agent.ts
@@ -10,8 +10,12 @@ import { logTaskError, logTaskPayload, logTaskProgress, logTaskStart, logTaskSuc
const app = new Hono()
+// Mastra v1.17 的 ToolCallChunk / ToolResultChunk 结构:
+// { type: 'tool-call', payload: { toolCallId, toolName, args } }
+// { type: 'tool-result', payload: { toolCallId, toolName, result, isError } }
function normalizeToolName(entry: any) {
- return entry?.toolName
+ return entry?.payload?.toolName
+ || entry?.toolName
|| entry?.tool?.toolName
|| entry?.tool?.id
|| entry?.name
@@ -20,7 +24,7 @@ function normalizeToolName(entry: any) {
}
function normalizeToolResult(entry: any) {
- const result = entry?.result ?? entry?.output ?? entry?.data ?? null
+ const result = entry?.payload?.result ?? entry?.result ?? entry?.payload?.output ?? entry?.output ?? entry?.data ?? null
return typeof result === 'string' ? result : JSON.stringify(result)
}
@@ -75,7 +79,7 @@ app.post('/:type/chat', async (c) => {
const toolResults = result.toolResults || []
const normalizedToolCalls = toolCalls.map((tc: any) => ({
toolName: normalizeToolName(tc),
- args: tc?.args ?? tc?.input ?? null,
+ args: tc?.payload?.args ?? tc?.args ?? tc?.input ?? null,
}))
const normalizedToolResults = toolResults.map((tr: any) => ({
toolName: normalizeToolName(tr),
diff --git a/backend/src/services/video-prompts.ts b/backend/src/services/video-prompts.ts
index f20a6af..7248af7 100644
--- a/backend/src/services/video-prompts.ts
+++ b/backend/src/services/video-prompts.ts
@@ -73,7 +73,7 @@ export async function startVideoPromptBatch(
await agent.generate([{
role: 'user',
content: `请为分镜 #${sb.storyboardNumber}(ID:${sb.id})生成视频提示词(video_prompt)。视频模型:${videoLabel},请根据该模型的特性和时长限制生成。
-请先调用 read_storyboard_context 获取该分镜的画面描述(含【镜头N】子镜头与台词/旁白)、氛围及时长,据此生成 video_prompt(按 3 秒分段换行、用 @角色名/@场景名/@道具名 引用参考素材;段落内允许多镜头切镜,段与段可以是不同景别/角度/对象,但不跨场景,切镜点对齐分镜 description 的【镜头N】结构),然后调用 update_storyboard 保存到分镜 ID:${sb.id}。只更新 video_prompt 字段,不要改动其他字段,不要重新拆分整集。`,
+请先调用 read_storyboard_context 获取该分镜的画面描述(含【镜头N】子镜头与台词/旁白)、氛围及时长,据此生成 video_prompt(按 3 秒分段换行、用 @角色名/@场景名/@道具名 引用参考素材;段落内允许多镜头切镜,段与段可以是不同景别/角度/对象,但不跨场景,切镜点对齐分镜 description 的【镜头N】结构),然后调用 update_storyboard 保存到分镜 ID:${sb.id}。update_storyboard 参数只传 storyboard_id 和 video_prompt 两个键,不要回传该分镜的其他任何字段,不要重新拆分整集。`,
}], { maxSteps: 8, requestContext })
// 以实际落库为准判定成败
const [fresh] = await db.select().from(schema.storyboards).where(eq(schema.storyboards.id, sb.id))