agency-lang 0.0.32 → 0.0.34

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.
@@ -31,6 +31,7 @@ export declare class AgencyGenerator extends BaseGenerator {
31
31
  protected processTimeBlock(node: TimeBlock): string;
32
32
  protected generateLiteral(literal: Literal): string;
33
33
  private generatePromptLiteral;
34
+ private renderObjectLiteral;
34
35
  private generateStringLiteral;
35
36
  private generateMultiLineStringLiteral;
36
37
  protected processPromptLiteral(variableName: string, variableType: VariableType | undefined, node: PromptLiteral): string;
@@ -103,9 +103,28 @@ export class AgencyGenerator extends BaseGenerator {
103
103
  result += `\${${segment.variableName}}`;
104
104
  }
105
105
  }
106
+ if (node.config) {
107
+ result += `", ${this.renderObjectLiteral(node.config)}`;
108
+ }
106
109
  result += `")`;
107
110
  return result;
108
111
  }
112
+ renderObjectLiteral(obj) {
113
+ const entries = Object.entries(obj).map(([key, value]) => {
114
+ let valueStr;
115
+ if (typeof value === "string") {
116
+ valueStr = `"${value}"`;
117
+ }
118
+ else if (typeof value === "object") {
119
+ valueStr = this.renderObjectLiteral(value);
120
+ }
121
+ else {
122
+ valueStr = String(value);
123
+ }
124
+ return `${key}: ${valueStr}`;
125
+ });
126
+ return `{ ${entries.join(", ")} }`;
127
+ }
109
128
  generateStringLiteral(node) {
110
129
  let result = '"';
111
130
  for (const segment of node.segments) {
@@ -196,14 +215,17 @@ export class AgencyGenerator extends BaseGenerator {
196
215
  return `[${items.join(", ")}]`;
197
216
  }
198
217
  processAgencyObject(node) {
218
+ this.increaseIndent();
199
219
  const entries = node.entries.map((entry) => {
200
220
  const valueCode = this.processNode(entry.value).trim();
201
- return `${entry.key}: ${valueCode}`;
221
+ return this.indentStr(`${entry.key}: ${valueCode}`);
202
222
  });
223
+ this.decreaseIndent();
203
224
  if (entries.length === 0) {
204
225
  return `{}`;
205
226
  }
206
- return `{ ${entries.join(", ")} }`;
227
+ let entriesStr = "\n" + entries.join(",\n") + "\n";
228
+ return `{ ${entriesStr}` + this.indentStr("}");
207
229
  }
208
230
  // Access expressions
209
231
  processAccessExpression(node) {
@@ -286,12 +308,12 @@ export class AgencyGenerator extends BaseGenerator {
286
308
  this.decreaseIndent();
287
309
  lines.push(elseBodyLines.join("").trimEnd() + "\n");
288
310
  }
289
- lines.push(this.indentStr(`}\n\n`));
311
+ lines.push(this.indentStr(`}`));
290
312
  return lines.join("");
291
313
  }
292
314
  processReturnStatement(node) {
293
315
  const valueCode = this.processNode(node.value).trim();
294
- return this.indentStr(`return ${valueCode}\n`);
316
+ return this.indentStr(`return ${valueCode}`);
295
317
  }
296
318
  // Utility methods
297
319
  processComment(node) {
@@ -337,7 +359,7 @@ export class AgencyGenerator extends BaseGenerator {
337
359
  return this.indentStr(`+${node.toolName}`);
338
360
  }
339
361
  processSpecialVar(node) {
340
- return this.indentStr(`@${node.name} = ${this.processNode(node.value).trim()}\n`);
362
+ return this.indentStr(`@${node.name} = ${this.processNode(node.value).trim()}`);
341
363
  }
342
364
  indentStr(str) {
343
365
  return `${this.indent()}${str}`;
@@ -119,6 +119,25 @@ export class TypeScriptGenerator extends BaseGenerator {
119
119
  return this.processPromptLiteral(variableName, typeHint, value);
120
120
  }
121
121
  else if (value.type === "functionCall") {
122
+ if (value.functionName === "llm") {
123
+ const args = value.arguments;
124
+ if (args.length === 0) {
125
+ throw new Error(`llm function call must have at least one argument for the prompt.`);
126
+ }
127
+ const promptArg = args[0];
128
+ if (promptArg.type !== "string") {
129
+ throw new Error(`First argument to llm function must be a prompt literal.`);
130
+ }
131
+ const promptConfig = args[1];
132
+ if (promptConfig && promptConfig.type !== "agencyObject") {
133
+ throw new Error(`Second argument to llm function must be an object literal for configuration.`);
134
+ }
135
+ return this.processPromptLiteral(variableName, typeHint, {
136
+ type: "prompt",
137
+ segments: promptArg.segments,
138
+ config: promptConfig,
139
+ });
140
+ }
122
141
  // Direct assignment for other literal types
123
142
  const code = this.processNode(value);
124
143
  return (`const ${variableName}${typeAnnotation} = await ${code.trim()};` + "\n");
@@ -163,7 +182,8 @@ export class TypeScriptGenerator extends BaseGenerator {
163
182
  //this.generatedStatements.push(functionCode);
164
183
  const argsStr = [...interpolatedVars, "__messages"].join(", ");
165
184
  // Generate the function call
166
- return `${functionCode}\nconst ${variableName} = await _${variableName}(${argsStr});` + "\n";
185
+ return (`${functionCode}\nconst ${variableName} = await _${variableName}(${argsStr});` +
186
+ "\n");
167
187
  }
168
188
  processTool(node) {
169
189
  const { functionName, body, parameters } = node;
@@ -364,6 +384,7 @@ export class TypeScriptGenerator extends BaseGenerator {
364
384
  });
365
385
  })
366
386
  .join("\n");
387
+ const clientConfig = prompt.config ? this.processNode(prompt.config) : "{}";
367
388
  this.toolsUsed = []; // reset after use
368
389
  return promptFunction.default({
369
390
  variableName,
@@ -374,6 +395,7 @@ export class TypeScriptGenerator extends BaseGenerator {
374
395
  zodSchema,
375
396
  tools,
376
397
  functionCalls,
398
+ clientConfig,
377
399
  });
378
400
  }
379
401
  processImportStatement(node) {
@@ -2,7 +2,7 @@ import { capture, char, manyWithJoin, noneOf, optional, or, sepBy, seqC, set, su
2
2
  import { accessExpressionParser, indexAccessParser } from "./access.js";
3
3
  import { functionCallParser } from "./functionCall.js";
4
4
  import { literalParser } from "./literals.js";
5
- import { comma, optionalSpaces, optionalSpacesOrNewline } from "./utils.js";
5
+ import { comma, commaWithNewline, optionalSpaces, optionalSpacesOrNewline, } from "./utils.js";
6
6
  export const agencyArrayParser = (input) => {
7
7
  const parser = trace("agencyArrayParser", seqC(set("type", "agencyArray"), char("["), capture(sepBy(comma, or(indexAccessParser, accessExpressionParser, functionCallParser, literalParser, agencyObjectParser, agencyArrayParser)), "items"), char("]")));
8
8
  return parser(input);
@@ -11,4 +11,4 @@ export const agencyObjectKVParser = (input) => {
11
11
  const parser = trace("agencyObjectKVParser", seqC(optionalSpaces, optional(char('"')), capture(manyWithJoin(noneOf('":\n\t ')), "key"), optional(char('"')), optionalSpaces, char(":"), optionalSpaces, capture(or(indexAccessParser, accessExpressionParser, functionCallParser, literalParser, agencyObjectParser, agencyArrayParser), "value")));
12
12
  return parser(input);
13
13
  };
14
- export const agencyObjectParser = seqC(set("type", "agencyObject"), char("{"), optionalSpacesOrNewline, capture(or(sepBy(comma, agencyObjectKVParser), succeed([])), "entries"), optional(char(",")), optionalSpacesOrNewline, char("}"));
14
+ export const agencyObjectParser = seqC(set("type", "agencyObject"), char("{"), optionalSpacesOrNewline, capture(or(sepBy(commaWithNewline, agencyObjectKVParser), succeed([])), "entries"), optional(char(",")), optionalSpacesOrNewline, char("}"));
@@ -1,10 +1,9 @@
1
- import { capture, char, many1WithJoin, or, sepBy, seqC, seqR, set, } from "tarsec";
1
+ import { capture, char, many1WithJoin, or, sepBy, seqC, set, } from "tarsec";
2
2
  import { accessExpressionParser, indexAccessParser } from "./access.js";
3
3
  import { literalParser } from "./literals.js";
4
4
  import { optionalSemicolon } from "./parserUtils.js";
5
- import { optionalSpaces, varNameChar } from "./utils.js";
5
+ import { comma, optionalSpaces, varNameChar } from "./utils.js";
6
6
  import { agencyArrayParser, agencyObjectParser } from "./dataStructures.js";
7
- const comma = seqR(optionalSpaces, char(","), optionalSpaces);
8
7
  export const functionCallParser = (input) => {
9
8
  const parser = seqC(set("type", "functionCall"), capture(many1WithJoin(varNameChar), "functionName"), char("("), optionalSpaces, capture(sepBy(comma, or(agencyArrayParser, agencyObjectParser, indexAccessParser, functionCallParser, accessExpressionParser, literalParser)), "arguments"), optionalSpaces, char(")"), optionalSemicolon);
10
9
  return parser(input);
@@ -5,7 +5,6 @@ export declare const stringTextSegmentParser: Parser<TextSegment>;
5
5
  export declare const multiLineStringTextSegmentParser: Parser<TextSegment>;
6
6
  export declare const interpolationSegmentParser: Parser<InterpolationSegment>;
7
7
  export declare const promptParserBackticks: Parser<PromptLiteral>;
8
- export declare const promptParserLlmFunction: Parser<PromptLiteral>;
9
8
  export declare const promptParser: Parser<PromptLiteral>;
10
9
  export declare const numberParser: Parser<NumberLiteral>;
11
10
  export declare const stringParser: Parser<StringLiteral>;
@@ -1,5 +1,5 @@
1
- import { backtick, optionalSpaces, varNameChar } from "./utils.js";
2
- import { capture, char, digit, letter, many, many1Till, many1WithJoin, manyTillStr, manyWithJoin, map, or, seq, seqC, set, str, } from "tarsec";
1
+ import { backtick, commaWithNewline, optionalSpaces, optionalSpacesOrNewline, varNameChar, } from "./utils.js";
2
+ import { capture, char, digit, letter, many, many1Till, many1WithJoin, manyTillStr, manyWithJoin, map, noneOf, optional, or, sepBy, seq, seqC, set, str, trace, } from "tarsec";
3
3
  export const textSegmentParser = map(many1Till(or(backtick, char("$"))), (text) => ({
4
4
  type: "text",
5
5
  value: text,
@@ -14,11 +14,70 @@ export const multiLineStringTextSegmentParser = map(many1Till(or(str('"""'), cha
14
14
  }));
15
15
  export const interpolationSegmentParser = seqC(set("type", "interpolation"), char("$"), char("{"), capture(manyTillStr("}"), "variableName"), char("}"));
16
16
  export const promptParserBackticks = seqC(set("type", "prompt"), backtick, capture(many(or(textSegmentParser, interpolationSegmentParser)), "segments"), backtick);
17
- export const promptParserLlmFunction = (input) => {
18
- const parser = seqC(set("type", "prompt"), str("llm("), optionalSpaces, capture(map(stringParser, (str) => str.segments), "segments"), optionalSpaces, char(")"));
17
+ const objectParser = (input) => {
18
+ const kvParser = trace("objectKVParser", seqC(optionalSpaces, optional(char('"')), capture(manyWithJoin(noneOf('":\n\t ')), "key"), optional(char('"')), optionalSpaces, char(":"), optionalSpaces, capture(or(literalParser, objectParser),
19
+ // arrayParser,
20
+ "value")));
21
+ const arrayToObj = (arr) => {
22
+ const obj = {};
23
+ arr.forEach(({ key, value }) => {
24
+ obj[key] = value;
25
+ });
26
+ return obj;
27
+ };
28
+ const parser = seq([
29
+ char("{"),
30
+ optionalSpacesOrNewline,
31
+ capture(map(sepBy(commaWithNewline, kvParser), arrayToObj), "entries"),
32
+ optionalSpacesOrNewline,
33
+ char("}"),
34
+ ], (_, captures) => {
35
+ return captures.entries;
36
+ });
19
37
  return parser(input);
20
38
  };
21
- export const promptParser = or(promptParserBackticks, promptParserLlmFunction);
39
+ /* export const promptParserLlmFunctionWithConfig: Parser<PromptLiteral> = (
40
+ input: string,
41
+ ) => {
42
+ const parser = seqC(
43
+ set("type", "prompt"),
44
+ str("llm("),
45
+ optionalSpaces,
46
+ capture(
47
+ map(stringParser, (str) => str.segments),
48
+ "segments",
49
+ ),
50
+ optionalSpaces,
51
+ char(","),
52
+ capture(objectParser, "config"),
53
+ optionalSpaces,
54
+ char(")"),
55
+ );
56
+ return parser(input);
57
+ };
58
+
59
+ export const promptParserLlmFunction: Parser<PromptLiteral> = (
60
+ input: string,
61
+ ) => {
62
+ const parser = seqC(
63
+ set("type", "prompt"),
64
+ str("llm("),
65
+ optionalSpaces,
66
+ capture(
67
+ map(stringParser, (str) => str.segments),
68
+ "segments",
69
+ ),
70
+ optionalSpaces,
71
+ char(")"),
72
+ );
73
+ return parser(input);
74
+ };
75
+ */
76
+ export const promptParser = promptParserBackticks; /* or(
77
+ promptParserBackticks,
78
+ promptParserLlmFunctionWithConfig,
79
+ promptParserLlmFunction,
80
+ ); */
22
81
  export const numberParser = seqC(set("type", "number"), capture(many1WithJoin(or(char("-"), char("."), digit)), "value"));
23
82
  export const stringParser = seqC(set("type", "string"), char('"'), capture(many(or(stringTextSegmentParser, interpolationSegmentParser)), "segments"), char('"'));
24
83
  export const multiLineStringParser = seqC(set("type", "multiLineString"), str('"""'), capture(many(or(multiLineStringTextSegmentParser, interpolationSegmentParser)), "segments"), str('"""'));
@@ -3,4 +3,5 @@ export declare const optionalSpacesOrNewline: Parser<string[]>;
3
3
  export declare const optionalSpaces: Parser<string[]>;
4
4
  export declare const backtick: Parser<"`">;
5
5
  export declare const comma: Parser<(string[] | ",")[]>;
6
+ export declare const commaWithNewline: Parser<(string[] | ",")[]>;
6
7
  export declare const varNameChar: Parser<string>;
@@ -3,4 +3,5 @@ export const optionalSpacesOrNewline = many(space);
3
3
  export const optionalSpaces = many(oneOf(" \t"));
4
4
  export const backtick = char("`");
5
5
  export const comma = seqR(optionalSpaces, char(","), optionalSpaces);
6
+ export const commaWithNewline = seqR(optionalSpacesOrNewline, char(","), optionalSpacesOrNewline);
6
7
  export const varNameChar = oneOf("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_");
@@ -1,4 +1,4 @@
1
- export declare const template = "import { z } from \"zod\";\nimport * as readline from \"readline\";\nimport fs from \"fs\";\nimport { PieMachine, goToNode } from \"piemachine\";\nimport { StatelogClient } from \"statelog-client\";\nimport { nanoid } from \"nanoid\";\nimport { assistantMessage, getClient, userMessage, toolMessage } from \"smoltalk\";\n\nconst statelogHost = \"https://statelog.adit.io\";\nconst traceId = nanoid();\nconst statelogConfig = {\n host: statelogHost,\n traceId: traceId,\n apiKey: process.env.STATELOG_API_KEY || \"\",\n projectId: \"agency-lang\",\n debugMode: false,\n };\nconst statelogClient = new StatelogClient(statelogConfig);\nconst __model: ModelName = \"gpt-4o-mini\";\n\n\nconst getClientWithConfig = (config = {}) => {\n const defaultConfig = {\n openAiApiKey: process.env.OPENAI_API_KEY || \"\",\n googleApiKey: process.env.GEMINI_API_KEY || \"\",\n model: __model,\n logLevel: \"warn\",\n };\n\n return getClient({ ...defaultConfig, ...config });\n};\n\nlet __client = getClientWithConfig();\n\ntype State = {\n messages: string[];\n data: any;\n}\n\n// enable debug logging\nconst graphConfig = {\n debug: {\n log: true,\n logData: true,\n },\n statelog: statelogConfig,\n};\n\n// Define the names of the nodes in the graph\n// Useful for type safety\nconst __nodes = {{{nodes:string}}} as const;\ntype Node = (typeof __nodes)[number];\n\nconst graph = new PieMachine<State, Node>(__nodes, graphConfig);\n\n// builtins\n\nconst not = (val: any): boolean => !val;\nconst eq = (a: any, b: any): boolean => a === b;\nconst neq = (a: any, b: any): boolean => a !== b;\nconst lt = (a: any, b: any): boolean => a < b;\nconst lte = (a: any, b: any): boolean => a <= b;\nconst gt = (a: any, b: any): boolean => a > b;\nconst gte = (a: any, b: any): boolean => a >= b;\nconst and = (a: any, b: any): boolean => a && b;\nconst or = (a: any, b: any): boolean => a || b;\nconst head = <T>(arr: T[]): T | undefined => arr[0];\nconst tail = <T>(arr: T[]): T[] => arr.slice(1);";
1
+ export declare const template = "import { z } from \"zod\";\nimport * as readline from \"readline\";\nimport fs from \"fs\";\nimport { PieMachine, goToNode } from \"piemachine\";\nimport { StatelogClient } from \"statelog-client\";\nimport { nanoid } from \"nanoid\";\nimport { assistantMessage, getClient, userMessage, toolMessage } from \"smoltalk\";\n\nconst statelogHost = \"https://statelog.adit.io\";\nconst traceId = nanoid();\nconst statelogConfig = {\n host: statelogHost,\n traceId: traceId,\n apiKey: process.env.STATELOG_API_KEY || \"\",\n projectId: \"agency-lang\",\n debugMode: false,\n };\nconst statelogClient = new StatelogClient(statelogConfig);\nconst __model: ModelName = \"gpt-4o-mini\";\n\n\nconst getClientWithConfig = (config = {}) => {\n const defaultConfig = {\n openAiApiKey: process.env.OPENAI_API_KEY || \"\",\n googleApiKey: process.env.GEMINI_API_KEY || \"\",\n model: __model,\n logLevel: \"warn\",\n };\n\n return getClient({ ...defaultConfig, ...config });\n};\n\nlet __client = getClientWithConfig();\n\ntype State = {\n messages: string[];\n data: any;\n}\n\n// enable debug logging\nconst graphConfig = {\n debug: {\n log: true,\n logData: true,\n },\n statelog: statelogConfig,\n};\n\n// Define the names of the nodes in the graph\n// Useful for type safety\nconst __nodes = {{{nodes:string}}} as const;\ntype Node = (typeof __nodes)[number];\n\nconst graph = new PieMachine<State, Node>(__nodes, graphConfig);\n\n// builtins\n\nconst not = (val: any): boolean => !val;\nconst eq = (a: any, b: any): boolean => a === b;\nconst neq = (a: any, b: any): boolean => a !== b;\nconst lt = (a: any, b: any): boolean => a < b;\nconst lte = (a: any, b: any): boolean => a <= b;\nconst gt = (a: any, b: any): boolean => a > b;\nconst gte = (a: any, b: any): boolean => a >= b;\nconst and = (a: any, b: any): boolean => a && b;\nconst or = (a: any, b: any): boolean => a || b;\nconst head = <T>(arr: T[]): T | undefined => arr[0];\nconst tail = <T>(arr: T[]): T[] => arr.slice(1);\nconst empty = <T>(arr: T[]): boolean => arr.length === 0;";
2
2
  export type TemplateType = {
3
3
  nodes: string;
4
4
  };
@@ -69,7 +69,8 @@ const gte = (a: any, b: any): boolean => a >= b;
69
69
  const and = (a: any, b: any): boolean => a && b;
70
70
  const or = (a: any, b: any): boolean => a || b;
71
71
  const head = <T>(arr: T[]): T | undefined => arr[0];
72
- const tail = <T>(arr: T[]): T[] => arr.slice(1);`;
72
+ const tail = <T>(arr: T[]): T[] => arr.slice(1);
73
+ const empty = <T>(arr: T[]): boolean => arr.length === 0;`;
73
74
  const render = (args) => {
74
75
  return apply(template, args);
75
76
  };
@@ -1,4 +1,4 @@
1
- export declare const template = "\nasync function _{{{variableName:string}}}({{{argsStr:string}}}): Promise<{{{typeString:string}}}> {\n const __prompt = {{{promptCode:string}}};\n const startTime = performance.now();\n __messages.push(userMessage(__prompt));\n const __tools = {{{tools}}};\n\n {{#hasResponseFormat}}\n // Need to make sure this is always an object\n const __responseFormat = z.object({\n response: {{{zodSchema:string}}}\n });\n {{/hasResponseFormat}}\n {{^hasResponseFormat}}\n const __responseFormat = undefined;\n {{/hasResponseFormat}}\n\n let __completion = await __client.text({\n messages: __messages,\n tools: __tools,\n responseFormat: __responseFormat,\n });\n\n const endTime = performance.now();\n statelogClient.promptCompletion({\n messages: __messages,\n completion: __completion,\n model: __client.getModel(),\n timeTaken: endTime - startTime,\n });\n\n if (!__completion.success) {\n throw new Error(\n `Error getting response from ${__model}: ${__completion.error}`\n );\n }\n\n let responseMessage = __completion.value;\n\n // Handle function calls\n while (responseMessage.toolCalls.length > 0) {\n // Add assistant's response with tool calls to message history\n __messages.push(assistantMessage(responseMessage.output, { toolCalls: responseMessage.toolCalls }));\n let toolCallStartTime, toolCallEndTime;\n\n // Process each tool call\n for (const toolCall of responseMessage.toolCalls) {\n {{{functionCalls:string}}}\n }\n \n const nextStartTime = performance.now();\n let __completion = await __client.text({\n messages: __messages,\n tools: __tools,\n responseFormat: __responseFormat,\n });\n\n const nextEndTime = performance.now();\n\n statelogClient.promptCompletion({\n messages: __messages,\n completion: __completion,\n model: __client.getModel(),\n timeTaken: nextEndTime - nextStartTime,\n });\n\n if (!__completion.success) {\n throw new Error(\n `Error getting response from ${__model}: ${__completion.error}`\n );\n }\n responseMessage = __completion.value;\n }\n\n // Add final assistant response to history\n // not passing tool calls back this time\n __messages.push(assistantMessage(responseMessage.output));\n {{#hasResponseFormat}}\n try {\n const result = JSON.parse(responseMessage.output || \"\");\n return result.response;\n } catch (e) {\n return responseMessage.output;\n // console.error(\"Error parsing response for variable '{{{variableName:string}}}':\", e);\n // console.error(\"Full completion response:\", JSON.stringify(__completion, null, 2));\n // throw e;\n }\n {{/hasResponseFormat}}\n\n {{^hasResponseFormat}}\n return responseMessage.output;\n {{/hasResponseFormat}}\n}\n";
1
+ export declare const template = "\nasync function _{{{variableName:string}}}({{{argsStr:string}}}): Promise<{{{typeString:string}}}> {\n const __prompt = {{{promptCode:string}}};\n const startTime = performance.now();\n __messages.push(userMessage(__prompt));\n const __tools = {{{tools}}};\n\n {{#hasResponseFormat}}\n // Need to make sure this is always an object\n const __responseFormat = z.object({\n response: {{{zodSchema:string}}}\n });\n {{/hasResponseFormat}}\n {{^hasResponseFormat}}\n const __responseFormat = undefined;\n {{/hasResponseFormat}}\n\n const __client = getClientWithConfig({{{clientConfig:string}}});\n\n let __completion = await __client.text({\n messages: __messages,\n tools: __tools,\n responseFormat: __responseFormat,\n });\n\n const endTime = performance.now();\n statelogClient.promptCompletion({\n messages: __messages,\n completion: __completion,\n model: __client.getModel(),\n timeTaken: endTime - startTime,\n });\n\n if (!__completion.success) {\n throw new Error(\n `Error getting response from ${__model}: ${__completion.error}`\n );\n }\n\n let responseMessage = __completion.value;\n\n // Handle function calls\n while (responseMessage.toolCalls.length > 0) {\n // Add assistant's response with tool calls to message history\n __messages.push(assistantMessage(responseMessage.output, { toolCalls: responseMessage.toolCalls }));\n let toolCallStartTime, toolCallEndTime;\n\n // Process each tool call\n for (const toolCall of responseMessage.toolCalls) {\n {{{functionCalls:string}}}\n }\n \n const nextStartTime = performance.now();\n let __completion = await __client.text({\n messages: __messages,\n tools: __tools,\n responseFormat: __responseFormat,\n });\n\n const nextEndTime = performance.now();\n\n statelogClient.promptCompletion({\n messages: __messages,\n completion: __completion,\n model: __client.getModel(),\n timeTaken: nextEndTime - nextStartTime,\n });\n\n if (!__completion.success) {\n throw new Error(\n `Error getting response from ${__model}: ${__completion.error}`\n );\n }\n responseMessage = __completion.value;\n }\n\n // Add final assistant response to history\n // not passing tool calls back this time\n __messages.push(assistantMessage(responseMessage.output));\n {{#hasResponseFormat}}\n try {\n const result = JSON.parse(responseMessage.output || \"\");\n return result.response;\n } catch (e) {\n return responseMessage.output;\n // console.error(\"Error parsing response for variable '{{{variableName:string}}}':\", e);\n // console.error(\"Full completion response:\", JSON.stringify(__completion, null, 2));\n // throw e;\n }\n {{/hasResponseFormat}}\n\n {{^hasResponseFormat}}\n return responseMessage.output;\n {{/hasResponseFormat}}\n}\n";
2
2
  export type TemplateType = {
3
3
  variableName: string;
4
4
  argsStr: string;
@@ -7,6 +7,7 @@ export type TemplateType = {
7
7
  tools: string | boolean | number;
8
8
  hasResponseFormat: boolean;
9
9
  zodSchema: string;
10
+ clientConfig: string;
10
11
  functionCalls: string;
11
12
  };
12
13
  declare const render: (args: TemplateType) => string;
@@ -19,6 +19,8 @@ async function _{{{variableName:string}}}({{{argsStr:string}}}): Promise<{{{type
19
19
  const __responseFormat = undefined;
20
20
  {{/hasResponseFormat}}
21
21
 
22
+ const __client = getClientWithConfig({{{clientConfig:string}}});
23
+
22
24
  let __completion = await __client.text({
23
25
  messages: __messages,
24
26
  tools: __tools,
@@ -1,3 +1,4 @@
1
+ import { AgencyObject } from "./dataStructures.js";
1
2
  export type Literal = NumberLiteral | MultiLineStringLiteral | StringLiteral | VariableNameLiteral | PromptLiteral;
2
3
  export type NumberLiteral = {
3
4
  type: "number";
@@ -27,4 +28,5 @@ export type InterpolationSegment = {
27
28
  export type PromptLiteral = {
28
29
  type: "prompt";
29
30
  segments: PromptSegment[];
31
+ config?: AgencyObject;
30
32
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agency-lang",
3
- "version": "0.0.32",
3
+ "version": "0.0.34",
4
4
  "description": "The Agency language",
5
5
  "main": "lib/index.js",
6
6
  "scripts": {
@@ -41,7 +41,7 @@
41
41
  "homepage": "https://github.com/egonSchiele/agency-lang#readme",
42
42
  "dependencies": {
43
43
  "egonlog": "^0.0.2",
44
- "smoltalk": "^0.0.11",
44
+ "smoltalk": "^0.0.12",
45
45
  "tarsec": "^0.1.1",
46
46
  "typestache": "^0.4.4",
47
47
  "zod": "^4.3.5"
@@ -56,4 +56,4 @@
56
56
  "typescript": "^5.9.3",
57
57
  "vitest": "^4.0.16"
58
58
  }
59
- }
59
+ }