QuizGen / src /utils /utils_quiz_llm.py
pluem9
cloze/TF
9b23490
Raw History Blame Contribute Delete
7.58 kB
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,
},
}