( ValueError: Missing key inputs argument! To use the Google AI API, provide (`a...

2025年12月13日 16:19 状态: processing

🚨 错误信息

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, projectlocation)参数。
`

2. 原因分析


  • 根本原因:在初始化genai.Client()时未提供必要的身份验证参数

  • 错误位置ollama_python.py文件第3行,调用client = genai.Client()

  • 上下文说明:Google的genai库需要API密钥或Google Cloud相关配置才能创建客户端实例
  • 3. 解决方案

    根据您的使用场景选择以下其中一种方案:

    方案一:使用Google AI API(需要API密钥)


    python
    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


    python
    from google import genai
    import vertexai

    初始化vertexai


    vertexai.init(project="YOUR_PROJECT_ID", location="us-central1")

    创建genai客户端


    client = genai.Client(vertexai=vertexai)

    4. ️ 预防措施

    安全最佳实践


  • 环境变量管理:永远不要将API密钥硬编码在代码中

  • - 使用
    .env文件管理敏感信息
    - 使用
    python-dotenv库加载环境变量

    python
    # requirements.txt中添加:python-dotenv
    # 使用示例:
    from dotenv import load_dotenv
    import os
    load_dotenv()
    api_key = os.getenv("GOOGLE_API_KEY")

  • 参数验证:在初始化客户端前检查必要参数是否存在

  • python
    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-decouplepython-dotenv管理配置

  • 使用pydantic-settings`进行配置验证

  • 使用Google Cloud Secret Manager存储API密钥
  • ---
    下次遇到类似错误时,记得先检查必要的身份验证参数是否已正确配置!