@learning-commons/evaluators 0.3.0 → 0.4.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.d.cts CHANGED
@@ -1,4 +1,6 @@
1
1
  import { z } from 'zod';
2
+ import { B as BaseEvaluator, a as BaseEvaluatorConfig } from './base-Ced9oKKa.cjs';
3
+ export { E as EvaluatorMetadata, b as LogContext, c as LogLevel, L as Logger, T as TelemetryOptions } from './base-Ced9oKKa.cjs';
2
4
 
3
5
  /**
4
6
  * Shared complexity levels used across all text complexity evaluators
@@ -202,85 +204,6 @@ declare class TimeoutError extends APIError {
202
204
  constructor(message?: string);
203
205
  }
204
206
 
205
- /**
206
- * Logging interface for the Evaluators SDK
207
- *
208
- * Provides structured logging with verbosity levels.
209
- * Users can inject custom loggers or use the default console logger.
210
- */
211
- /**
212
- * Log levels in order of verbosity
213
- */
214
- declare enum LogLevel {
215
- /** Debug messages - very verbose, for development */
216
- DEBUG = 0,
217
- /** Informational messages - normal operations */
218
- INFO = 1,
219
- /** Warning messages - potentially problematic situations */
220
- WARN = 2,
221
- /** Error messages - errors that need attention */
222
- ERROR = 3,
223
- /** Silent - no logging */
224
- SILENT = 4
225
- }
226
- /**
227
- * Context object for structured logging
228
- */
229
- interface LogContext {
230
- /** Evaluator type (vocabulary, sentence-structure, etc.) */
231
- evaluator?: string;
232
- /** Current operation or stage */
233
- operation?: string;
234
- /** Error object if applicable */
235
- error?: Error;
236
- /** Additional metadata */
237
- [key: string]: unknown;
238
- }
239
- /**
240
- * Logger interface
241
- *
242
- * Implement this interface to provide custom logging behavior.
243
- *
244
- * @example
245
- * ```typescript
246
- * const customLogger: Logger = {
247
- * debug: (msg, ctx) => myLogger.debug(msg, ctx),
248
- * info: (msg, ctx) => myLogger.info(msg, ctx),
249
- * warn: (msg, ctx) => myLogger.warn(msg, ctx),
250
- * error: (msg, ctx) => myLogger.error(msg, ctx),
251
- * };
252
- *
253
- * const evaluator = new VocabularyEvaluator({
254
- * googleApiKey: '...',
255
- * openaiApiKey: '...',
256
- * logger: customLogger,
257
- * logLevel: LogLevel.INFO,
258
- * });
259
- * ```
260
- */
261
- interface Logger {
262
- /**
263
- * Log debug message
264
- * Used for detailed debugging information
265
- */
266
- debug(message: string, context?: LogContext): void;
267
- /**
268
- * Log informational message
269
- * Used for normal operations
270
- */
271
- info(message: string, context?: LogContext): void;
272
- /**
273
- * Log warning message
274
- * Used for potentially problematic situations
275
- */
276
- warn(message: string, context?: LogContext): void;
277
- /**
278
- * Log error message
279
- * Used for errors that need attention
280
- */
281
- error(message: string, context?: LogContext): void;
282
- }
283
-
284
207
  /**
285
208
  * Message format for LLM conversations
286
209
  */
@@ -604,257 +527,6 @@ declare const ConventionalityOutputSchema: z.ZodObject<{
604
527
  }>;
605
528
  type ConventionalityInternal = z.infer<typeof ConventionalityOutputSchema>;
606
529
 
607
- /**
608
- * Evaluation status
609
- */
610
- type EvaluationStatus = 'success' | 'error';
611
- /**
612
- * Token usage metrics from LLM providers
613
- */
614
- interface TokenUsage {
615
- input_tokens: number;
616
- output_tokens: number;
617
- }
618
- /**
619
- * Per-stage details for multi-stage evaluations
620
- */
621
- interface StageDetail {
622
- /** Stage name (e.g., "background_knowledge", "complexity_evaluation") */
623
- stage: string;
624
- /** Provider used for this stage (e.g., "openai:gpt-4o") */
625
- provider: string;
626
- /** Total latency including all retries (ms) */
627
- latency_ms: number;
628
- /** Token usage aggregated across all attempts */
629
- token_usage?: TokenUsage;
630
- /**
631
- * Whether schema validation failed (indicates prompt needs clearer instructions)
632
- *
633
- * TODO: Not currently tracked. Vercel AI SDK abstracts validation away.
634
- * To implement: Add custom retry wrapper that catches validation errors.
635
- */
636
- schema_validation_failed?: boolean;
637
- }
638
- /**
639
- * Extensible metadata for telemetry events
640
- */
641
- interface TelemetryMetadata {
642
- /** Detailed breakdown by stage (for multi-stage evaluations) */
643
- stage_details?: StageDetail[];
644
- }
645
- /**
646
- * Telemetry event payload
647
- */
648
- interface TelemetryEvent {
649
- timestamp: string;
650
- sdk_version: string;
651
- evaluator_type: string;
652
- grade?: string;
653
- status: EvaluationStatus;
654
- error_code?: string;
655
- latency_ms: number;
656
- text_length_chars: number;
657
- provider: string;
658
- token_usage?: TokenUsage;
659
- metadata?: TelemetryMetadata;
660
- input_text?: string;
661
- }
662
- /**
663
- * Configuration for telemetry client
664
- */
665
- interface TelemetryConfig {
666
- /** Analytics service endpoint URL */
667
- endpoint: string;
668
- /** Learning Commons partner key (optional, sent as X-API-Key header) */
669
- partnerKey?: string;
670
- /** Client ID for anonymous tracking (persistent UUID from ~/.config/learning-commons/config.json) */
671
- clientId: string;
672
- /** Enable telemetry (default: true) */
673
- enabled: boolean;
674
- /** Logger instance (respects the SDK's configured log level and custom logger) */
675
- logger: Logger;
676
- }
677
-
678
- /**
679
- * Telemetry client for sending analytics events
680
- *
681
- * Fire-and-forget implementation that never blocks SDK operations.
682
- * Errors are logged but don't fail evaluations.
683
- */
684
- declare class TelemetryClient {
685
- private config;
686
- private logger;
687
- constructor(config: TelemetryConfig);
688
- /**
689
- * Send telemetry event to analytics service
690
- *
691
- * Fire-and-forget: Errors are logged but don't throw.
692
- */
693
- send(event: TelemetryEvent): Promise<void>;
694
- }
695
-
696
- /**
697
- * Granular telemetry configuration options
698
- */
699
- interface TelemetryOptions {
700
- /** Enable telemetry (default: true) */
701
- enabled?: boolean;
702
- /** Record input text in telemetry (default: false) */
703
- recordInputs?: boolean;
704
- }
705
- /**
706
- * Base configuration for all evaluators
707
- */
708
- interface BaseEvaluatorConfig {
709
- /** Google API key (for evaluators using Gemini) */
710
- googleApiKey?: string;
711
- /** OpenAI API key (for evaluators using GPT) */
712
- openaiApiKey?: string;
713
- /** Learning Commons partner key for authenticated telemetry (optional) */
714
- partnerKey?: string;
715
- /**
716
- * Maximum number of retries for failed API calls (default: 2)
717
- * Set to 0 to disable retries.
718
- *
719
- * Note: With maxRetries=2, a failed call will be attempted up to 3 times total
720
- * (1 initial attempt + 2 retries)
721
- */
722
- maxRetries?: number;
723
- /**
724
- * Telemetry configuration (default: all enabled)
725
- *
726
- * Can be:
727
- * - `true`: Enable with defaults (recordInputs: false)
728
- * - `false`: Disable completely
729
- * - `TelemetryOptions`: Granular control
730
- */
731
- telemetry?: boolean | TelemetryOptions;
732
- /**
733
- * Custom logger implementation (optional)
734
- * If not provided, uses console logger with specified logLevel
735
- */
736
- logger?: Logger;
737
- /**
738
- * Log level for default console logger (default: WARN)
739
- * Only used if custom logger is not provided
740
- *
741
- * - DEBUG: Very verbose, shows all operations
742
- * - INFO: Normal operations
743
- * - WARN: Warnings only (default)
744
- * - ERROR: Errors only
745
- * - SILENT: No logging
746
- */
747
- logLevel?: LogLevel;
748
- }
749
- /**
750
- * Evaluator metadata interface
751
- * Each evaluator must provide this metadata as static properties
752
- */
753
- interface EvaluatorMetadata {
754
- /** Unique identifier for the evaluator (e.g., 'vocabulary', 'sentence-structure') */
755
- readonly id: string;
756
- /** Human-readable name (e.g., 'Vocabulary', 'Sentence Structure') */
757
- readonly name: string;
758
- /** Brief description of what the evaluator does */
759
- readonly description: string;
760
- /** Supported grade levels (e.g., ['3', '4', '5', ...]) */
761
- readonly supportedGrades: readonly string[];
762
- /** Whether this evaluator requires a Google API key */
763
- readonly requiresGoogleKey: boolean;
764
- /** Whether this evaluator requires an OpenAI API key */
765
- readonly requiresOpenAIKey: boolean;
766
- }
767
- /**
768
- * Abstract base class for all evaluators
769
- *
770
- * Provides common functionality:
771
- * - Telemetry setup and event sending
772
- * - Text validation
773
- * - Grade validation (with overridable default)
774
- * - Metadata creation
775
- *
776
- * Concrete evaluators must implement:
777
- * - static metadata: Provide evaluator metadata (see EvaluatorMetadata interface)
778
- */
779
- declare abstract class BaseEvaluator {
780
- protected telemetryClient?: TelemetryClient;
781
- protected logger: Logger;
782
- protected config: Required<Pick<BaseEvaluatorConfig, 'maxRetries'>> & {
783
- telemetry: Required<TelemetryOptions>;
784
- };
785
- /**
786
- * Static metadata for the evaluator
787
- *
788
- * Concrete evaluators MUST define this property.
789
- *
790
- * @example
791
- * ```typescript
792
- * class MyEvaluator extends BaseEvaluator {
793
- * static readonly metadata = {
794
- * id: 'my-evaluator',
795
- * name: 'My Evaluator',
796
- * description: 'Does something useful',
797
- * supportedGrades: ['3', '4', '5'],
798
- * requiresGoogleKey: true,
799
- * requiresOpenAIKey: false,
800
- * };
801
- * }
802
- * ```
803
- */
804
- static readonly metadata: EvaluatorMetadata;
805
- constructor(config: BaseEvaluatorConfig);
806
- /**
807
- * Get metadata for this evaluator instance
808
- * @throws {ConfigurationError} If the subclass has not defined static metadata
809
- */
810
- protected get metadata(): EvaluatorMetadata;
811
- /**
812
- * Validate that required API keys are provided based on metadata
813
- * @throws {ConfigurationError} If required API keys are missing
814
- */
815
- private validateApiKeys;
816
- /**
817
- * Normalize telemetry config to standard format
818
- */
819
- private normalizeTelemetryConfig;
820
- /**
821
- * Get the evaluator type identifier from metadata
822
- * @returns The evaluator type ID (e.g., "vocabulary", "sentence-structure")
823
- */
824
- protected getEvaluatorType(): string;
825
- /**
826
- * Validate text meets requirements
827
- * Default implementation - can be overridden by concrete evaluators
828
- *
829
- * @throws {ValidationError} If text is invalid
830
- */
831
- protected validateText(text: string): void;
832
- /**
833
- * Validate grade is in supported range
834
- * Default implementation - can be overridden by concrete evaluators
835
- *
836
- * @param grade - Grade level to validate
837
- * @param validGrades - Set of valid grades for this evaluator
838
- * @throws {ValidationError} If grade is invalid
839
- */
840
- protected validateGrade(grade: string, validGrades: Set<string>): void;
841
- /**
842
- * Send telemetry event to analytics service
843
- * Common helper for all evaluators
844
- */
845
- protected sendTelemetry(params: {
846
- status: 'success' | 'error';
847
- latencyMs: number;
848
- textLength: number;
849
- grade?: string;
850
- provider: string;
851
- errorCode?: string;
852
- tokenUsage?: TokenUsage;
853
- metadata?: TelemetryMetadata;
854
- inputText?: string;
855
- }): Promise<void>;
856
- }
857
-
858
530
  /**
859
531
  * Vocabulary Evaluator
860
532
  *
@@ -1326,4 +998,4 @@ declare function addEngineeredFeatures(analysis: SentenceAnalysis): SentenceFeat
1326
998
  */
1327
999
  declare function featuresToJSON(features: SentenceFeatures, decimals?: number, castToInt?: boolean): string;
1328
1000
 
1329
- export { APIError, AuthenticationError, type BaseEvaluatorConfig, type ComplexityClassification, ComplexityClassificationSchema, ConfigurationError, ConventionalityEvaluator, type ConventionalityInternal, type EvaluationError, type EvaluationMetadata, type EvaluationResult, EvaluatorError, type EvaluatorMetadata, GradeBand, GradeLevelAppropriatenessEvaluator, type GradeLevelAppropriatenessInternal, GradeLevelAppropriatenessSchema, type LLMProvider, type LLMRequest, type LLMResponse, type LogContext, LogLevel, type Logger, type Message, NetworkError, type ProviderConfig, RateLimitError, type ReadabilityMetrics, type SentenceAnalysis, SentenceAnalysisSchema, type SentenceFeatures, SentenceStructureEvaluator, type SentenceStructureInternal, SmkEvaluator, type SmkInternal, type TelemetryOptions, TextComplexityEvaluator, TextComplexityLevel, type TextComplexityResult, type TextGenerationResponse, TimeoutError, ValidationError, VocabularyEvaluator, type VocabularyInternal, addEngineeredFeatures, calculateFleschKincaidGrade, calculateReadabilityMetrics, evaluateConventionality, evaluateGradeLevelAppropriateness, evaluateSentenceStructure, evaluateSmk, evaluateTextComplexity, evaluateVocabulary, featuresToJSON };
1001
+ export { APIError, AuthenticationError, BaseEvaluatorConfig, type ComplexityClassification, ComplexityClassificationSchema, ConfigurationError, ConventionalityEvaluator, type ConventionalityInternal, type EvaluationError, type EvaluationMetadata, type EvaluationResult, EvaluatorError, GradeBand, GradeLevelAppropriatenessEvaluator, type GradeLevelAppropriatenessInternal, GradeLevelAppropriatenessSchema, type LLMProvider, type LLMRequest, type LLMResponse, type Message, NetworkError, type ProviderConfig, RateLimitError, type ReadabilityMetrics, type SentenceAnalysis, SentenceAnalysisSchema, type SentenceFeatures, SentenceStructureEvaluator, type SentenceStructureInternal, SmkEvaluator, type SmkInternal, TextComplexityEvaluator, TextComplexityLevel, type TextComplexityResult, type TextGenerationResponse, TimeoutError, ValidationError, VocabularyEvaluator, type VocabularyInternal, addEngineeredFeatures, calculateFleschKincaidGrade, calculateReadabilityMetrics, evaluateConventionality, evaluateGradeLevelAppropriateness, evaluateSentenceStructure, evaluateSmk, evaluateTextComplexity, evaluateVocabulary, featuresToJSON };