Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions evals/group-conversation/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,16 @@ The four judge criteria are distinct useful ideas, explicit engagement with a pe

## Run

Put `ANTHROPIC_API_KEY` and `OPENAI_API_KEY` in the repo root `.env`. The package script loads that file. Direct APIs are the default. `--proxy` explicitly uses the existing MCP eval's `vibeproxy` configuration for GPT models instead. Missing credentials produce error rows, never model substitutions or passing samples.
Put `ANTHROPIC_API_KEY` and `OPENAI_API_KEY` in the repo root `.env`. The package script loads that file. Direct APIs are the default. `--proxy` explicitly uses the existing MCP eval's `vibeproxy` configuration for GPT models instead. `morph-` models, listed under Free in the table below, call Morph's free OpenAI-compatible API with `MORPH_API_KEY`, or the `morph` provider in OpenCode's config (`$XDG_CONFIG_HOME` or `~/.config`). Missing credentials produce error rows, never model substitutions or passing samples.

The model IDs below are the intended design pairings. They are not cheap shell models.

| Purpose | Models |
| ----------- | ------------------------------- |
| Pairing 1 | `claude-opus-5-5,gpt-6-astra` |
| Pairing 2 | `claude-sonnet-5-5,gpt-6.1-sol` |
| Blind judge | `claude-sonnet-5-5` |
| Purpose | Models |
| ----------- | ------------------------------------------------------ |
| Pairing 1 | `claude-opus-5-5,gpt-6-astra` |
| Pairing 2 | `claude-sonnet-5-5,gpt-6.1-sol` |
| Blind judge | `claude-sonnet-5-5` |
| Free | `morph-kimik31,morph-dsv41flash`, judge `morph-kimik3` |

```sh
cd evals
Expand All @@ -40,7 +41,7 @@ pnpm group-conversation --out runs/group-small --model claude-opus-5-5,gpt-6-ast
pnpm group-conversation --out runs/group-dry --model claude-opus-5-5,gpt-6-astra --judge claude-sonnet-5-5 --samples 1 --dry-run
```

`--out` is required. `--model` accepts one model for behavior cases, or a comma-separated primary/seat pair for design cases. Repeat it for the two pairings. `--case` accepts comma-separated IDs. `--baseline <results.json>` compares behavior rates only with identical models, cases, settings, and grader hashes. Prompt hashes may differ because the purpose is to measure text changes. `--samples` defaults to 3. `--effort` defaults to high. The fixed reply budget is 220 words. Each API call has a 120-second deadline and no retries. Errors stay out of pass rates but prevent promotion. Existing output directories with results are rejected to prevent accidental overwrites.
`--out` is required. `--model` accepts one model for behavior cases, or a comma-separated primary/seat pair for design cases. Repeat it for the two pairings. `--case` accepts comma-separated IDs. `--baseline <results.json>` compares behavior rates only with identical models, cases, settings, and grader hashes. Prompt hashes may differ because the purpose is to measure text changes. `--samples` defaults to 3. `--effort` defaults to high. The fixed reply budget is 220 words. Each request has a 120-second deadline. HTTP 429 and 5xx responses retry up to twice, waiting for `Retry-After` or 2 then 4 seconds, because they are transport, not model behaviour. Errors stay out of pass rates but prevent promotion. Existing output directories with results are rejected to prevent accidental overwrites.

Start with one case and one sample, inspect all requests and outputs, then run the small set. The default set has three design cases and fourteen behavior cases. Three samples and both pairings cost at most 312 participant turns and 174 judge calls before tool continuations. PASS and early closure can reduce design calls. File operations and delegation are simulated in memory. No real agent, file write, or child task is launched by a participant. Tools in the simulation can still fail the case. A behavior case passes only when a strict majority of its samples pass; errors make it incomplete.

Expand Down
43 changes: 43 additions & 0 deletions evals/group-conversation/client.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { expect, it, vi } from "vite-plus/test";

import { makeClient } from "./client.ts";

it("times out when response headers arrive but the body stalls", async () => {
vi.useFakeTimers();
vi.stubEnv("OPENAI_API_KEY", "eval-test-key");
const reading = Promise.withResolvers<void>();
const body = Promise.withResolvers<ArrayBuffer>();
const response = new Response(null, { status: 200 });
using _body = vi.spyOn(response, "arrayBuffer").mockImplementation(() => {
reading.resolve();
return body.promise;
});
using _fetch = vi.spyOn(globalThis, "fetch").mockResolvedValue(response);
const completed = new TextEncoder().encode(
JSON.stringify({
status: "completed",
output: [{ type: "message", content: [{ type: "output_text", text: "Finished" }] }],
usage: { input_tokens: 1, output_tokens: 1 },
}),
).buffer;
try {
const client = makeClient({ proxy: false, effort: "low" });
const result = client.call("gpt-test", "Answer", [], [], "timeout regression").then(
(value) => ({ value }),
(error: unknown) => ({ error }),
);
await vi.advanceTimersByTimeAsync(0);
await reading.promise;
await vi.advanceTimersByTimeAsync(120_001);
body.resolve(completed);
expect(await result).toMatchObject({ error: { _tag: "TimeoutError" } });
expect(client.attempts).toEqual([
{ model: "gpt-test", purpose: "timeout regression", completed: false },
]);
expect(client.ledger).toEqual([]);
} finally {
body.resolve(completed);
vi.unstubAllEnvs();
vi.useRealTimers();
}
});
60 changes: 42 additions & 18 deletions evals/group-conversation/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import * as NodePerfHooks from "node:perf_hooks";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";
import { proxyConfig } from "../shared/proxy.ts";
import { morphConfig, proxyConfig } from "../shared/proxy.ts";

export interface ApiTool {
readonly name: string;
Expand Down Expand Up @@ -61,6 +61,8 @@ const decodePreserved = Schema.decodeUnknownSync(
}),
);

const MAX_ATTEMPTS = 3;

export function makeClient(options: { readonly proxy: boolean; readonly effort: string }) {
const attempts: Array<{ model: string; purpose: string; completed: boolean }> = [];
const ledger: Array<{
Expand All @@ -73,11 +75,21 @@ export function makeClient(options: { readonly proxy: boolean; readonly effort:
request: unknown;
response: unknown;
}> = [];
// Read once per run: each read spawns python, and a mid-run config edit must not split the run.
let morph: ReturnType<typeof morphConfig> | undefined;
const unavailable = (model: string) => {
if (model.startsWith("claude-"))
return process.env.ANTHROPIC_API_KEY
? null
: "ANTHROPIC_API_KEY missing from repo-root .env and process environment.";
if (model.startsWith("morph-")) {
try {
morph ??= morphConfig();
return null;
} catch {
return "Morph unavailable; set MORPH_API_KEY or add a morph provider to ~/.config/opencode/opencode.json. No substitution.";
}
}
if (!model.startsWith("gpt-")) return `Unsupported model family for ${model}. No substitution.`;
if (!options.proxy)
return process.env.OPENAI_API_KEY
Expand All @@ -101,7 +113,9 @@ export function makeClient(options: { readonly proxy: boolean; readonly effort:
const missing = unavailable(model);
if (missing) throw new Error(missing);
const claude = model.startsWith("claude-");
const proxy = !claude && options.proxy ? proxyConfig() : undefined;
const isMorph = model.startsWith("morph-");
const proxy = isMorph ? undefined : !claude && options.proxy ? proxyConfig() : undefined;
const responsesEndpoint = isMorph ? morph : proxy;
const request = claude
? {
model,
Expand Down Expand Up @@ -182,26 +196,36 @@ export function makeClient(options: { readonly proxy: boolean; readonly effort:
attempts.push(attempt);
const headers = claude
? { "x-api-key": process.env.ANTHROPIC_API_KEY!, "anthropic-version": "2023-06-01" }
: (proxy?.headers ?? { Authorization: `Bearer ${process.env.OPENAI_API_KEY!}` });
: (responsesEndpoint?.headers ?? { Authorization: `Bearer ${process.env.OPENAI_API_KEY!}` });
const body = await Effect.runPromise(
Effect.gen(function* () {
const client = yield* HttpClient.HttpClient;
const response = yield* HttpClientRequest.post(
claude
? "https://api.anthropic.com/v1/messages"
: `${proxy?.url ?? "https://api.openai.com/v1"}/responses`,
).pipe(
HttpClientRequest.setHeaders(headers),
HttpClientRequest.bodyJson(request),
Effect.flatMap(client.execute),
);
if (response.status !== 200)
return yield* Effect.die(
new Error(
`Model API HTTP ${response.status}. Response body omitted to avoid leaking credentials.`,
),
for (let attempt = 1; ; attempt++) {
const response = yield* HttpClientRequest.post(
claude
? "https://api.anthropic.com/v1/messages"
: `${responsesEndpoint?.url ?? "https://api.openai.com/v1"}/responses`,
).pipe(
HttpClientRequest.setHeaders(headers),
HttpClientRequest.bodyJson(request),
Effect.flatMap(client.execute),
);
return yield* response.text;
// Rate limits and server errors are transport, not model behaviour, so they get retries.
if ((response.status === 429 || response.status >= 500) && attempt < MAX_ATTEMPTS) {
const retryAfter = Number(response.headers["retry-after"]);
yield* Effect.sleep(
`${retryAfter > 0 ? Math.min(retryAfter, 60) : 2 ** attempt} seconds`,
);
continue;
}
if (response.status !== 200)
return yield* Effect.die(
new Error(
`Model API HTTP ${response.status}. Response body omitted to avoid leaking credentials.`,
),
);
return yield* response.text;
}
}).pipe(Effect.timeout("120 seconds"), Effect.provide(FetchHttpClient.layer)),
);
const raw: unknown = proxy
Expand Down
30 changes: 30 additions & 0 deletions evals/shared/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,33 @@ print(json.dumps({'url': p['base_url'].rstrip('/'), 'headers': h}))
),
),
);

/**
* Morph's free OpenAI-compatible API, for evals that should not spend on paid models. The key is
* `MORPH_API_KEY`, else the `morph` provider in OpenCode's config (`$XDG_CONFIG_HOME` or `~/.config`).
*/
export const morphConfig = () =>
decodeProxyConfig(
JSON.parse(
NodeChildProcess.execFileSync(
"python3",
[
"-c",
`
import json, os, pathlib
key = os.environ.get('MORPH_API_KEY')
url = os.environ.get('MORPH_BASE_URL', 'https://api.morphllm.com/v1')
if not key:
home = pathlib.Path(os.environ.get('XDG_CONFIG_HOME') or pathlib.Path.home() / '.config')
# OpenCode writes literal control characters inside strings, which strict parsing rejects.
settings = json.loads((home / 'opencode' / 'opencode.json').read_text(), strict=False)['providers']['morph']['settings']
key, url = settings.get('apiKey'), settings.get('baseURL', url)
if not key:
raise SystemExit('no morph key')
print(json.dumps({'url': url.rstrip('/'), 'headers': {'Authorization': 'Bearer ' + key}}))
`,
],
{ encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] },
),
),
);
Loading