Skip to content

Conversation

@MathiasZander
Copy link
Contributor

@MathiasZander MathiasZander commented Dec 27, 2025

  • Expands the FinishReason enum to include additional values documented across Google’s APIs (including Vertex AI image/model-armor/tooling related reasons).
  • Replaces strict enum parsing with a lenient JSON converter (LenientFinishReasonConverter) that parses known values case-insensitively and falls back to FinishReason.OTHER for unknown strings instead of throwing System.Text.Json.JsonException.
  • Updates ResponseHelper.FormatErrorMessage to cover the newly added finish reasons.

Net effect: streaming and non-streaming responses no longer crash on previously unknown finishReason values, while preserving existing behavior for all known reasons.

Summary by CodeRabbit

  • New Features

    • Added eight new finish reason types for content generation: MODEL_ARMOR, IMAGE_PROHIBITED_CONTENT, IMAGE_RECITATION, IMAGE_OTHER, UNEXPECTED_TOOL_CALL, NO_IMAGE, and TOO_MANY_TOOL_CALLS.
    • Enhanced error message descriptions for all finish reason scenarios.
  • Improvements

    • Improved robustness in handling unknown finish reason values with graceful fallback behavior.
  • Tests

    • Added comprehensive unit tests for finish reason conversion and serialization.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link

coderabbitai bot commented Dec 27, 2025

📝 Walkthrough

Walkthrough

The pull request extends the FinishReason enum with eight new values (MODEL_ARMOR, IMAGE_PROHIBITED_CONTENT, IMAGE_RECITATION, IMAGE_OTHER, UNEXPECTED_TOOL_CALL, NO_IMAGE, TOO_MANY_TOOL_CALLS), introduces a lenient JSON converter that gracefully handles unknown enum values during deserialization, and updates error message handling for the new cases with corresponding unit tests.

Changes

Cohort / File(s) Summary
FinishReason Enum & Error Handling
src/GenerativeAI/Types/ContentGeneration/Outputs/FinishReason.cs, src/GenerativeAI/Core/ResponseHelper.cs
FinishReason enum expanded with 8 new values (12–18) and switched from standard JsonStringEnumConverter to LenientFinishReasonConverter. ResponseHelper.FormatErrorMessage() updated with corresponding switch cases for each new FinishReason.
Lenient Converter Implementation
src/GenerativeAI/Types/Converters/LenientFinishReasonConverter.cs
New JsonConverter subclass for lenient deserialization of FinishReason: attempts case-insensitive enum parse on string tokens, returns OTHER on unrecognized values, and FINISH_REASON_UNSPECIFIED for empty strings. Serialization writes enum string representation.
Converter Unit Tests
tests/GenerativeAI.Tests/Converters/LenientFinishReasonConverter_Tests.cs
Test suite covering deserialization of known values (case-insensitive), unknown values (fallback to OTHER), and serialization behavior.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 Eight new reasons now have names so clear,
And when the future brings what we don't know,
Our lenient converter shows no fear—
It gracefully accepts the ebb and flow.
hops happily

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly and concisely summarizes the main change: improving FinishReason handling to prevent deserialization errors when new values are introduced.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
tests/GenerativeAI.Tests/Converters/LenientFinishReasonConverter_Tests.cs (1)

7-31: Good test coverage for core scenarios.

The tests cover the main use cases effectively. Consider adding tests for edge cases that the converter handles:

  1. Empty string input → should return FINISH_REASON_UNSPECIFIED
  2. Non-string JSON token (e.g., number) → should throw JsonException

These cases are implemented in the converter but not verified by tests.

🔎 Suggested additional tests
+    [Fact]
+    public void Read_EmptyString_ReturnsUnspecified()
+    {
+        var result = JsonSerializer.Deserialize<FinishReason>("\"\"");
+        result.ShouldBe(FinishReason.FINISH_REASON_UNSPECIFIED);
+    }
+
+    [Fact]
+    public void Read_NonStringToken_ThrowsJsonException()
+    {
+        Should.Throw<JsonException>(() => JsonSerializer.Deserialize<FinishReason>("123"));
+    }
src/GenerativeAI/Types/Converters/LenientFinishReasonConverter.cs (2)

14-16: Add complete XML documentation for Read method.

As per coding guidelines, C# code should include comprehensive XML documentation. The method summary is present but <param> and <returns> elements are missing.

🔎 Suggested documentation
     /// <summary>
     /// Reads and converts the JSON to FinishReason.
     /// </summary>
+    /// <param name="reader">The reader to read JSON from.</param>
+    /// <param name="typeToConvert">The type to convert to.</param>
+    /// <param name="options">Serialization options.</param>
+    /// <returns>The deserialized <see cref="FinishReason"/> value.</returns>
+    /// <exception cref="JsonException">Thrown when the token is not a string.</exception>
     public override FinishReason Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)

38-40: Add complete XML documentation for Write method.

🔎 Suggested documentation
     /// <summary>
     /// Writes the FinishReason value as JSON.
     /// </summary>
+    /// <param name="writer">The writer to write JSON to.</param>
+    /// <param name="value">The <see cref="FinishReason"/> value to serialize.</param>
+    /// <param name="options">Serialization options.</param>
     public override void Write(Utf8JsonWriter writer, FinishReason value, JsonSerializerOptions options)
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9a90bb0 and 9c1fb9e.

📒 Files selected for processing (4)
  • src/GenerativeAI/Core/ResponseHelper.cs
  • src/GenerativeAI/Types/ContentGeneration/Outputs/FinishReason.cs
  • src/GenerativeAI/Types/Converters/LenientFinishReasonConverter.cs
  • tests/GenerativeAI.Tests/Converters/LenientFinishReasonConverter_Tests.cs
🧰 Additional context used
📓 Path-based instructions (1)
**/*.cs

📄 CodeRabbit inference engine (CLAUDE.md)

C# code should use latest language features, enable nullable reference types, and include comprehensive XML documentation

Files:

  • tests/GenerativeAI.Tests/Converters/LenientFinishReasonConverter_Tests.cs
  • src/GenerativeAI/Types/Converters/LenientFinishReasonConverter.cs
  • src/GenerativeAI/Core/ResponseHelper.cs
  • src/GenerativeAI/Types/ContentGeneration/Outputs/FinishReason.cs
🧬 Code graph analysis (2)
src/GenerativeAI/Core/ResponseHelper.cs (1)
src/GenerativeAI/Types/Converters/LenientFinishReasonConverter.cs (1)
  • FinishReason (17-36)
src/GenerativeAI/Types/ContentGeneration/Outputs/FinishReason.cs (1)
src/GenerativeAI/Types/Converters/LenientFinishReasonConverter.cs (1)
  • LenientFinishReasonConverter (12-45)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build (9.0.x)
🔇 Additional comments (4)
src/GenerativeAI/Core/ResponseHelper.cs (1)

76-82: LGTM!

The new finish reason cases are properly handled with clear, descriptive messages that align with the enum documentation. The existing default case at line 83 provides a safety net for any additional future values.

src/GenerativeAI/Types/Converters/LenientFinishReasonConverter.cs (1)

17-36: LGTM!

The converter logic is solid:

  • Correctly validates token type before reading
  • Handles empty/null strings by returning FINISH_REASON_UNSPECIFIED
  • Uses case-insensitive parsing for flexibility
  • Gracefully falls back to OTHER for unknown values

This prevents deserialization crashes when Google introduces new values.

src/GenerativeAI/Types/ContentGeneration/Outputs/FinishReason.cs (2)

9-15: LGTM!

Excellent documentation update. The remarks section clearly explains the lenient converter behavior, and the JsonConverter attribute switch to LenientFinishReasonConverter enables graceful handling of unknown enum values.


78-119: Well-structured enum expansion.

The new enum values are properly implemented:

  • Explicit numeric values (12-18) ensure binary/serialization compatibility
  • Sequential numbering prevents gaps
  • Each value has comprehensive XML documentation with API source references
  • Consistent naming convention with existing values

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.

2 participants