-
Notifications
You must be signed in to change notification settings - Fork 8
feat: Add Conventionality evaluator to TypeScript SDK #25
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
adnanrhussain
merged 3 commits into
main
from
ahussain/typescript_sdk_add_conventionality
Mar 20, 2026
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,229 @@ | ||
| import type { LLMProvider } from '../providers/index.js'; | ||
| import { createProvider } from '../providers/index.js'; | ||
| import { ConventionalityOutputSchema, type ConventionalityInternal } from '../schemas/conventionality.js'; | ||
| import { calculateFleschKincaidGrade } from '../features/index.js'; | ||
| import { getSystemPrompt, getUserPrompt } from '../prompts/conventionality/index.js'; | ||
| import type { EvaluationResult, TextComplexityLevel } from '../schemas/index.js'; | ||
| import { BaseEvaluator, type BaseEvaluatorConfig } from './base.js'; | ||
| import type { StageDetail } from '../telemetry/index.js'; | ||
| import { ValidationError, wrapProviderError } from '../errors.js'; | ||
|
|
||
| /** | ||
| * Conventionality Evaluator | ||
| * | ||
| * Evaluates how explicit, literal, and straightforward a text's meaning is versus | ||
| * how abstract, ironic, figurative, or archaic it is for the target grade level. | ||
| * | ||
| * Based on the Common Core Qualitative Text Complexity Rubric with 4 levels: | ||
| * - Slightly complex | ||
| * - Moderately complex | ||
| * - Very complex | ||
| * - Exceedingly complex | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * const evaluator = new ConventionalityEvaluator({ | ||
| * googleApiKey: process.env.GOOGLE_API_KEY | ||
| * }); | ||
| * | ||
| * const result = await evaluator.evaluate(text, "6"); | ||
| * console.log(result.score); // "Moderately complex" | ||
| * console.log(result.reasoning); | ||
| * ``` | ||
| */ | ||
| export class ConventionalityEvaluator extends BaseEvaluator { | ||
| static readonly metadata = { | ||
| id: 'conventionality', | ||
| name: 'Conventionality', | ||
| description: 'Evaluates how explicit, literal, and straightforward a text\'s meaning is relative to grade level', | ||
| supportedGrades: ['3', '4', '5', '6', '7', '8', '9', '10', '11', '12'] as const, | ||
| requiresGoogleKey: true, | ||
| requiresOpenAIKey: false, | ||
| }; | ||
adnanrhussain marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| private provider: LLMProvider; | ||
|
|
||
| constructor(config: BaseEvaluatorConfig) { | ||
| super(config); | ||
|
|
||
| this.provider = createProvider({ | ||
| type: 'google', | ||
| model: 'gemini-3-flash-preview', | ||
| apiKey: config.googleApiKey, | ||
| maxRetries: this.config.maxRetries, | ||
| }); | ||
| } | ||
|
|
||
| /** | ||
| * Evaluate conventionality complexity for a given text and grade level | ||
| * | ||
| * @param text - The text to evaluate | ||
| * @param grade - The target grade level (3-12) | ||
| * @returns Evaluation result with complexity score and detailed analysis | ||
| * @throws {ValidationError} If text is empty, too short/long, or grade is invalid | ||
| * @throws {APIError} If LLM API calls fail (includes AuthenticationError, RateLimitError, NetworkError, TimeoutError) | ||
| */ | ||
| async evaluate( | ||
| text: string, | ||
| grade: string | ||
| ): Promise<EvaluationResult<TextComplexityLevel, ConventionalityInternal>> { | ||
| this.logger.info('Starting Conventionality evaluation', { | ||
| evaluator: 'conventionality', | ||
| operation: 'evaluate', | ||
| grade, | ||
| textLength: text.length, | ||
| }); | ||
|
|
||
| const startTime = Date.now(); | ||
| const stageDetails: StageDetail[] = []; | ||
|
|
||
| try { | ||
| // Validate inputs — inside try so validation errors are telemetered. | ||
| this.validateText(text); | ||
| this.validateGrade(grade, new Set(ConventionalityEvaluator.metadata.supportedGrades)); | ||
|
|
||
| this.logger.debug('Evaluating conventionality complexity', { | ||
| evaluator: 'conventionality', | ||
| operation: 'conventionality_evaluation', | ||
| }); | ||
|
|
||
| const fkScore = calculateFleschKincaidGrade(text); | ||
| const response = await this.evaluateConventionality(text, grade, fkScore); | ||
|
|
||
| stageDetails.push({ | ||
| stage: 'conventionality_evaluation', | ||
| provider: 'google:gemini-3-flash-preview', | ||
| latency_ms: response.latencyMs, | ||
| token_usage: { | ||
| input_tokens: response.usage.inputTokens, | ||
| output_tokens: response.usage.outputTokens, | ||
| }, | ||
| }); | ||
|
|
||
| const latencyMs = Date.now() - startTime; | ||
|
|
||
| // Aggregate token usage | ||
| const totalTokenUsage = { | ||
| input_tokens: stageDetails.reduce((sum, s) => sum + (s.token_usage?.input_tokens || 0), 0), | ||
| output_tokens: stageDetails.reduce((sum, s) => sum + (s.token_usage?.output_tokens || 0), 0), | ||
| }; | ||
|
|
||
| const result = { | ||
| score: response.data.complexity_score, | ||
| reasoning: response.data.reasoning, | ||
| metadata: { | ||
| model: 'google:gemini-3-flash-preview', | ||
| processingTimeMs: latencyMs, | ||
| }, | ||
| _internal: response.data, | ||
| }; | ||
|
|
||
| // Send success telemetry (fire-and-forget) | ||
| this.sendTelemetry({ | ||
| status: 'success', | ||
| latencyMs, | ||
| textLength: text.length, | ||
| grade, | ||
| provider: 'google:gemini-3-flash-preview', | ||
| tokenUsage: totalTokenUsage, | ||
| metadata: { | ||
| stage_details: stageDetails, | ||
| }, | ||
| inputText: text, | ||
| }).catch(() => { | ||
| // Ignore telemetry errors | ||
| }); | ||
|
|
||
| this.logger.info('Conventionality evaluation completed successfully', { | ||
| evaluator: 'conventionality', | ||
| operation: 'evaluate', | ||
| grade, | ||
| score: result.score, | ||
| processingTimeMs: latencyMs, | ||
| }); | ||
|
|
||
| return result; | ||
| } catch (error) { | ||
| const latencyMs = Date.now() - startTime; | ||
|
|
||
| this.logger.error('Conventionality evaluation failed', { | ||
| evaluator: 'conventionality', | ||
| operation: 'evaluate', | ||
| grade, | ||
| error: error instanceof Error ? error : undefined, | ||
| processingTimeMs: latencyMs, | ||
| completedStages: stageDetails.length, | ||
| }); | ||
|
|
||
| const totalTokenUsage = stageDetails.length > 0 ? { | ||
| input_tokens: stageDetails.reduce((sum, s) => sum + (s.token_usage?.input_tokens || 0), 0), | ||
| output_tokens: stageDetails.reduce((sum, s) => sum + (s.token_usage?.output_tokens || 0), 0), | ||
| } : undefined; | ||
|
|
||
| this.sendTelemetry({ | ||
| status: 'error', | ||
| latencyMs, | ||
| textLength: text.length, | ||
| grade, | ||
| provider: 'google:gemini-3-flash-preview', | ||
| tokenUsage: totalTokenUsage, | ||
| errorCode: error instanceof Error ? error.name : 'UnknownError', | ||
| metadata: stageDetails.length > 0 ? { stage_details: stageDetails } : undefined, | ||
| inputText: text, | ||
| }).catch(() => { | ||
| // Ignore telemetry errors | ||
| }); | ||
|
|
||
| if (error instanceof ValidationError) { | ||
| throw error; | ||
| } | ||
|
|
||
| throw wrapProviderError(error, 'Conventionality evaluation failed'); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Run the Conventionality evaluation LLM call | ||
| */ | ||
| private async evaluateConventionality( | ||
| text: string, | ||
| grade: string, | ||
| fkScore: number | ||
| ): Promise<{ data: ConventionalityInternal; usage: { inputTokens: number; outputTokens: number }; latencyMs: number }> { | ||
| const response = await this.provider.generateStructured({ | ||
| messages: [ | ||
| { role: 'system', content: getSystemPrompt() }, | ||
| { role: 'user', content: getUserPrompt(text, grade, fkScore) }, | ||
| ], | ||
| schema: ConventionalityOutputSchema, | ||
| temperature: 0, | ||
| }); | ||
|
|
||
| return { | ||
| data: response.data, | ||
| usage: response.usage, | ||
| latencyMs: response.latencyMs, | ||
| }; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Functional API for Conventionality evaluation | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * const result = await evaluateConventionality( | ||
| * "The author uses sustained irony to critique societal norms.", | ||
| * "10", | ||
| * { googleApiKey: process.env.GOOGLE_API_KEY } | ||
| * ); | ||
| * ``` | ||
| */ | ||
| export async function evaluateConventionality( | ||
| text: string, | ||
| grade: string, | ||
| config: BaseEvaluatorConfig | ||
| ): Promise<EvaluationResult<TextComplexityLevel, ConventionalityInternal>> { | ||
| const evaluator = new ConventionalityEvaluator(config); | ||
| return evaluator.evaluate(text, grade); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.