Prerequisites
- .NET 10 or later
- GitHub Copilot in your personal GitHub account (includes the GitHub Copilot Free plan)
- Visual Studio Code with C# DevKit extension
- dotnet-ef tool
What is an AI agent?
An AI agent is a goal-driven AI entity that can reason, take actions, and adapt autonomously in pursuit of an objective. Unlike a simple chatbot that only responds to user queries with pre-scripted answers, an AI agent can make decisions, use tools or APIs, and maintain memory of context to achieve a goal without step-by-step human guidance.
- Reasoning and planning
- Tool use
- Memory and context
- Interactive execution
What is the GitHub Copilot SDK?
The GitHub Copilot SDK is a multi-platform toolkit that allows you to embed an AI agent runtime into your own applications.
Why use an SDK for AI agents?
Building a full-featured AI agent from the ground up is complex. You need to handle conversation state management across turns, decide when to call which external API, ensure the AI's responses stay within boundaries, manage multiple AI models for different tasks, and implement safety measures.
The GitHub Copilot SDK removes that complexity by providing a prebuilt, production-tested agent engine. The SDK handles authentication, model management, chat sessions, and streaming. You focus on what gets built on top of those building blocks - your domain-specific tools and business logic.
Core concepts
Client
The CopilotClient class manages the connection to the Copilot CLI server.
Session
A CopilotSession represents a single conversation or task context. Each session has its own conversation history, model configuration, tool definitions, and system prompt. You create sessions from the client using CreateSessionAsync, send messages to them, and receive responses through an event-driven model.
Tools
Tools are functions that you register with a session so the AI agent can call them during reasoning. Each tool has a name, description, parameters, and a handler function. When the AI model decides to use a tool, the SDK intercepts the request, calls your handler, and feeds the result back to the model for further reasoning.
In .NET, you define tools using AIFunctionFactory.Create from Microsoft.Extensions.AI:
AIFunctionFactory.Create(
async ([Description("The order ID number")] int orderId) =>
await GetOrderDetailsAsync(orderId),
"get_order_details",
"Look up the status and details of a specific order.")
Events
The SDK uses an event-driven communication model.
Session hooks
The SDK provides hooks that let you intercept and modify agent behavior at key points.
Getting started
In a working directory create a Blazor app and add required packages with these terminal window commands:
dotnet new blazor -o AI4SchoolAgent
cd AI4SchoolAgent
mkdir Models
mkdir Data
mkdir Services
mkdir Tools
dotnet add package GitHub.Copilot.SDK
dotnet add package Microsoft.Extensions.AI
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
In the Models folder, add this C# Student class:
public class Student {
public int StudentId { get; set; }
[Required]
public String? FirstName { get; set; }
[Required]
public String? LastName { get; set; }
[Required]
public String? School { get; set; }
[Required]
public String? Gender { get; set; }
public DateOnly? DateOfBirth { get; set; }
public String? Status { get; set; }
}
We will populate a SQLite database with some sample student data. We will need an Entity Framework database context class. Add the following C# SchoolDbContext class inside the Data folder:
public class SchoolDbContext : DbContext {
public DbSet<Student> Students => Set<Student>();
public SchoolDbContext(DbContextOptions<SchoolDbContext> options) : base(options) { }
protected override void OnModelCreating(ModelBuilder modelBuilder) {
base.OnModelCreating(modelBuilder);
modelBuilder.EntityStudent>().HasData(GetStudents());
}
private static IEnumerable<Student> GetStudents() {
const string studentsUrl =
"https://gist.githubusercontent.com/medhatelmasry/2ae7a36d5392f862b0d1039b2a52b9b4/raw/45533eda6c43ce439dbc65c37a7fbdef01546c2d/students.json";
using var httpClient = new HttpClient();
var json = httpClient.GetStringAsync(studentsUrl).GetAwaiter().GetResult();
return System.Text.Json.JsonSerializer.Deserialize<List<Student>>(json)
?? throw new InvalidOperationException("The students JSON returned no data.");
}
}
In the above code, note that sample data is being read from a URL.
Add the following connection string to appsettings.json:
"ConnectionStrings": {
"DefaultConnection": "DataSource=school-db.sqlite;Cache=Shared;"
}
Let’s add some tools that will help us query the database using natural language. In the Tools folder, add a C# class named StudentsAgentTools with the following code:
public class StudentsAgentTools {
private readonly DbContext _dbContext;
public StudentsAgentTools(DbContext dbContext) {
_dbContext = dbContext;
}
public async Task<string> GetStudentDetailsByIdAsync(int studentId) {
// Query the database for student information
var student = await _dbContext.Set<Student>().FindAsync(studentId);
return student != null
? $"Student {studentId}: {student.FirstName} {student.LastName}, School: {student.School}, Gender: {student.Gender}, Status: {student.Status ?? "not recorded"}"
: "Student not found.";
}
public async Task<string> GetStudentsByGenderAsync(string gender) {
// Query the database for student information by gender
var students = await _dbContext.Set<Student>().Where(s => s.Gender == gender).ToListAsync();
if (students.Count == 0)
return "No students found.";
var result = new StringBuilder();
foreach (var student in students) {
result.AppendLine($"Student {student.StudentId}: {student.FirstName} {student.LastName}, School: {student.School}, Gender: {student.Gender}, Status: {student.Status ?? "not recorded"}");
}
return result.ToString();
}
public async Task<string> GetStudentsBySchoolAsync(string school) {
// Query the database for student information by school
var students = await _dbContext.Set<Student>().Where(s => s.School == school).ToListAsync();
if (students.Count == 0)
return "No students found.";
var result = new StringBuilder();
foreach (var student in students) {
result.AppendLine($"Student {student.StudentId}: {student.FirstName} {student.LastName}, School: {student.School}, Gender: {student.Gender}, Status: {student.Status ?? "not recorded"}");
}
return result.ToString();
}
public async Task<string> GetStudentsByAgeAsync() {
// Query the database for student information by school
var students = await _dbContext.Set<Student>().ToListAsync();
if (students.Count == 0)
return "No students found.";
var result = new StringBuilder();
foreach (var student in students) {
var today = DateOnly.FromDateTime(DateTime.Today);
var age = student.DateOfBirth is { } dateOfBirth
? today.Year - dateOfBirth.Year - (today < dateOfBirth.AddYears(today.Year - dateOfBirth.Year) ? 1 : 0)
: (int?)null;
result.AppendLine($"Student {student.StudentId}: {student.FirstName} {student.LastName}, School: {student.School}, Gender: {student.Gender}, Born: {student.DateOfBirth?.ToString("yyyy-MM-dd") ?? "not recorded"}, Age: {age?.ToString() ?? "not recorded"}");
}
return result.ToString();
}
public async Task<string> GetAllStudentsAsync() {
// Query the database for all students
var students = await _dbContext.Set<Student>().ToListAsync();
if (students.Count == 0)
return "No students found.";
var result = new StringBuilder();
foreach (var student in students) {
result.AppendLine($"Student {student.StudentId}: {student.FirstName} {student.LastName}, School: {student.School}, Gender: {student.Gender}, Status: {student.Status ?? "not recorded"}");
}
return result.ToString();
}
public async Task<string> ProcessWithdrawalAsync(int studentId, string reason) {
// Business logic to process the withdrawal
var student = await _dbContext.Set<Student>().FindAsync(studentId);
if (student == null)
return "Student not found.";
// Assuming we have a property to track return status for the student
student.Status = "Withdrawal Initiated";
await _dbContext.SaveChangesAsync();
return $"Withdrawal initiated for student {studentId}.";
}
}
Create an agent service named AgentService inside the Services folder with this code:
public class AgentService {
private readonly SchoolDbContext _db;
public AgentService(SchoolDbContext db) {
_db = db;
}
public async Task<string> AskAsync(string prompt) {
var client = new CopilotClient(
new CopilotClientOptions {
LogLevel = CopilotLogLevel.Info
});
await client.StartAsync();
var toolService = new StudentsAgentTools(_db);
var tools = new List<AIFunctionDeclaration> {
AIFunctionFactory.Create(
async (int studentId) =>
await toolService.GetStudentDetailsByIdAsync(studentId),
"get_student_details",
"Look up student details."),
AIFunctionFactory.Create(
async (int studentId, string reason) =>
await toolService.ProcessWithdrawalAsync(studentId, reason),
"process_withdrawal",
"Process a withdrawal request."),
AIFunctionFactory.Create(
async (string gender) =>
await toolService.GetStudentsByGenderAsync(gender),
"get_students_by_gender",
"Find students by gender"),
AIFunctionFactory.Create(
async (string school) =>
await toolService.GetStudentsBySchoolAsync(school),
"get_students_by_school",
"Find students by school"),
AIFunctionFactory.Create(
async () =>
await toolService.GetStudentsByAgeAsync(),
"get_students_by_age",
"Find students by age"),
AIFunctionFactory.Create(
async () =>
await toolService.GetAllStudentsAsync(),
"get_all_students",
"Get all students")
};
var config = new SessionConfig {
Model = "kimi-k3",
OnPermissionRequest = PermissionHandler.ApproveAll,
Tools = tools
};
var session = await client.CreateSessionAsync(config);
var responseBuilder = new StringBuilder();
var tcs = new TaskCompletionSource<string>();
session.On<SessionEvent>(evt => {
switch (evt) {
case AssistantMessageEvent msg:
responseBuilder.Append(msg.Data.Content);
break;
case SessionIdleEvent:
tcs.SetResult(responseBuilder.ToString());
break;
}
});
await session.SendAsync(new MessageOptions {
Prompt = prompt
});
return await tcs.Task.WaitAsync(
TimeSpan.FromSeconds(30));
}
}
Add these services to Program.cs:
builder.Services.AddDbContext<SchoolDbContext>(options =>
options.UseSqlite(
builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddScoped<AgentService>();
Now we can add a migration using the dotnet-ef tool. To add this tool, run the following terminal window command:
dotnet tool install -g dotnet-ef
Thereafter, run this command from a terminal window inside the root folder of your C# project:
dotnet ef migrations add M1 -o Data/Migrations
We will create the database with sample student data with the following command:
dotnet ef database update
At this stage you will notice that a database file named school-db.sqlite has been created in the project.
Building the Blazor UI
Add Components/Pages/Agent.razor with this code:
@page "/agent"
@rendermode InteractiveServer
@using AI4SchoolAgent.Services
@inject AgentService AgentService
<PageTitle>School AI Agent</PageTitle>
<h3>School Administration AI Agent</h3>
@if (IsBusy) {
<p class="alert alert-info mt-3" role="status">Thinking...</p>
}
<div class="chat-window">
@foreach (var message in Messages) {
<div class="message">
<b>@message.Role:</b>
<div>@message.Content</div>
</div>
}
</div>
<div class="mt-3">
<InputTextArea class="form-control" rows="4" @bind-Value="Prompt" />
<button class="btn btn-primary mt-2" @onclick="SendPrompt" disabled="@IsBusy">
Ask Agent
</button>
</div>
@if (!string.IsNullOrEmpty(ErrorMessage)) {
<div class="alert alert-danger mt-3" role="alert">@ErrorMessage</div>
}
@code {
string Prompt = "";
bool IsBusy;
string? ErrorMessage;
List<ChatMessage> Messages = new();
async Task SendPrompt() {
if (string.IsNullOrWhiteSpace(Prompt))
return;
Messages.Add(new ChatMessage {
Role = "User",
Content = Prompt
});
IsBusy = true;
ErrorMessage = null;
try {
var result = await AgentService.AskAsync(Prompt);
Messages.Add(new ChatMessage {
Role = "Agent",
Content = result
});
Prompt = "";
} catch (Exception ex) {
ErrorMessage = $"Unable to get a response: {ex.Message}";
} finally {
IsBusy = false;
}
}
class ChatMessage {
public string Role { get; set; } = "";
public string Content { get; set; } = "";
}
}
Add styling to Components/Pages/Agent.razor.css:
.chat-window {
border: 1px solid #ddd;
height: 500px;
overflow-y: auto;
padding: 10px;
background-color: #fafafa;
}
.message {
margin-bottom: 15px;
padding: 10px;
border-radius: 6px;
background-color: white;
}
Add a menu item to the app’s navigation. Open Components/Layout/NavMenu.razor in the editor. Add the following before the </nav> closing tag:
<div class="nav-item px-3">
<NavLink class="nav-link" href="agent">
<span class="bi bi-list-nested-nav-menu" aria-hidden="true"></span> Agent
</NavLink>
</div>
I got the following response for prompt: “Who is the oldest student in the school of medicine?”:
I'll help you find the oldest student in the School of Medicine. Let me first look
up the available student tools.Let me get the list of students in the School of
Medicine.No exact match — let me list all students to check the school names.
I found five students in Medicine. Let me check each one's details to find the oldest.
The oldest student in the School of Medicine is **Dan Ash** (Student ID: 8),
who is **32 years old**, born on March 19, 1994. For reference, here are all the Medicine students by age: 1. **Dan Ash** — 32 (born 1994-03-19) 2. Cat Yao — 32 (born 1994-06-28, slightly younger) 3. Deb Roy — 30 4. Mat Tan — 28 5. Mia Chu — 25 While both Dan Ash and Cat Yao are 32 years old, Dan Ash is the older of the two
by birth date. Is there anything else I can help you with?










