Code Review Templates
Template Type: Handlebars
Best for: Consistent review criteria, language-specific guidelines
Data: Review type, language, strict mode, standards
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
templatePath
string
undefined
templateData
Record<string, unknown>
undefined
Returns the AgentForceAgent
instance for method chaining.
import { AgentForceAgent } from '@agentforce/adk';
// Load a plain text templateconst 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.
import { AgentForceAgent } from '@agentforce/adk';
// Load a markdown templateconst agent = new AgentForceAgent({ name: "DocumentationAgent"}) .withTemplate("./templates/api-doc-template.md") .useLLM("google", "gemini-1.5-flash") .prompt("Generate API documentation for the user management endpoints");
const response = await agent.output("text");
api-doc-template.md:
# API Documentation Template
## Endpoint OverviewProvide a clear description of the endpoint's purpose.
## Request Format- Method: [GET/POST/PUT/DELETE]- URL: /api/endpoint- Headers: Required headers- Body: Request body format
## Response Format- Status Codes: Possible response codes- Body: Response body structure- Examples: Sample responses
## Error HandlingCommon error scenarios and their responses.
import { AgentForceAgent } from '@agentforce/adk';
// Load and render Handlebars template with dataconst agent = new AgentForceAgent({ name: "PersonalizedAgent"}) .withTemplate("./templates/personalized.hbs", { userName: "Alice", userRole: "Senior Developer", projectType: "React TypeScript", deadline: "2024-03-15" }) .useLLM("ollama", "phi4-mini:latest") .prompt("Help with my project");
const response = await agent.output("text");
personalized.hbs:
# Personal Assistant for {{userName}}
Hello {{userName}}! I'm your AI assistant configured for your role as a {{userRole}}.
## Project Context- **Project Type**: {{projectType}}- **Deadline**: {{deadline}}- **User**: {{userName}}
## My CapabilitiesI can help you with:{{#if (eq projectType "React TypeScript")}}- TypeScript development and debugging- React component architecture- State management patterns- Testing strategies{{/if}}
Let's work together to meet your {{deadline}} deadline!
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}}
const agent = new AgentForceAgent({ name: "TaskAgent"}) .withTemplate("./templates/task-list.hbs", { tasks: [ { name: "Setup project", priority: "high", estimated: "2h" }, { name: "Implement API", priority: "medium", estimated: "4h" }, { name: "Write tests", priority: "high", estimated: "3h" } ], projectName: "E-commerce Platform" }) .prompt("Help me prioritize and plan these tasks");
task-list.hbs:
# {{projectName}} - Task Planning
## Task OverviewTotal tasks: {{tasks.length}}
## Task List{{#each tasks}}### {{@index}}. {{name}}- **Priority**: {{priority}}- **Estimated Time**: {{estimated}}{{#if (eq priority "high")}}- ⚠️ **High Priority** - Schedule immediately{{/if}}
{{/each}}
## RecommendationsPlease help me create an optimal schedule considering the priorities and time estimates above.
const isDevelopment = process.env.NODE_ENV === 'development';
const agent = new AgentForceAgent({ name: "EnvironmentAgent"}) .withTemplate("./templates/environment.hbs", { environment: process.env.NODE_ENV || 'development', debugMode: isDevelopment, apiUrl: process.env.API_URL || 'http://localhost:3000', features: { logging: isDevelopment, analytics: !isDevelopment, cache: !isDevelopment } }) .prompt("Configure the application settings");
environment.hbs:
# Application Configuration - {{environment}}
## Environment Settings- **Mode**: {{environment}}- **API URL**: {{apiUrl}}{{#if debugMode}}- **Debug Mode**: Enabled ⚠️{{/if}}
## Feature Flags{{#with features}}- **Logging**: {{#if logging}}✅ Enabled{{else}}❌ Disabled{{/if}}- **Analytics**: {{#if analytics}}✅ Enabled{{else}}❌ Disabled{{/if}}- **Caching**: {{#if cache}}✅ Enabled{{else}}❌ Disabled{{/if}}{{/with}}
Please help configure the application according to these {{environment}} environment settings.
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();
.txt
Plain Text
Static
.md
Markdown
Static
.hbs
Handlebars
Dynamic
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 logicallyconst 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 purposetemplates/├── 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 typeTemplate path cannot be empty
- Empty or whitespace-only pathFailed to load template from "path": ENOENT
- File not foundFailed 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