-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
67 lines (49 loc) · 1.89 KB
/
main.py
File metadata and controls
67 lines (49 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
from datetime import datetime, timezone
from fastapi import FastAPI, HTTPException
from typing import List, Dict
from pydantic import BaseModel, Field
app = FastAPI()
class Message(BaseModel):
role:str
content:str
class ChatSession(BaseModel):
session_id:int
session_user:str
created_at:datetime
messages: List[Message]= Field(default_factory=list)
class CreateSessionRequest(BaseModel):
username: str
# In-memory data structure to store chat sessions and messages
session_store: Dict[int, ChatSession] = {}
chat_store: Dict[int, List[Message]] = {}
@app.post("/sessions/", response_model=ChatSession)
def create_session(req: CreateSessionRequest):
username = req.username.strip().lower()
# Validation
if not username:
raise HTTPException(status_code=400, detail="Username cannot be empty or whitespace.")
# Generate session_id
session_id = len(session_store) + 1
created_at = datetime.now(timezone.utc)
# Create session and initialize chat
new_session = ChatSession(
session_id=session_id,
session_user=username,
created_at=created_at,
messages=[]
)
session_store[session_id] = new_session
chat_store[session_id] = [] # Initialize empty chat list
return new_session
@app.post("/sessions/{session_id}/messages", response_model=ChatSession)
def add_message(session_id: int, message: Message):
if session_id not in session_store:
raise HTTPException(status_code=404, detail="Session not found")
chat_store[session_id].append(message)
session_store[session_id].messages = chat_store[session_id]
return session_store[session_id]
@app.get("/sessions/{session_id}/messages", response_model=ChatSession)
def get_session(session_id: int):
if session_id not in session_store:
raise HTTPException(status_code=404, detail="Session not found")
return session_store[session_id]