Google Gemini 1.0 对接 - Python demo

本教程提供了通过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
}

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值