Hàm trả lời câu hỏi kiểu RAG
Bạn sắp hoàn thành rồi! Mảnh ghép cuối trong quy trình RAG là tích hợp các tài liệu đã truy xuất với một mô hình trả lời câu hỏi.
Một hàm prompt_with_context_builder() đã được định nghĩa sẵn và cung cấp cho bạn. Hàm này nhận các tài liệu lấy từ Pinecone index và tích hợp chúng vào một prompt mà mô hình trả lời câu hỏi có thể xử lý:
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
Bạn sẽ triển khai hàm question_answering(), hàm này sẽ cung cấp cho mô hình ngôn ngữ gpt-4o-mini của OpenAI thêm ngữ cảnh và nguồn trích dẫn để mô hình có thể trả lời câu hỏi của bạn.
Bài tập này là một phần của khóa học
Cơ sở dữ liệu vector cho Embeddings với Pinecone
Hướng dẫn bài tập
- Khởi tạo Pinecone client với API key của bạn (OpenAI client đã có sẵn dưới tên
client). - Truy xuất ba tài liệu giống nhất với văn bản
querytừ namespace'youtube_rag_dataset'. - Tạo phản hồi cho
promptvàsys_promptđã cho bằng mô hình'gpt-4o-mini'của OpenAI, được chỉ định thông qua đối số hàmchat_model.
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
# 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)