找回密码
 免费注册

[ChatGpt] PHP如何配置openai返回数据,保持流式输出,可以分段加载

[复制链接]
admin 发表于 2023-4-13 15:08:49 | 显示全部楼层 |阅读模式
可以使用OpenAI API的stream参数来实现流式输出,并且可以使用max_tokens参数控制每次返回数据的长度。 以下是一个示例代码,演示如何使用OpenAI API来实现流式输出并分段加载:
  1. <?php // 请求OpenAI接口获取stream数据,并转发到H5页面端
  2. $openAIUrl = 'https://api.openai.com/v1/engines/davinci-codex/completions'; $headers = array( 'Content-Type: application/json', 'Authorization: Bearer <YOUR_API_KEY>' );
  3. $data = array( 'prompt' => 'Hello, world!', 'max_tokens' => 5, 'temperature' => 0.7 );
  4. $ch = curl_init();
  5. curl_setopt($ch, CURLOPT_URL, $openAIUrl);
  6. curl_setopt($ch, CURLOPT_POST, true);
  7. curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
  8. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  9. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  10. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  11. $output = fopen('php://output', 'w');
  12. curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $chunk) use ($output) { fwrite($output, $chunk);
  13. return strlen($chunk); });
  14. curl_exec($ch);
  15. fclose($output); // 将stream数据转发给H5页面端
  16. header('Content-Type: text/event-stream');
  17. header('Cache-Control: no-cache');
  18. header('Connection: keep-alive');
  19. header('Access-Control-Allow-Origin: *');
  20. fpassthru($output);
复制代码

参考教程
  • https://blog.csdn.net/Climbman/article/details/129920946
  • https://www.coder.work/article/8058412

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 免费注册

本版积分规则

QQ|Archiver|手机版|小黑屋|信息共享网

GMT+8, 2024-5-14 15:57 , Processed in 0.086377 second(s), 23 queries .

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表