建立並查詢實體圖

Note

Foundry IQ(Azure AI 搜尋服務)提供直接的索引與查詢 API,並搭配高階知識來源與知識庫 API 用於受控檢索。 使用 Azure 入口網站、REST API 或 Azure SDK 來設定這些功能,或將代理連線到 Microsoft Foundry 入口網站 中的知識庫。

Important

實體圖目前處於公開預覽階段,並受 Microsoft Azure 預覽補充使用條款的約束。

有關此功能專屬的預覽條款,請參閱 「預覽功能」。

實體圖(預覽)將人物、組織、地點及其他概念表示為節點,其關係作為邊。 它能回答取決於實體之間關聯的問題,例如哪些人在特定城市中的組織任職。

在 Foundry IQ(Azure AI 搜尋服務)中,圖譜擷取會將 Blob 內容轉換為實體圖譜。 建立一個支援圖譜的 blob 知識來源,然後透過知識庫或直接用 GQL 查詢受管理圖譜。 與 主題圖不同,實體圖根據本體論捕捉明確的實體及其關係。

Prerequisites

  • 支援 2026-11-01-preview REST API 的 Foundry IQ 服務。
  • Python 範例需 Python 3.10 或更新版本,C# 範例則需 .NET 8 或更新版本。
  • 如需 SDK 範例,請依照「建立知識庫」中的公開資訊預覽套件指示操作。
  • Blob 知識來源的服務、模型部署、身分驗證和計費必要條件。
  • 一個包含文字內容的 Azure Blob 儲存體 容器。 此圖形工作流程不支援 ADLS Gen2、ACL 匯入或敏感度標籤擷取。
  • 必須在首次索引執行前啟用原生 Blob 軟刪除。 必須停用 Blob 版本控制功能。
  • 一種用於資料擷取的 chat-completion 模型。 知識庫需要自己的模型配置,以用於自然語言圖查詢。
  • 建立及刪除測試知識來源及知識庫的權限。 為這些範例設定 無金鑰驗證 。 關於查詢權限以及 SDK 範例所使用的 Azure 身份函式庫,請參閱查詢知識庫的先決條件。

Limitations

實體圖擷取需要新的知識庫。 您無法在現有知識庫上啟用實體圖擷取功能。

實體圖功能在此版本中僅支援 API。 你可以將內建的 UI 作為 Foundry IQ skills plugin的一部分使用。

最佳做法

  • 建議使用 Foundry IQ 技能外掛 作為入門方式。 若要直接使用 REST API 或 SDK 進行設定,請依照本文中的步驟操作。
  • 使用 gpt-5.6-luna 搭配低檢索推理工作量,以獲得最佳的品質與成本平衡。
  • 圍繞著你預期使用者會向你的知識庫提出的關鍵問題來設計你的本體論。 本體論的品質決定圖形的形狀與內容,因此請包含這些問題所需的實體類型與關係。
  • 先從一個關鍵使用案例開始,以及一小組實體類型與關聯。 在擴大規模之前,先將擷取出來的圖表與代表性查詢進行驗證。
  • 根據語料庫大小以及擷取的實體與關係數量,估算圖建構成本。
  • 預覽期間,實體圖功能本身不會額外收費。 你還是要為所使用的模型代幣付費。

準備內容與本體論

本 體論 定義要擷取的實體類型與關係。 設計時,就圍繞你預期使用者會提出的問題來設計。 這個例子使用了個人、他們的雇主,以及這些雇主所在的城市。

  1. 將以下虛構內容上傳到你容器中命名 roster.txt 的文字塊。

    Avery Chen works for Contoso Robotics.
    Contoso Robotics is located in Seattle.
    Jordan Davis works for Fabrikam Analytics.
    Fabrikam Analytics is located in Austin.
    
  2. 上傳第二個名為 avery.txt的文字 blob 。 這又為西雅圖關係提供了另一個來源斷言。

    Avery Chen is employed by Contoso Robotics, an organization located in Seattle.
    
  3. 將本體定義為受限 JSON-LD 文件。 命名空間用來識別您的應用程式詞彙;此範例定義 Person、Organization、Place、worksFor 及 locatedIn。

    {
      "@context": {
        "owl": "http://www.w3.org/2002/07/owl#",
        "rdfs": "http://www.w3.org/2000/01/rdf-schema#",
        "ex": "https://schema.search.azure.com/entities#"
      },
      "@graph": [
        {
          "@id": "ex:Person",
          "@type": "owl:Class",
          "rdfs:comment": "A person."
        },
        {
          "@id": "ex:Organization",
          "@type": "owl:Class",
          "rdfs:comment": "An organization."
        },
        {
          "@id": "ex:Place",
          "@type": "owl:Class",
          "rdfs:comment": "A geographic place."
        },
        {
          "@id": "ex:worksFor",
          "@type": "owl:ObjectProperty",
          "rdfs:domain": {"@id": "ex:Person"},
          "rdfs:range": {"@id": "ex:Organization"},
          "rdfs:comment": "A person's employer."
        },
        {
          "@id": "ex:locatedIn",
          "@type": "owl:ObjectProperty",
          "rdfs:domain": {"@id": "ex:Organization"},
          "rdfs:range": {"@id": "ex:Place"},
          "rdfs:comment": "The city where an organization is located."
        }
      ]
    }
    

建立支援圖形結構的知識來源

此導覽提供建立時的本體論,並未設定匯入快取。 在建立此來源前選擇本體:若沒有快取,後續本體變更將不被支援。 需要本體更新的來源需要在建立時設定一個支援重新處理的快取;你之後無法再新增該快取或移除附加的本體。

  1. 在 REST 範例中,請在您的 REST 用戶端中設定下列變數。 請用您自己的資源名稱和存取權杖取代佔位符。 若要取得存取權杖,請參閱 「連接至 Foundry IQ」。

    @search-endpoint = https://<search-service>.search.windows.net
    @api-version = 2026-11-01-preview
    @access-token = <search-access-token>
    @knowledge-source-name = employees-ks
    @knowledge-base-name = employees-kb
    @container-name = <blob-container>
    @storage-resource-id = /subscriptions/<subscription-id>/resourceGroups/<resource-group>/providers/Microsoft.Storage/storageAccounts/<storage-account>
    @model-endpoint = https://<model-resource>.openai.azure.com
    @chat-deployment = <chat-completion-deployment>
    @embedding-deployment = <embedding-deployment>
    
  2. 用 Python、C# 或 REST 建立新的知識來源。

    該 graphExtraction.ontology 屬性是一個 JSON 物件,而非 XML。 設 kind 為 inline,並設 value 為序列化為 JSON 字串的受限 JSON-LD 文件。 name 屬性是選擇性的。 在 SDK 範例中,將前一節的本體結構儲存為 ontology.json,並設定以下環境變數:SEARCH_ENDPOINT、 MODEL_ENDPOINTKNOWLEDGE_SOURCE_NAMEEMBEDDING_DEPLOYMENTCONTAINER_NAMESTORAGE_RESOURCE_IDCHAT_DEPLOYMENT。

import json
import os

from azure.identity import DefaultAzureCredential
from azure.search.documents.indexes import SearchIndexClient
from azure.search.documents.indexes.models import (
    AzureBlobKnowledgeSource,
    AzureBlobKnowledgeSourceParameters,
    AzureOpenAIVectorizerParameters,
    KnowledgeBaseAzureOpenAIModel,
    KnowledgeSourceContentExtractionMode,
    KnowledgeSourceGraphExtractionParameters,
    KnowledgeSourceGraphOntology,
)
from azure.search.documents.knowledgebases.models import (
    KnowledgeSourceAzureOpenAIVectorizer,
    KnowledgeSourceIngestionParameters,
)

with open("ontology.json", encoding="utf-8") as ontology_file:
    entity_ontology_value = json.dumps(
        json.load(ontology_file), separators=(",", ":")
    )

entity_model_endpoint = os.environ["MODEL_ENDPOINT"]
entity_ingestion_parameters = KnowledgeSourceIngestionParameters(
    content_extraction_mode=KnowledgeSourceContentExtractionMode.MINIMAL,
    disable_image_verbalization=True,
    chat_completion_model=KnowledgeBaseAzureOpenAIModel(
        azure_open_ai_parameters=AzureOpenAIVectorizerParameters(
            resource_url=entity_model_endpoint,
            deployment_name=os.environ["CHAT_DEPLOYMENT"],
            model_name="gpt-5.6-luna",
        )
    ),
    embedding_model=KnowledgeSourceAzureOpenAIVectorizer(
        azure_open_ai_parameters=AzureOpenAIVectorizerParameters(
            resource_url=entity_model_endpoint,
            deployment_name=os.environ["EMBEDDING_DEPLOYMENT"],
            model_name="text-embedding-3-small",
        )
    ),
)
entity_graph_parameters = KnowledgeSourceGraphExtractionParameters(
    graph_name="employees",
    page_degree_of_parallelism=2,
    ontology=KnowledgeSourceGraphOntology(
        kind="inline",
        name="employees-v1",
        value=entity_ontology_value,
    ),
)
entity_blob_parameters = AzureBlobKnowledgeSourceParameters(
    connection_string=f"ResourceId={os.environ['STORAGE_RESOURCE_ID']}",
    container_name=os.environ["CONTAINER_NAME"],
    ingestion_parameters=entity_ingestion_parameters,
    graph_extraction=entity_graph_parameters,
)
entity_knowledge_source = AzureBlobKnowledgeSource(
    name=os.environ["KNOWLEDGE_SOURCE_NAME"],
    description="Employees, their employers, and employer locations.",
    results_processing="none",
    azure_blob_parameters=entity_blob_parameters,
)
entity_index_client = SearchIndexClient(
    endpoint=os.environ["SEARCH_ENDPOINT"],
    credential=DefaultAzureCredential(),
)
entity_index_client.create_or_update_knowledge_source(
    entity_knowledge_source
)

參考資料:Python 用戶端函式庫。

回讀來源以取得配置後產生的資源名稱。

GET {{search-endpoint}}/knowledgesources('{{knowledge-source-name}}')?api-version={{api-version}}
Authorization: Bearer {{access-token}}

參考資料: 知識來源 REST API。

等待 azureBlobParameters.createdResources.graphIndex 出現;它可能不會出現在建立回應中。 將該回傳名稱用於直接圖查詢,並將 createdResources.index 用於來源區塊查找。 這些屬性是唯讀的。 來源擁有其產生的資料來源、索引器、技能集、區塊索引及圖表索引。

確認擷取完成

建立會開始擷取。 當原始內容被處理時,關聯會顯示在圖表中。

  1. 取得來源狀態。

    GET {{search-endpoint}}/knowledgesources('{{knowledge-source-name}}')/status?api-version={{api-version}}
    Authorization: Bearer {{access-token}}
    

    參考資料: 知識來源 REST API。

  2. 請等待同步完成。 檢查 lastSynchronizationState.endTime 是否存在、currentSynchronizationState 是否為空,且 lastSynchronizationState.itemsUpdatesFailed 是否為零。 若匯入失敗,請檢查同步錯誤及已產生的索引子的狀態。

    synchronizationStatus: "active" 表示來源可供同步,而非提取完成。 回傳時,graphStatistics.triplesWritten 描述該同步期間的寫入,而非圖形結構的總大小。

透過知識庫查詢圖形

知識庫將自然語言關係問題轉換成GQL。 其模型配置與用來擷取圖形的模型是分開的。

  1. 建立一個以 Python、C# 或 REST 引用支援圖譜的來源的知識庫。 如適用,重複使用現有模型部署,但請在知識庫中明確設定。

    若是 SDK 範例,也請在您的程序環境中設定 KNOWLEDGE_BASE_NAME。

import os

from azure.identity import DefaultAzureCredential
from azure.search.documents.indexes import SearchIndexClient
from azure.search.documents.indexes.models import (
    AzureOpenAIVectorizerParameters,
    KnowledgeBase,
    KnowledgeBaseAzureOpenAIModel,
    KnowledgeSourceReference,
)
from azure.search.documents.knowledgebases.models import (
    KnowledgeRetrievalLowReasoningEffort,
    KnowledgeRetrievalOutputMode,
)

entity_kb_model_parameters = AzureOpenAIVectorizerParameters(
    resource_url=os.environ["MODEL_ENDPOINT"],
    deployment_name=os.environ["CHAT_DEPLOYMENT"],
    model_name="gpt-5.6-luna",
)
entity_knowledge_base = KnowledgeBase(
    name=os.environ["KNOWLEDGE_BASE_NAME"],
    knowledge_sources=[
        KnowledgeSourceReference(
            name=os.environ["KNOWLEDGE_SOURCE_NAME"]
        )
    ],
    models=[
        KnowledgeBaseAzureOpenAIModel(
            azure_open_ai_parameters=entity_kb_model_parameters
        )
    ],
    retrieval_reasoning_effort=KnowledgeRetrievalLowReasoningEffort(),
    output_mode=KnowledgeRetrievalOutputMode.EXTRACTIVE_DATA,
    retrieval_instructions=(
        "Use graph_search for entity relationship questions. "
        "Answer the relationship question by traversing the graph, "
        "rather than using ordinary text search."
    ),
)
entity_kb_index_client = SearchIndexClient(
    endpoint=os.environ["SEARCH_ENDPOINT"],
    credential=DefaultAzureCredential(),
)
entity_kb_index_client.create_or_update_knowledge_base(
    entity_knowledge_base
)

參考資料:Python 用戶端函式庫。

  1. 請使用 Python、C# 或 REST 執行以下查詢。

    此請求啟用活動與來源參照。 它同時也啟用產生的查詢揭露與來源文件內容還原。

import os

from azure.identity import DefaultAzureCredential
from azure.search.documents.knowledgebases import KnowledgeBaseRetrievalClient
from azure.search.documents.knowledgebases.models import (
    AgentRuntimeGraphHydrateDocumentsParams,
    AgentRuntimeGraphParams,
    AgentRuntimeGraphProvenanceParams,
    AzureBlobKnowledgeSourceParams,
    KnowledgeBaseMessage,
    KnowledgeBaseMessageTextContent,
    KnowledgeBaseRetrievalRequest,
)

source = AzureBlobKnowledgeSourceParams(
    knowledge_source_name=os.environ["KNOWLEDGE_SOURCE_NAME"],
    include_references=True,
    include_reference_source_data=True,
    fail_on_error=True,
    graph_parameters=AgentRuntimeGraphParams(
        include_query=True,
        provenance=AgentRuntimeGraphProvenanceParams(
            kind="hydrate",
            hydrate_documents=AgentRuntimeGraphHydrateDocumentsParams(
                select="uid,snippet,snippet_parent_id,blob_url", top=10
            ),
        ),
    ),
)
request = KnowledgeBaseRetrievalRequest(
    messages=[
        KnowledgeBaseMessage(
            role="user",
            content=[
                KnowledgeBaseMessageTextContent(
                    text=(
                        "Which people work for organizations located in Seattle? "
                        "Return their names, organization names, and city names."
                    )
                )
            ],
        )
    ],
    include_activity=True,
    output_mode="extractiveData",
    max_runtime_in_seconds=60,
    knowledge_source_params=[source],
)
with KnowledgeBaseRetrievalClient(
    endpoint=os.environ["SEARCH_ENDPOINT"],
    credential=DefaultAzureCredential(),
    knowledge_base_name=os.environ["KNOWLEDGE_BASE_NAME"],
) as client:
    result = client.retrieve(request)

參考資料:Python 用戶端函式庫。

圖參照用來識別 graphIndexName 中的受管理圖以及 activitySource 中的執行活動。 啟用 hydration 時,額外參考會在 sourceData 中包含支援來源區塊。 其 uid、snippet_parent_id,以及 blob_url 允許你追蹤結果至其區塊與父文件。

知識庫圖的來源預設為 none。 若要回傳不含水合區塊的圖列,請省略 graphParameters.provenance。 hydration top 會獨立於圖形列數限制來源文件。

直接使用 GQL 查詢圖形

當您的應用程式自行提供遍歷時,請使用受管理的圖形索引。 直接 search.graph 運算需要 gql。 其 search 屬性為選用,且僅適用於全文搜尋。

  1. 在您的 REST 用戶端中設定 GRAPH_INDEX_NAME,或在您的 SDK 流程環境中設定 graph-index-name,並將其設為回傳的 createdResources.graphIndex 值。

  2. 先跑一個從一個人到雇主,再跑到城市的兩跳遍歷。 標籤與謂詞與先前定義的本體論相符。

import os

from azure.identity import DefaultAzureCredential
from azure.search.documents import SearchClient
from azure.search.documents.models import (
    GraphQueryProvenanceHydrateDocumentsParameters,
    GraphQueryProvenanceParameters,
)

gql = (
    "MATCH (person:Person)-[job]->(org:Organization)"
    "-[location]->(city:Place) "
    "WHERE job.predicate = 'worksFor' "
    "AND location.predicate = 'locatedIn' "
    "AND city.name = 'Seattle' "
    "RETURN person.name AS person, org.name AS organization, "
    "city.name AS city LIMIT 10"
)
with SearchClient(
    os.environ["SEARCH_ENDPOINT"],
    os.environ["GRAPH_INDEX_NAME"],
    DefaultAzureCredential(),
) as client:
    result = client.graph(
        gql=gql,
        include_statistics=True,
        include_diagnostics=True,
        provenance=GraphQueryProvenanceParameters(
            kind="hydrate",
            max_evidence_per_row=10,
            hydrate_documents=GraphQueryProvenanceHydrateDocumentsParameters(
                select="uid,snippet,snippet_parent_id,blob_url"
            ),
        ),
    )

參考資料:Python 用戶端函式庫。

每一列 @search.graphProvenance 包含支援 edgeId、chunkId 和 parentId 的識別碼。 將 id 連接到圖形宣告的 uid,並將 chunkId 連接到產生的區塊索引中的 edgeId。 hydrated chunks 會在 @search.graphProvenanceDocuments 的各列間共享;對於此受管理的圖形,映射鍵為區塊 ID。

用 evidenceCount.relation 來解釋證據計數:exact 表示計數是完整的,而 lowerBound 表示收集受到限制,因此可能存在更多支持證據。 maxEvidencePerRow 會限制蒐集到的證據量。

對於未進行文件水合的識別碼,請使用 kind: "ids" 並省略 hydrateDocuments。 直接 hydration 支援欄位選擇,但與知識庫 hydration 不同,它不接受 top。

排除圖形查詢疑難

對於擷取失敗,請檢查頂層錯誤,並在有傳回時檢查該 graphSearch 活動。

Problem Action
查詢模型節流 當知識庫的查詢模型回傳 429(TooManyRequests)時,擷取請求可以返回 502 與 All retrieval tasks failed。 檢查該模型部署的 令牌與請求速率限制 ,並 依照速率限制的重試指引 行事,而非不斷重複傳送請求。 此查詢模型失敗並不代表擷取失敗或對無伺服器圖查詢造成限制。
沒有預期的圖形資料列 確認 同步已完成,然後執行 直接 GQL 遍歷 以檢查已儲存的關聯。 空白的查詢結果並不會確認擷取成功。

清理測試資源

刪除您為本次練習建立的知識庫,然後刪除知識來源。

刪除來源會移除其產生的搜尋資源,包括管理式圖表索引,但不會刪除你的 blobs。 只移除測試 blob,或移除容器(若是為此練習建立)。 保留共用儲存帳戶和模型部署。

有關底層擷取設定與擷取工作流程,請參閱: