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);
|
}
|
}
|