Skip to content

Commit e891d9e

Browse files
committed
replace session id with user id
1 parent e2098da commit e891d9e

File tree

5 files changed

+157
-229
lines changed

5 files changed

+157
-229
lines changed

client/src/components/ChatTab.tsx

Lines changed: 19 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,20 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/com
44
import { Button } from '@/components/ui/button';
55
import { Input } from '@/components/ui/input';
66
import { MessageSquare, Send, Bot, User, Sparkles, FileText, Clock } from 'lucide-react';
7-
import { apiService, ChatMessage, ChatSessionResponse } from '@/lib/api';
7+
import { apiService, ChatMessage } from '@/lib/api';
88
import ReactMarkdown from 'react-markdown';
9+
import { useAuth } from '@/contexts/AuthContext';
910

1011
interface ChatTabProps {
1112
uploadedFiles: File[];
1213
documentIds: string[];
1314
}
1415

1516
const ChatTab = ({ uploadedFiles, documentIds }: ChatTabProps) => {
17+
const { user } = useAuth();
1618
const [messages, setMessages] = useState<ChatMessage[]>([]);
1719
const [inputMessage, setInputMessage] = useState('');
1820
const [isTyping, setIsTyping] = useState(false);
19-
const [sessionId, setSessionId] = useState<string | null>(null);
2021
const [isLoading, setIsLoading] = useState(false);
2122
const [error, setError] = useState<string | null>(null);
2223
const messagesEndRef = useRef<HTMLDivElement>(null);
@@ -29,47 +30,40 @@ const ChatTab = ({ uploadedFiles, documentIds }: ChatTabProps) => {
2930
scrollToBottom();
3031
}, [messages]);
3132

32-
// Initialize chat session when component mounts or documentIds change
33+
// Initialize chat when component mounts or documentIds change
3334
useEffect(() => {
34-
const initializeChatSession = async () => {
35-
if (documentIds.length > 0 && !sessionId) {
35+
const initializeChat = async () => {
36+
if (documentIds.length > 0 && user) {
3637
setIsLoading(true);
3738
setError(null);
3839
try {
39-
// Create chat session immediately with all provided documents
40-
const response = await apiService.createChatSession(documentIds);
41-
setSessionId(response.sessionId);
42-
setMessages(response.messages);
40+
// Optionally, fetch previous messages for user_id and documentIds if needed
41+
setMessages([]); // Start with empty messages
4342
} catch (error) {
44-
console.error('Failed to create chat session:', error);
45-
setError('Failed to create chat session. Please try again.');
43+
console.error('Failed to initialize chat:', error);
44+
setError('Failed to initialize chat. Please try again.');
4645
} finally {
4746
setIsLoading(false);
4847
}
4948
}
5049
};
51-
52-
initializeChatSession();
53-
}, [documentIds, sessionId]);
54-
55-
// Remove polling logic since we don't wait for processing anymore
50+
initializeChat();
51+
// eslint-disable-next-line react-hooks/exhaustive-deps
52+
}, [documentIds, user]);
5653

5754
const handleSendMessage = async () => {
58-
if (!inputMessage.trim() || !sessionId) return;
59-
55+
if (!inputMessage.trim() || !user) return;
6056
const userMessage: ChatMessage = {
6157
id: Date.now().toString(),
6258
content: inputMessage,
6359
sender: 'user',
6460
timestamp: new Date().toISOString(),
6561
};
66-
6762
setMessages(prev => [...prev, userMessage]);
6863
setInputMessage('');
6964
setIsTyping(true);
70-
7165
try {
72-
const response = await apiService.sendMessage(sessionId, inputMessage, documentIds);
66+
const response = await apiService.sendMessage(user.id, inputMessage, documentIds);
7367
const botMessage: ChatMessage = {
7468
id: response.id,
7569
content: response.content,
@@ -78,7 +72,6 @@ const ChatTab = ({ uploadedFiles, documentIds }: ChatTabProps) => {
7872
sources: response.sources,
7973
documentReferences: response.documentReferences
8074
};
81-
8275
setMessages(prev => [...prev, botMessage]);
8376
} catch (error) {
8477
console.error('Failed to send message:', error);
@@ -137,7 +130,6 @@ const ChatTab = ({ uploadedFiles, documentIds }: ChatTabProps) => {
137130
variant="outline"
138131
onClick={() => {
139132
setError(null);
140-
setSessionId(null);
141133
}}
142134
>
143135
Retry
@@ -165,7 +157,7 @@ const ChatTab = ({ uploadedFiles, documentIds }: ChatTabProps) => {
165157
</span>
166158
<span className="flex items-center text-green-600">
167159
<div className="w-2 h-2 bg-green-500 rounded-full mr-1"></div>
168-
{sessionId ? 'Online' : 'Connecting...'}
160+
{user ? 'Online' : 'Connecting...'}
169161
</span>
170162
</CardDescription>
171163
</div>
@@ -276,14 +268,14 @@ const ChatTab = ({ uploadedFiles, documentIds }: ChatTabProps) => {
276268
<Input
277269
value={inputMessage}
278270
onChange={(e) => setInputMessage(e.target.value)}
279-
placeholder={sessionId ? "Ask a question about your course materials..." : "Connecting to chat service..."}
271+
placeholder={user ? "Ask a question about your course materials..." : "Connecting to chat service..."}
280272
onKeyDown={(e) => e.key === 'Enter' && handleSendMessage()}
281-
disabled={!sessionId}
273+
disabled={!user}
282274
className="flex-1"
283275
/>
284276
<Button
285277
onClick={handleSendMessage}
286-
disabled={!inputMessage.trim() || isTyping || !sessionId}
278+
disabled={!inputMessage.trim() || isTyping || !user}
287279
className="bg-blue-500 hover:bg-blue-600"
288280
>
289281
<Send className="h-4 w-4" />

client/src/lib/api.ts

Lines changed: 4 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -200,12 +200,6 @@ export interface ChatSessionRequest {
200200
documentIds: string[];
201201
}
202202

203-
export interface ChatSessionResponse {
204-
sessionId: string;
205-
messages: ChatMessage[];
206-
documentsInContext: string[];
207-
}
208-
209203
export interface ChatMessageRequest {
210204
message: string;
211205
documentIds?: string[];
@@ -540,39 +534,12 @@ class ApiService {
540534
}
541535

542536
// Chat methods
543-
async createChatSession(documentIds: string[]): Promise<ChatSessionResponse> {
544-
const response = await this.authenticatedFetch(`${this.baseUrl}/api/genai/chat/sessions`, {
537+
async sendMessage(user_id: string, message: string, documentIds: string[] = []): Promise<ChatMessageResponse> {
538+
const payload: any = { user_id, message, documentIds };
539+
const response = await this.authenticatedFetch(`${this.baseUrl}/api/genai/chat/messages`, {
545540
method: 'POST',
546541
headers: this.getHeaders(),
547-
body: JSON.stringify({ documentIds }),
548-
});
549-
550-
if (!response.ok) {
551-
const errorData = await response.json().catch(() => ({}));
552-
throw new Error(errorData.error || `Failed to create chat session: ${response.status} ${response.statusText}`);
553-
}
554-
555-
return response.json();
556-
}
557-
558-
async getChatSession(sessionId: string): Promise<ChatSessionResponse> {
559-
const response = await this.authenticatedFetch(`${this.baseUrl}/api/genai/chat/sessions/${sessionId}`);
560-
561-
if (!response.ok) {
562-
throw new Error(`Failed to get chat session: ${response.status} ${response.statusText}`);
563-
}
564-
565-
return response.json();
566-
}
567-
568-
async sendMessage(sessionId: string, message: string, documentIds: string[] = []): Promise<ChatMessageResponse> {
569-
const response = await this.authenticatedFetch(`${this.baseUrl}/api/genai/chat/sessions/${sessionId}/messages`, {
570-
method: 'POST',
571-
headers: this.getHeaders(),
572-
body: JSON.stringify({
573-
message,
574-
documentIds
575-
}),
542+
body: JSON.stringify(payload),
576543
});
577544

578545
if (!response.ok) {

server/genai-service/src/main/kotlin/de/tum/cit/aet/genai/controller/GenAiController.kt

Lines changed: 15 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ class GenAiController(
114114
fun createSession(
115115
@Valid @RequestBody request: CreateSessionRequest
116116
): DeferredResult<ResponseEntity<Any>> {
117-
logger.info("POST /genai/sessions for user: {}", request.sessionId)
117+
logger.info("POST /genai/sessions for user: {}", request.userId)
118118

119119
val result = DeferredResult<ResponseEntity<Any>>(600000L) // 10 minutes timeout
120120

@@ -163,16 +163,16 @@ class GenAiController(
163163
return result
164164
}
165165

166-
@PostMapping("/sessions/{sessionId}/messages")
166+
@PostMapping("/sessions/messages")
167167
fun addMessage(
168-
@PathVariable sessionId: String,
168+
@RequestHeader("X-User-ID") userId: String,
169169
@Valid @RequestBody request: PromptRequest
170170
): DeferredResult<ResponseEntity<Any>> {
171-
logger.info("POST /genai/sessions/{}/messages for user: {}", sessionId, request.sessionId)
171+
logger.info("POST /genai/sessions/messages for user: {}", userId)
172172

173173
val result = DeferredResult<ResponseEntity<Any>>(600000L) // 10 minutes timeout
174174

175-
genAiService.addMessageAsync(sessionId, request) { response, error ->
175+
genAiService.addMessageAsync(userId, request) { response, error ->
176176
if (error != null) {
177177
logger.error("Error adding message: {}", error.message, error)
178178
result.setResult(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(
@@ -404,16 +404,15 @@ class GenAiController(
404404
return result
405405
}
406406

407-
@GetMapping("/chat/sessions/{sessionId}")
407+
@GetMapping("/chat/sessions")
408408
fun getChatSession(
409-
@PathVariable sessionId: String,
410409
@RequestHeader("X-User-ID") userId: String
411410
): DeferredResult<ResponseEntity<Any>> {
412-
logger.info("GET /genai/chat/sessions/{} for user: {}", sessionId, userId)
411+
logger.info("GET /genai/chat/sessions for user: {}", userId)
413412

414413
val result = DeferredResult<ResponseEntity<Any>>(600000L) // 10 minutes timeout
415414

416-
genAiService.getChatSessionAsync(sessionId, userId) { response, error ->
415+
genAiService.getChatSessionAsync(userId) { response, error ->
417416
if (error != null) {
418417
logger.error("Error getting chat session: {}", error.message, error)
419418
result.setResult(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(
@@ -431,23 +430,22 @@ class GenAiController(
431430
return result
432431
}
433432

434-
@PostMapping("/chat/sessions/{sessionId}/messages")
433+
@PostMapping("/chat/sessions/messages")
435434
fun sendChatMessage(
436-
@PathVariable sessionId: String,
437-
@Valid @RequestBody request: SendMessageRequest,
438-
@RequestHeader("X-User-ID") userId: String
435+
@RequestHeader("X-User-ID") userId: String,
436+
@Valid @RequestBody request: SendMessageRequest
439437
): DeferredResult<ResponseEntity<Any>> {
440-
logger.info("POST /genai/chat/sessions/{}/messages for user: {}", sessionId, userId)
438+
logger.info("POST /genai/chat/sessions/messages for user: {}", userId)
441439

442440
val result = DeferredResult<ResponseEntity<Any>>(600000L) // 10 minutes timeout
443441

444-
genAiService.sendChatMessageAsync(sessionId, request, userId) { response, error ->
442+
genAiService.sendChatMessageAsync(userId, request) { response, error ->
445443
if (error != null) {
446444
logger.error("Error sending chat message: {}", error.message, error)
447445
result.setResult(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(
448446
ErrorResponse(
449-
error = "Message sending failed",
450-
message = "Failed to send message: ${error.message}",
447+
error = "Chat message failed",
448+
message = "Failed to send chat message: ${error.message}",
451449
timestamp = LocalDateTime.now().format(dateFormatter)
452450
)
453451
))

server/genai-service/src/main/kotlin/de/tum/cit/aet/genai/dto/GenAiDtos.kt

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -7,33 +7,33 @@ import jakarta.validation.constraints.NotNull
77

88
// Request DTOs for GenAI service
99
data class CreateSessionRequest(
10-
@JsonProperty("session_id")
11-
val sessionId: String,
10+
@JsonProperty("user_id")
11+
val userId: String,
1212
@JsonProperty("document_name")
1313
val documentName: String,
1414
@JsonProperty("document_base64")
1515
val documentBase64: String
1616
)
1717

1818
data class SummaryRequest(
19-
@JsonProperty("session_id")
20-
val sessionId: String
19+
@JsonProperty("user_id")
20+
val userId: String
2121
)
2222

2323
data class PromptRequest(
24-
@JsonProperty("session_id")
25-
val sessionId: String,
24+
@JsonProperty("user_id")
25+
val userId: String,
2626
val message: String
2727
)
2828

2929
data class QuizRequest(
30-
@JsonProperty("session_id")
31-
val sessionId: String
30+
@JsonProperty("user_id")
31+
val userId: String
3232
)
3333

3434
data class FlashcardRequest(
35-
@JsonProperty("session_id")
36-
val sessionId: String
35+
@JsonProperty("user_id")
36+
val userId: String
3737
)
3838

3939
// Response DTOs from GenAI service
@@ -179,17 +179,15 @@ data class ChatRequest(
179179
@JsonProperty("userId")
180180
val userId: String,
181181

182-
@JsonProperty("sessionId")
183-
val sessionId: String? = null,
184182
@JsonProperty("documentContext")
185183
val documentContext: String? = null
186184
)
187185

188186
data class ChatResponse(
189187
@JsonProperty("response")
190188
val response: String,
191-
@JsonProperty("sessionId")
192-
val sessionId: String,
189+
@JsonProperty("userId")
190+
val userId: String,
193191
@JsonProperty("timestamp")
194192
val timestamp: String
195193
)
@@ -207,8 +205,8 @@ data class ChatSessionRequest(
207205
)
208206

209207
data class ChatSessionResponse(
210-
@JsonProperty("sessionId")
211-
val sessionId: String,
208+
@JsonProperty("userId")
209+
val userId: String,
212210
@JsonProperty("messages")
213211
val messages: List<ChatMessageDto> = emptyList(),
214212
@JsonProperty("documentsInContext")

0 commit comments

Comments
 (0)