Debian Codegraph @

vertexai/genai/example_test.go

raw
1 // Copyright 2023 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
15 package genai_test
16
17 import (
18 "context"
19 "fmt"
20 "log"
21 "os"
22
23 "cloud.google.com/go/vertexai/genai"
24
25 "google.golang.org/api/iterator"
26 )
27
28 // Your GCP project
29 const projectID = "your-project"
30
31 // A GCP location like "us-central1"; if you're using standard Google-published
32 // models (like untuned Gemini models), you can keep location blank ("").
33 const location = "some-gcp-location"
34
35 // A model name like "gemini-1.0-pro"
36 // For custom models from different publishers, prepent the full publisher
37 // prefix for the model, e.g.:
38 //
39 // modelName = publishers/some-publisher/models/some-model-name
40 const modelName = "some-model"
41
42 func ExampleGenerativeModel_GenerateContent() {
43 ctx := context.Background()
44 client, err := genai.NewClient(ctx, projectID, location)
45 if err != nil {
46 log.Fatal(err)
47 }
48 defer client.Close()
49
50 model := client.GenerativeModel(modelName)
51 model.SetTemperature(0.9)
52 resp, err := model.GenerateContent(ctx, genai.Text("What is the average size of a swallow?"))
53 if err != nil {
54 log.Fatal(err)
55 }
56
57 printResponse(resp)
58 }
59
60 // This example shows how to a configure a model. See [GenerationConfig]
61 // for the complete set of configuration options.
62 func ExampleGenerativeModel_GenerateContent_config() {
63 ctx := context.Background()
64 const projectID = "YOUR PROJECT ID"
65 const location = "GCP LOCATION"
66 client, err := genai.NewClient(ctx, projectID, location)
67 if err != nil {
68 log.Fatal(err)
69 }
70 defer client.Close()
71
72 model := client.GenerativeModel("gemini-1.0-pro")
73 model.SetTemperature(0.9)
74 model.SetTopP(0.5)
75 model.SetTopK(20)
76 model.SetMaxOutputTokens(100)
77 model.SystemInstruction = genai.NewUserContent(genai.Text("You are Yoda from Star Wars."))
78 resp, err := model.GenerateContent(ctx, genai.Text("What is the average size of a swallow?"))
79 if err != nil {
80 log.Fatal(err)
81 }
82 printResponse(resp)
83 }
84
85 // This example shows how to send multiple requests concurrently using goroutines.
86 func ExampleGenerativeModel_GenerateContent_goroutine() {
87 ctx := context.Background()
88 const projectID = "YOUR PROJECT ID"
89 const location = "GCP LOCATION"
90 client, err := genai.NewClient(ctx, projectID, location)
91 if err != nil {
92 log.Fatal(err)
93 }
94 defer client.Close()
95
96 model := client.GenerativeModel("gemini-1.0-pro")
97
98 queries := []string{"Hello, World!", "What's the weather today?"}
99 resultChan := make(chan *genai.GenerateContentResponse, len(queries))
100
101 worker := func(query string) {
102 result, err := model.GenerateContent(ctx, genai.Text(query))
103 if err != nil {
104 log.Fatal(err)
105 }
106 resultChan <- result
107 }
108 // Send two requests concurrently
109 for _, query := range queries {
110 go worker(query)
111 }
112
113 // Wait for the responses
114 for a := 0; a < len(queries); a++ {
115 result := <-resultChan
116 printResponse(result)
117 }
118 close(resultChan)
119 }
120
121 func ExampleGenerativeModel_GenerateContentStream() {
122 ctx := context.Background()
123 client, err := genai.NewClient(ctx, projectID, location)
124 if err != nil {
125 log.Fatal(err)
126 }
127 defer client.Close()
128
129 model := client.GenerativeModel(modelName)
130
131 iter := model.GenerateContentStream(ctx, genai.Text("Tell me a story about a lumberjack and his giant ox. Keep it very short."))
132 for {
133 resp, err := iter.Next()
134 if err == iterator.Done {
135 break
136 }
137 if err != nil {
138 log.Fatal(err)
139 }
140 printResponse(resp)
141 }
142 }
143
144 func ExampleGenerativeModel_CountTokens() {
145 ctx := context.Background()
146 client, err := genai.NewClient(ctx, projectID, location)
147 if err != nil {
148 log.Fatal(err)
149 }
150 defer client.Close()
151
152 model := client.GenerativeModel(modelName)
153
154 resp, err := model.CountTokens(ctx, genai.Text("What kind of fish is this?"))
155 if err != nil {
156 log.Fatal(err)
157 }
158
159 fmt.Println("Num tokens:", resp.TotalTokens)
160 }
161
162 func ExampleChatSession() {
163 ctx := context.Background()
164 client, err := genai.NewClient(ctx, projectID, location)
165 if err != nil {
166 log.Fatal(err)
167 }
168 defer client.Close()
169 model := client.GenerativeModel(modelName)
170 cs := model.StartChat()
171
172 send := func(msg string) *genai.GenerateContentResponse {
173 fmt.Printf("== Me: %s\n== Model:\n", msg)
174 res, err := cs.SendMessage(ctx, genai.Text(msg))
175 if err != nil {
176 log.Fatal(err)
177 }
178 return res
179 }
180
181 res := send("Can you name some brands of air fryer?")
182 printResponse(res)
183 iter := cs.SendMessageStream(ctx, genai.Text("Which one of those do you recommend?"))
184 for {
185 res, err := iter.Next()
186 if err == iterator.Done {
187 break
188 }
189 if err != nil {
190 log.Fatal(err)
191 }
192 printResponse(res)
193 }
194
195 for i, c := range cs.History {
196 log.Printf(" %d: %+v", i, c)
197 }
198 res = send("Why do you like the Philips?")
199 if err != nil {
200 log.Fatal(err)
201 }
202 printResponse(res)
203 }
204
205 func ExampleTool() {
206 ctx := context.Background()
207 client, err := genai.NewClient(ctx, projectID, location)
208 if err != nil {
209 log.Fatal(err)
210 }
211 defer client.Close()
212
213 currentWeather := func(city string) string {
214 switch city {
215 case "New York, NY":
216 return "cold"
217 case "Miami, FL":
218 return "warm"
219 default:
220 return "unknown"
221 }
222 }
223
224 // To use functions / tools, we have to first define a schema that describes
225 // the function to the model. The schema is similar to OpenAPI 3.0.
226 //
227 // In this example, we create a single function that provides the model with
228 // a weather forecast in a given location.
229 schema := &genai.Schema{
230 Type: genai.TypeObject,
231 Properties: map[string]*genai.Schema{
232 "location": {
233 Type: genai.TypeString,
234 Description: "The city and state, e.g. San Francisco, CA",
235 },
236 "unit": {
237 Type: genai.TypeString,
238 Enum: []string{"celsius", "fahrenheit"},
239 },
240 },
241 Required: []string{"location"},
242 }
243
244 weatherTool := &genai.Tool{
245 FunctionDeclarations: []*genai.FunctionDeclaration{{
246 Name: "CurrentWeather",
247 Description: "Get the current weather in a given location",
248 Parameters: schema,
249 }},
250 }
251
252 model := client.GenerativeModel("gemini-1.0-pro")
253
254 // Before initiating a conversation, we tell the model which tools it has
255 // at its disposal.
256 model.Tools = []*genai.Tool{weatherTool}
257
258 // For using tools, the chat mode is useful because it provides the required
259 // chat context. A model needs to have tools supplied to it in the chat
260 // history so it can use them in subsequent conversations.
261 //
262 // The flow of message expected here is:
263 //
264 // 1. We send a question to the model
265 // 2. The model recognizes that it needs to use a tool to answer the question,
266 // an returns a FunctionCall response asking to use the CurrentWeather
267 // tool.
268 // 3. We send a FunctionResponse message, simulating the return value of
269 // CurrentWeather for the model's query.
270 // 4. The model provides its text answer in response to this message.
271 session := model.StartChat()
272
273 res, err := session.SendMessage(ctx, genai.Text("What is the weather like in New York?"))
274 if err != nil {
275 log.Fatal(err)
276 }
277
278 part := res.Candidates[0].Content.Parts[0]
279 funcall, ok := part.(genai.FunctionCall)
280 if !ok {
281 log.Fatalf("expected FunctionCall: %v", part)
282 }
283
284 if funcall.Name != "CurrentWeather" {
285 log.Fatalf("expected CurrentWeather: %v", funcall.Name)
286 }
287
288 // Expect the model to pass a proper string "location" argument to the tool.
289 locArg, ok := funcall.Args["location"].(string)
290 if !ok {
291 log.Fatalf("expected string: %v", funcall.Args["location"])
292 }
293
294 weatherData := currentWeather(locArg)
295 res, err = session.SendMessage(ctx, genai.FunctionResponse{
296 Name: weatherTool.FunctionDeclarations[0].Name,
297 Response: map[string]any{
298 "weather": weatherData,
299 },
300 })
301 if err != nil {
302 log.Fatal(err)
303 }
304
305 printResponse(res)
306 }
307
308 func ExampleGenerativeModel_ToolConfig() {
309 // This example shows how to affect how the model uses the tools provided to it.
310 // By setting the ToolConfig, you can disable function calling.
311
312 // Assume we have created a Model and have set its Tools field with some functions.
313 // See the Example for Tool for details.
314 model := &genai.GenerativeModel{}
315
316 // By default, the model will use the functions in its responses if it thinks they are
317 // relevant, by returning FunctionCall parts.
318 // Here we set the model's ToolConfig to disable function calling completely.
319 model.ToolConfig = &genai.ToolConfig{
320 FunctionCallingConfig: &genai.FunctionCallingConfig{
321 Mode: genai.FunctionCallingNone,
322 },
323 }
324
325 // Subsequent calls to ChatSession.SendMessage will not result in FunctionCall responses.
326 session := model.StartChat()
327 res, err := session.SendMessage(context.Background(), genai.Text("What is the weather like in New York?"))
328 if err != nil {
329 log.Fatal(err)
330 }
331 for _, part := range res.Candidates[0].Content.Parts {
332 if _, ok := part.(genai.FunctionCall); ok {
333 log.Fatal("did not expect FunctionCall")
334 }
335 }
336
337 // It is also possible to force a function call by using FunctionCallingAny
338 // instead of FunctionCallingNone. See the documentation for FunctionCallingMode
339 // for details.
340 }
341
342 func ExampleClient_cachedContent() {
343 ctx := context.Background()
344 client, err := genai.NewClient(ctx, projectID, location)
345 if err != nil {
346 log.Fatal(err)
347 }
348 defer client.Close()
349 file := genai.FileData{MIMEType: "application/pdf", FileURI: "gs://my-bucket/my-doc.pdf"}
350 cc, err := client.CreateCachedContent(ctx, &genai.CachedContent{
351 Model: modelName,
352 Contents: []*genai.Content{genai.NewUserContent(file)},
353 })
354 model := client.GenerativeModelFromCachedContent(cc)
355 // Work with the model as usual in this program.
356 _ = model
357
358 // Store the CachedContent name for later use.
359 if err := os.WriteFile("my-cached-content-name", []byte(cc.Name), 0o644); err != nil {
360 log.Fatal(err)
361 }
362
363 ///////////////////////////////
364 // Later, in another process...
365
366 bytes, err := os.ReadFile("my-cached-content-name")
367 if err != nil {
368 log.Fatal(err)
369 }
370 ccName := string(bytes)
371
372 // No need to call [Client.GetCachedContent]; the name is sufficient.
373 model = client.GenerativeModel(modelName)
374 model.CachedContentName = ccName
375 // Proceed as usual.
376 }
377
378 func printResponse(resp *genai.GenerateContentResponse) {
379 for _, cand := range resp.Candidates {
380 for _, part := range cand.Content.Parts {
381 fmt.Println(part)
382 }
383 }
384 fmt.Println("---")
385 }