egg_server/test/llm/intentRecognition.ts

89 lines
1.7 KiB
TypeScript

import { parseJsonString } from "@egg/hooks"
import { z } from "zod"
import { zodToJsonSchema } from "zod-to-json-schema"
import initAppConfig from "../../constant/config"
import llm from "../../utils/llm"
import { cleanLLMRes } from "../../utils/llm/base"
await initAppConfig()
/**
* 基础意图模式
*/
const BaseIntentSchema = z.object({
intent: z.number().min(1).max(13),
})
/**
* 简报模式
*/
const BriefingSchema = BaseIntentSchema.extend({
intent: z.literal(5),
link: z.string().url(),
userDescription: z.string().min(1),
})
/**
* 简报存储链接模式
*/
const BriefingLinkSchema = z.object({
intent: z.literal(14),
link: z.string().url(),
})
/**
* 通用响应模式
*/
const CommonResponseSchema = BaseIntentSchema.extend({
intent: z.literal(2),
message: z.string().min(1),
})
/**
* 联网检索模式
*/
const NetSearchSchema = BaseIntentSchema.extend({
intent: z.literal(15),
query: z.string().min(1),
})
/**
* 意图模式
*/
const IntentSchema = z.union([
BriefingSchema,
CommonResponseSchema,
BaseIntentSchema,
BriefingLinkSchema,
NetSearchSchema,
])
const jsonSchema = zodToJsonSchema(IntentSchema)
const res = await llm.invoke(
"intentRecognition",
{
userInput: "今天是哪天",
time: new Date().toLocaleString("zh-CN", { timeZone: "Asia/Shanghai" }),
jsonSchema,
},
"test",
0,
true
)
const rawIntent = cleanLLMRes(res as string)
const parsedIntent = parseJsonString(rawIntent, null)
console.log("🚀 ~ parsedIntent:", parsedIntent)
try {
IntentSchema.parse(parsedIntent)
console.log("Intent is valid:", parsedIntent)
} catch (e: any) {
console.error("Invalid intent:", e.errors)
}
console.log(cleanLLMRes(res as string))