一、环境准备与初始化
1.1 Gemini开发者API方式
from langchain_google_genaiimportChatGoogleGenerativeAI# 推荐做法:提前在环境变量中设置API Key#exportGOOGLE_API_KEY='你的API密钥'# 直接代码中指定API Key也可以 model=ChatGoogleGenerativeAI(model="gemini-3-pro-preview",api_key="你的API密钥")
1.2 Vertex AI后端方式
方式1:API Key模式
# 在环境变量中填写:GCP项目ID、API Key、激活Vertex后端exportGEMINI_API_KEY='your-api-key'exportGOOGLE_GENAI_USE_VERTEXAI=trueexportGOOGLE_CLOUD_PROJECT='your-project-id'model=ChatGoogleGenerativeAI(model="gemini-3-pro-preview")# 或者更明确地配置 model=ChatGoogleGenerativeAI(model="gemini-3-pro-preview",api_key="你的API密钥",project="你的项目ID",vertexai=True,)方式2:凭证认证(使用Google Application Default Credentials)
model=ChatGoogleGenerativeAI(model="gemini-2.5-flash",project="你的项目ID",# 不指定api_key会自动使用本地Google ADC)from langchain_google_genaiimportChatGoogleGenerativeAISERVICE_ACCOUNT_FILE="service_account.json"os.environ["GOOGLE_APPLICATION_CREDENTIALS"]=SERVICE_ACCOUNT_FILE llm=ChatGoogleGenerativeAI(model="gemini-3-pro-preview",# Vertex AI 模型:gemini-2.0-flash-001project="******",# 你的 GCP 项目 ID location="global",# 区域 us-central1 temperature=0.28,max_output_tokens=1000,vertexai=True,)from google.oauth2importservice_accountfrom langchain_google_genaiimportChatGoogleGenerativeAIllm=ChatGoogleGenerativeAI(model="gemini-3-pro-preview",# Vertex AI 模型:gemini-2.0-flash-001project="******",# 你的 GCP 项目 ID location="global",# 区域 us-central1 temperature=0.28,max_output_tokens=1000,credentials=credentials,vertexai=True,)
二、环境变量一览
| 变量名 | 作用 | 后端类型 |
|---|---|---|
| GOOGLE_API_KEY | API主密钥(优先) | 两者均可 |
| GEMINI_API_KEY | API备用密钥 | 两者均可 |
| GOOGLE_GENAI_USE_VERTEXAI | 强制启用Vertex后端 | Vertex |
| GOOGLE_CLOUD_PROJECT | 谷歌云项目ID | Vertex |
| GOOGLE_CLOUD_LOCATION | GCP区域(默认central1) | Vertex |
| HTTPS_PROXY | HTTP/HTTPS代理配置 | 两者均可 |
| SSL_CERT_FILE | 自定义SSL证书 | 两者均可 |
三、代理和网络
#HTTP/HTTPS代理exportHTTPS_PROXY='http://用户名:密码@代理地址:端口'# 可选:自定义SSL证书exportSSL_CERT_FILE='路径/证书.pem'# 高级代理(如SOCKS5)可用client_args指定 model=ChatGoogleGenerativeAI(model="gemini-2.5-flash",client_args={"proxy":"socks5://user:pass@host:端口"},)四、模型调用与基础用法
4.1 普通文本对话示例
from langchain_google_genaiimportChatGoogleGenerativeAImodel=ChatGoogleGenerativeAI(model="gemini-3-pro-preview")result=model.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":"**J'adore la programmation.**\n\n你也可以说:...","extras":{"signature":"Eq0W..."},}],response_metadata={...},usage_metadata={...},)五、流式输出(Stream)
forchunk in llm.stream("用一句话介绍自己"):print(chunk.content,end="",flush=True)print()model=ChatGoogleGenerativeAI(model="gemini-2.5-flash")forchunk in model.stream(messages):print(chunk.content)# 每一小段文本流式输出六、异步调用
# 单次异步调用 result=await model.ainvoke(messages)# 异步流式输出 asyncforchunkin(await model.astream(messages)):print(chunk.content)# 批量异步 results=await model.abatch([messages])七、 工具调用(如天气/人口查询)
from pydanticimportBaseModel,Field # 定义天气工具classGetWeather(BaseModel):'''获取指定地点的当前天气'''location:str=Field(...,description="城市和州,例如 San Francisco, CA")# 定义人口工具classGetPopulation(BaseModel):'''获取指定地点的人口数量'''location:str=Field(...,description="城市和州,例如 San Francisco, CA")llm_with_tools=model.bind_tools([GetWeather,GetPopulation])res=llm_with_tools.invoke("今天洛杉矶和纽约哪个城市更热?哪个更大?")print(res.tool_calls)# 查看工具调用情况八、结构化输出(如笑话生成)
from pydanticimportBaseModel,Field from typingimportOptionalclassJoke(BaseModel):'''笑话结构'''setup:str=Field(description="笑话开场")punchline:str=Field(description="笑话梗")rating:Optional[int]=Field(description="搞笑程度(1~10)")# 推荐方式(gemini原生结构化输出) structured_model=model.with_structured_output(Joke)joke=structured_model.invoke("讲一个猫的笑话")print(joke)九、多模态输入
9.1 图片输入
importbase64importhttpxfrom langchain.messagesimportHumanMessageimage_url="https://xxx.jpg"image_data=base64.b64encode(httpx.get(image_url).content).decode("utf-8")message=HumanMessage(content=[{"type":"text","text":"描述一下这张图的天气"},{"type":"image_url","image_url":{"url":f"data:image/jpeg;base64,{image_data}"}},])ai_msg=model.invoke([message])print(ai_msg.content)# 打印图片分析结果9.2 PDF输入
importbase64from langchain.messagesimportHumanMessagepdf_bytes=open("/path/to.pdf","rb").read()pdf_base64=base64.b64encode(pdf_bytes).decode("utf-8")message=HumanMessage(content=[{"type":"text","text":"用一句话描述这份PDF"},{"type":"file","source_type":"base64","mime_type":"application/pdf","data":pdf_base64}])ai_msg=model.invoke([message])print(ai_msg.content)十、上下文缓存和文件上传
单文件缓存:
from googleimportgenaifrom google.genaiimporttypesimporttimefrom langchain.messagesimportHumanMessageclient=genai.Client()# 上传文件到Google云 file=client.files.upload(file="/path/to/file")whilefile.state.name=="PROCESSING":time.sleep(2)file=client.files.get(name=file.name)# 创建缓存 cache=client.caches.create(model="gemini-3-pro-preview",config=types.CreateCachedContentConfig(display_name="缓存内容描述",system_instruction="你是内容专家,需基于文件回答问题。",contents=[file],ttl="300s",))llm=ChatGoogleGenerativeAI(model="gemini-3-pro-preview",cached_content=cache.name)msg=HumanMessage(content="归纳这一内容的要点")print(llm.invoke([msg]))十一、安全策略设置
from langchain_google_genaiimport(ChatGoogleGenerativeAI,HarmBlockThreshold,HarmCategory,)# 关闭危险内容阻断 llm=ChatGoogleGenerativeAI(model="gemini-3-pro-preview",safety_settings={HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT:HarmBlockThreshold.BLOCK_NONE,},)十二、Token用量追踪
res=model.invoke(messages)print(res.usage_metadata)# 打印tokens消耗详情十三、 响应元数据查看
ai_msg=model.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":[...],}