当前位置:   article > 正文

【百度智能云千帆大模型平台】访问大模型流式响应数据_百度千帆php流式输出

百度千帆php流式输出

背景:

最近在调用千帆大模型,调用了他的接口,本文只是做一个记录.

正文:

1、描述

封装了千帆大模型的接口,采用了流式的方式的响应,减少用户的等待。

备注:以前没有使用过http的流式响应,也是感觉比较新奇,很好玩的事情,特意分享给大家。

2、代码:

  1. /**
  2. * @author twilight
  3. * @since V1.0
  4. */
  5. @Slf4j
  6. @Service
  7. public class HttpStreamServiceImpl {
  8. public void chat(String accesstoken) {
  9. try {
  10. //获取RequestBody
  11. RequestBody funcCallReqBody = getRequestBody();
  12. //发送请求
  13. sendRequest(funcCallReqBody,accesstoken);
  14. } catch (Exception e) {
  15. log.error("chat执行失败", e);
  16. }
  17. }
  18. /**
  19. * 获取RequestBody
  20. * @return
  21. */
  22. protected RequestBody getRequestBody() {
  23. List<Message> messages = new ArrayList<>();
  24. Message chatMsg = new Message("RoleName", "content");
  25. messages.add(chatMsg);
  26. //获取组装好的请求
  27. ReqChatMessage reqMessage = new ReqChatMessage();
  28. reqMessage.setMessages(messages);
  29. reqMessage.setStream(true);
  30. reqMessage.setSystem("systemInfo");
  31. reqMessage.setUser_id("userID");
  32. String content = JSONObject.toJSONString(reqMessage);
  33. MediaType mediaType = MediaType.parse("application/json");
  34. return RequestBody.create(mediaType, content);
  35. }
  36. /**
  37. * 发送请求
  38. *
  39. * @param body
  40. * @throws IOException
  41. * @returnline
  42. */
  43. protected String sendRequest(RequestBody body, String accessToken) {
  44. String respResult = "";
  45. Request request = new Request.Builder().url("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie_bot_8k?access_token=" +
  46. accessToken).method("POST", body).addHeader("Content-Type", "application/json").build();
  47. try (Response response = OkHttpUtil.HTTP_CLIENT.newCall(request).execute()) {
  48. if (!response.isSuccessful()) {
  49. throw new IOException("Unexpected code " + response);
  50. }
  51. BufferedSource source = Okio.buffer(response.body().source());
  52. String line = "";
  53. while ((line = source.readUtf8Line()) != null) {
  54. //流式打印出来
  55. System.out.println(line);
  56. }
  57. } catch (Exception e) {
  58. log.error("sendRequest请求执行失败", e);
  59. }
  60. return respResult;
  61. }
  62. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小舞很执着/article/detail/825204
推荐阅读
相关标签
  

闽ICP备14008679号