kongdeqiang
2026-10-09 9af621d181217a03b1b3dce208a163915db974a3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
package com.custom.webui.service.impl;
 
import com.custom.webui.config.props.LlmProperties;
import com.custom.webui.exception.BusinessException;
import com.custom.webui.service.LlmService;
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 lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;
 
/**
 * Ollama LLM 实现,对接 {@code POST /api/chat}。
 *
 * <p><b>为什么用 HttpURLConnection 而不是 RestTemplate?</b>
 * Ollama 的流式响应是 NDJSON(每行一个 JSON 对象),RestTemplate 没有开箱即用的
 * 「逐行消费」能力,需要写自定义 ResponseExtractor 反而更绕。
 * 直接用 {@link HttpURLConnection} + {@link BufferedReader#readLine()} 最直观,
 * 也避免引入 WebClient 这套响应式依赖(会显著增大打包体积)。
 *
 * <p>请求体示例:
 * <pre>
 * {
 *   "model": "qwen2.5:7b",
 *   "messages": [{"role":"user","content":"你好"}],
 *   "stream": true,
 *   "options": {"temperature":0.7,"top_p":0.9,"num_ctx":8192}
 * }
 * </pre>
 *
 * <p>响应体每行形如:
 * <pre>
 * {"model":"qwen2.5:7b","message":{"role":"assistant","content":"你"},"done":false}
 * {"model":"qwen2.5:7b","message":{"role":"assistant","content":""},"done":true,...}
 * </pre>
 *
 * <p>前置条件:Ollama 必须监听 0.0.0.0 才能被其他进程/机器访问 ——
 * 启动命令 {@code OLLAMA_HOST=0.0.0.0 ollama serve}。
 */
@Slf4j
@Service
@ConditionalOnProperty(name = "webui.llm.provider", havingValue = "ollama", matchIfMissing = true)
public class OllamaLlmService implements LlmService {
 
    private final LlmProperties properties;
    private final ObjectMapper objectMapper;
 
    public OllamaLlmService(LlmProperties properties, ObjectMapper objectMapper) {
        this.properties = properties;
        this.objectMapper = objectMapper;
        log.info("LLM 实现: Ollama, baseUrl={}, defaultModel={}",
                properties.getOllama().getBaseUrl(), properties.getOllama().getDefaultModel());
    }
 
    @Override
    public void streamChat(List<LlmMessage> messages, LlmOptions options, TokenConsumer consumer) {
        HttpURLConnection conn = null;
        try {
            conn = openConnection("/api/chat", properties.getOllama().getTimeoutMillis());
            String body = buildRequestBody(messages, options, true);
            writeBody(conn, body);
 
            int status = conn.getResponseCode();
            if (status != 200) {
                String err = readErrorBody(conn);
                log.error("Ollama 返回非 200: status={}, body={}", status, err);
                throw BusinessException.serverError(
                        "LLM 服务返回错误 (HTTP " + status + ")。请确认模型 "
                                + resolveModel(options) + " 已通过 `ollama pull` 下载。详情: " + err);
            }
 
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    if (line.isBlank()) {
                        continue;
                    }
                    JsonNode node;
                    try {
                        node = objectMapper.readTree(line);
                    } catch (IOException parseError) {
                        // 单行解析失败不应中断整个流,跳过即可
                        log.warn("无法解析 Ollama 响应行: {}", abbreviate(line));
                        continue;
                    }
 
                    // 错误字段优先:Ollama 可能在中途返回 {"error": "..."}
                    if (node.hasNonNull("error")) {
                        throw BusinessException.serverError("Ollama 错误: " + node.get("error").asText());
                    }
 
                    JsonNode messageNode = node.get("message");
                    if (messageNode != null) {
                        // 思考内容(qwen3 / deepseek-r1 等 reasoning 模型)
                        JsonNode thinkingNode = messageNode.get("thinking");
                        if (thinkingNode != null && !thinkingNode.asText().isEmpty()) {
                            if (properties.getOllama().isIncludeThinking()) {
                                consumer.accept(thinkingNode.asText(), true);
                            }
                        }
                        JsonNode contentNode = messageNode.get("content");
                        if (contentNode != null && !contentNode.asText().isEmpty()) {
                            consumer.accept(contentNode.asText(), false);
                        }
                    }
 
                    if (node.path("done").asBoolean(false)) {
                        break;
                    }
                }
            }
        } catch (BusinessException e) {
            throw e;
        } catch (IOException e) {
            log.error("调用 Ollama 失败", e);
            throw BusinessException.serverError(
                    "无法连接 LLM 服务 " + properties.getOllama().getBaseUrl()
                            + ",请确认 Ollama 已启动(OLLAMA_HOST=0.0.0.0 ollama serve)。原因: " + e.getMessage());
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }
 
    @Override
    public String complete(List<LlmMessage> messages, LlmOptions options) {
        HttpURLConnection conn = null;
        try {
            conn = openConnection("/api/chat", 30000);
            writeBody(conn, buildRequestBody(messages, options, false));
 
            if (conn.getResponseCode() != 200) {
                log.warn("Ollama 非流式调用失败, status={}", conn.getResponseCode());
                return null;
            }
            try (InputStream in = conn.getInputStream()) {
                JsonNode node = objectMapper.readTree(in);
                JsonNode contentNode = node.path("message").path("content");
                return contentNode.isMissingNode() ? null : contentNode.asText();
            }
        } catch (Exception e) {
            // 标题生成属于锦上添花,失败不抛出,由调用方回退到截断标题
            log.warn("Ollama 非流式调用异常: {}", e.getMessage());
            return null;
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }
 
    @Override
    public String defaultModel() {
        return properties.getOllama().getDefaultModel();
    }
 
    // ==================== 内部辅助 ====================
 
    private HttpURLConnection openConnection(String path, int timeoutMillis) throws IOException {
        String baseUrl = properties.getOllama().getBaseUrl();
        // 去掉末尾斜杠,避免拼出 //api/chat
        if (baseUrl.endsWith("/")) {
            baseUrl = baseUrl.substring(0, baseUrl.length() - 1);
        }
        URI uri = URI.create(baseUrl + path);
        HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(timeoutMillis);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Accept", "application/x-ndjson");
        return conn;
    }
 
    /** 组装请求体 JSON */
    private String buildRequestBody(List<LlmMessage> messages, LlmOptions options, boolean stream)
            throws IOException {
        ObjectNode root = objectMapper.createObjectNode();
        root.put("model", resolveModel(options));
        root.put("stream", stream);
 
        ArrayNode messageArray = root.putArray("messages");
        for (LlmMessage m : messages) {
            ObjectNode item = messageArray.addObject();
            item.put("role", m.role());
            item.put("content", m.content());
        }
 
        ObjectNode optionsNode = root.putObject("options");
        Double temperature = options.temperature() != null
                ? options.temperature() : properties.getDefaults().getTemperature();
        Double topP = options.topP() != null
                ? options.topP() : properties.getDefaults().getTopP();
        Integer numCtx = options.numCtx() != null
                ? options.numCtx() : properties.getDefaults().getNumCtx();
 
        if (temperature != null) {
            optionsNode.put("temperature", temperature);
        }
        if (topP != null) {
            optionsNode.put("top_p", topP);
        }
        if (numCtx != null) {
            optionsNode.put("num_ctx", numCtx);
        }
 
        return objectMapper.writeValueAsString(root);
    }
 
    /** 模型名解析优先级:会话参数 > 全局配置 */
    private String resolveModel(LlmOptions options) {
        if (options != null && options.modelName() != null && !options.modelName().isBlank()) {
            return options.modelName().trim();
        }
        return properties.getOllama().getDefaultModel();
    }
 
    private void writeBody(HttpURLConnection conn, String body) throws IOException {
        try (var out = conn.getOutputStream()) {
            out.write(body.getBytes(StandardCharsets.UTF_8));
            out.flush();
        }
    }
 
    /** 读取错误响应体,供日志与前端提示使用 */
    private String readErrorBody(HttpURLConnection conn) {
        try (InputStream err = conn.getErrorStream()) {
            if (err == null) {
                return "(无响应体)";
            }
            return new String(err.readAllBytes(), StandardCharsets.UTF_8);
        } catch (IOException e) {
            return "(读取错误响应失败)";
        }
    }
 
    private String abbreviate(String s) {
        return s.length() > 200 ? s.substring(0, 200) + "..." : s;
    }
}