-
-
Notifications
You must be signed in to change notification settings - Fork 305
Expand file tree
/
Copy pathCallsTools.php
More file actions
241 lines (207 loc) · 7.66 KB
/
Copy pathCallsTools.php
File metadata and controls
241 lines (207 loc) · 7.66 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
<?php
declare(strict_types=1);
namespace Prism\Prism\Concerns;
use Generator;
use Illuminate\Support\Facades\Concurrency;
use Illuminate\Support\ItemNotFoundException;
use Illuminate\Support\MultipleItemsFoundException;
use Prism\Prism\Exceptions\PrismException;
use Prism\Prism\Streaming\EventID;
use Prism\Prism\Streaming\Events\ArtifactEvent;
use Prism\Prism\Streaming\Events\ToolResultEvent;
use Prism\Prism\Tool;
use Prism\Prism\ValueObjects\ToolCall;
use Prism\Prism\ValueObjects\ToolError;
use Prism\Prism\ValueObjects\ToolOutput;
use Prism\Prism\ValueObjects\ToolResult;
trait CallsTools
{
/**
* Execute tools and return results (for non-streaming handlers).
*
* @param Tool[] $tools
* @param ToolCall[] $toolCalls
* @return ToolResult[]
*/
protected function callTools(array $tools, array $toolCalls): array
{
$toolResults = [];
// Consume generator to execute all tools and collect results
foreach ($this->callToolsAndYieldEvents($tools, $toolCalls, EventID::generate(), $toolResults) as $event) {
// Events are discarded for non-streaming handlers
}
return $toolResults;
}
/**
* Generate tool execution events and collect results (for streaming handlers).
*
* @param Tool[] $tools
* @param ToolCall[] $toolCalls
* @param ToolResult[] $toolResults Results are collected into this array by reference
* @return Generator<ToolResultEvent|ArtifactEvent>
*/
protected function callToolsAndYieldEvents(array $tools, array $toolCalls, string $messageId, array &$toolResults): Generator
{
$groupedToolCalls = $this->groupToolCallsByConcurrency($tools, $toolCalls);
$executionResults = $this->executeToolsWithConcurrency($tools, $groupedToolCalls, $messageId);
foreach (array_keys($toolCalls) as $index) {
$result = $executionResults[$index];
$toolResults[] = $result['toolResult'];
foreach ($result['events'] as $event) {
yield $event;
}
}
}
/**
* @param Tool[] $tools
* @param ToolCall[] $toolCalls
* @return array{concurrent: array<int, ToolCall>, sequential: array<int, ToolCall>}
*/
protected function groupToolCallsByConcurrency(array $tools, array $toolCalls): array
{
$concurrent = [];
$sequential = [];
foreach ($toolCalls as $index => $toolCall) {
try {
$tool = $this->resolveTool($toolCall->name, $tools);
if ($tool->isConcurrent()) {
$concurrent[$index] = $toolCall;
} else {
$sequential[$index] = $toolCall;
}
} catch (PrismException) {
$sequential[$index] = $toolCall;
}
}
return [
'concurrent' => $concurrent,
'sequential' => $sequential,
];
}
/**
* @param Tool[] $tools
* @param array{concurrent: array<int, ToolCall>, sequential: array<int, ToolCall>} $groupedToolCalls
* @return array<int, array{toolResult: ToolResult, events: array<int, ToolResultEvent|ArtifactEvent>}>
*/
protected function executeToolsWithConcurrency(array $tools, array $groupedToolCalls, string $messageId): array
{
$results = [];
$concurrentClosures = [];
foreach ($groupedToolCalls['concurrent'] as $index => $toolCall) {
$concurrentClosures[$index] = fn () => $this->executeToolCall($tools, $toolCall, $messageId);
}
if ($concurrentClosures !== []) {
foreach (Concurrency::run($concurrentClosures) as $index => $result) {
$results[$index] = $result;
}
}
foreach ($groupedToolCalls['sequential'] as $index => $toolCall) {
$results[$index] = $this->executeToolCall($tools, $toolCall, $messageId);
}
return $results;
}
/**
* @param Tool[] $tools
* @return array{toolResult: ToolResult, events: array<int, ToolResultEvent|ArtifactEvent>}
*/
protected static function executeToolCall(array $tools, ToolCall $toolCall, string $messageId): array
{
$events = [];
try {
$tool = self::resolveTool($toolCall->name, $tools);
$output = call_user_func_array(
$tool->handle(...),
$toolCall->arguments()
);
if ($output instanceof ToolError) {
$toolResult = new ToolResult(
toolCallId: $toolCall->id,
toolName: $toolCall->name,
args: $toolCall->arguments(),
result: $output->message,
toolCallResultId: $toolCall->resultId,
);
$events[] = new ToolResultEvent(
id: EventID::generate(),
timestamp: time(),
toolResult: $toolResult,
messageId: $messageId,
success: false,
error: $output->message,
);
return [
'toolResult' => $toolResult,
'events' => $events,
];
}
if (is_string($output)) {
$output = new ToolOutput(result: $output);
}
$toolResult = new ToolResult(
toolCallId: $toolCall->id,
toolName: $toolCall->name,
args: $toolCall->arguments(),
result: $output->result,
toolCallResultId: $toolCall->resultId,
artifacts: $output->artifacts,
);
$events[] = new ToolResultEvent(
id: EventID::generate(),
timestamp: time(),
toolResult: $toolResult,
messageId: $messageId,
success: true
);
foreach ($toolResult->artifacts as $artifact) {
$events[] = new ArtifactEvent(
id: EventID::generate(),
timestamp: time(),
artifact: $artifact,
toolCallId: $toolCall->id,
toolName: $toolCall->name,
messageId: $messageId,
);
}
return [
'toolResult' => $toolResult,
'events' => $events,
];
} catch (PrismException $e) {
$toolResult = new ToolResult(
toolCallId: $toolCall->id,
toolName: $toolCall->name,
args: $toolCall->arguments(),
result: $e->getMessage(),
toolCallResultId: $toolCall->resultId,
);
$events[] = new ToolResultEvent(
id: EventID::generate(),
timestamp: time(),
toolResult: $toolResult,
messageId: $messageId,
success: false,
error: $e->getMessage()
);
return [
'toolResult' => $toolResult,
'events' => $events,
];
}
}
/**
* @param Tool[] $tools
*
* @throws PrismException
*/
protected static function resolveTool(string $name, array $tools): Tool
{
try {
return collect($tools)
->sole(fn (Tool $tool): bool => $tool->name() === $name);
} catch (ItemNotFoundException $e) {
throw PrismException::toolNotFound($name, $e);
} catch (MultipleItemsFoundException $e) {
throw PrismException::multipleToolsFound($name, $e);
}
}
}