For the complete documentation index, see llms.txt. Markdown versions of documentation pages are available by appending .md to the page URL.
主要導覽

檢索

透過語意相似度搜尋你的資料。

Retrieval API 讓你對資料進行語意搜尋。這項技術能找出語意相近的結果,即使只有少數關鍵字相符,甚至完全沒有相符的關鍵字。檢索本身就很實用,搭配我們的模型來整合資訊並產生回應時,更能發揮強大效用。

檢索示意圖

Retrieval API 以向量儲存庫為基礎,利用向量儲存庫為你的資料建立索引。本指南將介紹如何執行語意搜尋,並詳細說明向量儲存庫。

快速入門

  • 建立向量儲存庫 並上傳檔案。

  • 建立含有檔案的向量儲存庫
    from openai import OpenAI
    
    client = OpenAI()
    
    vector_store = client.vector_stores.create(        # Create vector store
        name="Support FAQ",
    )
    
    client.vector_stores.files.upload_and_poll(        # Upload file
        vector_store_id=vector_store.id,
        file=open("customer_policies.txt", "rb")
    )
  • 傳送搜尋查詢 以取得相關結果。

  • 搜尋查詢
    user_query = "What is the return policy?"
    
    results = client.vector_stores.search(
        vector_store_id=vector_store.id,
        query=user_query,
    )

    如要瞭解如何將搜尋結果搭配我們的模型使用,請參閱整合資訊並 產生回應一節。

    語意搜尋 利用嵌入向量找出語意相關的結果。這項技術的關鍵在於,即使結果只有少數相同的關鍵字,甚至完全沒有相同的關鍵字,也能被找出來,而傳統搜尋技術可能會遺漏這些結果。

    例如,來看看 "When did we go to the moon?" 可能會得到哪些結果:

    文字關鍵字相似度語意相似度
    首次登月發生於 1969 年 7 月。0%65%
    第一位登上月球的人是尼爾.阿姆斯壯。27%43%
    我吃了那個月餅,覺得很好吃。40%28%

    (關鍵字相似度使用交集與聯集的比值計算;語意相似度則搭配 text-embedding-3-small,使用餘弦相似度計算。)

    請注意,最相關的結果完全不含搜尋查詢中的任何字詞。這種彈性讓語意搜尋成為查詢各種規模知識庫的強大技術。

    語意搜尋以向量儲存庫為基礎,本指南稍後會詳細介紹向量儲存庫。本節將著重說明語意搜尋的運作方式。

    你可以使用 search 函式,並以自然語言指定 query,來查詢向量儲存庫。這會傳回結果清單,每筆結果都包含相關的文字區塊、相似度分數及來源檔案。

    搜尋查詢
    results = client.vector_stores.search(
        vector_store_id=vector_store.id,
        query="How many woodchucks are allowed per passenger?",
    )
    結果
    {
      "object": "vector_store.search_results.page",
      "search_query": "How many woodchucks are allowed per passenger?",
      "data": [
        {
          "file_id": "file-12345",
          "filename": "woodchuck_policy.txt",
          "score": 0.85,
          "attributes": {
            "region": "North America",
            "author": "Wildlife Department"
          },
          "content": [
            {
              "type": "text",
              "text": "According to the latest regulations, each passenger is allowed to carry up to two woodchucks."
            },
            {
              "type": "text",
              "text": "Ensure that the woodchucks are properly contained during transport."
            }
          ]
        },
        {
          "file_id": "file-67890",
          "filename": "transport_guidelines.txt",
          "score": 0.75,
          "attributes": {
            "region": "North America",
            "author": "Transport Authority"
          },
          "content": [
            {
              "type": "text",
              "text": "Passengers must adhere to the guidelines set forth by the Transport Authority regarding the transport of woodchucks."
            }
          ]
        }
      ],
      "has_more": false,
      "next_page": null
    }

    回應預設最多包含 10 筆結果,但你可以透過 max_num_results 參數將上限設為最多 50 筆。

    查詢改寫

    某些查詢方式能得到更好的結果,因此我們提供了一項設定,可自動改寫查詢以達到最佳效果。執行 search 時,設定 rewrite_query=true 即可啟用這項功能。

    改寫後的查詢會出現在結果的 search_query 欄位中。

    原始查詢改寫後的查詢
    我想知道主要辦公大樓的高度。主要辦公大樓高度
    運送危險物品有哪些安全規範?危險物品安全規範
    我要如何針對服務問題提出申訴?服務申訴提出流程

    屬性篩選

    屬性篩選可透過套用條件來縮小結果範圍,例如將搜尋限制在特定日期範圍內。你可以在 attribute_filter 中定義及組合條件,在執行語意搜尋前,先依檔案屬性篩選出目標檔案。

    使用 比較篩選器 ,將檔案 attributes 中的特定 key 與指定的 value 比較;使用 複合篩選器 ,則可透過 andor 組合多個篩選器。

    比較篩選器
    {
      "type": "eq" | "ne" | "gt" | "gte" | "lt" | "lte" | "in" | "nin",  // comparison operators
      "key": "attributes_key",                           // attributes key
      "value": "target_value"                             // value to compare against
    }
    複合篩選器
    {
      "type": "and" | "or",                                // logical operators
      "filters": [...]
    }

    以下是一些篩選器範例。

    依地區篩選
    {
      "type": "eq",
      "key": "region",
      "value": "us"
    }

    排序

    如果檔案搜尋結果的相關性不夠高,你可以調整 ranking_options,改善回應品質。可調整的項目包括指定 ranker,例如 autodefault-2024-08-21,以及將 score_threshold 設為 0.0 到 1.0 之間的值。提高 score_threshold 會讓結果僅包含相關性較高的區塊,但也可能排除一些有用的區塊。提供 ranking_options.hybrid_search 時,你也可以調整 hybrid_search.embedding_weightrrf_embedding_weight)和 hybrid_search.text_weightrrf_text_weight),控制倒數排名融合如何平衡語意嵌入比對與稀疏關鍵字比對的結果。提高前者的權重可強調語意相似度,提高後者的權重可強調文字重疊程度,且至少須有一個權重大於零。

    向量儲存庫

    向量儲存庫是為 Retrieval API 和檔案搜尋工具提供語意搜尋功能的容器。將檔案加入向量儲存庫後,系統會自動將檔案分割成區塊、產生嵌入向量,並建立索引。

    向量儲存庫包含 vector_store_file 物件,每個物件都以一個 file 物件為基礎。

    物件類型
    說明
    file代表透過 Files API 上傳的內容。通常與向量儲存庫搭配使用,也可用於微調和其他使用案例。
    vector_store存放可搜尋檔案的容器。
    vector_store.file封裝類型,專門用來代表已分割成區塊、產生嵌入向量,並與 vector_store 建立關聯的 file
    包含用於篩選的 attributes 對應表。

    定價

    費用依所有向量儲存庫使用的總儲存空間計算,儲存用量取決於解析後的區塊及其對應嵌入向量的大小。

    儲存空間費用
    1 GB 以內(所有儲存庫合計)免費
    超過 1 GB 的部分$0.10/GB/天

    如需瞭解盡量降低費用的選項,請參閱到期政策

    向量儲存庫操作

    建立向量儲存庫
    client.vector_stores.create(
        name="Support FAQ",
        file_ids=["file_123"]
    )

    向量儲存庫檔案操作

    某些操作(例如 vector_store.filecreate)採非同步方式執行,可能需要一些時間才能完成。您可以使用我們的輔助函式(例如 create_and_poll)阻塞等待,直到操作完成,也可以自行檢查狀態。從向量儲存庫移除檔案採用最終一致性,因此搜尋結果在短時間內仍可能包含已移除檔案的內容。

    新增檔案的速率限制以各個向量儲存庫 ID 為單位。對 /vector_stores/{vector_store_id}/files/vector_stores/{vector_store_id}/file_batches 發出的請求,共用每個向量儲存庫每分鐘 300 次請求的限制。

    建立向量儲存庫檔案
    client.vector_stores.files.create_and_poll(
        vector_store_id="vs_123",
        file_id="file_123"
    )

    批次處理操作

    建立批次處理的操作
    client.vector_stores.file_batches.create_and_poll(
        vector_store_id="vs_123",
        files=[
            {
                "file_id": "file_123",
                "attributes": {"department": "finance"}
            },
            {
                "file_id": "file_456",
                "chunking_strategy": {
                    "type": "static",
                    "max_chunk_size_tokens": 1200,
                    "chunk_overlap_tokens": 200
                }
            }
        ]
    )

    建立批次時,你可以提供 file_ids,並選擇性地搭配 attributes 和/或 chunking_strategy;也可以使用 files 陣列,為每個檔案傳入包含 file_id 以及選填的 attributeschunking_strategy 的物件。這兩種方式不能同時使用,讓你能明確控制所有檔案是否共用相同設定,或是針對個別檔案覆寫設定。

    若要提高將資料匯入單一向量儲存庫的吞吐量,建議盡可能使用批次建立。每個批次可在一次請求中包含最多 500 個檔案。相較於傳送大量單一檔案建立請求,這通常能減少資源爭用,並降低端到端延遲。

    屬性

    每個 vector_store.file 都可以有關聯的 attributes,這是一個儲存值的字典,可在執行搭配屬性篩選語意搜尋時參照。字典最多可有 16 個鍵,每個鍵的長度上限為 256 個字元。

    建立具有屬性的向量儲存庫檔案
    client.vector_stores.files.create(
        vector_store_id="<vector_store_id>",
        file_id="file_123",
        attributes={
            "region": "US",
            "category": "Marketing",
            "date": 1672531200      # Jan 1, 2023
        }
    )

    到期政策

    你可以使用 expires_aftervector_store 物件設定到期政策。向量儲存庫到期後,所有關聯的 vector_store.file 物件都會遭到刪除,也不再產生費用。

    設定向量儲存庫的到期政策
    client.vector_stores.update(
        vector_store_id="vs_123",
        expires_after={
            "anchor": "last_active_at",
            "days": 7
        }
    )

    限制

    檔案大小上限為 512 MB。每個檔案應包含不超過 5,000,000 個 Token(附加檔案時會自動計算)。

    分塊

    預設情況下,max_chunk_size_tokens 設為 800chunk_overlap_tokens 設為 400。這表示每個檔案在建立索引時,都會分割成各含 800 個 Token 的區塊,相鄰區塊之間有 400 個 Token 重疊。

    你可以在將檔案新增至向量儲存庫時,設定 chunking_strategy 來調整分塊方式。此策略有以下限制:

    • max_chunk_size_tokens 必須介於 100 到 4096 之間,包含上下限。
    • chunk_overlap_tokens 必須為非負值,且不應超過 max_chunk_size_tokens / 2

    整合產生回應

    執行查詢後,你可能會想根據結果整合產生回應。你可以將結果和原始查詢提供給我們的模型,讓模型產生有依據的回應。

    執行搜尋查詢以取得結果
    from openai import OpenAI
    
    client = OpenAI()
    
    user_query = "What is the return policy?"
    
    results = client.vector_stores.search(
        vector_store_id=vector_store.id,
        query=user_query,
    )
    根據結果整合產生回應
    # Use results and user_query from the preceding search step.
    formatted_results = format_results(results.data)
    
    "\n".join("\n".join(c.text for c in result.content) for result in results.data)
    
    completion = client.chat.completions.create(
        model="gpt-6-astra",
        messages=[
            {
                "role": "developer",
                "content": "Produce a concise answer to the query based on the provided sources.",
            },
            {
                "role": "user",
                "content": f"Sources: {formatted_results}\n\nQuery: '{user_query}'",
            },
        ],
    )
    
    print(completion.choices[0].message.content)
    "Our return policy allows returns within 30 days of purchase."

    這裡使用了範例函式 format_results,其實作方式可以 如下:

    結果格式化函式範例
    def format_results(results):
        formatted_results = ""
        for result in results.data:
            formatted_result = (
                f"<result file_id='{result.file_id}' file_name='{result.file_name}'>"
            )
            for part in result.content:
                formatted_result += f"<content>{part.text}</content>"
            formatted_results += formatted_result + "</result>"
        return f"<sources>{formatted_results}</sources>"