検索された生成(RAG)は、外部情報検索を統合することにより、言語モデルを大幅に向上させます。 標準的なRAGは、応答の関連性を改善しながら、複雑な検索状況でしばしば衰退します。この記事では、基本的なぼろきれの欠点を検討し、精度と効率を改善するための高度な方法を提示します。
健康的で生産的なライフスタイルの実践を詳述した主要な文書。
<code>main_document_text = """ Morning Routine (5:30 AM - 9:00 AM) ✅ Wake Up Early - Aim for 6-8 hours of sleep to feel well-rested. ✅ Hydrate First - Drink a glass of water to rehydrate your body. ✅ Morning Stretch or Light Exercise - Do 5-10 minutes of stretching or a short workout to activate your body. ✅ Mindfulness or Meditation - Spend 5-10 minutes practicing mindfulness or deep breathing. ✅ Healthy Breakfast - Eat a balanced meal with protein, healthy fats, and fiber. ✅ Plan Your Day - Set goals, review your schedule, and prioritize tasks. ... """</code>
基本的なragの評価
事前定義されたクエリを使用して基本的なRAGをテストして、セマンティックの類似性に基づいて最も関連性の高いドキュメントを取得する能力を評価します。 これは、その制限を強調しています。
<code># **Imports** import os import json import openai import numpy as np from scipy.spatial.distance import cosine from google.colab import userdata # Set up OpenAI API key os.environ["OPENAI_API_KEY"] = userdata.get('AiTeam')</code>
<code>def query_chatgpt(prompt, model="gpt-4o", response_format=openai.NOT_GIVEN): try: response = client.chat.completions.create( model=model, messages=[{"role": "user", "content": prompt}], temperature=0.0 , # Adjust for more or less creativity response_format=response_format ) return response.choices[0].message.content.strip() except Exception as e: return f"Error: {e}"</code>
<code>def get_embedding(text, model="text-embedding-3-large"): #"text-embedding-ada-002" """Fetches the embedding for a given text using OpenAI's API.""" response = client.embeddings.create( input=[text], model=model ) return response.data[0].embedding</code>
<code>def compute_similarity_metrics(embed1, embed2): """Computes different similarity/distance metrics between two embeddings.""" cosine_sim = 1- cosine(embed1, embed2) # Cosine similarity return cosine_sim</code>
<code>def fetch_similar_docs(query, docs, threshold = .55, top=1): query_em = get_embedding(query) data = [] for d in docs: # Compute and print similarity metrics similarity_results = compute_similarity_metrics(d["embedding"], query_em) if(similarity_results >= threshold): data.append({"id":d["id"], "ref_doc":d.get("ref_doc", ""), "score":similarity_results}) # Sorting by value (second element in each tuple) sorted_data = sorted(data, key=lambda x: x["score"], reverse=True) # Ascending order sorted_data = sorted_data[:min(top, len(sorted_data))] return sorted_data</code>
"""# **Testing Vanilla RAG**"""
query = "what should I do to stay healthy and productive?"
r = fetch_similar_docs(query, docs)
print("query = ", query)
print("documents = ", r)
query = "what are the best practices to stay healthy and productive ?"
r = fetch_similar_docs(query, docs)
print("query = ", query)
print("documents = ", r)
ドキュメントからFAQを作成すると、クエリマッチングの可能性が拡張されます。 これらのFAQは1回生成され、保存され、繰り返しコストなしで検索スペースを充実させます。
簡潔な要約は、ドキュメントのコアアイデアをキャプチャし、検索の有効性を向上させます。概要の埋め込みは、ドキュメントコレクションに追加されます。
広いクエリは、より小さく、より正確なサブQuerieに分類されます。 これらのサブQuerieは、拡張されたドキュメントコレクション(元のドキュメント、FAQ、および概要)と比較されます。 結果が改善されるためにマージされます。
<code>main_document_text = """ Morning Routine (5:30 AM - 9:00 AM) ✅ Wake Up Early - Aim for 6-8 hours of sleep to feel well-rested. ✅ Hydrate First - Drink a glass of water to rehydrate your body. ✅ Morning Stretch or Light Exercise - Do 5-10 minutes of stretching or a short workout to activate your body. ✅ Mindfulness or Meditation - Spend 5-10 minutes practicing mindfulness or deep breathing. ✅ Healthy Breakfast - Eat a balanced meal with protein, healthy fats, and fiber. ✅ Plan Your Day - Set goals, review your schedule, and prioritize tasks. ... """</code>
これらの機能強化で最初のクエリを再実行すると、大幅な改善が示されます。クエリ分解により複数のサブQuerieが生成され、FAQと元のドキュメントの両方から検索が成功します。
<code># **Imports** import os import json import openai import numpy as np from scipy.spatial.distance import cosine from google.colab import userdata # Set up OpenAI API key os.environ["OPENAI_API_KEY"] = userdata.get('AiTeam')</code>
<code>def query_chatgpt(prompt, model="gpt-4o", response_format=openai.NOT_GIVEN): try: response = client.chat.completions.create( model=model, messages=[{"role": "user", "content": prompt}], temperature=0.0 , # Adjust for more or less creativity response_format=response_format ) return response.choices[0].message.content.strip() except Exception as e: return f"Error: {e}"</code>
以上がラグの強化:バニラを超えてアプローチしますの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。