Skip to content

Conversation

Pratham-Mishra04
Copy link
Collaborator

@Pratham-Mishra04 Pratham-Mishra04 commented Jul 29, 2025

Refactor Provider APIs with Type-Safe Structs

This PR introduces a major refactoring of the provider APIs to use type-safe structs instead of generic maps. The changes improve type safety, performance, and maintainability across the codebase.

  • Created a new api package in core/schemas/api to house provider-specific API types
  • Moved Anthropic, OpenAI, and Bedrock API types from providers to the new package
  • Updated all providers to use the new typed structs instead of generic maps
  • Fixed a bug in MCP tools handling by changing *[]schemas.Tool to []schemas.Tool
  • Switched from using json to sonic for better performance
  • Added proper JSON marshaling with conflict detection for extra parameters
  • Improved model detection with shared utility functions

These changes make the code more maintainable and type-safe while preserving backward compatibility with existing API contracts.

Copy link
Contributor

coderabbitai bot commented Jul 29, 2025

Summary by CodeRabbit

  • New Features

    • Added support for specifying the number of completions and log probabilities in model parameters.
    • Enhanced provider detection for model strings, improving routing and compatibility.
  • Refactor

    • Unified and centralized API request and response types for OpenAI, Anthropic, and Bedrock providers, reducing duplication and improving type safety.
    • Streamlined request construction and parameter handling for all major providers, resulting in more consistent and maintainable code.
    • Updated logging and integration structures to use direct slices for tool definitions, simplifying data access.
  • Bug Fixes

    • Improved handling of tool and stop sequence parameters, eliminating issues related to pointer dereferencing.
  • Chores

    • Updated dependencies and internal module references to improve build stability and performance.

Walkthrough

This change centralizes all OpenAI and Anthropic API request/response types and model string parsing utilities into new, strongly typed core/schemas/api submodules. All providers and HTTP transport integrations are refactored to use these shared types and builder functions, removing local type definitions and map-based request construction. Model parameter fields are also updated for direct slice usage.

Changes

Cohort / File(s) Change Summary
Anthropic/OpenAI API Schema Centralization
core/schemas/api/anthropic.go, core/schemas/api/openai.go, core/schemas/api/bedrock.go, core/schemas/api/utils.go
Introduces comprehensive, strongly typed Go structs and JSON logic for Anthropic, OpenAI, and Bedrock APIs, including requests, responses, streaming, tools, and utility/model parsing functions.
Provider Refactors to Centralized API Types
core/providers/anthropic.go, core/providers/openai.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/sgl.go, core/providers/vertex.go, core/providers/utils.go
Removes local API type definitions, replaces map-based request construction with builder functions returning shared API structs, updates streaming handlers and response parsing to use centralized types, and adjusts tool/parameter handling for new struct layouts.
Model Parameter Struct Update
core/schemas/bifrost.go, core/mcp.go
Changes ModelParameters.Tools and StopSequences from pointer-to-slice to direct slices, adds new fields (N, Logprobs), and updates all access patterns accordingly.
Transport Layer Integration Refactor
transports/bifrost-http/integrations/anthropic/router.go, transports/bifrost-http/integrations/anthropic/types.go, transports/bifrost-http/integrations/openai/router.go, transports/bifrost-http/integrations/openai/types.go, transports/bifrost-http/integrations/genai/types.go, transports/bifrost-http/integrations/litellm/router.go, transports/bifrost-http/integrations/utils.go
Removes all local OpenAI/Anthropic type definitions and conversion methods, updates routers and converters to use shared API types and conversion functions, and delegates model/provider parsing to the centralized utility package.
Dependency and Module Updates
transports/go.mod
Adds a local replace directive for the core module, updates indirect dependencies, and removes unused ones.
Logging Plugin Update
transports/bifrost-http/plugins/logging/main.go
Changes Tools field from pointer to slice to direct slice in logging structs.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant HTTPTransport
    participant APIBuilder
    participant Provider
    participant ExternalAPI

    Client->>HTTPTransport: Sends request (e.g., chat completion)
    HTTPTransport->>APIBuilder: Convert to shared API struct
    APIBuilder->>Provider: Passes typed API struct
    Provider->>ExternalAPI: Marshals struct, sends HTTP request
    ExternalAPI-->>Provider: Returns typed JSON response
    Provider->>APIBuilder: Unmarshals to shared API struct
    APIBuilder->>HTTPTransport: Converts to Bifrost response
    HTTPTransport->>Client: Returns response
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~90 minutes

Possibly related PRs

Suggested reviewers

  • danpiths
  • akshaydeo

Poem

In fields of structs, the rabbits play,
Centralizing types in a typed array.
No more pointer hops or scattered maps,
Just shared API schemas in neat little wraps.
With every hop, the code grows bright—
Unified, strong, and typed just right!
🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch test/request-typed-structs

🪧 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
Collaborator Author

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

Copy link
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: 7

Index *int `json:"index,omitempty"`
ContentBlock *AnthropicContentBlock `json:"content_block,omitempty"`
Delta *AnthropicDelta `json:"delta,omitempty"`
Usage *schemas.LLMUsage `json:"usage,omitempty"`
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Inconsistent usage type between streaming and non-streaming responses.

AnthropicStreamEvent and AnthropicStreamMessage use schemas.LLMUsage for the usage field, while AnthropicTextResponse and AnthropicChatResponse use inline structs. This inconsistency could lead to confusion and mapping issues.

Consider using a consistent approach - either use schemas.LLLUsage everywhere or define a separate AnthropicUsage type and use it consistently across all response types.

Also applies to: 83-83

🤖 Prompt for AI Agents
In core/schemas/api/anthropic.go at lines 69 and 83, the usage field types are
inconsistent between streaming and non-streaming response structs, causing
potential confusion and mapping issues. To fix this, define a single consistent
usage type—either use schemas.LLMUsage everywhere or create a new AnthropicUsage
type—and update all response structs to use this unified type for their usage
fields.

Comment on lines +144 to +148
type URLTypeInfo struct {
Type ImageContentType
MediaType *string
DataURLWithoutPrefix *string // URL without the prefix (eg data:image/png;base64,iVBORw0KGgo...)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Potential redundancy in image handling types.

There are multiple types handling image content:

  1. URLTypeInfo (lines 144-148) - contains type, media type, and data URL info
  2. AnthropicImageSource (lines 99-104) - similar structure for Anthropic API
  3. AnthropicImageContent (lines 158-162) - another image type with URL and media type

This redundancy could lead to confusion. Consider consolidating these types or clearly documenting their distinct purposes.

Also applies to: 158-162

🤖 Prompt for AI Agents
In core/schemas/api/anthropic.go around lines 99-104, 144-148, and 158-162,
there are multiple similar types handling image content (URLTypeInfo,
AnthropicImageSource, AnthropicImageContent) which creates redundancy and
potential confusion. Review these types to identify overlapping fields and
purposes, then consolidate them into fewer, well-documented types that clearly
differentiate their roles or unify them if they serve the same function. Add
comments to clarify any distinctions if consolidation is not possible.

Comment on lines 217 to 253
// BedrockChatRequest represents the unified request structure for Bedrock's chat completion API.
// This typed struct optimizes JSON marshalling performance and supports various models.
type BedrockChatRequest struct {
Messages []BedrockMistralChatMessage `json:"messages"` // Formatted messages
Tools []BedrockAnthropicToolCall `json:"tools,omitempty"` // Optional tool definitions
ToolChoice *string `json:"tool_choice,omitempty"` // Optional tool choice ("auto", "any", "none")
MaxTokens *int `json:"max_tokens,omitempty"` // Maximum tokens to generate
Temperature *float64 `json:"temperature,omitempty"` // Sampling temperature
TopP *float64 `json:"top_p,omitempty"` // Nucleus sampling
ExtraParams map[string]interface{} `json:"-"`
}

func (r *BedrockChatRequest) MarshalJSON() ([]byte, error) {
result := make(map[string]interface{}, 6+len(r.ExtraParams))

result["messages"] = r.Messages

if r.MaxTokens != nil {
result["max_tokens"] = *r.MaxTokens
}
if r.Temperature != nil {
result["temperature"] = *r.Temperature
}
if r.TopP != nil {
result["top_p"] = *r.TopP
}
if r.Tools != nil {
result["tools"] = r.Tools
}
if r.ToolChoice != nil {
result["tool_choice"] = *r.ToolChoice
}

maps.Copy(result, r.ExtraParams)

return sonic.Marshal(result)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider clarifying the provider-specific field usage.

The BedrockChatRequest struct mixes Mistral-specific message types with Anthropic-specific tool types. While this may work for Bedrock's unified API, it could be confusing for maintainers. Consider adding documentation to clarify which fields are used with which model families.

 // BedrockChatRequest represents the unified request structure for Bedrock's chat completion API.
 // This typed struct optimizes JSON marshalling performance and supports various models.
 type BedrockChatRequest struct {
-	Messages    []BedrockMistralChatMessage `json:"messages"`              // Formatted messages
-	Tools       []BedrockAnthropicToolCall  `json:"tools,omitempty"`       // Optional tool definitions
+	Messages    []BedrockMistralChatMessage `json:"messages"`              // Formatted messages (used by all models)
+	Tools       []BedrockAnthropicToolCall  `json:"tools,omitempty"`       // Optional tool definitions (Anthropic models only)
 	ToolChoice  *string                     `json:"tool_choice,omitempty"` // Optional tool choice ("auto", "any", "none")
🤖 Prompt for AI Agents
In core/schemas/api/bedrock.go around lines 217 to 253, the BedrockChatRequest
struct uses Mistral-specific message types and Anthropic-specific tool types
together, which may confuse maintainers. Add clear comments above each field to
specify which model family or provider the field is intended for, clarifying
usage for future readers and maintainers.

* feat: new api package and updated providers and integrations to use typed structs

* feat: added bedrock types to apo

* fix: switched from json to sonic
@Pratham-Mishra04 Pratham-Mishra04 force-pushed the test/request-typed-structs branch from 90a3b20 to 0332637 Compare July 29, 2025 20:11
@Pratham-Mishra04 Pratham-Mishra04 changed the title consolidated all provider interfaces logic refactor: change Tools from pointer to slice for better performance Jul 29, 2025
@Pratham-Mishra04 Pratham-Mishra04 changed the title refactor: change Tools from pointer to slice for better performance refactor: consolidated all provider request schemas Jul 29, 2025
Copy link
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: 12

🔭 Outside diff range comments (4)
transports/bifrost-http/integrations/genai/types.go (2)

348-385: Ensure Params is never nil before assigning Tools

bifrostReq.Params is assumed non-nil when assigning Tools, but that only holds if convertGenerationConfigToParams was called earlier.
Make the guarantee explicit to avoid future regressions.

-  if len(tools) > 0 {
-    bifrostReq.Params.Tools = tools
-  }
+  if len(tools) > 0 {
+    if bifrostReq.Params == nil { // defensive – cheap
+      bifrostReq.Params = &schemas.ModelParameters{}
+    }
+    bifrostReq.Params.Tools = tools
+  }

398-405: Minor: skip allocating params when nothing is set

convertGenerationConfigToParams always allocates a struct even when every field is zero.
Returning nil in that case would save an unnecessary allocation and keep the calling code simpler.
Not critical, but worth considering.

transports/bifrost-http/plugins/logging/main.go (2)

226-231: Compilation error – for range 1000 is invalid

range cannot iterate over an integer literal. This will not compile.

-// Prewarm the pools for better performance at startup
-for range 1000 {
+// Pre-warm the pools for better performance at startup
+for i := 0; i < 1000; i++ {
     plugin.logMsgPool.Put(&LogMessage{})
     plugin.updateDataPool.Put(&UpdateLogData{})
     plugin.streamDataPool.Put(&StreamUpdateData{})
 }

519-522: Redundant nil-check on slice

req.Params.Tools is now a slice, not a pointer.
The nil-check still works but len(req.Params.Tools) > 0 would better convey intent (non-empty list).

♻️ Duplicate comments (7)
core/schemas/api/bedrock.go (1)

217-253: Add documentation to clarify provider-specific field usage.

The struct mixes Mistral-specific message types with Anthropic-specific tool types, which could be confusing for maintainers. The past review comment correctly identified this issue.

Consider adding comprehensive documentation:

 // BedrockChatRequest represents the unified request structure for Bedrock's chat completion API.
 // This typed struct optimizes JSON marshalling performance and supports various models.
+//
+// Note: This struct serves as a unified interface for multiple model families:
+// - Messages: Uses Mistral format but is compatible with all Bedrock chat models
+// - Tools: Currently only supported by Anthropic models (Claude)
+// - Other providers (Llama, etc.) will ignore unsupported fields
 type BedrockChatRequest struct {
core/providers/anthropic.go (1)

21-23: Good fix for the MaxTokens default value issue.

The introduction of DEFAULT_MAX_TOKENS = 4096 properly addresses the previous concern about setting MaxTokens to 0. This ensures that Anthropic's API always receives a valid positive value for max_tokens, preventing potential API errors.

Also applies to: 139-143, 240-243

core/schemas/api/anthropic.go (5)

32-36: Extract inline Usage struct for consistency.

The inline Usage struct should be replaced with the already-defined AnthropicUsage type to improve consistency and reduce duplication.


44-51: Extract complex inline Content struct.

The inline Content struct is complex with many fields. Consider extracting it as a named type for better maintainability.


55-58: Replace inline Usage struct with AnthropicUsage type.

Similar to the previous Usage struct, this should use the already-defined AnthropicUsage type.


69-69: Inconsistent usage types between streaming and non-streaming responses.

Streaming responses use schemas.LLMUsage while non-streaming responses use inline structs. This inconsistency could lead to confusion and mapping issues.

Also applies to: 83-83


158-162: Potentially unused AnthropicImageContent type.

The AnthropicImageContent type appears to be redundant as it's not used in the codebase. AnthropicImageSource serves the same purpose for the Anthropic API.

Consider removing this type if it's not used elsewhere:

-type AnthropicImageContent struct {
-	Type      ImageContentType `json:"type"`
-	URL       string           `json:"url"`
-	MediaType string           `json:"media_type,omitempty"`
-}

Comment on lines +188 to +190
if input.VoiceConfig.Voice == nil {
return nil
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider returning an error instead of nil.

Returning nil when voice is missing could cause nil pointer dereferences in callers. Consider returning an error to make the validation failure explicit.

-func buildOpenAISpeechRequest(model string, input *schemas.SpeechInput, params *schemas.ModelParameters) *api.OpenAISpeechRequest {
+func buildOpenAISpeechRequest(model string, input *schemas.SpeechInput, params *schemas.ModelParameters) (*api.OpenAISpeechRequest, error) {
 	// Set default response format if not provided
 	responseFormat := input.ResponseFormat
 	if responseFormat == "" {
 		responseFormat = "mp3"
 	}
 
 	// Validate voice is provided
 	if input.VoiceConfig.Voice == nil {
-		return nil
+		return nil, fmt.Errorf("voice is required for speech synthesis")
 	}

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In core/providers/openai.go around lines 188 to 190, the function currently
returns nil when input.VoiceConfig.Voice is nil, which can lead to nil pointer
dereferences in callers. Modify the code to return an explicit error indicating
that the voice configuration is missing instead of returning nil. This will make
the validation failure clear and prevent potential runtime panics.

EncodingFormat *string `json:"encoding_format,omitempty"` // Format for embedding output (e.g., "float", "base64")
Dimensions *int `json:"dimensions,omitempty"` // Number of dimensions for embedding output
User *string `json:"user,omitempty"` // User identifier for tracking
User *string `json:"user,omitempty"`
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Removed comment on User field

The comment for the User field was removed. If this was intentional, consider whether the field is self-explanatory or if documentation should be maintained elsewhere.

🤖 Prompt for AI Agents
In core/schemas/bifrost.go at line 177, the comment for the User field was
removed. Review whether the User field is self-explanatory; if not, add a clear
and concise comment describing its purpose to maintain code documentation and
clarity.

Copy link
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: 2

♻️ Duplicate comments (5)
core/providers/openai.go (1)

188-190: Nil return is properly handled by callers

While returning an error directly would be cleaner, the current implementation is acceptable since all callers (lines 630 and 696) check for nil and return appropriate errors.

core/schemas/api/bedrock.go (1)

241-251: Consider clarifying the provider-specific field usage.

The BedrockChatRequest struct mixes Mistral-specific message types with Anthropic-specific tool types. While this may work for Bedrock's unified API, it could be confusing for maintainers. Consider adding documentation to clarify which fields are used with which model families.

 // BedrockChatRequest represents the unified request structure for Bedrock's chat completion API.
 // This typed struct optimizes JSON marshalling performance and supports various models.
 type BedrockChatRequest struct {
-	Messages    []BedrockMistralChatMessage `json:"messages"`              // Formatted messages
-	Tools       []BedrockAnthropicToolCall  `json:"tools,omitempty"`       // Optional tool definitions
+	Messages    []BedrockMistralChatMessage `json:"messages"`              // Formatted messages (used by all models)
+	Tools       []BedrockAnthropicToolCall  `json:"tools,omitempty"`       // Optional tool definitions (Anthropic models only)
 	ToolChoice  *string                     `json:"tool_choice,omitempty"` // Optional tool choice ("auto", "any", "none")
core/providers/anthropic.go (1)

276-291: Potential nil pointer dereference when accessing Function.Name.

At line 286, the code accesses params.ToolChoice.ToolChoiceStruct.Function.Name without checking if Function is nil first. This could cause a panic if Function is not set.

Apply this fix:

 } else if params.ToolChoice.ToolChoiceStruct != nil {
 	toolChoice := &api.AnthropicToolChoice{
 		Type: params.ToolChoice.ToolChoiceStruct.Type,
 	}
-	if params.ToolChoice.ToolChoiceStruct.Function.Name != "" {
+	if params.ToolChoice.ToolChoiceStruct.Function != nil && params.ToolChoice.ToolChoiceStruct.Function.Name != "" {
 		toolChoice.Name = &params.ToolChoice.ToolChoiceStruct.Function.Name
 	}
 	request.ToolChoice = toolChoice
 }
core/schemas/api/anthropic.go (2)

57-80: Inconsistent usage types between streaming and non-streaming responses.

The streaming structs (AnthropicStreamEvent and AnthropicStreamMessage) use schemas.LLMUsage for their usage fields, while non-streaming responses (AnthropicTextResponse and AnthropicChatResponse) use AnthropicUsage. This inconsistency could lead to confusion and mapping issues when converting between formats.

Consider using a consistent approach - either use AnthropicUsage everywhere or schemas.LLMUsage everywhere.


94-158: Multiple redundant image handling types need consolidation or clarification.

There are three similar types handling image content:

  1. AnthropicImageSource - contains type, media type, data, and URL
  2. URLTypeInfo - contains type, media type, and data URL info
  3. AnthropicImageContent - contains type, URL, and media type

This redundancy could lead to confusion about which type to use in different contexts. Consider:

  • Consolidating these into fewer types if they serve the same purpose
  • Adding clear documentation to distinguish their specific use cases
  • Using type aliases if they represent the same data in different contexts

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