RAG soru yanıtlama fonksiyonu
Neredeyse bitti! RAG iş akışındaki son adım, getirilen belgeleri bir soru-yanıtlama modeliyle entegre etmek.
Bir prompt_with_context_builder() fonksiyonu zaten tanımlandı ve kullanımına hazır. Bu fonksiyon, Pinecone indeksinden getirilen belgeleri alır ve soru-yanıtlama modelinin işleyebileceği bir isteme entegre eder:
def prompt_with_context_builder(query, docs):
delim = '\n\n---\n\n'
prompt_start = 'Answer the question based on the context below.\n\nContext:\n'
prompt_end = f'\n\nQuestion: {query}\nAnswer:'
prompt = prompt_start + delim.join(docs) + prompt_end
return prompt
question_answering() fonksiyonunu uygulayacaksın. Bu fonksiyon, OpenAI'nin gpt-4o-mini dil modeline, sorularını yanıtlarken kullanabileceği ek bağlam ve kaynaklar sağlayacak.
Bu egzersiz
Pinecone ile Vektör Veritabanları ve Embeddings
kursunun bir parçasıdırEgzersiz talimatları
- Pinecone istemcisini API anahtarınla başlat (OpenAI istemcisi
clientolarak mevcut). 'youtube_rag_dataset'namespace'indenquerymetnine en benzer üç belgeyi getir.chat_modelfonksiyon argümanı kullanılarak belirtilen OpenAI'nin'gpt-4o-mini'modeliyle verilenpromptvesys_promptiçin bir yanıt üret.
Uygulamalı interaktif egzersiz
Bu örnek kodu tamamlayarak bu egzersizi bitirin.
# Initialize the Pinecone client
pc = Pinecone(api_key="____")
index = pc.Index('pinecone-datacamp')
query = "How to build next-level Q&A with OpenAI"
# Retrieve the top three most similar documents and their sources
documents, sources = retrieve(____, top_k=____, namespace='____', emb_model="text-embedding-3-small")
prompt_with_context = prompt_with_context_builder(query, documents)
print(prompt_with_context)
def question_answering(prompt, sources, chat_model):
sys_prompt = "You are a helpful assistant that always answers questions."
# Use OpenAI chat completions to generate a response
res = ____(
model=____,
messages=[
{"role": "system", "content": ____},
{"role": "user", "content": ____}
],
temperature=0
)
answer = res.choices[0].message.content.strip()
answer += "\n\nSources:"
for source in sources:
answer += "\n" + source[0] + ": " + source[1]
return answer
answer = question_answering(
prompt=prompt_with_context,
sources=sources,
chat_model='gpt-4o-mini')
print(answer)