Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add support for handlebars templating engine as an option #1136

Merged
merged 3 commits into from
Dec 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 64 additions & 23 deletions docs/docs/api/functions/composeContext.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,44 +2,85 @@

> **composeContext**(`params`): `string`

Composes a context string by replacing placeholders in a template with corresponding values from the state.

This function takes a template string with placeholders in the format `{{placeholder}}` and a state object.
It replaces each placeholder with the value from the state object that matches the placeholder's name.
If a matching key is not found in the state object for a given placeholder, the placeholder is replaced with an empty string.
Composes a context string by replacing placeholders in a template with values from a state object. Supports both simple string replacement and the Handlebars templating engine.

## Parameters

• **params**

The parameters for composing the context.
### **params**: `Object`

• **params.state**: [`State`](../interfaces/State.md)
An object containing the following properties:

The state object containing values to replace the placeholders in the template.
- **state**: `State`
The state object containing key-value pairs for replacing placeholders in the template.

• **params.template**: `string`
- **template**: `string`
A string containing placeholders in the format `{{placeholder}}`.

The template string containing placeholders to be replaced with state values.
- **templatingEngine**: `"handlebars" | undefined` *(optional)*
The templating engine to use. If set to `"handlebars"`, the Handlebars engine is used for template compilation. Defaults to `undefined` (simple string replacement).

## Returns

`string`

The composed context string with placeholders replaced by corresponding state values.
The context string with placeholders replaced by corresponding values from the state object. If a placeholder has no matching key in the state, it is replaced with an empty string.

## Examples

## Example
### Simple Example

```ts
// Given a state object and a template
```javascript
const state = { userName: "Alice", userAge: 30 };
const template = "Hello, {{userName}}! You are {{userAge}} years old";
const template = "Hello, {{userName}}! You are {{userAge}} years old.";

// Composing the context will result in:
// "Hello, Alice! You are 30 years old."
const context = composeContext({ state, template });
```
// Simple string replacement
const contextSimple = composeContext({ state, template });
// Output: "Hello, Alice! You are 30 years old."

## Defined in
// Handlebars templating
const contextHandlebars = composeContext({ state, template, templatingEngine: 'handlebars' });
// Output: "Hello, Alice! You are 30 years old."
```

[packages/core/src/context.ts:24](https://github.com/ai16z/eliza/blob/7fcf54e7fb2ba027d110afcc319c0b01b3f181dc/packages/core/src/context.ts#L24)
### Advanced Example

```javascript
const advancedTemplate = `
{{#if userAge}}
Hello, {{userName}}!
{{#if (gt userAge 18)}}You are an adult.{{else}}You are a minor.{{/if}}
{{else}}
Hello! We don't know your age.
{{/if}}

{{#if favoriteColors.length}}
Your favorite colors are:
{{#each favoriteColors}}
- {{this}}
{{/each}}
{{else}}
You didn't specify any favorite colors.
{{/if}}
`;

const advancedState = {
userName: "Alice",
userAge: 30,
favoriteColors: ["blue", "green", "red"]
};

// Composing the context with Handlebars
const advancedContextHandlebars = composeContext({
state: advancedState,
template: advancedTemplate,
templatingEngine: 'handlebars'
});
// Output:
// Hello, Alice!
// You are an adult.
//
// Your favorite colors are:
// - blue
// - green
// - red
```
1 change: 1 addition & 0 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
"fastestsmallesttextencoderdecoder": "1.0.22",
"gaxios": "6.7.1",
"glob": "11.0.0",
"handlebars": "^4.7.8",
"js-sha1": "0.7.0",
"js-tiktoken": "1.0.15",
"langchain": "0.3.6",
Expand Down
15 changes: 13 additions & 2 deletions packages/core/src/context.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import handlebars from "handlebars";
import { type State } from "./types.ts";

/**
Expand All @@ -7,27 +8,37 @@ import { type State } from "./types.ts";
* It replaces each placeholder with the value from the state object that matches the placeholder's name.
* If a matching key is not found in the state object for a given placeholder, the placeholder is replaced with an empty string.
*
* By default, this function uses a simple string replacement approach. However, when `templatingEngine` is set to `'handlebars'`, it uses Handlebars templating engine instead, compiling the template into a reusable function and evaluating it with the provided state object.
*
* @param {Object} params - The parameters for composing the context.
* @param {State} params.state - The state object containing values to replace the placeholders in the template.
* @param {string} params.template - The template string containing placeholders to be replaced with state values.
* @param {"handlebars" | undefined} [params.templatingEngine] - The templating engine to use for compiling and evaluating the template (optional, default: `undefined`).
* @returns {string} The composed context string with placeholders replaced by corresponding state values.
*
* @example
* // Given a state object and a template
* const state = { userName: "Alice", userAge: 30 };
* const template = "Hello, {{userName}}! You are {{userAge}} years old";
*
* // Composing the context will result in:
* // Composing the context with simple string replacement will result in:
* // "Hello, Alice! You are 30 years old."
* const context = composeContext({ state, template });
* const contextSimple = composeContext({ state, template });
*/
export const composeContext = ({
state,
template,
templatingEngine,
}: {
state: State;
template: string;
templatingEngine?: "handlebars";
}) => {
if (templatingEngine === "handlebars") {
const templateFunction = handlebars.compile(template);
return templateFunction(state);
}

// @ts-expect-error match isn't working as expected
const out = template.replace(/{{\w+}}/g, (match) => {
const key = match.replace(/{{|}}/g, "");
Expand Down
198 changes: 198 additions & 0 deletions packages/core/src/tests/context.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
import { describe, expect, it } from "vitest";
import { composeContext } from "../context";
import handlebars from "handlebars";
import { State } from "../types.ts";

describe("composeContext", () => {
const baseState: State = {
actors: "",
recentMessages: "",
recentMessagesData: [],
roomId: "-----",
bio: "",
lore: "",
messageDirections: "",
postDirections: "",
userName: "",
};

// Test simple string replacement
describe("simple string replacement (default)", () => {
it("should replace placeholders with corresponding state values", () => {
const state: State = {
...baseState,
userName: "Alice",
userAge: 30,
};
const template =
"Hello, {{userName}}! You are {{userAge}} years old.";

const result = composeContext({ state, template });

expect(result).toBe("Hello, Alice! You are 30 years old.");
});

it("should replace missing state values with empty string", () => {
const state: State = {
...baseState,
userName: "Alice",
};
const template =
"Hello, {{userName}}! You are {{userAge}} years old.";

const result = composeContext({ state, template });

expect(result).toBe("Hello, Alice! You are years old.");
});

it("should handle templates with no placeholders", () => {
const state: State = {
...baseState,
userName: "Alice",
};
const template = "Hello, world!";

const result = composeContext({ state, template });

expect(result).toBe("Hello, world!");
});

it("should handle empty template", () => {
const state: State = {
...baseState,
userName: "Alice",
};
const template = "";

const result = composeContext({ state, template });

expect(result).toBe("");
});
});

// Test Handlebars templating
describe("handlebars templating", () => {
it("should process basic handlebars template", () => {
const state: State = {
...baseState,
userName: "Alice",
userAge: 30,
};
const template =
"Hello, {{userName}}! You are {{userAge}} years old.";

const result = composeContext({
state,
template,
templatingEngine: "handlebars",
});

expect(result).toBe("Hello, Alice! You are 30 years old.");
});

it("should handle handlebars conditionals", () => {
const state: State = {
...baseState,
userName: "Alice",
userAge: 30,
};
const template =
"{{#if userAge}}Age: {{userAge}}{{else}}Age unknown{{/if}}";

const result = composeContext({
state,
template,
templatingEngine: "handlebars",
});

expect(result).toBe("Age: 30");
});

it("should handle handlebars loops", () => {
const state: State = {
...baseState,
colors: ["red", "blue", "green"],
};
const template =
"{{#each colors}}{{this}}{{#unless @last}}, {{/unless}}{{/each}}";

const result = composeContext({
state,
template,
templatingEngine: "handlebars",
});

expect(result).toBe("red, blue, green");
});

it("should handle complex handlebars template", () => {
// Register the 'gt' helper before running tests
handlebars.registerHelper("gt", function (a, b) {
return a > b;
});

const state = {
...baseState,
userName: "Alice",
userAge: 30,
favoriteColors: ["blue", "green", "red"],
};
const template = `
{{#if userAge}}
Hello, {{userName}}! {{#if (gt userAge 18)}}You are an adult.{{else}}You are a minor.{{/if}}
{{else}}
Hello! We don't know your age.
{{/if}}
{{#each favoriteColors}}
- {{this}}
{{/each}}`;

const result = composeContext({
state,
template,
templatingEngine: "handlebars",
});

expect(result.trim()).toMatch(/Hello, Alice! You are an adult./);
expect(result).toContain("- blue");
expect(result).toContain("- green");
expect(result).toContain("- red");
});

it("should handle missing values in handlebars template", () => {
const state = {...baseState}
const template = "Hello, {{userName}}!";

const result = composeContext({
state,
template,
templatingEngine: "handlebars",
});

expect(result).toBe("Hello, !");
});
});

describe("error handling", () => {
it("should handle undefined state", () => {
const template = "Hello, {{userName}}!";

expect(() => {
// @ts-expect-error testing undefined state
composeContext({ template });
}).toThrow();
});

it("should handle undefined template", () => {
const state = {
...baseState,
userName: "Alice",
};

expect(() => {
// @ts-expect-error testing undefined template
composeContext({ state });
}).toThrow();
});
});
});
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading