Skip to main content

与Gemini集成

package main

import (
"context"
"fmt"
"github.com/tmc/langchaingo/llms/googleai"
"log"
"os"
"strings"
)

//go get github.com/tmc/langchaingo/llms/googleai@v0.1.13
//https://aistudio.google.com/app/apikey
//https://ai.google.dev/gemini-api/docs/models?hl=zh-cn
//https://ai.google.dev/gemini-api/docs/pricing?hl=zh-cn

func main() {

ctx := context.Background()

// Or with explicit API key
llm, err := googleai.New(
ctx,
googleai.WithDefaultModel("gemini-2.5-flash"),
googleai.WithAPIKey(os.Getenv("GEMINI_KEY")),
)

if err != nil {
log.Printf("创建 gemini LLM 失败: %v", err)
return
}

// 简单的文本生成
questions := []string{
"请用中文简单介绍一下人工智能",
"什么是 LangChain?",
}

for i, question := range questions {
fmt.Printf("\n问题 %d: %s\n", i+1, question)
fmt.Println(strings.Repeat("-", 50))
response, err := llm.Call(ctx, question)
if err != nil {
log.Printf("LLM 调用失败: %v", err)
continue
}
fmt.Printf("回答: %s\n", response)
}
}