amber-laravel/app/Logic/LLMTool.php

60 lines
1.5 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-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-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-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-24 17:26:29 +00:00
$http = Http::withToken($this->tool->api_key)->post($this->tool->data['callback_url'], [
2024-07-24 17:16:41 +00:00
'function_name' => $function_name,
'parameters' => $parameters,
]);
$r = new FunctionCall();
$r->name = $function_name;
$r->parameters = $parameters;
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;
}
}