Skip to content

Commit aad5550

Browse files
authored
Merge pull request #6 from Rayder-23/iteration-5
feat(rag): chatkit
2 parents 569497e + f74d2f8 commit aad5550

46 files changed

Lines changed: 1795 additions & 962 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
---
2+
name: backend-debugging-dependency-resolution
3+
description: Systematic approach to diagnose and resolve backend service issues including dependency conflicts, database schema mismatches, import errors, and middleware configuration problems in FastAPI applications.
4+
---
5+
6+
# Backend Debugging and Dependency Resolution Skill
7+
8+
## Purpose
9+
10+
This skill provides a systematic methodology for diagnosing and resolving backend service issues in FastAPI applications, with particular focus on dependency conflicts, database schema mismatches, import errors, and middleware configuration problems.
11+
12+
## When to Use This Skill
13+
14+
This skill should be used when:
15+
- FastAPI applications fail to start or respond with internal server errors
16+
- Dependency version conflicts arise between FastAPI, Starlette, and related packages
17+
- Database foreign key constraint violations occur
18+
- Import-related errors prevent module loading
19+
- Middleware configuration causes request processing failures
20+
- Authentication or session management systems malfunction
21+
- RAG agent or vector store integration fails
22+
23+
## Implementation Process
24+
25+
### Phase 1: Dependency Conflict Diagnosis
26+
27+
1. **Check version compatibility matrix**
28+
- Identify FastAPI version (e.g., 0.104.1)
29+
- Identify Starlette version and verify compatibility range
30+
- Identify anyio and other dependency versions
31+
- Consult official compatibility documentation
32+
33+
2. **Resolve dependency conflicts**
34+
- Install compatible versions (e.g., Starlette <0.28.0 for FastAPI 0.104.1)
35+
- Pin dependency versions in requirements.txt
36+
- Test with minimal dependency set first
37+
38+
3. **Verify resolution**
39+
- Test basic FastAPI functionality with simple endpoint
40+
- Confirm middleware stack processes requests without errors
41+
- Validate dependency compatibility with test client
42+
43+
### Phase 2: Database Schema Consistency
44+
45+
1. **Identify foreign key mismatches**
46+
- Check error messages for "ForeignKeyViolation" or "constraint violation"
47+
- Compare model definitions with actual database schema
48+
- Identify which table references which in foreign key relationships
49+
50+
2. **Fix relationship inconsistencies**
51+
- Update ForeignKey references to point to correct tables
52+
- Ensure relationship definitions match foreign key constraints
53+
- Update related model relationships accordingly
54+
55+
3. **Apply schema changes**
56+
- Drop and recreate tables if safe to do so (development)
57+
- Use Alembic migrations for production environments
58+
- Verify new relationships work correctly
59+
60+
### Phase 3: Import and Module Structure Resolution
61+
62+
1. **Diagnose import errors**
63+
- Identify missing module errors (e.g., "No module named 'embeddings'")
64+
- Trace import chains to find incorrect paths
65+
- Check for circular imports or namespace pollution
66+
67+
2. **Fix import paths**
68+
- Update import statements to reflect actual module structure
69+
- Use explicit imports instead of wildcard imports
70+
- Ensure all `__init__.py` files properly export required modules
71+
72+
3. **Validate module structure**
73+
- Test individual module imports in isolation
74+
- Verify `__init__.py` files contain proper exports
75+
- Confirm package structure matches import expectations
76+
77+
### Phase 4: Middleware and Configuration Fixes
78+
79+
1. **Diagnose middleware errors**
80+
- Look for "too many values to unpack" errors in middleware context
81+
- Check middleware stack construction and configuration
82+
- Verify middleware compatibility with FastAPI version
83+
84+
2. **Resolve configuration issues**
85+
- Remove conflicting middleware configurations
86+
- Ensure middleware is added in correct order
87+
- Validate middleware parameters and options
88+
89+
### Phase 5: System Integration Verification
90+
91+
1. **Test core components**
92+
- Verify RAG agent functionality with sample queries
93+
- Test authentication endpoints (registration, login, profile)
94+
- Confirm database connectivity and session management
95+
- Validate vector store integration
96+
97+
2. **Validate end-to-end flows**
98+
- Test complete user journey from authentication to content retrieval
99+
- Verify session persistence across requests
100+
- Confirm error handling and fallback mechanisms
101+
102+
## Validation Checklist
103+
104+
Before considering the debugging complete, verify:
105+
106+
- [ ] All dependency version conflicts resolved
107+
- [ ] Database schema consistency achieved
108+
- [ ] Import errors eliminated
109+
- [ ] Middleware configuration fixed
110+
- [ ] Core functionality tested (RAG, auth, sessions)
111+
- [ ] Error handling working properly
112+
- [ ] End-to-end flows functional
113+
- [ ] No regressions introduced
114+
115+
## Critical Indicators
116+
117+
- **Dependency conflicts**: Look for "ValueError: too many values to unpack" in middleware context
118+
- **Schema mismatches**: Check for "ForeignKeyViolation" or "constraint violation" errors
119+
- **Import issues**: Watch for "No module named 'X'" errors
120+
- **Middleware problems**: Monitor for errors in `build_middleware_stack` calls
121+
122+
## Expected Outcomes
123+
124+
Upon successful application of this skill:
125+
- Backend services start without errors
126+
- API endpoints respond with appropriate status codes
127+
- Database operations complete successfully
128+
- Authentication and session management work properly
129+
- RAG agent processes queries and returns responses
130+
- Frontend integration functions correctly
131+
- Error handling provides meaningful feedback

backend/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
"""
2+
Backend package initialization for Physical AI Book Platform
3+
"""

backend/agents/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
from .agent import rag_agent, QueryMode
2+
3+
__all__ = ["rag_agent", "QueryMode"]
Lines changed: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from enum import Enum
88

99
# Import the vector store
10-
from vector_store import vector_store
10+
from data.vector_store import vector_store
1111

1212
# Load environment variables
1313
load_dotenv()
@@ -67,7 +67,7 @@ def __call__(self, query: str, mode: str, selected_text: Optional[str] = None) -
6767
Returns:
6868
Dictionary containing retrieved content and metadata
6969
"""
70-
from embeddings import embeddings_service
70+
from data.embeddings import embeddings_service
7171

7272
try:
7373
# Generate embedding for the query
@@ -274,14 +274,15 @@ def _format_retrieved_content(self, retrieved_items: List[Dict]) -> str:
274274

275275
return full_content
276276

277-
def _call_agent(self, user_query: str, mode: QueryMode, selected_text: Optional[str] = None) -> AgentResponse:
277+
def _call_agent(self, user_query: str, mode: QueryMode, selected_text: Optional[str] = None, conversation_history: Optional[List[Dict[str, str]]] = None) -> AgentResponse:
278278
"""
279279
Call the agent to process a user query
280280
281281
Args:
282282
user_query: The user's question
283283
mode: Query mode (full-book or selected-text)
284284
selected_text: Text selected by user (for selected-text mode)
285+
conversation_history: List of previous messages in the conversation for context
285286
286287
Returns:
287288
AgentResponse with content, citations, and token usage
@@ -315,8 +316,27 @@ def _call_agent(self, user_query: str, mode: QueryMode, selected_text: Optional[
315316
token_usage={}
316317
)
317318

318-
# Create the full prompt
319-
full_prompt = f"""
319+
# Create the full prompt with conversation history if available
320+
if conversation_history:
321+
# Format conversation history
322+
history_text = "Previous conversation:\n"
323+
for msg in conversation_history[-5:]: # Use last 5 messages to avoid token overflow
324+
sender = msg.get("sender_type", "user")
325+
content = msg.get("content", "")
326+
history_text += f"{sender.capitalize()}: {content}\n"
327+
history_text += "\n"
328+
329+
full_prompt = f"""
330+
{history_text}
331+
Question: {user_query}
332+
333+
Context from Physical AI book:
334+
{formatted_context}
335+
336+
Based on the context above and the previous conversation, please answer the user's question. Remember to cite specific sections, chapters, or pages when possible, and only provide information that is grounded in the book content.
337+
"""
338+
else:
339+
full_prompt = f"""
320340
Question: {user_query}
321341
322342
Context from Physical AI book:
@@ -382,21 +402,22 @@ def _call_agent(self, user_query: str, mode: QueryMode, selected_text: Optional[
382402
token_usage={}
383403
)
384404

385-
def process_query(self, user_query: str, mode: QueryMode = QueryMode.FULL_BOOK, selected_text: Optional[str] = None) -> AgentResponse:
405+
def process_query(self, user_query: str, mode: QueryMode = QueryMode.FULL_BOOK, selected_text: Optional[str] = None, conversation_history: Optional[List[Dict[str, str]]] = None) -> AgentResponse:
386406
"""
387407
Process a user query through the RAG agent
388408
389409
Args:
390410
user_query: The user's question
391411
mode: Query mode (full-book or selected-text)
392412
selected_text: Text selected by user (for selected-text mode)
413+
conversation_history: List of previous messages in the conversation for context
393414
394415
Returns:
395416
AgentResponse with content, citations, and token usage
396417
"""
397418
logger.info(f"Processing query in {mode.value} mode: {user_query[:50]}...")
398419

399-
return self._call_agent(user_query, mode, selected_text)
420+
return self._call_agent(user_query, mode, selected_text, conversation_history)
400421

401422
# Create a global instance
402423
rag_agent = RAGAgent(vector_store)

backend/auth/__init__.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
from .models import User, UserProfile
2+
from .services import auth_service
3+
4+
__all__ = ["User", "UserProfile", "auth_service"]
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
1010
from sqlalchemy.orm import Session
1111
from typing import Optional
12-
from database import get_db
12+
from database.database import get_db
1313
from .models import User
1414
from .services import auth_service
1515
from pydantic import BaseModel
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
import bcrypt
1414
import jwt
1515
from .models import User, UserProfile
16-
from database import get_db
16+
from database.database import get_db
1717

1818

1919
class AuthService:

backend/chatkit/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
from .adapter import ChatkitAdapter
2+
3+
__all__ = ["ChatkitAdapter"]

0 commit comments

Comments
 (0)