Skip to content

Conversation

Copy link
Contributor

Copilot AI commented Jan 5, 2026

AI models can provide malformed function call arguments (wrong types, missing fields, invalid JSON). This documents three mitigation strategies using Microsoft.Extensions.AI.

Changes

  • New article: docs/ai/how-to/handle-invalid-tool-input.md

    • IncludeDetailedErrors property - sends full exception details to enable model self-correction
    • Custom FunctionInvoker delegate - catch exceptions, return descriptive errors to guide retry attempts
    • OpenAI strict schema mode - enforce exact schema adherence via Strict additional property
    • Security guidance for production error disclosure
  • Code examples (4 compilable snippets demonstrating each strategy)

  • Navigation: Added to TOC under "Call functions", linked from function calling quickstart

Example: Custom Error Handling

var client = new FunctionInvokingChatClient(innerClient)
{
    FunctionInvoker = async (context, cancellationToken) =>
    {
        try
        {
            return await context.Function.InvokeAsync(context.Arguments, cancellationToken);
        }
        catch (JsonException ex)
        {
            // AI sees error details and can retry with corrected input
            return $"Error: Invalid JSON format - {ex.Message}. " +
                   "Please check the parameter types match the function signature and retry.";
        }
        catch (ArgumentException ex)
        {
            return $"Error: Invalid argument - {ex.Message}. Please correct and retry.";
        }
    }
};

Addresses dotnet/extensions#7110 discussion points.

Original prompt

This section details on the original issue you should resolve

<issue_title>Document strategies to handle invalid tool input</issue_title>
<issue_description>### Type of issue

Missing information

Description

A LLM can provide invalid input when request tool calls. In this discussion with Stephen, several strategies were mentioned to deal with that.

The documentation could be improved with:

  • FunctionInvokingChatClient.IncludeDetailedErrors to send serialization (and other) exceptions back to the LLM
  • FunctionInvokingChatClient.FunctionInvoker to, for example, catch serialization exceptions. It could also be interesting to document that it can be used to implement a retry mechanism, like throwing a MyRetryException from a tool (because of incoherent input or something), catching it in the FunctionInvoker and returning a message to make the LLM retry "invalid something, please retry". Sharing good prompts that make some models retry a tool call would be a plus.
  • strictJsonSchema special property for OpenAI

Page URL

https://learn.microsoft.com/en-us/dotnet/ai/quickstarts/use-function-calling

Content source URL

https://github.com/dotnet/docs/blob/main/docs/ai/quickstarts/use-function-calling.md

Document Version Independent Id

7228f348-6649-a87d-bae5-4a70817c03bb

Platform Id

5a517f05-b64b-c471-b99d-72253c213be1

Article author

@gewarren

Metadata

  • ID: 27e2bbca-36b0-3883-11f7-321c044ee29a
  • PlatformId: 5a517f05-b64b-c471-b99d-72253c213be1
  • Service: dotnet
  • Sub-service: intelligent-apps</issue_description>

Comments on the Issue (you are @copilot in this section)

@adegeo Hello. If there's a specific (or close to it) documentation you think needs updating, please navigate to the bottom of that documentation page and click the open issue button. Otherwise, we're not sure what article you think needs updating.

💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.


Internal previews

📄 File 🔗 Preview link
docs/ai/how-to/handle-invalid-tool-input.md Handle invalid tool input from AI models
docs/ai/quickstarts/use-function-calling.md Invoke .NET functions using an AI model
docs/ai/toc.yml docs/ai/toc

Copilot AI and others added 4 commits January 5, 2026 18:54
Co-authored-by: gewarren <24882762+gewarren@users.noreply.github.com>
Co-authored-by: gewarren <24882762+gewarren@users.noreply.github.com>
Co-authored-by: gewarren <24882762+gewarren@users.noreply.github.com>
Co-authored-by: gewarren <24882762+gewarren@users.noreply.github.com>
Copilot AI changed the title [WIP] Document strategies to handle invalid tool input Document strategies for handling invalid AI function call input Jan 5, 2026
Copilot AI requested a review from gewarren January 5, 2026 19:07
@gewarren gewarren marked this pull request as ready for review January 7, 2026 00:13
@gewarren gewarren requested a review from a team as a code owner January 7, 2026 00:13
Copilot AI review requested due to automatic review settings January 7, 2026 00:13
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds comprehensive documentation on handling invalid tool input from AI models when using Microsoft.Extensions.AI. It addresses common scenarios where AI models provide malformed function call arguments and presents three mitigation strategies.

  • Documents three strategies: IncludeDetailedErrors property, custom FunctionInvoker delegates, and OpenAI's strict schema mode
  • Includes security guidance for production environments about exposing error details
  • Provides four compilable code examples demonstrating each strategy

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
docs/ai/how-to/handle-invalid-tool-input.md New documentation article covering error handling strategies with security considerations
docs/ai/how-to/snippets/handle-invalid-tool-input/csharp/IncludeDetailedErrors.cs Code example demonstrating the IncludeDetailedErrors property for AI self-correction
docs/ai/how-to/snippets/handle-invalid-tool-input/csharp/FunctionInvoker.cs Code example showing custom error handling with FunctionInvoker delegate
docs/ai/how-to/snippets/handle-invalid-tool-input/csharp/StrictSchema.cs Code example demonstrating OpenAI strict JSON schema mode
docs/ai/how-to/snippets/handle-invalid-tool-input/csharp/HandleInvalidToolInput.csproj Project file with .NET 10 target and required package references
docs/ai/toc.yml Adds navigation entry under "Call functions" section
docs/ai/quickstarts/use-function-calling.md Links to new article from "Next steps" section


List<ChatMessage> chatHistory = [
new(ChatRole.System, "You are a helpful weather assistant."),
new(ChatRole.User, "What's the temperature in Paris?")
Copy link

Copilot AI Jan 7, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The indentation is inconsistent. The closing brace should be aligned with the opening of the ChatMessage list. All list items should maintain consistent indentation.

Suggested change
new(ChatRole.User, "What's the temperature in Paris?")
new(ChatRole.User, "What's the temperature in Paris?")

Copilot uses AI. Check for mistakes.
Comment on lines +45 to +59
Tools = [AIFunctionFactory.Create((string location, int temperature) =>
{
if (string.IsNullOrWhiteSpace(location))
{
throw new ArgumentException("Location cannot be empty", nameof(location));
}
return $"Recorded temperature of {temperature}°C for {location}";
},
"record_temperature",
"Records the temperature for a location")]
};

List<ChatMessage> chatHistory = [
new(ChatRole.System, "You are a weather data recorder."),
new(ChatRole.User, "Record the temperature as 25 degrees for London")
Copy link

Copilot AI Jan 7, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The indentation is inconsistent. Lines 46-54 should be properly indented to match the AIFunctionFactory.Create call structure, and line 59 should align with line 58.

Suggested change
Tools = [AIFunctionFactory.Create((string location, int temperature) =>
{
if (string.IsNullOrWhiteSpace(location))
{
throw new ArgumentException("Location cannot be empty", nameof(location));
}
return $"Recorded temperature of {temperature}°C for {location}";
},
"record_temperature",
"Records the temperature for a location")]
};
List<ChatMessage> chatHistory = [
new(ChatRole.System, "You are a weather data recorder."),
new(ChatRole.User, "Record the temperature as 25 degrees for London")
Tools = [
AIFunctionFactory.Create(
(string location, int temperature) =>
{
if (string.IsNullOrWhiteSpace(location))
{
throw new ArgumentException("Location cannot be empty", nameof(location));
}
return $"Recorded temperature of {temperature}°C for {location}";
},
"record_temperature",
"Records the temperature for a location")
]
};
List<ChatMessage> chatHistory = [
new(ChatRole.System, "You are a weather data recorder."),
new(ChatRole.User, "Record the temperature as 25 degrees for London")

Copilot uses AI. Check for mistakes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Document strategies to handle invalid tool input

2 participants