Loading [MathJax]/jax/input/TeX/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >聊聊Spring AI的Evaluator

聊聊Spring AI的Evaluator

作者头像
code4it
发布于 2025-04-15 06:07:48
发布于 2025-04-15 06:07:48
6500
代码可运行
举报
文章被收录于专栏:码匠的流水账码匠的流水账
运行总次数:0
代码可运行

本文主要研究一下Spring AI的Evaluator

Evaluator

spring-ai-client-chat/src/main/java/org/springframework/ai/evaluation/Evaluator.java

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@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()));
	}

}

Evaluator接口定义了evaluate方法,用于对ai生成的内容进行评估,避免AI没有产生幻觉式的响应,它有两个实现,分别是RelevancyEvaluator、FactCheckingEvaluator

EvaluationRequest

org/springframework/ai/evaluation/EvaluationRequest.java

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public class EvaluationRequest {

	private final String userText;

	private final List<Document> dataList;

	private final String responseContent;

	public EvaluationRequest(String userText, String responseContent) {
		this(userText, Collections.emptyList(), responseContent);
	}

	public EvaluationRequest(List<Document> dataList, String responseContent) {
		this("", dataList, responseContent);
	}

	public EvaluationRequest(String userText, List<Document> dataList, String responseContent) {
		this.userText = userText;
		this.dataList = dataList;
		this.responseContent = responseContent;
	}

	//......
}	

EvaluationRequest定义了userText、dataList、responseContent属性,其中userText是用户的输入,dataList是上下文数据,比如RAG追加的内容,responseContent是AI模型的响应

EvaluationResponse

org/springframework/ai/evaluation/EvaluationResponse.java

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public class EvaluationResponse {

	private final boolean pass;

	private final float score;

	private final String feedback;

	private final Map<String, Object> metadata;

	@Deprecated
	public EvaluationResponse(boolean pass, float score, String feedback, Map<String, Object> metadata) {
		this.pass = pass;
		this.score = score;
		this.feedback = feedback;
		this.metadata = metadata;
	}

	public EvaluationResponse(boolean pass, String feedback, Map<String, Object> metadata) {
		this.pass = pass;
		this.score = 0;
		this.feedback = feedback;
		this.metadata = metadata;
	}

	//......
}	

EvaluationResponse定义了pass、score、feedback、metadata属性

RelevancyEvaluator

org/springframework/ai/evaluation/RelevancyEvaluator.java

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public class RelevancyEvaluator implements Evaluator {

	private static final String DEFAULT_EVALUATION_PROMPT_TEXT = """
				Your task is to evaluate if the response for the query
				is in line with the context information provided.\\n
				You have two options to answer. Either YES/ NO.\\n
				Answer - YES, if the response for the query
				is in line with context information otherwise NO.\\n
				Query: \\n {query}\\n
				Response: \\n {response}\\n
				Context: \\n {context}\\n
				Answer: "
			""";

	private final ChatClient.Builder chatClientBuilder;

	public RelevancyEvaluator(ChatClient.Builder chatClientBuilder) {
		this.chatClientBuilder = chatClientBuilder;
	}

	@Override
	public EvaluationResponse evaluate(EvaluationRequest evaluationRequest) {

		var response = evaluationRequest.getResponseContent();
		var context = doGetSupportingData(evaluationRequest);

		String evaluationResponse = this.chatClientBuilder.build()
			.prompt()
			.user(userSpec -> userSpec.text(DEFAULT_EVALUATION_PROMPT_TEXT)
				.param("query", evaluationRequest.getUserText())
				.param("response", response)
				.param("context", context))
			.call()
			.content();

		boolean passing = false;
		float score = 0;
		if (evaluationResponse.toLowerCase().contains("yes")) {
			passing = true;
			score = 1;
		}

		return new EvaluationResponse(passing, score, "", Collections.emptyMap());
	}

}

RelevancyEvaluator让AI去评估响应是否与上下文信息一致,给出yes或者no的结果,如果是yes则passing为true,score为1,否则默认passing为false,score为0

示例

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@Test
void testEvaluation() {

    dataController.delete();
    dataController.load();

    String userText = "What is the purpose of Carina?";

    ChatResponse response = ChatClient.builder(chatModel)
            .build().prompt()
            .advisors(new QuestionAnswerAdvisor(vectorStore))
            .user(userText)
            .call()
            .chatResponse();
    String responseContent = response.getResult().getOutput().getContent();

    var relevancyEvaluator = new RelevancyEvaluator(ChatClient.builder(chatModel));

    EvaluationRequest evaluationRequest = new EvaluationRequest(userText,
            (List<Content>) response.getMetadata().get(QuestionAnswerAdvisor.RETRIEVED_DOCUMENTS), responseContent);

    EvaluationResponse evaluationResponse = relevancyEvaluator.evaluate(evaluationRequest);

    assertTrue(evaluationResponse.isPass(), "Response is not relevant to the question");

}

这里先用userText去问下AI,然后将responseContent、QuestionAnswerAdvisor.RETRIEVED_DOCUMENTS一起丢给relevancyEvaluator,再用AI去评估一下

FactCheckingEvaluator

org/springframework/ai/evaluation/FactCheckingEvaluator.java

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public class FactCheckingEvaluator implements Evaluator {

	private static final String DEFAULT_EVALUATION_PROMPT_TEXT = """
				Evaluate whether or not the following claim is supported by the provided document.
				Respond with "yes" if the claim is supported, or "no" if it is not.
				Document: \\n {document}\\n
				Claim: \\n {claim}
			""";

	private static final String BESPOKE_EVALUATION_PROMPT_TEXT = """
				Document: \\n {document}\\n
				Claim: \\n {claim}
			""";

	private final ChatClient.Builder chatClientBuilder;

	private final String evaluationPrompt;

	/**
	 * Constructs a new FactCheckingEvaluator with the provided ChatClient.Builder. Uses
	 * the default evaluation prompt suitable for general purpose LLMs.
	 * @param chatClientBuilder The builder for the ChatClient used to perform the
	 * evaluation
	 */
	public FactCheckingEvaluator(ChatClient.Builder chatClientBuilder) {
		this(chatClientBuilder, DEFAULT_EVALUATION_PROMPT_TEXT);
	}

	/**
	 * Constructs a new FactCheckingEvaluator with the provided ChatClient.Builder and
	 * evaluation prompt.
	 * @param chatClientBuilder The builder for the ChatClient used to perform the
	 * evaluation
	 * @param evaluationPrompt The prompt text to use for evaluation
	 */
	public FactCheckingEvaluator(ChatClient.Builder chatClientBuilder, String evaluationPrompt) {
		this.chatClientBuilder = chatClientBuilder;
		this.evaluationPrompt = evaluationPrompt;
	}

	/**
	 * Creates a FactCheckingEvaluator configured for use with the Bespoke Minicheck
	 * model.
	 * @param chatClientBuilder The builder for the ChatClient used to perform the
	 * evaluation
	 * @return A FactCheckingEvaluator configured for Bespoke Minicheck
	 */
	public static FactCheckingEvaluator forBespokeMinicheck(ChatClient.Builder chatClientBuilder) {
		return new FactCheckingEvaluator(chatClientBuilder, BESPOKE_EVALUATION_PROMPT_TEXT);
	}

	/**
	 * Evaluates whether the response content in the EvaluationRequest is factually
	 * supported by the context provided in the same request.
	 * @param evaluationRequest The request containing the response to be evaluated and
	 * the supporting context
	 * @return An EvaluationResponse indicating whether the claim is supported by the
	 * document
	 */
	@Override
	public EvaluationResponse evaluate(EvaluationRequest evaluationRequest) {
		var response = evaluationRequest.getResponseContent();
		var context = doGetSupportingData(evaluationRequest);

		String evaluationResponse = this.chatClientBuilder.build()
			.prompt()
			.user(userSpec -> userSpec.text(this.evaluationPrompt).param("document", context).param("claim", response))
			.call()
			.content();

		boolean passing = evaluationResponse.equalsIgnoreCase("yes");
		return new EvaluationResponse(passing, "", Collections.emptyMap());
	}

}

FactCheckingEvaluator旨在评估AI生成的响应在给定上下文中的事实准确性。该评估器通过验证给定的声明(claim)是否逻辑上支持提供的上下文(document),帮助检测和减少AI输出中的幻觉现象;在使用FactCheckingEvaluator时,claim和document会被提交给AI模型进行评估。为了更高效地完成这一任务,可以使用更小且更高效的AI模型,例如Bespoke的Minicheck。Minicheck 是一种专门设计用于事实核查的小型高效模型,它通过分析事实信息片段和生成的输出,验证声明是否与文档相符。如果文档能够证实声明的真实性,模型将回答“是”,否则回答“否”。这种模型特别适用于检索增强型生成(RAG)应用,确保生成的答案基于上下文信息。

示例

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@Test
void testFactChecking() {
  // Set up the Ollama API
  OllamaApi ollamaApi = new OllamaApi("http://localhost:11434");

  ChatModel chatModel = new OllamaChatModel(ollamaApi,
				OllamaOptions.builder().model(BESPOKE_MINICHECK).numPredict(2).temperature(0.0d).build())


  // Create the FactCheckingEvaluator
  var factCheckingEvaluator = new FactCheckingEvaluator(ChatClient.builder(chatModel));

  // Example context and claim
  String context = "The Earth is the third planet from the Sun and the only astronomical object known to harbor life.";
  String claim = "The Earth is the fourth planet from the Sun.";

  // Create an EvaluationRequest
  EvaluationRequest evaluationRequest = new EvaluationRequest(context, Collections.emptyList(), claim);

  // Perform the evaluation
  EvaluationResponse evaluationResponse = factCheckingEvaluator.evaluate(evaluationRequest);

  assertFalse(evaluationResponse.isPass(), "The claim should not be supported by the context");

}

这里使用ollama调用bespoke-minicheck模型,其temperature设置为0.0,之后把context与claim都传递给factCheckingEvaluator去评估

小结

Spring AI提供了Evaluator接口定义了evaluate方法,用于对ai生成的内容进行评估,避免AI没有产生幻觉式的响应,它有两个实现,分别是RelevancyEvaluator、FactCheckingEvaluator。RelevancyEvaluator用于评估相关性,FactCheckingEvaluator用于评估事实准确性。

doc

  • testing
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2025-04-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 码匠的流水账 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
聊聊Spring AI的Evaluator
spring-ai-client-chat/src/main/java/org/springframework/ai/evaluation/Evaluator.java
code4it
2025/04/14
890
聊聊Spring AI的Evaluator
Spring AI、DeepSeek 与 MCP:对话驱动的接口查询新范式
随着人工智能技术的飞速发展,我们正步入一个全新的应用开发时代。传统的接口调用方式,即通过硬编码或配置文件进行静态调用,正逐渐被更为智能、动态的方式所取代。本文将不是探讨 Spring AI、DeepSeek 以及 MCP(Model Context Protocol)这三项前沿技术,而是结合一个实际的案例工程,展示如何利用对话驱动的方式实现接口查询。 Spring AI 作为一个新兴的框架,旨在简化 AI 应用的开发流程,提供了一套统一的抽象层,使得开发者能够轻松集成各种大语言模型。DeepSeek 作为国内领先的大语言模型,在自然语言处理方面表现出色,为我们提供了强大的语义理解和生成能力。而 MCP,作为一种模型上下文协议,则为大语言模型与外部工具和数据源之间的交互提供了标准化的方式。 本文将通过一个实际的案例,演示如何将这三项技术结合起来,构建一个能够通过自然语言对话查询接口数据的应用。我们将从环境搭建、代码实现到效果展示,一步步地剖析其原理和实现细节,帮助读者深入理解并掌握这项技术。
磊叔的技术博客
2025/06/09
720
Spring AI、DeepSeek 与 MCP:对话驱动的接口查询新范式
Spring AI 1.0 正式发布!核心内容和智能体详解
在经历了八个里程碑式的版本之后(M1~M8),Spring AI 1.0 正式版本,终于在 2025 年 5 月 20 日正式发布了,这是另一个新高度的里程碑式的版本,标志着 Spring 生态系统正式全面拥抱人工智能技术,并且意味着 Spring AI 将会给企业带来稳定 API 支持。
磊哥
2025/05/22
1.6K0
Spring AI 1.0 正式发布!核心内容和智能体详解
炸裂!Spring AI 1.0 正式发布,让 Java 再次伟大!
炸裂,炸裂,炸裂!从第一次提交代码到现在,经过 2 年的沉淀,Spring AI 框架的第一个正式版本 1.0 终于发布了。
程序员鱼皮
2025/05/23
4710
炸裂!Spring AI 1.0 正式发布,让 Java 再次伟大!
聊聊Spring AI的RAG
Spring AI受Modular RAG: Transforming RAG Systems into LEGO-like Reconfigurable Frameworks启发实现了Modular RAG,主要分为如下几个阶段:Pre-Retrieval、Retrieval、Post-Retrieval、Generation
code4it
2025/04/08
2751
聊聊Spring AI的RAG
Spring AI + DeepSeek:轻松打造你的第一个 AI 应用
在当今数字化时代,人工智能(AI)已成为推动技术进步和创新的核心力量。从智能语音助手到图像识别系统,从个性化推荐引擎到自动化流程,AI 的应用无处不在,正深刻地改变着我们的生活和工作方式。
用户1220090
2025/02/27
6160
Spring AI + DeepSeek:轻松打造你的第一个 AI 应用
使用Spring AI调用AI模型
Spring AI是Spring框架对人工智能和机器学习的支持模块,它提供了一套简单易用的API来集成各种AI服务和模型。
阿珍
2025/03/27
3760
使用Spring AI调用AI模型
spring-ai-starter-mcp-client小试牛刀
org/springframework/ai/mcp/client/autoconfigure/McpClientAutoConfiguration.java
code4it
2025/03/31
3930
spring-ai-starter-mcp-client小试牛刀
Spring AI调用Ollama+DeepSeek
ChatClient 是一个接口,它定义了一个与聊天服务交互的客户端。这个接口主要用于创建聊天客户端对象,设置请求规范,以及发起聊天请求。
鱼找水需要时间
2025/06/02
1240
Spring AI调用Ollama+DeepSeek
Java智能之Spring AI:5分钟打造智能聊天模型的利器
尽管Python最近成为了编程语言的首选,但是Java在人工智能领域的地位同样不可撼动,得益于强大的Spring框架。随着人工智能技术的快速发展,我们正处于一个创新不断涌现的时代。从智能语音助手到复杂的自然语言处理系统,人工智能已经成为了现代生活和工作中不可或缺的一部分。在这样的背景下,Spring AI 项目迎来了发展的机遇。尽管该项目汲取了Python项目如LangChain和LlamaIndex的灵感,但Spring AI并不是简单的移植。该项目的初衷在于推进生成式人工智能应用程序的发展,使其不再局限于Python开发者。
努力的小雨
2024/07/04
6.6K1
深入Spring AI:6大核心概念带你入门AI开发
前面我们快速了解了Spring AI的基础使用,以及他的分层体系。今天我们来了解一下他的几个核心概念,能够帮我们快速了解Spring AI的实现机制。
有一只柴犬
2025/03/31
4880
深入Spring AI:6大核心概念带你入门AI开发
聊聊Spring AI的Multimodality
org/springframework/ai/chat/messages/UserMessage.java
code4it
2025/04/12
640
spring-ai-starter-mcp-client小试牛刀
org/springframework/ai/mcp/client/autoconfigure/McpClientAutoConfiguration.java
code4it
2025/03/29
3230
spring-ai-starter-mcp-client小试牛刀
基于Spring Ai + Ollama + Qwen2.5/Deepseek+Milvus实现RAG
https://milvus.io/docs/zh/install_standalone-docker.md
用户11572955
2025/03/21
5630
聊天客户端(Chat Client) API
ChatClient,它提供了一个流畅的 API,用于与 AI 模型进行通信。 它支持同步编程模型和响应式编程模型。
jack.yang
2025/04/05
1460
ChatClient:探索与AI模型通信的Fluent API
开始之前推荐一篇实用的文章:《H5 App实战四:H5 App的跨域请求与数据交互》,作者:【china马斯克】。
小马哥学JAVA
2024/11/24
2990
聊聊Spring AI的RetrievalAugmentationAdvisor
本文主要研究一下Spring AI的RetrievalAugmentationAdvisor
code4it
2025/03/31
1540
聊聊Spring AI的RetrievalAugmentationAdvisor
有了 Spring AI ,Java 开发AI应用也就简单多了
Spring 官方自从发布了 Spring AI,AI 界的门槛儿算是被彻底踹飞了!为什么?因为这就意味着整天只会 CRUD 的 Javaer 们也能开发AI应用了,而且简单到让你怀疑人生。那么本文就基于 Spring AI Alibaba 开发一个简单的 AI 对话应用。
王二蛋
2024/11/07
1.5K0
Spring AI & Trae ,助力开发微信小程序
前面介绍了Spring boot快速集成Spring AI实现简单的Chat聊天模式。今天立马来实战一番,通过Trae这个火爆全网的工具,来写一个微信小程序。照理说,我们只是极少量的编码应该就可以完成这项工作。开撸~
有一只柴犬
2025/03/24
4350
Spring AI & Trae ,助力开发微信小程序
聊聊Spring AI的Tool Calling
org/springframework/ai/tool/ToolCallback.java
code4it
2025/04/11
5470
聊聊Spring AI的Tool Calling
相关推荐
聊聊Spring AI的Evaluator
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验