如需完整的文件索引,請參閱 llms.txt。在文件頁面的網址末尾加上 .md ,即可取得該頁面的 Markdown 版本。
主要導覽
主題

檢索

根據語意相似度搜尋資料。

你可以使用 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%
    第一位踏上月球的人是 Neil Armstrong。 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 筆。

    改寫查詢

    某些查詢寫法能得到更好的結果,因此我們提供了自動改寫查詢的設定,以改善搜尋效果。將 rewrite_query=true 設為執行 search 時的參數,即可啟用這項功能。

    你可以在結果的 search_query 欄位查看改寫後的查詢。

    原始查詢 改寫後的查詢
    我想知道總部辦公大樓有多高。 總部辦公大樓高度
    運輸危險物品有哪些安全規定? 危險物品安全規定
    遇到服務問題時,我該如何提出申訴? 服務申訴流程

    依屬性篩選

    你可以設定屬性條件來縮小搜尋範圍,例如只搜尋特定日期範圍內的檔案。在 filters 中定義並組合條件,即可先依屬性篩選檔案,再執行語意搜尋。

    使用比較篩選器時,先指定 key,再將檔案 attributes 中該鍵對應的值與給定的 value 比較。使用複合篩選器時,則可透過 and 和 or 組合多個篩選器。

    比較篩選器
    {
      "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": [...]
    }

    以下是幾個篩選器範例。

    下列檔名範例會比對自訂的 filename 屬性。你必須為向量儲存庫中的每個檔案明確設定這項屬性,例如 {"filename": "example.txt"}。篩選器不會自動比對上傳時的檔名。

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

    排序

    如果檔案搜尋結果的相關性不足,可以調整 ranking_options 來改善回應品質。你可以指定 ranker,例如 auto 或 default-2024-08-21,並將 score_threshold 設為 0.0 到 1.0 之間的值。提高 score_threshold 可讓結果只包含相關性較高的區塊,但也可能排除一些有用的內容。如果指定了 ranking_options.hybrid_search,還可以調整 hybrid_search.embedding_weight(rrf_embedding_weight)和 hybrid_search.text_weight(rrf_text_weight),控制倒數排名融合演算法如何權衡語意嵌入比對與稀疏關鍵字比對的結果。提高前者的權重會更重視語意相似度,提高後者的權重則會更重視文字重疊程度。至少要有一個權重大於零。

    向量儲存庫

    向量儲存庫是 Retrieval API 和檔案搜尋工具用來執行語意搜尋的容器。將檔案加入向量儲存庫後,系統會自動把檔案切成區塊、產生嵌入向量並建立索引。

    向量儲存庫包含 vector_store_file 物件,每個物件都對應一個底層的 file 物件。

    物件類型
    說明
    file 代表透過 Files API 上傳的內容。常與向量儲存庫搭配使用,也可用於微調及其他用途。
    vector_store 用來存放可搜尋檔案的容器。
    vector_store.file 此包裝類型代表一個 file,其內容已切成區塊並轉換為嵌入向量,且已與一個 vector_store 建立關聯。
    其中包含用於篩選的 attributes 對應表。

    費用

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

    儲存用量 費用
    所有儲存庫合計的前 1 GB 免費
    超過 1 GB 的部分 每 GB 每天 0.10 美元

    如要盡可能降低費用,請參閱到期政策。

    向量儲存庫操作

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

    向量儲存庫檔案操作

    部分操作採非同步方式執行,例如用 create 建立 vector_store.file,可能需要一些時間才能完成。你可以使用 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",
                    "static": {
                        "max_chunk_size_tokens": 1200,
                        "chunk_overlap_tokens": 200
                    }
                }
            }
        ]
    )

    建立批次時,可以提供 file_ids,並視需要指定 attributes 和 chunking_strategy 中的一項或兩項。也可以使用 files 陣列,為每個檔案傳入一個物件,內含 file_id 以及選用的 attributes 和 chunking_strategy。這兩種方式只能擇一使用。若所有檔案共用設定,請使用前者。若要個別覆寫檔案設定,請使用後者。

    若要提高單一向量儲存庫匯入檔案的吞吐量,建議盡可能使用批次建立。每次批次請求最多可包含 500 個檔案。相較於為每個檔案分別傳送建立請求,批次建立通常能減少資源競爭,縮短端對端延遲。

    屬性

    每個 vector_store.file 都可以設定 attributes。這個字典儲存屬性值,執行語意搜尋時,可透過屬性篩選引用這些值。字典最多可包含 16 個鍵。每個鍵最多可包含 64 個字元,每個字串值最多可包含 512 個字元。

    建立含有屬性的向量儲存庫檔案
    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
        }
    )

    到期政策

    你可以為 vector_store 物件設定 expires_after,指定到期政策。向量儲存庫到期後,系統會刪除所有相關的 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 設為 800,chunk_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.filename}'>"
            )
            for part in result.content:
                formatted_result += f"<content>{part.text}</content>"
            formatted_results += formatted_result + "</result>"
        return f"<sources>{formatted_results}</sources>"