本文目录导读:

我来为您提供一个Java调用ChatGPT的完整案例。
Maven依赖配置
<dependencies>
<!-- OkHttp 用于HTTP请求 -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.12.0</version>
</dependency>
<!-- Jackson 用于JSON处理 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.16.1</version>
</dependency>
<!-- Lombok 简化代码(可选) -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.30</version>
<scope>provided</scope>
</dependency>
</dependencies>
ChatGPT请求模型类
import lombok.Data;
import java.util.List;
@Data
public class ChatRequest {
private String model;
private List<Message> messages;
private double temperature = 0.7;
private int max_tokens = 2000;
@Data
public static class Message {
private String role;
private String content;
public Message(String role, String content) {
this.role = role;
this.content = content;
}
}
}
ChatGPT响应模型类
import lombok.Data;
import java.util.List;
@Data
public class ChatResponse {
private String id;
private String object;
private long created;
private String model;
private List<Choice> choices;
private Usage usage;
@Data
public static class Choice {
private int index;
private Message message;
private String finish_reason;
@Data
public static class Message {
private String role;
private String content;
}
}
@Data
public static class Usage {
private int prompt_tokens;
private int completion_tokens;
private int total_tokens;
}
}
ChatGPT客户端实现
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class ChatGPTClient {
private static final String API_URL = "https://api.openai.com/v1/chat/completions";
private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
private final String apiKey;
private final OkHttpClient httpClient;
private final ObjectMapper objectMapper;
public ChatGPTClient(String apiKey) {
this.apiKey = apiKey;
this.httpClient = new OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.build();
this.objectMapper = new ObjectMapper();
}
/**
* 发送消息到ChatGPT
* @param messages 消息列表
* @param model 模型名称(如:gpt-3.5-turbo, gpt-4)
* @return ChatGPT的响应内容
*/
public String sendMessage(List<ChatRequest.Message> messages, String model) throws IOException {
ChatRequest request = new ChatRequest();
request.setModel(model);
request.setMessages(messages);
String jsonRequest = objectMapper.writeValueAsString(request);
RequestBody body = RequestBody.create(jsonRequest, JSON);
Request httpRequest = new Request.Builder()
.url(API_URL)
.addHeader("Authorization", "Bearer " + apiKey)
.addHeader("Content-Type", "application/json")
.post(body)
.build();
try (Response response = httpClient.newCall(httpRequest).execute()) {
if (!response.isSuccessful()) {
throw new IOException("API请求失败: " + response.code() + " " + response.body().string());
}
String responseBody = response.body().string();
ChatResponse chatResponse = objectMapper.readValue(responseBody, ChatResponse.class);
if (chatResponse.getChoices() != null && !chatResponse.getChoices().isEmpty()) {
return chatResponse.getChoices().get(0).getMessage().getContent();
}
return "没有获取到响应";
}
}
/**
* 简单的发送消息方法(单条消息)
*/
public String ask(String question, String model) throws IOException {
List<ChatRequest.Message> messages = new ArrayList<>();
messages.add(new ChatRequest.Message("user", question));
return sendMessage(messages, model);
}
/**
* 带上下文的对话方法
*/
public String chat(List<ChatRequest.Message> conversation, String model) throws IOException {
return sendMessage(conversation, model);
}
}
使用示例
1 基础用法
public class ChatGPTExample {
public static void main(String[] args) {
// 替换为你的API密钥
String apiKey = "your-api-key-here";
ChatGPTClient client = new ChatGPTClient(apiKey);
try {
// 简单的问答
String response = client.ask("Java中什么是Stream API?", "gpt-3.5-turbo");
System.out.println("ChatGPT回答:");
System.out.println(response);
} catch (IOException e) {
System.err.println("请求失败: " + e.getMessage());
e.printStackTrace();
}
}
}
2 带上下文的对话
public class ConversationExample {
public static void main(String[] args) {
String apiKey = "your-api-key-here";
ChatGPTClient client = new ChatGPTClient(apiKey);
try {
List<ChatRequest.Message> conversation = new ArrayList<>();
// 添加对话历史
conversation.add(new ChatRequest.Message("system",
"你是一位专业的Java编程导师,请用中文回答"));
conversation.add(new ChatRequest.Message("user",
"什么是Java中的多态?"));
String response1 = client.chat(conversation, "gpt-3.5-turbo");
System.out.println("回答1: " + response1);
// 添加助手的回复到上下文
conversation.add(new ChatRequest.Message("assistant", response1));
conversation.add(new ChatRequest.Message("user",
"能给我一个具体的代码例子吗?"));
String response2 = client.chat(conversation, "gpt-3.5-turbo");
System.out.println("回答2: " + response2);
} catch (IOException e) {
System.err.println("请求失败: " + e.getMessage());
e.printStackTrace();
}
}
}
3 流式响应(Stream)
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.BufferedSource;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class StreamExample {
public static void main(String[] args) {
String apiKey = "your-api-key-here";
// OkHttp客户端配置
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(0, TimeUnit.SECONDS) // 流式响应超时时间设置为0
.build();
try {
// 构建请求体(启用流式响应)
String requestBody = "{\n" +
" \"model\": \"gpt-3.5-turbo\",\n" +
" \"messages\": [{\"role\": \"user\", \"content\": \"用Java写一个冒泡排序\"}],\n" +
" \"stream\": true\n" +
"}";
Request request = new Request.Builder()
.url("https://api.openai.com/v1/chat/completions")
.addHeader("Authorization", "Bearer " + apiKey)
.addHeader("Content-Type", "application/json")
.post(RequestBody.create(requestBody, MediaType.parse("application/json")))
.build();
Response response = client.newCall(request).execute();
ResponseBody body = response.body();
if (body != null) {
BufferedSource source = body.source();
while (!source.exhausted()) {
String line = source.readUtf8Line();
if (line != null && !line.isEmpty() && line.startsWith("data: ")) {
String data = line.substring(6); // 去掉 "data: " 前缀
if (!"[DONE]".equals(data)) {
// 解析流式响应数据
// 这里可以处理接收到的部分响应
System.out.println("接收到数据片段: " + data);
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
配置文件示例(application.properties)
# ChatGPT配置 chatgpt.api.key=your-api-key-here chatgpt.model=gpt-3.5-turbo chatgpt.temperature=0.7 chatgpt.max.tokens=2000 chatgpt.timeout=60
Spring Boot集成示例
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class ChatGPTService {
@Value("${chatgpt.api.key}")
private String apiKey;
@Value("${chatgpt.model}")
private String model;
private final ChatGPTClient client;
public ChatGPTService() {
this.client = new ChatGPTClient(apiKey);
}
public String askQuestion(String question) {
try {
return client.ask(question, model);
} catch (IOException e) {
throw new RuntimeException("ChatGPT API调用失败", e);
}
}
public String chatWithContext(List<ChatRequest.Message> conversation) {
try {
return client.chat(conversation, model);
} catch (IOException e) {
throw new RuntimeException("ChatGPT API调用失败", e);
}
}
}
// Controller
@RestController
@RequestMapping("/api/chat")
public class ChatController {
@Autowired
private ChatGPTService chatGPTService;
@PostMapping("/ask")
public ResponseEntity<?> ask(@RequestBody String question) {
try {
String answer = chatGPTService.askQuestion(question);
return ResponseEntity.ok(answer);
} catch (Exception e) {
return ResponseEntity.status(500).body("Error: " + e.getMessage());
}
}
@PostMapping("/conversation")
public ResponseEntity<?> conversation(@RequestBody List<Map<String, String>> messages) {
try {
List<ChatRequest.Message> conversation = new ArrayList<>();
for (Map<String, String> msg : messages) {
conversation.add(new ChatRequest.Message(
msg.get("role"),
msg.get("content")
));
}
String answer = chatGPTService.chatWithContext(conversation);
return ResponseEntity.ok(answer);
} catch (Exception e) {
return ResponseEntity.status(500).body("Error: " + e.getMessage());
}
}
}
注意事项
- API密钥安全:不要把API密钥硬编码在代码中,建议使用环境变量或配置中心
- 错误处理:合理处理网络异常、API限制等错误情况
- 速率限制:注意OpenAI API的速率限制,必要时添加重试机制
- 费用控制:监控API使用量,设置合理的max_tokens限制
- 数据安全:注意不要向API发送敏感信息
这个案例提供了完整的Java调用ChatGPT的实现,包括基础调用、上下文对话和流式响应等功能,根据实际需求可以进行调整和优化。