← رجوع

كيف تبني RAG؟ دليل عملي بـ Python خطوة بخطوة

ما هو RAG وكيف تبني نظاماً يجيب من مستنداتك: التقطيع، والتضمينات، والاسترجاع، والإجابة مع المصدر، ثم الاختبار.

كيف تبني RAG؟ دليل عملي بـ Python خطوة بخطوة

ما هو RAG؟

RAG (توليد الإجابة بعد الاسترجاع) طريقة تجعل النموذج يجيب من مستنداتك أنت: نبحث أولاً عن الفقرات المناسبة للسؤال، ثم نعطيها للنموذج ليكتب الإجابة منها.

مثل امتحان الكتاب المفتوح: الطالب لا يحفظ كل شيء، بل يجد الصفحة الصحيحة ثم يجيب.

متى تحتاجه؟

  • إجابات من ملفات شركتك أو دروسك أو سياساتك.
  • معلومات تتغيّر باستمرار.
  • تريد ذكر المصدر مع كل إجابة.

الخطوات الست

  1. اجمع المستندات مع اسم مصدر كل واحد.
  2. قطّعها (Chunking) إلى أجزاء صغيرة متداخلة.
  3. حوّل كل جزء إلى تضمين (Embedding): أرقام تمثّل المعنى، وخزّنها.
  4. استرجع أقرب الأجزاء إلى السؤال.
  5. أجب من هذه الأجزاء فقط، واذكر المصدر.
  6. اختبر الاسترجاع والإجابات.

التثبيت

pip install -U langchain-core langchain-ollama langchain-text-splitters numpy
ollama pull qwen2.5:3b
ollama pull embeddinggemma

الكود الكامل

from langchain_core.documents import Document
from langchain_core.vectorstores import InMemoryVectorStore
from langchain_ollama import ChatOllama, OllamaEmbeddings
from langchain_text_splitters import RecursiveCharacterTextSplitter

# 1) your documents (read them from files in a real project)
docs = [
    Document(page_content="Refunds are accepted within 14 days of purchase with a receipt.", metadata={"source": "refunds.md"}),
    Document(page_content="Standard shipping takes 3 to 5 working days. Express shipping takes 1 day.", metadata={"source": "shipping.md"}),
    Document(page_content="Support is open Sunday to Thursday, from 9 AM to 6 PM.", metadata={"source": "support.md"}),
]

# 2) split into chunks, 3) embed them and store the vectors
chunks = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=80).split_documents(docs)
store = InMemoryVectorStore(OllamaEmbeddings(model="embeddinggemma"))
store.add_documents(chunks)

model = ChatOllama(model="qwen2.5:3b", temperature=0)


def ask(question: str) -> str:
    # 4) retrieve the closest chunks
    hits = store.similarity_search(question, k=2)
    context = "\n\n".join(f"[{d.metadata['source']}]\n{d.page_content}" for d in hits)
    # 5) answer from those chunks only
    messages = [
        ("system", "Answer in one sentence using only the context, then write the source file name in brackets. If the answer is not there, say you don't know."),
        ("human", f"Context:\n{context}\n\nQuestion: {question}"),
    ]
    return model.invoke(messages).content


print(ask("How many days do I have to get a refund?"))

# 6) test retrieval before judging the answers
tests = [
    ("Can I return an item?", "refunds.md"),
    ("When will my parcel arrive?", "shipping.md"),
    ("What are your working hours?", "support.md"),
]
found = sum(source in [d.metadata["source"] for d in store.similarity_search(q, k=2)] for q, source in tests)
print(f"Retrieval: {found}/{len(tests)} questions found the right file")

النتيجة التي ظهرت عندنا:

You have 14 days to get a refund [refunds.md].
Retrieval: 3/3 questions found the right file

وعندما سألنا عن معلومة غير موجودة (رقم هاتف المدير) أجاب: I don't know.

كيف تحسّنه؟

المشكلة جرّب
لا يجد الفقرة الصحيحة حجم تقطيع مختلف، أو نموذج تضمين أفضل للغتك
يجد الفقرة لكن الإجابة خاطئة Prompt أوضح، أو نموذج أقوى
بطيء أجزاء أقل وأقصر في السياق، وقِس زمن كل خطوة
يخترع إجابات اطلب منه صراحة أن يقول «لا أعرف»، واختبر ذلك

من تجربتي: خفّضت زمن استجابة خدمة RAG من 25 ثانية إلى 4-5 ثوانٍ بإعادة هندسة التقطيع والتضمينات والـ Prompts والتوليد. قِس أولاً، ثم عدّل خطوة واحدة في كل مرة.

قبل الإنتاج

  • استبدل المخزن المؤقت (InMemoryVectorStore) بقاعدة متجهات مثل Qdrant أو FAISS.
  • لا تُرجع لمستخدم أجزاء من ملفات ليس له صلاحية رؤيتها.
  • جهّز مجموعة أسئلة اختبار حقيقية وكبّرها مع الوقت.

الدليل التالي

LangGraph (لانججراف): وكلاء بذاكرة وموافقة بشرية

جُرّب الكود في 30 تشرين الثاني 2026 على Python 3.10 و LangChain 1.4 و LangGraph 1.2.