amber-laravel/app/Logic/LLMTool.php

85 lines
2.1 KiB
PHP
Raw Normal View History

2024-07-24 17:16:41 +00:00
<?php
namespace App\Logic;
2024-07-24 17:26:29 +00:00
use App\Models\Tool;
2024-07-25 07:05:06 +00:00
use App\Models\User;
2024-07-24 17:16:41 +00:00
use App\Repositories\LLM\FunctionCall;
2024-07-24 17:26:29 +00:00
use Illuminate\Http\Client\ConnectionException;
2024-07-24 17:16:41 +00:00
use Illuminate\Support\Facades\Http;
class LLMTool
{
2024-07-24 17:26:29 +00:00
protected Tool $tool;
2024-07-25 07:41:50 +00:00
2024-07-25 07:05:06 +00:00
protected User $user;
2024-07-24 17:16:41 +00:00
2024-07-24 17:26:29 +00:00
public function setTool(int $tool_id): void
2024-07-24 17:16:41 +00:00
{
2024-07-24 17:26:29 +00:00
$this->tool = Tool::findOrFail($tool_id);
2024-07-24 17:16:41 +00:00
}
2024-07-25 07:41:50 +00:00
public function setUser(User $user): void
2024-07-25 07:05:06 +00:00
{
$this->user = $user;
}
2024-07-24 17:26:29 +00:00
/**
* @throws ConnectionException
*/
2024-07-24 17:16:41 +00:00
public function callTool(string $function_name, $parameters = []): FunctionCall
{
// 使用 _ 分割
$names = explode('_', $function_name)[0];
$prefix_length = strlen($names) + 1;
$function_name = substr($function_name, $prefix_length);
2024-07-25 07:05:06 +00:00
$data = [
2024-07-24 17:16:41 +00:00
'function_name' => $function_name,
'parameters' => $parameters,
2024-07-25 07:05:06 +00:00
'user' => [],
];
2024-07-24 17:16:41 +00:00
$r = new FunctionCall();
$r->name = $function_name;
$r->parameters = $parameters;
2024-07-25 07:05:06 +00:00
if (empty($this->tool->api_key)) {
$r->success = false;
2024-07-25 07:41:50 +00:00
$r->result = '[Error] 没有找到 API KEY请先在工具设置中设置 API KEY。';
2024-07-25 07:05:06 +00:00
return $r;
}
2024-07-25 07:41:50 +00:00
if (! empty($this->user)) {
2024-07-25 07:05:06 +00:00
$data['user'] = [
'id' => $this->user->external_id,
2024-07-25 07:41:50 +00:00
'name' => $this->user->name,
2024-07-25 07:05:06 +00:00
];
}
$http = Http::withToken($this->tool->api_key)->post($this->tool->data['callback_url'], $data);
2024-07-24 17:26:40 +00:00
if (! $http->ok()) {
2024-07-24 17:16:41 +00:00
$r->success = false;
$r->result = "[Error] 我们的服务器与工具 $function_name 通讯失败";
}
$d = $http->json();
// 必须有 success 和 message 两个
2024-07-24 17:26:40 +00:00
if (! isset($d['success']) || ! isset($d['message'])) {
2024-07-24 17:16:41 +00:00
$r->success = false;
$r->result = "[Error] 和 工具 $function_name 通讯失败,返回数据格式错误。";
2024-07-24 17:26:40 +00:00
2024-07-24 17:16:41 +00:00
return $r;
}
2024-07-24 17:26:29 +00:00
$r->success = $d['success'];
2024-07-24 17:16:41 +00:00
$r->result = $d['message'];
return $r;
}
}