我无法连接到Gemini / Vertex AI。我已经尝试了Gemini聊天提供的两种不同的代码建议(见下文)。我非常确定在URL中使用的以下信息是正确的(绝对没有拼写错误):
API keyproject id
关于位置,我不太确定,控制台中没有显示位置,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"; // 尝试过的几个位置之一 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(); // 解析JSON响应以获取生成的文本 return responseContent; } else { throw new Exception($"Gemini请求错误: {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!") } } } }; // 将实例转换为值列表 var instances = new List<Google.Protobuf.WellKnownTypes.Value> { instance }; // 可选:预测的附加参数 var parameters = new Google.Protobuf.WellKnownTypes.Value { StructValue = new Struct { Fields = { { "param_key", Google.Protobuf.WellKnownTypes.Value.ForString("param_value") } } } }; try { // 发出预测请求 PredictResponse response = predictionClient.Predict(url, instances, parameters); // 打印响应 foreach (var prediction in response.Predictions) { Debug.WriteLine($"预测: {prediction}"); } } catch (Grpc.Core.RpcException e) { Debug.WriteLine($"RPC失败: {e.Status}"); }
我不知道还能尝试什么。
回答:
连接(调用)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 = "这张照片里有什么?" }, new Part { FileData = new() { MimeType = "image/png", FileUri = "gs://generativeai-downloads/images/scones.jpg" } } } } } }; // 发出请求,返回流式响应 using PredictionServiceClient.StreamGenerateContentStream response = predictionServiceClient.StreamGenerateContent(generateContentRequest);
Vertex AI Gemini API也作为REST API公开,文档见这里。然而,建议首先使用客户端库。