人工智慧 (AI) 代理程式將大型語言模型與外部工具和資料庫結合在一起,來轉換應用程式與數據互動的方式。 代理程式可自動化複雜的工作流程、增強資訊擷取精確度,以及輔助資料庫的自然語言介面。 本文探討如何建立智慧型 AI 代理程式,以在 Azure PostgreSQL 資料庫中搜尋和分析您的數據。 我們逐步指導如何使用法律研究助理作為範例進行設定、執行和測試。
什麼是 AI 代理程式?
AI 代理程式透過結合大型語言模型與外部工具和資料庫,超越簡單的聊天機器人。 不同於獨立 LLM 或標準 RAG 系統,AI 代理程式可以:
- 計劃:將複雜工作細分為較小的循序步驟。
- 使用工具:使用 API、程式代碼執行和搜尋系統來收集資訊或執行動作。
- 感知:瞭解和處理來自各種數據源的輸入。
- 請記住:儲存並重新叫用先前的互動,以取得更好的決策。
藉由將 AI 代理程式連線到適用於 PostgreSQL 的 Azure 資料庫等資料庫,代理程式可以根據您的數據提供更精確的內容感知回應。 AI 代理程式超越基本人類對話,以根據自然語言執行工作。 這些工作傳統上需要自動程式代碼邏輯;不過,代理程式可以根據使用者提供的內容規劃執行所需的工作。
AI 代理程式的實作
使用適用於 PostgreSQL 的 Azure 資料庫實作 AI 代理程式,牽涉到整合進階 AI 功能與健全的資料庫功能,來建立智慧型、具情境感知能力的系統。 藉由利用向量搜尋、內嵌和 Azure AI 代理程式服務等工具,開發人員可以建置能夠瞭解自然語言查詢、擷取相關數據的代理程式,並提供可採取動作的深入解析。 本節概述設定、設定和部署 AI 代理程式的逐步程式,讓您能夠順暢地與 AI 模型與 PostgreSQL 資料庫互動。
框架
各種架構和工具可輔助開發及部署 AI 代理程式。 所有這些架構都支援使用適用於PostgreSQL的 Azure 資料庫作為工具
實作範例
我們使用 Azure AI 代理程式服務 進行代理程式規劃、工具使用和感知,同時使用適用於 PostgreSQL 的 Azure 資料庫作為向量資料庫和語意搜尋功能的工具。
在本教學課程中,我們會建置 AI 代理程式,協助法律小組研究相關案例,以支援其在華盛頓州的客戶。 我們的代理人:
- 接受有關法律情況的自然語言查詢。
- 使用適用於PostgreSQL的 Azure 資料庫中的向量搜尋來尋找相關的案例先例。
- 分析並以對法律專業人員有用的格式摘要這些發現。
先決條件
啟用和設定
azure_ai
和pg_vector
擴充功能。部署模型
gpt-4o-mini
&text-embedding-small
安裝 Python 延伸模組。
安裝 Python 3.11.x。
安裝 Azure CLI。(最新版本)
備註
您需要您為代理程式建立的已部署模型中的金鑰和端點。
入門指南
此 GitHub 存放庫中提供所有程式代碼和範例數據集。
步驟 1:在適用於 PostgreSQL 的 Azure 資料庫中設定向量搜尋
首先,我們會準備資料庫,以使用向量內嵌來儲存和搜尋法律案例數據:
環境設定
如果使用 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 可作為將數據載入適用於 PostgreSQL 的 Azure 資料庫的核心進入點。 程式代碼會處理 範例案例數據,包括華盛頓案例的相關信息。
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 資料庫。
定義代理程式呼叫的函式
首先,透過在文件字串中描述該函式的結構及所需參數,來定義代理程式呼叫的函式。 將所有函式定義包含在單一檔案 中,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 並使用向量搜尋用查詢「公寓樓上漏水進來」* 來擷取回答最佳答案所需的資料。
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
代理程式會使用適用於 PostgreSQL 的 Azure 資料庫工具來產生類似的結果,以存取儲存在 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 執行代理程式之後,代理程式會儲存在您的專案中,而且您可以在 Agent 遊樂場中實驗代理程式。
使用代理程式遊樂場
流覽至 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 設定追蹤。