Fixed entire calendar layout + chat layout + chat history

This commit is contained in:
c-d-p
2025-04-21 15:36:59 +02:00
parent 9e8e179a94
commit c158ff4e0e
37 changed files with 1050 additions and 285 deletions

119
backend/alembic.ini Normal file
View File

@@ -0,0 +1,119 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts
# Use forward slashes (/) also on windows to provide an os agnostic path
script_location = alembic
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
# for all available tokens
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory.
prepend_sys_path = .
# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the python>=3.9 or backports.zoneinfo library and tzdata library.
# Any required deps can installed by adding `alembic[tz]` to the pip requirements
# string value is passed to ZoneInfo()
# leave blank for localtime
# timezone =
# max length of characters to apply to the "slug" field
# truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false
# version location specification; This defaults
# to alembic/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "version_path_separator" below.
# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions
# version path separator; As mentioned above, this is the character used to split
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
# Valid values for version_path_separator are:
#
# version_path_separator = :
# version_path_separator = ;
# version_path_separator = space
# version_path_separator = newline
#
# Use os.pathsep. Default configuration used for new projects.
version_path_separator = os
# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
# sqlalchemy.url = driver://user:pass@localhost/dbname
sqlalchemy.url = postgresql://maia:maia@localhost:5432/maia
[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples
# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME
# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
# hooks = ruff
# ruff.type = exec
# ruff.executable = %(here)s/.venv/bin/ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARNING
handlers = console
qualname =
[logger_sqlalchemy]
level = WARNING
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S

1
backend/alembic/README Normal file
View File

@@ -0,0 +1 @@
Generic single-database configuration.

Binary file not shown.

97
backend/alembic/env.py Normal file
View File

@@ -0,0 +1,97 @@
import os
import sys
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
# --- Add project root to sys.path ---
# This assumes alembic/env.py is one level down from the project root (backend/)
PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, PROJECT_DIR)
# -----------------------------------
# --- Import Base and Models ---
from core.database import Base # Import your Base
# Import all your models here so Base registers them
from modules.auth.models import User # Example: Import User model
from modules.calendar.models import CalendarEvent # Example: Import CalendarEvent model
from modules.nlp.models import ChatMessage # Import the new ChatMessage model
# Add imports for any other models you have
# ----------------------------
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
# --- Set target_metadata ---
target_metadata = Base.metadata
# ---------------------------
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()

View File

@@ -0,0 +1,28 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[str, None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
def upgrade() -> None:
"""Upgrade schema."""
${upgrades if upgrades else "pass"}
def downgrade() -> None:
"""Downgrade schema."""
${downgrades if downgrades else "pass"}

View File

@@ -0,0 +1,32 @@
"""Initial migration with existing tables
Revision ID: 69069d6184b3
Revises:
Create Date: 2025-04-21 01:14:33.233195
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '69069d6184b3'
down_revision: Union[str, None] = None
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! ###
pass
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###

View File

@@ -17,6 +17,10 @@ def get_engine():
raise ValueError("DB_URL is not set in Settings.")
print(f"Connecting to database at {settings.DB_URL}")
_engine = create_engine(settings.DB_URL)
try:
_engine.connect()
except Exception as e:
raise Exception("Database connection failed. Is the database server running?")
Base.metadata.create_all(_engine) # Create tables here
return _engine

View File

@@ -38,6 +38,7 @@ app.add_middleware(
allow_origins=[
"http://localhost:8081", # Keep for web testing if needed
"http://192.168.1.9:8081", # Add your mobile device/emulator origin (adjust port if needed)
"http://192.168.255.221:8081",
# Add other origins if necessary, e.g., production frontend URL
],
allow_credentials=True,

View File

@@ -57,4 +57,4 @@ class CalendarEventResponse(CalendarEventBase):
return v
class Config:
from_attributes = True # Changed from orm_mode
from_attributes = True

Binary file not shown.

View File

@@ -7,13 +7,13 @@ from core.database import get_db
from modules.auth.dependencies import get_current_user
from modules.auth.models import User
from modules.nlp.service import process_request, ask_ai
# Import the response schema
# Import the new service functions and Enum
from modules.nlp.service import process_request, ask_ai, save_chat_message, get_chat_history, MessageSender
# Import the response schema and the new ChatMessage model for response type hinting
from modules.nlp.schemas import ProcessCommandRequest, ProcessCommandResponse
from modules.nlp.models import ChatMessage # Import ChatMessage model
from modules.calendar.service import create_calendar_event, get_calendar_events, update_calendar_event, delete_calendar_event
# Import the CalendarEvent *model* for type hinting
from modules.calendar.models import CalendarEvent
# Import the CalendarEvent Pydantic schemas for data validation
from modules.calendar.schemas import CalendarEventCreate, CalendarEventUpdate
router = APIRouter(prefix="/nlp", tags=["nlp"])
@@ -35,9 +35,14 @@ def format_calendar_events(events: List[CalendarEvent]) -> List[str]:
@router.post("/process-command", response_model=ProcessCommandResponse)
def process_command(request_data: ProcessCommandRequest, current_user: User = Depends(get_current_user), db: Session = Depends(get_db)):
"""
Process the user command, execute the action, and return user-friendly responses.
Process the user command, save messages, execute action, save response, and return user-friendly responses.
"""
user_input = request_data.user_input
# --- Save User Message ---
save_chat_message(db, user_id=current_user.id, sender=MessageSender.USER, text=user_input)
# ------------------------
command_data = process_request(user_input)
intent = command_data["intent"]
params = command_data["params"]
@@ -45,10 +50,19 @@ def process_command(request_data: ProcessCommandRequest, current_user: User = De
responses = [response_text] # Start with the initial response
# --- Save Initial AI Response ---
# Save the first response generated by process_request
save_chat_message(db, user_id=current_user.id, sender=MessageSender.AI, text=response_text)
# -----------------------------
if intent == "error":
raise HTTPException(status_code=400, detail=response_text)
# Don't raise HTTPException here if we want to save the error message
# Instead, return the error response directly
# save_chat_message(db, user_id=current_user.id, sender=MessageSender.AI, text=response_text) # Already saved above
return ProcessCommandResponse(responses=responses)
if intent == "clarification_needed" or intent == "unknown":
# save_chat_message(db, user_id=current_user.id, sender=MessageSender.AI, text=response_text) # Already saved above
return ProcessCommandResponse(responses=responses)
try:
@@ -56,48 +70,100 @@ def process_command(request_data: ProcessCommandRequest, current_user: User = De
case "ask_ai":
ai_answer = ask_ai(**params)
responses.append(ai_answer)
# --- Save Additional AI Response ---
save_chat_message(db, user_id=current_user.id, sender=MessageSender.AI, text=ai_answer)
# ---------------------------------
return ProcessCommandResponse(responses=responses)
case "get_calendar_events":
# get_calendar_events returns List[CalendarEvent models]
events: List[CalendarEvent] = get_calendar_events(db, current_user.id, **params)
responses.extend(format_calendar_events(events))
formatted_responses = format_calendar_events(events)
responses.extend(formatted_responses)
# --- Save Additional AI Responses ---
for resp in formatted_responses:
save_chat_message(db, user_id=current_user.id, sender=MessageSender.AI, text=resp)
# ----------------------------------
return ProcessCommandResponse(responses=responses)
case "add_calendar_event":
# Validate input with Pydantic schema
event_data = CalendarEventCreate(**params)
created_event = create_calendar_event(db, current_user.id, event_data)
start_str = created_event.start.strftime("%Y-%m-%d %H:%M") if created_event.start else "No start time"
title = created_event.title or "Untitled Event"
responses.append(f"Added: {title} starting at {start_str}.")
add_response = f"Added: {title} starting at {start_str}."
responses.append(add_response)
# --- Save Additional AI Response ---
save_chat_message(db, user_id=current_user.id, sender=MessageSender.AI, text=add_response)
# ---------------------------------
return ProcessCommandResponse(responses=responses)
case "update_calendar_event":
event_id = params.pop('event_id', None)
if event_id is None:
raise HTTPException(status_code=400, detail="Event ID is required for update.")
# Validate input with Pydantic schema
# Save the error message before raising
error_msg = "Event ID is required for update."
save_chat_message(db, user_id=current_user.id, sender=MessageSender.AI, text=error_msg)
raise HTTPException(status_code=400, detail=error_msg)
event_data = CalendarEventUpdate(**params)
updated_event = update_calendar_event(db, current_user.id, event_id, event_data=event_data)
title = updated_event.title or "Untitled Event"
responses.append(f"Updated event ID {updated_event.id}: {title}.")
update_response = f"Updated event ID {updated_event.id}: {title}."
responses.append(update_response)
# --- Save Additional AI Response ---
save_chat_message(db, user_id=current_user.id, sender=MessageSender.AI, text=update_response)
# ---------------------------------
return ProcessCommandResponse(responses=responses)
case "delete_calendar_event":
event_id = params.get('event_id')
if event_id is None:
raise HTTPException(status_code=400, detail="Event ID is required for delete.")
# Save the error message before raising
error_msg = "Event ID is required for delete."
save_chat_message(db, user_id=current_user.id, sender=MessageSender.AI, text=error_msg)
raise HTTPException(status_code=400, detail=error_msg)
delete_calendar_event(db, current_user.id, event_id)
responses.append(f"Deleted event ID {event_id}.")
delete_response = f"Deleted event ID {event_id}."
responses.append(delete_response)
# --- Save Additional AI Response ---
save_chat_message(db, user_id=current_user.id, sender=MessageSender.AI, text=delete_response)
# ---------------------------------
return ProcessCommandResponse(responses=responses)
case _:
print(f"Warning: Unhandled intent '{intent}' reached api.py match statement.")
# The initial response_text was already saved
return ProcessCommandResponse(responses=responses)
except HTTPException as http_exc:
# Don't save again if already saved before raising
if http_exc.status_code != 400 or ('event_id' not in http_exc.detail.lower()):
save_chat_message(db, user_id=current_user.id, sender=MessageSender.AI, text=http_exc.detail)
raise http_exc
except Exception as e:
print(f"Error executing intent '{intent}': {e}")
return ProcessCommandResponse(responses=["Sorry, I encountered an error while trying to perform that action."])
error_response = "Sorry, I encountered an error while trying to perform that action."
# --- Save Final Error AI Response ---
save_chat_message(db, user_id=current_user.id, sender=MessageSender.AI, text=error_response)
# ----------------------------------
return ProcessCommandResponse(responses=[error_response])
# --- New Endpoint for Chat History ---
# Define a Pydantic schema for the response (optional but good practice)
from pydantic import BaseModel
from datetime import datetime
class ChatMessageResponse(BaseModel):
id: int
sender: MessageSender # Use the enum directly
text: str
timestamp: datetime
class Config:
from_attributes = True # Allow Pydantic to work with ORM models
@router.get("/history", response_model=List[ChatMessageResponse])
def read_chat_history(current_user: User = Depends(get_current_user), db: Session = Depends(get_db)):
"""Retrieves the last 50 chat messages for the current user."""
history = get_chat_history(db, user_id=current_user.id, limit=50)
return history
# -------------------------------------

View File

@@ -0,0 +1,23 @@
\
# /home/cdp/code/MAIA/backend/modules/nlp/models.py
from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey, Enum as SQLEnum
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
import enum
from core.database import Base
class MessageSender(enum.Enum):
USER = "user"
AI = "ai"
class ChatMessage(Base):
__tablename__ = "chat_messages"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
sender = Column(SQLEnum(MessageSender), nullable=False)
text = Column(Text, nullable=False)
timestamp = Column(DateTime(timezone=True), server_default=func.now())
owner = relationship("User") # Relationship to the User model

View File

@@ -1,8 +1,14 @@
# modules/nlp/service.py
from sqlalchemy.orm import Session
from sqlalchemy import desc # Import desc for ordering
from google import genai
import json
from datetime import datetime, timezone
from typing import List # Import List
# Import the new model and Enum
from .models import ChatMessage, MessageSender
# from core.config import settings
# client = genai.Client(api_key=settings.GOOGLE_API_KEY)
@@ -70,6 +76,27 @@ Here is some context for you:
Here is the user request:
"""
# --- Chat History Service Functions ---
def save_chat_message(db: Session, user_id: int, sender: MessageSender, text: str):
"""Saves a chat message to the database."""
db_message = ChatMessage(user_id=user_id, sender=sender, text=text)
db.add(db_message)
db.commit()
db.refresh(db_message)
return db_message
def get_chat_history(db: Session, user_id: int, limit: int = 50) -> List[ChatMessage]:
"""Retrieves the last 'limit' chat messages for a user."""
return db.query(ChatMessage)\
.filter(ChatMessage.user_id == user_id)\
.order_by(desc(ChatMessage.timestamp))\
.limit(limit)\
.all()[::-1] # Reverse to get oldest first for display order
# --- Existing NLP Service Functions ---
def process_request(request: str):
"""
Process the user request using the Google GenAI API.

View File

@@ -43,3 +43,4 @@ tzdata==2025.2
uvicorn==0.34.1
vine==5.1.0
wcwidth==0.2.13
alembic