我正在尝试使用 python 验证 Gemini API 密钥,我进行了研究,找到的解决方案是这样的:
import subprocess
import json
def verifiy_api_key(api_key):
comand_curl = f"""curl -s -H 'Content-Type: application/json' \
-d '{{"contents":[
{{"role": "user",
"parts":[{{"text": "Give me five subcategories of jazz?"}}]}}]}}' \
"https://generativelanguage.googleapis.com/v1/models/gemini-1.0-pro:generateContent?key={api_key}" """
result = subprocess.run(comand_curl, shell=True, text=True, capture_output=True)
response_json = json.loads(result.stdout)
# Verify curl sucess
if result.check_returncode:
#verify valid api Key
if response_json.get("error"):
print("Invalid Key")
return False
else:
print("Valid Key")
return True
else:
print("Error in curl.")
return False
# Replace 'YOUR_API_KEY' with your actual API key
GOOGLE_API_KEY = input('Type API Key: ')
while(verifiy_api_key(GOOGLE_API_KEY) == False):
print("Try Again")
GOOGLE_API_KEY = input('Type API Key: ')
我的问题是:“还有另一种验证 Gemini API 密钥的最佳方法吗?有什么捷径吗?”
obs:不要关注糟糕的代码,我只是在学习。
不确定您想在这里做什么。 Google 有一套很好的库,供开发人员在他们的应用程序中与 Gemini 接口。
首先阅读他们的文档或示例这里