本文主要介绍如下内容
import requests
import json
def test_with_http(apikey, text):
url = f'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key={apikey}'
headers = {'Content-Type': 'application/json'}
data = {
'contents': [
{
'parts': [
{
'text': text
}
]
}
]
}
response = requests.post(url, headers=headers, data=json.dumps(data))
print(response.json())
if __name__ == '__main__':
apikey = "这里换成ApiKey"
text = "请做一个自我介绍"
test_with_http(apikey=apikey, text=text)
根据Gemini Api的使用文档介绍,要求Python版本在3.9以上,本次测试为 3.10 版本。
步骤
1.(可选) 建议创建一个全新的Python虚拟环境: python -m venv pyvenv
2.(可选)激活当前环境 : .\pyvenv\Scripts\activate
3. 安装Google提供的google-generativeai库:pip install google-generativeai
4. 测试代码:
import google.generativeai as genai
def test_with_api(apikey, text):
# 注意这行代码,官方提供的demo没有transport='rest' 会出现超时问题,因此一点要加上
genai.configure(api_key=apikey, transport='rest')
model = genai.GenerativeModel('gemini-pro')
response = model.generate_content(text, stream=True)
for chunk in response:
print(chunk.text, end='', flush=True)
if __name__ == '__main__':
apikey = "这里换成ApiKey"
text = "请做一个自我介绍"
test_with_api(apikey=apikey, text=text)
解决方案:
升级 google-auth ,在终端执行下面指令
pip install --upgrade google-auth
google.api_core.exceptions.RetryError: Deadline of 60.0s exceeded while calling target function
原因:
1. 网络问题,这个情况自行Google、BaiDu解决
2. 没有设置网络传输方式 transport = ‘rest’,也就是步骤4中提示的注意点,此时需要在代码中修改为 : genai.configure(api_key=apikey, transport='rest')
目前,Gemini提供了2个免费的APi服务:
import google.generativeai as genai
import PIL.Image
def test_gemini_pro_vision(apikey, text, image_path):
genai.configure(api_key=apikey, transport='rest')
model = genai.GenerativeModel('gemini-pro-vision')
img = PIL.Image.open(image_path)
response = model.generate_content([text, img], stream=True)
response.resolve()
print(response.text)
if __name__ == '__main__':
apikey = "这里换成ApiKey"
test_gemini_pro_vision(apikey, text="请你描述一下图片的内容。", image_path='2.jpg')
这样改写一下:
powered by kaifamiao