Text reranking
==============

``aidb.rerank_text()``
ファンクションを使用して、クエリーとの関連性によって一連の候補テキストパッセージを並べ替えます。再ランキングは通常、取得後のステップとして適用され、候補の初期セットがナレッジベースから取得された後、最も関連性の高い結果を上部に表示します。

**ステップ1リランキングモデルを登録する**

.. code:: sql

   SELECT aidb.create_model(
       my_reranker,
       nim_reranking,
       config => aidb.nim_reranking_config(
           api_key => nvapi-...,
           model   => nvidia/nv-rerankqa-mistral-4b-v3
       )
   );

**ステップ2:候補セットを再ランク付けする**

.. code:: sql

   SELECT * FROM aidb.rerank_text(
       model_name => my_reranker,
       query      => What is retrieval-augmented generation?,
       input      => ARRAY[
           RAG combines retrieval and generation to produce grounded answers.,
           Vector databases store high-dimensional embeddings for similarity search.,
           RAG systems retrieve relevant documents before generating a response.
       ]
   ) ORDER BY logit_score DESC;

   __OUTPUT__
                                 text                              | logit_score | id
   - ---------------------------------------------------------------+-------------+----
    RAG systems retrieve relevant documents before generating ...  |        0.97 |  2
    RAG combines retrieval and generation to produce grounded ...  |        0.91 |  0
    Vector databases store high-dimensional embeddings for ...     |        0.43 |  1
   (3 rows)

``id`` 列は、\ ``input``
配列内の各文字列の0ベースのインデックスであるため、元のデータに結合して戻すことができます。

完全なパラメーターのリファレンスについては、
:ref:`Models reference <Models reference>` を参照してください。

ナレッジベースの取得後に再ランキングを使用する
----------------------------------------------

一般的なパターンは、ナレッジベースから初期候補セットを取得し、結果を再ランク付けすることです。

.. code:: sql

   WITH candidates AS (
       SELECT key, value
       FROM aidb.retrieve_text(my_kb, What is RAG?, topk => 20)
   )
   SELECT c.key, c.value, r.logit_score
   FROM candidates c
   JOIN aidb.rerank_text(
       model_name => my_reranker,
       query      => What is RAG?,
       input      => ARRAY(SELECT value FROM candidates ORDER BY key)
   ) r ON r.text = c.value
   ORDER BY r.logit_score DESC
   LIMIT 5;

!!!注
再ランキングモデルは、クエリに対してパッセージをスコアリングしますが、テキストは生成しません。リランキングモデルを登録するには、プロバイダーに適切な :ref:`모델 설정 도우미 <모델 설정 도우미>` を使用します。たとえば、NVIDIA
NIMリランキングエンドポイントの場合は\ ``aidb.nim_reranking_config()``
です。
