Entwerfen Sie einen LLM-basierten Algorithmus, um Untertitel in Absätze und Kapitel zu organisieren.
Von Wikiprompt, der freien Prompt-Enzyklopädie
Entwerfen Sie einen LLM-basierten Algorithmus, um Untertitel in Absätze und Kapitel zu organisieren. Ein detaillierter Prompt, der darum bittet, einen Algorithmus mit LLM zu entwerfen, um Untertitelabschnitte in Absätze und Kapitel zu organisieren, mit spezifischen Einschränkungen bezüglich Kontextfenster, Paginierung, Kosten und Ausgabeformat.
Prompt-InhaltSpeichern
🌐
// 算法设计:基于大语言模型的字幕分段与章节整理
// 1. 预处理:将字幕按固定大小分页,确保语义完整性
function paginateSubtitles(segments: SubtitleSegment[], maxTokensPerPage: number): SubtitleSegment[][] {
const pages: SubtitleSegment[][] = [];
let currentPage: SubtitleSegment[] = [];
let currentTokens = 0;
for (const segment of segments) {
const segmentTokens = estimateTokens(segment.text);
// 如果当前页加上该段会超限,且当前页不为空,则翻页
if (currentTokens + segmentTokens > maxTokensPerPage && currentPage.length > 0) {
pages.push(currentPage);
currentPage = [];
currentTokens = 0;
}
currentPage.push(segment);
currentTokens += segmentTokens;
}
if (currentPage.length > 0) {
pages.push(currentPage);
}
return pages;
}
// 2. 单页处理:调用LLM获取该页的段落和章节信息
async function processPageWithLLM(
page: SubtitleSegment[],
previousContext: { lastChapterTitle?: string; lastParagraphEnd?: number }
): Promise<{ chapters: Chapter[]; lastChapterTitle?: string; lastParagraphEnd?: number }> {
// 构造提示词,要求LLM返回结构化数据
const prompt = `
以下是字幕片段(JSON格式):
${JSON.stringify(page)}
请分析这些字幕内容,将其组织成段落(Paragraph)和章节(Chapter)。
要求:
1. 段落由语义相关的连续字幕段组成
2. 章节由主题相关的段落组成,为每个章节起一个简洁的标题
3. 返回格式为JSON数组,每个元素包含:
- chapterTitle: 章节标题
- paragraphs: 段落数组,每个段落包含:
- startIndex: 起始字幕段索引(从0开始)
- endIndex: 结束字幕段索引(包含)
- text: 段落文本(可精简,但保留关键信息)
注意:
- 只返回JSON,不要有其他文字
- 如果某段内容与前文(上一页)紧密相关,可以将其标记为"continuation"
- 不要修改或删除字幕内容,只做分组
上一页的上下文:
- 上一章标题:${previousContext.lastChapterTitle || '无'}
- 上一段结束位置:${previousContext.lastParagraphEnd || '无'}
`;
// 调用LLM并解析结果
const llmResponse = await callLLM(prompt);
const parsedResult = JSON.parse(llmResponse);
// 将索引映射回实际的SubtitleSegment
const chapters: Chapter[] = [];
let lastChapterTitle = previousContext.lastChapterTitle;
let lastParagraphEnd = previousContext.lastParagraphEnd;
for (const chapterData of parsedResult) {
const paragraphs: Paragraph[] = [];
for (const paraData of chapterData.paragraphs) {
const startSeg = page[paraData.startIndex];
const endSeg = page[paraData.endIndex];
if (!startSeg || !endSeg) continue;
const paragraph: Paragraph = {
start: startSeg.start,
end: endSeg.end,
text: paraData.text || page.slice(paraData.startIndex, paraData.endIndex + 1)
.map(s => s.text).join(' '),
segments: page.slice(paraData.startIndex, paraData.endIndex + 1)
};
paragraphs.push(paragraph);
lastParagraphEnd = paragraph.end;
}
if (paragraphs.length > 0) {
const chapter: Chapter = {
title: chapterData.chapterTitle || lastChapterTitle || `章节 ${chapters.length + 1}`,
paragraphs
};
chapters.push(chapter);
lastChapterTitle = chapter.title;
}
}
return { chapters, lastChapterTitle, lastParagraphEnd };
}
// 3. 主算法:分页处理并合并结果
async function transcribeSubtitles(segments: SubtitleSegment[]): Promise<Transcription> {
const MAX_TOKENS_PER_PAGE = 3000; // 根据模型上下文调整
const pages = paginateSubtitles(segments, MAX_TOKENS_PER_PAGE);
const allChapters: Chapter[] = [];
let context = { lastChapterTitle: undefined, lastParagraphEnd: undefined };
for (let i = 0; i < pages.length; i++) {
const page = pages[i];
// 处理当前页
const result = await processPageWithLLM(page, context);
// 合并结果
if (result.chapters.length > 0) {
// 如果上一页有未完成的章节,且当前页第一段是continuation,则合并
if (allChapters.length > 0 && result.chapters[0].paragraphs[0]?.text.startsWith('continuation')) {
const lastChapter = allChapters[allChapters.length - 1];
lastChapter.paragraphs.push(...result.chapters[0].paragraphs);
result.chapters.shift();
}
allChapters.push(...result.chapters);
}
// 更新上下文
context = {
lastChapterTitle: result.lastChapterTitle || context.lastChapterTitle,
lastParagraphEnd: result.lastParagraphEnd || context.lastParagraphEnd
};
}
// 后处理:合并相邻的相同章节标题
const mergedChapters: Chapter[] = [];
for (const chapter of allChapters) {
const lastMerged = mergedChapters[mergedChapters.length - 1];
if (lastMerged && lastMerged.title === chapter.title) {
lastMerged.paragraphs.push(...chapter.paragraphs);
} else {
mergedChapters.push(chapter);
}
}
return { chapters: mergedChapters };
}
// 4. 辅助函数
function estimateTokens(text: string): number {
// 粗略估算:英文约4字符/token,中文约1.5字符/token
const chineseChars = (text.match(/[\u4e00-\u9fff]/g) || []).length;
const otherChars = text.length - chineseChars;
return Math.ceil(chineseChars / 1.5 + otherChars / 4);
}
// 5. 优化:批量处理多页以减少调用次数
async function processMultiplePagesWithLLM(
pages: SubtitleSegment[][],
batchSize: number = 3
): Promise<Chapter[]> {
const allChapters: Chapter[] = [];
for (let i = 0; i < pages.length; i += batchSize) {
const batch = pages.slice(i, i + batchSize);
// 将多页合并为一个提示词,但用特殊标记分隔
const combinedPrompt = batch.map((page, idx) => `
=== 第${idx + 1}页 ===
${JSON.stringify(page)}
`).join('\n');
// 调用LLM处理整个批次
const result = await callLLM(combinedPrompt);
// 解析并合并结果...
}
return allChapters;
}
// 6. 容错处理:LLM返回不完整时的修复
function repairLLMResponse(rawResponse: string, page: SubtitleSegment[]): any {
try {
// 尝试直接解析
return JSON.parse(rawResponse);
} catch {
// 提取JSON部分
const jsonMatch = rawResponse.match(/\[[\s\S]*\]/);
if (jsonMatch) {
try {
return JSON.parse(jsonMatch[0]);
} catch {
// 修复常见问题:缺失引号、多余逗号等
const fixed = jsonMatch[0]
.replace(/,\s*}/g, '}')
.replace(/,\s*]/g, ']')
.replace(/([{,]\s*)(\w+)(\s*:)/g, '$1"$2"$3');
return JSON.parse(fixed);
}
}
}
// 如果无法解析,返回空结果
return { chapters: [] };
}
```
**算法核心思路:**
1. **分页策略**:按token数分页,每页约3000 tokens,确保在上下文窗口内
2. **语义连续性**:通过传递上一页的章节标题和段落结束位置,让LLM知道上下文
3. **结构化输出**:要求LLM返回索引范围而非字符位置,避免数数错误
4. **容错处理**:对LLM输出进行修复,处理JSON解析失败的情况
5. **成本优化**:支持批量处理多页,减少调用次数;只传输必要的上下文信息
6. **后处理**:合并相同章节标题,确保章节完整性
**关键设计决策:**
- 使用索引而非时间戳,避免LLM处理数字错误
- 传递上一页的章节标题作为上下文,保持章节连贯
- 允许LLM返回"continuation"标记,处理跨页段落
- 批量处理减少API调用次数,降低成本
Melde dich an, um den vollständigen Prompt zu sehen
Weiter mit:
Mit der Anmeldung akzeptierst du unsere Nutzungsbedingungen und Datenschutz
Verwendung
Dieser Prompt ist für die Verwendung mit coding gedacht. Kopiere den Inhalt oben und füge ihn in dein bevorzugtes KI-Tool ein.
Für beste Ergebnisse passe die Platzhalter (eckige Klammern oder Großbuchstaben) an deine Anforderungen an.
Referenzen
- Kategorie: coding-Prompts
- Quelle: https://x.com/dotey/status/1869793040484741269
Diskussion
0 Kommentare