Wednesday, September 9, 2026

Build an AI Agent with C# and .NET 8

In the previous article, we learned what an AI Agent is, how the agent loop works, and how agents can use tools to accomplish tasks.

Now let's build a simple AI Agent using C# and .NET 8.

The goal of this tutorial is not to build a complicated autonomous system. Instead, we will create a simple agent that demonstrates the core concepts:

  • LLM integration
  • Tool calling
  • Agent decision-making
  • Tool execution
  • Observations
  • Agent loop

Once you understand this basic architecture, you can extend it with RAG, MCP, databases, APIs, memory, and multiple tools.


What We Are Building

We will create a simple customer-support AI agent.

The user will be able to ask something like:

"What is the status of order 1001?"

The agent will decide that it needs to call an order lookup tool.

User
 ↓
AI Agent
 ↓
LLM
 ↓
Choose Tool
 ↓
get_order_status()
 ↓
Order System
 ↓
Tool Result
 ↓
LLM
 ↓
Final Answer

Prerequisites

Before starting, make sure you have:

  • .NET 8 SDK
  • Visual Studio 2022 or Visual Studio Code
  • Basic C# knowledge
  • Basic understanding of APIs and JSON
  • Access to an LLM API or a locally running compatible model

You can also use a local LLM if your model and client support tool/function calling.


Step 1: Create a .NET 8 Console Application

Open a terminal and create a new console application:

dotnet new console -n SimpleAiAgent
cd SimpleAiAgent

Open the project in Visual Studio or Visual Studio Code.


Step 2: Install the OpenAI .NET SDK

For this example, we will use the official OpenAI .NET client.

Install the NuGet package:

dotnet add package OpenAI

The same general architecture can also be adapted to other LLM providers that support compatible tool/function calling.


Step 3: Configure the API Key

For a quick local test, you can configure your API key as an environment variable.

On Windows:

setx OPENAI_API_KEY "YOUR_API_KEY"

Restart your terminal after setting the environment variable.

Security Note: Never commit API keys directly into source control. Use environment variables, user secrets, managed identity, or a secure secret-management solution for production applications.

Step 4: Create an Order Service

Let's create a simple C# service that represents an external business system.

Create a class named OrderService.cs:

public class OrderService
{
    public string GetOrderStatus(int orderId)
    {
        if (orderId == 1001)
        {
            return "Order 1001 is shipped and is expected to arrive tomorrow.";
        }

        if (orderId == 1002)
        {
            return "Order 1002 is being processed.";
        }

        return $"Order {orderId} was not found.";
    }
}

In a real application, this method could call:

  • A REST API
  • SQL Server
  • An ERP system
  • An order-management system
  • A microservice

The AI agent does not need to know how the data is retrieved. It only needs a well-defined tool.


Step 5: Define the Agent Tool

We need to expose the order lookup operation to the LLM.

The tool definition tells the model:

  • What the tool is called
  • What the tool does
  • What parameters it accepts

A conceptual tool definition looks like:

Tool Name:
get_order_status

Description:
Gets the current status of a customer order.

Parameter:
orderId - The order number to look up.

The description is important because the model uses it to determine when the tool should be used.


Step 6: Create the Tool Definition in C#

Using the OpenAI .NET SDK, we can describe the function to the model.

using OpenAI.Chat;

var getOrderStatusTool = ChatTool.CreateFunctionTool(
    functionName: "get_order_status",
    functionDescription: "Gets the current status of a customer order.",
    functionParameters: BinaryData.FromString("""
    {
        "type": "object",
        "properties": {
            "orderId": {
                "type": "integer",
                "description": "The order number to look up."
            }
        },
        "required": ["orderId"]
    }
    """)
);

The JSON schema tells the model what arguments the function expects.


Step 7: Create the Chat Client

Now we can create the chat client.

using OpenAI.Chat;

string apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY")
    ?? throw new InvalidOperationException("OPENAI_API_KEY is not configured.");

ChatClient client = new(
    model: "gpt-4o-mini",
    apiKey: apiKey
);
Note: Model names and availability can change over time. Use a model that is currently available to your account and supports the capabilities required by your application.

Step 8: Send the User Request

Let's start with a simple request:

string userMessage =
    "What is the status of order 1001?";

We now send the message to the LLM along with the tool definition.

List messages =
[
    new UserChatMessage(userMessage)
];

ChatCompletionOptions options = new()
{
    Tools = { getOrderStatusTool }
};

ChatCompletion completion =
    client.CompleteChat(messages, options);

Step 9: Detect a Tool Call

The model may determine that it needs to use the get_order_status tool.

We can inspect the response:

if (completion.FinishReason == ChatFinishReason.ToolCalls)
{
    Console.WriteLine("The agent requested a tool.");
}

The model can return a tool call containing the function name and arguments.

Conceptually, the response may look like:

Function:
get_order_status

Arguments:
{
    "orderId": 1001
}

Step 10: Execute the Tool

Now our C# application needs to execute the requested function.

OrderService orderService = new();

string result =
    orderService.GetOrderStatus(1001);

Console.WriteLine(result);

The output will be:

Order 1001 is shipped and is expected to arrive tomorrow.

This is an important concept:

The LLM does not directly execute your C# method. The application receives the tool request, validates it, executes the appropriate code, and sends the result back to the model.

Step 11: Send the Tool Result Back to the LLM

After executing the tool, the application sends the result back to the model.

messages.Add(new AssistantChatMessage(completion));

messages.Add(
    new ToolChatMessage(
        toolCallId,
        result
    )
);

completion = client.CompleteChat(messages, options);

The LLM now has the information returned by the tool.


Step 12: Generate the Final Answer

The model can now generate a natural-language response.

Console.WriteLine(completion.Content[0].Text);

Example:

Order 1001 has been shipped and is expected
to arrive tomorrow.

The complete flow is:

User
 ↓
"What is the status of order 1001?"
 ↓
LLM
 ↓
Tool Call
 ↓
get_order_status(1001)
 ↓
C# OrderService
 ↓
Order System
 ↓
Tool Result
 ↓
LLM
 ↓
Final Answer

Step 13: Build the Agent Loop

A real agent may need to perform more than one action.

For example:

User:
"Find order 1001 and tell me whether
it is likely to arrive tomorrow."

Agent:

1. Get order status
2. Get shipment information
3. Check delivery estimate
4. Analyze results
5. Generate answer

Therefore, we need a loop.

while (true)
{
    Send messages to LLM

    if (LLM requests a tool)
    {
        Execute tool
        Add tool result to messages
        Continue
    }

    Return final response
    break;
}

This is the foundation of an agent loop.


Complete Simplified Agent Example

The following example demonstrates the overall architecture:

using OpenAI.Chat;

string apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY")
    ?? throw new InvalidOperationException("OPENAI_API_KEY is not configured.");

ChatClient client = new(
    model: "gpt-4o-mini",
    apiKey: apiKey
);

OrderService orderService = new();

var tool = ChatTool.CreateFunctionTool(
    functionName: "get_order_status",
    functionDescription: "Gets the current status of a customer order.",
    functionParameters: BinaryData.FromString("""
    {
        "type": "object",
        "properties": {
            "orderId": {
                "type": "integer",
                "description": "The order number."
            }
        },
        "required": ["orderId"]
    }
    """)
);

List messages =
[
    new UserChatMessage(
        "What is the status of order 1001?"
    )
];

ChatCompletionOptions options = new()
{
    Tools = { tool }
};

while (true)
{
    ChatCompletion completion =
        client.CompleteChat(messages, options);

    if (completion.FinishReason == ChatFinishReason.ToolCalls)
    {
        messages.Add(new AssistantChatMessage(completion));

        foreach (ChatToolCall toolCall in completion.ToolCalls)
        {
            if (toolCall.FunctionName == "get_order_status")
            {
                int orderId =
                    int.Parse(toolCall.FunctionArguments
                        .ToString()
                        .Replace("{\"orderId\":", "")
                        .Replace("}", ""));

                string result =
                    orderService.GetOrderStatus(orderId);

                messages.Add(
                    new ToolChatMessage(
                        toolCall.Id,
                        result
                    )
                );
            }
        }

        continue;
    }

    Console.WriteLine(completion.Content[0].Text);
    break;
}
Important: The JSON argument parsing above is intentionally simplified for demonstration. Production applications should deserialize tool arguments using System.Text.Json, validate all inputs, and handle malformed requests safely.

Production-Ready Argument Parsing

Instead of manually parsing JSON strings, use System.Text.Json.

using System.Text.Json;

public class OrderRequest
{
    public int OrderId { get; set; }
}

OrderRequest request =
    JsonSerializer.Deserialize<OrderRequest>(
        toolCall.FunctionArguments.ToString()
    )!;

Then execute:

string result =
    orderService.GetOrderStatus(request.OrderId);

This is safer and easier to maintain.


What Makes This an AI Agent?

You might ask:

"Isn't this just function calling?"

Function calling is one of the building blocks.

The agent behavior comes from combining the model with a loop that can:

  • Understand the user's goal
  • Choose a tool
  • Execute the tool
  • Observe the result
  • Decide whether another action is required
  • Return the final result

In simplified form:

LLM
 ↓
Decision
 ↓
Tool
 ↓
Observation
 ↓
LLM
 ↓
Decision
 ↓
Tool
 ↓
Observation
 ↓
Final Answer

Adding Multiple Tools

An agent becomes more useful when it has multiple tools.

For example:

get_order_status()
get_customer()
check_inventory()
get_shipment()
search_knowledge_base()
send_email()

The model can select the appropriate tool based on the user's request.

For example:

User:
"Is Product 123 available?"

        ↓

Agent

        ↓

check_inventory(123)

Another request might result in:

User:
"Where is my order?"

        ↓

Agent

        ↓

get_order_status(1001)

Tool Dispatcher Pattern

When you have many tools, it is useful to create a central dispatcher.

switch (toolCall.FunctionName)
{
    case "get_order_status":
        return GetOrderStatus(toolCall);

    case "get_customer":
        return GetCustomer(toolCall);

    case "check_inventory":
        return CheckInventory(toolCall);

    default:
        throw new InvalidOperationException(
            $"Unknown tool: {toolCall.FunctionName}");
}

This keeps the agent loop separate from the business logic.


Recommended .NET Architecture

For a production application, avoid putting everything inside Program.cs.

A cleaner structure could be:

SimpleAiAgent/
│
├── Agents/
│   ├── AiAgent.cs
│   └── AgentOptions.cs
│
├── Tools/
│   ├── IAgentTool.cs
│   ├── OrderTool.cs
│   ├── CustomerTool.cs
│   └── InventoryTool.cs
│
├── Services/
│   ├── OrderService.cs
│   └── CustomerService.cs
│
├── Models/
│   ├── Order.cs
│   └── Customer.cs
│
├── Program.cs
└── appsettings.json

This separation makes the application easier to test and maintain.


Adding an Interface for Tools

You can define a common interface:

public interface IAgentTool
{
    string Name { get; }

    string Description { get; }

    Task<string> ExecuteAsync(
        string arguments);
}

Each tool can implement this interface.

public class OrderTool : IAgentTool
{
    public string Name => "get_order_status";

    public string Description =>
        "Gets the current status of a customer order.";

    public Task<string> ExecuteAsync(string arguments)
    {
        // Validate arguments
        // Call order service
        // Return result

        return Task.FromResult(
            "Order is shipped."
        );
    }
}

Adding RAG to the Agent

We can extend the agent by adding a RAG tool.

search_company_documents()

Now the agent can answer questions using company documentation.

User
 ↓
Agent
 ↓
LLM
 ↓
Need company information?
 ↓
RAG Tool
 ↓
Vector Database
 ↓
Relevant Documents
 ↓
LLM
 ↓
Answer

This is a powerful combination of AI agents and RAG.


Adding MCP

MCP can also be incorporated into an agent architecture.

AI Agent
    ↓
MCP Client
    ↓
MCP Server
    ↓
Tools
    ↓
External Systems

Instead of implementing every integration directly inside the agent application, MCP can provide a standardized way for compatible AI applications to discover and use external capabilities.


Adding Memory

An agent can also maintain conversation or task state.

Conversation

User:
"My order is 1001."

Agent:
"Order 1001 is shipped."

User:
"When will it arrive?"

Agent:
"Order 1001 is expected tomorrow."

The agent needs the previous context to understand what the user means by it.

For longer-lived applications, memory can be stored in databases or other persistent storage systems.


Adding Guardrails

Production agents should not be allowed to execute arbitrary operations without controls.

Consider a tool such as:

delete_customer()
refund_payment()
cancel_order()

These operations can have real business consequences.

Therefore, implement:

  • Authentication
  • Authorization
  • Input validation
  • Tool allowlists
  • Rate limiting
  • Timeouts
  • Maximum agent steps
  • Audit logging
  • Human approval for sensitive operations

Maximum Agent Steps

An agent should not be allowed to loop forever.

For example:

const int maxSteps = 10;

for (int step = 0; step < maxSteps; step++)
{
    // Ask LLM
    // Execute tools
    // Continue or finish
}

If the maximum number of steps is reached, stop the agent and return an appropriate message.


Error Handling

Tools can fail.

For example:

Database unavailable
API timeout
Invalid order ID
Authorization failure
Network failure

Your tool layer should handle these errors gracefully.

try
{
    var result = await orderService.GetOrderStatusAsync(orderId);

    return result;
}
catch (Exception ex)
{
    // Log exception
    // Return safe tool result
}

The agent can then decide whether it should retry, use another tool, or report the problem.


Logging an AI Agent

Agent applications should have detailed logging.

Useful information includes:

  • User request
  • Agent execution ID
  • Tool selected
  • Tool arguments
  • Tool execution time
  • Tool result status
  • LLM response time
  • Number of agent steps
  • Errors

Be careful not to log sensitive information such as passwords, API keys, payment information, or unnecessary personal data.


Simple Agent Architecture for .NET

                   User
                     ↓
                ASP.NET Core
                     ↓
                 AI Agent
                     ↓
                    LLM
                     ↓
              Tool Dispatcher
                     ↓
        ┌────────────┼────────────┐
        ↓            ↓            ↓
     Order API    Database      RAG
        ↓            ↓            ↓
      Data         Data       Documents
        └────────────┼────────────┘
                     ↓
                 Tool Result
                     ↓
                    LLM
                     ↓
                 Final Answer

Agent vs Normal API

It is important to understand when an agent is actually necessary.

If your application simply needs:

GET /orders/1001

you probably do not need an AI agent.

A normal API is simpler and more predictable.

An agent becomes more useful when the request is open-ended:

"Investigate why order 1001 is delayed
and tell me what action we should take."

The agent may need to combine several operations:

Get Order
   ↓
Check Payment
   ↓
Check Shipment
   ↓
Search Documentation
   ↓
Analyze
   ↓
Recommend Action

Common Mistakes When Building AI Agents

1. Giving the Agent Too Many Tools

Providing hundreds of tools can make tool selection more difficult and increase complexity.

2. Poor Tool Descriptions

Tool descriptions should clearly explain what the tool does and when it should be used.

3. No Validation

Never trust tool arguments simply because they came from an LLM.

4. No Step Limit

Always protect the application from endless agent loops.

5. No Authorization

Agents should operate with only the permissions they actually need.

6. Using an Agent for Everything

Simple deterministic operations are often better implemented using normal application logic.


Agentic Application Design Principle

A useful principle is:

Use AI for decisions that benefit from flexibility, and use deterministic code for operations that require predictability.

For example:

AI:
"What should I do next?"

Code:
"How do I execute this operation safely?"

The AI can select the tool, while your application remains responsible for validation, security, business rules, and actual execution.


Complete Flow

Our simple AI agent can now be represented as:

                User
                  ↓
          "Check order 1001"
                  ↓
              AI Agent
                  ↓
                 LLM
                  ↓
          Choose Tool
                  ↓
        get_order_status()
                  ↓
          Validate Input
                  ↓
          Execute C# Code
                  ↓
          Order Service
                  ↓
          Business System
                  ↓
            Tool Result
                  ↓
                 LLM
                  ↓
            Final Answer

Key Takeaways

  • An AI agent can be built using an LLM, tools, application logic, and an execution loop.
  • Function calling is an important building block for tool-based agents.
  • The LLM decides which tool may be useful, but the application executes the tool.
  • Tool arguments must be validated before execution.
  • Multiple tools allow agents to perform more complex tasks.
  • RAG can provide an agent with access to external knowledge.
  • MCP can provide a standardized way to connect compatible AI applications with external capabilities.
  • Memory can maintain useful conversation or task state.
  • Production agents need security, authorization, logging, error handling, and step limits.
  • Not every application needs an AI agent.
  • Deterministic code should continue to handle critical business rules and operations.

Conclusion

Building an AI agent does not require a huge framework to understand the fundamentals.

At its core, an agent can be thought of as:

Goal
 ↓
LLM
 ↓
Choose Tool
 ↓
Execute Tool
 ↓
Observe Result
 ↓
LLM
 ↓
Next Action
 ↓
Repeat
 ↓
Final Answer

With C# and .NET 8, you can build this architecture using familiar concepts such as classes, interfaces, dependency injection, APIs, services, logging, and asynchronous programming.

Once the basic agent works, you can gradually add RAG, MCP, memory, additional tools, authentication, observability, and human approval.

The important thing is to start with a small, well-defined agent and expand its capabilities only when the use case requires them.

Next: AI Agent Memory Explained: Short-Term vs Long-Term Memory — Learn how AI agents maintain conversation context, task state, and persistent knowledge.

Tuesday, September 8, 2026

LLM vs AI Agent vs Chatbot: What’s the Difference?

Artificial Intelligence has introduced many terms that sound similar: LLM, chatbot, AI assistant, and AI agent.

These terms are often used interchangeably, but they describe different concepts.

An LLM can generate text. A chatbot provides a conversational interface. An AI assistant can help users perform tasks, while an AI agent can use tools and make decisions to accomplish a goal.

Understanding these differences is important when designing modern AI applications.


LLM vs Chatbot vs AI Agent — The Simple Explanation

LLM
↓
The AI model that understands and generates content.

Chatbot
↓
An application that allows users to interact conversationally.

AI Assistant
↓
A helpful AI application that can use context and tools
to assist with tasks.

AI Agent
↓
A goal-oriented system that can decide actions,
use tools, observe results, and continue working.

These concepts can overlap. For example, an AI agent can use an LLM and can also provide a chatbot-like interface.


What Is an LLM?

LLM stands for Large Language Model.

An LLM is an AI model trained on large amounts of text and other data to understand and generate language.

Examples of tasks an LLM can perform include:

  • Answering questions
  • Summarizing text
  • Generating code
  • Translating languages
  • Explaining technical concepts
  • Generating structured output
  • Analyzing information provided in its context

A simple interaction looks like:

User Prompt
     ↓
    LLM
     ↓
Generated Response

The LLM itself is the model. It is not necessarily a complete application.


Example of an LLM

Suppose a developer asks:

"Explain dependency injection in .NET."

The LLM can generate an explanation:

Dependency Injection is a design pattern
where dependencies are provided to a class
rather than created directly by the class.

This is a simple model interaction.


What Is a Chatbot?

A chatbot is an application that provides a conversational interface.

A chatbot may use an LLM, but the chatbot itself is the complete application around the model.

User
 ↓
Chat Interface
 ↓
Application
 ↓
LLM
 ↓
Response
 ↓
Chat Interface
 ↓
User

The chatbot can manage conversations, authentication, conversation history, UI, safety rules, and other application functionality.


Does a Chatbot Always Use an LLM?

No.

Traditional chatbots existed long before modern LLMs.

A traditional rule-based chatbot might work like:

User:
"What are your opening hours?"

        ↓

Rule:
If message contains "opening hours"

        ↓

Return:
"We are open from 9 AM to 6 PM."

An LLM-powered chatbot is more flexible because it can understand natural language rather than relying only on predefined rules.


What Is an AI Assistant?

An AI assistant is an application designed to help a user perform tasks or obtain information.

An assistant can combine:

  • LLMs
  • Conversation history
  • Tools
  • APIs
  • RAG
  • Memory
  • Application-specific instructions

For example, an AI assistant for a company might:

Answer questions
Search company documents
Check order status
Search customer information
Create reports
Summarize emails

An assistant does not necessarily need to be fully autonomous.


What Is an AI Agent?

An AI agent is a goal-oriented system that uses an AI model to decide what actions to take and interact with external tools or systems to accomplish a task.

A simplified architecture is:

User Goal
    ↓
   LLM
    ↓
Choose Action
    ↓
Use Tool
    ↓
Observe Result
    ↓
   LLM
    ↓
Choose Next Action
    ↓
Repeat
    ↓
Final Result

The key difference is the action loop.


A Simple AI Agent Example

Imagine a user says:

"Find out why order 12345 is delayed
and tell me what I should do."

An agent might perform:

1. Find Order 12345
       ↓
2. Check Order Status
       ↓
3. Check Shipment Status
       ↓
4. Find Delivery Information
       ↓
5. Analyze the results
       ↓
6. Generate recommendation

The agent can determine which actions are needed based on the results it receives.


LLM vs Chatbot vs AI Agent

Feature LLM Chatbot AI Agent
What is it? AI model Conversational application Goal-oriented AI system
Main purpose Generate and understand content Conversation Complete tasks
Conversation Can support it Yes Usually yes
Uses tools Not inherently Optional Commonly
Can make multi-step decisions Limited by itself Usually limited Yes
Memory Requires context/application Can maintain conversation history Can use short and long-term memory
External systems Requires integration Can integrate Commonly integrates through tools
Goal-oriented Not necessarily Usually conversational Yes

How an LLM Fits Inside an AI Agent

An AI agent does not replace the LLM.

The LLM is usually one of the most important components of the agent.

                 AI Agent
                     │
          ┌──────────┼──────────┐
          ↓          ↓          ↓
         LLM       Memory      Tools
          │                     │
          │                     ↓
          │              External Systems
          │
          ↓
       Decision
          ↓
       Action

The LLM can interpret the goal and help determine which action should happen next.


What Are Tools?

A tool is an operation that an AI application or agent can invoke.

Examples include:

search_web()
get_customer()
get_order()
check_inventory()
query_database()
send_email()
create_ticket()
calculate()

Tools allow AI systems to interact with the real world or with business applications.


Function Calling and AI Agents

Function calling allows an LLM to request that a specific function or tool be executed.

For example:

User:
"What's the stock for product 100?"

        ↓

LLM

        ↓

Tool Call:
check_inventory(100)

        ↓

Application

        ↓

Inventory System

        ↓

Result:
Stock = 12

        ↓

LLM

        ↓

"Product 100 currently has 12 items in stock."

This is one of the mechanisms that enables an AI agent to interact with external systems.


Where Does RAG Fit?

RAG stands for Retrieval-Augmented Generation.

RAG allows an AI application to retrieve relevant information from an external knowledge source and provide it to the LLM.

User Question
      ↓
   Retrieval
      ↓
Vector Database
      ↓
Relevant Documents
      ↓
     LLM
      ↓
    Answer

RAG is useful when the AI needs information that may not be available in the model's training data or when answers need to be grounded in a specific knowledge base.


RAG in an AI Agent

RAG can also be exposed as a tool.

AI Agent
    ↓
Search Knowledge Tool
    ↓
RAG
    ↓
Vector Database
    ↓
Relevant Documents
    ↓
AI Agent

The agent can decide when it needs to search the knowledge base.


Where Does MCP Fit?

MCP stands for Model Context Protocol.

MCP provides a standardized protocol for compatible AI applications to interact with external capabilities such as tools and resources.

A simplified architecture is:

AI Application
      ↓
   MCP Client
      ↓
   MCP Server
      ↓
 ┌────┼──────────┐
 ↓    ↓          ↓
Tools Resources Prompts

MCP can therefore be part of an AI agent architecture.

AI Agent
    ↓
MCP Client
    ↓
MCP Server
    ↓
External Tools
    ↓
APIs / Databases / Files

AI Assistant vs AI Agent

The terms assistant and agent can overlap, and there is no single universally accepted boundary between them.

Generally, an assistant is focused on helping the user, while an agent emphasizes goal-oriented action and decision-making.

For example:

AI Assistant:

User:
"What's my order status?"

Assistant:
"Your order is being shipped."

An agent might handle a more complex request:

User:
"My order is late. Find out why and
contact support if necessary."

Agent:

Find Order
   ↓
Check Shipment
   ↓
Identify Problem
   ↓
Determine Action
   ↓
Contact Support
   ↓
Report Result

Simple Example: Restaurant Reservation

Consider a user asking:

"Find a restaurant for four people
tomorrow at 7 PM and make a reservation."

An LLM can understand the request.

A chatbot can provide a conversational interface.

An assistant can help search for restaurants.

An agent could potentially:

Understand Request
       ↓
Find Restaurants
       ↓
Check Availability
       ↓
Compare Options
       ↓
Select Based on Criteria
       ↓
Make Reservation
       ↓
Confirm Reservation

The agent is coordinating multiple actions to achieve a goal.


Simple Example: Software Development

Imagine a developer says:

"Find the cause of this error
and fix the code."

An LLM can analyze the error.

A chatbot can discuss the problem.

An AI assistant can suggest code.

An AI coding agent may be able to:

Read Source Code
      ↓
Search Related Files
      ↓
Inspect Configuration
      ↓
Analyze Error
      ↓
Modify Code
      ↓
Run Tests
      ↓
Inspect Test Results
      ↓
Fix Problems
      ↓
Run Tests Again

This demonstrates why agents are becoming important in software development.


Reactive vs Agentic Systems

A simple LLM application is often reactive:

Input
 ↓
Process
 ↓
Output

An agentic system can be iterative:

Goal
 ↓
Think / Decide
 ↓
Act
 ↓
Observe
 ↓
Think / Decide
 ↓
Act
 ↓
Observe
 ↓
Complete Goal

The ability to iterate based on observations is a key characteristic of agentic systems.


Does an AI Agent Have to Be Autonomous?

No.

An agent can operate with different levels of autonomy.

For example:

Level 1:
AI suggests an action.

Level 2:
AI prepares the action and asks for approval.

Level 3:
AI executes low-risk actions automatically.

Level 4:
AI performs multi-step tasks with limited supervision.

The appropriate level depends on the application's risk, security requirements, and business rules.


Human-in-the-Loop AI Agents

For sensitive operations, a human can remain in control.

AI Agent
   ↓
Prepare Action
   ↓
Human Approval
   ↓
Execute Tool
   ↓
Result

For example, an AI agent might prepare a refund but require a human to approve it before the transaction is executed.


AI Agent Architecture

A modern AI application may combine many of the concepts we have discussed:

                         User
                           ↓
                    Chat Interface
                           ↓
                       AI Agent
                           ↓
                          LLM
                           ↓
                  Decision / Planning
                           ↓
             ┌─────────────┼─────────────┐
             ↓             ↓             ↓
           Tools          RAG           MCP
             ↓             ↓             ↓
            APIs       Vector DB    External Systems
             ↓             ↓             ↓
             └─────────────┼─────────────┘
                           ↓
                       Observation
                           ↓
                          LLM
                           ↓
                    Next Action?
                      ↙       ↘
                    Yes        No
                     ↓          ↓
                   Tools      Answer

How Everything Fits Together

The relationship between these technologies can be summarized like this:

LLM
 │
 │ provides intelligence
 ↓
AI Application
 │
 ├── Chatbot Interface
 │
 ├── Assistant Capabilities
 │
 ├── RAG
 │
 ├── Function Calling
 │
 └── MCP
        │
        ↓
      Tools
        │
        ↓
 APIs / Databases / Files / Services

An AI agent is an application architecture that can use these capabilities to accomplish goals.


Which One Should You Build?

The answer depends on the problem.

Use an LLM when:

  • You need text generation.
  • You need summarization.
  • You need classification or extraction.
  • You need natural-language understanding.

Use a Chatbot when:

  • You need a conversational interface.
  • Users primarily ask questions.
  • The application does not need complex autonomous actions.

Use an AI Assistant when:

  • You want AI to help users perform tasks.
  • You need context and useful tools.
  • The user remains actively involved.

Use an AI Agent when:

  • The task involves multiple steps.
  • The next action depends on previous results.
  • The system needs to select between tools.
  • The user provides a goal rather than a detailed procedure.

Comparison Using a Real Example

Suppose the user says:

"Analyze our sales data and tell me
why this month's revenue decreased."

LLM:

Can analyze sales data if the data is provided in its context.

Chatbot:

Can provide a conversational interface for asking questions about the data.

AI Assistant:

Can help retrieve and analyze the relevant data.

AI Agent:

Get Sales Data
      ↓
Calculate Revenue
      ↓
Compare Previous Month
      ↓
Analyze Product Categories
      ↓
Identify Changes
      ↓
Generate Explanation

The agent can coordinate the entire process.


Important: AI Agent Does Not Mean Human-Level Intelligence

The word agent can sometimes make AI systems sound more capable than they actually are.

An AI agent is still software operating within the capabilities and constraints defined by its architecture.

It may:

  • Choose an incorrect tool.
  • Misinterpret information.
  • Generate an incorrect plan.
  • Produce an incorrect answer.
  • Fail to complete a task.

Therefore, production agents need appropriate validation, permissions, monitoring, logging, and error handling.


Key Takeaways

  • LLM means Large Language Model.
  • An LLM is the model that understands and generates content.
  • A chatbot is an application that provides a conversational interface.
  • An AI assistant helps users accomplish tasks using AI and potentially external capabilities.
  • An AI agent is a goal-oriented system that can decide actions and use tools to accomplish tasks.
  • Function calling allows AI models to request tool execution.
  • RAG provides access to external knowledge.
  • MCP provides a standardized protocol for compatible AI applications to interact with external capabilities.
  • AI agents can combine LLMs, tools, RAG, memory, APIs, and MCP.
  • Not every AI application needs an agent.
  • Deterministic workflows are often better for predictable business processes.

Conclusion

The easiest way to remember the difference is:

LLM
↓
The model.

Chatbot
↓
The conversational application.

AI Assistant
↓
The application that helps the user.

AI Agent
↓
The goal-oriented system that can decide,
use tools, observe results, and continue working.

These concepts are not mutually exclusive. A modern AI application can contain an LLM inside an AI agent, provide a chatbot interface, use RAG for knowledge, use function calling for tools, and use MCP to connect to external capabilities.

Understanding this architecture is an important foundation for building production-ready AI applications.

Next: How AI Agents Use Tools: Function Calling Explained with C# — Learn how an LLM can select and invoke C# functions to interact with APIs, databases, and external systems.

Monday, September 7, 2026

What Is an AI Agent? A Beginner’s Guide to AI Agents

We have already explored LLMs, RAG, embeddings, vector databases, function calling, and MCP.

The next step is to understand one of the most important concepts in modern AI: AI Agents.

An AI chatbot usually responds to a question. An AI agent can go further: it can decide what actions are needed, use tools, observe the results, and continue working toward a goal.

In this beginner-friendly guide, we will understand what an AI agent is, how it works, the agent loop, tools, memory, planning, reasoning, observations, and how AI agents differ from traditional chatbots and LLM applications.


What Is an AI Agent?

An AI Agent is a software system that uses an AI model to pursue a goal by deciding what actions to take and interacting with external tools or systems.

A simplified definition is:

AI Agent =
LLM + Instructions + Tools + State/Memory + Action Loop

Unlike a simple chatbot, an agent can perform multiple steps to accomplish a task.


Simple Example

Imagine asking an AI assistant:

"Find the cheapest flight to Chennai,
check the weather there, and prepare a travel summary."

A simple chatbot may provide general information.

An AI agent could potentially:

Understand the goal
      ↓
Search flights
      ↓
Compare prices
      ↓
Check Chennai weather
      ↓
Collect results
      ↓
Prepare summary
      ↓
Return answer

The important part is that the system performs a sequence of actions instead of generating only one response.


Chatbot vs AI Agent

A traditional chatbot often follows this pattern:

User
 ↓
LLM
 ↓
Answer

An agent can follow a more complex loop:

User Goal
    ↓
   LLM
    ↓
Choose Action
    ↓
Use Tool
    ↓
Observe Result
    ↓
   LLM
    ↓
Choose Next Action
    ↓
Use Tool
    ↓
Observe Result
    ↓
Final Answer

This ability to repeatedly interact with tools is one of the defining characteristics of agentic systems.


The AI Agent Loop

The most important concept to understand is the agent loop.

              ┌───────────────┐
              │   User Goal   │
              └───────┬───────┘
                      ↓
              ┌───────────────┐
              │      LLM      │
              └───────┬───────┘
                      ↓
              ┌───────────────┐
              │ Decide Action │
              └───────┬───────┘
                      ↓
              ┌───────────────┐
              │     Tool      │
              └───────┬───────┘
                      ↓
              ┌───────────────┐
              │   Observation │
              └───────┬───────┘
                      ↓
                    LLM
                      ↓
                Next Action?
                 ↙       ↘
               Yes        No
                ↓          ↓
              Tool       Answer

The agent continues this cycle until it determines that the task is complete or it reaches a configured limit.


Why Do AI Agents Need Tools?

An LLM has limitations.

For example, a model may not automatically be able to:

  • Query your company's database
  • Read a private file
  • Check your inventory system
  • Call an internal API
  • Send an email
  • Execute a business operation

Tools provide the connection between the AI model and external systems.

                    AI Agent
                        ↓
                       LLM
                        ↓
              ┌─────────┼─────────┐
              ↓         ↓         ↓
           Search      API     Database
            Tool       Tool       Tool
              ↓         ↓         ↓
           Search     Service   Database

What Is an Agent Tool?

A tool is an operation that an AI agent can invoke to accomplish part of a task.

For example:

get_customer()
search_orders()
check_inventory()
search_documents()
send_email()
calculate_total()

A tool generally has:

  • A name
  • A description
  • Input parameters
  • An implementation
  • An output

Simple Tool Example in C#

Suppose we have a C# method:

public string GetCustomer(int customerId)
{
    return $"Customer {customerId} information";
}

An AI agent could have access to this operation as a tool.

The model might decide:

Tool:
GetCustomer

Arguments:
customerId = 10025

The application executes the C# method and sends the result back to the model.


What Is Planning?

An agent often needs to determine what steps should be performed to accomplish a goal.

For example:

Goal:
"Prepare a report about today's sales."

Possible plan:

1. Get today's sales.
2. Calculate total revenue.
3. Find the top-selling products.
4. Compare with yesterday.
5. Generate a summary.

The agent can then execute these operations using available tools.


Planning Does Not Always Mean a Fixed Plan

Agents can also plan dynamically.

For example:

Goal
 ↓
Search sales
 ↓
Result indicates missing data
 ↓
Search another source
 ↓
Analyze data
 ↓
Generate report

The next action can depend on the result of the previous action.

This makes agents different from simple predefined workflows.


What Is Observation?

After an agent executes a tool, it receives an observation or result.

For example:

Agent Action:

check_inventory("PRODUCT-100")

        ↓

Tool Result:

{
    "product": "PRODUCT-100",
    "stock": 5
}

The agent then uses that information to decide what to do next.

Action
  ↓
Tool
  ↓
Observation
  ↓
LLM
  ↓
Next Action

What Is Agent Memory?

Memory allows an agent to maintain useful information across interactions or during a task.

There are several ways to think about memory.

Short-Term Memory

Short-term memory contains information from the current conversation or task.

User:
My order number is 12345.

Later:

What is the status of my order?

The agent can use the conversation context to understand that the order number is 12345.

Long-Term Memory

Long-term memory can store information that should remain available beyond a single interaction.

For example:

User preferences
Previous interactions
Saved information
Business knowledge

Long-term memory can be implemented using databases, vector stores, or other persistent storage mechanisms depending on the use case.


RAG as Agent Memory or Knowledge

RAG can provide an agent with access to external knowledge.

AI Agent
    ↓
Search Knowledge Tool
    ↓
RAG
    ↓
Vector Database
    ↓
Relevant Documents
    ↓
Agent

This allows the agent to retrieve information when it needs it instead of keeping the entire knowledge base inside the prompt.


AI Agent vs LLM

LLM AI Agent
Generates text or structured output Uses an LLM to pursue a goal
Usually responds to a prompt Can perform multiple actions
Does not inherently execute external operations Can use tools
Usually stateless unless context is provided Can maintain state or memory
One model interaction can be enough May require multiple model/tool interactions

AI Agent vs Chatbot

Chatbot AI Agent
Primarily conversational Goal-oriented
Usually answers questions Can perform actions
May use an LLM only Can use multiple tools
Usually follows request → response Can execute multiple steps
Limited external interaction Can interact with external systems

AI Agent vs Traditional Automation

Traditional automation usually follows a predefined sequence.

Step 1
  ↓
Step 2
  ↓
Step 3
  ↓
Step 4

An AI agent can dynamically choose the next action.

Goal
 ↓
LLM
 ↓
Choose Action
 ↓
Result
 ↓
LLM
 ↓
Choose Next Action
 ↓
Result
 ↓
Done

However, not every problem needs an AI agent.

If the workflow is completely deterministic, traditional automation may be simpler, cheaper, faster, and easier to test.


When Should You Use an AI Agent?

AI agents are particularly useful when:

  • The task requires multiple steps.
  • The next step depends on the previous result.
  • The system needs to choose between multiple tools.
  • The task requires interaction with external systems.
  • The exact workflow cannot be completely predefined.
  • The user provides a high-level goal rather than detailed instructions.

When Should You NOT Use an AI Agent?

Agents are not always the best solution.

For a simple operation such as:

GetCustomerById(10025)

you probably do not need an AI agent.

A normal API call is faster and more predictable.

Similarly, a deterministic workflow such as:

Receive Order
    ↓
Validate Payment
    ↓
Update Database
    ↓
Send Confirmation

may be better implemented using normal application logic or workflow automation.


Agent Example: Customer Support

Imagine a customer says:

"My order hasn't arrived. Please check what happened."

An AI agent could perform:

Understand Customer Request
          ↓
Identify Customer
          ↓
Find Order
          ↓
Check Order Status
          ↓
Check Shipment
          ↓
Analyze Result
          ↓
Generate Response

The agent might need multiple tools:

get_customer()
get_orders()
get_order_status()
get_shipment()

The exact sequence can depend on the information returned from each tool.


Agent Example: Software Developer Assistant

A developer might ask:

"Find why the payment service is failing
and suggest a fix."

An AI coding agent could potentially:

Search Source Code
      ↓
Search Logs
      ↓
Inspect Configuration
      ↓
Find Related Code
      ↓
Analyze Error
      ↓
Suggest Fix

Depending on its permissions and tools, an agent might also run tests or inspect a repository.

Every additional capability should be protected with appropriate permissions.


Agent Example: Data Analysis

User:

"Analyze this month's sales and
tell me why revenue decreased."

The agent could:

Get Sales Data
      ↓
Calculate Revenue
      ↓
Compare Previous Month
      ↓
Analyze Product Categories
      ↓
Identify Changes
      ↓
Generate Explanation

This is a goal-oriented workflow rather than a simple question-answer interaction.


What Is Tool Selection?

An agent may have multiple tools available.

Tools:

search_customer
get_order
check_inventory
search_documents
send_email
calculate

If the user asks:

"Do we have Product 123 in stock?"

The agent should select:

check_inventory("Product 123")

Tool selection is typically guided by the model's understanding of the task and the available tool descriptions.


Agent State

An agent may need to maintain state while performing a task.

For example:

Task State

CustomerId = 10025
OrderId = 12345
OrderStatus = "Delayed"
ShipmentId = "SHIP-456"

State can be maintained in application memory, a database, a workflow engine, or another appropriate storage mechanism.


Agent Loop Example

Consider this request:

"Check Product 123 and order it if
there are fewer than 5 items in stock."

The agent could reason through the task as:

Goal
 ↓
Check Inventory
 ↓
Result: 3 items
 ↓
Condition is true
 ↓
Create Order
 ↓
Order Result
 ↓
Final Answer

The important part is that the second action depends on the first tool result.


Agent Guardrails

AI agents can make decisions and execute actions, so guardrails are important.

Examples include:

  • Tool allowlists
  • Input validation
  • Authorization
  • Rate limits
  • Maximum number of steps
  • Timeouts
  • Human approval
  • Audit logging

For example, a read operation might execute automatically:

get_customer()
get_order()
search_documents()

But a high-impact operation might require approval:

delete_customer()
refund_payment()
send_large_payment()

The exact approval policy should depend on the application's risk level.


Human-in-the-Loop

Some agent workflows should involve a human before performing important actions.

AI Agent
   ↓
Prepare Action
   ↓
Human Approval
   ↓
Execute Tool
   ↓
Result

For example:

AI:
"I found an invoice for ₹50,000.
Do you want me to approve it?"

        ↓

Human:
"Yes"

        ↓

Agent:
Execute approval

This approach can significantly reduce the risk of unintended actions in sensitive workflows.


How MCP Fits Into AI Agents

MCP can provide a standardized way for compatible AI applications to interact with external capabilities.

An agent can use MCP servers to access tools and resources.

AI Agent
    ↓
MCP Client
    ↓
MCP Server
    ↓
 ┌─────────────┬─────────────┐
 ↓             ↓             ↓
Tools       Resources      Prompts
 ↓             ↓             ↓
APIs        Documents     Templates

This makes MCP particularly relevant to agent-based architectures.


How RAG Fits Into AI Agents

RAG can provide an agent with access to external knowledge.

AI Agent
    ↓
Search Tool
    ↓
RAG Pipeline
    ↓
Vector Search
    ↓
Relevant Context
    ↓
LLM

For example, a support agent could search company documentation before answering a customer question.


AI Agent Architecture

A more complete agent architecture might look like this:

                    User Goal
                        ↓
                 ┌─────────────┐
                 │ AI Agent    │
                 └──────┬──────┘
                        ↓
                      LLM
                        ↓
                Planning / Decision
                        ↓
               ┌────────┼────────┐
               ↓        ↓        ↓
             Tool     RAG      MCP
               ↓        ↓        ↓
              API    Vector   External
                     Search    Systems
               └────────┼────────┘
                        ↓
                    Observation
                        ↓
                       LLM
                        ↓
                 More Actions?
                   ↙       ↘
                 Yes        No
                  ↓          ↓
                Tools      Answer

Single-Agent vs Multi-Agent Systems

A single-agent system uses one agent to perform the task.

User
 ↓
Agent
 ↓
Tools
 ↓
Answer

A multi-agent system uses multiple specialized agents.

                 Main Agent
                     ↓
          ┌──────────┼──────────┐
          ↓          ↓          ↓
      Research     Coding     Testing
       Agent       Agent       Agent
          ↓          ↓          ↓
       Sources     Code       Tests

Multi-agent architectures can be useful for complex workflows, but they also introduce additional complexity and should not be used when a simpler architecture is sufficient.


AI Agent vs Workflow

Workflow AI Agent
Steps are usually predefined Steps can be selected dynamically
Highly deterministic More adaptive
Easy to predict May produce different execution paths
Usually easier to test Requires additional evaluation and controls
Good for stable business processes Good for open-ended or dynamic tasks

In practice, many systems combine both approaches.

Deterministic Workflow
        ↓
      AI Agent
        ↓
Dynamic Decision
        ↓
Deterministic Tool
        ↓
Business System

Common AI Agent Terminology

Term Meaning
AI Agent Goal-oriented system that uses AI to decide and perform actions
Agent Loop Repeated cycle of deciding, acting, observing, and deciding again
Tool Operation an agent can invoke
Observation Result returned after an action
Planning Determining steps needed to accomplish a goal
Memory Information retained during or across tasks
State Current information maintained by the agent
Guardrail Control that limits or validates agent behavior
Human-in-the-Loop Human approval or intervention during an agent workflow

Key Takeaways

  • An AI Agent is a goal-oriented AI system that can decide and perform actions.
  • An LLM is the reasoning and generation component, but an agent typically includes additional components.
  • Tools allow agents to interact with external systems.
  • The agent loop commonly consists of decision, action, observation, and another decision.
  • Agents can use APIs, databases, RAG systems, MCP servers, and other tools.
  • Memory and state allow agents to maintain useful information.
  • Agents are useful for multi-step and dynamic tasks.
  • Traditional workflows are often better for deterministic processes.
  • High-impact actions should use appropriate authorization, validation, and possibly human approval.
  • RAG and MCP can be combined with AI agents.

Conclusion

An AI agent is more than an LLM that answers questions.

The key difference is the ability to work toward a goal by selecting actions, using tools, observing results, and continuing until the task is completed.

The basic agent loop can be remembered as:

Goal
 ↓
LLM
 ↓
Choose Action
 ↓
Tool
 ↓
Observation
 ↓
LLM
 ↓
Choose Next Action
 ↓
Repeat
 ↓
Final Answer

Once you understand this loop, concepts such as tool calling, MCP, RAG, memory, planning, and multi-agent systems become much easier to understand.

For developers, this is where AI moves from a simple question-and-answer system toward an application that can actually perform tasks.

Next: AI Agent vs Chatbot vs LLM: What's the Difference? — A practical comparison of LLMs, chatbots, AI assistants, and autonomous agents with real-world examples.