Skip to content

feat: add option to disable raw response in provider responses#196

Merged
akshaydeo merged 1 commit intomainfrom
07-29-feat_added_toggle_for_include_raw_response
Jul 29, 2025
Merged

feat: add option to disable raw response in provider responses#196
akshaydeo merged 1 commit intomainfrom
07-29-feat_added_toggle_for_include_raw_response

Conversation

@Pratham-Mishra04
Copy link
Copy Markdown
Collaborator

Make Raw Response Optional in Provider Responses

This PR adds a configuration option to control whether raw provider responses are included in Bifrost responses. Previously, raw responses were always included, which could increase response size and bandwidth usage unnecessarily.

Key changes:

  • Added send_back_raw_response boolean flag to provider configuration
  • Modified all providers to respect this setting when processing responses
  • Updated the UI to include a toggle for this option in the provider configuration form
  • Optimized response handling to avoid unnecessary JSON parsing when raw responses aren't needed
  • Standardized response object pools across providers to use the common BifrostResponse type

This change improves performance by avoiding unnecessary JSON parsing and reduces response sizes when raw responses aren't needed, while maintaining backward compatibility for users who rely on the raw response data.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jul 29, 2025

Summary by CodeRabbit

  • New Features

    • Added an option to include the raw API response in provider outputs for advanced debugging and inspection.
    • Introduced a switch in the provider configuration UI to enable or disable returning raw responses.
    • The provider management API now supports the new raw response option when adding or updating providers.
  • Bug Fixes

    • None.
  • Documentation

    • None.
  • Tests

    • Updated test scenarios and configurations to reflect changes in provider response handling.
  • Chores

    • Unified and streamlined response handling across all providers to support the new raw response option.

Walkthrough

A new configuration flag, sendBackRawResponse, was introduced across all provider implementations and their configuration schemas. This flag allows conditional inclusion of the raw API response in the returned BifrostResponse object. The change is reflected in backend provider logic, shared utilities, and the frontend provider configuration UI.

Changes

Cohort / File(s) Change Summary
Provider Structs & Constructors
core/providers/anthropic.go, core/providers/azure.go, core/providers/bedrock.go, core/providers/cohere.go, core/providers/groq.go, core/providers/mistral.go, core/providers/ollama.go, core/providers/openai.go, core/providers/sgl.go, core/providers/vertex.go
Added sendBackRawResponse boolean field to provider structs; constructors updated to initialize from config; response methods updated to conditionally include raw response based on this flag.
Provider Response Handling Refactor
core/providers/groq.go, core/providers/mistral.go, core/providers/ollama.go, core/providers/sgl.go
Removed custom response structs in favor of using schemas.BifrostResponse; updated pooling logic and response handling accordingly.
Shared Response Utility
core/providers/utils.go
Updated handleProviderResponse to accept sendBackRawResponse flag and conditionally unmarshal raw response.
Provider Configuration Schema
core/schemas/provider.go
Added SendBackRawResponse boolean field to ProviderConfig struct.
Frontend Provider Config UI
ui/components/config/provider-form.tsx
Added sendBackRawResponse to form state and UI; added switch control in performance tab; included in backend payload.
Frontend Types
ui/lib/types/config.ts
Added optional send_back_raw_response property to provider config and request interfaces.
Transport Layer Config and Handlers
transports/bifrost-http/handlers/providers.go, transports/bifrost-http/lib/config.go, transports/bifrost-http/lib/account.go
Added SendBackRawResponse field to request, response, and internal config structs; propagated this field through add/update provider handlers and account config retrieval.
Test Adjustments
tests/core-providers/config/account.go, tests/core-providers/scenarios/tool_calls.go
Modified Groq provider models list and appended phrase to test prompt for tool calls scenario.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant UI
    participant Backend
    participant Provider

    User->>UI: Toggle "Send Back Raw Response" in provider form
    UI->>Backend: Submit provider config (send_back_raw_response)
    Backend->>Provider: Initialize with sendBackRawResponse flag
    User->>Backend: Make completion request
    Backend->>Provider: Call ChatCompletion/TextCompletion
    Provider->>Provider: Conditionally include raw API response based on flag
    Provider-->>Backend: Return BifrostResponse (with/without raw response)
    Backend-->>User: Return response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • danpiths
  • akshaydeo

Poem

In the meadow of code where the APIs hop,
A new flag now tells us when raw bytes should drop.
With a flick of a switch, the response can expand—
Raw data or not, just as you planned!
🐇✨
Reviewers, come nibble, this patch is quite neat—
The garden of Bifrost is now more complete!

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 07-29-feat_added_toggle_for_include_raw_response

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

Copy link
Copy Markdown
Collaborator Author

Pratham-Mishra04 commented Jul 29, 2025

This stack of pull requests is managed by Graphite. Learn more about stacking.

Copy link
Copy Markdown
Contributor

@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: 1

🔭 Outside diff range comments (4)
ui/components/config/provider-form.tsx (2)

183-196: Add sendBackRawResponse to the useEffect dependency array.

The sendBackRawResponse field is missing from the dependency array, which means changes to this field alone won't mark the form as dirty, preventing users from saving.

-  }, [selectedProvider, keys, networkConfig, performanceConfig, metaConfig, proxyConfig, initialState, keysRequired])
+  }, [selectedProvider, keys, networkConfig, performanceConfig, metaConfig, proxyConfig, sendBackRawResponse, initialState, keysRequired])

236-250: Include sendBackRawResponse in new provider creation.

The sendBackRawResponse field is included for provider updates but missing from new provider creation, causing inconsistent behavior.

        meta_config: metaConfig,
        proxy_config: proxyConfig,
+       send_back_raw_response: sendBackRawResponse,
      }
core/providers/ollama.go (1)

80-86: Critical: Missing initialization of sendBackRawResponse field.

The sendBackRawResponse field is declared but not initialized in the constructor. This will cause the field to always be false, preventing the raw response feature from working.

Apply this fix to initialize the field from the provider configuration:

 return &OllamaProvider{
-	logger:        logger,
-	client:        client,
-	streamClient:  streamClient,
-	networkConfig: config.NetworkConfig,
+	logger:              logger,
+	client:              client,
+	streamClient:        streamClient,
+	networkConfig:       config.NetworkConfig,
+	sendBackRawResponse: config.SendBackRawResponse,
 }, nil
core/providers/sgl.go (1)

80-86: Critical: Missing initialization of sendBackRawResponse field.

The sendBackRawResponse field is declared but not initialized in the constructor, causing the raw response feature to be non-functional.

Apply this fix to initialize the field:

 return &SGLProvider{
-	logger:        logger,
-	client:        client,
-	streamClient:  streamClient,
-	networkConfig: config.NetworkConfig,
+	logger:              logger,
+	client:              client,
+	streamClient:        streamClient,
+	networkConfig:       config.NetworkConfig,
+	sendBackRawResponse: config.SendBackRawResponse,
 }, nil

Comment thread ui/components/config/provider-form.tsx
@Pratham-Mishra04 Pratham-Mishra04 marked this pull request as ready for review July 29, 2025 13:44
@Pratham-Mishra04 Pratham-Mishra04 force-pushed the 07-29-feat_added_toggle_for_include_raw_response branch 2 times, most recently from 71ad22f to eb6ae77 Compare July 29, 2025 14:17
Copy link
Copy Markdown
Contributor

@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: 1

🔭 Outside diff range comments (2)
core/providers/ollama.go (1)

80-85: Missing field initialization in constructor.

The sendBackRawResponse field is declared in the struct but not initialized from the configuration. This will cause the field to default to false regardless of the user's configuration setting.

Add the missing field initialization:

 return &OllamaProvider{
 	logger:        logger,
 	client:        client,
 	streamClient:  streamClient,
 	networkConfig: config.NetworkConfig,
+	sendBackRawResponse: config.SendBackRawResponse,
 }, nil
core/providers/sgl.go (1)

80-85: Missing field initialization in constructor.

The sendBackRawResponse field is declared in the struct but not initialized from the configuration, causing the same issue as in the Ollama provider.

Add the missing field initialization:

 return &SGLProvider{
 	logger:        logger,
 	client:        client,
 	streamClient:  streamClient,
 	networkConfig: config.NetworkConfig,
+	sendBackRawResponse: config.SendBackRawResponse,
 }, nil
♻️ Duplicate comments (1)
ui/components/config/provider-form.tsx (1)

924-937: Fix accessibility issue with the label element.

The label element needs proper association with the control for screen readers.

-                            <label className="text-sm font-medium">Include Raw Response</label>
+                            <label htmlFor="sendBackRawResponse" className="text-sm font-medium">Include Raw Response</label>
                            <p className="text-muted-foreground text-xs">
                              Include the raw provider response alongside the parsed response for debugging and advanced use cases
                            </p>
                          </div>
                          <Switch
+                           id="sendBackRawResponse"
                            checked={sendBackRawResponse}
                            onCheckedChange={(checked) => updateField('sendBackRawResponse', checked)}
                          />

Comment thread core/providers/mistral.go
@Pratham-Mishra04 Pratham-Mishra04 force-pushed the 07-29-feat_added_toggle_for_include_raw_response branch from eb6ae77 to 2fe3ada Compare July 29, 2025 15:30
Copy link
Copy Markdown
Contributor

@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: 3

♻️ Duplicate comments (2)
ui/components/config/provider-form.tsx (1)

924-937: Fix accessibility issue with the label element.

The label element needs proper association with the control for screen readers.

-                            <label className="text-sm font-medium">Include Raw Response</label>
+                            <label htmlFor="sendBackRawResponse" className="text-sm font-medium">Include Raw Response</label>
                            <p className="text-muted-foreground text-xs">
                              Include the raw provider response alongside the parsed response for debugging and advanced use cases
                            </p>
                          </div>
                          <Switch
+                           id="sendBackRawResponse"
                            checked={sendBackRawResponse}
                            onCheckedChange={(checked) => updateField('sendBackRawResponse', checked)}
                          />
core/providers/mistral.go (1)

33-51: Response pool refactoring already approved in previous review.

Also applies to: 81-81

Comment thread core/providers/ollama.go
Comment thread core/providers/openai.go
Comment thread core/providers/sgl.go
@Pratham-Mishra04 Pratham-Mishra04 force-pushed the 07-29-feat_added_toggle_for_include_raw_response branch from 2fe3ada to 80f516a Compare July 29, 2025 15:57
Copy link
Copy Markdown
Contributor

@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: 1

🔭 Outside diff range comments (2)
core/providers/openai.go (2)

170-176: Returning a pooled object after defer release causes use-after-recycle

response is released back to openAIResponsePool by the deferred call before the caller receives it, so the caller will read a struct that may already be reused or zeroed by another goroutine – classic data corruption bug.

- response := acquireOpenAIResponse()
- defer releaseOpenAIResponse(response)
+response := acquireOpenAIResponse()
+// Do **not** release here; the caller now owns the object.

If you want pooling without corruption, release only in paths where the object is not returned, or redesign to copy the data into a fresh struct before release.


857-876: Avoid double unmarshal when raw response is disabled

responseBody is unmarshaled into rawResponse even when sendBackRawResponse is false, incurring unnecessary CPU cost.

- // Parse raw response for RawResponse field
- var rawResponse interface{}
- if err := sonic.Unmarshal(responseBody, &rawResponse); err != nil {
-   return nil, newBifrostOperationError(schemas.ErrProviderDecodeRaw, err, schemas.OpenAI)
- }
+ var rawResponse interface{}
+ if provider.sendBackRawResponse {
+   if err := sonic.Unmarshal(responseBody, &rawResponse); err != nil {
+     return nil, newBifrostOperationError(schemas.ErrProviderDecodeRaw, err, schemas.OpenAI)
+   }
+ }

Then keep the existing conditional assignment.

♻️ Duplicate comments (2)
ui/components/config/provider-form.tsx (1)

924-937: Fix accessibility issue with the label element.

The label element needs proper association with the Switch control for screen readers.

Apply this fix to resolve the accessibility issue:

-                            <label className="text-sm font-medium">Include Raw Response</label>
+                            <label htmlFor="sendBackRawResponse" className="text-sm font-medium">Include Raw Response</label>
                            <p className="text-muted-foreground text-xs">
                              Include the raw provider response alongside the parsed response for debugging and advanced use cases
                            </p>
                          </div>
                          <Switch
+                           id="sendBackRawResponse"
                            checked={sendBackRawResponse}
                            onCheckedChange={(checked) => updateField('sendBackRawResponse', checked)}
                          />
core/providers/mistral.go (1)

33-51: Good refactoring to unify response handling.

The migration from provider-specific MistralResponse to the shared schemas.BifrostResponse reduces code duplication and improves consistency across providers.

Comment thread core/providers/bedrock.go
coderabbitai[bot]
coderabbitai Bot previously approved these changes Jul 29, 2025
akshaydeo
akshaydeo previously approved these changes Jul 29, 2025
Copy link
Copy Markdown
Contributor

akshaydeo commented Jul 29, 2025

Merge activity

  • Jul 29, 5:14 PM UTC: A user started a stack merge that includes this pull request via Graphite.
  • Jul 29, 5:15 PM UTC: Graphite rebased this pull request as part of a merge.
  • Jul 29, 5:17 PM UTC: Graphite couldn't merge this PR because it was not satisfying all requirements (PR does not have required approvals).

@akshaydeo akshaydeo changed the base branch from 07-29-enhancement_serialisation_optimisations to graphite-base/196 July 29, 2025 17:14
@akshaydeo akshaydeo changed the base branch from graphite-base/196 to main July 29, 2025 17:14
@akshaydeo akshaydeo dismissed stale reviews from coderabbitai[bot] and themself July 29, 2025 17:14

The base branch was changed.

@akshaydeo akshaydeo force-pushed the 07-29-feat_added_toggle_for_include_raw_response branch from 80f516a to 01ade14 Compare July 29, 2025 17:15
Copy link
Copy Markdown
Contributor

@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: 1

🔭 Outside diff range comments (1)
core/providers/mistral.go (1)

288-288: Embedding method doesn't respect the sendBackRawResponse flag.

The Embedding method always includes the raw response in line 288, which is inconsistent with the PR objectives and the implementation in other methods. It should conditionally set the raw response based on provider.sendBackRawResponse.

Apply this fix:

- ExtraFields: schemas.BifrostResponseExtraFields{
-     Provider:    schemas.Mistral,
-     RawResponse: rawResponse,
- },
+ ExtraFields: schemas.BifrostResponseExtraFields{
+     Provider: schemas.Mistral,
+ },

Then after creating the response, add:

+ if provider.sendBackRawResponse {
+     bifrostResponse.ExtraFields.RawResponse = rawResponse
+ }
♻️ Duplicate comments (2)
core/providers/bedrock.go (1)

841-848: Consider using handleProviderResponse utility for consistency.

While the current implementation works correctly, it's inconsistent with the ChatCompletion method which uses the handleProviderResponse utility function. For consistency across the codebase, consider refactoring this to use the same utility pattern.

Apply this diff to align with the consistent pattern:

-	// Parse raw response if enabled
-	if provider.sendBackRawResponse {
-		var rawResponse interface{}
-		if err := sonic.Unmarshal(body, &rawResponse); err != nil {
-			return nil, newBifrostOperationError("error parsing raw response", err, schemas.Bedrock)
-		}
-		bifrostResponse.ExtraFields.RawResponse = rawResponse
+	// Handle raw response if enabled
+	rawResponse, bifrostErr := handleProviderResponse(body, &struct{}{}, provider.sendBackRawResponse)
+	if bifrostErr != nil {
+		return nil, bifrostErr
+	}
+	if provider.sendBackRawResponse {
+		bifrostResponse.ExtraFields.RawResponse = rawResponse
	}
ui/components/config/provider-form.tsx (1)

924-937: Fix accessibility issue with the label element.

The label element needs proper association with the control for screen readers.

-                            <label className="text-sm font-medium">Include Raw Response</label>
+                            <label htmlFor="sendBackRawResponse" className="text-sm font-medium">Include Raw Response</label>
                            <p className="text-muted-foreground text-xs">
                              Include the raw provider response alongside the parsed response for debugging and advanced use cases
                            </p>
                          </div>
                          <Switch
+                           id="sendBackRawResponse"
                            checked={sendBackRawResponse}
                            onCheckedChange={(checked) => updateField('sendBackRawResponse', checked)}
                          />

Comment thread ui/components/config/provider-form.tsx
@akshaydeo akshaydeo merged commit 10a8067 into main Jul 29, 2025
2 checks passed
@akshaydeo akshaydeo deleted the 07-29-feat_added_toggle_for_include_raw_response branch August 31, 2025 17:28
akshaydeo pushed a commit that referenced this pull request Nov 17, 2025
# Make Raw Response Optional in Provider Responses

This PR adds a configuration option to control whether raw provider responses are included in Bifrost responses. Previously, raw responses were always included, which could increase response size and bandwidth usage unnecessarily.

Key changes:
- Added `send_back_raw_response` boolean flag to provider configuration
- Modified all providers to respect this setting when processing responses
- Updated the UI to include a toggle for this option in the provider configuration form
- Optimized response handling to avoid unnecessary JSON parsing when raw responses aren't needed
- Standardized response object pools across providers to use the common `BifrostResponse` type

This change improves performance by avoiding unnecessary JSON parsing and reduces response sizes when raw responses aren't needed, while maintaining backward compatibility for users who rely on the raw response data.
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