以下是 Java 中调用语言模型(如 OpenAI、阿里云通义千问、Hugging Face 等)API 的详细步骤和示例代码,涵盖常见场景及注意事项:
使用 HttpClient
或第三方库(如 Unirest
)发送 HTTP 请求:
<dependency>
<groupId>com.mashape.unirestgroupId>
<artifactId>unirest-javaartifactId>
<version>1.1.10version>
dependency>
// 示例:OpenAI API 密钥
String OPENAI_API_KEY = "sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
String OPENAI_API_URL = "https://api.openai.com/v1/completions";
import kong.unirest.*;
import java.util.HashMap;
import java.util.Map;
public class OpenAIExample {
public static void main(String[] args) {
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("model", "text-davinci-003");
requestBody.put("prompt", "写一个关于夏天的诗歌。");
requestBody.put("max_tokens", 50);
requestBody.put("temperature", 0.7);
HttpResponse<String> response = Unirest.post(OPENAI_API_URL)
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + OPENAI_API_KEY)
.body(requestBody)
.asString();
if (response.getStatus() == 200) {
System.out.println("响应:" + response.getBody());
} else {
System.err.println("错误:" + response.getStatusText());
}
}
}
// 需要阿里云 SDK 或直接调用 REST API
// 示例:通过 HTTP 请求调用通义千问(需替换参数)
String ALIYUN_API_URL = "https://dashscope.aliyun.com/api/v1/services/aigc/text-generation/generation";
String ALIYUN_API_KEY = "your-aliyun-api-key";
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("text", "请生成一个关于夏天的诗歌。");
requestBody.put("max_length", 100);
HttpResponse<String> response = Unirest.post(ALIYUN_API_URL)
.header("Authorization", "APPCODE " + ALIYUN_API_KEY)
.header("Content-Type", "application/json")
.body(requestBody)
.asString();
// 处理响应...
String HUGGINGFACE_API_URL = "https://api-inference.huggingface.co/models/gpt2";
String HUGGINGFACE_API_KEY = "your-huggingface-api-key";
Map<String, String> requestBody = new HashMap<>();
requestBody.put("inputs", "写一个关于夏天的诗歌。");
requestBody.put("options", "{\"max_length\": 50}");
HttpResponse<String> response = Unirest.post(HUGGINGFACE_API_URL)
.header("Authorization", "Bearer " + HUGGINGFACE_API_KEY)
.header("Content-Type", "application/json")
.body(requestBody)
.asString();
// 示例:解析 OpenAI 的响应
JSONObject jsonResponse = new JSONObject(response.getBody());
JSONArray choices = jsonResponse.getJSONArray("choices");
if (choices.length() > 0) {
String generatedText = choices.getJSONObject(0).getString("text");
System.out.println("生成内容:" + generatedText);
} else {
System.out.println("无结果返回。");
}
if (response.getStatus() != 200) {
JSONObject errorObj = new JSONObject(response.getBody());
String errorMessage = errorObj.optString("error", "未知错误");
throw new RuntimeException("API 调用失败:" + errorMessage);
}
参数 | 作用 |
---|---|
model |
指定使用的模型(如 text-davinci-003 、gpt-3.5-turbo )。 |
prompt |
输入提示文本,模型根据此生成内容。 |
max_tokens |
限制生成文本的最长 token 数(影响输出长度)。 |
temperature |
控制输出的随机性(0 表示确定性,1 表示高随机性)。 |
stop |
指定生成停止的标记(如 \\n )。 |
部分 API 支持流式返回生成内容(如 OpenAI 的 stream
参数):
// OpenAI 流式响应示例(需使用低层 HttpClient)
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(OPENAI_API_URL))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + OPENAI_API_KEY)
.POST(BodyPublishers.ofString(requestBody.toString()))
.build();
HttpClient.newHttpClient().sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println);
使用 Docker 部署本地模型(如 llama.cpp
):
docker run -p 8000:8000 -it --rm ghcr.io/codai/llama-cpp-serve:latest
Java 调用本地服务:
String LOCAL_MODEL_URL = "http://localhost:8000/complete";
// 发送请求逻辑与之前相同
requestBody.put("prompt", "写一个关于人工智能的科普文章。");
requestBody.put("prompt", "量子计算的基本原理是什么?");
requestBody.put("prompt", "分类这条评论是正面还是负面:'这个产品非常棒!'");
Java 调用语言模型 API 的核心步骤是:
对于复杂需求(如流式处理、模型微调),需参考具体 API 文档或使用框架(如 LangChain
)。注意安全性和性能优化,避免直接暴露 API 密钥。