ianrothmann / langserve-php-client
LangServe项目的PHP客户端,能够调用API端点,如调用、批量处理和流式传输。
1.1.0
2024-08-29 07:01 UTC
Requires
- php: >=7.4
- symfony/http-client: >=5.4
Requires (Dev)
- pestphp/pest: ^2.35
README
目的
本包为LangServe API提供PHP客户端,允许您轻松调用API端点,如invoke
、batch
和stream
。它简化了向LangServe项目发送请求和处理响应的过程。
它设计为与原生PHP一起使用,因此可以与任何框架(如Laravel)一起使用。
https://langchain.ac.cn/langserve
安装
要安装此包,请使用Composer
composer require ianrothmann/langserve-php-client
依赖关系
此包需要
- PHP 8.0或更高版本
- Symfony HttpClient组件,以支持通信和流式传输功能。
请确保它们已包含在您的项目中,如果尚未包含,请将它们添加到composer.json中
composer require symfony/http-client
用法
首先,使用您的LangServe API的基本URL实例化RemoteRunnable
use IanRothmann\LangServePhpClient\RemoteRunnable; $runnable = new RemoteRunnable('https://:8100/summarize/');
您可以选择将Bearer令牌作为第二个参数添加(请记住在LangServe中实现它)
$runnable = new RemoteRunnable('https://:8100/summarize/');
您有多种方法可以添加头和身份验证
$runnable->authenticateWithBearerToken('your-token'); //Add a Bearer token header with the token $runnable->authenticateWithXToken('your-token'); //Add the X-Token header, if you implemented it according to the LangServe Examples with X-Token $runnable->addHeader('Key', 'Value'); //Add any other header
调用
调用单个API调用
$input = ['text' => 'Hello, this is something for you to summarize']; $response = $runnable->invoke($inputs); dd($response->getRunId(), $response->getContent(), $response->getTokenUsage(), $response->getData(), $response->toJson());
批量
批量调用多个API调用
$input = [['text' => 'Hello, this is something for you to summarize'],['text' => 'Hello, this is more text for you to summarize']]; $batchResponse = $runnable->batch($inputs); foreach ($batchResponse->getResponses() as $response) { //$response->getRunId(), //$response->getContent(), //$response->getTokenUsage()); }
流式传输
处理流式响应
$result = $runnable->stream($input, function($response) { //Do something with the content here $response->getContent(); }); // Finally, this gives you the full content after everything has been streamed: $result->getContent();
响应类
invoke
和batch
的响应通过RemoteRunnableResponse
和RemoteRunnableBatchResponse
处理,分别。stream
最初为每个接收的事件提供RemoteRunnableStreamEvent
,最后,一个RemoteRunnableStreamResponse
将所有事件聚合以编译总内容。
异常
根据API响应,此客户端可以抛出几个异常
InternalServerErrorException
用于服务器错误。MalformedInputException
用于输入模式不匹配。- 当请求的资源未找到时抛出
NotFoundException
。 - 在远程调用过程中发生错误时抛出
RemoteInvocationException
。
这些异常有助于准确诊断API交互中存在的问题。
贡献
欢迎对这个包的贡献。我希望为它添加更多功能,并将根据需要处理它们。