add webpage info

This commit is contained in:
ipu 2025-09-03 22:42:24 +03:00
parent e4d2e64ce7
commit 959fd1ac86
5 changed files with 83 additions and 8 deletions

View file

@ -0,0 +1,45 @@
"""add webpage
Revision ID: 57f67bce2bec
Revises: 058739dc7aa6
Create Date: 2025-09-03 17:52:10.644879
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '57f67bce2bec'
down_revision: Union[str, Sequence[str], None] = '058739dc7aa6'
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('webpage',
sa.Column('id', sa.String(), nullable=False),
sa.Column('n', sa.Integer(), nullable=True),
sa.Column('description', sa.String(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
with op.batch_alter_table('webpage', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_webpage_id'), ['id'], unique=False)
batch_op.create_index(batch_op.f('ix_webpage_n'), ['n'], unique=False)
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('webpage', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_webpage_n'))
batch_op.drop_index(batch_op.f('ix_webpage_id'))
op.drop_table('webpage')
# ### end Alembic commands ###

View file

@ -3,6 +3,7 @@ from fastapi import APIRouter, HTTPException
from src.services.estimation_service_v2 import EstimationService from src.services.estimation_service_v2 import EstimationService
from . import models from . import models
from ...cache.page_cache import get_page_description
from ...services.chat_service import chat_service from ...services.chat_service import chat_service
router = APIRouter() router = APIRouter()
@ -11,10 +12,15 @@ router = APIRouter()
async def insurance_chat(request: models.InsuranceChatRequest): async def insurance_chat(request: models.InsuranceChatRequest):
"""Handle insurance chat requests""" """Handle insurance chat requests"""
try: try:
current_page = None
if request.context and request.context.page:
page_id = request.context.page
current_page = await get_page_description(page_id)
result = await chat_service.process_insurance_chat( result = await chat_service.process_insurance_chat(
message=request.message, message=request.message,
session_id=request.session_id, session_id=request.session_id,
uid=str(request.userId), uid=str(request.userId),
current_page=current_page,
) )
return models.InsuranceChatResponse( return models.InsuranceChatResponse(

9
src/cache/page_cache.py vendored Normal file
View file

@ -0,0 +1,9 @@
from src.database import Session, Webpage
async def get_page_description(page_id: str) -> str | None:
with Session() as session:
page = session.query(Webpage).filter(Webpage.id == page_id).first()
if not page:
return None
return page.description

View file

@ -1,4 +1,4 @@
from sqlalchemy import BigInteger, Column, MetaData, String, Float, Text, Index from sqlalchemy import BigInteger, Column, MetaData, String, Float, Text, Index, Integer
from sqlalchemy.orm import DeclarativeBase from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine from sqlalchemy import create_engine
@ -26,5 +26,13 @@ Index(
) )
class Webpage(Base):
__tablename__ = "webpage"
id = Column(String, primary_key=True, index=True)
n = Column(Integer, index=True)
description = Column(String)
engine = create_engine(settings.DATABASE_URL) engine = create_engine(settings.DATABASE_URL)
Session = sessionmaker(autocommit=False, autoflush=False, bind=engine) Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)

View file

@ -1,11 +1,13 @@
import json import json
import httpx
from typing import Dict, Any, List, Optional from typing import Dict, Any, List, Optional
from src.models import ApplicantParam, ChatHook, PlansParam import httpx
from ..config import settings
from src.models import ApplicantParam, ChatHook, PlansParam, InsuranceChatContext
from .session_service import session_service from .session_service import session_service
from ..api.v1.models import Source, HistoryItem from ..api.v1.models import Source, HistoryItem
from ..config import settings
class ChatService: class ChatService:
"""Service for handling chat functionality with talestorm-ai""" """Service for handling chat functionality with talestorm-ai"""
@ -108,15 +110,18 @@ class ChatService:
elif kind == "response": elif kind == "response":
parts = item.get("parts", []) parts = item.get("parts", [])
for part in parts: for part in parts:
if part.get("part_kind") == "text": if part.get("tool_name") == "final_result":
tool_args = json.loads(part.get("args"))
history.append(HistoryItem( history.append(HistoryItem(
role="assistant", role="assistant",
message=part.get("content", "") message=tool_args.get("answer", "")
)) ))
return history return history
return [] return []
except Exception as e: except Exception as e:
# raise e
print(f"Error getting chat history: {e}") print(f"Error getting chat history: {e}")
return [] return []
@ -130,7 +135,7 @@ class ChatService:
# For now, return empty list - this would be populated when RAG is implemented # For now, return empty list - this would be populated when RAG is implemented
return [] return []
async def process_insurance_chat(self, message: str, session_id: Optional[str] = None, uid: Optional[int] = None) -> Dict[str, Any]: async def process_insurance_chat(self, message: str, session_id: Optional[str] = None, uid: Optional[int] = None, current_page: Optional[str] = None) -> Dict[str, Any]:
"""Process an insurance chat request""" """Process an insurance chat request"""
try: try:
if not session_id: if not session_id:
@ -143,6 +148,8 @@ class ChatService:
if uid: if uid:
user_state = await self.get_user_state(uid) user_state = await self.get_user_state(uid)
instructions += f"\n\n# User Information\nApplication state (None means that application was not sent or pending):\n{user_state}" instructions += f"\n\n# User Information\nApplication state (None means that application was not sent or pending):\n{user_state}"
if current_page:
instructions += f"\n\n# User now is currently on page:"
chat_response = await self.send_message(session_id, message, instructions) chat_response = await self.send_message(session_id, message, instructions)
history = await self.get_chat_history(session_id) history = await self.get_chat_history(session_id)