kongdeqiang
2026-10-12 7c687dd3c8fba9f7632f5e29d94a708e5f497abd
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
package com.custom.webui.service;
 
import java.util.List;
 
/**
 * LLM 调用抽象。
 *
 * <p>当前有两个实现:
 * <ul>
 *   <li>{@link com.custom.webui.service.impl.OllamaLlmService} —— 对接本地 Ollama,生产使用</li>
 *   <li>{@link com.custom.webui.service.impl.MockLlmService} —— 本地模拟流式输出</li>
 * </ul>
 * 通过 {@code webui.llm.provider} 切换。抽出接口的收益是:
 * 未来接入 OpenAI 兼容协议(DeepSeek、通义等)时只需新增实现,业务层零改动。
 */
public interface LlmService {
 
    /**
     * 以流式方式生成回复。
     *
     * <p>本方法是<b>阻塞式</b>的:它会一直读到模型输出结束。
     * 调用方(MessageServiceImpl)负责把它放到 SSE 专用线程池里执行。
     *
     * @param messages 完整上下文(含 system / 历史对话 / 本轮用户输入),按时间正序
     * @param options  采样参数与模型名
     * @param consumer 每收到一个增量片段就回调一次
     * @throws com.custom.webui.exception.BusinessException LLM 不可用或返回错误时抛出
     */
    void streamChat(List<LlmMessage> messages, LlmOptions options, TokenConsumer consumer);
 
    /**
     * 非流式调用,用于会话标题生成这类短任务。
     *
     * @return 模型输出的完整文本;失败时返回 null,由调用方决定降级策略
     */
    String complete(List<LlmMessage> messages, LlmOptions options);
 
    /** 返回当前生效的默认模型名,用于前端展示和落库 */
    String defaultModel();
 
    // ==================== 内部值对象 ====================
 
    /**
     * 一条发给 LLM 的消息。
     *
     * @param role    system / user / assistant
     * @param content 文本内容
     */
    record LlmMessage(String role, String content) {
    }
 
    /**
     * 本次调用的生成参数。
     *
     * @param modelName   模型名,null 时用默认模型
     * @param temperature 采样温度
     * @param topP        核采样
     * @param numCtx      上下文窗口
     */
    record LlmOptions(String modelName, Double temperature, Double topP, Integer numCtx) {
    }
 
    /**
     * 增量输出回调。
     *
     * <p>约定:{@code thinking} 为 true 表示这是 reasoning 模型的思考过程而非正式回答,
     * 前端可折叠展示。普通模型该值恒为 false。
     */
    @FunctionalInterface
    interface TokenConsumer {
        void accept(String token, boolean thinking);
    }
}