Gemini API JSON 文本摘要实战:3 步把长文本变成结构化数据
Gemini API JSON 文本摘要实战3 步把长文本变成结构化数据【免费下载链接】cookbookExamples and guides for using the Gemini API项目地址: https://gitcode.com/GitHub_Trending/coo/cookbook想让小说、新闻、研报变成可入库的机器可读字段光让模型总结只会得到散文。用 Gemini API 的 JSON 能力预先声明输出结构模型会按模板返回整齐的 JSON。本文借 cookbook 仓库的示例跑通 JSON 文本摘要全流程。⏱️ 一分钟装好环境并配好 API 密钥pip install -U -q google-genai1.0.0装完创建客户端密钥直接传进去就行from google import genai client genai.Client(api_keyYOUR_API_KEY)密钥怎么申请、怎么放环境变量看仓库里的 quickstarts/Authentication.ipynb 即可本文不再展开。 核心机制给输出套上 schema 模板为什么先用 TypedDict 声明字段与其在 prompt 里反复叮嘱请返回角色、地点、类型不如直接用 Python 类型声明把要什么结构写死from typing_extensions import TypedDict class Character(TypedDict): name: str description: str alignment: str class TextSummary(TypedDict): synopsis: str genres: list[str] characters: list[Character]好处有两点约束前置模型按这个模板填充缺字段、类型错配基本不会出现免解析返回结果不用你从字符串里抠 JSON、手写json.loads。response_mime_type 与 response_schema 各管什么调用时把这两个参数一起传进configresponse client.models.generate_content( modelgemini-3.7-flash, contentsf总结这个故事{story}, config{ response_mime_type: application/json, response_schema: TextSummary, }, )参数管什么response_mime_type管格式把输出锁定为 JSON而不是散文response_schema管结构字段有哪些、什么类型、哪些是列表一个定长什么样一个定装什么内容缺一个都容易翻车。用 parsed 把返回结果直接当字典结果拿到手不用自己反序列化data response.parsed print(data[synopsis]) print(data[characters][0][name])response.parsed已经是一个 Python 字典按字段取值就行后续存库、渲染、二次处理都顺理成章。 效果对照故事进JSON 出仓库示例的做法是先让 Gemini 生成一段十段式的奇幻故事再用上面的 schema 让它做 JSON 文本摘要。输入是一整篇故事输出的关键字段长这样{ characters: [ { name: Elara, description: A cartographer and adventurer seeking the lost city of Eldoria., alignment: Good }, { name: Guardian of the Hidden Passage, description: A creature of stone and shadow protecting Eldorias secrets., alignment: Neutral } ], genres: [Fantasy, Adventure], synopsis: Elara follows an ancient map into the Dragons Tooth mountains… }散文进结构化数据出——角色、类型、梗概各归各位。换个文本也能用schema 换成你要的字段同一套机制换掉TextSummary的字段定义就能迁移到其他文本新闻title、summary、key_facts: list[str]、sentiment: str文章自动变成可检索的条目研报core_findings: list[str]、risk_level: str、time_horizon: str把结论和风险点挑出来商品描述features: list[str]、target_user、cons: list[str]为比价或导购页备料。原则只有一条schema 里声明的字段就是你能拿到的字段。延伸入口仓库里的完整示例完整可运行 notebookexamples/json_capabilities/Text_Summarization.ipynb实体抽取、情感分析、文本分类等同系列任务都在 examples/json_capabilities/ 目录下认证问题随时回查quickstarts/Authentication.ipynb把仓库克隆到本地git clone https://gitcode.com/GitHub_Trending/coo/cookbook然后打开 Text_Summarization.ipynb 跟着跑一遍换成你自己的文本试试。【免费下载链接】cookbookExamples and guides for using the Gemini API项目地址: https://gitcode.com/GitHub_Trending/coo/cookbook创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考