首页 > 其他分享 >Spring AI使用

Spring AI使用

时间:2024-07-02 22:28:31浏览次数:3  
标签:AI Spring 使用 springframework ai spring msg org import

一、背景

2024年5月30日发布了Spring AI 1.0.0 Milestone1,代表spring项目中引入包括LLM之类的AI类进入stable状态。jdk要求java 17以上体现出AI项目的未来趋势,更对企业开发环境升级提出了要求。

聊天模型:包括OpenAI、Azure Open AI、Amazon Bedrock、Cohere’s Command、AI21 Labs’ Jurassic-2、Meta’s LLama 2、Amazon’s Titan、Google Vertex AI Palm、Google Gemini、HuggingFace(包括Meta的Llama2等数千种模型)、Ollama(本地运行AI模型)、MistralAI等。
文本到图像模型:如OpenAI的DALL-E、StabilityAI等。
嵌入模型:包括OpenAI、Azure Open AI、Ollama、ONNX、PostgresML、Bedrock Cohere、Bedrock Titan、Google VertexAI、Mistal AI等。

spring-ai官方链接

二、导入依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!--spring ai的starter依赖,启动依赖,起步依赖-->
    <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>

<!--相当于是继承一个父项目:spring-ai-bom父项目-->
<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>

配置本项目的仓库(因为maven中心仓库还没有更新spring ai的jar包)

<repositories>
    <!--里程碑版本的仓库-->
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>

三、yml配置文件

spring:
  application:
    name: spring-ai-01-chat
  ai:
    openai:
      api-key: sk-bToZitPE`淘宝购买`
      base-url: https://api.openai.com/
      chat:
        options:
          model: gpt-3.5-turbo
          temperature: 0.3F

四、controller

package com.bjpowernode.controller;

import jakarta.annotation.Resource;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@RestController
public class ChatController {

    /**
     * spring-ai 自动装配的,可以直接注入使用
     */
    @Resource
    private OpenAiChatClient openAiChatClient;

    /**
     * 调用OpenAI的接口
     *
     * @param msg 我们提的问题
     * @return
     */
    @RequestMapping(value = "/ai/chat0")
    public String chat0(@RequestParam(value = "msg") String msg) {
        String called = openAiChatClient.call(msg);

        return called;
    }

    /**
     * 调用OpenAI的接口
     *
     * @param msg 我们提的问题
     * @return
     */
    @RequestMapping(value = "/ai/chat1")
    public Object chat1(@RequestParam(value = "msg") String msg) {
        ChatResponse chatResponse = openAiChatClient.call(new Prompt(msg));
        return chatResponse.getResult().getOutput().getContent();
    }



    /**
     * pt-3.5-turbo:
     * 费用:$0.002/1000 tokens大概1500汉字
     * <p>
     * gpt-4:
     * 费用:$0.06/1000 tokens大概1500汉字
     * <p>
     * gpt-4-32k:  32k是参数量
     * 费用:$0.12/1000 tokens大概1500汉字
     * <p>
     * 调用OpenAI的接口
     *
     * @param msg 我们提的问题
     * @return
     */

    @RequestMapping(value = "/ai/chat3")
    public Object chat3(@RequestParam(value = "msg") String msg) {
        //可选参数在配置文件中配置了,在代码中也配置了,那么以代码的配置为准,也就是代码的配置会覆盖掉配置文件中的配置
        ChatResponse chatResponse = openAiChatClient.call(new Prompt(msg, OpenAiChatOptions.builder()
                .withModel("pt-3.5-turbo") //gpt的版本
                .withTemperature(0.4F) //温度越高,回答得比较有创新性,但是准确率会下降,温度越低,回答的准确率会更好
                .build()));
        return chatResponse.getResult().getOutput().getContent();
    }

    @RequestMapping(value = "/ai/chat4")
    public Object chat4(@RequestParam(value = "msg") String msg) {
        //可选参数在配置文件中配置了,在代码中也配置了,那么以代码的配置为准,也就是代码的配置会覆盖掉配置文件中的配置
        ChatResponse chatResponse = openAiChatClient.call(new Prompt(msg, OpenAiChatOptions.builder()
                .withModel("gpt-4") //gpt的版本,暂时无法使用需要购买高级key
                .withTemperature(0.4F) //温度越高,回答得比较有创新性,但是准确率会下降,温度越低,回答的准确率会更好
                .build()));
        return chatResponse.getResult().getOutput().getContent();
    }

    /**
     * 调用OpenAI的接口
     *
     * @param msg 我们提的问题
     * @return
     */
    @RequestMapping(value = "/ai/chat5")
    public Object chat5(@RequestParam(value = "msg") String msg) {
        //可选参数在配置文件中配置了,在代码中也配置了,那么以代码的配置为准,也就是代码的配置会覆盖掉配置文件中的配置
        Flux<ChatResponse> flux = openAiChatClient.stream(new Prompt(msg, OpenAiChatOptions.builder()
                //.withModel("gpt-4-32k") //gpt的版本,32k是参数量
                .withTemperature(0.4F) //温度越高,回答得比较有创新性,但是准确率会下降,温度越低,回答的准确率会更好
                .build()));

        flux.toStream().forEach(chatResponse -> {
            System.out.println(chatResponse.getResult().getOutput().getContent());
        });
        return flux.collectList(); //数据的序列,一序列的数据,一个一个的数据返回
    }

}

标签:AI,Spring,使用,springframework,ai,spring,msg,org,import
From: https://blog.csdn.net/o0way0o/article/details/140137031

相关文章

  • SpringMVC和Servlet域对象
    SpringMVC和Servlet域对象1.Servlet域对象介绍1.1三大域对象Servlet有三个域对象分别是请求域(request)、会话域(seesion)和应用域(application)。域对象与数据的共享密不可分。通过方法可以向域对象中存储key:value键值对形式的数据。三个域对象都有以下通用方法,通过这些方法来达......
  • 仿论坛项目--初识Spring Boot
    1.技术准备技术架构•SpringBoot•Spring、SpringMVC、MyBatis•Redis、Kafka、Elasticsearch•SpringSecurity、SpringActuator开发环境•构建工具:ApacheMaven•集成开发工具:IntelliJIDEA•数据库:MySQL、Redis•应用服务器:ApacheTomcat•版本......
  • AOP的基本使用
    @Target({ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic@interfaceRequestLog{}@Slf4j@Aspect@ComponentpublicclassRequestLogAspect{@Around(“@within(org.springframework.stereotype.Controller)||@within(org.springframe......
  • SpringBoot的重要考点--自动配置
    SpringBoot的自动配置是其核心特性之一,它允许开发者快速启动和运行Spring应用,而无需编写大量的样板代码。SpringBoot的自动配置主要通过以下几个方式实现:@EnableAutoConfiguration:这个注解是SpringBoot自动配置的入口,它告诉SpringBoot根据类路径中的jar包和配置文件来......
  • 完全图解RAID存储技术:RAID 0、1、5、6、10、50、60
    转自:https://cloud.tencent.com/developer/article/2304179什么是RAID存储?独立磁盘冗余阵列(RAID)是一种存储技术,通过将两个或多个硬盘驱动器(HDD)或固态硬盘(SSD)合并成一个协调的存储单元或阵列,从而创建数据丢失的故障安全机制。RAID存储通过将数据重复或重新创建,并将其存储在......
  • 数据分表——使用 Mybatis-Plus插件实现动态表名分表(按年份分表、按月份分表)
    本博客适合Mybatis-Plus3.4以上版本,笔者使用版本为3.5.3。分库与分表的原因1.业务场景:日志、交易流水表或者其他数据量大的表,通过日期进行了水平分表,需要通过日期参数,动态的查询数据。实现思路:利用MybatisPlus的动态表名插件DynamicTableNameInnerInterceptor,实现Sql执行......
  • 基于SpringBoot+Vue+uniapp的论文管理系统的详细设计和实现(源码+lw+部署文档+讲解等)
    文章目录前言详细视频演示具体实现截图技术栈后端框架SpringBoot前端框架Vue持久层框架MyBaitsPlus系统测试系统测试目的系统功能测试系统测试结论为什么选择我代码参考数据库参考源码获取前言......
  • 【Java学习笔记】方法的使用
    【Java学习笔记】方法的使用一、一个例子二、方法的概念及使用(一)什么是方法(二)方法的定义(三)方法调用的执行过程(四)实参和形参的关系(重要)(五)没有返回值的方法三、方法重载(一)为什么需要方法重载(二)方法重载概念(三)方法签名四、递归(一)生活中的故事(二)递归的概念(三)递归执行过程分......
  • 专题五:Spring源码之初始化容器上下文
    上一篇我们通过如下一段基础代码作为切入点,最终找到核心的处理是refresh方法,从今天开始正式进入refresh方法的解读。publicclassMain{ publicstaticvoidmain(String[]args){ ApplicationContextcontext=newClassPathXmlApplicationContext("applicationContext......
  • Spring Boot 中 PGSQL 判断打卡点是否经过轨迹优化代码,循环查询物理表修改生成临时表,
    记录一下一个业务问题,流程是这样的,我现在有一个定时任务,5分钟执行一次,更新车辆打卡的情况。现在有20俩车,每辆车都分配了路线,每条路线都有打卡点,每个打卡点分配了不同的时间段,也就是说,一条路线可能有几百个打卡点,这几百个打卡点中每一个都分配了时间段,有可能是1个时间段,比如8......