@@ -5,7 +5,10 @@ package openai_test
5
5
import (
6
6
"context"
7
7
"errors"
8
+ "net"
9
+ "net/http"
8
10
"os"
11
+ "strings"
9
12
"testing"
10
13
11
14
"github.com/openai/openai-go"
@@ -122,6 +125,54 @@ func TestChatCompletionGet(t *testing.T) {
122
125
}
123
126
}
124
127
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
+
125
176
func TestChatCompletionUpdate (t * testing.T ) {
126
177
baseURL := "http://localhost:4010"
127
178
if envURL , ok := os .LookupEnv ("TEST_API_BASE_URL" ); ok {
0 commit comments