文章摘要
加载中...|
此内容根据文章生成,并经过人工审核,仅用于文章内容的解释与总结 投诉

概述

Google Gemini 是 Google 的多模态 AI 模型系列,原生支持文本、图像、视频、音频等多种数据类型。本文将深入介绍 Gemini API 的使用技巧和多模态应用实践。

Gemini 系列模型

模型对比

text
┌─────────────────────────────────────────────────────────┐
│                   Gemini 模型家族                         │
├─────────────────────────────────────────────────────────┤
│                                                         │
│  Gemini 1.5 系列                                         │
│  ├── Gemini 1.5 Pro: 高性能,1M token 上下文              │
│  ├── Gemini 1.5 Flash: 快速,高性价比                    │
│  └── Gemini 1.5 Pro-002: 最新版本                        │
│                                                         │
│  Gemini 1.0 系列                                         │
│  ├── Gemini Pro: 平衡性能                               │
│  └── Gemini Ultra: 最强性能                             │
│                                                         │
│  特色能力                                                │
│  • 原生多模态:文本、图像、视频、音频、代码                │
│  • 超长上下文:最多 1M tokens                            │
│  • 与 Google 服务深度集成                                │
│  • 强大的代码理解能力                                    │
│                                                         │
└─────────────────────────────────────────────────────────┘

模型选择建议

使用场景推荐模型理由
复杂推理gemini-1.5-pro最强能力
快速响应gemini-1.5-flash低延迟
超长文档gemini-1.5-pro-0021M 上下文
多模态gemini-1.5-pro原生支持
成本敏感gemini-1.5-flash更便宜

Gemini API 使用指南

安装与配置

bash
# 安装 SDK
pip install google-generativeai

# 设置 API Key
export GOOGLE_API_KEY="your-api-key"
python
import google.generativeai as genai
import os

genai.configure(api_key=os.environ["GOOGLE_API_KEY"])

基础用法

python
# 单次对话
model = genai.GenerativeModel('gemini-1.5-pro')

response = model.generate_content("用 Python 写一个快速排序算法")

print(response.text)

多轮对话

python
# 使用聊天历史
chat = model.start_chat(history=[])

# 第一轮
response1 = chat.send_message("我叫小明")
print(response1.text)

# 第二轮
response2 = chat.send_message("我叫什么名字?")
print(response2.text)
# 输出:你叫小明。

流式输出

python
# 流式响应
response = model.generate_content(
    "讲一个短故事",
    stream=True
)

for chunk in response:
    print(chunk.text, end="", flush=True)

系统指令

python
# 设置系统指令
model = genai.GenerativeModel(
    'gemini-1.5-pro',
    system_instruction="你是一个专业的 Python 程序员,只提供代码,不做额外解释。"
)

response = model.generate_content("写一个快排算法")
print(response.text)

多模态能力

图像理解

python
import PIL.Image

# 加载图像
img = PIL.Image.open("chart.png")

model = genai.GenerativeModel('gemini-1.5-pro')

# 图像 + 文本
response = model.generate_content([
    "请分析这个图表中的数据趋势。",
    img
])

print(response.text)

视频理解

python
# 上传视频
video_file = genai.upload_file("video.mp4")

# 等待处理
import time
while video_file.state.name == "PROCESSING":
    time.sleep(1)
    video_file = genai.get_file(video_file.name)

# 分析视频
model = genai.GenerativeModel('gemini-1.5-pro')

response = model.generate_content([
    "请描述这个视频的主要内容。",
    video_file
])

print(response.text)

Function Calling

python
# 定义函数
def get_weather(location: str) -> str:
    """获取天气"""
    return f"{location} 今天晴天,温度 25°C"

def calculate(expression: str) -> float:
    """计算表达式"""
    return float(eval(expression))

# 注册函数
model = genai.GenerativeModel(
    'gemini-1.5-pro',
    tools=[
        {
            "function_declarations": [
                {
                    "name": "get_weather",
                    "description": "获取天气",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "location": {"type": "string"}
                        },
                        "required": ["location"]
                    }
                },
                {
                    "name": "calculate",
                    "description": "计算数学表达式",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "expression": {"type": "string"}
                        },
                        "required": ["expression"]
                    }
                }
            ]
        }
    ]
)

# 处理函数调用
chat = model.start_chat()

response = chat.send_message("北京天气怎么样?")

if response.candidates[0].content.parts[0].function_call:
    function_call = response.candidates[0].content.parts[0].function_call
    result = get_weather(**function_call.args)

    response = chat.send_message(
        genai.types.FunctionResponse(
            name=function_call.name,
            response={"result": result}
        )
    )

print(response.text)

LangChain 集成

python
# pip install langchain-google-genai
from langchain_google_genai import ChatGoogleGenerativeAI

llm = ChatGoogleGenerativeAI(
    model="gemini-1.5-pro",
    temperature=0.7
)

response = llm.invoke("用 Python 写一个快速排序算法")
print(response.content)

成本优化

价格对比(美元/1M tokens)

模型输入输出上下文
gemini-1.5-pro$3.5$102M
gemini-1.5-flash$0.075$0.301M
gemini-1.0-pro$0.5$1.532K

小结

Gemini 是 Google 的多模态 AI 选择:

  1. 多模态能力:原生支持文本、图像、视频、音频
  2. 超长上下文:最多 1M tokens
  3. Google 集成:与 Google Cloud 深度集成
  4. 成本优势:Flash 版本极其便宜

下一篇文章将介绍开源模型与本地部署。

赞赏博主
评论 隐私政策