教學課程:開始使用 Gemini API


本教學課程示範如何透過 Google AI Go SDK 存取 Go 應用程式適用的 Gemini API。

在本教學課程中,您將瞭解如何執行下列操作:

此外,本教學課程包含進階用途相關章節 (例如嵌入計算符記),以及控制內容產生的選項。

先備知識

本教學課程假設您已熟悉如何使用 Go 建構應用程式。

如要完成本教學課程,請確認您的開發環境符合下列規定:

  • Go 1.20 以上版本

設定專案

呼叫 Gemini API 之前,您需要先設定專案,包括設定 API 金鑰、安裝 SDK 套件,以及初始化模型。

設定 API 金鑰

如要使用 Gemini API,您必須具備 API 金鑰。如果您沒有金鑰 請在 Google AI Studio 中建立金鑰

取得 API 金鑰

確保 API 金鑰安全

強烈建議您「不要」在版本管控系統中登錄 API 金鑰。您應該改用密鑰儲存庫做為 API 金鑰。

本教學課程的所有程式碼片段都假設您是以環境變數的形式存取 API 金鑰。

安裝 SDK 套件

如要在自己的應用程式中使用 Gemini API,請在模組目錄中將 Go SDK 套件 get

go get github.com/google/generative-ai-go

初始化生成式模型

您必須先匯入並初始化生成式模型,才能發出 API 呼叫。

import "github.com/google/generative-ai-go/genai"
import "google.golang.org/api/option"

ctx := context.Background()
// Access your API key as an environment variable (see "Set up your API key" above)
client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("API_KEY")))
if err != nil {
  log.Fatal(err)
}
defer client.Close()

// The Gemini 1.5 models are versatile and work with most use cases
model := client.GenerativeModel("gemini-1.5-flash")

指定模型時,請注意下列事項:

  • 使用您用途專屬的模型 (例如,gemini-1.5-flash 適用於多模態輸入)。在本指南中,各實作方法的操作說明會列出每種用途的建議模型。

實作常見用途

專案設定完成後,您就可以瞭解如何使用 Gemini API 實作不同的用途:

在進階用途部分中,您可以找到 Gemini API 和嵌入的相關資訊。

從純文字輸入來生成文字

如果提示內容只包含文字,請使用 Gemini 1.5 模型或搭載 generateContent 的 Gemini 1.0 Pro 模型,生成文字輸出:

ctx := context.Background()
// Access your API key as an environment variable (see "Set up your API key" above)
client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("API_KEY")))
if err != nil {
  log.Fatal(err)
}
defer client.Close()

// The Gemini 1.5 models are versatile and work with both text-only and multimodal prompts
model := client.GenerativeModel("gemini-1.5-flash")
resp, err := model.GenerateContent(ctx, genai.Text("Write a story about a magic backpack."))
if err != nil {
  log.Fatal(err)
}

根據文字和圖片輸入內容產生文字 (多模態)

Gemini 提供多種可處理多模態輸入的模型 (Gemini 1.5 模型),方便您輸入文字和圖片。請務必查看提示的圖片規定

如果提示輸入內容包含文字和圖片,請使用 Gemini 1.5 模型和 generateContent 方法生成文字輸出:

ctx := context.Background()
// Access your API key as an environment variable (see "Set up your API key" above)
client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("API_KEY")))
if err != nil {
  log.Fatal(err)
}
defer client.Close()

// The Gemini 1.5 models are versatile and work with both text-only and multimodal prompts
model := client.GenerativeModel("gemini-1.5-flash")

imgData1, err := os.ReadFile(pathToImage1)
if err != nil {
  log.Fatal(err)
}

imgData2, err := os.ReadFile(pathToImage1)
if err != nil {
  log.Fatal(err)
}

prompt := []genai.Part{
  genai.ImageData("jpeg", imgData1),
  genai.ImageData("jpeg", imgData2),
  genai.Text("What's different between these two pictures?"),
}
resp, err := model.GenerateContent(ctx, prompt...)

if err != nil {
  log.Fatal(err)
}

打造多輪對話 (聊天)

使用 Gemini 即可多回合,建立任意形式的對話。SDK 會透過管理對話狀態來簡化程序,因此與 GenerateContent 不同,您不需要自行儲存對話記錄。

如要建構多輪對話 (例如對話),請使用 Gemini 1.5 模型或 Gemini 1.0 Pro 模型,然後呼叫 startChat() 初始化對話。接著使用 sendMessage() 傳送新的使用者訊息,這個訊息也會將訊息和回應附加到即時通訊記錄中。

與對話中的內容相關的 role 有兩種可能的選項:

  • user:提供提示的角色。這個值是 SendMessage 呼叫的預設值。

  • model:提供回應的角色。透過現有的 history 呼叫 StartChat() 時,您可以使用這個角色。

ctx := context.Background()
// Access your API key as an environment variable (see "Set up your API key" above)
client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("API_KEY")))
if err != nil {
  log.Fatal(err)
}
defer client.Close()

// The Gemini 1.5 models are versatile and work with multi-turn conversations (like chat)
model := client.GenerativeModel("gemini-1.5-flash")
// Initialize the chat
cs := model.StartChat()
cs.History = []*genai.Content{
  &genai.Content{
    Parts: []genai.Part{
      genai.Text("Hello, I have 2 dogs in my house."),
    },
    Role: "user",
  },
  &genai.Content{
    Parts: []genai.Part{
      genai.Text("Great to meet you. What would you like to know?"),
    },
    Role: "model",
  },
}

resp, err := cs.SendMessage(ctx, genai.Text("How many paws are in my house?"))
if err != nil {
  log.Fatal(err)
}

使用串流加快互動速度

根據預設,模型會在完成整個產生程序後傳回回應。您不必等待整個結果,就能實現更快速的互動,並改用串流處理部分結果。

以下範例說明如何使用 GenerateContentStream 方法實作串流,根據文字和圖片輸入提示產生文字。

ctx := context.Background()
// Access your API key as an environment variable (see "Set up your API key" above)
client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("API_KEY")))
if err != nil {
  log.Fatal(err)
}
defer client.Close()

// The Gemini 1.5 models are versatile and work with both text-only and multimodal prompts
model := client.GenerativeModel("gemini-1.5-flash")

imageBytes, err := os.ReadFile(pathToImage)

img := genai.ImageData("jpeg", imageBytes)
prompt := genai.Text("Tell me a story about this animal")
iter := model.GenerateContentStream(ctx, img, prompt)

for {
  resp, err := iter.Next()
  if err == iterator.Done {
    break
  }
  if err != nil {
    log.Fatal(err)
  }

  // ... print resp
}

在純文字輸入和聊天使用情境中,您也可以採取類似的做法。

prompt := genai.Text("Tell me a story about a lumberjack and his giant ox")
iter := model.GenerateContentStream(ctx, prompt)
prompt := genai.Text("And how do you feel about that?")
iter := cs.SendMessageStream(ctx, prompt)

實作進階用途

本教學課程前一節所述的常見用途,可協助您熟悉 Gemini API 的使用方式。本節說明一些較進階的用途。

使用嵌入

嵌入是一種技術,用於將資訊顯示為陣列中的浮點數清單。您可以透過 Gemini 以向量形式表示文字 (字詞、句子和文字區塊),比較嵌入和對比。舉例來說,具有相同主題或情緒的兩段文字應有類似的嵌入,並且可透過數學相似度等數學比較技巧來識別。

搭配 EmbedContent 方法 (或 BatchEmbedContent 方法) 使用 embedding-001 模型產生嵌入。以下範例會產生單一字串的嵌入:

ctx := context.Background()
// Access your API key as an environment variable (see "Set up your API key" above)
client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("API_KEY")))
if err != nil {
  log.Fatal(err)
}
defer client.Close()
// For embeddings, use the embedding-001 model
em := client.EmbeddingModel("embedding-001")
res, err := em.EmbedContent(ctx, genai.Text("The quick brown fox jumps over the lazy dog."))

if err != nil {
  panic(err)
}
fmt.Println(res.Embedding.Values)

函式呼叫

函式呼叫可讓您輕鬆從生成式模型取得結構化資料輸出內容。接著,您可以使用這些輸出內容呼叫其他 API,並將相關的回應資料傳回模型。換句話說,函式呼叫可協助您將生成式模型連結至外部系統,讓產生的內容包含最新且準確的資訊。詳情請參閱函式呼叫教學課程

計算符記數量

使用長提示時,建議先計算符記再傳送任何內容至模型。下列範例說明如何將 CountTokens() 用於各種用途:

// For text-only input
text := "Parrots can be green and live a long time."
resp, err := model.CountTokens(ctx, genai.Text(text))
if err != nil {
  log.Fatal(err)
}
fmt.Println(resp.TotalTokens)
// For text-and-image input (multimodal)
text := "Parrots can be green and live a long time."
imageBytes, err := os.ReadFile(pathToImage)
if err != nil {
  log.Fatal(err)
}

resp, err := model.CountTokens(
    ctx,
    genai.Text(text),
    genai.ImageData("png", imageBytes))
  if err != nil {
    log.Fatal(err)
}
fmt.Println(resp.TotalTokens)

控管內容生成功能的選項

您可以設定模型參數及使用安全設定,控管內容產生作業。

設定模型參數

您傳送至模型的每個提示都含有參數值,用來控制模型生成回覆的方式。模型可能會針對不同的參數值產生不同的結果。進一步瞭解模型參數。系統會在模型執行個體的生命週期內保留設定。

// ...

// The Gemini 1.5 models are versatile and work with most use cases
model := client.GenerativeModel("gemini-1.5-flash")

// Configure model parameters by invoking Set* methods on the model.
model.SetTemperature(0.9)
model.SetTopK(1)

// ...

使用安全性設定

您可以使用安全性設定,調整收到可能視為有害回應的機率。根據預設,安全性設定會封鎖中等和/或很有可能為不安全的內容。進一步瞭解安全性設定

以下說明如何進行各項安全性設定:

// ...

// The Gemini 1.5 models are versatile and work with most use cases
model := client.GenerativeModel("gemini-1.5-flash")

model.SafetySettings = []*genai.SafetySetting{
  {
    Category:  genai.HarmCategoryHarassment,
    Threshold: genai.HarmBlockOnlyHigh,
  },
}

// ...

你也可以設置多項安全性設定:

// ...

// The Gemini 1.5 models are versatile and work with most use cases
model := client.GenerativeModel("gemini-1.5-flash")

model.SafetySettings = []*genai.SafetySetting{
  {
    Category:  genai.HarmCategoryHarassment,
    Threshold: genai.HarmBlockOnlyHigh,
  },
  {
    Category:  genai.HarmCategoryHateSpeech,
    Threshold: genai.HarmBlockMediumAndAbove,
  },
}

// ...

後續步驟

  • 「提示設計」是指建立提示的程序,會從語言模型中取得所需回應。想確保語言模型提供準確且高品質的回覆,就必須撰寫條理分明的提示。瞭解撰寫提示的最佳做法

  • Gemini 提供多種不同模型版本,可滿足不同用途的需求,例如輸入類型和複雜度、對話或其他對話方塊語言工作的實作方式,以及大小限制。瞭解可用的 Gemini 模型