计海龄 发表于 2025-5-30 20:20:14

Spring AI GA正式版试用感受

只花了一上午就搭建了一套向量搜索和 AI 问答+RAG 知识库 和 tools call的示例。
文档全还有示例,上手速度很快,个人感觉比 LangChain 系列好用。
完整项目在在文章末尾,如果对你有帮助请帮我点个star 。谢谢~

Spring AI 1.0 GA 功能介绍:
https://spring.io/blog/2025/05/20/spring-ai-1-0-GA-released
 
核心代码:
/**
   * 构造方法,注入必要的依赖,并配置 ChatClient
   *
   * @param builder ChatClient 构建器
   * @param chatMemory 聊天上下文记忆体
   * @param vectorStore 向量存储,用于语义检索
   * @param listObjectProvider 工具回调提供者对象列表
   */
    public AiSportSupportAssistant(
            ChatClient.Builder builder,
            ChatMemory chatMemory,
            VectorStore vectorStore,
            ObjectProvider<List<ToolCallbackProvider>> listObjectProvider) {

      this.chatBuilder = builder;
      this.vectorStore = vectorStore;
      this.listObjectProvider = listObjectProvider;

      // 配置知识库检索参数:相似度阈值为0.5,返回Top 3条
      SearchRequest searchRequest = SearchRequest.builder()
                .similarityThreshold(0.5d)
                .topK(3)
                .build();

      // 初始化 ChatClient
      this.chatClient = builder
                // 设置默认系统提示词,定义 AI 助理的身份和行为
                .defaultSystem(
                        "你是一个运动助手,帮助用户解决运动相关问题,上下文和历史信息帮助你更好了解用户需求," +
                        "但记住你不仅可以根据上下文来回答内容,而且你也可以调用工具帮助用户查询,始终遵守用户的指令。")
                // 配置对话顾问,包括记忆顾问、知识库问答顾问和日志顾问
                .defaultAdvisors(
                        MessageChatMemoryAdvisor.builder(chatMemory).build(), // 聊天记忆可以配置存储 mysql \Redis
                        QuestionAnswerAdvisor.builder(vectorStore).searchRequest(searchRequest).build(), // 向量知识库问答
                        new SimpleLoggerAdvisor()) // 简单日志
                // 配置默认工具,如时间工具
                .defaultTools(new DateTimeTools())
                // 配置默认可用工具名称
                .defaultToolNames("getStudentSportScore", "getStudentScoreRank")
                .build(); // 构建 ChatClient 实例
    } 
核心配置配置:
spring:
# api-key (项目测试使用是DeepSeek和阿里embedding https://bailian.console.aliyun.com/?tab=model)
ai:
    openai:
      api-key: sk-
      base-url: https://api.deepseek.com
      chat:
      options:
          model: deepseek-chat
      embedding:
      base-url: https://dashscope.aliyuncs.com/compatible-mode
      api-key: sk-
      options:
          model: text-embedding-v3
          dimensions: 1024
    vectorstore:
      milvus:
      client:
          host: "localhost"
          port: 19530
          username: "root"
          password: "milvus"
      databaseName: "default"
      collectionName: "vector_store"
      embeddingDimension: 1024
      indexType: IVF_FLAT
      metricType: COSINE
      initialize-schema: true
    chat:
      memory:
      repository:
          jdbc:
            initialize-schema: never 
 
项目参考:
https://github.com/git-syl/spring-ai-rag-toolscall-demo/

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: Spring AI GA正式版试用感受