agentlang 0.9.5 → 0.9.6

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 (77) hide show
  1. package/out/extension/main.cjs +250 -250
  2. package/out/extension/main.cjs.map +2 -2
  3. package/out/language/generated/ast.d.ts +80 -3
  4. package/out/language/generated/ast.d.ts.map +1 -1
  5. package/out/language/generated/ast.js +62 -1
  6. package/out/language/generated/ast.js.map +1 -1
  7. package/out/language/generated/grammar.d.ts.map +1 -1
  8. package/out/language/generated/grammar.js +432 -218
  9. package/out/language/generated/grammar.js.map +1 -1
  10. package/out/language/main.cjs +1133 -2510
  11. package/out/language/main.cjs.map +4 -4
  12. package/out/language/parser.js +8 -8
  13. package/out/language/parser.js.map +1 -1
  14. package/out/runtime/agents/common.d.ts +7 -1
  15. package/out/runtime/agents/common.d.ts.map +1 -1
  16. package/out/runtime/agents/common.js +101 -0
  17. package/out/runtime/agents/common.js.map +1 -1
  18. package/out/runtime/agents/impl/anthropic.js +4 -4
  19. package/out/runtime/agents/impl/anthropic.js.map +1 -1
  20. package/out/runtime/agents/impl/openai.js +4 -4
  21. package/out/runtime/agents/impl/openai.js.map +1 -1
  22. package/out/runtime/exec-graph.d.ts.map +1 -1
  23. package/out/runtime/exec-graph.js +5 -0
  24. package/out/runtime/exec-graph.js.map +1 -1
  25. package/out/runtime/interpreter.d.ts +4 -0
  26. package/out/runtime/interpreter.d.ts.map +1 -1
  27. package/out/runtime/interpreter.js +20 -4
  28. package/out/runtime/interpreter.js.map +1 -1
  29. package/out/runtime/loader.d.ts.map +1 -1
  30. package/out/runtime/loader.js +42 -5
  31. package/out/runtime/loader.js.map +1 -1
  32. package/out/runtime/module.d.ts +18 -3
  33. package/out/runtime/module.d.ts.map +1 -1
  34. package/out/runtime/module.js +62 -4
  35. package/out/runtime/module.js.map +1 -1
  36. package/out/runtime/modules/ai.d.ts +18 -2
  37. package/out/runtime/modules/ai.d.ts.map +1 -1
  38. package/out/runtime/modules/ai.js +271 -21
  39. package/out/runtime/modules/ai.js.map +1 -1
  40. package/out/runtime/modules/auth.d.ts.map +1 -1
  41. package/out/runtime/modules/auth.js +11 -5
  42. package/out/runtime/modules/auth.js.map +1 -1
  43. package/out/runtime/resolvers/interface.d.ts +1 -1
  44. package/out/runtime/resolvers/interface.d.ts.map +1 -1
  45. package/out/runtime/resolvers/interface.js.map +1 -1
  46. package/out/runtime/resolvers/sqldb/database.d.ts.map +1 -1
  47. package/out/runtime/resolvers/sqldb/database.js +17 -9
  48. package/out/runtime/resolvers/sqldb/database.js.map +1 -1
  49. package/out/runtime/resolvers/sqldb/impl.d.ts +1 -1
  50. package/out/runtime/resolvers/sqldb/impl.d.ts.map +1 -1
  51. package/out/runtime/resolvers/sqldb/impl.js +2 -2
  52. package/out/runtime/resolvers/sqldb/impl.js.map +1 -1
  53. package/out/runtime/state.d.ts +1 -0
  54. package/out/runtime/state.d.ts.map +1 -1
  55. package/out/runtime/state.js +3 -0
  56. package/out/runtime/state.js.map +1 -1
  57. package/out/syntaxes/agentlang.monarch.js +1 -1
  58. package/out/syntaxes/agentlang.monarch.js.map +1 -1
  59. package/package.json +1 -1
  60. package/src/language/agentlang.langium +8 -2
  61. package/src/language/generated/ast.ts +97 -3
  62. package/src/language/generated/grammar.ts +432 -218
  63. package/src/language/parser.ts +8 -8
  64. package/src/runtime/agents/common.ts +107 -0
  65. package/src/runtime/agents/impl/anthropic.ts +4 -4
  66. package/src/runtime/agents/impl/openai.ts +4 -4
  67. package/src/runtime/exec-graph.ts +4 -0
  68. package/src/runtime/interpreter.ts +23 -4
  69. package/src/runtime/loader.ts +42 -3
  70. package/src/runtime/module.ts +80 -3
  71. package/src/runtime/modules/ai.ts +391 -19
  72. package/src/runtime/modules/auth.ts +11 -5
  73. package/src/runtime/resolvers/interface.ts +1 -1
  74. package/src/runtime/resolvers/sqldb/database.ts +18 -10
  75. package/src/runtime/resolvers/sqldb/impl.ts +3 -3
  76. package/src/runtime/state.ts +4 -0
  77. package/src/syntaxes/agentlang.monarch.ts +1 -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;
@@ -71,5 +86,6 @@ export declare function findProviderForLLM(llmName: string, env: Environment): P
71
86
  export declare function findAgentChatSession(chatId: string, env: Environment): Promise<Instance | null>;
72
87
  export declare function saveAgentChatSession(chatId: string, messages: any[], env: Environment): Promise<void>;
73
88
  export declare function agentName(agentInstance: Instance): string;
74
- export declare function trimGeneratedCode(code: string | undefined): string;
89
+ export declare function normalizeGeneratedCode(code: string | undefined): string;
90
+ export declare function processAgentLearning(moduleName: string, agentName: string, instruction: string, env: Environment): Promise<any>;
75
91
  //# 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;;AAEnC,wBAsEE;AAEF,eAAO,MAAM,WAAW,QAAgD,CAAC;AAIzE,qBAAa,aAAa;IACxB,GAAG,EAAE,MAAM,CAAM;IACjB,IAAI,EAAE,MAAM,CAAM;IAClB,UAAU,EAAE,MAAM,CAAoB;IACtC,WAAW,EAAE,MAAM,CAAM;IACzB,IAAI,EAAE,MAAM,CAAU;IACtB,KAAK,EAAE,MAAM,GAAG,SAAS,CAAC;IAC1B,SAAS,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9B,QAAQ,EAAE,MAAM,GAAG,SAA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seconds, 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';
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';
8
8
  import { PathAttributeNameQuery } from '../defs.js';
9
9
  import { logger } from '../logger.js';
10
10
  import Handlebars from 'handlebars';
@@ -12,8 +12,12 @@ import { isMonitoringEnabled, TtlCache } from '../state.js';
12
12
  export const CoreAIModuleName = makeCoreModuleName('ai');
13
13
  export const AgentEntityName = 'Agent';
14
14
  export const LlmEntityName = 'LLM';
15
+ export const AgentLearnerType = 'learner';
16
+ const AgentEvalType = 'eval';
15
17
  export default `module ${CoreAIModuleName}
16
18
 
19
+ import "./modules/ai.js" @as ai
20
+
17
21
  entity ${LlmEntityName} {
18
22
  name String @id,
19
23
  service String @default("openai"),
@@ -23,7 +27,7 @@ entity ${LlmEntityName} {
23
27
  entity ${AgentEntityName} {
24
28
  name String @id,
25
29
  moduleName String @default("${CoreAIModuleName}"),
26
- type @enum("chat", "planner", "flow-exec") @default("chat"),
30
+ type @enum("chat", "planner", "flow-exec", "${AgentEvalType}", "${AgentLearnerType}") @default("chat"),
27
31
  runWorkflows Boolean @default(true),
28
32
  instruction String @optional,
29
33
  tools String @optional, // comma-separated list of tool names
@@ -82,7 +86,78 @@ entity GlossaryEntry {
82
86
  meaning String,
83
87
  synonyms String @optional
84
88
  }
89
+
90
+ entity EvaluationResult {
91
+ id UUID @id @default(uuid()),
92
+ agentFqName String @indexed,
93
+ userRequest String,
94
+ score Int,
95
+ summary String
96
+ }
97
+
98
+ entity AgentLearningResult {
99
+ id UUID @id @default(uuid()),
100
+ agentFqName String @indexed,
101
+ data String,
102
+ summary String
103
+ }
104
+
105
+ @public event agentLearning{
106
+ agentName String,
107
+ agentModuleName String,
108
+ instruction String
109
+ }
110
+
111
+ workflow agentLearning {
112
+ await ai.processAgentLearning(agentLearning.agentModuleName, agentLearning.agentName, agentLearning.instruction)
113
+ }
85
114
  `;
115
+ var AgentCacheType;
116
+ (function (AgentCacheType) {
117
+ AgentCacheType[AgentCacheType["DIRECTIVE"] = 0] = "DIRECTIVE";
118
+ AgentCacheType[AgentCacheType["GLOSSARY"] = 1] = "GLOSSARY";
119
+ AgentCacheType[AgentCacheType["SCENARIO"] = 2] = "SCENARIO";
120
+ AgentCacheType[AgentCacheType["SUMMARY"] = 3] = "SUMMARY";
121
+ })(AgentCacheType || (AgentCacheType = {}));
122
+ const MAX_USER_DEFINED_GLOSSARY = 20;
123
+ const MAX_USER_DEFINED_DIRECTIVES = 20;
124
+ const MAX_USER_DEFINED_SCENARIOS = 5;
125
+ const MAX_USER_DEFINED_SUMMARIES = 5;
126
+ async function activatedUserDefinedAgentLearnings(objLabel, learningObjects, activator, maxResults) {
127
+ const msg = `Consider the following ${objLabel} (in JSON format):
128
+ ${JSON.stringify(learningObjects)}
129
+
130
+ Return the indices of the ${objLabel} relevant for the following text:
131
+
132
+ ${activator.userMessage}
133
+
134
+ Return the relevant indices and a JSON array of integers with the index starting at zero (0). Do not return any additional comments
135
+ or text.
136
+ `;
137
+ const msgs = new Array();
138
+ msgs.push(new SystemMessage('You are an agent that filters a JSON array and return relevant indices as a JSON array of integers.'));
139
+ msgs.push(new HumanMessage(msg));
140
+ const response = await activator.provider.invoke(msgs, undefined);
141
+ const indices = JSON.parse(normalizeGeneratedCode(response.content));
142
+ if (indices.length == 0 || indices.length == learningObjects.length)
143
+ return learningObjects;
144
+ const result = new Array();
145
+ for (let i = 0; i < indices.length; ++i) {
146
+ if (i >= maxResults)
147
+ break;
148
+ result.push(learningObjects[indices[i]]);
149
+ }
150
+ return result;
151
+ }
152
+ async function activatedUserDefinedAgentGlossary(gls, activator) {
153
+ return await activatedUserDefinedAgentLearnings('glossary entries', gls, activator, MAX_USER_DEFINED_GLOSSARY);
154
+ }
155
+ async function activatedUserDefinedAgentScenarios(scns, activator) {
156
+ return await activatedUserDefinedAgentLearnings('scenarios', scns, activator, MAX_USER_DEFINED_SCENARIOS);
157
+ }
158
+ async function activatedUserDefinedAgentDirectives(dirs, activator) {
159
+ return await activatedUserDefinedAgentLearnings('directives or conditions', dirs, activator, MAX_USER_DEFINED_DIRECTIVES);
160
+ }
86
161
  export const AgentFqName = makeFqName(CoreAIModuleName, AgentEntityName);
87
162
  const ProviderDb = new Map();
88
163
  export class AgentInstance {
@@ -194,9 +269,15 @@ export class AgentInstance {
194
269
  isPlanner() {
195
270
  return this.hasModuleTools || this.type == 'planner';
196
271
  }
272
+ isLearner() {
273
+ return this.type === 'learner';
274
+ }
197
275
  isFlowExecutor() {
198
276
  return this.type == 'flow-exec';
199
277
  }
278
+ isEvaluator() {
279
+ return this.type == AgentEvalType;
280
+ }
200
281
  markAsDecisionExecutor() {
201
282
  this.decisionExecutor = true;
202
283
  return this;
@@ -212,13 +293,15 @@ export class AgentInstance {
212
293
  let r = [];
213
294
  if (result && result.length > 0) {
214
295
  r = result.map((inst) => {
215
- return newAgentDirective(inst.lookup('condition'), inst.lookup('consequent'));
296
+ return newAgentDirective(restoreSpecialChars(inst.lookup('condition')), restoreSpecialChars(inst.lookup('consequent')));
216
297
  });
217
298
  }
218
299
  return AgentInstance.DirectivesCache.set(fqName, r);
219
300
  }
220
- async directivesAsString(fqName) {
221
- const userDirs = await this.getUserDefinedAgentDirectives(fqName);
301
+ async directivesAsString(fqName, activator) {
302
+ let userDirs = await this.getUserDefinedAgentDirectives(fqName);
303
+ if (userDirs.length > MAX_USER_DEFINED_DIRECTIVES)
304
+ userDirs = await activatedUserDefinedAgentDirectives(userDirs, activator);
222
305
  const dirs = getAgentDirectives(fqName) || [];
223
306
  const conds = dirs.concat(userDirs);
224
307
  if (conds.length > 0) {
@@ -244,11 +327,24 @@ export class AgentInstance {
244
327
  let r = [];
245
328
  if (result && result.length > 0) {
246
329
  r = result.map((inst) => {
247
- return newAgentGlossaryEntry(inst.lookup('name'), inst.lookup('meaning'), inst.lookup('synonyms'));
330
+ return newAgentGlossaryEntry(inst.lookup('name'), restoreSpecialChars(inst.lookup('meaning')), inst.lookup('synonyms'));
248
331
  });
249
332
  }
250
333
  return AgentInstance.GlossaryCache.set(fqName, r);
251
334
  }
335
+ async getUserDefinedAgentLearningResults(fqName) {
336
+ const cached = AgentInstance.SummariesCache.get(fqName);
337
+ if (cached !== undefined)
338
+ return cached;
339
+ const result = await parseAndEvaluateStatement(`{${CoreAIModuleName}/AgentLearningResult {agentFqName? "${fqName}"}}`);
340
+ let r = [];
341
+ if (result && result.length > 0) {
342
+ r = result.map((inst) => {
343
+ return { data: inst.lookup('data'), summary: inst.lookup('summary') };
344
+ });
345
+ }
346
+ return AgentInstance.SummariesCache.set(fqName, r);
347
+ }
252
348
  async getUserDefinedAgentScenarios(fqName) {
253
349
  const cached = AgentInstance.ScenariosCache.get(fqName);
254
350
  if (cached !== undefined)
@@ -262,12 +358,30 @@ export class AgentInstance {
262
358
  }
263
359
  return AgentInstance.ScenariosCache.set(fqName, r);
264
360
  }
265
- async getFullInstructions(env) {
361
+ static ResetCache(fqName, type) {
362
+ switch (type) {
363
+ case AgentCacheType.DIRECTIVE:
364
+ AgentInstance.DirectivesCache.delete(fqName);
365
+ break;
366
+ case AgentCacheType.GLOSSARY:
367
+ AgentInstance.GlossaryCache.delete(fqName);
368
+ break;
369
+ case AgentCacheType.SCENARIO:
370
+ AgentInstance.ScenariosCache.delete(fqName);
371
+ break;
372
+ case AgentCacheType.SUMMARY:
373
+ AgentInstance.SummariesCache.delete(fqName);
374
+ break;
375
+ }
376
+ }
377
+ async getFullInstructions(env, activator) {
266
378
  const fqName = this.getFqName();
267
379
  const ins = this.role ? `${this.role}\n${this.instruction || ''}` : this.instruction || '';
268
- let finalInstruction = `${ins} ${await this.directivesAsString(fqName)}`;
380
+ let finalInstruction = `${ins} ${await this.directivesAsString(fqName, activator)}`;
269
381
  const staticGls = getAgentGlossary(fqName) || [];
270
- const userGls = await this.getUserDefinedAgentGlossary(fqName);
382
+ let userGls = await this.getUserDefinedAgentGlossary(fqName);
383
+ if (userGls.length > MAX_USER_DEFINED_GLOSSARY)
384
+ userGls = await activatedUserDefinedAgentGlossary(userGls, activator);
271
385
  const gls = staticGls.concat(userGls);
272
386
  if (gls.length > 0) {
273
387
  const glss = new Array();
@@ -278,7 +392,9 @@ export class AgentInstance {
278
392
  ${glss.join('\n')}\n`;
279
393
  }
280
394
  const staticScns = getAgentScenarios(fqName) || [];
281
- const userScns = await this.getUserDefinedAgentScenarios(fqName);
395
+ let userScns = await this.getUserDefinedAgentScenarios(fqName);
396
+ if (userScns.length > MAX_USER_DEFINED_SCENARIOS)
397
+ userScns = await activatedUserDefinedAgentScenarios(userScns, activator);
282
398
  const scenarios = staticScns.concat(userScns);
283
399
  if (scenarios.length > 0) {
284
400
  const scs = new Array();
@@ -293,6 +409,15 @@ export class AgentInstance {
293
409
  });
294
410
  finalInstruction = `${finalInstruction}\nHere are some example user requests and the corresponding responses you are supposed to produce:\n${scs.join('\n')}`;
295
411
  }
412
+ const summaries = await this.getUserDefinedAgentLearningResults(fqName);
413
+ if (summaries.length > 0) {
414
+ let s = summaries.map((sa) => {
415
+ return restoreSpecialChars(sa.summary);
416
+ });
417
+ if (s.length > MAX_USER_DEFINED_SUMMARIES)
418
+ s = await activatedUserDefinedAgentLearnings('summaries', s, activator, MAX_USER_DEFINED_SUMMARIES);
419
+ finalInstruction = `${finalInstruction}\nAlso keep in mind the following points:\n\n${s.join('\n')}\n\n`;
420
+ }
296
421
  const responseSchema = getAgentResponseSchema(fqName);
297
422
  if (responseSchema) {
298
423
  finalInstruction = `${finalInstruction}\nReturn your response in the following JSON schema:\n${asJSONSchema(responseSchema)}
@@ -321,7 +446,7 @@ Only return a pure JSON object with no extra text, annotations etc.`;
321
446
  if (response) {
322
447
  const responseSchema = getAgentResponseSchema(this.getFqName());
323
448
  if (responseSchema) {
324
- const attrs = JSON.parse(trimGeneratedCode(response));
449
+ const attrs = JSON.parse(normalizeGeneratedCode(response));
325
450
  const parts = nameToPath(responseSchema);
326
451
  const moduleName = parts.getModuleName();
327
452
  const entryName = parts.getEntryName();
@@ -383,16 +508,61 @@ Only return a pure JSON object with no extra text, annotations etc.`;
383
508
  env.addToScratchPad(n, data);
384
509
  return this;
385
510
  }
511
+ static RegisterEvaluator(e) {
512
+ const n = e.normalizedName();
513
+ const agentFqName = isFqName(n) ? n : makeFqName(e.moduleName, n);
514
+ const instruction = e.instruction;
515
+ let llm = e.llm;
516
+ const [agentModule, agentName] = splitFqName(agentFqName);
517
+ if (llm === undefined)
518
+ llm = `${agentName}_llm`;
519
+ const inst = makeInstance(CoreAIModuleName, AgentEntityName, newInstanceAttributes()
520
+ .set('llm', llm)
521
+ .set('name', agentName)
522
+ .set('moduleName', agentModule)
523
+ .set('instruction', instruction || 'You are an agent that evaluates the performance of another agent.')
524
+ .set('type', AgentEvalType));
525
+ const einst = AgentInstance.FromInstance(inst).disableSession();
526
+ this.AgentEvaluators.set(agentFqName, einst);
527
+ return einst;
528
+ }
529
+ static async maybeEvaluateResponse(agent, userRequest, fullRequest, response, env) {
530
+ const fqn = agent.getFqName();
531
+ const e = AgentInstance.AgentEvaluators.get(fqn);
532
+ if (e !== undefined) {
533
+ await e.invoke(JSON.stringify({ requestToAgent: fullRequest, responseFromAgent: response }), env);
534
+ try {
535
+ const r = JSON.parse(normalizeGeneratedCode(env.getLastResult()));
536
+ const score = r.score;
537
+ if (score === undefined || score === null) {
538
+ logger.warn(`Evaluation for agent ${fqn} failed to generate a valid score`);
539
+ }
540
+ else {
541
+ await parseAndEvaluateStatement(`{${CoreAIModuleName}/EvaluationResult {
542
+ agentFqName "${fqn}",
543
+ userRequest "${escapeSpecialChars(userRequest)}",
544
+ score ${score},
545
+ summary "${escapeSpecialChars(r.summary)}"
546
+ }}`);
547
+ }
548
+ }
549
+ catch (reason) {
550
+ logger.warn(`Failed to save evaluation for agent ${fqn} - ${reason}`);
551
+ }
552
+ }
553
+ }
386
554
  async invoke(message, env) {
387
555
  const p = await findProviderForLLM(this.llm, env);
388
556
  const agentName = this.name;
389
557
  const chatId = env.getAgentChatId() || agentName;
390
558
  let isplnr = this.isPlanner();
391
559
  const isflow = !isplnr && this.isFlowExecutor();
392
- if (isplnr && this.withSession) {
560
+ const iseval = !isplnr && !isflow && this.isEvaluator();
561
+ const islearner = !isflow && !isplnr && !iseval && this.isLearner();
562
+ if ((isplnr || islearner || iseval) && this.withSession) {
393
563
  this.withSession = false;
394
564
  }
395
- if (isflow) {
565
+ if (isflow || islearner) {
396
566
  this.withSession = false;
397
567
  }
398
568
  if (this.withSession && env.getFlowContext()) {
@@ -408,20 +578,32 @@ Only return a pure JSON object with no extra text, annotations etc.`;
408
578
  const sess = this.withSession ? await findAgentChatSession(chatId, env) : null;
409
579
  let msgs;
410
580
  let cachedMsg = undefined;
581
+ const activator = {
582
+ provider: p,
583
+ userMessage: message,
584
+ agentInstruction: this.instruction,
585
+ agentRole: this.role,
586
+ };
411
587
  if (sess) {
412
588
  msgs = sess.lookup('messages');
413
589
  }
414
590
  else {
415
- cachedMsg = await this.getFullInstructions(env);
591
+ cachedMsg = await this.getFullInstructions(env, activator);
416
592
  msgs = [systemMessage(cachedMsg || '')];
417
593
  }
418
594
  if (msgs) {
419
595
  try {
420
596
  const sysMsg = msgs[0];
421
- if (isplnr || isflow) {
422
- const s = isplnr ? PlannerInstructions : FlowExecInstructions;
597
+ if (isplnr || isflow || iseval || islearner) {
598
+ const s = isplnr
599
+ ? PlannerInstructions
600
+ : isflow
601
+ ? FlowExecInstructions
602
+ : iseval
603
+ ? EvalInstructions
604
+ : LearnerAgentInstructions;
423
605
  const ts = this.toolsAsString();
424
- const msg = `${s}\n${ts}\n${cachedMsg || (await this.getFullInstructions(env))}`;
606
+ const msg = `${s}\n${ts}\n${cachedMsg || (await this.getFullInstructions(env, activator))}`;
425
607
  const newSysMsg = systemMessage(msg);
426
608
  msgs[0] = newSysMsg;
427
609
  }
@@ -454,6 +636,8 @@ Only return a pure JSON object with no extra text, annotations etc.`;
454
636
  if (v) {
455
637
  response = await this.handleValidation(response, v, msgs, p);
456
638
  }
639
+ if (!iseval)
640
+ await AgentInstance.maybeEvaluateResponse(this, message, msgsContent, response.content, env);
457
641
  msgs.push(assistantMessage(response.content));
458
642
  if (isplnr) {
459
643
  msgs[0] = sysMsg;
@@ -489,7 +673,7 @@ Only return a pure JSON object with no extra text, annotations etc.`;
489
673
  }
490
674
  async invokeValidator(response, validationEventName) {
491
675
  let isstr = true;
492
- const content = trimGeneratedCode(response.content);
676
+ const content = normalizeGeneratedCode(response.content);
493
677
  try {
494
678
  const c = JSON.parse(content);
495
679
  isstr = isString(c);
@@ -648,7 +832,9 @@ Only return a pure JSON object with no extra text, annotations etc.`;
648
832
  AgentInstance.CACHE_TTL_MS = 5 * 60 * 1000; // 5 mins
649
833
  AgentInstance.DirectivesCache = new TtlCache(AgentInstance.CACHE_TTL_MS);
650
834
  AgentInstance.GlossaryCache = new TtlCache(AgentInstance.CACHE_TTL_MS);
835
+ AgentInstance.SummariesCache = new TtlCache(AgentInstance.CACHE_TTL_MS);
651
836
  AgentInstance.ScenariosCache = new TtlCache(AgentInstance.CACHE_TTL_MS);
837
+ AgentInstance.AgentEvaluators = new Map();
652
838
  AgentInstance.ToolsCache = new Map();
653
839
  function extractScratchData(scratchNames, inst) {
654
840
  const data = {};
@@ -768,7 +954,7 @@ function processScenarioResponse(resp) {
768
954
  }
769
955
  return resp;
770
956
  }
771
- export function trimGeneratedCode(code) {
957
+ export function normalizeGeneratedCode(code) {
772
958
  if (code !== undefined) {
773
959
  let s = code.trim();
774
960
  if (s.startsWith('```')) {
@@ -784,4 +970,68 @@ export function trimGeneratedCode(code) {
784
970
  return '';
785
971
  }
786
972
  }
973
+ async function parseAndInternAgentLearning(moduleName, agentName, learning, env) {
974
+ const obj = JSON.parse(normalizeGeneratedCode(learning));
975
+ const fqName = makeFqName(moduleName, agentName);
976
+ if (obj.decisions) {
977
+ for (let j = 0; j < obj.decisions.length; ++j) {
978
+ const conds = obj.decisions[j].conditions;
979
+ if (conds && conds.length > 0) {
980
+ AgentInstance.ResetCache(fqName, AgentCacheType.DIRECTIVE);
981
+ for (let i = 0; i < conds.length; ++i) {
982
+ const entry = conds[i];
983
+ const cond = entry.if;
984
+ const conseq = entry.then;
985
+ if (cond && conseq) {
986
+ await parseAndEvaluateStatement(`{${CoreAIModuleName}/Directive {
987
+ agentFqName "${fqName}",
988
+ condition "${escapeSpecialChars(cond)}",
989
+ consequent "${escapeSpecialChars(conseq)}"}}`, env.getActiveUser(), env);
990
+ }
991
+ else {
992
+ throw new Error(`Invalid directive generated - missing 'if' or 'then' in ${learning}`);
993
+ }
994
+ }
995
+ }
996
+ }
997
+ }
998
+ if (obj.glossary) {
999
+ AgentInstance.ResetCache(fqName, AgentCacheType.GLOSSARY);
1000
+ for (let i = 0; i < obj.glossary.length; ++i) {
1001
+ const word = obj.glossary[i].word;
1002
+ const meaning = obj.glossary[i].meaning;
1003
+ if (word && meaning) {
1004
+ await parseAndEvaluateStatement(`{${CoreAIModuleName}/GlossaryEntry {
1005
+ agentFqName "${fqName}",
1006
+ name "${word}",
1007
+ meaning "${escapeSpecialChars(meaning)}"}}`, env.getActiveUser(), env);
1008
+ }
1009
+ }
1010
+ }
1011
+ if (obj.scenarios) {
1012
+ AgentInstance.ResetCache(fqName, AgentCacheType.SCENARIO);
1013
+ for (let i = 0; i < obj.scenarios.length; ++i) {
1014
+ const user = obj.scenarios[i].user;
1015
+ const ai = obj.scenarios[i].ai;
1016
+ if (user && ai) {
1017
+ await parseAndEvaluateStatement(`{${CoreAIModuleName}/Scenario {
1018
+ agentFqName "${fqName}",
1019
+ user "${escapeSpecialChars(user)}",
1020
+ ai "${escapeSpecialChars(ai)}"}}`, env.getActiveUser(), env);
1021
+ }
1022
+ }
1023
+ }
1024
+ AgentInstance.ResetCache(fqName, AgentCacheType.SUMMARY);
1025
+ const summary = obj.summary;
1026
+ delete obj.summary;
1027
+ await parseAndEvaluateStatement(`{${CoreAIModuleName}/AgentLearningResult {
1028
+ agentFqName "${fqName}",
1029
+ data "${escapeSpecialChars(JSON.stringify(obj))}",
1030
+ summary "${escapeSpecialChars(summary) || ''}"}}`, env.getActiveUser(), env);
1031
+ }
1032
+ export async function processAgentLearning(moduleName, agentName, instruction, env) {
1033
+ const learning = await parseAndEvaluateStatement(`{${moduleName}/${agentName}_${AgentLearnerType} {message \`${instruction}\`}}`, env.getActiveUser(), env);
1034
+ await parseAndInternAgentLearning(moduleName, agentName, learning, env);
1035
+ return { agentLearning: { result: learning } };
1036
+ }
787
1037
  //# sourceMappingURL=ai.js.map