|
| 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 | +// https://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 express_mode shows how to use the GenAI SDK to generate text with VertexAI Api Key. |
| 16 | +package express_mode |
| 17 | + |
| 18 | +// [START googlegenaisdk_vertexai_express_mode] |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + "fmt" |
| 22 | + "io" |
| 23 | + |
| 24 | + "google.golang.org/genai" |
| 25 | +) |
| 26 | + |
| 27 | +var newClient = genai.NewClient |
| 28 | + |
| 29 | +// generateContent shows how to use Vertex AI Express mode with an API key. |
| 30 | +func generateContentWithApiKey(w io.Writer) error { |
| 31 | + ctx := context.Background() |
| 32 | + |
| 33 | + // TODO(developer): Replace with your actual API key |
| 34 | + apiKey := "YOUR_API_KEY" |
| 35 | + |
| 36 | + client, err := newClient(ctx, &genai.ClientConfig{ |
| 37 | + APIKey: apiKey, |
| 38 | + HTTPOptions: genai.HTTPOptions{APIVersion: "v1"}, |
| 39 | + }) |
| 40 | + if err != nil { |
| 41 | + return fmt.Errorf("failed to create genai client: %w", err) |
| 42 | + } |
| 43 | + |
| 44 | + modelName := "gemini-2.5-flash" |
| 45 | + resp, err := client.Models.GenerateContent(ctx, modelName, |
| 46 | + []*genai.Content{ |
| 47 | + {Parts: []*genai.Part{ |
| 48 | + {Text: "Explain bubble sort to me."}, |
| 49 | + }, Role: "user"}, |
| 50 | + }, |
| 51 | + nil, |
| 52 | + ) |
| 53 | + if err != nil { |
| 54 | + return fmt.Errorf("failed to generate content: %w", err) |
| 55 | + } |
| 56 | + |
| 57 | + fmt.Fprintln(w, resp.Text()) |
| 58 | + |
| 59 | + // Example response: |
| 60 | + // Bubble Sort is a simple sorting algorithm that repeatedly steps through the list |
| 61 | + |
| 62 | + return nil |
| 63 | +} |
| 64 | + |
| 65 | +// [END googlegenaisdk_vertexai_express_mode] |
0 commit comments