@acruxcoreai/mcp-server 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +48 -0
- package/README.md +3 -2
- package/dist/bin.js +325 -14
- package/dist/bin.js.map +1 -1
- package/dist/bin.mjs +325 -14
- package/dist/bin.mjs.map +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +325 -14
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +325 -14
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
package/dist/index.mjs
CHANGED
|
@@ -194,10 +194,15 @@ function toApiError(label, status, body) {
|
|
|
194
194
|
}
|
|
195
195
|
|
|
196
196
|
// src/format.ts
|
|
197
|
+
var TRUNCATION_MARKER = "\n\n[truncated: response exceeded the size limit \u2014 narrow the query, use a smaller `limit`, or fetch one item at a time]";
|
|
198
|
+
function isTruncated(result) {
|
|
199
|
+
const first = result.content[0];
|
|
200
|
+
return first?.type === "text" && first.text.endsWith(TRUNCATION_MARKER);
|
|
201
|
+
}
|
|
197
202
|
function truncateText(text, maxBytes) {
|
|
198
203
|
const encoder = new TextEncoder();
|
|
199
204
|
if (encoder.encode(text).length <= maxBytes) return text;
|
|
200
|
-
const marker =
|
|
205
|
+
const marker = TRUNCATION_MARKER;
|
|
201
206
|
const budget = Math.max(0, maxBytes - encoder.encode(marker).length);
|
|
202
207
|
let end = Math.min(text.length, budget);
|
|
203
208
|
while (end > 0 && encoder.encode(text.slice(0, end)).length > budget) {
|
|
@@ -583,10 +588,87 @@ var catalogTools = [
|
|
|
583
588
|
|
|
584
589
|
// src/toolsets/evaluations.ts
|
|
585
590
|
import { z as z2 } from "zod";
|
|
591
|
+
|
|
592
|
+
// src/optimize-report.ts
|
|
593
|
+
function summarizeCandidates(grid, cells) {
|
|
594
|
+
const cellByKey = new Map(cells.map((cell) => [cell.cellKey, cell]));
|
|
595
|
+
const baselineByModel = new Map(
|
|
596
|
+
cells.filter((cell) => cell.isProductionBaseline).map((cell) => [cell.model, cell])
|
|
597
|
+
);
|
|
598
|
+
const byCandidate = /* @__PURE__ */ new Map();
|
|
599
|
+
for (const gridCell of grid) {
|
|
600
|
+
if (gridCell.variantKind !== "candidate" || !gridCell.promptCandidateId) continue;
|
|
601
|
+
const reportCell = cellByKey.get(gridCell.cellKey);
|
|
602
|
+
const baseline = baselineByModel.get(gridCell.model);
|
|
603
|
+
let summary = byCandidate.get(gridCell.promptCandidateId);
|
|
604
|
+
if (!summary) {
|
|
605
|
+
summary = {
|
|
606
|
+
candidateId: gridCell.promptCandidateId,
|
|
607
|
+
label: gridCell.variantLabel,
|
|
608
|
+
scores: [],
|
|
609
|
+
beatsBaseline: false
|
|
610
|
+
};
|
|
611
|
+
byCandidate.set(gridCell.promptCandidateId, summary);
|
|
612
|
+
}
|
|
613
|
+
summary.scores.push({
|
|
614
|
+
model: gridCell.model,
|
|
615
|
+
avgScore: reportCell?.avgScore ?? null,
|
|
616
|
+
passRate: reportCell?.passRate ?? null,
|
|
617
|
+
baselineAvgScore: baseline?.avgScore ?? null,
|
|
618
|
+
scoreDelta: reportCell?.deltaVsBaseline?.score ?? null,
|
|
619
|
+
verdict: reportCell?.deltaVsBaseline?.label ?? "unknown"
|
|
620
|
+
});
|
|
621
|
+
}
|
|
622
|
+
const summaries = [...byCandidate.values()];
|
|
623
|
+
for (const summary of summaries) {
|
|
624
|
+
summary.beatsBaseline = summary.scores.some((score) => score.verdict === "improved") && summary.scores.every((score) => score.verdict === "improved" || score.verdict === "flat");
|
|
625
|
+
}
|
|
626
|
+
return summaries.sort((a, b) => a.label.localeCompare(b.label));
|
|
627
|
+
}
|
|
628
|
+
function bestCandidate(candidates) {
|
|
629
|
+
let best = null;
|
|
630
|
+
let bestDelta = -Infinity;
|
|
631
|
+
for (const candidate of candidates) {
|
|
632
|
+
if (!candidate.beatsBaseline) continue;
|
|
633
|
+
const deltas = candidate.scores.map((score) => score.scoreDelta).filter((delta) => delta !== null);
|
|
634
|
+
const mean = deltas.reduce((sum, delta) => sum + delta, 0) / Math.max(1, deltas.length);
|
|
635
|
+
if (mean > bestDelta) {
|
|
636
|
+
best = candidate;
|
|
637
|
+
bestDelta = mean;
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
return best;
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
// src/toolsets/evaluations.ts
|
|
586
644
|
var historyMessageSchema = z2.object({
|
|
587
645
|
role: z2.enum(["system", "user", "assistant", "tool"]),
|
|
588
646
|
content: z2.string()
|
|
589
647
|
});
|
|
648
|
+
async function loadOptimizeRun(client, runId) {
|
|
649
|
+
const run = await client.get(`/runs/${runId}`);
|
|
650
|
+
const notDraftedYet = run.grid.length === 0;
|
|
651
|
+
if (run.kind !== "optimize" && !notDraftedYet) {
|
|
652
|
+
throw new Error(
|
|
653
|
+
`Run ${runId} is an evaluation run, not an optimize run. Read it with get_experiment_run.`
|
|
654
|
+
);
|
|
655
|
+
}
|
|
656
|
+
if (run.status !== "succeeded") return { run, report: null, candidates: [] };
|
|
657
|
+
const report = await client.get(`/runs/${runId}/report`);
|
|
658
|
+
return { run, report, candidates: summarizeCandidates(run.grid, report.cells) };
|
|
659
|
+
}
|
|
660
|
+
function baselineOf(run) {
|
|
661
|
+
const cell = run.grid.find((row) => row.isProductionBaseline && row.promptVersionId);
|
|
662
|
+
if (!cell?.promptVersionId) {
|
|
663
|
+
throw new Error(`Run ${run.id} has no baseline version, so a promote cannot be checked.`);
|
|
664
|
+
}
|
|
665
|
+
const alias = /^v\d+$/.test(cell.variantLabel) ? null : cell.variantLabel;
|
|
666
|
+
return { versionId: cell.promptVersionId, alias };
|
|
667
|
+
}
|
|
668
|
+
function formatDelta(delta) {
|
|
669
|
+
if (delta === null) return "n/a";
|
|
670
|
+
return `${delta >= 0 ? "+" : ""}${delta.toFixed(1)}`;
|
|
671
|
+
}
|
|
590
672
|
var evaluationTools = [
|
|
591
673
|
defineTool({
|
|
592
674
|
name: "list_datasets",
|
|
@@ -665,21 +747,29 @@ var evaluationTools = [
|
|
|
665
747
|
title: "Create and start an experiment run",
|
|
666
748
|
toolset: "evaluations",
|
|
667
749
|
readOnlyHint: false,
|
|
668
|
-
description: "Create an experiment over a dataset and immediately start a run of it. The grid is every (version x model) pair you list. When `prompt` is given, a baseline cell for its production alias is added automatically unless that version is already in the grid. Returns as soon as the run is queued \u2014 the worker executes it asynchronously, so poll get_experiment_run for results.
|
|
750
|
+
description: "Create an experiment over a dataset and immediately start a run of it. The grid is every (version x model) pair you list. When `prompt` is given, a baseline cell for its production alias is added automatically unless that version is already in the grid. Returns as soon as the run is queued \u2014 the worker executes it asynchronously, so poll get_experiment_run for results. `judge_model` scores every answer and must be registered in the gateway (see list_models). `judge_prompt` grades with one of your prompts instead of the built-in judge.",
|
|
669
751
|
inputSchema: {
|
|
670
752
|
dataset_id: z2.string().uuid().describe("Dataset to evaluate against."),
|
|
671
753
|
version_ids: z2.array(z2.string().uuid()).min(1).describe("Prompt-version UUIDs to sweep. At least one."),
|
|
672
754
|
models: z2.array(z2.string().min(1)).min(1).describe("Gateway model public names to sweep."),
|
|
673
755
|
prompt: z2.string().optional().describe("Prompt name or UUID under test \u2014 enables the automatic baseline cell."),
|
|
674
756
|
name: z2.string().optional().describe("Experiment name, for the run history."),
|
|
675
|
-
alias: z2.string().optional().describe('Which alias the automatic baseline points at. Default "production".')
|
|
757
|
+
alias: z2.string().optional().describe('Which alias the automatic baseline points at. Default "production".'),
|
|
758
|
+
judge_model: z2.string().min(1).describe("Gateway model that scores every answer. Required."),
|
|
759
|
+
judge_prompt: z2.string().min(1).optional().describe(
|
|
760
|
+
"Name or UUID of a team prompt that grades instead of the built-in judge. The run uses its production version (else its latest). Default: the built-in judge."
|
|
761
|
+
)
|
|
676
762
|
},
|
|
677
763
|
async handler(args, { client, config }) {
|
|
678
764
|
const body = {
|
|
679
765
|
dataset_id: args.dataset_id,
|
|
680
766
|
version_ids: args.version_ids,
|
|
681
|
-
models: args.models
|
|
767
|
+
models: args.models,
|
|
768
|
+
judge_model: args.judge_model
|
|
682
769
|
};
|
|
770
|
+
if (args.judge_prompt !== void 0) {
|
|
771
|
+
body.judge_prompt_id = await resolvePromptRef(client, args.judge_prompt);
|
|
772
|
+
}
|
|
683
773
|
if (args.name !== void 0) body.name = args.name;
|
|
684
774
|
if (args.alias !== void 0) body.alias = args.alias;
|
|
685
775
|
if (args.prompt !== void 0) body.prompt_id = await resolvePromptRef(client, args.prompt);
|
|
@@ -721,23 +811,214 @@ var evaluationTools = [
|
|
|
721
811
|
title: "Get a run, optionally with its comparison report",
|
|
722
812
|
toolset: "evaluations",
|
|
723
813
|
readOnlyHint: true,
|
|
724
|
-
description: "Read one run's status and results. With include_report=true it also fetches the comparison report: the full (variant x model) matrix with per-cell averages, each cell's delta against the same-model production baseline, a leaderboard and an advisory winner. Ask for the report only once the run has succeeded \u2014 an in-flight run has nothing to compare.",
|
|
814
|
+
description: "Read one run's status and results. With include_report=true it also fetches the comparison report: the full (variant x model) matrix with per-cell averages, each cell's delta against the same-model production baseline, a leaderboard and an advisory winner. Ask for the report only once the run has succeeded \u2014 an in-flight run has nothing to compare. For an optimize run, get_optimize_report gives the same scores per candidate, with the ids promote_optimize_candidate needs.",
|
|
725
815
|
inputSchema: {
|
|
726
816
|
run_id: z2.string().uuid().describe("Run UUID."),
|
|
727
817
|
include_report: z2.boolean().optional().describe("Also fetch the comparison report.")
|
|
728
818
|
},
|
|
729
819
|
async handler({ run_id, include_report }, { client, config }) {
|
|
730
|
-
const run = await client.get(
|
|
820
|
+
const run = await client.get(
|
|
821
|
+
`/runs/${run_id}`
|
|
822
|
+
);
|
|
731
823
|
let report = void 0;
|
|
732
824
|
if (include_report) {
|
|
733
825
|
report = await client.get(`/runs/${run_id}/report`);
|
|
734
826
|
}
|
|
735
827
|
return okResult(
|
|
736
|
-
`Run ${run_id} is ${run.status} with ${run.results?.
|
|
828
|
+
`Run ${run_id} is ${run.status} with ${run.results?.total ?? 0} result(s).`,
|
|
737
829
|
{ run, report },
|
|
738
830
|
config.maxTextBytes
|
|
739
831
|
);
|
|
740
832
|
}
|
|
833
|
+
}),
|
|
834
|
+
defineTool({
|
|
835
|
+
name: "optimize_prompt",
|
|
836
|
+
title: "Start an optimizer run for a prompt",
|
|
837
|
+
toolset: "evaluations",
|
|
838
|
+
readOnlyHint: false,
|
|
839
|
+
description: 'Ask the optimizer to improve a prompt against a dataset. An optimizer model drafts `draft_count` rewrites of the version behind `alias` (default "production"), then every rewrite and that baseline run over the dataset on each of `models`, and `judge_model` scores every answer. Returns the run id as soon as the run is queued \u2014 drafting and scoring take minutes, so poll get_optimize_report. Nothing is promoted automatically: a rewrite only ships when promote_optimize_candidate is called. The dataset\'s examples need `criteria`, or the built-in judge has nothing to grade against. `judge_prompt` grades with one of your prompts instead, and the optimizer reads it too, so the rewrites aim at that rubric. Every model named here must be registered in the gateway (see list_models).',
|
|
840
|
+
inputSchema: {
|
|
841
|
+
prompt: z2.string().min(1).describe("Prompt name or UUID to improve."),
|
|
842
|
+
dataset_id: z2.string().uuid().describe("Dataset whose examples the rewrites are scored on."),
|
|
843
|
+
models: z2.array(z2.string().min(1)).min(1).describe("Gateway model public names to test each rewrite and the baseline on."),
|
|
844
|
+
judge_model: z2.string().min(1).describe("Gateway model that scores every answer. Required."),
|
|
845
|
+
optimizer_model: z2.string().min(1).optional().describe("Gateway model that writes the rewrites. Default: the first entry of `models`."),
|
|
846
|
+
draft_count: z2.number().int().min(1).max(6).optional().describe("How many rewrites to draft, 1 to 6. Default 3."),
|
|
847
|
+
alias: z2.string().min(1).optional().describe('Alias whose version is the baseline to beat. Default "production".'),
|
|
848
|
+
optimizer_prompt: z2.string().optional().describe("Name or UUID of a team prompt to use as the optimizer's instructions."),
|
|
849
|
+
judge_prompt: z2.string().min(1).optional().describe(
|
|
850
|
+
"Name or UUID of a team prompt that grades instead of the built-in judge. The run uses its production version (else its latest). Default: the built-in judge."
|
|
851
|
+
)
|
|
852
|
+
},
|
|
853
|
+
async handler(args, { client, config }) {
|
|
854
|
+
const promptId = await resolvePromptRef(client, args.prompt);
|
|
855
|
+
const body = {
|
|
856
|
+
dataset_id: args.dataset_id,
|
|
857
|
+
models: args.models,
|
|
858
|
+
judge_model: args.judge_model
|
|
859
|
+
};
|
|
860
|
+
if (args.optimizer_model !== void 0) body.optimizer_model = args.optimizer_model;
|
|
861
|
+
if (args.draft_count !== void 0) body.draft_count = args.draft_count;
|
|
862
|
+
if (args.alias !== void 0) body.alias = args.alias;
|
|
863
|
+
if (args.optimizer_prompt !== void 0) {
|
|
864
|
+
body.optimizer_prompt_id = await resolvePromptRef(client, args.optimizer_prompt);
|
|
865
|
+
}
|
|
866
|
+
if (args.judge_prompt !== void 0) {
|
|
867
|
+
body.judge_prompt_id = await resolvePromptRef(client, args.judge_prompt);
|
|
868
|
+
}
|
|
869
|
+
const result = await client.post(`/prompts/${promptId}/optimize`, body);
|
|
870
|
+
const warning = result.prompt_mismatch_warning ? " Warning: some dataset examples were built from a different prompt \u2014 see prompt_mismatch_warning." : "";
|
|
871
|
+
return okResult(
|
|
872
|
+
`Optimize run ${result.run_id} is ${result.status}; ${result.optimizer_model} drafts the rewrites, then they are scored against the ${args.alias ?? "production"} baseline. Poll get_optimize_report with this run id.${warning}`,
|
|
873
|
+
result,
|
|
874
|
+
config.maxTextBytes
|
|
875
|
+
);
|
|
876
|
+
}
|
|
877
|
+
}),
|
|
878
|
+
defineTool({
|
|
879
|
+
name: "get_optimize_report",
|
|
880
|
+
title: "Read an optimizer run's candidates and scores",
|
|
881
|
+
toolset: "evaluations",
|
|
882
|
+
readOnlyHint: true,
|
|
883
|
+
description: "Read an optimize run started by optimize_prompt. While it is queued or running this returns only its status \u2014 call again later. Once it has succeeded it lists every drafted rewrite with its candidate id, the optimizer's rationale, the rewritten messages, and its average score next to the baseline's on each model. `beatsBaseline` is true only for a rewrite that improved on at least one model and was improved or flat on every other; `recommended` is the one among those with the largest gain, or null when no rewrite beat the baseline. When the rewrites are too long to fit in one result, their messages are left out (`messagesOmitted`); pass `candidate_id` to read one rewrite in full.",
|
|
884
|
+
inputSchema: {
|
|
885
|
+
run_id: z2.string().uuid().describe("Optimize run UUID, from optimize_prompt."),
|
|
886
|
+
candidate_id: z2.string().uuid().optional().describe("Return only this candidate, with its full messages.")
|
|
887
|
+
},
|
|
888
|
+
async handler({ run_id, candidate_id }, { client, config }) {
|
|
889
|
+
const { run, report, candidates } = await loadOptimizeRun(client, run_id);
|
|
890
|
+
if (run.status === "queued" || run.status === "running") {
|
|
891
|
+
return okResult(
|
|
892
|
+
`Optimize run ${run_id} is ${run.status}. No scores yet \u2014 call get_optimize_report again shortly.`,
|
|
893
|
+
{ runId: run_id, status: run.status },
|
|
894
|
+
config.maxTextBytes
|
|
895
|
+
);
|
|
896
|
+
}
|
|
897
|
+
if (run.status === "failed") {
|
|
898
|
+
return okResult(
|
|
899
|
+
`Optimize run ${run_id} failed: ${run.error ?? "no reason recorded"}. Nothing to promote.`,
|
|
900
|
+
{ runId: run_id, status: run.status, error: run.error },
|
|
901
|
+
config.maxTextBytes
|
|
902
|
+
);
|
|
903
|
+
}
|
|
904
|
+
if (candidate_id !== void 0) {
|
|
905
|
+
const candidate = candidates.find((row) => row.candidateId === candidate_id);
|
|
906
|
+
if (!candidate) {
|
|
907
|
+
throw new Error(`Candidate ${candidate_id} is not a rewrite from run ${run_id}.`);
|
|
908
|
+
}
|
|
909
|
+
const detail = await client.get(
|
|
910
|
+
`/runs/${run_id}/candidates/${candidate_id}`
|
|
911
|
+
);
|
|
912
|
+
return okResult(
|
|
913
|
+
`${candidate.label} (candidate_id ${candidate_id}) from optimize run ${run_id}; beatsBaseline: ${candidate.beatsBaseline}.`,
|
|
914
|
+
{
|
|
915
|
+
runId: run_id,
|
|
916
|
+
candidate: { ...candidate, rationale: detail.rationale, messages: detail.messages }
|
|
917
|
+
},
|
|
918
|
+
config.maxTextBytes
|
|
919
|
+
);
|
|
920
|
+
}
|
|
921
|
+
const reads = await Promise.allSettled(
|
|
922
|
+
candidates.map(
|
|
923
|
+
(candidate) => client.get(`/runs/${run_id}/candidates/${candidate.candidateId}`)
|
|
924
|
+
)
|
|
925
|
+
);
|
|
926
|
+
const withContent = candidates.map((candidate, index) => {
|
|
927
|
+
const read = reads[index];
|
|
928
|
+
return read.status === "fulfilled" ? { ...candidate, rationale: read.value.rationale, messages: read.value.messages } : {
|
|
929
|
+
...candidate,
|
|
930
|
+
rationale: null,
|
|
931
|
+
messages: null,
|
|
932
|
+
readError: read.reason instanceof Error ? read.reason.message : String(read.reason)
|
|
933
|
+
};
|
|
934
|
+
});
|
|
935
|
+
const best = bestCandidate(candidates);
|
|
936
|
+
const winners = candidates.filter((candidate) => candidate.beatsBaseline).length;
|
|
937
|
+
const rejected = report?.optimizerRejections ?? [];
|
|
938
|
+
const rejectedNote = rejected.length > 0 ? ` ${rejected.length} more rewrite(s) were dropped before scoring: ${rejected.join(" | ")}.` : "";
|
|
939
|
+
const summary = (best ? `Optimize run ${run_id} succeeded. ${winners} of ${candidates.length} rewrite(s) beat the baseline. Recommended: ${best.label} (candidate_id ${best.candidateId}), ` + best.scores.map((score) => `${formatDelta(score.scoreDelta)} on ${score.model}`).join(", ") + ". Promote it with promote_optimize_candidate only if the user agrees." : `Optimize run ${run_id} succeeded, but none of its ${candidates.length} rewrite(s) beat the baseline. Nothing is worth promoting; keep the current version.`) + rejectedNote;
|
|
940
|
+
const payload = {
|
|
941
|
+
runId: run_id,
|
|
942
|
+
status: run.status,
|
|
943
|
+
judgeModel: report?.judge?.model ?? null,
|
|
944
|
+
// Null means the built-in judge graded the run.
|
|
945
|
+
judgePromptVersionId: report?.judge?.promptVersionId ?? null,
|
|
946
|
+
recommended: best?.candidateId ?? null,
|
|
947
|
+
rejectedRewrites: rejected,
|
|
948
|
+
baseline: (report?.cells ?? []).filter((cell) => cell.isProductionBaseline).map((cell) => ({
|
|
949
|
+
label: cell.variantLabel,
|
|
950
|
+
model: cell.model,
|
|
951
|
+
avgScore: cell.avgScore,
|
|
952
|
+
passRate: cell.passRate
|
|
953
|
+
})),
|
|
954
|
+
candidates: withContent
|
|
955
|
+
};
|
|
956
|
+
const full = okResult(summary, payload, config.maxTextBytes);
|
|
957
|
+
if (!isTruncated(full)) return full;
|
|
958
|
+
return okResult(
|
|
959
|
+
`${summary} The rewrites are too long to show together, so their messages are left out; call get_optimize_report again with candidate_id to read one.`,
|
|
960
|
+
{
|
|
961
|
+
...payload,
|
|
962
|
+
messagesOmitted: true,
|
|
963
|
+
candidates: withContent.map(({ messages: _messages, ...rest }) => rest)
|
|
964
|
+
},
|
|
965
|
+
config.maxTextBytes
|
|
966
|
+
);
|
|
967
|
+
}
|
|
968
|
+
}),
|
|
969
|
+
defineTool({
|
|
970
|
+
name: "promote_optimize_candidate",
|
|
971
|
+
title: "Ship an optimizer rewrite as a new prompt version",
|
|
972
|
+
toolset: "evaluations",
|
|
973
|
+
readOnlyHint: false,
|
|
974
|
+
destructiveHint: true,
|
|
975
|
+
description: "Commit one rewrite from a succeeded optimize run as a new prompt version and move `alias` to it, so live traffic on that alias starts using it. `alias` defaults to the alias the run was scored against (production when the run used the latest version). Take `candidate_id` from get_optimize_report. Refuses a rewrite that did not beat the baseline, and refuses when the alias now points at a version other than the one the run scored against; set `promote_without_improvement` only when the user has explicitly asked to ship that rewrite anyway. Undo by moving the alias back with promote_prompt_alias.",
|
|
976
|
+
inputSchema: {
|
|
977
|
+
run_id: z2.string().uuid().describe("Optimize run UUID."),
|
|
978
|
+
candidate_id: z2.string().uuid().describe("Candidate id from get_optimize_report."),
|
|
979
|
+
alias: z2.string().min(1).optional().describe("Alias to move. Default: the alias the run was scored against."),
|
|
980
|
+
promote_without_improvement: z2.boolean().optional().describe(
|
|
981
|
+
"Ship a rewrite that did not beat the baseline, or replace a version the run never scored. Only on the user's explicit say-so."
|
|
982
|
+
)
|
|
983
|
+
},
|
|
984
|
+
async handler(args, { client, config }) {
|
|
985
|
+
const { run, candidates } = await loadOptimizeRun(client, args.run_id);
|
|
986
|
+
if (run.status !== "succeeded") {
|
|
987
|
+
throw new Error(
|
|
988
|
+
`Optimize run ${args.run_id} is ${run.status}, so its rewrites are not fully scored. Promote only from a succeeded run.`
|
|
989
|
+
);
|
|
990
|
+
}
|
|
991
|
+
const candidate = candidates.find((row) => row.candidateId === args.candidate_id);
|
|
992
|
+
if (!candidate) {
|
|
993
|
+
throw new Error(
|
|
994
|
+
`Candidate ${args.candidate_id} is not a rewrite from run ${args.run_id}. Take the id from get_optimize_report.`
|
|
995
|
+
);
|
|
996
|
+
}
|
|
997
|
+
if (!candidate.beatsBaseline && !args.promote_without_improvement) {
|
|
998
|
+
const scores = candidate.scores.map((score) => `${formatDelta(score.scoreDelta)} (${score.verdict}) on ${score.model}`).join(", ");
|
|
999
|
+
throw new Error(
|
|
1000
|
+
`Refused: ${candidate.label} did not beat the baseline (${scores}). Promoting it would ship a prompt that scored no better than the current one. Set promote_without_improvement to true only if the user explicitly asked for this rewrite.`
|
|
1001
|
+
);
|
|
1002
|
+
}
|
|
1003
|
+
const baseline = baselineOf(run);
|
|
1004
|
+
const alias = args.alias ?? baseline.alias ?? "production";
|
|
1005
|
+
const detail = await client.get(
|
|
1006
|
+
`/runs/${args.run_id}/candidates/${args.candidate_id}`
|
|
1007
|
+
);
|
|
1008
|
+
const aliases = await client.get(`/prompts/${detail.promptId}/aliases`);
|
|
1009
|
+
const live = aliases.find((row) => row.alias === alias);
|
|
1010
|
+
if (live && live.versionId !== baseline.versionId && !args.promote_without_improvement) {
|
|
1011
|
+
throw new Error(
|
|
1012
|
+
`Refused: alias "${alias}" now points at version ${live.versionNumber}, but run ${args.run_id} scored its rewrites against a different version. Nothing compared ${candidate.label} with version ${live.versionNumber}. Start a new optimize run against this alias, or set promote_without_improvement to true only if the user explicitly asked to replace it anyway.`
|
|
1013
|
+
);
|
|
1014
|
+
}
|
|
1015
|
+
const result = await client.post(`/runs/${args.run_id}/promote`, { prompt_candidate_id: args.candidate_id, alias });
|
|
1016
|
+
return okResult(
|
|
1017
|
+
`Promoted ${candidate.label} as version ${result.version.versionNumber}; alias "${result.alias.alias}" now points at it.`,
|
|
1018
|
+
result,
|
|
1019
|
+
config.maxTextBytes
|
|
1020
|
+
);
|
|
1021
|
+
}
|
|
741
1022
|
})
|
|
742
1023
|
];
|
|
743
1024
|
|
|
@@ -764,6 +1045,9 @@ function gatewayMeta(headers) {
|
|
|
764
1045
|
}
|
|
765
1046
|
return meta;
|
|
766
1047
|
}
|
|
1048
|
+
function traceSuffix(meta) {
|
|
1049
|
+
return meta["trace-id"] ? ` Open it with get_trace, trace_id ${meta["trace-id"]}.` : "";
|
|
1050
|
+
}
|
|
767
1051
|
function firstChoiceText(body) {
|
|
768
1052
|
const choice = body?.choices?.[0];
|
|
769
1053
|
const content = choice?.message?.content;
|
|
@@ -808,9 +1092,7 @@ var gatewayTools = [
|
|
|
808
1092
|
});
|
|
809
1093
|
const meta = gatewayMeta(response.headers);
|
|
810
1094
|
return okResult(
|
|
811
|
-
`Ran "${name}"@${args.alias ?? "production"} on ${meta.model ?? "the resolved model"}${meta["cost-usd"] ? ` for $${meta["cost-usd"]}` : ""}
|
|
812
|
-
response.data
|
|
813
|
-
).slice(0, 400)}`,
|
|
1095
|
+
`Ran "${name}"@${args.alias ?? "production"} on ${meta.model ?? "the resolved model"}${meta["cost-usd"] ? ` for $${meta["cost-usd"]}` : ""}.${traceSuffix(meta)} Reply: ` + firstChoiceText(response.data).slice(0, 400),
|
|
814
1096
|
{ completion: response.data, gateway: meta },
|
|
815
1097
|
config.maxTextBytes
|
|
816
1098
|
);
|
|
@@ -851,9 +1133,7 @@ var gatewayTools = [
|
|
|
851
1133
|
});
|
|
852
1134
|
const meta = gatewayMeta(response.headers);
|
|
853
1135
|
return okResult(
|
|
854
|
-
`Completion from ${meta.model ?? args.model}${meta["cost-usd"] ? ` ($${meta["cost-usd"]})` : ""}:
|
|
855
|
-
response.data
|
|
856
|
-
).slice(0, 400)}`,
|
|
1136
|
+
`Completion from ${meta.model ?? args.model}${meta["cost-usd"] ? ` ($${meta["cost-usd"]})` : ""}.${traceSuffix(meta)} Reply: ` + firstChoiceText(response.data).slice(0, 400),
|
|
857
1137
|
{ completion: response.data, gateway: meta },
|
|
858
1138
|
config.maxTextBytes
|
|
859
1139
|
);
|
|
@@ -893,6 +1173,37 @@ var gatewayTools = [
|
|
|
893
1173
|
config.maxTextBytes
|
|
894
1174
|
);
|
|
895
1175
|
}
|
|
1176
|
+
}),
|
|
1177
|
+
defineTool({
|
|
1178
|
+
name: "get_spending_limits",
|
|
1179
|
+
title: "Get budgets and virtual-key limits",
|
|
1180
|
+
toolset: "gateway",
|
|
1181
|
+
readOnlyHint: true,
|
|
1182
|
+
description: "Every spend budget on the team \u2014 team-wide or on one virtual key \u2014 with its period, limit, live spend, what is left and when it resets, plus each virtual key's rate limits and model/provider allow-lists. Use this after a gateway call is refused with HTTP 402 (budget spent) or 429 (rate limit) to see which limit caused it. Read-only: budgets and keys are changed in the dashboard.",
|
|
1183
|
+
inputSchema: {},
|
|
1184
|
+
async handler(_args, { client, config }) {
|
|
1185
|
+
const [budgets, keys] = await Promise.all([
|
|
1186
|
+
client.get("/gateway/budgets"),
|
|
1187
|
+
client.get("/gateway/keys")
|
|
1188
|
+
]);
|
|
1189
|
+
const keyNames = new Map(keys.map((k) => [k.id, k.name]));
|
|
1190
|
+
const limits = budgets.map((b) => ({
|
|
1191
|
+
id: b.id,
|
|
1192
|
+
scope: b.virtualKeyId === null ? "team" : "virtual_key",
|
|
1193
|
+
virtualKeyId: b.virtualKeyId,
|
|
1194
|
+
virtualKeyName: b.virtualKeyId === null ? null : keyNames.get(b.virtualKeyId) ?? null,
|
|
1195
|
+
period: b.period,
|
|
1196
|
+
limitUsd: b.limitUsd,
|
|
1197
|
+
spendUsd: b.spendUsd,
|
|
1198
|
+
remainingUsd: Math.max(0, b.limitUsd - b.spendUsd),
|
|
1199
|
+
exhausted: b.spendUsd >= b.limitUsd,
|
|
1200
|
+
resetsAt: b.resetsAt
|
|
1201
|
+
}));
|
|
1202
|
+
const summary = limits.length === 0 ? `No budgets on this team, so the gateway never refuses a call for spend. ${keys.length} virtual key(s).` : `${limits.length} budget(s), ${keys.length} virtual key(s). ` + limits.map(
|
|
1203
|
+
(l) => `${l.scope === "team" ? "Team" : `Key "${l.virtualKeyName ?? l.virtualKeyId}"`} ${l.period}: $${l.spendUsd} of $${l.limitUsd} spent` + (l.exhausted ? " (EXHAUSTED)" : "") + (l.resetsAt ? `, resets ${l.resetsAt}` : "")
|
|
1204
|
+
).join("; ") + ".";
|
|
1205
|
+
return okResult(summary, { budgets: limits, virtualKeys: keys }, config.maxTextBytes);
|
|
1206
|
+
}
|
|
896
1207
|
})
|
|
897
1208
|
];
|
|
898
1209
|
|
|
@@ -1258,7 +1569,7 @@ function selectTools(config) {
|
|
|
1258
1569
|
}
|
|
1259
1570
|
|
|
1260
1571
|
// src/server.ts
|
|
1261
|
-
var SERVER_VERSION = "0.
|
|
1572
|
+
var SERVER_VERSION = "0.3.0";
|
|
1262
1573
|
function buildInstructions(toolNames, readOnly) {
|
|
1263
1574
|
const parts = [
|
|
1264
1575
|
`AcruxCore is an LLM-ops platform: a prompt registry, a versioned tool catalog, an AI gateway, tracing, and evaluation.
|