76 lines
2.1 KiB
TypeScript
76 lines
2.1 KiB
TypeScript
import { ChatOpenAI } from "@langchain/openai"
|
|
import { z } from "zod"
|
|
|
|
import db from "../db"
|
|
|
|
/**
|
|
* 获取Deepseek模型
|
|
* @param temperature 温度
|
|
*/
|
|
const getDeepseekModel = async (temperature = 0) => {
|
|
const model = "deepseek-chat"
|
|
const apiKey = await db.appConfig.getDeepseekApiKey()
|
|
const baseURL = "https://api.deepseek.com"
|
|
return new ChatOpenAI({ apiKey, temperature, model }, { baseURL })
|
|
}
|
|
|
|
const timeConfig = z.object({
|
|
startTime: z.string().describe("开始时间,格式为 YYYY-MM-DD HH:mm:ss"),
|
|
endTime: z.string().describe("结束时间,格式为 YYYY-MM-DD HH:mm:ss"),
|
|
})
|
|
|
|
/**
|
|
* 解析时间
|
|
* @param userInput 用户输入
|
|
* @returns
|
|
*/
|
|
const parseTime = async (userInput: string) => {
|
|
const model = await getDeepseekModel()
|
|
const structuredLlm = model.withStructuredOutput(timeConfig, { name: "time" })
|
|
return await structuredLlm.invoke(
|
|
`
|
|
当前时间为 ${new Date().toLocaleString("zh-CN", { timeZone: "Asia/Shanghai" })}
|
|
你是一个专业的语义解析工程师,给定以下用户输入,帮我解析出开始时间和结束时间
|
|
如果不包含时间信息,请返回当天的起始时间到当前时间
|
|
用户输入:
|
|
\`\`\`
|
|
${userInput.replaceAll("`", " ")}
|
|
\`\`\`
|
|
`
|
|
)
|
|
}
|
|
|
|
/**
|
|
* 根据聊天历史回答用户的问题
|
|
* @param userInput 用户输入
|
|
* @param chatHistory 聊天历史
|
|
* @returns
|
|
*/
|
|
const queryWithChatHistory = async (userInput: string, chatHistory: string) => {
|
|
const model = await getDeepseekModel(0.5)
|
|
return await model.invoke(
|
|
`
|
|
当前时间为 ${new Date().toLocaleString("zh-CN", { timeZone: "Asia/Shanghai" })}
|
|
你是一个专业的聊天记录分析工程师,给定以下用户输入和聊天历史,帮我回答用户的问题
|
|
如果无法回答或者用户的问题不清晰,请引导用户问出更具体的问题
|
|
|
|
用户输入:
|
|
\`\`\`
|
|
${userInput.replaceAll("`", " ")}
|
|
\`\`\`
|
|
聊天历史:
|
|
\`\`\`
|
|
${chatHistory.replaceAll("`", " ")}
|
|
\`\`\`
|
|
`
|
|
)
|
|
}
|
|
|
|
const llm = {
|
|
getDeepseekModel,
|
|
parseTime,
|
|
queryWithChatHistory,
|
|
}
|
|
|
|
export default llm
|