# Templates (Prompt Templates)

> \[!TIP]
>
> Location within the framework `Hive-agent-framework/template`.

**Template** is a predefined structure or format used to create consistent documents or outputs. It often includes placeholders for specific information that can be filled in later.

**Prompt template**, on the other hand, is a specific type of template used in the context of language models or AI applications. It consists of a structured prompt that guides the model in generating a response or output. The prompt often includes variables or placeholders for user input, which helps to elicit more relevant or targeted responses.

The Framework exposes such functionality via the `PromptTemplate` class, which is based on the well-known [`Mustache.js`](https://github.com/janl/mustache.js) template system, which is supported almost in every programming language. In addition, the framework provides type safety and validation against appropriate [\`code](https://zod.dev/) schema, as you can see in the following examples.

> \[!TIP]
>
> The Prompt Template concept is used anywhere - especially in our agents.

## Usage

### Primitives

```ts
import { PromptTemplate } from "Hive-agent-framework/template";
import { z } from "zod";

const greetTemplate = new PromptTemplate({
  template: `Hello {{name}}`,
  schema: z.object({
    name: z.string(),
  }),
});

const output = greetTemplate.render({
  name: "Alex",
});
console.log(output); // Hello Alex!
```

*Source: examples/templates/primitives.ts*

### Arrays

```ts
import { PromptTemplate } from "Hive-agent-framework/template";
import { z } from "zod";

const template = new PromptTemplate({
  schema: z.object({
    colors: z.array(z.string()).min(1),
  }),
  template: `Colors: {{#trim}}{{#colors}}{{.}},{{/colors}}{{/trim}}`,
});

const output = template.render({
  colors: ["Green", "Yellow"],
});
console.log(output); // Colors: Green,Yellow
```

*Source: examples/templates/arrays.ts*

### Objects

```ts
import { PromptTemplate } from "Hive-agent-framework/template";
import { z } from "zod";

const template = new PromptTemplate({
  template: `Expected Duration: {{expected}}ms; Retrieved: {{#responses}}{{duration}}ms {{/responses}}`,
  schema: z.object({
    expected: z.number(),
    responses: z.array(z.object({ duration: z.number() })),
  }),
  defaults: {
    expected: 5,
  },
});

const output = template.render({
  expected: undefined, // default value will be used
  responses: [{ duration: 3 }, { duration: 5 }, { duration: 6 }],
});
console.log(output); // Expected Duration: 5ms; Retrieved: 3ms 5ms 6ms
```

*Source: examples/templates/objects.ts*

### Forking

```ts
import { PromptTemplate } from "Hive-agent-framework/template";
import { z } from "zod";

const original = new PromptTemplate({
  template: `You are a helpful assistant called {{name}}. Your objective is to {{objective}}.`,
  schema: z.object({
    name: z.string(),
    objective: z.string(),
  }),
});

const modified = original.fork((config) => ({
  ...config,
  template: `${config.template} Your answers must be concise.`,
  defaults: {
    name: "Hive",
  },
}));

const output = modified.render({
  name: undefined, // default will be used
  objective: "fulfill the user needs",
});
console.log(output); // You are a helpful assistant called Hive. Your objective is to fulfill the user needs. Your answers must be concise.
```

*Source: examples/templates/forking.ts*

### Functions

```ts
import { PromptTemplate } from "Hive-agent-framework/template";
import { z } from "zod";

const messageTemplate = new PromptTemplate({
  schema: z
    .object({
      text: z.string(),
      author: z.string().optional(),
      createdAt: z.string().datetime().optional(),
    })
    .passthrough(),
  functions: {
    formatMeta: function () {
      if (!this.author && !this.createdAt) {
        return "";
      }

      const author = this.author || "anonymous";
      const createdAt = this.createdAt || new Date().toISOString();

      return `\nThis message was created at ${createdAt} by ${author}.`;
    },
  },
  template: `Message: {{text}}{{formatMeta}}`,
});

// Message: Hello from 2024!
// This message was created at 2024-01-01T00:00:00.000Z by John.
console.log(
  messageTemplate.render({
    text: "Hello from 2024!",
    author: "John",
    createdAt: new Date("2024-01-01").toISOString(),
  }),
);

// Message: Hello from the present!
console.log(
  messageTemplate.render({
    text: "Hello from the present!",
  }),
);
```

*Source: examples/templates/functions.ts*

## Agents

The Hive Agent internally uses multiple prompt templates, and because now you know how to work with them, you can alter the agent’s behavior.

The internal prompt templates can be modified here.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hive-4.gitbook.io/hive/modules/templates-prompt-templates.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
