MathTutor / backend /routers /explain.py
rsreenivasa's picture
Testing changes
c12625f
Raw History Blame Contribute Delete
2.42 kB
import logging
from fastapi import APIRouter, Depends
from fastapi.responses import StreamingResponse
from backend.core.auth import get_current_user
from backend.models.explain import ExplainRequest
from backend.core.config import settings
from backend.services import claude_service, prompt_templates, supabase_service
router = APIRouter(prefix="/api", tags=["explain"])
logger = logging.getLogger(__name__)
@router.post("/explain")
async def explain(
body: ExplainRequest,
user: dict = Depends(get_current_user),
):
"""
Stream a grade-appropriate explanation for the student's math query.
Also creates a session record in Supabase and returns session_id in headers.
"""
system = prompt_templates.explanation_system(body.grade)
user_msg = prompt_templates.explanation_user(body.query)
# Collect full explanation for DB storage while streaming to client
full_text_parts: list[str] = []
async def generate():
try:
async for chunk in claude_service.stream(system, user_msg):
full_text_parts.append(chunk)
yield chunk
except Exception as e:
# Avoid terminating the HTTP chunked stream mid-flight.
logger.exception("Explanation stream failed: %s", e)
provider = settings.llm_provider.strip().lower()
if provider == "ollama":
hint = (
"Please ensure Ollama is running and the model is available "
f"({settings.llm_model}) at {settings.llm_base_url}."
)
else:
hint = "Please verify your Anthropic API key and billing, then try again."
yield (
"\n\nSorry, I could not generate the explanation right now. "
+ hint
)
return
# After successful stream — save session to Supabase
full_text = "".join(full_text_parts).strip()
if full_text:
supabase_service.create_session(
user_id=user["id"],
topic=_extract_topic(body.query),
grade=body.grade,
explanation=full_text,
)
return StreamingResponse(generate(), media_type="text/plain")
def _extract_topic(query: str) -> str:
"""Simple topic extraction — first 80 chars of query as topic label."""
return query[:80].strip()