首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用php来自openai GPT-3 API的流数据

使用php来自openai GPT-3 API的流数据
EN

Stack Overflow用户
提问于 2022-06-22 07:05:28
回答 1查看 224关注 0票数 0

我遇到了OpenAI API的问题,基本上,我要做的是将每个数据节点从openai响应中流回来,并在每个数据节点从API调用中逐个输出,但是我不知道它是如何实现的,我研究了几个小时,找不到任何关于如何用PHP实现这一点的信息。

如何让我的代码在数据中的API流中实时输出每个数据节点?

下面是我所能想到的最好的方法,它在调用完成后立即输出所有数据,但它不会在数据中流。

代码语言:javascript
复制
function openAI(){
  $OPENAI_API_KEY="API_KEY_GOES_HERE";
  $user_id="1";  //  users id optional
   
    $prompt="tell me what you can do for me.";
    $temperature=0.5;  // 1 adds complete randomness  0 no randomness 0.0
    $max_tokens=30;
 
         $data = array('model'=>'text-davinci-002',
              'prompt'=>$prompt,
              'temperature'=>$temperature,
              'max_tokens'=>$max_tokens,
              'top_p'=>1.0,
              'stream'=>TRUE,// stream back response
              'frequency_penalty'=>0.0,
              'presence_penalty'=>0.0,
               'user' => $user_id);

   $post_json= json_encode($data);
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/completions');
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($ch, CURLOPT_POST, 1);
   curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
   curl_setopt($ch, CURLOPT_POSTFIELDS, $post_json);

  $headers = array();
  $headers[] = 'Content-Type: application/json';
  // $headers[] = 'Content-Type: text/event-stream';
   $headers[] = "Authorization: Bearer $OPENAI_API_KEY";
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

   $result = curl_exec($ch);
   return $result;

  curl_close($ch);
}

echo openAI();
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-06-25 01:19:45

我最终解决了我的问题。希望我的回答能对未来的人有所帮助。

我在代码中添加了以下内容。这个简单的逻辑使我所询问的工作。

代码语言:javascript
复制
// This should be at the very top, alternatively can be set in you php.ini file
@ini_set('zlib.output_compression',0);
@ini_set('implicit_flush',1);
// This function discards the contents of the topmost output buffer and turns off this output buffering.
@ob_end_clean(); 

还应该添加以下curl_setopt。我个人在CURLOPT_POSTFIELDS之后添加了它

代码语言:javascript
复制
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($curl, $data) {
  # str_repeat(' ',1024*8) is needed to fill the buffer and will make streaming the data possible
   echo $data.str_repeat(' ',1024*8);
   return strlen($data); 
});

或者,与添加str_repeat(‘',1024*8)不同,您可以关闭web服务器配置文件中的缓冲,例如(nginx.conf)

代码语言:javascript
复制
gzip off;
proxy_buffering off;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72711031

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档