@reactive-agents/reasoning 0.1.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/LICENSE +21 -0
- package/README.md +94 -0
- package/dist/index.d.ts +275 -0
- package/dist/index.js +566 -0
- package/dist/index.js.map +1 -0
- package/package.json +49 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Tyler Buell
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
# @reactive-agents/reasoning
|
|
2
|
+
|
|
3
|
+
Reasoning strategies for the [Reactive Agents](https://tylerjrbuell.github.io/reactive-agents-ts/) framework.
|
|
4
|
+
|
|
5
|
+
Adds structured thinking to agents via ReAct, Plan-Execute, Tree-of-Thought, and Reflexion strategies.
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
bun add @reactive-agents/reasoning effect
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Strategies
|
|
14
|
+
|
|
15
|
+
| Strategy | Description | LLM Calls | Best For |
|
|
16
|
+
|----------|-------------|-----------|----------|
|
|
17
|
+
| `reactive` | ReAct: Think → Act → Observe loop | 1/iteration | Tool-using agents |
|
|
18
|
+
| `plan-execute-reflect` | Plan all steps, then execute | 2+ | Multi-step tasks |
|
|
19
|
+
| `tree-of-thought` | Explore multiple branches | 3× breadth/depth | Complex reasoning |
|
|
20
|
+
| `reflexion` | Generate → Critique → Improve loop | 3/retry | Quality-critical output |
|
|
21
|
+
|
|
22
|
+
## Usage
|
|
23
|
+
|
|
24
|
+
```typescript
|
|
25
|
+
import { ReactiveAgents } from "reactive-agents";
|
|
26
|
+
|
|
27
|
+
const agent = await ReactiveAgents.create()
|
|
28
|
+
.withName("researcher")
|
|
29
|
+
.withProvider("anthropic")
|
|
30
|
+
.withReasoning() // defaults to ReAct
|
|
31
|
+
.build();
|
|
32
|
+
|
|
33
|
+
const result = await agent.run("Analyze the trade-offs between TCP and UDP");
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## ReAct Strategy
|
|
37
|
+
|
|
38
|
+
The default. A Thought → Action → Observation loop:
|
|
39
|
+
|
|
40
|
+
```
|
|
41
|
+
Thought: I need to find information about X
|
|
42
|
+
Action: search("X")
|
|
43
|
+
Observation: [search results]
|
|
44
|
+
Thought: Based on the results, I can conclude...
|
|
45
|
+
FINAL ANSWER: [conclusion]
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Reflexion Strategy
|
|
49
|
+
|
|
50
|
+
A Generate → Self-Critique → Improve loop based on the [Reflexion paper](https://arxiv.org/abs/2303.11366):
|
|
51
|
+
|
|
52
|
+
```
|
|
53
|
+
[ATTEMPT 1] Initial response...
|
|
54
|
+
[CRITIQUE 1] The response is missing X and Y. The explanation of Z is inaccurate.
|
|
55
|
+
[ATTEMPT 2] Improved response addressing X, Y, and correcting Z...
|
|
56
|
+
[CRITIQUE 2] SATISFIED: The response is now accurate and complete.
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Use Reflexion when output quality matters more than latency:
|
|
60
|
+
|
|
61
|
+
```typescript
|
|
62
|
+
import { executeReflexion } from "@reactive-agents/reasoning";
|
|
63
|
+
import { Effect } from "effect";
|
|
64
|
+
|
|
65
|
+
const result = await Effect.runPromise(
|
|
66
|
+
executeReflexion({
|
|
67
|
+
taskDescription: "Write a concise technical explanation of RAFT consensus.",
|
|
68
|
+
taskType: "explanation",
|
|
69
|
+
memoryContext: "",
|
|
70
|
+
availableTools: [],
|
|
71
|
+
config: {
|
|
72
|
+
defaultStrategy: "reflexion",
|
|
73
|
+
adaptive: { enabled: false, learning: false },
|
|
74
|
+
strategies: {
|
|
75
|
+
reactive: { maxIterations: 10, temperature: 0.7 },
|
|
76
|
+
planExecute: { maxRefinements: 2, reflectionDepth: "deep" },
|
|
77
|
+
treeOfThought: { breadth: 3, depth: 3, pruningThreshold: 0.5 },
|
|
78
|
+
reflexion: {
|
|
79
|
+
maxRetries: 3, // Max critique-improve cycles
|
|
80
|
+
selfCritiqueDepth: "deep", // "shallow" | "deep"
|
|
81
|
+
},
|
|
82
|
+
},
|
|
83
|
+
},
|
|
84
|
+
}).pipe(Effect.provide(llmLayer)),
|
|
85
|
+
);
|
|
86
|
+
|
|
87
|
+
console.log(result.output);
|
|
88
|
+
console.log(result.metadata.confidence); // 0.6–1.0
|
|
89
|
+
console.log(result.status); // "completed" | "partial"
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Documentation
|
|
93
|
+
|
|
94
|
+
Full documentation at [tylerjrbuell.github.io/reactive-agents-ts/guides/reasoning/](https://tylerjrbuell.github.io/reactive-agents-ts/guides/reasoning/)
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
import { Schema, Effect, Context, Layer } from 'effect';
|
|
2
|
+
import * as effect_Cause from 'effect/Cause';
|
|
3
|
+
import * as effect_Types from 'effect/Types';
|
|
4
|
+
import * as _reactive_agents_llm_provider from '@reactive-agents/llm-provider';
|
|
5
|
+
import { LLMService } from '@reactive-agents/llm-provider';
|
|
6
|
+
import { ReasoningStrategy } from '@reactive-agents/core';
|
|
7
|
+
export { ReasoningStrategy } from '@reactive-agents/core';
|
|
8
|
+
|
|
9
|
+
declare const StepId: Schema.brand<typeof Schema.String, "StepId">;
|
|
10
|
+
type StepId = typeof StepId.Type;
|
|
11
|
+
declare const StepType: Schema.Literal<["thought", "action", "observation", "plan", "reflection", "critique"]>;
|
|
12
|
+
type StepType = typeof StepType.Type;
|
|
13
|
+
declare const StepMetadataSchema: Schema.Struct<{
|
|
14
|
+
confidence: Schema.optional<typeof Schema.Number>;
|
|
15
|
+
toolUsed: Schema.optional<typeof Schema.String>;
|
|
16
|
+
cost: Schema.optional<typeof Schema.Number>;
|
|
17
|
+
duration: Schema.optional<typeof Schema.Number>;
|
|
18
|
+
}>;
|
|
19
|
+
type StepMetadata = typeof StepMetadataSchema.Type;
|
|
20
|
+
declare const ReasoningStepSchema: Schema.Struct<{
|
|
21
|
+
id: Schema.brand<typeof Schema.String, "StepId">;
|
|
22
|
+
type: Schema.Literal<["thought", "action", "observation", "plan", "reflection", "critique"]>;
|
|
23
|
+
content: typeof Schema.String;
|
|
24
|
+
timestamp: typeof Schema.DateFromSelf;
|
|
25
|
+
metadata: Schema.optional<Schema.Struct<{
|
|
26
|
+
confidence: Schema.optional<typeof Schema.Number>;
|
|
27
|
+
toolUsed: Schema.optional<typeof Schema.String>;
|
|
28
|
+
cost: Schema.optional<typeof Schema.Number>;
|
|
29
|
+
duration: Schema.optional<typeof Schema.Number>;
|
|
30
|
+
}>>;
|
|
31
|
+
}>;
|
|
32
|
+
type ReasoningStep = typeof ReasoningStepSchema.Type;
|
|
33
|
+
|
|
34
|
+
declare const ReasoningStatus: Schema.Literal<["completed", "failed", "partial"]>;
|
|
35
|
+
type ReasoningStatus = typeof ReasoningStatus.Type;
|
|
36
|
+
declare const ReasoningMetadataSchema: Schema.Struct<{
|
|
37
|
+
duration: typeof Schema.Number;
|
|
38
|
+
cost: typeof Schema.Number;
|
|
39
|
+
tokensUsed: typeof Schema.Number;
|
|
40
|
+
stepsCount: typeof Schema.Number;
|
|
41
|
+
confidence: typeof Schema.Number;
|
|
42
|
+
effectiveness: Schema.optional<typeof Schema.Number>;
|
|
43
|
+
selectedStrategy: Schema.optional<Schema.Literal<["reactive", "plan-execute-reflect", "tree-of-thought", "reflexion", "adaptive"]>>;
|
|
44
|
+
}>;
|
|
45
|
+
type ReasoningMetadata = typeof ReasoningMetadataSchema.Type;
|
|
46
|
+
declare const ReasoningResultSchema: Schema.Struct<{
|
|
47
|
+
strategy: Schema.Literal<["reactive", "plan-execute-reflect", "tree-of-thought", "reflexion", "adaptive"]>;
|
|
48
|
+
steps: Schema.Array$<Schema.Struct<{
|
|
49
|
+
id: Schema.brand<typeof Schema.String, "StepId">;
|
|
50
|
+
type: Schema.Literal<["thought", "action", "observation", "plan", "reflection", "critique"]>;
|
|
51
|
+
content: typeof Schema.String;
|
|
52
|
+
timestamp: typeof Schema.DateFromSelf;
|
|
53
|
+
metadata: Schema.optional<Schema.Struct<{
|
|
54
|
+
confidence: Schema.optional<typeof Schema.Number>;
|
|
55
|
+
toolUsed: Schema.optional<typeof Schema.String>;
|
|
56
|
+
cost: Schema.optional<typeof Schema.Number>;
|
|
57
|
+
duration: Schema.optional<typeof Schema.Number>;
|
|
58
|
+
}>>;
|
|
59
|
+
}>>;
|
|
60
|
+
output: typeof Schema.Unknown;
|
|
61
|
+
metadata: Schema.Struct<{
|
|
62
|
+
duration: typeof Schema.Number;
|
|
63
|
+
cost: typeof Schema.Number;
|
|
64
|
+
tokensUsed: typeof Schema.Number;
|
|
65
|
+
stepsCount: typeof Schema.Number;
|
|
66
|
+
confidence: typeof Schema.Number;
|
|
67
|
+
effectiveness: Schema.optional<typeof Schema.Number>;
|
|
68
|
+
selectedStrategy: Schema.optional<Schema.Literal<["reactive", "plan-execute-reflect", "tree-of-thought", "reflexion", "adaptive"]>>;
|
|
69
|
+
}>;
|
|
70
|
+
status: Schema.Literal<["completed", "failed", "partial"]>;
|
|
71
|
+
}>;
|
|
72
|
+
type ReasoningResult = typeof ReasoningResultSchema.Type;
|
|
73
|
+
declare const SelectionContextSchema: Schema.Struct<{
|
|
74
|
+
taskDescription: typeof Schema.String;
|
|
75
|
+
taskType: typeof Schema.String;
|
|
76
|
+
complexity: typeof Schema.Number;
|
|
77
|
+
urgency: typeof Schema.Number;
|
|
78
|
+
costBudget: Schema.optional<typeof Schema.Number>;
|
|
79
|
+
timeConstraint: Schema.optional<typeof Schema.Number>;
|
|
80
|
+
preferredStrategy: Schema.optional<Schema.Literal<["reactive", "plan-execute-reflect", "tree-of-thought", "reflexion", "adaptive"]>>;
|
|
81
|
+
}>;
|
|
82
|
+
type SelectionContext = typeof SelectionContextSchema.Type;
|
|
83
|
+
|
|
84
|
+
declare const StrategyEffectivenessSchema: Schema.Struct<{
|
|
85
|
+
strategy: Schema.Literal<["reactive", "plan-execute-reflect", "tree-of-thought", "reflexion", "adaptive"]>;
|
|
86
|
+
taskType: typeof Schema.String;
|
|
87
|
+
successRate: typeof Schema.Number;
|
|
88
|
+
avgCost: typeof Schema.Number;
|
|
89
|
+
avgDuration: typeof Schema.Number;
|
|
90
|
+
avgConfidence: typeof Schema.Number;
|
|
91
|
+
executions: typeof Schema.Number;
|
|
92
|
+
lastUsed: typeof Schema.DateFromSelf;
|
|
93
|
+
}>;
|
|
94
|
+
type StrategyEffectiveness = typeof StrategyEffectivenessSchema.Type;
|
|
95
|
+
|
|
96
|
+
declare const ReactiveConfigSchema: Schema.Struct<{
|
|
97
|
+
maxIterations: Schema.filter<Schema.filter<typeof Schema.Number>>;
|
|
98
|
+
temperature: typeof Schema.Number;
|
|
99
|
+
}>;
|
|
100
|
+
type ReactiveConfig = typeof ReactiveConfigSchema.Type;
|
|
101
|
+
declare const PlanExecuteConfigSchema: Schema.Struct<{
|
|
102
|
+
maxRefinements: Schema.filter<Schema.filter<typeof Schema.Number>>;
|
|
103
|
+
reflectionDepth: Schema.Literal<["shallow", "deep"]>;
|
|
104
|
+
}>;
|
|
105
|
+
type PlanExecuteConfig = typeof PlanExecuteConfigSchema.Type;
|
|
106
|
+
declare const TreeOfThoughtConfigSchema: Schema.Struct<{
|
|
107
|
+
breadth: Schema.filter<Schema.filter<typeof Schema.Number>>;
|
|
108
|
+
depth: Schema.filter<Schema.filter<typeof Schema.Number>>;
|
|
109
|
+
pruningThreshold: typeof Schema.Number;
|
|
110
|
+
}>;
|
|
111
|
+
type TreeOfThoughtConfig = typeof TreeOfThoughtConfigSchema.Type;
|
|
112
|
+
declare const ReflexionConfigSchema: Schema.Struct<{
|
|
113
|
+
maxRetries: Schema.filter<Schema.filter<typeof Schema.Number>>;
|
|
114
|
+
selfCritiqueDepth: Schema.Literal<["shallow", "deep"]>;
|
|
115
|
+
}>;
|
|
116
|
+
type ReflexionConfig = typeof ReflexionConfigSchema.Type;
|
|
117
|
+
declare const ReasoningConfigSchema: Schema.Struct<{
|
|
118
|
+
defaultStrategy: Schema.Literal<["reactive", "plan-execute-reflect", "tree-of-thought", "reflexion", "adaptive"]>;
|
|
119
|
+
adaptive: Schema.Struct<{
|
|
120
|
+
enabled: typeof Schema.Boolean;
|
|
121
|
+
learning: typeof Schema.Boolean;
|
|
122
|
+
}>;
|
|
123
|
+
strategies: Schema.Struct<{
|
|
124
|
+
reactive: Schema.Struct<{
|
|
125
|
+
maxIterations: Schema.filter<Schema.filter<typeof Schema.Number>>;
|
|
126
|
+
temperature: typeof Schema.Number;
|
|
127
|
+
}>;
|
|
128
|
+
planExecute: Schema.Struct<{
|
|
129
|
+
maxRefinements: Schema.filter<Schema.filter<typeof Schema.Number>>;
|
|
130
|
+
reflectionDepth: Schema.Literal<["shallow", "deep"]>;
|
|
131
|
+
}>;
|
|
132
|
+
treeOfThought: Schema.Struct<{
|
|
133
|
+
breadth: Schema.filter<Schema.filter<typeof Schema.Number>>;
|
|
134
|
+
depth: Schema.filter<Schema.filter<typeof Schema.Number>>;
|
|
135
|
+
pruningThreshold: typeof Schema.Number;
|
|
136
|
+
}>;
|
|
137
|
+
reflexion: Schema.Struct<{
|
|
138
|
+
maxRetries: Schema.filter<Schema.filter<typeof Schema.Number>>;
|
|
139
|
+
selfCritiqueDepth: Schema.Literal<["shallow", "deep"]>;
|
|
140
|
+
}>;
|
|
141
|
+
}>;
|
|
142
|
+
}>;
|
|
143
|
+
type ReasoningConfig = typeof ReasoningConfigSchema.Type;
|
|
144
|
+
declare const defaultReasoningConfig: ReasoningConfig;
|
|
145
|
+
|
|
146
|
+
declare const ReasoningError_base: new <A extends Record<string, any> = {}>(args: effect_Types.Equals<A, {}> extends true ? void : { readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }) => effect_Cause.YieldableError & {
|
|
147
|
+
readonly _tag: "ReasoningError";
|
|
148
|
+
} & Readonly<A>;
|
|
149
|
+
declare class ReasoningError extends ReasoningError_base<{
|
|
150
|
+
readonly message: string;
|
|
151
|
+
readonly cause?: unknown;
|
|
152
|
+
}> {
|
|
153
|
+
}
|
|
154
|
+
declare const StrategyNotFoundError_base: new <A extends Record<string, any> = {}>(args: effect_Types.Equals<A, {}> extends true ? void : { readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }) => effect_Cause.YieldableError & {
|
|
155
|
+
readonly _tag: "StrategyNotFoundError";
|
|
156
|
+
} & Readonly<A>;
|
|
157
|
+
declare class StrategyNotFoundError extends StrategyNotFoundError_base<{
|
|
158
|
+
readonly strategy: string;
|
|
159
|
+
}> {
|
|
160
|
+
}
|
|
161
|
+
declare const SelectionError_base: new <A extends Record<string, any> = {}>(args: effect_Types.Equals<A, {}> extends true ? void : { readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }) => effect_Cause.YieldableError & {
|
|
162
|
+
readonly _tag: "SelectionError";
|
|
163
|
+
} & Readonly<A>;
|
|
164
|
+
declare class SelectionError extends SelectionError_base<{
|
|
165
|
+
readonly message: string;
|
|
166
|
+
readonly context?: unknown;
|
|
167
|
+
}> {
|
|
168
|
+
}
|
|
169
|
+
declare const ExecutionError_base: new <A extends Record<string, any> = {}>(args: effect_Types.Equals<A, {}> extends true ? void : { readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }) => effect_Cause.YieldableError & {
|
|
170
|
+
readonly _tag: "ExecutionError";
|
|
171
|
+
} & Readonly<A>;
|
|
172
|
+
declare class ExecutionError extends ExecutionError_base<{
|
|
173
|
+
readonly strategy: string;
|
|
174
|
+
readonly message: string;
|
|
175
|
+
readonly step?: number;
|
|
176
|
+
readonly cause?: unknown;
|
|
177
|
+
}> {
|
|
178
|
+
}
|
|
179
|
+
declare const IterationLimitError_base: new <A extends Record<string, any> = {}>(args: effect_Types.Equals<A, {}> extends true ? void : { readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }) => effect_Cause.YieldableError & {
|
|
180
|
+
readonly _tag: "IterationLimitError";
|
|
181
|
+
} & Readonly<A>;
|
|
182
|
+
declare class IterationLimitError extends IterationLimitError_base<{
|
|
183
|
+
readonly strategy: string;
|
|
184
|
+
readonly limit: number;
|
|
185
|
+
readonly stepsCompleted: number;
|
|
186
|
+
}> {
|
|
187
|
+
}
|
|
188
|
+
type ReasoningErrors = ReasoningError | StrategyNotFoundError | SelectionError | ExecutionError | IterationLimitError;
|
|
189
|
+
|
|
190
|
+
type StrategyFn = (input: {
|
|
191
|
+
readonly taskDescription: string;
|
|
192
|
+
readonly taskType: string;
|
|
193
|
+
readonly memoryContext: string;
|
|
194
|
+
readonly availableTools: readonly string[];
|
|
195
|
+
readonly config: ReasoningConfig;
|
|
196
|
+
}) => Effect.Effect<ReasoningResult, ExecutionError | IterationLimitError, LLMService>;
|
|
197
|
+
declare const StrategyRegistry_base: Context.TagClass<StrategyRegistry, "StrategyRegistry", {
|
|
198
|
+
readonly get: (name: ReasoningStrategy) => Effect.Effect<StrategyFn, StrategyNotFoundError>;
|
|
199
|
+
readonly register: (name: ReasoningStrategy, fn: StrategyFn) => Effect.Effect<void>;
|
|
200
|
+
readonly list: () => Effect.Effect<readonly ReasoningStrategy[]>;
|
|
201
|
+
}>;
|
|
202
|
+
declare class StrategyRegistry extends StrategyRegistry_base {
|
|
203
|
+
}
|
|
204
|
+
declare const StrategyRegistryLive: Layer.Layer<StrategyRegistry, never, never>;
|
|
205
|
+
|
|
206
|
+
declare const ReasoningService_base: Context.TagClass<ReasoningService, "ReasoningService", {
|
|
207
|
+
/**
|
|
208
|
+
* Execute reasoning on a task.
|
|
209
|
+
* If `strategy` is provided, uses that strategy directly.
|
|
210
|
+
* Otherwise uses the configured default strategy.
|
|
211
|
+
*/
|
|
212
|
+
readonly execute: (params: {
|
|
213
|
+
readonly taskDescription: string;
|
|
214
|
+
readonly taskType: string;
|
|
215
|
+
readonly memoryContext: string;
|
|
216
|
+
readonly availableTools: readonly string[];
|
|
217
|
+
readonly strategy?: ReasoningStrategy;
|
|
218
|
+
}) => Effect.Effect<ReasoningResult, ReasoningErrors>;
|
|
219
|
+
/** Register a custom strategy function. */
|
|
220
|
+
readonly registerStrategy: (name: ReasoningStrategy, fn: StrategyFn) => Effect.Effect<void>;
|
|
221
|
+
}>;
|
|
222
|
+
declare class ReasoningService extends ReasoningService_base {
|
|
223
|
+
}
|
|
224
|
+
declare const ReasoningServiceLive: (config?: ReasoningConfig) => Layer.Layer<ReasoningService, never, LLMService | StrategyRegistry>;
|
|
225
|
+
|
|
226
|
+
interface ReactiveInput {
|
|
227
|
+
readonly taskDescription: string;
|
|
228
|
+
readonly taskType: string;
|
|
229
|
+
readonly memoryContext: string;
|
|
230
|
+
readonly availableTools: readonly string[];
|
|
231
|
+
readonly config: ReasoningConfig;
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* ReAct loop: Thought -> Action -> Observation, iterating until done.
|
|
235
|
+
* Each iteration calls the LLM once for reasoning.
|
|
236
|
+
*/
|
|
237
|
+
declare const executeReactive: (input: ReactiveInput) => Effect.Effect<ReasoningResult, ExecutionError | IterationLimitError, LLMService>;
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Reflexion Strategy — Generate → Reflect → Improve loop.
|
|
241
|
+
*
|
|
242
|
+
* Based on the Reflexion paper (Shinn et al., 2023).
|
|
243
|
+
* The agent:
|
|
244
|
+
* 1. Generates an initial response (attempt)
|
|
245
|
+
* 2. Self-critiques the response to identify gaps/errors
|
|
246
|
+
* 3. Improves the response using the critique as feedback
|
|
247
|
+
* 4. Repeats until maxRetries reached or the critique is satisfied
|
|
248
|
+
*/
|
|
249
|
+
|
|
250
|
+
interface ReflexionInput {
|
|
251
|
+
readonly taskDescription: string;
|
|
252
|
+
readonly taskType: string;
|
|
253
|
+
readonly memoryContext: string;
|
|
254
|
+
readonly availableTools: readonly string[];
|
|
255
|
+
readonly config: ReasoningConfig;
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Reflexion: Generate → Self-Critique → Improve, repeating until satisfied
|
|
259
|
+
* or maxRetries is reached.
|
|
260
|
+
*/
|
|
261
|
+
declare const executeReflexion: (input: ReflexionInput) => Effect.Effect<ReasoningResult, ExecutionError | IterationLimitError, LLMService>;
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Create the full Reasoning layer (Phase 1: reactive only).
|
|
265
|
+
*
|
|
266
|
+
* Provides: ReasoningService, StrategyRegistry
|
|
267
|
+
* Requires: LLMService (from Layer 1.5)
|
|
268
|
+
*
|
|
269
|
+
* Usage:
|
|
270
|
+
* const ReasoningLive = createReasoningLayer();
|
|
271
|
+
* const program = myEffect.pipe(Effect.provide(ReasoningLive));
|
|
272
|
+
*/
|
|
273
|
+
declare const createReasoningLayer: (config?: ReasoningConfig) => Layer.Layer<StrategyRegistry | ReasoningService, never, _reactive_agents_llm_provider.LLMService>;
|
|
274
|
+
|
|
275
|
+
export { ExecutionError, IterationLimitError, type PlanExecuteConfig, PlanExecuteConfigSchema, type ReactiveConfig, ReactiveConfigSchema, type ReasoningConfig, ReasoningConfigSchema, ReasoningError, type ReasoningErrors, type ReasoningMetadata, ReasoningMetadataSchema, type ReasoningResult, ReasoningResultSchema, ReasoningService, ReasoningServiceLive, ReasoningStatus, type ReasoningStep, ReasoningStepSchema, type ReflexionConfig, ReflexionConfigSchema, type SelectionContext, SelectionContextSchema, SelectionError, StepId, type StepMetadata, StepMetadataSchema, StepType, type StrategyEffectiveness, StrategyEffectivenessSchema, type StrategyFn, StrategyNotFoundError, StrategyRegistry, StrategyRegistryLive, type TreeOfThoughtConfig, TreeOfThoughtConfigSchema, createReasoningLayer, defaultReasoningConfig, executeReactive, executeReflexion };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,566 @@
|
|
|
1
|
+
// src/types/step.ts
|
|
2
|
+
import { Schema } from "effect";
|
|
3
|
+
var StepId = Schema.String.pipe(Schema.brand("StepId"));
|
|
4
|
+
var StepType = Schema.Literal(
|
|
5
|
+
"thought",
|
|
6
|
+
// Thinking/reasoning
|
|
7
|
+
"action",
|
|
8
|
+
// Tool call
|
|
9
|
+
"observation",
|
|
10
|
+
// Tool result
|
|
11
|
+
"plan",
|
|
12
|
+
// Planning step
|
|
13
|
+
"reflection",
|
|
14
|
+
// Self-reflection
|
|
15
|
+
"critique"
|
|
16
|
+
// Self-critique
|
|
17
|
+
);
|
|
18
|
+
var StepMetadataSchema = Schema.Struct({
|
|
19
|
+
confidence: Schema.optional(Schema.Number),
|
|
20
|
+
toolUsed: Schema.optional(Schema.String),
|
|
21
|
+
cost: Schema.optional(Schema.Number),
|
|
22
|
+
duration: Schema.optional(Schema.Number)
|
|
23
|
+
});
|
|
24
|
+
var ReasoningStepSchema = Schema.Struct({
|
|
25
|
+
id: StepId,
|
|
26
|
+
type: StepType,
|
|
27
|
+
content: Schema.String,
|
|
28
|
+
timestamp: Schema.DateFromSelf,
|
|
29
|
+
metadata: Schema.optional(StepMetadataSchema)
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
// src/types/reasoning.ts
|
|
33
|
+
import { Schema as Schema2 } from "effect";
|
|
34
|
+
import { ReasoningStrategy } from "@reactive-agents/core";
|
|
35
|
+
var ReasoningStatus = Schema2.Literal("completed", "failed", "partial");
|
|
36
|
+
var ReasoningMetadataSchema = Schema2.Struct({
|
|
37
|
+
duration: Schema2.Number,
|
|
38
|
+
// ms
|
|
39
|
+
cost: Schema2.Number,
|
|
40
|
+
// USD
|
|
41
|
+
tokensUsed: Schema2.Number,
|
|
42
|
+
stepsCount: Schema2.Number,
|
|
43
|
+
confidence: Schema2.Number,
|
|
44
|
+
// 0-1
|
|
45
|
+
effectiveness: Schema2.optional(Schema2.Number),
|
|
46
|
+
// 0-1 (learned)
|
|
47
|
+
selectedStrategy: Schema2.optional(ReasoningStrategy)
|
|
48
|
+
// for adaptive
|
|
49
|
+
});
|
|
50
|
+
var ReasoningResultSchema = Schema2.Struct({
|
|
51
|
+
strategy: ReasoningStrategy,
|
|
52
|
+
steps: Schema2.Array(ReasoningStepSchema),
|
|
53
|
+
output: Schema2.Unknown,
|
|
54
|
+
metadata: ReasoningMetadataSchema,
|
|
55
|
+
status: ReasoningStatus
|
|
56
|
+
});
|
|
57
|
+
var SelectionContextSchema = Schema2.Struct({
|
|
58
|
+
taskDescription: Schema2.String,
|
|
59
|
+
taskType: Schema2.String,
|
|
60
|
+
complexity: Schema2.Number,
|
|
61
|
+
// 0-1
|
|
62
|
+
urgency: Schema2.Number,
|
|
63
|
+
// 0-1
|
|
64
|
+
costBudget: Schema2.optional(Schema2.Number),
|
|
65
|
+
timeConstraint: Schema2.optional(Schema2.Number),
|
|
66
|
+
// ms
|
|
67
|
+
preferredStrategy: Schema2.optional(ReasoningStrategy)
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
// src/types/effectiveness.ts
|
|
71
|
+
import { Schema as Schema3 } from "effect";
|
|
72
|
+
var StrategyEffectivenessSchema = Schema3.Struct({
|
|
73
|
+
strategy: ReasoningStrategy,
|
|
74
|
+
taskType: Schema3.String,
|
|
75
|
+
successRate: Schema3.Number,
|
|
76
|
+
// 0-1
|
|
77
|
+
avgCost: Schema3.Number,
|
|
78
|
+
avgDuration: Schema3.Number,
|
|
79
|
+
avgConfidence: Schema3.Number,
|
|
80
|
+
executions: Schema3.Number,
|
|
81
|
+
lastUsed: Schema3.DateFromSelf
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
// src/types/config.ts
|
|
85
|
+
import { Schema as Schema4 } from "effect";
|
|
86
|
+
var ReactiveConfigSchema = Schema4.Struct({
|
|
87
|
+
maxIterations: Schema4.Number.pipe(Schema4.int(), Schema4.positive()),
|
|
88
|
+
temperature: Schema4.Number
|
|
89
|
+
});
|
|
90
|
+
var PlanExecuteConfigSchema = Schema4.Struct({
|
|
91
|
+
maxRefinements: Schema4.Number.pipe(Schema4.int(), Schema4.positive()),
|
|
92
|
+
reflectionDepth: Schema4.Literal("shallow", "deep")
|
|
93
|
+
});
|
|
94
|
+
var TreeOfThoughtConfigSchema = Schema4.Struct({
|
|
95
|
+
breadth: Schema4.Number.pipe(Schema4.int(), Schema4.positive()),
|
|
96
|
+
depth: Schema4.Number.pipe(Schema4.int(), Schema4.positive()),
|
|
97
|
+
pruningThreshold: Schema4.Number
|
|
98
|
+
});
|
|
99
|
+
var ReflexionConfigSchema = Schema4.Struct({
|
|
100
|
+
maxRetries: Schema4.Number.pipe(Schema4.int(), Schema4.positive()),
|
|
101
|
+
selfCritiqueDepth: Schema4.Literal("shallow", "deep")
|
|
102
|
+
});
|
|
103
|
+
var ReasoningConfigSchema = Schema4.Struct({
|
|
104
|
+
defaultStrategy: ReasoningStrategy,
|
|
105
|
+
adaptive: Schema4.Struct({
|
|
106
|
+
enabled: Schema4.Boolean,
|
|
107
|
+
learning: Schema4.Boolean
|
|
108
|
+
}),
|
|
109
|
+
strategies: Schema4.Struct({
|
|
110
|
+
reactive: ReactiveConfigSchema,
|
|
111
|
+
planExecute: PlanExecuteConfigSchema,
|
|
112
|
+
treeOfThought: TreeOfThoughtConfigSchema,
|
|
113
|
+
reflexion: ReflexionConfigSchema
|
|
114
|
+
})
|
|
115
|
+
});
|
|
116
|
+
var defaultReasoningConfig = {
|
|
117
|
+
defaultStrategy: "reactive",
|
|
118
|
+
adaptive: { enabled: false, learning: false },
|
|
119
|
+
strategies: {
|
|
120
|
+
reactive: { maxIterations: 10, temperature: 0.7 },
|
|
121
|
+
planExecute: { maxRefinements: 2, reflectionDepth: "deep" },
|
|
122
|
+
treeOfThought: { breadth: 3, depth: 3, pruningThreshold: 0.5 },
|
|
123
|
+
reflexion: { maxRetries: 3, selfCritiqueDepth: "deep" }
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
// src/errors/errors.ts
|
|
128
|
+
import { Data } from "effect";
|
|
129
|
+
var ReasoningError = class extends Data.TaggedError("ReasoningError") {
|
|
130
|
+
};
|
|
131
|
+
var StrategyNotFoundError = class extends Data.TaggedError(
|
|
132
|
+
"StrategyNotFoundError"
|
|
133
|
+
) {
|
|
134
|
+
};
|
|
135
|
+
var SelectionError = class extends Data.TaggedError("SelectionError") {
|
|
136
|
+
};
|
|
137
|
+
var ExecutionError = class extends Data.TaggedError("ExecutionError") {
|
|
138
|
+
};
|
|
139
|
+
var IterationLimitError = class extends Data.TaggedError(
|
|
140
|
+
"IterationLimitError"
|
|
141
|
+
) {
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
// src/services/reasoning-service.ts
|
|
145
|
+
import { Context as Context2, Effect as Effect4, Layer as Layer2 } from "effect";
|
|
146
|
+
|
|
147
|
+
// src/services/strategy-registry.ts
|
|
148
|
+
import { Context, Effect as Effect3, Layer, Ref } from "effect";
|
|
149
|
+
|
|
150
|
+
// src/strategies/reactive.ts
|
|
151
|
+
import { Effect } from "effect";
|
|
152
|
+
import { ulid } from "ulid";
|
|
153
|
+
import { LLMService } from "@reactive-agents/llm-provider";
|
|
154
|
+
var executeReactive = (input) => Effect.gen(function* () {
|
|
155
|
+
const llm = yield* LLMService;
|
|
156
|
+
const maxIter = input.config.strategies.reactive.maxIterations;
|
|
157
|
+
const temp = input.config.strategies.reactive.temperature;
|
|
158
|
+
const steps = [];
|
|
159
|
+
const start = Date.now();
|
|
160
|
+
let context = buildInitialContext(input);
|
|
161
|
+
let iteration = 0;
|
|
162
|
+
let totalTokens = 0;
|
|
163
|
+
let totalCost = 0;
|
|
164
|
+
while (iteration < maxIter) {
|
|
165
|
+
const thoughtResponse = yield* llm.complete({
|
|
166
|
+
messages: [
|
|
167
|
+
{ role: "user", content: buildThoughtPrompt(context, steps) }
|
|
168
|
+
],
|
|
169
|
+
systemPrompt: `You are a reasoning agent. Task: ${input.taskDescription}`,
|
|
170
|
+
maxTokens: 300,
|
|
171
|
+
temperature: temp
|
|
172
|
+
}).pipe(
|
|
173
|
+
Effect.mapError(
|
|
174
|
+
(err) => new ExecutionError({
|
|
175
|
+
strategy: "reactive",
|
|
176
|
+
message: `LLM thought failed at iteration ${iteration}`,
|
|
177
|
+
step: iteration,
|
|
178
|
+
cause: err
|
|
179
|
+
})
|
|
180
|
+
)
|
|
181
|
+
);
|
|
182
|
+
const thought = thoughtResponse.content;
|
|
183
|
+
totalTokens += thoughtResponse.usage.totalTokens;
|
|
184
|
+
totalCost += thoughtResponse.usage.estimatedCost;
|
|
185
|
+
steps.push({
|
|
186
|
+
id: ulid(),
|
|
187
|
+
type: "thought",
|
|
188
|
+
content: thought,
|
|
189
|
+
timestamp: /* @__PURE__ */ new Date()
|
|
190
|
+
});
|
|
191
|
+
if (hasFinalAnswer(thought)) {
|
|
192
|
+
return buildResult(
|
|
193
|
+
steps,
|
|
194
|
+
thought,
|
|
195
|
+
"completed",
|
|
196
|
+
start,
|
|
197
|
+
totalTokens,
|
|
198
|
+
totalCost
|
|
199
|
+
);
|
|
200
|
+
}
|
|
201
|
+
const toolRequest = parseToolRequest(thought);
|
|
202
|
+
if (toolRequest) {
|
|
203
|
+
steps.push({
|
|
204
|
+
id: ulid(),
|
|
205
|
+
type: "action",
|
|
206
|
+
content: JSON.stringify(toolRequest),
|
|
207
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
208
|
+
metadata: { toolUsed: toolRequest.tool }
|
|
209
|
+
});
|
|
210
|
+
steps.push({
|
|
211
|
+
id: ulid(),
|
|
212
|
+
type: "observation",
|
|
213
|
+
content: `[Tool call requested: ${toolRequest.tool}(${JSON.stringify(toolRequest.input)})]`,
|
|
214
|
+
timestamp: /* @__PURE__ */ new Date()
|
|
215
|
+
});
|
|
216
|
+
context = appendToContext(context, thought);
|
|
217
|
+
}
|
|
218
|
+
iteration++;
|
|
219
|
+
}
|
|
220
|
+
return buildResult(steps, null, "partial", start, totalTokens, totalCost);
|
|
221
|
+
});
|
|
222
|
+
function buildInitialContext(input) {
|
|
223
|
+
return [
|
|
224
|
+
`Task: ${input.taskDescription}`,
|
|
225
|
+
`Task Type: ${input.taskType}`,
|
|
226
|
+
`Relevant Memory:
|
|
227
|
+
${input.memoryContext}`,
|
|
228
|
+
`Available Tools: ${input.availableTools.join(", ")}`
|
|
229
|
+
].join("\n\n");
|
|
230
|
+
}
|
|
231
|
+
function buildThoughtPrompt(context, history) {
|
|
232
|
+
const historyStr = history.map((s) => `[${s.type}] ${s.content}`).join("\n");
|
|
233
|
+
return `${context}
|
|
234
|
+
|
|
235
|
+
Previous steps:
|
|
236
|
+
${historyStr}
|
|
237
|
+
|
|
238
|
+
Think step-by-step. If you need a tool, respond with "ACTION: tool_name(input)". If you have a final answer, respond with "FINAL ANSWER: ...".`;
|
|
239
|
+
}
|
|
240
|
+
function hasFinalAnswer(thought) {
|
|
241
|
+
return /final answer:/i.test(thought);
|
|
242
|
+
}
|
|
243
|
+
function parseToolRequest(thought) {
|
|
244
|
+
const match = thought.match(/ACTION:\s*(\w+)\((.+?)\)/i);
|
|
245
|
+
return match ? { tool: match[1], input: match[2] } : null;
|
|
246
|
+
}
|
|
247
|
+
function appendToContext(context, addition) {
|
|
248
|
+
return `${context}
|
|
249
|
+
|
|
250
|
+
${addition}`;
|
|
251
|
+
}
|
|
252
|
+
function buildResult(steps, output, status, startMs, tokensUsed, cost) {
|
|
253
|
+
return {
|
|
254
|
+
strategy: "reactive",
|
|
255
|
+
steps: [...steps],
|
|
256
|
+
output,
|
|
257
|
+
metadata: {
|
|
258
|
+
duration: Date.now() - startMs,
|
|
259
|
+
cost,
|
|
260
|
+
tokensUsed,
|
|
261
|
+
stepsCount: steps.length,
|
|
262
|
+
confidence: status === "completed" ? 0.8 : 0.4
|
|
263
|
+
},
|
|
264
|
+
status
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// src/strategies/reflexion.ts
|
|
269
|
+
import { Effect as Effect2 } from "effect";
|
|
270
|
+
import { ulid as ulid2 } from "ulid";
|
|
271
|
+
import { LLMService as LLMService2 } from "@reactive-agents/llm-provider";
|
|
272
|
+
var executeReflexion = (input) => Effect2.gen(function* () {
|
|
273
|
+
const llm = yield* LLMService2;
|
|
274
|
+
const { maxRetries, selfCritiqueDepth } = input.config.strategies.reflexion;
|
|
275
|
+
const steps = [];
|
|
276
|
+
const start = Date.now();
|
|
277
|
+
let totalTokens = 0;
|
|
278
|
+
let totalCost = 0;
|
|
279
|
+
let attempt = 0;
|
|
280
|
+
let previousCritiques = [];
|
|
281
|
+
const initialResponse = yield* llm.complete({
|
|
282
|
+
messages: [
|
|
283
|
+
{
|
|
284
|
+
role: "user",
|
|
285
|
+
content: buildGenerationPrompt(input, null)
|
|
286
|
+
}
|
|
287
|
+
],
|
|
288
|
+
systemPrompt: buildSystemPrompt(input.taskDescription),
|
|
289
|
+
maxTokens: selfCritiqueDepth === "deep" ? 800 : 500,
|
|
290
|
+
temperature: 0.7
|
|
291
|
+
}).pipe(
|
|
292
|
+
Effect2.mapError(
|
|
293
|
+
(err) => new ExecutionError({
|
|
294
|
+
strategy: "reflexion",
|
|
295
|
+
message: "Initial generation failed",
|
|
296
|
+
step: 0,
|
|
297
|
+
cause: err
|
|
298
|
+
})
|
|
299
|
+
)
|
|
300
|
+
);
|
|
301
|
+
let currentResponse = initialResponse.content;
|
|
302
|
+
totalTokens += initialResponse.usage.totalTokens;
|
|
303
|
+
totalCost += initialResponse.usage.estimatedCost;
|
|
304
|
+
steps.push({
|
|
305
|
+
id: ulid2(),
|
|
306
|
+
type: "thought",
|
|
307
|
+
content: `[ATTEMPT 1] ${currentResponse}`,
|
|
308
|
+
timestamp: /* @__PURE__ */ new Date()
|
|
309
|
+
});
|
|
310
|
+
while (attempt < maxRetries) {
|
|
311
|
+
attempt++;
|
|
312
|
+
const critiqueResponse = yield* llm.complete({
|
|
313
|
+
messages: [
|
|
314
|
+
{
|
|
315
|
+
role: "user",
|
|
316
|
+
content: buildCritiquePrompt(
|
|
317
|
+
input.taskDescription,
|
|
318
|
+
currentResponse,
|
|
319
|
+
selfCritiqueDepth,
|
|
320
|
+
previousCritiques
|
|
321
|
+
)
|
|
322
|
+
}
|
|
323
|
+
],
|
|
324
|
+
systemPrompt: "You are a critical evaluator. Analyze responses for accuracy, completeness, and quality.",
|
|
325
|
+
maxTokens: selfCritiqueDepth === "deep" ? 600 : 300,
|
|
326
|
+
temperature: 0.3
|
|
327
|
+
// low temp for objective critique
|
|
328
|
+
}).pipe(
|
|
329
|
+
Effect2.mapError(
|
|
330
|
+
(err) => new ExecutionError({
|
|
331
|
+
strategy: "reflexion",
|
|
332
|
+
message: `Self-critique failed at attempt ${attempt}`,
|
|
333
|
+
step: attempt,
|
|
334
|
+
cause: err
|
|
335
|
+
})
|
|
336
|
+
)
|
|
337
|
+
);
|
|
338
|
+
const critique = critiqueResponse.content;
|
|
339
|
+
totalTokens += critiqueResponse.usage.totalTokens;
|
|
340
|
+
totalCost += critiqueResponse.usage.estimatedCost;
|
|
341
|
+
steps.push({
|
|
342
|
+
id: ulid2(),
|
|
343
|
+
type: "observation",
|
|
344
|
+
content: `[CRITIQUE ${attempt}] ${critique}`,
|
|
345
|
+
timestamp: /* @__PURE__ */ new Date()
|
|
346
|
+
});
|
|
347
|
+
if (isSatisfied(critique)) {
|
|
348
|
+
return buildResult2(
|
|
349
|
+
steps,
|
|
350
|
+
currentResponse,
|
|
351
|
+
"completed",
|
|
352
|
+
start,
|
|
353
|
+
totalTokens,
|
|
354
|
+
totalCost,
|
|
355
|
+
attempt
|
|
356
|
+
);
|
|
357
|
+
}
|
|
358
|
+
previousCritiques.push(critique);
|
|
359
|
+
const improvedResponse = yield* llm.complete({
|
|
360
|
+
messages: [
|
|
361
|
+
{
|
|
362
|
+
role: "user",
|
|
363
|
+
content: buildGenerationPrompt(input, previousCritiques)
|
|
364
|
+
}
|
|
365
|
+
],
|
|
366
|
+
systemPrompt: buildSystemPrompt(input.taskDescription),
|
|
367
|
+
maxTokens: selfCritiqueDepth === "deep" ? 800 : 500,
|
|
368
|
+
temperature: 0.6
|
|
369
|
+
}).pipe(
|
|
370
|
+
Effect2.mapError(
|
|
371
|
+
(err) => new ExecutionError({
|
|
372
|
+
strategy: "reflexion",
|
|
373
|
+
message: `Improvement generation failed at attempt ${attempt}`,
|
|
374
|
+
step: attempt,
|
|
375
|
+
cause: err
|
|
376
|
+
})
|
|
377
|
+
)
|
|
378
|
+
);
|
|
379
|
+
currentResponse = improvedResponse.content;
|
|
380
|
+
totalTokens += improvedResponse.usage.totalTokens;
|
|
381
|
+
totalCost += improvedResponse.usage.estimatedCost;
|
|
382
|
+
steps.push({
|
|
383
|
+
id: ulid2(),
|
|
384
|
+
type: "thought",
|
|
385
|
+
content: `[ATTEMPT ${attempt + 1}] ${currentResponse}`,
|
|
386
|
+
timestamp: /* @__PURE__ */ new Date()
|
|
387
|
+
});
|
|
388
|
+
}
|
|
389
|
+
return buildResult2(
|
|
390
|
+
steps,
|
|
391
|
+
currentResponse,
|
|
392
|
+
"partial",
|
|
393
|
+
start,
|
|
394
|
+
totalTokens,
|
|
395
|
+
totalCost,
|
|
396
|
+
attempt
|
|
397
|
+
);
|
|
398
|
+
});
|
|
399
|
+
function buildSystemPrompt(taskDescription) {
|
|
400
|
+
return `You are a thoughtful reasoning agent. Your task is: ${taskDescription}
|
|
401
|
+
Provide clear, accurate, and complete responses.`;
|
|
402
|
+
}
|
|
403
|
+
function buildGenerationPrompt(input, previousCritiques) {
|
|
404
|
+
const parts = [
|
|
405
|
+
`Task: ${input.taskDescription}`,
|
|
406
|
+
`Task Type: ${input.taskType}`
|
|
407
|
+
];
|
|
408
|
+
if (input.memoryContext) {
|
|
409
|
+
parts.push(`Relevant Context:
|
|
410
|
+
${input.memoryContext}`);
|
|
411
|
+
}
|
|
412
|
+
if (previousCritiques && previousCritiques.length > 0) {
|
|
413
|
+
parts.push(
|
|
414
|
+
`Previous attempts had these issues:
|
|
415
|
+
${previousCritiques.map((c, i) => `${i + 1}. ${c}`).join("\n")}
|
|
416
|
+
|
|
417
|
+
Please address all of these issues in your improved response.`
|
|
418
|
+
);
|
|
419
|
+
}
|
|
420
|
+
parts.push(
|
|
421
|
+
"Provide a thorough and accurate response to the task above."
|
|
422
|
+
);
|
|
423
|
+
return parts.join("\n\n");
|
|
424
|
+
}
|
|
425
|
+
function buildCritiquePrompt(taskDescription, response, depth, previousCritiques) {
|
|
426
|
+
const deepInstructions = depth === "deep" ? "\n- Check for logical consistency and coherence\n- Identify any unsupported claims or assumptions\n- Assess whether all aspects of the task are addressed" : "";
|
|
427
|
+
const prevCritiqueNote = previousCritiques.length > 0 ? `
|
|
428
|
+
|
|
429
|
+
Previous critiques identified these issues:
|
|
430
|
+
${previousCritiques.map((c, i) => `${i + 1}. ${c}`).join("\n")}
|
|
431
|
+
|
|
432
|
+
Focus on whether the new response adequately addresses these.` : "";
|
|
433
|
+
return `Task: ${taskDescription}
|
|
434
|
+
|
|
435
|
+
Response to evaluate:
|
|
436
|
+
${response}
|
|
437
|
+
|
|
438
|
+
Critically evaluate this response. Identify:
|
|
439
|
+
- Factual errors or inaccuracies
|
|
440
|
+
- Missing information or incomplete answers
|
|
441
|
+
- Unclear or ambiguous statements${deepInstructions}${prevCritiqueNote}
|
|
442
|
+
|
|
443
|
+
If the response is accurate and complete, start your critique with "SATISFIED:".
|
|
444
|
+
Otherwise, clearly list the specific issues that need to be fixed.`;
|
|
445
|
+
}
|
|
446
|
+
function isSatisfied(critique) {
|
|
447
|
+
return /^SATISFIED:/i.test(critique.trim());
|
|
448
|
+
}
|
|
449
|
+
function buildResult2(steps, output, status, startMs, tokensUsed, cost, iterations) {
|
|
450
|
+
const maxNormal = 3;
|
|
451
|
+
const confidence = status === "completed" ? Math.max(0.6, 1 - iterations / maxNormal * 0.3) : 0.4;
|
|
452
|
+
return {
|
|
453
|
+
strategy: "reflexion",
|
|
454
|
+
steps: [...steps],
|
|
455
|
+
output,
|
|
456
|
+
metadata: {
|
|
457
|
+
duration: Date.now() - startMs,
|
|
458
|
+
cost,
|
|
459
|
+
tokensUsed,
|
|
460
|
+
stepsCount: steps.length,
|
|
461
|
+
confidence
|
|
462
|
+
},
|
|
463
|
+
status
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// src/services/strategy-registry.ts
|
|
468
|
+
var StrategyRegistry = class extends Context.Tag("StrategyRegistry")() {
|
|
469
|
+
};
|
|
470
|
+
var StrategyRegistryLive = Layer.effect(
|
|
471
|
+
StrategyRegistry,
|
|
472
|
+
Effect3.gen(function* () {
|
|
473
|
+
const registryRef = yield* Ref.make(
|
|
474
|
+
/* @__PURE__ */ new Map([
|
|
475
|
+
["reactive", executeReactive],
|
|
476
|
+
["reflexion", executeReflexion]
|
|
477
|
+
])
|
|
478
|
+
);
|
|
479
|
+
return {
|
|
480
|
+
get: (name) => Effect3.gen(function* () {
|
|
481
|
+
const registry = yield* Ref.get(registryRef);
|
|
482
|
+
const fn = registry.get(name);
|
|
483
|
+
if (!fn) {
|
|
484
|
+
return yield* Effect3.fail(
|
|
485
|
+
new StrategyNotFoundError({ strategy: name })
|
|
486
|
+
);
|
|
487
|
+
}
|
|
488
|
+
return fn;
|
|
489
|
+
}),
|
|
490
|
+
register: (name, fn) => Ref.update(registryRef, (m) => {
|
|
491
|
+
const next = new Map(m);
|
|
492
|
+
next.set(name, fn);
|
|
493
|
+
return next;
|
|
494
|
+
}),
|
|
495
|
+
list: () => Ref.get(registryRef).pipe(
|
|
496
|
+
Effect3.map((m) => Array.from(m.keys()))
|
|
497
|
+
)
|
|
498
|
+
};
|
|
499
|
+
})
|
|
500
|
+
);
|
|
501
|
+
|
|
502
|
+
// src/services/reasoning-service.ts
|
|
503
|
+
import { LLMService as LLMService3 } from "@reactive-agents/llm-provider";
|
|
504
|
+
var ReasoningService = class extends Context2.Tag("ReasoningService")() {
|
|
505
|
+
};
|
|
506
|
+
var ReasoningServiceLive = (config = defaultReasoningConfig) => Layer2.effect(
|
|
507
|
+
ReasoningService,
|
|
508
|
+
Effect4.gen(function* () {
|
|
509
|
+
const registry = yield* StrategyRegistry;
|
|
510
|
+
const llmService = yield* LLMService3;
|
|
511
|
+
const llmLayer = Layer2.succeed(LLMService3, llmService);
|
|
512
|
+
return {
|
|
513
|
+
execute: (params) => Effect4.gen(function* () {
|
|
514
|
+
const strategyName = params.strategy ?? config.defaultStrategy;
|
|
515
|
+
const strategyFn = yield* registry.get(strategyName);
|
|
516
|
+
const result = yield* strategyFn({
|
|
517
|
+
...params,
|
|
518
|
+
config
|
|
519
|
+
}).pipe(Effect4.provide(llmLayer));
|
|
520
|
+
return result;
|
|
521
|
+
}),
|
|
522
|
+
registerStrategy: (name, fn) => registry.register(name, fn)
|
|
523
|
+
};
|
|
524
|
+
})
|
|
525
|
+
);
|
|
526
|
+
|
|
527
|
+
// src/runtime.ts
|
|
528
|
+
import { Layer as Layer3 } from "effect";
|
|
529
|
+
var createReasoningLayer = (config = defaultReasoningConfig) => {
|
|
530
|
+
const RegistryLayer = StrategyRegistryLive;
|
|
531
|
+
const ServiceLayer = ReasoningServiceLive(config).pipe(
|
|
532
|
+
Layer3.provide(RegistryLayer)
|
|
533
|
+
);
|
|
534
|
+
return Layer3.mergeAll(ServiceLayer, RegistryLayer);
|
|
535
|
+
};
|
|
536
|
+
export {
|
|
537
|
+
ExecutionError,
|
|
538
|
+
IterationLimitError,
|
|
539
|
+
PlanExecuteConfigSchema,
|
|
540
|
+
ReactiveConfigSchema,
|
|
541
|
+
ReasoningConfigSchema,
|
|
542
|
+
ReasoningError,
|
|
543
|
+
ReasoningMetadataSchema,
|
|
544
|
+
ReasoningResultSchema,
|
|
545
|
+
ReasoningService,
|
|
546
|
+
ReasoningServiceLive,
|
|
547
|
+
ReasoningStatus,
|
|
548
|
+
ReasoningStepSchema,
|
|
549
|
+
ReasoningStrategy,
|
|
550
|
+
ReflexionConfigSchema,
|
|
551
|
+
SelectionContextSchema,
|
|
552
|
+
SelectionError,
|
|
553
|
+
StepId,
|
|
554
|
+
StepMetadataSchema,
|
|
555
|
+
StepType,
|
|
556
|
+
StrategyEffectivenessSchema,
|
|
557
|
+
StrategyNotFoundError,
|
|
558
|
+
StrategyRegistry,
|
|
559
|
+
StrategyRegistryLive,
|
|
560
|
+
TreeOfThoughtConfigSchema,
|
|
561
|
+
createReasoningLayer,
|
|
562
|
+
defaultReasoningConfig,
|
|
563
|
+
executeReactive,
|
|
564
|
+
executeReflexion
|
|
565
|
+
};
|
|
566
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/types/step.ts","../src/types/reasoning.ts","../src/types/effectiveness.ts","../src/types/config.ts","../src/errors/errors.ts","../src/services/reasoning-service.ts","../src/services/strategy-registry.ts","../src/strategies/reactive.ts","../src/strategies/reflexion.ts","../src/runtime.ts"],"sourcesContent":["// File: src/types/step.ts\nimport { Schema } from \"effect\";\n\n// ─── Step ID (branded string) ───\n\nexport const StepId = Schema.String.pipe(Schema.brand(\"StepId\"));\nexport type StepId = typeof StepId.Type;\n\n// ─── Step Type ───\n\nexport const StepType = Schema.Literal(\n \"thought\", // Thinking/reasoning\n \"action\", // Tool call\n \"observation\", // Tool result\n \"plan\", // Planning step\n \"reflection\", // Self-reflection\n \"critique\", // Self-critique\n);\nexport type StepType = typeof StepType.Type;\n\n// ─── Step Metadata ───\n\nexport const StepMetadataSchema = Schema.Struct({\n confidence: Schema.optional(Schema.Number),\n toolUsed: Schema.optional(Schema.String),\n cost: Schema.optional(Schema.Number),\n duration: Schema.optional(Schema.Number),\n});\nexport type StepMetadata = typeof StepMetadataSchema.Type;\n\n// ─── Reasoning Step ───\n\nexport const ReasoningStepSchema = Schema.Struct({\n id: StepId,\n type: StepType,\n content: Schema.String,\n timestamp: Schema.DateFromSelf,\n metadata: Schema.optional(StepMetadataSchema),\n});\nexport type ReasoningStep = typeof ReasoningStepSchema.Type;\n","// File: src/types/reasoning.ts\nimport { Schema } from \"effect\";\nimport { ReasoningStepSchema } from \"./step.js\";\n\n// ─── Reasoning Strategy ───\n// Canonical definition lives in @reactive-agents/core.\n// Re-export here so downstream reasoning code can import from either package.\nimport { ReasoningStrategy } from \"@reactive-agents/core\";\nexport { ReasoningStrategy };\n\n// ─── Result Status ───\n\nexport const ReasoningStatus = Schema.Literal(\"completed\", \"failed\", \"partial\");\nexport type ReasoningStatus = typeof ReasoningStatus.Type;\n\n// ─── Reasoning Metadata ───\n\nexport const ReasoningMetadataSchema = Schema.Struct({\n duration: Schema.Number, // ms\n cost: Schema.Number, // USD\n tokensUsed: Schema.Number,\n stepsCount: Schema.Number,\n confidence: Schema.Number, // 0-1\n effectiveness: Schema.optional(Schema.Number), // 0-1 (learned)\n selectedStrategy: Schema.optional(ReasoningStrategy), // for adaptive\n});\nexport type ReasoningMetadata = typeof ReasoningMetadataSchema.Type;\n\n// ─── Reasoning Result ───\n\nexport const ReasoningResultSchema = Schema.Struct({\n strategy: ReasoningStrategy,\n steps: Schema.Array(ReasoningStepSchema),\n output: Schema.Unknown,\n metadata: ReasoningMetadataSchema,\n status: ReasoningStatus,\n});\nexport type ReasoningResult = typeof ReasoningResultSchema.Type;\n\n// ─── Selection Context ───\n\nexport const SelectionContextSchema = Schema.Struct({\n taskDescription: Schema.String,\n taskType: Schema.String,\n complexity: Schema.Number, // 0-1\n urgency: Schema.Number, // 0-1\n costBudget: Schema.optional(Schema.Number),\n timeConstraint: Schema.optional(Schema.Number), // ms\n preferredStrategy: Schema.optional(ReasoningStrategy),\n});\nexport type SelectionContext = typeof SelectionContextSchema.Type;\n","// File: src/types/effectiveness.ts\nimport { Schema } from \"effect\";\nimport { ReasoningStrategy } from \"./reasoning.js\";\n\n// ─── Strategy Effectiveness Record ───\n\nexport const StrategyEffectivenessSchema = Schema.Struct({\n strategy: ReasoningStrategy,\n taskType: Schema.String,\n successRate: Schema.Number, // 0-1\n avgCost: Schema.Number,\n avgDuration: Schema.Number,\n avgConfidence: Schema.Number,\n executions: Schema.Number,\n lastUsed: Schema.DateFromSelf,\n});\nexport type StrategyEffectiveness = typeof StrategyEffectivenessSchema.Type;\n","// File: src/types/config.ts\nimport { Schema } from \"effect\";\nimport { ReasoningStrategy } from \"./reasoning.js\";\n\n// ─── Per-Strategy Configuration ───\n\nexport const ReactiveConfigSchema = Schema.Struct({\n maxIterations: Schema.Number.pipe(Schema.int(), Schema.positive()),\n temperature: Schema.Number,\n});\nexport type ReactiveConfig = typeof ReactiveConfigSchema.Type;\n\nexport const PlanExecuteConfigSchema = Schema.Struct({\n maxRefinements: Schema.Number.pipe(Schema.int(), Schema.positive()),\n reflectionDepth: Schema.Literal(\"shallow\", \"deep\"),\n});\nexport type PlanExecuteConfig = typeof PlanExecuteConfigSchema.Type;\n\nexport const TreeOfThoughtConfigSchema = Schema.Struct({\n breadth: Schema.Number.pipe(Schema.int(), Schema.positive()),\n depth: Schema.Number.pipe(Schema.int(), Schema.positive()),\n pruningThreshold: Schema.Number,\n});\nexport type TreeOfThoughtConfig = typeof TreeOfThoughtConfigSchema.Type;\n\nexport const ReflexionConfigSchema = Schema.Struct({\n maxRetries: Schema.Number.pipe(Schema.int(), Schema.positive()),\n selfCritiqueDepth: Schema.Literal(\"shallow\", \"deep\"),\n});\nexport type ReflexionConfig = typeof ReflexionConfigSchema.Type;\n\n// ─── Full Reasoning Config ───\n\nexport const ReasoningConfigSchema = Schema.Struct({\n defaultStrategy: ReasoningStrategy,\n adaptive: Schema.Struct({\n enabled: Schema.Boolean,\n learning: Schema.Boolean,\n }),\n strategies: Schema.Struct({\n reactive: ReactiveConfigSchema,\n planExecute: PlanExecuteConfigSchema,\n treeOfThought: TreeOfThoughtConfigSchema,\n reflexion: ReflexionConfigSchema,\n }),\n});\nexport type ReasoningConfig = typeof ReasoningConfigSchema.Type;\n\n// ─── Default Config ───\n\nexport const defaultReasoningConfig: ReasoningConfig = {\n defaultStrategy: \"reactive\",\n adaptive: { enabled: false, learning: false },\n strategies: {\n reactive: { maxIterations: 10, temperature: 0.7 },\n planExecute: { maxRefinements: 2, reflectionDepth: \"deep\" },\n treeOfThought: { breadth: 3, depth: 3, pruningThreshold: 0.5 },\n reflexion: { maxRetries: 3, selfCritiqueDepth: \"deep\" },\n },\n};\n","// File: src/errors/errors.ts\nimport { Data } from \"effect\";\n\n// ─── Base reasoning error ───\nexport class ReasoningError extends Data.TaggedError(\"ReasoningError\")<{\n readonly message: string;\n readonly cause?: unknown;\n}> {}\n\n// ─── Strategy not found in registry ───\nexport class StrategyNotFoundError extends Data.TaggedError(\n \"StrategyNotFoundError\",\n)<{\n readonly strategy: string;\n}> {}\n\n// ─── Strategy selection failed ───\nexport class SelectionError extends Data.TaggedError(\"SelectionError\")<{\n readonly message: string;\n readonly context?: unknown;\n}> {}\n\n// ─── Strategy execution failed ───\nexport class ExecutionError extends Data.TaggedError(\"ExecutionError\")<{\n readonly strategy: string;\n readonly message: string;\n readonly step?: number;\n readonly cause?: unknown;\n}> {}\n\n// ─── Max iterations / depth exceeded ───\nexport class IterationLimitError extends Data.TaggedError(\n \"IterationLimitError\",\n)<{\n readonly strategy: string;\n readonly limit: number;\n readonly stepsCompleted: number;\n}> {}\n\n// ─── Union type for service signatures ───\nexport type ReasoningErrors =\n | ReasoningError\n | StrategyNotFoundError\n | SelectionError\n | ExecutionError\n | IterationLimitError;\n","// File: src/services/reasoning-service.ts\nimport { Context, Effect, Layer } from \"effect\";\nimport type {\n ReasoningResult,\n ReasoningStrategy,\n} from \"../types/index.js\";\nimport type { ReasoningConfig } from \"../types/config.js\";\nimport { defaultReasoningConfig } from \"../types/config.js\";\nimport { StrategyRegistry, type StrategyFn } from \"./strategy-registry.js\";\nimport type { ReasoningErrors } from \"../errors/errors.js\";\nimport { LLMService } from \"@reactive-agents/llm-provider\";\n\n// ─── Service Tag ───\n\nexport class ReasoningService extends Context.Tag(\"ReasoningService\")<\n ReasoningService,\n {\n /**\n * Execute reasoning on a task.\n * If `strategy` is provided, uses that strategy directly.\n * Otherwise uses the configured default strategy.\n */\n readonly execute: (params: {\n readonly taskDescription: string;\n readonly taskType: string;\n readonly memoryContext: string;\n readonly availableTools: readonly string[];\n readonly strategy?: ReasoningStrategy;\n }) => Effect.Effect<ReasoningResult, ReasoningErrors>;\n\n /** Register a custom strategy function. */\n readonly registerStrategy: (\n name: ReasoningStrategy,\n fn: StrategyFn,\n ) => Effect.Effect<void>;\n }\n>() {}\n\n// ─── Live Layer ───\n// Requires: StrategyRegistry, LLMService\n\nexport const ReasoningServiceLive = (\n config: ReasoningConfig = defaultReasoningConfig,\n) =>\n Layer.effect(\n ReasoningService,\n Effect.gen(function* () {\n const registry = yield* StrategyRegistry;\n // Capture LLMService at layer construction time so we can provide\n // it to strategy functions when executing them.\n const llmService = yield* LLMService;\n const llmLayer = Layer.succeed(LLMService, llmService);\n\n return {\n execute: (params) =>\n Effect.gen(function* () {\n // ── Determine which strategy to use ──\n const strategyName: ReasoningStrategy =\n params.strategy ?? config.defaultStrategy;\n\n // ── Get strategy function from registry ──\n const strategyFn = yield* registry.get(strategyName);\n\n // ── Execute strategy, providing LLMService ──\n const result = yield* strategyFn({\n ...params,\n config,\n }).pipe(Effect.provide(llmLayer));\n\n return result;\n }),\n\n registerStrategy: (name, fn) => registry.register(name, fn),\n };\n }),\n );\n","// File: src/services/strategy-registry.ts\nimport { Context, Effect, Layer, Ref } from \"effect\";\nimport type { ReasoningResult, ReasoningStrategy } from \"../types/index.js\";\nimport type { ReasoningConfig } from \"../types/config.js\";\nimport {\n StrategyNotFoundError,\n type ExecutionError,\n type IterationLimitError,\n} from \"../errors/errors.js\";\nimport type { LLMService } from \"@reactive-agents/llm-provider\";\nimport { executeReactive } from \"../strategies/reactive.js\";\nimport { executeReflexion } from \"../strategies/reflexion.js\";\n\n// ─── Strategy function type ───\n\nexport type StrategyFn = (input: {\n readonly taskDescription: string;\n readonly taskType: string;\n readonly memoryContext: string;\n readonly availableTools: readonly string[];\n readonly config: ReasoningConfig;\n}) => Effect.Effect<\n ReasoningResult,\n ExecutionError | IterationLimitError,\n LLMService\n>;\n\n// ─── Service Tag ───\n\nexport class StrategyRegistry extends Context.Tag(\"StrategyRegistry\")<\n StrategyRegistry,\n {\n readonly get: (\n name: ReasoningStrategy,\n ) => Effect.Effect<StrategyFn, StrategyNotFoundError>;\n\n readonly register: (\n name: ReasoningStrategy,\n fn: StrategyFn,\n ) => Effect.Effect<void>;\n\n readonly list: () => Effect.Effect<readonly ReasoningStrategy[]>;\n }\n>() {}\n\n// ─── Live Layer (Phase 1: reactive only) ───\n\nexport const StrategyRegistryLive = Layer.effect(\n StrategyRegistry,\n Effect.gen(function* () {\n // Ref-based mutable map of strategies\n const registryRef = yield* Ref.make<Map<string, StrategyFn>>(\n new Map<string, StrategyFn>([\n [\"reactive\", executeReactive],\n [\"reflexion\", executeReflexion],\n ]),\n );\n\n return {\n get: (name) =>\n Effect.gen(function* () {\n const registry = yield* Ref.get(registryRef);\n const fn = registry.get(name);\n if (!fn) {\n return yield* Effect.fail(\n new StrategyNotFoundError({ strategy: name }),\n );\n }\n return fn;\n }),\n\n register: (name, fn) =>\n Ref.update(registryRef, (m) => {\n const next = new Map(m);\n next.set(name, fn);\n return next;\n }),\n\n list: () =>\n Ref.get(registryRef).pipe(\n Effect.map((m) => Array.from(m.keys()) as ReasoningStrategy[]),\n ),\n };\n }),\n);\n","// File: src/strategies/reactive.ts\nimport { Effect } from \"effect\";\nimport { ulid } from \"ulid\";\nimport type { ReasoningResult, ReasoningStep } from \"../types/index.js\";\nimport type { StepId } from \"../types/step.js\";\nimport { ExecutionError, IterationLimitError } from \"../errors/errors.js\";\nimport type { ReasoningConfig } from \"../types/config.js\";\nimport { LLMService } from \"@reactive-agents/llm-provider\";\n\ninterface ReactiveInput {\n readonly taskDescription: string;\n readonly taskType: string;\n readonly memoryContext: string;\n readonly availableTools: readonly string[];\n readonly config: ReasoningConfig;\n}\n\n/**\n * ReAct loop: Thought -> Action -> Observation, iterating until done.\n * Each iteration calls the LLM once for reasoning.\n */\nexport const executeReactive = (\n input: ReactiveInput,\n): Effect.Effect<\n ReasoningResult,\n ExecutionError | IterationLimitError,\n LLMService\n> =>\n Effect.gen(function* () {\n const llm = yield* LLMService;\n const maxIter = input.config.strategies.reactive.maxIterations;\n const temp = input.config.strategies.reactive.temperature;\n const steps: ReasoningStep[] = [];\n const start = Date.now();\n\n let context = buildInitialContext(input);\n let iteration = 0;\n let totalTokens = 0;\n let totalCost = 0;\n\n while (iteration < maxIter) {\n // ── THOUGHT ──\n const thoughtResponse = yield* llm\n .complete({\n messages: [\n { role: \"user\", content: buildThoughtPrompt(context, steps) },\n ],\n systemPrompt: `You are a reasoning agent. Task: ${input.taskDescription}`,\n maxTokens: 300,\n temperature: temp,\n })\n .pipe(\n Effect.mapError(\n (err) =>\n new ExecutionError({\n strategy: \"reactive\",\n message: `LLM thought failed at iteration ${iteration}`,\n step: iteration,\n cause: err,\n }),\n ),\n );\n\n const thought = thoughtResponse.content;\n totalTokens += thoughtResponse.usage.totalTokens;\n totalCost += thoughtResponse.usage.estimatedCost;\n\n steps.push({\n id: ulid() as StepId,\n type: \"thought\",\n content: thought,\n timestamp: new Date(),\n });\n\n // ── CHECK: does the thought indicate a final answer? ──\n if (hasFinalAnswer(thought)) {\n return buildResult(\n steps,\n thought,\n \"completed\",\n start,\n totalTokens,\n totalCost,\n );\n }\n\n // ── ACTION: does the thought request a tool call? ──\n const toolRequest = parseToolRequest(thought);\n if (toolRequest) {\n steps.push({\n id: ulid() as StepId,\n type: \"action\",\n content: JSON.stringify(toolRequest),\n timestamp: new Date(),\n metadata: { toolUsed: toolRequest.tool },\n });\n\n // Tool execution is deferred to the caller (ReasoningService) via a\n // placeholder observation. The service orchestrates tool calls through\n // the ToolService from Layer 8. Here, we note the request and continue.\n steps.push({\n id: ulid() as StepId,\n type: \"observation\",\n content: `[Tool call requested: ${toolRequest.tool}(${JSON.stringify(toolRequest.input)})]`,\n timestamp: new Date(),\n });\n\n // Update context with tool request for next iteration\n context = appendToContext(context, thought);\n }\n\n iteration++;\n }\n\n // Max iterations reached — return partial result\n return buildResult(steps, null, \"partial\", start, totalTokens, totalCost);\n });\n\n// ─── Helpers (private to module) ───\n\nfunction buildInitialContext(input: ReactiveInput): string {\n return [\n `Task: ${input.taskDescription}`,\n `Task Type: ${input.taskType}`,\n `Relevant Memory:\\n${input.memoryContext}`,\n `Available Tools: ${input.availableTools.join(\", \")}`,\n ].join(\"\\n\\n\");\n}\n\nfunction buildThoughtPrompt(\n context: string,\n history: readonly ReasoningStep[],\n): string {\n const historyStr = history.map((s) => `[${s.type}] ${s.content}`).join(\"\\n\");\n return `${context}\\n\\nPrevious steps:\\n${historyStr}\\n\\nThink step-by-step. If you need a tool, respond with \"ACTION: tool_name(input)\". If you have a final answer, respond with \"FINAL ANSWER: ...\".`;\n}\n\nfunction hasFinalAnswer(thought: string): boolean {\n return /final answer:/i.test(thought);\n}\n\nfunction parseToolRequest(\n thought: string,\n): { tool: string; input: string } | null {\n const match = thought.match(/ACTION:\\s*(\\w+)\\((.+?)\\)/i);\n return match ? { tool: match[1], input: match[2] } : null;\n}\n\nfunction appendToContext(context: string, addition: string): string {\n return `${context}\\n\\n${addition}`;\n}\n\nfunction buildResult(\n steps: readonly ReasoningStep[],\n output: unknown,\n status: \"completed\" | \"partial\",\n startMs: number,\n tokensUsed: number,\n cost: number,\n): ReasoningResult {\n return {\n strategy: \"reactive\",\n steps: [...steps],\n output,\n metadata: {\n duration: Date.now() - startMs,\n cost,\n tokensUsed,\n stepsCount: steps.length,\n confidence: status === \"completed\" ? 0.8 : 0.4,\n },\n status,\n };\n}\n","// File: src/strategies/reflexion.ts\n/**\n * Reflexion Strategy — Generate → Reflect → Improve loop.\n *\n * Based on the Reflexion paper (Shinn et al., 2023).\n * The agent:\n * 1. Generates an initial response (attempt)\n * 2. Self-critiques the response to identify gaps/errors\n * 3. Improves the response using the critique as feedback\n * 4. Repeats until maxRetries reached or the critique is satisfied\n */\nimport { Effect } from \"effect\";\nimport { ulid } from \"ulid\";\nimport type { ReasoningResult, ReasoningStep } from \"../types/index.js\";\nimport type { StepId } from \"../types/step.js\";\nimport { ExecutionError, IterationLimitError } from \"../errors/errors.js\";\nimport type { ReasoningConfig } from \"../types/config.js\";\nimport { LLMService } from \"@reactive-agents/llm-provider\";\n\ninterface ReflexionInput {\n readonly taskDescription: string;\n readonly taskType: string;\n readonly memoryContext: string;\n readonly availableTools: readonly string[];\n readonly config: ReasoningConfig;\n}\n\n/**\n * Reflexion: Generate → Self-Critique → Improve, repeating until satisfied\n * or maxRetries is reached.\n */\nexport const executeReflexion = (\n input: ReflexionInput,\n): Effect.Effect<\n ReasoningResult,\n ExecutionError | IterationLimitError,\n LLMService\n> =>\n Effect.gen(function* () {\n const llm = yield* LLMService;\n const { maxRetries, selfCritiqueDepth } = input.config.strategies.reflexion;\n const steps: ReasoningStep[] = [];\n const start = Date.now();\n let totalTokens = 0;\n let totalCost = 0;\n let attempt = 0;\n let previousCritiques: string[] = [];\n\n // ── STEP 1: Initial generation ──\n const initialResponse = yield* llm\n .complete({\n messages: [\n {\n role: \"user\",\n content: buildGenerationPrompt(input, null),\n },\n ],\n systemPrompt: buildSystemPrompt(input.taskDescription),\n maxTokens: selfCritiqueDepth === \"deep\" ? 800 : 500,\n temperature: 0.7,\n })\n .pipe(\n Effect.mapError(\n (err) =>\n new ExecutionError({\n strategy: \"reflexion\",\n message: \"Initial generation failed\",\n step: 0,\n cause: err,\n }),\n ),\n );\n\n let currentResponse = initialResponse.content;\n totalTokens += initialResponse.usage.totalTokens;\n totalCost += initialResponse.usage.estimatedCost;\n\n steps.push({\n id: ulid() as StepId,\n type: \"thought\",\n content: `[ATTEMPT 1] ${currentResponse}`,\n timestamp: new Date(),\n });\n\n // ── LOOP: Reflect → Improve ──\n while (attempt < maxRetries) {\n attempt++;\n\n // ── Reflect: self-critique the current response ──\n const critiqueResponse = yield* llm\n .complete({\n messages: [\n {\n role: \"user\",\n content: buildCritiquePrompt(\n input.taskDescription,\n currentResponse,\n selfCritiqueDepth,\n previousCritiques,\n ),\n },\n ],\n systemPrompt:\n \"You are a critical evaluator. Analyze responses for accuracy, completeness, and quality.\",\n maxTokens: selfCritiqueDepth === \"deep\" ? 600 : 300,\n temperature: 0.3, // low temp for objective critique\n })\n .pipe(\n Effect.mapError(\n (err) =>\n new ExecutionError({\n strategy: \"reflexion\",\n message: `Self-critique failed at attempt ${attempt}`,\n step: attempt,\n cause: err,\n }),\n ),\n );\n\n const critique = critiqueResponse.content;\n totalTokens += critiqueResponse.usage.totalTokens;\n totalCost += critiqueResponse.usage.estimatedCost;\n\n steps.push({\n id: ulid() as StepId,\n type: \"observation\",\n content: `[CRITIQUE ${attempt}] ${critique}`,\n timestamp: new Date(),\n });\n\n // ── Check if satisfied ──\n if (isSatisfied(critique)) {\n return buildResult(\n steps,\n currentResponse,\n \"completed\",\n start,\n totalTokens,\n totalCost,\n attempt,\n );\n }\n\n previousCritiques.push(critique);\n\n // ── Improve: generate a refined response ──\n const improvedResponse = yield* llm\n .complete({\n messages: [\n {\n role: \"user\",\n content: buildGenerationPrompt(input, previousCritiques),\n },\n ],\n systemPrompt: buildSystemPrompt(input.taskDescription),\n maxTokens: selfCritiqueDepth === \"deep\" ? 800 : 500,\n temperature: 0.6,\n })\n .pipe(\n Effect.mapError(\n (err) =>\n new ExecutionError({\n strategy: \"reflexion\",\n message: `Improvement generation failed at attempt ${attempt}`,\n step: attempt,\n cause: err,\n }),\n ),\n );\n\n currentResponse = improvedResponse.content;\n totalTokens += improvedResponse.usage.totalTokens;\n totalCost += improvedResponse.usage.estimatedCost;\n\n steps.push({\n id: ulid() as StepId,\n type: \"thought\",\n content: `[ATTEMPT ${attempt + 1}] ${currentResponse}`,\n timestamp: new Date(),\n });\n }\n\n // Max retries reached — return the best response so far\n return buildResult(\n steps,\n currentResponse,\n \"partial\",\n start,\n totalTokens,\n totalCost,\n attempt,\n );\n });\n\n// ─── Private Helpers ───\n\nfunction buildSystemPrompt(taskDescription: string): string {\n return `You are a thoughtful reasoning agent. Your task is: ${taskDescription}\\nProvide clear, accurate, and complete responses.`;\n}\n\nfunction buildGenerationPrompt(\n input: ReflexionInput,\n previousCritiques: string[] | null,\n): string {\n const parts: string[] = [\n `Task: ${input.taskDescription}`,\n `Task Type: ${input.taskType}`,\n ];\n\n if (input.memoryContext) {\n parts.push(`Relevant Context:\\n${input.memoryContext}`);\n }\n\n if (previousCritiques && previousCritiques.length > 0) {\n parts.push(\n `Previous attempts had these issues:\\n${previousCritiques.map((c, i) => `${i + 1}. ${c}`).join(\"\\n\")}\\n\\nPlease address all of these issues in your improved response.`,\n );\n }\n\n parts.push(\n \"Provide a thorough and accurate response to the task above.\",\n );\n\n return parts.join(\"\\n\\n\");\n}\n\nfunction buildCritiquePrompt(\n taskDescription: string,\n response: string,\n depth: \"shallow\" | \"deep\",\n previousCritiques: string[],\n): string {\n const deepInstructions =\n depth === \"deep\"\n ? \"\\n- Check for logical consistency and coherence\\n- Identify any unsupported claims or assumptions\\n- Assess whether all aspects of the task are addressed\"\n : \"\";\n\n const prevCritiqueNote =\n previousCritiques.length > 0\n ? `\\n\\nPrevious critiques identified these issues:\\n${previousCritiques.map((c, i) => `${i + 1}. ${c}`).join(\"\\n\")}\\n\\nFocus on whether the new response adequately addresses these.`\n : \"\";\n\n return `Task: ${taskDescription}\n\nResponse to evaluate:\n${response}\n\nCritically evaluate this response. Identify:\n- Factual errors or inaccuracies\n- Missing information or incomplete answers\n- Unclear or ambiguous statements${deepInstructions}${prevCritiqueNote}\n\nIf the response is accurate and complete, start your critique with \"SATISFIED:\".\nOtherwise, clearly list the specific issues that need to be fixed.`;\n}\n\nfunction isSatisfied(critique: string): boolean {\n return /^SATISFIED:/i.test(critique.trim());\n}\n\nfunction buildResult(\n steps: readonly ReasoningStep[],\n output: string,\n status: \"completed\" | \"partial\",\n startMs: number,\n tokensUsed: number,\n cost: number,\n iterations: number,\n): ReasoningResult {\n // Confidence is higher when fewer iterations were needed\n const maxNormal = 3;\n const confidence =\n status === \"completed\"\n ? Math.max(0.6, 1 - (iterations / maxNormal) * 0.3)\n : 0.4;\n\n return {\n strategy: \"reflexion\",\n steps: [...steps],\n output,\n metadata: {\n duration: Date.now() - startMs,\n cost,\n tokensUsed,\n stepsCount: steps.length,\n confidence,\n },\n status,\n };\n}\n","// File: src/runtime.ts\nimport { Layer } from \"effect\";\nimport type { ReasoningConfig } from \"./types/config.js\";\nimport { defaultReasoningConfig } from \"./types/config.js\";\nimport { StrategyRegistryLive } from \"./services/strategy-registry.js\";\nimport { ReasoningServiceLive } from \"./services/reasoning-service.js\";\n\n/**\n * Create the full Reasoning layer (Phase 1: reactive only).\n *\n * Provides: ReasoningService, StrategyRegistry\n * Requires: LLMService (from Layer 1.5)\n *\n * Usage:\n * const ReasoningLive = createReasoningLayer();\n * const program = myEffect.pipe(Effect.provide(ReasoningLive));\n */\nexport const createReasoningLayer = (\n config: ReasoningConfig = defaultReasoningConfig,\n) => {\n // StrategyRegistry has no deps (strategies are registered at construction)\n const RegistryLayer = StrategyRegistryLive;\n\n // ReasoningService needs StrategyRegistry\n const ServiceLayer = ReasoningServiceLive(config).pipe(\n Layer.provide(RegistryLayer),\n );\n\n // Merge all services into one layer\n return Layer.mergeAll(ServiceLayer, RegistryLayer);\n};\n"],"mappings":";AACA,SAAS,cAAc;AAIhB,IAAM,SAAS,OAAO,OAAO,KAAK,OAAO,MAAM,QAAQ,CAAC;AAKxD,IAAM,WAAW,OAAO;AAAA,EAC7B;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AAAA,EACA;AAAA;AACF;AAKO,IAAM,qBAAqB,OAAO,OAAO;AAAA,EAC9C,YAAY,OAAO,SAAS,OAAO,MAAM;AAAA,EACzC,UAAU,OAAO,SAAS,OAAO,MAAM;AAAA,EACvC,MAAM,OAAO,SAAS,OAAO,MAAM;AAAA,EACnC,UAAU,OAAO,SAAS,OAAO,MAAM;AACzC,CAAC;AAKM,IAAM,sBAAsB,OAAO,OAAO;AAAA,EAC/C,IAAI;AAAA,EACJ,MAAM;AAAA,EACN,SAAS,OAAO;AAAA,EAChB,WAAW,OAAO;AAAA,EAClB,UAAU,OAAO,SAAS,kBAAkB;AAC9C,CAAC;;;ACrCD,SAAS,UAAAA,eAAc;AAMvB,SAAS,yBAAyB;AAK3B,IAAM,kBAAkBC,QAAO,QAAQ,aAAa,UAAU,SAAS;AAKvE,IAAM,0BAA0BA,QAAO,OAAO;AAAA,EACnD,UAAUA,QAAO;AAAA;AAAA,EACjB,MAAMA,QAAO;AAAA;AAAA,EACb,YAAYA,QAAO;AAAA,EACnB,YAAYA,QAAO;AAAA,EACnB,YAAYA,QAAO;AAAA;AAAA,EACnB,eAAeA,QAAO,SAASA,QAAO,MAAM;AAAA;AAAA,EAC5C,kBAAkBA,QAAO,SAAS,iBAAiB;AAAA;AACrD,CAAC;AAKM,IAAM,wBAAwBA,QAAO,OAAO;AAAA,EACjD,UAAU;AAAA,EACV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schema","Schema","Context","Effect","Layer","Effect","Effect","ulid","LLMService","Effect","ulid","buildResult","Effect","LLMService","Context","Layer","Effect","Layer","Layer"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@reactive-agents/reasoning",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"main": "./dist/index.js",
|
|
6
|
+
"types": "./dist/index.d.ts",
|
|
7
|
+
"scripts": {
|
|
8
|
+
"build": "tsup --config ../../tsup.config.base.ts",
|
|
9
|
+
"typecheck": "tsc --noEmit",
|
|
10
|
+
"test": "bun test",
|
|
11
|
+
"test:watch": "bun test --watch"
|
|
12
|
+
},
|
|
13
|
+
"dependencies": {
|
|
14
|
+
"effect": "^3.10.0",
|
|
15
|
+
"@reactive-agents/core": "0.1.0",
|
|
16
|
+
"@reactive-agents/llm-provider": "0.1.0",
|
|
17
|
+
"ulid": "^2.3.0"
|
|
18
|
+
},
|
|
19
|
+
"devDependencies": {
|
|
20
|
+
"typescript": "^5.7.0",
|
|
21
|
+
"bun-types": "latest"
|
|
22
|
+
},
|
|
23
|
+
"license": "MIT",
|
|
24
|
+
"repository": {
|
|
25
|
+
"type": "git",
|
|
26
|
+
"url": "https://github.com/tylerjrbuell/reactive-agents-ts.git",
|
|
27
|
+
"directory": "packages/reasoning"
|
|
28
|
+
},
|
|
29
|
+
"publishConfig": {
|
|
30
|
+
"access": "public"
|
|
31
|
+
},
|
|
32
|
+
"files": [
|
|
33
|
+
"dist",
|
|
34
|
+
"README.md",
|
|
35
|
+
"LICENSE"
|
|
36
|
+
],
|
|
37
|
+
"exports": {
|
|
38
|
+
".": {
|
|
39
|
+
"types": "./dist/index.d.ts",
|
|
40
|
+
"import": "./dist/index.js",
|
|
41
|
+
"default": "./dist/index.js"
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
"description": "Reasoning strategies for Reactive Agents — ReAct, Plan-Execute, and Tree-of-Thought",
|
|
45
|
+
"homepage": "https://tylerjrbuell.github.io/reactive-agents-ts/",
|
|
46
|
+
"bugs": {
|
|
47
|
+
"url": "https://github.com/tylerjrbuell/reactive-agents-ts/issues"
|
|
48
|
+
}
|
|
49
|
+
}
|