RAG 問答函式
就快完成了!RAG 工作流程的最後一步,是把擷取到的文件整合進問答模型。
系統已經替你定義並提供一個 prompt_with_context_builder() 函式。這個函式會將從 Pinecone 索引擷取到的文件,整合成問答模型可讀取的提示內容:
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() 函式,為 OpenAI 的語言模型 gpt-4o-mini 提供額外的脈絡與來源,讓它能回答你的問題。
本練習屬於課程
使用 Pinecone 構建 AI 應用
練習說明
- 以你的 API 金鑰初始化 Pinecone 用戶端(OpenAI 用戶端已可用,名稱為
client)。 - 從
'youtube_rag_dataset'這個 namespace 擷取與query最相似的 3 份文件。 - 使用 OpenAI 的
'gpt-4o-mini'模型,根據提供的prompt與sys_prompt產生回應,並以函式參數chat_model指定模型。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# 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)