一、环境准备与初始化1.1 Gemini开发者API方式from langchain_google_genaiimportChatGoogleGenerativeAI# 推荐做法提前在环境变量中设置API Key#exportGOOGLE_API_KEY你的API密钥# 直接代码中指定API Key也可以 modelChatGoogleGenerativeAI(modelgemini-3-pro-preview,api_key你的API密钥)1.2 Vertex AI后端方式方式1API Key模式# 在环境变量中填写GCP项目ID、API Key、激活Vertex后端exportGEMINI_API_KEYyour-api-keyexportGOOGLE_GENAI_USE_VERTEXAItrueexportGOOGLE_CLOUD_PROJECTyour-project-idmodelChatGoogleGenerativeAI(modelgemini-3-pro-preview)# 或者更明确地配置 modelChatGoogleGenerativeAI(modelgemini-3-pro-preview,api_key你的API密钥,project你的项目ID,vertexaiTrue,)方式2凭证认证使用Google Application Default CredentialsmodelChatGoogleGenerativeAI(modelgemini-2.5-flash,project你的项目ID,# 不指定api_key会自动使用本地Google ADC)from langchain_google_genaiimportChatGoogleGenerativeAISERVICE_ACCOUNT_FILEservice_account.jsonos.environ[GOOGLE_APPLICATION_CREDENTIALS]SERVICE_ACCOUNT_FILE llmChatGoogleGenerativeAI(modelgemini-3-pro-preview,# Vertex AI 模型:gemini-2.0-flash-001project******,# 你的 GCP 项目 ID locationglobal,# 区域 us-central1 temperature0.28,max_output_tokens1000,vertexaiTrue,)from google.oauth2importservice_accountfrom langchain_google_genaiimportChatGoogleGenerativeAIllmChatGoogleGenerativeAI(modelgemini-3-pro-preview,# Vertex AI 模型:gemini-2.0-flash-001project******,# 你的 GCP 项目 ID locationglobal,# 区域 us-central1 temperature0.28,max_output_tokens1000,credentialscredentials,vertexaiTrue,)二、环境变量一览变量名作用后端类型GOOGLE_API_KEYAPI主密钥优先两者均可GEMINI_API_KEYAPI备用密钥两者均可GOOGLE_GENAI_USE_VERTEXAI强制启用Vertex后端VertexGOOGLE_CLOUD_PROJECT谷歌云项目IDVertexGOOGLE_CLOUD_LOCATIONGCP区域默认central1VertexHTTPS_PROXYHTTP/HTTPS代理配置两者均可SSL_CERT_FILE自定义SSL证书两者均可三、代理和网络#HTTP/HTTPS代理exportHTTPS_PROXYhttp://用户名:密码代理地址:端口# 可选自定义SSL证书exportSSL_CERT_FILE路径/证书.pem# 高级代理如SOCKS5可用client_args指定 modelChatGoogleGenerativeAI(modelgemini-2.5-flash,client_args{proxy:socks5://user:passhost:端口},)四、模型调用与基础用法4.1 普通文本对话示例from langchain_google_genaiimportChatGoogleGenerativeAImodelChatGoogleGenerativeAI(modelgemini-3-pro-preview)resultmodel.invoke(为LangChain写一首抒情诗)print(result)4.2 多轮消息格式messages[(system,请将用户发言翻译成法语。),(human,我爱编程。),]model.invoke(messages)messages[SystemMessage(content你是一个乐于助人的助手擅长数学计算。),HumanMessage(content请计算 123.45 678.9 等于多少)]model.invoke(messages)返回值示例内容可能包含AI回复内容、响应元数据、用量统计等AIMessage(content[{type:text,text:**Jadore la programmation.**\n\n你也可以说:...,extras:{signature:Eq0W...},}],response_metadata{...},usage_metadata{...},)五、流式输出Streamforchunk in llm.stream(用一句话介绍自己):print(chunk.content,end,flushTrue)print()modelChatGoogleGenerativeAI(modelgemini-2.5-flash)forchunk in model.stream(messages):print(chunk.content)# 每一小段文本流式输出六、异步调用# 单次异步调用 resultawait model.ainvoke(messages)# 异步流式输出 asyncforchunkin(await model.astream(messages)):print(chunk.content)# 批量异步 resultsawait model.abatch([messages])七、 工具调用如天气/人口查询from pydanticimportBaseModel,Field # 定义天气工具classGetWeather(BaseModel):获取指定地点的当前天气location:strField(...,description城市和州例如 San Francisco, CA)# 定义人口工具classGetPopulation(BaseModel):获取指定地点的人口数量location:strField(...,description城市和州例如 San Francisco, CA)llm_with_toolsmodel.bind_tools([GetWeather,GetPopulation])resllm_with_tools.invoke(今天洛杉矶和纽约哪个城市更热哪个更大)print(res.tool_calls)# 查看工具调用情况八、结构化输出如笑话生成from pydanticimportBaseModel,Field from typingimportOptionalclassJoke(BaseModel):笑话结构setup:strField(description笑话开场)punchline:strField(description笑话梗)rating:Optional[int]Field(description搞笑程度1~10)# 推荐方式gemini原生结构化输出 structured_modelmodel.with_structured_output(Joke)jokestructured_model.invoke(讲一个猫的笑话)print(joke)九、多模态输入9.1 图片输入importbase64importhttpxfrom langchain.messagesimportHumanMessageimage_urlhttps://xxx.jpgimage_database64.b64encode(httpx.get(image_url).content).decode(utf-8)messageHumanMessage(content[{type:text,text:描述一下这张图的天气},{type:image_url,image_url:{url:fdata:image/jpeg;base64,{image_data}}},])ai_msgmodel.invoke([message])print(ai_msg.content)# 打印图片分析结果9.2 PDF输入importbase64from langchain.messagesimportHumanMessagepdf_bytesopen(/path/to.pdf,rb).read()pdf_base64base64.b64encode(pdf_bytes).decode(utf-8)messageHumanMessage(content[{type:text,text:用一句话描述这份PDF},{type:file,source_type:base64,mime_type:application/pdf,data:pdf_base64}])ai_msgmodel.invoke([message])print(ai_msg.content)十、上下文缓存和文件上传单文件缓存from googleimportgenaifrom google.genaiimporttypesimporttimefrom langchain.messagesimportHumanMessageclientgenai.Client()# 上传文件到Google云 fileclient.files.upload(file/path/to/file)whilefile.state.namePROCESSING:time.sleep(2)fileclient.files.get(namefile.name)# 创建缓存 cacheclient.caches.create(modelgemini-3-pro-preview,configtypes.CreateCachedContentConfig(display_name缓存内容描述,system_instruction你是内容专家需基于文件回答问题。,contents[file],ttl300s,))llmChatGoogleGenerativeAI(modelgemini-3-pro-preview,cached_contentcache.name)msgHumanMessage(content归纳这一内容的要点)print(llm.invoke([msg]))十一、安全策略设置from langchain_google_genaiimport(ChatGoogleGenerativeAI,HarmBlockThreshold,HarmCategory,)# 关闭危险内容阻断 llmChatGoogleGenerativeAI(modelgemini-3-pro-preview,safety_settings{HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT:HarmBlockThreshold.BLOCK_NONE,},)十二、Token用量追踪resmodel.invoke(messages)print(res.usage_metadata)# 打印tokens消耗详情十三、 响应元数据查看ai_msgmodel.invoke(messages)print(ai_msg.response_metadata)返回结果如{model_name:gemini-3-pro-preview,model_provider:google_genai,prompt_feedback:{block_reason:0,safety_ratings:[]},finish_reason:STOP,safety_ratings:[...],}