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
59 changes: 57 additions & 2 deletions packages/api/src/harness/proxy-harness.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,9 @@ describe('proxyHarness', () => {
{role: 'tool', tool_call_id: 'c1', content: 'rows'},
],
tools: [{name: 'read', description: 'Reads', parameters: {type: 'object', properties: {}}}],
maxTokens: 4000,
timeoutMs: 120_000,
maxTokens: 32_000,
reasoningTokens: 16_000,
timeoutMs: 600_000,
},
]);
expect(events).toEqual([
Expand Down Expand Up @@ -158,6 +159,60 @@ describe('proxyHarness', () => {
expect(await Array.fromAsync(harness.turn(turnInput([entry('person', 'Hi')])))).toEqual([{kind: 'failed', error: turnedDown.error, retry: false}]);
});

test('either model may write 32,000 tokens a call, GLM thinking with at most 16,000 of them', async () => {
await Array.fromAsync(harness.turn(turnInput([entry('person', 'Hi')])));
await Array.fromAsync(harness.turn(turnInput([entry('person', 'Hi')], {model: 'glm'})));

expect(requests().map(({maxTokens, reasoningTokens, timeoutMs}) => ({maxTokens, reasoningTokens, timeoutMs}))).toEqual([
{maxTokens: 32_000, reasoningTokens: undefined, timeoutMs: 600_000},
{maxTokens: 32_000, reasoningTokens: 16_000, timeoutMs: 600_000},
]);
});

test('a model cut off at its limit is asked again in the turn, after what it had written, told so, its calls dropped; the turn costs what every call wrote', async () => {
askForTurn
.mockResolvedValueOnce(Ok({text: 'Writing the file.', toolCalls: [{id: 'c1', name: 'read', arguments: '{"content":"lo'}], inputTokens: 100, outputTokens: 32_000, cutOff: true}))
.mockResolvedValueOnce(Ok({text: '', toolCalls: [], inputTokens: 200, outputTokens: 32_000, cutOff: true}))
.mockResolvedValueOnce(Ok({text: 'In parts, then.', toolCalls: [{id: 'c2', name: 'read', arguments: '{}'}], inputTokens: 300, outputTokens: 500}));

const events = await Array.fromAsync(harness.turn(turnInput([entry('person', 'Write the file')], {model: 'glm'})));

const note =
'[Your last answer was cut off at the 32,000-token limit of an answer before it was complete, and was dropped: any call in it was not made. Go on with less in one answer: think less before acting, and write a large file or script in parts, one call each.]';
expect(requests()[1]?.messages.slice(1)).toEqual([
{role: 'user', content: 'Write the file'},
{role: 'assistant', content: 'Writing the file.'},
{role: 'user', content: note},
]);
expect(requests()[2]?.messages.slice(-2)).toEqual([
{role: 'user', content: note},
{role: 'user', content: note},
]);
expect(events).toEqual([
{kind: 'text', text: 'In parts, then.'},
{kind: 'tool_call', id: 'c2', name: 'read', arguments: '{}'},
{kind: 'done', session: null, system: 'You are signed in.', inputTokens: 300, outputTokens: 64_500},
]);
});

test('a model cut off every time it is asked tells the person it ran out of room, after what it had written, rather than nothing', async () => {
askForTurn
.mockResolvedValueOnce(Ok({text: '', toolCalls: [], inputTokens: 5712, outputTokens: 32_000, cutOff: true}))
.mockResolvedValueOnce(Ok({text: '', toolCalls: [], inputTokens: 5800, outputTokens: 32_000, cutOff: true}))
.mockResolvedValueOnce(Ok({text: 'The plan, so far:', toolCalls: [{id: 'c1', name: 'read', arguments: '{'}], inputTokens: 5900, outputTokens: 32_000, cutOff: true}));

const events = await Array.fromAsync(harness.turn(turnInput([entry('person', 'Write a plan')], {model: 'glm'})));

expect(askForTurn).toHaveBeenCalledTimes(3);
expect(events).toEqual([
{
kind: 'text',
text: 'The plan, so far:\n\nI kept running out of room: GLM 5.3 stops at 32,000 tokens an answer, and I was cut off 3 times before I could finish. Say something to try again, or switch this thread to another model.',
},
{kind: 'done', session: null, system: 'You are signed in.', inputTokens: 5900, outputTokens: 96_000},
]);
});

test('an answer of no words yields no text; a model it has not got, or a turn stopped before it began, fails without asking', async () => {
askForTurn.mockResolvedValue(Ok({text: '', toolCalls: [{id: 'c1', name: 'read', arguments: '{}'}], inputTokens: 10, outputTokens: 2}));
const events: HarnessEvent[] = await Array.fromAsync(harness.turn(turnInput([entry('person', 'Hi')])));
Expand Down
93 changes: 70 additions & 23 deletions packages/api/src/harness/proxy-harness.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import type {HarnessBackend, HarnessEvent, HarnessTurn} from '@proxy/backends/harness/backend';
import {ApiErr, type ApiError, CHAT_MODELS, isChatModel} from '@proxy/utils';
import {ApiErr, type ApiError, CHAT_MODELS, type ChatModel, isChatModel} from '@proxy/utils';
import {compactionCut, type ContextEntry, toMessages, toTranscript} from '@proxy/utils/harness-context';

import type {askForTurn as askForTurnOverRouter, ModelTool} from '../llm/open-router';
import type {askForTurn as askForTurnOverRouter, ModelMessage, ModelTool} from '../llm/open-router';

/**
* The harness this server has always run: one call to the model over OpenRouter per turn, on the
Expand All @@ -15,16 +15,43 @@ import type {askForTurn as askForTurnOverRouter, ModelTool} from '../llm/open-ro
* and the model then reads in place of what it covers. The model gets the log to summarize as
* text, not as the turns it made, which would need the tools sent along: a request with calls in
* it and no tools is refused. A model that couldn't be reached is worth trying again; one that
* refused the request, or turned the key down, is not.
* refused the request, or turned the key down, is not. One cut off at its limit, its answer not
* complete, is asked again in the same turn, told so, a couple of times before the person is told.
*/

// How a thread's long log is summarized, by the same model, for itself.
const SUMMARIZE =
'Summarize this conversation between a person and their agent, with the agent’s calls and their answers, so the agent can go on from the summary alone. Keep what the person asked for and wants; what was done and found, with names, ids, dates and numbers; what they were told; and what is still open or planned, such as after a sleep or an alert. Plain prose, from the agent’s side, no title.';
const SUMMARIZE_NOW = 'Write the summary now.';

const MAX_TOKENS = 4000;
const TIMEOUT_MS = 120_000;
// How much each model may write in a call, its thinking counted in, and how much of that it may
// think with: enough for a large file or script in one call, as agentic work needs, and for GLM,
// which thinks before it answers, room left for the answer however long it thinks. A model is
// billed for what it writes, not for the room it was given. A call that long takes minutes, so
// one is given ten before it counts as out of reach; the worker keeps the job's lease meanwhile.
const BUDGETS: Record<ChatModel, {maxTokens: number; reasoningTokens?: number}> = {
claude: {maxTokens: 32_000},
glm: {maxTokens: 32_000, reasoningTokens: 16_000},
};
const TIMEOUT_MS = 600_000;

// How many times a model cut off at its limit is asked again in the same turn, told so.
const MAX_CUT_OFF_RETRIES = 2;

// What the model is told where its last answer was cut off at its limit: nothing of it ran, and
// how to fit the next one.
function cutOffNote(model: ChatModel): string {
return `[Your last answer was cut off at the ${limitOf(model)}-token limit of an answer before it was complete, and was dropped: any call in it was not made. Go on with less in one answer: think less before acting, and write a large file or script in parts, one call each.]`;
}

// What the person is told where the model was cut off at its limit every time it was asked.
function outOfRoom(model: ChatModel): string {
return `I kept running out of room: ${CHAT_MODELS[model]} stops at ${limitOf(model)} tokens an answer, and I was cut off ${MAX_CUT_OFF_RETRIES + 1} times before I could finish. Say something to try again, or switch this thread to another model.`;
}

function limitOf(model: ChatModel): string {
return BUDGETS[model].maxTokens.toLocaleString('en-US');
}

export const PROXY_HARNESS = 'proxy';

Expand Down Expand Up @@ -76,7 +103,7 @@ export function proxyHarness(deps: ProxyHarnessDeps): HarnessBackend {
{role: 'user', content: `${toTranscript(entries.slice(0, cut))}\n\n${SUMMARIZE_NOW}`},
],
tools: [],
maxTokens: MAX_TOKENS,
...BUDGETS[model],
timeoutMs: TIMEOUT_MS,
});
if (summary.isErr()) {
Expand All @@ -98,25 +125,45 @@ export function proxyHarness(deps: ProxyHarnessDeps): HarnessBackend {
};
entries = [...entries, stored];
}
const turn = await deps.askForTurn({
key: deps.key,
model,
messages: [{role: 'system', content: input.system}, ...toMessages(entries, {clearOld: true})],
tools: toModelTools(input),
maxTokens: MAX_TOKENS,
timeoutMs: TIMEOUT_MS,
});
if (turn.isErr()) {
yield failed(turn.error);
// The model is asked again where it was cut off at its limit, told so, after what it had
// written; the calls of an answer cut off are dropped, since the last may be cut short.
// The input of the last call is the turn's, the log's size as the model last read it;
// the output, what every call wrote.
const messages: ModelMessage[] = [{role: 'system', content: input.system}, ...toMessages(entries, {clearOld: true})];
let outputTokens = 0;
for (let attempt = 0; ; attempt += 1) {
const turn = await deps.askForTurn({
key: deps.key,
model,
messages: [...messages],
tools: toModelTools(input),
...BUDGETS[model],
timeoutMs: TIMEOUT_MS,
});
if (turn.isErr()) {
yield failed(turn.error);
return;
}
const {text, toolCalls, inputTokens, cutOff} = turn.value;
outputTokens += turn.value.outputTokens;
if (cutOff === true && attempt < MAX_CUT_OFF_RETRIES && !input.signal.aborted) {
messages.push(...(text.trim() === '' ? [] : [{role: 'assistant' as const, content: text}]), {role: 'user', content: cutOffNote(model)});
continue;
}
if (cutOff === true) {
yield {kind: 'text', text: [text, outOfRoom(model)].filter((part) => part.trim() !== '').join('\n\n')};
yield {kind: 'done', session: input.session, system: input.system, inputTokens, outputTokens};
return;
}
if (text !== '') {
yield {kind: 'text', text};
}
for (const call of toolCalls) {
yield {kind: 'tool_call', ...call};
}
yield {kind: 'done', session: input.session, system: input.system, inputTokens, outputTokens};
return;
}
if (turn.value.text !== '') {
yield {kind: 'text', text: turn.value.text};
}
for (const call of turn.value.toolCalls) {
yield {kind: 'tool_call', ...call};
}
yield {kind: 'done', session: input.session, system: input.system, inputTokens: turn.value.inputTokens, outputTokens: turn.value.outputTokens};
},
};
}
21 changes: 20 additions & 1 deletion packages/api/src/llm/open-router.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,11 @@ import {askForJson, askForTurn} from './open-router';
// What OpenRouter answers, and with what status.
let status = 200;
let message: Record<string, unknown> = {content: 'Hello'};
let finishReason = 'stop';
const fetchSpy = spyOn(globalThis, 'fetch').mockImplementation((async () =>
status === 200 ? Response.json({choices: [{message}], usage: {prompt_tokens: 120, completion_tokens: 8}}) : Response.json({error: {message: 'down'}}, {status})) as unknown as typeof fetch);
status === 200
? Response.json({choices: [{message, finish_reason: finishReason}], usage: {prompt_tokens: 120, completion_tokens: 8}})
: Response.json({error: {message: 'down'}}, {status})) as unknown as typeof fetch);

afterAll(() => {
fetchSpy.mockRestore();
Expand All @@ -17,6 +20,7 @@ beforeEach(() => {
fetchSpy.mockClear();
status = 200;
message = {content: 'Hello'};
finishReason = 'stop';
});

const request = {
Expand Down Expand Up @@ -58,6 +62,21 @@ describe('askForTurn', () => {
expect(sent().provider).toEqual({only: ['together', 'fireworks', 'deepinfra', 'baseten'], data_collection: 'deny', zdr: true});
});

test('holds the model’s thinking to the tokens given for it, and sends no limit where none is given', async () => {
await askForTurn({...request, model: 'glm', maxTokens: 16_000, reasoningTokens: 8000});
expect(sent()).toMatchObject({max_tokens: 16_000, reasoning: {max_tokens: 8000}});

fetchSpy.mockClear();
await askForTurn(request);
expect(sent()).not.toHaveProperty('reasoning');
});

test('reads an answer the model was cut off in, at its limit, as cut off', async () => {
finishReason = 'length';
message = {content: ''};
expect((await askForTurn(request)).unwrap()).toEqual({text: '', toolCalls: [], inputTokens: 120, outputTokens: 8, cutOff: true});
});

test('reads the calls the model made, with their arguments as it wrote them', async () => {
message = {content: null, tool_calls: [{id: 'call-1', type: 'function', function: {name: 'read', arguments: '{"connection":"c1"}'}}]};
const turn = await askForTurn(request);
Expand Down
14 changes: 10 additions & 4 deletions packages/api/src/llm/open-router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,16 @@ type CompletionBody = {
provider: ProviderPolicy;
tools?: Array<{type: 'function'; function: ModelTool}>;
temperature?: number;
reasoning?: {effort: 'low' | 'medium' | 'high'};
reasoning?: {effort: 'low' | 'medium' | 'high'} | {max_tokens: number};
response_format?: {type: 'json_schema'; json_schema: {name: string; strict: boolean; schema: object}};
};

const completionSchema = z.object({
choices: z
.array(
z.object({
// Why the model stopped: 'length' where it reached max_tokens.
finish_reason: z.string().nullable().optional(),
message: z.object({
content: z.string().nullable().optional(),
tool_calls: z.array(z.object({id: z.string(), function: z.object({name: z.string(), arguments: z.string()})})).optional(),
Expand Down Expand Up @@ -199,11 +201,13 @@ export type TurnRequest = {
messages: ModelMessage[];
tools: ModelTool[];
maxTokens: number;
/** How much of maxTokens it may think with, where it thinks: the rest is kept for its answer. */
reasoningTokens?: number;
timeoutMs: number;
};

/** What the model answered: its text, the calls it made, and what the turn cost. */
export type ModelTurn = {text: string; toolCalls: ToolCall[]; inputTokens: number; outputTokens: number};
/** What the model answered: its text, the calls it made, and what the turn cost; cut off where it reached maxTokens before it was done. */
export type ModelTurn = {text: string; toolCalls: ToolCall[]; inputTokens: number; outputTokens: number; cutOff?: boolean};

/** One turn of the model on the conversation. */
export function askForTurn(request: TurnRequest): Promise<Result<ModelTurn, ApiError>> {
Expand All @@ -216,18 +220,20 @@ export function askForTurn(request: TurnRequest): Promise<Result<ModelTurn, ApiE
messages: request.messages,
tools: request.tools.map((tool) => ({type: 'function', function: {name: tool.name, description: tool.description, parameters: tool.parameters}})),
max_tokens: request.maxTokens,
...(request.reasoningTokens === undefined ? {} : {reasoning: {max_tokens: request.reasoningTokens}}),
provider: TURN_PROVIDERS[request.model],
},
request.timeoutMs,
{model: request.model, purpose: 'turn'},
),
);
const {message} = completion.choices[0] ?? {};
const {message, finish_reason: finishReason} = completion.choices[0] ?? {};
return {
text: message?.content ?? '',
toolCalls: (message?.tool_calls ?? []).map((call) => ({id: call.id, name: call.function.name, arguments: call.function.arguments})),
inputTokens: completion.usage?.prompt_tokens ?? 0,
outputTokens: completion.usage?.completion_tokens ?? 0,
...(finishReason === 'length' ? {cutOff: true} : {}),
};
});
}
Loading