本文将介绍如何使用 Ollama 生成 JSON 格式的结构化输出,并提供完整的 Java 实践示例。
注意:本文采用原生 HTTP 调用方式实现与 Ollama 的交互,不依赖任何第三方 SDK(如 Spring AI、LangChain4j 等)。这种方式可以让你更好地理解底层实现原理,并且可以根据实际需求自由选择是否使用其他 SDK。
# 使用 Homebrew 安装 brew install ollama
# 使用官方脚本安装 curl -fsSL https://ollama.com/install.sh | sh
# 启动 Ollama 服务 ollama serve
# 拉取通义千问2.5 32B参数量模型 ollama pull qwen2.5:32b
# 测试模型 ollama run qwen2.5:32b "你好,请做个自我介绍"
# 测试 API 服务是否正常 curl http://localhost:11434/api/version
@Data @Builder public class ChatMessage { private String role; private String content; } @Data @Builder public class ChatCompletionRequest { private String model; private List<ChatMessage> messages; private String format; } @Data public class ChatCompletionResponse { private String model; private String createdAt; private ChatMessage message; private String done; }
@Service @Slf4j public class ChatCompletionService { private static final String API_ENDPOINT = "http://localhost:11434/api/chat"; private final RestTemplate restTemplate; public ChatCompletionService(RestTemplate restTemplate) { this.restTemplate = restTemplate; } public String generateStructuredResponse(String prompt) { ChatCompletionRequest request = ChatCompletionRequest.builder() .model("qwen2.5:32b") .messages(List.of(ChatMessage.builder() .role("user") .content(prompt) .build())) .format("json") .build(); ResponseEntity<ChatCompletionResponse> response = restTemplate.postForEntity( API_ENDPOINT, request, ChatCompletionResponse.class ); return Optional.ofNullable(response.getBody()) .map(ChatCompletionResponse::getMessage) .map(ChatMessage::getContent) .orElse(""); } }
String prompt = """ 请生成问界M9车型的推荐信息,返回JSON格式,结构如下: { "model": string, "brand": string, "priceRange": string, "powerType": string, "scenarios": string[], "advantages": string[], "recommendation": { "trim": string, "color": string, "options": string[] } } """; String response = chatCompletionService.generateStructuredResponse(prompt);
{ "model": "问界M9", "brand": "问界AITO", "priceRange": "50-70万元", "powerType": "增程式混动", "scenarios": [ "商务接待", "家庭出行", "长途旅行", "城市通勤" ], "advantages": [ "华为智能座舱", "超大空间", "豪华舒适", "智能驾驶", "低油耗" ], "recommendation": { "trim": "旗舰版", "color": "星际银", "options": [ "全自动泊车辅助", "行政座椅套件", "全景天幕" ] } }