Sign In
Free Sign Up
  • English
  • Español
  • 简体中文
  • Deutsch
  • 日本語
Sign In
Free Sign Up
  • English
  • Español
  • 简体中文
  • Deutsch
  • 日本語

Claude 3とHugging Faceを使用して10分でRAGアプリケーションを構築する

AIの進歩の中で、RAG(Retrieval-Augmented Generation)アプリケーションは多様なセクターを変革する革新的なツールとして際立っています。これらのアプリケーションは、検索と生成モデルの組み合わせを活用して、さまざまなドメインの豊富な知識に瞬時にアクセスできるようにすることで、データ分析能力と予測機能を向上させ、企業に莫大な価値を提供します。

さまざまな業界の企業が、AIの可能性を高めるためにRAGに increasingly 頼っています。RAGアプリケーションにおける検索と生成のコンポーネントの融合は、広範な顧客データの分析を容易にし、パーソナライズされた推奨事項を推進する実用的な洞察を導き出します。このシナジーにより、企業は生成AI (opens new window)技術の力を幅広いアプリケーションで自信を持って活用することができます。さらに、RAGアプリケーションのアーキテクチャは、情報検索とテキスト生成 (opens new window)モデルを組み合わせ、ユーザーのクエリに効果的に対応するためのデータベースへのアクセスを可能にします。

埋め込み量子化 (opens new window)とリトリーバル拡張ファインチューニング(RAFT)といった技術を通じて大規模言語モデルを微調整することで、開発者はRAGアプリケーションの堅牢性と効率を向上させます (opens new window)

# ClaudeがRAGモデルをどのように強化するか

Anthropicが開発したClaude 3 (opens new window)は、精度とコンテキストの処理において新たな基準を設定する先進的なAIモデルファミリーです。Claude 3ファミリーには、Haiku、Sonnet、Opusの3つのモデルが含まれており、それぞれ異なるニーズに対応しています。これらのモデルは高い事実の正確性と長い会話の中でのコンテキストの維持能力で知られています。特に、Opusモデルは、卒業レベルの推論や基本的な数学テストなど、いくつかのベンチマークでGPT-4を上回っています。最大20万トークンのコンテキストウィンドウ (opens new window)を持つClaude 3は、競合他社よりも効果的に広範なテキスト入力を処理することができます。

LLMベンチマーク

性能に加えて、Claude 3モデルは倫理的なAIの使用と安全性を重視しています。これらのモデルはバイアスを減らし、ユーザーのプライバシーを保護し、複雑なプロンプトに対しても正確な応答を提供するように設計されています。これらのモデルはテキストとビジュアルの両方の入力をサポートしており、コンテンツの作成やデータ分析など、さまざまなアプリケーションに対応しています。強力なパートナーシップとさまざまなプラットフォームを通じてアクセスできるようになっているClaude 3モデルは、多くの分野でのイノベーションと効率を推進するために優れた位置にあります。

# RAGモデルにHugging Faceを選ぶ理由

Hugging Face (opens new window)は、事前学習済みモデル (opens new window)の広範なライブラリで知られる主要なプラットフォームであり、Retrieval-Augmented Generation (RAG) (opens new window)を含むさまざまな自然言語処理タスクに最適化されています。これらのモデルは密な検索、シーケンスからシーケンスへの生成、その他の高度なタスクをカバーしており、開発者が異なるRAG構成を簡単に設定し、実験することを可能にします。プラットフォームのユーザーフレンドリーなAPIと包括的なドキュメントは、統合と微調整のプロセスをさらに簡素化し、RAGモデルの初心者でも効果的なシステムを迅速に実装できるようにします。Hugging Faceのツール、例えばLangChainやRayを活用することで、開発者は大規模データと複雑なクエリを効率的に処理できるスケーラブルで高性能なRAGシステムを構築できます。

このブログでは、特にHugging Faceの埋め込みモデルの使用に焦点を当てます。Hugging Faceは、RAGシステムの初期ステップである関連ドキュメントの検索に重要な埋め込みモデルのさまざまな選択肢を提供しています。これらのモデルは、正確で効率的な情報検索に不可欠な高品質の埋め込みを生成するように設計されています。Hugging Faceの埋め込みモデルを使用することで、RAGシステムが与えられたクエリに対して最も関連性の高いコンテキストを取得することができるため、生成された応答の全体的な正確性とパフォーマンスが向上します。この選択により、Hugging Faceの提供する堅牢性と多様性を活用しながら、埋め込み生成の特定のニーズに合わせて実装を調整することができます。

Boost Your AI App Efficiency now
Sign up for free to benefit from 150+ QPS with 5,000,000 vectors
Free Trial
Explore our product

# Claude 3とHugging Faceの埋め込みを使用してRAGアプリケーションを構築する

それでは、Claude 3とHugging Faceの埋め込みモデルを使用してRAGアプリケーションを構築しましょう。環境の設定、ドキュメントの読み込み、埋め込みの作成、およびClaude 3モデルを使用して取得したドキュメントから回答を生成する手順を説明します。

# 環境の設定

まず、必要なライブラリをインストールする必要があります。以下の行のコメントを解除して実行し、必要なパッケージをインストールします。ライブラリがシステムにインストールされている場合は、このステップをスキップできます。

pip install langchain sentence-transformers anthropic

これにより、RAGシステムに必要なlangchainsentence-transformersanthropicライブラリがインストールされます。

# 環境変数の設定

次に、MyScaleとClaude 3 APIの接続のための環境変数を設定する必要があります。このRAGアプリケーションでは、ベクトルデータベースとしてMyScaleDB (opens new window)を使用します。MyScaleDBは高いパフォーマンス、スケーラビリティ、効率的なデータ検索機能を提供するため、このRAGアプリケーションに最適な選択肢となります。

import os
# ベクトルデータベースの接続を設定する
os.environ["MYSCALE_HOST"] = "your-host-name"
os.environ["MYSCALE_PORT"] = "443"
os.environ["MYSCALE_USERNAME"] = "your-user-name"
os.environ["MYSCALE_PASSWORD"] = "your-password-here"

# Claude 3のAPIキーを設定する
os.environ["ANTHROPIC_API_KEY"] = "your-claude-api-key-here"

このスクリプトは、MyScaleベクトルデータベースとClaude 3 APIに接続するための必要な環境変数を設定します。

注意:

MyScaleDBのアカウントをお持ちでない場合は、MyScaleのウェブサイト (opens new window)にアクセスして無料アカウントを作成し、クイックスタート (opens new window)ガイドに従ってください。 Claude 3 APIを使用するには、Claudeコンソール (opens new window)でアカウントを作成する必要があります。

# 必要なライブラリのインポート

次に、ドキュメントの読み込み、分割、埋め込み、およびClaude 3モデルとの対話に必要なライブラリをインポートします。

# ドキュメントを分割するためのライブラリ
from langchain.text_splitter import RecursiveCharacterTextSplitter
# ベクトルデータベースとしてMyScaleを使用するためのライブラリ
from langchain_community.vectorstores import MyScale
# 埋め込みにHugging Faceを使用するためのライブラリ
from langchain_huggingface import HuggingFaceEmbeddings
# Wikipediaのページを読み込むためのライブラリ
from langchain_community.document_loaders.wikipedia import WikipediaLoader

import anthropic

これらのライブラリは、ドキュメントの管理、埋め込みの作成、およびClaude 3モデルとの対話をサポートします。

# Claude 3クライアントの初期化

Claude 3 APIと通信するためのClaude 3クライアントを初期化します。

client = anthropic.Anthropic()

# ドキュメントの読み込み

この例では、WikipediaLoaderを使用してWikipediaからドキュメントを読み込みます。

loader = WikipediaLoader(query="Fifa")

# ドキュメントを読み込む
docs = loader.load()

これにより、Wikipediaから「Fifa」に関連するドキュメントが読み込まれます。

# ドキュメントの分割

読み込まれたドキュメントをRecursiveCharacterTextSplitterを使用して管理可能なチャンクに分割します。

character_splitter = RecursiveCharacterTextSplitter(
    chunk_size=1000,
    chunk_overlap=200
)
docs = character_splitter.split_documents(docs)

これにより、ドキュメントが1000文字のチャンクに分割され、オーバーラップが200文字になります。

# 埋め込みの作成

次に、Hugging Faceの埋め込みモデルを使用してドキュメントのチャンクに埋め込みを作成します。

embeddings = HuggingFaceEmbeddings(model_name="BAAI/bge-base-en-v1.5")
docsearch = MyScale(embedding_function=embeddings.embed_documents)
docsearch.add_documents(docs)

このステップでは、ドキュメントのチャンクに対して埋め込みを生成し、それらをMyScaleベクトルストアに追加します。

# ドキュメント検索のテスト

埋め込みとベクトルストアが正しく機能していることを確認するために、ドキュメント検索の機能をテストします。

query = "Who won fifa Fifa 2022?"
docs = docsearch.similarity_search(query, 3)
docs

これにより、クエリ「Who won Fifa 2022?」に対して類似性検索が実行され、最も関連性の高い上位3つのドキュメントが取得されます。以下のようなドキュメントが返されます。

[Document(page_content="The FIFA World Cup, often called the World Cup, is an international association football competition among the senior men's national teams of the members of the Fédération Internationale de Football Association (FIFA), the sport's global governing body. The tournament has been held every four years since the inaugural tournament in 1930, with the exception of 1942 and 1946 due to the Second World War. The reigning champions are Argentina, who won their third title at the 2022 tournament.\\nThe contest starts with the qualification phase, which takes place over the preceding three years to determine which teams qualify for the tournament phase. In the tournament phase, 32 teams compete for the title at venues within the host nation(s) over the course of about a month. The host nation(s) automatically qualify for the group stage of the tournament. The competition is scheduled to expand to 48 teams, starting with the 2026 tournament.", metadata={'source': '<https://en.wikipedia.org/wiki/FIFA_World_Cup>', 'summary': "The FIFA World Cup, often called the World Cup, is an international association football competition among the senior men's national teams of the members of the Fédération Internationale de Football Association (FIFA), the sport's global governing body. The tournament has been held every four years since the inaugural tournament in 1930, with the exception of 1942 and 1946 due to the Second World War. The reigning champions are Argentina, who won their third title at the 2022 tournament.\\nThe contest starts with the qualification phase, which takes place over the preceding three years to determine which teams qualify for the tournament phase. In the tournament phase, 32 teams compete for the title at venues within the host nation(s) over the course of about a month. The host nation(s) automatically qualify for the group stage of the tournament. The competition is scheduled to expand to 48 teams, starting with the 2026 tournament.\\nAs of the 2022 FIFA World Cup, 22 final tournaments have been held since the event's inception in 1930, and a total of 80 national teams have competed. The trophy has been won by eight national teams. With five wins, Brazil  is the only team to have played in every tournament. The other World Cup winners are Germany and Italy, with four titles each; Argentina, with three titles; France and inaugural winner Uruguay, each with two titles; and England and Spain, with one title each.\\nThe World Cup is the most prestigious association football tournament in the world, as well as the most widely viewed and followed single sporting event in the world. The viewership of the 2018 World Cup was estimated to be 3.57 billion, close to half of the global population, while the engagement with the 2022 World Cup was estimated to be 5 billion, with about 1.5 billion people watching the final match.\\nSeventeen countries have hosted the World Cup, most recently Qatar, who hosted the 2022 event. The 2026 tournament will be jointly hosted by Canada, the United States and Mexico, which will give Mexico the distinction of being the first country to host games in three World Cups.\\n\\n", 'title': 'FIFA World Cup'}),
 Document(page_content="The 2026 FIFA World Cup, marketed as FIFA World Cup 26, will be the 23rd FIFA World Cup, the quadrennial international men's soccer championship contested by the national teams of the member associations of FIFA. The tournament will take place from June 11 to July 19, 2026. It will be jointly hosted by 16 cities in three North American countries: Canada, Mexico, and the United States. The tournament will be the first hosted by three nations and the first North American World Cup since 1994. Argentina is the defending champion.", metadata={'source': '<https://en.wikipedia.org/wiki/2026_FIFA_World_Cup>', 'summary': "The 2026 FIFA World Cup, marketed as FIFA World Cup 26, will be the 23rd FIFA World Cup, the quadrennial international men's soccer championship contested by the national teams of the member associations of FIFA. The tournament will take place from June 11 to July 19, 2026. It will be jointly hosted by 16 cities in three North American countries: Canada, Mexico, and the United States. The tournament will be the first hosted by three nations and the first North American World Cup since 1994. Argentina is the defending champion.\\nThis tournament will be the first to include 48 teams, expanded from 32. The United 2026 bid beat a rival bid by Morocco during a final vote at the 68th FIFA Congress in Moscow. It will be the first World Cup since 2002 to be hosted by more than one nation. With its past hosting of the 1970 and 1986 tournaments, Mexico will become the first country to host or co-host the men's World Cup three times. The United States last hosted the men's World Cup in 1994, whereas it will be Canada's first time hosting or co-hosting the men's tournament. The event will also return to its traditional northern summer schedule after the 2022 edition in Qatar was held in November and December.", 'title': '2026 FIFA World Cup'}),
 Document(page_content="The 2022 FIFA World Cup was the 22nd FIFA World Cup, the world championship for national football teams organized by FIFA. It took place in Qatar from 20 November to 18 December 2022, after the country was awarded the hosting rights in 2010. It was the first World Cup to be held in the Arab world and Muslim world, and the second held entirely in Asia after the 2002 tournament in South Korea and Japan.\\nThis tournament was the last with 32 participating teams, with the number of teams being increased to 48 for the 2026 edition. To avoid the extremes of Qatar's hot climate, the event was held in November and December instead of during the traditional months of May, June, or July. It was held over a reduced time frame of 29 days with 64 matches played in eight venues across five cities. Qatar entered the event—their first World Cup—automatically as the host's national team, alongside 31 teams determined by the qualification process.", metadata={'source': '<https://en.wikipedia.org/wiki/2022_FIFA_World_Cup>', 'summary': "The 2022 FIFA World Cup was the 22nd FIFA World Cup, the world championship for national football teams organized by FIFA. It took place in Qatar from 20 November to 18 December 2022, after the country was awarded the hosting rights in 2010. It was the first World Cup to be held in the Arab world and Muslim world, and the second held entirely in Asia after the 2002 tournament in South Korea and Japan.\\nThis tournament was the last with 32 participating teams, with the number of teams being increased to 48 for the 2026 edition. To avoid the extremes of Qatar's hot climate, the event was held in November and December instead of during the traditional months of May, June, or July. It was held over a reduced time frame of 29 days with 64 matches played in eight venues across five cities. Qatar entered the event—their first World Cup—automatically as the host's national team, alongside 31 teams determined by the qualification process.\\nArgentina were crowned the champions after winning the final against the title holder France 4–2 on penalties following a 3–3 draw after extra time. It was Argentina's third title and their first since 1986, as well as being the first nation from outside of Europe to win the tournament since 2002. French player Kylian Mbappé became the first player to score a hat-trick in a World Cup final since Geoff Hurst in the 1966 final and won the Golden Boot as he scored the most goals (eight) during the tournament. Mbappé also became the first player to score in two consecutive finals since Vavá of Brazil did the same in 1958 and 1962. Argentine captain Lionel Messi was voted the tournament's best player, winning the Golden Ball. The tournament has been considered exceptionally poetic as the capstone of his career, for some commentators fulfilling a previously unmet criterion to be regarded as one of the greatest players of all time. Teammates Emiliano Martínez and Enzo Fernández won the Golden Glove, awarded to the tournament's best goalkeeper; and the Young Player Award, awarded to the tournament's best young player, respectively. With 172 goals, the tournament set a record for the highest number of goals scored in the 32-team format, with every participating team scoring at least one goal. Morocco became the first African nation to top Group stages with 7 points.\\nThe choice to host the World Cup in Qatar attracted significant criticism, with concerns raised over the country's treatment of migrant workers, women, and members of the LGBT community, as well as Qatar's climate, lack of a strong football culture, scheduling changes, and allegations of bribery for hosting rights and wider FIFA corruption.", 'title': '2022 FIFA World Cup'})]

次に、Claude 3モデルを使用して取得したコンテキストから必要な結果を取得するために、Claude 3モデルを使用します。

# クエリコンテキストの準備

Claude 3モデルに提供するためのコンテキストを取得したドキュメントから準備します。

stre = "".join(doc.page_content for doc in docs)

これにより、取得したドキュメントのコンテンツが1つの文字列に連結されます。

# モデルの設定

回答を生成するために使用するモデルを指定します。

model = 'claude-3-opus-20240229'

# 回答の生成

最後に、Claude 3モデルを使用して提供されたコンテキストに基づいて回答を生成します。

response = client.messages.create(
        system =  "You are a helpful research assistant. You will be shown data from a vast knowledge base. You have to answer the query from the provided context.",
        messages=[
                    {"role": "user", "content":  "Context: " + stre + "\\\\n\\\\n Query: " + query},
                ],
        model= model,
        temperature=0,
        max_tokens=160
    )
response.content[0].text

このスクリプトは、コンテキストとクエリをClaude 3モデルに送信し、生成された回答を取得します。以下のような出力が返されます。

'According to the provided context, Argentina won the 2022 FIFA World Cup, making them the 
reigning champions. The passage states:\\n\\n"The reigning champions are Argentina, who won their third title at the 2022 tournament."'

これらの手順に従うことで、Hugging Faceの埋め込みとClaude 3モデルを使用して、知識ベースから回答を取得するRAGアプリケーションを構築しました。

# RAGモデルにMyScaleDBを選ぶ理由

MyScaleDBは、高度なベクトル検索機能とSQLサポートの組み合わせにより、RAGアプリケーションに最適な選択肢となっています。ClickHouseをベースに構築されているため、ベクトルデータと構造化データをシームレスに統合することができ、複雑な効率的なクエリを可能にします。この統合により、データの管理が簡素化され、RAGシステムのパフォーマンスと正確性が向上し、大量のデータを効率的に処理することが容易になります。

MyScaleDBのもう一つの重要な利点は、コスト効率とスケーラビリティです。MyScaleDBは、競合他社に比べて優れたパフォーマンスを提供しながら、市場で最も手頃な価格のベクトルデータベースの1つとして設計されています。マルチスケールツリーグラフ(MSTG)などの高度なベクトルインデックス技術により、リソース消費を削減し、精度を向上させています。ダイナミックバッチングやマルチスレッディングなどの機能により、高い同時リクエストのボリュームをサポートし、低レイテンシと高スループットを維持します。これらの機能により、MyScaleDBはスケーラブルなRAGアプリケーションのための信頼性の高い効率的なデータベースソリューションとなります。

Join Our Newsletter

# 結論

シンプルなRAGアプリケーションの開発は比較的簡単ですが、それらを最適化し、応答の正確性を維持することは難しいです。そのため、LLM、ベクトルデータベース、埋め込みモデルなど、適切なツールの選択が重要です。各コンポーネントは、アプリケーションが効率的に実行され、正確で関連性のある応答を提供するために重要な役割を果たします。

ベクターデータベースの選択は、LLMに必要なコンテキストを提供するため、特に重要です。MyScaleDB (opens new window)は、パフォーマンスと精度の面で他の主要なベクターデータベースを上回ることが証明されています (opens new window)。さらに、MyScaleDBは新規ユーザーに500万の無料ベクターストレージを提供し、その機能をテストし、その利点を直接確認することができます。これにより、高性能なRAGシステムを構築したい方にとって優れた選択肢となります。

Keep Reading
images
MyScaleにおけるフィルタリングされたベクトル検索の最適化

ベクトル検索は、ベクトル表現に基づいてデータセット内の類似のベクトルまたはデータポイントを検索するものです。しかし、現実のシナリオでは純粋なベクトル検索だけでは十分ではありません。ベクトルには通常メタデータが付属しており、ユーザーはこのメタデータに1つ以上のフィルタを適用する必要があります。これがフィルタリングされたベクトル検索が重要になる理由です。 フィルタリングされたベクトル検索は、複雑な検 ...

images
静的なパイプラインを超えて:LlamaIndexでAIエージェントを強化する

基本的な検索支援生成(RAG)データパイプラインは、通常、ハードコードされたステップに依存し、実行するたびに事前に定義されたパスに従います。これらのシステムでは、リアルタイムの意思決定は行われず、入力データに基づいてアクションを動的 ...

Start building your Al projects with MyScale today

Free Trial
Contact Us