本页目录
LLM 的另一个经典使用场景是分类。
假设要把一条用户评论交给 LLM,并分类为 positive, negative或 neutral.
我们希望 LLM 只返回一个字符串,这个字符串只能是 positive, negative或 neutral.
用传统软件术语来说,这称为枚举,也就是一组预先列出的值。
可以使用 AI SDK 生成这个枚举。
滚动式代码讲解
1
我们再次使用 generateObject 函数,但这次传入的 output 类型是 enum.
2
还要传入一个 enum 属性,其中包含允许返回的字符串数组。
3
从 generateObject 得到的结果带有一个 object 属性,该对象就是枚举结果。
import { generateObject } from "ai";export const classifySentiment = async (text: string,) => {await generateObject({model,output: "enum",prompt: text,system:`Classify the sentiment of the text as either ` +`positive, negative, or neutral.`,});};
用几条不同的陈述测试一下:
滚动式代码讲解
1
I'm not sure how I feel 得到的分类是 neutral.
2
This is terrible 得到的分类是 negative.
3
而 I love this so much 得到的分类是 positive.
const result = await classifySentiment(`I'm not sure how I feel`,);console.log(result); // neutral
就这样,我们得到了一个情感分析系统。枚举很适合这个场景,而 AI SDK 把实现过程变得非常简单。
登录以保存进度。