当前位置: 首页 > article >正文

spring-ai

1.介绍

1. 目前 AI 应用程序开发框架主要是 Python 生态;而 Spring AI 是由 Spring 团队推出的一个扩展框架,专为将 AI 能力集成到 Java 应用中而设计。它利用 Spring 的生态系统优势,提供了一系列简单易用的 API 和工具,使开发者可以轻松地加载、训练和推理 AI模型。这不仅降低了开发门槛,还极大地提高了开发效率。

Spring AI 的核心是解决 AI 集成的根本挑战:将您的企业数据和 API 与 AI 模型连接起来。

2.ai会代替程序员吗?

个人理解5-10年不会替代程序员,之后必然会淘汰程序员

1.ai生成的代码不是100%正确

2.ai无法理解复杂的需求

3.ai生成代码没有办法无缝的接入到代码去

4.紧跟ai步伐

2.SpringAI请求流程

1. spring-ai只需要使用调用大模型接口进行使用即可,我们不需要了解其内部如何实现。

2.RAG检索增强生成:用于存储资料,知识到向量数据库,存储的过程叫Embeddings(绑定),大模型就可以结合向量数据库进行返回结果;

向量数据库可以使用redis,es等

3. fine-tuning(微调):垂直领域(具体行业),用于单独训练某个领域的知识、资料。

4. function-call(函数调用):通过定义Java函数接口,并使用特定注解来描述函数的输入参数、输出结果及其功能实现

3.创建项目

maven配置文件

<?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.4.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>spring-ai-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-ai-demo</name>
    <description>spring-ai-demo</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-M5</spring-ai.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</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-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>
            </plugin>
        </plugins>
    </build>

</project>

1.配置api-key

spring:
  application:
    name: spring-ai-demo
  ai:
    openai:
      api-key: sk-xxx
      base-url:

api-key:大模型key

base-url:大模型代理地址

1. 没有魔法,无法购买chatgpt接口,可以使用国内代理,也可以自行搜索,也可以使用如下

1. AiCore
访问地址:https://api.xty.app
注册登录后可以创建令牌
注意:不是纯免费
接口地址/BaseURL/密钥地址/代理地址(不同软件配置方式不同,请用下面的地址逐一测试):
https://api.xty.app,备用加速地址: https://hk.xty.app
https://api.xty.app/v1,备用加速地址: https://hk.xty.app/v1淘宝搜: open ai key也可以直接购买

2.eylink

访问地址:首页 | OpenAI_GPT4_购买平台_OpenAI API - eylink官网

2.编写demo-实现智能对话

编写controller

@RestController
@RequestMapping("/ai")
public class AiController {


    //智能对话客户端
    private final ChatClient chatClient;

    public AiController(ChatClient.Builder chatClientBuilder) {
        this.chatClient = chatClientBuilder.build();
    }

    //生成一個chat方法
    @RequestMapping("/chat")
    public String chat(
            @RequestParam(value = "userInput",defaultValue = "你好,讲个笑话") String userInput) {
        // prompt:提示词
        String answer
                = this.chatClient.prompt()
                //用户信息
                .user(userInput)
                //远程请求大模型
                .call()
                //返回文本
                .content();
        return answer;
    }
}

访问地址:

3.预设角色

1.创建AiConfig,

2.使用defaultSystem("")方法设置预设角色,后续对话都会通过预设角色进行对话。

3.controller就看可以使用@Autowired进行注解,因为ChatClient已经注入为bean

@Configuration
public class AiConfig {


    @Bean
    ChatClient chatClient(ChatClient.Builder chatClientBuilder){
        return chatClientBuilder.defaultSystem("你是一个医生").build();
    };
}

4.流式响应

1.相应结果会一个字一个字进行返回

//编写方法,返回流式
@RequestMapping(value = "/chatStream",produces = "text/html;charset=UTF-8")
public Flux<String> chatStream(
        @RequestParam(value = "userInput",defaultValue = "你好,讲个笑话") String userInput) {
    // prompt:提示词
    Flux<String> answer
            = this.chatClient.prompt()
            //用户信息
            .user(userInput)
            .stream()
            //返回文本
           .content();
    return answer;
}

5.访问官方openai

设置代理

6.ChatClient和ChatModel区别

1.ChatClient是在ChatModel进行了封装,变得更加简洁调用

2.使用ChatModel可以配置自己独有的参数,如大模型,temperature等参数。

@Autowired
private ChatModel chatModel;
@RequestMapping(value = "/chatModel", produces = "text/html;charset=UTF-8")
public Flux<String>  chatModel(
        @RequestParam(value = "userInput", defaultValue = "你好,讲个笑话") String userInput) {
    // prompt:提示词
    Flux<ChatResponse> stream = this.chatModel.stream(
            new Prompt(userInput, OpenAiChatOptions.builder()
                    .model("gpt-3.5-turbo")
                    .temperature(1.0D)
                    .build()
            ));
    //stream返回流式
    //map返回文本,报错了,提示没有getContent方法
    return stream.map(r -> {
        if (r.getResult() == null || r.getResult().getOutput() == null
                || r.getResult().getOutput().getText() == null) {
            return "";
        }
        return r.getResult().getOutput().getText();
    }).filter(StringUtils::hasLength);

}

7.文生图

@RequestMapping(value = "/text2Image", produces = "text/html;charset=UTF-8")
public String  text2Image(
        @RequestParam(value = "userInput", defaultValue = "一只可爱的小狗") String userInput) {
    // prompt:提示词
    ImageResponse imageResponse = this.openAiImageModel.call(
            new ImagePrompt(userInput, OpenAiImageOptions.builder()
                    .quality("hd")
                    .model(OpenAiImageApi.DEFAULT_IMAGE_MODEL)
                    .withN(1)
                    .withHeight(1024)
                    .withWidth(1024)
                    .build())
    );
    return imageResponse.getResult().getOutput().getUrl();
}

8.文生语音

OpenAiAudioSpeechOptions speechOptions = OpenAiAudioSpeechOptions.builder()
    .model("tts-1")
    .voice(OpenAiAudioApi.SpeechRequest.Voice.ALLOY)
    .responseFormat(OpenAiAudioApi.SpeechRequest.AudioResponseFormat.MP3)
    .speed(1.0f)
    .build();

SpeechPrompt speechPrompt = new SpeechPrompt("Hello, this is a text-to-speech example.", this.speechOptions);
SpeechResponse response = openAiAudioSpeechModel.call(this.speechPrompt);

9.语音翻译

OpenAiAudioApi.TranscriptResponseFormat responseFormat = OpenAiAudioApi.TranscriptResponseFormat.VTT;

OpenAiAudioTranscriptionOptions transcriptionOptions = OpenAiAudioTranscriptionOptions.builder()
    .language("en")
    .prompt("Ask not this, but ask that")
    .temperature(0f)
    .responseFormat(this.responseFormat)
    .build();
AudioTranscriptionPrompt transcriptionRequest = new AudioTranscriptionPrompt(audioFile, this.transcriptionOptions);
AudioTranscriptionResponse response = openAiTranscriptionModel.call(this.transcriptionRequest);

10.多模态

1. 什么是多模态,指的是能够同时处理文本、图像、音频、视频等多种数据类型或模态的机器学习模型

2.只能用gpt-4o或gpt-4-turbo-preview版本

11.Function Calling

1.大型语言模型(LLM)在生成文本的过程中调用外部函数或服务

2.它允许大型语言模型(如GPT)在生成文本的过程中调用外部函数或服务。这种功能的核心在于,模型本身不直接执行函数,而是生成包含函数名称和执行函数所需参数的JSON,然后由外部系统执行这些函数,并将结果返回给模型以完成对话或生成任务

3.Spring AI的Function Calling功能主要解决了大型语言模型在处理任务时的局限性,尤其是模型自身无法获取实时信息或执行复杂计算的问题。通过Function Calling,模型可以利用外部工具或服务来扩展其能力,从而能够处理更广泛的任务,如实时数据查询、复杂计算等。

使用场景

  1. 实时数据查询:模型可以通过调用外部API来获取实时数据,如股票价格、天气预报等,并将这些数据整合到生成的文本中。
  2. 复杂计算:模型可以调用外部函数来执行复杂的计算任务,如数学运算、统计分析等。
  3. 业务逻辑处理:在业务场景中,模型可以调用自定义的函数来处理特定的业务逻辑,如订单处理、用户验证等。
  4. 简化集成:Spring AI提供了一套简化的API,使得开发者能够更容易地在Java应用程序中集成和使用AI功能。
  5. 跨平台兼容性:支持多种AI模型和数据库提供商,提供了良好的兼容性和可移植性。
  6. 抽象化:通过提供抽象层,Spring AI允许开发者在不深入了解底层AI模型细节的情况下,实现复杂的AI功能。


http://www.kler.cn/a/541497.html

相关文章:

  • IPoIB模块初始化过程详解
  • 百度高德地图坐标转换
  • 荣耀手机Magic3系列、Magic4系列、Magic5系列、Magic6系列、Magic7系列详情对比以及最新二手价格预测
  • MYSQL学习笔记(七):新年第一篇之子查询
  • 【开源AI】AI一页一页读PDF
  • 机器学习怎么学习,还有算法基本的源代码
  • Java 大视界 -- Java 大数据在智能体育中的应用与赛事分析(80)
  • Android 稳定性优化总结
  • 【LeetCode: 378. 有序矩阵中第 K 小的元素 + 二分】
  • 缓存组件<keep-alive>
  • 关于SpringBoot的理解
  • 无人机常见的定位方式
  • Lisp语言的测试开发
  • 十三. Redis 应用问题和解决方案思想
  • 从零到一:我的元宵灯谜小程序诞生记
  • 从MySQL优化到脑力健康:技术人与效率的双重提升
  • IDEA接入DeepSeek
  • 企业级Mysql实战
  • Vue 响应式渲染 - Vue2 Class和style
  • 功能测试常用方法概述
  • 有关网络安全的案例分享 如何保障网络安全
  • c++面试:符号修饰
  • C# Winform 使用委托实现C++中回调函数的功能
  • Leetcode—1165. 单行键盘【简单】Plus
  • Linux 内核中断处理机制:上半部与下半部详解
  • Spring Boot @Import注解的作用