在这种情况下我应该怎么做才能更正此代码?

问题描述 投票:0回答:1

下面给出的代码给出错误输出“&{[0xc00040e740] }”

package main

import (
    "context"
    "fmt"
    "log"
    "os"

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

func main() {
    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("GEMINI_API_KEY")))
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()

    // For text-only input, use the gemini-pro model
    model := client.GenerativeModel("gemini-pro")
    resp, err := model.GenerateContent(ctx, genai.Text("Write a story about a magic backpack."))
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(resp)
}

上述所有内容都像 API KEY 一样设置,但仍然出现错误,请帮助我处理此代码。

我试图制作一个Go程序,它可以使用Gemini提供的API密钥与Gemini交互/聊天。但我收到错误输出“&{[0xc00040e740] }”。

go runtime-error google-gemini
1个回答
0
投票

您忘记加载 godotenv。

godotenv.Load()

这假设您还在 .env 中设置了环境变量

我的代码:

package main

import (
    "context"
    "fmt"
    "github.com/joho/godotenv"
    "log"
    "os"

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

func main() {
    godotenv.Load()
    ctx := context.Background()
    client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("GEMINI_API_KEY")))
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()

    model := client.GenerativeModel("gemini-1.0-pro")
    resp, err := model.GenerateContent(ctx, genai.Text("What is the average size of a swallow?"))
    if err != nil {
        log.Fatal(err)
    }

    printResponse(resp)
}

func printResponse(resp *genai.GenerateContentResponse) {
    for _, cand := range resp.Candidates {
        if cand.Content != nil {
            for _, part := range cand.Content.Parts {
                fmt.Println(part)
            }
        }
    }
    fmt.Println("---")
}
© www.soinside.com 2019 - 2024. All rights reserved.