当我们使用AI生成的内容时,怎么去评估它的质量和准确性呢?有时候,AI生成的结果可能答非所问,或者包含错误的信息。

目前的Spring AI(v1.1.0)提供了模型评估Model Evaluation的功能。

Evaluation Testing#

对AI生成内容进行评估的一个方式是使用AI模型本身进行评估。选择一个LLM模型来评估另一个LLM模型的输出。(本地测试时,可以使用同一个模型)

Spring AI对不同的评估场景提供了统一的接口Evaluator,通过实现这个接口,可以定义不同的评估逻辑。

@FunctionalInterface
public interface Evaluator {

	EvaluationResponse evaluate(EvaluationRequest evaluationRequest);

	default String doGetSupportingData(EvaluationRequest evaluationRequest) {
		List<Document> data = evaluationRequest.getDataList();
		return data.stream()
			.map(Document::getText)
			.filter(StringUtils::hasText)
			.collect(Collectors.joining(System.lineSeparator()));
	}

}

评估请求EvaluationRequest包含了用户的输入文本、用于生成内容的数据列表以及AI生成的响应内容。

public class EvaluationRequest {

	private final String userText;

	private final List<Document> dataList;

	private final String responseContent;

  ...
}
  • userText:用户的输入文本。
  • dataList:Contextual data, 对原始的用户输入进行补充,比如从检索增强生成(RAG)中获取的数据。
  • responseContent:AI生成的响应内容。

它提供了对该接口的不同实现

RelevancyEvaluator#

RelevancyEvaluator用于评估AI生成内容的相关性。它通过比较生成内容与预期答案之间的相似度来进行评估。

比如我们询问"法国的首都是哪里?",我们预期的答案是一个地点。如果AI生成的结果是“苹果”,那么这个结果显然是不相关的。

RelevancyEvaluator内部实际上是对一个Prompt进行封装,让一个LLM模型来判定另外一个LLM模型的输出。默认的Prompt模板如下:

public class RelevancyEvaluator implements Evaluator {

	private static final PromptTemplate DEFAULT_PROMPT_TEMPLATE = new PromptTemplate("""
				Your task is to evaluate if the response for the query
				is in line with the context information provided.

				You have two options to answer. Either YES or NO.

				Answer YES, if the response for the query
				is in line with context information otherwise NO.

				Query:
				{query}

				Response:
				{response}

				Context:
				{context}

				Answer:
			""");
...
}

我使用Ollama模型-mistral:7b测试,碰到了结果检测的bug。

spring:
  ai:
    ollama:
      chat:
        # http http://localhost:11434/api/tags -b to see available models
        model: mistral:7b

relevancy-evaluator-bug 评估的结果返回是" YES",但检测是失败的。在github上有类似的issue

因为是LLM模型的输出,相同问题返回的答案可能各不相同。结果中包含"YES"或"NO",但可能会有额外的文本。

relevancy_evaluator_bug_2

FactCheckingEvaluator#

FactCheckingEvaluator用于评估AI生成内容的准确性。它通过验证生成内容中的事实信息来进行评估。

比如我们询问"法国的首都是哪里?",我们预期的答案是“巴黎”。如果AI生成的结果是“马德里”,那么这个结果显然是错误的。

但是v1.1.0版本的实现上有类似的问题

factchecking-evaluator-bug

总结#

目前Evaluator的实现上还有一些问题,期待后续版本的改进。

测试源码#

Spring AI Demo