【大模型入门3】通过spring AI实现java调用openai chatGPT(附api-key)

admin 2024年4月19日21:19:15评论6 views字数 9605阅读32分1秒阅读模式

这是一篇大模型的小白入门文章。本章主要介绍如何使用spring AI在java项目中调用openAI chatGPT的接口。其实人工智能的研发是以python为主的,包括机器学习、深度学习和大模型。但我们很多正在运行的业务系统通常是用java开发的,如果想在业务系统中集成AI模型,比较简单的是用微服务的方式来实现,用python提供一个微服务,注册到注册中心,业务系统通过微服务网关来调用。但对于个人开发者或者小团队而言,多种语言的程序维护起来更耗精力,如果能用一种语言来实现则再好不过。

先分享几个openAI账号(来自互联网

登录官方地址:https://chat.openai.com

github不允许上传的代码中包含api-key,8个key一并放在这儿,下载项目后自行修改key

sk-g00T9D0bnScWHtHjldNWT3BlbkFJdVL0Mx0fHPMeOo75uq1Lsk-b9g6k2RvJzrOCP8fFmoTT3BlbkFJU8koHdpQ9p6MUCnbgwpJsk-2lUAjjebOMlldKHXNzszT3BlbkFJIwfOJAtdu4FsBU3wOnINsk-Nz261ZTva2iloIFHWKBZT3BlbkFJrJuGHOj7kL9nXMYR43bBsk-nTs1Iii5fb2RkbLUHBVsT3BlbkFJP9nZProcKdW3aXR3cVcFsk-RuybfBrzyRk27ulmmQ5xT3BlbkFJpcncl3sMfBeB64piY7uusk-okeCGFSU4OXb4D4N1yIhT3BlbkFJ8ziMM6TCvJbHiXnsxtmUsk-jqKVQ9KTDfxvqSqHUI0nT3BlbkFJ0ZBZ55nvaovWaHVnMb3k

01

spring AI简介

Spring AI是一个专为Java开发者设计的AI框架,旨在简化人工智能应用程序的开发过程。它建立在广泛使用的Spring Boot之上,利用其强大的依赖注入和自动配置特性,让开发者无需关心底层细节,专注于业务逻辑。Spring AI提供了丰富的自然语言处理工具、机器学习集成、图像识别和计算机视觉等功能,支持开发人员处理文本数据、执行情感分析、实现语音识别等。此外,它还提供了一个友好的API和开发AI应用的抽象,使得开发基于ChatGPT的对话应用程序等成为可能。

02

环境

JDK:想使用spring AI java版本必须要>=17 ,下载地址如下:

https://www.oracle.com/java/technologies/downloads/#jdk17-windows

如果你本地已经有了JDK8,可以直接再安装JDK17,因为默认安装路径不同可以共存,不用配置环境变量。

maven:maven要求3.6+版本

科学上网工具

03

创建项目

可以使用spring工具来创建项目,地址为

https://start.spring.io/

【大模型入门3】通过spring AI实现java调用openai chatGPT(附api-key)

project选择maven;sprign Boot选择3.2.4版本。dependencies选择ollama、openai等。选好后点击GENERATE下载demo,下载后解压并使用IDEA打开。

【大模型入门3】通过spring AI实现java调用openai chatGPT(附api-key)

配置maven

【大模型入门3】通过spring AI实现java调用openai chatGPT(附api-key)

【大模型入门3】通过spring AI实现java调用openai chatGPT(附api-key)

配置JDK

【大模型入门3】通过spring AI实现java调用openai chatGPT(附api-key)

【大模型入门3】通过spring AI实现java调用openai chatGPT(附api-key)

【大模型入门3】通过spring AI实现java调用openai chatGPT(附api-key)

【大模型入门3】通过spring AI实现java调用openai chatGPT(附api-key)

然后下载maven依赖包

【大模型入门3】通过spring AI实现java调用openai chatGPT(附api-key)

04

Spring AI调用openai接口

OpenAiChatClient.call()接口使用

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;        }        log.info(result);        return result;    }

【大模型入门3】通过spring AI实现java调用openai chatGPT(附api-key)

OpenAiChatClient.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)){                            log.info(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;    }

【大模型入门3】通过spring AI实现java调用openai chatGPT(附api-key)

05

完整代码

完整代码后台回复springai免费获取,获取到项目代码后找到DemoApplication类,右键运行,服务端口为8080。启动后使用工具调用接口即可运行

http://localhost:8080/openAiApi/chathttp://localhost:8080/openAiApi/stream

controller

package com.example.demo.controller;import com.example.demo.service.OpenaiService;import jakarta.servlet.http.HttpServletResponse;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;@RestController@RequestMapping("/openAiApi")public class OpenaiController {    @Autowired    private OpenAiChatClient openAiChatClient;    @Autowired    private OpenaiService openaiService;    @RequestMapping("/chat")    public String chat(){        return openaiService.chat();    }    @RequestMapping("/stream")    public SseEmitter stream(HttpServletResponse response){        return openaiService.stream(response);    }}

service

package com.example.demo.service.impl;import cn.hutool.core.collection.CollUtil;import cn.hutool.core.map.MapUtil;import com.example.demo.service.OpenaiService;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.stereotype.Service;import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;import java.util.List;@Slf4j@Servicepublic class OpenaiServiceImpl implements OpenaiService {    @Autowired    private OpenAiChatClient openAiChatClient;    @Override    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;        }        log.info(result);        return result;    }    @Override    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)){                            log.info(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;    }}

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 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.2.4</version>    <relativePath/>  </parent>  <groupId>com.example</groupId>  <artifactId>demo</artifactId>  <version>0.0.1-SNAPSHOT</version>  <name>demo</name>  <description>Demo project for Spring Boot</description>  <properties>    <java.version>17</java.version>    <spring-ai.version>0.8.1</spring-ai.version>  </properties>  <dependencies>    <dependency>      <groupId>org.springframework.ai</groupId>      <artifactId>spring-ai-ollama-spring-boot-starter</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.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>    <dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-starter-web</artifactId>    </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>jakarta.servlet</groupId>      <artifactId>jakarta.servlet-api</artifactId>      <scope>provided</scope>    </dependency>    <dependency>      <groupId>org.springframework</groupId>      <artifactId>spring-webmvc</artifactId>    </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>  <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>

原文始发于微信公众号(AI与网安):【大模型入门3】通过spring AI实现java调用openai chatGPT(附api-key)

  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2024年4月19日21:19:15
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   【大模型入门3】通过spring AI实现java调用openai chatGPT(附api-key)https://cn-sec.com/archives/2671202.html

发表评论

匿名网友 填写信息