@learning-commons/evaluators
v1.4.0
Published
TypeScript SDK for Learning Commons educational evaluators
Readme
@learning-commons/evaluators
TypeScript SDK for Learning Commons evaluators.
Supported evaluators
| Evaluator family | Evaluator | | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Text Complexity evaluators - Docs | Grade Level AppropriatenessInput schemaOutput schemaDocs | | | Background Knowledge DemandsInput schemaOutput schemaDocs | | | Vocabulary ComplexityInput schemaOutput schemaDocs | | | Sentence StructureInput schemaOutput schemaDocs | | | Meaning DirectnessInput schemaOutput schemaDocs | | | Purpose ClarityInput schemaOutput schemaDocs | | | Organizational StructureInput schemaOutput schemaDocs | | | Reference Knowledge DemandsInput schemaOutput schemaDocs | | Feedback evaluators - Docs | Strength AcknowledgmentInput schemaOutput schemaDocs | | | Revision ActionabilityInput schemaOutput schemaDocs | | | Student Response SpecificityInput schemaOutput schemaDocs | | | Revision AccuracyInput schemaOutput schemaDocs | | | Revision ManageabilityInput schemaOutput schemaDocs | | | Withholding AnswersInput schemaOutput schemaDocs | | | Tone AppropriatenessInput schemaOutput schemaDocs | | Academic Standards evaluators - Docs | Math Standards AlignmentInput schemaOutput schemaDocs | | Durable Skills evaluators - Docs | Critical ThinkingInput schemaOutput schemaDocs |
Dependencies
- Node 20.19+ or 22.12+ (
^20.19.0 || >=22.12.0) - Type packages:
npm install -D typescript @types/node @types/json-schema - Vercel AI and zod version 4:
npm install ai zod@^4.1.8 - In your project's
package.json:{ "type": "module" } - In your project's
tsconfig.json:{ "compilerOptions": { "module": "nodenext", "moduleResolution": "nodenext", "target": "es2022", "strict": true, "types": ["node"] } }
Installation
See MIGRATION.md if upgrading from an earlier major version.
Install the SDK:
npm install @learning-commons/evaluatorsAnd the provider adapter(s) for the evaluators you plan to run (See Required API keys for each evaluator):
npm install @ai-sdk/openai # OpenAI
npm install @ai-sdk/google # Google Gemini
npm install @ai-sdk/anthropic # AnthropicQuickstart
import { GradeLevelAppropriatenessEvaluator } from "@learning-commons/evaluators";
// Configure evaluator
const evaluator = new GradeLevelAppropriatenessEvaluator({
googleApiKey: process.env.GOOGLE_API_KEY,
});
// Run an evaluation
const { result, metadata } = await evaluator.evaluate({
text: "The cat's out of the bag now.",
});
// Print evaluation results
console.log(result.grade_band); // a CCSS band, e.g. "2-3"
console.log(result.alternative_grade_band); // the band reachable with scaffolding
console.log(result.scaffolding_needed); // what that band would need
console.log(metadata.model); // "google:gemini-3.6-flash"Methods
The package provides methods to import across the following categories:
These methods can be imported via 2 entry points:
@learning-commons/evaluators- Standalone functions and the evaluator classes@learning-commons/evaluators/batch- Batch evaluation
Discovery
import { getEvaluators, getEvaluator } from "@learning-commons/evaluators";
getEvaluators();
// readonly EvaluatorMetadata[] — every evaluator, in taxonomy order
getEvaluator("text_complexity.ela_reading.vocabulary_complexity");
// EvaluatorMetadata | undefined — current and historical ids both resolveEvaluatorMetadata carries id, stableId, idHistory, name,
description, supportedGrades, defaultProviders, optional
requiredCredentials, and an optional outcome block naming which result
fields hold the verdict and its rationale. requiredCredentials lists only
non-LLM services: ["learning_commons_api_key"] for math standards alignment
and [] for the other eighteen. Provider keys follow defaultProviders, so
["google"] means supply googleApiKey.
Evaluation
Every evaluator class exposes an .evaluate(input) method (see Supported evaluators for each evaluator's input and output).
Each evaluator class also has a matching helper evaluate<Name>(input, config):
import {
GradeLevelAppropriatenessEvaluator,
evaluateGradeLevelAppropriateness,
} from "@learning-commons/evaluators";
// Option 1
const evaluator = new GradeLevelAppropriatenessEvaluator({
googleApiKey: process.env.GOOGLE_API_KEY,
});
await evaluator.evaluate({ text: "The cat's out of the bag now." });
// Option 2: Equivalent helper function: configures, evaluates, discards the instance
await evaluateGradeLevelAppropriateness(
{ text: "The cat's out of the bag now." },
{ googleApiKey: process.env.GOOGLE_API_KEY },
);| Evaluator family | Evaluator | Helper | Typical input |
| ------------------ | ------------------------------------- | ------------------------------------ | ---------------------------------------------------- |
| Text Complexity | GradeLevelAppropriatenessEvaluator | evaluateGradeLevelAppropriateness | { text } |
| | BackgroundKnowledgeDemandsEvaluator | evaluateBackgroundKnowledgeDemands | { text, grade_level } |
| | VocabularyComplexityEvaluator | evaluateVocabularyComplexity | { text, grade_level } |
| | SentenceStructureEvaluator | evaluateSentenceStructure | { text, grade_level } |
| | MeaningDirectnessEvaluator | evaluateMeaningDirectness | { text, grade_level } |
| | PurposeClarityEvaluator | evaluatePurposeClarity | { text, grade_level } |
| | OrganizationalStructureEvaluator | evaluateOrganizationalStructure | { text, grade_level } |
| | ReferenceKnowledgeDemandsEvaluator | evaluateReferenceKnowledgeDemands | { text, grade_level } |
| Graphics | GraphicsComplexityEvaluator | evaluateGraphicsComplexity | { text, grade_level, image_paths, figure_labels? } |
| | GraphicsAccuracyEvaluator | evaluateGraphicsAccuracy | { image_paths, claim } |
| Feedback | StrengthAcknowledgmentEvaluator | evaluateStrengthAcknowledgment | { student_text, feedback_text } |
| | RevisionActionabilityEvaluator | evaluateRevisionActionability | { student_text, feedback_text } |
| | StudentResponseSpecificityEvaluator | evaluateStudentResponseSpecificity | { student_text, feedback_text } |
| | RevisionAccuracyEvaluator | evaluateRevisionAccuracy | { student_text, feedback_text } |
| | RevisionManageabilityEvaluator | evaluateRevisionManageability | { student_text, feedback_text } |
| | WithholdingAnswersEvaluator | evaluateWithholdingAnswers | { student_text, feedback_text } |
| | ToneAppropriatenessEvaluator | evaluateToneAppropriateness | { student_text, feedback_text } |
| Academic Standards | MathStandardsAlignmentEvaluator | evaluateMathStandardsAlignment | { question, statement_code, jurisdiction } |
| Durable Skills | CriticalThinkingEvaluator | evaluateCriticalThinking | { assignment_text, source_passages, essay_text } |
The Math Standards Alignment evaluator also exposes .evaluateByCode(), .evaluateByUuid({ question, case_identifier_uuid }) methods, as well as evaluateItems and evaluateByGradeLevel bulk methods on the instance (these have no helpers):
import {
MathStandardsAlignmentEvaluator,
Jurisdiction,
} from "@learning-commons/evaluators";
const math = new MathStandardsAlignmentEvaluator({
anthropicApiKey: process.env.ANTHROPIC_API_KEY,
learningCommonsApiKey: process.env.LEARNING_COMMONS_API_KEY,
});
// Single evaluate calls
await math.evaluateByCode({ question: "…", statement_code: "3.MD.C.7.d" });
await math.evaluateByUuid({
question: "…",
case_identifier_uuid: "6ba25656-d7cc-11e8-824f-0242ac160002",
});
// Bulk methods
await math.evaluateItems(
[{ question: "…", statement_codes: ["5.NBT.A.1"] }],
Jurisdiction.MultiState,
{ useCoarseFilter: true, onProgress: (done, total) => {} },
);
await math.evaluateByGradeLevel(["…"], "5", Jurisdiction.MultiState); // Fetch every 5th grade math standard + evaluate questions against themOutcomes
import { getEvaluator, readOutcome } from "@learning-commons/evaluators";
const evaluation = await evaluator.evaluate(input);
const outcome = getEvaluator(evaluation.evaluator)?.outcome;
const { score, reasoning } = readOutcome(evaluation, outcome);readOutcome picks the verdict and rationale named by the evaluator's declared outcome block.
score is always a string, so a failing feedback verdict is "0", which is truthy. Compare explicitly (score === "1"), or read the numeric field from the result directly. score is undefined when the evaluator has no declared outcome or the payload is missing that field — a reporting gap, not an evaluation failure.
Standards
import {
Jurisdiction,
StandardsCatalog,
normalizeStatementCode,
} from "@learning-commons/evaluators";
normalizeStatementCode(" 5.nbt.a.1 "); // "5.NBT.A.1"
const catalog = new StandardsCatalog({
learningCommonsApiKey: process.env.LEARNING_COMMONS_API_KEY!,
academicSubject: "Mathematics",
});
await catalog.listStandards("5", { jurisdiction: Jurisdiction.MultiState });
await catalog.getStandard("5.NBT.A.1");
await catalog.resolveStandard("5.NBT.A.1");
await catalog.validateCodes(["5.NBT.A.1", "5.NBT.A.2"]);| Method | Returns | Throws |
| --------------------------------------- | --------------------------------------------------------------------------------------------------- | ------------------------------------------------- |
| listStandards(gradeLevel, opts?) | every instructional standard for that grade | Knowledge Graph / auth errors |
| getStandard(statementCode, opts?) | one StandardInfo | InputValidationError, StandardNotFoundError |
| resolveStandard(statementCode, opts?) | a CodeValidation (resolved, ambiguous, not-found, no-learning-components, or unchecked) | only AuthenticationError / ConfigurationError |
| validateCodes(statementCodes, opts?) | one CodeValidation per distinct normalized code | only AuthenticationError / ConfigurationError |
Lookups default to Multi-State (Common Core). Pass jurisdiction or academicSubject on the call to override the catalog defaults.
Text features
These power sentence-structure preprocessing. They are deterministic and do not call a model.
import {
calculateFleschKincaidGrade,
calculateReadabilityMetrics,
addEngineeredFeatures,
featuresToJSON,
} from "@learning-commons/evaluators";
calculateFleschKincaidGrade(text); // number
calculateReadabilityMetrics(text); // counts, averages, and the FK grade
addEngineeredFeatures(analysis); // SentenceAnalysis → SentenceFeatures
featuresToJSON(features); // JSON string for a promptBatch evaluation
import {
BatchEvaluator,
getFamilies,
getFamily,
parseCSV,
renderOutputs,
formatAsCSV,
formatAsJSON,
formatAsHTML,
} from "@learning-commons/evaluators/batch";
getFamilies(); // [text-complexity, math-standards-alignment, feedback]
getFamily("feedback"); // throws if the id is unknown
const rows = parseCSV("./texts.csv"); // a path, not CSV text
const batch = new BatchEvaluator({
googleApiKey: process.env.GOOGLE_API_KEY,
openaiApiKey: process.env.OPENAI_API_KEY,
});
const output = await batch.evaluate(rows, "text-complexity", {
selectedMemberIds: ["text_complexity.ela_reading.vocabulary_complexity"],
onProgress: (result) => {},
});
batch.cancel(); // stops in-flight work; returns results collected so far
const { csv, json, html } = renderOutputs("text-complexity", output, {
csvPath: "./texts.csv",
groupId: "text-complexity",
reportId: "run-1",
generatedAt: new Date(),
totalInputRows: rows.length,
});| Function | Role |
| --------------------------------------------------- | ------------------------------------------------------------------------------------------ |
| getFamilies() | every family, copied so callers cannot mutate the registry |
| getFamily(id) | one family (members, columns, maxInputRows); throws listing valid ids |
| parseCSV(path) | file → BatchInput[]; family column rules apply later |
| BatchEvaluator.evaluate(inputs, family, options?) | run the family (or a subset) over the rows |
| BatchEvaluator.cancel() | abort and return partial BatchResult[] |
| renderOutputs(familyId, output, meta) | the same CSV / JSON / HTML the CLI writes (html is absent when the family has no report) |
| formatAsCSV(output) | flattened per-row summary |
| formatAsJSON(output, meta) | machine-readable per-(row, evaluator) records |
| formatAsHTML(output, meta) | text-complexity rubric report |
evaluate accepts a family id or an EvaluatorFamily object. For the CLI,
column requirements, and report shapes, see src/batch/README.md.
More resources
Check out the docs for more implementation details:
- Configuration, including model overrides
- Inputs and output schemas for all Supported evaluators
- Read exported schemas with
Object.keys(ToneAppropriatenessOutputSchema.shape.key_features.shape)
- Read exported schemas with
- Error handling
- Batch evaluator
License
MIT
