开源模型应用落地-工具使用篇-Spring AI(七)

news2024/9/22 11:26:45

一、前言

    在AI大模型百花齐放的时代,很多人都对新兴技术充满了热情,都想尝试一下。但是,实际上要入门AI技术的门槛非常高。除了需要高端设备,还需要面临复杂的部署和安装过程,这让很多人望而却步。不过,随着开源技术的不断进步,使得入门AI变得越来越容易。通过使用Ollama,您可以快速体验大语言模型的乐趣,不再需要担心繁琐的设置和安装过程。另外,通过集成Spring AI,让更多Java爱好者能便捷的将AI能力集成到项目中,接下来,跟随我的脚步,一起来体验一把。


二、术语

2.1、Spring AI

    是 Spring 生态系统的一个新项目,它简化了 Java 中 AI 应用程序的创建。它提供以下功能:

  • 支持所有主要模型提供商,例如 OpenAI、Microsoft、Amazon、Google 和 Huggingface。
  • 支持的模型类型包括“聊天”和“文本到图像”,还有更多模型类型正在开发中。
  • 跨 AI 提供商的可移植 API,用于聊天和嵌入模型。
  • 支持同步和流 API 选项。
  • 支持下拉访问模型特定功能。
  • AI 模型输出到 POJO 的映射。

2.2、Ollama
    是一个强大的框架,用于在 Docker 容器中部署 LLM(大型语言模型)。它的主要功能是在 Docker 容器内部署和管理 LLM 的促进者,使该过程变得简单。它可以帮助用户快速在本地运行大模型,通过简单的安装指令,用户可以执行一条命令就在本地运行开源大型语言模型。

    Ollama 支持 GPU/CPU 混合模式运行,允许用户根据自己的硬件条件(如 GPU、显存、CPU 和内存)选择不同量化版本的大模型。它提供了一种方式,使得即使在没有高性能 GPU 的设备上,也能够运行大型模型。
 


三、前置条件

3.1、JDK 17+

    下载地址:https://www.oracle.com/java/technologies/downloads/#jdk17-windows

    

    类文件具有错误的版本 61.0, 应为 52.0

3.2、创建Maven项目

    SpringBoot版本为3.2.3

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.2.3</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

3.3、导入Maven依赖包

<dependency>
	<groupId>org.projectlombok</groupId>
	<artifactId>lombok</artifactId>
	<optional>true</optional>
</dependency>

<dependency>
	<groupId>ch.qos.logback</groupId>
	<artifactId>logback-core</artifactId>
</dependency>

<dependency>
	<groupId>ch.qos.logback</groupId>
	<artifactId>logback-classic</artifactId>
</dependency>

<dependency>
	<groupId>cn.hutool</groupId>
	<artifactId>hutool-core</artifactId>
	<version>5.8.24</version>
</dependency>

<dependency>
	<groupId>org.springframework.ai</groupId>
	<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
	<version>0.8.0</version>
</dependency>

<dependency>
	<groupId>org.springframework.ai</groupId>
	<artifactId>spring-ai-ollama-spring-boot-starter</artifactId>
	<version>0.8.0</version>
</dependency>

3.4、 科学上网的软件

3.5、 安装Ollama及部署Qwen模型

    参见:开源模型应用落地-工具使用篇-Ollama(六)-CSDN博客


四、技术实现

4.1、调用Open AI

4.1.1、非流式调用

@RequestMapping("/chat")
public String chat(){
	String systemPrompt = "{prompt}";
	SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemPrompt);

	String userPrompt = "广州有什么特产?";
	Message userMessage = new UserMessage(userPrompt);

	Message systemMessage = systemPromptTemplate.createMessage(MapUtil.of("prompt", "you are a helpful AI assistant"));

	Prompt prompt = new Prompt(List.of(userMessage, systemMessage));

	List<Generation> response = openAiChatClient.call(prompt).getResults();

	String result = "";

	for (Generation generation : response){
		String content = generation.getOutput().getContent();
		result += content;
	}

	return result;
}

    调用结果:

    

4.1.2、流式调用

@RequestMapping("/stream")
public SseEmitter stream(HttpServletResponse response){
	response.setContentType("text/event-stream");
	response.setCharacterEncoding("UTF-8");
	SseEmitter emitter = new SseEmitter();


	String systemPrompt = "{prompt}";
	SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemPrompt);

	String userPrompt = "广州有什么特产?";
	Message userMessage = new UserMessage(userPrompt);

	Message systemMessage = systemPromptTemplate.createMessage(MapUtil.of("prompt", "you are a helpful AI assistant"));
	Prompt prompt = new Prompt(List.of(userMessage, systemMessage));

	openAiChatClient.stream(prompt).subscribe(x -> {
		try {
			log.info("response: {}",x);
			List<Generation> generations = x.getResults();
			if(CollUtil.isNotEmpty(generations)){
				for(Generation generation:generations){
				   AssistantMessage assistantMessage =  generation.getOutput();
					String content = assistantMessage.getContent();
					if(StringUtils.isNotEmpty(content)){
						emitter.send(content);
					}else{
						if(StringUtils.equals(content,"null"))
						emitter.complete(); // Complete the SSE connection
					}
				}
			}


		} catch (Exception e) {
			emitter.complete();
			log.error("流式返回结果异常",e);
		}
	});

	return emitter;
}

流式输出返回的数据结构:

    调用结果:

 

4.2、调用Ollama API

Spring封装的很好,基本和调用OpenAI的代码一致

4.2.1、非流式调用

@RequestMapping("/chat")
public String chat(){
	String systemPrompt = "{prompt}";
	SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemPrompt);

	String userPrompt = "广州有什么特产?";
	Message userMessage = new UserMessage(userPrompt);

	Message systemMessage = systemPromptTemplate.createMessage(MapUtil.of("prompt", "you are a helpful AI assistant"));

	Prompt prompt = new Prompt(List.of(userMessage, systemMessage));

	List<Generation> response = ollamaChatClient.call(prompt).getResults();

	String result = "";

	for (Generation generation : response){
		String content = generation.getOutput().getContent();
		result += content;
	}

	return result;
}

调用结果:

Ollam的server.log输出

4.2.2、流式调用

@RequestMapping("/stream")
public SseEmitter stream(HttpServletResponse response){
	response.setContentType("text/event-stream");
	response.setCharacterEncoding("UTF-8");
	SseEmitter emitter = new SseEmitter();


	String systemPrompt = "{prompt}";
	SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemPrompt);

	String userPrompt = "广州有什么特产?";
	Message userMessage = new UserMessage(userPrompt);

	Message systemMessage = systemPromptTemplate.createMessage(MapUtil.of("prompt", "you are a helpful AI assistant"));
	Prompt prompt = new Prompt(List.of(userMessage, systemMessage));

	ollamaChatClient.stream(prompt).subscribe(x -> {
		try {
			log.info("response: {}",x);
			List<Generation> generations = x.getResults();
			if(CollUtil.isNotEmpty(generations)){
				for(Generation generation:generations){
					AssistantMessage assistantMessage =  generation.getOutput();
					String content = assistantMessage.getContent();
					if(StringUtils.isNotEmpty(content)){
						emitter.send(content);
					}else{
						if(StringUtils.equals(content,"null"))
							emitter.complete(); // Complete the SSE connection
					}
				}
			}


		} catch (Exception e) {
			emitter.complete();
			log.error("流式返回结果异常",e);
		}
	});

	return emitter;
}

调用结果:


五、附带说明

5.1、OpenAiChatClient默认使用gpt-3.5-turbo模型

5.2、流式输出如何关闭连接

    不能判断是否为''(即空字符串),以下代码将提前关闭连接

    流式输出会返回''的情况

      应该在返回内容为字符串null的时候关闭

5.3、配置文件中指定的Ollama的模型参数,要和运行的模型一致,即

5.4、OpenAI调用完整代码

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api")
public class OpenaiTestController {
    @Autowired
    private OpenAiChatClient openAiChatClient;

//    http://localhost:7777/api/chat
    @RequestMapping("/chat")
    public String chat(){
        String systemPrompt = "{prompt}";
        SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemPrompt);

        String userPrompt = "广州有什么特产?";
        Message userMessage = new UserMessage(userPrompt);

        Message systemMessage = systemPromptTemplate.createMessage(MapUtil.of("prompt", "you are a helpful AI assistant"));

        Prompt prompt = new Prompt(List.of(userMessage, systemMessage));

        List<Generation> response = openAiChatClient.call(prompt).getResults();

        String result = "";

        for (Generation generation : response){
            String content = generation.getOutput().getContent();
            result += content;
        }

        return result;
    }

    @RequestMapping("/stream")
    public SseEmitter stream(HttpServletResponse response){
        response.setContentType("text/event-stream");
        response.setCharacterEncoding("UTF-8");
        SseEmitter emitter = new SseEmitter();


        String systemPrompt = "{prompt}";
        SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemPrompt);

        String userPrompt = "广州有什么特产?";
        Message userMessage = new UserMessage(userPrompt);

        Message systemMessage = systemPromptTemplate.createMessage(MapUtil.of("prompt", "you are a helpful AI assistant"));
        Prompt prompt = new Prompt(List.of(userMessage, systemMessage));

        openAiChatClient.stream(prompt).subscribe(x -> {
            try {
                log.info("response: {}",x);
                List<Generation> generations = x.getResults();
                if(CollUtil.isNotEmpty(generations)){
                    for(Generation generation:generations){
                       AssistantMessage assistantMessage =  generation.getOutput();
                        String content = assistantMessage.getContent();
                        if(StringUtils.isNotEmpty(content)){
                            emitter.send(content);
                        }else{
                            if(StringUtils.equals(content,"null"))
                            emitter.complete(); // Complete the SSE connection
                        }
                    }
                }


            } catch (Exception e) {
                emitter.complete();
                log.error("流式返回结果异常",e);
            }
        });

        return emitter;
    }
}

5.5、Ollama调用完整代码

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.ai.chat.Generation;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.ai.ollama.OllamaChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api")
public class OllamaTestController {
    @Autowired
    private OllamaChatClient ollamaChatClient;

    @RequestMapping("/chat")
    public String chat(){
        String systemPrompt = "{prompt}";
        SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemPrompt);

        String userPrompt = "广州有什么特产?";
        Message userMessage = new UserMessage(userPrompt);

        Message systemMessage = systemPromptTemplate.createMessage(MapUtil.of("prompt", "you are a helpful AI assistant"));

        Prompt prompt = new Prompt(List.of(userMessage, systemMessage));

        List<Generation> response = ollamaChatClient.call(prompt).getResults();

        String result = "";

        for (Generation generation : response){
            String content = generation.getOutput().getContent();
            result += content;
        }

        return result;
    }


    @RequestMapping("/stream")
    public SseEmitter stream(HttpServletResponse response){
        response.setContentType("text/event-stream");
        response.setCharacterEncoding("UTF-8");
        SseEmitter emitter = new SseEmitter();


        String systemPrompt = "{prompt}";
        SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemPrompt);

        String userPrompt = "广州有什么特产?";
        Message userMessage = new UserMessage(userPrompt);

        Message systemMessage = systemPromptTemplate.createMessage(MapUtil.of("prompt", "you are a helpful AI assistant"));
        Prompt prompt = new Prompt(List.of(userMessage, systemMessage));

        ollamaChatClient.stream(prompt).subscribe(x -> {
            try {
                log.info("response: {}",x);
                List<Generation> generations = x.getResults();
                if(CollUtil.isNotEmpty(generations)){
                    for(Generation generation:generations){
                        AssistantMessage assistantMessage =  generation.getOutput();
                        String content = assistantMessage.getContent();
                        if(StringUtils.isNotEmpty(content)){
                            emitter.send(content);
                        }else{
                            if(StringUtils.equals(content,"null"))
                                emitter.complete(); // Complete the SSE connection
                        }
                    }
                }


            } catch (Exception e) {
                emitter.complete();
                log.error("流式返回结果异常",e);
            }
        });

        return emitter;
    }
}

5.6、核心配置

spring:
  ai:
    openai:
      api-key: sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    ollama:
      base-url: http://localhost:11434
      chat:
        model: qwen:1.8b-chat

5.7、启动类

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

@SpringBootApplication
public class AiApplication {

    public static void main(String[] args) {
        System.setProperty("http.proxyHost","127.0.0.1");
        System.setProperty("http.proxyPort","7078"); // 修改为你代理软件的端口
        System.setProperty("https.proxyHost","127.0.0.1");
        System.setProperty("https.proxyPort","7078"); // 同理

        SpringApplication.run(AiApplication.class, args);
    }

}

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

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

相关文章

HCIA-HarmonyOS设备开发认证V2.0-习题2

目录 习题一习题二坚持就有收获 习题一 # 判断题## 1.PWM占空比指的是低电平时间占周期时间的百分比。(错误)正确(True)错误(False)解题&#xff1a; - PWM占空比指的是高电平时间占周期时间的百分比## 2.UART是通用异步收发传输器&#xff0c;是通用串行数据总线&#xff0c;…

vue router 解决路由带参数跳转时出现404问题

我的页面是从一个vue页面router跳转到另一个vue页面&#xff0c;并且利用windows.open() 浏览器重新创建一个页签。但是不知道为什么有时候可以有时候又不行&#xff0c;经过反复测试与分析&#xff0c;最终发现是因为有一个参数的值里包含了小数点., 小数点是浏览器合法字符&a…

COMSOL热应力仿真

热应力 热膨胀子节点 热膨胀输入类型 假如直接知道热膨胀大小&#xff0c;可以直接对热应变进行赋值。 约束与载荷 对于自由膨胀&#xff0c;可以添加抑制刚体运动。 案例分析 在参数部分&#xff0c;设定体积参考温度Tref&#xff0c;假定在25[degC]模型无热应变。 APP开发器-…

git分布式管理-头歌实验搭建Git服务器

一、Git服务器搭建 任务描述 虽然有提供托管代码服务的公共平台&#xff0c;但是对一部分开发团队来说&#xff0c;为了不泄露项目源代码、节省费用及为项目提供更好的安全保护&#xff0c;往往需要搭建私有Git服务器用做远程仓库。Git服务器为团队的开发者们&#xff0c;提供了…

鸿蒙Harmony应用开发—ArkTS声明式开发(基础手势:ImageSpan)

Text组件的子组件&#xff0c;用于显示行内图片。 说明&#xff1a; 该组件从API Version 10开始支持。后续版本如有新增内容&#xff0c;则采用上角标单独标记该内容的起始版本。 子组件 无 接口 ImageSpan(value: ResourceStr | PixelMap) 参数&#xff1a; 参数名参数类…

ShardingSphere-SQL 解析 Issue 处理流程

ShardingSphere-SQL 解析 Issue 处理流程 这是之前给社区写的 SQL 解析 Issue 的处理流程&#xff0c;可以帮助社区用户快速参与到 ShardingSphere-SQL 解析任务当中。 ShardingSphere SQL 解析 issue 列表 Issue 背景说明 当前 Issue 使用自定义的爬虫脚本从对应的数据库官…

vue2 div滚动条下拉到底部时触发事件(懒加载) 超级简易版本的懒加载

文章目录 导文文章重点内容效果展示&#xff1a;代码展示这些方法适用于哪些场景 总结 导文 vue2 div滚动条下拉到底部时触发事件(懒加载) 超级简易版本的懒加载 文章重点 内容效果展示&#xff1a; 当div拉到底部的时候&#xff1a; 编辑器返回&#xff1a; 代码展示 在…

分享axios+MQTT简单封装示例

MQTT&#xff08;Message Queuing Telemetry Transport&#xff0c;消息队列遥测传输协议&#xff09;&#xff0c;是一种基于发布/订阅&#xff08;publish/subscribe&#xff09;模式的"轻量级"通讯协议&#xff0c;该协议构建于TCP/IP协议上&#xff0c;由IBM在19…

鸿蒙实战开发Camera组件:【相机】

相机组件支持相机业务的开发&#xff0c;开发者可以通过已开放的接口实现相机硬件的访问、操作和新功能开发&#xff0c;最常见的操作如&#xff1a;预览、拍照和录像等。 基本概念 拍照 此功能用于拍摄采集照片。 预览 此功能用于在开启相机后&#xff0c;在缓冲区内重复采集…

IP地址定位技术的主要功能及应用

在互联网时代&#xff0c;IP地址定位技术成为了一项重要的技术&#xff0c;它通过分析用户的IP地址&#xff0c;确定用户的地理位置信息。IP地址定位技术不仅在网络安全、网络管理等领域有着重要的应用&#xff0c;也在商业、广告营销等领域发挥着重要作用。IP数据云将探讨IP地…

【网络层】IP多播技术的相关基本概念(湖科大慕课自学笔记)

IP多播 1&#xff1a;IP多播技术的相关基本概念 我们简单举例&#xff0c;如下图所示&#xff1a; 一共有60个主机要接受来自视频服务器的同一个节目&#xff0c;如果采用单播方式&#xff0c;则视频服务器要发送60份&#xff0c;这些视频节目通过路由器的转发&#xff0c;最…

⎣优化技术⎤CoT-Decoding

微信公众号|人工智能技术派 作 者|hws 一种解码策略优化技术&#xff1a;目标是不需要任何显示的CoT prompting&#xff0c;能够有效提升大型语言模型在各种推理任务中的表现&#xff0c;并通过自发地揭示CoT推理路径&#xff0c;改善模型的推理能力和准确性。 背景介绍 大模…

【Linux基础(四)】管道

学习分享 1、什么是管道2、管道的分类3、管道的特点4、pipe函数&#xff08;匿名管道&#xff09;5、命名管道&#xff1a;FIFO文件5.1、创建一个命名管道5.2、访问一个FIFO文件 6、命名管道示例6.1、写操作示例6.2、读操作示例 7、access函数和mkfifo函数8、删除FIFO文件 1、什…

基于java+springboot+vue实现的宠物健康咨询系统(文末源码+Lw)23-206

摘 要 本宠物健康咨询系统分为管理员还有用户两个权限&#xff0c;管理员可以管理用户的基本信息内容&#xff0c;可以管理公告信息以及宠物健康知识信息&#xff0c;能够与用户进行相互交流等操作&#xff0c;用户可以查看宠物健康知识信息&#xff0c;可以查看公告以及查看…

一个将图片转3D的开源项目TripoSR

TripoSR AI是StabilityAI联合发布的图生3D模型&#xff0c;TripoSR是一个快速的3D物体重建模型。TripoSR能够在不到一秒钟的时间内从单张图片生成高质量的3D模型。TripoSR模型的特点是能够快速处理输入&#xff0c;在 NVIDIA A100 GPU 上不到 0.5 秒的时间内生成高质量的 3D 模…

【STM32+OPENMV】二维云台颜色识别及追踪

一、准备工作 有关OPENMV最大色块追踪及与STM32通信内容&#xff0c;详情见【STM32HAL】与OpenMV通信 有关七针OLED屏显示内容&#xff0c;详情见【STM32HAL】七针OLED(SSD1306)配置(SPI版) 二、所用工具 1、芯片&#xff1a;STM32F407ZGT6 2、CUBEMX配置软件 3、KEIL5 4…

Python和Google Colab进行卫星图像二维小波变化和机器学习

2D 小波分解是图像处理中的一种流行技术,使用不同的滤波器将图像分解为不同的频率分量(“近似”和“细节”系数)。该技术对于各种图像处理任务特别有用,例如压缩、去噪、特征提取和边缘检测。 在本文中,我们将演示如何在 Google Colab 中使用 Python 下载高分辨率样本卫星…

XSS-Labs靶场1---11关

一、XSS环境搭建&#xff1a; [ 靶场环境篇 ] XSS-labs 靶场环境搭建(特别详细)_xss靶场搭建-CSDN博客 &#xff08;该博主总结的较为详细&#xff0c;若侵权必删&#xff09; 常用的xss攻击语句&#xff1a; 输入检测确定标签没有过滤后&#xff0c;为了显示存在漏洞&#…

Vue2 基础二常用特性

代码下载 表单操作 基于Vue的表单操作 input 单行文本textarea 多行文本select 下拉多选&#xff0c;multiple属性实现多选&#xff0c;多选时对应的 data 中的数据也要定义成数组radio 单选框checkbox 多选框&#xff0c;data 中的数据要定义成数组&#xff0c;否则无法实现…

C++ Qt开发:QNetworkInterface网络接口组件

Qt 是一个跨平台C图形界面开发库&#xff0c;利用Qt可以快速开发跨平台窗体应用程序&#xff0c;在Qt中我们可以通过拖拽的方式将不同组件放到指定的位置&#xff0c;实现图形化开发极大的方便了开发效率&#xff0c;本章将重点介绍如何运用QNetworkInterface组件实现查询详细的…