agentlang 0.9.5 → 0.9.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/out/cli/main.d.ts.map +1 -1
  2. package/out/cli/main.js +8 -3
  3. package/out/cli/main.js.map +1 -1
  4. package/out/language/generated/ast.d.ts +80 -3
  5. package/out/language/generated/ast.d.ts.map +1 -1
  6. package/out/language/generated/ast.js +62 -0
  7. package/out/language/generated/ast.js.map +1 -1
  8. package/out/language/generated/grammar.d.ts.map +1 -1
  9. package/out/language/generated/grammar.js +432 -218
  10. package/out/language/generated/grammar.js.map +1 -1
  11. package/out/language/main.cjs +485 -218
  12. package/out/language/main.cjs.map +2 -2
  13. package/out/language/parser.js +8 -8
  14. package/out/language/parser.js.map +1 -1
  15. package/out/runtime/agents/common.d.ts +7 -1
  16. package/out/runtime/agents/common.d.ts.map +1 -1
  17. package/out/runtime/agents/common.js +101 -0
  18. package/out/runtime/agents/common.js.map +1 -1
  19. package/out/runtime/agents/impl/anthropic.js +4 -4
  20. package/out/runtime/agents/impl/anthropic.js.map +1 -1
  21. package/out/runtime/agents/impl/openai.js +4 -4
  22. package/out/runtime/agents/impl/openai.js.map +1 -1
  23. package/out/runtime/docs.d.ts.map +1 -1
  24. package/out/runtime/docs.js +109 -7
  25. package/out/runtime/docs.js.map +1 -1
  26. package/out/runtime/embeddings/chunker.d.ts +9 -0
  27. package/out/runtime/embeddings/chunker.d.ts.map +1 -0
  28. package/out/runtime/embeddings/chunker.js +41 -0
  29. package/out/runtime/embeddings/chunker.js.map +1 -0
  30. package/out/runtime/embeddings/index.d.ts +6 -0
  31. package/out/runtime/embeddings/index.d.ts.map +1 -0
  32. package/out/runtime/embeddings/index.js +6 -0
  33. package/out/runtime/embeddings/index.js.map +1 -0
  34. package/out/runtime/embeddings/openai.d.ts +15 -0
  35. package/out/runtime/embeddings/openai.d.ts.map +1 -0
  36. package/out/runtime/embeddings/openai.js +34 -0
  37. package/out/runtime/embeddings/openai.js.map +1 -0
  38. package/out/runtime/embeddings/provider.d.ts +20 -0
  39. package/out/runtime/embeddings/provider.d.ts.map +1 -0
  40. package/out/runtime/embeddings/provider.js +17 -0
  41. package/out/runtime/embeddings/provider.js.map +1 -0
  42. package/out/runtime/embeddings/registry.d.ts +3 -0
  43. package/out/runtime/embeddings/registry.d.ts.map +1 -0
  44. package/out/runtime/embeddings/registry.js +16 -0
  45. package/out/runtime/embeddings/registry.js.map +1 -0
  46. package/out/runtime/exec-graph.d.ts.map +1 -1
  47. package/out/runtime/exec-graph.js +5 -0
  48. package/out/runtime/exec-graph.js.map +1 -1
  49. package/out/runtime/interpreter.d.ts +4 -0
  50. package/out/runtime/interpreter.d.ts.map +1 -1
  51. package/out/runtime/interpreter.js +27 -7
  52. package/out/runtime/interpreter.js.map +1 -1
  53. package/out/runtime/loader.d.ts.map +1 -1
  54. package/out/runtime/loader.js +42 -5
  55. package/out/runtime/loader.js.map +1 -1
  56. package/out/runtime/module.d.ts +22 -4
  57. package/out/runtime/module.d.ts.map +1 -1
  58. package/out/runtime/module.js +76 -10
  59. package/out/runtime/module.js.map +1 -1
  60. package/out/runtime/modules/ai.d.ts +20 -2
  61. package/out/runtime/modules/ai.d.ts.map +1 -1
  62. package/out/runtime/modules/ai.js +333 -37
  63. package/out/runtime/modules/ai.js.map +1 -1
  64. package/out/runtime/modules/auth.d.ts.map +1 -1
  65. package/out/runtime/modules/auth.js +11 -5
  66. package/out/runtime/modules/auth.js.map +1 -1
  67. package/out/runtime/resolvers/interface.d.ts +1 -1
  68. package/out/runtime/resolvers/interface.d.ts.map +1 -1
  69. package/out/runtime/resolvers/interface.js.map +1 -1
  70. package/out/runtime/resolvers/sqldb/database.d.ts +1 -1
  71. package/out/runtime/resolvers/sqldb/database.d.ts.map +1 -1
  72. package/out/runtime/resolvers/sqldb/database.js +139 -50
  73. package/out/runtime/resolvers/sqldb/database.js.map +1 -1
  74. package/out/runtime/resolvers/sqldb/impl.d.ts +22 -2
  75. package/out/runtime/resolvers/sqldb/impl.d.ts.map +1 -1
  76. package/out/runtime/resolvers/sqldb/impl.js +178 -47
  77. package/out/runtime/resolvers/sqldb/impl.js.map +1 -1
  78. package/out/runtime/state.d.ts +1 -0
  79. package/out/runtime/state.d.ts.map +1 -1
  80. package/out/runtime/state.js +3 -0
  81. package/out/runtime/state.js.map +1 -1
  82. package/out/syntaxes/agentlang.monarch.js +1 -1
  83. package/out/syntaxes/agentlang.monarch.js.map +1 -1
  84. package/package.json +188 -185
  85. package/public/pdf.worker.mjs +65152 -0
  86. package/src/cli/main.ts +7 -2
  87. package/src/language/agentlang.langium +8 -2
  88. package/src/language/generated/ast.ts +96 -2
  89. package/src/language/generated/grammar.ts +432 -218
  90. package/src/language/parser.ts +8 -8
  91. package/src/runtime/agents/common.ts +107 -0
  92. package/src/runtime/agents/impl/anthropic.ts +4 -4
  93. package/src/runtime/agents/impl/openai.ts +4 -4
  94. package/src/runtime/docs.ts +120 -9
  95. package/src/runtime/embeddings/chunker.ts +50 -0
  96. package/src/runtime/embeddings/index.ts +5 -0
  97. package/src/runtime/embeddings/openai.ts +49 -0
  98. package/src/runtime/embeddings/provider.ts +37 -0
  99. package/src/runtime/embeddings/registry.ts +17 -0
  100. package/src/runtime/exec-graph.ts +4 -0
  101. package/src/runtime/interpreter.ts +39 -16
  102. package/src/runtime/loader.ts +42 -3
  103. package/src/runtime/module.ts +127 -41
  104. package/src/runtime/modules/ai.ts +467 -38
  105. package/src/runtime/modules/auth.ts +11 -5
  106. package/src/runtime/resolvers/interface.ts +1 -1
  107. package/src/runtime/resolvers/sqldb/database.ts +146 -56
  108. package/src/runtime/resolvers/sqldb/impl.ts +238 -61
  109. package/src/runtime/state.ts +4 -0
  110. package/src/syntaxes/agentlang.monarch.ts +1 -1
  111. package/out/setupClassic.d.ts +0 -98
  112. package/out/setupClassic.d.ts.map +0 -1
  113. package/out/setupClassic.js +0 -38
  114. package/out/setupClassic.js.map +0 -1
  115. package/out/setupCommon.d.ts +0 -2
  116. package/out/setupCommon.d.ts.map +0 -1
  117. package/out/setupCommon.js +0 -33
  118. package/out/setupCommon.js.map +0 -1
  119. package/out/setupExtended.d.ts +0 -40
  120. package/out/setupExtended.d.ts.map +0 -1
  121. package/out/setupExtended.js +0 -67
  122. package/out/setupExtended.js.map +0 -1
@@ -1,12 +1,19 @@
1
1
  import { Environment } from '../interpreter.js';
2
- import { Decision, Instance } from '../module.js';
2
+ import { AgentEvaluator, Decision, Instance } from '../module.js';
3
3
  import { AgentServiceProvider } from '../agents/provider.js';
4
4
  import { FlowStep } from '../agents/flows.js';
5
5
  export declare const CoreAIModuleName: string;
6
6
  export declare const AgentEntityName = "Agent";
7
7
  export declare const LlmEntityName = "LLM";
8
+ export declare const AgentLearnerType = "learner";
8
9
  declare const _default: string;
9
10
  export default _default;
11
+ declare enum AgentCacheType {
12
+ DIRECTIVE = 0,
13
+ GLOSSARY = 1,
14
+ SCENARIO = 2,
15
+ SUMMARY = 3
16
+ }
10
17
  export declare const AgentFqName: string;
11
18
  export declare class AgentInstance {
12
19
  llm: string;
@@ -38,7 +45,9 @@ export declare class AgentInstance {
38
45
  enableSession(): AgentInstance;
39
46
  hasSession(): boolean;
40
47
  isPlanner(): boolean;
48
+ isLearner(): boolean;
41
49
  isFlowExecutor(): boolean;
50
+ isEvaluator(): boolean;
42
51
  markAsDecisionExecutor(): AgentInstance;
43
52
  isDecisionExecutor(): boolean;
44
53
  private static CACHE_TTL_MS;
@@ -47,8 +56,11 @@ export declare class AgentInstance {
47
56
  private directivesAsString;
48
57
  private static GlossaryCache;
49
58
  private getUserDefinedAgentGlossary;
59
+ private static SummariesCache;
60
+ private getUserDefinedAgentLearningResults;
50
61
  private static ScenariosCache;
51
62
  private getUserDefinedAgentScenarios;
63
+ static ResetCache(fqName: string, type: AgentCacheType): void;
52
64
  private getFullInstructions;
53
65
  private static maybeRewriteTemplatePatterns;
54
66
  maybeValidateJsonResponse(response: string | undefined): object | undefined;
@@ -56,6 +68,9 @@ export declare class AgentInstance {
56
68
  markAsFlowExecutor(): AgentInstance;
57
69
  getScratchNames(): Set<string> | undefined;
58
70
  maybeAddScratchData(env: Environment): AgentInstance;
71
+ private static AgentEvaluators;
72
+ static RegisterEvaluator(e: AgentEvaluator): AgentInstance;
73
+ private static maybeEvaluateResponse;
59
74
  invoke(message: string, env: Environment): Promise<void>;
60
75
  private maybeAddFlowContext;
61
76
  private invokeValidator;
@@ -63,6 +78,8 @@ export declare class AgentInstance {
63
78
  private getValidationEvent;
64
79
  private getExternalToolSpecs;
65
80
  private maybeAddRelevantDocuments;
81
+ private static docTitlesMatch;
82
+ private static getDocumentTitle;
66
83
  private static ToolsCache;
67
84
  private toolsAsString;
68
85
  }
@@ -71,5 +88,6 @@ export declare function findProviderForLLM(llmName: string, env: Environment): P
71
88
  export declare function findAgentChatSession(chatId: string, env: Environment): Promise<Instance | null>;
72
89
  export declare function saveAgentChatSession(chatId: string, messages: any[], env: Environment): Promise<void>;
73
90
  export declare function agentName(agentInstance: Instance): string;
74
- export declare function trimGeneratedCode(code: string | undefined): string;
91
+ export declare function normalizeGeneratedCode(code: string | undefined): string;
92
+ export declare function processAgentLearning(moduleName: string, agentName: string, instruction: string, env: Environment): Promise<any>;
75
93
  //# sourceMappingURL=ai.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ai.d.ts","sourceRoot":"","sources":["../../../src/runtime/modules/ai.ts"],"names":[],"mappings":"AAUA,OAAO,EACL,WAAW,EAIZ,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAEL,QAAQ,EAIR,QAAQ,EAST,MAAM,cAAc,CAAC;AAEtB,OAAO,EACL,oBAAoB,EAKrB,MAAM,uBAAuB,CAAC;AAoB/B,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAK9C,eAAO,MAAM,gBAAgB,QAA2B,CAAC;AACzD,eAAO,MAAM,eAAe,UAAU,CAAC;AACvC,eAAO,MAAM,aAAa,QAAQ,CAAC;;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AG,EAAE,EAAE,GAAG,EAAE,WAAW,iBAM3F;AAED,wBAAgB,SAAS,CAAC,aAAa,EAAE,QAAQ,GAAG,MAAM,CAEzD;AAuBD,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAcvE;AAkFD,wBAAsB,oBAAoB,CACxC,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,EACjB,WAAW,EAAE,MAAM,EACnB,GAAG,EAAE,WAAW,GACf,OAAO,CAAC,GAAG,CAAC,CAQd"}
@@ -1,19 +1,22 @@
1
- import { escapeSpecialChars, isFqName, isString, makeCoreModuleName, makeFqName, nameToPath, sleepMilliseconds, splitFqName, } from '../util.js';
1
+ import { escapeSpecialChars, isFqName, isString, makeCoreModuleName, makeFqName, nameToPath, restoreSpecialChars, sleepMilliseconds, splitFqName, } from '../util.js';
2
2
  import { GlobalEnvironment, makeEventEvaluator, parseAndEvaluateStatement, } from '../interpreter.js';
3
3
  import { asJSONSchema, fetchModule, getDecision, getGlobalRetry, Instance, instanceToObject, isAgent, isInstanceOfType, isModule, makeInstance, newInstanceAttributes, Record, } from '../module.js';
4
4
  import { provider } from '../agents/registry.js';
5
5
  import { assistantMessage, humanMessage, systemMessage, } from '../agents/provider.js';
6
- import { AIMessage, HumanMessage } from '@langchain/core/messages';
7
- import { DecisionAgentInstructions, FlowExecInstructions, getAgentDirectives, getAgentGlossary, getAgentResponseSchema, getAgentScenarios, getAgentScratchNames, newAgentDirective, newAgentGlossaryEntry, newAgentScenario, PlannerInstructions, } from '../agents/common.js';
8
- import { PathAttributeNameQuery } from '../defs.js';
6
+ import { AIMessage, HumanMessage, SystemMessage } from '@langchain/core/messages';
7
+ import { DecisionAgentInstructions, EvalInstructions, FlowExecInstructions, getAgentDirectives, getAgentGlossary, getAgentResponseSchema, getAgentScenarios, getAgentScratchNames, LearningAgentInstructions as LearnerAgentInstructions, newAgentDirective, newAgentGlossaryEntry, newAgentScenario, PlannerInstructions, } from '../agents/common.js';
9
8
  import { logger } from '../logger.js';
10
9
  import Handlebars from 'handlebars';
11
10
  import { isMonitoringEnabled, TtlCache } from '../state.js';
12
11
  export const CoreAIModuleName = makeCoreModuleName('ai');
13
12
  export const AgentEntityName = 'Agent';
14
13
  export const LlmEntityName = 'LLM';
14
+ export const AgentLearnerType = 'learner';
15
+ const AgentEvalType = 'eval';
15
16
  export default `module ${CoreAIModuleName}
16
17
 
18
+ import "./modules/ai.js" @as ai
19
+
17
20
  entity ${LlmEntityName} {
18
21
  name String @id,
19
22
  service String @default("openai"),
@@ -23,7 +26,7 @@ entity ${LlmEntityName} {
23
26
  entity ${AgentEntityName} {
24
27
  name String @id,
25
28
  moduleName String @default("${CoreAIModuleName}"),
26
- type @enum("chat", "planner", "flow-exec") @default("chat"),
29
+ type @enum("chat", "planner", "flow-exec", "${AgentEvalType}", "${AgentLearnerType}") @default("chat"),
27
30
  runWorkflows Boolean @default(true),
28
31
  instruction String @optional,
29
32
  tools String @optional, // comma-separated list of tool names
@@ -82,7 +85,78 @@ entity GlossaryEntry {
82
85
  meaning String,
83
86
  synonyms String @optional
84
87
  }
88
+
89
+ entity EvaluationResult {
90
+ id UUID @id @default(uuid()),
91
+ agentFqName String @indexed,
92
+ userRequest String,
93
+ score Int,
94
+ summary String
95
+ }
96
+
97
+ entity AgentLearningResult {
98
+ id UUID @id @default(uuid()),
99
+ agentFqName String @indexed,
100
+ data String,
101
+ summary String
102
+ }
103
+
104
+ @public event agentLearning{
105
+ agentName String,
106
+ agentModuleName String,
107
+ instruction String
108
+ }
109
+
110
+ workflow agentLearning {
111
+ await ai.processAgentLearning(agentLearning.agentModuleName, agentLearning.agentName, agentLearning.instruction)
112
+ }
85
113
  `;
114
+ var AgentCacheType;
115
+ (function (AgentCacheType) {
116
+ AgentCacheType[AgentCacheType["DIRECTIVE"] = 0] = "DIRECTIVE";
117
+ AgentCacheType[AgentCacheType["GLOSSARY"] = 1] = "GLOSSARY";
118
+ AgentCacheType[AgentCacheType["SCENARIO"] = 2] = "SCENARIO";
119
+ AgentCacheType[AgentCacheType["SUMMARY"] = 3] = "SUMMARY";
120
+ })(AgentCacheType || (AgentCacheType = {}));
121
+ const MAX_USER_DEFINED_GLOSSARY = 20;
122
+ const MAX_USER_DEFINED_DIRECTIVES = 20;
123
+ const MAX_USER_DEFINED_SCENARIOS = 5;
124
+ const MAX_USER_DEFINED_SUMMARIES = 5;
125
+ async function activatedUserDefinedAgentLearnings(objLabel, learningObjects, activator, maxResults) {
126
+ const msg = `Consider the following ${objLabel} (in JSON format):
127
+ ${JSON.stringify(learningObjects)}
128
+
129
+ Return the indices of the ${objLabel} relevant for the following text:
130
+
131
+ ${activator.userMessage}
132
+
133
+ Return the relevant indices and a JSON array of integers with the index starting at zero (0). Do not return any additional comments
134
+ or text.
135
+ `;
136
+ const msgs = new Array();
137
+ msgs.push(new SystemMessage('You are an agent that filters a JSON array and return relevant indices as a JSON array of integers.'));
138
+ msgs.push(new HumanMessage(msg));
139
+ const response = await activator.provider.invoke(msgs, undefined);
140
+ const indices = JSON.parse(normalizeGeneratedCode(response.content));
141
+ if (indices.length == 0 || indices.length == learningObjects.length)
142
+ return learningObjects;
143
+ const result = new Array();
144
+ for (let i = 0; i < indices.length; ++i) {
145
+ if (i >= maxResults)
146
+ break;
147
+ result.push(learningObjects[indices[i]]);
148
+ }
149
+ return result;
150
+ }
151
+ async function activatedUserDefinedAgentGlossary(gls, activator) {
152
+ return await activatedUserDefinedAgentLearnings('glossary entries', gls, activator, MAX_USER_DEFINED_GLOSSARY);
153
+ }
154
+ async function activatedUserDefinedAgentScenarios(scns, activator) {
155
+ return await activatedUserDefinedAgentLearnings('scenarios', scns, activator, MAX_USER_DEFINED_SCENARIOS);
156
+ }
157
+ async function activatedUserDefinedAgentDirectives(dirs, activator) {
158
+ return await activatedUserDefinedAgentLearnings('directives or conditions', dirs, activator, MAX_USER_DEFINED_DIRECTIVES);
159
+ }
86
160
  export const AgentFqName = makeFqName(CoreAIModuleName, AgentEntityName);
87
161
  const ProviderDb = new Map();
88
162
  export class AgentInstance {
@@ -194,9 +268,15 @@ export class AgentInstance {
194
268
  isPlanner() {
195
269
  return this.hasModuleTools || this.type == 'planner';
196
270
  }
271
+ isLearner() {
272
+ return this.type === 'learner';
273
+ }
197
274
  isFlowExecutor() {
198
275
  return this.type == 'flow-exec';
199
276
  }
277
+ isEvaluator() {
278
+ return this.type == AgentEvalType;
279
+ }
200
280
  markAsDecisionExecutor() {
201
281
  this.decisionExecutor = true;
202
282
  return this;
@@ -212,13 +292,15 @@ export class AgentInstance {
212
292
  let r = [];
213
293
  if (result && result.length > 0) {
214
294
  r = result.map((inst) => {
215
- return newAgentDirective(inst.lookup('condition'), inst.lookup('consequent'));
295
+ return newAgentDirective(restoreSpecialChars(inst.lookup('condition')), restoreSpecialChars(inst.lookup('consequent')));
216
296
  });
217
297
  }
218
298
  return AgentInstance.DirectivesCache.set(fqName, r);
219
299
  }
220
- async directivesAsString(fqName) {
221
- const userDirs = await this.getUserDefinedAgentDirectives(fqName);
300
+ async directivesAsString(fqName, activator) {
301
+ let userDirs = await this.getUserDefinedAgentDirectives(fqName);
302
+ if (userDirs.length > MAX_USER_DEFINED_DIRECTIVES)
303
+ userDirs = await activatedUserDefinedAgentDirectives(userDirs, activator);
222
304
  const dirs = getAgentDirectives(fqName) || [];
223
305
  const conds = dirs.concat(userDirs);
224
306
  if (conds.length > 0) {
@@ -244,11 +326,24 @@ export class AgentInstance {
244
326
  let r = [];
245
327
  if (result && result.length > 0) {
246
328
  r = result.map((inst) => {
247
- return newAgentGlossaryEntry(inst.lookup('name'), inst.lookup('meaning'), inst.lookup('synonyms'));
329
+ return newAgentGlossaryEntry(inst.lookup('name'), restoreSpecialChars(inst.lookup('meaning')), inst.lookup('synonyms'));
248
330
  });
249
331
  }
250
332
  return AgentInstance.GlossaryCache.set(fqName, r);
251
333
  }
334
+ async getUserDefinedAgentLearningResults(fqName) {
335
+ const cached = AgentInstance.SummariesCache.get(fqName);
336
+ if (cached !== undefined)
337
+ return cached;
338
+ const result = await parseAndEvaluateStatement(`{${CoreAIModuleName}/AgentLearningResult {agentFqName? "${fqName}"}}`);
339
+ let r = [];
340
+ if (result && result.length > 0) {
341
+ r = result.map((inst) => {
342
+ return { data: inst.lookup('data'), summary: inst.lookup('summary') };
343
+ });
344
+ }
345
+ return AgentInstance.SummariesCache.set(fqName, r);
346
+ }
252
347
  async getUserDefinedAgentScenarios(fqName) {
253
348
  const cached = AgentInstance.ScenariosCache.get(fqName);
254
349
  if (cached !== undefined)
@@ -262,12 +357,30 @@ export class AgentInstance {
262
357
  }
263
358
  return AgentInstance.ScenariosCache.set(fqName, r);
264
359
  }
265
- async getFullInstructions(env) {
360
+ static ResetCache(fqName, type) {
361
+ switch (type) {
362
+ case AgentCacheType.DIRECTIVE:
363
+ AgentInstance.DirectivesCache.delete(fqName);
364
+ break;
365
+ case AgentCacheType.GLOSSARY:
366
+ AgentInstance.GlossaryCache.delete(fqName);
367
+ break;
368
+ case AgentCacheType.SCENARIO:
369
+ AgentInstance.ScenariosCache.delete(fqName);
370
+ break;
371
+ case AgentCacheType.SUMMARY:
372
+ AgentInstance.SummariesCache.delete(fqName);
373
+ break;
374
+ }
375
+ }
376
+ async getFullInstructions(env, activator) {
266
377
  const fqName = this.getFqName();
267
378
  const ins = this.role ? `${this.role}\n${this.instruction || ''}` : this.instruction || '';
268
- let finalInstruction = `${ins} ${await this.directivesAsString(fqName)}`;
379
+ let finalInstruction = `${ins} ${await this.directivesAsString(fqName, activator)}`;
269
380
  const staticGls = getAgentGlossary(fqName) || [];
270
- const userGls = await this.getUserDefinedAgentGlossary(fqName);
381
+ let userGls = await this.getUserDefinedAgentGlossary(fqName);
382
+ if (userGls.length > MAX_USER_DEFINED_GLOSSARY)
383
+ userGls = await activatedUserDefinedAgentGlossary(userGls, activator);
271
384
  const gls = staticGls.concat(userGls);
272
385
  if (gls.length > 0) {
273
386
  const glss = new Array();
@@ -278,7 +391,9 @@ export class AgentInstance {
278
391
  ${glss.join('\n')}\n`;
279
392
  }
280
393
  const staticScns = getAgentScenarios(fqName) || [];
281
- const userScns = await this.getUserDefinedAgentScenarios(fqName);
394
+ let userScns = await this.getUserDefinedAgentScenarios(fqName);
395
+ if (userScns.length > MAX_USER_DEFINED_SCENARIOS)
396
+ userScns = await activatedUserDefinedAgentScenarios(userScns, activator);
282
397
  const scenarios = staticScns.concat(userScns);
283
398
  if (scenarios.length > 0) {
284
399
  const scs = new Array();
@@ -293,6 +408,15 @@ export class AgentInstance {
293
408
  });
294
409
  finalInstruction = `${finalInstruction}\nHere are some example user requests and the corresponding responses you are supposed to produce:\n${scs.join('\n')}`;
295
410
  }
411
+ const summaries = await this.getUserDefinedAgentLearningResults(fqName);
412
+ if (summaries.length > 0) {
413
+ let s = summaries.map((sa) => {
414
+ return restoreSpecialChars(sa.summary);
415
+ });
416
+ if (s.length > MAX_USER_DEFINED_SUMMARIES)
417
+ s = await activatedUserDefinedAgentLearnings('summaries', s, activator, MAX_USER_DEFINED_SUMMARIES);
418
+ finalInstruction = `${finalInstruction}\nAlso keep in mind the following points:\n\n${s.join('\n')}\n\n`;
419
+ }
296
420
  const responseSchema = getAgentResponseSchema(fqName);
297
421
  if (responseSchema) {
298
422
  finalInstruction = `${finalInstruction}\nReturn your response in the following JSON schema:\n${asJSONSchema(responseSchema)}
@@ -321,7 +445,7 @@ Only return a pure JSON object with no extra text, annotations etc.`;
321
445
  if (response) {
322
446
  const responseSchema = getAgentResponseSchema(this.getFqName());
323
447
  if (responseSchema) {
324
- const attrs = JSON.parse(trimGeneratedCode(response));
448
+ const attrs = JSON.parse(normalizeGeneratedCode(response));
325
449
  const parts = nameToPath(responseSchema);
326
450
  const moduleName = parts.getModuleName();
327
451
  const entryName = parts.getEntryName();
@@ -383,16 +507,61 @@ Only return a pure JSON object with no extra text, annotations etc.`;
383
507
  env.addToScratchPad(n, data);
384
508
  return this;
385
509
  }
510
+ static RegisterEvaluator(e) {
511
+ const n = e.normalizedName();
512
+ const agentFqName = isFqName(n) ? n : makeFqName(e.moduleName, n);
513
+ const instruction = e.instruction;
514
+ let llm = e.llm;
515
+ const [agentModule, agentName] = splitFqName(agentFqName);
516
+ if (llm === undefined)
517
+ llm = `${agentName}_llm`;
518
+ const inst = makeInstance(CoreAIModuleName, AgentEntityName, newInstanceAttributes()
519
+ .set('llm', llm)
520
+ .set('name', agentName)
521
+ .set('moduleName', agentModule)
522
+ .set('instruction', instruction || 'You are an agent that evaluates the performance of another agent.')
523
+ .set('type', AgentEvalType));
524
+ const einst = AgentInstance.FromInstance(inst).disableSession();
525
+ this.AgentEvaluators.set(agentFqName, einst);
526
+ return einst;
527
+ }
528
+ static async maybeEvaluateResponse(agent, userRequest, fullRequest, response, env) {
529
+ const fqn = agent.getFqName();
530
+ const e = AgentInstance.AgentEvaluators.get(fqn);
531
+ if (e !== undefined) {
532
+ await e.invoke(JSON.stringify({ requestToAgent: fullRequest, responseFromAgent: response }), env);
533
+ try {
534
+ const r = JSON.parse(normalizeGeneratedCode(env.getLastResult()));
535
+ const score = r.score;
536
+ if (score === undefined || score === null) {
537
+ logger.warn(`Evaluation for agent ${fqn} failed to generate a valid score`);
538
+ }
539
+ else {
540
+ await parseAndEvaluateStatement(`{${CoreAIModuleName}/EvaluationResult {
541
+ agentFqName "${fqn}",
542
+ userRequest "${escapeSpecialChars(userRequest)}",
543
+ score ${score},
544
+ summary "${escapeSpecialChars(r.summary)}"
545
+ }}`);
546
+ }
547
+ }
548
+ catch (reason) {
549
+ logger.warn(`Failed to save evaluation for agent ${fqn} - ${reason}`);
550
+ }
551
+ }
552
+ }
386
553
  async invoke(message, env) {
387
554
  const p = await findProviderForLLM(this.llm, env);
388
555
  const agentName = this.name;
389
556
  const chatId = env.getAgentChatId() || agentName;
390
557
  let isplnr = this.isPlanner();
391
558
  const isflow = !isplnr && this.isFlowExecutor();
392
- if (isplnr && this.withSession) {
559
+ const iseval = !isplnr && !isflow && this.isEvaluator();
560
+ const islearner = !isflow && !isplnr && !iseval && this.isLearner();
561
+ if ((isplnr || islearner || iseval) && this.withSession) {
393
562
  this.withSession = false;
394
563
  }
395
- if (isflow) {
564
+ if (isflow || islearner) {
396
565
  this.withSession = false;
397
566
  }
398
567
  if (this.withSession && env.getFlowContext()) {
@@ -408,20 +577,32 @@ Only return a pure JSON object with no extra text, annotations etc.`;
408
577
  const sess = this.withSession ? await findAgentChatSession(chatId, env) : null;
409
578
  let msgs;
410
579
  let cachedMsg = undefined;
580
+ const activator = {
581
+ provider: p,
582
+ userMessage: message,
583
+ agentInstruction: this.instruction,
584
+ agentRole: this.role,
585
+ };
411
586
  if (sess) {
412
587
  msgs = sess.lookup('messages');
413
588
  }
414
589
  else {
415
- cachedMsg = await this.getFullInstructions(env);
590
+ cachedMsg = await this.getFullInstructions(env, activator);
416
591
  msgs = [systemMessage(cachedMsg || '')];
417
592
  }
418
593
  if (msgs) {
419
594
  try {
420
595
  const sysMsg = msgs[0];
421
- if (isplnr || isflow) {
422
- const s = isplnr ? PlannerInstructions : FlowExecInstructions;
596
+ if (isplnr || isflow || iseval || islearner) {
597
+ const s = isplnr
598
+ ? PlannerInstructions
599
+ : isflow
600
+ ? FlowExecInstructions
601
+ : iseval
602
+ ? EvalInstructions
603
+ : LearnerAgentInstructions;
423
604
  const ts = this.toolsAsString();
424
- const msg = `${s}\n${ts}\n${cachedMsg || (await this.getFullInstructions(env))}`;
605
+ const msg = `${s}\n${ts}\n${cachedMsg || (await this.getFullInstructions(env, activator))}`;
425
606
  const newSysMsg = systemMessage(msg);
426
607
  msgs[0] = newSysMsg;
427
608
  }
@@ -454,6 +635,8 @@ Only return a pure JSON object with no extra text, annotations etc.`;
454
635
  if (v) {
455
636
  response = await this.handleValidation(response, v, msgs, p);
456
637
  }
638
+ if (!iseval)
639
+ await AgentInstance.maybeEvaluateResponse(this, message, msgsContent, response.content, env);
457
640
  msgs.push(assistantMessage(response.content));
458
641
  if (isplnr) {
459
642
  msgs[0] = sysMsg;
@@ -489,7 +672,7 @@ Only return a pure JSON object with no extra text, annotations etc.`;
489
672
  }
490
673
  async invokeValidator(response, validationEventName) {
491
674
  let isstr = true;
492
- const content = trimGeneratedCode(response.content);
675
+ const content = normalizeGeneratedCode(response.content);
493
676
  try {
494
677
  const c = JSON.parse(content);
495
678
  isstr = isString(c);
@@ -575,28 +758,75 @@ Only return a pure JSON object with no extra text, annotations etc.`;
575
758
  }
576
759
  async maybeAddRelevantDocuments(message, env) {
577
760
  if (this.documents && this.documents.length > 0) {
578
- const s = `${message}. Relevant documents are: ${this.documents}`;
579
- const result = await parseHelper(`{${CoreAIModuleName}/Document? "${s}"}`, env);
580
- if (result && result.length > 0) {
581
- const docs = [];
582
- for (let i = 0; i < result.length; ++i) {
583
- const v = result[i];
584
- const r = await parseHelper(`{${CoreAIModuleName}/Document {${PathAttributeNameQuery} "${v.id}"}}`, env);
585
- if (r && r.length > 0) {
586
- docs.push(r[0]);
761
+ try {
762
+ const docNames = this.documents.split(',').map(d => d.trim());
763
+ const searchQuery = message;
764
+ try {
765
+ const semanticResult = await parseHelper(`{${CoreAIModuleName}/Document {content? "${searchQuery.replace(/"/g, '\\"')}"}}`, env);
766
+ if (semanticResult && semanticResult.length > 0) {
767
+ const docs = [];
768
+ for (const doc of semanticResult) {
769
+ const docTitle = doc.lookup ? doc.lookup('title') : doc.title;
770
+ if (AgentInstance.docTitlesMatch(docTitle, docNames)) {
771
+ docs.push(doc instanceof Instance
772
+ ? doc
773
+ : Instance.newWithAttributes(doc, new Map(Object.entries(doc))));
774
+ }
775
+ }
776
+ if (docs.length > 0) {
777
+ return message.concat('\n\nRelevant context from documents:\n').concat(docs
778
+ .map((v) => {
779
+ return `Document: ${v.lookup('title')}\n${v.lookup('content')}`;
780
+ })
781
+ .join('\n\n---\n\n'));
782
+ }
587
783
  }
588
784
  }
589
- if (docs.length > 0) {
590
- message = message.concat('\nUse the additional information given below:\n').concat(docs
591
- .map((v) => {
592
- return v.lookup('content');
593
- })
594
- .join('\n'));
785
+ catch (semanticErr) {
786
+ logger.debug(`Semantic search is not available, falling back to title-based filtering: ${semanticErr}`);
787
+ }
788
+ const result = await parseHelper(`{${CoreAIModuleName}/Document? {}}`, env);
789
+ if (result && result.length > 0) {
790
+ const docs = [];
791
+ for (let i = 0; i < result.length; ++i) {
792
+ const v = result[i];
793
+ const docTitle = AgentInstance.getDocumentTitle(v);
794
+ if (docTitle && docNames.includes(docTitle)) {
795
+ if (v instanceof Instance) {
796
+ docs.push(v);
797
+ }
798
+ }
799
+ }
800
+ if (docs.length > 0) {
801
+ return message.concat('\n\nRelevant context from documents:\n').concat(docs
802
+ .map((v) => {
803
+ return v.lookup('content');
804
+ })
805
+ .join('\n\n'));
806
+ }
595
807
  }
596
808
  }
809
+ catch (err) {
810
+ logger.debug(`Error retrieving documents: ${err}`);
811
+ }
597
812
  }
598
813
  return message;
599
814
  }
815
+ static docTitlesMatch(title, docNames) {
816
+ return title !== undefined && docNames.includes(title);
817
+ }
818
+ static getDocumentTitle(doc) {
819
+ if (typeof doc.lookup === 'function') {
820
+ return doc.lookup('title');
821
+ }
822
+ else if (doc.attributes) {
823
+ return doc.attributes.get('title');
824
+ }
825
+ else if (doc.title) {
826
+ return doc.title;
827
+ }
828
+ return undefined;
829
+ }
600
830
  toolsAsString() {
601
831
  const cachedTools = AgentInstance.ToolsCache.get(this.name);
602
832
  if (cachedTools) {
@@ -648,7 +878,9 @@ Only return a pure JSON object with no extra text, annotations etc.`;
648
878
  AgentInstance.CACHE_TTL_MS = 5 * 60 * 1000; // 5 mins
649
879
  AgentInstance.DirectivesCache = new TtlCache(AgentInstance.CACHE_TTL_MS);
650
880
  AgentInstance.GlossaryCache = new TtlCache(AgentInstance.CACHE_TTL_MS);
881
+ AgentInstance.SummariesCache = new TtlCache(AgentInstance.CACHE_TTL_MS);
651
882
  AgentInstance.ScenariosCache = new TtlCache(AgentInstance.CACHE_TTL_MS);
883
+ AgentInstance.AgentEvaluators = new Map();
652
884
  AgentInstance.ToolsCache = new Map();
653
885
  function extractScratchData(scratchNames, inst) {
654
886
  const data = {};
@@ -768,7 +1000,7 @@ function processScenarioResponse(resp) {
768
1000
  }
769
1001
  return resp;
770
1002
  }
771
- export function trimGeneratedCode(code) {
1003
+ export function normalizeGeneratedCode(code) {
772
1004
  if (code !== undefined) {
773
1005
  let s = code.trim();
774
1006
  if (s.startsWith('```')) {
@@ -784,4 +1016,68 @@ export function trimGeneratedCode(code) {
784
1016
  return '';
785
1017
  }
786
1018
  }
1019
+ async function parseAndInternAgentLearning(moduleName, agentName, learning, env) {
1020
+ const obj = JSON.parse(normalizeGeneratedCode(learning));
1021
+ const fqName = makeFqName(moduleName, agentName);
1022
+ if (obj.decisions) {
1023
+ for (let j = 0; j < obj.decisions.length; ++j) {
1024
+ const conds = obj.decisions[j].conditions;
1025
+ if (conds && conds.length > 0) {
1026
+ AgentInstance.ResetCache(fqName, AgentCacheType.DIRECTIVE);
1027
+ for (let i = 0; i < conds.length; ++i) {
1028
+ const entry = conds[i];
1029
+ const cond = entry.if;
1030
+ const conseq = entry.then;
1031
+ if (cond && conseq) {
1032
+ await parseAndEvaluateStatement(`{${CoreAIModuleName}/Directive {
1033
+ agentFqName "${fqName}",
1034
+ condition "${escapeSpecialChars(cond)}",
1035
+ consequent "${escapeSpecialChars(conseq)}"}}`, env.getActiveUser(), env);
1036
+ }
1037
+ else {
1038
+ throw new Error(`Invalid directive generated - missing 'if' or 'then' in ${learning}`);
1039
+ }
1040
+ }
1041
+ }
1042
+ }
1043
+ }
1044
+ if (obj.glossary) {
1045
+ AgentInstance.ResetCache(fqName, AgentCacheType.GLOSSARY);
1046
+ for (let i = 0; i < obj.glossary.length; ++i) {
1047
+ const word = obj.glossary[i].word;
1048
+ const meaning = obj.glossary[i].meaning;
1049
+ if (word && meaning) {
1050
+ await parseAndEvaluateStatement(`{${CoreAIModuleName}/GlossaryEntry {
1051
+ agentFqName "${fqName}",
1052
+ name "${word}",
1053
+ meaning "${escapeSpecialChars(meaning)}"}}`, env.getActiveUser(), env);
1054
+ }
1055
+ }
1056
+ }
1057
+ if (obj.scenarios) {
1058
+ AgentInstance.ResetCache(fqName, AgentCacheType.SCENARIO);
1059
+ for (let i = 0; i < obj.scenarios.length; ++i) {
1060
+ const user = obj.scenarios[i].user;
1061
+ const ai = obj.scenarios[i].ai;
1062
+ if (user && ai) {
1063
+ await parseAndEvaluateStatement(`{${CoreAIModuleName}/Scenario {
1064
+ agentFqName "${fqName}",
1065
+ user "${escapeSpecialChars(user)}",
1066
+ ai "${escapeSpecialChars(ai)}"}}`, env.getActiveUser(), env);
1067
+ }
1068
+ }
1069
+ }
1070
+ AgentInstance.ResetCache(fqName, AgentCacheType.SUMMARY);
1071
+ const summary = obj.summary;
1072
+ delete obj.summary;
1073
+ await parseAndEvaluateStatement(`{${CoreAIModuleName}/AgentLearningResult {
1074
+ agentFqName "${fqName}",
1075
+ data "${escapeSpecialChars(JSON.stringify(obj))}",
1076
+ summary "${escapeSpecialChars(summary) || ''}"}}`, env.getActiveUser(), env);
1077
+ }
1078
+ export async function processAgentLearning(moduleName, agentName, instruction, env) {
1079
+ const learning = await parseAndEvaluateStatement(`{${moduleName}/${agentName}_${AgentLearnerType} {message \`${instruction}\`}}`, env.getActiveUser(), env);
1080
+ await parseAndInternAgentLearning(moduleName, agentName, learning, env);
1081
+ return { agentLearning: { result: learning } };
1082
+ }
787
1083
  //# sourceMappingURL=ai.js.map