Gemini Example with Go

English 简体中文 Tiếng Việt
Summary

To interact with Google's Gemini LLM using Go, developers can leverage the official Go SDK. The process involves initializing a genai.Client with an API key, then selecting a specific generative model such as "gemini-1.5-flash-latest". After optionally setting parameters like Temperature to control output randomness, content generation is initiated by calling model.GenerateContent with the desired text prompt. The response, containing potential outputs in resp.Candidates, can then be iterated and cast to genai.Text to retrieve the model's generated content. This workflow facilitates basic chat functionalities, like translation, with the Gemini model.

要连接并使用 Google 的 LLM Gemini 和 Go,可以使用他们的官方Go SDK来实现。在这篇文章中,我们将展示一个简单的聊天示例,以演示如何使其与 Go 一起工作。

此示例只是要求模型将一些英文翻译成中文并获取其输出。代码实际上如下所示:

var client *genai.Client
// geminiOnce.Do(func() {
client, err = genai.NewClient(ctx, option.WithAPIKey(string(apiKey)))
if err != nil {
	log.Fatal(err)
}

model := client.GenerativeModel("gemini-1.5-flash-latest")
model.SetTemperature(0.1)
resp, err := model.GenerateContent(ctx, genai.Text("Translate 'Hello world' to Chinese"))
if err != nil {
	log.Printf("Error generating content: %v", err)
	return "", err
}

for _, candidate := range resp.Candidates {
	if candidate != nil {
		if candidate.Content.Parts != nil {
		     log.Printf("Output: %s", string(candidate.Content.Parts[0].(genai.Text)))
		}
	}
}

以下是提供的代码片段的分步解释:

1. 声明一个客户端变量

var client *genai.Client
  • 声明了一个类型为*genai.Client的指针变量 client。
  • 此变量将保存用于与genai服务交互的已初始化客户端实例。

2. 初始化客户端

client, err = genai.NewClient(ctx, option.WithAPIKey(string(apiKey)))
if err != nil {
	log.Fatal(err)
}
  • genai.NewClient(ctx, option.WithAPIKey(string(apiKey))):
    • 使用 genai 库创建一个新的客户端实例。
    • ctx: 传递一个 context.Context,启用请求取消或超时控制。
    • option.WithAPIKey(string(apiKey)): 指定用于对客户端进行身份验证的 API 密钥。可以在Google AI Studio上创建一个新项目来生成 API 密钥。
  • 错误处理:
    • 如果 err 不为 nil,程序将记录错误并使用 log.Fatal(err) 退出。

3. 选择一个生成模型

model := client.GenerativeModel("gemini-1.5-flash-latest")
  • 客户端的 GenerativeModel 方法选择一个特定的模型版本来使用。
  • 这里,模型是“gemini-1.5-flash-latest”,它大概是一个生成式 AI 模型。有其他可用的模型,其中 2.0 是实验阶段的最新模型。

4. 设置模型参数

model.SetTemperature(0.1)
  • 将模型的温度设置为 0.1。
  • 温度控制输出的随机性。
  • 较低的温度(例如,0.1)会产生更确定的结果,而较高的温度会引入更多变化。

通过调用 model.SetXXX() 也可以设置其他参数,例如输出标记长度,

5. 生成内容

resp, err := model.GenerateContent(ctx, genai.Text("Translate 'Hello world' to Chinese"))
if err != nil {
	log.Printf("Error generating content: %v", err)
	return "", err
}
  • GenerateContent(ctx, genai.Text(...)):
    • 使用输入“Translate 'Hello world' to Chinese”向模型发送生成请求。
    • 输入包含在genai.Text中。一种通用的文本处理方式,它也支持其他类型,如 Blob(图像)、FunctionCall。

6. 处理响应

for _, candidate := range resp.Candidates {
	if candidate != nil {
		if candidate.Content.Parts != nil {
		     log.Printf("Output: %s", string(candidate.Content.Parts[0].(genai.Text)))
		}
	}
}
  • 迭代候选者:
    • resp.Candidates包含模型可能的输出。候选者的数量可以在步骤 4 中使用model.SetCandidateCount()设置。默认值为 1,目前也只支持 1。
    • 循环处理响应中的每个候选者。
  • 由于上下文是文本聊天,因此这里的输出也是genai.Text类型。我们需要将Part转换为genai.Text类型,因为它最初是一个接口。

有了以上内容,您应该能够深入研究 SDK 和 Gemini 模型提供的其他大量功能。

EXAMPLE GO TRANSLATION GOLANG GEMINI

  RELATED

  COMMENTS

2
Anonymous
Dec 23, 2024 at 5:14 am

Where the ctx comming from? (cwl)

Ke Pi
Dec 23, 2024 at 6:09 am

you can just create one or pass from your request if you have one already.

To create one, can just do:

ctx := context.Background()