大模型LLM之SpringAI:Web+AI(一)

第六章 Spring AI 中文版 如下面的代码片段所示,然后可以为您希望使用的一个或多个spring-ai模块(例如spring-ai-openai)的Starter Dependencies进行无版本声明。和熟悉 JavaScript 生态系统的人的“create-react-app”命令一样,Spring CLI 提供了一个用于创建基于 Spring 的项目spring boot new的命令。Spring AI 清单 (BOM) 声明给定版本的 Spring AI 使用的所有依赖项的推荐版本。 阅读详情
AI摘要

Spring AI是简化人工智能应用开发的项目,支持多模型供应商和类型,提供统一API。介绍了模型、提示词、嵌入等概念,以及AI整合私有数据的方法。还说明了使用Spring AI的条件和API,如聊天客户端API,包括返回响应、流式响应等功能。

官网:https://docs.spring.io/spring-ai/reference/index.html

版本:1.0.0-M1

Spring AI是一个旨在简化开发人员构建人工智能应用程序的项目的名称,它通过消除不必要的复杂性来实现这一目标。该项目受到了Python项目的启发,如LangChain和LlamaIndex,但它并不是后者的直接移植。Spring AI相信,下一个人工智能应用浪潮将不仅仅局限于Python开发人员,而是会普及到许多编程语言。

特点:

  • 对所有主要模型供应商(如OpenAI、Microsoft、Amazon、Google和Hugging Face)的支持。
  • 支持的模型类型包括聊天、文本转图像、音频转录、文字转语音等,未来还会支持更多。
  • 在所有模型中提供跨AI供应商的统一API。同时支持同步和流式API选项。也可以访问特定于模型的特性。
  • 将AI模型的输出映射到POJO
  • 支持所有主要向量数据库供应商(如Apache Cassandra、Azure向量搜索、Chroma、Milvus、MongoDB Atlas、Neo4j、Oracle、PostgreSQL/PGVector、PineCone、Qdrant、Redis和Weaviate)。
  • …

1、概念

1.1、模型Model

功能分类:文生文、文生图、图生文、声音转文字、文字转声音、文本(图片)转向量(嵌套)等

temperature温度:这个参数控制着生成的随机性。较高的温度值会增加文本的多样性和创造性,但可能会牺牲一些准确性或连贯性。
在这里插入图片描述

1.2、提示词prompts

提示词作为基于语言的输入的基础,指导人工智能模型生成具体的输出,但提示词不仅仅是对话框中输入的文本。ChatGPT 的 API 在提示中有多个文本输入,每个文本输入都被分配一个角色。例如,存在系统角色,它告诉模型如何行为并为交互设置上下文。还有用户角色,通常是来自用户的输入。

提示词模板:创建有效的提示涉及建立请求的上下文,并用特定于用户输入的值替换请求的部分。此过程使用传统的基于文本的模板引擎进行提示创建和管理。Spring AI 使用 OSS 库 StringTemplate 来实现此目的。

官网例子:

Tell me a {adjective} joke about {content}.

在 Spring AI 中,提示模板可以比作 Spring MVC 架构中的“视图”。提供了一个模型对象,通常为 java.util.Map ,用于填充模板中的占位符。

prompts后续会根据OpenAI的文档单独写一章

1.3、嵌入Embeddings

翻译的软件说是嵌入,即文本、图像或视频的数字表示形式,用于捕获输入之间的关系。**我更认为是文本和图像的向量化。**嵌入的工作原理是将文本、图像和视频转换为浮点数数组,称为向量。这些向量旨在捕获文本、图像和视频的含义。嵌入数组的长度称为向量的维数。

通过计算两段文本的向量表示之间的数值距离,应用程序可以确定用于生成嵌入向量的对象之间的相似性。

在这里插入图片描述
嵌入在检索增强生成 (RAG) 模式等实际应用中尤为重要。它们使数据能够表示为语义空间中的点,语义空间类似于欧几里得几何的二维空间,但维度更高。这意味着,就像欧几里得几何中平面上的点根据其坐标可以近或远一样,在语义空间中,点的接近反映了含义的相似性。在这个多维空间中,关于相似主题的句子位置更近,就像图表上彼此靠近的点一样。这种接近性有助于文本分类、语义搜索甚至产品推荐等任务,因为它允许人工智能根据它们在这个扩展的语义景观中的“位置”来辨别和分组相关概念。

RAG、agent(智能体)等后续文章会讲,期待后续吧!

1.4、令牌Token

在英语中,一个token大致相当于一个单词的 75%。自己买的API通过token进行消耗,狭义理解为使用OpenAI的流量。在托管 AI 模型的上下文中,您的费用由使用的令牌数量决定。输入和输出都会影响总令牌计数。

1.5、结构化输出

一般输出以String形式出现,也可以是JSON,JSON不一定准。
在这里插入图片描述

结构化输出转换采用精心设计的提示,通常需要与模型进行多次交互才能实现所需的格式设置。

1.6、AI整合私有数据

一般三种方法:

  1. 使用私有数据微调模型,修改模型权重等
  2. 将私有数据转换为向量存储到向量数据库,在对话时进行查询检索,即检索增强生成(RAG)
  3. 函数调用,直接调用OpenAI、Ollama等

推荐使用2和3

1.7、检索增强生成 Retrieval Augmented Generation(RAG)

该方法涉及批处理样式编程模型,其中作业从文档中读取非结构化数据,对其进行转换,然后将其写入向量数据库。概括地说,这是一个 ETL(提取、转换和加载)管道。向量数据库用于RAG技术的检索部分。

作为将非结构化数据加载到矢量数据库的一部分,最重要的转换之一是将原始文档拆分为较小的部分。将原始文档拆分为较小部分的过程有两个重要步骤:

  1. 将文档拆分为多个部分,同时保留内容的语义边界。例如,对于包含段落和表格的文档,应避免将文档拆分在段落或表格的中间。对于代码,请避免在方法实现的过程中拆分代码。
  2. 将文档的各个部分进一步拆分为多个部分,其大小仅占 AI 模型令牌限制的一小部分。

RAG 的下一阶段是处理用户输入。当 AI 模型要回答用户的问题时,该问题和所有“相似”的文档片段都会被放入发送到 AI 模型的提示中。这就是使用向量数据库的原因。它非常擅长寻找类似的内容。
在这里插入图片描述

1.8、函数调用

Spring AI 大大简化了您需要编写以支持函数调用的代码。它为您处理函数调用对话。您可以将函数提供@Bean ,然后在提示选项中提供函数的 bean 名称以激活该函数。此外,您可以在单个提示中定义和引用多个函数。
在这里插入图片描述

  1. 执行聊天请求,发送功能定义信息。后者提供 name 、 description (例如解释模型何时应调用函数)和 input parameters (例如函数的输入参数架构)。
  2. 当模型决定调用函数时,它将使用输入参数调用函数,并将输出返回给模型。
  3. Spring AI 为您处理此对话。它将函数调用分派给相应的函数,并将结果返回给模型。
  4. 模型可以执行多个函数调用来检索它需要的所有信息。
  5. 一旦获取了所需的所有信息,模型将生成响应。

2、使用

2.1、开始

要使用SpringBoot3,OpenJDK17或以上

<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.8</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.ai</groupId>
    <artifactId>spring-ai</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-ai</name>
    <description>spring-ai</description>
    <url/>
    <licenses>
        <license/>
    </licenses>
    <developers>
        <developer/>
    </developers>
    <scm>
        <connection/>
        <developerConnection/>
        <tag/>
        <url/>
    </scm>
    <properties>
        <java.version>17</java.version>
        <spring-ai.version>1.0.0-M1</spring-ai.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--需要ollama时候再使用,否则在自动装配情况下启动报错,提示chatClient.Builder需要指定一个大模型,在不使用自动装配时可以不注释-->
<!--        <dependency>-->
<!--            <groupId>org.springframework.ai</groupId>-->
<!--            <artifactId>spring-ai-ollama-spring-boot-starter</artifactId>-->
<!--        </dependency>-->
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-openai-spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </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>
    <dependencyManagement>
        <dependencies>
            <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>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

</project>

2.2、API

AI Model API分为普通Model和StreamingModel。StreamingModel是以流式返回响应,类似与AI回答一个个字显示而不是一下全部显示出来。
在这里插入图片描述
支持 OpenAI、Microsoft、Amazon、Google、Amazon Bedrock、Hugging Face 等的 AI 模型。支持 14 个向量数据库。Spring AI 可以轻松地让 AI 模型调用 POJO java.util.Function 对象。

2.2.1、Chat Client (聊天客户端 )API

SpringAI提供了一个流畅的 API,用于与 AI 模型进行通信。它支持同步和反应式编程模型(最简单、最基础的API)。AI 模型处理两种主要类型的消息:用户消息(来自用户的直接输入)和系统消息(由系统生成以指导对话)。这些消息通常包含占位符,这些占位符在运行时根据用户输入进行替换,以自定义 AI 模型对用户输入的响应。还可以指定提示选项,例如要使用的 AI 模型的名称和控制生成输出的随机性或创造力设置。

ChatClient 使用 ChatClient.Builder 对象创建的。您可以为任何 ChatModel Spring Boot 自动配置获取自动配置 ChatClient.Builder 的实例,也可以以编程方式创建一个实例。

官网代码

package com.ai.springai.controller;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Title: MyController
 * @Author lizhe
 * @Package com.ai.springai.controller
 * @Date 2024/8/15 下午11:33
 * @description: 测试chat client API
 */

@RestController
public class MyController {
    private final ChatClient chatClient;
    public MyController(ChatClient.Builder chatClientBuilder) {
        this.chatClient = chatClientBuilder.build();
    }
    @GetMapping("/ai")
    String generation(String userInput) {
        return this.chatClient.prompt()
                .user(userInput)
                .call()
                .content();
    }


}

将函数改造一下(调用OpenAI接口)

package com.ai.springai.controller;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Title: MyController
 * @Author lizhe
 * @Package com.ai.springai.controller
 * @Date 2024/8/15 下午11:33
 * @description: 测试chat client API
 */

@RestController
public class MyController {
    private final ChatClient chatClient;
    public MyController(ChatClient.Builder chatClientBuilder) {
        this.chatClient = chatClientBuilder.build();
    }
    @GetMapping("/ai")
    String generation(@RequestParam(value = "message", defaultValue = "Tell me a joke") String userInput) {
        return this.chatClient.prompt()
                .user(userInput)
                .call()
                .content();
    }


}

配置文件

spring:
  application:
    name: spring-ai

  ai:
  	#api-key需要自己买,base-url买的时候会告诉你
    openai:
      api-key: sk-***********************************
      base-url: https://*********


测试结果
在这里插入图片描述
如果要使用多个大模型进行聊天,需要把Spring的自动注入关闭。可以通过设置属性 spring.ai.chat.client.enabled=false 来禁用 ChatClient.Builder 自动配置。

修改配置文件

spring:
  application:
    name: spring-ai

  ai:
  	#api-key需要自己买,base-url买的时候会告诉你
    openai:
      api-key: sk-***********************************
      base-url: https://*********
    chat:
      client:
        enabled: false


修改代码

package com.ai.springai.controller;

import jakarta.annotation.Resource;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Title: MyController
 * @Author lizhe
 * @Package com.ai.springai.controller
 * @Date 2024/8/15 下午11:33
 * @description: 测试chat client API
 */

@RestController
public class MyController {
    private final ChatClient chatClient;
	// 在使用多模型可能会用到,后续遇到再写
    // private final ChatClient chatClientOther;
    @Autowired
    public MyController(OpenAiChatModel openAiChatModel) {
        this.chatClient = ChatClient.create(openAiChatModel);
    }



    @GetMapping("/ai")
    String generation(@RequestParam(value = "message", defaultValue = "Tell me a joke") String userInput) {
        return this.chatClient.prompt()
                .user(userInput)
                .call()
                .content();
    }


}

测试结果
在这里插入图片描述

客户端返回响应

AI 模型的响应是由 ChatResponse 类型定义的丰富结构。它包括有关如何生成响应的元数据,还可以包含多个响应(称为“生成”),每个响应都有自己的元数据。元数据包括用于创建响应的标记数(每个标记大约为单词的 3/4)。此信息很重要,因为托管 AI 模型根据每个请求使用的令牌数量收费。

    @GetMapping("/getChatResponse")
    String index() {
        ChatResponse chatResponse = chatClient.prompt()
                .user("Tell me a joke")
                .call()
                .chatResponse();
        return chatResponse.toString();
    }

返回结果

ChatResponse [metadata={ @type: org.springframework.ai.openai.metadata.OpenAiChatResponseMetadata, id: chatcmpl-DsGla7joCoVCOc5ZiBoUDbFbNZYnA, usage: Usage[completionTokens=17, promptTokens=11, totalTokens=28], rateLimit: { @type: org.springframework.ai.openai.metadata.OpenAiRateLimit, requestsLimit: null, requestsRemaining: null, requestsReset: null, tokensLimit: null; tokensRemaining: null; tokensReset: null } }, generations=[Generation{assistantMessage=AssistantMessage{content='Sure thing! What kind of shoes do ninjas wear? Sneakers!', properties={finishReason=STOP, role=ASSISTANT, id=chatcmpl-DsGla7joCoVCOc5ZiBoUDbFbNZYnA, messageType=ASSISTANT}, messageType=ASSISTANT}, chatGenerationMetadata=org.springframework.ai.chat.metadata.ChatGenerationMetadata$1@5e07f126}]]
返回实体对象
    @GetMapping("/getEntity")
    ActorFilms getEntity() {
        ActorFilms actorFilms = chatClient.prompt()
                .user("Generate the filmography for a random actor.")
                .call()
                .entity(ActorFilms.class);
        return actorFilms;
    }

结果
在这里插入图片描述

流式响应**

使 stream 您可以获得异步响应

@GetMapping("/getStreamOutput")
    Flux<String> getStreamOutput() {
        Flux<String> output = chatClient.prompt()
                .user("讲一个不少于500字的通话故事")
                .stream()
                .content();
        return output;
    }

生成的结果文字是通过流的方式一点点的呈现,对于生成大量文字的用户体验感更好。
在这里插入图片描述

使用默认值

在 @Configuration 类中使用默认系统文本创建 ChatClient 可简化运行时代码。通过设置默认值,您只需在调用 ChatClient 时指定用户文本,而无需为运行时代码路径中的每个请求设置系统文本。

系统默认文本可以提前设置输入给模型的角色、任务、方式等

config

package com.ai.springai.config;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Title: AIConfig
 * @Author lizhe
 * @Package com.ai.springai.config
 * @Date 2024/8/16 下午11:10
 * @description: 配置系统默认文本
 */
@Configuration
public class AIConfig {
    @Bean
    ChatClient chatClient(ChatClient.Builder builder) {
        return builder.defaultSystem("你是一名专业的中国法律顾问,回答问题时要引用中国的法律条文")
                .build();
    }
}

contrller

package com.ai.springai.controller;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @Title: TestDefaultText
 * @Author lizhe
 * @Package com.ai.springai.controller
 * @Date 2024/8/16 下午11:14
 * @description: 测试默认系统文本
 */
@RestController
public class TestDefaultTextController {
    private final ChatClient chatClient;
    TestDefaultTextController(ChatClient chatClient){
        this.chatClient = chatClient;
    }
    @GetMapping("/defaultText")
    public Map<String, String> completion(@RequestParam(value = "message", defaultValue = "单位克扣工资违法吗") String message) {
        return Map.of("completion", chatClient.prompt().user(message).call().content());
    }

}

结果
在这里插入图片描述
在默认文本中加入参数,在参数中可以设置AI的不同角色

config

package com.ai.springai.config;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Title: AIConfig
 * @Author lizhe
 * @Package com.ai.springai.config
 * @Date 2024/8/16 下午11:10
 * @description: 配置系统默认文本
 */
@Configuration
public class AIConfig {
    @Bean
    ChatClient chatClient(ChatClient.Builder builder) {
        return builder.defaultSystem("你是一名专业的中国{profession}")
                .build();
    }
}

controller

package com.ai.springai.controller;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @Title: TestDefaultText
 * @Author lizhe
 * @Package com.ai.springai.controller
 * @Date 2024/8/16 下午11:14
 * @description: 测试默认系统文本
 */
@RestController
public class TestDefaultTextController {
    private final ChatClient chatClient;
    TestDefaultTextController(ChatClient chatClient){
        this.chatClient = chatClient;
    }
    @GetMapping("/defaultText")
    public Map<String, String> completion(@RequestParam(value = "message", defaultValue = "关于环保说出你的专业看法") String message,String profession) {
        return Map.of("completion", chatClient.prompt().system(systemSpec -> systemSpec.param("profession",profession)).user(message).call().content());
    }

}

农民角色
在这里插入图片描述
环保主义者角色
在这里插入图片描述

聊天记忆

ChatMemory 代表聊天对话历史记录的存储。它提供了向对话添加消息、从对话中检索消息以及清除对话历史记录的方法。

有两种实现 InMemoryChatMemory , CassandraChatMemory 它们为聊天对话历史记录、内存中和 time-to-live 相应的持久化提供存储。

使用 ChatMemory 接口通过对话历史记录向提示提供建议,这些对话历史记录在如何将内存添加到提示的详细信息上有所不同。

  • MessageChatMemoryAdvisor :检索内存并将其作为消息集合添加到提示符中
  • PromptChatMemoryAdvisor :检索内存并将其添加到提示的系统文本中。
  • VectorStoreChatMemoryAdvisor :构造函数 VectorStoreChatMemoryAdvisor(VectorStore vectorStore, String defaultConversationId, int chatHistoryWindowSize) 允许您指定要从中检索聊天记录的 VectorStore、唯一对话 ID、要检索的聊天记录的大小(以令牌大小表示)。

官网代码

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

@Service
public class CustomerSupportAssistant {

    private final ChatClient chatClient;

    public CustomerSupportAssistant(ChatClient.Builder builder, VectorStore vectorStore, ChatMemory chatMemory) {

    this.chatClient = builder
            .defaultSystem("""
                    You are a customer chat support agent of an airline named "Funnair".", Respond in a friendly,
                    helpful, and joyful manner.

                    Before providing information about a booking or cancelling a booking, you MUST always
                    get the following information from the user: booking number, customer first name and last name.

                    Before changing a booking you MUST ensure it is permitted by the terms.

                    If there is a charge for the change, you MUST ask the user to consent before proceeding.
                    """)
            .defaultAdvisors(
                    new PromptChatMemoryAdvisor(chatMemory),
                    // new MessageChatMemoryAdvisor(chatMemory), // CHAT MEMORY
                    new QuestionAnswerAdvisor(vectorStore, SearchRequest.defaults()),
                    new LoggingAdvisor()) // RAG
            .defaultFunctions("getBookingDetails", "changeBooking", "cancelBooking") // FUNCTION CALLING
            .build();
}

public Flux<String> chat(String chatId, String userMessageContent) {

    return this.chatClient.prompt()
            .user(userMessageContent)
            .advisors(a -> a
                    .param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                    .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 100))
            .stream().content();
    }
}

但是我粘贴后,导包后还是报红,不知道咋回事,估计后续官网会更新吧
在这里插入图片描述
源码中的参数并没有LoggingAdvisor
在这里插入图片描述

日志记录

SimpleLoggerAdvisor 用于记录 ChatClient 的 request 和 response 数据。这对于调试和监视 AI 交互非常有用。

Spring AI:让ChatGPT成为你的开发助手 在当今快速发展的技术世界中,人工智能(AI)正逐渐成为开发者的得力助手。而ChatGPT作为一种强大的自然语言处理模型,已经被广泛应用于聊天机器人、智能助手、自动回复系统等领域。本文将介绍如何使用Spring AI集成ChatGPT,让它成为你的开发助手。Spring AI是一个基于Spring Boot框架的AI应用开发工具包。它旨在简化AI模型的集成和部署,使开发者能够更快地构建智能应用。Spring AI提供了一系列功能,包括对话管理、自然语言处理、图像识别等,其中ChatGPT就是其中之一。 阅读详情

相关推荐

SpringAI——Java生态接入LLM

本文将使用SpringAI配合Ollama完成SpringAI的体验,下面分别介绍SpringAI和Ollama。

【叫我姜同学】的个人博客 7027

Spring AI -使用Spring快速开发ChatGPT应用

本篇文章将会对SpringAI进行简单的介绍和使用,并通过SpringBoot来集成SpringAI实际开发出一个简单的http对话接口。

qq_41481367的博客 5万+

大模型LLM之SpringAI:Web+AI(二)

然后,当要向 AI 模型发送用户查询时,首先检索一组相似的文档。然后,这些文档充当用户问题的上下文,并与用户的查询一起发送到 AI 模型。设计成一个简单便携的界面,用于与专门用于图像生成的各种 AI 模型进行交互,允许开发人员以最少的代码更改在不同的图像相关模型之间切换。当将向量作为查询时,向量数据库将返回与查询向量“相似”的向量。多模态是指模型同时理解和处理来自各种来源的信息的能力,包括文本、图像、音频和其他数据格式。向量数据库是一种特殊类型的数据库,在人工智能应用中发挥着至关重要的作用。

wslzoooo的博客 1490

Spring推出Spring AI框架,看看怎么个事

在当今快速发展的技术时代,人工智能(AI)已经成为各行各业的关键驱动力。而作为一种领先的Java应用开发框架,Spring Framework在软件开发领域享有盛誉。下面跟着我一起去了解Spring AI的庐山真面目吧。

qq_43657722的博客 7246

Spring AI与大模型Ollama如何集成整合?

这两种方法的操作方式都是获取一个 Payload 对象(该对象封装了要嵌入的字符串),并以不同的格式返回嵌入结果--在 getEmbeddingsWithModelOverride 的情况下直接返回 EmbeddingResponse,而在 getEmbeddingsWithDefaultModel 的情况下返回一个包含 EmbeddingResponse 的映射。借助 Ollama 在本地运行 LLM 的能力,开发人员可以对人工智能驱动的功能获得前所未有的控制力和灵活性,确保数据隐私并减少延迟。

极道Jdon的技术博客 3414

基于SpringAI与MCP构建智能AI Agent岗位匹配系统实战

大语言模型(LLM)通过理解自然语言和生成结构化数据,正在重塑传统工作流程。其核心原理在于将非结构化文本转换为向量表示,从而进行语义相似度计算和智能推理。这一技术价值在于能够自动化处理复杂的信息匹配任务,显著提升效率与精准度。在招聘领域,传统基于关键词的简历筛选方式难以评估“软技能”和“隐性要求”,而AI Agent通过集成LLM的深度理解与推理能力,可以模拟专业招聘顾问,实现岗位与人才的多维度智能匹配。本文以SpringAI框架为基础,结合MCP协议扩展外部工具能力,详细演示了如何构建一个集职位描述解析、

weixin_34007886的博客 367

SpringAI学习及搭建AI原生应用

SpringAI的推出被认为是Java开发领域的一大福音,因为它结合了Spring生态系统的设计原则和模块化的概念,降低了接入大型语言模型(LLM)的学习成本。此外,在输入封装和输出处理等配套类的帮助下,聊天模型 API 统一了与 AI 模型的通信。简单而言,Spring AI 是AI工程师所使用的一种应用性框架,通过提供出来的API和API key来进行开发应用,所用在于使用AI应用来简化开发工序流程。

qq_43548590的博客 1万+

SpringAI提示词模板实战:从概念到构建动态AI应用

提示词模板是构建大语言模型(LLM)应用的核心技术,它通过预定义文本结构实现指令的动态化与复用。其原理是将固定文本与可变占位符结合,利用字符串插值技术动态生成最终指令,从而将业务逻辑与提示构造解耦。这项技术的核心价值在于提升代码可维护性、支持复杂工作流编排,并能显著提高开发效率。在工程实践中,它广泛应用于智能对话、内容生成、代码审查与翻译服务等场景。本文以SpringAI框架为例,深入解析其PromptTemplate类的用法,并通过一个完整的动态翻译服务实战案例,展示如何利用模板技术高效构建AI应用,实现

weixin_34187862的博客 380

ollama+llm+springai集成

本文详细介绍了ollama+anything+llm本地环境搭建与RAG检索增强环境的配置方法。主要内容包括:1)ollama的安装配置及模型下载;2)与SpringAI的集成验证,包括ChatClient、ChatModel、工具调用和MCPServer的实现;3)AnythingLLM的安装使用,重点讲解Workspace工作区配置和RAG文档验证;4)常用ollama命令汇总。文章指出SpringAI文档更新滞后,建议直接使用HTTP接口而非依赖第三方包,并分享了实际开发中的经验教训和问题发现。

yanghuashuiyue的专栏 1231

8. Spring Ai之入门到精通(超级详细)

Spring AI 1.0.0 M1里程碑版本发布,标志着 Java 终于踏进Ai的时代半只脚。

gorgor在码农 3万+

深入SVT SPI VIP配置:如何灵活控制CS间隔、数据帧大小与时钟频率(含代码片段)

本文深入探讨了SVT SPI VIP的高级配置技巧,包括精确控制CS信号间隔、突破数据帧大小限制以及动态时钟频率切换。通过实战代码片段和详细配置步骤,帮助验证工程师灵活应对复杂SPI协议验证场景,提升验证效率和覆盖率。特别适合需要处理非标准SPI时序和特殊数据帧的芯片验证项目。

weixin_27014595的博客 296

JB3-9-SpringAI(一)

基础对话,通义千问,SpringAI,SpringAIAlibaba,AI对话,文生图,文生音频,文生视频,AI记忆,RAG,ETL,向量库,ToolCalling,MCP,Graph 等。

周航宇的博客 3967

从Live2D到Unreal Engine:2D与3D虚拟数字人核心技术实现路径解析

本文深入解析了从Live2D到Unreal Engine的2D与3D虚拟数字人核心技术实现路径,涵盖技术选型、制作流程与优化技巧。通过对比2D骨骼动画与3D建模渲染的差异,结合实战案例,帮助开发者根据项目需求选择合适方案,提升虚拟数字人的交互体验与视觉效果。

weixin_30379531的博客 162

《大模型应用开发 2:SpringAI 支持的多语言大模型调用实践》

SpringAI 是 Spring 生态系统的一部分,它提供了统一的接口调用各种 AI 服务。简化 API 调用:通过声明式配置,减少底层代码。支持多模型:兼容 OpenAI、Anthropic、Hugging Face 等。多语言处理:内置机制处理不同语言输入,如中文、英文、西班牙文等,适合全球化应用。

2501_93893367的博客 1303

有限元缺陷:剪切锁死

有限元缺陷:剪切锁死

wsxww11的博客 5201

掌控板玩板指南1:初识掌控板、扩展板、Mind+编辑器

掌控板、I/O扩展板入门

好乐无荒之地 1万+

《大模型应用开发 2:SpringAI 处理大模型输出格式标准化》

在大型语言模型(LLM)应用中,输出格式往往不一致(如文本、JSON片段或非结构化数据),这会导致下游处理困难。标准化输出格式(如统一为JSON或XML)能提升系统可靠性和集成效率。SpringAI作为Spring框架的扩展,提供工具来自动化这一过程。下面我将逐步解释问题、解决方案和实现方法,确保内容清晰可靠。SpringAI通过模块化组件处理输出标准化:关键优势:以下是基于Java的Spring Boot示例,展示如何将大模型输出标准化为JSON格式。假设使用OpenAI模型,目标输出结构为: $$ \{

2501_93893341的博客 1061

YOLOv11n-seg 实战指南:从训练到模型部署的完整流程

本文提供了YOLOv11n-seg实例分割模型从环境准备、数据标注到模型训练、验证及最终部署的完整实战指南。详细讲解了如何准备多边形掩码数据、配置关键训练参数、解读分割核心评估指标,并重点介绍了将模型导出为ONNX等格式进行部署的流程与优化技巧,帮助开发者高效完成从开发到生产的全链路实践。

weixin_29062255的博客 562

SpringAI+Ollama+Qwen:7b,轻松搭建本地大模型聊天程序!大模型入门到精通,收藏这篇就足够了!

还记得ChatGPT刚火那会儿,朋友圈满屏都是"我和AI的对话截图"。可最近,越来越多开发者开始担心:我的敏感数据会不会被云端大模型"偷窥"?

pythonhy的博客 1066

蓝牙HCI Dongle实战:从芯片选型到协议栈集成的完整指南

本文详细介绍了蓝牙HCI Dongle的实战应用,从芯片选型到协议栈集成的完整指南。通过对比CSR8510、nRF52840等主流芯片的性能和价格,提供选型建议和避坑技巧。同时,深入解析Zephyr协议栈移植和常见问题排查,帮助开发者高效完成蓝牙项目开发。

weixin_30786657的博客 330

MicroCap声学仿真介绍(三)-人耳的频率响应

这里需要注意的是,24mm我们会填为”24m”,这里的“m”是毫的意思,24m意思是24e-3,同理7.4mm我们可以填为7.4m,意思是7.4e-3。MicroCap声学库中,已内置“声源”模块和“管”模块,我们需要调用这两个模块,并用连接线将这两个模块连接到一起,完成仿真工作。上图中第一个图是在管的一端输入1Pa(94dBSPL)的信号,管的另一端的不同频率的声压大小的仿真结果。上述的结果跟我们的常识也是符合的。换言之,我们要仿真的目的是在管的一端加1pa的声压时,管的另一端不同频率下的声压分布。

山无忧的博客 1488

基于SpringAI与MCP构建智能招聘AI Agent:从语义匹配到职业规划

在数字化转型浪潮中,AI Agent正成为解决复杂业务场景的关键技术。其核心原理在于通过大语言模型(LLM)赋予系统理解、推理和决策能力,并结合工具调用扩展其功能边界。这一技术价值在于能够将传统的关键词匹配升级为深度的语义理解与动态规划,从而显著提升人岗匹配的精准度与用户体验。在招聘与求职领域,传统方法常因语义鸿沟和需求泛化导致效率低下。本文以SpringAI为模型集成框架,引入MCP(Model Context Protocol)实现能力模块化,详细展示了如何构建一个集简历解析、语义匹配、技能差距分析和职

weixin_34378767的博客 405

【教程4>第4章>第22节】FFT频偏估计方法,导频+cordic频偏估计方法,costas环的性能对比

频偏范围适应性:Costas 环频偏锁定和基于 PN 导频和 CORDIC 算法的频偏估计都可以通过调整参数来适应一定范围的频偏,但 Costas 环的频率捕获范围相对较窄,而基于 PN 导频和 CORDIC 算法的频偏估计,基于 FFT 变换频偏估计对频偏范围较大。在高信噪比条件下,三种方法都可以获得较高的估计精度,但在低信噪比环境中,基于 PN 导频和 CORDIC 算法的频偏估计,基于 FFT 变换频偏估计这两个开环方案相对更具优势,而Costas 环频偏锁定的精度可能会受到较大影响.

FPGA/MATLAB学习教程/源码/项目合作开发 619

SpringAI智能助手案例

接下来,我们就利用SpringAI发起与大模型的第一次对话。Java 领域 实现大模型开发(LLM),有两个非常重要的框架SpringAI 最低支持的 jdk 版本是 17LangChain4J 最低支持的版本是 8。

二进制专栏 917

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

拥抱AI大模型开发——SpringAI快速入门

‍SpringAI 是 Spring 生态体系下官方推出的 ​AI 能力集成框架,核心定位是为 Java 开发者提供低门槛、高兼容的企业级 AI 应用开发方案。它延续了 Spring “约定优于配置” 的设计哲学,将复杂的 AI 模型调用、服务集成、流程编排逻辑封装为标准化组件,让开发者无需深入理解 AI 底层技术,即可快速在 Spring Boot、Spring Cloud 等现有项目中集成大语言模型(LLM)、图像生成、语音识别等 AI 能力,大幅降低企业级 AI 应用的开发成本与技术门槛。​。

zxb的博客 603

inori mmd 7z

楪祈的模型资源....................................................................................................................................................................................................................

又一个项目完结:基于SpringAI Alibaba开发大模型智能体,支持基础版和多模式

今天,带着大家使用SpringAI Alibaba框架,从零开始构建一个功能完善的智能对话助手。无论你是刚入门的新手还是有一定经验的开发者,都能通过本教程快速掌握大模型应用开发的核心技能。

瓦罗兰特顶级C位的博客 887

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

上一篇: 大数据之Spark(二)
下一篇: 大模型LLM之SpringAI:Web+AI(二)
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

空指针异常Null_Point_Ex

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值