Autonomous Agents
An autonomous agent receives a goal, decides which approved actions may help, observes their results, and continues until it can respond or must stop. This guide explains bounded agent loops in .NET, compares NuGet options, and includes a working read-only agent playground.
Key capabilities
- Goal-oriented task execution
- Tool calls through application code
- Observe, decide, and stop
- Budgets and approval boundaries
The model proposes; the host controls execution
- Goal: accept a task and the user's relevant constraints.
- Decide: the model returns either a user-facing answer or a structured request for an exposed function.
- Validate: .NET checks the tool name, arguments, permissions, and request budget.
- Execute: the application runs the approved function and bounds its time and result size.
- Observe: the result is returned to the model, which may call another allowed tool or finish.
- Stop: enforce iteration, call, token, timeout, and human-approval limits.
Use the least autonomy that solves the task
| Pattern | Control flow | Example fit | Typical boundary |
|---|---|---|---|
| Single model call | The application sends a prompt and returns one response. | Rewrite, classify, or summarize supplied text. | No tools and no model-directed loop. |
| Tool-using assistant | The model may request an approved function during a response. | Look up a status or retrieve a small set of public facts. | Small fixed tool set; the host validates and executes every call. |
| Bounded autonomous agent | The model can use tool results to make another decision before finishing. | A short research or planning task with a clear success condition. | Strict maximum iterations, tool calls, output, timeout, and data access. |
| Durable agent workflow | A workflow can pause, request human input, checkpoint, and resume. | A long-running process with approvals or external events. | Versioned state, idempotent steps, observability, and recovery procedures. |
Prefer a deterministic workflow when the steps are already known. Use an agent loop when the next useful step depends on the result of the previous one.
Packages and integration choices
| Package / API | What it provides | Choose it for |
|---|---|---|
Microsoft.Extensions.AI |
IChatClient, tool abstractions, AIFunctionFactory, and function-invocation middleware. |
A provider-independent tool loop with explicit .NET functions and limits. |
Microsoft.Extensions.AI.OpenAI + OpenAI |
OpenAI .NET client and adapter to the common chat interface. | OpenAI models or compatible endpoints; confirm each model supports the requested tools and options. |
Microsoft.Agents.AI |
Microsoft Agent Framework agent abstractions, tools, sessions, and integrations. | Applications that need managed agent instances, middleware, or conversation state. |
Microsoft.Agents.AI.Workflows |
Workflow graph and execution primitives around agents and other steps. | Long-running, event-driven, resumable, or human-in-the-loop processes. |
Microsoft.SemanticKernel |
Kernel services, plugins, prompts, and higher-level orchestration abstractions. | Existing Semantic Kernel applications or systems built around its plugin model. |
IHttpClientFactory |
Built-in .NET named and typed HTTP clients for calling external services. | Implementing an application-owned tool with a fixed, reviewed host and timeout. |
This application already references Microsoft.Extensions.AI 10.11.0, Microsoft.Extensions.AI.OpenAI 10.11.0, and OpenAI 2.14.0. Agent Framework, its workflow package, and Semantic Kernel are optional integrations and are not dependencies of the live playground. Check each framework's current NuGet release, provider matrix, and preview status before adopting its APIs.
Expose functions, then cap the model-directed loop
UseFunctionInvocation() can execute tool calls returned by the model, add the results to
the conversation, and request the next model response. The functions still run in your application;
the model never receives direct filesystem, database, or network access.
dotnet add package Microsoft.Extensions.AI
dotnet add package Microsoft.Extensions.AI.OpenAI
dotnet add package OpenAI
using System;
using System.ComponentModel;
using System.Threading;
using Microsoft.Extensions.AI;
using OpenAI;
var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY")
?? throw new InvalidOperationException("Set OPENAI_API_KEY.");
IChatClient modelClient = new OpenAIClient(apiKey)
.GetChatClient("gpt-6.1-sol")
.AsIChatClient();
using var agent = modelClient.AsBuilder()
.UseFunctionInvocation(configure: options =>
{
options.MaximumIterationsPerRequest = 5;
options.MaximumConsecutiveErrorsPerRequest = 2;
})
.Build();
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(60));
var chatOptions = new ChatOptions
{
MaxOutputTokens = 1200,
Tools = [AIFunctionFactory.Create(AgentTools.GetCurrentUtcTime)]
};
var response = await agent.GetResponseAsync(
"Check the current UTC time and explain it briefly.",
chatOptions,
timeout.Token);
Console.WriteLine(response.Text
?? throw new InvalidOperationException("The agent returned no text."));
static class AgentTools
{
[Description("Returns the current UTC time.")]
public static string GetCurrentUtcTime() => DateTimeOffset.UtcNow.ToString("O");
}
The function-invocation middleware caps the model loop, but it does not replace business authorization, per-tool call limits, result-size bounds, or an overall timeout. Add those in the function and hosting layer as well.
Make every action reviewable
Use a narrow allowlist
Expose named functions with typed arguments. Do not provide arbitrary shell, SQL, file, or URL tools. Pin external tools to fixed HTTPS hosts and validate their inputs.
Treat tool output as untrusted
Retrieved pages and API fields can contain misleading content. Keep them separate from system instructions, sanitize before rendering, and validate claims before consequential use.
Require approval for side effects
Use a human confirmation step for actions that contact people, change records, commit money, or affect access. Re-check the user's authorization inside the tool.
Measure the whole run
Track tool name, duration, result status, model-call count, and token usage. Test invalid inputs, timeouts, repeated calls, prompt injection, and the agent's stop condition.
See Tools & Plugins for external API functions, Multi-Agent Systems for specialist collaboration, and the .NET LLM guide for broader provider and framework comparisons.
Try a bounded .NET autonomous agent
Give a configured provider a goal; its bounded agent loop can choose read-only .NET tools, inspect their results, and decide when to return an answer.
Keys remain in this browser's saved AI Agent settings. When you send a message, the selected provider's key is transferred over this Interactive Server circuit to the server, where its .NET SDK makes the HTTPS request. The key is not written to server storage or returned with the answer. Use this demo only with a server you trust; production applications should authenticate users and use a server-side secret manager.
The agent can use up to five model iterations and eight tool calls within 120 seconds. Wikipedia receives a search query; Open-Meteo receives a city name. These tools are read-only and use fixed public hosts; provider credentials are never sent to them. Do not include private information in public API queries.