探索Google AlloyDB for PostgreSQL:使用Langchain加载文档

43 阅读2分钟

引言

Google AlloyDB for PostgreSQL 是一个全托管的关系数据库服务,提供了高性能、无缝集成和强大的可扩展性。它与PostgreSQL完全兼容,使开发者能够构建基于AI的应用程序。在这篇文章中,我们将通过使用AlloyDBLoader类来学习如何在AlloyDB中加载文档。

主要内容

1. 开始之前

要运行本文的示例,你需要:

  • 创建一个Google Cloud项目
  • 启用AlloyDB API
  • 创建一个AlloyDB集群和实例
  • 创建一个AlloyDB数据库
  • 向数据库添加用户

2. 库安装

首先,需要安装集成库langchain-google-alloydb-pg:

%pip install --upgrade --quiet langchain-google-alloydb-pg

3. 认证

通过以下代码在Google Cloud中进行认证,确保你可以访问项目资源:

from google.colab import auth
auth.authenticate_user()

4. 设置Google Cloud项目

在运行代码前,设置项目ID:

PROJECT_ID = "gcp_project_id"  # 将此替换为你的实际项目ID
! gcloud config set project {PROJECT_ID}

连接AlloyDB数据库

设置数据库变量

确保获取并设置以下变量:

REGION = "us-central1"
CLUSTER = "my-cluster"
INSTANCE = "my-primary"
DATABASE = "my-database"
TABLE_NAME = "vector_store"

创建AlloyDB引擎连接池

使用AlloyDBEngine.from_instance创建连接池:

from langchain_google_alloydb_pg import AlloyDBEngine

# 使用API代理服务提高访问稳定性
engine = await AlloyDBEngine.afrom_instance(
    project_id=PROJECT_ID,
    region=REGION,
    cluster=CLUSTER,
    instance=INSTANCE,
    database=DATABASE,
)

使用AlloyDBLoader加载文档

创建并使用AlloyDBLoader加载文档:

from langchain_google_alloydb_pg import AlloyDBLoader

# 创建AlloyDBLoader对象
loader = await AlloyDBLoader.create(engine, table_name=TABLE_NAME)

# 加载文档
docs = await loader.aload()
print(docs)

自定义表和格式

你可以自定义加载的列和格式:

loader = await AlloyDBLoader.create(
    engine,
    table_name=TABLE_NAME,
    content_columns=["product_name"],
    metadata_columns=["id"],
)
docs = await loader.aload()
print(docs)

# 设置内容格式为YAML
loader = AlloyDBLoader.create(
    engine,
    table_name="products",
    content_columns=["product_name", "description"],
    format="YAML",
)
docs = await loader.aload()
print(docs)

常见问题和解决方案

总结和进一步学习资源

通过这篇文章,你已经学会如何在Google AlloyDB中使用Langchain集成加载文档。建议阅读以下资源以深入学习:

参考资料

  1. Google AlloyDB 官方文档
  2. Langchain GitHub 项目

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---