exams-ai / app.py
contactdigoman-source
Reduce Space generation latency on CPU
9f5f686
Raw History Blame Contribute Delete
8.38 kB
import json
import os
import re
import time
from typing import List, Optional
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
from transformers import pipeline
app = FastAPI(title="Exams AI Space")
MODEL_ID = os.getenv("MODEL_ID", "TinyLlama/TinyLlama-1.1B-Chat-v1.0")
_GENERATOR = None
_MODEL_ERROR = None
def _load_generator():
global _GENERATOR, _MODEL_ERROR
if _GENERATOR is not None or _MODEL_ERROR is not None:
return
try:
_GENERATOR = pipeline(
"text-generation",
model=MODEL_ID,
tokenizer=MODEL_ID,
# HF cpu-basic: force plain CPU path to avoid accelerate meta-tensor dispatch issues.
device=-1,
)
except Exception as exc:
_MODEL_ERROR = str(exc)
class Message(BaseModel):
role: str
content: str
class ChatRequest(BaseModel):
model: str = "local-model"
messages: List[Message]
max_tokens: Optional[int] = 1024
temperature: Optional[float] = 0.4
stream: Optional[bool] = False
@app.get("/")
def health():
_load_generator()
return {
"ok": True,
"service": "exams-ai-space",
"model_id": MODEL_ID,
"model_ready": _GENERATOR is not None and _MODEL_ERROR is None,
"model_error": _MODEL_ERROR,
}
def _extract_context(last_user: str):
answer_key = "unknown"
m = re.search(r"Correct Answer:\s*([A-E](?:\s*,\s*[A-E])*|\S+)", last_user, re.IGNORECASE)
if m:
answer_key = m.group(1).replace(" ", "")
question_context = ""
qm = re.search(r"Question Context:\s*(.+?)\s*Correct Answer:", last_user, re.IGNORECASE | re.DOTALL)
if qm:
question_context = qm.group(1).strip()
elif last_user:
question_context = last_user[:800].strip()
return question_context, answer_key
def _build_tutor_prompt(last_user: str) -> str:
question_context, answer_key = _extract_context(last_user)
return (
"You are an expert exam tutor. Provide concept-rich, topic-specific guidance.\n"
"Use the exact output format below and do not add extra headers.\n\n"
"EXPLANATION:\n"
"WRONG OPTIONS:\n"
"EXAM TIPS:\n\n"
f"Question Context:\n{question_context}\n\n"
f"Correct Answer: {answer_key}\n\n"
"Instructions:\n"
"1) Explain the topic context and why the correct answer is right.\n"
"2) In WRONG OPTIONS, write one line per wrong choice in 'A: ...' style when choices exist.\n"
"3) In EXAM TIPS, give practical bullet points for exam solving.\n"
"4) Keep it concise but meaningful, and stay faithful to the given context."
)
def _fallback_answer(last_user: str) -> str:
question_context, answer_key = _extract_context(last_user)
topics = []
for kw in ["pygmalion", "shaw", "mansfield park", "jane austen", "glass menagerie", "tennessee williams"]:
if kw in question_context.lower():
topics.append(kw.title())
topic_line = ", ".join(topics[:4]) if topics else "the given syllabus context"
return (
"EXPLANATION:\n"
f"The likely correct answer is {answer_key}. This item tests author-work mapping and period awareness in literary studies. "
f"Anchor your reasoning to {topic_line}, then verify each statement one by one instead of guessing from familiar names.\n\n"
"WRONG OPTIONS:\n"
"A: May include a close but incorrect author-work or concept mapping.\n"
"B: Often a plausible distractor from a nearby topic.\n"
"C: Can be partly true but not fully aligned with the stem.\n"
"D: Choose only if it fully satisfies all conditions in the question.\n\n"
"EXAM TIPS:\n"
"- Mark each statement true/false first in assertion or multi-statement items.\n"
"- Trust syllabus pairings for author-work and period mapping questions.\n"
f"- Focus context: {question_context[:220]}"
)
def _looks_low_quality(text: str, question_context: str) -> bool:
t = (text or "").strip().lower()
if not t:
return True
# Common weak/generic drift patterns from small models.
bad_markers = [
"use a clear and concise language",
"proofread your explanation",
"proper grammar and punctuation",
]
if any(b in t for b in bad_markers):
return True
# Must contain structure expected by frontend.
if "explanation:" not in t or "exam tips:" not in t:
return True
# If no overlap with context keywords, answer likely generic.
ctx_words = [w for w in re.findall(r"[a-zA-Z]{5,}", question_context.lower()) if w not in {"question", "context", "correct", "answer"}]
if ctx_words:
overlap = sum(1 for w in set(ctx_words[:20]) if w in t)
if overlap == 0:
return True
return False
def _generate_answer(last_user: str, max_tokens: int, temperature: float) -> str:
_load_generator()
if _GENERATOR is None:
return _fallback_answer(last_user)
question_context, _ = _extract_context(last_user)
prompt = _build_tutor_prompt(last_user)
# Keep generation tightly bounded for CPU-friendly latency.
token_budget = max(96, min(max_tokens or 192, 256))
temp = max(0.1, min(temperature or 0.4, 0.9))
try:
outputs = _GENERATOR(
prompt,
max_new_tokens=token_budget,
do_sample=True,
temperature=temp,
top_p=0.92,
repetition_penalty=1.08,
num_return_sequences=1,
)
raw = outputs[0].get("generated_text", "").strip()
if raw.startswith(prompt):
raw = raw[len(prompt):].strip()
except Exception:
return _fallback_answer(last_user)
# On cpu-basic, skip a second generation pass for latency.
if _looks_low_quality(raw, question_context):
raw = _fallback_answer(last_user)
if "EXPLANATION:" not in raw.upper():
# Enforce parseable structure expected by frontend.
raw = (
"EXPLANATION:\n"
f"{raw}\n\n"
"WRONG OPTIONS:\n"
"A: Not aligned with the complete requirement in the stem.\n"
"B: Distractor from adjacent content area.\n"
"C: Partially related but incorrect in this context.\n\n"
"EXAM TIPS:\n"
"- Compare every option directly against the key phrase in the question."
)
return raw
@app.post("/v1/chat/completions")
def chat(req: ChatRequest):
try:
last_user = ""
for m in req.messages:
if m.role == "user":
last_user = m.content
answer = _generate_answer(
last_user=last_user,
max_tokens=req.max_tokens or 512,
temperature=req.temperature or 0.4,
)
except Exception:
last_user = req.messages[-1].content if req.messages else ""
answer = _fallback_answer(last_user)
if req.stream:
def event_stream():
# OpenAI-compatible SSE chunk stream
chunks = answer.split(" ")
for token in chunks:
payload = {
"id": "chatcmpl-exams-ai-1",
"object": "chat.completion.chunk",
"choices": [
{
"index": 0,
"delta": {"content": token + " "},
"finish_reason": None,
}
],
}
yield f"data: {json.dumps(payload)}\n\n"
time.sleep(0.02)
final_payload = {
"id": "chatcmpl-exams-ai-1",
"object": "chat.completion.chunk",
"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],
}
yield f"data: {json.dumps(final_payload)}\n\n"
yield "data: [DONE]\n\n"
return StreamingResponse(event_stream(), media_type="text/event-stream")
return {
"id": "chatcmpl-exams-ai-1",
"object": "chat.completion",
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": answer},
"finish_reason": "stop",
}
],
}