java结合Ai

Spring AI

Spring AI提供的API支持跨人工智能提供商的 聊天,文本到图像,和嵌入模型等,同时支持同步和流API选项;

介绍

Spring AI 是 AI 工程的应用框架。其目标是将Spring生态系统的设计原则(如可移植性和模块化设计)应用于AI领域,并促进使用POJO作为应用程序的构建块到AI领域。

特征

跨 AI 提供商的可移植 API 支持,适用于聊天、文本到图像和嵌入模型。支持同步 API 和流 API 选项。还支持下拉以访问特定于模型的功能。

聊天模型
  • 亚马逊基岩
    • 人类学
    • Cohere的命令
    • AI21 Labs的侏罗纪-2
    • Meta 的 LLama
    • 亚马逊的泰坦
  • 人类学克劳德
  • Azure 开放式 AI
  • 谷歌顶点 AI
    • 帕LM2
    • 双子座
  • 格罗克
  • HuggingFace - 访问数以千计的模型,包括来自 Meta 的模型,例如 Llama
  • 米斯特拉尔AI
  • 极大 极小
  • Moonshot AI
  • Ollama - 在本地计算机上运行 AI 模型
  • OpenAI的
  • 芊芊
  • 智普人工智能
  • Watsonx.AI
文本到图像模型
  • OpenAI 与 DALL-E
  • 稳定性AI
转录(音频到文本)模型
  • OpenAI的
嵌入模型
  • 蔚蓝 OpenAI
  • 亚马逊基岩
    • 凝聚力
    • 巨人
  • 蔚蓝 OpenAI
  • 米斯特拉尔 AI
  • 极大 极小
  • 奥拉玛
  • (ONNX)变形金刚
  • OpenAI的
  • PostgresML的
  • 芊芊
  • 顶点AI
    • 发短信
    • 模 态
    • 帕LM2
  • 智普人工智能

Vector Store API 提供跨不同提供商的可移植性,具有一种新颖的类似 SQL 的元数据过滤 API,可保持可移植性。

向量数据库
  • Azure AI 服务
  • Apache Cassandra
  • 色度
  • 弹性搜索
  • 宝石火
  • Milvus (小米)
  • MongoDB地图集
  • Neo4j的
  • Open搜索
  • 神谕
  • PG矢量
  • 松果
  • Qdrant的
  • 雷迪斯
  • SAP Hana(萨普哈纳)
  • 类型感知
  • 织造

Spring Boot 自动配置和 AI 模型和向量存储的启动器。

函数调用您可以向 OpenAI 模型声明实现,以便在其提示响应中使用。您可以直接将这些函数作为对象提供,或者在应用程序上下文中作为@Bean注册时引用其名称。此功能最大限度地减少了不必要的代码,并使 AI 模型能够请求更多信息以实现其响应。java.util.Function

支持的模型包括

  • OpenAI的
  • 蔚蓝 OpenAI
  • 顶点AI
  • 米斯特拉尔 AI
  • 人类学克劳德
  • 格罗克
用于数据工程的 ETL 框架
  • 我们的 ETL 框架的核心功能是促进使用 Vector Store 将文档传输到模型提供者。ETL 框架基于 Java 函数式编程概念,可帮助您将多个步骤链接在一起。
  • 我们支持阅读各种格式的文档,包括 PDF、JSON 等。
  • 该框架允许进行数据操作以满足您的需求。这通常涉及拆分文档以遵守上下文窗口限制,并使用关键字增强它们以提高文档检索效率。
  • 最后,处理过的文档存储在矢量数据库中,以便将来检索。

广泛的参考文档、示例应用程序和研讨会/课程材料。

未来的版本将在此基础上提供对其他 AI 模型的访问,例如,Google 刚刚发布的 Gemini 多模态模型、用于评估 AI 应用程序有效性的框架、更方便的 API 以及帮助解决“查询/汇总我的文档”用例的功能。请查看 GitHub,了解即将发布的版本的详细信息。

官网地址

https://spring.io/projects/spring-ai

使用

1、本机电脑要可以访问OpenAI网站 https://openai.com/(科学上网)

2、要有OpenAI的API Key;(注册账号或者购买)

怎么获取OpenAI的api-key

这种方法需要一个国外手机号,某些国家(如俄罗斯)的手机号可能无法使用。具体步骤如下:

1.访问控制台
https://platform.openai.com/docs/overview

 进入 OpenAI 网站:登录你的 OpenAI 账号。
进入 API 密钥页面:
点击右上角的个人头像,选择【Your profile】。
点击【User API keys】。
点击【Start verification】进行手机短信验证。

2.点击API keys

https://platform.openai.com/api-keys

依赖

<?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.3.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.cqh</groupId>
    <artifactId>spring-ai</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-ai</name>
    <description>spring-ai</description>

    <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>
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-openai-spring-boot-starter</artifactId>
        </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>

 yml

spring:
  application:
    name: spring-ai
  ai:
    openai:
      api-key: ${OPENAI_API_KEY}
      api-key-file-location: ${OPENAI_API_KEY_FILE_LOCATION}
      api-key-file-type: ${OPENAI_API_KEY_FILE_TYPE}
      api-key-file-name: ${OPENAI_API_KEY_FILE_NAME}
      api-key-file-path: ${OPENAI_API_KEY_FILE_PATH}
      api-key-header: ${OPENAI_API_KEY_HEADER}
      api-key-property: ${OPENAI_API_KEY_PROPERTY}
      api-key-env: ${OPENAI_API_KEY_ENV}
      api-key-file: ${OPENAI_API_KEY_FILE}
      api-type: ${OPENAI_API_TYPE}
      api-host: ${OPENAI_API_HOST}
      api-base: ${OPENAI_API_BASE}
      api-version: ${OPENAI_API_VERSION}
      base-url: ${OPENAI_BASE_URL}

yml解释

  • api-key: API 密钥,用于认证和授权对 OpenAI API 的访问。它从环境变量 ${OPENAI_API_KEY} 中读取。

  • api-key-file-location: API 密钥文件的位置。如果 API 密钥存储在文件中,这个配置项指定文件的位置。

  • api-key-file-type: API 密钥文件的类型(例如 JSON、YAML 等)。

  • api-key-file-name: API 密钥文件的名称。

  • api-key-file-path: API 密钥文件的完整路径,包括文件名。

  • api-key-header: API 密钥在请求头中的名称。

  • api-key-property: API 密钥存储在配置文件中的属性名。

  • api-key-env: API 密钥存储在环境变量中的名称。

  • api-key-file: API 密钥存储在文件中的位置或路径。

  • api-type: API 类型,可能用于指定使用的 API 版本或类型。

  • api-host: OpenAI API 的主机名或域名。

  • api-base: OpenAI API 的基础 URL 或路径。

  • api-version: OpenAI API 的版本号。

  • base-url: OpenAI API 的基础 URL,通常用于构造请求的完整 URL。

 一般这两个就够了

spring:
  ai:
    openai:
      api-key: sk-3sfER03LDLG3SDFsdadadadJSdw023lkrmrHDND32fmREKFD (换成你的api-key)
      base-url: https://api.openai.com(或者中转站)

安装

https://docs.spring.io/spring-cli/reference/installation.html
https://github.com/spring-projects/spring-cli/releases/tag/early-access

jdk使用17及以上

springboot3.几以上 

如果是0.8.1使用这个仓库

<?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.3.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>spring-ai3</artifactId>
    <version>0.8.1</version>
    <name>spring-ai3</name>
    <description>spring-ai3</description>

    <properties>
        <java.version>17</java.version>
        <spring-ai.version>1.0.0-SNAPSHOT</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>
            <version>${spring-ai.version}</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</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>
               <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>

消息聊天使用
    @RequestMapping("/chat3/hello2")
    public String hello2(@RequestParam(value = "msg") String msg)
    {
        String call = openAiChatClient.call(msg);
        System.out.println(call);
        return call;
    }

同步api

    @RequestMapping("/chat3/hello3")
    public Object hello3(@RequestParam(value = "msg") String msg)
    {
        ChatResponse call = openAiChatClient.call(new Prompt(msg));

        System.out.println(call);
        // 获取内容
        System.out.println("call.getResult().getOutput().getContent() = " + call.getResult().getOutput().getContent());
        return call;
    }

流式api

    @RequestMapping("/chat3/hello4")
    public Object hello4(@RequestParam(value = "msg") String msg)
    {
        Flux<ChatResponse> stream = openAiChatClient.stream(new Prompt(msg, OpenAiChatOptions.builder()
                .withTemperature(0.4F)
                .build()));

        stream.toStream().forEach(chatResponse -> {
            System.out.println(chatResponse.getResult().getOutput().getContent());
        });

        return stream.collectList();
    }
绘图(文字转图片)
    @Autowired
    private OpenAiImageClient openAiImageClient;   

 // 绘图
    @RequestMapping("/chat3/image1")
    public Object hello5(@RequestParam(value = "msg") String msg)
    {
        ImageResponse call = openAiImageClient.call(new ImagePrompt(msg));

        return call.getResult().getOutput();
    }

 

 

    @RequestMapping("/chat3/image2")
    public Object hello6(@RequestParam(value = "msg") String msg)
    {
        ImageResponse hd = openAiImageClient.call(new ImagePrompt(msg, OpenAiImageOptions.builder()
                .withQuality("hd") // 高清
                .withN(2) // 数量
                .withHeight(512) // 高度
                .withWidth(512) // 宽度
                .build()
        ));



        return hd.getResult().getOutput();
    }

或者 

使用版本1.0.0-快照版 

 语音转文字
  @Test
    public void test2() {
        //FileSystemResource fileSystemResource = new FileSystemResource("D:\\myDesktop\\test1\\test.mp3");
          ClassPathResource classPathResource = new ClassPathResource("test.mp3");

        String call = openAiTranscriptionModel.call(classPathResource);
        System.out.println("call = " + call);
    }


    @Autowired
    private OpenAiAudioTranscriptionModel openAiTranscriptionModel;
    // 语音转文字
    @Test
    public void test() {
        OpenAiAudioApi.TranscriptResponseFormat responseFormat = OpenAiAudioApi.TranscriptResponseFormat.VTT;
        // FileSystemResource fileSystemResource = new FileSystemResource("D:\\myDesktop\\test1\\test.mp3");
          ClassPathResource classPathResource = new ClassPathResource("test.mp3");

        OpenAiAudioTranscriptionOptions transcriptionOptions = OpenAiAudioTranscriptionOptions.builder()
                .withLanguage("en")
                .withPrompt("Ask not this, but ask that")
                .withTemperature(0f)
                .withResponseFormat(responseFormat)
                .build();
        AudioTranscriptionPrompt transcriptionRequest = new AudioTranscriptionPrompt(classPathResource, transcriptionOptions);
        AudioTranscriptionResponse response = openAiTranscriptionModel.call(transcriptionRequest);
        String output = response.getResult().getOutput();
        System.out.println("output = " + output);
    }

 

文字转语音
  @Autowired
    private OpenAiAudioSpeechModel openAiAudioSpeechModel;

    @Test
    void contextLoads() {
        OpenAiAudioSpeechOptions speechOptions = OpenAiAudioSpeechOptions.builder()
                .withModel("tts-1")
                .withVoice(OpenAiAudioApi.SpeechRequest.Voice.ALLOY)
                .withResponseFormat(OpenAiAudioApi.SpeechRequest.AudioResponseFormat.MP3)
                .withSpeed(1.0f)
                .build();

        SpeechPrompt speechPrompt = new SpeechPrompt("Hello, this is a text-to-speech example.", speechOptions);
        SpeechResponse response = openAiAudioSpeechModel.call(speechPrompt);
        System.out.println("response = " + response);
        byte[] output = response.getResult().getOutput();
        boolean b = FileUtil2.save2File("D:\\myDesktop\\test1\\test.mp3", output);
        System.out.println("b = " + b);


    }
package com.cqh.springai5.utils;



import java.io.*;

public class FileUtil2 {
        /**
         * 方法功能:将字节数组写入到新建文件中。

         * @return boolean
         * */
        public static boolean save2File(String fname, byte[] msg){
            OutputStream fos = null;
            try{
                File file = new File(fname);
                File parent = file.getParentFile();
                boolean bool;
                if ((!parent.exists()) &&
                        (!parent.mkdirs())) {
                    return false;
                }
                fos = new FileOutputStream(file);
                fos.write(msg);
                fos.flush();
                return true;
            }catch (FileNotFoundException e){
                return false;
            }catch (IOException e){
                File parent;
                return false;
            }
            finally{
                if (fos != null) {
                    try{
                        fos.close();
                    }catch (IOException e) {}
                }
            }
        }
        public static void main(String[] args)  {
            String msgStr = "aaaaa中国加油!!!!战胜新冠状病毒!!!";
            String filename = "E:\\test\\system\\test.txt";//注意修改为自己的文件名
            byte[] bytes = msgStr.getBytes();
            FileUtil2 fileUtil = new FileUtil2();
            boolean flag = fileUtil.save2File(filename, bytes);
        }
    }
    // 文字转语音
    @Test
    void contextLoads2() {

        SpeechPrompt speechPrompt = new SpeechPrompt("你好我是中国人");
        SpeechResponse response = openAiAudioSpeechModel.call(speechPrompt);
        System.out.println("response = " + response);
        byte[] output = response.getResult().getOutput();
        boolean b = FileUtil2.save2File("D:\\myDesktop\\test1\\test2.mp3", output);
        System.out.println("b = " + b);


    }

多模态Api

多模态是指模型同时理解和处理来自各种来源的信息的能力,包括文本、图像、音频和其他数据格式
多模式大语言模型(LLM)特征使模型能够结合其他模态(如图像、音频或视频)来处理和生成文本
Spring Al 多模态API提供了所有必要的统一抽象和代码封装来支持多模式LLM;

    @Au
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值