From 7b223590a4e24306b5edc8cf44334d698811e540 Mon Sep 17 00:00:00 2001 From: DIYgod Date: Thu, 5 Sep 2024 14:26:46 +0800 Subject: [PATCH] feat: use gpt-4o-mini --- src/app/api/score/route.ts | 2 +- src/app/api/translate-note/route.ts | 33 +++------- src/lib/calculate-tokens.ts | 66 -------------------- src/lib/llm-model-switcher-by-text-length.ts | 54 ---------------- src/queries/page.server.ts | 2 +- 5 files changed, 9 insertions(+), 148 deletions(-) delete mode 100644 src/lib/calculate-tokens.ts delete mode 100644 src/lib/llm-model-switcher-by-text-length.ts diff --git a/src/app/api/score/route.ts b/src/app/api/score/route.ts index 26217128..e676990e 100644 --- a/src/app/api/score/route.ts +++ b/src/app/api/score/route.ts @@ -60,7 +60,7 @@ ${content} --------`, }, ], - model: "gpt-3.5-turbo", + model: "gpt-4o-mini", temperature: 0, response_format: { type: "json_object" }, }) diff --git a/src/app/api/translate-note/route.ts b/src/app/api/translate-note/route.ts index 7c517a65..6b14b1f9 100644 --- a/src/app/api/translate-note/route.ts +++ b/src/app/api/translate-note/route.ts @@ -8,7 +8,6 @@ import { Metadata } from "@prisma/client" import { languageNames } from "~/i18n" import { detectLanguage } from "~/lib/detect-lang" import { toGateway } from "~/lib/ipfs-parser" -import { llmModelSwitcherByTextLength } from "~/lib/llm-model-switcher-by-text-length" import prisma from "~/lib/prisma.server" import { cacheGet } from "~/lib/redis.server" import { getQuery, NextServerResponse } from "~/lib/server-helper" @@ -21,22 +20,17 @@ type ContentTranslation = { content?: string } -let translationModel4K: OpenAI | undefined -let translationModel16K: OpenAI | undefined +let openai: OpenAI | undefined if (process.env.OPENAI_API_KEY) { const options = { openAIApiKey: process.env.OPENAI_API_KEY, temperature: 0.2, maxTokens: -1, } - translationModel4K = new OpenAI({ ...options, modelName: "gpt-3.5-turbo" }) - translationModel16K = new OpenAI({ - ...options, - modelName: "gpt-3.5-turbo-16k", - }) + openai = new OpenAI({ ...options, modelName: "gpt-4o-mini" }) } -type ChainKeyType = `${4 | 16}k_${Language}` // e.g. "4k_en" | "4k_zh" | "4k_zh-TW" | "4k_ja" | "16k_en" | "16k_zh" | "16k_zh-TW" | "16k_ja" +type ChainKeyType = Language // e.g. "4k_en" | "4k_zh" | "4k_zh-TW" | "4k_ja" | "16k_en" | "16k_zh" | "16k_zh-TW" | "16k_ja" const translationChains = new Map() const getOriginalTranslation = async ({ @@ -50,7 +44,7 @@ const getOriginalTranslation = async ({ }): Promise => { if (fromLang === toLang) return - if (!translationModel4K || !translationModel16K) return + if (!openai) return try { const { title, content } = await ( @@ -60,18 +54,8 @@ const getOriginalTranslation = async ({ if (!fromLang && detectLanguage(title + content) === toLang) return console.time(`fetching translation ${cid}, ${toLang}`) - const { modelSize, tokens } = llmModelSwitcherByTextLength(content, { - includeResponse: { lang: toLang }, - }) - if (!modelSize) { - console.error( - `|__ Error: Content too long for translation: ${cid}, ${toLang}. (Tokens: ${tokens})`, - ) - return - } - - let chain = translationChains.get(`${modelSize}_${toLang}`) + let chain = translationChains.get(toLang) if (!chain) { const template = ` @@ -101,12 +85,9 @@ Translate the following text to ${languageNames[toLang]} language: inputVariables: ["text"], }) - const translateModel = - modelSize === "4k" ? translationModel4K : translationModel16K + chain = new LLMChain({ llm: openai, prompt }) - chain = new LLMChain({ llm: translateModel, prompt }) - - translationChains.set(`${modelSize}_${toLang}`, chain) + translationChains.set(toLang, chain) } const t = diff --git a/src/lib/calculate-tokens.ts b/src/lib/calculate-tokens.ts deleted file mode 100644 index 62cf242d..00000000 --- a/src/lib/calculate-tokens.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { encode } from "gpt-tokenizer" - -export type ModelTypes = - | "gpt-3.5-turbo" - | "gpt-3.5-turbo-0613" - | "gpt-3.5-turbo-16k" - | "gpt-3.5-turbo-16k-0613" - | "gpt-3.5-turbo-0301" - | "gpt-4" - | "gpt-4-0314" - | "gpt-4-32k-0314" - | "gpt-4-0613" - | "gpt-4-32k-0613" - -export function calculateTokens( - messages: string, - model: ModelTypes = "gpt-3.5-turbo-0613", -) { - let tokens_per_message = 0 - let tokens_per_name = 0 - if ( - [ - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-16k-0613", - "gpt-4-0314", - "gpt-4-32k-0314", - "gpt-4-0613", - "gpt-4-32k-0613", - ].includes(model) - ) { - tokens_per_message = 3 - tokens_per_name = 1 - } else if (model == "gpt-3.5-turbo-0301") { - tokens_per_message = 4 - tokens_per_name = -1 - } else if (model.includes("gpt-3.5-turbo")) { - console.log( - "Warning: gpt-3.5-turbo may update over time. Returning num tokens assuming gpt-3.5-turbo-0613.", - ) - return calculateTokens(messages, "gpt-3.5-turbo-0613") - } else if (model.includes("gpt-4")) { - console.log( - "Warning: gpt-4 may update over time. Returning num tokens assuming gpt-4-0613.", - ) - return calculateTokens(messages, "gpt-4-0613") - } else { - throw new Error( - `num_tokens_from_messages() is not implemented for model ${model}. See https://github.com/openai/openai-python/blob/main/chatml.md for information on how messages are converted to tokens.`, - ) - } - let num_tokens = 0 - for (let i = 0; i < messages.length; i++) { - let message = messages[i] - num_tokens += tokens_per_message - // @ts-ignore - for (let key in message) { - let value = message[key] - num_tokens += encode(value).length - if (key == "name") { - num_tokens += tokens_per_name - } - } - } - num_tokens += 3 - return num_tokens -} diff --git a/src/lib/llm-model-switcher-by-text-length.ts b/src/lib/llm-model-switcher-by-text-length.ts deleted file mode 100644 index 6cef8b35..00000000 --- a/src/lib/llm-model-switcher-by-text-length.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { calculateTokens } from "./calculate-tokens" -import { Language } from "./types" - -function getTolerantCount(textLength: "4k" | "16k"): number { - const ratio = 0.8 - - if (textLength == "4k") { - return 4000 * ratio - } - - return 16000 -} - -// TODO: This is a temporary solution. Because we don't know the language of the original text, we can't calculate the tokens accurately. Currently, only "Chinese to other languages" is supported. -export function llmModelSwitcherByTextLength( - text: string, - options: { - // If true, include the response in the text length calculation with the specified language - includeResponse?: { lang: Language } - } = {}, -): { - modelSize: "4k" | "16k" | undefined - tokens: number -} { - const { includeResponse } = options - const tokens = calculateTokens(text) - - const langRatioMapping: { [key in Language]: number } = { - en: 1.6, - ja: 1.25, - zh: 1, - "zh-TW": 1, - } - - const finalCount = - tokens / (includeResponse ? langRatioMapping[includeResponse.lang] : 1) - - if (finalCount < getTolerantCount("4k")) { - return { - modelSize: "4k", - tokens, - } - } else if (finalCount < getTolerantCount("16k")) { - return { - modelSize: "16k", - tokens, - } - } - - return { - modelSize: undefined, - tokens, - } -} diff --git a/src/queries/page.server.ts b/src/queries/page.server.ts index c10e3f26..bd7cc10f 100644 --- a/src/queries/page.server.ts +++ b/src/queries/page.server.ts @@ -79,7 +79,7 @@ let model: OpenAI | undefined if (process.env.OPENAI_API_KEY) { model = new OpenAI({ openAIApiKey: process.env.OPENAI_API_KEY, - modelName: "gpt-3.5-turbo", + modelName: "gpt-4o-mini", temperature: 0.3, maxTokens: 400, })