你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

Azure Database for PostgreSQL 中的 AI 代理

AI 代理通过将大型语言模型(LLM)与外部工具和数据库相结合来转换应用程序与数据交互的方式。 代理可以自动化复杂的工作流,提高信息检索的准确性,并促进数据库的自然语言接口。

本文介绍如何创建智能 AI 代理,以在 Azure Database for PostgreSQL 中搜索和分析数据。 它以法律研究助理为例,演练设置、实现和测试。

什么是 AI 代理?

AI 代理通过将 LLM 与外部工具和数据库组合在一起,超越简单的聊天机器人。 与独立的 LLM 或标准检索扩充生成(RAG)系统不同,AI 代理可以:

  • 计划:将复杂任务分解为较小的顺序步骤。
  • 使用工具:使用 API、代码执行和搜索系统收集信息或执行作。
  • 感知:了解和处理来自各种数据源的输入。
  • 请记住:存储和召回以前的交互,以便做出更好的决策。

通过将 AI 代理连接到 Azure Database for PostgreSQL 等数据库,代理可以根据数据提供更准确的上下文感知响应。 AI 代理超越了基本的人工对话,可以基于自然语言执行任务。 这些任务传统上需要编码逻辑。 但是,代理可以计划根据用户提供的上下文执行所需的任务。

AI 代理的实现

使用 Azure Database for PostgreSQL 实现 AI 代理涉及将高级 AI 功能与可靠的数据库功能集成,以创建智能上下文感知系统。 通过使用矢量搜索、嵌入和 Azure AI Foundry 代理服务等工具,开发人员可以生成了解自然语言查询、检索相关数据的代理,并提供可作的见解。

以下部分概述了设置、配置和部署 AI 代理的分步过程。 此过程可实现 AI 模型和 PostgreSQL 数据库之间的无缝交互。

框架

各种框架和工具可以促进 AI 代理的开发和部署。 所有这些框架都支持使用 Azure Database for PostgreSQL 作为工具:

实现示例

本文的示例使用 Azure AI Foundry 代理服务 来进行代理规划、工具使用和感知。 它使用 Azure Database for PostgreSQL 作为矢量数据库和语义搜索功能的工具。

以下部分将指导你构建一个 AI 代理,帮助法律团队研究相关案例,以支持他们在华盛顿州的客户。 代理:

  1. 接受有关法律情况的自然语言查询。
  2. 使用 Azure Database for PostgreSQL 中的矢量搜索查找相关案例先例。
  3. 分析并以对法律专业人员有用的格式汇总调查结果。

先决条件

  1. 启用和配置azure_aipg_vector扩展。

  2. 创建 Azure AI Foundry 项目

  3. 部署模型gpt-4o-minitext-embedding-small.

  4. 安装 Visual Studio Code

  5. 安装 Python 扩展。

  6. 安装 Python 3.11.x

  7. 安装 Azure CLI (最新版本)。

    注释

    需要为代理创建的已部署模型中的密钥和终结点。

入门指南

此 GitHub 存储库中提供了所有代码和示例数据集。

步骤 1:在 Azure Database for PostgreSQL 中设置矢量搜索

首先,使用矢量嵌入准备数据库来存储和搜索法律案例数据。

设置环境

如果使用 macOS 和 Bash,请运行以下命令:

python -m venv .pg-azure-ai 
source .pg-azure-ai/bin/activate 
pip install -r requirements.txt

如果使用 Windows 和 PowerShell,请运行以下命令:

python -m venv .pg-azure-ai 
.pg-azure-ai \Scripts\Activate.ps1 
pip install -r requirements.txt

如果使用的是 Windows 和 cmd.exe,请运行以下命令:

python -m venv .pg-azure-ai 
.pg-azure-ai \Scripts\activate.bat 
pip install -r requirements.txt

配置环境变量

创建一个包含您凭据的.env文件:

AZURE_OPENAI_API_KEY="" 
AZURE_OPENAI_ENDPOINT="" 
EMBEDDING_MODEL_NAME="" 
AZURE_PG_CONNECTION=""

加载文档和矢量

Python 文件 load_data/main.py 用作将数据加载到 Azure Database for PostgreSQL 的中心入口点。 该代码处理 示例事例的数据,包括有关华盛顿案例的信息。

main.py 文件:

  1. 创建必要的扩展,设置 OpenAI API 设置,并通过删除现有的表和创建新的表来管理数据库表,以存储案件数据。
  2. 从 CSV 文件读取数据并将其插入临时表中,然后处理数据并将其传输到主事例表中。
  3. 添加一个新列用于在事例表中嵌入内容,并使用 OpenAI 的 API 为案例意见生成嵌入内容。 它将嵌入内容存储在新列中。 嵌入过程大约需要 3 到 5 分钟。

若要启动数据加载过程,请从 load_data 目录中运行以下命令:

python main.py

这是 main.py 的输出:

Extensions created successfully 
OpenAI connection established successfully 
The case table was created successfully 
Temp cases table created successfully 
Data loaded into temp_cases_data table successfully 
Data loaded into cases table successfully.
Adding Embeddings will take a while, around 3-5 mins.
Embeddings added successfully All Data loaded successfully!

步骤 2:为代理创建 Postgres 工具

接下来,将 AI 代理工具配置为从 Postgres 检索数据。 然后使用 Azure AI Foundry 代理服务 SDK 将 AI 代理连接到 Postgres 数据库。

定义代理要调用的函数

首先,通过描述代理的结构和 docstring 中的任何必需参数来定义要调用的函数。 在单个文件中包括所有函数定义, legal_agent_tools.py。 然后,可以将文件导入主脚本。

def vector_search_cases(vector_search_query: str, start_date: datetime ="1911-01-01", end_date: datetime ="2025-12-31", limit: int = 10) -> str:
    """
 Fetches the case information in Washington State for the specified query.

 :param query(str): The query to fetch cases specifically in Washington.
 :type query: str
 :param start_date: The start date for the search defaults to "1911-01-01"
 :type start_date: datetime, optional
 :param end_date: The end date for the search, defaults to "2025-12-31"
 :type end_date: datetime, optional
 :param limit: The maximum number of cases to fetch, defaults to 10
 :type limit: int, optional

 :return: Cases information as a JSON string.
 :rtype: str
 """
        
 db = create_engine(CONN_STR)
    
 query = """
 SELECT id, name, opinion, 
 opinions_vector <=> azure_openai.create_embeddings(
 'text-embedding-3-small', %s)::vector as similarity
 FROM cases
 WHERE decision_date BETWEEN %s AND %s
 ORDER BY similarity
 LIMIT %s;
 """
    
    # Fetch case information from the database
 df = pd.read_sql(query, db, params=(vector_search_query,datetime.strptime(start_date, "%Y-%m-%d"), datetime.strptime(end_date, "%Y-%m-%d"),limit))

 cases_json = json.dumps(df.to_json(orient="records"))
    return cases_json

步骤 3:使用 Postgres 创建和配置 AI 代理

现在,设置 AI 代理并将其与 Postgres 工具集成。 Python 文件 src/simple_postgres_and_ai_agent.py 充当用于创建和使用代理的中心入口点。

simple_postgres_and_ai_agent.py 文件:

  1. 使用特定模型初始化 Azure AI Foundry 项目中的代理。
  2. 在代理初始化期间,添加 Postgres 工具,以便在数据库上搜索矢量。
  3. 设置通信线程。 此线程用于将消息发送到代理进行处理。
  4. 使用代理和工具处理用户的查询。 代理可以使用工具进行计划,以获取正确的答案。 在此用例中,代理基于函数签名和 docstring 调用 Postgres 工具,以执行矢量搜索并检索相关数据以回答问题。
  5. 显示代理对用户查询的响应。

在 Azure AI Foundry 中查找项目连接字符串

在 Azure AI Foundry 项目中,可以从项目的概述页中找到项目连接字符串。 使用此字符串将项目连接到 Azure AI Foundry 代理服务 SDK。 将此字符串添加到 .env 文件。

显示项目设置页的屏幕截图。

设置连接

将这些变量添加到 .env 根目录中的文件:

PROJECT_CONNECTION_STRING=" " 
MODEL_DEPLOYMENT_NAME="gpt-4o-mini" 
AZURE_TRACING_GEN_AI_CONTENT_RECORDING_ENABLED="true"
### Create the agent with tool access
We created the agent in the Azure AI Foundry project and added the Postgres tools needed to query the database. The code snippet below is an excerpt from the file [simple_postgres_and_ai_agent.py](https://github.com/Azure-Samples/postgres-agents/blob/main/src/simple_postgres_and_ai_agent.py).

# Create an Azure AI Foundry client
project_client = AIProjectClient.from_connection_string(
    credential=DefaultAzureCredential(),
    conn_str=os.environ["PROJECT_CONNECTION_STRING"],
)

# Initialize the agent toolset with user functions
functions = FunctionTool(user_functions)
toolset = ToolSet()
toolset.add(functions)

agent = project_client.agents.create_agent(
    model= os.environ["MODEL_DEPLOYMENT_NAME"], 
    name="legal-cases-agent",
    instructions= "You are a helpful legal assistant who can retrieve information about legal cases.", 
    toolset=toolset
)

创建通信线程

此代码片段演示如何创建代理线程和消息,代理在运行中处理该线程:

# Create a thread for communication
thread = project_client.agents.create_thread()

# Create a message to thread
message = project_client.agents.create_message(
    thread_id=thread.id,
    role="user",
    content="Water leaking into the apartment from the floor above. What are the prominent legal precedents in Washington regarding this problem in the last 10 years?"
)

处理请求

以下代码片段为代理创建一个执行过程,以处理消息,并使用相应的工具来提供最佳结果。

通过使用这些工具,代理可以调用​ Postgres 和针对查询“Water leaking into the apartment from the floor above”进行的矢量搜索来检索以最佳方式回答问题所需的数据。

from pprint import pprint

# Create and process an agent run in the thread with tools
run = project_client.agents.create_and_process_run(
thread_id=thread.id, 
agent_id=agent.id
)

# Fetch and log all messages
messages = project_client.agents.list_messages(thread_id=thread.id)
pprint(messages['data'][0]['content'][0]['text']['value'])

运行代理

若要运行代理,请从 src 目录中运行以下命令:

python simple_postgres_and_ai_agent.py

代理使用 Azure Database for PostgreSQL 工具访问 Postgres 数据库中保存的案例数据,从而生成类似的结果。

下面是代理的输出片段:

1.     Pham v. Corbett

Citation: Pham v. Corbett, No. 4237124
Summary: This case involved tenants who counterclaimed against their landlord for relocation assistance and breached the implied warranty of habitability due to severe maintenance issues, including water and sewage leaks. The trial court held that the landlord had breached the implied warranty and awarded damages to the tenants.

2.     Hoover v. Warner

Citation: Hoover v. Warner, No. 6779281
Summary: The Warners appealed a ruling finding them liable for negligence and nuisance after their road grading project caused water drainage issues affecting Hoover's property. The trial court found substantial evidence supporting the claim that the Warners' actions impeded the natural water flow and damaged Hoover's property.

步骤 4:在代理沙盒中进行测试和调试

使用 Azure AI Foundry 代理服务 SDK 运行代理后,代理将存储在项目中。 可以尝试在代理操场中使用代理:

  1. 在 Azure AI Foundry 中,转到 “代理 ”部分。

  2. 请在列表中找到您的代理人,然后选择它以打开。

  3. 使用沙盒界面测试各种法律查询。

    显示用于查找代理操场的选项的屏幕截图。

  4. 测试查询“从上面的楼层渗水到公寓,华盛顿州有哪些著名的法律先例?”。代理程序选择要使用的正确工具,并请求该查询的预期输出。 使用 sample_vector_search_cases_output.json 作为示例输出。

    在 Agent Playground 中显示查询结果的屏幕截图。

步骤 5:使用 Azure AI Foundry 跟踪进行调试

使用 Azure AI Foundry 代理服务 SDK 开发代理时,可以使用 跟踪调试代理。 通过跟踪可以调试对 Postgres 等工具的调用,并查看代理如何协调每个任务。

  1. 在 Azure AI Foundry 中,转到 “跟踪”。

  2. 若要创建新的 Application Insights 资源,请选择“ 新建”。 若要连接现有资源,请在 Application Insights 资源名称 框中选择一个资源,然后选择“ 连接”。

    显示用于选择 Application Insights 资源并激活跟踪的区域的屏幕截图。

  3. 查看代理的操作的详细记录。

    AI Foundry 中跟踪结果的屏幕截图。

详细了解如何在 GitHub 上的 advanced_postgres_and_ai_agent_with_tracing.py 文件中使用 AI 代理和 Postgres 设置跟踪。