base_url.go

 1// Copyright 2025 Google LLC
 2//
 3// Licensed under the Apache License, Version 2.0 (the "License");
 4// you may not use this file except in compliance with the License.
 5// You may obtain a copy of the License at
 6//
 7//      http://www.apache.org/licenses/LICENSE-2.0
 8//
 9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package genai
16
17var defaultBaseGeminiURL string = ""
18var defaultBaseVertexURL string = ""
19
20// BaseURLParameters are parameters for setting the base URLs for the Gemini API and Vertex AI API.
21type BaseURLParameters struct {
22	GeminiURL string
23	VertexURL string
24}
25
26// SetDefaultBaseURLs overrides the base URLs for the Gemini API and Vertex AI API.
27//
28// [HTTPOptions.BaseURL] takes precedence over URLs set here.
29//
30// Note: This function should be called before initializing the SDK. If the
31// base URLs are set after initializing the SDK, the base URLs will not be
32// updated.
33func SetDefaultBaseURLs(baseURLParams BaseURLParameters) {
34	defaultBaseGeminiURL = baseURLParams.GeminiURL
35	defaultBaseVertexURL = baseURLParams.VertexURL
36}
37
38// getDefaultBaseURLs returns the default base URLs for the Gemini API and Vertex AI API.
39func getDefaultBaseURLs() *BaseURLParameters {
40	return &BaseURLParameters{
41		GeminiURL: defaultBaseGeminiURL,
42		VertexURL: defaultBaseVertexURL,
43	}
44}
45
46// getBaseURL returns the default base URL based on the following priority:
47//
48//  1. Base URLs set via HTTPOptions.
49//  2. Base URLs set via the latest call to SetDefaultBaseURLs.
50//  3. Base URLs set via environment variables.
51func getBaseURL(backend Backend, httpOptions *HTTPOptions, envVars map[string]string) string {
52	if httpOptions != nil && httpOptions.BaseURL != "" {
53		return httpOptions.BaseURL
54	}
55	baseURLs := getDefaultBaseURLs()
56	if backend == BackendVertexAI {
57		if baseURLs.VertexURL != "" {
58			return baseURLs.VertexURL
59		} else if v := envVars["GOOGLE_VERTEX_BASE_URL"]; v != "" {
60			return v
61		}
62	} else {
63		if baseURLs.GeminiURL != "" {
64			return baseURLs.GeminiURL
65		} else if v := envVars["GOOGLE_GEMINI_BASE_URL"]; v != "" {
66			return v
67		}
68	}
69
70	return ""
71}