You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何避免Spring AI结合Vector Store时提及上下文的无关响应?

解决方案:消除Spring AI结合Vector Store时的上下文提及回复

一、通过OpenAI Prompt工程直接规避

优化系统提示词,明确要求模型禁止提及上下文检索过程或相关术语,仅基于自身知识储备回答问题,无相关信息时直接告知无法解答。

示例系统提示词配置:

你是专注于Z-Wave网络技术的助手,仅依托自身知识回答用户问题。若无法解答,直接回复"我暂时无法提供相关信息",绝对不能提及上下文检索、向量库、蓝图或内部消息等内容。

在Spring AI中通过配置类注入自定义系统提示:

@Bean
public OpenAiChatClient openAiChatClient(OpenAiApi openAiApi) {
    return OpenAiChatClient.builder(openAiApi)
            .defaultSystemPrompt("你是专注于Z-Wave网络技术的助手...(上述完整提示词)")
            .build();
}

二、使用StringTemplate处理Prompt与回复

1. 预处理:重构检索后的Prompt模板

借助Spring AI的VectorStoreRetrievalAugmentor自定义Prompt模板,仅将检索到的内容作为背景信息注入,完全隐藏检索相关逻辑,避免模型感知上下文来源。

示例自定义Prompt模板:

基于以下信息回答用户问题:
<context>

用户问题:<question>

替换默认模板的配置代码:

@Bean
public VectorStoreRetrievalAugmentor augmentor(VectorStore vectorStore) {
    String promptTemplate = "基于以下信息回答用户问题:\n<context>\n\n用户问题:<question>";
    return VectorStoreRetrievalAugmentor.builder(vectorStore)
            .promptTemplate(promptTemplate)
            .build();
}

2. 后处理:过滤违规回复内容

若模型仍偶尔出现违规回复,可结合StringTemplate的字符串处理能力,在返回结果前自动替换或删除包含违规关键词的内容。

示例后处理代码:

public String cleanAiResponse(String rawResponse) {
    String[] forbiddenKeywords = {"上下文", "蓝图", "内部消息", "向量库"};
    String cleaned = rawResponse;
    for (String keyword : forbiddenKeywords) {
        cleaned = cleaned.replaceAll(keyword, "");
    }
    // 替换整句违规表述
    cleaned = cleaned.replaceAll("遗憾的是,.*内部消息。", "我暂时无法提供相关信息");
    return cleaned;
}

三、Spring AI配置层面的进阶调整

通过ChatClient的filter方法添加自定义拦截器,在请求发送前修改Prompt,或在响应返回后处理结果:

@Bean
public ChatClient chatClient(OpenAiChatClient openAiChatClient) {
    return openAiChatClient
            .filter(request -> {
                // 修改请求Prompt,移除可能触发上下文提及的表述
                String modifiedPrompt = request.prompt().replace("根据上下文", "根据提供的信息");
                return request.withPrompt(modifiedPrompt);
            })
            .filter(response -> {
                // 清理响应中的违规内容
                String cleanedContent = cleanAiResponse(response.content());
                return response.withContent(cleanedContent);
            });
}

内容的提问来源于stack exchange,提问作者Jackie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 08:40:02