เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

ฟังก์ชันตอบคำถามแบบ RAG

ใกล้เสร็จแล้ว! ขั้นตอนสุดท้ายของ RAG workflow คือการนำเอกสารที่ดึงมาได้มาผนวกเข้ากับโมเดลตอบคำถาม

ฟังก์ชัน prompt_with_context_builder() ถูกกำหนดไว้ให้แล้ว ฟังก์ชันนี้รับเอกสารที่ดึงมาจาก Pinecone index แล้วนำไปสร้าง prompt ที่โมเดลตอบคำถามสามารถนำไปใช้งานได้:

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() ไปใช้งาน ซึ่งจะส่งข้อมูล context และแหล่งอ้างอิงเพิ่มเติมให้กับโมเดลภาษา gpt-4o-mini ของ OpenAI เพื่อช่วยให้ตอบคำถามได้แม่นยำยิ่งขึ้น

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

Vector Databases สำหรับ Embeddings ด้วย Pinecone

ดูคอร์ส

คำแนะนำการฝึกหัด

  • เริ่มต้น Pinecone client ด้วย API key ของคุณ (OpenAI client พร้อมใช้งานในชื่อ client)
  • ดึงเอกสารที่มีความคล้ายคลึงกับข้อความ query มากที่สุด 3 รายการจาก namespace 'youtube_rag_dataset'
  • สร้างคำตอบจาก prompt และ sys_prompt ที่กำหนดให้ โดยใช้โมเดล 'gpt-4o-mini' ของ OpenAI ซึ่งระบุผ่านอาร์กิวเมนต์ 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)
แก้ไขและรันโค้ด