[V0.1 WORKING] Added chat, profile, & calendar screen implementations.

This commit is contained in:
c-d-p
2025-04-18 17:30:09 +02:00
parent bf7eb8275c
commit 8d884111fd
19 changed files with 613 additions and 181 deletions

View File

@@ -14,7 +14,7 @@ def lifespan_factory() -> Callable[[FastAPI], _AsyncGeneratorContextManager[Any]
@asynccontextmanager
async def lifespan(app: FastAPI):
Base.metadata.drop_all(bind=get_engine())
# Base.metadata.drop_all(bind=get_engine())
Base.metadata.create_all(bind=get_engine())
yield

View File

@@ -14,4 +14,11 @@ class CalendarEventResponse(CalendarEventCreate):
user_id: int
class Config:
from_attributes = True
from_attributes = True
class CalendarEventUpdate(BaseModel):
title: str | None = None
description: str | None = None
start: datetime | None = None
end: datetime | None = None
location: str | None = None

View File

@@ -1,53 +1,74 @@
# modules/nlp/api.py
from fastapi import APIRouter, Depends
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from core.database import get_db
from core.exceptions import bad_request_exception
from modules.auth.dependencies import get_current_user
from modules.auth.models import User
from modules.nlp.service import process_request, ask_ai
from modules.nlp.schemas import ProcessCommandRequest
from modules.calendar.service import create_calendar_event, get_calendar_events, update_calendar_event, delete_calendar_event
from modules.calendar.schemas import CalendarEventCreate
from modules.calendar.schemas import CalendarEventCreate, CalendarEventUpdate
router = APIRouter(prefix="/nlp", tags=["nlp"])
@router.post("/process-command")
def process_command(user_input: str, current_user: User = Depends(get_current_user), db: Session = Depends(get_db)):
def process_command(request_data: ProcessCommandRequest, current_user: User = Depends(get_current_user), db: Session = Depends(get_db)):
"""
Process the user command and return the appropriate action.
Process the user command, execute the action, and return a user-friendly response.
"""
command = process_request(user_input)
if "error" in command:
raise bad_request_exception(command["error"])
match command["intent"]:
case "ask_ai":
result = ask_ai(**command["params"])
return {"action": "ai_response", "details": result}
case "get_calendar_events":
result = get_calendar_events(db, current_user.id, **command["params"])
return {"action": "calendar_events_retrieved", "details": result}
case "add_calendar_event":
event = CalendarEventCreate(**command["params"])
result = create_calendar_event(db, current_user.id, event)
return {"action": "calendar_event_created", "details": result}
user_input = request_data.user_input
command_data = process_request(user_input)
intent = command_data["intent"]
params = command_data["params"]
response_text = command_data["response_text"]
case "update_calendar_event":
event = CalendarEventCreate(**command["params"])
result = update_calendar_event(db, current_user.id, 0, event_data=event) ## PLACEHOLDER
return {"action": "calendar_event_updated", "details": result}
case "delete_calendar_event":
result = update_calendar_event(db, current_user.id, 0) ## PLACEHOLDER
return {"action": "calendar_event_deleted", "details": result}
if intent == "error":
raise HTTPException(status_code=400, detail=response_text)
if intent == "clarification_needed":
return {"response": response_text}
if intent == "unknown":
return {"response": response_text}
try:
match intent:
case "ask_ai":
ai_answer = ask_ai(**params)
return {"response": ai_answer}
case "unknown":
return {"action": "unknown_command", "details": command["params"]}
case _:
raise bad_request_exception(400, detail="Unrecognized command")
case "get_calendar_events":
result = get_calendar_events(db, current_user.id, **params)
return {"response": response_text, "details": result}
case "add_calendar_event":
event = CalendarEventCreate(**params)
result = create_calendar_event(db, current_user.id, event)
return {"response": response_text, "details": result}
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.")
event_data = CalendarEventUpdate(**params)
result = update_calendar_event(db, current_user.id, event_id, event_data=event_data)
return {"response": response_text, "details": result}
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.")
result = delete_calendar_event(db, current_user.id, event_id)
return {"response": response_text, "details": {"deleted": True, "event_id": event_id}}
case _:
print(f"Warning: Unhandled intent '{intent}' reached api.py match statement.")
raise HTTPException(status_code=500, detail="An unexpected error occurred processing the command.")
except HTTPException as http_exc:
raise http_exc
except Exception as e:
print(f"Error executing intent '{intent}': {e}")
raise HTTPException(status_code=500, detail="Sorry, I encountered an error while trying to perform that action.")

View File

@@ -0,0 +1,5 @@
# modules/nlp/schemas.py
from pydantic import BaseModel
class ProcessCommandRequest(BaseModel):
user_input: str

View File

@@ -10,25 +10,53 @@ client = genai.Client(api_key="AIzaSyBrte_mETZJce8qE6cRTSz_fHOjdjlShBk")
### Base prompt for MAIA, used for inital user requests
SYSTEM_PROMPT = """
You are MAIA - My AI Assistant. Your job is to parse user requests into structured JSON commands.
You are MAIA - My AI Assistant. Your job is to parse user requests into structured JSON commands and generate a user-facing response text.
Available functions:
1. ask_ai(request: str). If the intent of the request is a simple question (e.x. What is the weather like today?), you should call this function, and forward the user's request as the parameter.
2. get_calendar_events(start: Optional[datetime], end: Optional[datetime])
3. add_calendar_event(title: str, description: str, start: datetime, end: Optional[datetime], location: str)
4. update_calendar_event(event_id: int, title: Optional[str], description: Optional[str], start: Optional[datetime], end: Optional[datetime], location: Optional[str])
5. delete_calendar_event(event_id: int)
Available functions/intents:
1. ask_ai(request: str): Use for simple questions (e.g., weather, facts). Forward the user's request.
2. get_calendar_events(start: Optional[datetime], end: Optional[datetime]): Retrieve calendar events.
3. add_calendar_event(title: str, description: str, start: datetime, end: Optional[datetime], location: str): Add a new event.
4. update_calendar_event(event_id: int, title: Optional[str], description: Optional[str], start: Optional[datetime], end: Optional[datetime], location: Optional[str]): Update an existing event. Requires event_id.
5. delete_calendar_event(event_id: int): Delete an event. Requires event_id.
6. clarification_needed(request: str): Use this if the user's request is ambiguous or lacks necessary information (like event_id for update/delete). The original user request should be passed in the 'request' parameter.
Respond **ONLY** with JSON like this:
**IMPORTANT:** Respond ONLY with JSON containing BOTH "intent" and "params", AND a "response_text" field.
- "response_text" should be a friendly, user-facing message confirming the action taken, providing the answer, or asking for clarification.
Examples:
User: Add a meeting tomorrow at 3pm about project X
MAIA:
{
"intent": "add_calendar_event",
"params": {
"title": "Team Meeting",
"description": "Discuss project updates",
"start": "2025-04-16 15:00:00.000000+00:00",
"end": "2025-04-16 16:00:00.000000+00:00",
"location": "Office"
}
"title": "Meeting",
"description": "Project X",
"start": "2025-04-19 15:00:00.000000+00:00",
"end": null,
"location": null
},
"response_text": "Okay, I've added a meeting about Project X to your calendar for tomorrow at 3 PM."
}
User: What's the weather like?
MAIA:
{
"intent": "ask_ai",
"params": {
"request": "What's the weather like?"
},
"response_text": "Let me check the weather for you."
}
User: Delete the team sync event.
MAIA:
{
"intent": "clarification_needed",
"params": {
"request": "Delete the team sync event."
},
"response_text": "Okay, I can help with that. Could you please provide the ID or more specific details about the 'team sync' event you want me to delete?"
}
The datetime right now is """+str(datetime.now(timezone.utc))+""".
@@ -45,6 +73,7 @@ Here is the user request:
def process_request(request: str):
"""
Process the user request using the Google GenAI API.
Expects a JSON response with intent, params, and response_text.
"""
response = client.models.generate_content(
model="gemini-2.0-flash",
@@ -52,41 +81,25 @@ def process_request(request: str):
config={
"temperature": 0.3, # Less creativity, more factual
"response_mime_type": "application/json",
# "response_schema": { ### NOT WORKING
# "type": "object",
# "properties": {
# "intent": {
# "type": "string",
# "enum": [
# "get_calendar_events",
# "add_calendar_event",
# "update_calendar_event",
# "delete_calendar_event"
# ]
# },
# "params": {
# "type": "object",
# "properties": {
# "title": {"type": "string"},
# "description": {"type": "string"},
# "start": {"type": "string", "format": "date-time"},
# "end": {"type": "string", "format": "date-time"},
# "location": {"type": "string"},
# "event_id": {"type": "integer"},
# },
# }
# },
# "required": ["intent", "params"]
# }
}
)
# Parse the JSON response
try:
return json.loads(response.text)
except ValueError:
raise ValueError("Invalid JSON response from AI")
parsed_response = json.loads(response.text)
# Validate required fields
if not all(k in parsed_response for k in ("intent", "params", "response_text")):
raise ValueError("AI response missing required fields (intent, params, response_text)")
return parsed_response
except (json.JSONDecodeError, ValueError) as e:
print(f"Error parsing AI response: {e}")
print(f"Raw AI response: {response.text}")
# Return a structured error that the API layer can handle
return {
"intent": "error",
"params": {},
"response_text": "Sorry, I had trouble understanding that request or formulating a response. Could you please try rephrasing?"
}
def ask_ai(request: str):
"""