@devilsdev/rag-core 3.3.0 → 3.5.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.
Files changed (66) hide show
  1. package/README.md +1 -1
  2. package/dist/all.d.ts +58 -0
  3. package/dist/index.cjs +275 -15
  4. package/dist/index.d.ts +1 -1
  5. package/dist/index.mjs +1 -1
  6. package/dist/types/adapters/ai-sdk-middleware.d.ts +10 -0
  7. package/dist/types/adapters/mastra.d.ts +6 -2
  8. package/dist/types/agentic/agentic-pipeline.d.ts +1 -1
  9. package/dist/types/agentic/iterative-retriever.d.ts +1 -1
  10. package/dist/types/agentic/query-planner.d.ts +1 -1
  11. package/dist/types/agentic/self-critique.d.ts +1 -1
  12. package/dist/types/ai/federation/federated-learning-coordinator.d.ts +1 -1
  13. package/dist/types/ai/training/model-training-orchestrator.d.ts +1 -1
  14. package/dist/types/chunking/chunking-engine.d.ts +1 -1
  15. package/dist/types/citation/citation-tracker.d.ts +1 -1
  16. package/dist/types/connectors/anthropic-connector.d.ts +35 -1
  17. package/dist/types/connectors/base-connector.d.ts +1 -1
  18. package/dist/types/connectors/connector-utils.d.ts +20 -0
  19. package/dist/types/cost/cost-calculator.d.ts +1 -1
  20. package/dist/types/cost/cost-tracker.d.ts +1 -1
  21. package/dist/types/cost/token-budget.d.ts +1 -1
  22. package/dist/types/dashboard/dashboard-generator.d.ts +1 -1
  23. package/dist/types/dashboard/metrics-aggregator.d.ts +1 -1
  24. package/dist/types/debug/execution-tracer.d.ts +1 -1
  25. package/dist/types/debug/trace-inspector.d.ts +1 -1
  26. package/dist/types/dev/dev-server.d.ts +1 -1
  27. package/dist/types/dev/hot-reload.d.ts +1 -1
  28. package/dist/types/ecosystem/plugin-analytics-dashboard.d.ts +1 -1
  29. package/dist/types/ecosystem/plugin-certification.d.ts +1 -1
  30. package/dist/types/ecosystem/plugin-hub.d.ts +1 -1
  31. package/dist/types/enterprise/audit-logging.d.ts +1 -1
  32. package/dist/types/enterprise/data-governance.d.ts +1 -1
  33. package/dist/types/enterprise/multi-tenancy.d.ts +1 -1
  34. package/dist/types/enterprise/sso-integration.d.ts +1 -1
  35. package/dist/types/evaluate/pipeline-evaluator.d.ts +1 -1
  36. package/dist/types/graph/entity-extractor.d.ts +1 -1
  37. package/dist/types/graph/graph-retriever.d.ts +1 -1
  38. package/dist/types/graph/knowledge-graph.d.ts +1 -1
  39. package/dist/types/grounding/check-answer.d.ts +109 -1
  40. package/dist/types/grounding/llm-judge.d.ts +93 -0
  41. package/dist/types/grounding/provider-citations.d.ts +244 -0
  42. package/dist/types/guardrails/detectors.d.ts +88 -0
  43. package/dist/types/guardrails/evaluate-detectors.d.ts +61 -0
  44. package/dist/types/guardrails/guardrails-pipeline.d.ts +2 -9
  45. package/dist/types/guardrails/post-generation-guard.d.ts +33 -3
  46. package/dist/types/guardrails/pre-retrieval-guard.d.ts +29 -1
  47. package/dist/types/guardrails/retrieval-guard.d.ts +30 -1
  48. package/dist/types/mcp/mcp-server.d.ts +1 -1
  49. package/dist/types/observability/otel.d.ts +9 -3
  50. package/dist/types/observability/scores.d.ts +57 -0
  51. package/dist/types/reranker/cascade-reranker.d.ts +1 -1
  52. package/dist/types/reranker/embedding-reranker.d.ts +1 -1
  53. package/dist/types/reranker/scoring-reranker.d.ts +1 -1
  54. package/dist/types/retrieval/bm25-search.d.ts +1 -1
  55. package/dist/types/retrieval/hybrid-retriever.d.ts +1 -1
  56. package/dist/types/security/jwt-validator.d.ts +1 -1
  57. package/dist/types/security/plugin-sandbox.d.ts +1 -1
  58. package/dist/types/streaming/sse-adapter.d.ts +1 -1
  59. package/dist/types/streaming/stream-router.d.ts +1 -1
  60. package/dist/types/streaming/streaming-embedder.d.ts +1 -1
  61. package/dist/types/streaming/websocket-adapter.d.ts +1 -1
  62. package/dist/types/templates/scaffold.d.ts +1 -1
  63. package/dist/types/testing/contract-tests.d.ts +8 -4
  64. package/dist/types/utils/batch-processor.d.ts +1 -1
  65. package/dist/types/utils/connection-pool.d.ts +1 -1
  66. package/package.json +1 -1
@@ -38,11 +38,13 @@ export function createMastraScorer(options?: {
38
38
  * const guardrails = createMastraGuardrails({ injection: true, pii: "redact" });
39
39
  *
40
40
  * @param {Object} [options]
41
- * @param {boolean|Object} [options.injection=true] - Check the last user message; PreRetrievalGuard options
41
+ * @param {boolean|Object} [options.injection=true] - Check the last user message; PreRetrievalGuard options, including `detectors`
42
42
  * @param {'redact'|'block'|false} [options.pii='redact'] - Redact PII in the answer, or abort the run
43
43
  * @param {Object<string, RegExp>} [options.piiPatterns] - Extra PII patterns by name
44
+ * @param {Array<Object>} [options.piiDetectors] - PII detectors to run on the answer too; their matches are redacted
45
+ * @param {boolean} [options.piiBuiltIn=true] - false: use only piiDetectors, not the built-in PII patterns
44
46
  * @param {string} [options.id='rag-pipeline-guardrails']
45
- * @returns {Object} A Mastra processor
47
+ * @returns {Object} A Mastra processor. With detectors, its methods return promises (Mastra awaits them)
46
48
  */
47
49
  export function createMastraGuardrails(options?: {
48
50
  injection?: boolean | any;
@@ -50,6 +52,8 @@ export function createMastraGuardrails(options?: {
50
52
  piiPatterns?: {
51
53
  [x: string]: RegExp;
52
54
  };
55
+ piiDetectors?: Array<any>;
56
+ piiBuiltIn?: boolean;
53
57
  id?: string;
54
58
  }): any;
55
59
  export declare let MASTRA_METRICS: string[];
@@ -5,7 +5,7 @@
5
5
  *
6
6
  * @extends EventEmitter
7
7
  */
8
- export class AgenticPipeline extends EventEmitter<[never]> {
8
+ export class AgenticPipeline extends EventEmitter {
9
9
  /**
10
10
  * @param {object} [options] - Override default configuration
11
11
  * @param {number} [options.maxConcurrency=3] - Max concurrent DAG node execution
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * @extends EventEmitter
6
6
  */
7
- export class IterativeRetriever extends EventEmitter<[never]> {
7
+ export class IterativeRetriever extends EventEmitter {
8
8
  /**
9
9
  * @param {object} [options] - Override default configuration
10
10
  * @param {number} [options.maxIterations=3] - Maximum retrieval iterations
@@ -13,7 +13,7 @@
13
13
  *
14
14
  * @extends EventEmitter
15
15
  */
16
- export class QueryPlanner extends EventEmitter<[never]> {
16
+ export class QueryPlanner extends EventEmitter {
17
17
  /**
18
18
  * @param {object} [options] - Override default configuration
19
19
  * @param {number} [options.minComplexityToSplit=2] - Minimum complexity
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * @extends EventEmitter
6
6
  */
7
- export class SelfCritiqueChecker extends EventEmitter<[never]> {
7
+ export class SelfCritiqueChecker extends EventEmitter {
8
8
  /**
9
9
  * @param {object} [options] - Override default configuration
10
10
  * @param {number} [options.approvalThreshold=0.5] - Minimum groundedness score to approve an answer
@@ -1,4 +1,4 @@
1
- export class FederatedLearningCoordinator extends EventEmitter<[never]> {
1
+ export class FederatedLearningCoordinator extends EventEmitter {
2
2
  constructor(options?: {});
3
3
  config: {
4
4
  minParticipants: any;
@@ -1,4 +1,4 @@
1
- export class ModelTrainingOrchestrator extends EventEmitter<[never]> {
1
+ export class ModelTrainingOrchestrator extends EventEmitter {
2
2
  constructor(options?: {});
3
3
  config: {
4
4
  batchSize: any;
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * @extends EventEmitter
6
6
  */
7
- export class ChunkingEngine extends EventEmitter<[never]> {
7
+ export class ChunkingEngine extends EventEmitter {
8
8
  /**
9
9
  * Create a ChunkingEngine instance.
10
10
  *
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * @extends EventEmitter
6
6
  */
7
- export class CitationTracker extends EventEmitter<[never]> {
7
+ export class CitationTracker extends EventEmitter {
8
8
  /**
9
9
  * @param {object} [options] - Override default configuration
10
10
  * @param {number} [options.similarityThreshold=0.5] - Minimum similarity for a citation match
@@ -66,11 +66,37 @@ export class AnthropicConnector extends BaseConnector {
66
66
  * @param {Array<Object|string>} [context=[]] - Retrieved documents for RAG
67
67
  * @param {Object} [options={}] - Override model, temperature, maxTokens per-call
68
68
  * @param {AbortSignal} [options.signal] - Cancels the request
69
- * @returns {Promise<string>} The generated text
69
+ * @returns {Promise<string>} The answer: every text block of the reply,
70
+ * joined. Rejects (code MODEL_REFUSED or NO_TEXT) when the reply has no
71
+ * text, such as a refusal or a reply that ran out of maxTokens while
72
+ * thinking.
70
73
  */
71
74
  generate(query: string, context?: Array<any | string>, options?: {
72
75
  signal?: AbortSignal;
73
76
  }): Promise<string>;
77
+ /**
78
+ * Like generate(), with the reply's token usage. The LLM judge uses it so
79
+ * `check.judge.usage` reports what the judge cost.
80
+ *
81
+ * @param {string} query
82
+ * @param {Array<Object|string>} [context=[]]
83
+ * @param {Object} [options={}] - As for generate()
84
+ * @returns {Promise<{text: string, usage: {inputTokens: number, outputTokens: number, totalTokens: number}}>}
85
+ */
86
+ generateWithUsage(query: string, context?: Array<any | string>, options?: any): Promise<{
87
+ text: string;
88
+ usage: {
89
+ inputTokens: number;
90
+ outputTokens: number;
91
+ totalTokens: number;
92
+ };
93
+ }>;
94
+ /**
95
+ * POST a Messages request with retries; a model that rejects
96
+ * `temperature` gets the request again without it.
97
+ * @private
98
+ */
99
+ private _post;
74
100
  /**
75
101
  * Stream a response from Claude token-by-token via SSE.
76
102
  *
@@ -108,6 +134,14 @@ export namespace DEFAULT_CONFIG {
108
134
  export let retryDelay: number;
109
135
  export const apiKey: string;
110
136
  }
137
+ /**
138
+ * The answer text of a Messages API response: every `text` block, joined.
139
+ * Models that think reply with `thinking` blocks before the text, so the
140
+ * first block is not always the answer.
141
+ * @param {Object} data - The response body
142
+ * @returns {string}
143
+ */
144
+ export function responseText(data: any): string;
111
145
  import { BaseConnector } from "./base-connector";
112
146
  /**
113
147
  * Default configuration for the Anthropic connector.
@@ -3,7 +3,7 @@
3
3
  * Provides connection lifecycle, health checking, and retry logic.
4
4
  * @extends EventEmitter
5
5
  */
6
- export class BaseConnector extends EventEmitter<[never]> {
6
+ export class BaseConnector extends EventEmitter {
7
7
  /**
8
8
  * @param {Object} options
9
9
  * @param {string} [options.name] - Connector display name
@@ -1,3 +1,23 @@
1
+ /**
2
+ * An axios error without what it carries from the request. axios errors
3
+ * keep the request config, headers included, so logging or serializing one
4
+ * prints the API key. This copies what callers and the retry logic use
5
+ * (the response status, headers and body, and the network error code)
6
+ * into a plain Error, and puts the API's own explanation in the message:
7
+ * "Anthropic API error 401: authentication_error: invalid x-api-key".
8
+ *
9
+ * @param {*} err
10
+ * @param {string} provider - Name for the message, e.g. "Anthropic"
11
+ * @returns {*} A clean Error for an axios error; anything else unchanged
12
+ */
13
+ export function toConnectorError(err: any, provider: string): any;
14
+ /**
15
+ * Make every error from an axios client a toConnectorError() one.
16
+ * @param {Object} client - From axios.create()
17
+ * @param {string} provider
18
+ * @returns {Object} The client
19
+ */
20
+ export function cleanAxiosErrors(client: any, provider: string): any;
1
21
  /**
2
22
  * The text of a streamed response body, chunk by chunk. Handles what axios
3
23
  * returns for `responseType: 'stream'` on each runtime: a Node stream of
@@ -6,7 +6,7 @@
6
6
  * const cost = calc.estimate('gpt-4o', 1500, 500);
7
7
  * console.log(cost.totalCost); // 0.015
8
8
  */
9
- export class CostCalculator extends EventEmitter<[never]> {
9
+ export class CostCalculator extends EventEmitter {
10
10
  /**
11
11
  * Provenance of the built-in pricing table.
12
12
  * @returns {typeof PRICING_METADATA}
@@ -8,7 +8,7 @@
8
8
  * console.log(result.cost); // { inputTokens, outputTokens, estimatedCost, model }
9
9
  * console.log(tracker.getSummary());
10
10
  */
11
- export class CostTracker extends EventEmitter<[never]> {
11
+ export class CostTracker extends EventEmitter {
12
12
  /**
13
13
  * @param {object} [options]
14
14
  * @param {string} [options.model='gpt-3.5-turbo'] - Default LLM model for cost estimation.
@@ -12,7 +12,7 @@
12
12
  * const status = budget.check(2000, 0.10);
13
13
  * if (status.allowed) budget.record(2000, 0.10);
14
14
  */
15
- export class TokenBudget extends EventEmitter<[never]> {
15
+ export class TokenBudget extends EventEmitter {
16
16
  /**
17
17
  * @param {object} [options]
18
18
  * @param {number} [options.maxTokens=Infinity] - Hard token limit.
@@ -16,7 +16,7 @@ export type DashboardGeneratorConfig = {
16
16
  * Generates standalone HTML dashboards from pipeline metrics snapshots.
17
17
  * @extends EventEmitter
18
18
  */
19
- export class DashboardGenerator extends EventEmitter<[never]> {
19
+ export class DashboardGenerator extends EventEmitter {
20
20
  /**
21
21
  * @param {Partial<DashboardGeneratorConfig>} options
22
22
  */
@@ -71,7 +71,7 @@ export type ErrorData = {
71
71
  * Collects and aggregates pipeline metrics into dashboard-ready snapshots.
72
72
  * @extends EventEmitter
73
73
  */
74
- export class MetricsAggregator extends EventEmitter<[never]> {
74
+ export class MetricsAggregator extends EventEmitter {
75
75
  /**
76
76
  * @param {Partial<MetricsAggregatorConfig>} options
77
77
  */
@@ -2,7 +2,7 @@
2
2
  * Execution tracer that wraps pipelines to capture run traces
3
3
  * @extends EventEmitter
4
4
  */
5
- export class ExecutionTracer extends EventEmitter<[never]> {
5
+ export class ExecutionTracer extends EventEmitter {
6
6
  /**
7
7
  * Create a new ExecutionTracer
8
8
  * @param {object} [options] - Tracer configuration
@@ -2,7 +2,7 @@
2
2
  * Trace inspector that analyzes execution traces produced by ExecutionTracer
3
3
  * @extends EventEmitter
4
4
  */
5
- export class TraceInspector extends EventEmitter<[never]> {
5
+ export class TraceInspector extends EventEmitter {
6
6
  /**
7
7
  * Create a new TraceInspector
8
8
  * @param {object} [options] - Inspector configuration
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * Integrates hot reloading with a development workflow
5
5
  */
6
- export class DevServer extends EventEmitter<[never]> {
6
+ export class DevServer extends EventEmitter {
7
7
  constructor(options?: {});
8
8
  options: {
9
9
  port: any;
@@ -11,7 +11,7 @@ export function toIgnoreMatcher(patterns: Array<string | RegExp | Function>): (f
11
11
  *
12
12
  * Manages file watching and hot reloading of plugins and configuration.
13
13
  */
14
- export class HotReloadManager extends EventEmitter<[never]> {
14
+ export class HotReloadManager extends EventEmitter {
15
15
  constructor(options?: {});
16
16
  options: {
17
17
  enabled: boolean;
@@ -1,4 +1,4 @@
1
- export class PluginAnalyticsDashboard extends EventEmitter<[never]> {
1
+ export class PluginAnalyticsDashboard extends EventEmitter {
2
2
  constructor(_options?: {});
3
3
  _config: {
4
4
  port: any;
@@ -1,4 +1,4 @@
1
- export class PluginCertification extends EventEmitter<[never]> {
1
+ export class PluginCertification extends EventEmitter {
2
2
  constructor(_options?: {});
3
3
  _config: {
4
4
  registryUrl: any;
@@ -2,7 +2,7 @@
2
2
  * Client for a plugin hub registry: search, inspect, install, publish and
3
3
  * rate plugins.
4
4
  */
5
- export class PluginHub extends EventEmitter<[never]> {
5
+ export class PluginHub extends EventEmitter {
6
6
  constructor(_options?: {});
7
7
  _config: {
8
8
  registryUrl: any;
@@ -3,7 +3,7 @@
3
3
  * in hash-chained logs, with querying, compliance reports and an integrity
4
4
  * check.
5
5
  */
6
- export class AuditLogger extends EventEmitter<[never]> {
6
+ export class AuditLogger extends EventEmitter {
7
7
  constructor(_options?: {});
8
8
  _config: {
9
9
  logDir: any;
@@ -1,4 +1,4 @@
1
- export class DataGovernanceManager extends EventEmitter<[never]> {
1
+ export class DataGovernanceManager extends EventEmitter {
2
2
  constructor(_options?: {});
3
3
  _config: {
4
4
  policies: {
@@ -1,4 +1,4 @@
1
- export class TenantManager extends EventEmitter<[never]> {
1
+ export class TenantManager extends EventEmitter {
2
2
  constructor(_options?: {});
3
3
  _config: {
4
4
  dataDir: any;
@@ -1,4 +1,4 @@
1
- export class SSOManager extends EventEmitter<[never]> {
1
+ export class SSOManager extends EventEmitter {
2
2
  constructor(_options?: {});
3
3
  _config: any;
4
4
  sessions: Map<any, any>;
@@ -9,7 +9,7 @@
9
9
  * evaluator.on('evaluated', (result) => console.log(result.scores));
10
10
  * const result = evaluator.evaluate({ query: 'What is RAG?', answer: '...', results: [...] });
11
11
  */
12
- export class PipelineEvaluator extends EventEmitter<[never]> {
12
+ export class PipelineEvaluator extends EventEmitter {
13
13
  /**
14
14
  * Create a new PipelineEvaluator.
15
15
  * @param {object} [options={}] - Configuration options
@@ -4,7 +4,7 @@
4
4
  * Uses configurable regex patterns to identify named entities,
5
5
  * dates, measurements, URLs, emails, and technical terms.
6
6
  */
7
- export class EntityExtractor extends EventEmitter<[never]> {
7
+ export class EntityExtractor extends EventEmitter {
8
8
  /**
9
9
  * @param {Object} [options={}] - Extractor options
10
10
  * @param {Object<string, RegExp>} [options.patterns] - Custom patterns to merge with defaults
@@ -4,7 +4,7 @@
4
4
  * Combines entity-based graph traversal with token-overlap text scoring
5
5
  * to rank and retrieve relevant documents from a corpus.
6
6
  */
7
- export class GraphRetriever extends EventEmitter<[never]> {
7
+ export class GraphRetriever extends EventEmitter {
8
8
  /**
9
9
  * @param {Object} [options={}] - Retriever options
10
10
  * @param {number} [options.traversalDepth=2] - Graph traversal depth
@@ -4,7 +4,7 @@
4
4
  * Stores typed entities and directed relationships between them,
5
5
  * supporting traversal, pattern-based querying, and adjacency lookups.
6
6
  */
7
- export class KnowledgeGraph extends EventEmitter<[never]> {
7
+ export class KnowledgeGraph extends EventEmitter {
8
8
  /**
9
9
  * @param {Object} [options={}] - Graph configuration options
10
10
  */
@@ -37,6 +37,74 @@ export type AnswerCheck = {
37
37
  content: string;
38
38
  metadata: any;
39
39
  }>;
40
+ /**
41
+ * - Only when the `judge` option is given
42
+ */
43
+ judge?: JudgeReport;
44
+ };
45
+ /**
46
+ * Any LLM for the `judge` option: this library's LLM plugin contract.
47
+ * `generate` may return the text, or an object with `text` or `content`
48
+ * (and optionally `usage`).
49
+ */
50
+ export type JudgeLLM = {
51
+ generate: (prompt: string, context: Array<any>, options?: any) => (string | {
52
+ text?: string;
53
+ content?: string;
54
+ usage?: any;
55
+ } | Promise<string | {
56
+ text?: string;
57
+ content?: string;
58
+ usage?: any;
59
+ }>);
60
+ };
61
+ /**
62
+ * The verdict on one sentence when a judge is used.
63
+ */
64
+ export type JudgeVerdict = {
65
+ sentence: string;
66
+ /**
67
+ * - The combined verdict
68
+ */
69
+ verdict: "supported" | "unsupported";
70
+ /**
71
+ * - Id of the supporting source, when supported
72
+ */
73
+ sourceId: string | null;
74
+ /**
75
+ * - Why, in words (the judge's reason when it decided)
76
+ */
77
+ reason: string;
78
+ /**
79
+ * - What the lexical check found. Only `low_overlap` sentences go to the judge
80
+ */
81
+ lexicalReason: "supported" | "low_overlap" | "number_mismatch" | "polarity_mismatch" | "no_sources";
82
+ decidedBy: "lexical" | "judge";
83
+ };
84
+ /**
85
+ * What the judge did.
86
+ */
87
+ export type JudgeReport = {
88
+ /**
89
+ * - One per sentence, in order
90
+ */
91
+ verdicts: JudgeVerdict[];
92
+ /**
93
+ * - Calls made to `judge.generate` (0 or 1)
94
+ */
95
+ calls: number;
96
+ /**
97
+ * - Token usage summed over the calls, when the LLM result carries `usage`
98
+ */
99
+ usage?: {
100
+ inputTokens: number;
101
+ outputTokens: number;
102
+ totalTokens: number;
103
+ };
104
+ /**
105
+ * - Why the judge's reply could not be parsed
106
+ */
107
+ error?: string;
40
108
  };
41
109
  /**
42
110
  * @typedef {Object} AnswerCheck
@@ -51,6 +119,37 @@ export type AnswerCheck = {
51
119
  * referenceAnswer is given); only when `evaluate` is not false
52
120
  * @property {Array<{id: string, content: string, metadata: Object}>} sources
53
121
  * - The sources as they were checked
122
+ * @property {JudgeReport} [judge] - Only when the `judge` option is given
123
+ */
124
+ /**
125
+ * Any LLM for the `judge` option: this library's LLM plugin contract.
126
+ * `generate` may return the text, or an object with `text` or `content`
127
+ * (and optionally `usage`).
128
+ *
129
+ * @typedef {Object} JudgeLLM
130
+ * @property {(prompt: string, context: Array<any>, options?: Object) => (string|{text?: string, content?: string, usage?: Object}|Promise<string|{text?: string, content?: string, usage?: Object}>)} generate
131
+ */
132
+ /**
133
+ * The verdict on one sentence when a judge is used.
134
+ *
135
+ * @typedef {Object} JudgeVerdict
136
+ * @property {string} sentence
137
+ * @property {'supported'|'unsupported'} verdict - The combined verdict
138
+ * @property {string|null} sourceId - Id of the supporting source, when supported
139
+ * @property {string} reason - Why, in words (the judge's reason when it decided)
140
+ * @property {'supported'|'low_overlap'|'number_mismatch'|'polarity_mismatch'|'no_sources'} lexicalReason
141
+ * - What the lexical check found. Only `low_overlap` sentences go to the judge
142
+ * @property {'lexical'|'judge'} decidedBy
143
+ */
144
+ /**
145
+ * What the judge did.
146
+ *
147
+ * @typedef {Object} JudgeReport
148
+ * @property {JudgeVerdict[]} verdicts - One per sentence, in order
149
+ * @property {number} calls - Calls made to `judge.generate` (0 or 1)
150
+ * @property {{inputTokens: number, outputTokens: number, totalTokens: number}} [usage]
151
+ * - Token usage summed over the calls, when the LLM result carries `usage`
152
+ * @property {string} [error] - Why the judge's reply could not be parsed
54
153
  */
55
154
  /**
56
155
  * Check an answer against the sources it was generated from.
@@ -74,15 +173,24 @@ export type AnswerCheck = {
74
173
  * @param {Object} [params.embedder] - With a referenceAnswer, adds
75
174
  * `evaluation.scores.semanticSimilarity` (computeSemanticSimilarity)
76
175
  * @param {boolean} [params.evaluate=true] - Also compute evaluation scores
176
+ * @param {JudgeLLM} [params.judge] - Opt-in LLM judge for sentences the
177
+ * lexical check failed for lack of word overlap (correct paraphrases).
178
+ * It never overturns a sentence that failed the number or negation check,
179
+ * and a "supported" verdict must name a source whose numbers and negation
180
+ * match the sentence. Unparseable output keeps a sentence unsupported.
181
+ * With a judge, `grounded`, `groundedness` and `unsupported` combine both
182
+ * checks and `judge` reports the verdicts; `citations` and `evaluation`
183
+ * stay lexical. Errors thrown by `judge.generate` are not caught.
77
184
  * @returns {Promise<AnswerCheck>}
78
185
  */
79
- export function checkAnswer({ answer, sources, question, referenceAnswer, embedder, evaluate, }?: {
186
+ export function checkAnswer({ answer, sources, question, referenceAnswer, embedder, evaluate, judge, }?: {
80
187
  answer: string;
81
188
  sources: Array<string | any>;
82
189
  question?: string;
83
190
  referenceAnswer?: string;
84
191
  embedder?: any;
85
192
  evaluate?: boolean;
193
+ judge?: JudgeLLM;
86
194
  }): Promise<AnswerCheck>;
87
195
  /**
88
196
  * Normalize sources to `{ id, content, metadata }`.
@@ -0,0 +1,93 @@
1
+ export namespace REASONS {
2
+ let supported: string;
3
+ let lowOverlap: string;
4
+ let numberMismatch: string;
5
+ let polarityMismatch: string;
6
+ let noSources: string;
7
+ }
8
+ /** Instructions at the top of every judge prompt. */
9
+ export const JUDGE_INSTRUCTIONS: string;
10
+ /**
11
+ * Build the judge prompt for the given claims.
12
+ *
13
+ * @param {string[]} claims - Sentences to rule on
14
+ * @param {Array<{id: string, content: string}>} docs
15
+ * @returns {string}
16
+ */
17
+ export function buildJudgePrompt(claims: string[], docs: Array<{
18
+ id: string;
19
+ content: string;
20
+ }>): string;
21
+ /**
22
+ * Parse the judge's reply into one verdict per claim. Tolerates a code fence
23
+ * around the JSON; anything else that is not the expected array leaves every
24
+ * claim without a verdict.
25
+ *
26
+ * @param {*} raw - What llm.generate() returned
27
+ * @param {number} claimCount
28
+ * @returns {{ verdicts: Array<{verdict: string, source: string|null, reason: string}|null>, error: string|null }}
29
+ * verdicts[i] is null when claim i+1 got no well-formed verdict
30
+ */
31
+ export function parseJudgeVerdicts(raw: any, claimCount: number): {
32
+ verdicts: Array<{
33
+ verdict: string;
34
+ source: string | null;
35
+ reason: string;
36
+ } | null>;
37
+ error: string | null;
38
+ };
39
+ /**
40
+ * The lexical reason for every sentence, in order.
41
+ *
42
+ * @param {Array<{text: string, classification: string}>} sentences - From
43
+ * CitationTracker's hallucination report
44
+ * @param {Array<{id?: string, content: string}>} docs
45
+ * @param {Array<string[]>} [allowed] - Per sentence, the ids of the only
46
+ * docs that may support it (verifyCitations: the passages it cites)
47
+ * @returns {string[]}
48
+ */
49
+ export function lexicalReasons(sentences: Array<{
50
+ text: string;
51
+ classification: string;
52
+ }>, docs: Array<{
53
+ id?: string;
54
+ content: string;
55
+ }>, allowed?: Array<string[]>): string[];
56
+ /**
57
+ * Run the judge on the sentences that failed for lack of overlap and
58
+ * combine its verdicts with the lexical result.
59
+ *
60
+ * Overturn rule: a judge "supported" counts only when the sentence failed
61
+ * for lack of overlap, the verdict is well formed, it names a source that
62
+ * exists, and that source passes the numeric and polarity checks against
63
+ * the sentence. Everything else keeps the lexical verdict.
64
+ *
65
+ * @param {Object} params
66
+ * @param {{generate: Function}} params.judge
67
+ * @param {Array<{text: string, classification: string, bestSource: Object|null}>} params.sentences
68
+ * @param {Array<{id: string, content: string}>} params.docs
69
+ * @param {Array<string[]>} [params.allowed] - Per sentence, the ids of the
70
+ * only docs that may support it; a verdict naming another doc is kept
71
+ * unsupported. Default: any doc.
72
+ * @returns {Promise<{verdicts: Array<Object>, calls: number, usage?: Object, error?: string}>}
73
+ */
74
+ export function runJudge({ judge, sentences, docs, allowed }: {
75
+ judge: {
76
+ generate: Function;
77
+ };
78
+ sentences: Array<{
79
+ text: string;
80
+ classification: string;
81
+ bestSource: any | null;
82
+ }>;
83
+ docs: Array<{
84
+ id: string;
85
+ content: string;
86
+ }>;
87
+ allowed?: Array<string[]>;
88
+ }): Promise<{
89
+ verdicts: Array<any>;
90
+ calls: number;
91
+ usage?: any;
92
+ error?: string;
93
+ }>;