Files
Metacase/src/app/vitoria-ai-page/vitoria-ai-page.ts
T
2026-08-14 16:03:47 +01:00

158 lines
4.5 KiB
TypeScript

import { CommonModule } from '@angular/common';
import { HttpErrorResponse } from '@angular/common/http';
import { Component, ElementRef, ViewChild, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { RouterLink } from '@angular/router';
import { finalize } from 'rxjs';
import { ChatMessage, VitoriaAiService } from './vitoria-ai.service';
@Component({
selector: 'app-vitoria-ai-page',
standalone: true,
imports: [CommonModule, FormsModule, RouterLink],
templateUrl: './vitoria-ai-page.html',
styleUrl: './vitoria-ai-page.css'
})
export class VitoriaAiPageComponent {
@ViewChild('scrollContainer') private scrollContainer?: ElementRef<HTMLDivElement>;
private readonly chatService = inject(VitoriaAiService);
readonly appName = 'Vitoria AI';
readonly badge = 'Beta Release';
prompt = '';
isLoading = false;
conversations: string[] = [];
messages: ChatMessage[] = [
{
id: crypto.randomUUID(),
role: 'assistant',
content: 'Ola. Sou a Vitoria AI, uma assistente virtual para a area da formacao. Em que posso ajudar?',
createdAt: new Date()
}
];
newChat(): void {
this.prompt = '';
this.isLoading = false;
this.messages = [
{
id: crypto.randomUUID(),
role: 'assistant',
content: 'Nova conversa iniciada. Em que posso ajudar?',
createdAt: new Date()
}
];
this.scrollToBottom();
}
send(): void {
const content = this.prompt.trim();
if (!content || this.isLoading) {
return;
}
const userMessage: ChatMessage = {
id: crypto.randomUUID(),
role: 'user',
content,
createdAt: new Date()
};
this.messages = [...this.messages, userMessage];
this.prompt = '';
this.isLoading = true;
this.trackConversation(content);
this.scrollToBottom();
this.chatService
.sendMessage(
content,
this.messages.map(({ role, content: messageContent, createdAt }) => ({
role,
content: messageContent,
createdAt
}))
)
.pipe(finalize(() => (this.isLoading = false)))
.subscribe({
next: (reply) => {
const assistantMessage: ChatMessage = {
id: crypto.randomUUID(),
role: 'assistant',
content: reply.resposta || 'Sem resposta do servico.',
createdAt: new Date(),
sources: reply.fontes ?? []
};
this.messages = [...this.messages, assistantMessage];
this.scrollToBottom();
},
error: (error: unknown) => {
const errorMessage: ChatMessage = {
id: crypto.randomUUID(),
role: 'assistant',
content: this.getErrorMessage(error),
createdAt: new Date(),
isError: true
};
this.messages = [...this.messages, errorMessage];
this.scrollToBottom();
}
});
}
handleKeyDown(event: KeyboardEvent): void {
if (event.key === 'Enter' && !event.shiftKey) {
event.preventDefault();
this.send();
}
}
trackByMessage(_: number, message: ChatMessage): string {
return message.id;
}
private trackConversation(content: string): void {
const normalized = content.slice(0, 60);
this.conversations = [normalized, ...this.conversations.filter((item) => item !== normalized)].slice(0, 6);
}
private scrollToBottom(): void {
queueMicrotask(() => {
const native = this.scrollContainer?.nativeElement;
if (native) {
native.scrollTop = native.scrollHeight;
}
});
}
private getErrorMessage(error: unknown): string {
if (error && typeof error === 'object' && 'name' in error && error.name === 'TimeoutError') {
return 'O backend demorou demasiado tempo a responder. Verifica a latencia do modelo e do endpoint Python.';
}
if (error instanceof HttpErrorResponse) {
const detail =
typeof error.error?.detail === 'string'
? error.error.detail
: typeof error.error?.message === 'string'
? error.error.message
: typeof error.error === 'string'
? error.error
: '';
if (error.status === 0) {
return 'Nao foi possivel ligar ao backend da Vitoria AI. Confirma que o servico Python esta em execucao e acessivel para este servidor.';
}
return detail ? `Erro do backend (${error.status}): ${detail}` : `Erro do backend (${error.status}).`;
}
return 'O pedido falhou por um erro inesperado ao comunicar com o backend.';
}
}