无法连接Gemini / Vertex AI (C#/.Net)

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

我是 Gemini / Vertex AI 新手,无法连接。我尝试了 Gemini 聊天提出的两种不同的代码建议(见下文)。我非常确定 URL 中使用的以下信息是正确的(当然没有拼写错误):

API密钥 项目编号

我不太确定该位置,控制台中没有显示任何内容,并且 Gemini 聊天说我的项目没有明确的位置。根据机器人的建议,我通过 Cloud SDK 请求了我的项目 ID 的列表,并尝试了结果列表中的多个位置。不过,位置似乎对响应没有影响。

该项目启用了 Gemini 和 Vertex AI API。我还在 Cloud 控制台中定义了用户角色“所有者”和“Vertex AI 用户”,并且 API 密钥没有限制。此外,环境变量 GOOGLE_APPLICATION_CREDENTIALS 已使用适当的信息进行设置。

根据 Gemini 聊天机器人的说法,生成的 URL 应该“很有可能”工作。据我所知,机器人列出的条件也已满足,但显然有些问题。非常感谢任何帮助!

以下是两个代码版本(虽然都使用相同的URL,但HTTP错误不同):

// 以下变量对于两者来说是相同的:========================================

    private static readonly string projectId = "xxxx";
    private static readonly string location = "europe-west1"; // one of several tried
    private static readonly string geminiApiKey = "xxxx";
    private static readonly string url = $"https://{location}-aiplatform.googleapis.com/v1/projects/{projectId}/locations/{location}/publishers/google/models/gemini-pro:generateContent";

//================================================ =============================================

// 尝试 1 - 导致 HTTP 401“未经授权”========================================

    var content = new StringContent(CreateTextRequestBody(text), Encoding.UTF8, "application/json");
    var client = new HttpClient();

    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", geminiApiKey);

    var response = await client.PostAsync(url, content);

    if (response.IsSuccessStatusCode)
    {
          string responseContent = await response.Content.ReadAsStringAsync();
          // Parse the JSON response to get the generated text
          return responseContent;
     }
     else
     {
          throw new Exception($"Gemini request error: {response.StatusCode} {response.ReasonPhrase}");
     }

//================================================ =============================================

// 尝试 2 - 导致 HTTP 404“错误的 gRPC 响应”。 =====================================

    var instance = new Google.Protobuf.WellKnownTypes.Value
    {
         StructValue = new Struct
         {
             Fields =
             {
                 { "input_text", Google.Protobuf.WellKnownTypes.Value.ForString("Hello, world!") }
             }
         }
    };

    // Convert instance to a list of values
    var instances = new List<Google.Protobuf.WellKnownTypes.Value> { instance };

    // Optional: Additional parameters for prediction
    var parameters = new Google.Protobuf.WellKnownTypes.Value
    {
        StructValue = new Struct
        {
            Fields =
            {
                { "param_key", Google.Protobuf.WellKnownTypes.Value.ForString("param_value") }
            }
        }
    };

    try
    {
        // Making the predict request
        PredictResponse response = predictionClient.Predict(url, instances, parameters);

        // Print the response
        foreach (var prediction in response.Predictions)
        {
            Debug.WriteLine($"Prediction: {prediction}");
        }
    }
    catch (Grpc.Core.RpcException e)
    {
        Debug.WriteLine($"RPC failed: {e.Status}");
    }

//================================================ =============================================

再次强调,任何帮助都会很棒,我不知道还能尝试什么。

c# .net google-cloud-platform google-gemini
1个回答
0
投票

连接(调用)Gemini 模型 API 有两种方式:Google AI 或 GCP Vertex AI。请参阅此讨论以详细了解何时使用哪些方法及其差异。 Google AI 使用 API 密钥作为身份验证凭据,而 Vertex AI 使用 GCP 服务帐户。 您的描述和代码似乎混合了两种方法(调用 Vertex AI 端点时不需要 API 密钥)。

由于您已配置 GCP 项目,因此您可以使用 Vertex AI C# 客户端库连接到 Gemini API。这是详细说明。长话短说:博士:

  • 安装客户端库
  • 设置身份验证
  • 使用库来使用 Gemini 模型

这是示例代码片段:

var generateContentRequest = new GenerateContentRequest
        {
            Model = $"projects/{projectId}/locations/{location}/publishers/{publisher}/models/{model}",
            GenerationConfig = new GenerationConfig
            {
                Temperature = 0.4f,
                TopP = 1,
                TopK = 32,
                MaxOutputTokens = 2048
            },
            Contents =
            {
                new Content
                {
                    Role = "USER",
                    Parts =
                    {
                        new Part { Text = "What's in this photo?" },
                        new Part { FileData = new() { MimeType = "image/png", FileUri = "gs://generativeai-downloads/images/scones.jpg" } }
                    }
                }
            }
        };

        // Make the request, returning a streaming response
        using PredictionServiceClient.StreamGenerateContentStream response = predictionServiceClient.StreamGenerateContent(generateContentRequest);

Vertex AI Gemini API 也作为 REST API 公开,如此处所述。不过,建议先使用客户端库。

© www.soinside.com 2019 - 2024. All rights reserved.