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

สร้างฟังก์ชันดึงข้อมูล

กระบวนการสำคัญในเวิร์กโฟลว์ของ Retrieval Augmented Generation (RAG) คือการดึงข้อมูลจากฐานข้อมูล ในแบบฝึกหัดนี้ คุณจะออกแบบฟังก์ชันที่กำหนดเองชื่อ retrieve() เพื่อทำหน้าที่นี้ในแบบฝึกหัดสุดท้ายของคอร์ส

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

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

ดูคอร์ส

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

  • เริ่มต้น Pinecone client ด้วย API key ของคุณ (OpenAI client พร้อมใช้งานในชื่อ client)
  • กำหนดฟังก์ชัน retrieve ที่รับพารามิเตอร์ 4 ตัว ได้แก่ query, top_k, namespace และ emb_model
  • สร้าง embedding จาก query ที่รับเข้ามา โดยใช้อาร์กิวเมนต์ emb_model
  • ดึงเวกเตอร์ที่คล้ายกับ query_emb มากที่สุด top_k รายการพร้อม metadata โดยระบุ namespace ที่ส่งเข้ามาเป็นอาร์กิวเมนต์

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

# Initialize the Pinecone client
pc = Pinecone(api_key="____")
index = pc.Index('pinecone-datacamp')

# Define a retrieve function that takes four arguments: query, top_k, namespace, and emb_model
def retrieve(query, top_k, namespace, emb_model):
    # Encode the input query using OpenAI
    query_response = ____(
        input=____,
        model=____
    )
    
    query_emb = query_response.data[0].embedding
    
    # Query the index using the query_emb
    docs = index.query(vector=____, top_k=____, namespace=____, include_metadata=True)
    
    retrieved_docs = []
    sources = []
    for doc in docs['matches']:
        retrieved_docs.append(doc['metadata']['text'])
        sources.append((doc['metadata']['title'], doc['metadata']['url']))
    
    return retrieved_docs, sources

documents, sources = retrieve(
  query="How to build next-level Q&A with OpenAI",
  top_k=3,
  namespace='youtube_rag_dataset',
  emb_model="text-embedding-3-small"
)
print(documents)
print(sources)
แก้ไขและรันโค้ด