ITADN
googleapis/langchain-google-cloud-sql-pg-python
README.md
以下内容由 AI 翻译,如有问题请点此提交 issue 反馈

用于 LangChain 的 Cloud SQL for PostgreSQL

|preview| |pypi| |versions|

  • Client Library Documentation_
  • Product Documentation_

Cloud SQL for PostgreSQL for LangChain 包为从 LangChain 生态系统连接到 Cloud SQL 实例提供了一流体验,同时提供以下优势:

  • 简化且安全的连接:利用 IAM 进行授权和数据库身份验证,轻松安全地创建共享连接池以连接到 Google Cloud 数据库,无需管理 SSL 证书、配置防火墙规则或启用授权网络。
  • 提升性能并简化管理:使用单表模式可以加快查询执行速度,尤其适用于大型集合。
  • 改进的元数据处理:将元数据存储在列中而非 JSON 中,从而带来显著的性能提升。
  • 清晰的分离:明确分离表和扩展的创建,允许独立的权限和简化的工作流。

.. |preview| image:: https://img.shields.io/badge/support-preview-orange.svg :target: https://github.com/googleapis/google-cloud-python/blob/main/README.rst#stability-levels .. |pypi| image:: https://img.shields.io/pypi/v/langchain-google-cloud-sql-pg.svg :target: https://pypi.org/project/langchain-google-cloud-sql-pg/ .. |versions| image:: https://img.shields.io/pypi/pyversions/langchain-google-cloud-sql-pg.svg :target: https://pypi.org/project/langchain-google-cloud-sql-pg/ .. _Client Library Documentation: https://cloud.google.com/python/docs/reference/langchain-google-cloud-sql-pg/latest .. _Product Documentation: https://cloud.google.com/sql/docs

快速入门

为了使用此库,您首先需要完成以下步骤:

  1. Select or create a Cloud Platform project._
  2. Enable billing for your project._
  3. Enable the Cloud SQL Admin API._
  4. Setup Authentication._

.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project .. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project .. _Enable the Cloud SQL Admin API.: .. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html

安装


使用 `venv`_ 在虚拟环境中安装此库。`venv`_ 是一个用于
创建隔离 Python 环境的工具。这些隔离环境可以拥有
不同版本的 Python 包,从而允许你将一个项目的依赖项
与其他项目的依赖项隔离开来。

借助 `venv`_,可以在无需系统
安装权限的情况下安装此库,并且不会与已安装的
系统依赖项发生冲突。

.. _`venv`: https://docs.python.org/3/library/venv.html

支持的 Python 版本
^^^^^^^^^^^^^^^^^^^^^^^^^

Python >= 3.10

Mac/Linux
^^^^^^^^^

.. code-block:: console

pip install virtualenv
    virtualenv <your-env>
    source <your-env>/bin/activate
    <your-env>/bin/pip install langchain-google-cloud-sql-pg

Windows
^^^^^^^

.. code-block:: console

pip install virtualenv
    virtualenv <your-env>
    <your-env>\Scripts\activate
    <your-env>\Scripts\pip.exe install langchain-google-cloud-sql-pg

示例用法
-------------

代码示例和代码片段位于 `samples/`_ 文件夹中。

.. _samples/: https://github.com/googleapis/langchain-google-cloud-sql-pg-python/tree/main/samples

向量存储的使用

使用向量存储来存储嵌入数据并执行向量搜索。

.. code-block:: python

from langchain_google_cloud_sql_pg import PostgresVectorstore, PostgresEngine from langchain.embeddings import VertexAIEmbeddings

    engine = PostgresEngine.from_instance("project-id", "region", "my-instance", "my-database")
    engine.init_vectorstore_table(
        table_name="my-table",
        vector_size=768,  # `VertexAIEmbeddings()` 的向量大小
    )
    embeddings_service = VertexAIEmbeddings(model_name="textembedding-gecko@003")
    vectorstore = PostgresVectorStore.create_sync(
        engine,
        table_name="my-table",
        embeddings=embedding_service
    )

混合搜索


`PostgresVectorStore` 支持混合搜索(稠密向量 + 全文搜索),以提供更全面且相关的搜索结果。

.. code-block:: python

from langchain_google_cloud_sql_pg import HybridSearchConfig, reciprocal_rank_fusion

  vs = PostgresVectorStore.create_sync(
      engine=engine,
      table_name=TABLE_NAME,
      embedding_service=embedding,
      hybrid_search_config=HybridSearchConfig(
        fusion_function=reciprocal_rank_fusion
      ),
  )
  hybrid_docs = vector_store.similarity_search("products", k=5)

查看完整的 `Vector Store`_ 教程。

.. _`Vector Store`: https://github.com/googleapis/langchain-google-cloud-sql-pg-python/tree/main/docs/vector_store.ipynb

Document Loader 用法

Use a document loader to load data as Documents.

.. code-block:: python

    from langchain_google_cloud_sql_pg import PostgresEngine, PostgresLoader


    engine = PostgresEngine.from_instance("project-id", "region", "my-instance", "my-database")
    loader = PostgresSQLLoader.create_sync(
        engine,
        table_name="my-table-name"
    )
    docs = loader.lazy_load()

See the full Document Loader_ tutorial.

.. _Document Loader: https://github.com/googleapis/langchain-google-cloud-sql-pg-python/tree/main/docs/document_loader.ipynb

Chat Message History Usage


使用 Chat Message History 存储消息,并为 LLM 提供对话历史。

.. code-block:: python

from langchain_google_cloud_sql_pg import PostgresChatMessageHistory, PostgresEngine

        engine = PostgresEngine.from_instance("project-id", "region", "my-instance", "my-database")
        engine.init_chat_history_table(table_name="my-message-store")
        history = PostgresChatMessageHistory.create_sync(
            engine,
            table_name="my-message-store",
            session_id="my-session_id"
        )

查看完整的 `Chat Message History`_ 教程。

.. _`Chat Message History`: https://github.com/googleapis/langchain-google-cloud-sql-pg-python/tree/main/docs/chat_message_history.ipynb

Langgraph 检查点使用
~~~~~~~~~~~~~~~~~~~~~~~~~~

使用 ``PostgresSaver`` 在特定时间点保存图状态的快照。

.. code:: python

from langchain_google_cloud_sql_pg import PostgresSaver, PostgresEngine

   engine = PostgresEngine.from_instance("project-id", "region", "my-instance", "my-database")
   checkpoint = PostgresSaver.create_sync(engine)

查看完整的 `Checkpoint`_ 教程。

.. _`Checkpoint`: https://github.com/googleapis/langchain-google-cloud-sql-pg-python/blob/main/docs/langgraph_checkpoint.ipynb

示例用法
-------------

代码示例可在 `samples/`_ 文件夹中找到。

.. _samples/: https://github.com/googleapis/langchain-google-cloud-sql-pg-python/tree/main/samples

在同步与异步用法之间转换
-------------------------------------

异步功能通过并发提高了数据库连接的速度和效率,
这对于在 GenAI 应用中提供企业级性能和扩展性至关重要。此
包使用原生异步 Postgres 驱动程序 `asyncpg`_,以优化 Python 的异步功能。

LangChain 支持 `async programming`_,因为基于 LLM 的应用程序利用了许多 I/O 密集型操作,
例如对语言模型、数据库或其他服务进行 API 调用。所有组件都应提供
所有方法的异步和同步版本。

`asyncio`_ 是一个用于并发编程的 Python 库,并用作多个
Python 异步框架的基础。asyncio 使用 `async` / `await` 语法,通过单线程协作式多任务处理而非多线程,
为非阻塞 I/O 密集型任务实现并发。

.. _`async programming`: https://python.langchain.com/docs/concepts/async/
.. _`asyncio`: https://docs.python.org/3/library/asyncio.html
.. _`asyncpg`: https://github.com/MagicStack/asyncpg

将同步转换为异步
~~~~~~~~~~~~~~~~~~~~~~~~

将同步方法更新为 `await` 异步方法

.. code:: python

engine = await PostgresEngine.afrom_instance("project-id", "region", "my-instance", "my-database")
   await engine.ainit_vectorstore_table(table_name="my-table", vector_size=768)
   vectorstore = await PostgresVectorStore.create(
      engine,
      table_name="my-table",
      embedding_service=VertexAIEmbeddings(model_name="textembedding-gecko@003")
   )

运行代码:notebooks
^^^^^^^^^^^^^^^^^^^^^^^

ipython 和 jupyter notebooks 支持使用 `await` 关键字,无需任何额外设置

运行代码:FastAPI
^^^^^^^^^^^^^^^^^^^^^

更新路由以使用 `async def`。

.. code:: python

@app.get("/invoke/")
   async def invoke(query: str):
      return await retriever.ainvoke(query)

运行代码:本地 Python 文件
^^^^^^^^^^^^^^^^^^^^^^^^^^^

建议创建一个顶层异步方法定义:`async def` 来封装多个异步方法。
然后使用 `asyncio.run()` 来运行顶层入口点,例如 "main()"

.. code:: python

async def main():
      response = await retriever.ainvoke(query)
      print(response)

   asyncio.run(main())

贡献
-------------

欢迎并高度鼓励对本库的贡献。

有关如何开始,请参阅 `CONTRIBUTING`_。

请注意,本项目附有贡献者行为准则。参与本项目即表示您同意遵守其条款。有关
更多信息,请参阅 `Code of Conduct`_。

.. _`CONTRIBUTING`: https://github.com/googleapis/langchain-google-cloud-sql-pg-python/tree/main/CONTRIBUTING.md
.. _`Code of Conduct`: https://github.com/googleapis/langchain-google-cloud-sql-pg-python/tree/main/CODE_OF_CONDUCT.md

许可证
-------

Apache 2.0 - 参见
`LICENSE <https://github.com/googleapis/langchain-google-cloud-sql-pg-python/tree/main/LICENSE>`_
以获取更多信息。

免责声明
----------

这不是 Google 官方支持的产品。