Documentation Index
Fetch the complete documentation index at: https://langchain-zh.cn/llms.txt
Use this file to discover all available pages before exploring further.
Cloud SQL 是一个全托管的关系型数据库服务,提供高性能、无缝集成以及出色的可扩展性,并支持 PostgreSQL 等数据库引擎。
本指南简要介绍了如何使用 Cloud SQL for PostgreSQL 通过 PostgresLoader 类加载文档。
开始之前
为了使用此包,您首先需要完成以下步骤:
- 选择或创建一个 Cloud Platform 项目。
- 为您的项目启用结算功能。
- 启用 Cloud SQL Admin API。
- 设置身份验证。
- 创建 CloudSQL 实例
- 创建 CloudSQL 数据库
- 向数据库添加用户
身份验证
使用 gcloud auth login 命令在本地对您的 Google Cloud 账户进行身份验证。
设置您的 Google Cloud 项目
设置您的 Google Cloud 项目 ID,以便在本地使用 Google Cloud 资源:
gcloud config set project YOUR-PROJECT-ID
如果您不知道您的项目 ID,请尝试以下方法:
- 运行
gcloud config list。
- 运行
gcloud projects list。
- 查看支持页面:查找项目 ID。
设置 PostgresLoader 实例
要使用 PostgresLoader 类,您需要安装 @langchain/google-cloud-sql-pg 包,然后按照以下步骤操作。
首先,您需要登录到您的 Google Cloud 账户,并根据您的 Google Cloud 项目设置以下环境变量;这些变量将根据您希望如何配置(fromInstance、fromEngine、fromEngineArgs)PostgresEngine 实例来定义:
PROJECT_ID="your-project-id"
REGION="your-project-region" // 示例:"us-central1"
INSTANCE_NAME="your-instance"
DB_NAME="your-database-name"
DB_USER="your-database-user"
PASSWORD="your-database-password"
设置实例
要实例化 PostgresLoader,您首先需要通过 PostgresEngine 创建数据库连接。
import {
PostgresLoader,
PostgresEngine,
PostgresEngineArgs,
} from "@langchain/google-cloud-sql-pg";
import * as dotenv from "dotenv";
dotenv.config();
const peArgs: PostgresEngineArgs = {
user: process.env.DB_USER ?? "",
password: process.env.PASSWORD ?? "",
};
// PostgresEngine 实例化
const engine: PostgresEngine = await PostgresEngine.fromInstance(
process.env.PROJECT_ID ?? "",
process.env.REGION ?? "",
process.env.INSTANCE_NAME ?? "",
process.env.DB_NAME ?? "",
peArgs
);
使用 table_name 参数加载文档
加载器从表中返回一个文档列表,使用第一列作为 page_content,其他所有列作为元数据。默认表将第一列作为 page_content,第二列作为元数据(JSON)。每一行成为一个文档。
const documentLoaderArgs: PostgresLoaderOptions = {
tableName: "test_table_custom",
contentColumns: ["fruit_name", "variety"],
metadataColumns: [
"fruit_id",
"quantity_in_stock",
"price_per_unit",
"organic",
],
format: "text",
};
const documentLoaderInstance = await PostgresLoader.initialize(
PEInstance,
documentLoaderArgs
);
使用 SQL 查询加载文档
query 参数允许用户指定自定义 SQL 查询,其中可以包含过滤器以从数据库加载特定文档。
const documentLoaderArgs: PostgresLoaderOptions = {
query: "SELECT * FROM my_fruit_table",
contentColumns: ["fruit_name", "variety"],
metadataColumns: [
"fruit_id",
"quantity_in_stock",
"price_per_unit",
"organic",
],
format: "text",
};
const documentLoaderInstance = await PostgresLoader.initialize(
PEInstance,
docucumetLoaderArgs
);
设置页面内容格式
加载器返回一个文档列表,每行一个文档,页面内容以指定的字符串格式呈现,例如 text(空格分隔的连接)、JSON、YAML、CSV 等。JSON 和 YAML 格式包含标题,而 text 和 CSV 不包含字段标题。