-
Notifications
You must be signed in to change notification settings - Fork 0
Feature/pyq solver #4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
f5b545c
feat: implement Phase 4 - PYQ Solver with SSE streaming and Chat UI
shubhamxdd d6f1b4e
fix: update model in stream_chat method and add pgadmin volume in doc…
shubhamxdd 47aff4c
feat: add file viewing button to resources and solver pages
shubhamxdd 158adf2
fix: resolve syntax error and broken JSX in Solver.tsx
shubhamxdd 5e42a11
feat: implement 'Stop Processing' feature for resources
shubhamxdd f98cd21
feat: improve worker reliability, add confirmation alerts, and file r…
shubhamxdd 59fd21b
fix: enforce 12-page limit at upload and improve worker abort logic
shubhamxdd 9caf21e
feat: implement multi-session chat with history and persistent UI
shubhamxdd 718dcc8
feat: implement collapsible sidebar and chat session renaming
shubhamxdd 3e75e83
fix: provide explicit name for foreign key in alembic migration
shubhamxdd 6333577
fix: raise RuntimeError for non-200 responses in LLM client
shubhamxdd f5849ed
fix: remove delete-orphan cascade from chat session questions
shubhamxdd 534c2e0
fix: only mark resource as failed if current status is processing
shubhamxdd 3f01d52
fix: verify chat session ownership in ask_question endpoint
shubhamxdd c1d206e
fix: persist delivery_mode from request in ask_question endpoint
shubhamxdd b105df8
fix: address remaining CodeRabbit audit findings for data integrity a…
shubhamxdd dd75fe4
feat: parameterize frontend API URL via environment variables
shubhamxdd File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
46 changes: 46 additions & 0 deletions
46
backend/alembic/versions/d3dcf6b6fe3f_add_chat_sessions_and_processing_.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| """add chat sessions and processing progress | ||
|
|
||
| Revision ID: d3dcf6b6fe3f | ||
| Revises: 9f2c76932a93 | ||
| Create Date: 2026-05-17 16:07:40.708352 | ||
|
|
||
| """ | ||
| from typing import Sequence, Union | ||
|
|
||
| from alembic import op | ||
| import sqlalchemy as sa | ||
|
|
||
|
|
||
| # revision identifiers, used by Alembic. | ||
| revision: str = 'd3dcf6b6fe3f' | ||
| down_revision: Union[str, Sequence[str], None] = '9f2c76932a93' | ||
| branch_labels: Union[str, Sequence[str], None] = None | ||
| depends_on: Union[str, Sequence[str], None] = None | ||
|
|
||
|
|
||
| def upgrade() -> None: | ||
| """Upgrade schema.""" | ||
| # ### commands auto generated by Alembic - please adjust! ### | ||
| op.create_table('chat_sessions', | ||
| sa.Column('id', sa.UUID(), nullable=False), | ||
| sa.Column('user_id', sa.UUID(), nullable=False), | ||
| sa.Column('title', sa.String(), nullable=True), | ||
| sa.Column('created_at', sa.DateTime(), nullable=True), | ||
| sa.Column('updated_at', sa.DateTime(), nullable=True), | ||
| sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'), | ||
| sa.PrimaryKeyConstraint('id') | ||
| ) | ||
| op.add_column('questions', sa.Column('session_id', sa.UUID(), nullable=True)) | ||
| op.create_foreign_key('fk_questions_session_id_chat_sessions', 'questions', 'chat_sessions', ['session_id'], ['id'], ondelete='CASCADE') | ||
| op.add_column('resources', sa.Column('processing_progress', sa.Integer(), nullable=True)) | ||
| # ### end Alembic commands ### | ||
|
|
||
|
|
||
| def downgrade() -> None: | ||
| """Downgrade schema.""" | ||
| # ### commands auto generated by Alembic - please adjust! ### | ||
| op.drop_column('resources', 'processing_progress') | ||
| op.drop_constraint('fk_questions_session_id_chat_sessions', 'questions', type_='foreignkey') | ||
| op.drop_column('questions', 'session_id') | ||
| op.drop_table('chat_sessions') | ||
| # ### end Alembic commands ### |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| import json | ||
| import httpx | ||
| from typing import AsyncGenerator | ||
| from ..config import settings | ||
|
|
||
| class OpenRouterClient: | ||
| def __init__(self): | ||
| self.api_key = settings.OPENROUTER_API_KEY | ||
| self.base_url = "https://openrouter.ai/api/v1/chat/completions" | ||
|
|
||
| async def stream_chat(self, messages: list, model: str = "openrouter/owl-alpha") -> AsyncGenerator[str, None]: | ||
| headers = { | ||
| "Authorization": f"Bearer {self.api_key}", | ||
| "Content-Type": "application/json", | ||
| "HTTP-Referer": settings.FRONTEND_URL, | ||
| "X-Title": "PYQ Solver", | ||
| } | ||
|
|
||
| payload = { | ||
| "model": model, | ||
| "messages": messages, | ||
| "stream": True | ||
| } | ||
|
|
||
| async with httpx.AsyncClient(timeout=120.0) as client: | ||
| async with client.stream("POST", self.base_url, headers=headers, json=payload) as response: | ||
| if response.status_code != 200: | ||
| error_text = await response.aread() | ||
| raise RuntimeError(f"OpenRouter Error: {response.status_code} - {error_text.decode()}") | ||
|
|
||
| async for line in response.aiter_lines(): | ||
| if not line or line == "": | ||
| continue | ||
|
|
||
| if line.startswith("data: "): | ||
| data_str = line[6:] | ||
| if data_str == "[DONE]": | ||
| break | ||
|
|
||
| try: | ||
| data = json.loads(data_str) | ||
| chunk = data['choices'][0]['delta'].get('content', "") | ||
| if chunk: | ||
| yield chunk | ||
| except Exception: | ||
| continue | ||
|
|
||
| open_router_client = OpenRouterClient() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| SOLVER_SYSTEM = """ | ||
| You are an expert academic tutor helping a student understand a question from their study materials. | ||
|
|
||
| You are given relevant excerpts from the student's own documents as context. | ||
| Answer the question using ONLY the provided context. | ||
|
|
||
| Rules: | ||
| - Be clear, structured, and student-friendly. | ||
| - Use markdown for formatting: headings (###), bold, and bullet points. | ||
| - If the context does not contain enough information to answer the question, say so honestly. Do not make up information. | ||
| - Provide a concise answer first, followed by a more detailed explanation if helpful. | ||
| - Cite the source filename when referencing specific points. | ||
| - DO NOT add information that is not present in the provided context. | ||
| """ | ||
|
|
||
| SOLVER_USER_TEMPLATE = """ | ||
| Context from student materials: | ||
| {context} | ||
|
|
||
| Question: | ||
| {question} | ||
| """ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| from sqlalchemy import Column, String, DateTime, UUID, ForeignKey | ||
| from sqlalchemy.orm import relationship | ||
| from datetime import datetime | ||
| import uuid | ||
| from .base import Base | ||
|
|
||
| class ChatSession(Base): | ||
| __tablename__ = "chat_sessions" | ||
|
|
||
| id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) | ||
| user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False) | ||
| title = Column(String, default="New Chat") | ||
| created_at = Column(DateTime, default=datetime.utcnow) | ||
| updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) | ||
|
|
||
| user = relationship("User", back_populates="chat_sessions") | ||
| questions = relationship("Question", back_populates="session", cascade="all") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
🏁 Script executed:
Repository: shubhamxdd/pyq-appl
Length of output: 119
🏁 Script executed:
Repository: shubhamxdd/pyq-appl
Length of output: 92
🏁 Script executed:
Repository: shubhamxdd/pyq-appl
Length of output: 928
🏁 Script executed:
cat -n backend/app/llm/client.py | head -80Repository: shubhamxdd/pyq-appl
Length of output: 2237
🏁 Script executed:
rg "class.*Client" backend/app/llm/client.py -A 5Repository: shubhamxdd/pyq-appl
Length of output: 350
🏁 Script executed:
rg "stream_chat" backend/ -B 3 -A 15Repository: shubhamxdd/pyq-appl
Length of output: 2865
🏁 Script executed:
rg "stream_chat" backend/ -B 2 -A 10Repository: shubhamxdd/pyq-appl
Length of output: 1942
🏁 Script executed:
Repository: shubhamxdd/pyq-appl
Length of output: 234
🏁 Script executed:
Repository: shubhamxdd/pyq-appl
Length of output: 45
🏁 Script executed:
Repository: shubhamxdd/pyq-appl
Length of output: 2465
🏁 Script executed:
rg "def event_generator" backend/app/routers/solver.py -A 40Repository: shubhamxdd/pyq-appl
Length of output: 1304
Narrow exception handling to distinguish protocol errors from schema mismatches.
The bare
except Exception: continuesilently drops malformed frames, allowing truncated responses to be markedstatus="done"upstream. If a frame fails to parse, it's lost silently rather than surfacing the error. Distinguish JSON parse failures (which should be skipped) from unexpected schema structure (which should fail the answer):📝 Committable suggestion
🧰 Tools
🪛 Ruff (0.15.12)
[error] 45-46:
try-except-continuedetected, consider logging the exception(S112)
[warning] 45-45: Do not catch blind exception:
Exception(BLE001)
🤖 Prompt for AI Agents