依赖坐标(腾讯云所有产品sdk下载到本地)
<dependency> <groupId>com.tencentcloudapi</groupId> <artifactId>tencentcloud-sdk-java</artifactId> <version>3.1.1014</version> </dependency>
单独引入
<dependency> <groupId>com.tencentcloudapi</groupId> <artifactId>tencentcloud-sdk-java-hunyuan</artifactId> <version>3.1.1010</version> </dependency>
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.SSEResponseModel;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.hunyuan.v20230901.HunyuanClient;
import com.tencentcloudapi.hunyuan.v20230901.models.ChatStdRequest;
import com.tencentcloudapi.hunyuan.v20230901.models.ChatStdResponse;
import com.tencentcloudapi.hunyuan.v20230901.models.Choice;
import com.tencentcloudapi.hunyuan.v20230901.models.Message;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@RestController
@RequestMapping
public class HunYuanAi {
@GetMapping("/ai")
public String streamRes(String wd, HttpServletResponse response) throws IOException {
ServletOutputStream outputStream = response.getOutputStream();
String SecretKey = "SecretKey";
String SecretId = "SecretId";
try {
//核心设置数据流格式响应头
response.setContentType("text/event-stream");
response.setCharacterEncoding("UTF-8");
Credential cred = new Credential(SecretId, SecretKey);
ClientProfile clientProfile = new ClientProfile();
HunyuanClient client = new HunyuanClient(cred, "ap-guangzhou", clientProfile);
ChatStdRequest req = new ChatStdRequest();
Message msg = new Message();
msg.setRole("user");
msg.setContent(wd);
req.setMessages(new Message[]{msg});
req.setStream(true);
ChatStdResponse resp = client.ChatStd(req);
if (req.getStream()) {
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
for (SSEResponseModel.SSE e : resp) {
ChatStdResponse eventModel = gson.fromJson(e.Data, ChatStdResponse.class);
Choice[] choices = eventModel.getChoices();
if (choices.length > 0) {
String res = choices[0].getDelta().getContent();
outputStream.write(res.getBytes());
outputStream.flush();
}
// 如果希望在任意时刻中止事件流, 使用 resp.close() + break
boolean iWantToCancelNow = false;
if (iWantToCancelNow) {
outputStream.close();
resp.close();
break;
}
}
}
} catch (TencentCloudSDKException e) {
e.printStackTrace();
}
return "";
}
}