forked from googleapis/go-genai
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
179 lines (159 loc) · 5.95 KB
/
client.go
File metadata and controls
179 lines (159 loc) · 5.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package genai
import (
"context"
"fmt"
"net/http"
"os"
"strings"
"time"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
// Client is the GenAI client.
type Client struct {
clientConfig ClientConfig
Models *Models
Live *Live
Caches *Caches
}
// Backend is the GenAI backend to use for the client.
type Backend int
const (
// BackendUnspecified causes the backend determined automatically. If the
// GOOGLE_GENAI_USE_VERTEXAI environment variable is set to "1" or "true", then
// the backend is BackendVertexAI. Otherwise, if GOOGLE_GENAI_USE_VERTEXAI
// is unset or set to any other value, then BackendGeminiAPI is used. Explicitly
// setting the backend in ClientConfig overrides the environment variable.
BackendUnspecified Backend = iota
// BackendGeminiAPI is the Gemini API backend.
BackendGeminiAPI
// BackendVertexAI is the Vertex AI backend.
BackendVertexAI
)
// The Stringer interface for Backend.
func (t Backend) String() string {
switch t {
case BackendGeminiAPI:
return "BackendGeminiAPI"
case BackendVertexAI:
return "BackendVertexAI"
default:
return "BackendUnspecified"
}
}
// ClientConfig is the configuration for the GenAI client.
type ClientConfig struct {
APIKey string // API Key for GenAI. Required for BackendGeminiAPI.
Backend Backend // Backend for GenAI. See Backend constants. Defaults to BackendGeminiAPI unless explicitly set to BackendVertexAI, or the environment variable GOOGLE_GENAI_USE_VERTEXAI is set to "1" or "true".
Project string // GCP Project ID for Vertex AI. Required for BackendVertexAI.
Location string // GCP Location/Region for Vertex AI. Required for BackendVertexAI. See https://cloud.google.com/vertex-ai/docs/general/locations
Credentials *google.Credentials // Optional. Google credentials. If not specified, application default credentials will be used.
HTTPClient *http.Client // Optional HTTP client to use. If nil, a default client will be created. For Vertex AI, this client must handle authentication appropriately.
HTTPOptions HTTPOptions // Optional HTTP options to override.
}
// NewClient creates a new GenAI client.
//
// You can configure the client by passing in a ClientConfig struct.
func NewClient(ctx context.Context, cc *ClientConfig) (*Client, error) {
if cc == nil {
cc = &ClientConfig{}
}
if cc.Project != "" && cc.APIKey != "" {
return nil, fmt.Errorf("project and API key are mutually exclusive in the client initializer. ClientConfig: %v", cc)
}
if cc.Location != "" && cc.APIKey != "" {
return nil, fmt.Errorf("location and API key are mutually exclusive in the client initializer. ClientConfig: %v", cc)
}
if cc.Backend == BackendUnspecified {
if v, ok := os.LookupEnv("GOOGLE_GENAI_USE_VERTEXAI"); ok {
v = strings.ToLower(v)
if v == "1" || v == "true" {
cc.Backend = BackendVertexAI
} else {
cc.Backend = BackendGeminiAPI
}
} else {
cc.Backend = BackendGeminiAPI
}
}
// Only set the API key for MLDev API.
if cc.APIKey == "" && cc.Backend == BackendGeminiAPI {
cc.APIKey = os.Getenv("GOOGLE_API_KEY")
}
if cc.Project == "" {
cc.Project = os.Getenv("GOOGLE_CLOUD_PROJECT")
}
if cc.Location == "" {
if location, ok := os.LookupEnv("GOOGLE_CLOUD_LOCATION"); ok {
cc.Location = location
} else if location, ok := os.LookupEnv("GOOGLE_CLOUD_REGION"); ok {
cc.Location = location
}
}
if cc.Backend == BackendVertexAI {
if cc.Project == "" {
return nil, fmt.Errorf("project is required for Vertex AI backend. ClientConfig: %v", cc)
}
if cc.Location == "" {
return nil, fmt.Errorf("location is required for Vertex AI backend. ClientConfig: %v", cc)
}
} else {
if cc.APIKey == "" {
return nil, fmt.Errorf("api key is required for Google AI backend. ClientConfig: %v.\nYou can get the API key from https://ai.google.dev/gemini-api/docs/api-key", cc)
}
}
if cc.Backend == BackendVertexAI && cc.Credentials == nil {
cred, err := google.FindDefaultCredentials(ctx, "https://www.googleapis.com/auth/cloud-platform")
if err != nil {
return nil, fmt.Errorf("failed to find default credentials: %w", err)
}
cc.Credentials = cred
}
if cc.HTTPOptions.BaseURL == "" && cc.Backend == BackendVertexAI {
cc.HTTPOptions.BaseURL = fmt.Sprintf("https://%s-aiplatform.googleapis.com/", cc.Location)
} else if cc.HTTPOptions.BaseURL == "" {
cc.HTTPOptions.BaseURL = "https://generativelanguage.googleapis.com/"
}
if cc.HTTPOptions.APIVersion == "" && cc.Backend == BackendVertexAI {
cc.HTTPOptions.APIVersion = "v1beta1"
} else if cc.HTTPOptions.APIVersion == "" {
cc.HTTPOptions.APIVersion = "v1beta"
}
if cc.HTTPClient == nil {
if cc.Backend == BackendVertexAI {
cc.HTTPClient = oauth2.NewClient(ctx, oauth2.ReuseTokenSource(nil, cc.Credentials.TokenSource))
} else {
cc.HTTPClient = &http.Client{}
}
}
if cc.HTTPOptions.Timeout > 0 {
cc.HTTPClient.Timeout = time.Duration(cc.HTTPOptions.Timeout) * time.Millisecond
}
ac := &apiClient{clientConfig: cc}
c := &Client{
clientConfig: *cc,
Models: &Models{apiClient: ac},
Live: &Live{apiClient: ac},
Caches: &Caches{apiClient: ac},
}
return c, nil
}
// ClientConfig returns the ClientConfig for the client.
//
// The returned ClientConfig is a copy of the ClientConfig used to create the client.
func (c Client) ClientConfig() ClientConfig {
return c.clientConfig
}