当前位置:   article > 正文

用【Java】调用百度千帆大模型并提供流式接口【SSE】响应_java 怎么实现调用千帆模型流式输出数据

java 怎么实现调用千帆模型流式输出数据

代码参考:

千帆API流式调用:PHP、JS、Nodejs、Python、Java、C# 、Go流式示例代码 - 百度智能云千帆社区本文旨在提供一个全面的指南,涵盖了在PHP、JS、Nodejs、Python、Java、C# 中流式调用千帆API的关键技巧和最佳实践。不论您是初学者还是有经验的开发者,相信这里的内容都能帮助您提升icon-default.png?t=N7T8https://cloud.baidu.com/qianfandev/topic/268202

效果演示:

API服务:

接口地址:

V1版本:https://apis.ydxiaoshuai.cn/xai/rest/llm/baidu/qianfan/chat?accessToken=ACCESSTOKEN&prompt=PROMPT

V2版本使用WebFlux:https://apis.ydxiaoshuai.cn/xai/rest/llm/baidu/qianfan/v2/chat?accessToken=ACCESSTOKEN&prompt=PROMPT

请求方式:GET

参数替换:

替换ACCESSTOKEN为自己的

替换PROMPT为自己要提问的问题

注意:服务器带宽有限,请不要恶意攻击

Java-Controller代码:

  1. /**
  2. * 发送问题
  3. *
  4. * @param apiKey - 用于获取token的apiKey
  5. * @param secretKey - 用于获取token的secretKey
  6. * @param accessToken - 接口token
  7. * @param prompt - 用于权限验证,从服务接口认证信息中获取
  8. * @return 百度千帆的回答
  9. */
  10. @GetMapping(value = "/baidu/qianfan/chat")
  11. public void baiduQianfanChat(@RequestParam(value ="apiKey",required = false) String apiKey,
  12. @RequestParam(value ="secretKey",required = false) String secretKey,
  13. @RequestParam(value ="accessToken",required = false) String accessToken,
  14. @RequestParam(value ="prompt",required = false) String prompt,
  15. HttpServletResponse res) throws Exception {
  16. LiteLLMResult bean = new LiteLLMResult();
  17. QianFanResponseDTO responseDTO = new QianFanResponseDTO();
  18. log.info("【百度千帆-prompt内容】:{}", prompt);
  19. // 响应流
  20. res.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_EVENT_STREAM_VALUE);
  21. res.setCharacterEncoding("UTF-8");
  22. res.setHeader(HttpHeaders.PRAGMA, "no-cache");
  23. ServletOutputStream out = null;
  24. String REQ_URL = null;
  25. try {
  26. out = res.getOutputStream();
  27. if (StrUtil.isEmpty(prompt)) {
  28. bean.fail("无效问题,请重新输入",500);
  29. out.write(JSON.toJSONString(bean).getBytes());
  30. return;
  31. }
  32. okhttp3.MediaType mediaType = okhttp3.MediaType.parse(MediaType.APPLICATION_JSON_VALUE);
  33. QianFanChatBean requestBean = QianFanUtil.getRequestData(prompt);
  34. requestBean.setStream(true);
  35. RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(requestBean));
  36. boolean flag = StrUtil.isEmpty(apiKey)||StrUtil.isEmpty(secretKey);
  37. if(flag && StrUtil.isNotEmpty(accessToken)){
  38. REQ_URL = QianFanUtil.API_URL.replace("ACCESS_TOKEN",accessToken);
  39. }else if(StrUtil.isNotEmpty(apiKey)&&StrUtil.isNotEmpty(secretKey)){
  40. REQ_URL = QianFanUtil.API_URL.replace("ACCESS_TOKEN",QianFanUtil.getAccessToken(apiKey,secretKey));
  41. }else{
  42. bean.fail("apiKey|secretKey|accessToken参数为空,请检查",500);
  43. out.write(JSON.toJSONString(bean).getBytes());
  44. return;
  45. }
  46. Request request = new Request.Builder()
  47. .url(REQ_URL)
  48. .method(Method.POST.toString(), body)
  49. .addHeader(Header.CONTENT_TYPE.getValue(), MediaType.APPLICATION_JSON_VALUE)
  50. .build();
  51. Response response = QianFanUtil.HTTP_CLIENT.newCall(request).execute();
  52. try (ResponseBody responseBody = response.body()) {
  53. if (responseBody != null) {
  54. try (BufferedReader reader = new BufferedReader(responseBody.charStream())) {
  55. String line;
  56. while ((line = reader.readLine()) != null) {
  57. String result = line.replace("data: ", "");
  58. if(StrUtil.isNotEmpty(result)){
  59. QianFanResponseBean qianFanResponseBean = JSON.parseObject(result,QianFanResponseBean.class);
  60. responseDTO.setContent(qianFanResponseBean.getResult());
  61. bean.success("执行成功",responseDTO);
  62. out.write(JSON.toJSONString(bean).getBytes());
  63. out.flush();
  64. //防止返回内容重复或错误。暂停一下
  65. Thread.sleep(100);
  66. }
  67. }
  68. }finally {
  69. responseBody.close();
  70. response.close();
  71. QianFanUtil.HTTP_CLIENT.connectionPool().evictAll();
  72. QianFanUtil.HTTP_CLIENT.dispatcher().executorService().shutdown();
  73. QianFanUtil.HTTP_CLIENT.newCall(request).cancel();
  74. }
  75. }
  76. }
  77. } catch (Exception e) {
  78. bean.fail("系统内部错误,请联系管理员",500);
  79. out.write(JSON.toJSONString(bean).getBytes());
  80. return;
  81. } finally {
  82. try {
  83. if (out != null) {
  84. out.close();
  85. }
  86. } catch (IOException e) {
  87. bean.fail("系统内部错误,请联系管理员",500);
  88. out.write(JSON.toJSONString(bean).getBytes());
  89. return;
  90. }
  91. }
  92. }

LiteLLMResult

  1. @Data
  2. @JsonInclude(JsonInclude.Include.NON_NULL)
  3. public class LiteLLMResult extends BaseResponseBean {
  4. /**
  5. * 具体参数
  6. **/
  7. private XingHuoResponseDTO data;
  8. public LiteLLMResult success(String message, XingHuoResponseDTO data) {
  9. this.message = message;
  10. this.code = CommonConstant.SC_OK_200;
  11. this.data = data;
  12. return this;
  13. }
  14. public LiteLLMResult fail(String message, Integer code) {
  15. this.message = message;
  16. this.code = code;
  17. return this;
  18. }
  19. public LiteLLMResult error(String message) {
  20. this.message = message;
  21. this.code = CommonConstant.SC_INTERNAL_SERVER_ERROR_500;
  22. return this;
  23. }
  24. }

BaseResponseBean

  1. @Data
  2. @JsonInclude(JsonInclude.Include.NON_NULL)
  3. public class BaseResponseBean implements Serializable {
  4. private static final long serialVersionUID = 1L;
  5. private static final long timestamps = System.currentTimeMillis();
  6. /**
  7. * 返回处理消息
  8. */
  9. public String log_id = timestamps+"-"+IdUtil.fastSimpleUUID();
  10. /**
  11. * 返回处理消息
  12. */
  13. public String message = "ok";
  14. /**
  15. * 返回处理消息
  16. */
  17. public String message_zh = "操作成功!";
  18. /**
  19. * 返回代码
  20. */
  21. public Integer code = 200;
  22. /**
  23. * 时间戳
  24. */
  25. public long timestamp = timestamps;
  26. /**
  27. * 作者
  28. */
  29. public String author = "小帅丶";
  30. }

QianFanResponseDTO

  1. @Data
  2. public class QianFanResponseDTO{
  3. private String uId;
  4. private String content;
  5. private String chatId;
  6. }

Nginx配置SSE

在自己域名反向代理的location下面配置即可

  1. proxy_buffering off;
  2. proxy_cache off;
  3. proxy_set_header Connection '';
  4. chunked_transfer_encoding off; # 开启分块传输编码
  5. tcp_nopush on; # 开启TCP NOPUSH选项,禁止Nagle算法
  6. tcp_nodelay on; # 开启TCP NODELAY选项,禁止延迟ACK算法
  7. # SSE事件流
  8. add_header Content-Type text/event-stream;
  9. add_header Cache-Control no-cache;
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/517974
推荐阅读
相关标签
  

闽ICP备14008679号