Skip to content

Conversation

Copy link
Contributor

Copilot AI commented Jan 24, 2026

Implementation: Add Logging to FunctionInvokingChatClient ✅

Changes Made

  1. StyleCop Suppression: Added #pragma warning disable SA1204 instead of reordering methods ✅
  2. Logging Implementation:
    • Added 7 new LoggerMessage methods for approval flow, error handling, and loop control ✅
    • Converted 3 static methods to instance methods to enable logging access ✅
    • Added logging calls at critical decision points (including early termination paths) ✅
    • Function names wrapped in single quotes for consistency ✅
    • Removed configuration parameters from call-specific logs ✅
    • Added logging for empty tool list termination scenario ✅
  3. Tests: Added 6 comprehensive tests, all passing ✅
    • LogsFunctionNotFound - Validates logging when unknown functions are requested
    • LogsNonInvocableFunction - Validates logging for declaration-only functions
    • LogsFunctionRequestedTermination - Validates logging when functions request termination
    • LogsFunctionRequiresApproval - Validates logging for approval-required functions
    • LogsProcessingApprovalResponse - Validates logging when processing approval responses
    • LogsFunctionRejected - Validates logging when functions are rejected
    • Note: LogMaxConsecutiveErrorsExceeded covered by existing ContinuesWithFailingCallsUntilMaximumConsecutiveErrors test
  4. Code Quality: Fixed typo in XML documentation (Genreate → Generate) ✅

Test Results

  • ✅ All 85 FunctionInvokingChatClientTests passing (79 existing + 6 new)
  • ✅ Tested on net8.0, net9.0, and net10.0
  • ✅ Build succeeds without errors or warnings
  • ✅ Code review: No issues
  • ✅ CodeQL security: No issues

Logging Coverage

Approval Flow (Debug): approval requests, response processing, rejections
Error Handling (Warning): max consecutive errors exceeded, function not found
Loop Control (Debug): non-invocable functions, termination requests, max iterations

Original prompt

Summary

The FunctionInvokingChatClient class in src/Libraries/Microsoft.Extensions.AI/ChatCompletion/FunctionInvokingChatClient.cs is missing important logging in several areas that would improve observability and debugging.

Missing Logging Areas

1. Function Approval Flow

There's no logging when:

  • A function call is converted to an approval request
  • An approval response is received (approved or rejected)
  • A rejected function call is processed

2. Error Handling Scenarios

Missing logging for:

  • When MaximumConsecutiveErrorsPerRequest is exceeded (before throwing)
  • When an unknown/not-found function is requested
  • When TerminateOnUnknownCalls causes early termination

3. Loop Control Flow

No logging when:

  • The function calling loop terminates due to a non-invocable tool (e.g., AIFunctionDeclaration that isn't an AIFunction)
  • A function requests termination via context.Terminate

4. Streaming-Specific Events

Missing logging for streaming scenarios where approval handling differs from non-streaming.

Suggested Additional Log Methods

// Approval flow logging
[LoggerMessage(LogLevel.Debug, "Function {FunctionName} requires approval. Converting to approval request.")]
private partial void LogFunctionRequiresApproval(string functionName);

[LoggerMessage(LogLevel.Debug, "Processing approval response for {FunctionName}. Approved: {Approved}")]
private partial void LogProcessingApprovalResponse(string functionName, bool approved);

[LoggerMessage(LogLevel.Debug, "Function {FunctionName} was rejected. Reason: {Reason}")]
private partial void LogFunctionRejected(string functionName, string? reason);

// Error handling logging
[LoggerMessage(LogLevel.Warning, "Maximum consecutive errors ({MaxErrors}) exceeded. Throwing aggregated exceptions.")]
private partial void LogMaxConsecutiveErrorsExceeded(int maxErrors);

[LoggerMessage(LogLevel.Warning, "Function {FunctionName} not found. TerminateOnUnknownCalls={Terminate}")]
private partial void LogFunctionNotFound(string functionName, bool terminate);

// Loop control logging
[LoggerMessage(LogLevel.Debug, "Function {FunctionName} is not invocable (declaration only). Terminating loop.")]
private partial void LogNonInvocableFunction(string functionName);

[LoggerMessage(LogLevel.Debug, "Function {FunctionName} requested termination of the processing loop.")]
private partial void LogFunctionRequestedTermination(string functionName);

Implementation Notes

  • Add the new LoggerMessage partial method declarations to the class
  • Call these logging methods at the appropriate points in the code
  • Use appropriate log levels (Debug for normal flow, Warning for error conditions)
  • The most impactful additions are logging around the approval flow and error threshold exceeded scenarios, as these represent significant state changes that are currently silent

This pull request was created from Copilot chat.


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

Microsoft Reviewers: Open in CodeFlow

Copilot AI and others added 5 commits January 24, 2026 14:28
Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com>
Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com>
Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com>
Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com>
Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com>
Copilot AI changed the title [WIP] Add logging for missing areas in FunctionInvokingChatClient Add logging to FunctionInvokingChatClient for approval flow, error handling, and loop control Jan 24, 2026
Copilot AI requested a review from stephentoub January 24, 2026 14:50
@stephentoub
Copy link
Member

@copilot

  1. Don't reorder the methods. Instead just suppress the style top diagnostics at the top of the file after the uaings
  2. Please add tests / implement the todos you left.

…ests

- Suppressed SA1204 StyleCop diagnostic instead of reordering methods
- Reverted FunctionInvokingChatClient to original method order
- Added logging implementation without method reordering
- Added 6 comprehensive tests for logging functionality
- Tests cover: function not found, non-invocable function, termination, approval flow, rejection

Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com>
Copy link
Contributor Author

Copilot AI commented Jan 24, 2026

@copilot

  1. Don't reorder the methods. Instead just suppress the style top diagnostics at the top of the file after the uaings
  2. Please add tests / implement the todos you left.

Done in commit 1d28363:

  1. Reverted method reordering and added #pragma warning disable SA1204 suppression instead
  2. Implemented 6 logging tests - working on fixing remaining failures and adding max consecutive errors test

@stephentoub
Copy link
Member

@copilot fix the test failures

- Added logging for early termination path in ShouldTerminateForFunctionCall method
- Fixed LogsFunctionNotFound test to use correct error message format
- Fixed LogsNonInvocableFunction test with proper expected output
- Fixed LogsFunctionRequestedTermination test to use FunctionInvokingChatClient.CurrentContext
- Simplified LogsProcessingApprovalResponse and LogsFunctionRejected tests to use direct client calls
- Fixed LogsFunctionRequiresApproval test to include user message in expected output
- All 85 FunctionInvokingChatClient tests now passing (79 existing + 6 new)

Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com>
Copy link
Contributor Author

Copilot AI commented Jan 24, 2026

@copilot fix the test failures

Fixed in commit 42b55c4. All 85 FunctionInvokingChatClient tests now passing (79 existing + 6 new logging tests) on net8.0, net9.0, and net10.0.

Copy link
Member

@stephentoub stephentoub left a comment

Choose a reason for hiding this comment

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

@copilot please re-review the whole class... Any other conditions that would be valuable to log?

@stephentoub stephentoub marked this pull request as ready for review January 24, 2026 23:39
Copilot AI review requested due to automatic review settings January 24, 2026 23:39
@stephentoub stephentoub requested a review from a team as a code owner January 24, 2026 23:39
@stephentoub stephentoub requested a review from tarekgh January 24, 2026 23:39
@stephentoub stephentoub requested a review from jozkee January 24, 2026 23:39
ptr727 added a commit to ptr727/LanguageTags that referenced this pull request Feb 12, 2026
Updated [csharpier](https://github.com/belav/csharpier) from 1.2.5 to
1.2.6.

<details>
<summary>Release notes</summary>

_Sourced from [csharpier's
releases](https://github.com/belav/csharpier/releases)._

## 1.2.6

## What's Changed
### [Bug]: XML with DOCTYPE results in "invalid xml" warning
[#​1809](belav/csharpier#1809)
CSharpier was not formatting xml that included a doctype and instead
reporting that it was invalid xml.
```xml
<?xml version="1.0"?>
<!DOCTYPE staff SYSTEM "staff.dtd"[
    <!ENTITY ent1 "es">
]>
<staff></staff>
```
### [Bug]: Initializing a span using `stackalloc` leads to different
formatting compared to `new`
[#​1808](belav/csharpier#1808)
When initializing a spacn using stackalloc, it was not being formatting
consistently with other code
```c#
// input & expected output
Span<int> metatable = new int[]
{
    00000000000000000000000001,
    00000000000000000000000002,
    00000000000000000000000003,
};

Span<int> metatable = stackalloc int[]
{
    00000000000000000000000001,
    00000000000000000000000002,
    00000000000000000000000003,
};

// 1.2.5
Span<int> metatable = new int[]
{
    00000000000000000000000001,
    00000000000000000000000002,
    00000000000000000000000003,
};

Span<int> metatable =
    stackalloc int[] {
        00000000000000000000000001,
        00000000000000000000000002,
        00000000000000000000000003,
    };

```
### [Bug]: Comments in otherwise empty object pattern disappear when
formatting [#​1804](belav/csharpier#1804)
CSharpier was removing comments if they were the only content of an
object pattern.
```c#
// input & expected output
var match = obj is {
    //Property: 123
 ... (truncated)

Commits viewable in [compare view](belav/csharpier@1.2.5...1.2.6).
</details>

Updated [Microsoft.Extensions.Http.Resilience](https://github.com/dotnet/extensions) from 10.2.0 to 10.3.0.

<details>
<summary>Release notes</summary>

_Sourced from [Microsoft.Extensions.Http.Resilience's releases](https://github.com/dotnet/extensions/releases)._

## 10.3.0

## What's Changed
* Bump version to 10.3.0 for next development cycle by @​Copilot in dotnet/extensions#7197
* Fix race condition in UnreliableL2Tests.WriteFailureInvisible by @​Copilot in dotnet/extensions#7075
* Set Microsoft.McpServer.ProjectTemplates version to align with MCP packages by @​jeffhandley in dotnet/extensions#7170
* ToChatResponse: Merge AdditionalProperties into ChatMessage instead of ChatResponse by @​Copilot in dotnet/extensions#7194
* Fix NRT resolution for AIFunction parameters. by @​eiriktsarpalis in dotnet/extensions#7200
* Bump mdast-util-to-hast from 13.2.0 to 13.2.1 in /src/Libraries/Microsoft.Extensions.AI.Evaluation.Reporting/TypeScript by @​dependabot[bot] in dotnet/extensions#7198
* Add .npmrc next to package.json and add lockfile for PublishAIEvaluationReport by @​akoeplinger in dotnet/extensions#7108
* Bump qs from 6.14.0 to 6.14.1 in /src/Libraries/Microsoft.Extensions.AI.Evaluation.Reporting/TypeScript by @​dependabot[bot] in dotnet/extensions#7189
* Bump js-yaml from 4.1.0 to 4.1.1 in /src/Libraries/Microsoft.Extensions.AI.Evaluation.Reporting/TypeScript by @​dependabot[bot] in dotnet/extensions#7054
* Bump validator from 13.15.20 to 13.15.23 in /src/Libraries/Microsoft.Extensions.AI.Evaluation.Reporting/TypeScript by @​dependabot[bot] in dotnet/extensions#7103
* Update AI changelogs by @​stephentoub in dotnet/extensions#7206
* Merge changes from internal after 10.2 release by @​joperezr in dotnet/extensions#7205
* Merge changes from release/10.2 to main by @​joperezr in dotnet/extensions#7209
* Categorize MEAI001 experimental APIs by @​Copilot in dotnet/extensions#7116
* [main] Update dependencies from dotnet/arcade by @​dotnet-maestro[bot] in dotnet/extensions#7212
* Update Package Validation Baseline to 10.2.0 by @​Copilot in dotnet/extensions#7208
* Enable package validation for M.E.AmbientMetadata.Build by @​evgenyfedorov2 in dotnet/extensions#7213
* [5752] FakeLogCollector waiting capabilities by @​Demo30 in dotnet/extensions#6228
* Set network isolation policy for extensions-ci by @​wtgodbe in dotnet/extensions#7221
* Fix FunctionInvokingChatClient invoke_agent span detection with exact match or space delimiter by @​Copilot in dotnet/extensions#7224
* Add Ordinal into ordering by @​cincuranet in dotnet/extensions#7225
* Remove AIFunctionDeclaration tools on last iteration in FunctionInvokingChatClient by @​Copilot in dotnet/extensions#7207
* Remove unnecessary description tags by @​gewarren in dotnet/extensions#7226
* Fix FunctionInvokingChatClient to respect ChatOptions.Tools modifications by function tools by @​Copilot in dotnet/extensions#7218
* Add LoadFromAsync and SaveToAsync helper methods to DataContent by @​Copilot in dotnet/extensions#7159
* Bump lodash from 4.17.21 to 4.17.23 in /src/Libraries/Microsoft.Extensions.AI.Evaluation.Reporting/TypeScript by @​dependabot[bot] in dotnet/extensions#7227
* Add logging to FunctionInvokingChatClient for approval flow, error handling, and loop control by @​Copilot in dotnet/extensions#7228
* [main] Update dependencies from dotnet/arcade by @​dotnet-maestro[bot] in dotnet/extensions#7230
* Allow FunctionResultContent pass-through when CallId matches by @​Copilot in dotnet/extensions#7229
* Propagate CachedInputTokenCount in OpenTelemetry telemetry by @​Copilot in dotnet/extensions#7234
* Add InvocationRequired property to FunctionCallContent by @​Copilot in dotnet/extensions#7126
* Escape the JSON data before embedding in Evaluation reports by @​peterwald in dotnet/extensions#7238
* Update mcpserver template to ModelContextProtocol 0.7.0-preview.1 by @​Copilot in dotnet/extensions#7236
* Update aiagent-webapi template to Agent Framework 1.0.0-preview.260127.1 by @​Copilot in dotnet/extensions#7237
* Fix token metric unit to use UCUM format {token} by @​stephentoub in dotnet/extensions#7241
* Add server tool call support to OpenTelemetryChatClient per semantic conventions by @​Copilot in dotnet/extensions#7240
* Preserve extra JSON schema properties in ToolJson serialization by @​Copilot in dotnet/extensions#7250
* Bring new cpu.requests formula from Kubernetes by @​amadeuszl in dotnet/extensions#7239
* Update M.E.AI changelogs with recent changes by @​stephentoub in dotnet/extensions#7242
* Fix DataUriParser to default to text/plain;charset=US-ASCII per RFC 2397 by @​Copilot in dotnet/extensions#7247
* Fix deadlock in ServiceEndpointWatcher when disposing change token registration by @​ReubenBond in dotnet/extensions#7255
* Rename FunctionCallContent.InvocationRequired to InformationalOnly with inverted polarity by @​Copilot in dotnet/extensions#7262
* Fix approval request/response correlation in FunctionInvokingChatClient by @​Copilot in dotnet/extensions#7261
* Add ReasoningOptions to ChatOptions by @​Copilot in dotnet/extensions#7252

## New Contributors
* @​cincuranet made their first contribution in dotnet/extensions#7225
* @​ReubenBond made their first contribution in dotnet/extensions#7255

 ... (truncated)

Commits viewable in [compare view](dotnet/extensions@v10.2.0...v10.3.0).
</details>

Updated [Microsoft.Extensions.Logging.Abstractions](https://github.com/dotnet/dotnet) from 10.0.2 to 10.0.3.

<details>
<summary>Release notes</summary>

_Sourced from [Microsoft.Extensions.Logging.Abstractions's releases](https://github.com/dotnet/dotnet/releases)._

## 10.0.3

[Release](https://github.com/dotnet/core/releases/tag/v10.0.3)

Commits viewable in [compare view](https://github.com/dotnet/dotnet/commits/v10.0.3).
</details>

Updated [Microsoft.SourceLink.GitHub](https://github.com/dotnet/dotnet) from 10.0.102 to 10.0.103.

<details>
<summary>Release notes</summary>

_Sourced from [Microsoft.SourceLink.GitHub's releases](https://github.com/dotnet/dotnet/releases)._

## 10.0.103

You can build .NET 10.0 from the repository by cloning the release tag `v10.0.103` and following the build instructions in the [main README.md](https://github.com/dotnet/dotnet/blob/v10.0.103/README.md#building).

Alternatively, you can build from the sources attached to this release directly.
More information on this process can be found in the [dotnet/dotnet repository](https://github.com/dotnet/dotnet/blob/v10.0.103/README.md#building-from-released-sources).

Attached is the PGP signature for the GitHub generated tarball. You can find the public key at https://dot.net/release-key-2023

Commits viewable in [compare view](https://github.com/dotnet/dotnet/commits/v10.0.103).
</details>

Updated [Serilog](https://github.com/serilog/serilog) from 4.3.0 to 4.3.1.

<details>
<summary>Release notes</summary>

_Sourced from [Serilog's releases](https://github.com/serilog/serilog/releases)._

## 4.3.1

## What's Changed
* Remove SourceLink by @​SimonCropp in serilog/serilog#2183
* Handle Exception.ToString failures in text formatter by @​krisbiradar in serilog/serilog#2197
* Remove char[] allocation by @​karpinsn in serilog/serilog#2198
* Remove backpressure from XMLDoc by @​timothycoleman in serilog/serilog#2203
* Don't enable XDOC for tests by @​nblumhardt in serilog/serilog#2205
* Target and test on net10 by @​SimonCropp in serilog/serilog#2206
* Fix trimming error when Serilog is a transitive dependency by @​Numpsy in serilog/serilog#2214
* Inline TraceId and SpanId JSON string formatting by @​SimonCropp in serilog/serilog#2215

## New Contributors
* @​krisbiradar made their first contribution in serilog/serilog#2197
* @​karpinsn made their first contribution in serilog/serilog#2198
* @​timothycoleman made their first contribution in serilog/serilog#2203
* @​Numpsy made their first contribution in serilog/serilog#2214

**Full Changelog**: serilog/serilog@v4.3.0...v4.3.1

Commits viewable in [compare view](serilog/serilog@v4.3.0...v4.3.1).
</details>

Updated [System.CommandLine](https://github.com/dotnet/dotnet) from 2.0.2 to 2.0.3.

<details>
<summary>Release notes</summary>

_Sourced from [System.CommandLine's releases](https://github.com/dotnet/dotnet/releases)._

No release notes found for this version range.

Commits viewable in [compare view](https://github.com/dotnet/dotnet/commits).
</details>

Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all of the ignore conditions of the specified dependency
- `@dependabot ignore <dependency name> major version` will close this group update PR and stop Dependabot creating any more for the specific dependency's major version (unless you unignore this specific dependency's major version or upgrade to it yourself)
- `@dependabot ignore <dependency name> minor version` will close this group update PR and stop Dependabot creating any more for the specific dependency's minor version (unless you unignore this specific dependency's minor version or upgrade to it yourself)
- `@dependabot ignore <dependency name>` will close this group update PR and stop Dependabot creating any more for the specific dependency (unless you unignore this specific dependency or upgrade to it yourself)
- `@dependabot unignore <dependency name>` will remove all of the ignore conditions of the specified dependency
- `@dependabot unignore <dependency name> <ignore condition>` will remove the ignore condition of the specified dependency and ignore conditions


</details>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Pieter Viljoen <ptr727@users.noreply.github.com>
This was referenced Feb 12, 2026
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.

3 participants