以下是 Java 中调用语言模型(如 OpenAI、阿里云通义千问、Hugging Face 等)API 的详细步骤和示例代码,涵盖常见场景及注意事项:
1. 常见语言模型 API 选择
(1) OpenAI API
- 特点:支持 GPT-3、GPT-3.5、GPT-4 等模型,功能全面。
- 官网:https://platform.openai.com/docs/api-reference
(2) 阿里云通义千问
- 特点:阿里云的超大规模语言模型,支持多语言和多种任务。
- 官网:https://help.aliyun.com/zh/nlp/developer-reference/tae
(3) Hugging Face
- 特点:开源模型丰富,支持自定义模型部署。
- 官网:https://huggingface.co/docs/api-inference/detailed_parameters
2. Java 调用语言模型 API 的通用步骤
步骤 1:添加依赖
使用 HttpClient
或第三方库(如 Unirest
)发送 HTTP 请求:
<!-- Maven 依赖示例(使用 Unirest) -->
<dependency>
<groupId>com.mashape.unirest</groupId>
<artifactId>unirest-java</artifactId>
<version>1.1.10</version>
</dependency>
步骤 2:配置 API 密钥
// 示例:OpenAI API 密钥
String OPENAI_API_KEY = "sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
String OPENAI_API_URL = "https://api.openai.com/v1/completions";
步骤 3:构建请求并调用
(1) OpenAI API 示例
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());
}
}
}
(2) 阿里云通义千问 API 示例
// 需要阿里云 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();
// 处理响应...
(3) Hugging Face API 示例
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();
3. 响应解析与错误处理
(1) 解析 JSON 响应
// 示例:解析 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("无结果返回。");
}
(2) 错误处理
if (response.getStatus() != 200) {
JSONObject errorObj = new JSONObject(response.getBody());
String errorMessage = errorObj.optString("error", "未知错误");
throw new RuntimeException("API 调用失败:" + errorMessage);
}
4. 关键参数说明
参数 | 作用 |
---|---|
model |
指定使用的模型(如 text-davinci-003 、gpt-3.5-turbo )。 |
prompt |
输入提示文本,模型根据此生成内容。 |
max_tokens |
限制生成文本的最长 token 数(影响输出长度)。 |
temperature |
控制输出的随机性(0 表示确定性,1 表示高随机性)。 |
stop |
指定生成停止的标记(如 \\n )。 |
5. 高级场景与优化
(1) 流式响应(Streaming)
部分 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);
(2) 认证与安全
- API 密钥管理:使用环境变量或配置文件存储密钥,避免硬编码。
- HTTPS 安全:确保所有请求使用 HTTPS。
- 速率限制:遵守 API 的 QPS 限制,避免被封禁。
(3) 自定义模型部署
使用 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"; // 发送请求逻辑与之前相同
6. 典型应用场景
(1) 文本生成
- 场景:生成文章、诗歌、代码注释。
- 示例:
requestBody.put("prompt", "写一个关于人工智能的科普文章。");
(2) 问答系统
- 场景:构建智能客服或知识库问答。
- 示例:
requestBody.put("prompt", "量子计算的基本原理是什么?");
(3) 文本分类
- 场景:情感分析、垃圾邮件过滤。
- 示例:
requestBody.put("prompt", "分类这条评论是正面还是负面:'这个产品非常棒!'");
7. 总结
Java 调用语言模型 API 的核心步骤是:
- 选择合适的 API 服务(根据需求和预算)。
- 发送 HTTP 请求(使用 Unirest 或原生 HttpClient)。
- 处理响应并集成到业务逻辑。
对于复杂需求(如流式处理、模型微调),需参考具体 API 文档或使用框架(如 LangChain
)。注意安全性和性能优化,避免直接暴露 API 密钥。