Gemini API 实验场
聊天只是开始。下面这些实时演示展示谷歌 Gemini API 能为社区里的真实任务做什么:根据情况推荐活动、看懂照片和 PDF、把杂乱文字整理成规范数据、调用自己的工具、运行代码,还能朗读。
结构化输出 · 真实数据
根据我的情况推荐活动
用一句话描述您的情况,中英文均可。Gemini 会阅读 G8 的三角区近期活动列表,挑出最适合您的 3 到 5 个,并说明理由。它只能从列表中选择真实活动,服务器会逐一核对。
查看代码
from google import genai
from google.genai import types
client = genai.Client() # reads GEMINI_API_KEY from the environment
events = open("events.txt").read() # one line per event: "id | start | town | category | cost | title | summary"
ids = [line.split(" | ")[0] for line in events.splitlines()]
schema = {
"type": "object",
"properties": {"matches": {"type": "array", "maxItems": 5, "items": {
"type": "object",
"properties": {
"id": {"type": "string", "enum": ids}, # can only pick real events
"reason": {"type": "string"},
"score": {"type": "integer", "minimum": 0, "maximum": 100}},
"required": ["id", "reason", "score"]}}},
"required": ["matches"],
}
resp = client.models.generate_content(
model="gemini-3.8-flash",
contents=f"EVENTS:\n{events}\n\nVISITOR: We just moved to Cary with two kids...",
config=types.GenerateContentConfig(
system_instruction="Recommend 3-5 events ONLY from the EVENTS list, by exact id. "
"Never invent events. One-sentence reason in the visitor's language.",
response_mime_type="application/json",
response_json_schema=schema,
),
)
print(resp.text) # {"matches": [{"id": "...", "reason": "...", "score": 92}, ...]}结构化输出(JSON 架构)
杂乱传单文字变规范数据
粘贴活动传单或群聊里的文字。Gemini 会按固定的 JSON 架构填写,不知道的字段留空,不会乱猜。
查看代码
from google import genai
from google.genai import types
from pydantic import BaseModel
class Event(BaseModel):
title: str
date: str | None # YYYY-MM-DD
start_time: str | None
end_time: str | None
venue: str | None
town: str | None
cost: str | None # None if not stated: never assume free
organizer: str | None
registration_url: str | None
languages: list[str]
client = genai.Client()
resp = client.models.generate_content(
model="gemini-3.8-flash",
contents=open("flyer.txt").read(),
config=types.GenerateContentConfig(
system_instruction="Extract the event. Use null for anything not stated.",
response_mime_type="application/json",
response_json_schema=Event.model_json_schema(),
),
)
event = Event.model_validate_json(resp.text)
print(event)函数调用
让 Gemini 调用您自己的工具
我们给 Gemini 一个工具 get_events,用来读取本网站的活动数据。Gemini 自己决定何时调用、用什么筛选条件,再根据真实结果回答。
查看代码
from google import genai
from google.genai import types
def get_events(town: str = "", start_date: str = "", end_date: str = "",
free_only: bool = False) -> dict:
"""List upcoming Triangle events from the G8 site's events data."""
... # filter your own events.json and return {"events": [...]}
client = genai.Client()
resp = client.models.generate_content(
model="gemini-3.8-flash",
contents="What's on in Cary this weekend that's free for families?",
config=types.GenerateContentConfig(
system_instruction="Today is Tuesday, October 20, 2026. Use get_events; never invent events.",
tools=[get_events], # the Python SDK calls the function for you, then Gemini answers
),
)
print(resp.text)图像理解
看懂一张照片
选择示例照片或上传自己的照片,然后提一个问题。
查看代码
from google import genai
from google.genai import types
client = genai.Client()
image = open("photo.jpg", "rb").read()
resp = client.models.generate_content(
model="gemini-3.8-flash",
contents=[
types.Part.from_bytes(data=image, mime_type="image/jpeg"),
"What is happening in this photo? List three details.",
],
)
print(resp.text)文档理解
向 PDF 提问
Gemini 可以读完整个 PDF(包括表格)并回答问题。示例是一份虚构的社区通讯。
查看代码
from google import genai
from google.genai import types
client = genai.Client()
pdf = open("newsletter.pdf", "rb").read()
resp = client.models.generate_content(
model="gemini-3.8-flash",
contents=[
types.Part.from_bytes(data=pdf, mime_type="application/pdf"),
"Summarize in 5 bullet points, then list every date and deadline in a table.",
],
)
print(resp.text)代码执行
编写并运行 Python
Gemini 编写 Python 代码,在谷歌的沙盒中运行,并使用真实的运行结果,包括图表。
查看代码
from google import genai
from google.genai import types
client = genai.Client()
resp = client.models.generate_content(
model="gemini-3.8-flash",
contents="Family budget: rent 1850, groceries 720, car 410 ... "
"Make a sorted bar chart and give each item's percent of the total.",
config=types.GenerateContentConfig(
tools=[types.Tool(code_execution=types.ToolCodeExecution())],
),
)
for part in resp.candidates[0].content.parts:
if part.executable_code: print(part.executable_code.code)
if part.code_execution_result: print(part.code_execution_result.output)
if part.inline_data: open("chart.png", "wb").write(part.inline_data.data)
if part.text: print(part.text)网址上下文
总结一个网页
给 Gemini 一个公开网址,它会自己读取网页,并根据网页内容回答。
查看代码
from google import genai
from google.genai import types
client = genai.Client()
resp = client.models.generate_content(
model="gemini-3.8-flash",
contents="What can a new Cary resident do on this website? "
"https://www.townofcary.org/",
config=types.GenerateContentConfig(
tools=[types.Tool(url_context=types.UrlContext())],
),
)
print(resp.text)
print(resp.candidates[0].url_context_metadata) # which URLs were fetched语音生成
文字转语音
把简短文字变成自然的语音,支持中文和英文,可选择不同声音。
查看代码
from google import genai
from google.genai import types
client = genai.Client()
resp = client.models.generate_content(
model="gemini-3.8-flash-tts",
contents="Welcome to the Triangle! The English conversation group meets every Tuesday.",
config=types.GenerateContentConfig(
response_modalities=["AUDIO"],
speech_config=types.SpeechConfig(
voice_config=types.VoiceConfig(
prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name="Kore"))),
),
)
audio = resp.candidates[0].content.parts[0].inline_data
open("welcome.wav", "wb").write(audio.data) # 3.8 TTS models return WAV工作原理
您的浏览器把演示请求发送到 G8 的一个小型服务器函数。该函数在服务器端加上 API 密钥(密钥保密,不会发到浏览器),用 Flash 模型调用 Gemini API,再把结果返回。每张卡片都有“查看代码”按钮,展示同样调用的 Python 写法。
未包含的功能及原因
- Google 搜索接地(Grounding): 当前 Gemini Flash 模型的免费额度不提供搜索接地功能(谷歌价格页面显示仅限付费)。
- 向量嵌入 / 语义搜索: 免费的嵌入模型在这里每次只能处理一条内容,搜索全部活动会让每位访客消耗几十次请求。上面的活动推荐演示已涵盖同样的思路。
- 图片生成: 谷歌的 Flash 图片模型(Nano Banana)不提供免费额度。