refactor(module-llm):重构停止微调任务接口

- 使用 OkHttpClient 替代 HttpRequest 发送 HTTP 请求
- 设置连接、读取和写入的超时时间为 2 分钟
- 构建带有查询参数的 URL
- 添加空的请求体
-优化异常处理,使用 IOException 替代 Exception
This commit is contained in:
Liuyang 2025-02-25 18:14:19 +08:00
parent 1cb2ad25e7
commit a8cca3b52e

View File

@ -10,10 +10,15 @@ import cn.iocoder.yudao.module.llm.service.http.vo.AigcFineTuningCreateRespVO;
import cn.iocoder.yudao.module.llm.service.http.vo.AigcRespVO;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
/**
* @Description 微调任务相关接口
@ -33,22 +38,43 @@ public class FineTuningTaskHttpService {
public void stopFinetuning (String host, FineTuningTaskDO fineTuningTaskDO) {
log.info(" ===== 停止微调任务 ===== stopFinetuning");
// 1. 获取停止微调任务的URL
String url = host + llmBackendProperties.getStopFinetuning();
log.info("获取停止微调任务的URL: {}", url);
// 创建 OkHttpClient 实例
log.info("创建 OkHttpClient 实例,设置超时时间为 2 分钟");
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(2, TimeUnit.MINUTES)
.readTimeout(2, TimeUnit.MINUTES)
.writeTimeout(2, TimeUnit.MINUTES)
.build();
// 2. 发送HTTP POST请求停止微调任务
// 1. 获取停止微调任务的URL
String baseUrl = host + llmBackendProperties.getStopFinetuning();
log.info("获取停止微调任务的URL: {}", baseUrl);
HttpUrl url = Objects.requireNonNull(HttpUrl.parse(baseUrl))
.newBuilder()
.addQueryParameter("fine_tuned_model", fineTuningTaskDO.getJobModelName())
.build();
// 2. 构建请求体空请求体
RequestBody requestBody = RequestBody.create("", MediaType.parse("application/json"));
// 3. 构建请求
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.addHeader("accept", "application/json")
.build();
// 4. 发送请求
log.info("开始发送HTTP POST请求停止微调任务任务模型名称: {}", fineTuningTaskDO.getJobModelName());
try {
// 使用 try-with-resources 确保 HttpResponse 被正确关闭
try (HttpResponse response = HttpRequest.post(url)
.form("fine_tuned_model", fineTuningTaskDO.getJobModelName())
.timeout(60000)
.executeAsync()) {
String body = response.body();
try (Response response = client.newCall(request).execute()) {
if (response.body()!=null) {
String body = response.body().string();
log.info("HTTP请求完成响应内容: {}", body);
} else {
log.error("HTTP请求失败: " + "响应为空");
throw new RuntimeException("HTTP请求失败: " + "响应为空");
}
} catch (Exception e) {
} catch (IOException e) {
log.error("发送HTTP请求停止微调任务时发生异常任务模型名称: {}", fineTuningTaskDO.getJobModelName(), e);
throw new RuntimeException("HTTP请求失败", e);
}