总结之Spring AI(一)——使用Spring AI

news2024/11/26 15:53:25

前言

当前各种AI项目层出不穷,但绝大多数都是用python写的,现在Spring开源了Spring AI项目,让Java开发者也可以轻松给自己的springboot项目集成AI能力。目前spring AI正式版本为0.8.1,支持接入openAI、Ollama、Azure openAI、Huggingface等,可实现聊天、embedding、图片生成、语音转文字、向量数据库、function calling、prompt模板、outputparser、RAG等功能,就像Java版本的langchain。

Spring AI有以下特点:

1、在AI的聊天、文生图、嵌入模型等方面提供API级别的支持
2、与模型之间支持同步式和流式交互(还记得ChatGPT返回内容时,是逐字生成的吗,这就是流式交互的效果)
3、多种模型支持

使用Spring AI

版本

maven:3.8.1
jdk:17
springboot:3.2.4
spring ai:0.8.1 (稳定版)

OpenAI

使用OpenAI需要对应账号及api key才行,这里可以使用自己账号也可以借助网络免费使用chatGPT的方法
https://gitcode.com/chatanywhere/GPT_API_free/overview

在这里插入图片描述

运行AI

创建一个maven工程

pom

<?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 http://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.4</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

    <groupId>com.imaniy</groupId>
    <artifactId>hello-springai</artifactId>
    <version>1.0-SNAPSHOT</version>

	<description>Simple AI Application demos</description>

	<properties>
		<java.version>17</java.version>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
	</properties>


    <dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.ai</groupId>
				<artifactId>spring-ai-bom</artifactId>
				<version>0.8.1</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<repositories>
		<repository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/milestone</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
		<repository>
			<id>spring-snapshots</id>
			<name>Spring Snapshots</name>
			<url>https://repo.spring.io/snapshot</url>
			<releases>
				<enabled>false</enabled>
			</releases>
		</repository>
	</repositories>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</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.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<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>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

这里最重要的是spring-ai-openai-spring-boot-starter这个包,如果出现这个包拉不下来,可以更改一下setting.xml文件,使用更快的镜像,再拉不下来就自己手动下载贴在对应的
在这里插入图片描述
setting.xml

<?xml version="1.0" encoding="UTF-8"?>

<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->

<!--
 | This is the configuration file for Maven. It can be specified at two levels:
 |
 |  1. User Level. This settings.xml file provides configuration for a single user,
 |                 and is normally provided in ${user.home}/.m2/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -s /path/to/user/settings.xml
 |
 |  2. Global Level. This settings.xml file provides configuration for all Maven
 |                 users on a machine (assuming they're all using the same Maven
 |                 installation). It's normally provided in
 |                 ${maven.conf}/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -gs /path/to/global/settings.xml
 |
 | The sections in this sample file are intended to give you a running start at
 | getting the most out of your Maven installation. Where appropriate, the default
 | values (values used when the setting is not specified) are provided.
 |
 |-->
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <!-- localRepository
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ${user.home}/.m2/repository
  <localRepository>/path/to/local/repo</localRepository>
  -->

  <!-- interactiveMode
   | This will determine whether maven prompts you when it needs input. If set to false,
   | maven will use a sensible default value, perhaps based on some other setting, for
   | the parameter in question.
   |
   | Default: true
  <interactiveMode>true</interactiveMode>
  -->

  <!-- offline
   | Determines whether maven should attempt to connect to the network when executing a build.
   | This will have an effect on artifact downloads, artifact deployment, and others.
   |
   | Default: false
  <offline>false</offline>
  -->

  <!-- pluginGroups
   | This is a list of additional group identifiers that will be searched when resolving plugins by their prefix, i.e.
   | when invoking a command line like "mvn prefix:goal". Maven will automatically add the group identifiers
   | "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not already contained in the list.
   |-->
  <pluginGroups>
    <!-- pluginGroup
     | Specifies a further group identifier to use for plugin lookup.
    <pluginGroup>com.your.plugins</pluginGroup>
    -->
  </pluginGroups>

  <!-- proxies
   | This is a list of proxies which can be used on this machine to connect to the network.
   | Unless otherwise specified (by system property or command-line switch), the first proxy
   | specification in this list marked as active will be used.
   |-->
  <proxies>
    <!-- proxy
     | Specification for one proxy, to be used in connecting to the network.
     |
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>proxyuser</username>
      <password>proxypass</password>
      <host>proxy.host.net</host>
      <port>80</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
    -->
  </proxies>

  <!-- servers
   | This is a list of authentication profiles, keyed by the server-id used within the system.
   | Authentication profiles can be used whenever maven must make a connection to a remote server.
   |-->
  <servers>
    <!-- server
     | Specifies the authentication information to use when connecting to a particular server, identified by
     | a unique name within the system (referred to by the 'id' attribute below).
     |
     | NOTE: You should either specify username/password OR privateKey/passphrase, since these pairings are
     |       used together.
     |
    <server>
      <id>deploymentRepo</id>
      <username>repouser</username>
      <password>repopwd</password>
    </server>
    -->

    <!-- Another sample, using keys to authenticate.
    <server>
      <id>siteServer</id>
      <privateKey>/path/to/private/key</privateKey>
      <passphrase>optional; leave empty if not used.</passphrase>
    </server>
    -->
  </servers>

  <!-- mirrors
   | This is a list of mirrors to be used in downloading artifacts from remote repositories.
   |
   | It works like this: a POM may declare a repository to use in resolving certain artifacts.
   | However, this repository may have problems with heavy traffic at times, so people have mirrored
   | it to several places.
   |
   | That repository definition will have a unique id, so we can create a mirror reference for that
   | repository, to be used as an alternate download site. The mirror site will be the preferred
   | server for that repository.
   |-->
  <mirrors>
   <mirror>
        <id>alimaven</id>
        <name>aliyun maven</name>
        <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
        <mirrorOf>central</mirrorOf>        
    </mirror>
    <!-- mirror
     | Specifies a repository mirror site to use instead of a given repository. The repository that
     | this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used
     | for inheritance and direct lookup purposes, and must be unique across the set of mirrors.
     |
    <mirror>
      <id>mirrorId</id>
      <mirrorOf>repositoryId</mirrorOf>
      <name>Human Readable Name for this Mirror.</name>
      <url>http://my.repository.com/repo/path</url>
    </mirror>
     -->
  </mirrors>

  <!-- profiles
   | This is a list of profiles which can be activated in a variety of ways, and which can modify
   | the build process. Profiles provided in the settings.xml are intended to provide local machine-
   | specific paths and repository locations which allow the build to work in the local environment.
   |
   | For example, if you have an integration testing plugin - like cactus - that needs to know where
   | your Tomcat instance is installed, you can provide a variable here such that the variable is
   | dereferenced during the build process to configure the cactus plugin.
   |
   | As noted above, profiles can be activated in a variety of ways. One way - the activeProfiles
   | section of this document (settings.xml) - will be discussed later. Another way essentially
   | relies on the detection of a system property, either matching a particular value for the property,
   | or merely testing its existence. Profiles can also be activated by JDK version prefix, where a
   | value of '1.4' might activate a profile when the build is executed on a JDK version of '1.4.2_07'.
   | Finally, the list of active profiles can be specified directly from the command line.
   |
   | NOTE: For profiles defined in the settings.xml, you are restricted to specifying only artifact
   |       repositories, plugin repositories, and free-form properties to be used as configuration
   |       variables for plugins in the POM.
   |
   |-->
  <profiles>
    <!-- profile
     | Specifies a set of introductions to the build process, to be activated using one or more of the
     | mechanisms described above. For inheritance purposes, and to activate profiles via <activatedProfiles/>
     | or the command line, profiles have to have an ID that is unique.
     |
     | An encouraged best practice for profile identification is to use a consistent naming convention
     | for profiles, such as 'env-dev', 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc.
     | This will make it more intuitive to understand what the set of introduced profiles is attempting
     | to accomplish, particularly when you only have a list of profile id's for debug.
     |
     | This profile example uses the JDK version to trigger activation, and provides a JDK-specific repo.
    <profile>
      <id>jdk-1.4</id>

      <activation>
        <jdk>1.4</jdk>
      </activation>

      <repositories>
        <repository>
          <id>jdk14</id>
          <name>Repository for JDK 1.4 builds</name>
          <url>http://www.myhost.com/maven/jdk14</url>
          <layout>default</layout>
          <snapshotPolicy>always</snapshotPolicy>
        </repository>
      </repositories>
    </profile>
    -->

    <!--
     | Here is another profile, activated by the system property 'target-env' with a value of 'dev',
     | which provides a specific path to the Tomcat instance. To use this, your plugin configuration
     | might hypothetically look like:
     |
     | ...
     | <plugin>
     |   <groupId>org.myco.myplugins</groupId>
     |   <artifactId>myplugin</artifactId>
     |
     |   <configuration>
     |     <tomcatLocation>${tomcatPath}</tomcatLocation>
     |   </configuration>
     | </plugin>
     | ...
     |
     | NOTE: If you just wanted to inject this configuration whenever someone set 'target-env' to
     |       anything, you could just leave off the <value/> inside the activation-property.
     |
    <profile>
      <id>env-dev</id>

      <activation>
        <property>
          <name>target-env</name>
          <value>dev</value>
        </property>
      </activation>

      <properties>
        <tomcatPath>/path/to/tomcat/instance</tomcatPath>
      </properties>
    </profile>
    -->
  </profiles>

  <!-- activeProfiles
   | List of profiles that are active for all builds.
   |
  <activeProfiles>
    <activeProfile>alwaysActiveProfile</activeProfile>
    <activeProfile>anotherAlwaysActiveProfile</activeProfile>
  </activeProfiles>
  -->
</settings>

配置

# 调用OpenAI接口时表明身份的API Key,前面的章节有提到如何生成一个免费的
spring.ai.openai.api-key=sk-xxxxxx
# 调用OpenAI接口时的基础地址,如果用的是chatanywhere的API Key,这里就要用chatanywhere提供的地址,
# 如果用的是OpenAI的原生API Key,就不用配置这个参数
spring.ai.openai.base-url=https://api.chatanywhere.tech
# 用到的模型
spring.ai.openai.chat.options.model=gpt-3.5-turbo
# temperature越小,回答的内容越严谨,temperature越大,回答的内容越有创造性
spring.ai.openai.chat.options.temperature=0.7

调用

我们这里使用的是springboot工程,需要一个启动类

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

调用AI的Controller

import org.springframework.ai.chat.ChatClient;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;


import java.util.List;
import java.util.Map;

@RestController
public class SimpleAiController {
	// 负责处理OpenAI的bean,所需参数来自properties文件
	private final ChatClient chatClient;

	public SimpleAiController(@Qualifier("openAiChatClient") ChatClient chatClient) {
		this.chatClient = chatClient;
	}

	@PostMapping("/ai/simple")
	public Map<String, String> completion(@RequestBody Map<String,String> map) {
		return Map.of("generation", chatClient.call(map.get("message")));
	}
}

使用API访问gpt

在这里插入图片描述
上面就是简单的使用Sping AI,也是对Spring AI的初步认识。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1816672.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

手机短信验证码登录

用户需求&#xff1a; 1、用户使用手机号和短信验证码登录系统 2、未注册过的手机号再登录时实现自动注册 3、新注册的账号只有7天的使用时间&#xff0c;过期后不允许进行登录 功能需求&#xff1a; 登录页面设计 图1.手机号登录 【验证码登录】规则说明&#xff1a; 1…

【three.js】设置three.js全屏展示,并解决大小动态变化

目录 一、设置全屏 二、canvas画布宽高度动态变化 一、设置全屏 这个很简单,直接用代码读取当前全屏需要的长宽即可。 const width = window.innerWidth; //窗口文档显示区的宽度作为画布宽度 const height = window.innerHeight; //窗口文档显示区的高度作为画布高度 二、…

水帘降温水温

不同环境下的水帘啊&#xff0c;使用水温是不一样的&#xff0c;夏天使用水疗的水有两种&#xff0c;一个是常温的循环水&#xff0c;20~26左右&#xff0c;另外一个呢&#xff0c;就是深井水&#xff0c;重点是啥呢&#xff1f;就是无论我们用哪一种&#xff0c;能够把温度降到…

计算机网络(4) 最长前缀匹配(路由转发表)

一.路由转发 网络数据包IP段只包含源地址与目的地址&#xff0c;经过数据链路层包装与物理层信号形式转换&#xff0c;最终经由不同的链路节点到达目的地址。这个过程是一步一步&#xff08;hop by hop&#xff09;进行的&#xff0c;路过一个路由节点则称为一跳。每个路由节点…

绘唐一键追爆款3正式版

【绘唐2一键追爆款】 这是一个关于追求梦想的故事&#xff0c;讲述了一个普通人如何利用一键追爆款的技巧&#xff0c;成功打造自己的事业的动人故事。 主人公小明是一个市井小民&#xff0c;生活过得平凡无奇。他一直怀揣着一个梦想&#xff0c;希望能够通过自己的努力&#x…

Stable Diffusion: ControlNet Openpose

上一文已经介绍了ControlNet的安装&#xff0c;点击右边的三角箭头。 拖放原始姿态图片。 勾选“启用”&#xff0c;“完美像素模式”&#xff0c;“允许预览” 控制类型选择“OpenPose(姿态&#xff09;” 预处理器选“openpose_full”&#xff0c;会对原始姿态图片做整体分…

【C++】编译

三、C编译 前面给大家演示了如何从写C代码到编译代码再到执行代码的全过程。这个过程中非常重要的编译环节&#xff0c;被我们一个按钮或者一个ctrlF7快捷键就给带过了。其实这个环节非常重要&#xff0c;如果你非常了解这个环节&#xff0c;你开发源代码就会更加自信和清醒&a…

Java基础面试重点-1

0. 符号&#xff1a; *&#xff1a;记忆模糊&#xff0c;验证后特别标注的知识点。 &&#xff1a;容易忘记知识点。 *&#xff1a;重要的知识点。 1. 简述一下Java面向对象的基本特征&#xff08;四个&#xff09;&#xff0c;以及你自己的应用&#xff1f; 抽象&#…

c#调用c++dll方法

添加dll文件到debug目录&#xff0c;c#生成的exe的相同目录 就可以直接使用了&#xff0c;放在构造函数里面测试

【git使用四】git分支理解与操作(详解)

目录 &#xff08;1&#xff09;理解git分支 主分支&#xff08;主线&#xff09; 功能分支 主线和分支关系 将分支合并到主分支 快速合并 非快速合并 git代码管理流程 &#xff08;2&#xff09;理解git提交对象 提交对象与commitID Git如何保存数据 示例讲解 &a…

CorelDRAW2024官方最新中文破解版Crack安装包网盘下载安装方法

在设计的世界里&#xff0c;软件工具的更新与升级总是令人瞩目的焦点。近期&#xff0c;CorelDRAW 2024中文版及其终身永久版的发布&#xff0c;以及中文破解版Crack的出现&#xff0c;再次掀起了设计圈的热潮。对于追求专业精确的设计师而言&#xff0c;了解这些版本的下载安装…

Jemeter做性能测试

目录 1. 测试计划 2. 线程组 3. HTTP请求 4. 查看结果树 5. 聚合报告 【要求】 用JMeter取样器&#xff0c;实现对云边AI (qinzhi.xyz)的访问 【步骤】 1. 测试计划 2. 线程组 右击测试计划——添加——线程(用户)——线程组 3. HTTP请求 右击线程组——添加——取样…

鸿蒙轻内核A核源码分析系列五 虚实映射(6)虚拟映射修改转移

6.1 映射属性修改函数LOS_ArchMmuChangeProt 函数LOS_ArchMmuChangeProt用于修改进程空间虚拟地址区间的映射保护属性&#xff0c;其中参数archMmu为进程空间的MMU结构体&#xff0c;vaddr为虚拟地址&#xff0c;count为映射的页数&#xff0c;flags为映射使用的新标签属性信息…

easyrecovery专业版破解无需注册绿色版免费下载 easyrecovery16数据恢复软件永久激活码密钥百度网盘crack文件

EasyRecovery &#xff08;易恢复中国&#xff09;是由全球著名数据厂商Ontrack 出品的一款数据文件恢复软件。支持恢复不同存储介质数据&#xff1a;硬盘、光盘、U盘/移动硬盘、数码相机、Raid文件恢复等&#xff0c;能恢复包括文档、表格、图片、音视频等各种文件。 开发背景…

【网络安全的神秘世界】2024.6.6 Docker镜像停服?解决最近Docker镜像无法拉取问题

&#x1f31d;博客主页&#xff1a;泥菩萨 &#x1f496;专栏&#xff1a;Linux探索之旅 | 网络安全的神秘世界 | 专接本 解决Docker镜像无法拉取问题 &#x1f64b;‍♂️问题描述 常用镜像站&#xff1a;阿里云、科大、南大、上交等&#xff0c;全部挂掉 执行docker pull命…

手机数据删除很意外?失而复得,2个技巧揭晓

在这个快节奏的时代&#xff0c;手机就像是我们的“第二心脏”&#xff0c;不仅用来跟人聊天&#xff0c;还藏着我们的秘密宝藏——个人数据。但有时候&#xff0c;手一抖&#xff0c;心一慌&#xff0c;重要数据就消失了&#xff01;是不是感觉天都要塌下来了&#xff1f;别怕…

翻译: Gen AI生成式人工智能学习资源路线图一

Introduction 介绍 本文档旨在作为学习现代人工智能系统背后的关键概念的手册。考虑到人工智能最近的发展速度&#xff0c;确实没有一个好的教科书式的资源来快速了解 LLMs 或其他生成模型的最新和最伟大的创新&#xff0c;但互联网上有大量关于这些主题的优秀解释资源&#x…

postman教程-21-Newman运行集合生成测试报告

上一小节我们Postman Newman的安装方法&#xff0c;本小节我们讲解一下Postman Newman的具体使用方法。 使用Newman运行集合 1、导出Postman集合&#xff1a; 在Postman中&#xff0c;选择你想要运行的集合&#xff0c;然后点击“导出”按钮&#xff0c;选择导出为“Collect…

Figma文字标注工具的使用方法是什么?

在UI设计过程中&#xff0c;有一个让设计师头疼的工作环节&#xff0c;那就是文字标注的问题。相信大家对Figma软件都很熟悉&#xff0c;但是这个软件的使用也有自己的缺点&#xff0c;就是文字标注等问题&#xff0c;日常使用自己是做不到的&#xff0c;需要依靠第三方工具来执…

推荐使用三丰云免费云服务器、免费虚拟主机

官网地址&#xff1a;www.sanfengyun.com 三丰云服务器&#xff1a; 配置高&#xff1a;能够轻松运行应用程序和网站&#xff0c;在处理大量请求和保持高可靠性方面表现出色。 易用性好&#xff1a;界面直观、简单&#xff0c;能够轻松管理服务器和资源&#xff0c;快速创建和…