Table of Contents

Build Agent Templates for Reusable Patterns

Agent templates are pre-configured agent blueprints that encapsulate persona, instructions, planning strategy, and tool configuration into a single reusable object. Instead of repeating the same AgentBuilder calls across your codebase, you pick a template, customize it with fluent methods, and call Build().

For background on agents and their execution model, see the AI Agents glossary entry.


Why This Matters

Two production problems that agent templates solve:

  1. Configuration drift across teams. When multiple developers build agents with raw AgentBuilder, each one picks different personas, instructions, and planning strategies. Templates enforce a shared baseline so that every "Code" agent in your organization behaves consistently, while still allowing per-instance customization.
  2. Boilerplate reduction. Setting up a ReAct agent with tools, verbose thinking, and max iterations requires a dozen builder calls. AgentTemplates.ReAct(model).WithTools(webSearch).Build() replaces all of them.

Prerequisites

Requirement Minimum
.NET SDK 8.0+
VRAM 6+ GB

Step 1: Create the Project

dotnet new console -n AgentTemplatesDemo
cd AgentTemplatesDemo
dotnet add package LM-Kit.NET

Step 2: Understand the Template Architecture

Every template inherits from AgentTemplate, which provides:

Member Purpose
TemplateName Identifier (e.g., "Chat", "Code", "ReAct")
Model The language model to use
AdditionalInstructions Extra instructions appended to the template's base prompt
MaxIterations Override the default iteration limit
Build() Produces a fully configured Agent

The AgentTemplates static class is the factory. It exposes one method per template, with two overloads: parameterless (set model later) and with an LM parameter.


Step 3: Use a Chat Template

The simplest template. It configures a conversational agent with a personality and optional context.

using System.Text;
using LMKit.Model;
using LMKit.Agents;
using LMKit.Agents.Templates;

LMKit.Licensing.LicenseManager.SetLicenseKey("");

Console.InputEncoding = Encoding.UTF8;
Console.OutputEncoding = Encoding.UTF8;

Console.WriteLine("Loading model...");
using LM model = LM.LoadFromModelID("qwen3:8b",
    loadingProgress: p => { Console.Write($"\rLoading: {p * 100:F0}%   "); return true; });
Console.WriteLine("\n");

// Create a chat agent from a template
Agent agent = AgentTemplates.Chat(model)
    .WithPersonality("friendly and concise")
    .WithContext("You are helping a software developer debug .NET code.")
    .Build();

var executor = new AgentExecutor();
AgentExecutionResult result = executor.Execute(agent, "What causes a NullReferenceException?");
Console.WriteLine(result.Content);

Step 4: Use a Code Template with Language and Style Options

The Code template adds language filters, coding style presets, and optional test/documentation generation.

Agent coder = AgentTemplates.Code(model)
    .WithLanguages("C#", "Python")
    .WithStyle(CodeStyle.Defensive)
    .WithTests(true)
    .WithDocumentation(true)
    .WithProjectContext("ASP.NET Core 8 REST API with EF Core")
    .Build();

var executor = new AgentExecutor();
AgentExecutionResult result = executor.Execute(coder,
    "Write a retry helper that wraps HttpClient calls with exponential backoff.");
Console.WriteLine(result.Content);

The five CodeStyle presets:

Style Behavior
Clean Readable, well-structured code
Performant Optimized for speed and memory
Defensive Null checks, input validation, error handling
Minimal Fewest lines possible
Enterprise Patterns, interfaces, dependency injection

Step 5: Use a ReAct Template with Tools

The ReAct template configures Reason + Act planning, making the agent think step-by-step and invoke tools between reasoning steps.

using LMKit.Agents.Tools.BuiltIn;

Agent researcher = AgentTemplates.ReAct(model)
    .WithTools(BuiltInTools.WebSearch, BuiltInTools.CalcArithmetic)
    .WithVerboseThinking(true)
    .WithMaxSteps(10)
    .ForTask("Answer complex questions by searching the web and computing values.")
    .Build();

var executor = new AgentExecutor();
AgentExecutionResult result = await executor.ExecuteAsync(researcher,
    "What is the current population of France divided by the area in km²?");
Console.WriteLine(result.Content);

Step 6: Use a Writer Template for Content Generation

The Writer template supports content types, tones, audience targeting, and SEO optimization.

Agent writer = AgentTemplates.Writer(model)
    .WithContentType(ContentType.BlogPost)
    .WithTone(WritingTone.Conversational)
    .WithAudience("software engineers learning AI")
    .WithWordCount(500)
    .WithSeoOptimization(true)
    .Build();

var executor = new AgentExecutor();
AgentExecutionResult result = executor.Execute(writer,
    "Write about the benefits of running LLMs locally.");
Console.WriteLine(result.Content);

Step 7: Use Quick Factory Methods

For one-off agents, AgentTemplates provides convenience methods that return a ready-to-use Agent directly.

// Quick assistant: no configuration needed
Agent assistant = AgentTemplates.QuickAssistant(model);

// Quick coder: specify languages
Agent coder = AgentTemplates.QuickCoder(model, "C#", "TypeScript");

// Simple: just a model and optional system prompt
Agent simple = AgentTemplates.Simple(model, "You answer questions about cooking.");

Step 8: Discover Available Templates at Runtime

GetAvailableTemplates() returns metadata for all built-in templates. Use this to build selection menus or configuration UIs.

TemplateInfo[] templates = AgentTemplates.GetAvailableTemplates();

Console.WriteLine($"Available templates:\n");
foreach (TemplateInfo info in templates)
{
    Console.WriteLine($"  {info.Name,-16} {info.Description}");
}

Each TemplateInfo exposes:

Property Type Purpose
Name string Template name (e.g., "Chat")
Description string Human-readable summary
TemplateType Type The concrete AgentTemplate subclass

Step 9: Add Custom Instructions to Any Template

Every template supports AdditionalInstructions, which appends to the built-in system prompt without replacing it.

Agent analyst = AgentTemplates.Analyst(model);
analyst.AdditionalInstructions = "Always include data sources and confidence levels in your analysis.";
analyst.MaxIterations = 5;

Agent agent = analyst.Build();

This works on all templates: Chat, Code, ReAct, Tool, Analyst, Writer, Planner, Research, Reviewer, Summarizer, Extractor, Tutor, Translator, Classifier, Debugger, Editor, QA.