Java SpringBoot 调用大模型 AI 构建 AI 应用
通过本篇文章,我们展示了如何使用调用模型,构建一个基于 AI 的对话系统。这个系统能够根据用户输入的 prompt,生成 AI 响应,解决诸如自动客服、智能问答等问题。使用 SpringBoot 构建 Web 应用。调用外部大模型 AI 提供的 API。使用发起 HTTP 请求并解析 JSON 响应。这种方式可以应用到多种 AI 场景中,如自然语言处理、情感分析、机器翻译等。随着大模型 API 的
随着人工智能(AI)技术的快速发展,越来越多的大型预训练模型(如 GPT-4、BERT、T5 等)被广泛应用于各种实际场景,如自然语言处理、图像识别、语音识别等。借助这些大模型,开发者能够轻松构建各种智能应用,例如智能客服、自动化内容生成、情感分析等。
在这篇文章中,我们将介绍如何使用 Java SpringBoot 框架,调用一个大模型 AI,构建一个智能应用。我们将通过调用 OpenAI API(以 GPT-3 或 GPT-4 为例)来实现一个简单的对话系统。
一、准备工作
- SpringBoot 环境搭建:如果你还没有安装 SpringBoot 环境,可以参考 Spring 官方文档进行搭建。
- OpenAI API:我们将调用 OpenAI 的 GPT API,首先需要到 OpenAI 官方网站 注册并获取 API 密钥。
- Maven 依赖:我们将使用
RestTemplate或WebClient来调用 OpenAI 的 HTTP API。
二、创建 SpringBoot 项目
-
使用 Spring Initializr 创建项目
在 Spring Initializr 中创建一个 Spring Boot 项目,选择以下选项:
- Project: Maven Project
- Language: Java
- Spring Boot: 2.x.x
- Dependencies: Spring Web, Spring Boot DevTools
-
添加必要的 Maven 依赖
打开
pom.xml文件,添加Spring Web和Jackson依赖(用于 JSON 解析):<dependencies> <!-- Spring Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Jackson JSON Library --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> <!-- Spring Boot DevTools (Optional for Development) --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> </dependency> </dependencies> -
配置 OpenAI API 密钥
在项目的
application.properties文件中,添加 OpenAI 的 API 密钥:openai.api.key=YOUR_API_KEY_HERE
三、创建服务类调用 OpenAI API
-
创建 OpenAI 服务类
我们将创建一个
OpenAIService类,负责与 OpenAI 的 GPT 模型进行交互。使用RestTemplate发送 HTTP 请求,并处理返回的 JSON 数据。package com.example.aiapp.service; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import org.springframework.http.*; import com.fasterxml.jackson.databind.JsonNode; import java.util.HashMap; import java.util.Map; @Service public class OpenAIService { @Value("${openai.api.key}") private String apiKey; private static final String API_URL = "https://api.openai.com/v1/completions"; // RestTemplate 用于发送请求 private final RestTemplate restTemplate; public OpenAIService(RestTemplate restTemplate) { this.restTemplate = restTemplate; } // 调用 OpenAI API 获取 GPT-3 或 GPT-4 响应 public String generateResponse(String prompt) { // 构建请求体 Map<String, Object> body = new HashMap<>(); body.put("model", "text-davinci-003"); // 或 "gpt-4" body.put("prompt", prompt); body.put("max_tokens", 150); body.put("temperature", 0.7); HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", "Bearer " + apiKey); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<Map<String, Object>> entity = new HttpEntity<>(body, headers); // 发送 POST 请求 ResponseEntity<JsonNode> response = restTemplate.exchange( API_URL, HttpMethod.POST, entity, JsonNode.class); // 获取 GPT 返回的响应 if (response.getStatusCode() == HttpStatus.OK) { JsonNode choices = response.getBody().get("choices"); return choices.get(0).get("text").asText().trim(); } else { throw new RuntimeException("OpenAI API request failed with status: " + response.getStatusCode()); } } }说明:
- 通过
@Value注解获取application.properties中的 API 密钥。 - 构建一个 HTTP 请求体,将
prompt、model、max_tokens、temperature等参数传递给 OpenAI API。 - 使用
RestTemplate发送 POST 请求,并接收返回的 JSON 响应。 - 在返回的 JSON 数据中提取
choices字段的text值,即 AI 生成的回答。
- 通过
-
配置 RestTemplate Bean
我们需要创建一个
RestTemplateBean 来进行 HTTP 请求的发送。package com.example.aiapp.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; @Configuration public class AppConfig { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } }
四、创建控制器类暴露接口
我们将创建一个控制器类 AIController,为前端提供一个接口,用户可以通过这个接口发送文本并获取 AI 生成的回复。
package com.example.aiapp.controller;
import com.example.aiapp.service.OpenAIService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/ai")
public class AIController {
private final OpenAIService openAIService;
@Autowired
public AIController(OpenAIService openAIService) {
this.openAIService = openAIService;
}
// 处理用户请求,获取 AI 响应
@PostMapping("/chat")
public String chatWithAI(@RequestBody String prompt) {
return openAIService.generateResponse(prompt);
}
}
说明:
@PostMapping("/chat"):通过 POST 请求接收用户输入的文本(即 prompt)。- 调用
OpenAIService的generateResponse方法获取 AI 返回的结果,并将其作为响应返回。
五、启动应用并测试
-
启动 Spring Boot 应用
使用 IDE 启动 Spring Boot 应用,或者通过命令行运行:
mvn spring-boot:run -
测试接口
使用 Postman 或 cURL 发送请求测试接口:
请求 URL:
http://localhost:8080/api/ai/chat请求方式: POST
请求体(JSON 格式):
"What is the weather like today?"响应:
"The weather today is sunny with a high of 25°C."
六、总结
通过本篇文章,我们展示了如何使用 Java SpringBoot 调用 OpenAI GPT-3/4 模型,构建一个基于 AI 的对话系统。这个系统能够根据用户输入的 prompt,生成 AI 响应,解决诸如自动客服、智能问答等问题。
本示例展示了如何:
- 使用 SpringBoot 构建 Web 应用。
- 调用外部大模型 AI 提供的 API。
- 使用
RestTemplate发起 HTTP 请求并解析 JSON 响应。
这种方式可以应用到多种 AI 场景中,如自然语言处理、情感分析、机器翻译等。随着大模型 API 的普及,开发者可以轻松地构建智能化的应用,提升产品的智能化水平。
火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。
更多推荐
所有评论(0)