所有 LangChain 与 Google Cloud、Google Gemini 以及其他 Google 产品的集成。
- Google Generative AI (Gemini API & AI Studio):通过 Gemini API 直接访问 Google Gemini 模型。使用 Google AI Studio 进行快速原型设计,并通过
langchain-google-genai 包快速上手。这通常是个人开发者的最佳起点。
- Google Cloud (Vertex AI 及其他服务):通过 Google Cloud Platform 访问 Gemini 模型、Vertex AI Model Garden 以及各种云服务(数据库、存储、文档 AI 等)。使用
langchain-google-vertexai 包来访问 Vertex AI 模型,并使用特定包(例如 langchain-google-cloud-sql-pg、langchain-google-community)来访问其他云服务。这非常适合已经在使用 Google Cloud 或需要企业级功能(如 MLOps、特定模型调优或企业支持)的开发者。
有关差异的更多详细信息,请参阅 Google 的从 Gemini API 迁移到 Vertex AI指南。
用于 Gemini 模型和 Vertex AI 平台的集成包在 langchain-google 仓库中维护。您可以在 googleapis Github 组织和 langchain-google-community 包中找到大量与其他 Google API 和服务的 LangChain 集成。
Google 生成式AI (Gemini API & AI Studio)
直接使用 Gemini API 访问 Google Gemini 模型,最适合快速开发和实验。Gemini 模型可在 Google AI Studio 中获取。
pip install -U langchain-google-genai
免费开始,并从 Google AI Studio 获取你的 API 密钥。
export GOOGLE_API_KEY="YOUR_API_KEY"
聊天模型
使用 ChatGoogleGenerativeAI 类与 Gemini 模型交互。详情请参阅本指南。
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain.messages import HumanMessage
llm = ChatGoogleGenerativeAI(model="gemini-2.5-flash")
# Simple text invocation
result = llm.invoke("Sing a ballad of LangChain.")
print(result.content)
# Multimodal invocation with gemini-pro-vision
message = HumanMessage(
content=[
{
"type": "text",
"text": "What's in this image?",
},
{"type": "image_url", "image_url": "https://picsum.photos/seed/picsum/200/300"},
]
)
result = llm.invoke([message])
print(result.content)
image_url 可以是公共 URL、GCS URI (gs://...)、本地文件路径、base64 编码的图像字符串 (data:image/png;base64,...) 或 PIL Image 对象。
嵌入模型
使用像 gemini-embedding-001 这样的模型,通过 GoogleGenerativeAIEmbeddings 类生成文本嵌入。
参见使用示例。
from langchain_google_genai import GoogleGenerativeAIEmbeddings
embeddings = GoogleGenerativeAIEmbeddings(model="models/gemini-embedding-001")
vector = embeddings.embed_query("What are embeddings?")
print(vector[:5])
LLMs
使用 GoogleGenerativeAI 类,通过(旧版)LLM 接口访问相同的 Gemini 模型。
参见使用示例。
from langchain_google_genai import GoogleGenerativeAI
llm = GoogleGenerativeAI(model="gemini-2.5-flash")
result = llm.invoke("Sing a ballad of LangChain.")
print(result)
Google Cloud
通过 Vertex AI 和特定的云集成,访问 Gemini 模型、Vertex AI Model Garden 和其他 Google Cloud 服务。
Vertex AI 模型需要 langchain-google-vertexai 包。其他服务可能需要额外的包,如 langchain-google-community、langchain-google-cloud-sql-pg 等。
pip install langchain-google-vertexai
# pip install langchain-google-community[...] # For other services
Google Cloud 集成通常使用应用默认凭据 (ADC)。设置说明请参考 Google Cloud 身份验证文档(例如,使用 gcloud auth application-default login)。
聊天模型
Vertex AI
通过 Vertex AI 平台访问像 Gemini 这样的聊天模型。
请参阅使用示例。
from langchain_google_vertexai import ChatVertexAI
Anthropic on Vertex AI Model Garden
参见使用示例。
from langchain_google_vertexai.model_garden import ChatAnthropicVertex
Vertex AI Model Garden 中的 Llama
from langchain_google_vertexai.model_garden_maas.llama import VertexModelGardenLlama
Vertex AI Model Garden 上的 Mistral
from langchain_google_vertexai.model_garden_maas.mistral import VertexModelGardenMistral
来自 Hugging Face 的本地 Gemma
从 HuggingFace 加载的本地 Gemma 模型。需要 langchain-google-vertexai。
from langchain_google_vertexai.gemma import GemmaChatLocalHF
来自 Kaggle 的本地 Gemma
从 Kaggle 加载的本地 Gemma 模型。需要 langchain-google-vertexai。
from langchain_google_vertexai.gemma import GemmaChatLocalKaggle
Vertex AI 模型花园中的 Gemma
需要 langchain-google-vertexai。
from langchain_google_vertexai.gemma import GemmaChatVertexAIModelGarden
Vertex AI 图像字幕生成
将图像描述模型实现为聊天形式。需要 langchain-google-vertexai。
from langchain_google_vertexai.vision_models import VertexAIImageCaptioningChat
Vertex AI 图像编辑器
给定一张图片和一个提示,编辑图片。目前仅支持无遮罩编辑。需要 langchain-google-vertexai。
from langchain_google_vertexai.vision_models import VertexAIImageEditorChat
Vertex AI 图像生成器
根据提示词生成图像。需要 langchain-google-vertexai。
from langchain_google_vertexai.vision_models import VertexAIImageGeneratorChat
Vertex AI 视觉问答
视觉问答模型的对话实现。需要 langchain-google-vertexai。
from langchain_google_vertexai.vision_models import VertexAIVisualQnAChat
LLMs
您也可以使用(遗留的)字符串输入、字符串输出的 LLM 接口。
Vertex AI Model Garden
通过 Vertex AI Model Garden 服务访问 Gemini 和数百个开源模型。需要 langchain-google-vertexai。
请参阅使用示例。
from langchain_google_vertexai import VertexAIModelGarden
来自 Hugging Face 的本地 Gemma
从 HuggingFace 加载的本地 Gemma 模型。需要 langchain-google-vertexai。
from langchain_google_vertexai.gemma import GemmaLocalHF
Gemma 本地(来自 Kaggle)
从 Kaggle 加载的本地 Gemma 模型。需要 langchain-google-vertexai。
from langchain_google_vertexai.gemma import GemmaLocalKaggle
Vertex AI Model Garden 中的 Gemma
需要 langchain-google-vertexai。
from langchain_google_vertexai.gemma import GemmaVertexAIModelGarden
Vertex AI 图像字幕生成
将图像描述模型实现为 LLM。需要 langchain-google-vertexai。
from langchain_google_vertexai.vision_models import VertexAIImageCaptioning
嵌入模型
Vertex AI
使用部署在 Vertex AI 上的模型生成嵌入。需要 langchain-google-vertexai。
查看使用示例。
from langchain_google_vertexai import VertexAIEmbeddings
文档加载器
从各种 Google Cloud 源加载文档。
AlloyDB for PostgreSQL
Google Cloud AlloyDB 是一个完全托管的、兼容 PostgreSQL 的数据库服务。
安装 python 包:
pip install langchain-google-alloydb-pg
请参阅使用示例。
from langchain_google_alloydb_pg import AlloyDBLoader # AlloyDBEngine also available
BigQuery
Google Cloud BigQuery 是一个无服务器数据仓库。
安装 BigQuery 依赖项:
pip install langchain-google-community[bigquery]
参见使用示例。
from langchain_google_community import BigQueryLoader
Bigtable
Google Cloud Bigtable 是一个完全托管的 NoSQL 大数据数据库服务。
安装 Python 包:
pip install langchain-google-bigtable
查看使用示例。
from langchain_google_bigtable import BigtableLoader
Cloud SQL for MySQL
Google Cloud SQL for MySQL 是一个完全托管的 MySQL 数据库服务。
安装 Python 包:
pip install langchain-google-cloud-sql-mysql
请参阅使用示例。
from langchain_google_cloud_sql_mysql import MySQLLoader # MySQLEngine also available
Cloud SQL 用于 SQL Server
Google Cloud SQL for SQL Server 是一个完全托管的 SQL Server 数据库服务。
安装 Python 包:
pip install langchain-google-cloud-sql-mssql
请参阅 使用示例。
from langchain_google_cloud_sql_mssql import MSSQLLoader # MSSQLEngine also available
适用于 PostgreSQL 的 Cloud SQL
Google Cloud SQL for PostgreSQL 是一个完全托管的 PostgreSQL 数据库服务。
安装 Python 包:
pip install langchain-google-cloud-sql-pg
请参阅使用示例。
from langchain_google_cloud_sql_pg import PostgresLoader # PostgresEngine also available
云存储
Cloud Storage 是一种用于存储非结构化数据的托管服务。
安装包含 GCS 依赖项:
pip install langchain-google-community[gcs]
从目录或特定文件加载:
请参阅 目录使用示例。
from langchain_google_community import GCSDirectoryLoader
请参阅文件使用示例。
from langchain_google_community import GCSFileLoader
Cloud Vision 加载器
使用 Google Cloud Vision API 加载数据。
安装包含 Vision 依赖:
pip install langchain-google-community[vision]
from langchain_google_community.vision import CloudVisionLoader
El Carro 用于 Oracle 工作负载
Google El Carro Oracle Operator 在 Kubernetes 上运行 Oracle 数据库。
安装 Python 包:
pip install langchain-google-el-carro
参见 使用示例。
from langchain_google_el_carro import ElCarroLoader
Firestore (原生模式)
Google Cloud Firestore 是一个 NoSQL 文档数据库。
安装 Python 包:
pip install langchain-google-firestore
请参阅使用示例。
from langchain_google_firestore import FirestoreLoader
Firestore(数据存储模式)
Google Cloud Firestore 在 Datastore 模式下.
安装 Python 包:
pip install langchain-google-datastore
请参阅使用示例。
from langchain_google_datastore import DatastoreLoader
Memorystore for Redis
Google Cloud Memorystore for Redis 是一项完全托管的 Redis 服务。
安装 Python 包:
pip install langchain-google-memorystore-redis
请参阅使用示例。
from langchain_google_memorystore_redis import MemorystoreDocumentLoader
Spanner
Google Cloud Spanner 是一个全托管的、全球分布式关系型数据库服务。
安装 python 包:
pip install langchain-google-spanner
请参阅使用示例。
from langchain_google_spanner import SpannerLoader
语音转文本
Google Cloud Speech-to-Text 可转录音频文件。
安装语音转文本依赖:
pip install langchain-google-community[speech]
请参阅使用示例和授权说明。
from langchain_google_community import SpeechToTextLoader
文档转换器
使用 Google Cloud 服务转换文档。
文档AI
Google Cloud Document AI 是一项 Google Cloud 服务,可将文档中的非结构化数据转换为结构化数据,使其更易于理解、分析和使用。
我们需要设置一个 GCS 存储桶并创建您自己的 OCR 处理器
GCS_OUTPUT_PATH 应该是 GCS 上文件夹的路径(以 gs:// 开头)
处理器名称应该类似于 projects/PROJECT_NUMBER/locations/LOCATION/processors/PROCESSOR_ID。
我们可以通过编程方式获取,或者从 Google Cloud 控制台的 Processor details 标签页的 Prediction endpoint 部分复制。
pip install langchain-google-community[docai]
请参阅使用示例。
from langchain_core.document_loaders.blob_loaders import Blob
from langchain_google_community import DocAIParser
Google Translate
谷歌翻译 是 Google 开发的一项多语言神经机器翻译服务,用于将文本、文档和网站从一种语言翻译成另一种语言。
GoogleTranslateTransformer 允许您使用 Google Cloud Translation API 翻译文本和 HTML。
首先,我们需要安装 langchain-google-community 及其翻译依赖项。
pip install langchain-google-community[translate]
请查看使用示例和授权说明。
from langchain_google_community import GoogleTranslateTransformer
向量存储
使用 Google Cloud 数据库和 Vertex AI Vector Search 存储和搜索向量。
AlloyDB 为 PostgreSQL
Google Cloud AlloyDB 是 Google Cloud 上的一项完全托管的关系型数据库服务,提供高性能、无缝集成和出色的可扩展性。AlloyDB 与 PostgreSQL 100% 兼容。
安装 Python 包:
pip install langchain-google-alloydb-pg
查看使用示例。
from langchain_google_alloydb_pg import AlloyDBVectorStore # AlloyDBEngine also available
BigQuery 向量搜索
Google Cloud BigQuery,
BigQuery 是 Google Cloud 上的无服务器、经济高效的企业级数据仓库。
Google Cloud BigQuery Vector Search
BigQuery vector search 让您可以使用 GoogleSQL 进行语义搜索,您可以使用向量索引获得快速但近似的结果,或使用暴力搜索获得精确结果。
它可以计算欧几里得距离或余弦距离。在 LangChain 中,我们默认使用欧几里得距离。
我们需要安装几个 Python 包。
pip install google-cloud-bigquery
查看使用示例。
# Note: BigQueryVectorSearch might be in langchain or langchain_community depending on version
# Check imports in the usage example.
from langchain.vectorstores import BigQueryVectorSearch # Or langchain_community.vectorstores
Memorystore for Redis 版
使用 Memorystore for Redis 的向量存储。
安装 python 包:
pip install langchain-google-memorystore-redis
请参阅使用示例。
from langchain_google_memorystore_redis import RedisVectorStore
Spanner
使用 Cloud Spanner 的向量存储。
安装 Python 包:
pip install langchain-google-spanner
请参阅使用示例。
from langchain_google_spanner import SpannerVectorStore
Firestore (原生模式)
向量存储使用 Firestore。
安装 python 包:
pip install langchain-google-firestore
请参阅使用示例。
from langchain_google_firestore import FirestoreVectorStore
Cloud SQL for MySQL
使用 Cloud SQL for MySQL 的向量存储。
安装 Python 包:
pip install langchain-google-cloud-sql-mysql
查看使用示例。
from langchain_google_cloud_sql_mysql import MySQLVectorStore # MySQLEngine also available
Cloud SQL for PostgreSQL
使用 适用于 PostgreSQL 的 Cloud SQL 的向量存储。
安装 Python 包:
pip install langchain-google-cloud-sql-pg
请参阅使用示例。
from langchain_google_cloud_sql_pg import PostgresVectorStore # PostgresEngine also available
Vertex AI 向量搜索
Google Cloud Vertex AI Vector Search 来自 Google Cloud,前身为 Vertex AI Matching Engine,提供业界领先的大规模低延迟向量数据库。这些向量数据库通常被称为向量相似性匹配或近似最近邻 (ANN) 服务。
安装 Python 包:
pip install langchain-google-vertexai
参见使用示例。
from langchain_google_vertexai import VectorSearchVectorStore
使用 DataStore 后端
使用 Datastore 进行文档存储的向量搜索。
请参阅使用示例。
from langchain_google_vertexai import VectorSearchVectorStoreDatastore
使用 GCS 后端
VectorSearchVectorStore 的别名,用于在 GCS 中存储文档/索引。
from langchain_google_vertexai import VectorSearchVectorStoreGCS
检索器
使用 Google Cloud 服务检索信息。
Vertex AI 搜索
使用 Vertex AI Search 构建由生成式 AI 驱动的搜索引擎。
来自 Google Cloud 的服务允许开发者为客户和员工快速构建由生成式 AI 驱动的搜索引擎。
查看一个使用示例。
注意:GoogleVertexAISearchRetriever 已弃用。请使用以下来自 langchain-google-community 的组件。
安装 google-cloud-discoveryengine 包用于底层访问。
pip install google-cloud-discoveryengine langchain-google-community
VertexAIMultiTurnSearchRetriever
from langchain_google_community import VertexAIMultiTurnSearchRetriever
VertexAISearchRetriever
# Note: The example code shows VertexAIMultiTurnSearchRetriever, confirm if VertexAISearchRetriever is separate or related.
# Assuming it might be related or a typo in the original doc:
from langchain_google_community import VertexAISearchRetriever # Verify class name if needed
VertexAISearchSummaryTool
from langchain_google_community import VertexAISearchSummaryTool
文档AI仓库
使用 Document AI Warehouse 搜索、存储和管理文档。
注意:GoogleDocumentAIWarehouseRetriever(来自 langchain)已弃用。请使用来自 langchain-google-community 的 DocumentAIWarehouseRetriever。
需要安装相关的文档 AI 包(请参考具体文档)。
pip install langchain-google-community # Add specific docai dependencies if needed
from langchain_google_community.documentai_warehouse import DocumentAIWarehouseRetriever
将智能体与各种 Google 服务集成。
文本转语音
Google Cloud Text-to-Speech 是一项 Google Cloud 服务,可让开发者使用 100 多种支持多种语言和变体的语音来合成自然语音。
它应用了 DeepMind 在 WaveNet 方面的突破性研究以及 Google 强大的神经网络,以实现最高保真度。
安装必需的包:
pip install google-cloud-text-to-speech langchain-google-community
请参阅使用示例和授权说明。
from langchain_google_community import TextToSpeechTool
Google Drive
用于与 Google Drive 交互的工具。
安装所需的包:
pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib langchain-googledrive
请参阅使用示例和授权说明。
from langchain_googledrive.utilities.google_drive import GoogleDriveAPIWrapper
from langchain_googledrive.tools.google_drive.tool import GoogleDriveSearchTool
Google Finance
查询金融数据。需要 google-search-results 包和 SerpApi 密钥。
pip install google-search-results langchain-community # Requires langchain-community
请参阅 使用示例和授权说明。
from langchain_community.tools.google_finance import GoogleFinanceQueryRun
from langchain_community.utilities.google_finance import GoogleFinanceAPIWrapper
Google Jobs
查询职位列表。需要 google-search-results 包和 SerpApi 密钥。
pip install google-search-results langchain-community # Requires langchain-community
查看使用示例和授权说明。
from langchain_community.tools.google_jobs import GoogleJobsQueryRun
# Note: Utilities might be shared, e.g., GoogleFinanceAPIWrapper was listed, verify correct utility
# from langchain_community.utilities.google_jobs import GoogleJobsAPIWrapper # If exists
Google Lens
进行视觉搜索。需要 google-search-results 包和 SerpApi 密钥。
pip install google-search-results langchain-community # Requires langchain-community
查看使用示例和授权说明。
from langchain_community.tools.google_lens import GoogleLensQueryRun
from langchain_community.utilities.google_lens import GoogleLensAPIWrapper
Google Places
搜索地点信息。需要 googlemaps 包和 Google Maps API 密钥。
pip install googlemaps langchain # Requires base langchain
查看 使用示例和授权说明。
# Note: GooglePlacesTool might be in langchain or langchain_community depending on version
from langchain.tools import GooglePlacesTool # Or langchain_community.tools
Google Scholar
搜索学术论文。需要 google-search-results 包和 SerpApi 密钥。
pip install google-search-results langchain-community # Requires langchain-community
请参阅使用示例和授权说明。
from langchain_community.tools.google_scholar import GoogleScholarQueryRun
from langchain_community.utilities.google_scholar import GoogleScholarAPIWrapper
Google 搜索
使用 Google 自定义搜索引擎 (CSE) 执行网络搜索。需要 GOOGLE_API_KEY 和 GOOGLE_CSE_ID。
安装 langchain-google-community:
pip install langchain-google-community
包装器:
from langchain_google_community import GoogleSearchAPIWrapper
工具:
from langchain_community.tools import GoogleSearchRun, GoogleSearchResults
智能体加载:
from langchain_community.agent_toolkits.load_tools import load_tools
tools = load_tools(["google-search"])
查看详细笔记。
Google Trends
查询 Google Trends 数据。需要 google-search-results 包和 SerpApi 密钥。
pip install google-search-results langchain-community # Requires langchain-community
请参阅使用示例和授权说明。
from langchain_community.tools.google_trends import GoogleTrendsQueryRun
from langchain_community.utilities.google_trends import GoogleTrendsAPIWrapper
工具包
用于特定 Google 服务的工具集合。
Gmail
Google Gmail 是 Google 提供的免费电子邮件服务。
该工具包通过 Gmail API 处理电子邮件。
pip install langchain-google-community[gmail]
请参阅使用示例和授权说明。
# Load the whole toolkit
from langchain_google_community import GmailToolkit
# Or use individual tools
from langchain_google_community.gmail.create_draft import GmailCreateDraft
from langchain_google_community.gmail.get_message import GmailGetMessage
from langchain_google_community.gmail.get_thread import GmailGetThread
from langchain_google_community.gmail.search import GmailSearch
from langchain_google_community.gmail.send_message import GmailSendMessage
MCP 工具箱
MCP Toolbox 提供了一种简单高效的方式来连接您的数据库,包括 Google Cloud 上的数据库,例如 Cloud SQL 和 AlloyDB。借助 MCP Toolbox,您可以将您的数据库与 LangChain 无缝集成,以构建强大的、数据驱动的应用程序。
要开始,安装 Toolbox 服务器和客户端。
配置 一个 tools.yaml 来定义你的工具,然后执行 toolbox 来启动服务器:
toolbox --tools-file "tools.yaml"
然后,安装 Toolbox 客户端:
pip install toolbox-langchain
快速入门
以下是使用 MCP Toolbox 连接数据库的快速示例:
from toolbox_langchain import ToolboxClient
async with ToolboxClient("http://127.0.0.1:5000") as client:
tools = client.load_toolset()
请参阅使用示例和设置说明。
跟踪 LLM/聊天模型的使用情况。
Vertex AI 回调处理器
跟踪 VertexAI 使用信息的回调处理器。
需要 langchain-google-vertexai。
from langchain_google_vertexai.callbacks import VertexAICallbackHandler
评估器
使用 Vertex AI 评估模型输出。
需要 langchain-google-vertexai。
VertexPairWiseStringEvaluator
使用 Vertex AI 模型进行成对评估。
from langchain_google_vertexai.evaluators.evaluation import VertexPairWiseStringEvaluator
VertexStringEvaluator
使用 Vertex AI 模型评估单个预测字符串。
# Note: Original doc listed VertexPairWiseStringEvaluator twice. Assuming this class exists.
from langchain_google_vertexai.evaluators.evaluation import VertexStringEvaluator # Verify class name if needed
其他 Google 产品
与核心云平台之外的各种 Google 服务集成。
文档加载器
Google Drive
Google Drive 文件存储。目前支持 Google Docs。
安装带有 Drive 依赖项:
pip install langchain-google-community[drive]
请参阅使用示例和授权说明。
from langchain_google_community import GoogleDriveLoader
向量存储
ScaNN (本地索引)
Google ScaNN
(可扩展最近邻) 是一个 Python 包。
ScaNN 是一种用于大规模高效向量相似性搜索的方法。
ScaNN 包含了最大内积搜索的搜索空间剪枝和量化,同时也支持其他距离函数,例如欧几里得距离。该实现针对支持 AVX2 的 x86 处理器进行了优化。请参阅其 Google Research github 了解更多详情。
安装 scann 包:
pip install scann langchain-community # Requires langchain-community
查看一个使用示例。
from langchain_community.vectorstores import ScaNN
检索器
Google Drive
从 Google Drive 检索文档。
安装所需包:
pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib langchain-googledrive
查看使用示例和授权说明。
from langchain_googledrive.retrievers import GoogleDriveRetriever
Google Drive
与 Google Drive 交互的工具
安装所需包:
pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib langchain-googledrive
请查看使用示例和授权说明。
from langchain_googledrive.utilities.google_drive import GoogleDriveAPIWrapper
from langchain_googledrive.tools.google_drive.tool import GoogleDriveSearchTool
Google Finance
查询金融数据。需要 google-search-results 包和 SerpApi 密钥。
pip install google-search-results langchain-community # Requires langchain-community
请查看使用示例和授权说明。
from langchain_community.tools.google_finance import GoogleFinanceQueryRun
from langchain_community.utilities.google_finance import GoogleFinanceAPIWrapper
Google 职位
查询职位列表。需要 google-search-results 包和 SerpApi 密钥。
pip install google-search-results langchain-community # Requires langchain-community
请参阅使用示例和授权说明。
from langchain_community.tools.google_jobs import GoogleJobsQueryRun
# Note: Utilities might be shared, e.g., GoogleFinanceAPIWrapper was listed, verify correct utility
# from langchain_community.utilities.google_jobs import GoogleJobsAPIWrapper # If exists
Google Lens
执行视觉搜索。需要 google-search-results 包和 SerpApi 密钥。
pip install google-search-results langchain-community # Requires langchain-community
参见 使用示例和授权说明。
from langchain_community.tools.google_lens import GoogleLensQueryRun
from langchain_community.utilities.google_lens import GoogleLensAPIWrapper
Google Places
搜索地点信息。需要 googlemaps 包和一个 Google Maps API 密钥。
pip install googlemaps langchain # Requires base langchain
请参阅 使用示例和授权说明。
# Note: GooglePlacesTool might be in langchain or langchain_community depending on version
from langchain.tools import GooglePlacesTool # Or langchain_community.tools
Google Scholar
搜索学术论文。需要 google-search-results 包和 SerpApi 密钥。
pip install google-search-results langchain-community # Requires langchain-community
请参阅 使用示例和授权说明。
from langchain_community.tools.google_scholar import GoogleScholarQueryRun
from langchain_community.utilities.google_scholar import GoogleScholarAPIWrapper
Google 搜索
使用 Google 自定义搜索引擎 (CSE) 执行网络搜索。需要 GOOGLE_API_KEY 和 GOOGLE_CSE_ID。
Install langchain-google-community:
pip install langchain-google-community
包装器:
from langchain_google_community import GoogleSearchAPIWrapper
工具:
from langchain_community.tools import GoogleSearchRun, GoogleSearchResults
智能体加载:
from langchain_community.agent_toolkits.load_tools import load_tools
tools = load_tools(["google-search"])
查看详细的笔记本。
Google Trends
查询 Google Trends 数据。需要 google-search-results 包和 SerpApi 密钥。
pip install google-search-results langchain-community # Requires langchain-community
请查看使用示例和授权说明。
from langchain_community.tools.google_trends import GoogleTrendsQueryRun
from langchain_community.utilities.google_trends import GoogleTrendsAPIWrapper
工具包
Gmail
Google Gmail 是 Google 提供的一项免费电子邮件服务。
此工具包通过 Gmail API 处理电子邮件。
pip install langchain-google-community[gmail]
查看使用示例和授权说明。
# Load the whole toolkit
from langchain_google_community import GmailToolkit
# Or use individual tools
from langchain_google_community.gmail.create_draft import GmailCreateDraft
from langchain_google_community.gmail.get_message import GmailGetMessage
from langchain_google_community.gmail.get_thread import GmailGetThread
from langchain_google_community.gmail.search import GmailSearch
from langchain_google_community.gmail.send_message import GmailSendMessage
聊天加载器
Gmail
从 Gmail 线程加载聊天记录。
安装 Gmail 依赖项:
pip install langchain-google-community[gmail]
请参阅 使用示例和授权说明。
from langchain_google_community import GMailLoader
第三方集成
通过第三方 API 访问 Google 服务。
SearchApi
SearchApi 提供对 Google 搜索、YouTube 等的 API 访问。需要 langchain-community。
查看使用示例和授权说明。
from langchain_community.utilities import SearchApiAPIWrapper
SerpApi
SerpApi 提供对 Google 搜索结果的 API 访问。需要 langchain-community。
查看使用示例和授权说明。
from langchain_community.utilities import SerpAPIWrapper
Serper.dev
Google Serper 提供 API 访问 Google 搜索结果。需要 langchain-community。
查看 使用示例和授权说明。
from langchain_community.utilities import GoogleSerperAPIWrapper
YouTube
YouTube 搜索工具
搜索 YouTube 视频,无需官方 API。需要 youtube_search 包。
pip install youtube_search langchain # Requires base langchain
查看使用示例。
# Note: YouTubeSearchTool might be in langchain or langchain_community
from langchain.tools import YouTubeSearchTool # Or langchain_community.tools
YouTube 音频加载器
从 YouTube 视频下载音频。需要 yt_dlp, pydub, librosa。
pip install yt_dlp pydub librosa langchain-community # Requires langchain-community
请查看使用示例和授权说明。
from langchain_community.document_loaders.blob_loaders.youtube_audio import YoutubeAudioLoader
# Often used with whisper parsers:
# from langchain_community.document_loaders.parsers import OpenAIWhisperParser, OpenAIWhisperParserLocal
YouTube 字幕加载器
加载视频转录文本。需要 youtube-transcript-api。
pip install youtube-transcript-api langchain-community # Requires langchain-community
参见使用示例。
from langchain_community.document_loaders import YoutubeLoader
LangGraph.js
LangGraph.js 是一个用于构建有状态、多参与者应用程序的库,专为 LLM(大语言模型)创建而设计。它建立在 LangChain.js 之上,并扩展了其功能,以支持创建由多个智能体(或链)组成的循环和联网图。
主要特性
- 循环和分支:实现你需要的循环和条件逻辑。不要被 DAG(有向无环图)限制。
- 持久化:为每个图步骤自动保存状态,支持暂停和恢复图执行,以及错误恢复。
- 人机协作:允许你的图与人类交互,以进行批准或输入。
- 时间旅行:在任何步骤“重放”图的过去状态。
- 内置分析:使用 LangSmith 轻松可视化、检查和调试你的图执行。
npm install @langchain/langgraph
快速开始
让我们构建一个简单的智能体,它可以搜索网络以回答问题。
bash bash pip
pip install -U langchain-google-genai
确保你已设置 OPENAI_API_KEY 环境变量。
typescript bash
export GOOGLE_API_KEY=“YOUR_API_KEY”
import { ChatOpenAI } from "@langchain/openai";
import { HumanMessage } from "@langchain/core/messages";
import { tool } from "@langchain/core/tools";
import { z } from "zod";
import { StateGraph, MessagesAnnotation } from "@langchain/langgraph";
// 定义我们智能体的工具
const search = tool(async ({ query }: { query: string }) => {
// 这是一个占位符,但在实际应用中,你会使用真实的搜索 API
if (query.toLowerCase().includes("sf")) {
return "现在是 60 度,有雾。"
}
return "现在是 90 度,晴朗。"
}, {
name: "search",
description: "用于查询当前天气。",
schema: z.object({
query: z.string().describe("要搜索的查询内容"),
}),
});
const tools = [search];
const model = new ChatOpenAI({
temperature: 0,
model: "gpt-4o",
}).bindTools(tools);
// 定义智能体的状态
const AgentState = MessagesAnnotation;
// 定义节点
const callModel = async (state: typeof AgentState.State) => {
const { messages } = state;
const response = await model.invoke(messages);
return { messages: [response] };
};
const shouldContinue = (state: typeof AgentState.State) => {
const { messages } = state;
const lastMessage = messages[messages.length - 1];
// 如果 LLM 发出了工具调用,则路由到 "tools" 节点
if (lastMessage && lastMessage._getType() === "ai" && lastMessage.tool_calls?.length) {
return "tools";
}
// 否则,结束
return "__end__";
};
// 我们构建一个简单的图
const workflow = new StateGraph(AgentState)
.addNode("agent", callModel)
.addNode("tools", new ToolNode({ tools }))
.addEdge("__start__", "agent")
.addConditionalEdges(
"agent",
shouldContinue,
)
.addEdge("tools", "agent");
// 最后,我们编译它!
// 这将其转换为一个 LangChain Runnable,
// 意味着你可以像使用任何其他链一样使用它
const app = workflow.compile();
// 使用它
const finalState = await app.invoke({
messages: [new HumanMessage("旧金山的天气怎么样?")],
});
console.log(finalState.messages[finalState.messages.length - 1].content);
LangGraph.js 提供了几个核心概念来帮助你构建强大的应用程序:
状态图
状态图是 LangGraph.js 的核心抽象。它定义了应用程序的结构和逻辑。
- 节点:代表一个函数或一个智能体。
- 边:代表节点之间的转换。
- 状态:代表应用程序的共享状态。
持久化
LangGraph.js 内置了对持久化的支持。这意味着你可以:
- 暂停和恢复图执行
- 在任何步骤“重放”图的过去状态
- 在错误后恢复执行
人机协作
LangGraph.js 支持人机协作模式,允许你的图与人类交互以进行批准或输入。
更多资源