### Install Teleprompt Source: https://github.com/create-inc/teleprompt/blob/main/README.md Install the package using pnpm. ```bash pnpm add @anythingai/teleprompt ``` -------------------------------- ### Installation Source: https://context7.com/create-inc/teleprompt/llms.txt Install the Teleprompt package using npm or pnpm. ```APIDOC ## Installation Install the package via npm or pnpm to add it to your TypeScript/JavaScript project. ### Command ```bash pnpm add @anythingai/teleprompt ``` ``` -------------------------------- ### Testing Prompt Rendering and Structure Source: https://github.com/create-inc/teleprompt/blob/main/README.md Provides examples of using testing utilities from '@anythingai/teleprompt/testing' to isolate and render sections of a prompt, and to assert on the included and excluded sections of a fully built prompt. ```typescript import { mockContext, renderSection } from '@anythingai/teleprompt/testing'; // Render a section in isolation const output = renderSection(webSearch, { flags: { webSearchEnabled: true } }); expect(output).toContain('web search'); // Assert on prompt structure const { included, excluded } = builder.buildWithMeta(ctx); expect(included).toContain('web-search'); expect(excluded).toContain('citation'); ``` -------------------------------- ### Get All Section IDs with PromptBuilder.ids() Source: https://context7.com/create-inc/teleprompt/llms.txt Retrieves an array containing all section IDs in their insertion order. This includes IDs from groups, nested children, and oneOf candidates. ```typescript import { PromptBuilder, section, type PromptContext } from '@anythingai/teleprompt'; type Ctx = PromptContext<{}, {}>; const builder = new PromptBuilder() .use(section('identity', () => 'Identity')) .group('tools', b => b .use(section('bash', () => 'Bash')) .use(section('git', () => 'Git')) ) .useOneOf( section('has-tasks', () => 'Tasks'), section('no-tasks', () => 'No tasks') ) .use(section('footer', () => 'Footer')); console.log(builder.ids()); // Output: ['identity', 'tools', 'bash', 'git', 'has-tasks', 'no-tasks', 'footer'] ``` -------------------------------- ### PromptBuilder.build(ctx, options?) Source: https://context7.com/create-inc/teleprompt/llms.txt Renders the complete prompt into a string. It accepts a context object and optional build options, including a `format` property that can be set to 'text' (default) or 'xml'. ```APIDOC ## PromptBuilder.build(ctx, options?) ### Description Renders the prompt to a string. Accepts optional `BuildOptions` with `format` property ('text' or 'xml'). Text format joins sections with double newlines; XML format wraps each section in `` tags. ### Method `build(ctx: PromptContext, options?: BuildOptions)` ### Endpoint N/A (Instance method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { PromptBuilder, section, type PromptContext } from '@anythingai/teleprompt'; type Ctx = PromptContext<{ webSearch: boolean }, { name: string }>; const identity = section('identity', (ctx: Ctx) => `You are ${ctx.vars.name}.`); const rules = section('rules', () => 'Be concise.'); const webSearch = section('web-search', (ctx: Ctx) => { if (!ctx.flags.webSearch) return null; return 'You can search the web.'; }); const builder = new PromptBuilder() .use(identity) .use(rules) .use(webSearch); const ctx: Ctx = { flags: { webSearch: true }, vars: { name: 'Claude' }, }; // Text format (default) console.log(builder.build(ctx)); // XML format — recommended for Claude and Gemini console.log(builder.build(ctx, { format: 'xml' })); ``` ### Response #### Success Response (200) - **string** - The rendered prompt string in the specified format. #### Response Example ``` // Text format output: You are Claude. Be concise. You can search the web. // XML format output: You are Claude. Be concise. You can search the web. ``` ``` -------------------------------- ### Create Prompt Sections with section() Helper Source: https://github.com/create-inc/teleprompt/blob/main/llms.txt Demonstrates how to create individual prompt sections using the `section()` helper function. Sections can be static, dynamic (reading from context), or conditional (returning null to exclude). ```typescript import { section } from "@anythingai/teleprompt"; // Static — no context needed, works in any builder const guidelines = section("guidelines", () => `Be concise and direct.`); // Dynamic — reads from context const identity = section("identity", (ctx: Ctx) => `You are ${ctx.vars.userName}'s assistant.` ); // Conditional — return null to exclude const webSearch = section("web-search", (ctx: Ctx) => { if (!ctx.flags.webSearchEnabled) return null; return "You have access to web search."; }); ``` -------------------------------- ### Build Prompt with Metadata using PromptBuilder Source: https://context7.com/create-inc/teleprompt/llms.txt Demonstrates how to use `buildWithMeta` from PromptBuilder to construct a prompt and retrieve metadata about included and excluded sections. This is useful for debugging and testing prompt composition. It requires defining a context type and using sections that conditionally return content. ```typescript import { PromptBuilder, section, type PromptContext } from '@anythingai/teleprompt'; type Ctx = PromptContext<{ verbose: boolean; beta: boolean }, {}>; const identity = section('identity', () => 'You are an assistant.'); const verbose = section('verbose', (ctx: Ctx) => { if (!ctx.flags.verbose) return null; return 'Provide detailed explanations.'; }); const beta = section('beta-features', (ctx: Ctx) => { if (!ctx.flags.beta) return null; return 'You have access to beta features.'; }); const rules = section('rules', () => 'Be helpful.'); const builder = new PromptBuilder() .use(identity) .use(verbose) .use(beta) .use(rules); const ctx: Ctx = { flags: { verbose: true, beta: false }, vars: {} }; const result = builder.buildWithMeta(ctx); console.log('Prompt:', result.prompt); // Output: // You are an assistant. // // Provide detailed explanations. // // Be helpful. console.log('Included:', result.included); // Output: ['identity', 'verbose', 'rules'] console.log('Excluded:', result.excluded); // Output: ['beta-features'] ``` -------------------------------- ### Leverage Builder for Composition, Not Direct Rendering Source: https://github.com/create-inc/teleprompt/blob/main/llms.txt Highlights the importance of using the `PromptBuilder` for composing sections, handling formatting, and tracking metadata. Directly rendering sections bypasses these features and is discouraged. ```typescript // Preferred — builder handles joining, format, and metadata const prompt = new PromptBuilder().use(identity).use(guidelines).build(ctx); // Avoid — bypasses composition, forking, and metadata tracking const prompt = identity.render(ctx) + "\n\n" + guidelines.render(ctx); ``` -------------------------------- ### Render Prompt with PromptBuilder.build() Source: https://context7.com/create-inc/teleprompt/llms.txt Renders the prompt to a string, supporting both plain text and XML formats. The text format joins sections with double newlines, while the XML format wraps each section in its corresponding ID tags. Accepts optional BuildOptions with a 'format' property. ```typescript import { PromptBuilder, section, type PromptContext } from '@anythingai/teleprompt'; type Ctx = PromptContext<{ webSearch: boolean }, { name: string }>; const identity = section('identity', (ctx: Ctx) => `You are ${ctx.vars.name}.`); const rules = section('rules', () => 'Be concise.'); const webSearch = section('web-search', (ctx: Ctx) => { if (!ctx.flags.webSearch) return null; return 'You can search the web.'; }); const builder = new PromptBuilder() .use(identity) .use(rules) .use(webSearch); const ctx: Ctx = { flags: { webSearch: true }, vars: { name: 'Claude' }, }; // Text format (default) console.log(builder.build(ctx)); // Output: // You are Claude. // // Be concise. // // You can search the web. // XML format — recommended for Claude and Gemini console.log(builder.build(ctx, { format: 'xml' })); // Output: // // You are Claude. // // // // Be concise. // // // // You can search the web. // ``` -------------------------------- ### Compose Prompts with PromptBuilder Source: https://context7.com/create-inc/teleprompt/llms.txt Shows how to use the `PromptBuilder` to compose multiple sections into a final prompt. Sections are added using `.use()` and rendered in order, respecting conditional logic. ```typescript import { PromptBuilder, section, type PromptContext } from '@anythingai/teleprompt'; type Ctx = PromptContext<{ verbose: boolean }, { name: string }>; const identity = section('identity', (ctx: Ctx) => `You are ${ctx.vars.name}.`); const rules = section('rules', () => 'Be helpful and concise.'); const verbose = section('verbose', (ctx: Ctx) => { if (!ctx.flags.verbose) return null; return 'Provide detailed explanations with examples.'; }); const prompt = new PromptBuilder() .use(identity) .use(rules) .use(verbose) .build({ flags: { verbose: true }, vars: { name: 'Assistant' }, }); // Output: // You are Assistant. // // Be helpful and concise. // // Provide detailed explanations with examples. ``` -------------------------------- ### Fork PromptBuilder for Variants Source: https://github.com/create-inc/teleprompt/blob/main/llms.txt Shows how to create different prompt compositions (variants) from a common base using the `fork()` method. This allows for code reuse while enabling specific modifications for each variant. ```typescript const base = new PromptBuilder().use(identity).use(guidelines).use(tone); const supportAgent = base.fork().use(escalationPolicy); const codeAgent = base.fork().without(tone).use(codingRules); ``` -------------------------------- ### PromptBuilder.use(section) Source: https://context7.com/create-inc/teleprompt/llms.txt Appends a section to the PromptBuilder, allowing for sequential composition of prompt elements. ```APIDOC ## PromptBuilder.use(section) Appends a section to the builder. If a section with the same id already exists, it replaces the existing one. Sections render in the order they are added via `.use()`. ### TypeScript Example ```typescript import { PromptBuilder, section, type PromptContext } from '@anythingai/teleprompt'; type Ctx = PromptContext<{ verbose: boolean }, { name: string }>; const identity = section('identity', (ctx: Ctx) => `You are ${ctx.vars.name}.`); const rules = section('rules', () => 'Be helpful and concise.'); const verbose = section('verbose', (ctx: Ctx) => { if (!ctx.flags.verbose) return null; return 'Provide detailed explanations with examples.'; }); const prompt = new PromptBuilder() .use(identity) .use(rules) .use(verbose) .build({ flags: { verbose: true }, vars: { name: 'Assistant' }, }); // Output: // You are Assistant. // // Be helpful and concise. // // Provide detailed explanations with examples. ``` ``` -------------------------------- ### Test Sections in Isolation with Testing Utilities Source: https://context7.com/create-inc/teleprompt/llms.txt Illustrates the use of `mockContext` and `renderSection` from `@anythingai/teleprompt/testing` for unit testing individual prompt sections. `mockContext` provides a default context, while `renderSection` allows rendering a single section without a full builder, facilitating isolated testing of logic and conditional outputs. ```typescript import { section, type PromptContext } from '@anythingai/teleprompt'; import { mockContext, renderSection } from '@anythingai/teleprompt/testing'; type Flags = { webSearchEnabled: boolean }; type Vars = { userName: string }; type Ctx = PromptContext; const greeting = section('greeting', (ctx: Ctx) => `Hello, ${ctx.vars.userName}!`); const webSearch = section('web-search', (ctx: Ctx) => { if (!ctx.flags.webSearchEnabled) return null; return 'You have access to web search.'; }); // Test with mockContext const ctx = mockContext({ flags: { webSearchEnabled: true }, vars: { userName: 'Claude' }, }); // Render section in isolation const greetingOutput = renderSection(greeting, { vars: { userName: 'Claude' }, }); console.log(greetingOutput); // Output: Hello, Claude! // Test conditional section — enabled const enabledOutput = renderSection(webSearch, { flags: { webSearchEnabled: true }, }); console.log(enabledOutput); // Output: You have access to web search. // Test conditional section — disabled (returns null) const disabledOutput = renderSection(webSearch, { flags: { webSearchEnabled: false }, }); console.log(disabledOutput); // Output: null ``` -------------------------------- ### Compose Prompt Sections with PromptBuilder Source: https://github.com/create-inc/teleprompt/blob/main/llms.txt Illustrates how to compose multiple prompt sections into a final prompt using the `PromptBuilder`. Supports sequential use, grouping, mutual exclusion, and conditional inclusion. ```typescript import { PromptBuilder } from "@anythingai/teleprompt"; const builder = new PromptBuilder() .use(identity) .use(guidelines) .use(webSearch) .group("tools", (b) => b.use(bashTool).use(gitTool)) .useOneOf(hasTasks, noTasks); const prompt = builder.build(ctx); const xmlPrompt = builder.build(ctx, { format: "xml" }); ``` -------------------------------- ### Using the PromptBuilder API Source: https://github.com/create-inc/teleprompt/blob/main/README.md Demonstrates various methods of the PromptBuilder class for constructing and modifying prompt sections. It covers appending, conditionally including, grouping, removing, checking existence, listing IDs, copying, and building the final prompt string in different formats. ```typescript new PromptBuilder() .use(section) .useOneOf(sectionA, sectionB) .group('name', b => b.use(...)) .without(section) .has(section) .ids() .fork() .build(ctx) .build(ctx, { format: 'xml' }) .buildWithMeta(ctx) ``` -------------------------------- ### Define and Compose Prompt Sections Source: https://github.com/create-inc/teleprompt/blob/main/README.md Define static and dynamic sections using the section function and compose them into a prompt using PromptBuilder. Sections can return null to be excluded from the final output. ```typescript import { PromptBuilder, section, type PromptContext } from '@anythingai/teleprompt'; type MyFlags = { webSearchEnabled: boolean }; type MyVars = { assistantName: string }; type MyContext = PromptContext; const guidelines = section('guidelines', () => `# Guidelines\n- Be concise and direct.\n- Cite sources when making factual claims.\n- Ask for clarification when a request is ambiguous.`); const identity = section('identity', (ctx: MyContext) => `You are ${ctx.vars.assistantName}, a helpful AI assistant.`); const webSearch = section('web-search', (ctx: MyContext) => { if (!ctx.flags.webSearchEnabled) return null; return `You have access to web search. Use it when the user asks about\ncurrent events or information that may have changed after your training cutoff.`; }); const prompt = new PromptBuilder() .use(identity) .use(guidelines) .use(webSearch) .build({ flags: { webSearchEnabled: true }, vars: { assistantName: 'Daniel' }, }); ``` -------------------------------- ### Small, Focused Sections for Reusability Source: https://github.com/create-inc/teleprompt/blob/main/llms.txt Illustrates the pattern of keeping prompt sections small and focused on a single concern. This enhances reusability across different prompt compositions and aids in debugging by providing granular metadata. ```typescript // Preferred — each concern is a composable unit const identity = section("identity", (ctx: Ctx) => `You are ${ctx.vars.userName}'s assistant.`); const guidelines = section("guidelines", () => "# Guidelines\n- Be concise."); const webSearch = section("web-search", (ctx: Ctx) => { if (!ctx.flags.webSearchEnabled) return null; return "You can search the web."; }); ``` -------------------------------- ### PromptBuilder.fork Source: https://context7.com/create-inc/teleprompt/llms.txt Creates an independent deep copy of the builder. Modifications to the fork don't affect the original, enabling creation of prompt variants from a shared base. ```APIDOC ## PromptBuilder.fork() ### Description Creates an independent deep copy of the builder. Modifications to the fork don't affect the original, enabling creation of prompt variants from a shared base. ### Method `fork` ### Parameters None ### Request Example ```typescript import { PromptBuilder, section, type PromptContext } from '@anythingai/teleprompt'; type Ctx = PromptContext<{}, { name: string }>; const identity = section('identity', (ctx: Ctx) => `You are ${ctx.vars.name}.`); const guidelines = section('guidelines', () => 'Be helpful and concise.'); const tone = section('tone', () => 'Maintain a friendly, professional tone.'); const escalation = section('escalation', () => 'Escalate to human support if unable to resolve.'); const codingRules = section('coding-rules', () => 'Follow best practices. Write clean, documented code.'); // Create a shared base const base = new PromptBuilder() .use(identity) .use(guidelines) .use(tone); // Customer support variant — adds escalation policy const supportAgent = base.fork() .use(escalation); // Code assistant variant — swaps tone for coding rules const codeAgent = base.fork() .without(tone) .use(codingRules); const ctx: Ctx = { flags: {}, vars: { name: 'Assistant' } }; console.log('=== Support Agent ==='); console.log(supportAgent.build(ctx)); // Output: // You are Assistant. // // Be helpful and concise. // // Maintain a friendly, professional tone. // // Escalate to human support if unable to resolve. console.log('\n=== Code Agent ==='); console.log(codeAgent.build(ctx)); // Output: // You are Assistant. // // Be helpful and concise. // // Follow best practices. Write clean, documented code. ``` ``` -------------------------------- ### section(id, render) Source: https://github.com/create-inc/teleprompt/blob/main/llms.txt Creates a modular PromptSection that can be conditionally included in a prompt based on the provided context. ```APIDOC ## section(id, render) ### Description Creates a new PromptSection. The render function receives the current PromptContext and returns either a string to be included in the final prompt or null to exclude it. ### Method Function Call ### Parameters #### Arguments - **id** (string) - Required - A unique identifier for the section. - **render** (function) - Required - A function with signature `(ctx: PromptContext) => string | null`. ### Request Example ```ts const identity = section("identity", (ctx: Ctx) => `You are ${ctx.vars.userName}'s assistant.`); ``` ### Response - **PromptSection** (object) - A section object ready to be used by a PromptBuilder. ``` -------------------------------- ### Teleprompt Testing Utilities Source: https://github.com/create-inc/teleprompt/blob/main/llms.txt Provides utility functions for testing prompt generation. Includes mocking contexts and rendering individual sections for isolated testing and asserting builder metadata. ```typescript import { mockContext, renderSection } from "@anythingai/teleprompt/testing"; // Render a single section in isolation const output = renderSection(webSearch, { flags: { webSearchEnabled: true } }); // Assert on builder metadata const { included, excluded } = builder.buildWithMeta(ctx); ``` -------------------------------- ### PromptBuilder API Source: https://github.com/create-inc/teleprompt/blob/main/README.md The PromptBuilder class allows for the programmatic construction of prompts using a fluent API to add, remove, or group sections before rendering. ```APIDOC ## PromptBuilder API ### Description The PromptBuilder class provides a fluent interface to construct prompts. It supports adding sections, conditional logic, grouping, and metadata extraction. ### Methods - **use(section)**: Appends a section or replaces it if the ID exists. - **useOneOf(...sections)**: Adds the first matching section from the provided list. - **group(name, callback)**: Wraps sections in a named XML group. - **without(section)**: Removes a section by object or string ID. - **has(section)**: Checks if a section exists in the builder. - **ids()**: Returns a list of all section IDs. - **fork()**: Creates an independent copy of the current builder state. - **build(ctx, options)**: Renders the prompt to a string, optionally with XML formatting. - **buildWithMeta(ctx)**: Renders the prompt and returns an object containing the included and excluded section IDs. ### Request Example ```ts new PromptBuilder() .use(section) .group('instructions', b => b.use(systemPrompt)) .build(ctx); ``` ``` -------------------------------- ### Define and Use PromptContext Interface Source: https://context7.com/create-inc/teleprompt/llms.txt Demonstrates how to define and create a custom PromptContext, including flags and variables, for use with Teleprompt sections. This provides type safety for context data passed to render functions. ```typescript import { type PromptContext } from '@anythingai/teleprompt'; // Define your application's context shape type MyFlags = { webSearchEnabled: boolean; citationEnabled: boolean; verbose: boolean; }; type MyVars = { assistantName: string; language: string; tasks: { title: string; status: string }[]; }; type MyContext = PromptContext; // Create a context instance const ctx: MyContext = { flags: { webSearchEnabled: true, citationEnabled: false, verbose: true, }, vars: { assistantName: 'Claude', language: 'English', tasks: [ { title: 'Review PR #123', status: 'pending' }, { title: 'Fix auth bug', status: 'in_progress' }, ], }, }; ``` -------------------------------- ### API: section(id, render) Function Signature Source: https://github.com/create-inc/teleprompt/blob/main/llms.txt Provides the API signature for the `section` function, which is used to create a `PromptSection`. The `render` function receives the context and should return a string or null. ```typescript /** * Creates a PromptSection. * @param id - Unique identifier for the section. * @param render - Function that receives context and returns the section's content as a string, or null to exclude. */ function section(id: string, render: (ctx: PromptContext) => string | null): PromptSection; ``` -------------------------------- ### Fork Prompt Builders Source: https://github.com/create-inc/teleprompt/blob/main/README.md Create independent variants of a prompt builder from a shared base configuration. ```typescript const base = new PromptBuilder() .use(identity) .use(guidelines) .use(tone); const supportAgent = base.fork() .use(escalationPolicy) .use(ticketFormat); const codeAssistant = base.fork() .without(guidelines) .without(tone) .use(codingGuidelines) .use(outputFormat); ``` -------------------------------- ### Testing Utilities Source: https://github.com/create-inc/teleprompt/blob/main/README.md Utilities for rendering sections in isolation and asserting on the structure of the generated prompt. ```APIDOC ## Testing Utilities ### Description Provides helper functions to render individual sections and inspect the inclusion/exclusion status of sections within a builder. ### Methods - **renderSection(section, context)**: Renders a specific section in isolation given a context. - **buildWithMeta(ctx)**: Returns an object containing the list of included and excluded section IDs for validation. ### Example ```ts import { mockContext, renderSection } from '@anythingai/teleprompt/testing'; const output = renderSection(webSearch, { flags: { webSearchEnabled: true } }); expect(output).toContain('web search'); ``` ``` -------------------------------- ### PromptBuilder.useOneOf Source: https://context7.com/create-inc/teleprompt/llms.txt Adds mutually exclusive sections where the first candidate that renders a non-empty string wins. Use this when exactly one of several sections should appear in the output based on runtime conditions. ```APIDOC ## PromptBuilder.useOneOf(...sections) ### Description Adds mutually exclusive sections where the first candidate that renders a non-empty string wins. Use this when exactly one of several sections should appear in the output based on runtime conditions. ### Method `useOneOf` ### Parameters - **sections** (Array
) - Required - An array of sections to choose from. ### Request Example ```typescript import { PromptBuilder, section, type PromptContext } from '@anythingai/teleprompt'; type Ctx = PromptContext<{}, { tasks: { title: string; status: string }[] }>; const hasTasks = section('has-tasks', (ctx: Ctx) => { if (ctx.vars.tasks.length === 0) return null; const lines = ctx.vars.tasks.map(t => `- ${t.title} [${t.status}]`); return `## Active Tasks\n\n${lines.join('\n')}`; }); const noTasks = section('no-tasks', (ctx: Ctx) => { if (ctx.vars.tasks.length > 0) return null; return '## Active Tasks\n\nNo tasks currently running.'; }); const builder = new PromptBuilder().useOneOf(hasTasks, noTasks); // With tasks const withTasks = builder.build({ flags: {}, vars: { tasks: [{ title: 'Fix bug', status: 'in_progress' }] }, }); // Output: ## Active Tasks // // - Fix bug [in_progress] // Without tasks const withoutTasks = builder.build({ flags: {}, vars: { tasks: [] }, }); // Output: ## Active Tasks // // No tasks currently running. ``` ``` -------------------------------- ### Create Teleprompt Sections Source: https://context7.com/create-inc/teleprompt/llms.txt Illustrates the creation of different types of Teleprompt sections using the `section` function. Sections can be static, dynamic (using context), or conditional (returning null to exclude). ```typescript import { section, type PromptContext } from '@anythingai/teleprompt'; type Flags = { webSearchEnabled: boolean; verbose: boolean }; type Vars = { userName: string; tasks: { title: string }[] }; type Ctx = PromptContext; // Static section — no context needed, works in any builder const guidelines = section('guidelines', () => `# Guidelines - Be concise and direct. - Cite sources when making factual claims. - Ask for clarification when a request is ambiguous.`); // Dynamic section — uses context variables const identity = section('identity', (ctx: Ctx) => `You are ${ctx.vars.userName}'s assistant.` ); // Conditional section — return null to exclude const webSearch = section('web-search', (ctx: Ctx) => { if (!ctx.flags.webSearchEnabled) return null; return 'You have access to web search. Use it for current events or information that may be outdated.'; }); // Conditional section with dynamic content const taskList = section('tasks', (ctx: Ctx) => { if (ctx.vars.tasks.length === 0) return null; const items = ctx.vars.tasks.map(t => `- ${t.title}`).join('\n'); return `## Active Tasks\n\n${items}`; }); ``` -------------------------------- ### PromptContext Interface Source: https://context7.com/create-inc/teleprompt/llms.txt Defines the structure for the typed context object passed to section render functions, including flags and variables. ```APIDOC ## PromptContext Interface PromptContext is the typed context object passed to every section's render function. It contains `flags` (boolean feature toggles) and `vars` (arbitrary data) that sections use to conditionally render content. ### TypeScript Example ```typescript import { type PromptContext } from '@anythingai/teleprompt'; // Define your application's context shape type MyFlags = { webSearchEnabled: boolean; citationEnabled: boolean; verbose: boolean; }; type MyVars = { assistantName: string; language: string; tasks: { title: string; status: string }[]; }; type MyContext = PromptContext; // Create a context instance const ctx: MyContext = { flags: { webSearchEnabled: true, citationEnabled: false, verbose: true, }, vars: { assistantName: 'Claude', language: 'English', tasks: [ { title: 'Review PR #123', status: 'pending' }, { title: 'Fix auth bug', status: 'in_progress' }, ], }, }; ``` ``` -------------------------------- ### Creating Prompt Variants with fork Source: https://context7.com/create-inc/teleprompt/llms.txt The fork method creates an independent deep copy of a PromptBuilder instance. This allows for the creation of different prompt variations from a common base without affecting the original builder. Modifications made to the forked builder, such as adding or removing sections, are isolated. ```typescript import { PromptBuilder, section, type PromptContext } from '@anythingai/teleprompt'; type Ctx = PromptContext<{}, { name: string }>; const identity = section('identity', (ctx: Ctx) => `You are ${ctx.vars.name}.`); const guidelines = section('guidelines', () => 'Be helpful and concise.'); const tone = section('tone', () => 'Maintain a friendly, professional tone.'); const escalation = section('escalation', () => 'Escalate to human support if unable to resolve.'); const codingRules = section('coding-rules', () => 'Follow best practices. Write clean, documented code.'); // Create a shared base const base = new PromptBuilder() .use(identity) .use(guidelines) .use(tone); // Customer support variant — adds escalation policy const supportAgent = base.fork() .use(escalation); // Code assistant variant — swaps tone for coding rules const codeAgent = base.fork() .without(tone) .use(codingRules); const ctx: Ctx = { flags: {}, vars: { name: 'Assistant' } }; console.log('=== Support Agent ==='); console.log(supportAgent.build(ctx)); // Output: // You are Assistant. // // Be helpful and concise. // // Maintain a friendly, professional tone. // // Escalate to human support if unable to resolve. console.log('\n=== Code Agent ==='); console.log(codeAgent.build(ctx)); // Output: // You are Assistant. // // Be helpful and concise. // // Follow best practices. Write clean, documented code. ``` -------------------------------- ### PromptBuilder.group Source: https://context7.com/create-inc/teleprompt/llms.txt Creates a named group of sections. In text format, groups are transparent (children render directly). In XML format, groups wrap children in `` tags. Groups can be nested for hierarchical organization. ```APIDOC ## PromptBuilder.group(id, configure) ### Description Creates a named group of sections. In text format, groups are transparent (children render directly). In XML format, groups wrap children in `` tags. Groups can be nested for hierarchical organization. ### Method `group` ### Parameters - **id** (string) - Required - The name of the group. - **configure** (function) - Required - A function that configures the sections within the group. ### Request Example ```typescript import { PromptBuilder, section, type PromptContext } from '@anythingai/teleprompt'; type Ctx = PromptContext<{ bashEnabled: boolean; gitEnabled: boolean }, {}>; const bashTool = section('bash', (ctx: Ctx) => { if (!ctx.flags.bashEnabled) return null; return 'You can execute bash commands.'; }); const gitTool = section('git', (ctx: Ctx) => { if (!ctx.flags.gitEnabled) return null; return 'You can run git operations.'; }); const identity = section('identity', () => 'You are a coding assistant.'); const builder = new PromptBuilder() .use(identity) .group('tools', b => b .use(bashTool) .use(gitTool) ); const ctx: Ctx = { flags: { bashEnabled: true, gitEnabled: true }, vars: {} }; // Text format — groups are transparent console.log(builder.build(ctx)); // Output: // You are a coding assistant. // // You can execute bash commands. // // You can run git operations. // XML format — groups wrap children console.log(builder.build(ctx, { format: 'xml' })); // Output: // // You are a coding assistant. // // // // // You can execute bash commands. // // // // You can run git operations. // // ``` ``` -------------------------------- ### Group Sections and XML Formatting Source: https://github.com/create-inc/teleprompt/blob/main/README.md Organize sections into groups which can be rendered as nested XML tags for improved LLM parsing. ```typescript const prompt = new PromptBuilder() .use(identity) .group('tools', b => b .use(webSearch) .use(calculator) ) .use(guidelines) .build(ctx, { format: 'xml' }); ``` -------------------------------- ### PromptBuilder.ids() Source: https://context7.com/create-inc/teleprompt/llms.txt Retrieves an array containing all section IDs present in the PromptBuilder. This includes IDs of regular sections, groups, and sections within oneOf candidates, maintaining their insertion order. ```APIDOC ## PromptBuilder.ids() ### Description Returns an array of all section ids in insertion order, including group ids and their children, and oneOf candidate ids. ### Method `ids()` ### Endpoint N/A (Instance method) ### Parameters None ### Request Example ```typescript import { PromptBuilder, section, type PromptContext } from '@anythingai/teleprompt'; type Ctx = PromptContext<{}, {}>; const builder = new PromptBuilder() .use(section('identity', () => 'Identity')) .group('tools', b => b .use(section('bash', () => 'Bash')) .use(section('git', () => 'Git')) ) .useOneOf( section('has-tasks', () => 'Tasks'), section('no-tasks', () => 'No tasks') ) .use(section('footer', () => 'Footer')); console.log(builder.ids()); ``` ### Response #### Success Response (200) - **string[]** - An array of all section IDs in insertion order. #### Response Example ``` ['identity', 'tools', 'bash', 'git', 'has-tasks', 'no-tasks', 'footer'] ``` ``` -------------------------------- ### Conditional Sections: Preferred Null Return Pattern Source: https://github.com/create-inc/teleprompt/blob/main/llms.txt Demonstrates the preferred method for handling conditional prompt content by returning `null` from the `section` render function. This approach keeps the condition and content together and is tracked in metadata. ```typescript // Preferred — condition and content together const verbose = section("verbose", (ctx: Ctx) => { if (!ctx.flags.verbose) return null; return "Show detailed explanations."; }); // Avoid — splits the condition from the content it controls const verbose: PromptSection = { id: "verbose", when: (ctx) => ctx.flags.verbose, render: () => "Show detailed explanations.", }; ``` -------------------------------- ### PromptContext Interface Definition Source: https://github.com/create-inc/teleprompt/blob/main/llms.txt Defines the structure for PromptContext, which holds flags and variables used in prompt generation. It defaults to open records for flexibility. ```typescript interface PromptContext< TFlags extends Record, TVars extends object, > { flags: TFlags; vars: TVars; } ``` -------------------------------- ### Grouping Sections with group Source: https://context7.com/create-inc/teleprompt/llms.txt The group method organizes sections into named groups. In text format, groups are transparent, rendering their children directly. In XML format, groups wrap their children in tags corresponding to the group's ID. This allows for hierarchical structuring of prompts. ```typescript import { PromptBuilder, section, type PromptContext } from '@anythingai/teleprompt'; type Ctx = PromptContext<{ bashEnabled: boolean; gitEnabled: boolean }, {}>; const bashTool = section('bash', (ctx: Ctx) => { if (!ctx.flags.bashEnabled) return null; return 'You can execute bash commands.'; }); const gitTool = section('git', (ctx: Ctx) => { if (!ctx.flags.gitEnabled) return null; return 'You can run git operations.'; }); const identity = section('identity', () => 'You are a coding assistant.'); const builder = new PromptBuilder() .use(identity) .group('tools', b => b .use(bashTool) .use(gitTool) ); const ctx: Ctx = { flags: { bashEnabled: true, gitEnabled: true }, vars: {} }; // Text format — groups are transparent console.log(builder.build(ctx)); // Output: // You are a coding assistant. // // You can execute bash commands. // // You can run git operations. // XML format — groups wrap children console.log(builder.build(ctx, { format: 'xml' })); // Output: // // You are a coding assistant. // // // // // You can execute bash commands. // // // // You can run git operations. // // ``` -------------------------------- ### Define Application Context Type with TypeScript Source: https://github.com/create-inc/teleprompt/blob/main/llms.txt Defines a custom context type for your application by extending the base PromptContext. This allows for strongly-typed flags and variables to be passed to prompt sections. ```typescript import { type PromptContext } from "@anythingai/teleprompt"; type Flags = { webSearchEnabled: boolean; verbose: boolean }; type Vars = { userName: string; tasks: Task[] }; type Ctx = PromptContext; ``` -------------------------------- ### PromptBuilder.has(id | section) Source: https://context7.com/create-inc/teleprompt/llms.txt Checks if a section exists within the PromptBuilder, identified by its string ID or section object. The search is performed recursively through groups and oneOf candidates. ```APIDOC ## PromptBuilder.has(id | section) ### Description Checks if a section exists in the builder by id string or section object. Searches recursively into groups and oneOf candidates. ### Method `has(id: string | section, ...)` ### Endpoint N/A (Instance method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { PromptBuilder, section, type PromptContext } from '@anythingai/teleprompt'; type Ctx = PromptContext<{}, {}>; const identity = section('identity', () => 'You are an assistant.'); const tools = section('tools', () => 'You have access to tools.'); const builder = new PromptBuilder() .use(identity) .group('capabilities', b => b.use(tools)); // Check by string id console.log(builder.has('identity')); // true console.log(builder.has('tools')); // true (found in group) console.log(builder.has('capabilities')); // true (group itself) console.log(builder.has('nonexistent')); // false // Check by section object console.log(builder.has(identity)); // true console.log(builder.has(tools)); // true ``` ### Response #### Success Response (200) - **boolean** - `true` if the section exists, `false` otherwise. #### Response Example ``` true ``` ``` -------------------------------- ### Conditional Section Rendering with useOneOf Source: https://context7.com/create-inc/teleprompt/llms.txt The useOneOf method adds mutually exclusive sections to a prompt. It selects the first section that produces a non-empty output based on the provided context. This is useful for scenarios where only one of several options should be included in the final prompt. ```typescript import { PromptBuilder, section, type PromptContext } from '@anythingai/teleprompt'; type Ctx = PromptContext<{}, { tasks: { title: string; status: string }[] }>; const hasTasks = section('has-tasks', (ctx: Ctx) => { if (ctx.vars.tasks.length === 0) return null; const lines = ctx.vars.tasks.map(t => `- ${t.title} [${t.status}]`); return `## Active Tasks\n\n${lines.join('\n')}`; }); const noTasks = section('no-tasks', (ctx: Ctx) => { if (ctx.vars.tasks.length > 0) return null; return '## Active Tasks\n\nNo tasks currently running.'; }); const builder = new PromptBuilder().useOneOf(hasTasks, noTasks); // With tasks const withTasks = builder.build({ flags: {}, vars: { tasks: [{ title: 'Fix bug', status: 'in_progress' }] }, }); // Output: ## Active Tasks // // - Fix bug [in_progress] // Without tasks const withoutTasks = builder.build({ flags: {}, vars: { tasks: [] }, }); // Output: ## Active Tasks // // No tasks currently running. ``` -------------------------------- ### Check Section Existence with PromptBuilder.has() Source: https://context7.com/create-inc/teleprompt/llms.txt Checks if a section exists within the PromptBuilder by its ID string or section object. The search is performed recursively through groups and oneOf candidates. ```typescript import { PromptBuilder, section, type PromptContext } from '@anythingai/teleprompt'; type Ctx = PromptContext<{}, {}>; const identity = section('identity', () => 'You are an assistant.'); const tools = section('tools', () => 'You have access to tools.'); const builder = new PromptBuilder() .use(identity) .group('capabilities', b => b.use(tools)); // Check by string id console.log(builder.has('identity')); // true console.log(builder.has('tools')); // true (found in group) console.log(builder.has('capabilities')); // true (group itself) console.log(builder.has('nonexistent')); // false // Check by section object console.log(builder.has(identity)); // true console.log(builder.has(tools)); // true ``` -------------------------------- ### Intentional Absence: Return Null Instead of Empty String Source: https://github.com/create-inc/teleprompt/blob/main/llms.txt Explains the best practice of returning `null` from a section's render function to signal intentional absence of content. This is preferred over an empty string as it is tracked in metadata, aiding observability. ```typescript // Preferred — null signals intentional absence, tracked in metadata const tools = section("tools", (ctx: Ctx) => { if (!ctx.flags.webSearchEnabled) return null; return "You can search the web."; }); // Avoid — empty string is ambiguous and not tracked as excluded const tools = section("tools", (ctx: Ctx) => ctx.flags.webSearchEnabled ? "You can search the web." : "" ); ``` -------------------------------- ### Implement Mutually Exclusive Sections Source: https://github.com/create-inc/teleprompt/blob/main/README.md Use useOneOf to ensure exactly one section from a group is rendered based on the first valid return value. ```typescript const hasTasks = section('has-tasks', (ctx: MyContext) => { if (ctx.vars.tasks.length === 0) return null; return `## Active Tasks\n\n${ctx.vars.tasks.map(t => `- ${t.title}`).join('\n')}`; }); const noTasks = section('no-tasks', () => '## Active Tasks\n\nNo tasks currently running.'); builder.useOneOf(hasTasks, noTasks); ``` -------------------------------- ### Remove Section with PromptBuilder.without() Source: https://context7.com/create-inc/teleprompt/llms.txt Demonstrates how to remove a section from the PromptBuilder using its ID string or section object. This method searches recursively and returns the builder for chaining. It is safe to call with non-existent IDs. ```typescript import { PromptBuilder, section, type PromptContext } from '@anythingai/teleprompt'; type Ctx = PromptContext<{}, {}>; const identity = section('identity', () => 'You are an assistant.'); const verbose = section('verbose', () => 'Provide detailed explanations.'); const disclaimer = section('disclaimer', () => 'This is not professional advice.'); const builder = new PromptBuilder() .use(identity) .use(verbose) .use(disclaimer); // Remove by string id const concise = builder.fork().without('verbose'); console.log(concise.build({ flags: {}, vars: {} })); // Output: // You are an assistant. // // This is not professional advice. // Remove by section object const noDisclaimer = builder.fork().without(disclaimer); console.log(noDisclaimer.build({ flags: {}, vars: {} })); // Output: // You are an assistant. // // Provide detailed explanations. // Remove from nested group const withTools = new PromptBuilder() .use(identity) .group('tools', b => b .use(section('bash', () => 'Bash access')) .use(section('git', () => 'Git access')) ); const noBash = withTools.fork().without('bash'); console.log(noBash.build({ flags: {}, vars: {} }, { format: 'xml' })); // Output: // // You are an assistant. // // // // // Git access // // ``` -------------------------------- ### PromptBuilder.without(id | section) Source: https://context7.com/create-inc/teleprompt/llms.txt Removes a section from the PromptBuilder by its ID or section object. It searches recursively through groups and oneOf candidates. This method is chainable and safe to call with non-existent IDs, performing no operation in such cases. ```APIDOC ## PromptBuilder.without(id | section) ### Description Removes a section by id string or section object. Searches recursively into groups and oneOf candidates. Returns the builder for chaining. Safe to call with non-existent ids (no-op). ### Method `without(id: string | section, ...)` ### Endpoint N/A (Instance method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { PromptBuilder, section, type PromptContext } from '@anythingai/teleprompt'; type Ctx = PromptContext<{}, {}>; const identity = section('identity', () => 'You are an assistant.'); const verbose = section('verbose', () => 'Provide detailed explanations.'); const disclaimer = section('disclaimer', () => 'This is not professional advice.'); const builder = new PromptBuilder() .use(identity) .use(verbose) .use(disclaimer); // Remove by string id const concise = builder.fork().without('verbose'); console.log(concise.build({ flags: {}, vars: {} })); // Remove by section object const noDisclaimer = builder.fork().without(disclaimer); console.log(noDisclaimer.build({ flags: {}, vars: {} })); // Remove from nested group const withTools = new PromptBuilder() .use(identity) .group('tools', b => b .use(section('bash', () => 'Bash access')) .use(section('git', () => 'Git access')) ); const noBash = withTools.fork().without('bash'); console.log(noBash.build({ flags: {}, vars: {} }, { format: 'xml' })); ``` ### Response #### Success Response (200) Returns the modified PromptBuilder instance for chaining. #### Response Example (Returns a `PromptBuilder` instance) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.