Skip to content

Commit c9a7c12

Browse files
cgsvcgsv
cgsv
authored and
cgsv
committed
prompt tuning
1 parent b0bc344 commit c9a7c12

File tree

4 files changed

+24
-18
lines changed

4 files changed

+24
-18
lines changed

lib/openai/prompt.ts

+9-10
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
import { getRandomInt } from "../../utils/fp";
22
import {Node} from "../srt"
33
import { OpenAIStreamPayload } from "./OpenAIResult";
4+
import { DEFAULT_PROMPT } from "../../utils/constants";
45

56
// gpt返回格式为: '1\n我仍然在问自己,当我离开这个漂浮的城市时,我是否做了正确的事情。\n\n2\n我不仅指工作。'
67
export function parse_gpt_resp(content: string, res_keys: number[]) {
8+
console.log(content);
79
const lines = content.split("\n").map(line => line.trim()).filter(line => line.length > 0);
810
const positions = res_keys.map(i => lines.indexOf(String(i)));
911
const res: string[] = [];
@@ -12,8 +14,7 @@ export function parse_gpt_resp(content: string, res_keys: number[]) {
1214
if (p1 === -1) {
1315
res.push("");
1416
} else {
15-
let next_pos: number | undefined = positions[i+1];
16-
if (next_pos === -1) next_pos = undefined;
17+
let next_pos = positions.slice(i+1).find(p2 => p2 !== -1);
1718
res.push(lines.slice(p1+1, next_pos).join('\n'));
1819
}
1920
}
@@ -28,13 +29,11 @@ export function nodesToQueryText(nodes: Node[]) {
2829

2930
// 中文, 英文
3031
function systemMessage(targetLang: string, srcLang?: string, promptTemplate?: string) {
31-
if (!srcLang) {
32-
if (promptTemplate) return promptTemplate.replace("{{target_lang}}", targetLang);
33-
return `你是一个专业的翻译。请逐行翻译上面的文本到${targetLang},注意保留行号及换行符。`;
34-
} else {
35-
if (promptTemplate) return promptTemplate.replace("{{target_lang}}", targetLang).replace("{{src_lang}}", srcLang);
36-
return `你是一个专业的翻译。请逐行把上面的文本从${srcLang}翻译到${targetLang},注意保留行号及换行符。`;
32+
let prompt = (promptTemplate || DEFAULT_PROMPT).replace("{{target_lang}}", targetLang);
33+
if (srcLang) {
34+
prompt = prompt.replace("{{src_lang}}", srcLang);
3735
}
36+
return prompt;
3837
}
3938

4039
const rand4 = () => getRandomInt(1000, 9999);
@@ -59,8 +58,8 @@ export function getPayload(sentences: string[], targetLang: string, srcLang?: st
5958
const payload: OpenAIStreamPayload = {
6059
model: "gpt-3.5-turbo",
6160
messages: [
62-
// {role: "system" as const, content: systemMessage(targetLang, srcLang) },
63-
{role: "user" as const, content: nodesToQueryText(nodes) + "\n" + systemMessage(targetLang, srcLang, promptTemplate)}],
61+
{role: "system" as const, content: systemMessage(targetLang, srcLang, promptTemplate) },
62+
{role: "user" as const, content: nodesToQueryText(nodes)}],
6463
temperature: 0, // translate task temperature 0?
6564
top_p: 1,
6665
frequency_penalty: 0,

middleware.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,8 @@ export async function middleware(req: NextRequest, context: NextFetchEvent) {
1515
rkey = "tranres_" + await digestMessage(rkey);
1616
const cached = await redis.get<string[]>(rkey);
1717

18-
//if (!isDev && cached) {
19-
if (cached) {
18+
if (!isDev && cached) {
19+
//if (cached) {
2020
console.log("Using cached response " + rkey);
2121
return NextResponse.json(cached);
2222
}

pages/srt.tsx

+12-6
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ function curPageNodes(nodes: Node[], curPage: number) {
3939

4040
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
4141

42-
async function traslate_all(nodes: Node[], lang: string, apiKey?: string, notifyResult?: any, useGoogle?: boolean) {
42+
async function traslate_all(nodes: Node[], lang: string, apiKey?: string, notifyResult?: any, useGoogle?: boolean, promptTemplate?: string) {
4343
const batches: Node[][] = [];
4444
for (let i = 0; i < nodes.length; i += PAGE_SIZE) {
4545
batches.push(nodes.slice(i, i + PAGE_SIZE));
@@ -51,7 +51,7 @@ async function traslate_all(nodes: Node[], lang: string, apiKey?: string, notify
5151
let success = false;
5252
for (let i = 0; i < MAX_RETRY && !success; i++) {
5353
try {
54-
const r = await translate_one_batch(batch, lang, apiKey, useGoogle);
54+
const r = await translate_one_batch(batch, lang, apiKey, useGoogle, promptTemplate);
5555
results.push(...r);
5656
success = true;
5757
if (notifyResult) {
@@ -72,7 +72,7 @@ async function traslate_all(nodes: Node[], lang: string, apiKey?: string, notify
7272
return results;
7373
}
7474

75-
async function translate_one_batch(nodes: Node[], lang: string, apiKey?: string, useGoogle?: boolean) {
75+
async function translate_one_batch(nodes: Node[], lang: string, apiKey?: string, useGoogle?: boolean, promptTemplate?: string) {
7676
const sentences = nodes.map(node => node.content);
7777
// if last sentence ends with ",", remove it
7878
const lastSentence = sentences[sentences.length - 1];
@@ -88,7 +88,8 @@ async function translate_one_batch(nodes: Node[], lang: string, apiKey?: string,
8888
body: JSON.stringify({
8989
"targetLang": lang,
9090
"sentences": sentences,
91-
"apiKey": apiKey
91+
"apiKey": apiKey,
92+
"promptTemplate": promptTemplate
9293
})
9394
};
9495

@@ -157,6 +158,11 @@ export default function Srt() {
157158
else return userLicenceKey;
158159
}
159160

161+
const getUserPrompt = () => {
162+
const res = localStorage.getItem("user-prompt-template");
163+
if (res) return res;
164+
}
165+
160166
const getLang = () => {
161167
return (document.getElementById("langSelect") as HTMLSelectElement).value;
162168
}
@@ -227,7 +233,7 @@ export default function Srt() {
227233
const translateFile = async () => {
228234
setTransFileStatus({isTranslating: true, transCount: 0});
229235
try {
230-
const newnodes = await traslate_all(nodes, getLang(), getUserKey(), on_trans_result, getUseGoogle());
236+
const newnodes = await traslate_all(nodes, getLang(), getUserKey(), on_trans_result, getUseGoogle(), getUserPrompt());
231237
//download("output.srt", nodesToSrtText(newnodes));
232238
toast.success(t("translate file successfully"));
233239
} catch (e) {
@@ -239,7 +245,7 @@ export default function Srt() {
239245
const translate = async () => {
240246
setLoading(true);
241247
try {
242-
const newnodes = await translate_one_batch(curPageNodes(nodes, curPage), getLang(), getUserKey(), getUseGoogle());
248+
const newnodes = await translate_one_batch(curPageNodes(nodes, curPage), getLang(), getUserKey(), getUseGoogle(), getUserPrompt());
243249
setTransNodes(nodes => {
244250
const nodesCopy = [...nodes];
245251
for (let i = 0; i < PAGE_SIZE; i++) {

utils/constants.ts

+1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
export const RATE_LIMIT_COUNT = 5;
22
export const CHECKOUT_URL = "https://coolapps.lemonsqueezy.com/checkout/buy/f53d875a-4424-4ea3-8398-f3559dfaef98";
33
export const ENABLE_SHOP = process.env.NEXT_PUBLIC_ENABLE_SHOP === "true";
4+
export const DEFAULT_PROMPT = "你是一个专业的翻译。请逐行翻译下面的文本到{{target_lang}},注意保留数字和换行符,请勿自行创建内容,除了翻译,不要输出任何其他文本。"

0 commit comments

Comments
 (0)