Skip to content
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
2 changes: 2 additions & 0 deletions js/src/dotprompt.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,7 @@ describe('Dotprompt', () => {
expect(mockCompiledTemplate).toHaveBeenCalled();
expect(toMessagesMock).toHaveBeenCalledWith(
'Hello World!',
expect.stringMatching(/^[0-9a-f]{32}$/),
expect.anything()
);
expect(result.messages).toEqual([
Expand Down Expand Up @@ -257,6 +258,7 @@ describe('Dotprompt', () => {
expect(mockCompiledTemplate).toHaveBeenCalled();
expect(toMessagesMock).toHaveBeenCalledWith(
'Hello World!',
expect.stringMatching(/^[0-9a-f]{32}$/),
expect.anything()
);
expect(result.messages).toEqual([
Expand Down
8 changes: 7 additions & 1 deletion js/src/dotprompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import Handlebars from 'handlebars/dist/cjs/handlebars.js';
import * as builtinHelpers from './helpers';
import { generateMarkerNonce, MARKER_NONCE_DATA_KEY } from './markers';
import { parseDocument, toMessages } from './parse';
import { picoschema } from './picoschema';
import type {
Expand Down Expand Up @@ -205,6 +206,9 @@ export class Dotprompt {
const { input, ...mergedMetadata } =
await this.renderMetadata(parsedSource);

// Fresh per render so user-supplied values can't forge role/media/etc.
// markers in the rendered string. See markers.ts.
const nonce = generateMarkerNonce();
const renderedString = renderString(
{ ...(options?.input?.default || {}), ...data.input },
{
Expand All @@ -215,13 +219,15 @@ export class Dotprompt {
messages: data.messages,
},
...(data.context || {}),
// Must come after `data.context` so it can't be overridden.
[MARKER_NONCE_DATA_KEY]: nonce,
},
}
);

return {
...mergedMetadata,
messages: toMessages<ModelConfig>(renderedString, data),
messages: toMessages<ModelConfig>(renderedString, nonce, data),
};
};

Expand Down
71 changes: 35 additions & 36 deletions js/src/helpers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
section,
unlessEquals,
} from './helpers';
import { MARKER_NONCE_DATA_KEY } from './markers';

describe('helpers', () => {
describe('json', () => {
Expand Down Expand Up @@ -79,58 +80,56 @@ describe('helpers', () => {
});
});

describe('role', () => {
it('should return a role marker for system', () => {
const result = role('system');
expect(result.toString()).toBe('<<<dotprompt:role:system>>>');
});
describe('marker helpers', () => {
const NONCE = '0123456789abcdef0123456789abcdef';
const options = (hash: Record<string, unknown> = {}) =>
({
hash,
data: { [MARKER_NONCE_DATA_KEY]: NONCE },
}) as Handlebars.HelperOptions;

it('should return a role marker for user', () => {
const result = role('user');
expect(result.toString()).toBe('<<<dotprompt:role:user>>>');
it('role emits a nonced role marker', () => {
expect(role('system', options()).toString()).toBe(
`<<<dotprompt:${NONCE}:role:system>>>`
);
});

it('should return a role marker for model', () => {
const result = role('model');
expect(result.toString()).toBe('<<<dotprompt:role:model>>>');
it('history emits a nonced history marker', () => {
expect(history(options()).toString()).toBe(
`<<<dotprompt:${NONCE}:history>>>`
);
});
});

describe('history', () => {
it('should return a history marker', () => {
const result = history();
expect(result.toString()).toBe('<<<dotprompt:history>>>');
});
});

describe('section', () => {
it('should return a section marker', () => {
const result = section('examples');
expect(result.toString()).toBe('<<<dotprompt:section examples>>>');
it('section emits a nonced section marker', () => {
expect(section('examples', options()).toString()).toBe(
`<<<dotprompt:${NONCE}:section examples>>>`
);
});
});

describe('media', () => {
it('should return a media marker with url only', () => {
const result = media({
hash: { url: 'https://example.com/image.png' },
} as Handlebars.HelperOptions);
it('media emits a nonced media marker with url only', () => {
const result = media(options({ url: 'https://example.com/image.png' }));
expect(result.toString()).toBe(
'<<<dotprompt:media:url https://example.com/image.png>>>'
`<<<dotprompt:${NONCE}:media:url https://example.com/image.png>>>`
);
});

it('should return a media marker with url and contentType', () => {
const result = media({
hash: {
it('media emits a nonced media marker with url and contentType', () => {
const result = media(
options({
url: 'https://example.com/image.png',
contentType: 'image/png',
},
} as Handlebars.HelperOptions);
})
);
expect(result.toString()).toBe(
'<<<dotprompt:media:url https://example.com/image.png image/png>>>'
`<<<dotprompt:${NONCE}:media:url https://example.com/image.png image/png>>>`
);
});

it('throws when the nonce is missing from the data frame', () => {
const noNonce = { hash: {}, data: {} } as Handlebars.HelperOptions;
expect(() => role('system', noNonce)).toThrow(/must be rendered/);
expect(() => history(noNonce)).toThrow(/must be rendered/);
});
});

describe('ifEquals', () => {
Expand Down
59 changes: 50 additions & 9 deletions js/src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,28 @@

import handlebars from 'handlebars/dist/cjs/handlebars.js';

import { formatMarker, MARKER_NONCE_DATA_KEY } from './markers';

const { SafeString } = handlebars;

// NOTE: every export of this module is registered as a template helper.

/**
* Reads the per-render marker nonce from the Handlebars data frame. Data frames
* are inherited by blocks (`#each`, `#if`, ...) and partials, so this only
* fails if the helper runs outside `Dotprompt` rendering or a custom block
* helper replaces `data` wholesale instead of using `createFrame`.
*/
function markerNonce(options: Handlebars.HelperOptions): string {
const nonce: unknown = options.data?.[MARKER_NONCE_DATA_KEY];
Comment thread
pavelgj marked this conversation as resolved.
Resolved
if (typeof nonce !== 'string') {
throw new Error(
'dotprompt: marker helpers (role, history, section, media) must be rendered via Dotprompt'
);
}
return nonce;
}

export function json(
serializable: any,
options: { hash: { indent?: number } }
Expand All @@ -29,23 +49,44 @@ export function json(
);
}

export function role(role: string) {
return new SafeString(`<<<dotprompt:role:${role}>>>`);
/**
* With no positional argument (`{{role}}`), Handlebars passes the options
* object as the first parameter and leaves the second undefined.
*/
function requireName(
helper: string,
example: string,
options: Handlebars.HelperOptions | undefined
): Handlebars.HelperOptions {
if (options === undefined) {
throw new Error(
`dotprompt: {{${helper}}} requires a name, e.g. {{${helper} "${example}"}}`
);
}
return options;
}

export function role(role: string, options?: Handlebars.HelperOptions) {
const opts = requireName('role', 'system', options);
return new SafeString(formatMarker(markerNonce(opts), `role:${role}`));
}

export function history() {
return new SafeString('<<<dotprompt:history>>>');
export function history(options: Handlebars.HelperOptions) {
return new SafeString(formatMarker(markerNonce(options), 'history'));
}

export function section(name: string) {
return new SafeString(`<<<dotprompt:section ${name}>>>`);
export function section(name: string, options?: Handlebars.HelperOptions) {
const opts = requireName('section', 'output', options);
return new SafeString(formatMarker(markerNonce(opts), `section ${name}`));
}

export function media(options: Handlebars.HelperOptions) {
const { url, contentType } = options.hash;
return new SafeString(
`<<<dotprompt:media:url ${options.hash.url}${
options.hash.contentType ? ` ${options.hash.contentType}` : ''
}>>>`
formatMarker(
markerNonce(options),
`media:url ${url}${contentType ? ` ${contentType}` : ''}`
)
);
}

Expand Down
Loading
Loading