Tencent Cloud Big Data Elasticsearch 8.8.1 を使用して、NLP + ベクトル検索 + GAI を実現します。

ガイド

Tencent Cloud Big Data Elasticsearch Service は最近、バージョン 8.8.1 をリリースしました。このバージョンのコア機能は、AI 革命のための高度な検索機能を提供することです。このリリースには、検索と分析に新しい最先端のエクスペリエンスをもたらす強力な AI 強化検索エンジンである Elasticsearch Relevance Engine™ (ESRE​​™) が搭載されています。

ベクトル ライブラリがあちこちで開花していると誰もが感じるでしょうが、今回のリリースは「そのうちの 1 つ」にすぎません。ただし、重要なポイントを強調すると、より明確な理解と位置付けが得られるかもしれません。

これは現在、自然言語処理、ベクトル化、ベクトル検索を提供し、大規模モデルと統合できる、中国のパブリック クラウド上で唯一のエンドツーエンドの検索および分析プラットフォームです。

49f33c3e058a8eecaf24f0890cc2869d.png

図1

1. すべてのベクトル ライブラリが単一のインターフェイス呼び出しでマルチウェイ リコール混合ソートを実現できるわけではありません。

2. すべての検索エンジンがベクトル検索の実行後に集計操作を実行できるわけではありません。

6b54790c9c7a3837e9132d173dcef004.png

図Ⅱ

もちろん、この記事の焦点は導入ではなく、応用と実践です。次に、この記事では、Tencent Cloud 上に Elasticsearch 8.8.1 クラスターを作成し、NLP モデルをデプロイして使用し、ベクトル検索に基づいて大規模モデルと組み合わせる方法を示します。

1. Elasticsearch 8.8.1 クラスターを作成する

ビルドのプロセスは非常に簡単で、以前と同様に、対応するバージョンを選択するだけです。ここで強調する必要があるのは、さまざまな NLP モデルと埋め込みモデルをクラスターにデプロイする必要があるため、モデルのデプロイメントにできるだけ十分なメモリを選択する必要があるということです。

cc04f18d922f6e9b504215c657a6a76b.gif

図 3

18718a876129f7c02f9929fbe7b7fa0f.gif

図4

2. NLP モデルをデプロイする

ベクトル検索を実行する場合でも、固有表現認識などの NLP タスクを実行してテキストから情報を抽出する場合でも、推論タスクを実行する必要があります。Tencent Cloud Elasticsearch 8.8.1の最大の違いは、データ処理や推論のための機械学習環境を構築する必要がなく、パイプラインに異なるプロセッサを統合することでElasticsearch上で直接データを柔軟に処理できることです。

3d72918d8561c545e4f631922b7e741f.png

図 5. 取り込みパイプラインでの処理と推論の実行

また、クエリと書き込まれたデータが同じモデルを使用してデータを処理するようにします。モデルの使用、更新、保守のコストを簡素化するため。

926d68d11981c6da411c7f7265614266.png

図6

そして導入方法は非常に簡単です。モデルをアップロードしてデプロイするための eland というツールを提供します。

eland_import_hub_model --url https://es-7cu6zx9m.public.tencentelasticsearch.com:9200  --insecure -u elastic -p changeme --hub-model-id sentence-transformers/msmarco-MiniLM-L-12-v3 --task-type text_embedding --start --insecure

デプロイ時に、自分のパソコンで eland_import_hub_model を使用する場合 (huggingFace からモデルをダウンロードする場合はインターネット アクセスが必要なため)、Tencent Cloud Elasticsearch のパブリック ネットワーク アクセス インターフェイスを提供する必要があります。

14972b029b9fdee817dad7fb37b6e34e.png

図7

もちろん、Tencent Cloud で CVM を購入し、イントラネット アクセス アドレスを使用することもできます。

eland_import_hub_model --url https://172.27.0.11:9200  --insecure -u elastic -p changeme --hub-model-id canIjoin/datafun --task-type ner --start

ただし、場合によっては CVM 上で HuggingFace にアクセスできないか、アクセスがタイムアウトになり、モデルのアップロードとデプロイに失敗する可能性があることに注意してください。

制限されたインターネット アクセスと同様に、独自のモデルをトレーニングし、それを HuggingFace に公開したくない場合は、この記事「ローカル トランスフォーマー モデルを Elasticsearch にデプロイする方法」を参照して、ローカル NLP モデルをアップロードしてデプロイできます。

モデルのアップロードが正しく実行されると、次の出力が表示されます。

eland_import_hub_model --url https://es-7cu6zx9m.public.tencentelasticsearch.com:9200  --insecure -u elastic -p changeme  --hub-model-id distilbert-base-uncased-finetuned-sst-2-english --task-type text_classification --start --insecure
2023-07-13 10:06:23,354 WARNING : NOTE: Redirects are currently not supported in Windows or MacOs.
2023-07-13 10:06:24,358 INFO : Establishing connection to Elasticsearch
/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/elasticsearch/_sync/client/__init__.py:394: SecurityWarning: Connecting to 'https://es-7cu6zx9m.public.tencentelasticsearch.com:9200' using TLS with verify_certs=False is insecure
  _transport = transport_class(
/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/urllib3/connectionpool.py:1045: InsecureRequestWarning: Unverified HTTPS request is being made to host 'es-7cu6zx9m.public.tencentelasticsearch.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#ssl-warnings
  warnings.warn(
2023-07-13 10:06:24,535 INFO : Connected to cluster named 'es-7cu6zx9m' (version: 8.8.1)
2023-07-13 10:06:24,537 INFO : Loading HuggingFace transformer tokenizer and model 'distilbert-base-uncased-finetuned-sst-2-english'
Downloading pytorch_model.bin: 100%|████████████████████████████████████████████████████████████| 268M/268M [00:19<00:00, 13.6MB/s]
/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/transformers/models/distilbert/modeling_distilbert.py:223: TracerWarning: torch.tensor results are registered as constants in the trace. You can safely ignore this warning if you use this function to create tensors out of constant variables that would be the same every time you call this function. In any other case, this might cause the trace to be incorrect.
  mask, torch.tensor(torch.finfo(scores.dtype).min)
/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/urllib3/connectionpool.py:1045: InsecureRequestWarning: Unverified HTTPS request is being made to host 'es-7cu6zx9m.public.tencentelasticsearch.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#ssl-warnings
  warnings.warn(
2023-07-13 10:06:48,795 INFO : Creating model with id 'distilbert-base-uncased-finetuned-sst-2-english'
/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/urllib3/connectionpool.py:1045: InsecureRequestWarning: Unverified HTTPS request is being made to host 'es-7cu6zx9m.public.tencentelasticsearch.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#ssl-warnings
  warnings.warn(
2023-07-13 10:06:48,855 INFO : Uploading model definition
  0%|                                                                                                   | 0/64 [00:00<?, ? parts/s]/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/urllib3/connectionpool.py:1045: InsecureRequestWarning: Unverified HTTPS request is being made to host 'es-7cu6zx9m.public.tencentelasticsearch.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#ssl-warnings
  warnings.warn(
  2%|█                                                                                         | 1/64 [00:01<01:25,  1.36s/ parts]/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/urllib3/connectionpool.py:1045: InsecureRequestWarning: Unverified HTTPS request is being made to host 'es-7cu6zx9m.public.tencentelasticsearch.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#ssl-warnings
  warnings.warn(
  3%|██                                                                                        | 2/64 [00:01<00:53,  1.16 parts/s]/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/urllib3/connectionpool.py:1045: InsecureRequestWarning: Unverified HTTPS request is being made to host 'es-7cu6zx9m.public.tencentelasticsearch.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#ssl-warnings
...
100%|██████████████████████████████████████████████████████████████████████████████████████████| 64/64 [00:45<00:00,  1.42 parts/s]
2023-07-13 10:07:34,021 INFO : Uploading model vocabulary
/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/urllib3/connectionpool.py:1045: InsecureRequestWarning: Unverified HTTPS request is being made to host 'es-7cu6zx9m.public.tencentelasticsearch.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#ssl-warnings
  warnings.warn(
2023-07-13 10:07:34,110 INFO : Starting model deployment
/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/urllib3/connectionpool.py:1045: InsecureRequestWarning: Unverified HTTPS request is being made to host 'es-7cu6zx9m.public.tencentelasticsearch.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#ssl-warnings
  warnings.warn(
2023-07-13 10:07:41,163 INFO : Model successfully imported with id 'distilbert-base-uncased-finetuned-sst-2-english'

3. モデルの管理とテスト

モデルがアップロードされたら、Tencent Cloud Elasticsearch Service の Kibana インターフェイスでモデルを直接管理およびテストできます。

37c0968b2ecbd7d7e3c623557ea85725.gif

図8

4. アプリケーション内のElasticsearchによるNLP+Vector Search+GAIを実現

モデルのデプロイとデバッグが完了したら、この機能をアプリケーションに統合できます。たとえば、論文に質問応答システムを実装したい場合は、次の手順で実装できます。

6e637b844e6e533e6c4590cbb8b6f94d.png

図9

コアコードの一部は次のとおりです。

async def nlp_blog_search():
    # 判断模型是否在Elasticsaerch中加载
    global app_models
    is_model_up_and_running(INFER_MODEL_TEXT_EMBEDDINGS)
    is_model_up_and_running(INFER_MODEL_Q_AND_A)


    qa_model = True if app_models.get(
        INFER_MODEL_Q_AND_A) == 'started' else False
    index_name = INDEX_BLOG_SEARCH


    if not es.indices.exists(index=index_name):
        return render_template('nlp_blog_search.html', title='Blog search', te_model_up=False,
                               index_name=index_name, missing_index=True, qa_model_up=qa_model)


    if app_models.get(INFER_MODEL_TEXT_EMBEDDINGS) == 'started':
        form = SearchBlogsForm()


        # Check for method
        if request.method == 'POST':


            if form.validate_on_submit():
                if 'filter_by_author' in request.form:
                    form.searchboxAuthor.data = request.form['filter_by_author']


                if form.searchboxBlogWindow.data is None or len(form.searchboxBlogWindow.data) == 0:
                    # 对查询进行embedding转换
                    embeddings_response = infer_trained_model(
                        form.searchbox.data, INFER_MODEL_TEXT_EMBEDDINGS)
                    # 执行向量搜索()混合搜索、/混合搜索                     
                    search_response = knn_blogs_embeddings(embeddings_response['predicted_value'],
                                                           form.searchboxAuthor.data)
                    cfg = {
                        "question_answering": {
                            "question": form.searchbox.data,
                            "max_answer_length": 30
                        }
                    }


                    hits_with_answers = search_response['hits']['hits']
                    #使用QA模型做第一遍过滤
                    answers = executor.map(q_and_a, map(lambda hit: hit["_id"], hits_with_answers),
                                           map(lambda hit: form.searchbox.data, hits_with_answers),
                                           map(lambda hit: get_text(hit=hit), hits_with_answers))


                    best_answer = None
                    for i in range(0, len(hits_with_answers)):
                        hit_with_answer = hits_with_answers[i]


                        matched_answer = next(
                            (obj['result'] for obj in answers if obj["_id"] == hit_with_answer["_id"]), None)


                        if (matched_answer is not None):
                            hit_with_answer['answer'] = matched_answer
                            if (best_answer is None or (
                                    matched_answer is not None and 'prediction_probability' in matched_answer and
                                    matched_answer['prediction_probability'] > best_answer['prediction_probability'])):
                                best_answer = matched_answer


                            start_idx = matched_answer['start_offset']
                            end_idx = matched_answer['end_offset']


                            text = hits_with_answers[i]['fields']['body_content_window'][0]
                            text_with_highlighted_answer = Markup(''.join([text[0:start_idx - 1],
                                                                           "<b>", text[start_idx -
                                                                                       1:end_idx],
                                                                           "</b>", text[end_idx:]]))
                            hits_with_answers[i]['fields']['body_content_window'][0] = text_with_highlighted_answer


                    # 将结果交给大模型进行总结
                    messages = blogs_convert_es_response_to_messages(search_response,
                                                                            form.searchbox.data)
                    # Send a request to the OpenAI API
                    try:
                        response_ai = openai.ChatCompletion.create(
                            engine="gpt-35-turbo",
                            temperature=0,
                            messages=messages
                        )


                        answer_openai = response_ai["choices"][0]["message"]["content"]
                    except RateLimitError as e:
                        print(e.error.message)
                        answer_openai =  e.error.message
                    except APIConnectionError as e:
                        print(e.error.message)
                        answer_openai = e.error.message


                    return render_template('nlp_blog_search.html', title='Blog search', form=form,
                                           search_results=hits_with_answers,
                                           best_answer=best_answer, openai_answer=answer_openai,
                                           query=form.searchbox.data, te_model_up=True, qa_model_up=qa_model,
                                           missing_index=False)
                else:
                    search_response = q_and_a(
                        question=form.searchbox.data, full_text=form.searchboxBlogWindow.data)
                    return render_template('nlp_blog_search.html', title='Blog search', form=form,
                                           qa_results=search_response,
                                           query=form.searchbox.data, te_model_up=True, qa_model_up=qa_model,
                                           missing_index=False)
            else:
                return redirect(url_for('nlp_blog_search'))
        else:  # GET
            return render_template('nlp_blog_search.html', title='Blog Search', form=form, te_model_up=True,
                               qa_model_up=qa_model, missing_index=False)
    else:
        return render_template('nlp_blog_search.html', title='Blog search', te_model_up=False, qa_model_up=qa_model,
                               model_name=INFER_MODEL_TEXT_EMBEDDINGS, missing_index=False)

これらの統合により、次の効果が得られます。

058944f7265a7b2f5c5c76656bac9417.gif

図10

つまり、Tencent Cloud Elasticsearch 8.8.1 を通じて、Elasticsearch のインターフェイスを呼び出すだけでアプリケーションにベクトル検索を簡単に実装し、結果を QnA モデルに渡して重要なポイントをキャプチャできます。そして、その内容をさらに大きなモデルに与えて要約します。

V. まとめ

Tencent Cloud Big Data Elasticsearch Service によってリリースされた最新バージョン 8.8.1 では、高度な検索と AI 強化検索機能を提供する Elasticsearch Relevance Engine™ (ESRE​​™) が導入されています。このリリースでは、自然言語処理、ベクトル検索、および単一のエンドツーエンドの検索および分析プラットフォームでの大規模モデルとの統合がサポートされています。このサービスを使用すると、クラスターの作成、NLP モデルのデプロイ、検索および推論タスクの実行が簡単に行えます。Kibana インターフェイスでモデルを管理およびテストすることもできます。Tencent Cloud Elasticsearch を通じて、AI による高度な検索機能を実現し、AI テクノロジーをより有効に活用できます。急いで体験してください!

新しいカスタマー エクスペリエンス アクティビティ ゾーン

Elasticsearch Service の新規顧客限定の特典!

2コア 4G-20GB-SSD クラウド ハード ドライブ

初月体験は 10% 割引、早期導入価格はわずか 87 元です! クラウド上でスムーズにクラスタリングを体験し、ESサービスを簡単に始めましょう!

514f403d0863e45ee430487c48a999a2.png

推奨読書

c461a4aa641a5164f4a1221b1093daa1.jpeg

7dd078ccf6666f7a089b66e945a00708.jpeg

ee1c236f790a94de58f82c44ea977db1.jpeg

Tencent Cloud Big Data公式アカウントをフォローしてください

データの無限の可能性を探求しましょう

a86fa94b9728b3354f7efe2a2a7868a1.png

製品情報の詳細については、クリックして原文を読んでください。

↓↓↓

おすすめ

転載: blog.csdn.net/cloudbigdata/article/details/131843265