Agent

RAG

RAG 概念

什么是 RAG

RAG 是一种结合信息检索技术和 AI 内容生成的混合结构,可以解决大模型的知识时效性限制和幻读问题

简单来说就是让模型开卷考,让 AI 回答问题之前先查一下特定的知识库来获取信息,确保回答是基于资料而不是凭空捏造

RAG 和传统 AI 模型的区别

特性传统大语言模型RAG 增强模型
知识时效性受训练数据截止日期限制可接入最新知识库
领域专业性泛化知识⁠,专业深度有限可接入专业领域知识
响应准‌确性可能产生 “幻觉”基于检索的事​实依据
可控性依赖原始训练可通过知‎识库定制输出
资源消耗较高(需要大模型参‌数)模型可更小,结合外部知识

RAG 的工作流程

  • 文档收集和切割
  • 向量转换和存储
  • 文档过滤和检索
  • 检查增强和关联

文档收集和切割

文档收集:从各种来源(网页、PDF、数据库等)收集原始文档

Token

基础提示技巧

  • 明确指定任务和角色
    • 为 AI 提供清晰的任务描述和角色定位,帮助模型理解背景和期望
系统:你是一位经验丰富的 Java 教师,擅长向初学者解释编程概念。
用户:请解释 Java 中的列表推导式,包括基本语法和 2-3 个实用示例。
  • 提供详细说明和具体实例
    • 提供足够的上下文信息和期望的输出,减少模型的不确定性
请提供一个[计划],针对[项目],计划包括
1. ***
2. ***

示例格式:



  • 使用结构化格式引导思维
    • 通过列表、表格等格式,使指令更容易理解,输出更有条理
分析下面项目的优缺点
项目:****

请使用表格格式回答,包含下列:

  • 优势(最少三项)
  • 对每项优势的具体分析
  • 劣势(最少三项)
  • 对每项劣势的具体分析
  • 对应建议
  • 明确输出格式要求
    • 指定格式,长度,样式,使得输出更符合期望
  • 撰写一篇关于 Java 的学习路线推荐,要求:
    - 使用通俗易懂的语言,适合非专业阅读
    - 包含5个小标题,每个标题下2-3段文字
    - 总字数控制在800字左右
    - 结尾提供3个可行的个人行动建议
    

    进阶提示技巧

    • 思维链提示法(‌Chain-of-​Thought)
      • 引导模型展示推导过程,逐步思考问题,提高复杂问题的准确性
    问题:一个商店售卖T恤,每件15元。如果购买5件以上可以享受8折优惠。小明买了7件T恤,他需要支付多少钱?
    

    请一步步思考解决这个问题:

    1. 首先计算7件T恤的原价
    2. 确定是否符合折扣条件
    3. 如果符合,计算折扣后的价格
    4. 得出最终支付金额
    • 少样本学习(F‌ew-Shot L​earning)
      • 提供几个样本,帮助模型理解任务模式和期望输出
    我将给你几个代码,请你按照相同的方式解析错误所在
    

    输入:“system.out.print("hello world");” 输出:“错误所在:system,应该修改为 System,因为是调用 System 库”

    • 分步骤指导(Step-by-Step)
      • 将复杂问题分解为可管理的步骤,确保模型完成的每个环节正确
    请帮我创建一个简单的网站落地页设计方案,按照以下步骤:
    

    步骤1: 分析目标受众(考虑年龄、职业、需求等因素) 步骤2: 确定页面核心信息(主标题、副标题、价值主张) 步骤3: 设计页面结构(至少包含哪些区块) 步骤4: 制定视觉引导策略(颜色、图像建议) 步骤5: 设计行动召唤(CTA)按钮和文案

    • 自我评估和修正
      • 让模型评估自己的输出并进行改进,提高准确性和质量
    解决以下概率问题:
    从一副标准扑克牌中随机抽取两张牌,求抽到至少一张红桃的概率。
    

    首先给出你的解答,然后:

    1. 检查你的推理过程是否存在逻辑错误
    2. 验证你使用的概率公式是否正确
    3. 检查计算步骤是否有误
    4. 如果发现任何问题,提供修正后的解答
    • 知识检索和引用
      • 引导模型检索相关信息并明确引用信息来源,提高可靠性
    请讲解 SpringBoot 在执行的时候的启动流程。在回答中:
    1. 提供 SpringBoot 的官方解释
    2. 给出分别是哪几个组件
    3. 描述执行的先后顺序
    

    对于任何可能需要具体数据或研究支持的陈述,请明确指出这些信息的来源,并说明这些信息的可靠性。

    • 多视角分析
      • 引导模型从不同角度、立场或专业视角分析问题,提供全面见解
    分析"城市应该禁止私家车进入市中心"这一提议:
    

    请从以下4个不同角度分析:

    1. 环保专家视角
    2. 经济学家视角
    3. 市中心商户视角
    4. 通勤居民视角

    对每个视角:

    • 提供支持该提议的2个论点
    • 提供反对该提议的2个论点
    • 分析可能的折中方案
    • 多模态思维
      • 结合不同表⁠达形式进行思考,如‌文字描述、图表结构​、代码逻辑等
    • 设计一个智能家居系统的基础架构:
      
      1. 首先用文字描述系统的主要功能和组件
      2. 然后创建一个系统架构图(用ASCII或文本形式表示)
      3. 接着提供用户交互流程
      4. 最后简述实现这个系统可能面临的技术挑战

      尝试从不同角度思考:功能性、用户体验、技术实现、安全性等。

      超级智能体

      后端项目初始化

      环境准备

      安装的 JDK 版本必须是 21 以上,最好是 21 ,因为支持使用虚拟线程

      **不能使用其他版本

      新建项目

      在 IDEA 中新建项目,选择 Spring Boot 模板,注意需要确保 Server URL 为  https://start.spring.io/

      ![[Pasted image 20251106194511.png]]

      复习智能体搭建

      程序调用 AI 大模型

      SDK 接入

      首先需要按照官方文档安装 SDK: 安装SDK官方指南

      在选择 SDK 版本时,建议在 Maven 仓库查看最新的版本号: Maven 中央仓库版本信息

      • 在 pom.xml 中引入依赖:
      <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>dashscope-sdk-java</artifactId>
          <version>2.19.1</version>
      </dependency>
      
      • 创建一个接口类​来存储密钥信息(在‎实际生产环境中,应‌使用配置文件或环境变量)
      public interface TestApiKey {
          String API_KEY = "你的 API Key";
      }
      
      package com.example.superaiagent.demo.invoke;// 建议dashscope SDK的版本 >= 2.12.0import java.util.Arrays;  
      import java.lang.System;  
      import com.alibaba.dashscope.aigc.generation.Generation;  
      import com.alibaba.dashscope.aigc.generation.GenerationParam;  
      import com.alibaba.dashscope.aigc.generation.GenerationResult;  
      import com.alibaba.dashscope.common.Message;  
      import com.alibaba.dashscope.common.Role;  
      import com.alibaba.dashscope.exception.ApiException;  
      import com.alibaba.dashscope.exception.InputRequiredException;  
      import com.alibaba.dashscope.exception.NoApiKeyException;  
      import com.alibaba.dashscope.utils.JsonUtils;  
        
      /*  
      * 阿里云灵积 AI SDK 调用  
      * */  
      public class SdkAiInvoke {  
          public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {  
              Generation gen = new Generation();  
              Message systemMsg = Message.builder()  
                      .role(Role.SYSTEM.getValue())  
                      .content("You are a helpful assistant.")  
                      .build();  
              Message userMsg = Message.builder()  
                      .role(Role.USER.getValue())  
                      .content("你是谁?")  
                      .build();  
              GenerationParam param = GenerationParam.builder()  
                      // 若没有配置环境变量,请用百炼API Key将下行替换为:.apiKey("sk-xxx")  
                      .apiKey(TestApiKey.API_KEY)  
                      // 此处以qwen-plus为例,可按需更换模型名称。模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models  
                      .model("qwen-plus")  
                      .messages(Arrays.asList(systemMsg, userMsg))  
                      .resultFormat(GenerationParam.ResultFormat.MESSAGE)  
                      .build();  
              return gen.call(param);  
          }  
          public static void main(String[] args) {  
              try {  
                  GenerationResult result = callWithMessage();  
                  System.out.println(JsonUtils.toJson(result));  
              } catch (ApiException | NoApiKeyException | InputRequiredException e) {  
                  // 使用日志框架记录异常信息  
                  System.err.println("An error occurred while calling the generation service: " + e.getMessage());  
              }  
              System.exit(0);  
          }  
      }
      

      HTTP 接入

      1. 对于 SD⁠K 不支持的编程语言‌或需要更灵活控制的场​景,可以直接使用 H‎TTP 请求调用 A‌I 大模型的 API
      2. 一⁠般来说,如果有官方 SDK 支持,优‌先使用 SDK;只有在不支持 SDK​ 的情况下,再考虑直接 HTTP 调用‎
      3. HTTP 调用的详细说明可参考官方文档: 通过 API 调用通义千问
      package com.example.superaiagent.demo.invoke;  
        
      import cn.hutool.http.HttpRequest;  
      import cn.hutool.http.HttpResponse;  
      import cn.hutool.json.JSONArray;  
      import cn.hutool.json.JSONObject;  
        
      /*  
       * 阿里云灵积 AI Http 调用  
       * */public class HttpAiInvoke {  
        
          public static void main(String[] args) {  
              // 替换为您的API密钥  
              String apiKey = TestApiKey.API_KEY;  
        
              // 构建请求URL  
              String url = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";  
        
              // 构建请求体  
              JSONObject requestBody = new JSONObject();  
              requestBody.put("model", "qwen-plus");  
                
              // 构建messages数组  
              JSONArray messages = new JSONArray();  
                
              // system消息  
              JSONObject systemMessage = new JSONObject();  
              systemMessage.put("role", "system");  
              systemMessage.put("content", "You are a helpful assistant.");  
              messages.add(systemMessage);  
                
              // user消息  
              JSONObject userMessage = new JSONObject();  
              userMessage.put("role", "user");  
              userMessage.put("content", "你是谁?");  
              messages.add(userMessage);  
                
              requestBody.put("messages", messages);  
        
              try {  
                  // 发送POST请求  
                  HttpResponse response = HttpRequest.post(url)  
                          .header("Authorization", "Bearer " + apiKey)  
                          .header("Content-Type", "application/json")  
                          .body(requestBody.toString())  
                          .execute();  
        
                  // 打印响应结果  
                  System.out.println("响应状态码: " + response.getStatus());  
                  System.out.println("响应内容: " + response.body());  
        
              } catch (Exception e) {  
                  e.printStackTrace();  
              }  
          }  
      }
      

      Spring A‌I

      • Spring AI 默认没有支持所有的大模型(尤其是国产的),更多的是支持兼容 OpenAI API 的大模型的集成

      快速上手SpringAI 2.0

      前面那篇1.0没用,一点用没有,还得是CSDN大佬啊

      快速使用

      创建项目

      • 选择创建 Spring Initializr 项目,JDK最低要求17,不可低于17

      • 依赖选择

        • SpringBoot版本需要高于3.X
      • 需要的依赖项:

        • Lombok
        • Spring Web
        • MySQL Driver
        • openAI

      最终的xml文件应为:

      <?xml version="1.0" encoding="UTF-8"?>
      <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
          <modelVersion>4.0.0</modelVersion>
          <groupId>com.example</groupId>
          <artifactId>SpringAI_Study</artifactId>
          <version>0.0.1-SNAPSHOT</version>
          <name>SpringAI_Study</name>
          <description>SpringAI_Study</description>
      
          <properties>
              <java.version>17</java.version>
              <spring-boot.version>3.5.3</spring-boot.version>
              <spring-ai.version>1.0.0</spring-ai.version>
          </properties>
      
          <!-- 添加仓库配置 -->
          <repositories>
              <repository>
                  <id>maven-central</id>
                  <url>https://repo1.maven.org/maven2</url>
              </repository>
              <repository>
                  <id>spring-milestones</id>
                  <url>https://repo.spring.io/milestone</url>
              </repository>
          </repositories>
      
          <dependencies>
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-web</artifactId>
              </dependency>
              <dependency>
                  <groupId>org.springframework.ai</groupId>
                  <artifactId>spring-ai-starter-model-openai</artifactId>
              </dependency>
              <dependency>
                  <groupId>com.mysql</groupId>
                  <artifactId>mysql-connector-j</artifactId>
                  <scope>runtime</scope>
              </dependency>
              <dependency>
                  <groupId>org.projectlombok</groupId>
                  <artifactId>lombok</artifactId>
                  <optional>true</optional>
              </dependency>
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-test</artifactId>
                  <scope>test</scope>
              </dependency>
          </dependencies>
      
          <!-- 关键:手动导入 BOM 管理版本 -->
          <dependencyManagement>
              <dependencies>
                  <!-- Spring Boot BOM -->
                  <dependency>
                      <groupId>org.springframework.boot</groupId>
                      <artifactId>spring-boot-dependencies</artifactId>
                      <version>${spring-boot.version}</version>
                      <type>pom</type>
                      <scope>import</scope>
                  </dependency>
                  <!-- Spring AI BOM -->
                  <dependency>
                      <groupId>org.springframework.ai</groupId>
                      <artifactId>spring-ai-bom</artifactId>
                      <version>${spring-ai.version}</version>
                      <type>pom</type>
                      <scope>import</scope>
                  </dependency>
              </dependencies>
          </dependencyManagement>
      
          <build>
              <plugins>
                  <plugin>
                      <groupId>org.springframework.boot</groupId>
                      <artifactId>spring-boot-maven-plugin</artifactId>
                      <version>${spring-boot.version}</version>
                      <configuration>
                          <excludes>
                              <exclude>
                                  <groupId>org.projectlombok</groupId>
                                  <artifactId>lombok</artifactId>
                              </exclude>
                          </excludes>
                      </configuration>
                  </plugin>
              </plugins>
          </build>
      </project>
      

      配置文件

      application.yaml

      快速上手SpringAI

      快速入门

      导入依赖

      <?xml version="1.0" encoding="UTF-8"?>
      <project xmlns="http://maven.apache.org/POM/4.0.0"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
          <modelVersion>4.0.0</modelVersion>
      
          <artifactId>springAi_deepseek</artifactId>
      
          <properties>
              <maven.compiler.source>17</maven.compiler.source>
              <maven.compiler.target>17</maven.compiler.target>
              <!-- 明确指定Spring Boot和Spring AI版本 -->
              <spring-boot.version>3.2.0</spring-boot.version>
              <spring-ai.version>1.0.0-M5</spring-ai.version>
          </properties>
      
          <!-- 仓库配置:确保依赖可下载 -->
          <repositories>
              <repository>
                  <id>maven-central</id>
                  <url>https://repo1.maven.org/maven2</url>
              </repository>
              <repository>
                  <id>spring-milestones</id>
                  <url>https://repo.spring.io/milestone</url>
              </repository>
          </repositories>
      
          <dependencies>
              <!-- Spring Boot Web Starter(版本由下方BOM管理) -->
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-web</artifactId>
              </dependency>
      
              <!-- 复用OpenAI Starter兼容DeepSeek(版本由Spring AI BOM管理) -->
              <dependency>
                  <groupId>org.springframework.ai</groupId>
                  <artifactId>spring-ai-openai-spring-boot-starter</artifactId>
              </dependency>
      
              <!-- Spring Boot Test Starter(版本由下方BOM管理) -->
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-test</artifactId>
                  <scope>test</scope>
              </dependency>
          </dependencies>
      
          <!-- 关键:手动导入Spring Boot和Spring AI的BOM管理版本 -->
          <dependencyManagement>
              <dependencies>
                  <!-- Spring Boot的BOM,管理所有starter的版本 -->
                  <dependency>
                      <groupId>org.springframework.boot</groupId>
                      <artifactId>spring-boot-dependencies</artifactId>
                      <version>${spring-boot.version}</version>
                      <type>pom</type>
                      <scope>import</scope>
                  </dependency>
      
                  <!-- Spring AI的BOM,管理AI相关依赖版本 -->
                  <dependency>
                      <groupId>org.springframework.ai</groupId>
                      <artifactId>spring-ai-bom</artifactId>
                      <version>${spring-ai.version}</version>
                      <type>pom</type>
                      <scope>import</scope>
                  </dependency>
              </dependencies>
          </dependencyManagement>
      
      </project>
      

      配置文件

      server.port=8899  
      spring.application.name=spring-ai-deepseek-demo  
        
      spring.ai.openai.api-key=sk-43745c46cd5a4d80821e998030******  
      spring.ai.openai.base-url=https://api.deepseek.com  
      spring.ai.openai.chat.options.model=deepseek-chat  
      spring.ai.openai.chat.options.temperature=0.7
      
        • temperature参数用于控制生成文本的多样性。具体来说:

      快速上手LangChain4j

      LangChain4j入门

      创建一个Maven项目

      创建空项目并且导入依赖

      <properties>  
          <maven.compiler.source>17</maven.compiler.source>  
          <maven.compiler.target>17</maven.compiler.target>  
          <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
          <spring-boot.version>3.2.6</spring-boot.version>  
          <knife4j.version>4.3.0</knife4j.version>  
          <mybatis-plus.version>3.5.11</mybatis-plus.version>  
          <langchain4j.version>1.0.0-beta3</langchain4j.version>  
      </properties>
      
      <dependencies>
      	<!-- web应用程序核心依赖 -->
      	<dependency>
      		<groupId>org.springframework.boot</groupId>
      		<artifactId>spring-boot-starter-web</artifactId>
      	</dependency>
      	<!-- 编写和运行测试用例 -->
      	<dependency>
      		<groupId>org.springframework.boot</groupId>
      		<artifactId>spring-boot-starter-test</artifactId>
      		<scope>test</scope>
      	</dependency>
      	<!-- 前后端分离中的后端接口测试工具 -->
      	<dependency>
      		<groupId>com.github.xiaoymin</groupId>
      		<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
      		<version>${knife4j.version}</version>
      	</dependency>
      </dependencies>
      
      <dependencyManagement>
      	<dependencies>
      		<!--引入SpringBoot依赖管理清单-->
      		<dependency>
      			<groupId>org.springframework.boot</groupId>
      			<artifactId>spring-boot-dependencies</artifactId>
      			<version>${spring-boot.version}</version>
      			<type>pom</type>
      			<scope>import</scope>
      		</dependency>
      	</dependencies>
      </dependencyManagement>
      

      配置文件

      先随便写点,写个端口让他跑起来先