All files / src dotprompt.ts

98.51% Statements 266/270
97.56% Branches 80/82
100% Functions 17/17
98.51% Lines 266/270

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471                                    1x 1x 1x 1x                           1x                                                               1x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x   78x 78x 78x 78x 78x 78x 78x 78x 78x   78x 546x 546x 546x   78x 1x 1x 1x 1x   78x 1x 2x 2x 1x 78x                 78x 549x 549x 549x 549x                 78x 13x 13x 13x               78x 3x 3x 3x               78x 95x 95x 95x 95x                   78x       47x 47x 47x 47x 47x 47x 47x               78x 96x 96x 96x 59x 59x   37x 96x 3x 3x 3x 3x 3x 3x 3x 96x 37x 37x 37x 37x 37x 37x 37x 37x 96x               78x 9x 9x 9x 7x 7x 3x 1x 1x 1x 9x                 78x 96x 96x 96x 96x   96x 191x 191x 191x 191x 191x   96x 96x 96x   96x 96x 96x 96x 96x               78x 97x 97x 97x     97x 3x 3x   3x 3x 4x 1x 1x 1x 4x 2x 2x 1x 1x 1x 1x 1x 1x 1x 3x 1x 1x 3x 3x   2x 2x 96x 97x               78x 49x 49x     49x   49x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 49x   49x 49x 49x               78x 58x 3x 3x   55x     55x 55x 15x 7x   7x 7x 7x   7x 1x 1x 1x   7x 7x   7x 7x 7x 55x 55x 58x                 78x       48x 48x 48x 48x 48x 48x 48x       48x         48x   48x 48x 48x 48x 48x 48x 48x 48x   48x 48x 48x 48x   48x 48x   48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x   48x 48x 48x 48x 48x 48x 48x 48x                 78x 97x 97x 97x 97x 97x 46x 51x 51x 51x   97x 97x   97x 97x 1x 1x   97x 97x 97x 97x 97x 97x 78x  
/**
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * SPDX-License-Identifier: Apache-2.0
 */
 
import * as Handlebars from 'handlebars';
import * as helpers from './helpers';
import { parseDocument, toMessages } from './parse';
import { picoschema } from './picoschema';
import {
  type DataArgument,
  type JSONSchema,
  type ParsedPrompt,
  type PromptFunction,
  type PromptMetadata,
  PromptRefFunction,
  type PromptStore,
  type RenderedPrompt,
  type SchemaResolver,
  type ToolDefinition,
  type ToolResolver,
} from './types';
import { removeUndefinedFields } from './util';
 
/** Function to resolve partial names to their content */
export type PartialResolver = (
  partialName: string
) => string | null | Promise<string | null>;
 
/** Options for the Dotprompt class. */
export interface DotpromptOptions {
  /** A default model to use if none is supplied. */
  defaultModel?: string;
  /** Assign a set of default configuration options to be used with a particular model. */
  modelConfigs?: Record<string, object>;
  /** Helpers to pre-register. */
  helpers?: Record<string, Handlebars.HelperDelegate>;
  /** Partials to pre-register. */
  partials?: Record<string, string>;
  /** Provide a static mapping of tool definitions that should be used when resolving tool names. */
  tools?: Record<string, ToolDefinition>;
  /** Provide a lookup implementation to resolve tool names to definitions. */
  toolResolver?: ToolResolver;
  /** Provide a static mapping of schema names to their JSON Schema definitions. */
  schemas?: Record<string, JSONSchema>;
  /** Provide a lookup implementation to resolve schema names to JSON schema definitions. */
  schemaResolver?: SchemaResolver;
  /** Provide a lookup implementation to resolve partial names to their content. */
  partialResolver?: PartialResolver;
}
 
/**
 * The main class for the Dotprompt library.
 */
export class Dotprompt {
  private handlebars: typeof Handlebars;
  private knownHelpers: Record<string, true> = {};
  private defaultModel?: string;
  private modelConfigs: Record<string, object> = {};
  private tools: Record<string, ToolDefinition> = {};
  private toolResolver?: ToolResolver;
  private schemas: Record<string, JSONSchema> = {};
  private schemaResolver?: SchemaResolver;
  private partialResolver?: PartialResolver;
  private store?: PromptStore;
 
  constructor(options?: DotpromptOptions) {
    this.handlebars = Handlebars.noConflict();
    this.modelConfigs = options?.modelConfigs || this.modelConfigs;
    this.defaultModel = options?.defaultModel;
    this.tools = options?.tools || {};
    this.toolResolver = options?.toolResolver;
    this.schemas = options?.schemas || {};
    this.schemaResolver = options?.schemaResolver;
    this.partialResolver = options?.partialResolver;
 
    for (const key in helpers) {
      this.defineHelper(key, helpers[key as keyof typeof helpers]);
      this.handlebars.registerHelper(key, helpers[key as keyof typeof helpers]);
    }
 
    if (options?.helpers) {
      for (const key in options.helpers) {
        this.defineHelper(key, options.helpers[key]);
      }
    }
 
    if (options?.partials) {
      for (const key in options.partials) {
        this.definePartial(key, options.partials[key]);
      }
    }
  }
 
  /**
   * Registers a helper function for use in templates.
   *
   * @param name The name of the helper function to register
   * @param fn The helper function implementation
   * @return This instance for method chaining
   */
  defineHelper(name: string, fn: Handlebars.HelperDelegate): this {
    this.handlebars.registerHelper(name, fn);
    this.knownHelpers[name] = true;
    return this;
  }
 
  /**
   * Registers a partial template for use in other templates.
   *
   * @param name The name of the partial to register
   * @param source The template source for the partial
   * @return This instance for method chaining
   */
  definePartial(name: string, source: string): this {
    this.handlebars.registerPartial(name, source);
    return this;
  }
 
  /**
   * Registers a tool definition for use in prompts.
   *
   * @param def The tool definition to register
   * @return This instance for method chaining
   */
  defineTool(def: ToolDefinition): this {
    this.tools[def.name] = def;
    return this;
  }
 
  /**
   * Parses a prompt template string into a structured ParsedPrompt object.
   *
   * @param source The template source string to parse
   * @return A parsed prompt object with extracted metadata and template
   */
  parse<ModelConfig = Record<string, unknown>>(
    source: string
  ): ParsedPrompt<ModelConfig> {
    return parseDocument<ModelConfig>(source);
  }
 
  /**
   * Renders a prompt template with the provided data.
   *
   * @param source The template source string to render
   * @param data The data to use when rendering the template
   * @param options Additional metadata and options for rendering
   * @return A promise resolving to the rendered prompt
   */
  async render<
    Variables = Record<string, unknown>,
    ModelConfig = Record<string, unknown>,
  >(
    source: string,
    data: DataArgument<Variables> = {},
    options?: PromptMetadata<ModelConfig>
  ): Promise<RenderedPrompt<ModelConfig>> {
    const renderer = await this.compile<Variables, ModelConfig>(source);
    return renderer(data, options);
  }
 
  /**
   * Processes schema definitions in picoschema format into standard JSON Schema.
   *
   * @param meta The prompt metadata containing schema definitions
   * @return A promise resolving to the processed metadata with expanded schemas
   */
  private async renderPicoschema<ModelConfig>(
    meta: PromptMetadata<ModelConfig>
  ): Promise<PromptMetadata<ModelConfig>> {
    if (!meta.output?.schema && !meta.input?.schema) {
      return meta;
    }
 
    const newMeta = { ...meta };
    if (meta.input?.schema) {
      newMeta.input = {
        ...meta.input,
        schema: await picoschema(meta.input.schema, {
          schemaResolver: this.wrappedSchemaResolver.bind(this),
        }),
      };
    }
    if (meta.output?.schema) {
      newMeta.output = {
        ...meta.output,
        schema: await picoschema(meta.output.schema, {
          schemaResolver: this.wrappedSchemaResolver.bind(this),
        }),
      };
    }
    return newMeta;
  }
 
  /**
   * Resolves a schema name to its definition, using registered schemas or schema resolver.
   *
   * @param name The name of the schema to resolve
   * @return A promise resolving to the schema definition or null if not found
   */
  private async wrappedSchemaResolver(
    name: string
  ): Promise<JSONSchema | null> {
    if (this.schemas[name]) {
      return this.schemas[name];
    }
    if (this.schemaResolver) {
      return await this.schemaResolver(name);
    }
    return null;
  }
 
  /**
   * Merges multiple metadata objects together, resolving tools and schemas.
   *
   * @param base The base metadata object
   * @param merges Additional metadata objects to merge into the base
   * @return A promise resolving to the merged and processed metadata
   */
  private async resolveMetadata<ModelConfig = Record<string, unknown>>(
    base: PromptMetadata<ModelConfig>,
    ...merges: (PromptMetadata<ModelConfig> | undefined)[]
  ): Promise<PromptMetadata<ModelConfig>> {
    let out = { ...base };
 
    for (let i = 0; i < merges.length; i++) {
      if (!merges[i]) continue;
      const config = out.config || ({} as ModelConfig);
      out = { ...out, ...merges[i] };
      out.config = { ...config, ...(merges[i]?.config || {}) };
    }
 
    const { template: _, ...outWithoutTemplate } =
      out as PromptMetadata<ModelConfig> & { template?: string };
    out = outWithoutTemplate as PromptMetadata<ModelConfig>;
 
    out = removeUndefinedFields(out);
    out = await this.resolveTools(out);
    out = await this.renderPicoschema(out);
    return out;
  }
 
  /**
   * Resolves tool names to their definitions using registered tools or tool resolver.
   *
   * @param base The metadata containing tool references to resolve
   * @return A promise resolving to metadata with resolved tool definitions
   */
  private async resolveTools<ModelConfig>(
    base: PromptMetadata<ModelConfig>
  ): Promise<PromptMetadata<ModelConfig>> {
    const out = { ...base };
    // Resolve tools that are already registered into toolDefs, leave
    // unregistered tools alone..
    if (out.tools) {
      const outTools: string[] = [];
      out.toolDefs = out.toolDefs || [];
 
      await Promise.all(
        out.tools.map(async (toolName) => {
          if (this.tools[toolName]) {
            if (out.toolDefs) {
              out.toolDefs.push(this.tools[toolName]);
            }
          } else if (this.toolResolver) {
            const resolvedTool = await this.toolResolver(toolName);
            if (!resolvedTool) {
              throw new Error(
                `Dotprompt: Unable to resolve tool '${toolName}' to a recognized tool definition.`
              );
            }
            if (out.toolDefs) {
              out.toolDefs.push(resolvedTool);
            }
          } else {
            outTools.push(toolName);
          }
        })
      );
 
      out.tools = outTools;
    }
    return out;
  }
 
  /**
   * Identifies all partial references in a template.
   *
   * @param template The template to scan for partial references
   * @return A set of partial names referenced in the template
   */
  private identifyPartials(template: string): Set<string> {
    const ast = this.handlebars.parse(template);
    const partials = new Set<string>();
 
    // Create a visitor to collect partial names.
    const visitor = new (class extends this.handlebars.Visitor {
      // Visit partial statements and add their names to our set.
      PartialStatement(partial: unknown): void {
        if (
          partial &&
          typeof partial === 'object' &&
          'name' in partial &&
          partial.name &&
          typeof partial.name === 'object' &&
          'original' in partial.name &&
          typeof partial.name.original === 'string'
        ) {
          partials.add(partial.name.original);
        }
      }
    })();
 
    visitor.accept(ast);
    return partials;
  }
 
  /**
   * Resolves and registers all partials referenced in a template.
   *
   * @param template The template containing partial references
   * @return A promise that resolves when all partials are registered
   */
  private async resolvePartials(template: string): Promise<void> {
    if (!this.partialResolver && !this.store) {
      return;
    }
 
    const partials = this.identifyPartials(template);
 
    // Resolve and register each partial.
    await Promise.all(
      Array.from(partials).map(async (name) => {
        if (!this.handlebars.partials[name]) {
          let content: string | null | undefined = null;
 
          if (this.partialResolver) {
            content = await this.partialResolver(name);
          }
 
          if (!content && this.store) {
            const partial = await this.store.loadPartial(name);
            content = partial?.source;
          }
 
          if (content) {
            this.definePartial(name, content);
            // Recursively resolve partials in the partial content.
            await this.resolvePartials(content);
          }
        }
      })
    );
  }
 
  /**
   * Compiles a template into a reusable function for rendering prompts.
   *
   * @param source The template source or parsed prompt to compile
   * @param additionalMetadata Additional metadata to include in the compiled template
   * @return A promise resolving to a function for rendering the template
   */
  async compile<
    Variables = Record<string, unknown>,
    ModelConfig = Record<string, unknown>,
  >(
    source: string | ParsedPrompt<ModelConfig>,
    additionalMetadata?: PromptMetadata<ModelConfig>
  ): Promise<PromptFunction<ModelConfig>> {
    let parsedSource: ParsedPrompt<ModelConfig>;
    if (typeof source === 'string') {
      parsedSource = this.parse<ModelConfig>(source);
    } else {
      parsedSource = source;
    }
 
    if (additionalMetadata) {
      parsedSource = { ...parsedSource, ...additionalMetadata };
    }
 
    // Resolve all partials before compilation.
    await this.resolvePartials(parsedSource.template);
 
    const renderString = this.handlebars.compile<Variables>(
      parsedSource.template,
      {
        knownHelpers: this.knownHelpers,
        knownHelpersOnly: true,
        noEscape: true,
      }
    );
 
    const renderFunc = async (
      data: DataArgument,
      options?: PromptMetadata<ModelConfig>
    ) => {
      // Discard the input schema as once rendered it doesn't make sense.
      const { input, ...mergedMetadata } =
        await this.renderMetadata(parsedSource);
 
      const renderedString = renderString(
        { ...(options?.input?.default || {}), ...data.input },
        {
          data: {
            metadata: {
              prompt: mergedMetadata,
              docs: data.docs,
              messages: data.messages,
            },
            ...(data.context || {}),
          },
        }
      );
 
      return {
        ...mergedMetadata,
        messages: toMessages<ModelConfig>(renderedString, data),
      };
    };
    (renderFunc as PromptFunction<ModelConfig>).prompt = parsedSource;
    return renderFunc as PromptFunction<ModelConfig>;
  }
 
  /**
   * Processes and resolves all metadata for a prompt template.
   *
   * @param source The template source or parsed prompt
   * @param additionalMetadata Additional metadata to include
   * @return A promise resolving to the fully processed metadata
   */
  async renderMetadata<ModelConfig>(
    source: string | ParsedPrompt<ModelConfig>,
    additionalMetadata?: PromptMetadata<ModelConfig>
  ): Promise<PromptMetadata<ModelConfig>> {
    let parsedSource: ParsedPrompt<ModelConfig>;
    if (typeof source === 'string') {
      parsedSource = this.parse<ModelConfig>(source);
    } else {
      parsedSource = source;
    }
 
    const selectedModel =
      additionalMetadata?.model || parsedSource.model || this.defaultModel;
 
    let modelConfig: ModelConfig | undefined;
    if (selectedModel && this.modelConfigs[selectedModel]) {
      modelConfig = this.modelConfigs[selectedModel] as ModelConfig;
    }
 
    return this.resolveMetadata<ModelConfig>(
      modelConfig ? { config: modelConfig } : {},
      parsedSource,
      additionalMetadata
    );
  }
}