当前位置:首页>php>[php]composer 包 lsswear/curl

[php]composer 包 lsswear/curl

  • 2026-10-11 08:18:20
[php]composer 包 lsswear/curl

composer 包 lsswear/curl

lsswear/curl 是自己创建的第一个composer包~~o( ̄▽ ̄)ブ欢迎使用~

github

https://github.com/lsswear/curl

composer

https://packagist.org/packages/lsswear/curl

功能很简单,在curl/curl包基础上做修改,将构建请求的参数格式改成和guzzlehttp/guzzle类似,实现curl流式请求和非流式请求。

使用

以讯飞开放平台的接口请求为例,目前免费。

加载

require_once'vendor/autoload.php';useLsswear\Curl\Curl;

请求

//默认回执处理类use Lsswear\Curl\AgentResponse;//设置请求数据$url = "https://spark-api-open.xf-yun.com/x2/chat/completions";$token = "your_token";$model = "spark-x";//是否流式请求 true是 false不是$stream = true;//设置 header$authorization = "Bearer " . $token;$headers = ["authorization" => $authorization,"Content-Type" => "application/json",];//系统提示词$tsc = "你是大眼萌妹,可爱聪明。";$body = ["model" => $model,"stream" => $stream,"messages" => [//系统提示词        ["role" => "system","content" => $tsc,        ],//用户输入        ["role" => "user","content" => "你好呀",        ],    ],];//请求体参数$conf = ['headers' => $headers,"body" => $body,"stream" => $stream,"vertify" => false,];//请求方法$method = "post";//执行请求$curl = new Curl(new AgentResponse());

处理请求回执

try {    $response = $curl->post($url, $conf, true);    $response = $curl->getResponse();//回复内容    $content = $response->getContent();//思考过程    $reasoning_content = $response->getReasoningContent();//回执原数据    $stream = $response->getStream();    var_dump($content);    var_dump($reasoning_content);    var_dump($stream);} catch (\Throwable $th) {    var_dump($th->getCode());    var_dump($th->getMessage());    var_dump($th->getTraceAsString());}

自定义请求

参考Lsswear\Curl\AgentResponse类,其继承抽象类Lsswear\Curl\ResponseAbstract。

样例

classTestResponseextendsResponseAbstract{//流式回复处理回执内容publicfunctionstreamCallback($curl, $chunk){return strlen($chunk);  }//非流式回复处理回执内容publicfunctionsetContent(string $content): void{    $data = $this->formatResponse($content);$this->content = $data['content'];$this->stream = $data['stream'];  }//获取回复内容publicfunctiongetContent(): string{return trim($this->content);  }//获取原数据流publicfunctiongetStream(): string{return trim($this->stream);  }//格式化回执protectedfunctionformatResponse(string $content): array{    $data = [];return $data;  }}

streamCallback()必须返回内容,否则流式回复时返回第一条就停止处理。

其中streamCallback()和setContent()中调用formatResponse()处理Content值或其他值,比如AgentResponse中reasoning_content智能体的思考过程就是后定义的内容。

扫描识别二维码关注我们获取更多

最新文章

随机文章