-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.php
More file actions
217 lines (196 loc) · 5.82 KB
/
main.php
File metadata and controls
217 lines (196 loc) · 5.82 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
<?php
declare(strict_types=1);
/*
* capability_negotiation — capability-driven peer routing with ordered
* fallback + cost rollups via the standard `cost.usd` metric.
*
* RFC §7 (capability negotiation), §17.3.1 (standard metrics), §18.3
* (canonical retry classification), §21 (extensions).
*/
require __DIR__ . '/../../vendor/autoload.php';
use Arcp\Client\ARCPClient;
use Arcp\Envelope\Envelope;
use Arcp\Errors\ARCPException;
use Arcp\Errors\ErrorCode;
use Arcp\Errors\UnavailableException;
use Arcp\Ids\TraceId;
use Arcp\Messages\Execution\ToolResult;
use Arcp\Messages\Telemetry\MetricEvent;
const PEERS = [
'anthropic-haiku',
'anthropic-sonnet',
'openai-4o',
'groq-llama',
];
const FALLBACK_CHAINS = [
'cheap_fast' => ['groq-llama', 'anthropic-haiku', 'openai-4o'],
'balanced' => ['anthropic-sonnet', 'openai-4o', 'anthropic-haiku'],
'deep' => ['anthropic-sonnet'],
];
const COST_CEILING_USD_PER_MTOK = 8.0;
const LATENCY_CEILING_MS = 800;
function isRetryable(ErrorCode $code): bool
{
return in_array($code, [
ErrorCode::ResourceExhausted,
ErrorCode::Unavailable,
ErrorCode::DeadlineExceeded,
ErrorCode::Aborted,
], true);
}
final class Profile
{
public function __construct(
public readonly float $costPerMtok,
public readonly int $p50LatencyMs,
public readonly string $modelClass,
) {
}
}
function profileFrom(ARCPClient $client): Profile
{
// Capabilities allows extra namespaced keys via `extra`.
// NOTE: §21 covers extension *messages* but not extension
// *capability values* — load-bearing convention here.
$caps = $client->session->capabilities;
$extra = $caps !== null ? $caps->extra : [];
return new Profile(
costPerMtok: asFloat($extra['arcpx.market.cost_per_mtok.v1'] ?? 0.0),
p50LatencyMs: asInt($extra['arcpx.market.p50_latency_ms.v1'] ?? 0),
modelClass: asString($extra['arcpx.market.model_class.v1'] ?? 'unknown'),
);
}
function asFloat(mixed $v): float
{
return is_int($v) || is_float($v) || is_string($v) ? (float) $v : 0.0;
}
function asInt(mixed $v): int
{
return is_int($v) || is_float($v) || is_string($v) ? (int) $v : 0;
}
function asString(mixed $v): string
{
return is_string($v) ? $v : (is_scalar($v) ? (string) $v : 'unknown');
}
/**
* @param array<string, Profile> $profiles
*
* @return list<string>
*/
function candidateChain(array $profiles, string $requestClass): array
{
$out = [];
foreach (FALLBACK_CHAINS[$requestClass] ?? [] as $name) {
$p = $profiles[$name] ?? null;
if ($p === null) {
continue;
}
if ($p->costPerMtok > COST_CEILING_USD_PER_MTOK) {
continue;
}
if ($p->p50LatencyMs > LATENCY_CEILING_MS) {
continue;
}
$out[] = $name;
}
return $out;
}
/**
* Walk the chain. Retryable error → next peer; otherwise rethrow.
*
* @param array<string, ARCPClient> $clients
* @param list<string> $chain
* @param array<string, mixed> $arguments
*/
function invokeWithFallback(array $clients, array $chain, string $tool, array $arguments, TraceId $traceId): ToolResult
{
$last = null;
foreach ($chain as $name) {
if (!isset($clients[$name])) {
continue;
}
$client = $clients[$name];
try {
return $client->invokeTool($tool, $arguments, traceId: $traceId);
} catch (ARCPException $exc) {
$last = $exc;
if (isRetryable($exc->code())) {
continue;
}
throw $exc;
}
}
throw $last ?? new UnavailableException('no peers available');
}
final class Usage
{
public int $tokensIn = 0;
public int $tokensOut = 0;
public float $costUsd = 0.0;
/** @var array<string, float> */
public array $byPeer = [];
}
/**
* @param array<string, Usage> $totals
*/
function consumeMetric(Envelope $env, array &$totals): void
{
$msg = $env->payload;
if (!$msg instanceof MetricEvent) {
return;
}
$dims = $msg->dims;
$tenant = asString($dims['tenant'] ?? 'unknown');
$totals[$tenant] ??= new Usage();
$u = $totals[$tenant];
if ($msg->name === 'tokens.used') {
$kind = asString($dims['kind'] ?? '');
if ($kind === 'input') {
$u->tokensIn += (int) $msg->value;
} elseif ($kind === 'output') {
$u->tokensOut += (int) $msg->value;
}
} elseif ($msg->name === 'cost.usd') {
$u->costUsd += (float) $msg->value;
$peer = asString($dims['peer'] ?? 'unknown');
$u->byPeer[$peer] = ($u->byPeer[$peer] ?? 0.0) + (float) $msg->value;
}
}
function main(): void
{
/** @var array<string, ARCPClient> $clients */
$clients = [];
/** @var array<string, Profile> $profiles */
$profiles = [];
foreach (PEERS as $name) {
$c = elided(); // transport per peer URL, identity, auth elided
$clients[$name] = $c;
// Marketplace fields ride on the negotiated capabilities;
// no extra round trip to learn cost / latency / class.
$profiles[$name] = profileFrom($c);
}
/** @var array<string, Usage> $totals */
$totals = [];
foreach ($clients as $c) {
$c->subscribe(['types' => ['metric']], static function (Envelope $env) use (&$totals): void {
consumeMetric($env, $totals);
});
}
$chain = candidateChain($profiles, 'balanced');
$reply = invokeWithFallback(
$clients,
$chain,
'chat.completion',
['prompt' => 'Hello', 'tenant' => 'acme-corp'],
TraceId::random(),
);
printf("got tool.result; usage=%s\n", json_encode($totals));
foreach ($clients as $c) {
$c->close();
}
}
function elided(): ARCPClient
{
throw new \RuntimeException('not implemented');
}
main();