Skip to content

OpenAI conversation: Standardizing API response#318

Merged
AkhileshNegi merged 3 commits intomainfrom
hotfix/handling-conversation-failures
Aug 8, 2025
Merged

OpenAI conversation: Standardizing API response#318
AkhileshNegi merged 3 commits intomainfrom
hotfix/handling-conversation-failures

Conversation

@AkhileshNegi
Copy link
Copy Markdown
Collaborator

@AkhileshNegi AkhileshNegi commented Aug 4, 2025

Summary

Target issue is #317
Explain the motivation for making this change. What existing problem does the pull request solve?

Checklist

Before submitting a pull request, please ensure that you mark these task.

  • Ran fastapi run --reload app/main.py or docker compose up in the repository root and test.
  • If you've fixed a bug or added code that is tested and has test cases.

Notes

Please add here if any other information is required for the reviewer.

Summary by CodeRabbit

  • Bug Fixes
    • Improved error responses by including additional contextual metadata from the original request when an OpenAI API error occurs.

@AkhileshNegi AkhileshNegi self-assigned this Aug 4, 2025
@AkhileshNegi AkhileshNegi added the bug Something isn't working label Aug 4, 2025
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Aug 4, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

The failure response mechanism was enhanced to include additional metadata extracted from the original request. The get_additional_data function now distinguishes between async and sync requests to exclude different keys. Failure responses in multiple handlers were updated to include this metadata, enriching error context.

Changes

Cohort / File(s) Change Summary
Failure Response Enhancement
backend/app/utils.py
Updated APIResponse.failure_response method to accept an optional metadata argument, allowing failure responses to include additional context.
Error Context Enrichment in Responses
backend/app/api/routes/responses.py
Modified get_additional_data to differentiate async vs sync requests with distinct exclusion keys; failure responses now include metadata from requests in multiple error handlers.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API
    participant OpenAI

    Client->>API: Send request (async or sync)
    API->>API: Determine request type (async or sync)
    API->>API: Extract additional metadata (exclude keys based on type)
    API->>OpenAI: Forward request
    OpenAI-->>API: Return error
    API->>API: Generate failure response with error + metadata
    API-->>Client: Return enriched failure response
Loading

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~5 minutes

Possibly related PRs

Suggested labels

enhancement

Suggested reviewers

  • avirajsingh7
  • kartpop

Poem

When things go wrong, don’t fear the night,
Metadata shines a guiding light.
Async or sync, we now know,
What details to keep, what to let go.
A rabbit hops with joy in sight! 🐇✨

Note

🔌 MCP (Model Context Protocol) integration is now available in Early Access!

Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context.


📜 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 e8a09e0 and 92849e6.

📒 Files selected for processing (1)
  • backend/app/api/routes/responses.py (4 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch hotfix/handling-conversation-failures

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
🪧 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.
  • 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.

Support

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

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 generate unit tests to generate unit tests for 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.

@AkhileshNegi AkhileshNegi linked an issue Aug 4, 2025 that may be closed by this pull request
@codecov
Copy link
Copy Markdown

codecov bot commented Aug 4, 2025

Codecov Report

❌ Patch coverage is 53.84615% with 6 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
backend/app/api/routes/responses.py 45.45% 6 Missing ⚠️

📢 Thoughts on this report? Let us know!

Copy link
Copy Markdown
Collaborator

@avirajsingh7 avirajsingh7 left a comment

Choose a reason for hiding this comment

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

In the current implementation of Prompt Management, I’m only including pagination details in the metadata field of the API response. However, I’ve been thinking about introducing a proper structure and validation to metadata as well. By defining it using Pydantic (via SQLModel), we can make the API responses easier to document and validate.

Adding code snippet

from sqlmodel import SQLModel, Field


class Pagination(SQLModel):
    """
    Pagination metadata for API responses.
    """

    total: int = Field(..., description="Total number of items", ge=0)
    skip: int = Field(..., description="Number of items to skip", ge=0)
    limit: int = Field(
        ..., description="Maximum number of items to return", ge=1, le=100
    )

class Metadata(SQLModel):
    """
    Metadata for API responses.
    """
    pagination: Pagination | None = None


class ResponseMetadata(Metadata):
    """
    Metadata for API responses.
    """
    assistants_id: str | None = Field(
        None, description="ID of the assistant", example="12345"
    )
    call_back_url: str | None = Field(
        None, description="Callback URL for the response", example="https://example.com/callback"
    )

The idea is to have a base Metadata class that contains common fields—like pagination—and then allow more specific metadata to be added by extending this base class.

For now you can ignore pagination thing that I will include in Prompt PR.

I will wait for @kartpop opinion also, this can be considered over engineering also but it is always good to return validated response.

Copy link
Copy Markdown
Collaborator

@kartpop kartpop left a comment

Choose a reason for hiding this comment

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

Approving this, anticipating that the assumption in my comment is correct.

k: v
for k, v in request.items()
if k not in {"assistant_id", "callback_url", "response_id", "question"}
# Keys to exclude for async request (ResponsesAPIRequest)
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I assume that the only reason we are hardcoding here is because:

  • this route is very specific to OpenAI Responses API AND
  • these keys are very specific to that API
    Right? If yes, this is fine.

@kartpop
Copy link
Copy Markdown
Collaborator

kartpop commented Aug 6, 2025

In the current implementation of Prompt Management, I’m only including pagination details in the metadata field of the API response. However, I’ve been thinking about introducing a proper structure and validation to metadata as well. By defining it using Pydantic (via SQLModel), we can make the API responses easier to document and validate.

Adding code snippet

from sqlmodel import SQLModel, Field


class Pagination(SQLModel):
    """
    Pagination metadata for API responses.
    """

    total: int = Field(..., description="Total number of items", ge=0)
    skip: int = Field(..., description="Number of items to skip", ge=0)
    limit: int = Field(
        ..., description="Maximum number of items to return", ge=1, le=100
    )

class Metadata(SQLModel):
    """
    Metadata for API responses.
    """
    pagination: Pagination | None = None


class ResponseMetadata(Metadata):
    """
    Metadata for API responses.
    """
    assistants_id: str | None = Field(
        None, description="ID of the assistant", example="12345"
    )
    call_back_url: str | None = Field(
        None, description="Callback URL for the response", example="https://example.com/callback"
    )

The idea is to have a base Metadata class that contains common fields—like pagination—and then allow more specific metadata to be added by extending this base class.

For now you can ignore pagination thing that I will include in Prompt PR.

I will wait for @kartpop opinion also, this can be considered over engineering also but it is always good to return validated response.

Yes, I think that this might be over-engineering. At least in the context of the current PR, where the additional metadata param is included for failure_response, keeping that metadata a generic Dict[str, Any] is good enough.

Even in the case of success_response, I think pagination may not be as generic a parameter - it will only make sense when our response includes a very large collection. Now, this may very well be the case for most of our APIs, in which case we should discuss.

@AkhileshNegi AkhileshNegi merged commit cae70be into main Aug 8, 2025
1 of 2 checks passed
@AkhileshNegi AkhileshNegi deleted the hotfix/handling-conversation-failures branch August 8, 2025 08:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working ready-for-review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

OpenAI conversation: Standardizing API response

3 participants