Skip to content

Commit e2827f4

Browse files
committed
fix: WithBaseURL() should support custom path
1 parent eff15bb commit e2827f4

File tree

2 files changed

+60
-1
lines changed

2 files changed

+60
-1
lines changed

chatcompletion_test.go

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,10 @@ package openai_test
55
import (
66
"context"
77
"errors"
8+
"net"
9+
"net/http"
810
"os"
11+
"strings"
912
"testing"
1013

1114
"github.com/openai/openai-go"
@@ -122,6 +125,54 @@ func TestChatCompletionGet(t *testing.T) {
122125
}
123126
}
124127

128+
func TestChatCompletionCustomBaseURL(t *testing.T) {
129+
ctx, cancel := context.WithCancel(context.Background())
130+
defer cancel()
131+
srv := &http.Server{}
132+
133+
ready := make(chan struct{})
134+
go func() {
135+
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
136+
if !strings.HasPrefix(r.URL.String(), "/openai/v1") {
137+
t.Errorf("expected prefix to be /openai/v1, got %s", r.URL.String())
138+
}
139+
140+
w.Header().Set("content-type", "application/json")
141+
w.WriteHeader(http.StatusOK)
142+
w.Write([]byte(`{"id": "completion_id"}`))
143+
})
144+
lstr, err := net.Listen("tcp", "localhost:4011")
145+
if err != nil {
146+
t.Errorf("net.Listen: %s", err.Error())
147+
}
148+
close(ready)
149+
if err := srv.Serve(lstr); err != http.ErrServerClosed {
150+
t.Errorf("srv.Serve: %s", err.Error())
151+
}
152+
}()
153+
// Wait until the server is listening
154+
<-ready
155+
156+
go func() {
157+
<-ctx.Done()
158+
srv.Shutdown(ctx)
159+
}()
160+
161+
baseURL := "http://localhost:4011/openai/v1"
162+
client := openai.NewClient(
163+
option.WithBaseURL(baseURL),
164+
option.WithAPIKey("My API Key"),
165+
)
166+
_, err := client.Chat.Completions.Get(context.TODO(), "completion_id")
167+
if err != nil {
168+
var apierr *openai.Error
169+
if errors.As(err, &apierr) {
170+
t.Log(string(apierr.DumpRequest(true)))
171+
}
172+
t.Fatalf("err should be nil: %s", err.Error())
173+
}
174+
}
175+
125176
func TestChatCompletionUpdate(t *testing.T) {
126177
baseURL := "http://localhost:4010"
127178
if envURL, ok := os.LookupEnv("TEST_API_BASE_URL"); ok {

internal/requestconfig/requestconfig.go

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -353,7 +353,15 @@ func (cfg *RequestConfig) Execute() (err error) {
353353
return fmt.Errorf("requestconfig: base url is not set")
354354
}
355355

356-
cfg.Request.URL, err = cfg.BaseURL.Parse(strings.TrimLeft(cfg.Request.URL.String(), "/"))
356+
effectiveURL, err := url.JoinPath(cfg.BaseURL.String(), cfg.Request.URL.String())
357+
if err != nil {
358+
return err
359+
}
360+
effectiveURL, err = url.PathUnescape(effectiveURL)
361+
if err != nil {
362+
return err
363+
}
364+
cfg.Request.URL, err = url.Parse(effectiveURL)
357365
if err != nil {
358366
return err
359367
}

0 commit comments

Comments
 (0)