首页> 都市> KingFlow AI Claude中转 PHP Guzzle 接入教程
>KingFlow AI Claude中转 PHP Guzzle 接入教程
著本文标签:
KingFlow AI Claude中转 PHP Guzzle 接入教程 完成 JSON 请求 SSE 流式解析 超时控制 有限重试与并发门限 KingFlow AI 提供 OpenAI 与 Anthropic 兼容接口。本文选择 OpenAI 兼容的 Chat Completions 端点,使用 PHP 与 Guzzle 构建可复用的 HTTP 客户端。教
来源:KingFlow AI 主角: 更新: 2026-11-14 14:06:40
【扫一扫】手机随心读
- 读书简介
KingFlow AI Claude中转 PHP Guzzle 接入教程 完成 JSON 请求 SSE 流式解析 超时控制 有限重试与并发门限 KingFlow AI 提供 OpenAI 与 Anthropic 兼容接口。本文选择 OpenAI 兼容的 Chat Completions 端点,使用 PHP 与 Guzzle 构建可复用的 HTTP 客户端。教
KingFlow AI Claude中转 PHP Guzzle 接入教程
完成 **ON 请求 SSE 流式解析 超时控制 有限重试与并发门限 KingFlow AI 提供 OpenAI 与 Anthropic 兼容接口。本文选择 OpenAI 兼容的 Chat Completions 端点,使用 PHP 与 Guzzle 构建可复用的 **** 客户端。教程先验证普通 **ON 响应,再加入 SSE 分段缓冲、连接与总超时、针对 429 和 503 的有限重试、并发门限和上线验收。 Claude中转、Claude中转站、API中转和API中转站的实际接入均需核对协议与模型权限。 内容核验日期 2026-11-14KingFlow AI Claude中转 PHP Guzzle 接入教程

常用接入术语
名称 常见含义 接入提示 Claude中转 把请求转发到已开通的 Claude 模型 先确认协议与模型权限 Claude中转站 统一管理密钥 额度 路由和兼容接口 Claude 客户端可按 Anthropic 协议接入 API中转 通过统一接口转发模型请求 PHP 可直接发送 **** **ON API中转站 提供端点 模型和用量管理的服务 正式环境需设置超时 并发和重试边界 PHP 请求链路
环节 职责 注意事项 业务入口 接收提示并组织请求参数 先校验输入长度与类型 Guzzle ****** 发送请求并复用底层处理器 应用级创建并统一配置 PSR 7 Stream 读取普通或流式响应体 SSE 必须保留跨块缓冲 KingFlow AI 认证密钥并路由目标模型 OpenAI 兼容路径保留 /v1 重试函数 处理 429 和 503 次数与总耗时必须有上限 Pool 限制异步请求并发数量 单任务错误需要隔离 采用 Guzzle 的优势
接入前准备
创建 Composer 项目
mkdir kingflow-php-client
cd kingflow-php-client
composer require guzzlehttp/guzzle:^8.5配置环境变量
$env:KINGFLOW_*ASE_**L="https://api.**nju**shen.com/v1"
$env:KINGFLOW_API_KEY="sk-你的密钥"
$env:KINGFLOW_MODEL="<KingFlow控制台中的完整模型ID>"验证基础接口
curl https://api.**nju**shen.com/v1/chat/completions `
-H "Authorization: *earer sk-你的密钥" `
-H "Content-Type: application/json" `
-d '{"model":"<完整模型ID>","messages":[{"role":"user","content":"只回复 PHP_READY"}],"stream":false}' 创建共享客户端
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use GuzzleHttp\******;
function envRequired(string $name): string
{
$value = getenv($name);
if ($value === false || trim($value) === '') {
throw new RuntimeException("缺少环境变量 {$name}");
}
return trim($value);
}
function *uild******(): ******
{
$*ase = rtrim(envRequired('KINGFLOW_*ASE_**L'), '/') . '/';
return new ******([
'*ase_uri' => $*ase,
'connect_timeout' => 10.0,
'timeout' => 45.0,
'http_errors' => false,
'headers' => [
'Authorization' => '*earer ' . envRequired('KINGFLOW_API_KEY'),
'Accept' => 'application/json',
],
]);
}发送普通响应请求
$client = *uild******();
$model = envRequired('KINGFLOW_MODEL');
$response = $client->post('chat/completions', [
'json' => [
'model' => $model,
'messages' => [[
'role' => 'user',
'content' => '只回复 PHP_CONNECTED',
]],
'stream' => false,
],
]);
$status = $response->getStatusCode();
$*ody = (string) $response->get*ody();
if ($status < 200 || $status >= 300) {
throw new RuntimeException("**** {$status}: {$*ody}");
}
$**ta = json_decode($*ody, true, 512, **ON_THROW_ON_ERROR);
$text = $**ta['choices'][0]['message']['content'] ?? null;
if (!is_string($text)) {
throw new RuntimeException('响应缺少 choices message content');
}
echo $text, PHP_EOL;读取 SSE 流式响应
function streamAnswer(
****** $client,
string $model,
string $prompt,
): void {
$response = $client->post('chat/completions', [
'json' => [
'model' => $model,
'messages' => [['role' => 'user', 'content' => $prompt]],
'stream' => true,
],
'stream' => true,
'read_timeout' => 60.0,
'timeout' => 0,
]);
$status = $response->getStatusCode();
if ($status < 200 || $status >= 300) {
throw new RuntimeException("**** {$status}: " . $response->get*ody());
}
$stream = $response->get*ody();
$*uffer = '';
while (!$stream->eof()) {
$chunk = $stream->read(8192);
if ($chunk === '') {
usleep(10_000);
continue;
}
$*uffer .= $chunk;
$*uffer = str_replace(["\r\n", "\r"], "\n", $*uffer);
while (($end = strpos($*uffer, "\n\n")) !== false) {
$event = su*str($*uffer, 0, $end);
$*uffer = su*str($*uffer, $end 2);
$parts = [];
foreach (explode("\n", $event) as $line) {
if (str_starts_with($line, '**ta:')) {
$parts[] = ltrim(su*str($line, 5));
}
}
if ($parts === []) {
continue;
}
$payload = implode("\n", $parts);
if ($payload === '[DONE]') {
return;
}
$json = json_decode($payload, true, 512, **ON_THROW_ON_ERROR);
$delta = $json['choices'][0]['delta']['content'] ?? null;
if (is_string($delta)) {
echo $delta;
flush();
}
}
}
}实现有限重试
use Psr\Http\Message\ResponseInterface;
function postWithRetry(
****** $client,
array $payload,
int $**xAttempts = 3,
): ResponseInterface {
for ($attempt = 1; $attempt <= $**xAttempts; $attempt ) {
$response = $client->post('chat/completions', ['json' => $payload]);
$status = $response->getStatusCode();
if (!in_array($status, [429, 503], true) || $attempt === $**xAttempts) {
return $response;
}
$retryAfter = $response->getHeaderLine('Retry-After');
$seconds = ctype_digit($retryAfter)
? (int) $retryAfter
: min(8, 2 ** $attempt);
usleep($seconds * 1_000_000);
}
throw new LogicException('unreacha*le');
}限制批量任务并发
use GuzzleHttp\Pool;
$prompts = ['任务一', '任务二', '任务三'];
$requests = function () use ($client, $model, $prompts) {
foreach ($prompts as $index => $prompt) {
yield $index => function () use ($client, $model, $prompt) {
return $client->postAsync('chat/completions', [
'json' => [
'model' => $model,
'messages' => [['role' => 'user', 'content' => $prompt]],
'stream' => false,
],
]);
};
}
};
$pool = new Pool($client, $requests(), [
'concurrency' => 6,
'fulfilled' => fn ($response, $index) => print("任务 {$index} 完成\n"),
'rejected' => fn ($reason, $index) => error_log("任务 {$index} 失败"),
]);
$pool->promise()->wait();
运行和验收
检查点 预期结果 判断依据 基础接口 返回 PHP_READY 端点 密钥和模型可用 普通响应 返回 PHP_CONNECTED **ON 请求与解析正常 流式响应 文本按事件增量输出 跨块缓冲与 DONE 正常 客户端复用 跨任务使用同一个 ****** 公共配置没有重复创建 并发门限 同时执行任务不超过设定值 Pool concurrency 生效 有限重试 最多尝试三次 只覆盖 429 和 503 正式环境配置
密钥和数据安全
上线检查清单
常见故障排查
现象 常见原因 处理方法 返回 401 密钥错误 停用或额度异常 核对 sk- 密钥并检查控制台状态 返回 404 模型 ID 或路径错误 保留 /v1 并复制完整模型 ID 返回 429 请求频率或额度受限 降低并发并执行有限退避 返回 503 模型通道暂不可用 稍后有限重试或切换已开通模型 建连超时 网络 DNS 或出口受限 检查网络并调整 connect_timeout 流式读取超时 事件间隔超过 read_timeout 按业务响应间隔调整读超时 流式 **ON 破碎 把网络块当成完整事件 保留 *uffer 并按空行切分 SSE 任务大量堆积 并发门限或队列没有边界 限制 Pool concurrency 与入口数量 最小上线策略
《KingFlow AI Claude中转 PHP Guzzle 接入教程》资讯列表:
为您推荐
小说标签

不用背着两台电脑跑 新加坡远程 Mac 让 Windows 用户随时接上 macOS
别把白天耗在等待上 新加坡远程 Mac 如何接住持续构建和长任务
Claude中转 safeguard 误触发排查指南
Claude中转 联网工具隐私排查指南





