Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add custom HTTP transport with headers for OpenAI client #245

Merged
merged 2 commits into from
Feb 17, 2025

Conversation

icereed
Copy link
Owner

@icereed icereed commented Feb 17, 2025

Closes #237

Summary by CodeRabbit

  • New Features

    • Enhanced API integration by including a custom header in outgoing requests, ensuring improved interaction with external services.
  • Bug Fixes

    • Added tests to verify the functionality of the custom HTTP client, ensuring it correctly includes the custom header in requests.

Copy link
Contributor

coderabbitai bot commented Feb 17, 2025

Walkthrough

This update modifies the main.go file by introducing a custom HTTP transport to include specific headers in OpenAI API requests. A new type headerTransport implementing the http.RoundTripper interface is added. The changes update the createLLM and createVisionLLM functions to utilize this custom transport, ensuring that each API request includes the "X-Title": "paperless-gpt" header. Additionally, the import block has been reorganized without affecting functionality.

Changes

File(s) Change Summary
main.go - Added headerTransport type with a RoundTrip method for custom header injection.
- Updated createLLM and createVisionLLM to use a custom HTTP client with the new transport.
- Reordered import statements (e.g., moving strconv and strings).
main_test.go - Added TestCreateCustomHTTPClient to test custom HTTP client functionality, verifying the presence of the X-Title header.
- Updated import section to include net/http/httptest.

Sequence Diagram(s)

sequenceDiagram
    participant App as Application
    participant LLM as LLM Initialization
    participant HT as headerTransport
    participant API as OpenAI API

    App->>LLM: Call createLLM/createVisionLLM
    LLM->>HT: Instantiate headerTransport
    HT->>API: Send HTTP request with header "X-Title: paperless-gpt"
    API-->>HT: Return API response
    HT-->>LLM: Pass response to LLM
    LLM-->>App: Return initialized LLM
Loading

Poem

I'm a hopping rabbit in a code-filled glen,
Adding headers with flair again and again.
With "X-Title" shining on each API call,
My custom transport answers the call!
A tweak in the imports, a joyful spring –
CodeRabbit hops with delight in everything!

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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
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: 0

🧹 Nitpick comments (2)
main.go (2)

643-654: Reduce code duplication in transport initialization.

The custom transport initialization is duplicated between createLLM and createVisionLLM. Consider extracting this into a helper function.

+func createCustomHTTPClient() *http.Client {
+    customTransport := &headerTransport{
+        transport: http.DefaultTransport,
+        headers: map[string]string{
+            "X-Title": "paperless-gpt",
+        },
+    }
+    httpClient := http.DefaultClient
+    httpClient.Transport = customTransport
+    return httpClient
+}

 func createLLM() (llms.Model, error) {
     switch strings.ToLower(llmProvider) {
     case "openai":
         if openaiAPIKey == "" {
             return nil, fmt.Errorf("OpenAI API key is not set")
         }
-        customTransport := &headerTransport{
-            transport: http.DefaultTransport,
-            headers: map[string]string{
-                "X-Title": "paperless-gpt",
-            },
-        }
-        httpClient := http.DefaultClient
-        httpClient.Transport = customTransport
+        httpClient := createCustomHTTPClient()
         return openai.New(
             openai.WithModel(llmModel),
             openai.WithToken(openaiAPIKey),
             openai.WithHTTPClient(httpClient),
         )

Also applies to: 681-692


647-647: Consider making the header value configurable.

The "X-Title" header value is hardcoded. Consider making it configurable through environment variables for flexibility.

+// Add to global variables
+var paperlessGptHeader = os.Getenv("PAPERLESS_GPT_HEADER")
+
+// Add to validateOrDefaultEnvVars()
+if paperlessGptHeader == "" {
+    paperlessGptHeader = "paperless-gpt"
+}

 // In createCustomHTTPClient
 headers: map[string]string{
-    "X-Title": "paperless-gpt",
+    "X-Title": paperlessGptHeader,
 },

Also applies to: 685-685

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d5bd238 and f5bd2fd.

📒 Files selected for processing (1)
  • main.go (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (1)
main.go (1)

713-725: LGTM! Clean implementation of the custom transport.

The headerTransport implementation correctly follows the http.RoundTripper interface pattern and safely adds headers to requests.

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

🧹 Nitpick comments (2)
main.go (2)

713-725: Add nil transport handling and improve documentation.

The headerTransport implementation is clean but could benefit from some improvements:

 // headerTransport is a custom http.RoundTripper that adds custom headers to requests
 type headerTransport struct {
-	transport http.RoundTripper
+	transport http.RoundTripper // underlying transport, defaults to http.DefaultTransport if nil
 	headers   map[string]string
 }
 
 // RoundTrip implements the http.RoundTripper interface
 func (t *headerTransport) RoundTrip(req *http.Request) (*http.Response, error) {
+	if t.transport == nil {
+		t.transport = http.DefaultTransport
+	}
 	for key, value := range t.headers {
 		req.Header.Add(key, value)
 	}
 	return t.transport.RoundTrip(req)
 }

646-648: Make headers configurable via environment variables.

Consider making the headers configurable to improve flexibility:

+// Environment Variables
+var (
+	// ... existing variables ...
+	customHeaders = map[string]string{
+		"X-Title": getEnvOrDefault("OPENAI_CLIENT_TITLE", "paperless-gpt"),
+	}
+)

 // headerTransport is a custom http.RoundTripper that adds custom headers to requests
 type headerTransport struct {
 	transport http.RoundTripper
-	headers: map[string]string{
-		"X-Title": "paperless-gpt",
-	},
+	headers: customHeaders,
 }

+// getEnvOrDefault returns environment variable value or default if not set
+func getEnvOrDefault(key, defaultValue string) string {
+	if value := os.Getenv(key); value != "" {
+		return value
+	}
+	return defaultValue
+}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f5bd2fd and 23632f6.

📒 Files selected for processing (1)
  • main.go (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: test
  • GitHub Check: Analyze (go)
🔇 Additional comments (1)
main.go (1)

643-725: Implementation looks good overall!

The custom HTTP transport implementation successfully adds headers to OpenAI API requests. The code is clean and follows Go best practices.

main.go Outdated
Comment on lines 643 to 654
// Create custom transport that adds headers
customTransport := &headerTransport{
transport: http.DefaultTransport,
headers: map[string]string{
"X-Title": "paperless-gpt",
},
}

// Create custom client with the transport
httpClient := http.DefaultClient
httpClient.Transport = customTransport

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

Reduce code duplication in transport creation.

The custom transport creation is duplicated between createLLM and createVisionLLM. Consider extracting this into a helper function:

+// createCustomHTTPClient returns an http.Client with custom headers
+func createCustomHTTPClient() *http.Client {
+	customTransport := &headerTransport{
+		transport: http.DefaultTransport,
+		headers: map[string]string{
+			"X-Title": "paperless-gpt",
+		},
+	}
+	client := http.DefaultClient
+	client.Transport = customTransport
+	return client
+}

 func createLLM() (llms.Model, error) {
 	switch strings.ToLower(llmProvider) {
 	case "openai":
 		if openaiAPIKey == "" {
 			return nil, fmt.Errorf("OpenAI API key is not set")
 		}
-		// Create custom transport that adds headers
-		customTransport := &headerTransport{
-			transport: http.DefaultTransport,
-			headers: map[string]string{
-				"X-Title": "paperless-gpt",
-			},
-		}
-		// Create custom client with the transport
-		httpClient := http.DefaultClient
-		httpClient.Transport = customTransport
+		httpClient := createCustomHTTPClient()

Also applies to: 681-692

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

🧹 Nitpick comments (1)
main.go (1)

705-717: Consider adding error handling for the transport.

The implementation is correct, but it could be enhanced with error handling for the underlying transport.

Apply this diff to add error handling:

 func (t *headerTransport) RoundTrip(req *http.Request) (*http.Response, error) {
+    if t.transport == nil {
+        return nil, fmt.Errorf("transport cannot be nil")
+    }
     for key, value := range t.headers {
         req.Header.Add(key, value)
     }
     return t.transport.RoundTrip(req)
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 23632f6 and 5194674.

📒 Files selected for processing (2)
  • main.go (4 hunks)
  • main_test.go (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build-arm64
  • GitHub Check: build-amd64
  • GitHub Check: Analyze (go)
🔇 Additional comments (4)
main_test.go (1)

180-199: LGTM! The test verifies the custom HTTP client functionality.

The test correctly verifies that the custom HTTP client adds the expected header to requests.

main.go (3)

642-647: LGTM! The OpenAI client is correctly configured with the custom HTTP client.

The implementation properly integrates the custom HTTP client with the OpenAI client configuration.


668-673: LGTM! The Vision OpenAI client is correctly configured with the custom HTTP client.

The implementation properly integrates the custom HTTP client with the Vision OpenAI client configuration.


689-703: LGTM! The custom HTTP client creation is well-implemented.

The function follows the suggestion from past review comments to extract the transport creation logic into a helper function. The implementation is clean and reusable.

@icereed icereed merged commit b7fab1a into main Feb 17, 2025
9 checks passed
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.

Feature Request: Add X-Title Header for paperless-gpt in openA API Requests
1 participant