#AI
zhou zhou
4 小时以前 51877df13075ad10ef51107f15bcd21f1661febe
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
package com.vincent.rsf.server.ai.service;
 
import com.fasterxml.jackson.databind.JsonNode;
import com.vincent.rsf.server.ai.dto.GatewayChatRequest;
import org.springframework.stereotype.Service;
 
import javax.annotation.Resource;
 
@Service
public class AiTextCompletionService {
 
    @Resource
    private AiGatewayClient aiGatewayClient;
 
    /**
     * 用流式网关接口模拟一次“同步补全文本”调用。
     * 适合工具规划、结构化 JSON 选择这类短文本任务,内部仍然复用统一的流式网关能力。
     */
    public String complete(GatewayChatRequest request) throws Exception {
        final StringBuilder output = new StringBuilder();
        aiGatewayClient.stream(request, event -> handleEvent(event, output));
        return output.toString().trim();
    }
 
    /**
     * 只收集 delta 文本,并把 error / done 事件转换成同步调用语义。
     */
    private boolean handleEvent(JsonNode event, StringBuilder output) {
        String type = event.path("type").asText("");
        if ("delta".equals(type)) {
            output.append(event.path("content").asText(""));
            return true;
        }
        if ("error".equals(type)) {
            throw new IllegalStateException(event.path("message").asText("模型调用失败"));
        }
        return !"done".equals(type);
    }
}