Skip to content

Conversation

@ChiragAgg5k
Copy link
Member

@ChiragAgg5k ChiragAgg5k commented May 30, 2025

Summary by CodeRabbit

  • Bug Fixes
    • Improved error message consistency and clarity for users by standardizing error formatting across multiple integrations.
    • Enhanced reliability when processing streamed responses, ensuring better handling of data with or without the "data: " prefix.

@coderabbitai
Copy link

coderabbitai bot commented May 30, 2025

"""

Walkthrough

Error message formatting is centralized by adding a new abstract protected method formatErrorMessage in the Adapter base class and implementing it in multiple adapter subclasses. Error handling in streaming and non-streaming modes is refactored to use this method, improving consistency and robustness in processing JSON error responses.

Changes

File Change Summary
src/Agents/Adapter.php Added abstract protected method formatErrorMessage($json): string to Adapter base class.
src/Agents/Adapters/Anthropic.php Added protected method formatErrorMessage; updated send and process methods to use it; improved streaming JSON line parsing to handle "data: " prefix.
src/Agents/Adapters/OpenAI.php Added protected method formatErrorMessage; enhanced error handling in non-streaming and streaming responses using this method.
src/Agents/Adapters/Deepseek.php Added protected method formatErrorMessage; refactored process method to delegate error formatting to it.
src/Agents/Adapters/Gemini.php Added protected method formatErrorMessage; refactored process method to use it for error formatting.
src/Agents/Adapters/Perplexity.php Simplified error handling in process by delegating error message formatting to a new formatErrorMessage method.
src/Agents/Adapters/XAI.php Added new protected methods process and formatErrorMessage; implemented streaming response processing and error formatting.

Poem

🐇 Hopping through lines of code so neat,
Errors now dressed in a tidy seat.
From Anthropic to XAI's new song,
FormatErrorMessage makes right from wrong.
Streams flow smooth, exceptions clear,
Rabbits cheer — no bugs near here! 🎉✨
"""


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 11bb934 and ef5a93f.

📒 Files selected for processing (7)
  • src/Agents/Adapter.php (1 hunks)
  • src/Agents/Adapters/Anthropic.php (4 hunks)
  • src/Agents/Adapters/Deepseek.php (2 hunks)
  • src/Agents/Adapters/Gemini.php (2 hunks)
  • src/Agents/Adapters/OpenAI.php (3 hunks)
  • src/Agents/Adapters/Perplexity.php (1 hunks)
  • src/Agents/Adapters/XAI.php (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/Agents/Adapters/Anthropic.php
🧰 Additional context used
🧬 Code Graph Analysis (6)
src/Agents/Adapter.php (5)
src/Agents/Adapters/Gemini.php (1)
  • formatErrorMessage (339-350)
src/Agents/Adapters/Deepseek.php (1)
  • formatErrorMessage (309-319)
src/Agents/Adapters/XAI.php (1)
  • formatErrorMessage (145-155)
src/Agents/Adapters/OpenAI.php (1)
  • formatErrorMessage (406-416)
src/Agents/Adapters/Anthropic.php (1)
  • formatErrorMessage (449-459)
src/Agents/Adapters/Gemini.php (5)
src/Agents/Adapter.php (1)
  • formatErrorMessage (102-102)
src/Agents/Adapters/Deepseek.php (1)
  • formatErrorMessage (309-319)
src/Agents/Adapters/XAI.php (1)
  • formatErrorMessage (145-155)
src/Agents/Adapters/OpenAI.php (1)
  • formatErrorMessage (406-416)
src/Agents/Adapters/Anthropic.php (1)
  • formatErrorMessage (449-459)
src/Agents/Adapters/Perplexity.php (6)
src/Agents/Adapter.php (1)
  • formatErrorMessage (102-102)
src/Agents/Adapters/Gemini.php (1)
  • formatErrorMessage (339-350)
src/Agents/Adapters/Deepseek.php (1)
  • formatErrorMessage (309-319)
src/Agents/Adapters/XAI.php (1)
  • formatErrorMessage (145-155)
src/Agents/Adapters/OpenAI.php (1)
  • formatErrorMessage (406-416)
src/Agents/Adapters/Anthropic.php (1)
  • formatErrorMessage (449-459)
src/Agents/Adapters/Deepseek.php (5)
src/Agents/Adapter.php (1)
  • formatErrorMessage (102-102)
src/Agents/Adapters/Gemini.php (1)
  • formatErrorMessage (339-350)
src/Agents/Adapters/XAI.php (1)
  • formatErrorMessage (145-155)
src/Agents/Adapters/OpenAI.php (1)
  • formatErrorMessage (406-416)
src/Agents/Adapters/Anthropic.php (1)
  • formatErrorMessage (449-459)
src/Agents/Adapters/OpenAI.php (5)
src/Agents/Adapter.php (2)
  • formatErrorMessage (102-102)
  • getName (54-54)
src/Agents/Adapters/Gemini.php (2)
  • formatErrorMessage (339-350)
  • getName (328-331)
src/Agents/Adapters/Deepseek.php (2)
  • formatErrorMessage (309-319)
  • getName (298-301)
src/Agents/Adapters/XAI.php (2)
  • formatErrorMessage (145-155)
  • getName (82-85)
src/Agents/Adapters/Anthropic.php (2)
  • formatErrorMessage (449-459)
  • getName (438-441)
src/Agents/Adapters/XAI.php (3)
src/Agents/Adapters/Perplexity.php (1)
  • process (114-164)
src/Agents/Adapters/OpenAI.php (2)
  • process (258-299)
  • formatErrorMessage (406-416)
src/Agents/Adapter.php (1)
  • formatErrorMessage (102-102)
🔇 Additional comments (12)
src/Agents/Adapter.php (1)

96-102: Excellent addition of abstract error formatting method.

This abstract method establishes a consistent contract for error message formatting across all adapter subclasses, improving code modularity and standardization.

src/Agents/Adapters/Gemini.php (2)

200-200: Good refactoring to use centralized error formatting.

The change delegates error message formatting to the dedicated formatErrorMessage method, improving code modularity and consistency.


333-350: Well-implemented error formatting with enhanced details.

The implementation correctly follows the established pattern while adding value through pretty-printed error details. The type checking, fallback handling, and multi-line formatting enhance error message quality.

src/Agents/Adapters/Perplexity.php (1)

121-122:

Details

✅ Verification successful

Good refactoring with proper inheritance.

The change correctly delegates to formatErrorMessage, which will be inherited from the parent OpenAI class. This maintains consistency while leveraging the existing implementation.

Let me verify that the inheritance is working correctly:


🏁 Script executed:

#!/bin/bash
# Description: Verify that OpenAI class has formatErrorMessage method that Perplexity can inherit

# Search for formatErrorMessage implementation in OpenAI adapter
ast-grep --pattern $'class OpenAI {
  $$$
  protected function formatErrorMessage($_) {
    $$$
  }
  $$$
}'

Length of output: 109


I wasn’t able to locate the method with the previous pattern. Let’s try a broader search:

This will confirm whether formatErrorMessage exists (and where) so we can ensure Perplexity inherits it correctly.


🏁 Script executed:

#!/bin/bash
# Search for any definition or usage of formatErrorMessage across PHP files
rg "formatErrorMessage" -n --glob="*.php"

Length of output: 1334


formatErrorMessage Inheritance Verified

I’ve confirmed that formatErrorMessage is declared as an abstract method in src/Agents/Adapter.php (line 102) and implemented in src/Agents/Adapters/OpenAI.php (line 406). Since Perplexity extends OpenAI, it correctly inherits this method—no further changes are needed.

src/Agents/Adapters/Deepseek.php (2)

186-186: Consistent refactoring to centralized error handling.

The change properly delegates error formatting to the dedicated method, following the established pattern across all adapters.


303-319: Correct implementation following established pattern.

The formatErrorMessage method properly implements the abstract interface with appropriate type checking, error extraction from the Deepseek API response structure, and consistent formatting.

src/Agents/Adapters/XAI.php (3)

5-5: Import addition looks good.

The Chunk import is necessary for the new process() method parameter type and is correctly namespaced.


145-155:

Details

❓ Verification inconclusive

Error message format differs from OpenAI - verify XAI API response structure.

The formatErrorMessage() implementation extracts error information from top-level code and error fields, which differs from OpenAI's nested error.code and error.message structure.

Please verify that XAI API returns errors in this format:

{
  "code": "error_code",
  "error": "error_message"
}

Rather than OpenAI's format:

{
  "error": {
    "code": "error_code", 
    "message": "error_message"
  }
}

🌐 Web query:

What is the XAI API error response format for the chat completions endpoint?

💡 Result:

I'm sorry, but I couldn't find specific information about the error response format for the chat completions endpoint of the XAI API. API error response formats can vary between services, and without access to the official XAI API documentation, it's challenging to provide precise details.

In general, many APIs return error responses in JSON format, often including fields such as:

  • error: A brief description of the error.
  • message: A more detailed explanation of the error.
  • code: An error code representing the type of error.
  • status: The HTTP status code associated with the error.

For example:

{
  "error": "InvalidRequest",
  "message": "The 'model' parameter is required.",
  "code": 400,
  "status": 400
}

To obtain accurate information about the XAI API's error response format, I recommend consulting the official XAI API documentation or reaching out to their support team directly.


Confirm XAI API Error Response Format

I wasn’t able to find official XAI documentation for the chat completions endpoint error payload. Please verify whether errors are returned as:

  • Top-level fields:
    { "code": "error_code", "error": "error_message" }
  • Or nested under error:
    { "error": { "code": "error_code", "message": "error_message" } }

If the latter, update formatErrorMessage() in src/Agents/Adapters/XAI.php (lines 145–155) accordingly:

- $errorType    = isset($json['code'])  ? (string)$json['code']  : 'unknown_error';
- $errorMessage = isset($json['error']) ? (string)$json['error'] : 'Unknown error';
+ $errorType    = isset($json['error']['code'])    ? (string)$json['error']['code']    : 'unknown_error';
+ $errorMessage = isset($json['error']['message']) ? (string)$json['error']['message'] : 'Unknown error';

87-137:

Details

❓ Verification inconclusive

Verify consistency with parent OpenAI adapter processing logic.

The process() method implementation closely follows the OpenAI adapter pattern, which is good for consistency. However, since XAI extends OpenAI, this method overrides the parent's process() method.

Please verify if the XAI API response format is identical to OpenAI's format, particularly:

  1. The streaming data format (lines prefixed with "data: ")
  2. The [DONE] termination signal
  3. The JSON structure with choices[0].delta.content

🏁 Script executed:

#!/bin/bash
# Description: Compare XAI process method with OpenAI process method to identify differences.

# Search for process method implementations in both adapters
echo "=== OpenAI process method ==="
ast-grep --pattern 'protected function process($_, $_) {
  $$$
}'

echo "=== Comparing error handling patterns ==="
rg -A 5 -B 2 "formatErrorMessage.*json" src/Agents/Adapters/

Length of output: 6810


🏁 Script executed:

#!/bin/bash
# Verify that XAI extends the OpenAI adapter
echo "=== XAI class declaration ==="
rg -n "class XAI" -n src/Agents/Adapters/XAI.php

# Show the process() implementation in the OpenAI adapter
echo "=== OpenAI process method ==="
rg -A5 -B2 "protected function process" src/Agents/Adapters/OpenAI.php

Length of output: 498


🏁 Script executed:

#!/bin/bash
# Extract the full implementation of the OpenAI adapter's process method for comparison
echo "=== OpenAI process method body ==="
rg -A40 -B2 "protected function process(Chunk \$chunk, \?callable \$listener): string" src/Agents/Adapters/OpenAI.php

Length of output: 196


🏁 Script executed:

#!/bin/bash
# Extract the full process() implementation from OpenAI adapter
sed -n -e '/protected function process/,/^[[:space:]]*}/p' src/Agents/Adapters/OpenAI.php

Length of output: 428


Confirm XAI streaming format matches OpenAI
The override of process() in src/Agents/Adapters/XAI.php (lines 87–137) is identical to the parent implementation. Unless the XAI API actually differs in its streaming payload, this duplication can be removed. Please verify that XAI’s responses use the same:

  • Lines prefixed with "data: "
  • A "data: [DONE]" termination signal
  • JSON objects containing choices[0].delta.content

If XAI matches exactly, drop the override to stay DRY; if not, document the format deviations.

src/Agents/Adapters/OpenAI.php (3)

229-236: Improved error handling with centralized formatting.

The non-streaming error handling now properly decodes JSON responses and uses the centralized formatErrorMessage() method, which is a good improvement over throwing raw content in exceptions.


266-266: Consistent error formatting in streaming mode.

The streaming error handling now uses the centralized formatErrorMessage() method, maintaining consistency with non-streaming error handling.


406-416: Well-implemented error message formatting with proper fallbacks.

The formatErrorMessage() method correctly:

  • Validates input is an array
  • Extracts error code from nested error.code structure
  • Extracts error message from nested error.message structure
  • Provides sensible fallback values for missing fields
  • Returns consistently formatted error strings

This implementation aligns well with OpenAI's actual API error response structure.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@ChiragAgg5k ChiragAgg5k requested a review from Copilot May 30, 2025 04:10
Copy link

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 centralizes error formatting across all agent adapters and enhances streamed response processing by standardizing how chunks and errors are handled.

  • Introduces an abstract formatErrorMessage method in the base Adapter class and implements it in each adapter.
  • Updates each adapter’s process and HTTP status check logic to use the new unified formatter.
  • Improves stream parsing by handling optional "data: " prefixes and non-stream error responses.

Reviewed Changes

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

Show a summary per file
File Description
src/Agents/Adapters/XAI.php Added chunk processing with unified error formatting via formatErrorMessage.
src/Agents/Adapters/Perplexity.php Swapped in formatErrorMessage call for error cases (implementation missing).
src/Agents/Adapters/OpenAI.php Added HTTP status check, throws formatted exception, and implemented formatErrorMessage.
src/Agents/Adapters/Gemini.php Refactored error handling to delegate to formatErrorMessage.
src/Agents/Adapters/Deepseek.php Replaced inline error formatting with formatErrorMessage.
src/Agents/Adapters/Anthropic.php Enhanced non-stream error capture, unified prefix stripping, and added formatter.
src/Agents/Adapter.php Declares abstract protected function formatErrorMessage($json): string;.
Comments suppressed due to low confidence (3)

src/Agents/Adapters/Perplexity.php:121

  • The Perplexity adapter now calls formatErrorMessage($json) but does not implement this method, leading to a fatal error. Add a protected formatErrorMessage($json): string implementation to Perplexity.php or inherit a default.
if (is_array($json) && isset($json['error'])) {

src/Agents/Adapters/Anthropic.php:222

  • The variable $payload is not defined in this scope, which will cause an undefined variable error. Ensure the stream flag is retrieved from a valid variable (e.g., method parameter or class property) or include $payload in the closure's context.
if (! $payload['stream']) {

src/Agents/Adapter.php:102

  • [nitpick] Multiple adapters implement very similar formatErrorMessage logic. Consider providing a default implementation in the base Adapter class and letting adapters override only when necessary to reduce duplication.
abstract protected function formatErrorMessage($json): string;

@eldadfux eldadfux merged commit 4d2f173 into main May 30, 2025
4 checks passed
@TorstenDittmann TorstenDittmann deleted the fix-anthropic-error-catching branch May 30, 2025 11:16
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