Skip to content

feat: improve plugin pipeline and add custom base URLs to providers#79

Merged
akshaydeo merged 1 commit intomainfrom
06-13-enhancement_base_url_support_added_to_providers
Jun 14, 2025
Merged

feat: improve plugin pipeline and add custom base URLs to providers#79
akshaydeo merged 1 commit intomainfrom
06-13-enhancement_base_url_support_added_to_providers

Conversation

@Pratham-Mishra04
Copy link
Copy Markdown
Collaborator

Add Custom Base URL Support for OpenAI, Anthropic, and Cohere Providers

This PR adds support for configuring custom base URLs for the OpenAI, Anthropic, and Cohere providers. This enhancement allows users to:

  • Connect to alternative API endpoints or self-hosted instances
  • Use compatible API proxies
  • Support enterprise deployments with custom domains

The implementation:

  • Adds a base_url field to the NetworkConfig struct
  • Modifies each provider to use the configured base URL or fall back to the default if not specified
  • Ensures proper URL handling by trimming trailing slashes from configured URLs
  • Maintains the API version for Anthropic as a provider property

For Anthropic, the default remains https://api.anthropic.com, for OpenAI it's https://api.openai.com, and for Cohere it's https://api.cohere.ai.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jun 13, 2025

Caution

Review failed

The pull request is closed.

Summary by CodeRabbit

  • New Features

    • Added support for configuring custom API base URLs for OpenAI, Anthropic, and Cohere providers.
  • Documentation

    • Improved plugin system documentation, clarifying plugin lifecycle, error handling, and interface requirements.
    • Updated example plugin implementations and best practices in the documentation.
  • Refactor

    • Enhanced plugin execution tracking and error handling for improved reliability and clarity.

Summary by CodeRabbit

  • New Features
    • Added support for customizing the API base URL for OpenAI, Anthropic, and Cohere providers via configuration.
  • Documentation
    • Clarified that the new base URL configuration option is available only for OpenAI, Anthropic, and Cohere providers.
    • Expanded and clarified plugin interface lifecycle, error handling, and hook semantics in documentation and code comments.
    • Updated plugin interface in docs with new GetName() method and enhanced PostHook signature.
    • Revised example plugins and guidelines to reflect new plugin interface and lifecycle semantics.
  • Internal Improvements
    • Changed PluginPipeline to track executed PreHooks by count instead of indices.
    • Updated RunPreHooks and RunPostHooks methods for improved defensive error handling and clearer plugin execution logic.
    • Enhanced comments in plugin interface code to clarify hook behavior and error handling.

Walkthrough

The changes introduce configurable base URL support for OpenAI, Anthropic, and Cohere providers by adding a BaseURL field to their configuration structs and provider implementations. Constructors and API request methods are updated to use this field, allowing endpoint overrides. Anthropic also centralizes its API version as a configurable field. Additionally, the plugin system's lifecycle and error handling semantics were clarified and formalized in documentation and code comments, with interface updates in docs and example plugins. The plugin pipeline's tracking and error handling logic were refined for robustness.

Changes

File(s) Change Summary
core/providers/anthropic.go Added baseURL and apiVersion fields to AnthropicProvider; updated constructor and API calls to use them.
core/providers/cohere.go Added baseURL field to CohereProvider; updated constructor and API calls to use it.
core/providers/openai.go Added baseURL field to OpenAIProvider; updated constructor and API calls to use it.
core/schemas/provider.go Added optional BaseURL field to NetworkConfig struct with documentation comment.
core/bifrost.go Changed PluginPipeline.preHookRan slice to executedPreHooks int; updated RunPreHooks and RunPostHooks for error handling and plugin execution tracking.
core/schemas/plugin.go Expanded and clarified comments on Plugin interface and hooks; no signature changes.
docs/plugins.md Updated plugin interface example with GetName() method and new PostHook signature; enhanced lifecycle and error handling docs; revised example plugins and guidelines.

Sequence Diagram(s)

sequenceDiagram
    participant Config as ProviderConfig
    participant Provider as Provider (OpenAI/Anthropic/Cohere)
    participant API as API Endpoint

    Config->>Provider: Initialize with NetworkConfig.BaseURL
    Provider->>Provider: Set baseURL (default if empty)
    User->>Provider: ChatCompletion/TextCompletion request
    Provider->>API: Send request to baseURL + endpoint path
    API-->>Provider: Return response
    Provider-->>User: Return completion result
Loading

Possibly related PRs

Suggested reviewers

  • akshaydeo
  • danpiths

Poem

🐇✨
Three providers leap with URLs new,
Anthropic, Cohere, OpenAI too.
Base paths no longer fixed in stone,
Configured endpoints now their own.
Plugins dance with hooks refined,
Errors caught and well-defined.
CodeRabbit hops, with joy aligned! 🐰🚀


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 11585c7 and 43e879a.

📒 Files selected for processing (7)
  • core/bifrost.go (8 hunks)
  • core/providers/anthropic.go (5 hunks)
  • core/providers/cohere.go (3 hunks)
  • core/providers/openai.go (4 hunks)
  • core/schemas/plugin.go (2 hunks)
  • core/schemas/provider.go (1 hunks)
  • docs/plugins.md (9 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Commit Unit Tests in branch 06-13-enhancement_base_url_support_added_to_providers
  • Post Copyable Unit Tests in Comment

🪧 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 auto-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 Jun 13, 2025

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: 6

🔭 Outside diff range comments (2)
core/schemas/provider.go (1)

30-35: 🧹 Nitpick (assertive)

Comment style & serialization nitpick

  1. Missing space after the // in the field comment (//BaseURL// BaseURL).
  2. Consider adding omitempty to the tag to avoid serialising empty strings:
- //BaseURL is only supported for OpenAI, Anthropic and Cohere providers
- BaseURL string `json:"base_url"` // Base URL for the provider (optional)
+ // BaseURL is only supported for OpenAI, Anthropic and Cohere providers.
+ BaseURL string `json:"base_url,omitempty"` // Base URL for the provider (optional)

This keeps JSON payloads clean and stays consistent with the other optional fields.

core/providers/cohere.go (1)

349-353: 🧹 Nitpick (assertive)

Minor: fmt.Sprintf makes the path clearer

Purely readability; avoid manual concatenation:

-req.SetRequestURI(provider.baseURL + "/v1/chat")
+req.SetRequestURI(fmt.Sprintf("%s/v1/chat", provider.baseURL))

Up to you – not blocking.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between db1a389 and 791c727.

📒 Files selected for processing (4)
  • core/providers/anthropic.go (5 hunks)
  • core/providers/cohere.go (3 hunks)
  • core/providers/openai.go (4 hunks)
  • core/schemas/provider.go (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
core/providers/anthropic.go (2)
core/schemas/logger.go (1)
  • Logger (18-35)
core/schemas/provider.go (1)
  • NetworkConfig (29-36)
core/providers/cohere.go (2)
core/schemas/logger.go (1)
  • Logger (18-35)
core/schemas/provider.go (1)
  • NetworkConfig (29-36)

Comment thread core/providers/cohere.go
Comment thread core/providers/cohere.go Outdated
Comment thread core/providers/anthropic.go
Comment thread core/providers/anthropic.go Outdated
Comment thread core/providers/openai.go Outdated
Comment thread core/providers/openai.go
@akshaydeo akshaydeo marked this pull request as ready for review June 13, 2025 07:10
Copy link
Copy Markdown

@cursor cursor Bot left a comment

Choose a reason for hiding this comment

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

✅ BugBot reviewed your changes and found no bugs!


BugBot free trial expires on June 17, 2025
You have used $0.00 of your $50.00 spend limit so far. Manage your spend limit in the Cursor dashboard.

Was this report helpful? Give feedback by reacting with 👍 or 👎

@Pratham-Mishra04 Pratham-Mishra04 force-pushed the 06-13-enhancement_base_url_support_added_to_providers branch 2 times, most recently from 29ce962 to 0ea6031 Compare June 13, 2025 18:54
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

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

115-119: ⚠️ Potential issue

Compilation blocker – cannot range over an int

for range config.ConcurrencyAndBufferSize.Concurrency { … } will not compile (cannot range over Concurrency).
Replace with an indexed loop:

- for range config.ConcurrencyAndBufferSize.Concurrency {
+ for i := 0; i < config.ConcurrencyAndBufferSize.Concurrency; i++ {
     cohereResponsePool.Put(&CohereChatResponse{})
     bifrostResponsePool.Put(&schemas.BifrostResponse{})
 }
core/providers/anthropic.go (1)

141-145: ⚠️ Potential issue

Compilation blocker – cannot range over an int

Same issue as in Cohere provider.

- for range config.ConcurrencyAndBufferSize.Concurrency {
+ for i := 0; i < config.ConcurrencyAndBufferSize.Concurrency; i++ {
     anthropicTextResponsePool.Put(&AnthropicTextResponse{})
     anthropicChatResponsePool.Put(&AnthropicChatResponse{})
     bifrostResponsePool.Put(&schemas.BifrostResponse{})
 }
core/providers/openai.go (1)

86-90: ⚠️ Potential issue

Compilation blocker – cannot range over an int

- for range config.ConcurrencyAndBufferSize.Concurrency {
+ for i := 0; i < config.ConcurrencyAndBufferSize.Concurrency; i++ {
     openAIResponsePool.Put(&OpenAIResponse{})
     bifrostResponsePool.Put(&schemas.BifrostResponse{})
 }
core/bifrost.go (2)

351-358: ⚠️ Potential issue

min is undefined – compilation will fail

min is not part of the standard-library imports and no helper with that name exists in this file.
The call therefore causes an “undefined: min” compiler error.

-	backoff := min(config.NetworkConfig.RetryBackoffInitial*time.Duration(1<<uint(attempt)), config.NetworkConfig.RetryBackoffMax)
+	// Helper to choose the smaller duration
+	minDur := func(a, b time.Duration) time.Duration {
+		if a < b {
+			return a
+		}
+		return b
+	}
+	backoff := minDur(config.NetworkConfig.RetryBackoffInitial*time.Duration(1<<uint(attempt)),
+	                  config.NetworkConfig.RetryBackoffMax)

Add the helper locally (or move it to a shared util) to restore buildability.


633-639: 🛠️ Refactor suggestion

Incorrect PostHook count – may execute hooks that never ran a PreHook

RunPostHooks should receive only the number of plugins whose PreHook actually ran (preCount).
Passing len(bifrost.plugins) risks calling a PostHook whose PreHook short-circuited or errored out earlier.

-	resp, bifrostErr := pipeline.RunPostHooks(&ctx, result, nil, len(bifrost.plugins))
+	resp, bifrostErr := pipeline.RunPostHooks(&ctx, result, nil, preCount)

Repeat the same change for the error branch below.
Identical issue exists in tryChatCompletion (lines 757-763 & 765-772).

This keeps the Pre/Post symmetry the pipeline contract guarantees.

Also applies to: 645-652

♻️ Duplicate comments (3)
core/providers/cohere.go (1)

121-124: Base-URL normalisation repeated in every provider – consider a small helper (normalizeBaseURL) and/or embedding a common struct to DRY this up.

core/providers/anthropic.go (1)

150-160: API version hard-coded – still fixed to "2023-06-01". Exposing this via config (or env var) was discussed earlier; keeping it hard-coded forces a re-compile for every Anthropic upgrade.

core/providers/openai.go (1)

94-98: Repeated Base-URL trimming logic – consider extracting to a shared helper to avoid subtle drift between providers.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 29ce962 and 0ea6031.

📒 Files selected for processing (7)
  • core/bifrost.go (8 hunks)
  • core/providers/anthropic.go (5 hunks)
  • core/providers/cohere.go (3 hunks)
  • core/providers/openai.go (4 hunks)
  • core/schemas/plugin.go (2 hunks)
  • core/schemas/provider.go (1 hunks)
  • docs/plugins.md (9 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
core/providers/anthropic.go (2)
core/schemas/logger.go (1)
  • Logger (18-35)
core/schemas/provider.go (1)
  • NetworkConfig (29-36)
🪛 LanguageTool
docs/plugins.md

[uncategorized] ~172-~172: You might be missing the article “the” here.
Context: ...peline. - To invalidate a response, set result to nil and return a non-nil err. - Keep...

(AI_EN_LECTOR_MISSING_DETERMINER_THE)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Graphite / mergeability_check
🔇 Additional comments (1)
core/schemas/plugin.go (1)

19-27: Comments read clearly – no further action required
Only documentation was touched; wording accurately reflects the current implementation of the plugin pipeline.

Comment thread core/schemas/provider.go Outdated
Comment thread core/bifrost.go
Comment thread docs/plugins.md
@Pratham-Mishra04 Pratham-Mishra04 changed the title feat: add configurable base URL support for OpenAI, Anthropic and Cohere providers feat: improve plugin pipeline and add custom base URLs Jun 13, 2025
@Pratham-Mishra04 Pratham-Mishra04 changed the title feat: improve plugin pipeline and add custom base URLs feat: improve plugin pipeline and add custom base URLs to providers Jun 13, 2025
@Pratham-Mishra04 Pratham-Mishra04 force-pushed the 06-13-enhancement_base_url_support_added_to_providers branch from 0ea6031 to 11585c7 Compare June 13, 2025 19:05
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: 4

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

115-124: ⚠️ Potential issue

for range <int> is a compile-time error

range cannot iterate over an int; this will not build.

-// Pre-warm response pools
-for range config.ConcurrencyAndBufferSize.Concurrency {
+// Pre-warm response pools
+for i := 0; i < config.ConcurrencyAndBufferSize.Concurrency; i++ {

Apply the same fix in other providers that copied this pattern.


349-353: 🧹 Nitpick (assertive)

Robust URI construction

String concatenation can mis-behave if users pass a path segment in base_url.
Prefer url.JoinPath (Go 1.19+) for safety:

-req.SetRequestURI(provider.baseURL + "/v1/chat")
+req.SetRequestURI(url.JoinPath(provider.baseURL, "v1", "chat"))
core/providers/openai.go (1)

150-154: 🧹 Nitpick (assertive)

Join paths instead of concatenation

-req.SetRequestURI(provider.baseURL + "/v1/chat/completions")
+req.SetRequestURI(url.JoinPath(provider.baseURL, "v1", "chat", "completions"))

Prevents accidental double slashes or duplicate /v1 segments.

core/bifrost.go (1)

633-641: 🧹 Nitpick (assertive)

Avoid re-shadowing resp with :=—use assignment for consistency

Inside both select blocks a new resp variable is created with :=, shadowing the previously declared resp. This is harmless but inconsistent (the error branch already uses =).

-        resp, bifrostErr := pipeline.RunPostHooks(&ctx, result, nil, len(bifrost.plugins))
+        resp, bifrostErr = pipeline.RunPostHooks(&ctx, result, nil, len(bifrost.plugins))

Replicate the same change in tryChatCompletion.

This tiny tweak eliminates unnecessary shadowing and keeps both branches symmetrical.

Also applies to: 755-761

♻️ Duplicate comments (2)
core/providers/anthropic.go (2)

150-154: Base-URL trimming duplication
Same note as Cohere/OpenAI – a shared helper would remove repetition.


159-160: apiVersion still hard-coded

Previous feedback about making the version configurable hasn’t been addressed.
Consider exposing it via config or env var so users can upgrade without recompiling.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0ea6031 and 11585c7.

📒 Files selected for processing (7)
  • core/bifrost.go (8 hunks)
  • core/providers/anthropic.go (5 hunks)
  • core/providers/cohere.go (3 hunks)
  • core/providers/openai.go (4 hunks)
  • core/schemas/plugin.go (2 hunks)
  • core/schemas/provider.go (1 hunks)
  • docs/plugins.md (9 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (4)
core/providers/anthropic.go (2)
core/schemas/logger.go (1)
  • Logger (18-35)
core/schemas/provider.go (1)
  • NetworkConfig (29-36)
core/providers/openai.go (2)
core/schemas/logger.go (1)
  • Logger (18-35)
core/schemas/provider.go (1)
  • NetworkConfig (29-36)
core/bifrost.go (3)
core/schemas/plugin.go (1)
  • Plugin (29-50)
core/schemas/logger.go (1)
  • Logger (18-35)
core/schemas/bifrost.go (2)
  • BifrostResponse (237-247)
  • BifrostError (365-371)
core/providers/cohere.go (2)
core/schemas/logger.go (1)
  • Logger (18-35)
core/schemas/provider.go (1)
  • NetworkConfig (29-36)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Graphite / mergeability_check
  • GitHub Check: Graphite / mergeability_check
🔇 Additional comments (2)
core/schemas/provider.go (1)

30-31: Field tag polish looks good

Space after // and omitempty flag correctly added. No further concerns.

core/schemas/plugin.go (1)

12-28: Documentation update is clear & thorough

The expanded comments accurately describe pipeline behaviour and edge-cases.
No action needed.

Comment thread core/providers/cohere.go
Comment thread core/providers/openai.go
Comment thread core/bifrost.go
Comment thread docs/plugins.md
@Pratham-Mishra04 Pratham-Mishra04 changed the base branch from 06-13-feat_plugin_handling_in_bifrost_enchancements to graphite-base/79 June 14, 2025 05:06
@Pratham-Mishra04 Pratham-Mishra04 force-pushed the 06-13-enhancement_base_url_support_added_to_providers branch from 11585c7 to 43e879a Compare June 14, 2025 05:06
@Pratham-Mishra04 Pratham-Mishra04 changed the base branch from graphite-base/79 to main June 14, 2025 05:06
@akshaydeo akshaydeo merged commit 86dce4f into main Jun 14, 2025
1 of 2 checks passed
@coderabbitai coderabbitai Bot requested a review from akshaydeo June 14, 2025 05:09
@akshaydeo akshaydeo deleted the 06-13-enhancement_base_url_support_added_to_providers branch August 31, 2025 17:31
akshaydeo added a commit that referenced this pull request Nov 17, 2025
)

# Add Custom Base URL Support for OpenAI, Anthropic, and Cohere Providers

This PR adds support for configuring custom base URLs for the OpenAI, Anthropic, and Cohere providers. This enhancement allows users to:

- Connect to alternative API endpoints or self-hosted instances
- Use compatible API proxies
- Support enterprise deployments with custom domains

The implementation:
- Adds a `base_url` field to the `NetworkConfig` struct
- Modifies each provider to use the configured base URL or fall back to the default if not specified
- Ensures proper URL handling by trimming trailing slashes from configured URLs
- Maintains the API version for Anthropic as a provider property

For Anthropic, the default remains `https://api.anthropic.com`, for OpenAI it's `https://api.openai.com`, and for Cohere it's `https://api.cohere.ai`.
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