@learning-commons/evaluators 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1769,29 +1769,482 @@ async function evaluateGradeLevelAppropriateness(text, config) {
1769
1769
  const evaluator = new GradeLevelAppropriatenessEvaluator(config);
1770
1770
  return evaluator.evaluate(text);
1771
1771
  }
1772
+ var SmkOutputSchema = zod.z.object({
1773
+ identified_topics: zod.z.array(zod.z.string()).describe("List of major subjects/concepts found in the text."),
1774
+ curriculum_check: zod.z.string().describe("Whether the topics are standard K-8 or specialized high school level."),
1775
+ assumptions_and_scaffolding: zod.z.string().describe("What the author assumes the reader knows vs. what is explained."),
1776
+ friction_analysis: zod.z.string().describe("Whether difficulty comes from vocabulary/structure or actual knowledge demands."),
1777
+ complexity_score: TextComplexityLevel.describe("The subject matter knowledge complexity level of the text"),
1778
+ reasoning: zod.z.string().describe("A brief synthesis of why the text fits the chosen complexity level.")
1779
+ });
1780
+
1781
+ // ../../evals/prompts/subject-matter-knowledge/system.txt
1782
+ var system_default2 = `
1783
+ To perform the task of evaluating text complexity based on Subject Matter Knowledge (SMK), strictly adhere to the following instructions.
1784
+ Role
1785
+ You are an expert K-12 Literacy Pedagogue and Text Complexity Evaluator. Your specific focus is analyzing Subject Matter Knowledge (SMK) demands according to the Common Core Qualitative Text Complexity Rubric.
1786
+ Objective
1787
+ Analyze a provided text relative to a target grade_level. You must determine the extent of background knowledge required to comprehend the text. You must distinguish between Common/Standard knowledge (generally lower/moderate complexity) and Specialized/Theoretical knowledge (generally higher complexity).
1788
+ Input Data
1789
+ text: The passage to analyze.
1790
+ grade_level: The target student grade (integer).
1791
+ fk_score: Flesch-Kincaid Grade Level. Note: Use this only as a loose proxy for sentence structure. Do not let a high FK score artificially inflate the Subject Matter Knowledge score if the concepts remain simple.
1792
+
1793
+ 1. The Rubric: Subject Matter Knowledge (SMK)
1794
+ 1. Slightly Complex
1795
+ Scope: Everyday, practical knowledge, and Introduction to Skills.
1796
+ Concept Type: Concrete, directly observable, and familiar.
1797
+ Key Indicator: "How-to" texts involving familiar objects (e.g., drawing a cupboard, playing a game, family life). Even if specific terms (like "scale" or "measure") are used, if the application is on a common object, it remains Slightly Complex.
1798
+ 2. Moderately Complex
1799
+ Scope: Common Discipline-Specific Knowledge or Narrative History.
1800
+ Definition: Topics widely introduced in K-8 curricula (Basic American History, Geography, Earth Science, Biology).
1801
+ Key Characteristic: The text bridges concrete descriptions with abstract themes (e.g., using farming to discuss justice), OR narrates historical events via sensory details.
1802
+ Spatial Reasoning: Texts requiring mental manipulation of maps/routes are generally Moderate, unless the object is a familiar household item (see Slightly Complex).
1803
+ 3. Very Complex
1804
+ Scope: Specialized Discipline-Specific, Engineering Mechanics, or Political Theory.
1805
+ Definition: Topics characteristic of High School (9-12) curricula requiring abstract mental models.
1806
+ Key Characteristic: Requires understanding mechanisms (how physics works/propulsion), chemical composition, or undefined political stakes (specific treaties, alliances, or secularization without context).
1807
+ 4. Exceedingly Complex
1808
+ Scope: Professional or Academic knowledge.
1809
+
1810
+ 2. The Expert Mental Model (Decision Logic)
1811
+ Use these refined rules to categorize cases.
1812
+ Rule A: The "Layers of Meaning" Check
1813
+ Concrete -> Abstract (Moderate): The text describes concrete things (farming) to argue an abstract point (justice, rights).
1814
+ Concrete -> Concrete (Slightly): The text describes concrete things (lines, paper) to achieve a concrete result (drawing a cupboard). Do not over-rank practical instructions.
1815
+ Rule B: The Science & Engineering Boundary
1816
+ Observational (Moderate): Habitats, Water Cycle, observable traits, simple definitions.
1817
+ Mechanistic/Theoretical (Very): Engineering mechanics (how propulsion works via reaction), Instrumentation (using a spectroscope), or Chemical/Atomic theory.
1818
+ Test: Does the text explain how a machine functions using physical principles? If yes, it is Very Complex.
1819
+ Rule C: The History/Social Studies Boundary
1820
+ General/Narrative (Moderate):
1821
+ Sensory: Battle descriptions focusing on sights/sounds (flashes, smoke).
1822
+ Standard Topics: Immigration, Slavery, Government, Geography. Lists of nationalities or religions are "Common Knowledge" for Grades 6-8.
1823
+ Political/Contextual (Very):
1824
+ Implicit Context: Texts assuming knowledge of specific political factions, treaties, or the causes of events without explanation (e.g., "The Allies," "The Front," "The secularization of the clergy").
1825
+ Test: If the reader must know why two groups are fighting or the specific political history of a revolution to understand the text, it is Very Complex.
1826
+ Rule D: The "Technical vs. Practical" Trap
1827
+ Scenario: A text teaches a technical skill (e.g., Technical Drawing/Technology) but applies it to a familiar object (a cupboard).
1828
+ Decision: Slightly Complex.
1829
+ Reasoning: Do not confuse "Technical Vocabulary" (scale, thick lines) with "Theoretical Complexity." If the underlying concept is familiar (furniture), the SMK load is low.
1830
+
1831
+ 3. Critical Calibration Examples
1832
+ Text: "Make a rough sketch... How many shelves should the cupboard have?" (Grade 2) -> Slightly Complex.
1833
+ Reasoning: (Rule D/Rule A) Although it mentions "scale" and "technology," the task is concrete and relies on everyday knowledge.
1834
+ Text: "Hydraulic propulsion works by sucking water at the bow and forcing it sternward." (Grade 10) -> Very Complex.
1835
+ Reasoning: (Rule B) Explains a mechanism using physics principles.
1836
+ Text: "The Allies fight the enemy's cavalry; we remember the hospitality to priests during the Revolution." (Grade 6) -> Very Complex.
1837
+ Reasoning: (Rule C) Assumes undefined knowledge of WWI alliances and the specific political history of the French Revolution.
1838
+ Text: "Immigrants from Poland, Italy, and Russia arrived. Most were Catholic or Orthodox." (Grade 7) -> Moderately Complex.
1839
+ Reasoning: (Rule C) Standard K-8 topic. Lists of nationalities are content vocabulary, not specialized theory.
1840
+
1841
+ 4. Output Format
1842
+ Return your analysis in a valid JSON object. Do not include markdown formatting.
1843
+ Keys:
1844
+ - identified_topics: List[str] identifying the core subjects.
1845
+ - curriculum_check: String explaining if the topics are "Standard/General" (typical for K-8) or "Specialized/High School" (typical for 9-12).
1846
+ - assumptions_and_scaffolding: String analyzing what the author assumes the reader knows vs what is explained.
1847
+ - friction_analysis: String discussing the gap between Concrete description and Abstract meaning.
1848
+ - complexity_score: String (One of: slightly_complex, moderately_complex, very_complex, exceedingly_complex).
1849
+ - reasoning: String synthesizing the decision.
1850
+
1851
+ `;
1852
+
1853
+ // ../../evals/prompts/subject-matter-knowledge/user.txt
1854
+ var user_default2 = "Analyze:\nText: {text}\nGrade: {grade}\nFK Score: {fk_score}";
1855
+
1856
+ // src/prompts/subject-matter-knowledge/index.ts
1857
+ function getSystemPrompt3() {
1858
+ return system_default2;
1859
+ }
1860
+ function getUserPrompt3(text, grade, fkScore) {
1861
+ return user_default2.replaceAll("{text}", text).replaceAll("{grade}", grade).replaceAll("{fk_score}", fkScore.toString());
1862
+ }
1863
+
1864
+ // src/evaluators/smk.ts
1865
+ var SmkEvaluator = class _SmkEvaluator extends BaseEvaluator {
1866
+ static metadata = {
1867
+ id: "subject-matter-knowledge",
1868
+ name: "Subject Matter Knowledge",
1869
+ description: "Evaluates background knowledge demands of educational texts relative to grade level",
1870
+ supportedGrades: ["3", "4", "5", "6", "7", "8", "9", "10", "11", "12"],
1871
+ requiresGoogleKey: true,
1872
+ requiresOpenAIKey: false
1873
+ };
1874
+ provider;
1875
+ constructor(config) {
1876
+ super(config);
1877
+ this.provider = createProvider({
1878
+ type: "google",
1879
+ model: "gemini-3-flash-preview",
1880
+ apiKey: config.googleApiKey,
1881
+ maxRetries: this.config.maxRetries
1882
+ });
1883
+ }
1884
+ /**
1885
+ * Evaluate subject matter knowledge complexity for a given text and grade level
1886
+ *
1887
+ * @param text - The text to evaluate
1888
+ * @param grade - The target grade level (3-12)
1889
+ * @returns Evaluation result with complexity score and detailed analysis
1890
+ * @throws {ValidationError} If text is empty, too short/long, or grade is invalid
1891
+ * @throws {APIError} If LLM API calls fail (includes AuthenticationError, RateLimitError, NetworkError, TimeoutError)
1892
+ */
1893
+ async evaluate(text, grade) {
1894
+ this.logger.info("Starting SMK evaluation", {
1895
+ evaluator: "subject-matter-knowledge",
1896
+ operation: "evaluate",
1897
+ grade,
1898
+ textLength: text.length
1899
+ });
1900
+ const startTime = Date.now();
1901
+ const stageDetails = [];
1902
+ try {
1903
+ this.validateText(text);
1904
+ this.validateGrade(grade, new Set(_SmkEvaluator.metadata.supportedGrades));
1905
+ this.logger.debug("Evaluating subject matter knowledge complexity", {
1906
+ evaluator: "subject-matter-knowledge",
1907
+ operation: "smk_evaluation"
1908
+ });
1909
+ const fkScore = calculateFleschKincaidGrade(text);
1910
+ const response = await this.evaluateSmk(text, grade, fkScore);
1911
+ stageDetails.push({
1912
+ stage: "smk_evaluation",
1913
+ provider: "google:gemini-3-flash-preview",
1914
+ latency_ms: response.latencyMs,
1915
+ token_usage: {
1916
+ input_tokens: response.usage.inputTokens,
1917
+ output_tokens: response.usage.outputTokens
1918
+ }
1919
+ });
1920
+ const latencyMs = Date.now() - startTime;
1921
+ const totalTokenUsage = {
1922
+ input_tokens: stageDetails.reduce((sum, s) => sum + (s.token_usage?.input_tokens || 0), 0),
1923
+ output_tokens: stageDetails.reduce((sum, s) => sum + (s.token_usage?.output_tokens || 0), 0)
1924
+ };
1925
+ const result = {
1926
+ score: response.data.complexity_score,
1927
+ reasoning: response.data.reasoning,
1928
+ metadata: {
1929
+ model: "google:gemini-3-flash-preview",
1930
+ processingTimeMs: latencyMs
1931
+ },
1932
+ _internal: response.data
1933
+ };
1934
+ this.sendTelemetry({
1935
+ status: "success",
1936
+ latencyMs,
1937
+ textLength: text.length,
1938
+ grade,
1939
+ provider: "google:gemini-3-flash-preview",
1940
+ tokenUsage: totalTokenUsage,
1941
+ metadata: {
1942
+ stage_details: stageDetails
1943
+ },
1944
+ inputText: text
1945
+ }).catch(() => {
1946
+ });
1947
+ this.logger.info("SMK evaluation completed successfully", {
1948
+ evaluator: "subject-matter-knowledge",
1949
+ operation: "evaluate",
1950
+ grade,
1951
+ score: result.score,
1952
+ processingTimeMs: latencyMs
1953
+ });
1954
+ return result;
1955
+ } catch (error) {
1956
+ const latencyMs = Date.now() - startTime;
1957
+ this.logger.error("SMK evaluation failed", {
1958
+ evaluator: "subject-matter-knowledge",
1959
+ operation: "evaluate",
1960
+ grade,
1961
+ error: error instanceof Error ? error : void 0,
1962
+ processingTimeMs: latencyMs,
1963
+ completedStages: stageDetails.length
1964
+ });
1965
+ const totalTokenUsage = stageDetails.length > 0 ? {
1966
+ input_tokens: stageDetails.reduce((sum, s) => sum + (s.token_usage?.input_tokens || 0), 0),
1967
+ output_tokens: stageDetails.reduce((sum, s) => sum + (s.token_usage?.output_tokens || 0), 0)
1968
+ } : void 0;
1969
+ this.sendTelemetry({
1970
+ status: "error",
1971
+ latencyMs,
1972
+ textLength: text.length,
1973
+ grade,
1974
+ provider: "google:gemini-3-flash-preview",
1975
+ tokenUsage: totalTokenUsage,
1976
+ errorCode: error instanceof Error ? error.name : "UnknownError",
1977
+ metadata: stageDetails.length > 0 ? { stage_details: stageDetails } : void 0,
1978
+ inputText: text
1979
+ }).catch(() => {
1980
+ });
1981
+ if (error instanceof ValidationError) {
1982
+ throw error;
1983
+ }
1984
+ throw wrapProviderError(error, "SMK evaluation failed");
1985
+ }
1986
+ }
1987
+ /**
1988
+ * Run the SMK evaluation LLM call
1989
+ */
1990
+ async evaluateSmk(text, grade, fkScore) {
1991
+ const response = await this.provider.generateStructured({
1992
+ messages: [
1993
+ { role: "system", content: getSystemPrompt3() },
1994
+ { role: "user", content: getUserPrompt3(text, grade, fkScore) }
1995
+ ],
1996
+ schema: SmkOutputSchema,
1997
+ temperature: 0
1998
+ });
1999
+ return {
2000
+ data: response.data,
2001
+ usage: response.usage,
2002
+ latencyMs: response.latencyMs
2003
+ };
2004
+ }
2005
+ };
2006
+ async function evaluateSmk(text, grade, config) {
2007
+ const evaluator = new SmkEvaluator(config);
2008
+ return evaluator.evaluate(text, grade);
2009
+ }
2010
+ var ConventionalityOutputSchema = zod.z.object({
2011
+ conventionality_features: zod.z.array(zod.z.string()).describe("The specific language features driving the complexity (e.g., literal narrative, concrete actions, sustained irony, abstract qualities) with direct quotes from the text."),
2012
+ grade_context: zod.z.string().describe("How the conventionality demands compare to general expectations for the provided target grade."),
2013
+ instructional_insights: zod.z.string().describe("Actionable pedagogical suggestions for scaffolding the conventionality features in the classroom."),
2014
+ complexity_score: TextComplexityLevel.describe("The conventionality complexity level of the text"),
2015
+ reasoning: zod.z.string().describe("A detailed explanation of the rating, citing specific features in the text and referencing the expert guardrails.")
2016
+ });
2017
+
2018
+ // ../../evals/prompts/conventionality/system.txt
2019
+ var system_default3 = `Role
2020
+ You are an expert reading teacher and text complexity evaluator. Your task is to evaluate the "Conventionality" of a text and assign it a complexity level based on a 4-point scale, carefully factoring in the target grade level.
2021
+
2022
+ Objective
2023
+ Measure how explicit, literal, and straightforward the text's meaning is, versus how abstract, ironic, figurative, or archaic it is. Focus on the hiddenness of the meaning, the use of conceptual framing, the reliance on abstract reasoning, and the familiarity of the expression for the target grade.
2024
+
2025
+ Complexity Levels
2026
+ - Slightly Complex: Explicit, literal, straightforward, easy to understand. Meaning is entirely on the surface. The language is concrete, and the meaning is clear and procedural, mostly referring to observable materials and actions. Contains no symbolic or ironic language, and conceptual interpretation is not required. Contains limited figurative language that is common and easy to comprehend at the target grade level.
2027
+ - Moderately Complex: Largely explicit and easy to understand with some occasions for more complex meaning. May contain a noticeable amount of archaic/dated phrasing, formal historical prose, vocabulary demands, background knowledge requirements, or expressions that are less familiar to the target grade level, which might make the text feel vague or slightly challenging.
2028
+ - Very Complex: Fairly complex; contains sustained abstract language, conceptual framing, rhetorical idealization, ironic comparisons, or central metaphors that drive the meaning of the text. Addresses concepts, beliefs, and abstract qualities rather than just concrete objects. The tone or underlying message requires interpretation, even if the surface message is clear.
2029
+ - Exceedingly Complex: Dense and complex; contains considerable abstract, ironic, and/or figurative language. Meaning is heavily hidden, deeply conceptual, or relies heavily on complex rhetorical devices.
2030
+
2031
+ Essential Evaluation Rules
2032
+ 1. Concrete & Procedural Texts: Texts that are highly concrete, clear, and procedural (e.g., describing observable materials, mechanical processes, or physical actions) should typically be rated "Slightly Complex."
2033
+
2034
+ 2. Grade-Level Anchoring and Vague Narratives: Always consider the target grade. A literal historical narrative that might be straightforward for older students can be "Moderately Complex" for younger students (e.g., 4th graders) if it involves less familiar expressions, older contexts (e.g., wagon loads, traveling by horseback), vocabulary demands, and background knowledge requirements that make the text feel vague or slightly demanding for that age group.
2035
+
2036
+ 3. Rhetorical Idealization and Abstract Qualities: If an entire argument or narrative is built around abstract qualities (e.g., national character, bravery, liberty) and uses repeated figurative language or personification to portray a subject in a certain idealized way, rate the text as "Very Complex." Even if the figurative language is easy to interpret, the need to interpret the rhetorical tone and sustained abstract focus elevates the complexity beyond level two.
2037
+
2038
+ 4. Common Idioms and Grade-Level Appropriateness: Do NOT elevate a text to "Moderately Complex" simply because it contains a few common idiomatic expressions. If these expressions are widely known and easy for the target grade to understand without making the text feel vague, the text remains "Slightly Complex."
2039
+
2040
+ 5. Conversational and Hypothetical Framing: Using a second-person conversational hook (e.g., "Imagine you are...") to explain a concept is a standard, literal device for engaging readers. It does not constitute complex conceptual framing.
2041
+
2042
+ 6. Sustained vs. Occasional Impact: If abstract language, figurative phrasing, irony, or conceptual framing is sustained throughout the text and central to the argument/meaning, the text is Very Complex. Reserve Moderately Complex for texts where the explicit meaning dominates but the expression, vocabulary, or archaic language provides a moderate conventionality challenge.
2043
+
2044
+ 7. Central Metaphors and Conceptual Framing: When an author uses a central metaphor to explain a concept or uses figurative phrasing to explain how things "work," this abstract reasoning drives the meaning, elevating the text to Very Complex.
2045
+
2046
+ 8. Irony and Abstract Comparisons: Texts that rely on sustained irony, especially through comparative arguments, are inherently Very Complex for younger students.
2047
+
2048
+ 9. Isolate Conventionality from Vocabulary: Do not inflate the Conventionality score just because the text uses archaic, dated, or highly academic vocabulary.
2049
+
2050
+ Input Format
2051
+ You will receive:
2052
+ - text: The passage to evaluate.
2053
+ - grade_level: The target student grade level.
2054
+ - fk_score: The Flesch-Kincaid readability score.
2055
+
2056
+ Output Format
2057
+ Provide a JSON object containing ONLY the following keys:
2058
+ - complexity_score: (String) One of the 4 scale levels exactly as formatted: 'slightly_complex', 'moderately_complex', 'very_complex', or 'exceedingly_complex'.
2059
+ - reasoning: (String) A detailed explanation of the rating, citing specific features in the text and referencing the expert guardrails (e.g., noting if the text relies on abstract qualities/rhetorical idealization, if vocabulary/background knowledge demands make a literal text vague for the grade level, or if it is strictly concrete/procedural).
2060
+ - conventionality_features: (List of Strings) The specific language features driving the complexity (e.g., literal narrative, concrete actions, less familiar expressions, sustained irony, abstract qualities, rhetorical idealization, archaic phrasing) with direct quotes from the text.
2061
+ - grade_context: (String) How the conventionality demands compare to general expectations for the provided target grade.
2062
+ - instructional_insights: (String) Actionable pedagogical suggestions for scaffolding the conventionality features in the classroom.`;
2063
+
2064
+ // ../../evals/prompts/conventionality/user.txt
2065
+ var user_default3 = "Analyze:\nText: {text}\nGrade: {grade}\nFK Score: {fk_score}";
2066
+
2067
+ // src/prompts/conventionality/index.ts
2068
+ function getSystemPrompt4() {
2069
+ return system_default3;
2070
+ }
2071
+ function getUserPrompt4(text, grade, fkScore) {
2072
+ return user_default3.replaceAll("{text}", text).replaceAll("{grade}", grade).replaceAll("{fk_score}", fkScore.toString());
2073
+ }
2074
+
2075
+ // src/evaluators/conventionality.ts
2076
+ var ConventionalityEvaluator = class _ConventionalityEvaluator extends BaseEvaluator {
2077
+ static metadata = {
2078
+ id: "conventionality",
2079
+ name: "Conventionality",
2080
+ description: "Evaluates how explicit, literal, and straightforward a text's meaning is relative to grade level",
2081
+ supportedGrades: ["3", "4", "5", "6", "7", "8", "9", "10", "11", "12"],
2082
+ requiresGoogleKey: true,
2083
+ requiresOpenAIKey: false
2084
+ };
2085
+ provider;
2086
+ constructor(config) {
2087
+ super(config);
2088
+ this.provider = createProvider({
2089
+ type: "google",
2090
+ model: "gemini-3-flash-preview",
2091
+ apiKey: config.googleApiKey,
2092
+ maxRetries: this.config.maxRetries
2093
+ });
2094
+ }
2095
+ /**
2096
+ * Evaluate conventionality complexity for a given text and grade level
2097
+ *
2098
+ * @param text - The text to evaluate
2099
+ * @param grade - The target grade level (3-12)
2100
+ * @returns Evaluation result with complexity score and detailed analysis
2101
+ * @throws {ValidationError} If text is empty, too short/long, or grade is invalid
2102
+ * @throws {APIError} If LLM API calls fail (includes AuthenticationError, RateLimitError, NetworkError, TimeoutError)
2103
+ */
2104
+ async evaluate(text, grade) {
2105
+ this.logger.info("Starting Conventionality evaluation", {
2106
+ evaluator: "conventionality",
2107
+ operation: "evaluate",
2108
+ grade,
2109
+ textLength: text.length
2110
+ });
2111
+ const startTime = Date.now();
2112
+ const stageDetails = [];
2113
+ try {
2114
+ this.validateText(text);
2115
+ this.validateGrade(grade, new Set(_ConventionalityEvaluator.metadata.supportedGrades));
2116
+ this.logger.debug("Evaluating conventionality complexity", {
2117
+ evaluator: "conventionality",
2118
+ operation: "conventionality_evaluation"
2119
+ });
2120
+ const fkScore = calculateFleschKincaidGrade(text);
2121
+ const response = await this.evaluateConventionality(text, grade, fkScore);
2122
+ stageDetails.push({
2123
+ stage: "conventionality_evaluation",
2124
+ provider: "google:gemini-3-flash-preview",
2125
+ latency_ms: response.latencyMs,
2126
+ token_usage: {
2127
+ input_tokens: response.usage.inputTokens,
2128
+ output_tokens: response.usage.outputTokens
2129
+ }
2130
+ });
2131
+ const latencyMs = Date.now() - startTime;
2132
+ const totalTokenUsage = {
2133
+ input_tokens: stageDetails.reduce((sum, s) => sum + (s.token_usage?.input_tokens || 0), 0),
2134
+ output_tokens: stageDetails.reduce((sum, s) => sum + (s.token_usage?.output_tokens || 0), 0)
2135
+ };
2136
+ const result = {
2137
+ score: response.data.complexity_score,
2138
+ reasoning: response.data.reasoning,
2139
+ metadata: {
2140
+ model: "google:gemini-3-flash-preview",
2141
+ processingTimeMs: latencyMs
2142
+ },
2143
+ _internal: response.data
2144
+ };
2145
+ this.sendTelemetry({
2146
+ status: "success",
2147
+ latencyMs,
2148
+ textLength: text.length,
2149
+ grade,
2150
+ provider: "google:gemini-3-flash-preview",
2151
+ tokenUsage: totalTokenUsage,
2152
+ metadata: {
2153
+ stage_details: stageDetails
2154
+ },
2155
+ inputText: text
2156
+ }).catch(() => {
2157
+ });
2158
+ this.logger.info("Conventionality evaluation completed successfully", {
2159
+ evaluator: "conventionality",
2160
+ operation: "evaluate",
2161
+ grade,
2162
+ score: result.score,
2163
+ processingTimeMs: latencyMs
2164
+ });
2165
+ return result;
2166
+ } catch (error) {
2167
+ const latencyMs = Date.now() - startTime;
2168
+ this.logger.error("Conventionality evaluation failed", {
2169
+ evaluator: "conventionality",
2170
+ operation: "evaluate",
2171
+ grade,
2172
+ error: error instanceof Error ? error : void 0,
2173
+ processingTimeMs: latencyMs,
2174
+ completedStages: stageDetails.length
2175
+ });
2176
+ const totalTokenUsage = stageDetails.length > 0 ? {
2177
+ input_tokens: stageDetails.reduce((sum, s) => sum + (s.token_usage?.input_tokens || 0), 0),
2178
+ output_tokens: stageDetails.reduce((sum, s) => sum + (s.token_usage?.output_tokens || 0), 0)
2179
+ } : void 0;
2180
+ this.sendTelemetry({
2181
+ status: "error",
2182
+ latencyMs,
2183
+ textLength: text.length,
2184
+ grade,
2185
+ provider: "google:gemini-3-flash-preview",
2186
+ tokenUsage: totalTokenUsage,
2187
+ errorCode: error instanceof Error ? error.name : "UnknownError",
2188
+ metadata: stageDetails.length > 0 ? { stage_details: stageDetails } : void 0,
2189
+ inputText: text
2190
+ }).catch(() => {
2191
+ });
2192
+ if (error instanceof ValidationError) {
2193
+ throw error;
2194
+ }
2195
+ throw wrapProviderError(error, "Conventionality evaluation failed");
2196
+ }
2197
+ }
2198
+ /**
2199
+ * Run the Conventionality evaluation LLM call
2200
+ */
2201
+ async evaluateConventionality(text, grade, fkScore) {
2202
+ const response = await this.provider.generateStructured({
2203
+ messages: [
2204
+ { role: "system", content: getSystemPrompt4() },
2205
+ { role: "user", content: getUserPrompt4(text, grade, fkScore) }
2206
+ ],
2207
+ schema: ConventionalityOutputSchema,
2208
+ temperature: 0
2209
+ });
2210
+ return {
2211
+ data: response.data,
2212
+ usage: response.usage,
2213
+ latencyMs: response.latencyMs
2214
+ };
2215
+ }
2216
+ };
2217
+ async function evaluateConventionality(text, grade, config) {
2218
+ const evaluator = new ConventionalityEvaluator(config);
2219
+ return evaluator.evaluate(text, grade);
2220
+ }
1772
2221
  var TextComplexityEvaluator = class _TextComplexityEvaluator extends BaseEvaluator {
1773
2222
  static metadata = {
1774
2223
  id: "text-complexity",
1775
2224
  name: "Text Complexity",
1776
- description: "Composite evaluator analyzing vocabulary and sentence structure complexity",
2225
+ description: "Composite evaluator analyzing vocabulary, sentence structure, subject matter knowledge, and conventionality complexity",
1777
2226
  supportedGrades: ["3", "4", "5", "6", "7", "8", "9", "10", "11", "12"],
1778
2227
  requiresGoogleKey: true,
1779
2228
  requiresOpenAIKey: true
1780
2229
  };
1781
2230
  vocabularyEvaluator;
1782
2231
  sentenceStructureEvaluator;
2232
+ smkEvaluator;
2233
+ conventionalityEvaluator;
1783
2234
  limit;
1784
2235
  constructor(config) {
1785
2236
  super(config);
1786
2237
  this.vocabularyEvaluator = new VocabularyEvaluator(config);
1787
2238
  this.sentenceStructureEvaluator = new SentenceStructureEvaluator(config);
2239
+ this.smkEvaluator = new SmkEvaluator(config);
2240
+ this.conventionalityEvaluator = new ConventionalityEvaluator(config);
1788
2241
  this.limit = pLimit__default.default(3);
1789
2242
  }
1790
2243
  /**
1791
2244
  * Evaluate text complexity for a given text and grade level
1792
2245
  *
1793
- * Runs vocabulary and sentence structure evaluations in parallel with concurrency control.
1794
- * If both sub-evaluators fail, throws an error. Otherwise returns a result map where
2246
+ * Runs vocabulary, sentence structure, and SMK evaluations in parallel with concurrency control.
2247
+ * If all three sub-evaluators fail, throws an error. Otherwise returns a result map where
1795
2248
  * failed sub-evaluators are represented as `{ error: Error }`.
1796
2249
  *
1797
2250
  * @param text - The text to evaluate
@@ -1810,18 +2263,24 @@ var TextComplexityEvaluator = class _TextComplexityEvaluator extends BaseEvaluat
1810
2263
  this.validateText(text);
1811
2264
  this.validateGrade(grade, new Set(_TextComplexityEvaluator.metadata.supportedGrades));
1812
2265
  const startTime = Date.now();
1813
- const [vocabResult, sentenceResult] = await Promise.all([
2266
+ const [vocabResult, sentenceResult, smkResult, conventionalityResult] = await Promise.all([
1814
2267
  this.limit(() => this.runSubEvaluator(this.vocabularyEvaluator, text, grade)),
1815
- this.limit(() => this.runSubEvaluator(this.sentenceStructureEvaluator, text, grade))
2268
+ this.limit(() => this.runSubEvaluator(this.sentenceStructureEvaluator, text, grade)),
2269
+ this.limit(() => this.runSubEvaluator(this.smkEvaluator, text, grade)),
2270
+ this.limit(() => this.runSubEvaluator(this.conventionalityEvaluator, text, grade))
1816
2271
  ]);
1817
2272
  const latencyMs = Date.now() - startTime;
1818
2273
  const vocabFailed = "error" in vocabResult;
1819
2274
  const sentenceFailed = "error" in sentenceResult;
1820
- const hasFailures = vocabFailed || sentenceFailed;
2275
+ const smkFailed = "error" in smkResult;
2276
+ const conventionalityFailed = "error" in conventionalityResult;
2277
+ const hasFailures = vocabFailed || sentenceFailed || smkFailed || conventionalityFailed;
1821
2278
  if (hasFailures) {
1822
2279
  const errors = [];
1823
2280
  if (vocabFailed) errors.push(`Vocabulary: ${vocabResult.error.message}`);
1824
2281
  if (sentenceFailed) errors.push(`Sentence structure: ${sentenceResult.error.message}`);
2282
+ if (smkFailed) errors.push(`Subject matter knowledge: ${smkResult.error.message}`);
2283
+ if (conventionalityFailed) errors.push(`Conventionality: ${conventionalityResult.error.message}`);
1825
2284
  this.logger.error("Text complexity evaluation completed with errors", {
1826
2285
  evaluator: "text-complexity",
1827
2286
  operation: "evaluate",
@@ -1829,7 +2288,7 @@ var TextComplexityEvaluator = class _TextComplexityEvaluator extends BaseEvaluat
1829
2288
  errors,
1830
2289
  processingTimeMs: latencyMs
1831
2290
  });
1832
- if (vocabFailed && sentenceFailed) {
2291
+ if (vocabFailed && sentenceFailed && smkFailed && conventionalityFailed) {
1833
2292
  throw new Error(`Text complexity evaluation failed: ${errors.join("; ")}`);
1834
2293
  }
1835
2294
  }
@@ -1850,7 +2309,7 @@ var TextComplexityEvaluator = class _TextComplexityEvaluator extends BaseEvaluat
1850
2309
  processingTimeMs: latencyMs,
1851
2310
  hasFailures
1852
2311
  });
1853
- return { vocabulary: vocabResult, sentenceStructure: sentenceResult };
2312
+ return { vocabulary: vocabResult, sentenceStructure: sentenceResult, subjectMatterKnowledge: smkResult, conventionality: conventionalityResult };
1854
2313
  }
1855
2314
  /**
1856
2315
  * Run a sub-evaluator with error handling.
@@ -1873,6 +2332,7 @@ exports.APIError = APIError;
1873
2332
  exports.AuthenticationError = AuthenticationError;
1874
2333
  exports.ComplexityClassificationSchema = ComplexityClassificationSchema;
1875
2334
  exports.ConfigurationError = ConfigurationError;
2335
+ exports.ConventionalityEvaluator = ConventionalityEvaluator;
1876
2336
  exports.EvaluatorError = EvaluatorError;
1877
2337
  exports.GradeBand = GradeBand;
1878
2338
  exports.GradeLevelAppropriatenessEvaluator = GradeLevelAppropriatenessEvaluator;
@@ -1882,6 +2342,7 @@ exports.NetworkError = NetworkError;
1882
2342
  exports.RateLimitError = RateLimitError;
1883
2343
  exports.SentenceAnalysisSchema = SentenceAnalysisSchema;
1884
2344
  exports.SentenceStructureEvaluator = SentenceStructureEvaluator;
2345
+ exports.SmkEvaluator = SmkEvaluator;
1885
2346
  exports.TextComplexityEvaluator = TextComplexityEvaluator;
1886
2347
  exports.TextComplexityLevel = TextComplexityLevel;
1887
2348
  exports.TimeoutError = TimeoutError;
@@ -1890,8 +2351,10 @@ exports.VocabularyEvaluator = VocabularyEvaluator;
1890
2351
  exports.addEngineeredFeatures = addEngineeredFeatures;
1891
2352
  exports.calculateFleschKincaidGrade = calculateFleschKincaidGrade;
1892
2353
  exports.calculateReadabilityMetrics = calculateReadabilityMetrics;
2354
+ exports.evaluateConventionality = evaluateConventionality;
1893
2355
  exports.evaluateGradeLevelAppropriateness = evaluateGradeLevelAppropriateness;
1894
2356
  exports.evaluateSentenceStructure = evaluateSentenceStructure;
2357
+ exports.evaluateSmk = evaluateSmk;
1895
2358
  exports.evaluateTextComplexity = evaluateTextComplexity;
1896
2359
  exports.evaluateVocabulary = evaluateVocabulary;
1897
2360
  exports.featuresToJSON = featuresToJSON;