File size: 7,576 Bytes
d6c4a0f
 
 
 
 
 
 
 
 
 
 
9b23490
 
 
 
 
 
d6c4a0f
 
 
 
 
9b23490
d6c4a0f
 
 
 
 
9b23490
d6c4a0f
9b23490
 
 
 
d6c4a0f
 
9b23490
d6c4a0f
 
 
 
9b23490
d6c4a0f
 
9b23490
 
d6c4a0f
 
 
 
9b23490
 
 
 
 
 
 
 
 
 
 
d6c4a0f
39f146b
 
d6c4a0f
9b23490
d6c4a0f
 
 
 
 
 
 
 
 
 
 
 
9b23490
d6c4a0f
9b23490
 
d6c4a0f
 
 
 
 
 
 
 
 
9b23490
d6c4a0f
 
 
 
 
 
 
 
 
39f146b
d6c4a0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39f146b
 
 
d6c4a0f
39f146b
 
 
 
 
 
 
 
 
 
 
d6c4a0f
 
 
 
 
 
 
9b23490
 
 
d6c4a0f
 
9b23490
d6c4a0f
 
 
 
 
 
 
9b23490
d6c4a0f
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
from __future__ import annotations
import os
import json
from typing import List, Dict, Any
import requests

# ===== Anthropic (Claude 3) config =====
ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY", "").strip()
ANTHROPIC_MODEL = os.getenv("ANTHROPIC_MODEL", "claude-3-haiku-20240307").strip()


def _build_prompt(
    slides: List[str],
    n_questions: int,
    level: str,
    q_types: List[str],
) -> str:
    """
    รวมเนื้อหาจากสไลด์แล้วสร้างคำสั่งให้ LLM สร้างข้อสอบ MCQ
    """
    text = "\n\n".join(slides[:5])  # กัน prompt ยาวเกิน เอาแค่ไม่กี่สไลด์บน ๆ
    level_th = {"easy": "ง่าย", "medium": "ปานกลาง", "hard": "ยาก"}.get(level, "ปานกลาง")
    types_str = ", ".join(q_types) if q_types else "MCQ"

    prompt = f"""
คุณเป็นระบบสร้างข้อสอบอัตโนมัติ (quiz generator)

- อ่านเนื้อหาด้านล่าง (อาจเป็นภาษาอังกฤษหรือภาษาไทย)
- สร้างข้อสอบจำนวนไม่เกิน {n_questions} ข้อ
- ระดับความยาก {level_th}
- ประเภทคำถามที่สามารถใช้ได้: {types_str}
  * "CLOZE" = เติมคำในช่องว่าง (question ต้องมี "____" อย่างน้อย 1 ตำแหน่ง)
  * "T/F"   = True / False (options ต้องเป็น ["True","False"])
  * "MCQ"   = Multiple choice 4 ตัวเลือก

รูปแบบคำตอบ: ให้ตอบกลับมาเป็น JSON เท่านั้น ห้ามเขียนคำอธิบายอื่น
โครงสร้าง JSON:

{{
  "questions": [
    {{
      "type": "CLOZE" | "T/F" | "MCQ",
      "question": "string",
      "answer": "correct answer string",
      "options": ["opt1", "opt2", "opt3", "opt4"],
      "explanation": "short explanation (optional, อาจเป็นสตริงว่างได้)"
    }}
  ]
}}

กติกาเพิ่มเติม:
- "type" ต้องเป็นหนึ่งใน {types_str}
- สำหรับ "CLOZE":
  - "question" ต้องมี "____" เป็นช่องว่าง
  - "options" มี 4 ตัวเลือก และมีคำตอบที่ถูกต้องเพียง 1 ตัว
- สำหรับ "T/F":
  - "options" ต้องเป็น ["True","False"] เท่านั้น
  - "answer" ต้องเป็น "True" หรือ "False"
- สำหรับ "MCQ":
  - "options" ควรมี 4 ตัวเลือก (ถ้าขาดให้เติมจนเป็น 4)
- ห้ามใส่ข้อความอธิบายอื่นนอกเหนือจาก JSON
- เนื้อหาคำถามต้องมาจากข้อมูลด้านล่างเท่านั้น ห้ามมั่ว
- ตรวจสอบให้แน่ใจว่า JSON สมบูรณ์และปิดวงเล็บครบทุกอัน ก่อนส่งคำตอบ
- ถ้าตอบได้ไม่ครบ {n_questions} ข้อ ให้ตอบเท่าที่ทำได้ แต่ต้องให้ JSON ถูกต้อง 100%


===== CONTENT START =====
{text}
===== CONTENT END =====
""".strip()
    return prompt


def generate_quiz_llm(
    slides: List[str],
    n_questions: int = 10,
    level: str = "medium",
    seed: int = 42,
    q_types: List[str] | None = None,
) -> Dict[str, Any]:
    if not q_types:
        q_types = ["MCQ", "CLOZE", "T/F"]
    """
    เรียก Anthropic Claude 3 ให้สร้างข้อสอบ MCQ
    """
    if not ANTHROPIC_API_KEY:
        raise RuntimeError("ANTHROPIC_API_KEY ยังไม่ถูกตั้งใน environment / .env")

    model = ANTHROPIC_MODEL or "claude-3-haiku-20240307"
    api_url = "https://api.anthropic.com/v1/messages"

    prompt = _build_prompt(slides, n_questions, level, q_types)

    headers = {
        "x-api-key": ANTHROPIC_API_KEY,
        "anthropic-version": "2023-06-01",
        "content-type": "application/json",
    }

    payload: Dict[str, Any] = {
        "model": model,
        "max_tokens": 2048,
        "temperature": 0.7,
        "messages": [
            {
                "role": "user",
                "content": prompt,
            }
        ],
    }

    resp = requests.post(api_url, headers=headers, data=json.dumps(payload), timeout=120)
    try:
        resp.raise_for_status()
    except Exception as e:
        raise RuntimeError(f"Claude API error: {resp.status_code} {resp.text}") from e

    data = resp.json()

    # โครงตอบ Claude 3: {"content": [ {"type": "text", "text": "..."} ], ...}
    try:
        parts = data.get("content", [])
        content_text = "".join(
            str(p.get("text", ""))
            for p in parts
            if isinstance(p, dict) and p.get("type") == "text"
        ).strip()
    except Exception as e:
        raise RuntimeError(f"response จาก Claude ผิดรูปแบบ: {data}") from e

    if not content_text:
        raise RuntimeError(f"ไม่พบข้อความในคำตอบของ Claude: {data}")

    # พยายามดึง JSON ก้อนแรกออกจากข้อความ
    start = content_text.find("{")
    end = content_text.rfind("}")
    if start == -1 or end == -1:
        raise RuntimeError(f"ไม่พบ JSON ในคำตอบของ LLM: {content_text}")

    raw_json = content_text[start: end + 1]

    # พยายาม parse รอบแรก
    try:
        obj = json.loads(raw_json)
    except Exception:
        # ถ้าไม่สำเร็จ ลองตัดหางทิ้งอีกนิด เผื่อท้าย ๆ แตก
        last_brace = raw_json.rfind("}")
        if last_brace != -1:
            try:
                obj = json.loads(raw_json[: last_brace + 1])
            except Exception as e2:
                raise RuntimeError(f"parse JSON จาก LLM ไม่สำเร็จ: {raw_json}") from e2
        else:
            raise RuntimeError(f"parse JSON จาก LLM ไม่สำเร็จ: {raw_json}")

    questions = obj.get("questions", []) or []

    norm_q = []
    for q in questions:
        if not isinstance(q, dict):
            continue
        q_type = str(q.get("type", "MCQ")).upper()
        if q_type not in ("CLOZE", "T/F", "MCQ"):
            q_type = "MCQ"
        norm_q.append(
            {
                "type": q_type,
                "question": str(q.get("question", "")).strip(),
                "answer": str(q.get("answer", "")).strip(),
                "options": [
                    str(o).strip()
                    for o in q.get("options", [])
                    if isinstance(o, (str, int, float))
                ],
                "explanation": str(q.get("explanation", "") or "").strip(),
            }
        )

    return {
        "questions": norm_q,
        "qc_report": {
            "engine": "LLM (Claude 3)",
            "requested": n_questions,
            "generated": len(norm_q),
            "level": level,
        },
    }