当前位置: 首页 > news >正文

Java: 简单本地调用deepseek-r1:1.5b 模型 using JDK 21

 

/*** 版权所有 2021 涂聚文有限公司* 许可信息查看: 言語成了邀功盡責的功臣,還需要行爲每日來值班嗎* 描述:DB 数据库帮助,连接SQL Server,Oracle,PostgreSQL,MySQL,SQLite,neo4j* 数据库:MS SQL Server 2019* IDE: IntelliJ IDEA 2025.1.3* OS: Windows 10 x64* 历史版本:  JDK 21* author: Geovin Du 涂聚文,geovindu*/import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;public class Main {// Default Ollama API URLprivate static final String OLLAMA_API_URL = "http://localhost:11434/api/chat";// Model name - change this if your local model has a different tagprivate static final String MODEL_NAME = "deepseek-r1:1.5b";public static void main(String[] args) {System.out.println("Connecting to Ollama (" + MODEL_NAME + ")...");System.out.println("Type 'exit' or 'quit' to end the chat.");HttpClient client = HttpClient.newHttpClient();ObjectMapper mapper = new ObjectMapper();Scanner scanner = new Scanner(System.in);// Chat historyArrayNode messages = mapper.createArrayNode();while (true) {System.out.print("\nYou: ");String userInput = scanner.nextLine();if ("exit".equalsIgnoreCase(userInput) || "quit".equalsIgnoreCase(userInput)) {System.out.println("Goodbye!");break;}if (userInput.trim().isEmpty()) {continue;}// Add user message to historyObjectNode userMessage = mapper.createObjectNode();userMessage.put("role", "user");userMessage.put("content", userInput);messages.add(userMessage);// Prepare request bodyObjectNode requestBody = mapper.createObjectNode();requestBody.put("model", MODEL_NAME);requestBody.set("messages", messages);requestBody.put("stream", true); // Enable streamingtry {String jsonRequest = mapper.writeValueAsString(requestBody);HttpRequest request = HttpRequest.newBuilder().uri(URI.create(OLLAMA_API_URL)).header("Content-Type", "application/json").POST(HttpRequest.BodyPublishers.ofString(jsonRequest)).build();System.out.print("AI: ");// Send request and handle streaming responseclient.sendAsync(request, HttpResponse.BodyHandlers.ofInputStream()).thenAccept(response -> {if (response.statusCode() != 200) {System.err.println("\nError: " + response.statusCode());return;}try (InputStream is = response.body();BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {StringBuilder fullResponseContent = new StringBuilder();String line;while ((line = reader.readLine()) != null) {JsonNode jsonResponse = mapper.readTree(line);if (jsonResponse.has("message")) {JsonNode messageNode = jsonResponse.get("message");if (messageNode.has("content")) {String content = messageNode.get("content").asText();System.out.print(content);fullResponseContent.append(content);}}if (jsonResponse.has("done") && jsonResponse.get("done").asBoolean()) {// Message complete, add to historyObjectNode assistantMessage = mapper.createObjectNode();assistantMessage.put("role", "assistant");assistantMessage.put("content", fullResponseContent.toString());messages.add(assistantMessage);}}} catch (IOException e) {e.printStackTrace();}}).join(); // Wait for completionSystem.out.println(); // New line after response} catch (Exception e) {System.err.println("Error communicating with Ollama: " + e.getMessage());e.printStackTrace();}}}
}

  

输出:

f5858421cf914b7b57c479755776a6d5

 

http://www.jsqmd.com/news/357882/

相关文章:

  • Qwen-Image-Edit-2511+AnythingtoRealCharacters2511深度解析:2.5D转真人效果实测与参数详解
  • OFA-large模型教学应用:人工智能课程中视觉蕴含任务的实验平台搭建
  • cv_unet_image-colorization模型在数学建模中的应用探索
  • 2026年湖南冷库建造定制公司排名,宏国制冷等靠谱品牌推荐 - myqiye
  • Qwen3-ASR-0.6B快速部署:GitHub Actions自动化构建Docker镜像并推送Registry
  • 网上管家婆联系方式:关于SaaS软件服务的几点考量 - 品牌推荐
  • VSCode插件开发:集成Qwen3-ForcedAligner音频分析功能
  • LongCat-Image-Editn镜像使用手册:图片≤1MB/短边≤768px的最优输入规范
  • 2026年广东环卫设备公司推荐,有美工贸公司介绍及交货及时性分析 - 工业品网
  • 网上管家婆联系方式:SaaS产品服务咨询路径说明 - 品牌推荐
  • 2026年江苏盈和环保节能设备产品质量排名,好用又实惠 - 工业设备
  • 网上管家婆联系方式:企业软件选择与使用指南 - 品牌推荐
  • Qwen3-TTS-VoiceDesign惊艳效果:中文绕口令+英文 tongue twister 高速清晰合成展示
  • CogVideoX-2b应用场景:为教师生成课堂动画、为设计师提供创意灵感视频
  • AI头像生成器与LaTeX结合:学术论文头像自动生成
  • 2026年质量好的耐水解纤维缠绕轴承/复合材料纤维缠绕轴承生产商实力参考哪家质量好(更新) - 行业平台推荐
  • PDF-Extract-Kit-1.0详细步骤:/root/PDF-Extract-Kit目录下各脚本执行逻辑解析
  • 探讨2026年环保全屋定制,济南地区哪家口碑好值得选 - 工业品牌热点
  • 网上管家婆联系方式:客观介绍其产品线与发展历程 - 品牌推荐
  • lychee-rerank-mm UI定制指南:Streamlit组件集成与响应式布局优化
  • mPLUG本地智能分析工具一文详解:ModelScope pipeline轻量推理实战
  • 2026年UV平板机零售厂家排名,浙江工正智能设备股份有限公司上榜 - mypinpai
  • DeepSeek-OCR开源大模型部署:支持<|grounding|>提示词的空间感知教程
  • 怎么选购电镀设备,电镀设备快速定制服务商为你支招 - 工业推荐榜
  • Go 定时任务调度系统的数据库表结构
  • 数学建模应用:RMBG-2.0在图像分析赛题中的创新使用
  • 2026年上海热门旅行社排名,景中游国际旅行社创新能力强上榜 - myqiye
  • PasteMD开发者案例:嵌入VS Code插件,右键菜单直接调用本地Markdown美化
  • Hunyuan-MT Pro效果展示:中→日技术文档术语一致性与敬语处理案例
  • 通义千问2.5-7B vs InternLM2-7B性能对比:长文本处理实测