Together AI チュートリアル: 基礎から高度なRAGまで

Together AIの中級チュートリアルへようこそ!🚀

Together AIは、幅広いオープンソース生成AIモデルにアクセスできるクラウドプラットフォームです。高性能な推論、微調整機能、開発者に優しいツールで知られています。このノートブックでは、基礎を拡張し、高品質な埋め込みと再ランキングなどの重要な機能を紹介しながら、より堅牢なRetrieval-Augmented Generation(RAG)システムの構築をガイドします。

1. セットアップ

まず、必要なライブラリをインストールしましょう。数値演算にはnumpyを、APIキーの安全な管理にはpython-dotenvを使用します。

# Uncomment the following line to install the required packages
# %pip install together python-dotenv numpy

次に、このノートブックと同じディレクトリに.envという名前のファイルを作成し、Together AIのAPIキーを追加してください:

TOGETHER_API_KEY="your_api_key_here"

では、APIキーを読み込んでクライアントを初期化しましょう。

import os
from dotenv import load_dotenv
import together

load_dotenv()

client = together.Together(api_key=os.environ.get("TOGETHER_API_KEY"))

2. Together AIの機能を簡単に見てみよう

RAGに入る前に、Together AIの際立った機能をいくつか紹介します:

  • 豊富なモデルライブラリ: 100以上のオープンソースモデルにアクセス(チャット、コード、画像、埋め込みなど)。
  • 高性能: 高速な応答時間を実現する最適化された推論スタック。
  • OpenAI互換性: PythonクライアントはOpenAIクライアントのドロップイン代替として設計されており、移行が簡単。
  • サーバーレスエンドポイント: インフラを管理せずに従量課金でモデルを利用。
  • 微調整と再ランキング: モデルをカスタマイズし、情報検索の品質を向上するツール。

3. 高度なRAGシステムの構築

Retrieval-Augmented Generation(RAG)は、外部のナレッジベースから関連情報を大規模言語モデルに提供することで、応答を強化します。これにより、幻覚が減少し、特定の最新データやプライベートデータに関する質問に答えられます。

RAGパイプラインには以下が含まれます:

  1. ナレッジベースの準備: テキストファイルを作成して処理します。
  2. インデックス作成: 高品質な埋め込みモデルを使用してデータのベクトル表現を作成します。
  3. 検索: クエリに最も関連性の高いドキュメントを見つけます。
  4. 再ランキング: 再ランキングモデルを使用して検索結果を洗練します。
  5. 生成: 検索および再ランキングされた情報に基づいて最終的な回答を生成します。

ステップ1: ナレッジベースの準備

Together AIに関する小さなナレッジベースを作成し、ファイルに保存しましょう。

knowledge_base_content = """
Together AI offers a cloud platform for building and running generative AI. It provides access to over 100 open-source models.
The platform is designed for high-performance inference, leveraging techniques like speculative decoding.
For Retrieval-Augmented Generation, Together AI offers both embedding models and reranker models.
The BAAI/bge-large-en-v1.5 is a popular and powerful model for generating text embeddings.
Reranking is a crucial step in a RAG pipeline to improve the quality of retrieved documents before sending them to the language model.
The Together AI Python client is compatible with the OpenAI API, making it easy for developers to switch.
Users can fine-tune models on their own data to create specialized, expert models.
Together AI offers both serverless, pay-as-you-go endpoints and dedicated instances for large-scale applications.
"""

with open("knowledge_base.txt", "w") as f:
    f.write(knowledge_base_content)

# Now, we'll load the text and split it into chunks (in this case, by line).
with open("knowledge_base.txt", "r") as f:
    knowledge_base = [line.strip() for line in f.readlines() if line.strip()]

ステップ2: 高品質な埋め込みモデルによるインデックス作成

Together AIで利用可能なトップクラスの埋め込みモデルであるBAAI/bge-large-en-v1.5を使用して、テキストチャンクをベクトルに変換します。

embedding_model = "BAAI/bge-large-en-v1.5"

embeddings_response = client.embeddings.create(
    model=embedding_model,
    input=knowledge_base,
)

document_embeddings = [embedding.embedding for embedding in embeddings_response.data]

ステップ3: 検索

次に、ユーザーのクエリを埋め込み、コサイン類似度を使用してナレッジベースから最も関連性の高いチャンクを見つけます。

import numpy as np
from numpy.linalg import norm

def cosine_similarity(a, b):
    return np.dot(a, b) / (norm(a) * norm(b))

user_query = "How can I improve my RAG system?"
top_k = 3

query_embedding_response = client.embeddings.create(
    model=embedding_model,
    input=[user_query],
)
query_embedding = query_embedding_response.data[0].embedding

similarities = [cosine_similarity(query_embedding, doc_embedding) for doc_embedding in document_embeddings]

top_indices = np.argsort(similarities)[-top_k:][::-1]
retrieved_documents = [knowledge_base[i] for i in top_indices]

print("Retrieved documents (before reranking):")
for doc in retrieved_documents:
    print(f"- {doc}")
Retrieved documents (before reranking):
- Reranking is a crucial step in a RAG pipeline to improve the quality of retrieved documents before sending them to the language model.
- Users can fine-tune models on their own data to create specialized, expert models.
- The BAAI/bge-large-en-v1.5 is a popular and powerful model for generating text embeddings.

ステップ4: 品質のための再ランキング

コサイン類似度は有用ですが、完璧ではありません。再ランキングモデルは、取得したドキュメントを取得し、クエリとの関連性についてより繊細な理解に基づいて再順序付けできます。これは、本番品質のRAGシステムを構築する上で重要な機能です。

rerank_model = "mixedbread-ai/Mxbai-Rerank-Large-V2"

rerank_response = client.rerank.create(
    model=rerank_model,
    query=user_query,
    documents=retrieved_documents,
)

reranked_indices = [result.index for result in rerank_response.results]
reranked_documents = [retrieved_documents[i] for i in reranked_indices]

print("\nReranked documents:")
for doc in reranked_documents:
    print(f"- {doc}")
Reranked documents:
- The BAAI/bge-large-en-v1.5 is a popular and powerful model for generating text embeddings.
- Users can fine-tune models on their own data to create specialized, expert models.
- Reranking is a crucial step in a RAG pipeline to improve the quality of retrieved documents before sending them to the language model.

ステップ5: 生成

最後に、クエリとトップの再ランキング済みドキュメントをプロンプトに組み合わせ、強力なチャットモデルに送信して包括的な回答を生成します。

context = reranked_documents[0] # Use the top reranked document

prompt = f"""
Context: {context}
Question: {user_query}
Based on the provided context, give a concise answer.
Answer:
"""

response = client.chat.completions.create(
    model="meta-llama/Llama-3-8b-chat-hf",
    messages=[{"role": "user", "content": prompt}],
    temperature=0.7,
)

print(f"\nFinal Answer:\n{response.choices[0].message.content}")
Final Answer:
To improve your RAG (Reactor Alignment Generator) system, consider fine-tuning the BAAI/bge-large-en-v1.5 model on your specific task and dataset to adapt its text embeddings to your use case. This can be done using a technique like masked language modeling or sentence similarity tasks to adjust the model's output to better suit your requirements.

4. まとめ

このチュートリアルでは、Together AIを使用してより洗練されたRAGシステムを構築する方法を示しました。高品質な埋め込みモデルと再ランキングモデルなどの重要な機能を活用して、情報検索の精度を向上させました。このアプローチにより、大規模言語モデルを事実に基づく外部知識に基づいて強化でき、能力が大幅に向上します。

ここからは、以下のようなさらに高度なトピックを探索できます:

  • 微調整: 独自のデータでモデルを訓練し、専門的なタスクに対応。
  • 大規模なナレッジベース: PineconeやMongoDBなどのベクトルデータベースと統合して、スケーラブルなRAGを実現。
  • 異なるモデル: Together AIプラットフォームで利用可能な幅広いモデルを試す。