调用Google AI嵌入接口遇“Specified method is not supported”异常求助
解决Google AI Embedding调用中的"Specified method is not supported"异常
代码中的核心问题
- 重复初始化GenerativeModel:连续两次调用
googleAI.GenerativeModel(embeddingModel),第一次调用未赋值给变量,属于无效操作。 - EmbedContent方法参数冗余:调用
model.EmbedContent(input, embeddingModel)时,额外传递embeddingModel完全多余——当前model已经基于该嵌入模型创建,SDK的EmbedContent方法不需要重复传入模型ID。 - 异常捕获后的空对象访问:当
EmbedContent抛出异常时,仅打印错误信息但未处理空对象,此时embedding仍是初始的空EmbedContentResponse实例,访问embedding.Embedding.Values必然引发后续异常。
修正后的代码
public static async Task<List<float>> GetEmbedding(string input, CancellationToken cancellationToken = default) { string embeddingModel = "text-embedding-3-small"; string apiKey = "your-actual-api-key"; // 替换为真实API Key // 初始化GoogleAI客户端 GoogleAI googleAI = new(apiKey: apiKey); // 创建嵌入模型实例 GenerativeModel model = googleAI.GenerativeModel(embeddingModel); EmbedContentResponse embedding; try { // 正确调用EmbedContent,无需重复传入模型ID embedding = await model.EmbedContent(input, cancellationToken: cancellationToken); } catch (Exception ex) { Console.WriteLine($"嵌入生成失败: {ex.Message}"); // 根据业务需求选择:抛出异常终止流程,或返回空列表 throw; // return new List<float>(); } // 空值保护,避免空引用异常 return embedding?.Embedding?.Values?.ToList() ?? new List<float>(); }
额外注意事项
- 确保使用最新版本的Google AI .NET SDK,旧版本可能存在方法参数不兼容问题。
- 确认API Key具备调用嵌入模型的权限,且账户有足够的调用配额。
- 生产环境中禁止硬编码API Key,建议通过配置文件或环境变量读取。
内容的提问来源于stack exchange,提问作者Max
相关产品推荐
相关产品推荐

