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 애플리케이션 구축하기
연습 안내
- Pinecone 클라이언트를 API 키로 초기화하세요(OpenAI 클라이언트는
client로 제공됩니다). 'youtube_rag_dataset'네임스페이스에서query텍스트와 가장 유사한 문서 3개를 검색하세요.chat_model함수 인자로 지정된 OpenAI의'gpt-4o-mini'모델을 사용해, 제공된prompt와sys_prompt에 대한 응답을 생성하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# 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)