amber-laravel/app/Logic/LLMTool.php
2024-07-25 15:41:50 +08:00

85 lines
2.1 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Logic;
use App\Models\Tool;
use App\Models\User;
use App\Repositories\LLM\FunctionCall;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Http;
class LLMTool
{
protected Tool $tool;
protected User $user;
public function setTool(int $tool_id): void
{
$this->tool = Tool::findOrFail($tool_id);
}
public function setUser(User $user): void
{
$this->user = $user;
}
/**
* @throws ConnectionException
*/
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);
$data = [
'function_name' => $function_name,
'parameters' => $parameters,
'user' => [],
];
$r = new FunctionCall();
$r->name = $function_name;
$r->parameters = $parameters;
if (empty($this->tool->api_key)) {
$r->success = false;
$r->result = '[Error] 没有找到 API KEY请先在工具设置中设置 API KEY。';
return $r;
}
if (! empty($this->user)) {
$data['user'] = [
'id' => $this->user->external_id,
'name' => $this->user->name,
];
}
$http = Http::withToken($this->tool->api_key)->post($this->tool->data['callback_url'], $data);
if (! $http->ok()) {
$r->success = false;
$r->result = "[Error] 我们的服务器与工具 $function_name 通讯失败";
}
$d = $http->json();
// 必须有 success 和 message 两个
if (! isset($d['success']) || ! isset($d['message'])) {
$r->success = false;
$r->result = "[Error] 和 工具 $function_name 通讯失败,返回数据格式错误。";
return $r;
}
$r->success = $d['success'];
$r->result = $d['message'];
return $r;
}
}