All files / web/src/lib/worksheet-parsing parser.ts

0% Statements 0/456
0% Branches 0/1
0% Functions 0/1
0% Lines 0/456

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 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
/**
 * Worksheet Parser
 *
 * Uses the LLM client to parse abacus workbook page images
 * into structured problem data.
 */
import {
  type LLMClient,
  type LLMProgress,
  llm,
  type ReasoningEffort,
  type StreamEvent,
} from '@/lib/llm'
import { buildWorksheetParsingPrompt, type PromptOptions } from './prompt-builder'
import { type WorksheetParsingResult, WorksheetParsingResultSchema } from './schemas'

/**
 * Available model configurations for worksheet parsing
 */
export interface ModelConfig {
  /** Unique identifier for this config */
  id: string
  /** Display name for UI */
  name: string
  /** Provider name */
  provider: 'openai' | 'anthropic'
  /** Model ID to use */
  model: string
  /** Reasoning effort (for GPT-5.2+) */
  reasoningEffort?: ReasoningEffort
  /** Description of when to use this config */
  description: string
  /** Whether this is the default config */
  isDefault?: boolean
}

/**
 * Available model configurations for worksheet parsing
 */
export const PARSING_MODEL_CONFIGS: ModelConfig[] = [
  {
    id: 'gpt-5.2-thinking',
    name: 'GPT-5.2 Thinking',
    provider: 'openai',
    model: 'gpt-5.2',
    reasoningEffort: 'medium',
    description: 'Best balance of quality and speed for worksheet analysis',
    isDefault: true,
  },
  {
    id: 'gpt-5.2-thinking-high',
    name: 'GPT-5.2 Thinking (High)',
    provider: 'openai',
    model: 'gpt-5.2',
    reasoningEffort: 'high',
    description: 'More thorough reasoning, better for difficult handwriting',
  },
  {
    id: 'gpt-5.2-instant',
    name: 'GPT-5.2 Instant',
    provider: 'openai',
    model: 'gpt-5.2-chat-latest',
    reasoningEffort: 'none',
    description: 'Faster but less accurate, good for clear worksheets',
  },
  {
    id: 'claude-sonnet',
    name: 'Claude Sonnet 4',
    provider: 'anthropic',
    model: 'claude-sonnet-4-20250514',
    description: 'Alternative provider, good for comparison',
  },
]

/**
 * Get the default model config
 */
export function getDefaultModelConfig(): ModelConfig {
  return PARSING_MODEL_CONFIGS.find((c) => c.isDefault) ?? PARSING_MODEL_CONFIGS[0]
}

/**
 * Get a model config by ID
 */
export function getModelConfig(id: string): ModelConfig | undefined {
  return PARSING_MODEL_CONFIGS.find((c) => c.id === id)
}

/**
 * Options for parsing a worksheet
 */
export interface ParseWorksheetOptions {
  /** Progress callback for UI updates */
  onProgress?: (progress: LLMProgress) => void
  /** Maximum retries on validation failure */
  maxRetries?: number
  /** Additional prompt customization */
  promptOptions?: PromptOptions
  /** Specific provider to use (defaults to configured default) */
  provider?: string
  /** Specific model to use (defaults to configured default) */
  model?: string
  /** Reasoning effort for GPT-5.2+ models */
  reasoningEffort?: ReasoningEffort
  /** Use a specific model config by ID */
  modelConfigId?: string
}

/**
 * Result of worksheet parsing
 */
export interface ParseWorksheetResult {
  /** Parsed worksheet data */
  data: WorksheetParsingResult
  /** Number of LLM call attempts made */
  attempts: number
  /** Provider used */
  provider: string
  /** Model used */
  model: string
  /** Token usage */
  usage: {
    promptTokens: number
    completionTokens: number
    totalTokens: number
  }
  /** Raw JSON response from the LLM (before validation/parsing) */
  rawResponse: string
  /** JSON Schema sent to the LLM (with field descriptions) */
  jsonSchema: string
}

/**
 * Parse an abacus workbook page image
 *
 * @param imageDataUrl - Base64-encoded data URL of the worksheet image
 * @param options - Parsing options
 * @returns Structured parsing result
 *
 * @example
 * ```typescript
 * import { parseWorksheetImage } from '@/lib/worksheet-parsing'
 *
 * const result = await parseWorksheetImage(imageDataUrl, {
 *   onProgress: (p) => console.log(p.message),
 * })
 *
 * console.log(`Found ${result.data.problems.length} problems`)
 * console.log(`Overall confidence: ${result.data.overallConfidence}`)
 * ```
 */
export async function parseWorksheetImage(
  imageDataUrl: string,
  options: ParseWorksheetOptions = {}
): Promise<ParseWorksheetResult> {
  const {
    onProgress,
    maxRetries = 2,
    promptOptions = {},
    provider: explicitProvider,
    model: explicitModel,
    reasoningEffort: explicitReasoningEffort,
    modelConfigId,
  } = options

  // Resolve model config
  let provider = explicitProvider
  let model = explicitModel
  let reasoningEffort = explicitReasoningEffort

  if (modelConfigId) {
    const config = getModelConfig(modelConfigId)
    if (config) {
      provider = provider ?? config.provider
      model = model ?? config.model
      reasoningEffort = reasoningEffort ?? config.reasoningEffort
    }
  } else if (!provider && !model) {
    // Use default config
    const defaultConfig = getDefaultModelConfig()
    provider = defaultConfig.provider
    model = defaultConfig.model
    reasoningEffort = reasoningEffort ?? defaultConfig.reasoningEffort
  }

  // Build the prompt
  const prompt = buildWorksheetParsingPrompt(promptOptions)

  // Make the vision call
  const response = await llm.vision({
    prompt,
    images: [imageDataUrl],
    schema: WorksheetParsingResultSchema,
    maxRetries,
    onProgress,
    provider,
    model,
    reasoningEffort,
  })

  return {
    data: response.data,
    attempts: response.attempts,
    provider: response.provider,
    model: response.model,
    usage: response.usage,
    rawResponse: response.rawResponse,
    jsonSchema: response.jsonSchema,
  }
}

/**
 * Streaming event specific to worksheet parsing
 */
export type WorksheetParseStreamEvent =
  | StreamEvent<WorksheetParsingResult>
  | { type: 'progress'; stage: string; message: string }

/**
 * Options for streaming worksheet parsing
 */
export interface StreamParseWorksheetOptions {
  /** Additional prompt customization */
  promptOptions?: PromptOptions
  /** Specific provider to use (defaults to configured default) */
  provider?: string
  /** Specific model to use (defaults to configured default) */
  model?: string
  /** Use a specific model config by ID */
  modelConfigId?: string
  /** Request timeout in milliseconds (default: 5 minutes for streaming) */
  timeoutMs?: number
}

/**
 * Stream parse an abacus workbook page image with reasoning summaries
 *
 * Uses the OpenAI Responses API to stream the parsing process, including:
 * - Reasoning summaries (model's thinking about each problem)
 * - Output deltas (partial structured output)
 * - Final validated result
 *
 * @param imageDataUrl - Base64-encoded data URL of the worksheet image
 * @param options - Parsing options
 * @param llmClient - LLM client to use (typically with middleware for task integration)
 * @returns AsyncGenerator yielding stream events
 *
 * @example
 * ```typescript
 * import { streamParseWorksheetImage } from '@/lib/worksheet-parsing'
 * import { createTaskLLM } from '@/lib/llm'
 *
 * const taskLLM = createTaskLLM(handle)
 * const stream = streamParseWorksheetImage(imageDataUrl, {}, taskLLM)
 *
 * for await (const event of stream) {
 *   if (event.type === 'complete') {
 *     console.log('Found', event.data.problems.length, 'problems')
 *   }
 * }
 * ```
 */
export async function* streamParseWorksheetImage(
  imageDataUrl: string,
  options: StreamParseWorksheetOptions,
  llmClient: LLMClient
): AsyncGenerator<WorksheetParseStreamEvent, void, unknown> {
  const {
    promptOptions = {},
    provider: explicitProvider,
    model: explicitModel,
    modelConfigId,
    timeoutMs = 300_000, // 5 minutes default for streaming
  } = options

  // Resolve model config
  let provider = explicitProvider
  let model = explicitModel

  if (modelConfigId) {
    const config = getModelConfig(modelConfigId)
    if (config) {
      provider = provider ?? config.provider
      model = model ?? config.model
    }
  } else if (!provider && !model) {
    // Use default config
    const defaultConfig = getDefaultModelConfig()
    provider = defaultConfig.provider
    model = defaultConfig.model
  }

  // Only OpenAI supports streaming with reasoning
  if (provider && provider !== 'openai') {
    throw new Error(
      `Streaming with reasoning summaries is only supported for OpenAI. ` +
        `Use parseWorksheetImage() for provider '${provider}'.`
    )
  }

  // Emit progress event
  yield {
    type: 'progress',
    stage: 'preparing',
    message: 'Preparing worksheet analysis...',
  }

  // Build the prompt
  const prompt = buildWorksheetParsingPrompt(promptOptions)

  // Stream the response using provided client (with middleware)
  const stream = llmClient.stream({
    prompt,
    images: [imageDataUrl],
    schema: WorksheetParsingResultSchema,
    provider: 'openai',
    model,
    reasoning: {
      effort: 'medium',
      summary: 'auto',
    },
    timeoutMs,
  })

  // Yield all events from the LLM stream
  for await (const event of stream) {
    yield event
  }
}

/**
 * Re-parse specific problems with additional context
 *
 * Used when the user provides corrections or hints about specific problems
 * that were incorrectly parsed in the first attempt.
 *
 * @param imageDataUrl - Base64-encoded data URL of the worksheet image
 * @param problemNumbers - Which problems to focus on
 * @param additionalContext - User-provided context or hints
 * @param originalWarnings - Warnings from the original parse
 * @param options - Parsing options
 */
export async function reparseProblems(
  imageDataUrl: string,
  problemNumbers: number[],
  additionalContext: string,
  originalWarnings: string[],
  options: Omit<ParseWorksheetOptions, 'promptOptions'> = {}
): Promise<ParseWorksheetResult> {
  return parseWorksheetImage(imageDataUrl, {
    ...options,
    promptOptions: {
      focusProblemNumbers: problemNumbers,
      additionalContext: `${additionalContext}

Previous warnings for these problems:
${originalWarnings.map((w) => `- ${w}`).join('\n')}`,
    },
  })
}

/**
 * Compute problem statistics from parsed results
 */
export function computeParsingStats(result: WorksheetParsingResult) {
  const problems = result.problems

  // Count problems needing review (low confidence)
  const lowConfidenceProblems = problems.filter(
    (p) => p.termsConfidence < 0.7 || p.studentAnswerConfidence < 0.7
  )

  // Count problems with answers
  const answeredProblems = problems.filter((p) => p.studentAnswer !== null)

  // Compute accuracy if answers are present
  const correctAnswers = answeredProblems.filter((p) => p.studentAnswer === p.correctAnswer)

  return {
    totalProblems: problems.length,
    answeredProblems: answeredProblems.length,
    unansweredProblems: problems.length - answeredProblems.length,
    correctAnswers: correctAnswers.length,
    incorrectAnswers: answeredProblems.length - correctAnswers.length,
    accuracy: answeredProblems.length > 0 ? correctAnswers.length / answeredProblems.length : null,
    lowConfidenceCount: lowConfidenceProblems.length,
    problemsNeedingReview: lowConfidenceProblems.map((p) => p.problemNumber),
    warningCount: result.warnings.length,
  }
}

/**
 * Merge corrections into parsing result
 *
 * Creates a new result with user corrections applied.
 */
export function applyCorrections(
  result: WorksheetParsingResult,
  corrections: Array<{
    problemNumber: number
    correctedTerms?: number[] | null
    correctedStudentAnswer?: number | null
    shouldExclude?: boolean
    shouldRestore?: boolean
  }>
): WorksheetParsingResult {
  const correctionMap = new Map(corrections.map((c) => [c.problemNumber, c]))

  const correctedProblems = result.problems.map((problem) => {
    const correction = correctionMap.get(problem.problemNumber)
    if (!correction) return problem

    // Handle exclude/restore toggle
    if (correction.shouldExclude) {
      return { ...problem, excluded: true }
    }
    if (correction.shouldRestore) {
      return { ...problem, excluded: false }
    }

    return {
      ...problem,
      terms: correction.correctedTerms ?? problem.terms,
      correctAnswer: correction.correctedTerms
        ? correction.correctedTerms.reduce((sum, t) => sum + t, 0)
        : problem.correctAnswer,
      studentAnswer:
        correction.correctedStudentAnswer !== undefined
          ? correction.correctedStudentAnswer
          : problem.studentAnswer,
      // Boost confidence since user verified
      termsConfidence: correction.correctedTerms ? 1.0 : problem.termsConfidence,
      studentAnswerConfidence:
        correction.correctedStudentAnswer !== undefined ? 1.0 : problem.studentAnswerConfidence,
    }
  })

  // Recalculate overall confidence (only for non-excluded problems)
  const activeProblems = correctedProblems.filter((p) => !p.excluded)
  const avgConfidence =
    activeProblems.length > 0
      ? activeProblems.reduce(
          (sum, p) => sum + (p.termsConfidence + p.studentAnswerConfidence) / 2,
          0
        ) / activeProblems.length
      : 0

  return {
    ...result,
    problems: correctedProblems,
    overallConfidence: avgConfidence,
    needsReview: activeProblems.some(
      (p) => p.termsConfidence < 0.7 || p.studentAnswerConfidence < 0.7
    ),
  }
}