src/core/model.ts
2 KB - 查看原始文件
// The one interface every model call goes through.
//
// The turn loop never imports the Anthropic SDK client directly. It talks to a ModelClient, so
// tests can swap in a scripted fake (tests/fakes/fake-model.ts) and run with no API key and no
// cost. Message and content types still come from the SDK: we never redefine them.
import type {
BetaMessage,
BetaMessageParam,
BetaTextBlockParam,
BetaTool,
BetaToolUnion,
} from '@anthropic-ai/sdk/resources/beta/messages/messages';
export type { BetaMessage, BetaMessageParam, BetaTextBlockParam, BetaTool, BetaToolUnion };
export interface ModelRequest {
/** System prompt blocks. Stable content first, so it can be cached (lab 03). */
system: BetaTextBlockParam[];
/** The full conversation, oldest first. Never edited, only appended to (lab 02). */
messages: BetaMessageParam[];
/**
* Tool definitions in API form: our own tools (BetaTool) and Anthropic-defined ones such as
* the memory tool (lab 06). Keep their order stable: it is part of the cached prefix.
*/
tools: BetaToolUnion[];
}
const PARTIAL = Symbol('partialMessage');
/**
* A call that stops early (Ctrl+C, shutdown) is still billed for the input and for any output
* that streamed. The model client attaches what the API reported so far to the error, and the
* turn loop counts it (lab 12: the daily limit must see it).
*/
export function attachPartialMessage(err: unknown, message: BetaMessage | undefined): unknown {
if (message && err !== null && typeof err === 'object') {
(err as { [PARTIAL]?: BetaMessage })[PARTIAL] = message;
}
return err;
}
export function partialMessageOf(err: unknown): BetaMessage | undefined {
return err !== null && typeof err === 'object'
? (err as { [PARTIAL]?: BetaMessage })[PARTIAL]
: undefined;
}
export interface ModelCallOptions {
/** Called with each chunk of visible text as it streams in. */
onText?: (delta: string) => void;
/** Cancels the request (Ctrl+C in the terminal, shutdown in lab 12). */
signal?: AbortSignal;
}
export interface ModelClient {
/** Which model answers. Shown in logs and stored in the session log. */
readonly model: string;
/** Send one request and return the complete assistant message. */
complete(request: ModelRequest, options?: ModelCallOptions): Promise<BetaMessage>;
}