php调用大模型api实现流式输出、超时控制与自动重试,关键在于:一、用curl流式读取sse,禁用缓冲并逐行解析data:字段;二、分设连接与总超时,并用low_speed_limit/time防假活;三、对网络错误及429/5xx状态码实施指数退避重试。

PHP 调用大模型 API(如 OpenAI、Qwen、DeepSeek 等)实现流式输出、合理超时控制和自动重试,关键在于用好 cURL 的流式读取能力、stream_get_line() 或 fread() 处理 SSE(Server-Sent Events),并结合指数退避策略做重试。下面给出可直接运行的完整示例,覆盖核心痛点。
一、启用流式响应与逐块解析 SSE
大模型 API(如 OpenAI 的 /chat/completions)在启用 stream=true 时返回的是以 data: 开头、换行分隔的文本流(SSE 格式)。PHP 需禁用 cURL 缓冲、手动读取响应流,并按行解析。
注意:不能用 curl_exec() 一次性获取全部响应,必须用 CURLOPT_WRITEFUNCTION 或 CURLOPT_RETURNTRANSFER => false + fread()。
- 设置
CURLOPT_HTTPHEADER包含Accept: text/event-stream和Content-Type: application/json - 关闭
CURLOPT_RETURNTRANSFER,改用fopen('php://temp', 'r+')作为输出句柄 - 循环调用
fread($fp, 1024),用stream_get_line($fp, 1024, "\n")提取每行 - 过滤空行和
data: [DONE],对data: { ... }做json_decode(substr($line, 6), true)
二、设置精准超时:连接 + 传输双控
仅设 CURLOPT_TIMEOUT 不够——它包含连接时间,而流式请求常需长连接但单次响应块间隔短。应分开控制:
将小说章节转换为电影分镜剧本。用户上传txt/md/docx文本,AI分析场景、角色、情绪、镜头语言,输出专业分镜脚本。适用于用户提及“分镜”“storyboard”“小说转分镜”“影视改编”“镜头脚本”或需要将小说改编为分镜的场景。
-
CURLOPT_CONNECTTIMEOUT_MS = 5000:连接建立最多 5 秒 -
CURLOPT_TIMEOUT_MS = 120000:整个请求生命周期上限(如 2 分钟) - 更关键的是用
CURLOPT_LOW_SPEED_LIMIT+CURLOPT_LOW_SPEED_TIME防“假活”:CURLOPT_LOW_SPEED_LIMIT => 1(字节/秒)、CURLOPT_LOW_SPEED_TIME => 30(持续 30 秒低于 1B/s 则中断)
三、带退避的重试逻辑(含状态码判断)
网络抖动、429(限流)、503(服务不可用)都该重试;400/401/403/422 等客户端错误不应重试。推荐指数退避(1s → 2s → 4s → 8s),最多 3 次:
- 捕获
curl_error()和curl_getinfo($ch, CURLINFO_HTTP_CODE) - 对
0(网络失败)、429、500、502、503、504触发重试 - 每次重试前
usleep(pow(2, $attempt) * 1000000)(单位微秒) - 记录重试次数到日志,避免静默失败
四、完整可运行代码(含注释)
以下为整合上述要点的最小可行代码,适配 OpenAI 兼容接口(如官方、LiteLLM、FastChat):
<?php function callLLMStream($apiKey, $apiUrl, $messages, $model = 'gpt-3.5-turbo') {
$maxRetries = 3;
$attempt = 0;
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">while ($attempt <= $maxRetries) {
$ch = curl_init();
$body = json_encode([
'model' => $model,
'messages' => $messages,
'stream' => true
]);
curl_setopt_array($ch, [
CURLOPT_URL => $apiUrl . '/chat/completions',
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $body,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . $apiKey,
'Content-Type: application/json',
'Accept: text/event-stream'
],
CURLOPT_RETURNTRANSFER => false,
CURLOPT_HEADER => false,
CURLOPT_CONNECTTIMEOUT_MS => 5000,
CURLOPT_TIMEOUT_MS => 120000,
CURLOPT_LOW_SPEED_LIMIT => 1,
CURLOPT_LOW_SPEED_TIME => 30,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_FOLLOWLOCATION => false,
]);
// 使用临时流接收响应
$responseStream = fopen('php://temp', 'r+');
curl_setopt($ch, CURLOPT_FILE, $responseStream);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlErrno = curl_errno($ch);
$curlError = curl_error($ch);
curl_close($ch);
if ($result === false || $curlErrno !== 0) {
if ($attempt < $maxRetries && in_array($curlErrno, [7, 28, 52, 56])) {
$wait = (int)pow(2, $attempt) * 1000000;
usleep($wait);
$attempt++;
continue;
}
throw new Exception("cURL error {$curlErrno}: {$curlError}");
}
if ($httpCode >= 400) {
$errorData = stream_get_contents($responseStream, -1, 0);
if ($httpCode == 429 || $httpCode >= 500) {
if ($attempt < $maxRetries) {
$wait = (int)pow(2, $attempt) * 1000000;
usleep($wait);
$attempt++;
continue;
}
}
throw new Exception("HTTP {$httpCode}: " . $errorData);
}
// 解析流
rewind($responseStream);
$buffer = '';
while (!feof($responseStream)) {
$chunk = fread($responseStream, 8192);
if ($chunk === false) break;
$buffer .= $chunk;
$lines = explode("\n", $buffer);
$buffer = array_pop($lines); // 保留不完整行
foreach ($lines as $line) {
$line = trim($line);
if (empty($line) || $line === 'event: message' || $line === 'data:') continue;
if (str_starts_with($line, 'data:')) {
$json = trim(substr($line, 5));
if ($json === '[DONE]') break;
$data = json_decode($json, true);
if (isset($data['choices'][0]['delta']['content'])) {
echo $data['choices'][0]['delta']['content'];
flush();
ob_flush();
}
}
}
}
fclose($responseStream);
return;
}
throw new Exception("Max retries exceeded");}
// 使用示例 try { ob_implicit_flush(true); ob_end_flush(); callLLMStream( $_ENV['OPENAI_API_KEY'] ?? 'your-key', $_ENV['OPENAI_API_BASE'] ?? 'https://www.php.cn/link/8e5ac35e1661cc14cb518fa9b9364854', [['role' => 'user', 'content' => '用一句话解释量子计算']] ); } catch (Exception $e) { echo "\nError: " . $e->getMessage(); } ?>
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!










