( ValueError: Missing key inputs argument! To use the Google AI API, provide (`a...
错误信息
Traceback (most recent call last):
File "D:\新建文件夹\langchain-base\ollama_python.py", line 3, in <module>
client = genai.Client()
^^^^^^^^^^^^^^
File "C:\Users\27717\AppData\Local\Programs\Python\Python311\Lib\site-packages\google\genai\client.py", line 271, in __init__
self._api_client = self._get_api_client(
^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\27717\AppData\Local\Programs\Python\Python311\Lib\site-packages\google\genai\client.py", line 318, in _get_api_client
return BaseApiClient(
^^^^^^^^^^^^^^
File "C:\Users\27717\AppData\Local\Programs\Python\Python311\Lib\site-packages\google\genai\_api_client.py", line 683, in __init__
raise ValueError(
ValueError: Missing key inputs argument! To use the Google AI API, provide (`api_key`) arguments. To use the Google Cloud API,
provide (`vertexai`, `project` & `location`) arguments.
AI 解决方案
代码报错分析报告
1. 错误翻译
原文:ValueError: Missing key inputs argument! To use the Google AI API, provide (`api_key`) arguments. To use the Google Cloud API,
provide (`vertexai`, `project` & `location`) arguments.
译文:值错误:缺少关键输入参数!要使用Google AI API,请提供(`api_key`)参数。要使用Google Cloud API,
请提供(`vertexai`, `project`和`location`)参数。
2. 原因分析
genai.Client()时未提供必要的身份验证参数ollama_python.py文件第3行,调用client = genai.Client()时3. 解决方案
根据您的使用场景选择以下其中一种方案:
方案一:使用Google AI API(需要API密钥)
from google import genai
# 方式1:直接传入API密钥
client = genai.Client(api_key="YOUR_API_KEY_HERE")
# 方式2:从环境变量读取(推荐)
import os
client = genai.Client(api_key=os.getenv("GOOGLE_API_KEY"))
方案二:使用Google Cloud Vertex AI API
from google import genai
import vertexai
# 初始化vertexai
vertexai.init(project="YOUR_PROJECT_ID", location="us-central1")
# 创建genai客户端
client = genai.Client(vertexai=vertexai)
4. ️ 预防措施
安全最佳实践
- 使用
.env文件管理敏感信息- 使用
python-dotenv库加载环境变量 # requirements.txt中添加:python-dotenv
# 使用示例:
from dotenv import load_dotenv
import os
load_dotenv()
api_key = os.getenv("GOOGLE_API_KEY")
- 参数验证:在初始化客户端前检查必要参数是否存在
import os
api_key = os.getenv("GOOGLE_API_KEY")
if not api_key:
raise ValueError("请设置GOOGLE_API_KEY环境变量")
client = genai.Client(api_key=api_key)
️ 开发工具推荐
python-decouple或python-dotenv管理配置pydantic-settings进行配置验证下次遇到类似错误时,记得先检查必要的身份验证参数是否已正确配置!