You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在openai-php SDK流式补全函数中传递外部变量?

解决orhanerday/open-ai流式补全回调中变量累积的问题

在PHP里,要让流式补全的回调函数能访问并修改外部变量,核心是用匿名函数的use关键字+引用传递,具体操作如下:

  1. 先在回调函数外部定义用于累积内容的变量,比如$full_response = '';
  2. 定义回调函数时,通过use (&$full_response)引入外部变量,这里的&是关键——它表示传递变量的引用,这样回调内部对变量的修改会同步到外部,而不是操作副本。

完整代码示例

<?php
require 'vendor/autoload.php';

use Orhanerday\OpenAi\OpenAi;

$open_ai_key = '你的API密钥';
$client = new OpenAi($open_ai_key);

// 外部定义用于累积完整响应的变量
$full_response = '';

$completion_options = [
    'model' => 'text-davinci-003',
    'prompt' => '请介绍PHP的匿名函数特性',
    'temperature' => 0.7,
    'max_tokens' => 300,
    'stream' => true, // 开启流式模式
];

$client->completion($completion_options, function($chunk_data) use (&$full_response) {
    // 解析流式返回的单块数据
    $response_chunk = json_decode($chunk_data, true);
    if (isset($response_chunk['choices'][0]['text'])) {
        $text = $response_chunk['choices'][0]['text'];
        echo $text; // 实时输出单块内容
        $full_response .= $text; // 把单块内容追加到外部变量中
    }
});

// 流式请求结束后,$full_response就是完整的补全内容
echo "\n\n=== 完整响应内容 ===\n";
echo $full_response;
?>

关键注意点

  • 必须加&符号:如果去掉&,use引入的是变量的副本,回调里的修改不会影响外部变量,自然无法累积内容。
  • 数据解析容错:如果遇到json_decode失败的情况,可能是返回的$chunk_data包含非JSON前缀(比如data: ),可以先做处理,比如:
    $chunk_data = trim(str_replace('data: ', '', $chunk_data));
    if ($chunk_data === '[DONE]') {
        return; // 流式结束标记,直接返回
    }
    $response_chunk = json_decode($chunk_data, true);
    

内容的提问来源于stack exchange,提问作者Dennis Liu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 01:32:14