@caretakerai/agent 0.0.3 → 0.0.5

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 ADDED
@@ -0,0 +1,166 @@
1
+ # Agent Framework Documentation
2
+
3
+ The Agent Framework provides a flexible and extensible environment for building intelligent agents that can perform a variety of tasks. It is built on top of the `langchain` library and utilizes language models for natural language understanding and generation.
4
+
5
+ ## Key Components
6
+
7
+ - `Agent`: The core class that represents an intelligent agent. It is initialized with a set of parameters that define its behavior, capabilities, and objectives.
8
+
9
+ - `Activity`: Represents a single unit of work or thought that the agent performs. Activities can be of different kinds, such as `Observation`, `Thought`, or `Action`.
10
+
11
+ - `Action`: A subclass of `Activity` that represents a concrete action the agent can take.
12
+
13
+ - `Optimizer`: A component used to improve the agent's performance by optimizing its activities and decisions.
14
+
15
+ ## Initialization Parameters
16
+
17
+ When creating an `Agent`, you must provide an `AgentPrams` object with the following properties:
18
+
19
+ - `name`: The name of the agent.
20
+ - `llm`: The language model the agent will use for understanding and generating text.
21
+ - `actions`: A list of `Action` objects that the agent can perform.
22
+ - `description`: (Optional) A description of the agent's purpose and capabilities.
23
+ - `history`: (Optional) A list of `Activity` objects representing the agent's past experiences.
24
+ - `examples`: (Optional) Examples of activities to guide the agent's behavior.
25
+ - `constraints`: (Optional) A list of constraints that the agent must adhere to.
26
+ - `objective`: (Optional) The goal the agent is trying to achieve.
27
+ - `thoughtSuffix`: (Optional) A suffix to append to thoughts in the agent's output.
28
+ - `actionSuffix`: (Optional) A suffix to append to actions in the agent's output.
29
+ - `maxIterations`: (Optional) The maximum number of iterations the agent can perform in a single run.
30
+ - `maxRetries`: (Optional) The maximum number of retries for actions.
31
+ - `optimizer`: The optimizer used to improve the agent's performance.
32
+ - `template`: (Optional) The template for generating prompts for the agent.
33
+ - `logger`: (Optional) The logger the agent will use for outputting information.
34
+
35
+ ## Objective
36
+ The `objective` parameter defines the goal or purpose that the Agent is trying to achieve. It is a guiding force for the Agent's behavior and decision-making process. When initializing an Agent, you can optionally provide an objective to inform the Agent's actions and ensure they align with the desired outcomes. Here is an example of how an objective might be set:
37
+
38
+ ```typescript
39
+ const agent = new Agent({
40
+ // ... other parameters
41
+ objective: `Help the user with math calculations using specific actions.`,
42
+ });
43
+ ```
44
+
45
+ The objective will be included in the Agent's prompt template to provide context to the language model, ensuring that the Agent's interactions are focused and relevant to the goal.
46
+
47
+
48
+ ## Action
49
+ Actions are the mechanisms through which an AI agent interacts with the application and its environment. They are the operational components that translate the agent's decisions into executable tasks. Each action extends from an abstract `Action` class, which provides a common structure and ensures compatibility with the agent framework.
50
+
51
+ Here's an example of an `Action` subclass:
52
+
53
+ ```typescript
54
+ import { Action, ActionInput } from '@caretaker/agent';
55
+
56
+ export class Say extends Action {
57
+ async call(input: ActionInput): Promise<void> {
58
+ // Logic to perform the action, e.g., output a message
59
+ console.log(input.params.message);
60
+ }
61
+ }
62
+ ```
63
+
64
+ In this `Say` action example, the `call` method is where the action's specific behavior is implemented. When an agent decides to use the `Say` action, it will call this method, passing in the necessary parameters.
65
+
66
+ Actions are defined and added to the agent's configuration, allowing the agent to use them during its processing loop. They serve as the bridge between the AI's decision-making capabilities and the application's functional operations, enabling the agent to perform tasks such as communicating with the user or calculating results.
67
+
68
+ The parameters for actions are defined using JSON Schema, which provides a clear and enforceable structure for the data that an action can accept. This ensures that the agent and the actions it performs can interact with consistent and validated data formats.
69
+
70
+ For example, in the `Say` action from `@say.ts`, the parameters are defined as follows:
71
+
72
+ ```typescript
73
+ const SayParamsSchema = z.object({
74
+ message: z.string().describe('message to say to the user'),
75
+ }).describe('Parameters for Say action');
76
+ ```
77
+
78
+ This schema is then converted to a JSON Schema, which is used by the `Say` action to validate the parameters before the action is executed:
79
+
80
+ ```typescript
81
+ const SayParamsJsonSchema = zodToJsonSchema(SayParamsSchema, 'SayParamsSchema')
82
+ .definitions!.SayParamsSchema as JSONSchema;
83
+ ```
84
+
85
+ The use of JSON Schema in action parameters allows for the automatic validation of inputs, ensuring that only the correct data types and structures are passed to the action's `call` method. This is crucial for maintaining the integrity of the agent's operations and preventing runtime errors due to invalid data.
86
+
87
+
88
+ The `Multiply` action example above demonstrates how to define an action with input parameters and a return type using Zod schemas and TypeScript. The `params` property is assigned a JSON Schema that is generated from the Zod schema, which is used for runtime validation of the action's input parameters. The `call` method implements the logic to multiply an array of numbers, which are provided as input parameters, and returns the multiplication result. This action can be used by the agent to perform multiplication operations as part of its task execution.
89
+
90
+
91
+ ```typescript
92
+ import { z } from 'zod';
93
+ import { zodToJsonSchema } from 'zod-to-json-schema';
94
+ import { Action, ActionInput } from '@caretaker/agent';
95
+ import { JSONSchema } from 'json-schema-to-typescript';
96
+
97
+ // Define the parameters schema using Zod for the Multiply action
98
+ const MultiplyParamsSchema = z.array(z.number()).describe('Array of numbers to multiply');
99
+ // Infer the TypeScript type from the Zod schema
100
+ type MultiplyParams = z.infer<typeof MultiplyParamsSchema>;
101
+ // Convert the Zod schema to a JSON Schema for runtime validation
102
+ const MultiplyParamsJsonSchema = zodToJsonSchema(MultiplyParamsSchema, 'MultiplyParamsSchema')
103
+ .definitions!.MultiplyParamsSchema as JSONSchema;
104
+
105
+ // Define the result schema using Zod for the Multiply action
106
+ const MultiplyResultSchema = z.number().describe('The result of the multiplication');
107
+ // Infer the TypeScript type from the Zod schema
108
+ type MultiplyResult = z.infer<typeof MultiplyResultSchema>;
109
+ // Convert the Zod schema to a JSON Schema for runtime validation
110
+ const MultiplyResultJsonSchema = zodToJsonSchema(MultiplyResultSchema, 'MultiplyResultSchema')
111
+ .definitions!.MultiplyResultSchema as JSONSchema;
112
+
113
+ // Multiply action class definition
114
+ export class Multiply extends Action<MultiplyParams, MultiplyResult> {
115
+ // Assign the JSON Schema to the params and result properties
116
+ readonly params = MultiplyParamsJsonSchema;
117
+ readonly result = MultiplyResultJsonSchema;
118
+ // Define whether this action should signal the agent to exit
119
+ readonly exit = false;
120
+ // Define the kind of action, which is the class name
121
+ readonly kind = Multiply.name;
122
+ // Provide a description for the action
123
+ readonly description = 'Multiply the numbers and provide you with the result.';
124
+ // Provide examples of usage (optional)
125
+ readonly examples = [];
126
+
127
+ // The call method is invoked by the agent when this action is performed
128
+ async call({ params }: ActionInput<MultiplyParams>): Promise<MultiplyResult> {
129
+ // Implement the action logic: multiply the numbers provided in params
130
+ return params.reduce((acc, n) => acc * n, 1);
131
+ }
132
+ }
133
+ ```
134
+
135
+ ## Usage
136
+
137
+ To use the Agent Framework, create an instance of the `Agent` class with the necessary parameters, including the language model, actions, and any optional configurations such as history, objectives, and optimizers. Then, invoke the `agent.invoke()` method to start the agent's processing loop. The agent will utilize the provided actions, such as `Say` to communicate with the user or `Multiply` to perform multiplication tasks, to fulfill its objectives within the given constraints.
138
+
139
+ ```typescript
140
+ import { Agent, Activity, ActivityKind } from '@caretaker/agent';
141
+ import { OpenAI } from 'langchain/llms/openai';
142
+ import { Say } from './actions/say';
143
+
144
+ const llm = new OpenAI({
145
+ modelName: 'gpt-3.5-turbo',
146
+ temperature: 0.7,
147
+ maxTokens: 256,
148
+ });
149
+
150
+ const agent = new Agent({
151
+ name: 'CalculatorAI',
152
+ description: 'An agent that performs arithmetic operations',
153
+ llm,
154
+ actions: [
155
+ new Say(),
156
+ // ... other actions
157
+ ],
158
+ history: [
159
+ new Activity({ kind: ActivityKind.Observation, input: 'The user says: How can you help me?' })
160
+ ],
161
+ // ... other parameters
162
+ });
163
+
164
+ await agent.invoke();
165
+ ```
166
+
package/package.json CHANGED
@@ -1,24 +1,32 @@
1
1
  {
2
2
  "name": "@caretakerai/agent",
3
- "version": "0.0.3",
3
+ "version": "0.0.5",
4
4
  "description": "Single framework for building text-agents",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
7
  "files": [
8
- "dist"
8
+ "dist",
9
+ "README.md"
9
10
  ],
10
11
  "scripts": {
11
12
  "test": "echo \"Error: no test specified\" && exit 1",
12
- "build": "tsc"
13
+ "build": "rimraf dist && tsc",
14
+ "build:watch": "tsc --watch"
13
15
  },
14
16
  "author": "",
15
17
  "license": "ISC",
16
18
  "dependencies": {
19
+ "ajv": "^8.12.0",
20
+ "ajv-errors": "^3.0.0",
17
21
  "debug": "^4.3.4",
18
- "langchain": "^0.0.151"
22
+ "json-schema-to-typescript": "^13.1.1",
23
+ "langchain": "^0.0.191",
24
+ "winston": "^3.11.0",
25
+ "xml-js": "^1.6.11"
19
26
  },
20
27
  "devDependencies": {
21
28
  "@types/node": "^20.4.1",
29
+ "rimraf": "^5.0.5",
22
30
  "tsx": "^3.12.7",
23
31
  "typescript": "^5.2.2"
24
32
  }
package/dist/action.d.ts DELETED
@@ -1,22 +0,0 @@
1
- import type { Agent } from './agent';
2
- import type { Activity } from './activity';
3
- export interface ActionInput {
4
- input: string;
5
- agent: Agent;
6
- }
7
- export interface ActionExample {
8
- description?: string;
9
- activities: Activity[];
10
- }
11
- export declare abstract class Action {
12
- abstract get exit(): boolean;
13
- abstract get kind(): string;
14
- abstract get description(): string;
15
- abstract get examples(): ActionExample[];
16
- abstract execute(input: ActionInput): Promise<string>;
17
- toString(): string;
18
- static parse(text: string): {
19
- kind: string;
20
- input: string;
21
- };
22
- }
package/dist/action.js DELETED
@@ -1,37 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.Action = void 0;
7
- const dedent_1 = __importDefault(require("dedent"));
8
- const constants_1 = require("./constants");
9
- class Action {
10
- toString() {
11
- const examples = this.examples
12
- .reduce((acc, { description, activities }) => (0, dedent_1.default) `
13
- ${acc}
14
-
15
- ${description}
16
- \`\`\`
17
- ${activities.map(a => a.toString()).join(`\n${constants_1.ACTIVITY_SEP}\n`)}
18
- \`\`\`
19
- `.trim(), '');
20
- return (0, dedent_1.default) `
21
- ### ${this.kind}
22
- ${this.description}
23
-
24
- #### Examples
25
- ${examples}
26
- `.trim();
27
- }
28
- static parse(text) {
29
- const [kind, ...rest] = text.split('\n');
30
- return {
31
- kind: kind.trim(),
32
- input: rest.join('\n'),
33
- };
34
- }
35
- }
36
- exports.Action = Action;
37
- //# sourceMappingURL=action.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"action.js","sourceRoot":"","sources":["../src/action.ts"],"names":[],"mappings":";;;;;;AAAA,oDAA4B;AAG5B,2CAA2C;AAY3C,MAAsB,MAAM;IAQ1B,QAAQ;QACN,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ;aAC3B,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,WAAW,EAAE,UAAU,EAAE,EAAE,EAAE,CAAC,IAAA,gBAAM,EAAA;UAChD,GAAG;;UAEH,WAAW;;UAEX,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC,IAAI,CAAC,KAAK,wBAAY,IAAI,CAAC;;OAEhE,CAAC,IAAI,EAAE,EAAE,EAAE,CAAC,CAAC;QAEhB,OAAO,IAAA,gBAAM,EAAA;YACL,IAAI,CAAC,IAAI;QACb,IAAI,CAAC,WAAW;;;QAGhB,QAAQ;OACT,CAAC,IAAI,EAAE,CAAA;IACZ,CAAC;IAED,MAAM,CAAC,KAAK,CAAC,IAAY;QACvB,MAAM,CAAC,IAAI,EAAE,GAAG,IAAI,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;QAExC,OAAO;YACL,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE;YACjB,KAAK,EAAE,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;SACvB,CAAC;IACJ,CAAC;CACF;AApCD,wBAoCC"}
@@ -1,23 +0,0 @@
1
- export declare enum ActivityKind {
2
- Observation = "Observation",
3
- Thought = "Thought",
4
- Action = "Action"
5
- }
6
- export type ActivityParams = {
7
- kind: ActivityKind;
8
- order: number;
9
- input: string;
10
- tokens?: number;
11
- };
12
- export declare class Activity implements ActivityParams {
13
- kind: ActivityKind;
14
- order: number;
15
- input: string;
16
- tokens?: number;
17
- static readonly defaults: Partial<ActivityParams>;
18
- constructor(params: ActivityParams);
19
- toString(): string;
20
- toObject(): this;
21
- static parse(text: string): Activity;
22
- static fromObject({ kind, order, input }: Record<string, any>): Activity;
23
- }
package/dist/activity.js DELETED
@@ -1,42 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Activity = exports.ActivityKind = void 0;
4
- var ActivityKind;
5
- (function (ActivityKind) {
6
- ActivityKind["Observation"] = "Observation";
7
- ActivityKind["Thought"] = "Thought";
8
- ActivityKind["Action"] = "Action";
9
- })(ActivityKind || (exports.ActivityKind = ActivityKind = {}));
10
- class Activity {
11
- constructor(params) {
12
- Object.assign(this, params);
13
- }
14
- toString() {
15
- return `//${this.kind} ${this.order}// ${this.input}`;
16
- }
17
- toObject() {
18
- return { ...this };
19
- }
20
- static parse(text) {
21
- var _a, _b;
22
- const kindRegexp = /^\/\/(.+?)\s/;
23
- const orderRegexp = /^\/\/\w+\s(.+?)\/\//;
24
- if (!kindRegexp.test(text)) {
25
- throw new Error('Cannot parse kind from the given text');
26
- }
27
- const kind = (_a = text.match(kindRegexp)) === null || _a === void 0 ? void 0 : _a[1].trim();
28
- if (!orderRegexp.test(text)) {
29
- throw new Error('Cannot parse order from the given text');
30
- }
31
- const order = parseInt((_b = text.match(orderRegexp)) === null || _b === void 0 ? void 0 : _b[1].trim());
32
- const input = text.replace(/^\/\/.+\/\/\s/, '');
33
- const activity = new Activity({ kind, order, input });
34
- return activity;
35
- }
36
- static fromObject({ kind, order, input }) {
37
- return new Activity({ kind, order, input });
38
- }
39
- }
40
- exports.Activity = Activity;
41
- Activity.defaults = {};
42
- //# sourceMappingURL=activity.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"activity.js","sourceRoot":"","sources":["../src/activity.ts"],"names":[],"mappings":";;;AAAA,IAAY,YAIX;AAJD,WAAY,YAA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,IAAI,EAAE,KAAK,EAAE,KAAK,EAAuB;QAC3D,OAAO,IAAI,QAAQ,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;IAC9C,CAAC;;AA7CH,4BA8CC;AAxCiB,iBAAQ,GAA4B,EACnD,CAAA"}
package/dist/agent.d.ts DELETED
@@ -1,39 +0,0 @@
1
- import { BaseLanguageModel } from 'langchain/base_language';
2
- import { BasePromptTemplate } from 'langchain/prompts';
3
- import { Action } from './action';
4
- import { Activity } from './activity';
5
- import { Optimizer } from './types';
6
- interface AgentPrams {
7
- name: string;
8
- description: string;
9
- llm: BaseLanguageModel;
10
- actions: Action[];
11
- activities?: Activity[];
12
- example?: Activity[];
13
- instruction: string;
14
- optimizer: Optimizer;
15
- template?: BasePromptTemplate;
16
- stop?: string[];
17
- }
18
- export declare class Agent implements AgentPrams {
19
- name: string;
20
- description: string;
21
- llm: BaseLanguageModel;
22
- actions: Action[];
23
- activities: Activity[];
24
- example: Activity[];
25
- instruction: string;
26
- optimizer: Optimizer;
27
- template?: BasePromptTemplate;
28
- stop?: string[];
29
- static defaults: Partial<AgentPrams>;
30
- static parseActivities(input: string): Activity[];
31
- constructor(params: AgentPrams);
32
- appendActivity(...experience: Activity[]): void;
33
- complete(experienceTemplate: Activity): Promise<Activity[]>;
34
- think(latestActivity: Activity): Promise<void>;
35
- act(latestActivity: Activity): Promise<void>;
36
- execute(latestActivity: Activity): Promise<string>;
37
- invoke(): Promise<string>;
38
- }
39
- export {};
package/dist/agent.js DELETED
@@ -1,115 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Agent = void 0;
4
- const prompts_1 = require("langchain/prompts");
5
- const runnable_1 = require("langchain/schema/runnable");
6
- const output_parser_1 = require("langchain/schema/output_parser");
7
- const action_1 = require("./action");
8
- const constants_1 = require("./constants");
9
- const activity_1 = require("./activity");
10
- class Agent {
11
- static parseActivities(input) {
12
- return input
13
- .split('\n//')
14
- .filter(text => text)
15
- .map(text => `//${text.replace(/^\/\//, '').trim()}`)
16
- .map(text => activity_1.Activity.parse(text.trim()));
17
- }
18
- constructor(params) {
19
- const { actions } = params;
20
- if (!actions.length) {
21
- throw new Error('Actions list must be non empty');
22
- }
23
- Object.assign(this, Agent.defaults, params);
24
- }
25
- appendActivity(...experience) {
26
- experience.forEach(e => console.log(e.toString()));
27
- this.activities.push(...experience);
28
- }
29
- async complete(experienceTemplate) {
30
- const activities = await this.optimizer.optimize(this.activities);
31
- const completion = await runnable_1.RunnableSequence.from([
32
- this.template,
33
- this.llm.bind({ stop: this.stop }),
34
- new output_parser_1.StringOutputParser(),
35
- ]).invoke({
36
- instruction: this.instruction,
37
- actions: this.actions.map((a, index) => `${index + 1}. ${a.toString()}`).join(constants_1.ACTION_SEP),
38
- example: this.example.map(e => e.toString()).join(`\n`),
39
- activities: [...activities, experienceTemplate].map(e => e.toString()).join(`\n`),
40
- }, {
41
- callbacks: [
42
- {
43
- handleLLMStart: (llm, prompts) => {
44
- }
45
- }
46
- ]
47
- });
48
- return Agent.parseActivities(experienceTemplate.toString() + completion.trim());
49
- }
50
- async think(latestActivity) {
51
- this.appendActivity(...(await this.complete(new activity_1.Activity({
52
- kind: activity_1.ActivityKind.Thought,
53
- order: latestActivity.order,
54
- input: '',
55
- }))));
56
- }
57
- async act(latestActivity) {
58
- this.appendActivity(...(await this.complete(new activity_1.Activity({
59
- kind: activity_1.ActivityKind.Action,
60
- order: latestActivity.order,
61
- input: '',
62
- }))));
63
- }
64
- async execute(latestActivity) {
65
- const { kind, input } = action_1.Action.parse(latestActivity.input);
66
- const action = this.actions.find(a => a.kind === kind);
67
- if (!action) {
68
- throw new Error(`Action "${kind}" is not permitted.`);
69
- }
70
- const observation = await action.execute({ agent: this, input });
71
- this.appendActivity(new activity_1.Activity({
72
- kind: activity_1.ActivityKind.Observation,
73
- order: latestActivity.order + 1,
74
- input: observation,
75
- }));
76
- if (action.exit) {
77
- return observation;
78
- }
79
- }
80
- async invoke() {
81
- var _a;
82
- if (!this.activities.length) {
83
- throw new Error('Activity list must not be empty.');
84
- }
85
- if (((_a = this.activities.at(-1)) === null || _a === void 0 ? void 0 : _a.kind) !== activity_1.ActivityKind.Observation) {
86
- throw new Error('Lastest experience must be of Observation kind');
87
- }
88
- while (true) {
89
- const latestActivity = this.activities.at(-1);
90
- if (latestActivity.kind === activity_1.ActivityKind.Observation) {
91
- await this.think(latestActivity);
92
- }
93
- else if (latestActivity.kind === activity_1.ActivityKind.Thought) {
94
- await this.act(latestActivity);
95
- }
96
- else if (latestActivity.kind === activity_1.ActivityKind.Action) {
97
- const result = await this.execute(latestActivity);
98
- if (result) {
99
- return result;
100
- }
101
- }
102
- else {
103
- throw new Error(`Activity "${latestActivity.kind}" is not permitted.`);
104
- }
105
- }
106
- }
107
- }
108
- exports.Agent = Agent;
109
- Agent.defaults = {
110
- template: prompts_1.PromptTemplate.fromTemplate(constants_1.TEMPLATE),
111
- stop: [`//${activity_1.ActivityKind.Observation}`],
112
- activities: [],
113
- example: []
114
- };
115
- //# sourceMappingURL=agent.js.map
package/dist/agent.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":";;;AACA,+CAAuE;AACvE,wDAA6D;AAC7D,kEAAoE;AACpE,qCAAkC;AAClC,2CAAiE;AACjE,yCAAoD;AAgBpD,MAAa,KAAK;IAmBhB,MAAM,CAAC,eAAe,CAAC,KAAa;QAClC,OAAO,KAAK;aACT,KAAK,CAAC,MAAM,CAAC;aACb,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC;aACpB,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,KAAK,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;aACpD,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,mBAAQ,CAAC,KAAK,CAAC,IAAI,CAAC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,EAAE;gBACtD,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC;gBAElD,IAAI,MAAM,EAAE;oBACV,OAAO,MAAM,CAAC;iBACf;aACF;iBAAM;gBACL,MAAM,IAAI,KAAK,CAAC,aAAa,cAAc,CAAC,IAAI,qBAAqB,CAAC,CAAC;aACxE;SACF;IACH,CAAC;;AAtIH,sBAuIC;AA3HQ,cAAQ,GAAwB;IACrC,QAAQ,EAAE,wBAAc,CAAC,YAAY,CAAC,oBAAQ,CAAC;IAC/C,IAAI,EAAE,CAAC,KAAK,uBAAY,CAAC,WAAW,EAAE,CAAC;IACvC,UAAU,EAAE,EAAE;IACd,OAAO,EAAE,EAAE;CACZ,CAAA"}
@@ -1,3 +0,0 @@
1
- export declare const ACTION_SEP = "\n\n";
2
- export declare const ACTIVITY_SEP = "***";
3
- export declare const TEMPLATE: string;
package/dist/constants.js DELETED
@@ -1,24 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TEMPLATE = exports.ACTIVITY_SEP = exports.ACTION_SEP = void 0;
4
- exports.ACTION_SEP = '\n\n';
5
- exports.ACTIVITY_SEP = '***';
6
- exports.TEMPLATE = `
7
- ## Instruction
8
- {instruction}
9
-
10
- ## Additional Requirements:
11
- 1. I understand that there are no exceptions;
12
- 2. I am not permitted to perform any actions other than those listed in section Actions;
13
- 3. I must provide your thoughts on the observations before proceeding to the next action;
14
- 4. I am strongly prohibited from using Observations, Actions, and Thoughts provided in the Action examples as the source of truth;
15
-
16
- ## Actions
17
- The permissible actions I may take are listed below:
18
- {actions}
19
-
20
- ## Context:
21
- {example}
22
- {activities}
23
- `.trim();
24
- //# sourceMappingURL=constants.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"constants.js","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":";;;AAAa,QAAA,UAAU,GAAG,MAAM,CAAA;AACnB,QAAA,YAAY,GAAG,KAAK,CAAC;AACrB,QAAA,QAAQ,GAAG;;;;;;;;;;;;;;;;;CAiBvB,CAAC,IAAI,EAAE,CAAC"}
package/dist/index.d.ts DELETED
@@ -1,5 +0,0 @@
1
- export * from './action';
2
- export * from './agent';
3
- export * from './constants';
4
- export * from './activity';
5
- export * from './types';
package/dist/index.js DELETED
@@ -1,22 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./action"), exports);
18
- __exportStar(require("./agent"), exports);
19
- __exportStar(require("./constants"), exports);
20
- __exportStar(require("./activity"), exports);
21
- __exportStar(require("./types"), exports);
22
- //# sourceMappingURL=index.js.map
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,2CAAyB;AACzB,0CAAwB;AACxB,8CAA4B;AAC5B,6CAA2B;AAC3B,0CAAwB"}
package/dist/types.d.ts DELETED
@@ -1,4 +0,0 @@
1
- import type { Activity } from './activity';
2
- export interface Optimizer {
3
- optimize(activities: Activity[]): Promise<Activity[]>;
4
- }
package/dist/types.js DELETED
@@ -1,3 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- //# sourceMappingURL=types.js.map
package/dist/types.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}