検索関数を作成する
Retrieval Augmented Generation (RAG) ワークフローの重要な工程は、データベースからの検索です。この演習では、コース最後の演習で重要な処理を行うカスタム関数 retrieve() を設計します。
この演習はコースの一部です
Pineconeを使ったAIアプリケーション開発
演習の手順
- OpenAI クライアントは
clientとして利用できます。Pinecone クライアントを API キーで初期化します。 - 4 つの引数
query、top_k、namespace、emb_modelを取る関数retrieveを定義します。 - 引数
emb_modelを使って入力のqueryを埋め込みに変換します。 - メタデータ付きで、
query_embに類似する上位top_k個のベクトルを取得し、関数に渡されたnamespaceを指定します。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# Initialize the Pinecone client
pc = Pinecone(api_key="____")
index = pc.Index('pinecone-datacamp')
# Define a retrieve function that takes four arguments: query, top_k, namespace, and emb_model
def retrieve(query, top_k, namespace, emb_model):
# Encode the input query using OpenAI
query_response = ____(
input=____,
model=____
)
query_emb = query_response.data[0].embedding
# Query the index using the query_emb
docs = index.query(vector=____, top_k=____, namespace=____, include_metadata=True)
retrieved_docs = []
sources = []
for doc in docs['matches']:
retrieved_docs.append(doc['metadata']['text'])
sources.append((doc['metadata']['title'], doc['metadata']['url']))
return retrieved_docs, sources
documents, sources = retrieve(
query="How to build next-level Q&A with OpenAI",
top_k=3,
namespace='youtube_rag_dataset',
emb_model="text-embedding-3-small"
)
print(documents)
print(sources)