diff --git a/package.json b/package.json index 12904b4..e7df409 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "modprompt", - "version": "0.2.0", + "version": "0.3.0", "description": "Prompt templates for language models", "license": "MIT", "scripts": { diff --git a/src/cls.ts b/src/cls.ts index b948a49..b2191eb 100644 --- a/src/cls.ts +++ b/src/cls.ts @@ -1,4 +1,4 @@ -import { LmTemplate, PromptBlock, TurnBlock, SpacingSlots } from "./interfaces"; +import { LmTemplate, PromptBlock, TurnBlock, SpacingSlots, HistoryTurn } from "./interfaces"; import { templates } from "./db.js"; /** @@ -12,6 +12,7 @@ class PromptTemplate { name: string; user: string; assistant: string; + history: Array = []; system?: PromptBlock; shots?: Array; stop?: Array; @@ -187,6 +188,26 @@ class PromptTemplate { return this } + + /** + * Render a turn block + * + * @param {TurnBlock | HistoryTurn} shot the shot to render + * @returns {string} ther rendered text + */ + renderShot(shot: TurnBlock | HistoryTurn): string { + const buf = []; + buf.push(this._buildUserBlock(shot.user)); + let _assistantMsg = shot.assistant; + if (this.afterShot) { + _assistantMsg += this.afterShot + } else { + _assistantMsg += "\n\n" + } + buf.push(this._buildAssistantBlock(_assistantMsg)); + return buf.join("") + } + /** * Renders the template into a string representation. * @@ -213,16 +234,13 @@ class PromptTemplate { // shots if (this?.shots) { for (const shot of this.shots) { - buf.push(this._buildUserBlock(shot.user)); - let _assistantMsg = shot.assistant; - if (this.afterShot) { - _assistantMsg += this.afterShot - } else { - _assistantMsg += "\n\n" - } - buf.push(this._buildAssistantBlock(_assistantMsg)); + buf.push(this.renderShot(shot)); } } + // history + for (const turn of this.history) { + buf.push(this.renderShot(turn)); + } // user block buf.push(this._buildUserBlock()); // assistant block @@ -246,7 +264,19 @@ class PromptTemplate { } - private _buildSystemBlock(skip_empty_system: boolean = false): string { + /** + * Push a turn into history + * + * @param {HistoryTurn} turn the history turn + * @returns {PromptTemplate} + */ + pushToHistory(turn: HistoryTurn): PromptTemplate { + this.history.push(turn) + return this + } + + + private _buildSystemBlock(skip_empty_system: boolean): string { let res = ""; if (!this?.system) { return "" diff --git a/src/interfaces.ts b/src/interfaces.ts index 7cb5552..a5804f4 100644 --- a/src/interfaces.ts +++ b/src/interfaces.ts @@ -147,4 +147,10 @@ interface LmTemplate { prefix?: string; } -export { SpacingSlots, PromptBlock, TurnBlock, LmTemplate } \ No newline at end of file +interface HistoryTurn { + user: string; + assistant: string; + images?: Array<{ id: string, data: ArrayBuffer }>; +} + +export { SpacingSlots, PromptBlock, TurnBlock, LmTemplate, HistoryTurn } \ No newline at end of file