Building AI Agents with code examples in C#
Building AI Agents with C#. A Practical Guide with Code Examples.
Creating AI agents in C# is becoming increasingly accessible thanks to powerful frameworks and libraries. AI agents are autonomous programs that can reason, plan, learn, and take actions to achieve specific goals. In this article, we’ll explore the core concepts behind AI agents and provide you with concrete C# code examples to get started building your own intelligent agents.
What Is an AI Agent?
An AI agent perceives its environment through sensors and acts upon that environment through actuators. Typically, they combine components like:
- Reasoning and decision making
- Memory and knowledge storage
- Planning and executing actions
- Learning from experience
With modern AI models, you can integrate natural language understanding and generation capabilities into your agents. C# frameworks enable you to orchestrate these components efficiently.
Getting Started. Setting Up a Basic AI Agent in C#
Below is a simple example demonstrating setting up an AI agent that uses an AI service (like OpenAI or Azure OpenAI) to generate responses. It employs a modular design welcoming expansion towards complex behaviors.
using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
class SimpleAIAgent
{
private readonly HttpClient _httpClient;
private readonly string _apiKey;
private readonly string _endpoint;
public SimpleAIAgent(string apiKey, string endpoint)
{
_httpClient = new HttpClient();
_apiKey = apiKey;
_endpoint = endpoint;
}
public async Task<string> GenerateResponseAsync(string prompt)
{
var requestBody = new
{
prompt = prompt,
max_tokens = 100,
temperature = 0.7
};
var content = new StringContent(JsonSerializer.Serialize(requestBody));
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
_httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}");
var response = await _httpClient.PostAsync(_endpoint, content);
var jsonResponse = await response.Content.ReadAsStringAsync();
using var doc = JsonDocument.Parse(jsonResponse);
var result = doc.RootElement.GetProperty("choices")[0].GetProperty("text").GetString();
return result.Trim();
}
}
class Program
{
static async Task Main()
{
string apiKey = "YOUR_API_KEY";
string endpoint = "https://api.openai.com/v1/engines/davinci/completions";
var agent = new SimpleAIAgent(apiKey, endpoint);
Console.WriteLine("Ask the AI agent anything:");
string input = Console.ReadLine();
string response = await agent.GenerateResponseAsync(input);
Console.WriteLine("AI Agent says: " + response);
}
}
This example demonstrates connecting to an AI text generation service. You can upgrade your AI agent by adding modules for planning, memory management, or tool usage to execute specific tasks.
Advanced Example. Creating A Planner Agent Using Microsoft’s Semantic Kernel
Microsoft’s Semantic Kernel is an open-source SDK to easily build AI-driven applications and agents in C#. Here’s a conceptual snippet illustrating how to create and run a simple AI planner agent:
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Orchestration;
var kernel = Kernel.Builder.Build();
var planner = kernel.CreatePlanner();
var goal = "Plan a weekend trip to Bonaire including beach visits and snorkeling";
PlanResult plan = await planner.CreatePlanAsync(goal);
foreach(var step in plan.Steps)
{
Console.WriteLine($"Step: {step.Description}");
// You can invoke the step action here
}
This approach allows you to define complex task goals and let the AI create actionable plans, which your agent can then execute or prompt user input.
Best Practices for Building AI Agents in C#
- Modular Design: Isolate reasoning, memory, and action modules for easy testing and upgrade.
- Error Handling: Robustly handle network/API failures and unexpected data.
- Security: Always secure your API keys and sensitive info.
- Experiment With Tools Integration: Add plugins or API connectors to enable your agents to complete real-world tasks such as data retrieval or invoking services.
- Use Existing Frameworks: Explore Microsoft’s Semantic Kernel or third-party libraries for faster development.
Resources to Explore
- Microsoft Semantic Kernel Documentation
- GitHub Repository for AI Agents in C#
- Building Autonomous AI Agents in C# – Real World Tips
Conclusion
Building AI agents in C# is a highly rewarding endeavor that can range from simple conversational bots to complex autonomous planners. Leveraging APIs for large language models and combining them with intelligent planning and memory systems enables the creation of responsive and useful AI-driven applications.
Start small with a basic interaction agent and progressively include advanced components like planning and memory management. With the steady evolution of AI frameworks and Microsoft’s Semantic Kernel, C# developers have powerful tools at their fingertips to create the AI agents of tomorrow.