Ollama 已部署DeepSeek模型,如果用Java语言实现调用
String result = client.generate("deepseek", "解释量子纠缠", 0.8, 1000);System.err.println("JSON 解析错误: " + e.getMessage());System.out.println("模型回复:\n" + response);System.err.println("网络错误: " + e.getMessage(
·
以下是使用 Java 调用 Ollama 部署的 DeepSeek 模型的详细方法:
1. 通过 HTTP API 调用(推荐)
Ollama 提供了 RESTful API,可以用 Java 的 HTTP 客户端库(如 OkHttp)直接调用。
步骤 1:添加依赖
在 Maven 项目的 pom.xml 中添加:
xml
复制
<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> <!-- 用于 JSON 解析 -->
</dependency>
运行 HTML
步骤 2:完整示例代码
java
复制
import okhttp3.*;
import com.google.gson.Gson;
import java.io.IOException;
public class OllamaDeepSeekClient {
private static final String OLLAMA_URL = "http://localhost:11434/api/generate";
private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
private static final Gson gson = new Gson();
static class RequestBodyData {
String model = "deepseek"; // 确认模型名称
String prompt;
boolean stream = false; // 关闭流式输出(默认)
Options options = new Options();
static class Options {
double temperature = 0.7; // 随机性控制
int num_predict = 500; // 最大 token 数
}
}
public static String generateText(String prompt) throws IOException {
OkHttpClient client = new OkHttpClient();
// 构建请求体
RequestBodyData requestBodyData = new RequestBodyData();
requestBodyData.prompt = prompt;
String json = gson.toJson(requestBodyData);
RequestBody body = RequestBody.create(json, JSON);
Request request = new Request.Builder()
.url(OLLAMA_URL)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code: " + response);
}
return response.body().string();
}
}
public static void main(String[] args) {
try {
String response = generateText("为什么天空是蓝色的?");
System.out.println("模型回复:\n" + response);
} catch (IOException e) {
e.printStackTrace();
}
}
}
输出示例:
json
复制
{
"model": "deepseek",
"created_at": "2024-05-01T12:34:56.789Z",
"response": "天空呈现蓝色是由于瑞利散射现象...",
"done": true
}
2. 流式输出处理
如果需要实时获取生成结果(类似 ChatGPT 的逐字输出),启用流式模式:
修改代码:
java
复制
// 修改请求体
requestBodyData.stream = true; // 启用流式
// 处理流式响应
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code: " + response);
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(response.body().byteStream())
);
String line;
while ((line = reader.readLine()) != null) {
System.out.println("收到片段: " + line);
}
}
3. 高级功能封装
可以进一步封装为工具类:
java
复制
public class OllamaClient {
private final OkHttpClient client;
private final String baseUrl;
private final Gson gson = new Gson();
public OllamaClient(String baseUrl) {
this.client = new OkHttpClient();
this.baseUrl = baseUrl;
}
public String generate(String model, String prompt, double temperature, int maxTokens)
throws IOException {
// 构建请求体
JsonObject jsonBody = new JsonObject();
jsonBody.addProperty("model", model);
jsonBody.addProperty("prompt", prompt);
jsonBody.addProperty("stream", false);
JsonObject options = new JsonObject();
options.addProperty("temperature", temperature);
options.addProperty("num_predict", maxTokens);
jsonBody.add("options", options);
RequestBody body = RequestBody.create(
jsonBody.toString(),
MediaType.get("application/json")
);
Request request = new Request.Builder()
.url(baseUrl + "/api/generate")
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
}
// 使用示例
OllamaClient client = new OllamaClient("http://localhost:11434");
String result = client.generate("deepseek", "解释量子纠缠", 0.8, 1000);
4. 注意事项
-
服务验证:确保 Ollama 服务正在运行
bash
复制
curl http://localhost:11434 # 验证服务状态
-
性能优化:
-
使用连接池:
new OkHttpClient.Builder().connectionPool(...) -
添加超时设置:
.callTimeout(30, TimeUnit.SECONDS)
-
-
错误处理:
java
复制
try { // API 调用代码 } catch (IOException e) { System.err.println("网络错误: " + e.getMessage()); } catch (JsonSyntaxException e) { System.err.println("JSON 解析错误: " + e.getMessage()); }
完整项目结构建议
复制
src/ ├── main/ │ ├── java/ │ │ └── com/ │ │ └── yourcompany/ │ │ ├── OllamaClient.java # 核心客户端 │ │ ├── models/ # 数据模型 │ │ └── exceptions/ # 自定义异常 │ └── resources/ └── test/ # 单元测试
通过这种方式,你可以将 Ollama 的 DeepSeek 模型集成到任何 Java 应用中,包括 Spring Boot 服务、桌面应用等。
更多推荐


所有评论(0)