本教程提供了通过Python使用gemini1.0版本的方法,目前1.0版本是免费使用的,但是数据会被收集。
想要对接API,不仅需要自己去获取Key,还需要 科学 上网。
Python环境
- Python 3.9+
环境配置
安装Python sdk
pip install -q -U google-generativeai
使用
gemini-pro
此模型仅支持文本聊天、文本补全
import google.generativeai as genai
import os
API_KEY = os.environ.get('API_KEY')
model = 'gemini-pro'
genai.configure(api_key=API_KEY)
contents_chat = [
{
"role": "user",
"parts": [
{
"text": "太阳系"
},
]
}
]
client = genai.GenerativeModel(model)
response = client.generate_content(
contents=contents_chat
)
print(response.text)
contents_text = ['什么是太阳系']
response = client.generate_content(
contents=contents_text
)
print(response.text)
gemini-pro-vision
此模型支持多模态输入,文本+图片/文件数据
值得注意的是,图片base64数据要去掉 data:image/jpeg;base64,
前缀
import google.generativeai as genai
from meutils.io.image import image_to_base64
import os
API_KEY = os.environ.get('API_KEY')
model = 'gemini-pro-vision'
genai.configure(api_key=API_KEY)
image_base64 = image_to_base64('test-assets/test1.jpg', for_image_url=False)
contents_chat = [
{
"role": "user",
"parts": [
{
"text": "这个图上有什么"
},
{
"inline_data": {
"mime_type": "image/jpeg",
"data": image_base64
}
}
]
}
]
client = genai.GenerativeModel(model)
response = client.generate_content(
contents=contents_chat
)
print(response.text)
方法
generate_content
generate_content(
contents: content_types.ContentsType,
*,
generation_config: (generation_types.GenerationConfigType | None) = None,
safety_settings: (safety_types.SafetySettingOptions | None) = None,
stream: bool = False,
**kwargs
) -> generation_types.GenerateContentResponse
参数类型
contents
[
object (Content)
]
Content
{
"parts": [
{
object (Part)
}
],
"role": string
}
Part
{
// 以下字段必须放在不同的object里:
"text": string,
"inlineData": {
object (Blob)
},
"functionCall": {
object (FunctionCall)
},
"functionResponse": {
object (FunctionResponse)
}
// End of list of possible types for union field data.
}
Blob
{
"mimeType": string,
"data": string
}