Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions genai/embeddings/embeddings_docretrieval_with_txt.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// Copyright 2025 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
//
// https://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 embeddings shows examples of how Gemini-embedding model can use embedding.
package embeddings

// [START googlegenaisdk_embeddings_docretrieval_with_txt]
import (
"context"
"fmt"
"io"

"google.golang.org/genai"
)

// generateEmbedContentWithText shows how to embed content with text.
func generateEmbedContentWithText(w io.Writer) error {
ctx := context.Background()

client, err := genai.NewClient(ctx, &genai.ClientConfig{
HTTPOptions: genai.HTTPOptions{APIVersion: "v1"},
})
if err != nil {
return fmt.Errorf("failed to create genai client: %w", err)
}

outputDimensionality := int32(3072)
config := &genai.EmbedContentConfig{
TaskType: "RETRIEVAL_DOCUMENT", //optional
Title: "Driver's License", //optional
OutputDimensionality: &outputDimensionality, //optional
}

contents := []*genai.Content{
{
Parts: []*genai.Part{
{
Text: "How do I get a driver's license/learner's permit?",
},
{
Text: "How long is my driver's license valid for?",
},
{
Text: "Driver's knowledge test study guide",
},
},
Role: "user",
},
}

modelName := "gemini-embedding-001"
resp, err := client.Models.EmbedContent(ctx, modelName, contents, config)
if err != nil {
return fmt.Errorf("failed to generate content: %w", err)
}

fmt.Fprintln(w, resp)

// Example response:
// embeddings=[ContentEmbedding(values=[-0.06302902102470398, 0.00928034819662571, 0.014716853387653828, -0.028747491538524628, ... ],
// statistics=ContentEmbeddingStatistics(truncated=False, token_count=13.0))]
// metadata=EmbedContentMetadata(billable_character_count=112)

return nil
}

// [END googlegenaisdk_embeddings_docretrieval_with_txt]
46 changes: 46 additions & 0 deletions genai/embeddings/embeddings_examples_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// Copyright 2025 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 embeddings

import (
"bytes"
"testing"

"github.com/GoogleCloudPlatform/golang-samples/internal/testutil"
)

func TestEmbedGeneration(t *testing.T) {
tc := testutil.SystemTest(t)

t.Setenv("GOOGLE_GENAI_USE_VERTEXAI", "1")
t.Setenv("GOOGLE_CLOUD_LOCATION", "us-central1")
t.Setenv("GOOGLE_CLOUD_PROJECT", tc.ProjectID)

buf := new(bytes.Buffer)

t.Run("generate embed content with text", func(t *testing.T) {
buf.Reset()
err := generateEmbedContentWithText(buf)
if err != nil {
t.Fatalf("generateEmbedContentWithText failed: %v", err)
}

output := buf.String()
if output == "" {
t.Error("expected non-empty output, got empty")
}
})

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// Copyright 2025 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 provisionedthroughput

import (
"bytes"
"testing"

"github.com/GoogleCloudPlatform/golang-samples/internal/testutil"
)

func TestProvisionedThroughputGeneration(t *testing.T) {
tc := testutil.SystemTest(t)

t.Setenv("GOOGLE_GENAI_USE_VERTEXAI", "1")
t.Setenv("GOOGLE_CLOUD_LOCATION", "us-central1")
t.Setenv("GOOGLE_CLOUD_PROJECT", tc.ProjectID)

buf := new(bytes.Buffer)

t.Run("generate Provisioned Throughput with text", func(t *testing.T) {
buf.Reset()
err := generateProvisionedThroughputWithText(buf)
if err != nil {
t.Fatalf("generateProvisionedThroughputWithText failed: %v", err)
}

output := buf.String()
if output == "" {
t.Error("expected non-empty output, got empty")
}
})

}
69 changes: 69 additions & 0 deletions genai/provisioned_throughput/provisionedthroughput_with_txt.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// Copyright 2025 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
//
// https://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 provisionedthroughput shows examples of Gemini model can use to generate with text.
package provisionedthroughput

// [START googlegenaisdk_provisionedthroughput_with_txt]
import (
"context"
"fmt"
"io"
"net/http"

"google.golang.org/genai"
)

// generateProvisionedThroughputWithText shows how to generate text Provisioned Throughput.
func generateProvisionedThroughputWithText(w io.Writer) error {
ctx := context.Background()

client, err := genai.NewClient(ctx, &genai.ClientConfig{
HTTPOptions: genai.HTTPOptions{
APIVersion: "v1",
Headers: http.Header{
// Options:
// - "dedicated": Use Provisioned Throughput
// - "shared": Use pay-as-you-go
// https://cloud.google.com/vertex-ai/generative-ai/docs/use-provisioned-throughput
"X-Vertex-AI-LLM-Request-Type": []string{"shared"},
},
},
})
if err != nil {
return fmt.Errorf("failed to create genai client: %w", err)
}

modelName := "gemini-2.5-flash"
contents := genai.Text("How does AI work?")

resp, err := client.Models.GenerateContent(ctx, modelName, contents, nil)
if err != nil {
return fmt.Errorf("failed to generate content: %w", err)
}

respText := resp.Text()

fmt.Fprintln(w, respText)

// Example response:
// Artificial Intelligence (AI) isn't magic, nor is it a single "thing." Instead, it's a broad field of computer science focused on creating machines that can perform tasks that typically require human intelligence.
// .....
// In Summary:
// ...

return nil
}

// [END googlegenaisdk_provisionedthroughput_with_txt]
13 changes: 13 additions & 0 deletions genai/text_generation/text_generation_examples_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -239,4 +239,17 @@ func TestTextGeneration(t *testing.T) {
}
})

t.Run("generate chat with text", func(t *testing.T) {
buf.Reset()
err := generateChatWithText(buf)
if err != nil {
t.Fatalf("generateChatWithText failed: %v", err)
}

output := buf.String()
if output == "" {
t.Error("expected non-empty output, got empty")
}
})

}
74 changes: 74 additions & 0 deletions genai/text_generation/textgen_chat_with_txt.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// Copyright 2025 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
//
// https://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 text_generation shows examples of generating text using the GenAI SDK.
package text_generation

// [START googlegenaisdk_textgen_chat_with_txt]
import (
"context"
"fmt"
"io"

"google.golang.org/genai"
)

// generateChatWithText shows how to generate chat using a text prompt.
func generateChatWithText(w io.Writer) error {
ctx := context.Background()

client, err := genai.NewClient(ctx, &genai.ClientConfig{
HTTPOptions: genai.HTTPOptions{APIVersion: "v1"},
})
if err != nil {
return fmt.Errorf("failed to create genai client: %w", err)
}
modelName := "gemini-2.5-flash"
history := []*genai.Content{
{
Role: "user",
Parts: []*genai.Part{
{Text: "Hello there"},
},
},
{
Role: "model",
Parts: []*genai.Part{
{Text: "Great to meet you. What would you like to know?"},
},
},
}
chatSession, err := client.Chats.Create(ctx, modelName, nil, history)
if err != nil {
return fmt.Errorf("failed to create genai chat session: %w", err)
}
contents := genai.Part{Text: "Tell me a story."}
resp, err := chatSession.SendMessage(ctx, contents)
if err != nil {
return fmt.Errorf("failed to send message: %w", err)
}

respText := resp.Text()

fmt.Fprintln(w, respText)
// Example response:
// Okay, settle in. Let me tell you a story about a quiet cartographer, but not of lands and seas.
// ...
// In the sleepy town of Oakhaven, nestled between the Whispering Hills and the Murmuring River, lived a woman named Elara.
// ...

return nil
}

// [END googlegenaisdk_textgen_chat_with_txt]
15 changes: 15 additions & 0 deletions genai/tools/tools_examples_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package tools

import (
"bytes"
"fmt"
"testing"

"github.com/GoogleCloudPlatform/golang-samples/internal/testutil"
Expand Down Expand Up @@ -68,4 +69,18 @@ func TestTextGeneration(t *testing.T) {
t.Error("expected non-empty output, got empty")
}
})

t.Run("generate with VAIS Search", func(t *testing.T) {
buf.Reset()
dataStore := fmt.Sprintf("projects/%s/locations/global/collections/default_collection/dataStores/grounding-test-datastore", tc.ProjectID)
err := generateWithGoogleVAIS(buf, dataStore)
if err != nil {
t.Fatalf("generateWithGoogleVAIS failed: %v", err)
}

output := buf.String()
if output == "" {
t.Error("expected non-empty output, got empty")
}
})
}
Loading
Loading