你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
人工智能(AI)代理通过将大型语言模型(LLM)与外部工具和数据库相结合来转换应用程序与数据交互的方式。 代理可以自动化复杂的工作流,提高信息检索准确性,并促进数据库的自然语言接口。 本文介绍如何创建能够搜索和分析 Azure Database for PostgreSQL 中的数据的智能 AI 代理。 我们将使用法律研究助理作为示例,讲解设置、实施与测试流程。
什么是 AI 代理?
AI 代理通过将大型语言模型(LLM)与外部工具和数据库组合在一起,超越简单的聊天机器人。 与独立的 LLM 或标准 RAG 系统不同,AI 代理可以:
- 计划:将复杂任务分解为较小的顺序步骤。
- 使用工具:使用 API、代码执行和搜索系统收集信息或执行作。
- 感知:了解和处理来自各种数据源的输入。
- 请记住:存储和召回以前的交互,以便做出更好的决策。
通过将 AI 代理连接到 Azure Database for PostgreSQL 等数据库,代理可以根据数据提供更准确的上下文感知响应。 AI 代理超越了基本的人工对话,可以基于自然语言执行任务。 这些任务传统上需要编码的逻辑;但是,代理可以计划根据用户提供的上下文执行所需的任务。
AI 代理的实现
使用 Azure Database for PostgreSQL 实现 AI 代理涉及将高级 AI 功能与可靠的数据库功能集成,以创建智能上下文感知系统。 通过利用矢量搜索、嵌入和 Azure AI 代理服务等工具,开发人员可以构建能够理解自然语言查询、检索相关数据并提供可作见解的代理。 本部分概述了设置、配置和部署 AI 代理的分步过程,从而在 AI 模型和 PostgreSQL 数据库之间实现无缝交互。
框架
各种框架和工具可以促进 AI 代理的开发和部署。 所有这些框架都支持使用 Azure Database for PostgreSQL 作为工具
实施示例
我们将 Azure AI 代理服务 用于代理规划、工具使用情况和感知,同时使用 Azure Database for PostgreSQL 作为矢量数据库和语义搜索功能的工具。
在本教程中,我们构建了一个 AI 代理,帮助法律团队研究相关案例以支持他们在华盛顿州的客户。 我们的代理:
- 接受有关法律情况的自然语言查询。
- 使用 Azure Database for PostgreSQL 中的矢量搜索查找相关案例先例。
- 分析和汇总调查结果,以便以对法律专业人员有益的格式呈现。
先决条件
启用和配置
azure_ai
和pg_vector
扩展。部署模型
gpt-4o-mini
&text-embedding-small
安装 Python 扩展。
安装 Python 3.11.x。
安装 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 的高级详细信息:
- 数据库设置和表创建:创建必要的扩展、设置 OpenAI API 设置,并通过删除现有扩展并创建用于存储事例数据的新扩展来管理数据库表。
- 数据引入:此过程从 CSV 文件读取数据,并将其插入临时表中,然后处理数据并将其传输到主事例表中。
- 嵌入生成:在事例表中添加新的用于嵌入的列,并使用 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 代理服务 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 cases 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 代理并将其与 PostgreSQL 工具集成。 Python 文件 src/simple_postgres_and_ai_agent.py 充当用于创建和使用代理的中心入口点。
simple_postgres_and_ai_agent.py的高级详细信息:
- 创建代理:使用特定模型初始化 Azure AI 项目中的代理。
- 添加 Postgres 工具:在代理初始化期间,将添加 Postgres 工具,以便对数据库进行矢量搜索。
- 创建线程:设置通信线程。 这用于将消息发送到代理进行处理
- 运行代理和调用 Postgres 工具:使用代理和工具处理用户的查询。 代理可以使用工具进行计划,以便获取正确的答案。 在此用例中,代理基于函数签名和 docstring 调用 Postgres 工具,以执行矢量搜索并检索相关数据以回答问题。
- 显示代理的响应:此函数输出代理对用户查询的响应。
在 Azure AI Foundry 中查找项目连接字符串
在 Azure AI Foundry 项目中,可以从项目的“概述”页中找到项目连接字符串。 我们使用此字符串将项目连接到 AI 代理 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 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 Client
project_client = AIProjectClient.from_connection_string(
credential=DefaultAzureCredential(),
conn_str=os.environ["PROJECT_CONNECTION_STRING"],
)
# Initialize 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 thread for communication
thread = project_client.agents.create_thread()
# Create 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 agent run in 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 平台进行测试和调试
使用 Azure AI 代理 SDK 运行代理后,代理将存储在项目中,可以在代理场中试验代理。
使用代理操场
导航到 Azure AI Foundry 中的“代理”部分
在列表中查找代理,然后选择并打开
使用游乐场界面测试各种法律查询
测试查询 “水从上面的楼层漏到公寓中,什么是华盛顿重要的法律先例?” 代理选择恰当的工具进行使用,并请求该查询的预期结果。 使用 sample_vector_search_cases_output.json 作为示例输出。
步骤 5:使用 Azure AI Foundry 跟踪进行调试
使用 Azure AI Foundry SDK 开发代理时,可以使用 Tracing 调试代理,从而调试对 Postgres 等工具的调用,并了解代理如何协调每个任务。
使用跟踪进行调试
在 Azure AI Foundry 菜单中选择“跟踪”
创建新的 Application Insights 资源或连接现有的一个
查看代理操作的详细追踪
详细了解如何在 GitHub 上的 advanced_postgres_and_ai_agent_with_tracing.py 文件中使用 AI 代理和 Postgres 设置跟踪。