evolvoltd / laravel-openai-assistants
向您选择的OpenAI助手发送消息的方法。
Requires
- php: >=8.2.0
- laravel/framework: ^11.0
- openai-php/laravel: ^0.8.1
README
开始使用
首先,使用Composer安装
composer require evolvoltd/laravel-openai-assistants
然后,确保设置您的.env变量
OPENAI_API_KEY =
GPT_ASSISTANT_ID =
请注意,此包使用队列。队列需要配置。默认情况下,使用的队列是'default'。您可以设置下面的.env变量来更改此设置。
QUEUE_NAME =
您还可以设置最大重试次数。默认值为60。您可以设置下面的.env变量来更改此设置。
MAX_RETRIES =
用法
此包的关键部分是ask
函数
(new GPTService)->ask($message, $parser)
此函数将消息添加到助手的线程中,运行线程,并将任务调度到检查运行状态并在运行完成后检索响应。
第一个参数'message'
需要您传递要发送给助手的消息。
第二个参数'parser'
需要您创建并传递一个实现接口ParseGPTResponse
的类
ParseGPTResponse接口
此接口有三个函数
public function parseResponse();
此函数允许您根据您的需求设置解析助手响应的功能。以下是一个示例
public function parseResponse(string $response)
{
return strtoupper($response);
}
public function executeFunctions());
此函数允许您设置助手从它们请求数据时的预定义函数。以下是一个示例。注意,$name
完全基于您分配给助手的函数。在此示例中,输出是硬编码的,但可以返回您选择的任何数据。
public function executeFunctions(string $name, $arguments, $toolCall)
{
if ($name == 'get_weather') {
return [
'tool_call_id' => $toolCall->id,
'output' => "25 degrees celsius"
];
} else return [];
}
public function statusUpdate();
此函数允许您设置自己的方式来存储运行的状态和数据以供将来参考。以下是一个示例。注意,在此示例中,GptQuery是一个数据库表的模型。您需要创建自己的数据库表和模型才能使用此功能。
public function statusUpdate(string $status, string $run_id, string $thread_id, string $message = null, string $file_path = null, string $file_name = null, string $response = null)
{
if ($status === 'new') {
$query = GptQuery::query()->create([
'user_id' => auth::id(),
'status' => $status,
'run_id' => $run_id,
'thread_id' => $thread_id,
'message' => $message,
'response' => $response,
'file_path' => $file_path,
'file_name' => $file_name
]);
} else {
$query = GptQuery::query()->where('run_id', $run_id)->where('thread_id', $thread_id)->first();
$query->update([
'status' => $status,
'response' => $response
]);
}
return $query;
}
多个队列/助手
您还可以在调用ask
函数时传入可选变量,以指定特定消息发送的队列和助手。这允许您在应用程序中使用多个队列和/或助手。以下是一个示例
(new GPTService)->ask($message, $parser, null, $assistantId, $queueName)
在这里,$assistantId
允许您传递您想要在此请求中使用的助手,而$queueName
允许您传递您想要在此请求中使用的队列的名称。ask
函数检查这些变量是否提供。如果提供,它将使用提供的变量,否则将使用配置中的值。