Repository navigation
Expand file tree
/
Copy pathCreateTomReply.php
More file actions
85 lines (68 loc) · 2.75 KB
/
Copy pathCreateTomReply.php
File metadata and controls
85 lines (68 loc) · 2.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?php
declare(strict_types=1);
namespace App\Actions;
use App\Ai\Agents\Tom;
use App\Contracts\Services\ToolDecisionProvider;
use App\Enums\CommitStatus;
use App\Models\Commit;
use App\Models\User;
use App\Queries\TomQuery;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Messages\UserMessage;
use RuntimeException;
final readonly class CreateTomReply
{
public function __construct(private CreateCommit $createCommit, private TomQuery $tomQuery, private ToolDecisionProvider $toolDecision)
{
//
}
public function handle(string $commitId): void
{
$commit = Commit::query()->visibleTo(null)->with('user')->find($commitId);
if (! $commit instanceof Commit) {
return;
}
$tom = $this->tomQuery->get();
if (! $tom instanceof User || ! $commit->isAddressedTo($tom) || ! $this->replyable($commit, $tom) || $commit->user?->is($tom)) {
return;
}
$history = new Tom($commit)->messages();
$tools = $this->toolDecision->tools($commit->body, $history);
$attempt = 0;
$messages = [];
$called = collect();
do {
$response = new Tom($commit, $tools, $messages)->prompt($commit->body);
$messages = [...$messages, new UserMessage($commit->body), ...$response->messages];
$called = $called->concat($response->toolResults->pluck('name'));
$missingTools = $tools->contains(fn (Tool $tool): bool => $called->doesntContain(class_basename($tool)));
$attempt++;
} while ($missingTools && $attempt < 3);
if ($missingTools) {
throw new RuntimeException('Tom skipped a selected tool after retries.');
}
$body = mb_trim($response->text);
if ($body === '') {
throw new RuntimeException('Tom returned an empty reply.');
}
DB::transaction(function () use ($commit, $tom, $body): void {
$current = Commit::query()->lockForUpdate()->find($commit->id);
if (! $current instanceof Commit || $current->status !== CommitStatus::Approved
|| $current->body !== $commit->body || ! $this->replyable($current, $tom)) {
return;
}
$this->createCommit->handle($tom, Str::limit($body, Commit::MAX_BODY_LENGTH - 3), parent: $current, linkPreview: false);
});
}
/**
* Tom replies once per post, and never to someone he has a block with.
*/
private function replyable(Commit $commit, User $tom): bool
{
return $commit->user instanceof User
&& ! $commit->user->hasBlockWith($tom)
&& ! $commit->replies()->withTrashed()->whereBelongsTo($tom)->exists();
}
}