@cogitator-ai/core 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/README.md +117 -0
- package/dist/causal/capabilities/causal-explainer.d.ts +33 -0
- package/dist/causal/capabilities/causal-explainer.d.ts.map +1 -0
- package/dist/causal/capabilities/causal-explainer.js +327 -0
- package/dist/causal/capabilities/causal-explainer.js.map +1 -0
- package/dist/causal/capabilities/causal-planner.d.ts +42 -0
- package/dist/causal/capabilities/causal-planner.d.ts.map +1 -0
- package/dist/causal/capabilities/causal-planner.js +289 -0
- package/dist/causal/capabilities/causal-planner.js.map +1 -0
- package/dist/causal/capabilities/effect-predictor.d.ts +30 -0
- package/dist/causal/capabilities/effect-predictor.d.ts.map +1 -0
- package/dist/causal/capabilities/effect-predictor.js +270 -0
- package/dist/causal/capabilities/effect-predictor.js.map +1 -0
- package/dist/causal/causal-reasoner.d.ts +63 -0
- package/dist/causal/causal-reasoner.d.ts.map +1 -0
- package/dist/causal/causal-reasoner.js +325 -0
- package/dist/causal/causal-reasoner.js.map +1 -0
- package/dist/causal/discovery/causal-extractor.d.ts +46 -0
- package/dist/causal/discovery/causal-extractor.d.ts.map +1 -0
- package/dist/causal/discovery/causal-extractor.js +154 -0
- package/dist/causal/discovery/causal-extractor.js.map +1 -0
- package/dist/causal/discovery/causal-validator.d.ts +50 -0
- package/dist/causal/discovery/causal-validator.d.ts.map +1 -0
- package/dist/causal/discovery/causal-validator.js +235 -0
- package/dist/causal/discovery/causal-validator.js.map +1 -0
- package/dist/causal/discovery/hypothesis-generator.d.ts +37 -0
- package/dist/causal/discovery/hypothesis-generator.d.ts.map +1 -0
- package/dist/causal/discovery/hypothesis-generator.js +225 -0
- package/dist/causal/discovery/hypothesis-generator.js.map +1 -0
- package/dist/causal/discovery/prompts.d.ts +99 -0
- package/dist/causal/discovery/prompts.d.ts.map +1 -0
- package/dist/causal/discovery/prompts.js +263 -0
- package/dist/causal/discovery/prompts.js.map +1 -0
- package/dist/causal/graph/causal-graph.d.ts +38 -0
- package/dist/causal/graph/causal-graph.d.ts.map +1 -0
- package/dist/causal/graph/causal-graph.js +321 -0
- package/dist/causal/graph/causal-graph.js.map +1 -0
- package/dist/causal/graph/graph-builder.d.ts +68 -0
- package/dist/causal/graph/graph-builder.d.ts.map +1 -0
- package/dist/causal/graph/graph-builder.js +128 -0
- package/dist/causal/graph/graph-builder.js.map +1 -0
- package/dist/causal/index.d.ts +28 -0
- package/dist/causal/index.d.ts.map +1 -0
- package/dist/causal/index.js +18 -0
- package/dist/causal/index.js.map +1 -0
- package/dist/causal/inference/adjustment.d.ts +5 -0
- package/dist/causal/inference/adjustment.d.ts.map +1 -0
- package/dist/causal/inference/adjustment.js +189 -0
- package/dist/causal/inference/adjustment.js.map +1 -0
- package/dist/causal/inference/counterfactual.d.ts +24 -0
- package/dist/causal/inference/counterfactual.d.ts.map +1 -0
- package/dist/causal/inference/counterfactual.js +199 -0
- package/dist/causal/inference/counterfactual.js.map +1 -0
- package/dist/causal/inference/d-separation.d.ts +4 -0
- package/dist/causal/inference/d-separation.d.ts.map +1 -0
- package/dist/causal/inference/d-separation.js +168 -0
- package/dist/causal/inference/d-separation.js.map +1 -0
- package/dist/causal/inference/inference-engine.d.ts +33 -0
- package/dist/causal/inference/inference-engine.d.ts.map +1 -0
- package/dist/causal/inference/inference-engine.js +254 -0
- package/dist/causal/inference/inference-engine.js.map +1 -0
- package/dist/causal/stores/causal-graph-store.d.ts +12 -0
- package/dist/causal/stores/causal-graph-store.d.ts.map +1 -0
- package/dist/causal/stores/causal-graph-store.js +60 -0
- package/dist/causal/stores/causal-graph-store.js.map +1 -0
- package/dist/causal/stores/causal-pattern-store.d.ts +19 -0
- package/dist/causal/stores/causal-pattern-store.d.ts.map +1 -0
- package/dist/causal/stores/causal-pattern-store.js +117 -0
- package/dist/causal/stores/causal-pattern-store.js.map +1 -0
- package/dist/causal/stores/intervention-log.d.ts +16 -0
- package/dist/causal/stores/intervention-log.d.ts.map +1 -0
- package/dist/causal/stores/intervention-log.js +113 -0
- package/dist/causal/stores/intervention-log.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/learning/ab-testing.d.ts.map +1 -1
- package/dist/learning/ab-testing.js +6 -5
- package/dist/learning/ab-testing.js.map +1 -1
- package/dist/learning/auto-optimizer.d.ts.map +1 -1
- package/dist/learning/auto-optimizer.js +4 -2
- package/dist/learning/auto-optimizer.js.map +1 -1
- package/dist/learning/postgres-trace-store.d.ts.map +1 -1
- package/dist/learning/postgres-trace-store.js +15 -5
- package/dist/learning/postgres-trace-store.js.map +1 -1
- package/dist/learning/prompt-monitor.d.ts.map +1 -1
- package/dist/learning/prompt-monitor.js.map +1 -1
- package/dist/learning/rollback-manager.d.ts.map +1 -1
- package/dist/learning/rollback-manager.js.map +1 -1
- package/package.json +5 -5
package/README.md
CHANGED
|
@@ -51,6 +51,7 @@ console.log(result.output);
|
|
|
51
51
|
- **Tree-of-Thought** - Advanced reasoning with branch exploration
|
|
52
52
|
- **Agent Optimizer** - DSPy-style learning from traces
|
|
53
53
|
- **Time Travel** - Checkpoint, replay, fork, and compare executions
|
|
54
|
+
- **Causal Reasoning** - Pearl's do-calculus, counterfactuals, d-separation
|
|
54
55
|
- **Resilience** - Retry, circuit breaker, and fallback patterns
|
|
55
56
|
- **Observability** - Full tracing with spans and callbacks
|
|
56
57
|
|
|
@@ -717,6 +718,106 @@ const liveReplay = await timeTravel.replayLive(agent, checkpointId, {
|
|
|
717
718
|
|
|
718
719
|
---
|
|
719
720
|
|
|
721
|
+
## Causal Reasoning
|
|
722
|
+
|
|
723
|
+
Full causal reasoning framework implementing Pearl's Ladder of Causation:
|
|
724
|
+
|
|
725
|
+
- **Level 1 (Association)**: Observational queries P(Y|X)
|
|
726
|
+
- **Level 2 (Intervention)**: do-calculus P(Y|do(X))
|
|
727
|
+
- **Level 3 (Counterfactual)**: "What if" queries P(Y_x|X', Y')
|
|
728
|
+
|
|
729
|
+
### Building Causal Graphs
|
|
730
|
+
|
|
731
|
+
```typescript
|
|
732
|
+
import { CausalGraphBuilder, CausalInferenceEngine } from '@cogitator-ai/core';
|
|
733
|
+
|
|
734
|
+
const graph = CausalGraphBuilder.create('medical-study')
|
|
735
|
+
.treatment('X', 'Drug Treatment')
|
|
736
|
+
.outcome('Y', 'Recovery')
|
|
737
|
+
.confounder('Z', 'Age')
|
|
738
|
+
.from('Z')
|
|
739
|
+
.causes('X')
|
|
740
|
+
.from('Z')
|
|
741
|
+
.causes('Y')
|
|
742
|
+
.from('X')
|
|
743
|
+
.causes('Y', { strength: 0.8 })
|
|
744
|
+
.build();
|
|
745
|
+
|
|
746
|
+
const engine = new CausalInferenceEngine(graph);
|
|
747
|
+
```
|
|
748
|
+
|
|
749
|
+
### Effect Identification
|
|
750
|
+
|
|
751
|
+
```typescript
|
|
752
|
+
const identifiable = engine.isIdentifiable('X', 'Y');
|
|
753
|
+
if (identifiable.identifiable) {
|
|
754
|
+
console.log('Effect is identifiable via:', identifiable.method);
|
|
755
|
+
console.log('Adjustment set:', identifiable.adjustmentSet);
|
|
756
|
+
}
|
|
757
|
+
```
|
|
758
|
+
|
|
759
|
+
### Interventional Queries
|
|
760
|
+
|
|
761
|
+
```typescript
|
|
762
|
+
const effect = engine.computeInterventionalEffect({
|
|
763
|
+
target: 'Y',
|
|
764
|
+
interventions: { X: 1 },
|
|
765
|
+
observed: { Z: 0.5 },
|
|
766
|
+
});
|
|
767
|
+
|
|
768
|
+
console.log('Expected effect:', effect.effect);
|
|
769
|
+
console.log('Confidence:', effect.confidence);
|
|
770
|
+
```
|
|
771
|
+
|
|
772
|
+
### Counterfactual Reasoning
|
|
773
|
+
|
|
774
|
+
```typescript
|
|
775
|
+
import { evaluateCounterfactual } from '@cogitator-ai/core';
|
|
776
|
+
|
|
777
|
+
const result = evaluateCounterfactual(graph, {
|
|
778
|
+
target: 'Y',
|
|
779
|
+
intervention: { X: 1 },
|
|
780
|
+
factual: { X: 0, Y: 0.2 },
|
|
781
|
+
question: 'What would Y be if X was 1?',
|
|
782
|
+
});
|
|
783
|
+
|
|
784
|
+
console.log('Factual value:', result.factualValue);
|
|
785
|
+
console.log('Counterfactual value:', result.counterfactualValue);
|
|
786
|
+
```
|
|
787
|
+
|
|
788
|
+
### D-Separation Analysis
|
|
789
|
+
|
|
790
|
+
```typescript
|
|
791
|
+
import { dSeparation, findBackdoorAdjustment } from '@cogitator-ai/core';
|
|
792
|
+
|
|
793
|
+
const separated = dSeparation(graph, 'X', 'Y', ['Z']);
|
|
794
|
+
console.log('D-separated:', separated.separated);
|
|
795
|
+
|
|
796
|
+
const backdoor = findBackdoorAdjustment(graph, 'X', 'Y');
|
|
797
|
+
if (backdoor?.isValid) {
|
|
798
|
+
console.log('Backdoor adjustment set:', backdoor.variables);
|
|
799
|
+
}
|
|
800
|
+
```
|
|
801
|
+
|
|
802
|
+
### Causal Discovery from Traces
|
|
803
|
+
|
|
804
|
+
```typescript
|
|
805
|
+
import { CausalExtractor, CausalHypothesisGenerator } from '@cogitator-ai/core';
|
|
806
|
+
|
|
807
|
+
const extractor = new CausalExtractor({ llmBackend: backend });
|
|
808
|
+
|
|
809
|
+
const relations = await extractor.extractFromToolResult(
|
|
810
|
+
{ name: 'database_query', arguments: { table: 'users' } },
|
|
811
|
+
{ rows: 100, cached: true },
|
|
812
|
+
{ agentId: 'agent-1' }
|
|
813
|
+
);
|
|
814
|
+
|
|
815
|
+
const generator = new CausalHypothesisGenerator({ llmBackend: backend });
|
|
816
|
+
const hypotheses = await generator.generateFromFailure(trace, { agentId: 'agent-1' });
|
|
817
|
+
```
|
|
818
|
+
|
|
819
|
+
---
|
|
820
|
+
|
|
720
821
|
## Error Handling & Resilience
|
|
721
822
|
|
|
722
823
|
### Retry with Backoff
|
|
@@ -894,6 +995,22 @@ import type {
|
|
|
894
995
|
} from '@cogitator-ai/core';
|
|
895
996
|
```
|
|
896
997
|
|
|
998
|
+
### Causal Types
|
|
999
|
+
|
|
1000
|
+
```typescript
|
|
1001
|
+
import type {
|
|
1002
|
+
CausalNode,
|
|
1003
|
+
CausalEdge,
|
|
1004
|
+
CausalGraph,
|
|
1005
|
+
CausalRelationType,
|
|
1006
|
+
InterventionQuery,
|
|
1007
|
+
CounterfactualQuery,
|
|
1008
|
+
CausalHypothesis,
|
|
1009
|
+
CausalEvidence,
|
|
1010
|
+
StructuralEquation,
|
|
1011
|
+
} from '@cogitator-ai/core';
|
|
1012
|
+
```
|
|
1013
|
+
|
|
897
1014
|
### Error Types
|
|
898
1015
|
|
|
899
1016
|
```typescript
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { CausalGraph, CausalContext, CausalExplanation, ExecutionTrace, LLMBackend } from '@cogitator-ai/types';
|
|
2
|
+
export interface CausalExplainerOptions {
|
|
3
|
+
llmBackend: LLMBackend;
|
|
4
|
+
model?: string;
|
|
5
|
+
maxRootCauses?: number;
|
|
6
|
+
maxCounterfactuals?: number;
|
|
7
|
+
}
|
|
8
|
+
export declare class CausalExplainer {
|
|
9
|
+
private llm;
|
|
10
|
+
private model;
|
|
11
|
+
private maxRootCauses;
|
|
12
|
+
private maxCounterfactuals;
|
|
13
|
+
constructor(options: CausalExplainerOptions);
|
|
14
|
+
explainCause(effect: string, effectValue: number | string | boolean, graph: CausalGraph, context: CausalContext): Promise<CausalExplanation>;
|
|
15
|
+
analyzeError(error: {
|
|
16
|
+
message: string;
|
|
17
|
+
stack?: string;
|
|
18
|
+
}, trace: ExecutionTrace, _graph: CausalGraph, context: CausalContext): Promise<CausalExplanation>;
|
|
19
|
+
analyzeSuccess(outcome: string, trace: ExecutionTrace, graph: CausalGraph): Promise<CausalExplanation>;
|
|
20
|
+
private findRootCauses;
|
|
21
|
+
private findContributingFactors;
|
|
22
|
+
private generateCounterfactuals;
|
|
23
|
+
private generateSummary;
|
|
24
|
+
private calculateConfidence;
|
|
25
|
+
private describeMechanism;
|
|
26
|
+
private suggestIntervention;
|
|
27
|
+
private getAlternativeValue;
|
|
28
|
+
private findRelevantNodes;
|
|
29
|
+
private describeStep;
|
|
30
|
+
private isStepSuccessful;
|
|
31
|
+
private createBasicErrorExplanation;
|
|
32
|
+
}
|
|
33
|
+
//# sourceMappingURL=causal-explainer.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"causal-explainer.d.ts","sourceRoot":"","sources":["../../../src/causal/capabilities/causal-explainer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,EACX,aAAa,EACb,iBAAiB,EAGjB,cAAc,EAEd,UAAU,EACX,MAAM,qBAAqB,CAAC;AAI7B,MAAM,WAAW,sBAAsB;IACrC,UAAU,EAAE,UAAU,CAAC;IACvB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,kBAAkB,CAAC,EAAE,MAAM,CAAC;CAC7B;AAED,qBAAa,eAAe;IAC1B,OAAO,CAAC,GAAG,CAAa;IACxB,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,aAAa,CAAS;IAC9B,OAAO,CAAC,kBAAkB,CAAS;gBAEvB,OAAO,EAAE,sBAAsB;IAOrC,YAAY,CAChB,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,EACtC,KAAK,EAAE,WAAW,EAClB,OAAO,EAAE,aAAa,GACrB,OAAO,CAAC,iBAAiB,CAAC;IA+BvB,YAAY,CAChB,KAAK,EAAE;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,EAC1C,KAAK,EAAE,cAAc,EACrB,MAAM,EAAE,WAAW,EACnB,OAAO,EAAE,aAAa,GACrB,OAAO,CAAC,iBAAiB,CAAC;IAqDvB,cAAc,CAClB,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,cAAc,EACrB,KAAK,EAAE,WAAW,GACjB,OAAO,CAAC,iBAAiB,CAAC;IA8C7B,OAAO,CAAC,cAAc;IAsEtB,OAAO,CAAC,uBAAuB;YAqCjB,uBAAuB;IAyCrC,OAAO,CAAC,eAAe;IA6BvB,OAAO,CAAC,mBAAmB;IAe3B,OAAO,CAAC,iBAAiB;IAazB,OAAO,CAAC,mBAAmB;IA2B3B,OAAO,CAAC,mBAAmB;IAU3B,OAAO,CAAC,iBAAiB;IAiBzB,OAAO,CAAC,YAAY;IAUpB,OAAO,CAAC,gBAAgB;IAOxB,OAAO,CAAC,2BAA2B;CA4BpC"}
|
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
import { CounterfactualReasoner } from '../inference/counterfactual';
|
|
2
|
+
import { buildErrorCausalAnalysisPrompt, parseRootCauseResponse } from '../discovery/prompts';
|
|
3
|
+
export class CausalExplainer {
|
|
4
|
+
llm;
|
|
5
|
+
model;
|
|
6
|
+
maxRootCauses;
|
|
7
|
+
maxCounterfactuals;
|
|
8
|
+
constructor(options) {
|
|
9
|
+
this.llm = options.llmBackend;
|
|
10
|
+
this.model = options.model ?? 'gpt-4';
|
|
11
|
+
this.maxRootCauses = options.maxRootCauses ?? 5;
|
|
12
|
+
this.maxCounterfactuals = options.maxCounterfactuals ?? 3;
|
|
13
|
+
}
|
|
14
|
+
async explainCause(effect, effectValue, graph, context) {
|
|
15
|
+
const rootCauses = this.findRootCauses(effect, graph, context);
|
|
16
|
+
const contributingFactors = this.findContributingFactors(effect, graph);
|
|
17
|
+
const counterfactuals = await this.generateCounterfactuals(effect, effectValue, graph, context);
|
|
18
|
+
const summary = this.generateSummary(effect, effectValue, rootCauses);
|
|
19
|
+
const confidence = this.calculateConfidence(rootCauses, contributingFactors);
|
|
20
|
+
return {
|
|
21
|
+
effect,
|
|
22
|
+
effectValue,
|
|
23
|
+
rootCauses,
|
|
24
|
+
contributingFactors,
|
|
25
|
+
counterfactuals,
|
|
26
|
+
summary,
|
|
27
|
+
confidence,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
async analyzeError(error, trace, _graph, context) {
|
|
31
|
+
const recentActions = trace.steps.slice(-10).map((s) => this.describeStep(s));
|
|
32
|
+
const prompt = buildErrorCausalAnalysisPrompt(error, trace, {
|
|
33
|
+
recentActions,
|
|
34
|
+
systemState: context.observedVariables,
|
|
35
|
+
});
|
|
36
|
+
const response = await this.llm.chat({
|
|
37
|
+
model: this.model,
|
|
38
|
+
messages: [{ role: 'user', content: prompt }],
|
|
39
|
+
temperature: 0.3,
|
|
40
|
+
});
|
|
41
|
+
const parsed = parseRootCauseResponse(response.content);
|
|
42
|
+
if (!parsed) {
|
|
43
|
+
return this.createBasicErrorExplanation(error, trace);
|
|
44
|
+
}
|
|
45
|
+
const rootCauses = parsed.rootCauses.map((rc) => ({
|
|
46
|
+
variable: rc.variable,
|
|
47
|
+
contribution: rc.contribution,
|
|
48
|
+
mechanism: rc.description,
|
|
49
|
+
path: { nodes: [], edges: [], totalStrength: rc.contribution, isBlocked: false, blockingNodes: [] },
|
|
50
|
+
confidence: rc.contribution,
|
|
51
|
+
actionable: rc.actionable,
|
|
52
|
+
suggestedIntervention: parsed.preventiveInterventions.find((p) => p.target === rc.variable)?.action,
|
|
53
|
+
}));
|
|
54
|
+
const contributingFactors = parsed.causalChain.map((c) => ({
|
|
55
|
+
variable: c.from,
|
|
56
|
+
contribution: 0.5,
|
|
57
|
+
direction: 'negative',
|
|
58
|
+
}));
|
|
59
|
+
return {
|
|
60
|
+
effect: 'error',
|
|
61
|
+
effectValue: error.message,
|
|
62
|
+
rootCauses,
|
|
63
|
+
contributingFactors,
|
|
64
|
+
counterfactuals: parsed.preventiveInterventions.map((p) => ({
|
|
65
|
+
change: `${p.target}: ${p.action}`,
|
|
66
|
+
wouldPrevent: true,
|
|
67
|
+
confidence: 0.7,
|
|
68
|
+
})),
|
|
69
|
+
summary: parsed.reasoning,
|
|
70
|
+
confidence: 0.7,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
async analyzeSuccess(outcome, trace, graph) {
|
|
74
|
+
const successfulSteps = trace.steps.filter((s) => this.isStepSuccessful(s));
|
|
75
|
+
const rootCauses = [];
|
|
76
|
+
const contributingFactors = [];
|
|
77
|
+
for (const step of successfulSteps.slice(-5)) {
|
|
78
|
+
const stepDesc = this.describeStep(step);
|
|
79
|
+
const relevantNodes = this.findRelevantNodes(stepDesc, graph);
|
|
80
|
+
for (const nodeId of relevantNodes) {
|
|
81
|
+
const paths = graph.findPaths(nodeId, outcome);
|
|
82
|
+
if (paths.length > 0) {
|
|
83
|
+
const bestPath = paths.reduce((a, b) => a.totalStrength > b.totalStrength ? a : b);
|
|
84
|
+
rootCauses.push({
|
|
85
|
+
variable: nodeId,
|
|
86
|
+
contribution: bestPath.totalStrength,
|
|
87
|
+
mechanism: `${stepDesc} enabled ${outcome}`,
|
|
88
|
+
path: bestPath,
|
|
89
|
+
confidence: bestPath.totalStrength,
|
|
90
|
+
actionable: true,
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
rootCauses.sort((a, b) => b.contribution - a.contribution);
|
|
96
|
+
return {
|
|
97
|
+
effect: outcome,
|
|
98
|
+
effectValue: true,
|
|
99
|
+
rootCauses: rootCauses.slice(0, this.maxRootCauses),
|
|
100
|
+
contributingFactors,
|
|
101
|
+
counterfactuals: [],
|
|
102
|
+
summary: `Success achieved through ${rootCauses.length} contributing factors`,
|
|
103
|
+
confidence: 0.7,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
findRootCauses(effect, graph, context) {
|
|
107
|
+
const rootCauses = [];
|
|
108
|
+
const effectNode = graph.getNode(effect);
|
|
109
|
+
if (!effectNode) {
|
|
110
|
+
return rootCauses;
|
|
111
|
+
}
|
|
112
|
+
const ancestors = graph.getAncestors(effect);
|
|
113
|
+
const rootNodes = ancestors.filter((ancestor) => {
|
|
114
|
+
const parents = graph.getParents(ancestor.id);
|
|
115
|
+
return parents.length === 0;
|
|
116
|
+
});
|
|
117
|
+
for (const root of rootNodes) {
|
|
118
|
+
const paths = graph.findPaths(root.id, effect);
|
|
119
|
+
if (paths.length === 0)
|
|
120
|
+
continue;
|
|
121
|
+
const bestPath = paths.reduce((a, b) => a.totalStrength > b.totalStrength ? a : b);
|
|
122
|
+
const isObserved = context.observedVariables[root.id] !== undefined;
|
|
123
|
+
rootCauses.push({
|
|
124
|
+
variable: root.id,
|
|
125
|
+
contribution: bestPath.totalStrength,
|
|
126
|
+
mechanism: this.describeMechanism(bestPath),
|
|
127
|
+
path: bestPath,
|
|
128
|
+
confidence: isObserved ? 0.9 : 0.6,
|
|
129
|
+
actionable: root.variableType === 'treatment' || root.variableType === 'observed',
|
|
130
|
+
suggestedIntervention: this.suggestIntervention(root.id, bestPath, graph),
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
for (const ancestor of ancestors) {
|
|
134
|
+
if (rootNodes.some((r) => r.id === ancestor.id))
|
|
135
|
+
continue;
|
|
136
|
+
const directEdge = graph.getEdgeBetween(ancestor.id, effect);
|
|
137
|
+
if (!directEdge)
|
|
138
|
+
continue;
|
|
139
|
+
const parents = graph.getParents(ancestor.id);
|
|
140
|
+
if (parents.length === 0) {
|
|
141
|
+
rootCauses.push({
|
|
142
|
+
variable: ancestor.id,
|
|
143
|
+
contribution: directEdge.strength,
|
|
144
|
+
mechanism: directEdge.mechanism || `Direct ${directEdge.relationType} relationship`,
|
|
145
|
+
path: {
|
|
146
|
+
nodes: [ancestor.id, effect],
|
|
147
|
+
edges: [directEdge],
|
|
148
|
+
totalStrength: directEdge.strength,
|
|
149
|
+
isBlocked: false,
|
|
150
|
+
blockingNodes: [],
|
|
151
|
+
},
|
|
152
|
+
confidence: directEdge.confidence,
|
|
153
|
+
actionable: ancestor.variableType !== 'latent',
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
rootCauses.sort((a, b) => b.contribution - a.contribution);
|
|
158
|
+
return rootCauses.slice(0, this.maxRootCauses);
|
|
159
|
+
}
|
|
160
|
+
findContributingFactors(effect, graph) {
|
|
161
|
+
const factors = [];
|
|
162
|
+
const parents = graph.getParents(effect);
|
|
163
|
+
for (const parent of parents) {
|
|
164
|
+
const edge = graph.getEdgeBetween(parent.id, effect);
|
|
165
|
+
if (!edge)
|
|
166
|
+
continue;
|
|
167
|
+
let direction;
|
|
168
|
+
if (edge.relationType === 'causes' || edge.relationType === 'enables') {
|
|
169
|
+
direction = 'positive';
|
|
170
|
+
}
|
|
171
|
+
else if (edge.relationType === 'prevents') {
|
|
172
|
+
direction = 'negative';
|
|
173
|
+
}
|
|
174
|
+
else {
|
|
175
|
+
direction = edge.strength > 0 ? 'positive' : 'negative';
|
|
176
|
+
}
|
|
177
|
+
factors.push({
|
|
178
|
+
variable: parent.id,
|
|
179
|
+
contribution: Math.abs(edge.strength),
|
|
180
|
+
direction,
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
factors.sort((a, b) => b.contribution - a.contribution);
|
|
184
|
+
return factors;
|
|
185
|
+
}
|
|
186
|
+
async generateCounterfactuals(effect, effectValue, graph, context) {
|
|
187
|
+
const counterfactuals = [];
|
|
188
|
+
const parents = graph.getParents(effect);
|
|
189
|
+
const reasoner = new CounterfactualReasoner();
|
|
190
|
+
for (const parent of parents.slice(0, this.maxCounterfactuals)) {
|
|
191
|
+
const edge = graph.getEdgeBetween(parent.id, effect);
|
|
192
|
+
if (!edge)
|
|
193
|
+
continue;
|
|
194
|
+
const currentValue = context.observedVariables[parent.id];
|
|
195
|
+
const alternativeValue = this.getAlternativeValue(currentValue);
|
|
196
|
+
const result = reasoner.evaluate(graph, {
|
|
197
|
+
target: effect,
|
|
198
|
+
intervention: { [parent.id]: alternativeValue },
|
|
199
|
+
factual: context.observedVariables,
|
|
200
|
+
question: `What if ${parent.id} was ${alternativeValue}?`,
|
|
201
|
+
});
|
|
202
|
+
const wouldPrevent = result.counterfactualValue !== effectValue;
|
|
203
|
+
counterfactuals.push({
|
|
204
|
+
change: `If ${parent.id} was ${alternativeValue} instead of ${currentValue}`,
|
|
205
|
+
wouldPrevent,
|
|
206
|
+
confidence: edge.confidence,
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
return counterfactuals;
|
|
210
|
+
}
|
|
211
|
+
generateSummary(effect, effectValue, rootCauses) {
|
|
212
|
+
if (rootCauses.length === 0) {
|
|
213
|
+
return `Unable to determine root causes for ${effect} = ${effectValue}`;
|
|
214
|
+
}
|
|
215
|
+
const topCause = rootCauses[0];
|
|
216
|
+
const otherCauses = rootCauses.slice(1, 3);
|
|
217
|
+
let summary = `The primary cause of ${effect} = ${effectValue} is ${topCause.variable} (${Math.round(topCause.contribution * 100)}% contribution)`;
|
|
218
|
+
if (topCause.mechanism) {
|
|
219
|
+
summary += ` through ${topCause.mechanism}`;
|
|
220
|
+
}
|
|
221
|
+
if (otherCauses.length > 0) {
|
|
222
|
+
summary += `. Contributing factors include ${otherCauses.map((c) => c.variable).join(', ')}`;
|
|
223
|
+
}
|
|
224
|
+
if (topCause.suggestedIntervention) {
|
|
225
|
+
summary += `. To change this outcome, consider: ${topCause.suggestedIntervention}`;
|
|
226
|
+
}
|
|
227
|
+
return summary;
|
|
228
|
+
}
|
|
229
|
+
calculateConfidence(rootCauses, contributingFactors) {
|
|
230
|
+
if (rootCauses.length === 0)
|
|
231
|
+
return 0.1;
|
|
232
|
+
const avgRootCauseConfidence = rootCauses.reduce((sum, rc) => sum + rc.confidence, 0) / rootCauses.length;
|
|
233
|
+
const totalContribution = contributingFactors.reduce((sum, f) => sum + f.contribution, 0);
|
|
234
|
+
const contributionFactor = Math.min(1, totalContribution);
|
|
235
|
+
return avgRootCauseConfidence * 0.7 + contributionFactor * 0.3;
|
|
236
|
+
}
|
|
237
|
+
describeMechanism(path) {
|
|
238
|
+
if (path.nodes.length <= 2) {
|
|
239
|
+
const edge = path.edges[0];
|
|
240
|
+
return edge?.mechanism || 'Direct causal relationship';
|
|
241
|
+
}
|
|
242
|
+
const steps = path.edges.map((edge) => {
|
|
243
|
+
return `${edge.source} ${edge.relationType} ${edge.target}`;
|
|
244
|
+
});
|
|
245
|
+
return `Causal chain: ${steps.join(' → ')}`;
|
|
246
|
+
}
|
|
247
|
+
suggestIntervention(variable, path, graph) {
|
|
248
|
+
const node = graph.getNode(variable);
|
|
249
|
+
if (!node)
|
|
250
|
+
return undefined;
|
|
251
|
+
if (node.variableType === 'treatment') {
|
|
252
|
+
return `Modify ${variable} to change the outcome`;
|
|
253
|
+
}
|
|
254
|
+
if (node.variableType === 'confounder') {
|
|
255
|
+
return `Control for ${variable} to eliminate confounding`;
|
|
256
|
+
}
|
|
257
|
+
if (path.edges.length > 0) {
|
|
258
|
+
const firstEdge = path.edges[0];
|
|
259
|
+
if (firstEdge.relationType === 'prevents') {
|
|
260
|
+
return `Enable ${variable} to prevent the effect`;
|
|
261
|
+
}
|
|
262
|
+
return `Adjust ${variable} to modify the causal pathway`;
|
|
263
|
+
}
|
|
264
|
+
return undefined;
|
|
265
|
+
}
|
|
266
|
+
getAlternativeValue(currentValue) {
|
|
267
|
+
if (typeof currentValue === 'boolean') {
|
|
268
|
+
return !currentValue;
|
|
269
|
+
}
|
|
270
|
+
if (typeof currentValue === 'number') {
|
|
271
|
+
return currentValue === 0 ? 1 : 0;
|
|
272
|
+
}
|
|
273
|
+
return 'alternative';
|
|
274
|
+
}
|
|
275
|
+
findRelevantNodes(description, graph) {
|
|
276
|
+
const nodes = graph.getNodes();
|
|
277
|
+
const relevant = [];
|
|
278
|
+
const descLower = description.toLowerCase();
|
|
279
|
+
for (const node of nodes) {
|
|
280
|
+
if (descLower.includes(node.id.toLowerCase()) ||
|
|
281
|
+
descLower.includes(node.name.toLowerCase())) {
|
|
282
|
+
relevant.push(node.id);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
return relevant;
|
|
286
|
+
}
|
|
287
|
+
describeStep(step) {
|
|
288
|
+
if (step.toolCall) {
|
|
289
|
+
return `${step.toolCall.name}(${JSON.stringify(step.toolCall.arguments)})`;
|
|
290
|
+
}
|
|
291
|
+
if (step.response) {
|
|
292
|
+
return step.response.substring(0, 100);
|
|
293
|
+
}
|
|
294
|
+
return `step-${step.type}-${step.index}`;
|
|
295
|
+
}
|
|
296
|
+
isStepSuccessful(step) {
|
|
297
|
+
if (step.toolResult) {
|
|
298
|
+
return !step.toolResult.error;
|
|
299
|
+
}
|
|
300
|
+
return step.response !== undefined;
|
|
301
|
+
}
|
|
302
|
+
createBasicErrorExplanation(error, trace) {
|
|
303
|
+
const failedStep = trace.steps.find((s) => !this.isStepSuccessful(s));
|
|
304
|
+
return {
|
|
305
|
+
effect: 'error',
|
|
306
|
+
effectValue: error.message,
|
|
307
|
+
rootCauses: failedStep
|
|
308
|
+
? [
|
|
309
|
+
{
|
|
310
|
+
variable: 'failed_step',
|
|
311
|
+
contribution: 1,
|
|
312
|
+
mechanism: `Step "${this.describeStep(failedStep)}" failed`,
|
|
313
|
+
path: { nodes: [], edges: [], totalStrength: 1, isBlocked: false, blockingNodes: [] },
|
|
314
|
+
confidence: 0.5,
|
|
315
|
+
actionable: true,
|
|
316
|
+
suggestedIntervention: 'Review and fix the failed step',
|
|
317
|
+
},
|
|
318
|
+
]
|
|
319
|
+
: [],
|
|
320
|
+
contributingFactors: [],
|
|
321
|
+
counterfactuals: [],
|
|
322
|
+
summary: `Error occurred: ${error.message}`,
|
|
323
|
+
confidence: 0.3,
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
//# sourceMappingURL=causal-explainer.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"causal-explainer.js","sourceRoot":"","sources":["../../../src/causal/capabilities/causal-explainer.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EAAE,8BAA8B,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAS9F,MAAM,OAAO,eAAe;I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AC;IAC3C,CAAC;IAEO,gBAAgB,CAAC,IAAmB;QAC1C,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;YACpB,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC;QAChC,CAAC;QACD,OAAO,IAAI,CAAC,QAAQ,KAAK,SAAS,CAAC;IACrC,CAAC;IAEO,2BAA2B,CACjC,KAA0C,EAC1C,KAAqB;QAErB,MAAM,UAAU,GAAG,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC,CAAC;QAEtE,OAAO;YACL,MAAM,EAAE,OAAO;YACf,WAAW,EAAE,KAAK,CAAC,OAAO;YAC1B,UAAU,EAAE,UAAU;gBACpB,CAAC,CAAC;oBACE;wBACE,QAAQ,EAAE,aAAa;wBACvB,YAAY,EAAE,CAAC;wBACf,SAAS,EAAE,SAAS,IAAI,CAAC,YAAY,CAAC,UAAU,CAAC,UAAU;wBAC3D,IAAI,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE,aAAa,EAAE,CAAC,EAAE,SAAS,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE,EAAE;wBACrF,UAAU,EAAE,GAAG;wBACf,UAAU,EAAE,IAAI;wBAChB,qBAAqB,EAAE,gCAAgC;qBACxD;iBACF;gBACH,CAAC,CAAC,EAAE;YACN,mBAAmB,EAAE,EAAE;YACvB,eAAe,EAAE,EAAE;YACnB,OAAO,EAAE,mBAAmB,KAAK,CAAC,OAAO,EAAE;YAC3C,UAAU,EAAE,GAAG;SAChB,CAAC;IACJ,CAAC;CACF"}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { CausalGraph, CausalContext, CausalPlan, CausalPlanStep, LLMBackend } from '@cogitator-ai/types';
|
|
2
|
+
export interface CausalPlannerOptions {
|
|
3
|
+
llmBackend: LLMBackend;
|
|
4
|
+
model?: string;
|
|
5
|
+
maxPlanSteps?: number;
|
|
6
|
+
maxAlternatives?: number;
|
|
7
|
+
robustnessThreshold?: number;
|
|
8
|
+
}
|
|
9
|
+
export declare class CausalPlanner {
|
|
10
|
+
private llm;
|
|
11
|
+
private model;
|
|
12
|
+
private effectPredictor;
|
|
13
|
+
private maxPlanSteps;
|
|
14
|
+
private maxAlternatives;
|
|
15
|
+
private robustnessThreshold;
|
|
16
|
+
constructor(options: CausalPlannerOptions);
|
|
17
|
+
planForGoal(goal: string, goalValue: number | string | boolean, graph: CausalGraph, context: CausalContext, constraints?: {
|
|
18
|
+
forbidden?: string[];
|
|
19
|
+
required?: string[];
|
|
20
|
+
maxCost?: number;
|
|
21
|
+
}): Promise<CausalPlan>;
|
|
22
|
+
findInterventions(target: string, targetValue: number | string | boolean, graph: CausalGraph, _context: CausalContext): Array<{
|
|
23
|
+
variable: string;
|
|
24
|
+
value: unknown;
|
|
25
|
+
effectiveness: number;
|
|
26
|
+
}>;
|
|
27
|
+
reverseEngineer(desiredOutcome: Record<string, number | string | boolean>, graph: CausalGraph, context: CausalContext): Promise<CausalPlan[]>;
|
|
28
|
+
analyzeRobustness(steps: CausalPlanStep[], graph: CausalGraph, _context: CausalContext): Promise<{
|
|
29
|
+
score: number;
|
|
30
|
+
vulnerabilities: string[];
|
|
31
|
+
backupPlans: CausalPlan[];
|
|
32
|
+
}>;
|
|
33
|
+
private applyConstraints;
|
|
34
|
+
private buildPlanSteps;
|
|
35
|
+
private topologicalSortInterventions;
|
|
36
|
+
private findPreconditions;
|
|
37
|
+
private findAlternativeSteps;
|
|
38
|
+
private calculateExpectedOutcome;
|
|
39
|
+
private estimateCost;
|
|
40
|
+
private generatePlanReasoning;
|
|
41
|
+
}
|
|
42
|
+
//# sourceMappingURL=causal-planner.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"causal-planner.d.ts","sourceRoot":"","sources":["../../../src/causal/capabilities/causal-planner.ts"],"names":[],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