### Creating Parts Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/API-OVERVIEW.md Examples of how to create different types of content parts. ```APIDOC ### Creating Parts ```go genai.Text("Hello") // Plain text genai.ImageData("png", bytes) // Image blob genai.FileData{URI: "..."} // File reference genai.FunctionCall{Name: "fn", Args: ..} // Function call ``` ``` -------------------------------- ### Create User Content Example Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/types.md Shows how to use NewUserContent to create a simple text-based user message. ```go content := genai.NewUserContent( genai.Text("What is AI?"), ) ``` -------------------------------- ### Initialize Pointer Fields Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/types.md Example of using the Ptr utility function to set optional configuration parameters like Temperature and MaxOutputTokens. ```go model.Temperature = genai.Ptr[float32](0.7) model.MaxOutputTokens = genai.Ptr[int32](1000) ``` -------------------------------- ### Reusing Clients Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/API-OVERVIEW.md Example demonstrating the pattern for reusing client instances for efficiency. ```APIDOC ### Reusing Clients ```go // Create once, reuse multiple times client, _ := genai.NewClient(ctx, option.WithAPIKey(apiKey)) defer client.Close() model1 := client.GenerativeModel("gemini-1.5-flash") model2 := client.GenerativeModel("gemini-1.5-pro") embedModel := client.EmbeddingModel("embedding-001") ``` ``` -------------------------------- ### Install Pre-Push Hook Source: https://github.com/google/generative-ai-go/blob/main/CONTRIBUTING.md Install the pre-push hook to ensure code quality before pushing commits. This hook helps in maintaining the project's standards. ```bash cp devtools/pre-push-hook.sh .git/hooks/pre-push ``` -------------------------------- ### Generate Image Blob Example Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/types.md Demonstrates how to read image file data and create a Blob using the ImageData function. ```go imgData, _ := os.ReadFile("photo.png") blob := genai.ImageData("png", imgData) ``` -------------------------------- ### Start a Chat Session Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/README.md Initiate a chat session with a generative model. This allows for multi-turn conversations with automatic history management. ```go session := model.StartChat() resp, _ := session.SendMessage(ctx, genai.Text("message")) ``` -------------------------------- ### Go SDK Installation Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/API-OVERVIEW.md Import necessary packages for using the Generative AI Go SDK. This includes the genai package and options for API key configuration. ```go import ( "github.com/google/generative-ai-go/genai" "google.golang.org/api/option" ) ``` -------------------------------- ### StartChat Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/api-reference/generative-model.md Starts a chat session with the model, allowing for conversational interactions. It returns a `ChatSession` object. ```APIDOC ## StartChat ### Description Starts a chat session with the model. ### Method POST ### Endpoint /v1beta/models/{model_id}:startChat ### Parameters #### Path Parameters - **model_id** (string) - Required - The ID of the model to start a chat session with. #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **chatSession** (object) - The chat session object. - **history** (array[object]) - The history of the chat session. #### Response Example ```json { "chatSession": { "history": [] } } ``` ### Note Chat history is maintained automatically within the `ChatSession` object. ``` -------------------------------- ### Chat Session Management in Go Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/API-OVERVIEW.md Illustrates how to start a chat session and send messages. The chat history is automatically managed by the session. ```go session := model.StartChat() resp1, _ := session.SendMessage(ctx, genai.Text("What is AI?")) fmt.Println(resp1.Candidates[0].Content) resp2, _ := session.SendMessage(ctx, genai.Text("How does it work?")) fmt.Println(resp2.Candidates[0].Content) // Chat history is maintained automatically ``` -------------------------------- ### Start Chat Session Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/api-reference/generative-model.md Use StartChat to initiate a chat session. The ChatSession object automatically maintains conversation history for subsequent messages. ```go session := model.StartChat() resp, err := session.SendMessage(ctx, genai.Text("What is AI?")) resp2, err := session.SendMessage(ctx, genai.Text("How is it used?")) // Chat history is maintained automatically ``` -------------------------------- ### Batch Embed Contents Example Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/api-reference/responses-and-iterators.md Illustrates how to process the BatchEmbedContentsResponse to find the dimensions of each embedding in the batch. Embeddings are returned in the same order as the request. ```go resp, _ := model.BatchEmbedContents(ctx, batch) for i, embedding := range resp.Embeddings { fmt.Printf("Embedding %d: %d dimensions\n", i, len(embedding.Values)) } ``` -------------------------------- ### Count Tokens Example Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/api-reference/responses-and-iterators.md Demonstrates how to use the CountTokensResponse to retrieve the total number of tokens for a given text. Ensure the model and context are properly initialized. ```go resp, _ := model.CountTokens(ctx, genai.Text("Hello world")) fmt.Printf("Total tokens: %d\n", resp.TotalTokens) ``` -------------------------------- ### Set System Instruction for Model Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/configuration.md Assigns a system prompt to guide the model's behavior. This is useful for setting the model's persona or task. ```go model.SystemInstruction = genai.NewUserContent( genai.Text("You are a helpful Python coding assistant. Provide complete, runnable code examples.")) ``` -------------------------------- ### Set Cached Content Expiration Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/types.md Examples demonstrating how to set cached content expiration using either an absolute ExpireTime or a TTL duration. ```go // Set expiration time: cc.Expiration = genai.ExpireTimeOrTTL{ ExpireTime: time.Now().Add(24 * time.Hour), } // Or TTL: cc.Expiration = genai.ExpireTimeOrTTL{ TTL: 24 * time.Hour, } ``` -------------------------------- ### Get Embedding Dimension Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/types.md Example of retrieving an embedding and printing its dimension. The embedding values are stored in the Values field of ContentEmbedding. ```go resp, _ := model.EmbedContent(ctx, genai.Text("Hello")) embedding := resp.Embedding fmt.Printf("Dimension: %d\n", len(embedding.Values)) ``` -------------------------------- ### Initialize Client with Credentials File Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/configuration.md Configure the client using a service account credentials file by providing its path. ```go client, err := genai.NewClient(ctx, option.WithCredFile("/path/to/credentials.json")) ``` -------------------------------- ### Initialize Client with Credentials JSON Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/configuration.md Authenticate by providing service account credentials directly as JSON bytes. ```go credBytes, _ := ioutil.ReadFile("/path/to/credentials.json") client, err := genai.NewClient(ctx, option.WithCredentialsJSON(credBytes)) ``` -------------------------------- ### Embed Content Example Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/api-reference/responses-and-iterators.md Shows how to use EmbedContentResponse to get the dimension of an embedding for a given text. The Embedding field contains the computed embedding values. ```go resp, _ := model.EmbedContent(ctx, genai.Text("Hello")) fmt.Printf("Dimension: %d\n", len(resp.Embedding.Values)) ``` -------------------------------- ### Iterate Through Streaming GenerateContent Responses Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/api-reference/responses-and-iterators.md Iterate over chunks of a streaming content generation response. Use `iter.Next()` to get individual chunks and `iter.MergedResponse()` after the loop to get the complete response. ```go iter := model.GenerateContentStream(ctx, genai.Text("Write a story")) for { resp, err := iter.Next() if err == iterator.Done { break } if err != nil { log.Fatal(err) } // Process each response chunk } ``` -------------------------------- ### Basic Text Generation in Go Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/API-OVERVIEW.md Demonstrates how to create a client, select a generative model, and generate text content. Ensure the GEMINI_API_KEY environment variable is set. ```go ctx := context.Background() client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("GEMINI_API_KEY"))) if err != nil { log.Fatal(err) } deferr client.Close() model := client.GenerativeModel("gemini-1.5-flash") resp, err := model.GenerateContent(ctx, genai.Text("Write a story")) if err != nil { log.Fatal(err) } fmt.Println(resp.Candidates[0].Content) ``` -------------------------------- ### Initialize Client with API Key Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/configuration.md Use an API key for authentication when creating a new client. The API key can be stored in an environment variable. ```go import "google.golang.org/api/option" client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("GEMINI_API_KEY"))) ``` -------------------------------- ### Get Model Information Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/api-reference/generative-model.md Use Info to retrieve metadata about the generative model, such as its name and version. ```go info, err := model.Info(ctx) if err != nil { log.Fatal(err) } fmt.Printf("Model: %s\nVersion: %s\n", info.Name, info.Version) ``` -------------------------------- ### Initialize Client with Custom HTTP Client Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/configuration.md Provide a custom HTTP client for the client configuration. This implies authentication is handled elsewhere. Note that this option cannot be used with cache clients. ```go import "net/http" customClient := &http.Client{ Timeout: 30 * time.Second, Transport: &http.Transport{ MaxIdleConns: 100, }, } client, err := genai.NewClient(ctx, option.WithHTTPClient(customClient)) ``` -------------------------------- ### Error Pattern Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/API-OVERVIEW.md Example of how to handle potential errors, including custom errors like `BlockedError`. ```APIDOC ### Error Pattern ```go resp, err := model.GenerateContent(ctx, ...) if err != nil { if be, ok := err.(*genai.BlockedError); ok { // Handle blocked content log.Printf("Blocked: %v", be) } else { // Handle other errors log.Printf("Error: %v", err) } } ``` ``` -------------------------------- ### Initialize Client with OAuth2 Token Source Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/configuration.md Authenticate using an OAuth2 token source, which is an alternative to using an API key. ```go import "golang.org/x/oauth2" tokenSource := oauth2.NewStaticTokenSource(&oauth2.Token{ AccessToken: accessToken, TokenType: "Bearer", }) client, err := genai.NewClient(ctx, option.WithTokenSource(tokenSource)) ``` -------------------------------- ### Get Embedding Model Name Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/api-reference/embedding-model.md Retrieve the name of the embedding model. This is useful for identifying which model is being used. ```go model := client.EmbeddingModel("embedding-001") fmt.Println(model.Name()) // "embedding-001" ``` -------------------------------- ### Create a New Client Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/README.md Instantiate a new client for SDK operations. This client is thread-safe and reusable. Ensure to close the client when done. ```go client, _ := genai.NewClient(ctx, option.WithAPIKey(apiKey)) deffer client.Close() ``` -------------------------------- ### Info Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/api-reference/generative-model.md Gets information about the model, including its metadata. It takes a context and returns model details or an error. ```APIDOC ## Info ### Description Gets information about the model, including its metadata. ### Method GET ### Endpoint /v1beta/models/{model_id} ### Parameters #### Path Parameters - **model_id** (string) - Required - The ID of the model to retrieve information for. #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **name** (string) - The name of the model. - **version** (string) - The version of the model. #### Response Example ```json { "name": "gemini-1.5-flash", "version": "1.5-flash-001" } ``` ``` -------------------------------- ### Configure Models Once Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/configuration.md Demonstrates the efficient approach of configuring model parameters once and reusing the configured model, compared to reconfiguring for each request. ```go // Good: Configure model once, reuse model := client.GenerativeModel("gemini-1.5-flash") model.Temperature = genai.Ptr[float32](0.7) model.MaxOutputTokens = genai.Ptr[int32](1000) for i := 0; i < 100; i++ { resp, _ := model.GenerateContent(ctx, genai.Text("prompt")) } // Less efficient: Reconfigure each time for i := 0; i < 100; i++ { model := client.GenerativeModel("gemini-1.5-flash") model.Temperature = genai.Ptr[float32](0.7) resp, _ := model.GenerateContent(ctx, genai.Text("prompt")) } ``` -------------------------------- ### Update Cached Content with Expiration Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/types.md Example of creating a CachedContentToUpdate and using it to update cached content with a TTL. ```go update := &genai.CachedContentToUpdate{ Expiration: &genai.ExpireTimeOrTTL{ TTL: 1 * time.Hour, }, } updated, _ := client.UpdateCachedContent(ctx, cc, update) ``` -------------------------------- ### Get Cached Content Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/api-reference/client.md Retrieves cached content by its name. The name should typically be in the format "cachedContents/xyz". ```go cc, err := client.GetCachedContent(ctx, "cachedContents/abc123xyz") ``` -------------------------------- ### Upload and Use a File Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/README.md Upload a file (e.g., a PDF document) and then reference it using its URI in a content generation prompt. ```go file, _ := client.UploadFileFromPath(ctx, "document.pdf", nil) resp, _ := model.GenerateContent(ctx, genai.FileData{URI: file.URI}) ``` -------------------------------- ### Creating Parts Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/API-OVERVIEW.md Demonstrates how to create different types of content parts for model input, including text, image data, file references, and function calls. ```go genai.Text("Hello") // Plain text genai.ImageData("png", bytes) // Image blob genai.FileData{URI: "..."} // File reference genai.FunctionCall{Name: "fn", Args: ..} // Function call ``` -------------------------------- ### Get Embedding Model Information Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/api-reference/embedding-model.md Retrieve metadata about the embedding model. This includes information like the model's name. ```go info, err := model.Info(ctx) fmt.Printf("Model: %s\n", info.Name) ``` -------------------------------- ### Client Creation Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/README.md The entry point for all SDK operations. The client is thread-safe and reusable. It is created using `genai.NewClient` with necessary authentication options. ```APIDOC ## Client The entry point for all SDK operations. Thread-safe and reusable. ### Usage ```go client, _ := genai.NewClient(ctx, option.WithAPIKey(apiKey)) defer client.Close() ``` ``` -------------------------------- ### Create and Use Cached Content with Tools in Go Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/api-reference/cached-content.md Demonstrates how to define tools, create a cached content object with these tools, and then use the cached content with a generative model. This is useful for scenarios where you want to reuse a set of tools and initial content across multiple interactions to improve efficiency. ```Go // Define tools to cache tools := []*genai.Tool{ { FunctionDeclarations: []*genai.FunctionDeclaration{ { Name: "get_weather", Description: "Get weather for a location", Parameters: &genai.Schema{ Type: genai.TypeObject, Properties: map[string]*genai.Schema{ "location": {Type: genai.TypeString}, }, }, }, }, }, } // Create cache with tools cc, _ := client.CreateCachedContent(ctx, &genai.CachedContent{ Model: "gemini-1.5-flash", Tools: tools, Contents: []*genai.Content{...}, Expiration: genai.ExpireTimeOrTTL{TTL: 1 * time.Hour}, }) // Use with cached tools model := client.GenerativeModelFromCachedContent(cc) resp, _ := model.GenerateContent(ctx, genai.Text("What's the weather?")) // Process function calls for _, call := range resp.Candidates[0].FunctionCalls() { result := getWeather(call.Args) // Send result back... } ``` -------------------------------- ### Cache Large Context with Go SDK Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/api-reference/cached-content.md Demonstrates creating a cached content with a large system instruction and multiple content parts, then using it to generate content and cleaning it up. ```go // Setup: Create cache once with large context largeSystemInstruction := genai.NewUserContent( genai.Text("You are a Python expert...")) largeContext := []*genai.Content{ genai.NewUserContent(genai.Text("Here are 100 code examples...")), genai.NewUserContent(genai.Text("Here are best practices...")), } cc, _ := client.CreateCachedContent(ctx, &genai.CachedContent{ Model: "gemini-1.5-flash", SystemInstruction: largeSystemInstruction, Contents: largeContext, Expiration: genai.ExpireTimeOrTTL{TTL: 1 * time.Hour}, }) // Use: Create model and make requests model := client.GenerativeModelFromCachedContent(cc) for i := 0; i < 100; i++ { resp, _ := model.GenerateContent(ctx, genai.Text("Code review this...")) } // Cleanup defer client.DeleteCachedContent(ctx, cc.Name) ``` -------------------------------- ### Client Info Configuration Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/API-OVERVIEW.md Shows how to configure client information, such as application name and version, for the Generative AI client. ```go genai.WithClientInfo("app-name", "1.0") ``` -------------------------------- ### Get Merged Response from Stream Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/api-reference/responses-and-iterators.md Retrieve the complete response by combining all streamed chunks after iteration is complete. This merged response should be equivalent to a non-streaming call. ```go iter := model.GenerateContentStream(ctx, genai.Text("Hello")) for { _, err := iter.Next() if err == iterator.Done { break } } merged := iter.MergedResponse() fmt.Println(merged.Candidates[0].Content) ``` -------------------------------- ### Concurrent Update Conflict Example Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/errors.md Demonstrates a concurrent update conflict when the `UpdateTime` of cached content is stale. This error occurs during an optimistic locking failure. ```go cc, _ := client.GetCachedContent(ctx, "cachedContents/abc123") // Another process updates the same cached content... // This fails because UpdateTime is stale _, err := client.UpdateCachedContent(ctx, cc, &genai.CachedContentToUpdate{...}) if err != nil { // Error: update time mismatch (concurrent modification) } ``` -------------------------------- ### Client Creation and Core Operations Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/COMPLETION_REPORT.txt Documentation for creating and managing the client, along with core operations like listing models and file management. ```APIDOC ## Client ### Description Provides methods for creating a client, managing models, handling file operations, and managing cached content. ### Methods - **NewClient**: Creates a new Generative AI client. - **Close**: Closes the client connection. - **GenerativeModel**: Retrieves a generative model. - **EmbeddingModel**: Retrieves an embedding model. - **ListModels**: Lists available generative models. - **UploadFile**: Uploads a file. - **UploadFileFromPath**: Uploads a file from a given path. - **GetFile**: Retrieves information about a file. - **DeleteFile**: Deletes a file. - **ListFiles**: Lists uploaded files. - **CreateCachedContent**: Creates cached content. - **GetCachedContent**: Retrieves cached content. - **UpdateCachedContent**: Updates cached content. - **DeleteCachedContent**: Deletes cached content. - **ListCachedContents**: Lists cached content. - **GenerativeModelFromCachedContent**: Creates a generative model from cached content. ### Parameters (Details for parameters for each method are found in the respective markdown files like `client.md` and `file-operations.md`) ### Request Example (Examples for specific operations are provided in the generated markdown files.) ### Response (Response details for specific operations are provided in the generated markdown files.) ``` -------------------------------- ### Configure Service Account Authentication (File Path) Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/README.md Authenticate API requests using a service account by specifying the credentials file path with `option.WithCredFile`. ```go option.WithCredFile(path) ``` -------------------------------- ### Handling File Upload Errors Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/errors.md Check for errors when uploading files. This example specifically notes the error condition when a file with the same name already exists. ```Go file, err := client.UploadFile(ctx, "existing-file", reader, nil) if err != nil { // Error: file with this name already exists } ``` -------------------------------- ### ChatSession - Multi-turn Conversations Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/README.md Enables multi-turn conversations with automatic history management. You can start a chat session from a model and send messages to maintain context. ```APIDOC ## ChatSession Multi-turn conversations with automatic history management. ### Usage ```go session := model.StartChat() resp, _ := session.SendMessage(ctx, genai.Text("message")) ``` ``` -------------------------------- ### Reuse Cache with Different Prompts Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/api-reference/cached-content.md Creates a cached content once with system instructions and initial contents, then reuses it to generate responses for multiple different prompts. ```go // Setup once cc, _ := client.CreateCachedContent(ctx, &genai.CachedContent{ Model: "gemini-1.5-flash", SystemInstruction: genai.NewUserContent(genai.Text("Help with coding")), Contents: []*genai.Content{ genai.NewUserContent(genai.Text("Here's our codebase...")), }, Expiration: genai.ExpireTimeOrTTL{TTL: 24 * time.Hour}, }) // Use multiple times with different prompts model := client.GenerativeModelFromCachedContent(cc) questions := []string{ "Explain the authentication flow", "What are the performance bottlenecks?", "How should we refactor the auth module?", } for _, q := range questions { resp, _ := model.GenerateContent(ctx, genai.Text(q)) fmt.Println(resp.Candidates[0].Content) } ``` -------------------------------- ### Use Cached Content for Large Context Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/configuration.md Shows how to cache system instructions and large context to reuse across multiple requests, improving efficiency for repeated interactions. ```go // Good: Cache system context for multiple requests cc, _ := client.CreateCachedContent(ctx, &genai.CachedContent{ Model: "gemini-1.5-flash", SystemInstruction: genai.NewUserContent( genai.Text("Large system instruction...")), Contents: []*genai.Content{ // Large context that will be reused }, Expiration: genai.ExpireTimeOrTTL{TTL: 1 * time.Hour}, }) model := client.GenerativeModelFromCachedContent(cc) for i := 0; i < 100; i++ { resp, _ := model.GenerateContent(ctx, genai.Text("query")) } ``` -------------------------------- ### Reusing Generative AI Clients Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/API-OVERVIEW.md Demonstrates the pattern of creating a Generative AI client once and reusing it for multiple model interactions to improve efficiency. ```go // Create once, reuse multiple times client, _ := genai.NewClient(ctx, option.WithAPIKey(apiKey)) defer client.Close() model1 := client.GenerativeModel("gemini-1.5-flash") model2 := client.GenerativeModel("gemini-1.5-pro") embedModel := client.EmbeddingModel("embedding-001") ``` -------------------------------- ### Generate Content with GenerativeModel Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/api-reference/generative-model.md Use GenerateContent to get a single response from the model. Ensure you handle potential errors like blocked content or API issues. ```go ctx := context.Background() model := client.GenerativeModel("gemini-1.5-flash") resp, err := model.GenerateContent(ctx, genai.Text("Explain quantum computing")) if err != nil { log.Fatal(err) } fmt.Println(resp.Candidates[0].Content) ``` -------------------------------- ### Get Cached Content by Name in Go Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/api-reference/cached-content.md Retrieves cached content metadata by its name using the `GetCachedContent` method. This is useful for checking cache status, expiration, and other metadata. ```go cc, err := client.GetCachedContent(ctx, "cachedContents/abc123xyz") if err != nil { log.Fatal(err) } fmt.Printf("Name: %s\n", cc.DisplayName) fmt.Printf("Created: %v\n", cc.CreateTime) fmt.Printf("Updated: %v\n", cc.UpdateTime) // Check if expiring soon if time.Until(cc.Expiration.ExpireTime) < 5*time.Minute { fmt.Println("Cache expiring soon!") } ``` -------------------------------- ### Update Cached Content Expiration Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/api-reference/cached-content.md Updates the expiration time for cached content. This example shows how to extend the TTL and includes a retry mechanism for concurrent modification errors. ```go cc, _ := client.GetCachedContent(ctx, "cachedContents/abc123") updated, err := client.UpdateCachedContent(ctx, cc, &genai.CachedContentToUpdate{ Expiration: &genai.ExpireTimeOrTTL{ TTL: 1 * time.Hour, }, }) if err != nil { log.Printf("Update failed: %v", err) cc, _ = client.GetCachedContent(ctx, "cachedContents/abc123") updated, _ = client.UpdateCachedContent(ctx, cc, &genai.CachedContentToUpdate{ Expiration: &genai.ExpireTimeOrTTL{TTL: 1 * time.Hour}, }) } fmt.Printf("Updated expiration: %v\n", updated.Expiration.ExpireTime) ``` -------------------------------- ### Create User Content Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/types.md Construct `Content` objects to represent messages in a conversation. Use `NewUserContent` for user messages, specifying the role and parts. ```go type Content struct { // "user" or "model" Role string // Parts that make up this content Parts []Part } ``` ```go content := genai.NewUserContent( genai.Text("What is AI?"), ) resp, _ := model.GenerateContent(ctx, genai.Text("What is AI?")) // Equivalent to: content2 := &genai.Content{ Role: "user", Parts: []genai.Part{genai.Text("What is AI?")}, } ``` -------------------------------- ### Configure Safety Settings Appropriately Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/configuration.md Illustrates adjusting specific safety categories and thresholds, rather than setting all categories, to fine-tune content moderation. ```go // Good: Adjust only categories you care about model.SafetySettings = []*genai.SafetySetting{ { Category: genai.HarmCategoryHateSpeech, Threshold: genai.HarmBlockThresholdLow, }, } // Other categories use model defaults // Less explicit: Let model use defaults // model.SafetySettings = nil ``` -------------------------------- ### GenerateContentStream Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/api-reference/generative-model.md Returns an iterator over streamed responses for content generation. It takes a context and variable parts as input and returns an iterator. Users can call `Next()` on the iterator to get response chunks. ```APIDOC ## GenerateContentStream ### Description Returns an iterator over streamed responses for content generation. ### Method POST ### Endpoint /v1beta/models/{model_id}:generateContentStream ### Parameters #### Path Parameters - **model_id** (string) - Required - The ID of the model to use. #### Query Parameters None #### Request Body - **contents** (array[object]) - Required - The content to send to the model. - **parts** (array[object]) - Required - The parts of the content. - **text** (string) - Optional - The text part of the content. - **inlineData** (object) - Optional - Inline data for the content. - **mimeType** (string) - Required - The MIME type of the data. - **data** (string) - Required - The base64-encoded data. ### Request Example ```json { "contents": [ { "parts": [ { "text": "Tell me a story" } ] } ] } ``` ### Response #### Success Response (200) - **candidates** (array[object]) - The model's generated candidates. - **content** (object) - The generated content. - **parts** (array[object]) - The parts of the content. - **text** (string) - The text part of the content. #### Response Example ```json { "candidates": [ { "content": { "parts": [ { "text": "Once upon a time..." } ] } } ] } ``` ### Note Call `Next()` on the iterator to get each response chunk. The iterator combines all chunks into a single merged response available via `MergedResponse()`. ``` -------------------------------- ### Get File Metadata Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/api-reference/client.md Retrieves metadata for a specific file using its name. The name can include or omit the "files/" prefix. Consider adding a delay if checking the file state immediately after retrieval. ```go file, err := client.GetFile(ctx, "files/abc123") if file.State == genai.FileStateProcessing { time.Sleep(5 * time.Second) } ``` -------------------------------- ### Set API Key Environment Variable (Windows) Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/configuration.md Shows how to set the GEMINI_API_KEY environment variable on Windows systems. ```cmd set GEMINI_API_KEY=your-api-key-here ``` -------------------------------- ### Upload File with Options and Error Handling Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/api-reference/file-operations.md Upload a file from a local path, specifying display name and MIME type. Includes robust error handling for the upload and deferred cleanup to delete the file. ```go file, err := client.UploadFileFromPath(ctx, "input.pdf", &genai.UploadFileOptions{ DisplayName: "Input Document", MIMEType: "application/pdf", }) if err != nil { // Handle error (file exists, permission denied, etc.) log.Printf("Upload failed: %v", err) return } defer func() { if err := client.DeleteFile(ctx, file.Name); err != nil { log.Printf("Cleanup failed: %v", err) } }() ``` -------------------------------- ### Upload File From Path Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/api-reference/client.md Convenience wrapper to upload a file by reading from a local file path. Requires a context and the path to the file. ```go file, err := client.UploadFileFromPath(ctx, "/path/to/document.pdf", nil) ``` -------------------------------- ### List Files with Iterator Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/api-reference/file-operations.md Iterate over all uploaded files associated with the client. Ensure to handle potential errors during iteration and check for iterator completion. ```go iter := client.ListFiles(ctx) for { file, err := iter.Next() if err == iterator.Done { break } if err != nil { log.Fatal(err) } fmt.Printf("%s (%s): %d bytes\n", file.DisplayName, file.Name, file.SizeBytes) } ``` -------------------------------- ### Diagnosing BlockedError Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/errors.md Demonstrates how to check for and handle a BlockedError when content generation fails. It shows how to access prompt feedback and candidate details if either was blocked. ```go resp, err := model.GenerateContent(ctx, genai.Text("prompt")) if err != nil { if be, ok := err.(*genai.BlockedError); ok { // Prompt was blocked if be.PromptFeedback != nil { fmt.Printf("Prompt blocked: %v\n", be.PromptFeedback.BlockReason) for _, sr := range be.PromptFeedback.SafetyRatings { fmt.Printf(" Category: %v, Probability: %v\n", sr.Category, sr.Probability) } } // Response was blocked if be.Candidate != nil { fmt.Printf("Response blocked: %v\n", be.Candidate.FinishReason) for _, sr := range be.Candidate.SafetyRatings { fmt.Printf(" Category: %v, Probability: %v\n", sr.Category, sr.Probability) } } } } ``` -------------------------------- ### Configure Service Account Authentication (JSON Bytes) Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/README.md Authenticate API requests using a service account by providing the credentials as JSON bytes with `option.WithCredentialsJSON`. ```go option.WithCredentialsJSON(bytes) ``` -------------------------------- ### Set Custom Client Info with WithClientInfo Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/types.md Use the `WithClientInfo` option to add custom key-value pairs to the client's request headers. This is useful for identifying your application or specific versions making requests. ```go func WithClientInfo(key, value string) option.ClientOption client, _ := genai.NewClient(ctx, option.WithAPIKey(apiKey), genai.WithClientInfo("my-app", "1.0")) ``` -------------------------------- ### Embedding Content in Go Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/API-OVERVIEW.md Demonstrates how to create an embedding model and generate content embeddings. This is useful for natural language understanding tasks. ```go embModel := client.EmbeddingModel("embedding-001") resp, _ := embModel.EmbedContent(ctx, genai.Text("Hello, world!")) fmt.Printf("Embedding dimension: %d\n", len(resp.Embedding.Values)) ``` -------------------------------- ### Create a New Generative AI Client Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/api-reference/client.md Creates a new Google generative AI client. Clients should be reused and are safe for concurrent use. Ensure authentication options like an API key are provided. ```go ctx := context.Background() client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("GEMINI_API_API_KEY"))) if err != nil { log.Fatal(err) } deffer client.Close() ``` -------------------------------- ### Configure Generative Model Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/API-OVERVIEW.md Set model parameters like temperature, max output tokens, and safety settings. Ensure the model name is valid for the API. ```go model := client.GenerativeModel("gemini-1.5-flash") model.Temperature = genai.Ptr[float32](0.7) model.MaxOutputTokens = genai.Ptr[int32](1000) model.SafetySettings = []*genai.SafetySetting{ {Category: genai.HarmCategoryHateSpeech, Threshold: genai.HarmBlockThresholdLow}, } ``` -------------------------------- ### Generate Text Content Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/README.md Create a generative model instance and use it to generate content from a text prompt. The model "gemini-1.5-flash" is used here. ```go model := client.GenerativeModel("gemini-1.5-flash") resp, _ := model.GenerateContent(ctx, genai.Text("prompt")) ``` -------------------------------- ### Configure Generation Settings Source: https://github.com/google/generative-ai-go/blob/main/_autodocs/types.md Customize generation parameters like `CandidateCount`, `MaxOutputTokens`, `Temperature`, `TopP`, and `TopK` by setting fields directly on the `GenerativeModel`. ```go type GenerationConfig struct { // Number of candidates to generate (default 1) CandidateCount *int32 // Maximum number of tokens in the response MaxOutputTokens *int32 // Randomness of responses (0.0 to 2.0, default 1.0) Temperature *float32 // Diversity parameter for nucleus sampling (0.0 to 1.0) TopP *float32 // Top-K sampling (only consider top K tokens) TopK *int32 // Sequence where generation should stop StopSequences []string // Additional format modifiers FrequencyPenalty *float32 // Presence penalty PresencePenalty *float32 } ``` ```go model := client.GenerativeModel("gemini-1.5-flash") model.Temperature = genai.Ptr[float32](0.7) model.MaxOutputTokens = genai.Ptr[int32](1000) model.TopP = genai.Ptr[float32](0.9) ```