本文目录导读:

我来为您提供几个Java调用大模型(如OpenAI、百度文心、阿里通义千问等)的完整案例。
调用OpenAI GPT模型(最通用)
添加Maven依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.12.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>
基础调用示例
import okhttp3.*;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
public class OpenAIClient {
private static final String API_KEY = "your-openai-api-key";
private static final String API_URL = "https://api.openai.com/v1/chat/completions";
public static void main(String[] args) {
try {
String response = callGPT("用中文介绍一下Java语言");
System.out.println("AI响应: " + response);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String callGPT(String prompt) throws IOException {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(30, java.util.concurrent.TimeUnit.SECONDS)
.readTimeout(60, java.util.concurrent.TimeUnit.SECONDS)
.build();
// 构建请求体
JsonObject requestBody = new JsonObject();
requestBody.addProperty("model", "gpt-3.5-turbo");
JsonObject message = new JsonObject();
message.addProperty("role", "user");
message.addProperty("content", prompt);
requestBody.add("messages", JsonParser.parseString(
"[{\"role\":\"user\",\"content\":\"" + prompt + "\"}]"
));
RequestBody body = RequestBody.create(
MediaType.parse("application/json"),
requestBody.toString()
);
Request request = new Request.Builder()
.url(API_URL)
.header("Authorization", "Bearer " + API_KEY)
.header("Content-Type", "application/json")
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("API调用失败: " + response.code());
}
String jsonResponse = response.body().string();
// 解析返回的JSON
JsonObject jsonObject = JsonParser.parseString(jsonResponse).getAsJsonObject();
return jsonObject.getAsJsonArray("choices")
.get(0).getAsJsonObject()
.get("message").getAsJsonObject()
.get("content").getAsString();
}
}
}
带流式输出的高级版本
import okhttp3.*;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class OpenAIStreamClient {
private static final String API_KEY = "your-openai-api-key";
public static void main(String[] args) {
try {
streamCall("写一首关于春天的诗");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void streamCall(String prompt) throws Exception {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(30, java.util.concurrent.TimeUnit.SECONDS)
.readTimeout(0, java.util.concurrent.TimeUnit.SECONDS) // 无超时
.build();
// 构建请求体
JsonObject requestBody = new JsonObject();
requestBody.addProperty("model", "gpt-3.5-turbo");
requestBody.addProperty("stream", true);
JsonObject message = new JsonObject();
message.addProperty("role", "user");
message.addProperty("content", prompt);
requestBody.add("messages", JsonParser.parseString(
"[{\"role\":\"user\",\"content\":\"" + prompt + "\"}]"
));
RequestBody body = RequestBody.create(
MediaType.parse("application/json"),
requestBody.toString()
);
Request request = new Request.Builder()
.url("https://api.openai.com/v1/chat/completions")
.header("Authorization", "Bearer " + API_KEY)
.header("Content-Type", "application/json")
.post(body)
.build();
// 流式处理
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
System.err.println("请求失败: " + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) {
System.err.println("请求失败: " + response.code());
return;
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(response.body().byteStream())
);
String line;
while ((line = reader.readLine()) != null) {
if (line.startsWith("data: ")) {
String data = line.substring(6);
if ("[DONE]".equals(data)) {
break;
}
try {
JsonObject jsonObject = JsonParser.parseString(data).getAsJsonObject();
String content = jsonObject.getAsJsonArray("choices")
.get(0).getAsJsonObject()
.getAsJsonObject("delta")
.get("content")
.getAsString();
System.out.print(content); // 流式输出
} catch (Exception e) {
// 跳过结尾标记
}
}
}
}
});
// 等待流式输出完成
Thread.sleep(10000);
}
}
调用百度文心一言
import okhttp3.*;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class BaiduWenxinClient {
private static final String API_KEY = "your-baidu-api-key";
private static final String SECRET_KEY = "your-baidu-secret-key";
public static void main(String[] args) {
try {
String accessToken = getAccessToken();
String response = callWenxin(accessToken, "用中文介绍Java编程语言");
System.out.println("文心一言响应: " + response);
} catch (Exception e) {
e.printStackTrace();
}
}
// 获取Access Token
private static String getAccessToken() throws IOException {
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(
MediaType.parse("application/x-www-form-urlencoded"),
"grant_type=client_credentials&client_id=" + API_KEY +
"&client_secret=" + SECRET_KEY
);
Request request = new Request.Builder()
.url("https://aip.baidubce.com/oauth/2.0/token")
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
String json = response.body().string();
JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();
return jsonObject.get("access_token").getAsString();
}
}
// 调用文心一言API
private static String callWenxin(String accessToken, String prompt) throws IOException {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(30, java.util.concurrent.TimeUnit.SECONDS)
.readTimeout(60, java.util.concurrent.TimeUnit.SECONDS)
.build();
JsonObject requestBody = new JsonObject();
requestBody.addProperty("messages", "[{\"role\":\"user\",\"content\":\"" + prompt + "\"}]");
RequestBody body = RequestBody.create(
MediaType.parse("application/json"),
requestBody.toString()
);
Request request = new Request.Builder()
.url("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=" + accessToken)
.header("Content-Type", "application/json")
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
String jsonResponse = response.body().string();
JsonObject jsonObject = JsonParser.parseString(jsonResponse).getAsJsonObject();
return jsonObject.get("result").getAsString();
}
}
}
调用阿里通义千问
import okhttp3.*;
import com.google.gson.*;
public class TongyiQwenClient {
private static final String API_KEY = "your-dashscope-api-key";
public static void main(String[] args) {
try {
String response = callQwen("用Java写一个Hello World程序");
System.out.println("通义千问响应: " + response);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String callQwen(String prompt) throws IOException {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(30, java.util.concurrent.TimeUnit.SECONDS)
.readTimeout(60, java.util.concurrent.TimeUnit.SECONDS)
.build();
// 构建请求体
JsonObject requestBody = new JsonObject();
requestBody.addProperty("model", "qwen-turbo");
JsonObject input = new JsonObject();
input.addProperty("prompt", prompt);
requestBody.add("input", input);
JsonObject parameters = new JsonObject();
parameters.addProperty("temperature", 0.8);
parameters.addProperty("top_p", 0.8);
requestBody.add("parameters", parameters);
RequestBody body = RequestBody.create(
MediaType.parse("application/json"),
requestBody.toString()
);
Request request = new Request.Builder()
.url("https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation")
.header("Authorization", "Bearer " + API_KEY)
.header("Content-Type", "application/json")
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
String jsonResponse = response.body().string();
JsonObject jsonObject = JsonParser.parseString(jsonResponse).getAsJsonObject();
return jsonObject.getAsJsonObject("output").get("text").getAsString();
}
}
}
通用大模型调用工具类
import okhttp3.*;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.util.concurrent.TimeUnit;
public class AIModelClient {
private static final OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.build();
// 通用调用方法
public static String callAI(String url, String apiKey, String model, String prompt) throws Exception {
JsonObject requestBody = new JsonObject();
requestBody.addProperty("model", model);
JsonObject message = new JsonObject();
message.addProperty("role", "user");
message.addProperty("content", prompt);
requestBody.add("messages", JsonParser.parseString(
"[{\"role\":\"user\",\"content\":\"" + prompt + "\"}]"
));
RequestBody body = RequestBody.create(
MediaType.parse("application/json"),
requestBody.toString()
);
Request request = new Request.Builder()
.url(url)
.header("Authorization", "Bearer " + apiKey)
.header("Content-Type", "application/json")
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new Exception("API调用失败: " + response.code());
}
String jsonResponse = response.body().string();
JsonObject jsonObject = JsonParser.parseString(jsonResponse).getAsJsonObject();
// 通用解析逻辑(根据实际API调整)
return jsonObject.getAsJsonArray("choices")
.get(0).getAsJsonObject()
.get("message").getAsJsonObject()
.get("content").getAsString();
}
}
// 使用示例
public static void main(String[] args) {
try {
String response = callAI(
"https://api.openai.com/v1/chat/completions",
"your-api-key",
"gpt-3.5-turbo",
"用Java实现一个单例模式"
);
System.out.println("AI响应: " + response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用建议
- API Key管理:建议使用环境变量或配置文件存储API Key
- 错误处理:添加重试机制和更好的错误处理
- 流式处理:对长文本回复使用流式API
- 限流控制:注意API调用频率限制
- 成本控制:监控API使用量和费用
这些案例涵盖了主流大模型的调用方式,您可以根据需要选择使用,注意替换代码中的API Key为实际的值。