ブログ

高度なRAGテクニックパート2:クエリとテスト

RAG のパフォーマンスを向上させる可能性のあるテクニックについて議論し、実装します。パート 2/2。高度な RAG パイプラインのクエリとテストに焦点を当てます。

すべてのコードは 、Searchlabs リポジトリの advanced-rag-techniques ブランチに あります 。

高度な RAG テクニックに関する記事のパート 2 へようこそ。このシリーズのパート 1では、高度な RAG パイプラインのデータ処理コンポーネントを設定、説明、実装しました。

高度なRAGパイプライン

著者が使用した RAG パイプライン。

この部分では、実装のクエリとテストを進めていきます。早速始めましょう!

目次

検索と取得、回答の生成

最初のクエリ、理想的には主に年次報告書に記載されている情報を尋ねてみましょう。いかがでしょうか:

Who audits Elastic?"

ここで、クエリを強化するためにいくつかのテクニックを適用してみましょう。

同義語によるクエリの強化

まず、クエリの文言の多様性を高めて、Elasticsearch クエリに簡単に処理できる形式に変えてみましょう。GPT-4o の助けを借りて、クエリを OR 句のリストに変換します。次のプロンプトを書いてみましょう:


ELASTIC_SEARCH_QUERY_GENERATOR_PROMPT = '''
You are an AI assistant specialized in generating Elasticsearch query strings. Your task is to create the most effective query string for the given user question. This query string will be used to search for relevant documents in an Elasticsearch index.

Guidelines:
1. Analyze the user's question carefully.
2. Generate ONLY a query string suitable for Elasticsearch's match query.
3. Focus on key terms and concepts from the question.
4. Include synonyms or related terms that might be in relevant documents.
5. Use simple Elasticsearch query string syntax if helpful (e.g., OR, AND).
6. Do not use advanced Elasticsearch features or syntax.
7. Do not include any explanations, comments, or additional text.
8. Provide only the query string, nothing else.

For the question "What is Clickthrough Data?", we would expect a response like:
clickthrough data OR click-through data OR click through rate OR CTR OR user clicks OR ad clicks OR search engine results OR web analytics

AND operator is not allowed. Use only OR.

User Question:
[The user's question will be inserted here]

Generate the Elasticsearch query string:
'''

GPT-4o をクエリに適用すると、基本クエリの同義語と関連語彙が生成されます。

'audits elastic OR 
elasticsearch audits OR 
elastic auditor OR 
elasticsearch auditor OR 
elastic audit firm OR 
elastic audit company OR 
elastic audit organization OR 
elastic audit service'

ESQueryMakerクラスでは、クエリを分割する関数を定義しました。

def parse_or_query(self, query_text: str) -> List[str]:
    # Split the query by 'OR' and strip whitespace from each term
    # This converts a string like "term1 OR term2 OR term3" into a list ["term1", "term2", "term3"]
    return [term.strip() for term in query_text.split(' OR ')]

その役割は、この OR 句の文字列を取得して用語のリストに分割し、主要なドキュメント フィールドで複数の一致を実行できるようにすることです。

["original_text", 'keyphrases', 'potential_questions', 'entities']

最終的にこのクエリに至ります:

 'query': {
    'bool': {
        'must': [
            {
                'multi_match': {
                'query': 'audits Elastic Elastic auditing Elastic audit process Elastic compliance Elastic security audit Elasticsearch auditing Elasticsearch compliance Elasticsearch security audit',
                'fields': [
                    'original_text',
                'keyphrases',
                'potential_questions',
                'entities'
                ],
                'type': 'best_fields',
                'operator': 'or'
                }
            }
      ]

これにより、元のクエリよりも多くのベースがカバーされ、同義語を忘れたために検索結果を見逃すリスクが軽減されることが期待されます。しかし、私たちにはもっとできることがある。

トップに戻る

HyDE(仮想文書埋め込み)

今回はHyDE を実装するために、再び GPT-4o を活用しましょう。

HyDE の基本的な前提は、仮想ドキュメント (元のクエリに対する回答が含まれる可能性のある種類のドキュメント) を生成することです。文書の事実性や正確性は問題ではありません。それを念頭に置いて、次のプロンプトを書いてみましょう。

HYDE_DOCUMENT_GENERATOR_PROMPT = '''
You are an AI assistant specialized in generating hypothetical documents based on user queries. Your task is to create a detailed, factual document that would likely contain the answer to the user's question. This hypothetical document will be used to enhance the retrieval process in a Retrieval-Augmented Generation (RAG) system.

Guidelines:
1. Carefully analyze the user's query to understand the topic and the type of information being sought.
2. Generate a hypothetical document that:
   a. Is directly relevant to the query
   b. Contains factual information that would answer the query
   c. Includes additional context and related information
   d. Uses a formal, informative tone similar to an encyclopedia or textbook entry
3. Structure the document with clear paragraphs, covering different aspects of the topic.
4. Include specific details, examples, or data points that would be relevant to the query.
5. Aim for a document length of 200-300 words.
6. Do not use citations or references, as this is a hypothetical document.
7. Avoid using phrases like "In this document" or "This text discusses" - write as if it's a real, standalone document.
8. Do not mention or refer to the original query in the generated document.
9. Ensure the content is factual and objective, avoiding opinions or speculative information.
10. Output only the generated document, without any additional explanations or meta-text.

User Question:
[The user's question will be inserted here]

Generate a hypothetical document that would likely contain the answer to this query:
'''

ベクトル検索は通常、コサインベクトルの類似度に基づいて行われるため、クエリをドキュメントに一致させるのではなく、ドキュメントをドキュメントに一致させることでより良い結果を達成できるというのが HyDE の前提です。

私たちが重視するのは、構造、フロー、用語です。あまり事実ではない。GPT-4o は次のような HyDE ドキュメントを出力します。

'Elastic N.V., the parent company of Elastic, the organization known for developing Elasticsearch, is subject to audits to ensure financial accuracy, 
regulatory compliance, and the integrity of its financial statements. The auditing of Elastic N.V. is typically conducted by an external, 
independent auditing firm. This is common practice for publicly traded companies to provide stakeholders with assurance regarding the company\'s 
financial position and operations.\n\nThe primary external auditor for Elastic is the audit firm Ernst & Young LLP (EY). Ernst & Young is one of the 
four largest professional services networks in the world, commonly referred to as the "Big Four" audit firms. These firms handle a substantial number 
of audits for major corporations around the globe, ensuring adherence to generally accepted accounting principles (GAAP) and international financial 
reporting standards (IFRS).\n\nThe audit process conducted by EY involves several steps. Initially, the auditors perform a risk assessment to identify 
areas where misstatements due to error or fraud could occur. They then design audit procedures to test the accuracy and completeness of financial statements,
 which include examining financial transactions, assessing internal controls, and reviewing compliance with relevant laws and regulations. Upon completion of 
 the audit, Ernst & Young issues an audit report, which includes the auditor’s opinion on whether the financial statements are free from material misstatement 
 and are presented fairly in accordance with the applicable financial reporting framework.\n\nIn addition to external audits by firms like Ernst & Young, 
 Elastic may also be subject to internal audits. Internal audits are performed by the company’s own internal auditors to evaluate the effectiveness of internal 
 controls, risk management, and governance processes.\n\nOverall, the auditing process plays a crucial role in maintaining the transparency and reliability of 
 Elastic\'s financial information, providing confidence to investors, regulators, and other stakeholders.'

これはかなり信憑性があり、インデックスを作成したい種類のドキュメントに最適な候補のように見えます。これを埋め込み、ハイブリッド検索に使用します。

トップに戻る

ハイブリッド検索

これが私たちの検索ロジックの中核です。語彙検索コンポーネントは、生成された OR 句の文字列になります。高密度ベクトル コンポーネントには、HyDE ドキュメント (検索ベクトルとも呼ばれます) が埋め込まれます。KNN を使用して、検索ベクトルに最も近い候補ドキュメントをいくつか効率的に識別します。デフォルトでは、語彙検索コンポーネントをTF-IDF と BM25 によるスコアリングと呼びます。最後に、語彙スコアと密なベクトルスコアは、 Wang らが推奨する 30/70 比率を使用して結合されます。

def hybrid_vector_search(self, index_name: str, query_text: str, query_vector: List[float], 
                         text_fields: List[str], vector_field: str, 
                         num_candidates: int = 100, num_results: int = 10) -> Dict:
    """
    Perform a hybrid search combining text-based and vector-based similarity.

    Args:
        index_name (str): The name of the Elasticsearch index to search.
        query_text (str): The text query string, which may contain 'OR' separated terms.
        query_vector (List[float]): The query vector for semantic similarity search.
        text_fields (List[str]): List of text fields to search in the index.
        vector_field (str): The name of the field containing document vectors.
        num_candidates (int): Number of candidates to consider in the initial KNN search.
        num_results (int): Number of final results to return.

    Returns:
        Dict: A tuple containing the Elasticsearch response and the search body used.
    """
    try:
        # Parse the query_text into a list of individual search terms
        # This splits terms separated by 'OR' and removes any leading/trailing whitespace
        query_terms = self.parse_or_query(query_text)

        # Construct the search body for Elasticsearch
        search_body = {
            # KNN search component for vector similarity
            "knn": {
                "field": vector_field,  # The field containing document vectors
                "query_vector": query_vector,  # The query vector to compare against
                "k": num_candidates,  # Number of nearest neighbors to retrieve
                "num_candidates": num_candidates  # Number of candidates to consider in the KNN search
            },
            "query": {
                "bool": {
                    # The 'must' clause ensures that matching documents must satisfy this condition
                    # Documents that don't match this clause are excluded from the results
                    "must": [
                        {
                            # Multi-match query to search across multiple text fields
                            "multi_match": {
                                "query": " ".join(query_terms),  # Join all query terms into a single space-separated string
                                "fields": text_fields,  # List of fields to search in
                                "type": "best_fields",  # Use the best matching field for scoring
                                "operator": "or"  # Match any of the terms (equivalent to the original OR query)
                            }
                        }
                    ],
                    # The 'should' clause boosts relevance but doesn't exclude documents
                    # It's used here to combine vector similarity with text relevance
                    "should": [
                        {
                            # Custom scoring using a script to combine vector and text scores
                            "script_score": {
                                "query": {"match_all": {}},  # Apply this scoring to all documents that matched the 'must' clause
                                "script": {
                                    # Script to combine vector similarity and text relevance
                                    "source": """
                                    # Calculate vector similarity (cosine similarity + 1)
                                    # Adding 1 ensures the score is always positive
                                    double vector_score = cosineSimilarity(params.query_vector, params.vector_field) + 1.0;
                                    # Get the text-based relevance score from the multi_match query
                                    double text_score = _score;
                                    # Combine scores: 70% vector similarity, 30% text relevance
                                    # This weighting can be adjusted based on the importance of semantic vs keyword matching
                                    return 0.7 * vector_score + 0.3 * text_score;
                                    """,
                                    # Parameters passed to the script
                                    "params": {
                                        "query_vector": query_vector,  # Query vector for similarity calculation
                                        "vector_field": vector_field  # Field containing document vectors
                                    }
                                }
                            }
                        }
                    ]
                }
            }
        }

        # Execute the search request against the Elasticsearch index
        response = self.conn.search(index=index_name, body=search_body, size=num_results)
        # Log the successful execution of the search for monitoring and debugging
        logger.info(f"Hybrid search executed on index: {index_name} with text query: {query_text}")
        # Return both the response and the search body (useful for debugging and result analysis)
        return response, search_body
    except Exception as e:
        # Log any errors that occur during the search process
        logger.error(f"Error executing hybrid search on index: {index_name}. Error: {e}")
        # Re-raise the exception for further handling in the calling code
        raise e

最後に、RAG 関数を組み立てることができます。クエリから回答までの RAG の流れは次のようになります。

  1. クエリを OR 句に変換します。

  2. HyDE ドキュメントを生成して埋め込みます。

  3. 両方をハイブリッド検索への入力として渡します。

  4. 上位 n 件の結果を取得し、最も関連性の高いスコアが LLM のコンテキスト メモリ内で「最新」になるように結果を逆にします (逆パッキング)。逆パッキングの例: クエリ:「Elasticsearch クエリ最適化手法」取得されたドキュメント (関連性の高い順): LLM コンテキストの順序を逆にする: 順序を逆にすることで、最も関連性の高い情報 (1) がコンテキストの最後に表示され、回答生成中に LLM からより多くの注目を受ける可能性が高くなります。

    1. 「ブールクエリを使用して、複数の検索条件を効率的に組み合わせます。」

    2. 「クエリの応答時間を改善するためのキャッシュ戦略を実装します。」

    3. 「インデックス マッピングを最適化して、検索パフォーマンスを高速化します。」

    4. 「インデックス マッピングを最適化して、検索パフォーマンスを高速化します。」

    5. 「クエリの応答時間を改善するためのキャッシュ戦略を実装します。」

    6. 「ブールクエリを使用して、複数の検索条件を効率的に組み合わせます。」

  5. 生成のためにコンテキストを LLM に渡します。

def get_context(index_name, 
                match_query, 
                text_query, 
                fields, 
                num_candidates=100, 
                num_results=20, 
                text_fields=["original_text", 'keyphrases', 'potential_questions', 'entities'], 
                embedding_field="primary_embedding"):

    embedding=embedder.get_embeddings_from_text(text_query)

    results, search_body = es_query_maker.hybrid_vector_search(
        index_name=index_name,
        query_text=match_query,
        query_vector=embedding[0][0],
        text_fields=text_fields,
        vector_field=embedding_field,
        num_candidates=num_candidates,
        num_results=num_results
    )

    # Concatenates the text in each 'field' key of the search result objects into a single block of text.
    context_docs=['\n\n'.join([field+":\n\n"+j['_source'][field] for field in fields]) for j in results['hits']['hits']]

    # Reverse Packing to ensure that the highest ranking document is seen first by the LLM.
    context_docs.reverse()
    return context_docs, search_body

def retrieval_augmented_generation(query_text):
    match_query= gpt4o.generate_query(query_text)
    fields=['original_text']

    hyde_document=gpt4o.generate_HyDE(query_text)

    context, search_body=get_context(index_name, match_query, hyde_document, fields)

    answer= gpt4o.basic_qa(query=query_text, context=context)
    return answer, match_query, hyde_document, context, search_body

クエリを実行して回答を取得してみましょう。

According to the context, Elastic N.V. is audited by an independent registered public accounting firm, PricewaterhouseCoopers (PwC). 
This information is found in the section titled "report of independent registered public accounting firm," which states:

"We have audited the accompanying consolidated balance sheets of Elastic N.V. [...] / s / pricewaterhouseco."

ニース。そうです。

トップに戻る

実験

今答えなければならない重要な質問があります。これらの実装に多大な労力と追加の複雑さを投資することで、何が得られましたか?

少し比較してみましょう。私たちが実装した RAG パイプラインと、私たちが行った機能強化のないベースライン ハイブリッド検索を比較したものです。小規模な一連のテストを実行して、大きな違いが見られるか確認します。ここで実装した RAG を AdvancedRAG と呼び、基本パイプラインを SimpleRAG と呼びます。

シンプルなRAGパイプライン

余計な機能のないシンプルなRAGパイプライン

結果の要約

この表は、両方の RAG パイプラインの 5 つのテストの結果をまとめたものです。回答の詳細と品質に基づいて各方法の相対的な優位性を判断しましたが、これは完全に主観的な判断です。実際の回答はこの表の下に再現されていますので、ご参照ください。それでは、彼らの成果を見てみましょう!

SimpleRAG は質問 1 と 5 に答えることができませんでした。AdvancedRAG は質問 2、3、4 についても非常に詳しく説明しました。詳細度が増したことにより、AdvancedRAG の回答の質が優れていると判断しました。

テスト

質問

高度なRAGパフォーマンス

SimpleRAG パフォーマンス

AdvancedRAG レイテンシー

SimpleRAG レイテンシ

勝者

1

Elastic を監査するのは誰ですか?

監査人として PwC を正しく特定しました。

監査人を識別できませんでした。

11.6秒

4.4秒

アドバンスドRAG

2

2023年の総収益はいくらでしたか?

正しい収益数値を提供しました。前年度の収益に関する追加のコンテキストを含めました。

正しい収益数値を提供しました。

13.3秒

2.8秒

アドバンスドRAG

3

成長は主にどの製品に依存しますか?いくら?

Elastic Cloud が主要な推進力であることを正しく認識しました。全体的な収益コンテキストとより詳しい詳細が含まれています。

Elastic Cloud が主要な推進力であることを正しく認識しました。

14.1秒

12.8秒

アドバンスドRAG

4

従業員福利厚生プランの説明

退職金制度、健康プログラム、その他の福利厚生について包括的に説明しました。異なる年ごとの具体的な寄付金額が含まれています。

報酬、退職金制度、職場環境、Elastic Cares プログラムなどの福利厚生の概要をわかりやすく説明しました。

26.6秒

11.6秒

アドバンスドRAG

5

Elastic が買収した企業はどれですか?

レポートに記載されている最近の買収 (CmdWatch、Build Security、Optimyze) を正しくリストしました。いくつかの取得日と購入価格を提供しました。

提供されたコンテキストから関連情報を取得できませんでした。

11.9秒

2.7秒

アドバンスドRAG

テスト 1: Elastic を監査するのは誰ですか?

アドバンスドRAG

According to the context, Elastic N.V. is audited by an independent 
registered public accounting firm, PricewaterhouseCoopers (PwC). 
This information is found in the section titled "report of 
independent registered public accounting firm," which states:
"We have audited the accompanying consolidated balance sheets 
of Elastic N.V. [...] / s / pricewaterhouseco."

シンプルラグ

According to the provided context, no specific auditing firm 
or company is mentioned as the auditor for Elastic. 
The context provided talks about various features, strengths, 
deployment options, and other details related to Elastic and 
its operations but does not specify which auditing firm is 
responsible for auditing Elastic's financial statements or 
internal controls.

要約: SimpleRAGはPWCを監査人として特定しなかった

そうですね、それは実はかなり驚きました。これは SimpleRAG 側の検索失敗のようです。監査に関連する文書は取得されませんでした。次のテストでは難易度を少し下げてみましょう。

テスト2:2023年の総収入

アドバンスドRAG

### Total Revenue for 2023

According to the provided context, the total revenue for the 
year ended April 30, 2023, was **$1,068,989,000**. This 
information can be found several times in the provided text. 
Specifically, one part states:

"The following table sets forth our results of operations 
for the periods presented in dollars and as a percentage of 
our total revenue. ... year ended April 30, 2023, ... 
total revenue 1,068,989".

Additionally, it is mentioned here as well:

"For the years ended April 30, 2023, 2022, and 2021, 
representing year-over-year growth of 24% for the year 
ended April 30, 2023... total revenue $1,068,989".

Therefore, the total revenue for 2023 is $1.069 billion.

シンプルラグ

According to the context provided, the total revenue for the fiscal year ended April 30, 2023, is:

$1,068,989,000 (or approximately $1.1 billion).

要約: 両RAGとも正解: 2023年の総収益は1,068,989,000ドル

二人ともここにいました。AdvancedRAG がより広範囲の文書を入手したように思われますか?確かに、答えはより詳細で、前年からの情報が組み込まれています。私たちが行った機能強化を考えると、それは予想されることですが、判断するには時期尚早です。

難易度を上げてみましょう。

テスト 3: 成長は主にどの製品に依存しますか?いくら?

アドバンスドRAG

### Product Growth Primarily Depends On:
According to the context, "our revenue is derived primarily from 
subscriptions of search, observability and security built into 
the elastic stack." The document mentions various strategies and 
factors contributing to the company’s growth which include investment 
in "elastic cloud," "elastic stack," and the conversion of free 
users to paid subscribers.

### Quantitative Data:
- **Revenue**: The document states, "Our total revenue was $1.1 billion, 
$862.4 million, and $608.5 million for the years ended April 30, 2023, 
2022, and 2021, respectively."
- **Subscription Revenue**: "Subscriptions accounted for 92%, 93%, 
and 93% of our total revenue for the years ended April 30, 2023, 
2022, and 2021, respectively."
- **Elastic Cloud Contribution**: "For the years ended April 30, 2023, 
2022, and 2021, Elastic Cloud contributed 40%, 35%, and 27% of our 
total revenue, respectively."
- **Customer Growth**: The number of customers increased from 
"over 15,000 as of April 30, 2021," to "approximately 20,200 as of 
April 30, 2023."

### Summary:
Product growth for the company primarily depends on the "Elastic Stack" 
(which includes search, observability, and security solutions) and 
particularly the "Elastic Cloud." The Elastic Cloud's growing contribution 
to revenue highlights its significance, which grew from 27% in 2021 to 40% in 2023.

シンプルラグ

According to the provided context, growth primarily depends on **Elastic Cloud**, 
which is described as the company's "family of cloud-based offerings." 
The context also emphasizes the significance of Elastic Cloud in achieving 
the company's long-term growth potential and its role in increasing subscription revenue.

From the context:

- "Increasing adoption of Elastic Cloud... is an important growth opportunity 
for our business. Organizations are increasingly looking for hosted 
deployment alternatives with reduced administrative burdens."
- "We believe that offering Elastic Cloud is important for achieving 
our long-term growth potential, and we expect Elastic Cloud’s contribution 
to our subscription revenue to continue to increase."

In terms of the contribution to total revenue, here are the specific figures provided:

- Elastic Cloud contributed 40% of the total revenue for the year ended April 30, 2023.
- Elastic Cloud contributed 35% of the total revenue for the year ended April 30, 2022.
- Elastic Cloud contributed 27% of the total revenue for the year ended April 30, 2021.

This progression shows a clear upward trend in the importance and 
contribution of Elastic Cloud to the company's overall revenue.

概要: 両方の RAG は、Elastic Cloud を主要な成長原動力として正しく認識しました。ただし、AdvancedRAG では、サブスクリプション収益と顧客の増加を考慮したより詳細な情報が含まれており、Elastic の他の製品についても明示的に言及されています。

テスト4: 従業員福利厚生制度の説明

アドバンスドRAG

### Employee Benefit Plan Overview

The provided context outlines various elements of the employee benefit plan at 
Elastic, often referred to as "Elasticians." Here are the key components 
described in the texts:

1. **401(k) Plan**:
   - **Coverage**: The 401(k) plan is available to substantially all U.S. 
   employees who meet minimum age and service requirements.
   - **Contributions**: Elastic makes contributions to the 401(k) plan up to 
   6% of the participating employee’s W-2 earnings and wages.
   - **Expenses**: For the fiscal years ended April 30, Elastic recorded 
   expenses of $17.9 million (2023), $15.2 million (2022), and $11.4 million (2021) 
   related to the 401(k) plan.
   - **Defined-Contribution Plans in Other Countries**: Elastic has 
   defined-contribution plans in various other countries and recorded respective 
   expenses of $9.4 million (2023), $7.2 million (2022), and $5.1 million (2021).

2. **Stock-Based Compensation**:
   - **Types of Awards**: Stock options, restricted stock units (RSUs), 
   and shares under the Employee Stock Purchase Plan (ESPP).
   - **Fair Value Measurement**: Fair value of these stock awards is 
   measured using models like Black-Scholes.
   - **Employee Stock Purchase Plan (2022 ESPP)**: 
     - Started in 2022, it allows employees to acquire ordinary 
     shares at a discount (85% of the market value at the beginning 
     or end of the offering period).
     - Offering periods are approximately six months long.

3. **Total Rewards Compensation**:
   - **Components**: Includes cash compensation as well as equity awards, 
   reflecting a comprehensive interest in the well-being of the employees.
   - **Programs**: Market competitive medical and dental programs, 
   mental health, and holistic well-being programs.
   - **Paid Time Off**: Features 16 weeks of paid leave for new 
   parents and life-planning benefits.

4. **Retirement and Income Protection Plans**:
   - **401(k) Match**: Elastic provides a dollar-for-dollar 
   match up to 6% of eligible earnings up to a plan-limit 
   maximum for U.S.-based employees.
   - **Similar Plans Outside the U.S.**: Competitive retirement 
   plans available for employees based outside the United States.

5. **Flexible Work Environment**: 
   - **Distributed Workforce**: Elastic operates with a global 
   distributed workforce model, allowing employees to work remotely 
   and providing a broad candidate pool.
   
6. **Learning and Development**:
   - **Programs**: Access to on-demand video-based learning, 
   leadership development programs, and other specific training 
   to develop managers and leaders.

7. **Employee Engagement and Surveys**:
   - **Mechanisms**: Annual employee engagement survey and 
   mid-year pulse survey.
   - **Objectives**: To monitor morale, develop action plans, 
   and maintain high engagement scores.

8. **Onboarding Program**:
   - **X-School**: An extensive new-hire orientation program to 
   help new employees meet peers and learn about the company's 
   products and solutions.

In summary, Elastic's employee benefit plan encompasses a broad 
spectrum of financial, health, well-being, and professional development 
benefits designed to support and enhance the lives of its employees. 
The plan is both competitive and comprehensive, aiming to attract,
retain, and engage its global workforce.

シンプルラグ

The employee benefit plan at the Company includes several key 
components aimed at enhancing the overall well-being and 
professional development of employees, referred to as "Elasticians." 

1. **Compensation and Benefits:**
   - The Company provides market-competitive compensation 
   packages which typically include cash compensation and equity awards.
   - Comprehensive medical and dental programs are offered, 
   emphasizing mental health and holistic well-being.
   - Paid time off programs feature:
     - 16 weeks of paid leave for new parents.
     - Life-planning benefits.
     - Travel reimbursements for certain healthcare services.

2. **Retirement and Income Protection Plans:**
   - In the United States, employees are eligible for a 401k 
   plan with a dollar-for-dollar match by the Company up to 6% 
   of eligible earnings, subject to a plan limit.
   - Similar competitive retirement and income protection plans 
   are available for employees outside the United States.

3. **Work Environment:**
   - The Company offers a flexible work environment, allowing most 
   employees to work from anywhere as often as they would like.
   - Physical offices around the world are available for employees 
   who prefer to work on-site or need a space for face-to-face interactions.

4. **Community Involvement:**
   - The Elastic Cares Program supports charitable organizations 
   that matter to employees on both local and global levels.
   - The program includes:
     - Donation matching.
     - Providing the Company's technology for free to certain 
     nonprofit organizations.
     - Volunteer time off initiative.

概要: AdvancedRAG では、米国に拠点を置く従業員向けの 401K プランや、米国外の定義拠出金プランについてさらに詳しく取り上げています。また、健康と幸福の計画についても言及していますが、SimpleRAG が言及している Elastic Cares プログラムについては触れられていません。

テスト 5: Elastic が買収した企業はどれですか?

アドバンスドRAG

Elastic acquired several companies over the years to enhance its 
technology and market presence. According to the provided context, 
the specific acquisitions include:

1. **CmdWatch Security Inc.**: Acquired on September 17, 2021. 
The total purchase consideration was $77.8 million.
2. **Build Security Ltd.**: Acquired on September 2, 2021. The 
combined purchase price for Build Security Ltd. and another acquisition was $57.2 million.
3. **Optimyze Cloud Inc.**: Acquired on November 1, 2021. Part 
of the combined purchase price mentioned above with Build Security Ltd.
4. **Endgame, Inc.**: Although the context mentions an amended 
and restated stock incentive plan, it indicates that Endgame, Inc. was 
associated with Elastic, suggesting it could have been acquired at some point.

These acquisitions are part of Elastic's strategy to 
enhance the technology underlying its security and 
observability offerings.

シンプルラグ

The provided context does not specify any companies that Elastic has acquired. 
Therefore, based on the context, there is no information available about the companies acquired by Elastic.

概要: SimpleRAG は買収に関する関連情報を取得せず、回答に失敗しました。AdvancedRAG は、レポートに記載されている主要な買収である CmdWatch、Build Security、Optimyze を正しくリストしています。

トップに戻る

まとめ

私たちのテストによると、私たちの高度な技術により、提示される情報の範囲と深さが拡大し、RAG 回答の品質が向上する可能性があるようです。

さらに、 Which companies did Elastic acquire?Who audits Elasticなどのあいまいな表現の質問に対して、AdvancedRAG では正しく回答されましたが、SimpleRAG では正しく回答されなかったため、信頼性が向上する可能性があります。

ただし、5 件中 3 件では、ハイブリッド検索のみを組み込んだ基本的な RAG パイプラインで、重要な情報のほとんどを捉えた回答を生成できたという点に留意する価値があります。

データ準備フェーズとクエリフェーズに LLM が組み込まれているため、AdvancedRAG のレイテンシは通常、SimpleRAG の 2 ~ 5 倍になることに注意してください。これは大きなコストであるため、AdvancedRAG は、応答品質がレイテンシーよりも優先される状況にのみ適している可能性があります。

データ準備段階で Claude Haiku や GPT-4o-mini などの小型で安価な LLM を使用すると、大きなレイテンシ コストを軽減できます。回答生成用の高度なモデルを保存します。

これは Wang らの研究結果と一致しています。結果が示すように、行われた改善は比較的漸進的です。つまり、シンプルなベースライン RAG を使用すると、安価で高速でありながら、適切な最終製品にほぼ到達できます。私にとっては、それは興味深い結論です。速度と効率が重要となるユースケースでは、SimpleRAG が賢明な選択です。パフォーマンスを最大限に引き出す必要があるユースケースでは、AdvancedRAG に組み込まれたテクニックが解決策となる可能性があります。

王パイプライン

Wang らによる研究の結果は、高度な技術の使用により、一貫性のある漸進的な改善がもたらされることを明らかにしました。

トップに戻る

付記

プロンプト

RAG質問回答プロンプト

クエリとコンテキストに基づいて LLM に回答を生成させるためのプロンプト。

BASIC_RAG_PROMPT = '''
You are an AI assistant tasked with answering questions based primarily on the provided context, while also drawing on your own knowledge when appropriate. Your role is to accurately and comprehensively respond to queries, prioritizing the information given in the context but supplementing it with your own understanding when beneficial. Follow these guidelines:

1. Carefully read and analyze the entire context provided.
2. Primarily focus on the information present in the context to formulate your answer.
3. If the context doesn't contain sufficient information to fully answer the query, state this clearly and then supplement with your own knowledge if possible.
4. Use your own knowledge to provide additional context, explanations, or examples that enhance the answer.
5. Clearly distinguish between information from the provided context and your own knowledge. Use phrases like "According to the context..." or "The provided information states..." for context-based information, and "Based on my knowledge..." or "Drawing from my understanding..." for your own knowledge.
6. Provide comprehensive answers that address the query specifically, balancing conciseness with thoroughness.
7. When using information from the context, cite or quote relevant parts using quotation marks.
8. Maintain objectivity and clearly identify any opinions or interpretations as such.
9. If the context contains conflicting information, acknowledge this and use your knowledge to provide clarity if possible.
10. Make reasonable inferences based on the context and your knowledge, but clearly identify these as inferences.
11. If asked about the source of information, distinguish between the provided context and your own knowledge base.
12. If the query is ambiguous, ask for clarification before attempting to answer.
13. Use your judgment to determine when additional information from your knowledge base would be helpful or necessary to provide a complete and accurate answer.

Remember, your goal is to provide accurate, context-based responses, supplemented by your own knowledge when it adds value to the answer. Always prioritize the provided context, but don't hesitate to enhance it with your broader understanding when appropriate. Clearly differentiate between the two sources of information in your response.

Context:
[The concatenated documents will be inserted here]

Query:
[The user's question will be inserted here]

Please provide your answer based on the above guidelines, the given context, and your own knowledge where appropriate, clearly distinguishing between the two:
'''

弾性クエリジェネレータプロンプト

同義語を使用してクエリを拡充し、OR 形式に変換するように要求します。

ELASTIC_SEARCH_QUERY_GENERATOR_PROMPT = '''
You are an AI assistant specialized in generating Elasticsearch query strings. Your task is to create the most effective query string for the given user question. This query string will be used to search for relevant documents in an Elasticsearch index.

Guidelines:
1. Analyze the user's question carefully.
2. Generate ONLY a query string suitable for Elasticsearch's match query.
3. Focus on key terms and concepts from the question.
4. Include synonyms or related terms that might be in relevant documents.
5. Use simple Elasticsearch query string syntax if helpful (e.g., OR, AND).
6. Do not use advanced Elasticsearch features or syntax.
7. Do not include any explanations, comments, or additional text.
8. Provide only the query string, nothing else.

For the question "What is Clickthrough Data?", we would expect a response like:
clickthrough data OR click-through data OR click through rate OR CTR OR user clicks OR ad clicks OR search engine results OR web analytics

AND operator is not allowed. Use only OR.

User Question:
[The user's question will be inserted here]

Generate the Elasticsearch query string:
'''

潜在的な質問ジェネレータプロンプト

潜在的な質問の生成を促し、ドキュメントのメタデータを充実させます。

RAG_QUESTION_GENERATOR_PROMPT = '''
You are an AI assistant specialized in generating questions for Retrieval-Augmented Generation (RAG) systems. Your task is to analyze a given document and create 10 diverse questions that would effectively test a RAG system's ability to retrieve and synthesize information from this document.

Guidelines:
1. Thoroughly analyze the entire document.
2. Generate exactly 10 questions that cover various aspects and levels of complexity within the document's content.
3. Create questions that specifically target:
   a. Key facts and information
   b. Main concepts and ideas
   c. Relationships between different parts of the content
   d. Potential applications or implications of the information
   e. Comparisons or contrasts within the document
4. Ensure questions require answers of varying lengths and complexity, from simple retrieval to more complex synthesis.
5. Include questions that might require combining information from different parts of the document.
6. Frame questions to test both literal comprehension and inferential understanding.
7. Avoid yes/no questions; focus on open-ended questions that promote comprehensive answers.
8. Consider including questions that might require additional context or knowledge to fully answer, to test the RAG system's ability to combine retrieved information with broader knowledge.
9. Number the questions from 1 to 10.
10. Output only the ten questions, without any additional text, explanations, or answers.

Document:
[The document content will be inserted here]

Generate 10 questions optimized for testing a RAG system based on this document:
'''

HyDEジェネレータプロンプト

HyDEを使用して仮想文書を生成するためのプロンプト

HYDE_DOCUMENT_GENERATOR_PROMPT = '''
You are an AI assistant specialized in generating hypothetical documents based on user queries. Your task is to create a detailed, factual document that would likely contain the answer to the user's question. This hypothetical document will be used to enhance the retrieval process in a Retrieval-Augmented Generation (RAG) system.

Guidelines:
1. Carefully analyze the user's query to understand the topic and the type of information being sought.
2. Generate a hypothetical document that:
   a. Is directly relevant to the query
   b. Contains factual information that would answer the query
   c. Includes additional context and related information
   d. Uses a formal, informative tone similar to an encyclopedia or textbook entry
3. Structure the document with clear paragraphs, covering different aspects of the topic.
4. Include specific details, examples, or data points that would be relevant to the query.
5. Aim for a document length of 200-300 words.
6. Do not use citations or references, as this is a hypothetical document.
7. Avoid using phrases like "In this document" or "This text discusses" - write as if it's a real, standalone document.
8. Do not mention or refer to the original query in the generated document.
9. Ensure the content is factual and objective, avoiding opinions or speculative information.
10. Output only the generated document, without any additional explanations or meta-text.

User Question:
[The user's question will be inserted here]

Generate a hypothetical document that would likely contain the answer to this query:
'''

ハイブリッド検索クエリのサンプル

{'knn': {'field': 'primary_embedding',
  'query_vector': [0.4265527129173279,
   -0.1712949573993683,
   -0.042020395398139954,
   ...],
  'k': 100,
  'num_candidates': 100},
 'query': {'bool': {'must': [{'multi_match': {'query': 'audits Elastic Elastic auditing Elastic audit process Elastic compliance Elastic security audit Elasticsearch auditing Elasticsearch compliance Elasticsearch security audit',
      'fields': ['original_text',
       'keyphrases',
       'potential_questions',
       'entities'],
      'type': 'best_fields',
      'operator': 'or'}}],
   'should': [{'script_score': {'query': {'match_all': {}},
      'script': {'source': '\n                                        double vector_score = cosineSimilarity(params.query_vector, params.vector_field) + 1.0;\n                                        double text_score = _score;\n                                        return 0.7 * vector_score + 0.3 * text_score;\n                                        ',
       'params': {'query_vector': [0.4265527129173279,
         -0.1712949573993683,
         -0.042020395398139954,
        ...],
        'vector_field': 'primary_embedding'}}}}]}},
 'size': 10}

関連記事

LINQ to Elasticsearch ES|QL:C#を記述してElasticsearchをクエリ

Florian Bernd

Elasticsearch の NLP とベクトル検索によるチャットボット機能の強化

Priscilla Parodi

OpenSearchとElasticsearchの違い:ベクトル検索のパフォーマンス比較

Ugo Sangiorgi

AI盗作:Elasticsearchによる盗作検出

Priscilla Parodi

ElasticsearchにおけるHNSWの適応的早期終了

Tommaso Teofili

最先端の検索体験を構築する準備はできましたか?

十分に高度な検索は 1 人の努力だけでは実現できません。Elasticsearch は、データ サイエンティスト、ML オペレーター、エンジニアなど、あなたと同じように検索に情熱を傾ける多くの人々によって支えられています。ぜひつながり、協力して、希望する結果が得られる魔法の検索エクスペリエンスを構築しましょう。

はじめましょう