Skip to main content

Lab 3 — วัดผล RAG

Lab walkthrough · EP11 Advanced & Agentic RAG

หมายเหตุวิธีใช้หน้านี้

หน้านี้คือ notebook เฉลยของ lab นี้ทีละ cell พร้อม output จากการรันจริงตอนอัดคลิป ไว้อ่านทวนก่อนหรือหลังลงมือ cell ที่มี ✏️ TODO แสดงโค้ดแบบใน starter notebook ส่วนเฉลยเต็มอยู่ในกล่อง ดูเฉลย ลองเขียนเองก่อนค่อยเปิด

▶ วิดีโอ · ✏️ Starter ใน Colab · ✅ เฉลยใน Colab · กลับไปหน้า EP11 Advanced & Agentic RAG

model ตอบไม่เหมือนเดิมทุกครั้ง output ที่คุณรันเองจึงอาจต่างจากหน้านี้

ตั้งแต่ EP10 เราวัดด้วย hit@3 อย่างเดียว: หน้าที่ถูกอยู่ในสามชิ้นแรกไหม — ตำราบอกว่าต้องวัด สามระดับ (§16.8)

  1. Retrieval: ค้นได้ชิ้นที่ถูกไหม — Recall@K · MRR · NDCG@K
  2. Generation: คำตอบมีหลักฐานจากเอกสารไหม ตรงคำถามไหม ถูกไหม — faithfulness · answer relevance · correctness
  3. End-to-end: ผู้ใช้ได้สิ่งที่ต้องการไหม (ต้องใช้คนหรืองานจริง — นอก lab นี้)

สิ่งที่จะได้ทำ

  1. เขียน Recall@K, MRR, NDCG@K เอง ตามสมการ 16.22, 16.24, 16.25
  2. วัด ห้าระบบ ที่เราสร้างมาตั้งแต่ EP10 บนคำถาม 20 ข้อชุดเดิม
  3. เขียน faithfulness (สมการ 16.26) และ answer relevance (สมการ 16.27) ด้วย LLM judge
  4. วัดคำตอบสามแบบของคำถามยาว แล้วดูว่าตัววัดแต่ละตัวมองเห็นอะไร และมองไม่เห็นอะไร

คำตอบของ model ทุกคำตอบมาจากการรันจริง

อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §16.8 — CC BY-SA 4.0

0. เตรียมเครื่องก่อนเริ่ม

สิ่งที่ต้องมี รายละเอียด
Python 3.10 ขึ้นไป หรือใช้ Google Colab ซึ่งมีให้แล้ว
OpenRouter API key key เดิมจาก Lab 1 (lab นี้ใช้ราว 7 เซ็นต์ดอลลาร์ ส่วนใหญ่เป็นค่า re-ranking) — วิธีตั้งค่า key และเหตุผลที่เลือก model อยู่ใน Lab 1
Packages openai, python-dotenv, pypdf, numpy, tokenizers, requests (ติดตั้งใน cell ถัดไป)

ใส่ API key

  • Colab: ไอคอน 🔑 Secrets → ชื่อ OPENROUTER_API_KEY → เปิด Notebook access
  • เครื่องตัวเอง: สร้างไฟล์ .env ในโฟลเดอร์เดียวกับ notebook แล้วใส่บรรทัด OPENROUTER_API_KEY=sk-or-...

⚠️ อย่าใส่ key ลงในโค้ดโดยตรง และอย่าแชร์ไฟล์ .env

%pip install -q "openai>=1.50" python-dotenv "pypdf>=6" numpy "tokenizers==0.23.3" requests

1. ทุกอย่างที่เราสร้างมา

สาม cell ถัดไปคือโค้ดจาก Lab ก่อนๆ: model สามตัว · คลัง 141 ชิ้น + BM25 · HyDE, RRF, re-ranking · คำถามทดสอบ 20 ข้อ

import os, re, math, json, urllib.request, requests
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
import numpy as np
from openai import OpenAI
from pypdf import PdfReader
from tokenizers import Tokenizer

def load_key():
    try:  # Google Colab Secrets
        from google.colab import userdata
        return userdata.get("OPENROUTER_API_KEY")
    except ImportError:
        pass
    from dotenv import load_dotenv
    load_dotenv()
    return os.environ["OPENROUTER_API_KEY"]

MODEL = "google/gemma-4-26b-a4b-it"
EXTRA = {"reasoning": {"enabled": False},
         "provider": {"order": ["makora"], "allow_fallbacks": False}}
EMBED_MODEL = "qwen/qwen3-embedding-8b"
EMBED_EXTRA = {"provider": {"order": ["nebius"], "allow_fallbacks": False}}
RERANK_MODEL = "qwen/qwen3-reranker-8b"
RERANK_PROVIDER = {"order": ["fireworks"], "allow_fallbacks": False}
KEY = load_key()
client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=KEY, max_retries=5)
COST = {"chat": 0.0, "embed": 0.0, "rerank": 0.0}

def ask(prompt):
    r = client.chat.completions.create(model=MODEL, temperature=0, extra_body=EXTRA,
                                       messages=[{"role": "user", "content": prompt}])
    COST["chat"] += r.usage.cost
    return r.choices[0].message.content

def embed(texts):
    vectors = []
    for i in range(0, len(texts), 64):
        r = client.embeddings.create(model=EMBED_MODEL, input=texts[i:i + 64],
                                     extra_body=EMBED_EXTRA)
        COST["embed"] += r.usage.cost
        vectors += [d.embedding for d in r.data]
    V = np.array(vectors)
    return V / np.linalg.norm(V, axis=1, keepdims=True)

def obj(**fields):
    return {"type": "object", "properties": fields,
            "required": list(fields), "additionalProperties": False}
TEXT = {"type": "string"}

def ask_json(prompt, schema):
    for attempt in range(2):                            # one retry if the JSON comes back cut off
        r = client.chat.completions.create(
            model=MODEL, temperature=0, extra_body=EXTRA, max_tokens=1500,
            messages=[{"role": "user", "content": prompt}],
            response_format={"type": "json_schema",
                             "json_schema": {"name": "reply", "strict": True, "schema": schema}})
        COST["chat"] += r.usage.cost
        try:
            return json.loads(r.choices[0].message.content)
        except json.JSONDecodeError:
            pass
    raise ValueError("the model did not return valid JSON")
urllib.request.urlretrieve("https://arxiv.org/pdf/2606.24937v1", "hitchhikers-guide-v1.pdf")
reader = PdfReader("hitchhikers-guide-v1.pdf")
HEADER = "H. Roitman — The Hitchhiker’s Guide to Agentic AI: From Foundations to Systems\n"
pages = [{"page": n, "text": reader.pages[n - 1].extract_text().replace(HEADER, "")}
         for n in range(292, 375)]                      # chapters 15–19
tok = Tokenizer.from_pretrained(MODEL)

def chunk_page(page, W=512, O=64):
    ids = tok.encode(page["text"], add_special_tokens=False).ids
    return [{"source": "hitchhikers-guide-v1.pdf", "page": page["page"],
             "text": tok.decode(ids[s:s + W])}
            for s in range(0, max(len(ids) - O, 1), W - O)]

chunks = [c for p in pages for c in chunk_page(p)]
E = embed([c["text"] for c in chunks])

def words(text):                                        # BM25 from EP10 Lab 2
    return re.findall(r"\w+", text.lower())
docs = [words(c["text"]) for c in chunks]
N, avgdl = len(docs), sum(len(d) for d in docs) / len(docs)
df = Counter(w for d in docs for w in set(d))
tfs = [Counter(d) for d in docs]
def idf(t):
    n = df.get(t, 0)
    return math.log((N - n + 0.5) / (n + 0.5) + 1)
def bm25_rank(query, k1=1.5, b=0.75):
    scores = [sum(idf(t) * tf[t] * (k1 + 1) / (tf[t] + k1 * (1 - b + b * len(d) / avgdl))
                  for t in words(query)) for d, tf in zip(docs, tfs)]
    return list(np.argsort(-np.array(scores)))
print(len(chunks), "chunks")
Warning: You are sending unauthenticated requests to the HF Hub. Please set a HF_TOKEN to enable higher rate limits and faster downloads.

141 chunks
def dense(query):                                       # EP10 Lab 1
    return list(np.argsort(-(E @ embed([query])[0])))

def rrf(lists, k=60):                                   # EP10 Lab 2
    score = {}
    for order in lists:
        for rank, i in enumerate(order, 1):
            score[i] = score.get(i, 0) + 1 / (k + rank)
    return sorted(score, key=score.get, reverse=True)

def hyde(query):                                        # Lab 1
    draft = ask("Write a short passage (about 100 words) from a textbook that answers this question. "
                "Write it as the textbook would, even if you are not sure.\n\nQuestion: " + query)
    return dense(draft)

def rerank(query, order, n=20):                         # Lab 1
    top = order[:n]
    r = requests.post("https://openrouter.ai/api/v1/rerank",
                      headers={"Authorization": f"Bearer {KEY}"},
                      json={"model": RERANK_MODEL, "provider": RERANK_PROVIDER, "query": query,
                            "documents": [chunks[i]["text"] for i in top]}, timeout=60)
    r.raise_for_status()
    data = r.json()
    COST["rerank"] += data["usage"]["cost"]
    return [top[x["index"]] for x in data["results"]]

TESTS = [  # (question, the pages that answer it) — from EP10 Lab 3
    ("What is PLAID?", {301}), ("What is HyDE?", {303}), ("What does FAISS stand for?", {298}),
    ("How can I search millions of vectors quickly?", {298}),
    ("Which method compares every query token with every document token?", {300}),
    ("How do I make keyword search understand synonyms?", {299}),
    ("When should I fine-tune a model instead of looking things up?", {296}),
    ("Which chunks should I give the model if small ones retrieve better but lack context?", {302, 303}),
    ("How do I combine keyword search and embedding search?", {298}),
    ("What analogy does the textbook use to explain RAG?", {295}),
    ("How does the textbook add randomness to retry waits?", {357}),
    ("What does FIFO mean for conversation history?", {345}),
    ("Where should the unchanging part of a prompt go so caching works?", {358}),
    ("When should a person approve an agent's action?", {355}),
    ("How does Graph RAG find groups of related entities?", {305}),
    ("Which chunking method splits where the topic changes?", {302}),
    ("Which frameworks are compared in Table 18.1?", {359}),
    ("What is the difference between episodic and semantic memory?", {321, 322}),
    ("What does an evaluator-optimizer workflow do?", {370, 371}),
    ("How does the harness notice an agent repeating the same tool call?", {357, 363}),
]

2. ตัววัดฝั่งการค้น (§16.8.1)

\(R_K\) = ชิ้นใน K อันดับแรก · \(R^*\) = ชิ้นที่ถูกทั้งหมด

\[\text{Recall@K}=\frac{|R_K\cap R^*|}{|R^*|}\;(16.22)\qquad \text{MRR}=\frac{1}{|Q|}\sum_i\frac{1}{\text{rank}_i}\;(16.24)\qquad \text{NDCG@K}=\frac{\text{DCG@K}}{\text{IDCG@K}},\;\text{DCG@K}=\sum_{i=1}^{K}\frac{rel_i}{\log_2(i+1)}\;(16.25)\]

ชิ้นที่ถูก ของเรา: ชิ้นที่มาจากหน้าที่ตอบคำถาม (ป้ายระดับหน้า — หน้าหนึ่งอาจมีสองชิ้น) · rel เป็น 0 หรือ 1

def relevant(gold):
    return {i for i, c in enumerate(chunks) if c["page"] in gold}

# ✏️ TODO 1 (▶ วิดีโอ 2:25): นับชิ้นใน k อันดับแรกที่อยู่ในเซต R แล้วหารด้วยขนาดของ R

def recall_at_k(order, gold, k=5):
    R = relevant(gold)
    return ___

# ✏️ TODO 2 (▶ วิดีโอ 2:39): เมื่อเจอชิ้นที่ถูกชิ้นแรก คืนค่า 1 หารด้วยอันดับของมัน

def reciprocal_rank(order, gold):
    for rank, i in enumerate(order, 1):
        if chunks[i]["page"] in gold:
            return ___
    return 0.0

# ✏️ TODO 3 (▶ วิดีโอ 3:00): รวม 1 / log2(rank + 1) ของชิ้นที่ถูกที่อยู่ใน k อันดับแรก

def ndcg_at_k(order, gold, k=5):
    dcg = sum(___
              for rank, i in enumerate(order[:k], 1) if chunks[i]["page"] in gold)
    ideal = sum(1 / math.log2(rank + 1) for rank in range(1, min(len(relevant(gold)), k) + 1))
    return dcg / ideal
def relevant(gold):
    return {i for i, c in enumerate(chunks) if c["page"] in gold}

def recall_at_k(order, gold, k=5):
    R = relevant(gold)
    return len(set(order[:k]) & R) / len(R)

def reciprocal_rank(order, gold):
    for rank, i in enumerate(order, 1):
        if chunks[i]["page"] in gold:
            return 1 / rank
    return 0.0

def ndcg_at_k(order, gold, k=5):
    dcg = sum(1 / math.log2(rank + 1)
              for rank, i in enumerate(order[:k], 1) if chunks[i]["page"] in gold)
    ideal = sum(1 / math.log2(rank + 1) for rank in range(1, min(len(relevant(gold)), k) + 1))
    return dcg / ideal
q, gold = TESTS[9]
order = dense(q)
print(q, gold, "→ pages", [chunks[i]["page"] for i in order[:5]])
print("Recall@5", recall_at_k(order, gold), "· RR", reciprocal_rank(order, gold),
      "· NDCG@5", round(ndcg_at_k(order, gold), 2))
What analogy does the textbook use to explain RAG? {295} → pages [296, 295, 305, 310, 309]
Recall@5 1.0 · RR 0.5 · NDCG@5 0.63
SYSTEMS = {
    "dense":           dense,
    "BM25":            bm25_rank,
    "hybrid (RRF)":    lambda q: rrf([dense(q), bm25_rank(q)]),
    "dense + re-rank": lambda q: rerank(q, dense(q)),
    "HyDE + re-rank":  lambda q: rerank(q, hyde(q)),
}

# ✏️ TODO 4 (▶ วิดีโอ 4:13): MRR คือค่าเฉลี่ยของ reciprocal rank บนทุกคำถาม

def measure(name, system):
    with ThreadPoolExecutor(5) as pool:
        orders = list(pool.map(system, [q for q, _ in TESTS]))
    golds = [g for _, g in TESTS]
    recall = np.mean([recall_at_k(o, g) for o, g in zip(orders, golds)])
    mrr = ___
    ndcg = np.mean([ndcg_at_k(o, g) for o, g in zip(orders, golds)])
    print(f"{name:16} Recall@5 {recall:.2f}   MRR {mrr:.2f}   NDCG@5 {ndcg:.2f}")

for name, system in SYSTEMS.items():
    measure(name, system)
SYSTEMS = {
    "dense":           dense,
    "BM25":            bm25_rank,
    "hybrid (RRF)":    lambda q: rrf([dense(q), bm25_rank(q)]),
    "dense + re-rank": lambda q: rerank(q, dense(q)),
    "HyDE + re-rank":  lambda q: rerank(q, hyde(q)),
}

def measure(name, system):
    with ThreadPoolExecutor(5) as pool:
        orders = list(pool.map(system, [q for q, _ in TESTS]))
    golds = [g for _, g in TESTS]
    recall = np.mean([recall_at_k(o, g) for o, g in zip(orders, golds)])
    mrr = np.mean([reciprocal_rank(o, g) for o, g in zip(orders, golds)])
    ndcg = np.mean([ndcg_at_k(o, g) for o, g in zip(orders, golds)])
    print(f"{name:16} Recall@5 {recall:.2f}   MRR {mrr:.2f}   NDCG@5 {ndcg:.2f}")

for name, system in SYSTEMS.items():
    measure(name, system)
dense            Recall@5 0.53   MRR 0.51   NDCG@5 0.43
BM25             Recall@5 0.33   MRR 0.44   NDCG@5 0.28
hybrid (RRF)     Recall@5 0.51   MRR 0.65   NDCG@5 0.47
dense + re-rank  Recall@5 0.53   MRR 0.78   NDCG@5 0.56
HyDE + re-rank   Recall@5 0.58   MRR 0.83   NDCG@5 0.61

3. ตัววัดฝั่งคำตอบ (§16.8.2)

\[\text{Faithfulness}=\frac{\#\,\text{claims supported by context}}{\#\,\text{total claims in answer}}\;(16.26)\qquad \text{AnswerRelevance}=\frac{1}{N}\sum_{i=1}^{N}\cos\big(E(q),E(\hat q_i)\big)\;(16.27)\]

ทั้งสองใช้ LLM judge — ไม่ต้องมีคำตอบที่ถูก (reference-free) แบบเดียวกับ RAGAs (Listing 16.12) เราเพิ่ม correctness: เทียบกับคำตอบอ้างอิง (ground_truth ใน RAGAs)

CLAIMS = obj(claims={"type": "array", "items": TEXT})
def claims_of(answer):
    return ask_json("Break this answer into short, standalone factual claims. If the answer only says that "
                    f"the context lacks the information, return an empty list.\n\nAnswer:\n{answer}", CLAIMS)["claims"]

SUPPORT = obj(reasoning=TEXT, supported={"type": "boolean"})
def supported(claim, docs):
    context = "\n\n".join(f"(page {d['page']}) {d['text']}" for d in docs)
    return ask_json(f"Context:\n{context}\n\nClaim: {claim}\n\nDoes the context support this claim?",
                    SUPPORT)["supported"]

# ✏️ TODO 5 (▶ วิดีโอ 5:41): สัดส่วนของ claim ที่ได้ True (จำนวนที่มีหลักฐาน ÷ จำนวนทั้งหมด)

def faithfulness(answer, docs):
    claims = claims_of(answer)
    if not claims:
        return None, []
    marks = [supported(c, docs) for c in claims]
    return ___, list(zip(claims, marks))

Q3 = obj(q1=TEXT, q2=TEXT, q3=TEXT)
def answer_relevance(question, answer):
    qs = list(ask_json(f"Write three different questions that this answer would answer.\n\nAnswer:\n{answer}",
                       Q3).values())
    V = embed([question] + qs)
    return float(np.mean(V[1:] @ V[0]))

VERDICT = obj(reasoning=TEXT, correct={"type": "boolean"})
def correct(question, answer, reference):
    return ask_json(f"Question: {question}\nReference answer: {reference}\nAnswer: {answer}\n\n"
                    "Does the answer agree with the reference answer?", VERDICT)["correct"]
CLAIMS = obj(claims={"type": "array", "items": TEXT})
def claims_of(answer):
    return ask_json("Break this answer into short, standalone factual claims. If the answer only says that "
                    f"the context lacks the information, return an empty list.\n\nAnswer:\n{answer}", CLAIMS)["claims"]

SUPPORT = obj(reasoning=TEXT, supported={"type": "boolean"})
def supported(claim, docs):
    context = "\n\n".join(f"(page {d['page']}) {d['text']}" for d in docs)
    return ask_json(f"Context:\n{context}\n\nClaim: {claim}\n\nDoes the context support this claim?",
                    SUPPORT)["supported"]

def faithfulness(answer, docs):
    claims = claims_of(answer)
    if not claims:
        return None, []
    marks = [supported(c, docs) for c in claims]
    return sum(marks) / len(marks), list(zip(claims, marks))

Q3 = obj(q1=TEXT, q2=TEXT, q3=TEXT)
def answer_relevance(question, answer):
    qs = list(ask_json(f"Write three different questions that this answer would answer.\n\nAnswer:\n{answer}",
                       Q3).values())
    V = embed([question] + qs)
    return float(np.mean(V[1:] @ V[0]))

VERDICT = obj(reasoning=TEXT, correct={"type": "boolean"})
def correct(question, answer, reference):
    return ask_json(f"Question: {question}\nReference answer: {reference}\nAnswer: {answer}\n\n"
                    "Does the answer agree with the reference answer?", VERDICT)["correct"]
question = ("In Roitman's book The Hitchhiker's Guide to Agentic AI, "
            "what analogy does the RAG chapter use to explain RAG?")
REFERENCE = "A library card: RAG gives a scholar who memorized a library years ago a card to look things up."
plain3 = [chunks[i] for i in dense(question)[:3]]
reranked3 = [chunks[i] for i in rerank(question, dense(question))[:3]]

SYSTEM_PROMPT = """You are a helpful assistant. Answer the question using ONLY
the provided context. If the context does not contain enough information,
say so explicitly. Cite your sources using [Doc N] notation."""
def rag_answer(query, docs):
    context = "\n\n".join(f"[Doc {i+1}] (Source: {c['source']}, Page: {c['page']})\n{c['text']}"
                          for i, c in enumerate(docs))
    return ask(f"{SYSTEM_PROMPT}\n\nContext:\n{context}\n\nQuestion: {query}\n\nAnswer:")

cases = {"no RAG":               (ask(question),                 reranked3),
         "RAG, plain top 3":     (rag_answer(question, plain3),    plain3),
         "RAG, re-ranked top 3": (rag_answer(question, reranked3), reranked3)}
faith = {name: faithfulness(answer, docs) for name, (answer, docs) in cases.items()}
f, marks = faith["no RAG"]
for claim, ok in marks:
    print("✓" if ok else "✗", claim[:100])
print("faithfulness", round(f, 2))
✗ Roitman wrote a book titled *The Hitchhiker's Guide to Agentic AI*.
✗ The chapter on Retrieval-Augmented Generation (RAG) in Roitman's book uses the analogy of an open-bo
✓ In the RAG analogy, the Large Language Model (LLM) is compared to a student taking an exam.
✓ In the RAG analogy, the RAG process is compared to a student being allowed to use a textbook or refe
✓ The LLM has internalized knowledge from its training.
✓ An LLM may forget specific details or lack access to recent information.
✓ Providing retrieved documents is equivalent to providing a student with a textbook.
✓ Using retrieved documents allows the LLM to look up specific facts to ensure answers are accurate, g
✓ Relying solely on memory can lead to hallucinations in an LLM.
faithfulness 0.78
for name, (answer, docs) in cases.items():
    f, _ = faith[name]
    print(f"{name:21} faithfulness {'—' if f is None else f'{f:.2f}':>5}   "
          f"relevance {answer_relevance(question, answer):.2f}   "
          f"correct {correct(question, answer, REFERENCE)}")
no RAG                faithfulness  0.78   relevance 0.74   correct False
RAG, plain top 3      faithfulness  0.67   relevance 0.83   correct False
RAG, re-ranked top 3  faithfulness  1.00   relevance 0.73   correct True
print({k: f"${v:.4f}" for k, v in COST.items()})
{'chat': '$0.0044', 'embed': '$0.0005', 'rerank': '$0.0672'}

สรุป

ตัววัด ตอบคำถามว่า ที่เราเห็นใน lab
Recall@5 ค้นได้ชิ้นที่ถูกครบแค่ไหน ราว 0.5 แทบทุกระบบ — re-ranking ไม่ได้หาชิ้นใหม่
MRR ชิ้นที่ถูกชิ้นแรกอยู่สูงแค่ไหน dense ≈ 0.5 → HyDE + re-rank ≈ 0.8
NDCG@5 ชิ้นที่ถูกอยู่ใกล้ด้านบนไหม ไต่ขึ้นแบบเดียวกับ MRR
Faithfulness คำตอบมีหลักฐานจากเอกสารไหม ไม่มี RAG ≈ 0.7–0.8 ทั้งที่ข้อหลักผิด · re-rank ≈ 1 · คำตอบปฏิเสธ: วัดไม่ได้ หรือได้ ≈ 0.7 · judge เองก็ผิดได้
Answer relevance คำตอบตรงประเด็นไหม ทั้งสามแบบ 0.7–0.9 — แยกไม่ออก
Correctness ถูกไหม (ต้องมีคำตอบอ้างอิง) ถูกแค่แบบ re-rank

ไม่มีตัววัดตัวเดียวที่พอ — ตรงกับที่ตำราเตือนว่าอย่า optimize ระดับเดียว

แบบฝึกหัด

  1. เขียน Precision@K (สมการ 16.23) แล้วเพิ่มเป็นคอลัมน์ที่สี่ — ระบบไหนได้สูงสุด
  2. วัด agent ของ Lab 2 ด้วย faithfulness และ correctness บนคำถาม 5 ข้อ เทียบกับ RAG ธรรมดา — คุ้มกับจำนวนครั้งที่เรียก model ไหม
  3. ลอง RAGAs (Listing 16.12) กับคำตอบสามแบบเดียวกัน — ได้ตัวเลขใกล้กับของเราไหม

ถัดไป — Lab 4: สร้าง agent ตัวเดียวกับ Lab 2 ด้วย LangGraph