Spaces:
Sleeping
Sleeping
Commit
·
aa43da8
1
Parent(s):
4b7eb7e
Upd api endpoint from chat to session/chat
Browse files- src/api/routes/account.py +22 -10
- src/models/session.py +1 -0
- static/js/app.js +50 -23
src/api/routes/account.py
CHANGED
|
@@ -11,23 +11,16 @@ router = APIRouter(prefix="/account", tags=["Account"])
|
|
| 11 |
|
| 12 |
|
| 13 |
@router.get("", response_model=list[Account])
|
| 14 |
-
async def
|
| 15 |
-
q: str | None = None,
|
| 16 |
limit: int = 50,
|
| 17 |
state: AppState = Depends(get_state)
|
| 18 |
):
|
| 19 |
"""
|
| 20 |
Retrieves a list of all accounts.
|
| 21 |
-
Optionally, filters accounts by a search query 'q'.
|
| 22 |
"""
|
| 23 |
try:
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
accounts = state.memory_manager.search_accounts(q, limit=limit)
|
| 27 |
-
else:
|
| 28 |
-
logger().info(f"GET /account limit={limit}")
|
| 29 |
-
accounts = state.memory_manager.get_all_accounts(limit=limit)
|
| 30 |
-
|
| 31 |
logger().info(f"Retrieved {len(accounts)} accounts")
|
| 32 |
return accounts
|
| 33 |
except ActionFailed as e:
|
|
@@ -35,6 +28,25 @@ async def search_or_get_all_accounts(
|
|
| 35 |
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="A database error occurred.")
|
| 36 |
|
| 37 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
@router.post("", response_model=Account, status_code=status.HTTP_201_CREATED)
|
| 39 |
async def create_account_profile(
|
| 40 |
req: AccountCreateRequest,
|
|
|
|
| 11 |
|
| 12 |
|
| 13 |
@router.get("", response_model=list[Account])
|
| 14 |
+
async def get_all_accounts(
|
|
|
|
| 15 |
limit: int = 50,
|
| 16 |
state: AppState = Depends(get_state)
|
| 17 |
):
|
| 18 |
"""
|
| 19 |
Retrieves a list of all accounts.
|
|
|
|
| 20 |
"""
|
| 21 |
try:
|
| 22 |
+
logger().info(f"GET /account limit={limit}")
|
| 23 |
+
accounts = state.memory_manager.get_all_accounts(limit=limit)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
logger().info(f"Retrieved {len(accounts)} accounts")
|
| 25 |
return accounts
|
| 26 |
except ActionFailed as e:
|
|
|
|
| 28 |
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="A database error occurred.")
|
| 29 |
|
| 30 |
|
| 31 |
+
@router.get("/search", response_model=list[Account])
|
| 32 |
+
async def search_accounts(
|
| 33 |
+
q: str,
|
| 34 |
+
limit: int = 50,
|
| 35 |
+
state: AppState = Depends(get_state)
|
| 36 |
+
):
|
| 37 |
+
"""
|
| 38 |
+
Searches for accounts by name.
|
| 39 |
+
"""
|
| 40 |
+
try:
|
| 41 |
+
logger().info(f"GET /account/search?q='{q}' limit={limit}")
|
| 42 |
+
accounts = state.memory_manager.search_accounts(q, limit=limit)
|
| 43 |
+
logger().info(f"Retrieved {len(accounts)} accounts")
|
| 44 |
+
return accounts
|
| 45 |
+
except ActionFailed as e:
|
| 46 |
+
logger().error(f"Database error while searching accounts: {e}")
|
| 47 |
+
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="A database error occurred.")
|
| 48 |
+
|
| 49 |
+
|
| 50 |
@router.post("", response_model=Account, status_code=status.HTTP_201_CREATED)
|
| 51 |
async def create_account_profile(
|
| 52 |
req: AccountCreateRequest,
|
src/models/session.py
CHANGED
|
@@ -40,6 +40,7 @@ class ChatRequest(BaseModel):
|
|
| 40 |
account_id: str # For context, though session_id implies this
|
| 41 |
patient_id: str # For context, though session_id implies this
|
| 42 |
message: str
|
|
|
|
| 43 |
|
| 44 |
# --- API Response Models ---
|
| 45 |
|
|
|
|
| 40 |
account_id: str # For context, though session_id implies this
|
| 41 |
patient_id: str # For context, though session_id implies this
|
| 42 |
message: str
|
| 43 |
+
session_id: str | None = None # Optional session ID for continuing existing sessions
|
| 44 |
|
| 45 |
# --- API Response Models ---
|
| 46 |
|
static/js/app.js
CHANGED
|
@@ -1709,25 +1709,8 @@ How can I assist you today?`;
|
|
| 1709 |
this.addMessage('user', message);
|
| 1710 |
this.showLoading(true);
|
| 1711 |
try {
|
| 1712 |
-
const isNewSession = this.currentSession && this.currentSession.id === 'default';
|
| 1713 |
const responseData = await this.callMedicalAPI(message);
|
| 1714 |
|
| 1715 |
-
if (isNewSession && responseData.session_id) {
|
| 1716 |
-
console.log(`[DEBUG] New session created on backend. Updating session ID from 'default' to '${responseData.session_id}'`);
|
| 1717 |
-
const oldId = this.currentSession.id;
|
| 1718 |
-
this.currentSession.id = responseData.session_id;
|
| 1719 |
-
|
| 1720 |
-
// Update the session ID in the locally stored array
|
| 1721 |
-
const sessions = this.getChatSessions();
|
| 1722 |
-
const sessionIndex = sessions.findIndex(s => s.id === oldId);
|
| 1723 |
-
if (sessionIndex !== -1) {
|
| 1724 |
-
sessions[sessionIndex].id = this.currentSession.id;
|
| 1725 |
-
localStorage.setItem(`chatSessions_${this.currentUser.id}`, JSON.stringify(sessions));
|
| 1726 |
-
}
|
| 1727 |
-
// Re-render the session list to reflect the new ID
|
| 1728 |
-
this.loadChatSessions();
|
| 1729 |
-
}
|
| 1730 |
-
|
| 1731 |
this.addMessage('assistant', responseData.response || 'I apologize, but I received an empty response. Please try again.');
|
| 1732 |
this.updateCurrentSession();
|
| 1733 |
|
|
@@ -1750,18 +1733,24 @@ How can I assist you today?`;
|
|
| 1750 |
|
| 1751 |
callMedicalAPI = async function (message) {
|
| 1752 |
try {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1753 |
const payload = {
|
| 1754 |
account_id: this.currentUser.id,
|
| 1755 |
patient_id: this.currentPatientId,
|
| 1756 |
message: message
|
| 1757 |
};
|
| 1758 |
|
| 1759 |
-
|
| 1760 |
-
if (this.currentSession?.id && this.currentSession.id !== 'default') {
|
| 1761 |
-
payload.session_id = this.currentSession.id;
|
| 1762 |
-
}
|
| 1763 |
-
|
| 1764 |
-
const response = await fetch('/chat', {
|
| 1765 |
method: 'POST',
|
| 1766 |
headers: { 'Content-Type': 'application/json' },
|
| 1767 |
body: JSON.stringify(payload)
|
|
@@ -1785,6 +1774,44 @@ How can I assist you today?`;
|
|
| 1785 |
}
|
| 1786 |
}
|
| 1787 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1788 |
generateMockResponse(message) {
|
| 1789 |
const responses = [
|
| 1790 |
"Based on your question about medical topics, I can provide general information. However, please remember that this is for educational purposes only and should not replace professional medical advice.",
|
|
|
|
| 1709 |
this.addMessage('user', message);
|
| 1710 |
this.showLoading(true);
|
| 1711 |
try {
|
|
|
|
| 1712 |
const responseData = await this.callMedicalAPI(message);
|
| 1713 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1714 |
this.addMessage('assistant', responseData.response || 'I apologize, but I received an empty response. Please try again.');
|
| 1715 |
this.updateCurrentSession();
|
| 1716 |
|
|
|
|
| 1733 |
|
| 1734 |
callMedicalAPI = async function (message) {
|
| 1735 |
try {
|
| 1736 |
+
let sessionId = this.currentSession?.id;
|
| 1737 |
+
|
| 1738 |
+
// If no session or default session, create a new one first
|
| 1739 |
+
if (!sessionId || sessionId === 'default') {
|
| 1740 |
+
console.log('[DEBUG] Creating new session before sending message');
|
| 1741 |
+
sessionId = await this.createNewSession();
|
| 1742 |
+
if (!sessionId) {
|
| 1743 |
+
throw new Error('Failed to create new session');
|
| 1744 |
+
}
|
| 1745 |
+
}
|
| 1746 |
+
|
| 1747 |
const payload = {
|
| 1748 |
account_id: this.currentUser.id,
|
| 1749 |
patient_id: this.currentPatientId,
|
| 1750 |
message: message
|
| 1751 |
};
|
| 1752 |
|
| 1753 |
+
const response = await fetch(`/session/${sessionId}/messages`, {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1754 |
method: 'POST',
|
| 1755 |
headers: { 'Content-Type': 'application/json' },
|
| 1756 |
body: JSON.stringify(payload)
|
|
|
|
| 1774 |
}
|
| 1775 |
}
|
| 1776 |
|
| 1777 |
+
createNewSession = async function () {
|
| 1778 |
+
try {
|
| 1779 |
+
const payload = {
|
| 1780 |
+
account_id: this.currentUser.id,
|
| 1781 |
+
patient_id: this.currentPatientId,
|
| 1782 |
+
title: "New Chat"
|
| 1783 |
+
};
|
| 1784 |
+
|
| 1785 |
+
const response = await fetch('/session', {
|
| 1786 |
+
method: 'POST',
|
| 1787 |
+
headers: { 'Content-Type': 'application/json' },
|
| 1788 |
+
body: JSON.stringify(payload)
|
| 1789 |
+
});
|
| 1790 |
+
|
| 1791 |
+
if (!response.ok) {
|
| 1792 |
+
throw new Error(`HTTP error! status: ${response.status}`);
|
| 1793 |
+
}
|
| 1794 |
+
|
| 1795 |
+
const session = await response.json();
|
| 1796 |
+
console.log('[DEBUG] Created new session:', session);
|
| 1797 |
+
|
| 1798 |
+
// Update current session with the new session data
|
| 1799 |
+
this.currentSession = {
|
| 1800 |
+
id: session.id,
|
| 1801 |
+
title: session.title,
|
| 1802 |
+
messages: [],
|
| 1803 |
+
createdAt: session.created_at,
|
| 1804 |
+
lastActivity: new Date().toISOString(),
|
| 1805 |
+
source: 'backend'
|
| 1806 |
+
};
|
| 1807 |
+
|
| 1808 |
+
return session.id;
|
| 1809 |
+
} catch (error) {
|
| 1810 |
+
console.error('Failed to create new session:', error);
|
| 1811 |
+
throw error;
|
| 1812 |
+
}
|
| 1813 |
+
}
|
| 1814 |
+
|
| 1815 |
generateMockResponse(message) {
|
| 1816 |
const responses = [
|
| 1817 |
"Based on your question about medical topics, I can provide general information. However, please remember that this is for educational purposes only and should not replace professional medical advice.",
|