@devilsdev/rag-pipeline-utils 2.4.5 → 2.6.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/.ragrc.schema.json +83 -192
- package/CHANGELOG.md +431 -0
- package/README.md +418 -117
- package/SECURITY.md +5 -5
- package/dist/experimental.cjs +2 -0
- package/dist/experimental.d.ts +1 -0
- package/dist/experimental.mjs +5 -0
- package/dist/index.cjs +6442 -1355
- package/dist/index.d.ts +129 -2
- package/dist/index.mjs +1 -1
- package/dist/testing.cjs +2 -0
- package/dist/testing.d.ts +1 -0
- package/dist/testing.mjs +5 -0
- package/dist/types/adapters/ai-sdk.d.ts +53 -0
- package/dist/types/agentic/agentic-pipeline.d.ts +103 -0
- package/dist/types/agentic/iterative-retriever.d.ts +85 -0
- package/dist/types/agentic/query-planner.d.ts +145 -0
- package/dist/types/agentic/self-critique.d.ts +45 -0
- package/dist/types/ai/adaptive-retrieval.d.ts +44 -0
- package/dist/types/ai/federation/federated-learning-coordinator.d.ts +62 -0
- package/dist/types/ai/multimodal-processing.d.ts +32 -0
- package/dist/types/ai/multimodal.d.ts +39 -0
- package/dist/types/ai/retrieval-engine.d.ts +37 -0
- package/dist/types/ai/training/model-training-orchestrator.d.ts +31 -0
- package/dist/types/cache/component-keys.d.ts +7 -0
- package/dist/types/cache/memory-cache.d.ts +54 -0
- package/dist/types/cache/pipeline-cache.d.ts +66 -0
- package/dist/types/cache/redis-cache.d.ts +46 -0
- package/dist/types/chunking/chunking-engine.d.ts +70 -0
- package/dist/types/chunking/strategies/fixed-size.d.ts +17 -0
- package/dist/types/chunking/strategies/recursive.d.ts +20 -0
- package/dist/types/chunking/strategies/semantic.d.ts +19 -0
- package/dist/types/chunking/strategies/sentence.d.ts +13 -0
- package/dist/types/chunking/strategies/structure-aware.d.ts +19 -0
- package/dist/types/citation/citation-tracker.d.ts +64 -0
- package/dist/types/citation/hallucination-detector.d.ts +40 -0
- package/dist/types/citation/source-mapper.d.ts +37 -0
- package/dist/types/connectors/anthropic-connector.d.ts +97 -0
- package/dist/types/connectors/base-connector.d.ts +87 -0
- package/dist/types/connectors/cohere-connector.d.ts +94 -0
- package/dist/types/connectors/connector-utils.d.ts +110 -0
- package/dist/types/connectors/local-embedder.d.ts +95 -0
- package/dist/types/connectors/memory-retriever.d.ts +99 -0
- package/dist/types/connectors/ollama-connector.d.ts +115 -0
- package/dist/types/connectors/openai-connector.d.ts +129 -0
- package/dist/types/connectors/rag-prompt.d.ts +40 -0
- package/dist/types/core/create-pipeline.d.ts +8 -0
- package/dist/types/core/plugin-registry.d.ts +136 -0
- package/dist/types/core/stage-contracts.d.ts +36 -0
- package/dist/types/core/validate-plugin.d.ts +45 -0
- package/dist/types/cost/cost-calculator.d.ts +152 -0
- package/dist/types/cost/cost-tracker.d.ts +126 -0
- package/dist/types/cost/token-budget.d.ts +110 -0
- package/dist/types/dag/core/error-context.d.ts +239 -0
- package/dist/types/dag/core/execution-scheduler.d.ts +191 -0
- package/dist/types/dag/core/topology-validation.d.ts +226 -0
- package/dist/types/dag/dag-engine.d.ts +156 -0
- package/dist/types/dag/dag-node.d.ts +37 -0
- package/dist/types/dashboard/dashboard-generator.d.ts +127 -0
- package/dist/types/dashboard/metrics-aggregator.d.ts +218 -0
- package/dist/types/debug/execution-tracer.d.ts +57 -0
- package/dist/types/debug/trace-inspector.d.ts +31 -0
- package/dist/types/ecosystem/plugin-certification.d.ts +169 -0
- package/dist/types/enterprise/data-governance.d.ts +203 -0
- package/dist/types/enterprise/multi-tenancy.d.ts +137 -0
- package/dist/types/enterprise/sso-integration.d.ts +420 -0
- package/dist/types/evaluate/context-metrics.d.ts +55 -0
- package/dist/types/evaluate/faithfulness.d.ts +41 -0
- package/dist/types/evaluate/groundedness.d.ts +60 -0
- package/dist/types/evaluate/pipeline-evaluator.d.ts +88 -0
- package/dist/types/evaluate/relevance.d.ts +21 -0
- package/dist/types/evaluate/scoring.d.ts +123 -0
- package/dist/types/evaluate/semantic-similarity.d.ts +14 -0
- package/dist/types/experimental.d.ts +15 -0
- package/dist/types/graph/entity-extractor.d.ts +84 -0
- package/dist/types/graph/graph-index.d.ts +49 -0
- package/dist/types/graph/graph-retriever.d.ts +81 -0
- package/dist/types/graph/knowledge-graph.d.ts +129 -0
- package/dist/types/grounding/check-answer.d.ts +101 -0
- package/dist/types/guardrails/guardrails-pipeline.d.ts +63 -0
- package/dist/types/guardrails/injection-detector.d.ts +47 -0
- package/dist/types/guardrails/post-generation-guard.d.ts +61 -0
- package/dist/types/guardrails/pre-retrieval-guard.d.ts +64 -0
- package/dist/types/guardrails/retrieval-guard.d.ts +57 -0
- package/dist/types/mcp/mcp-server.d.ts +85 -0
- package/dist/types/mcp/mcp-tool-builder.d.ts +55 -0
- package/dist/types/reranker/cascade-reranker.d.ts +40 -0
- package/dist/types/reranker/embedding-reranker.d.ts +77 -0
- package/dist/types/reranker/scoring-reranker.d.ts +41 -0
- package/dist/types/retrieval/bm25-search.d.ts +43 -0
- package/dist/types/retrieval/file-vector-store.d.ts +99 -0
- package/dist/types/retrieval/hybrid-retriever.d.ts +35 -0
- package/dist/types/retrieval/rank-fusion.d.ts +10 -0
- package/dist/types/security/jwt-config.d.ts +80 -0
- package/dist/types/security/jwt-validator.d.ts +195 -0
- package/dist/types/security/plugin-sandbox.d.ts +158 -0
- package/dist/types/security/plugin-signature-verifier.d.ts +139 -0
- package/dist/types/security/validator.d.ts +5 -0
- package/dist/types/streaming/embedding-stream.d.ts +65 -0
- package/dist/types/streaming/sse-adapter.d.ts +59 -0
- package/dist/types/streaming/stream-router.d.ts +88 -0
- package/dist/types/streaming/streaming-embedder.d.ts +99 -0
- package/dist/types/streaming/websocket-adapter.d.ts +71 -0
- package/dist/types/templates/scaffold.d.ts +55 -0
- package/dist/types/templates/template-registry.d.ts +63 -0
- package/dist/types/testing.d.ts +168 -0
- package/dist/types/utils/embed-query.d.ts +20 -0
- package/dist/types/utils/logger.d.ts +50 -0
- package/dist/types/utils/rate-limiter.d.ts +66 -0
- package/dist/types/utils/retry.d.ts +27 -0
- package/dist/types/utils/run-abort.d.ts +34 -0
- package/dist/types/utils/secure-logging.d.ts +51 -0
- package/dist/types/utils/structured-logger.d.ts +126 -0
- package/package.json +72 -33
- package/src/adapters/ai-sdk.js +215 -0
- package/src/agentic/agentic-pipeline.js +75 -7
- package/src/agentic/iterative-retriever.js +47 -10
- package/src/agentic/query-planner.js +329 -78
- package/src/cache/component-keys.js +38 -0
- package/src/cache/memory-cache.js +87 -0
- package/src/cache/pipeline-cache.js +260 -0
- package/src/cache/redis-cache.js +83 -0
- package/src/citation/citation-tracker.js +6 -4
- package/src/citation/hallucination-detector.js +2 -2
- package/src/citation/source-mapper.js +15 -28
- package/src/cli/commands/ai.js +106 -0
- package/src/cli/commands/plugin-hub/event-handlers.js +6 -0
- package/src/cli/commands/plugin-hub/hub-commands.js +0 -74
- package/src/cli/commands/plugin-hub/local-commands.js +143 -0
- package/src/cli/commands/plugin-hub.js +114 -49
- package/src/cli/diagnostics/config-checker.js +76 -63
- package/src/cli/diagnostics/environment-checker.js +62 -31
- package/src/cli/diagnostics/plugin-checker.js +36 -89
- package/src/cli/doctor-command.js +39 -5
- package/src/cli/enhanced-cli-commands.js +104 -233
- package/src/cli/handlers/ai-handler.js +364 -0
- package/src/cli/handlers/diagnostics-handler.js +78 -31
- package/src/cli/handlers/ingest-handler.js +28 -22
- package/src/cli/handlers/init-handler.js +148 -25
- package/src/cli/handlers/query-handler.js +203 -25
- package/src/cli/handlers/run-handler.js +16 -167
- package/src/cli/handlers/serve-handler.js +60 -0
- package/src/cli/services/bench-stats.js +54 -0
- package/src/cli/services/benchmark.js +161 -0
- package/src/cli/services/feedback.js +155 -0
- package/src/cli/services/instrument.js +83 -0
- package/src/cli/services/rag-service.js +361 -0
- package/src/cli/shared/cli-utils.js +24 -7
- package/src/cli/shared/config-context.js +21 -0
- package/src/cli/wizard/config-builder.js +81 -0
- package/src/cli/wizard/init-wizard.js +602 -0
- package/src/config/component-factory.js +125 -0
- package/src/config/enhanced-ragrc-schema.js +0 -2
- package/src/config/load-config.js +29 -10
- package/src/config/load-plugin-config.js +46 -2
- package/src/config/validate-schema.js +4 -1
- package/src/connectors/anthropic-connector.js +115 -57
- package/src/connectors/base-connector.js +74 -19
- package/src/connectors/cohere-connector.js +108 -34
- package/src/connectors/connector-utils.js +302 -0
- package/src/connectors/local-embedder.js +63 -5
- package/src/connectors/memory-retriever.js +125 -14
- package/src/connectors/ollama-connector.js +112 -51
- package/src/connectors/openai-connector.js +153 -44
- package/src/connectors/rag-prompt.js +88 -0
- package/src/core/create-pipeline.js +307 -61
- package/src/core/performance/parallel-processor.js +62 -1
- package/src/core/plugin-registry.js +125 -26
- package/src/core/stage-contracts.js +36 -0
- package/src/core/validate-plugin.js +85 -0
- package/src/cost/cost-calculator.js +205 -32
- package/src/debug/execution-tracer.js +14 -4
- package/src/dev/dev-server.js +173 -11
- package/src/dev/hot-reload.js +44 -4
- package/src/ecosystem/plugin-checks.js +181 -0
- package/src/ecosystem/plugin-hub.js +50 -125
- package/src/ecosystem/plugin-installer.js +298 -0
- package/src/ecosystem/plugin-probe.js +127 -0
- package/src/ecosystem/plugin-scanner.js +185 -0
- package/src/ecosystem/tar-extract.js +114 -0
- package/src/enterprise/audit-logging.js +158 -29
- package/src/enterprise/sso-integration.js +716 -228
- package/src/evaluate/context-metrics.js +28 -16
- package/src/evaluate/evaluator.js +3 -3
- package/src/evaluate/faithfulness.js +18 -14
- package/src/evaluate/groundedness.js +43 -12
- package/src/evaluate/pipeline-evaluator.js +35 -8
- package/src/evaluate/scoring.js +251 -3
- package/src/evaluate/semantic-similarity.js +79 -0
- package/src/experimental.js +71 -0
- package/src/grounding/check-answer.js +173 -0
- package/src/guardrails/guardrails-pipeline.js +69 -7
- package/src/guardrails/injection-detector.js +283 -0
- package/src/guardrails/post-generation-guard.js +19 -0
- package/src/guardrails/pre-retrieval-guard.js +36 -36
- package/src/guardrails/retrieval-guard.js +58 -8
- package/src/index.js +58 -1
- package/src/loader/csv-loader.js +3 -2
- package/src/loader/document-reader.js +91 -0
- package/src/loader/html-loader.js +3 -1
- package/src/loader/markdown-loader.js +3 -2
- package/src/reranker/cascade-reranker.js +3 -0
- package/src/reranker/embedding-reranker.js +136 -21
- package/src/reranker/llm-reranker.js +79 -12
- package/src/reranker/scoring-reranker.js +3 -0
- package/src/retrieval/bm25-search.js +12 -6
- package/src/retrieval/file-vector-store.js +241 -0
- package/src/retrieval/hybrid-retriever.js +22 -19
- package/src/security/jwt-config.js +13 -2
- package/src/security/jwt-validator.js +139 -34
- package/src/security/plugin-sandbox.js +18 -1
- package/src/security/plugin-signature-verifier.js +245 -70
- package/src/testing.js +254 -0
- package/src/utils/deprecate.js +69 -0
- package/src/utils/embed-query.js +33 -0
- package/src/utils/input-sanitizer.js +19 -4
- package/src/utils/logger.js +34 -4
- package/src/utils/run-abort.js +102 -0
- package/src/ai/federated-learning.js +0 -211
- package/src/ai/federation.js +0 -71
- package/src/ai/index.js +0 -22
- package/src/ai/model-trainer.js +0 -217
- package/src/ai/model-training.js +0 -202
- package/src/ai/multimodal/multi-modal-processor.js +0 -345
- package/src/ai/orchestrator.js +0 -65
- package/src/ai/retrieval/adaptive-retrieval-engine.js +0 -398
- package/src/cli/commands/ai-ml/adaptive-commands.js +0 -178
- package/src/cli/commands/ai-ml/federated-commands.js +0 -207
- package/src/cli/commands/ai-ml/index.js +0 -17
- package/src/cli/commands/ai-ml/multimodal-commands.js +0 -187
- package/src/cli/commands/ai-ml/shared.js +0 -51
- package/src/cli/commands/ai-ml/training-commands.js +0 -228
- package/src/cli/commands/ai-ml.js +0 -386
- package/src/cli/commands/docs.js +0 -228
- package/src/cli/commands/dx.js +0 -538
- package/src/cli/commands/wizard.js +0 -627
- package/src/cli/input-sanitization-middleware.js +0 -356
- package/src/cli/interactive-wizard.js +0 -373
- package/src/cli/templates/development.template.json +0 -64
- package/src/cli/templates/minimal.template.json +0 -33
- package/src/cli/templates/production.template.json +0 -104
- package/src/cli/templates/testing.template.json +0 -45
- package/src/cli/wizard/configuration.js +0 -148
- package/src/cli/wizard/observability.js +0 -79
- package/src/cli/wizard/performance.js +0 -76
- package/src/cli/wizard/plugin-selection.js +0 -297
- package/src/cli/wizard/preview-save.js +0 -172
- package/src/cli/wizard/project-setup.js +0 -66
- package/src/core/pipeline-factory.js +0 -59
- package/src/dag/enhanced-dag-engine.js +0 -894
- package/src/dx/index.js +0 -40
- package/src/dx/integration-templates.js +0 -662
- package/src/dx/performance-profiler.js +0 -968
- package/src/dx/realtime-debugger.js +0 -755
- package/src/dx/visual-pipeline-builder.js +0 -578
- package/src/ingest.js +0 -59
- package/src/pipeline/pipeline.js +0 -18
- package/src/query.js +0 -117
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Maps token counts to cost estimates by provider and model.
|
|
3
|
+
*
|
|
4
|
+
* @example
|
|
5
|
+
* const calc = new CostCalculator();
|
|
6
|
+
* const cost = calc.estimate('gpt-4o', 1500, 500);
|
|
7
|
+
* console.log(cost.totalCost); // 0.015
|
|
8
|
+
*/
|
|
9
|
+
export class CostCalculator extends EventEmitter<[never]> {
|
|
10
|
+
/**
|
|
11
|
+
* Provenance of the built-in pricing table.
|
|
12
|
+
* @returns {typeof PRICING_METADATA}
|
|
13
|
+
*/
|
|
14
|
+
static getPricingMetadata(): typeof PRICING_METADATA;
|
|
15
|
+
/**
|
|
16
|
+
* @param {object} [options]
|
|
17
|
+
* @param {Record<string, {input: number, output: number, unit?: number, source?: string, asOf?: string}>} [options.pricing]
|
|
18
|
+
* Replaces the built-in pricing table entirely (only these models are known).
|
|
19
|
+
* @param {Record<string, {input: number, output: number, unit: number}>} [options.customPricing]
|
|
20
|
+
* Additional or override model pricing entries, merged over the base table.
|
|
21
|
+
*/
|
|
22
|
+
constructor(options?: {
|
|
23
|
+
pricing?: Record<string, {
|
|
24
|
+
input: number;
|
|
25
|
+
output: number;
|
|
26
|
+
unit?: number;
|
|
27
|
+
source?: string;
|
|
28
|
+
asOf?: string;
|
|
29
|
+
}>;
|
|
30
|
+
customPricing?: Record<string, {
|
|
31
|
+
input: number;
|
|
32
|
+
output: number;
|
|
33
|
+
unit: number;
|
|
34
|
+
}>;
|
|
35
|
+
});
|
|
36
|
+
pricing: {
|
|
37
|
+
[x: string]: {
|
|
38
|
+
input: number;
|
|
39
|
+
output: number;
|
|
40
|
+
unit: number;
|
|
41
|
+
source: string;
|
|
42
|
+
asOf: string;
|
|
43
|
+
};
|
|
44
|
+
};
|
|
45
|
+
/** @private Models already warned about as unknown */
|
|
46
|
+
private _warnedModels;
|
|
47
|
+
/**
|
|
48
|
+
* Resolve a model key from the pricing table.
|
|
49
|
+
* Tries an exact match (case-insensitive, '.' and '-' equivalent), then the
|
|
50
|
+
* longest known key contained in the model name (so dated snapshots such
|
|
51
|
+
* as "gpt-4o-mini-2024-07-18" resolve to "gpt-4o-mini", not "gpt-4"), then
|
|
52
|
+
* a known key that contains the model name.
|
|
53
|
+
* @param {string} model
|
|
54
|
+
* @returns {string|null} The matched pricing key or null.
|
|
55
|
+
* @private
|
|
56
|
+
*/
|
|
57
|
+
private _resolveModel;
|
|
58
|
+
/**
|
|
59
|
+
* Emit a one-time warning for a model with no known price.
|
|
60
|
+
* Listeners on 'warning' receive `{ type: 'unknown-model', model, message }`;
|
|
61
|
+
* without a listener the warning goes to process.emitWarning.
|
|
62
|
+
* @param {string} model
|
|
63
|
+
* @private
|
|
64
|
+
*/
|
|
65
|
+
private _warnUnknownModel;
|
|
66
|
+
/**
|
|
67
|
+
* Estimate the cost for a given token count.
|
|
68
|
+
*
|
|
69
|
+
* @param {string} model - Model identifier (case-insensitive, partial match supported).
|
|
70
|
+
* @param {number} inputTokens - Number of input / prompt tokens.
|
|
71
|
+
* @param {number} [outputTokens=0] - Number of output / completion tokens.
|
|
72
|
+
* @returns {{inputCost: number, outputCost: number, totalCost: number, model: string,
|
|
73
|
+
* inputTokens: number, outputTokens: number, currency: string,
|
|
74
|
+
* pricingSource?: string, pricingAsOf?: string|null, warning?: string}}
|
|
75
|
+
*/
|
|
76
|
+
estimate(model: string, inputTokens: number, outputTokens?: number): {
|
|
77
|
+
inputCost: number;
|
|
78
|
+
outputCost: number;
|
|
79
|
+
totalCost: number;
|
|
80
|
+
model: string;
|
|
81
|
+
inputTokens: number;
|
|
82
|
+
outputTokens: number;
|
|
83
|
+
currency: string;
|
|
84
|
+
pricingSource?: string;
|
|
85
|
+
pricingAsOf?: string | null;
|
|
86
|
+
warning?: string;
|
|
87
|
+
};
|
|
88
|
+
/**
|
|
89
|
+
* Register custom model pricing.
|
|
90
|
+
*
|
|
91
|
+
* @param {string} model - Model identifier.
|
|
92
|
+
* @param {{input: number, output: number, unit?: number, source?: string, asOf?: string}} pricing - Pricing definition.
|
|
93
|
+
*/
|
|
94
|
+
addModel(model: string, pricing: {
|
|
95
|
+
input: number;
|
|
96
|
+
output: number;
|
|
97
|
+
unit?: number;
|
|
98
|
+
source?: string;
|
|
99
|
+
asOf?: string;
|
|
100
|
+
}): void;
|
|
101
|
+
/**
|
|
102
|
+
* List all known model names.
|
|
103
|
+
* @returns {string[]}
|
|
104
|
+
*/
|
|
105
|
+
listModels(): string[];
|
|
106
|
+
/**
|
|
107
|
+
* Retrieve pricing for a specific model.
|
|
108
|
+
*
|
|
109
|
+
* @param {string} model - Model identifier (supports fuzzy resolution).
|
|
110
|
+
* @returns {{input: number, output: number, unit: number, source?: string, asOf?: string|null}|null}
|
|
111
|
+
*/
|
|
112
|
+
getModelPricing(model: string): {
|
|
113
|
+
input: number;
|
|
114
|
+
output: number;
|
|
115
|
+
unit: number;
|
|
116
|
+
source?: string;
|
|
117
|
+
asOf?: string | null;
|
|
118
|
+
} | null;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Built-in pricing table for common LLM and embedding models.
|
|
122
|
+
* Prices are in USD per `unit` tokens. Each entry records its `source`
|
|
123
|
+
* (provider pricing page) and `asOf` date.
|
|
124
|
+
* @type {Record<string, {input: number, output: number, unit: number, source: string, asOf: string}>}
|
|
125
|
+
*/
|
|
126
|
+
export const PRICING: Record<string, {
|
|
127
|
+
input: number;
|
|
128
|
+
output: number;
|
|
129
|
+
unit: number;
|
|
130
|
+
source: string;
|
|
131
|
+
asOf: string;
|
|
132
|
+
}>;
|
|
133
|
+
/**
|
|
134
|
+
* Where the built-in prices come from and when they were recorded.
|
|
135
|
+
*
|
|
136
|
+
* The values are the providers' published list prices as copied into this
|
|
137
|
+
* library on `asOf`; they have not been re-verified since and providers
|
|
138
|
+
* change prices often. Pass `pricing` or `customPricing` to CostCalculator
|
|
139
|
+
* to use current or negotiated prices.
|
|
140
|
+
*/
|
|
141
|
+
export const PRICING_METADATA: Readonly<{
|
|
142
|
+
asOf: "2026-04-07";
|
|
143
|
+
verified: false;
|
|
144
|
+
currency: "USD";
|
|
145
|
+
sources: Readonly<{
|
|
146
|
+
openai: "https://openai.com/api/pricing/";
|
|
147
|
+
anthropic: "https://www.anthropic.com/pricing#api";
|
|
148
|
+
cohere: "https://cohere.com/pricing";
|
|
149
|
+
}>;
|
|
150
|
+
note: "Built-in list prices, not re-verified since asOf. Override with the `pricing` or `customPricing` option.";
|
|
151
|
+
}>;
|
|
152
|
+
import { EventEmitter } from "events";
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wraps pipeline execution to automatically track token usage and costs.
|
|
3
|
+
*
|
|
4
|
+
* @example
|
|
5
|
+
* const tracker = new CostTracker({ model: 'gpt-4o', enableBudget: true, budgetOptions: { maxCost: 10 } });
|
|
6
|
+
* const wrapped = tracker.wrap(pipeline);
|
|
7
|
+
* const result = await wrapped.run(input);
|
|
8
|
+
* console.log(result.cost); // { inputTokens, outputTokens, estimatedCost, model }
|
|
9
|
+
* console.log(tracker.getSummary());
|
|
10
|
+
*/
|
|
11
|
+
export class CostTracker extends EventEmitter<[never]> {
|
|
12
|
+
/**
|
|
13
|
+
* @param {object} [options]
|
|
14
|
+
* @param {string} [options.model='gpt-3.5-turbo'] - Default LLM model for cost estimation.
|
|
15
|
+
* @param {string} [options.embeddingModel='text-embedding-3-small'] - Default embedding model.
|
|
16
|
+
* @param {boolean} [options.enableBudget=false] - Whether to enforce a token/cost budget.
|
|
17
|
+
* @param {object} [options.budgetOptions] - Options forwarded to {@link TokenBudget}.
|
|
18
|
+
* @param {object} [options.calculatorOptions] - Options forwarded to {@link CostCalculator}.
|
|
19
|
+
*/
|
|
20
|
+
constructor(options?: {
|
|
21
|
+
model?: string;
|
|
22
|
+
embeddingModel?: string;
|
|
23
|
+
enableBudget?: boolean;
|
|
24
|
+
budgetOptions?: object;
|
|
25
|
+
calculatorOptions?: object;
|
|
26
|
+
});
|
|
27
|
+
config: {
|
|
28
|
+
model: string;
|
|
29
|
+
embeddingModel: string;
|
|
30
|
+
enableBudget: boolean;
|
|
31
|
+
budgetOptions: object;
|
|
32
|
+
calculatorOptions?: object;
|
|
33
|
+
};
|
|
34
|
+
calculator: CostCalculator;
|
|
35
|
+
budget: TokenBudget;
|
|
36
|
+
sessions: any[];
|
|
37
|
+
currentSession: {
|
|
38
|
+
id: string;
|
|
39
|
+
startTime: number;
|
|
40
|
+
endTime: any;
|
|
41
|
+
metadata: any;
|
|
42
|
+
entries: any[];
|
|
43
|
+
totalTokens: number;
|
|
44
|
+
totalCost: number;
|
|
45
|
+
};
|
|
46
|
+
/**
|
|
47
|
+
* Extract token usage from a pipeline result.
|
|
48
|
+
* Checks common locations: result.usage, result.evaluation, or estimates from content length.
|
|
49
|
+
* @param {object} result
|
|
50
|
+
* @returns {{inputTokens: number, outputTokens: number}}
|
|
51
|
+
* @private
|
|
52
|
+
*/
|
|
53
|
+
private _extractUsage;
|
|
54
|
+
/**
|
|
55
|
+
* Wrap a pipeline so that every `.run()` call is cost-tracked.
|
|
56
|
+
*
|
|
57
|
+
* @param {object} pipeline - Object with a `.run()` method.
|
|
58
|
+
* @returns {object} A proxy pipeline whose `.run()` enriches results with cost data.
|
|
59
|
+
*/
|
|
60
|
+
wrap(pipeline: object): object;
|
|
61
|
+
/**
|
|
62
|
+
* Start a new tracking session.
|
|
63
|
+
*
|
|
64
|
+
* @param {object} [metadata={}] - Arbitrary metadata to attach to the session.
|
|
65
|
+
* @returns {{id: string, startTime: number, metadata: object, entries: Array,
|
|
66
|
+
* totalTokens: number, totalCost: number}}
|
|
67
|
+
*/
|
|
68
|
+
startSession(metadata?: object): {
|
|
69
|
+
id: string;
|
|
70
|
+
startTime: number;
|
|
71
|
+
metadata: object;
|
|
72
|
+
entries: any[];
|
|
73
|
+
totalTokens: number;
|
|
74
|
+
totalCost: number;
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* End the current tracking session and compute totals.
|
|
78
|
+
*
|
|
79
|
+
* @returns {object|null} The closed session, or null if no session was active.
|
|
80
|
+
*/
|
|
81
|
+
endSession(): object | null;
|
|
82
|
+
/**
|
|
83
|
+
* Return an aggregate summary across all sessions.
|
|
84
|
+
*
|
|
85
|
+
* @returns {{totalTokens: number, totalCost: number, sessionCount: number,
|
|
86
|
+
* avgCostPerQuery: number, breakdown: Record<string, {tokens: number, cost: number, count: number}>}}
|
|
87
|
+
*/
|
|
88
|
+
getSummary(): {
|
|
89
|
+
totalTokens: number;
|
|
90
|
+
totalCost: number;
|
|
91
|
+
sessionCount: number;
|
|
92
|
+
avgCostPerQuery: number;
|
|
93
|
+
breakdown: Record<string, {
|
|
94
|
+
tokens: number;
|
|
95
|
+
cost: number;
|
|
96
|
+
count: number;
|
|
97
|
+
}>;
|
|
98
|
+
};
|
|
99
|
+
/**
|
|
100
|
+
* Return the full history of tracked operations across all sessions.
|
|
101
|
+
*
|
|
102
|
+
* @returns {Array<{timestamp: number, inputTokens: number, outputTokens: number,
|
|
103
|
+
* cost: number, model: string, sessionId: string}>}
|
|
104
|
+
*/
|
|
105
|
+
getHistory(): Array<{
|
|
106
|
+
timestamp: number;
|
|
107
|
+
inputTokens: number;
|
|
108
|
+
outputTokens: number;
|
|
109
|
+
cost: number;
|
|
110
|
+
model: string;
|
|
111
|
+
sessionId: string;
|
|
112
|
+
}>;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Default tracker configuration.
|
|
116
|
+
* @type {{model: string, embeddingModel: string, enableBudget: boolean, budgetOptions: object}}
|
|
117
|
+
*/
|
|
118
|
+
export const DEFAULT_CONFIG: {
|
|
119
|
+
model: string;
|
|
120
|
+
embeddingModel: string;
|
|
121
|
+
enableBudget: boolean;
|
|
122
|
+
budgetOptions: object;
|
|
123
|
+
};
|
|
124
|
+
import { EventEmitter } from "events";
|
|
125
|
+
import { CostCalculator } from "./cost-calculator";
|
|
126
|
+
import { TokenBudget } from "./token-budget";
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Configurable token and cost budgets with hard and soft limits.
|
|
3
|
+
*
|
|
4
|
+
* Emits:
|
|
5
|
+
* - `usage` — after every {@link record} call with the recorded entry.
|
|
6
|
+
* - `warning` — when usage crosses the soft limit threshold.
|
|
7
|
+
* - `exceeded` — when usage crosses a hard limit.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* const budget = new TokenBudget({ maxTokens: 100000, maxCost: 5.0 });
|
|
11
|
+
* budget.on('warning', (msg) => console.warn(msg));
|
|
12
|
+
* const status = budget.check(2000, 0.10);
|
|
13
|
+
* if (status.allowed) budget.record(2000, 0.10);
|
|
14
|
+
*/
|
|
15
|
+
export class TokenBudget extends EventEmitter<[never]> {
|
|
16
|
+
/**
|
|
17
|
+
* @param {object} [options]
|
|
18
|
+
* @param {number} [options.maxTokens=Infinity] - Hard token limit.
|
|
19
|
+
* @param {number} [options.maxCost=Infinity] - Hard cost limit (USD).
|
|
20
|
+
* @param {number} [options.softLimitPercent=0.8] - Fraction (0-1) at which soft-limit warnings fire.
|
|
21
|
+
* @param {number} [options.trackingWindow=0] - Sliding window in ms (0 disables).
|
|
22
|
+
*/
|
|
23
|
+
constructor(options?: {
|
|
24
|
+
maxTokens?: number;
|
|
25
|
+
maxCost?: number;
|
|
26
|
+
softLimitPercent?: number;
|
|
27
|
+
trackingWindow?: number;
|
|
28
|
+
});
|
|
29
|
+
config: {
|
|
30
|
+
maxTokens: number;
|
|
31
|
+
maxCost: number;
|
|
32
|
+
softLimitPercent: number;
|
|
33
|
+
trackingWindow: number;
|
|
34
|
+
};
|
|
35
|
+
usage: {
|
|
36
|
+
tokens: number;
|
|
37
|
+
cost: number;
|
|
38
|
+
operations: number;
|
|
39
|
+
history: any[];
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Prune history entries outside the sliding window.
|
|
43
|
+
* @private
|
|
44
|
+
*/
|
|
45
|
+
private _pruneWindow;
|
|
46
|
+
/**
|
|
47
|
+
* Check whether a prospective usage fits within the budget.
|
|
48
|
+
*
|
|
49
|
+
* @param {number} [tokens=0] - Tokens about to be consumed.
|
|
50
|
+
* @param {number} [cost=0] - Cost about to be incurred.
|
|
51
|
+
* @returns {{allowed: boolean, reason?: string, remaining: {tokens: number, cost: number},
|
|
52
|
+
* warnings: string[], usage: {tokens: number, cost: number, operations: number}}}
|
|
53
|
+
*/
|
|
54
|
+
check(tokens?: number, cost?: number): {
|
|
55
|
+
allowed: boolean;
|
|
56
|
+
reason?: string;
|
|
57
|
+
remaining: {
|
|
58
|
+
tokens: number;
|
|
59
|
+
cost: number;
|
|
60
|
+
};
|
|
61
|
+
warnings: string[];
|
|
62
|
+
usage: {
|
|
63
|
+
tokens: number;
|
|
64
|
+
cost: number;
|
|
65
|
+
operations: number;
|
|
66
|
+
};
|
|
67
|
+
};
|
|
68
|
+
/**
|
|
69
|
+
* Record actual token and cost usage.
|
|
70
|
+
*
|
|
71
|
+
* @param {number} tokens - Tokens consumed.
|
|
72
|
+
* @param {number} [cost=0] - Cost incurred (USD).
|
|
73
|
+
*/
|
|
74
|
+
record(tokens: number, cost?: number): void;
|
|
75
|
+
/**
|
|
76
|
+
* Reset all usage counters to zero.
|
|
77
|
+
*/
|
|
78
|
+
reset(): void;
|
|
79
|
+
/**
|
|
80
|
+
* Return current usage summary.
|
|
81
|
+
*
|
|
82
|
+
* @returns {{tokens: number, cost: number, operations: number,
|
|
83
|
+
* limits: {maxTokens: number, maxCost: number},
|
|
84
|
+
* remaining: {tokens: number, cost: number}}}
|
|
85
|
+
*/
|
|
86
|
+
getUsage(): {
|
|
87
|
+
tokens: number;
|
|
88
|
+
cost: number;
|
|
89
|
+
operations: number;
|
|
90
|
+
limits: {
|
|
91
|
+
maxTokens: number;
|
|
92
|
+
maxCost: number;
|
|
93
|
+
};
|
|
94
|
+
remaining: {
|
|
95
|
+
tokens: number;
|
|
96
|
+
cost: number;
|
|
97
|
+
};
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Default budget configuration.
|
|
102
|
+
* @type {{maxTokens: number, maxCost: number, softLimitPercent: number, trackingWindow: number}}
|
|
103
|
+
*/
|
|
104
|
+
export const DEFAULT_CONFIG: {
|
|
105
|
+
maxTokens: number;
|
|
106
|
+
maxCost: number;
|
|
107
|
+
softLimitPercent: number;
|
|
108
|
+
trackingWindow: number;
|
|
109
|
+
};
|
|
110
|
+
import { EventEmitter } from "events";
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
export = ErrorContext;
|
|
2
|
+
/**
|
|
3
|
+
* ErrorContext class for managing DAG execution errors
|
|
4
|
+
*
|
|
5
|
+
* Provides comprehensive error management with:
|
|
6
|
+
* - Rich error context creation with node metadata
|
|
7
|
+
* - Error aggregation for multiple failures
|
|
8
|
+
* - Property preservation across error transformations
|
|
9
|
+
* - Error serialization for logging and monitoring
|
|
10
|
+
* - Cycle path tracking and reporting
|
|
11
|
+
* - Downstream impact analysis
|
|
12
|
+
*
|
|
13
|
+
* @class
|
|
14
|
+
* @since 2.2.4
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* const errorContext = new ErrorContext();
|
|
18
|
+
*
|
|
19
|
+
* // Create error with context
|
|
20
|
+
* const nodeError = errorContext.createErrorContext('nodeA', new Error('Failed'), {
|
|
21
|
+
* downstream: ['nodeB', 'nodeC'],
|
|
22
|
+
* timestamp: Date.now()
|
|
23
|
+
* });
|
|
24
|
+
*
|
|
25
|
+
* // Aggregate multiple errors
|
|
26
|
+
* const errorsMap = new Map([['nodeA', error1], ['nodeB', error2]]);
|
|
27
|
+
* const aggregated = errorContext.aggregateErrors(errorsMap);
|
|
28
|
+
*
|
|
29
|
+
* // Serialize for logging
|
|
30
|
+
* console.log(errorContext.serializeError(nodeError));
|
|
31
|
+
*/
|
|
32
|
+
declare class ErrorContext {
|
|
33
|
+
/**
|
|
34
|
+
* Create error context with node information and downstream impact
|
|
35
|
+
*
|
|
36
|
+
* Creates a new Error object enriched with:
|
|
37
|
+
* - Node ID for tracing execution path
|
|
38
|
+
* - Timestamp for temporal analysis
|
|
39
|
+
* - Original error as cause (for stack trace preservation)
|
|
40
|
+
* - Downstream node impact message
|
|
41
|
+
*
|
|
42
|
+
* @param {string} nodeId - ID of the node that failed
|
|
43
|
+
* @param {Error} error - Original error that occurred
|
|
44
|
+
* @param {Object} [options={}] - Additional context options
|
|
45
|
+
* @param {string[]} [options.downstream=[]] - Array of downstream node IDs affected
|
|
46
|
+
* @param {number} [options.timestamp=Date.now()] - Error timestamp
|
|
47
|
+
* @returns {Error} Enhanced error object with context
|
|
48
|
+
*
|
|
49
|
+
* @example
|
|
50
|
+
* const error = errorContext.createErrorContext(
|
|
51
|
+
* 'processData',
|
|
52
|
+
* new Error('Invalid input'),
|
|
53
|
+
* {
|
|
54
|
+
* downstream: ['saveResults', 'sendNotification'],
|
|
55
|
+
* timestamp: Date.now()
|
|
56
|
+
* }
|
|
57
|
+
* );
|
|
58
|
+
* // Error message: "Node processData execution failed: Invalid input.
|
|
59
|
+
* // This affects downstream nodes: saveResults, sendNotification"
|
|
60
|
+
* // error.nodeId === 'processData'
|
|
61
|
+
* // error.cause === original Error object
|
|
62
|
+
*
|
|
63
|
+
* @since 2.2.4
|
|
64
|
+
*/
|
|
65
|
+
createErrorContext(nodeId: string, error: Error, options?: {
|
|
66
|
+
downstream?: string[];
|
|
67
|
+
timestamp?: number;
|
|
68
|
+
}): Error;
|
|
69
|
+
/**
|
|
70
|
+
* Aggregate multiple errors into a single error object
|
|
71
|
+
*
|
|
72
|
+
* Creates a consolidated error when multiple nodes fail during execution.
|
|
73
|
+
* The aggregated error maintains references to all original errors for
|
|
74
|
+
* comprehensive debugging.
|
|
75
|
+
*
|
|
76
|
+
* @param {Map<string, Error>} errorsMap - Map of node ID to error object
|
|
77
|
+
* @returns {Error|null} Aggregated error, single error, or null if no errors
|
|
78
|
+
*
|
|
79
|
+
* @example
|
|
80
|
+
* const errors = new Map([
|
|
81
|
+
* ['nodeA', new Error('A failed')],
|
|
82
|
+
* ['nodeB', new Error('B failed')]
|
|
83
|
+
* ]);
|
|
84
|
+
* const aggregated = errorContext.aggregateErrors(errors);
|
|
85
|
+
* // aggregated.message === 'Multiple execution errors'
|
|
86
|
+
* // aggregated.errors === [Error('A failed'), Error('B failed')]
|
|
87
|
+
*
|
|
88
|
+
* @since 2.2.4
|
|
89
|
+
*/
|
|
90
|
+
aggregateErrors(errorsMap: Map<string, Error>): Error | null;
|
|
91
|
+
/**
|
|
92
|
+
* Preserve node context when wrapping or transforming errors
|
|
93
|
+
*
|
|
94
|
+
* Ensures all error metadata (nodeId, timestamp, cause, cycle, errors)
|
|
95
|
+
* is preserved when creating wrapped errors. This is critical for
|
|
96
|
+
* maintaining debugging information through error propagation.
|
|
97
|
+
*
|
|
98
|
+
* @param {Error} error - Original error to preserve
|
|
99
|
+
* @param {Object} [context={}] - Additional context to add
|
|
100
|
+
* @returns {Error} New error with preserved properties
|
|
101
|
+
*
|
|
102
|
+
* @example
|
|
103
|
+
* const originalError = new Error('Original');
|
|
104
|
+
* originalError.nodeId = 'nodeA';
|
|
105
|
+
* originalError.timestamp = Date.now();
|
|
106
|
+
*
|
|
107
|
+
* const wrapped = errorContext.preserveNodeContext(originalError, {
|
|
108
|
+
* retryCount: 3
|
|
109
|
+
* });
|
|
110
|
+
* // wrapped.nodeId === 'nodeA'
|
|
111
|
+
* // wrapped.timestamp === original timestamp
|
|
112
|
+
* // wrapped.retryCount === 3
|
|
113
|
+
*
|
|
114
|
+
* @since 2.2.4
|
|
115
|
+
*/
|
|
116
|
+
preserveNodeContext(error: Error, context?: any): Error;
|
|
117
|
+
/**
|
|
118
|
+
* Format error report for debugging and monitoring
|
|
119
|
+
*
|
|
120
|
+
* Creates a structured representation of an error suitable for logging,
|
|
121
|
+
* monitoring systems, or debugging tools. Includes all metadata and
|
|
122
|
+
* nested error information.
|
|
123
|
+
*
|
|
124
|
+
* @param {Error} error - Error to format
|
|
125
|
+
* @returns {Object} Structured error report
|
|
126
|
+
*
|
|
127
|
+
* @example
|
|
128
|
+
* const report = errorContext.formatErrorReport(nodeError);
|
|
129
|
+
* // {
|
|
130
|
+
* // message: "Node A execution failed: ...",
|
|
131
|
+
* // nodeId: "A",
|
|
132
|
+
* // timestamp: 1234567890,
|
|
133
|
+
* // cause: { message: "...", stack: "..." },
|
|
134
|
+
* // cycle: null,
|
|
135
|
+
* // errors: null
|
|
136
|
+
* // }
|
|
137
|
+
*
|
|
138
|
+
* @since 2.2.4
|
|
139
|
+
*/
|
|
140
|
+
formatErrorReport(error: Error): any;
|
|
141
|
+
/**
|
|
142
|
+
* Serialize error for logging and monitoring systems
|
|
143
|
+
*
|
|
144
|
+
* Converts error to JSON string with formatting for readability.
|
|
145
|
+
* Safe for logging systems that require string representation.
|
|
146
|
+
*
|
|
147
|
+
* @param {Error} error - Error to serialize
|
|
148
|
+
* @param {number} [indent=2] - JSON indentation spaces
|
|
149
|
+
* @returns {string} JSON string representation of error
|
|
150
|
+
*
|
|
151
|
+
* @example
|
|
152
|
+
* const json = errorContext.serializeError(nodeError);
|
|
153
|
+
* console.log(json);
|
|
154
|
+
* // {
|
|
155
|
+
* // "message": "Node A execution failed: ...",
|
|
156
|
+
* // "nodeId": "A",
|
|
157
|
+
* // "timestamp": 1234567890,
|
|
158
|
+
* // ...
|
|
159
|
+
* // }
|
|
160
|
+
*
|
|
161
|
+
* @since 2.2.4
|
|
162
|
+
*/
|
|
163
|
+
serializeError(error: Error, indent?: number): string;
|
|
164
|
+
/**
|
|
165
|
+
* Wrap execution errors with appropriate context
|
|
166
|
+
*
|
|
167
|
+
* Implements error wrapping policy:
|
|
168
|
+
* - Node errors (with nodeId or starting with "Node ") are rethrown unchanged
|
|
169
|
+
* - Validation/cycle errors are wrapped once with "DAG execution failed"
|
|
170
|
+
* - Timeout and "no sink nodes" errors are not wrapped
|
|
171
|
+
* - All other errors are wrapped with "DAG execution failed"
|
|
172
|
+
*
|
|
173
|
+
* All error properties are preserved during wrapping.
|
|
174
|
+
*
|
|
175
|
+
* @param {Error} error - Error to wrap
|
|
176
|
+
* @returns {Error} Appropriately wrapped error
|
|
177
|
+
*
|
|
178
|
+
* @example
|
|
179
|
+
* const nodeError = new Error('Node A failed');
|
|
180
|
+
* nodeError.nodeId = 'A';
|
|
181
|
+
* const wrapped = errorContext.wrapExecutionError(nodeError);
|
|
182
|
+
* // Returns same error unchanged (node error policy)
|
|
183
|
+
*
|
|
184
|
+
* @example
|
|
185
|
+
* const validationError = new Error('DAG validation failed: cycle detected');
|
|
186
|
+
* validationError.cycle = ['A', 'B', 'A'];
|
|
187
|
+
* const wrapped = errorContext.wrapExecutionError(validationError);
|
|
188
|
+
* // Returns: Error('DAG execution failed: DAG validation failed: cycle detected')
|
|
189
|
+
* // with cycle property preserved
|
|
190
|
+
*
|
|
191
|
+
* @since 2.2.4
|
|
192
|
+
*/
|
|
193
|
+
wrapExecutionError(error: Error): Error;
|
|
194
|
+
/**
|
|
195
|
+
* Create cycle error with path information
|
|
196
|
+
*
|
|
197
|
+
* Creates a specialized error for cycle detection with the cycle path
|
|
198
|
+
* embedded for debugging and error reporting.
|
|
199
|
+
*
|
|
200
|
+
* @param {string[]} cyclePath - Array of node IDs forming the cycle
|
|
201
|
+
* @returns {Error} Cycle error with path information
|
|
202
|
+
*
|
|
203
|
+
* @example
|
|
204
|
+
* const cycleError = errorContext.createCycleError(['A', 'B', 'C', 'A']);
|
|
205
|
+
* // cycleError.message === 'Cycle detected involving node: A -> B -> C -> A'
|
|
206
|
+
* // cycleError.cycle === ['A', 'B', 'C', 'A']
|
|
207
|
+
*
|
|
208
|
+
* @since 2.2.4
|
|
209
|
+
*/
|
|
210
|
+
createCycleError(cyclePath: string[]): Error;
|
|
211
|
+
/**
|
|
212
|
+
* Check if error should halt execution
|
|
213
|
+
*
|
|
214
|
+
* Determines if an error is critical enough to stop DAG execution
|
|
215
|
+
* based on error type and execution options.
|
|
216
|
+
*
|
|
217
|
+
* @param {Error} error - Error to evaluate
|
|
218
|
+
* @param {Object} options - Execution options
|
|
219
|
+
* @param {boolean} [options.continueOnError=false] - Continue on non-critical errors
|
|
220
|
+
* @param {boolean} [options.isNonCritical=false] - Whether node is non-critical
|
|
221
|
+
* @returns {boolean} True if execution should halt
|
|
222
|
+
*
|
|
223
|
+
* @example
|
|
224
|
+
* const shouldHalt = errorContext.shouldHaltExecution(error, {
|
|
225
|
+
* continueOnError: true,
|
|
226
|
+
* isNonCritical: true
|
|
227
|
+
* });
|
|
228
|
+
* // Returns false - execution continues
|
|
229
|
+
*
|
|
230
|
+
* @since 2.2.4
|
|
231
|
+
*/
|
|
232
|
+
shouldHaltExecution(error: Error, options?: {
|
|
233
|
+
continueOnError?: boolean;
|
|
234
|
+
isNonCritical?: boolean;
|
|
235
|
+
}): boolean;
|
|
236
|
+
}
|
|
237
|
+
declare namespace ErrorContext {
|
|
238
|
+
export { ErrorContext as default };
|
|
239
|
+
}
|