Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 35x 35x 35x 14x 14x 14x 14x 14x 14x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 20x 20x 20x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 35x 35x 35x 15x 15x 1x 1x 1x 1x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 1x 23x 23x 23x 23x 23x 23x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 11x 23x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 23x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 23x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 23x 111x 111x 111x 111x 111x 111x 111x | import Anthropic from '@anthropic-ai/sdk';
import type {
Message,
MessageParam,
ToolResultBlockParam,
ToolUseBlock,
} from '@anthropic-ai/sdk/resources/messages/messages.js';
import type {
ModelProvider,
ModelTier,
AIInteraction,
WorkoutGenerationContext,
WorkoutAdaptationContext,
ReviewContext,
NarrativeContext,
WorkoutPlan,
AdaptedWorkout,
ReviewPrompt,
} from '../model-provider.js';
import type { PrescribedExercise } from '@strengthsys/shared';
import {
TOOL_DEFINITIONS,
SUBMIT_WORKOUT_PLAN_TOOL,
SUBMIT_ADAPTED_WORKOUT_TOOL,
SUBMIT_REVIEW_QUESTIONS_TOOL,
SUBMIT_NARRATIVE_TOOL,
} from '../tool-definitions.js';
import { dispatchTool } from '../tool-dispatch.js';
import {
generateWorkoutPrompt,
adaptWorkoutPrompt,
reviewQuestionsPrompt,
narrativePrompt,
} from '../prompts/index.js';
// ── Model constants ──────────────────────────────────────────
/** Complex tier: high-stakes creative tasks */
export const COMPLEX_MODEL = 'claude-sonnet-4-20250514';
/** Simple tier: lower-stakes, model-agnostic tasks */
export const SIMPLE_MODEL = 'claude-haiku-4-5-20251001';
/** Maximum tool dispatch iterations before giving up */
const MAX_ITERATIONS = 10;
// ── Tool type guards ─────────────────────────────────────────
const SUBMIT_TOOL_NAMES = new Set([
'submit_workout_plan',
'submit_adapted_workout',
'submit_review_questions',
'submit_narrative',
]);
function isToolUseBlock(block: Anthropic.ContentBlock): block is ToolUseBlock {
return block.type === 'tool_use';
}
// ── UUID post-processing ─────────────────────────────────────
function reassignExerciseIds(exercises: PrescribedExercise[]): PrescribedExercise[] {
return exercises.map((ex) => ({
...ex,
id: crypto.randomUUID(),
}));
}
// ── Core multi-turn dispatch loop ────────────────────────────
interface ToolCallDetail {
tool_name: string;
input_parameters: unknown;
output_result: unknown;
called_at: string; // ISO timestamp
}
interface LoopState {
toolsCalled: string[];
toolResults: unknown[];
toolCallDetails: ToolCallDetail[];
totalInputTokens: number;
totalOutputTokens: number;
}
interface LoopResult {
submitToolName: string;
submitInput: unknown;
state: LoopState;
}
async function runToolLoop(
client: Anthropic,
model: string,
system: string,
initialMessages: MessageParam[],
tools: Anthropic.Tool[],
): Promise<LoopResult> {
const messages: MessageParam[] = [...initialMessages];
const state: LoopState = {
toolsCalled: [],
toolResults: [],
toolCallDetails: [],
totalInputTokens: 0,
totalOutputTokens: 0,
};
for (let iteration = 0; iteration < MAX_ITERATIONS; iteration++) {
const response: Message = await client.messages.create({
model,
max_tokens: 4096,
system,
messages,
tools,
});
state.totalInputTokens += response.usage.input_tokens;
state.totalOutputTokens += response.usage.output_tokens;
if (response.stop_reason !== 'tool_use') {
throw new Error(
`Expected stop_reason 'tool_use' but got '${response.stop_reason ?? 'null'}'. ` +
'The model must call a submit tool to return its result.',
);
}
// Collect all tool_use blocks
const toolUseBlocks = response.content.filter(isToolUseBlock);
// Add assistant turn to message history
messages.push({ role: 'assistant', content: response.content });
// Process each tool call
const toolResultBlocks: ToolResultBlockParam[] = [];
for (const block of toolUseBlocks) {
const calledAt = new Date().toISOString();
state.toolsCalled.push(block.name);
// Check for submit tools — these terminate the loop
if (SUBMIT_TOOL_NAMES.has(block.name)) {
state.toolResults.push(block.input);
return { submitToolName: block.name, submitInput: block.input, state };
}
// Dispatch computation tool
const { output, isError } = await dispatchTool(block.name, block.input);
state.toolResults.push(output);
state.toolCallDetails.push({
tool_name: block.name,
input_parameters: block.input,
output_result: output,
called_at: calledAt,
});
toolResultBlocks.push({
type: 'tool_result',
tool_use_id: block.id,
content: JSON.stringify(output),
is_error: isError || undefined,
});
}
// Send tool results back to the model
messages.push({ role: 'user', content: toolResultBlocks });
}
throw new Error(
`Max iterations (${MAX_ITERATIONS}) exceeded without a submit tool call. ` +
'The model failed to produce a final result.',
);
}
// ── AIInteraction builder ─────────────────────────────────────
function buildInteraction(
athleteId: string,
actionType: string,
contextSent: unknown,
responseReceived: unknown,
state: LoopState,
startTime: number,
): AIInteraction {
return {
athlete_id: athleteId,
action_type: actionType,
context_sent: contextSent,
response_received: responseReceived,
tools_called: state.toolsCalled,
tool_results: state.toolResults,
tool_call_details: state.toolCallDetails.length > 0 ? state.toolCallDetails : undefined,
duration_ms: Date.now() - startTime,
};
}
// ── AnthropicModelProvider ────────────────────────────────────
export class AnthropicModelProvider implements ModelProvider {
readonly tier: ModelTier = 'complex';
private readonly client: Anthropic;
constructor(options?: Anthropic.ClientOptions) {
this.client = new Anthropic(options);
}
async generateWorkout(
context: WorkoutGenerationContext,
): Promise<{ result: WorkoutPlan; interaction: AIInteraction }> {
const startTime = Date.now();
const system = generateWorkoutPrompt(context);
const allTools: Anthropic.Tool[] = [
...TOOL_DEFINITIONS.map(toolDefToAnthropic),
toolDefToAnthropic(SUBMIT_WORKOUT_PLAN_TOOL),
];
const messages: MessageParam[] = [
{
role: 'user',
content: `Generate a ${context.session_type} workout session for block ${context.block_id}. Use the provided tools as needed, then call submit_workout_plan with the final result.`,
},
];
const { submitInput, state } = await runToolLoop(
this.client,
COMPLEX_MODEL,
system,
messages,
allTools,
);
const raw = submitInput as { prescribed_exercises: PrescribedExercise[] };
const result: WorkoutPlan = {
prescribed_exercises: reassignExerciseIds(raw.prescribed_exercises),
};
return {
result,
interaction: buildInteraction(
context.athlete_id,
'generate_workout',
context,
result,
state,
startTime,
),
};
}
async adaptWorkout(
context: WorkoutAdaptationContext,
): Promise<{ result: AdaptedWorkout; interaction: AIInteraction }> {
const startTime = Date.now();
const system = adaptWorkoutPrompt(context);
const allTools: Anthropic.Tool[] = [
...TOOL_DEFINITIONS.map(toolDefToAnthropic),
toolDefToAnthropic(SUBMIT_ADAPTED_WORKOUT_TOOL),
];
const messages: MessageParam[] = [
{
role: 'user',
content: `Adapt the current workout. Kind: ${context.kind}. ${context.context_description ? `Athlete note: "${context.context_description.replace(/#{1,6}\s/g, '').replace(/\n{2,}/g, '\n').slice(0, 500)}".` : ''} Call submit_adapted_workout with the modified plan and explanation.`,
},
];
const { submitInput, state } = await runToolLoop(
this.client,
COMPLEX_MODEL,
system,
messages,
allTools,
);
const raw = submitInput as { prescribed_exercises: PrescribedExercise[]; explanation: string };
const result: AdaptedWorkout = {
prescribed_exercises: reassignExerciseIds(raw.prescribed_exercises),
explanation: raw.explanation,
};
return {
result,
interaction: buildInteraction(
context.athlete_id,
'adapt_workout',
context,
result,
state,
startTime,
),
};
}
async generateReviewQuestions(
context: ReviewContext,
): Promise<{ result: ReviewPrompt[]; interaction: AIInteraction }> {
const startTime = Date.now();
const system = reviewQuestionsPrompt(context);
const allTools: Anthropic.Tool[] = [toolDefToAnthropic(SUBMIT_REVIEW_QUESTIONS_TOOL)];
const messages: MessageParam[] = [
{
role: 'user',
content: `Generate post-${context.scope} review questions for athlete ${context.athlete_id}. Call submit_review_questions with the question list.`,
},
];
const { submitInput, state } = await runToolLoop(
this.client,
SIMPLE_MODEL,
system,
messages,
allTools,
);
// The model may return the array directly or nested under a 'questions' key
let rawQuestions: unknown;
const rawInput = submitInput as Record<string, unknown>;
if (Array.isArray(rawInput)) {
rawQuestions = rawInput;
} else if (Array.isArray(rawInput.questions)) {
rawQuestions = rawInput.questions;
} else {
rawQuestions = [];
}
const result = rawQuestions as ReviewPrompt[];
return {
result,
interaction: buildInteraction(
context.athlete_id,
'generate_review_questions',
context,
result,
state,
startTime,
),
};
}
async generateNarrative(
context: NarrativeContext,
): Promise<{ result: string; interaction: AIInteraction }> {
const startTime = Date.now();
const system = narrativePrompt(context);
const allTools: Anthropic.Tool[] = [toolDefToAnthropic(SUBMIT_NARRATIVE_TOOL)];
const messages: MessageParam[] = [
{
role: 'user',
content: `Generate a training narrative for athlete ${context.athlete_id} covering the ${context.timeframe} timeframe. Call submit_narrative with the result.`,
},
];
const { submitInput, state } = await runToolLoop(
this.client,
SIMPLE_MODEL,
system,
messages,
allTools,
);
const raw = submitInput as { narrative: string };
const result = raw.narrative;
return {
result,
interaction: buildInteraction(
context.athlete_id,
'generate_narrative',
context,
result,
state,
startTime,
),
};
}
}
// ── Adapter: ToolDefinition → Anthropic.Tool ─────────────────
function toolDefToAnthropic(def: { name: string; description: string; input_schema: Anthropic.Tool['input_schema'] }): Anthropic.Tool {
return {
name: def.name,
description: def.description,
input_schema: def.input_schema,
};
}
|