Spaces:
Runtime error
Runtime error
Commit Β·
af054cd
1
Parent(s): 29a8fdb
working sol only duplicates
Browse files- alembic/versions/108b7295afeb_add_cascade_delete_to_agent_sessions.py +54 -0
- alembic/versions/182d311c1308_change_conversation_id_to_int_and_add_.py +57 -0
- alembic/versions/__pycache__/108b7295afeb_add_cascade_delete_to_agent_sessions.cpython-312.pyc +0 -0
- alembic/versions/__pycache__/182d311c1308_change_conversation_id_to_int_and_add_.cpython-312.pyc +0 -0
- app/__pycache__/main.cpython-312.pyc +0 -0
- app/api/v1/endpoints/__pycache__/agents.cpython-312.pyc +0 -0
- app/api/v1/endpoints/agents.py +24 -16
- app/core/__pycache__/error_handlers.cpython-312.pyc +0 -0
- app/core/error_handlers.py +110 -21
- app/db/models/__pycache__/agent.cpython-312.pyc +0 -0
- app/db/models/__pycache__/conversation.cpython-312.pyc +0 -0
- app/db/models/agent.py +14 -1
- app/db/models/conversation.py +5 -0
- app/main.py +177 -37
- app/schemas/__pycache__/agent.cpython-312.pyc +0 -0
- app/schemas/agent.py +3 -3
- app/services/agents/__pycache__/agent_service.cpython-312.pyc +0 -0
- app/services/agents/agent_service.py +63 -63
alembic/versions/108b7295afeb_add_cascade_delete_to_agent_sessions.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""add cascade delete to agent_sessions conversation FK
|
| 2 |
+
|
| 3 |
+
Revision ID: 108b7295afeb
|
| 4 |
+
Revises: 182d311c1308
|
| 5 |
+
Create Date: 2026-05-09
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from typing import Sequence, Union
|
| 10 |
+
|
| 11 |
+
from alembic import op
|
| 12 |
+
|
| 13 |
+
# revision identifiers
|
| 14 |
+
revision: str = "108b7295afeb"
|
| 15 |
+
down_revision: Union[str, None] = "182d311c1308"
|
| 16 |
+
branch_labels: Union[str, Sequence[str], None] = None
|
| 17 |
+
depends_on: Union[str, Sequence[str], None] = None
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def upgrade() -> None:
|
| 21 |
+
# Drop old FK
|
| 22 |
+
op.drop_constraint(
|
| 23 |
+
"fk_agent_sessions_conversation_id_conversations",
|
| 24 |
+
"agent_sessions",
|
| 25 |
+
type_="foreignkey",
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
# Recreate with CASCADE
|
| 29 |
+
op.create_foreign_key(
|
| 30 |
+
"fk_agent_sessions_conversation_id_conversations",
|
| 31 |
+
"agent_sessions",
|
| 32 |
+
"conversations",
|
| 33 |
+
["conversation_id"],
|
| 34 |
+
["id"],
|
| 35 |
+
ondelete="CASCADE",
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def downgrade() -> None:
|
| 40 |
+
# Drop cascade FK
|
| 41 |
+
op.drop_constraint(
|
| 42 |
+
"fk_agent_sessions_conversation_id_conversations",
|
| 43 |
+
"agent_sessions",
|
| 44 |
+
type_="foreignkey",
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
# Restore original FK
|
| 48 |
+
op.create_foreign_key(
|
| 49 |
+
"fk_agent_sessions_conversation_id_conversations",
|
| 50 |
+
"agent_sessions",
|
| 51 |
+
"conversations",
|
| 52 |
+
["conversation_id"],
|
| 53 |
+
["id"],
|
| 54 |
+
)
|
alembic/versions/182d311c1308_change_conversation_id_to_int_and_add_.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""change_conversation_id_to_int_and_add_relationship
|
| 2 |
+
|
| 3 |
+
Revision ID: 182d311c1308
|
| 4 |
+
Revises: 36d3b0279270
|
| 5 |
+
Create Date: 2026-05-09 14:42:10.382508
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
from typing import Sequence, Union
|
| 9 |
+
|
| 10 |
+
from alembic import op
|
| 11 |
+
import sqlalchemy as sa
|
| 12 |
+
from sqlalchemy.dialects import postgresql
|
| 13 |
+
|
| 14 |
+
# revision identifiers, used by Alembic.
|
| 15 |
+
revision: str = '182d311c1308'
|
| 16 |
+
down_revision: Union[str, None] = '36d3b0279270'
|
| 17 |
+
branch_labels: Union[str, Sequence[str], None] = None
|
| 18 |
+
depends_on: Union[str, Sequence[str], None] = None
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def upgrade() -> None:
|
| 22 |
+
# 1. Convert the column type with an explicit cast
|
| 23 |
+
op.alter_column('agent_sessions', 'conversation_id',
|
| 24 |
+
existing_type=sa.VARCHAR(length=36),
|
| 25 |
+
type_=sa.Integer(),
|
| 26 |
+
existing_nullable=True,
|
| 27 |
+
postgresql_using='conversation_id::integer')
|
| 28 |
+
|
| 29 |
+
# 2. CLEANUP ORPHANS: Set conversation_id to NULL for any row where the ID
|
| 30 |
+
# doesn't exist in the conversations table.
|
| 31 |
+
op.execute(
|
| 32 |
+
"UPDATE agent_sessions SET conversation_id = NULL "
|
| 33 |
+
"WHERE conversation_id NOT IN (SELECT id FROM conversations)"
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
# 3. DROP INDEX IF EXISTS: This prevents the 'DuplicateTable/relation already exists' error
|
| 37 |
+
op.execute("DROP INDEX IF EXISTS ix_agent_sessions_conversation_id")
|
| 38 |
+
|
| 39 |
+
# 4. Create the index fresh
|
| 40 |
+
op.create_index(op.f('ix_agent_sessions_conversation_id'), 'agent_sessions', ['conversation_id'], unique=False)
|
| 41 |
+
|
| 42 |
+
# 5. Create the foreign key constraint
|
| 43 |
+
op.create_foreign_key(
|
| 44 |
+
op.f('fk_agent_sessions_conversation_id_conversations'),
|
| 45 |
+
'agent_sessions',
|
| 46 |
+
'conversations',
|
| 47 |
+
['conversation_id'],
|
| 48 |
+
['id']
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
def downgrade() -> None:
|
| 52 |
+
op.drop_constraint(op.f('fk_agent_sessions_conversation_id_conversations'), 'agent_sessions', type_='foreignkey')
|
| 53 |
+
op.create_index('ix_agent_sessions_conversation_id', 'agent_sessions', ['conversation_id'], unique=False)
|
| 54 |
+
op.alter_column('agent_sessions', 'conversation_id',
|
| 55 |
+
existing_type=sa.Integer(),
|
| 56 |
+
type_=sa.VARCHAR(length=36),
|
| 57 |
+
existing_nullable=True)
|
alembic/versions/__pycache__/108b7295afeb_add_cascade_delete_to_agent_sessions.cpython-312.pyc
ADDED
|
Binary file (1.51 kB). View file
|
|
|
alembic/versions/__pycache__/182d311c1308_change_conversation_id_to_int_and_add_.cpython-312.pyc
ADDED
|
Binary file (2.61 kB). View file
|
|
|
app/__pycache__/main.cpython-312.pyc
CHANGED
|
Binary files a/app/__pycache__/main.cpython-312.pyc and b/app/__pycache__/main.cpython-312.pyc differ
|
|
|
app/api/v1/endpoints/__pycache__/agents.cpython-312.pyc
CHANGED
|
Binary files a/app/api/v1/endpoints/__pycache__/agents.cpython-312.pyc and b/app/api/v1/endpoints/__pycache__/agents.cpython-312.pyc differ
|
|
|
app/api/v1/endpoints/agents.py
CHANGED
|
@@ -146,36 +146,41 @@ async def delete_agent(
|
|
| 146 |
|
| 147 |
# ==================== AGENT SESSIONS ====================
|
| 148 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
@router.post("/sessions", response_model=SessionResponse)
|
| 150 |
async def start_session(
|
| 151 |
session_data: SessionCreate,
|
| 152 |
db: AsyncSession = Depends(get_db),
|
| 153 |
current_user: Optional[User] = Depends(get_current_active_user)
|
| 154 |
):
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
|
|
|
| 160 |
service = AgentService(db, user=current_user)
|
| 161 |
|
| 162 |
try:
|
| 163 |
-
# Call start_session with correct parameters
|
| 164 |
session_result = await service.start_session(
|
| 165 |
agent_id=session_data.agent_id,
|
| 166 |
-
conversation_id=
|
| 167 |
-
user_id=current_user.id if current_user else None
|
| 168 |
)
|
| 169 |
|
| 170 |
-
|
|
|
|
| 171 |
session = session_result["session"]
|
| 172 |
|
| 173 |
return SessionResponse(
|
| 174 |
id=session.id,
|
| 175 |
agent_id=session.agent_id,
|
| 176 |
-
conversation_id=
|
| 177 |
status=session.status,
|
| 178 |
-
current_step=
|
| 179 |
collected_data=session.collected_data,
|
| 180 |
retry_count=session.retry_count,
|
| 181 |
started_at=session.started_at,
|
|
@@ -186,12 +191,15 @@ async def start_session(
|
|
| 186 |
is_completed=session_result["is_completed"]
|
| 187 |
)
|
| 188 |
|
| 189 |
-
except ValueError as e:
|
| 190 |
-
raise HTTPException(status_code=400, detail=str(e))
|
| 191 |
except Exception as e:
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 195 |
@router.post("/sessions/{session_id}/message", response_model=AgentMessageResponse)
|
| 196 |
async def process_message(
|
| 197 |
session_id: int,
|
|
|
|
| 146 |
|
| 147 |
# ==================== AGENT SESSIONS ====================
|
| 148 |
|
| 149 |
+
import traceback
|
| 150 |
+
import logging
|
| 151 |
+
|
| 152 |
+
logger = logging.getLogger(__name__)
|
| 153 |
+
|
| 154 |
@router.post("/sessions", response_model=SessionResponse)
|
| 155 |
async def start_session(
|
| 156 |
session_data: SessionCreate,
|
| 157 |
db: AsyncSession = Depends(get_db),
|
| 158 |
current_user: Optional[User] = Depends(get_current_active_user)
|
| 159 |
):
|
| 160 |
+
logger.info(
|
| 161 |
+
f"π SESSION START REQUEST | "
|
| 162 |
+
f"agent_id={session_data.agent_id} "
|
| 163 |
+
f"conversation_id={session_data.conversation_id}"
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
service = AgentService(db, user=current_user)
|
| 167 |
|
| 168 |
try:
|
|
|
|
| 169 |
session_result = await service.start_session(
|
| 170 |
agent_id=session_data.agent_id,
|
| 171 |
+
conversation_id=session_data.conversation_id,
|
|
|
|
| 172 |
)
|
| 173 |
|
| 174 |
+
logger.info("β
SESSION START SUCCESS")
|
| 175 |
+
|
| 176 |
session = session_result["session"]
|
| 177 |
|
| 178 |
return SessionResponse(
|
| 179 |
id=session.id,
|
| 180 |
agent_id=session.agent_id,
|
| 181 |
+
conversation_id=session_result["conversation_id"],
|
| 182 |
status=session.status,
|
| 183 |
+
current_step=session.current_step,
|
| 184 |
collected_data=session.collected_data,
|
| 185 |
retry_count=session.retry_count,
|
| 186 |
started_at=session.started_at,
|
|
|
|
| 191 |
is_completed=session_result["is_completed"]
|
| 192 |
)
|
| 193 |
|
|
|
|
|
|
|
| 194 |
except Exception as e:
|
| 195 |
+
logger.exception("π₯ SESSION START ROUTE FAILED")
|
| 196 |
+
|
| 197 |
+
return {
|
| 198 |
+
"error_type": type(e).__name__,
|
| 199 |
+
"error": str(e),
|
| 200 |
+
"traceback": traceback.format_exc()
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
@router.post("/sessions/{session_id}/message", response_model=AgentMessageResponse)
|
| 204 |
async def process_message(
|
| 205 |
session_id: int,
|
app/core/__pycache__/error_handlers.cpython-312.pyc
CHANGED
|
Binary files a/app/core/__pycache__/error_handlers.cpython-312.pyc and b/app/core/__pycache__/error_handlers.cpython-312.pyc differ
|
|
|
app/core/error_handlers.py
CHANGED
|
@@ -4,13 +4,16 @@ Global exception handlers
|
|
| 4 |
Centralized error handling for the entire application
|
| 5 |
"""
|
| 6 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
from fastapi import Request, status
|
| 8 |
-
from fastapi.responses import JSONResponse
|
| 9 |
-
from fastapi.exceptions import RequestValidationError
|
| 10 |
from fastapi.encoders import jsonable_encoder
|
|
|
|
|
|
|
| 11 |
from pydantic import ValidationError
|
| 12 |
-
from datetime import datetime
|
| 13 |
-
from typing import Union
|
| 14 |
|
| 15 |
from app.core.exceptions import AppException
|
| 16 |
from app.models.error import (
|
|
@@ -19,15 +22,43 @@ from app.models.error import (
|
|
| 19 |
ValidationError as ValidationErrorModel,
|
| 20 |
)
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
-
async def app_exception_handler(
|
|
|
|
|
|
|
|
|
|
| 24 |
"""
|
| 25 |
Handler for custom application exceptions
|
| 26 |
|
| 27 |
Returns standardized error response
|
| 28 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
error_response = ErrorResponse(
|
| 30 |
-
error_code=exc.error_code,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
)
|
| 32 |
|
| 33 |
return JSONResponse(
|
|
@@ -36,28 +67,57 @@ async def app_exception_handler(request: Request, exc: AppException) -> JSONResp
|
|
| 36 |
)
|
| 37 |
|
| 38 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
async def validation_exception_handler(
|
| 40 |
-
request: Request,
|
|
|
|
| 41 |
) -> JSONResponse:
|
| 42 |
"""
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
|
|
|
| 46 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
errors = []
|
| 48 |
|
| 49 |
for error in exc.errors():
|
| 50 |
-
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
errors.append(
|
| 54 |
ValidationErrorModel(
|
| 55 |
-
field=field
|
|
|
|
|
|
|
| 56 |
)
|
| 57 |
)
|
| 58 |
|
| 59 |
error_response = ValidationErrorResponse(
|
| 60 |
-
errors=errors,
|
|
|
|
| 61 |
)
|
| 62 |
|
| 63 |
return JSONResponse(
|
|
@@ -66,23 +126,52 @@ async def validation_exception_handler(
|
|
| 66 |
)
|
| 67 |
|
| 68 |
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
"""
|
| 71 |
Handler for any unhandled exceptions
|
| 72 |
|
| 73 |
Last resort error handler
|
| 74 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
error_response = ErrorResponse(
|
| 76 |
error_code="INTERNAL_SERVER_ERROR",
|
| 77 |
-
message=
|
| 78 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
path=str(request.url.path),
|
| 80 |
)
|
| 81 |
|
| 82 |
-
# Log the error (we'll implement proper logging later)
|
| 83 |
-
print(f"Unhandled exception: {exc}")
|
| 84 |
-
|
| 85 |
return JSONResponse(
|
| 86 |
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 87 |
content=jsonable_encoder(error_response.model_dump()),
|
| 88 |
-
)
|
|
|
|
| 4 |
Centralized error handling for the entire application
|
| 5 |
"""
|
| 6 |
|
| 7 |
+
import logging
|
| 8 |
+
import traceback
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
from typing import Union
|
| 11 |
+
|
| 12 |
from fastapi import Request, status
|
|
|
|
|
|
|
| 13 |
from fastapi.encoders import jsonable_encoder
|
| 14 |
+
from fastapi.exceptions import RequestValidationError
|
| 15 |
+
from fastapi.responses import JSONResponse
|
| 16 |
from pydantic import ValidationError
|
|
|
|
|
|
|
| 17 |
|
| 18 |
from app.core.exceptions import AppException
|
| 19 |
from app.models.error import (
|
|
|
|
| 22 |
ValidationError as ValidationErrorModel,
|
| 23 |
)
|
| 24 |
|
| 25 |
+
# =========================================================
|
| 26 |
+
# LOGGER
|
| 27 |
+
# =========================================================
|
| 28 |
+
|
| 29 |
+
logger = logging.getLogger(__name__)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
# =========================================================
|
| 33 |
+
# APP EXCEPTION HANDLER
|
| 34 |
+
# =========================================================
|
| 35 |
|
| 36 |
+
async def app_exception_handler(
|
| 37 |
+
request: Request,
|
| 38 |
+
exc: AppException
|
| 39 |
+
) -> JSONResponse:
|
| 40 |
"""
|
| 41 |
Handler for custom application exceptions
|
| 42 |
|
| 43 |
Returns standardized error response
|
| 44 |
"""
|
| 45 |
+
|
| 46 |
+
logger.exception(
|
| 47 |
+
f"β APP EXCEPTION | "
|
| 48 |
+
f"path={request.url.path} | "
|
| 49 |
+
f"method={request.method} | "
|
| 50 |
+
f"error_code={exc.error_code}"
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
error_response = ErrorResponse(
|
| 54 |
+
error_code=exc.error_code,
|
| 55 |
+
message=exc.detail,
|
| 56 |
+
path=str(request.url.path),
|
| 57 |
+
details={
|
| 58 |
+
"type": type(exc).__name__,
|
| 59 |
+
"traceback": traceback.format_exc(),
|
| 60 |
+
"timestamp": datetime.utcnow().isoformat(),
|
| 61 |
+
} if request.app.debug else None,
|
| 62 |
)
|
| 63 |
|
| 64 |
return JSONResponse(
|
|
|
|
| 67 |
)
|
| 68 |
|
| 69 |
|
| 70 |
+
# =========================================================
|
| 71 |
+
# VALIDATION EXCEPTION HANDLER
|
| 72 |
+
# =========================================================
|
| 73 |
+
|
| 74 |
async def validation_exception_handler(
|
| 75 |
+
request: Request,
|
| 76 |
+
exc: Union[RequestValidationError, ValidationError]
|
| 77 |
) -> JSONResponse:
|
| 78 |
"""
|
| 79 |
+
Handles:
|
| 80 |
+
- Request body validation errors
|
| 81 |
+
- Response validation errors
|
| 82 |
+
- Pydantic schema validation errors
|
| 83 |
"""
|
| 84 |
+
|
| 85 |
+
logger.exception(
|
| 86 |
+
f"β VALIDATION ERROR | "
|
| 87 |
+
f"path={request.url.path} | "
|
| 88 |
+
f"method={request.method}"
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
print("\n================ VALIDATION ERROR ================")
|
| 92 |
+
print(f"PATH: {request.url.path}")
|
| 93 |
+
print(f"METHOD: {request.method}")
|
| 94 |
+
print(f"ERROR TYPE: {type(exc).__name__}")
|
| 95 |
+
print("RAW ERRORS:")
|
| 96 |
+
print(exc.errors())
|
| 97 |
+
print("FULL TRACEBACK:")
|
| 98 |
+
traceback.print_exc()
|
| 99 |
+
print("==================================================\n")
|
| 100 |
+
|
| 101 |
errors = []
|
| 102 |
|
| 103 |
for error in exc.errors():
|
| 104 |
+
field = " -> ".join(
|
| 105 |
+
str(loc)
|
| 106 |
+
for loc in error.get("loc", [])
|
| 107 |
+
if loc != "body"
|
| 108 |
+
)
|
| 109 |
|
| 110 |
errors.append(
|
| 111 |
ValidationErrorModel(
|
| 112 |
+
field=field or "unknown",
|
| 113 |
+
message=error.get("msg", "Validation error"),
|
| 114 |
+
error_type=error.get("type", "unknown_error"),
|
| 115 |
)
|
| 116 |
)
|
| 117 |
|
| 118 |
error_response = ValidationErrorResponse(
|
| 119 |
+
errors=errors,
|
| 120 |
+
message=f"Validation failed for {len(errors)} field(s)"
|
| 121 |
)
|
| 122 |
|
| 123 |
return JSONResponse(
|
|
|
|
| 126 |
)
|
| 127 |
|
| 128 |
|
| 129 |
+
# =========================================================
|
| 130 |
+
# GENERIC EXCEPTION HANDLER
|
| 131 |
+
# =========================================================
|
| 132 |
+
|
| 133 |
+
async def generic_exception_handler(
|
| 134 |
+
request: Request,
|
| 135 |
+
exc: Exception
|
| 136 |
+
) -> JSONResponse:
|
| 137 |
"""
|
| 138 |
Handler for any unhandled exceptions
|
| 139 |
|
| 140 |
Last resort error handler
|
| 141 |
"""
|
| 142 |
+
|
| 143 |
+
logger.exception(
|
| 144 |
+
f"π₯ UNHANDLED EXCEPTION | "
|
| 145 |
+
f"path={request.url.path} | "
|
| 146 |
+
f"method={request.method}"
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
print("\n================ UNHANDLED EXCEPTION ================")
|
| 150 |
+
print(f"PATH: {request.url.path}")
|
| 151 |
+
print(f"METHOD: {request.method}")
|
| 152 |
+
print(f"ERROR TYPE: {type(exc).__name__}")
|
| 153 |
+
print(f"ERROR: {repr(exc)}")
|
| 154 |
+
print("FULL TRACEBACK:")
|
| 155 |
+
traceback.print_exc()
|
| 156 |
+
print("=====================================================\n")
|
| 157 |
+
|
| 158 |
error_response = ErrorResponse(
|
| 159 |
error_code="INTERNAL_SERVER_ERROR",
|
| 160 |
+
message=(
|
| 161 |
+
str(exc)
|
| 162 |
+
if request.app.debug
|
| 163 |
+
else "An unexpected error occurred"
|
| 164 |
+
),
|
| 165 |
+
details={
|
| 166 |
+
"type": type(exc).__name__,
|
| 167 |
+
"error": str(exc),
|
| 168 |
+
"traceback": traceback.format_exc(),
|
| 169 |
+
"timestamp": datetime.utcnow().isoformat(),
|
| 170 |
+
} if request.app.debug else None,
|
| 171 |
path=str(request.url.path),
|
| 172 |
)
|
| 173 |
|
|
|
|
|
|
|
|
|
|
| 174 |
return JSONResponse(
|
| 175 |
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 176 |
content=jsonable_encoder(error_response.model_dump()),
|
| 177 |
+
)
|
app/db/models/__pycache__/agent.cpython-312.pyc
CHANGED
|
Binary files a/app/db/models/__pycache__/agent.cpython-312.pyc and b/app/db/models/__pycache__/agent.cpython-312.pyc differ
|
|
|
app/db/models/__pycache__/conversation.cpython-312.pyc
CHANGED
|
Binary files a/app/db/models/__pycache__/conversation.cpython-312.pyc and b/app/db/models/__pycache__/conversation.cpython-312.pyc differ
|
|
|
app/db/models/agent.py
CHANGED
|
@@ -84,6 +84,12 @@ class Agent(Base):
|
|
| 84 |
|
| 85 |
# Configuration
|
| 86 |
config = Column(JSON, nullable=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
# Example config structure:
|
| 88 |
# {
|
| 89 |
# "steps": [
|
|
@@ -136,7 +142,10 @@ class AgentSession(Base):
|
|
| 136 |
|
| 137 |
# References
|
| 138 |
agent_id = Column(Integer, ForeignKey("agents.id"), nullable=False)
|
| 139 |
-
conversation_id = Column(
|
|
|
|
|
|
|
|
|
|
| 140 |
user_id = Column(Integer, ForeignKey("users.id"), nullable=True) # For logged-in users
|
| 141 |
|
| 142 |
# Session State
|
|
@@ -164,6 +173,10 @@ class AgentSession(Base):
|
|
| 164 |
|
| 165 |
# Relationships
|
| 166 |
agent = relationship("Agent", back_populates="sessions")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
actions = relationship("AgentActionLog", back_populates="session", cascade="all, delete-orphan")
|
| 168 |
|
| 169 |
|
|
|
|
| 84 |
|
| 85 |
# Configuration
|
| 86 |
config = Column(JSON, nullable=False)
|
| 87 |
+
|
| 88 |
+
@property
|
| 89 |
+
def steps_config(self):
|
| 90 |
+
"""Helper to access steps directly from config dict"""
|
| 91 |
+
return self.config.get("steps", [])
|
| 92 |
+
|
| 93 |
# Example config structure:
|
| 94 |
# {
|
| 95 |
# "steps": [
|
|
|
|
| 142 |
|
| 143 |
# References
|
| 144 |
agent_id = Column(Integer, ForeignKey("agents.id"), nullable=False)
|
| 145 |
+
conversation_id = Column(Integer, ForeignKey(
|
| 146 |
+
"conversations.id",
|
| 147 |
+
ondelete="CASCADE"
|
| 148 |
+
), nullable=True)
|
| 149 |
user_id = Column(Integer, ForeignKey("users.id"), nullable=True) # For logged-in users
|
| 150 |
|
| 151 |
# Session State
|
|
|
|
| 173 |
|
| 174 |
# Relationships
|
| 175 |
agent = relationship("Agent", back_populates="sessions")
|
| 176 |
+
conversation = relationship(
|
| 177 |
+
"Conversation",
|
| 178 |
+
back_populates="agent_sessions"
|
| 179 |
+
)
|
| 180 |
actions = relationship("AgentActionLog", back_populates="session", cascade="all, delete-orphan")
|
| 181 |
|
| 182 |
|
app/db/models/conversation.py
CHANGED
|
@@ -59,6 +59,11 @@ class Conversation(Base):
|
|
| 59 |
cascade="all, delete-orphan",
|
| 60 |
order_by="Message.created_at",
|
| 61 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
def __repr__(self) -> str:
|
| 64 |
return f"<Conversation(id={self.id}, title='{self.title}', user_id={self.user_id})>"
|
|
|
|
| 59 |
cascade="all, delete-orphan",
|
| 60 |
order_by="Message.created_at",
|
| 61 |
)
|
| 62 |
+
agent_sessions = relationship(
|
| 63 |
+
"AgentSession",
|
| 64 |
+
back_populates="conversation",
|
| 65 |
+
cascade="all, delete-orphan"
|
| 66 |
+
)
|
| 67 |
|
| 68 |
def __repr__(self) -> str:
|
| 69 |
return f"<Conversation(id={self.id}, title='{self.title}', user_id={self.user_id})>"
|
app/main.py
CHANGED
|
@@ -4,59 +4,123 @@ FastAPI AI Backend - Main Application
|
|
| 4 |
Updated with JWT authentication
|
| 5 |
"""
|
| 6 |
|
| 7 |
-
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
from fastapi.exceptions import RequestValidationError
|
|
|
|
| 10 |
from pydantic import ValidationError
|
| 11 |
-
from contextlib import asynccontextmanager
|
| 12 |
|
| 13 |
-
from app.core.config import settings
|
| 14 |
from app.api.v1.api import api_router
|
| 15 |
-
from app.core.
|
| 16 |
from app.core.error_handlers import (
|
| 17 |
app_exception_handler,
|
| 18 |
-
validation_exception_handler,
|
| 19 |
generic_exception_handler,
|
|
|
|
| 20 |
)
|
| 21 |
-
from app.
|
| 22 |
-
from app.middleware.performance_middleware import PerformanceMiddleware
|
| 23 |
-
from app.utils.logger import logger
|
| 24 |
from app.db.session import close_db
|
| 25 |
from app.db.utils import check_database_connection, get_database_info
|
|
|
|
|
|
|
| 26 |
from app.services.rag.lightweight_embeddings import get_embedding_function
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
@asynccontextmanager
|
| 30 |
async def lifespan(app: FastAPI):
|
| 31 |
"""Application lifespan events"""
|
| 32 |
|
|
|
|
| 33 |
print(f"π Starting {settings.APP_NAME} v{settings.APP_VERSION}")
|
| 34 |
print(f"π Environment: {settings.ENVIRONMENT}")
|
| 35 |
print(f"π§ Debug mode: {settings.DEBUG}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
if db_connected:
|
| 46 |
-
print("β
Database connection successful")
|
| 47 |
-
#db_info = await get_database_info()
|
| 48 |
-
#print(f"π PostgreSQL version: {db_info.get('version', 'unknown')}")
|
| 49 |
-
else:
|
| 50 |
-
print("β Database connection failed!")
|
| 51 |
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
yield
|
| 55 |
|
| 56 |
-
|
| 57 |
-
logger.info("Application shutdown", extra={"app_name": settings.APP_NAME})
|
| 58 |
print(f"π Shutting down {settings.APP_NAME}")
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
|
| 62 |
def create_application() -> FastAPI:
|
|
@@ -104,7 +168,42 @@ def create_application() -> FastAPI:
|
|
| 104 |
lifespan=lifespan,
|
| 105 |
)
|
| 106 |
|
| 107 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
app.add_middleware(
|
| 109 |
CORSMiddleware,
|
| 110 |
allow_origins=[
|
|
@@ -115,19 +214,60 @@ def create_application() -> FastAPI:
|
|
| 115 |
allow_methods=["*"],
|
| 116 |
allow_headers=["*"],
|
| 117 |
)
|
| 118 |
-
#app.add_middleware(PerformanceMiddleware, slow_request_threshold=1.0)
|
| 119 |
-
#app.add_middleware(LoggingMiddleware)
|
| 120 |
|
| 121 |
-
#
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
app.
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
-
#
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
|
| 130 |
return app
|
| 131 |
|
| 132 |
|
| 133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
Updated with JWT authentication
|
| 5 |
"""
|
| 6 |
|
| 7 |
+
import logging
|
| 8 |
+
import traceback
|
| 9 |
+
|
| 10 |
+
from contextlib import asynccontextmanager
|
| 11 |
+
|
| 12 |
+
from fastapi import FastAPI, Request
|
| 13 |
from fastapi.exceptions import RequestValidationError
|
| 14 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 15 |
from pydantic import ValidationError
|
|
|
|
| 16 |
|
|
|
|
| 17 |
from app.api.v1.api import api_router
|
| 18 |
+
from app.core.config import settings
|
| 19 |
from app.core.error_handlers import (
|
| 20 |
app_exception_handler,
|
|
|
|
| 21 |
generic_exception_handler,
|
| 22 |
+
validation_exception_handler,
|
| 23 |
)
|
| 24 |
+
from app.core.exceptions import AppException
|
|
|
|
|
|
|
| 25 |
from app.db.session import close_db
|
| 26 |
from app.db.utils import check_database_connection, get_database_info
|
| 27 |
+
from app.middleware.logging_middleware import LoggingMiddleware
|
| 28 |
+
from app.middleware.performance_middleware import PerformanceMiddleware
|
| 29 |
from app.services.rag.lightweight_embeddings import get_embedding_function
|
| 30 |
+
from app.utils.logger import logger
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# =========================================================
|
| 34 |
+
# GLOBAL LOGGING CONFIGURATION
|
| 35 |
+
# =========================================================
|
| 36 |
+
|
| 37 |
+
logging.basicConfig(
|
| 38 |
+
level=logging.DEBUG if settings.DEBUG else logging.INFO,
|
| 39 |
+
format=(
|
| 40 |
+
"%(asctime)s | "
|
| 41 |
+
"%(levelname)s | "
|
| 42 |
+
"%(name)s | "
|
| 43 |
+
"%(message)s"
|
| 44 |
+
),
|
| 45 |
+
)
|
| 46 |
|
| 47 |
+
# Reduce noisy third-party logs
|
| 48 |
+
logging.getLogger("uvicorn.access").setLevel(logging.INFO)
|
| 49 |
+
logging.getLogger("sqlalchemy.engine").setLevel(logging.INFO)
|
| 50 |
+
|
| 51 |
+
# Enable SQLAlchemy debug logs if needed
|
| 52 |
+
# logging.getLogger("sqlalchemy.engine").setLevel(logging.DEBUG)
|
| 53 |
+
logging.getLogger("httpcore").disabled = True
|
| 54 |
|
| 55 |
@asynccontextmanager
|
| 56 |
async def lifespan(app: FastAPI):
|
| 57 |
"""Application lifespan events"""
|
| 58 |
|
| 59 |
+
print("\n================================================")
|
| 60 |
print(f"π Starting {settings.APP_NAME} v{settings.APP_VERSION}")
|
| 61 |
print(f"π Environment: {settings.ENVIRONMENT}")
|
| 62 |
print(f"π§ Debug mode: {settings.DEBUG}")
|
| 63 |
+
print("================================================\n")
|
| 64 |
+
|
| 65 |
+
try:
|
| 66 |
+
# =========================================================
|
| 67 |
+
# PRELOAD EMBEDDING MODEL
|
| 68 |
+
# =========================================================
|
| 69 |
+
|
| 70 |
+
print("π§ Initializing AI models...")
|
| 71 |
+
get_embedding_function()
|
| 72 |
+
print("β
Embedding model loaded")
|
| 73 |
+
|
| 74 |
+
# =========================================================
|
| 75 |
+
# DATABASE CHECK
|
| 76 |
+
# =========================================================
|
| 77 |
+
|
| 78 |
+
print("π Checking database connection...")
|
| 79 |
+
|
| 80 |
+
db_connected = await check_database_connection()
|
| 81 |
+
|
| 82 |
+
if db_connected:
|
| 83 |
+
print("β
Database connection successful")
|
| 84 |
|
| 85 |
+
try:
|
| 86 |
+
db_info = await get_database_info()
|
| 87 |
+
print(
|
| 88 |
+
f"π PostgreSQL version: "
|
| 89 |
+
f"{db_info.get('version', 'unknown')}"
|
| 90 |
+
)
|
| 91 |
+
except Exception:
|
| 92 |
+
print("β οΈ Could not retrieve database info")
|
| 93 |
|
| 94 |
+
else:
|
| 95 |
+
print("β Database connection failed!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
+
print("\n================================================")
|
| 98 |
+
print("β
APPLICATION STARTUP COMPLETE")
|
| 99 |
+
print("================================================\n")
|
| 100 |
+
|
| 101 |
+
except Exception as e:
|
| 102 |
+
|
| 103 |
+
print("\n================================================")
|
| 104 |
+
print("π₯ STARTUP FAILURE")
|
| 105 |
+
print(f"TYPE: {type(e).__name__}")
|
| 106 |
+
print(f"ERROR: {repr(e)}")
|
| 107 |
+
print("TRACEBACK:")
|
| 108 |
+
traceback.print_exc()
|
| 109 |
+
print("================================================\n")
|
| 110 |
+
|
| 111 |
+
raise
|
| 112 |
|
| 113 |
yield
|
| 114 |
|
| 115 |
+
print("\n================================================")
|
|
|
|
| 116 |
print(f"π Shutting down {settings.APP_NAME}")
|
| 117 |
+
print("================================================\n")
|
| 118 |
+
|
| 119 |
+
try:
|
| 120 |
+
await close_db()
|
| 121 |
+
print("β
Database connections closed")
|
| 122 |
+
except Exception as e:
|
| 123 |
+
print(f"β οΈ Failed to close database cleanly: {e}")
|
| 124 |
|
| 125 |
|
| 126 |
def create_application() -> FastAPI:
|
|
|
|
| 168 |
lifespan=lifespan,
|
| 169 |
)
|
| 170 |
|
| 171 |
+
# =========================================================
|
| 172 |
+
# DEBUG REQUEST/RESPONSE MIDDLEWARE
|
| 173 |
+
# =========================================================
|
| 174 |
+
|
| 175 |
+
@app.middleware("http")
|
| 176 |
+
async def debug_requests(request: Request, call_next):
|
| 177 |
+
|
| 178 |
+
print("\n================================================")
|
| 179 |
+
print(f"π REQUEST: {request.method} {request.url}")
|
| 180 |
+
print("================================================")
|
| 181 |
+
|
| 182 |
+
try:
|
| 183 |
+
response = await call_next(request)
|
| 184 |
+
|
| 185 |
+
print("\n================================================")
|
| 186 |
+
print(f"β
RESPONSE STATUS: {response.status_code}")
|
| 187 |
+
print("================================================\n")
|
| 188 |
+
|
| 189 |
+
return response
|
| 190 |
+
|
| 191 |
+
except Exception as e:
|
| 192 |
+
|
| 193 |
+
print("\n================================================")
|
| 194 |
+
print("π₯ MIDDLEWARE CAUGHT EXCEPTION")
|
| 195 |
+
print(f"TYPE: {type(e).__name__}")
|
| 196 |
+
print(f"ERROR: {repr(e)}")
|
| 197 |
+
print("TRACEBACK:")
|
| 198 |
+
traceback.print_exc()
|
| 199 |
+
print("================================================\n")
|
| 200 |
+
|
| 201 |
+
raise
|
| 202 |
+
|
| 203 |
+
# =========================================================
|
| 204 |
+
# CORS
|
| 205 |
+
# =========================================================
|
| 206 |
+
|
| 207 |
app.add_middleware(
|
| 208 |
CORSMiddleware,
|
| 209 |
allow_origins=[
|
|
|
|
| 214 |
allow_methods=["*"],
|
| 215 |
allow_headers=["*"],
|
| 216 |
)
|
|
|
|
|
|
|
| 217 |
|
| 218 |
+
# =========================================================
|
| 219 |
+
# CUSTOM MIDDLEWARE
|
| 220 |
+
# =========================================================
|
| 221 |
+
|
| 222 |
+
# app.add_middleware(
|
| 223 |
+
# PerformanceMiddleware,
|
| 224 |
+
# slow_request_threshold=1.0
|
| 225 |
+
# )
|
| 226 |
|
| 227 |
+
# app.add_middleware(LoggingMiddleware)
|
| 228 |
+
|
| 229 |
+
# =========================================================
|
| 230 |
+
# EXCEPTION HANDLERS
|
| 231 |
+
# =========================================================
|
| 232 |
+
|
| 233 |
+
app.add_exception_handler(
|
| 234 |
+
AppException,
|
| 235 |
+
app_exception_handler
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
app.add_exception_handler(
|
| 239 |
+
RequestValidationError,
|
| 240 |
+
validation_exception_handler
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
app.add_exception_handler(
|
| 244 |
+
ValidationError,
|
| 245 |
+
validation_exception_handler
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
app.add_exception_handler(
|
| 249 |
+
Exception,
|
| 250 |
+
generic_exception_handler
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
# =========================================================
|
| 254 |
+
# ROUTERS
|
| 255 |
+
# =========================================================
|
| 256 |
+
|
| 257 |
+
app.include_router(
|
| 258 |
+
api_router,
|
| 259 |
+
prefix=settings.API_V1_PREFIX
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
+
print("\n================================================")
|
| 263 |
+
print("β
FastAPI application created successfully")
|
| 264 |
+
print("================================================\n")
|
| 265 |
|
| 266 |
return app
|
| 267 |
|
| 268 |
|
| 269 |
+
# =========================================================
|
| 270 |
+
# APPLICATION INSTANCE
|
| 271 |
+
# =========================================================
|
| 272 |
+
|
| 273 |
+
app = create_application()
|
app/schemas/__pycache__/agent.cpython-312.pyc
CHANGED
|
Binary files a/app/schemas/__pycache__/agent.cpython-312.pyc and b/app/schemas/__pycache__/agent.cpython-312.pyc differ
|
|
|
app/schemas/agent.py
CHANGED
|
@@ -110,14 +110,14 @@ class AgentResponse(BaseModel):
|
|
| 110 |
class SessionCreate(BaseModel):
|
| 111 |
"""Create agent session"""
|
| 112 |
agent_id: int
|
| 113 |
-
conversation_id: Optional[
|
| 114 |
user_id: Optional[int] = None
|
| 115 |
|
| 116 |
|
| 117 |
class SessionResponse(BaseModel):
|
| 118 |
id: int
|
| 119 |
agent_id: int
|
| 120 |
-
conversation_id: Optional[
|
| 121 |
status: SessionStatus
|
| 122 |
current_step: Optional[str]
|
| 123 |
collected_data: Dict[str, Any] = Field(default_factory=dict)
|
|
@@ -126,7 +126,7 @@ class SessionResponse(BaseModel):
|
|
| 126 |
completed_at: Optional[datetime]
|
| 127 |
welcome_message: Optional[str] = None
|
| 128 |
first_prompt: Optional[str] = None
|
| 129 |
-
progress: Optional[
|
| 130 |
is_completed: bool = False
|
| 131 |
|
| 132 |
class Config:
|
|
|
|
| 110 |
class SessionCreate(BaseModel):
|
| 111 |
"""Create agent session"""
|
| 112 |
agent_id: int
|
| 113 |
+
conversation_id: Optional[int] = None
|
| 114 |
user_id: Optional[int] = None
|
| 115 |
|
| 116 |
|
| 117 |
class SessionResponse(BaseModel):
|
| 118 |
id: int
|
| 119 |
agent_id: int
|
| 120 |
+
conversation_id: Optional[int]
|
| 121 |
status: SessionStatus
|
| 122 |
current_step: Optional[str]
|
| 123 |
collected_data: Dict[str, Any] = Field(default_factory=dict)
|
|
|
|
| 126 |
completed_at: Optional[datetime]
|
| 127 |
welcome_message: Optional[str] = None
|
| 128 |
first_prompt: Optional[str] = None
|
| 129 |
+
progress: Optional[int] = None
|
| 130 |
is_completed: bool = False
|
| 131 |
|
| 132 |
class Config:
|
app/services/agents/__pycache__/agent_service.cpython-312.pyc
CHANGED
|
Binary files a/app/services/agents/__pycache__/agent_service.cpython-312.pyc and b/app/services/agents/__pycache__/agent_service.cpython-312.pyc differ
|
|
|
app/services/agents/agent_service.py
CHANGED
|
@@ -161,87 +161,87 @@ class AgentService:
|
|
| 161 |
result = await self.db.execute(query)
|
| 162 |
return list(result.scalars().all())
|
| 163 |
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
user_id: Optional[int] = None
|
| 169 |
-
) -> Dict[str, Any]:
|
| 170 |
-
"""
|
| 171 |
-
Start new agent session with proper transaction handling
|
| 172 |
-
|
| 173 |
-
Args:
|
| 174 |
-
agent_id: Agent ID
|
| 175 |
-
conversation_id: Optional conversation ID for tracking
|
| 176 |
-
user_id: Optional user ID for logged-in users
|
| 177 |
-
|
| 178 |
-
Returns:
|
| 179 |
-
Dict with session details and first prompt
|
| 180 |
-
"""
|
| 181 |
try:
|
| 182 |
-
#
|
| 183 |
agent = await self.get_agent(agent_id)
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
raise ValueError(f"Agent '{agent.name}' is not active")
|
| 188 |
-
|
| 189 |
-
# Initialize state machine
|
| 190 |
-
state_machine = AgentStateMachine(agent.config)
|
| 191 |
-
first_step = state_machine.get_current_step()
|
| 192 |
|
| 193 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
session = AgentSession(
|
| 195 |
agent_id=agent_id,
|
| 196 |
conversation_id=conversation_id,
|
| 197 |
-
user_id=
|
| 198 |
-
current_step=first_step["id"] if first_step else None,
|
| 199 |
status=SessionStatus.IN_PROGRESS,
|
|
|
|
| 200 |
collected_data={},
|
| 201 |
-
|
| 202 |
-
started_at=datetime.utcnow(),
|
| 203 |
-
last_activity_at=datetime.utcnow()
|
| 204 |
)
|
| 205 |
-
|
| 206 |
self.db.add(session)
|
| 207 |
-
await self.db.
|
| 208 |
-
|
| 209 |
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
)
|
| 218 |
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
role="assistant",
|
| 224 |
-
content=first_prompt,
|
| 225 |
-
metadata={"agent_session_id": session.id, "is_initial": True}
|
| 226 |
-
)
|
| 227 |
-
await self.db.commit()
|
| 228 |
-
|
| 229 |
return {
|
| 230 |
"session": session,
|
| 231 |
-
"
|
| 232 |
-
"
|
| 233 |
-
"current_step": first_step
|
| 234 |
-
"
|
| 235 |
-
"
|
|
|
|
| 236 |
}
|
| 237 |
-
|
| 238 |
-
except ValueError:
|
| 239 |
-
raise
|
| 240 |
except Exception as e:
|
| 241 |
await self.db.rollback()
|
| 242 |
-
logger.exception(
|
| 243 |
-
|
| 244 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
async def process_message(
|
| 246 |
self,
|
| 247 |
session_id: int,
|
|
|
|
| 161 |
result = await self.db.execute(query)
|
| 162 |
return list(result.scalars().all())
|
| 163 |
|
| 164 |
+
# app/services/agents/agent_service.py
|
| 165 |
+
|
| 166 |
+
async def start_session(self, agent_id: int, conversation_id: Optional[int] = None, model_name: str = "default") -> Dict[str, Any]:
|
| 167 |
+
logger.info(f"π Starting agent session: agent_id={agent_id}, conv_id={conversation_id}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
try:
|
| 169 |
+
# Trace 1: Fetch Agent
|
| 170 |
agent = await self.get_agent(agent_id)
|
| 171 |
+
if not agent:
|
| 172 |
+
logger.error(f"β Agent {agent_id} not found")
|
| 173 |
+
raise ValueError(f"Agent {agent_id} not found")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
|
| 175 |
+
# Trace 2: Dynamic Conversation
|
| 176 |
+
if not conversation_id:
|
| 177 |
+
logger.info("π No conversation_id provided. Creating new conversation...")
|
| 178 |
+
if not self.user:
|
| 179 |
+
raise ValueError("User required to create agent conversation")
|
| 180 |
+
|
| 181 |
+
new_conv = await self.conv_service.create_conversation(
|
| 182 |
+
user_id=self.user.id,
|
| 183 |
+
title=f"Chat with {agent.name}",
|
| 184 |
+
model_name=model_name
|
| 185 |
+
)
|
| 186 |
+
await self.db.flush()
|
| 187 |
+
conversation_id = new_conv.id
|
| 188 |
+
logger.info(f"β
Created conversation: {conversation_id}")
|
| 189 |
+
|
| 190 |
+
steps = agent.steps_config
|
| 191 |
+
first_step = steps[0] if steps else None
|
| 192 |
+
|
| 193 |
+
# Session Creation
|
| 194 |
session = AgentSession(
|
| 195 |
agent_id=agent_id,
|
| 196 |
conversation_id=conversation_id,
|
| 197 |
+
user_id=self.user.id if self.user else None,
|
|
|
|
| 198 |
status=SessionStatus.IN_PROGRESS,
|
| 199 |
+
current_step=first_step.get("id") if first_step else None,
|
| 200 |
collected_data={},
|
| 201 |
+
session_metadata={}
|
|
|
|
|
|
|
| 202 |
)
|
|
|
|
| 203 |
self.db.add(session)
|
| 204 |
+
await self.db.flush()
|
| 205 |
+
logger.info(f"β
Created agent session: {session.id}")
|
| 206 |
|
| 207 |
+
# State Machine & Welcome Message
|
| 208 |
+
state_machine = AgentStateMachine(agent.config)
|
| 209 |
+
if first_step:
|
| 210 |
+
state_machine.current_step_id = first_step["id"]
|
| 211 |
+
|
| 212 |
+
current_step = state_machine.get_current_step()
|
| 213 |
+
welcome_msg = current_step["prompt"] if current_step else "Hello! How can I help?"
|
| 214 |
+
|
| 215 |
+
# Trace 5: Persistence
|
| 216 |
+
await self.conv_service.add_message(
|
| 217 |
+
conversation_id=conversation_id,
|
| 218 |
+
role="assistant",
|
| 219 |
+
content=welcome_msg,
|
| 220 |
+
metadata={"agent_session_id": session.id, "is_initial": True}
|
| 221 |
)
|
| 222 |
|
| 223 |
+
await self.db.commit()
|
| 224 |
+
logger.info("π Session start transaction committed successfully")
|
| 225 |
+
|
| 226 |
+
# Trace 6: Return Mapping (Crucial for FastAPI Schema)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 227 |
return {
|
| 228 |
"session": session,
|
| 229 |
+
"conversation_id": conversation_id,
|
| 230 |
+
"welcome_message": welcome_msg,
|
| 231 |
+
"current_step": first_step,
|
| 232 |
+
"first_prompt": welcome_msg, # Mapping for schema compatibility
|
| 233 |
+
"progress": 0,
|
| 234 |
+
"is_completed": False
|
| 235 |
}
|
|
|
|
|
|
|
|
|
|
| 236 |
except Exception as e:
|
| 237 |
await self.db.rollback()
|
| 238 |
+
logger.exception(
|
| 239 |
+
f"π₯ Failed to start session | "
|
| 240 |
+
f"agent_id={agent_id} "
|
| 241 |
+
f"conversation_id={conversation_id}"
|
| 242 |
+
)
|
| 243 |
+
raise
|
| 244 |
+
|
| 245 |
async def process_message(
|
| 246 |
self,
|
| 247 |
session_id: int,
|