AI-powered applications are becoming more than simple chat interfaces. Modern applications allow language models to call functions, retrieve database records, search documents, check order statuses, and interact with external services.
These capabilities are commonly called AI tool calling or function calling.
For example, an ASP.NET Core application may provide an AI assistant with tools to retrieve customer information, check product availability, or create support tickets. The model decides which tool to call, provides the required arguments, and uses the returned result to generate an answer.
However, tool execution introduces another source of failure. A tool may receive invalid arguments, a database query may time out, an external API may become unavailable, or a business operation may fail.
If these failures are not handled correctly, a single tool execution problem can terminate the complete AI conversation or produce an HTTP 500 response.
In this article, we will explore how to handle AI tool call failures in ASP.NET Core using Microsoft.Extensions.AI. We will cover argument validation, exception handling, timeouts, cancellation, retries, safe error messages, and production practices that help keep AI-powered APIs reliable.
Understanding AI Tool Calling
AI tool calling allows a language model to request the execution of application functions.
The model does not directly execute database queries or access external services. Instead, it generates a structured function call that the application validates and executes.
Consider an AI assistant that can retrieve customer order information.
The application provides a tool named GetOrderStatus. When a user asks about an order, the model may generate a function call with an order identifier.
The request flow looks like this:
User Question
|
v
ASP.NET Core API
|
v
AI Model
|
v
Tool Call Request
|
v
Application Tool
|
v
Database or External API
|
v
Tool Result
|
v
AI Model
|
v
Final Response
The application executes the tool and returns its result to the model. The model then uses that result to prepare a response.
Several things can go wrong during this process.
Failure Scenario | Example |
|---|
Invalid arguments | Model provides an invalid order ID |
Missing arguments | Required customer ID is not provided |
Database failure | SQL connection times out |
External API failure | Payment provider returns HTTP 503 |
Business validation failure | Requested order does not exist |
Authorization failure | User is not allowed to access the order |
Tool execution timeout | External service takes too long |
Unknown tool | Model requests a function that is not registered |
A reliable application should handle these failures without unnecessarily terminating the entire request.
Why Tool Failures Should Not Break the Complete Request
Consider an application that provides three AI tools:
GetOrderStatus
GetCustomerDetails
GetProductInformation
A user asks:
"Check my order status and tell me the product details."
The model may request GetOrderStatus first. However, the order service is temporarily unavailable.
If the application allows the exception to propagate directly, the complete AI request may fail even though the product information tool could still work.
A better approach is to return a controlled tool failure to the AI model.
The model can then decide whether to retry with corrected arguments, use another available tool, or explain that the requested information is temporarily unavailable.
This approach separates tool execution failures from the overall AI conversation.
It does not mean every failure should be hidden. Authentication failures, security violations, and request cancellation still require appropriate handling.
Setting Up the ASP.NET Core Application
Let's build a small application using ASP.NET Core and Microsoft.Extensions.AI.
We will use Ollama as the local model provider for this example. The same error-handling concepts apply to compatible cloud AI providers.
Create a new project:
dotnet new web -n AIToolFailureApp
cd AIToolFailureApp
Install the required packages:
dotnet add package Microsoft.Extensions.AI
dotnet add package OllamaSharp
Make sure Ollama is installed and a supported model is available:
ollama pull llama3.2
The application will expose an endpoint that accepts a user question. The AI model will be able to call a tool to retrieve order information.
Creating an AI Tool
First, define a service that retrieves order information.
For demonstration purposes, we will use an in-memory implementation. In a production application, this service would normally communicate with a database or another business system.
public sealed class OrderService
{
public Task<string> GetOrderStatusAsync(
int orderId,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (orderId <= 0)
{
throw new ArgumentException(
"Order ID must be greater than zero."
);
}
if (orderId == 999)
{
throw new InvalidOperationException(
"Order service is temporarily unavailable."
);
}
if (orderId != 1001)
{
throw new KeyNotFoundException(
"Order was not found."
);
}
return Task.FromResult(
"Order 1001 is currently being shipped."
);
}
}
This service demonstrates three possible outcomes:
A valid order request returns order information.
An invalid order ID produces an argument error.
A simulated unavailable order service produces an exception.
The example uses different exceptions to demonstrate error handling. In a real application, use domain-specific result types or exceptions where appropriate.
Handling Tool Execution Failures With FunctionInvokingChatClient
Microsoft.Extensions.AI provides FunctionInvokingChatClient, which handles function invocation as part of the AI conversation.
It can invoke registered tools and return their results to the model.
It also provides a custom FunctionInvoker delegate. This allows developers to intercept tool execution, handle exceptions, and return controlled error messages.
This is particularly useful when tools depend on databases, external APIs, or business services.
Let's create the AI client configuration.
using Microsoft.Extensions.AI;
using OllamaSharp;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<OrderService>();
builder.Services.AddSingleton<IChatClient>(_ =>
{
IChatClient innerClient = new OllamaApiClient(
new Uri("http://localhost:11434"),
"llama3.2"
);
var functionClient = new FunctionInvokingChatClient(
innerClient
)
{
FunctionInvoker = async (
context,
cancellationToken) =>
{
try
{
return await context.Function.InvokeAsync(
context.Arguments,
cancellationToken
);
}
catch (OperationCanceledException)
when (cancellationToken.IsCancellationRequested)
{
throw;
}
catch (ArgumentException)
{
return "Error: The supplied tool arguments are invalid.";
}
catch (KeyNotFoundException)
{
return "Error: The requested order was not found.";
}
catch (TimeoutException)
{
return "Error: The order service timed out. Try again later.";
}
catch (Exception)
{
return "Error: The order service is temporarily unavailable.";
}
}
};
return functionClient;
});
var app = builder.Build();
app.Run();
Let's understand the important parts.
Creating the Inner AI Client
IChatClient innerClient = new OllamaApiClient(
new Uri("http://localhost:11434"),
"llama3.2"
);
This creates the underlying AI client.
The application uses Ollama for model inference, but the function invocation layer is provided by Microsoft.Extensions.AI.
This separation allows the application to use the same tool execution strategy with other compatible AI providers.
Wrapping the Client With FunctionInvokingChatClient
var functionClient = new FunctionInvokingChatClient(
innerClient
);
FunctionInvokingChatClient manages the tool invocation process.
When the model requests a registered function, the client invokes the corresponding application function and adds its result to the conversation.
It also supports custom invocation behavior through the FunctionInvoker property.
Implementing Custom Error Handling
FunctionInvoker = async (
context,
cancellationToken) =>
{
try
{
return await context.Function.InvokeAsync(
context.Arguments,
cancellationToken
);
}
catch (Exception)
{
return "Error: The order service is temporarily unavailable.";
}
}
The FunctionInvoker delegate receives a FunctionInvocationContext containing the function, arguments, and other invocation information.
Instead of allowing every exception to terminate tool processing, the delegate catches expected failures and returns a controlled result.
The AI model can receive this result and decide how to continue.
One important security consideration is that detailed exception messages should not automatically be returned to the model. An exception may contain database details, internal service addresses, or sensitive information.
Returning a safe error message keeps internal implementation details out of the conversation.
The example also rethrows cancellation when the supplied cancellation token has been cancelled. Cancellation should not be converted into an ordinary tool error.
Registering Tools and Creating an API Endpoint
Now we need to expose the order service as an AI tool.
Microsoft.Extensions.AI provides AIFunctionFactory for creating function definitions from C# methods.
Add the following endpoint to Program.cs:
using Microsoft.Extensions.AI;
app.MapPost(
"/api/assistant",
async (
ChatRequest request,
OrderService orderService,
IChatClient chatClient,
CancellationToken cancellationToken) =>
{
if (string.IsNullOrWhiteSpace(request.Message))
{
return Results.BadRequest(
new { error = "Message is required." }
);
}
var orderTool = AIFunctionFactory.Create(
async (int orderId) =>
await orderService.GetOrderStatusAsync(
orderId,
cancellationToken
),
"GetOrderStatus",
"Gets the current status of an order using its ID."
);
var options = new ChatOptions
{
Tools = [orderTool]
};
var messages = new List<ChatMessage>
{
new(
ChatRole.System,
"You are a helpful order support assistant. " +
"Use the available tool when order status is requested. " +
"Never invent order information."
),
new(
ChatRole.User,
request.Message
)
};
try
{
ChatResponse response =
await chatClient.GetResponseAsync(
messages,
options,
cancellationToken
);
return Results.Ok(new
{
response = response.Text
});
}
catch (OperationCanceledException)
when (cancellationToken.IsCancellationRequested)
{
throw;
}
catch (Exception)
{
return Results.Problem(
title: "AI request failed",
detail: "The assistant could not process your request.",
statusCode: StatusCodes.Status503ServiceUnavailable
);
}
}
);
public sealed record ChatRequest(string Message);
The endpoint creates the GetOrderStatus tool and passes it through ChatOptions.
When the model determines that order information is required, it can request the function with the appropriate argument.
The FunctionInvokingChatClient handles the invocation and returns the tool result to the model.
The endpoint then returns the final response.
The important distinction is that a handled tool failure does not necessarily become an HTTP failure. The model can receive the safe error result and explain the situation to the user.
For example, if the order service is unavailable, the assistant may respond that it cannot retrieve the order status right now.
If the model itself fails, the endpoint handles that separately and returns an appropriate HTTP error.
Handling Invalid Tool Arguments
AI models do not always generate valid function arguments.
For example, the tool expects an integer:
public Task<string> GetOrderStatusAsync(int orderId)
However, the model may provide an invalid value, omit a required property, or generate malformed JSON.
Possible problems include:
Missing orderId.
A string supplied instead of an integer.
An invalid numeric value.
Malformed function arguments.
Microsoft.Extensions.AI provides mechanisms for handling invalid function input.
A custom FunctionInvoker can catch argument and serialization errors and return a controlled message.
For example:
catch (System.Text.Json.JsonException)
{
return "Error: Tool arguments could not be parsed. " +
"Check the required parameter types.";
}
catch (ArgumentException)
{
return "Error: The supplied order information is invalid.";
}
This gives the model an opportunity to correct its function arguments.
However, argument validation should not depend on the model. Every tool must validate its inputs independently before performing a business operation.
For example, a valid integer does not necessarily represent an order the current user is authorized to access.
Handling Tool Timeouts
A tool may depend on a remote service that takes too long to respond.
For example, an order service may call a third-party logistics API. If that API becomes slow, the AI request may remain open while waiting for the result.
Use cancellation tokens and explicit time limits to control how long a tool can execute.
The following example uses a linked CancellationTokenSource:
public async Task<string> GetOrderFromExternalServiceAsync(
int orderId,
CancellationToken cancellationToken)
{
using var timeout = CancellationTokenSource
.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(TimeSpan.FromSeconds(10));
try
{
return await CallExternalOrderApiAsync(
orderId,
timeout.Token
);
}
catch (OperationCanceledException)
when (!cancellationToken.IsCancellationRequested)
{
throw new TimeoutException(
"The order service exceeded its time limit."
);
}
}
This example distinguishes between two situations.
The first is when the external operation exceeds its configured time limit. This is converted into a TimeoutException.
The second is when the original request is cancelled by the caller. That cancellation is not converted into a timeout error.
This distinction is important because a user disconnecting from the application is not the same as an external service becoming slow.
Should You Retry Failed Tool Calls?
Retries can improve reliability when failures are temporary.
For example, an external API may return HTTP 503 because of a short service interruption.
However, retrying every tool failure is dangerous.
Consider a tool that creates a payment transaction. If the request reaches the payment provider but the response is lost, retrying the operation may create a duplicate transaction.
Before adding retries, classify tool operations.
Tool Operation | Retry Consideration |
|---|
Read order status | Usually safe with appropriate limits |
Search product catalog | Usually safe |
Retrieve customer details | Safe if authorization is checked again |
Create support ticket | Requires idempotency protection |
Process payment | Requires strong idempotency controls |
Delete customer record | Requires careful business-level retry handling |
For read-only operations, a limited retry with exponential backoff may be appropriate.
For operations that change data, use idempotency keys or another mechanism to prevent duplicate execution.
Also, avoid combining multiple retry layers without considering their effect. If the HTTP client retries three times and the AI model independently repeats a failed tool call, the total number of operations may become much larger than expected.
Microsoft.Extensions.Http.Resilience provides retry, timeout, rate-limiting, and circuit-breaker strategies for HTTP dependencies. These strategies should be configured according to the behavior of the specific tool operation.
Limiting Consecutive Tool Failures
A model may repeatedly call a function with incorrect arguments or continue trying an unavailable service.
Without limits, this can increase request duration and consume unnecessary resources.
FunctionInvokingChatClient provides the MaximumConsecutiveErrorsPerRequest property.
For example:
var functionClient = new FunctionInvokingChatClient(
innerClient
)
{
MaximumConsecutiveErrorsPerRequest = 2
};
This limits consecutive iterations that fail with function invocation exceptions before the failure is propagated to the caller.
The default value is three.
This setting is useful when the model repeatedly attempts unsuccessful tool calls. It should be combined with application-level request timeouts and limits on the number of tool executions.
It is also important to distinguish between an exception thrown during tool execution and a tool that returns a controlled error result. Returning a safe error string gives the model a result to reason about, but it is not the same as an invocation exception for this consecutive-error counter.
Protecting Sensitive Information in Error Messages
Tool failures can contain sensitive information.
For example, a database exception might include:
Connection failed for server database-internal-01.
Login failed for user application_service.
Returning this message directly to the model can expose infrastructure details that should remain internal.
A better approach is to separate internal diagnostics from model-facing results.
Internal Error | Safe Tool Result |
|---|
SQL connection failure | Order service is temporarily unavailable |
Database timeout | Order lookup timed out |
Customer authorization failure | Requested customer information is unavailable |
Invalid JSON | Tool arguments could not be processed |
External API failure | External service could not complete the request |
Log the actual exception on the server, but return a controlled message to the AI model.
Do not include passwords, connection strings, access tokens, personal information, or internal server details in tool error messages.
Best Practices for Production Applications
Validate Every Tool Independently
Never assume that the model will always provide valid arguments.
Validate required values, data types, ranges, and business rules inside the tool implementation.
Separate Business Failures From Technical Failures
An order that does not exist is different from a database being unavailable.
Use clear error categories so the application can handle expected business outcomes without treating every situation as an infrastructure failure.
Apply Timeouts to External Dependencies
Every tool that calls an external service should have an appropriate timeout.
A slow dependency should not keep the entire AI request open indefinitely.
Use Idempotency for Important Operations
For operations such as payments, ticket creation, and record updates, use idempotency mechanisms to prevent duplicate actions.
Do not automatically retry non-idempotent operations.
Keep Error Messages Safe
Return useful information to the model without exposing internal exceptions.
Use structured server-side logging for detailed diagnostics.
Monitor Tool Execution
Track tool names, execution duration, success rates, failure categories, timeout counts, and retry counts.
Avoid logging sensitive arguments or complete customer records.
Apply Authorization Before Execution
A tool should never trust the model to decide whether a user has permission to access a resource.
Check the authenticated user's identity and authorization inside the application before returning data or performing an operation.
Common Mistakes and Troubleshooting
Problem | Possible Cause | Recommended Solution |
|---|
Complete AI request fails after one tool error | Exception is not handled | Use a custom FunctionInvoker |
Model repeatedly calls a failed tool | No invocation limits | Configure consecutive error limits |
Invalid tool arguments cause failures | Input is not validated | Validate arguments inside the tool |
API request remains open too long | External dependency has no timeout | Apply a linked cancellation token |
Duplicate business operations | Unsafe retries | Use idempotency protection |
Internal database information appears in responses | Detailed exceptions are exposed | Return safe error messages |
Tool succeeds for unauthorized users | Authorization is delegated to the model | Validate permissions inside the tool |
AI returns incorrect information after a failure | Error result is unclear | Provide a structured, understandable failure result |
Advantages and Disadvantages of Controlled Tool Error Handling
Advantages
Prevents many tool execution errors from terminating the complete AI conversation.
Allows the model to respond appropriately when a tool is unavailable.
Improves the reliability of AI-powered ASP.NET Core APIs.
Provides better control over invalid function arguments.
Supports timeout and cancellation handling.
Reduces the risk of exposing internal exception details.
Makes tool execution easier to monitor and maintain.
Disadvantages
Requires additional error-handling logic.
Incorrect error messages may cause the model to make unnecessary attempts.
Retry strategies can increase load on already unhealthy services.
Tool-level recovery does not guarantee that the AI model will produce a useful final response.
Security and authorization checks must still be implemented independently.
Summary
AI tool calling allows language models to interact with application services, databases, and external APIs. However, every tool introduces potential failure points that can affect the complete AI request.
Microsoft.Extensions.AI provides FunctionInvokingChatClient and its custom FunctionInvoker delegate to help developers control function execution and handle failures.
In this article, we explored how to handle invalid arguments, database and external service failures, timeouts, cancellation, and repeated tool errors in an ASP.NET Core application.
The most important principle is to treat tool execution as an independent operation with its own validation, security, timeout, and recovery strategy. A failed tool should not automatically mean that the entire AI conversation must fail.
With controlled error handling, safe error messages, appropriate retry policies, and proper authorization, developers can build more reliable AI-powered applications using ASP.NET Core and Microsoft.Extensions.AI.
Join the conversation! Your thoughts help the community grow.