Skip to content

.withTemplate()


AgentForceAgent Optional Chainable

Load and apply template files to the agent with support for both plain text templates and Handlebars (.hbs) templates with dynamic data injection. Templates define structured content or instructions that the agent can use consistently across different executions.

withTemplate(templatePath: string, templateData?: Record<string, unknown>): AgentForceAgent
Parameter
Type
Default
Description
templatePath
string
undefined
The path to the template file to load (.txt, .md, .hbs supported)
templateData
Record<string, unknown>
undefined
Optional data object for Handlebars template rendering (only used with .hbs files)

Returns the AgentForceAgent instance for method chaining.

import { AgentForceAgent } from '@agentforce/adk';
// Load a plain text template
const agent = new AgentForceAgent({
name: "TemplateAgent"
})
.withTemplate("./templates/instructions.txt")
.useLLM("ollama", "gemma3:4b")
.prompt("Follow the template instructions");
const response = await agent.output("text");

instructions.txt:

You are a professional code reviewer.
Review Guidelines:
- Check for security vulnerabilities
- Verify proper error handling
- Ensure code follows best practices
- Provide constructive feedback
- Include specific examples
Please review the provided code thoroughly.
const agent = new AgentForceAgent({
name: "ConditionalAgent"
})
.withTemplate("./templates/role-based.hbs", {
userLevel: "expert",
includeAdvanced: true,
frameworks: ["React", "Vue", "Angular"]
})
.prompt("Provide framework recommendations");

role-based.hbs:

# Framework Recommendations
{{#if (eq userLevel "beginner")}}
I'll provide simple, beginner-friendly explanations.
{{else if (eq userLevel "intermediate")}}
I'll include some advanced concepts with explanations.
{{else}}
I'll provide comprehensive, expert-level guidance.
{{/if}}
## Available Frameworks
{{#each frameworks}}
- **{{this}}**: {{#if ../includeAdvanced}}Advanced features and best practices{{else}}Basic usage patterns{{/if}}
{{/each}}
{{#if includeAdvanced}}
## Advanced Topics
- Performance optimization
- Architecture patterns
- Testing strategies
{{/if}}

The withTemplate() method supports fluent chaining with other AgentForceAgent methods:

const agent = new AgentForceAgent({
name: "ChainedTemplateAgent",
tools: ["fs_read_file", "fs_write_file"]
})
.withTemplate("./templates/code-review.hbs", {
reviewType: "security",
language: "TypeScript",
strict: true
})
.systemPrompt("You are an expert code reviewer")
.useLLM("google", "gemini-1.5-pro")
.task("Read the source code file")
.task("Perform detailed code review")
.task("Generate review report")
.debug();
await agent.run();
Parameter
Type
Default
Description
.txt
Plain Text
Static
Simple text templates without variable substitution
.md
Markdown
Static
Markdown formatted templates with structure and formatting
.hbs
Handlebars
Dynamic
Dynamic templates with variables, conditionals, and loops

Code Review Templates

Template Type: Handlebars

Best for: Consistent review criteria, language-specific guidelines

Data: Review type, language, strict mode, standards

Documentation Templates

Template Type: Markdown

Best for: API docs, user guides, project documentation

Data: Project info, endpoints, examples

Prompt Templates

Template Type: Plain Text/Handlebars

Best for: Consistent agent behavior, role definitions

Data: User context, role parameters, preferences

Report Generation

Template Type: Handlebars

Best for: Structured reports, data visualization, analysis

Data: Metrics, time periods, formatting options

// Use descriptive template names
.withTemplate("./templates/security-code-review.hbs", reviewData)
// Structure data logically
const templateData = {
context: {
project: "E-commerce API",
language: "TypeScript",
framework: "Express.js"
},
settings: {
strictMode: true,
includePerformance: false
},
requirements: ["security", "maintainability"]
};
// Use conditional logic in Handlebars
{{#if settings.strictMode}}
Apply strict review criteria including:
- Type safety validation
- Error handling completeness
{{/if}}
// Organize templates by purpose
templates/
├── code-review/
│ ├── security-review.hbs
│ └── performance-review.hbs
├── documentation/
│ ├── api-reference.md
│ └── user-guide.md
└── prompts/
├── developer-assistant.txt
└── content-writer.hbs
// Missing file extension
.withTemplate("./templates/review") // Should be ./templates/review.hbs
// Wrong data structure
.withTemplate("./template.hbs", "string data") // Should be object
// Complex logic in templates
{{#if (and (eq type "security") (gt score 8) (not disabled))}}
// Too complex - move logic to JavaScript
// Hardcoded paths
.withTemplate("/absolute/path/template.hbs") // Use relative paths
// Missing error handling
// Always wrap in try/catch for production use
try {
const agent = new AgentForceAgent({ name: "SafeAgent" })
.withTemplate("./templates/review.hbs", {
type: "security",
language: "TypeScript"
})
.prompt("Perform code review");
const response = await agent.output("text");
} catch (error) {
if (error.message.includes("Failed to load template")) {
console.error("Template Error:", error.message);
// Handle missing file, invalid path, etc.
} else if (error.message.includes("Template path must be a string")) {
console.error("Invalid template path provided");
} else if (error.message.includes("Template path cannot be empty")) {
console.error("Empty template path provided");
} else {
console.error("Unexpected error:", error.message);
}
}

Common Error Messages:

  • Template path must be a string - Invalid parameter type
  • Template path cannot be empty - Empty or whitespace-only path
  • Failed to load template from "path": ENOENT - File not found
  • Failed to load template from "path": Permission denied - File access issues
  • .systemPrompt() - Set system instructions (can be used with templates)
  • .prompt() - Set user prompt (templates can enhance prompts)
  • .task() - Add tasks (templates can define task structures)
  • .useLLM() - Configure LLM provider