flare / flare-ui /src /app /services /api.service.ts
ciyidogan's picture
Update flare-ui/src/app/services/api.service.ts
aec91d8 verified
raw
history blame
13.8 kB
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';
import { Router } from '@angular/router';
import { AuthService } from './auth.service';
// Interfaces
export interface API {
name: string;
url: string;
method: string;
headers?: any;
body_template?: any;
timeout_seconds: number;
retry?: {
retry_count: number;
backoff_seconds: number;
strategy: string;
};
auth?: {
enabled: boolean;
token_endpoint?: string;
response_token_path?: string;
token_request_body?: any;
token_refresh_endpoint?: string;
token_refresh_body?: any;
};
response_prompt?: string;
response_mappings?: ResponseMapping[]; // Yeni alan
deleted?: boolean;
last_update_date?: string;
last_update_user?: string;
}
export interface ResponseMapping {
variable_name: string;
type: 'str' | 'int' | 'float' | 'bool' | 'date';
json_path: string;
caption: string;
}
export interface IntentParameter {
name: string;
caption: string;
type: 'str' | 'int' | 'float' | 'bool' | 'date';
required: boolean;
variable_name: string;
extraction_prompt?: string;
validation_regex?: string;
invalid_prompt?: string;
type_error_prompt?: string;
}
export interface Intent {
name: string;
caption: string;
locale: string;
detection_prompt: string;
examples: string[];
parameters: IntentParameter[];
action: string;
fallback_timeout_prompt?: string;
fallback_error_prompt?: string;
}
export interface GenerationConfig {
max_new_tokens: number;
temperature: number;
top_p: number;
top_k?: number;
repetition_penalty?: number;
do_sample?: boolean;
num_beams?: number;
length_penalty?: number;
early_stopping?: boolean;
}
export interface LLMConfig {
repo_id: string;
generation_config: GenerationConfig; // any yerine GenerationConfig
use_fine_tune: boolean;
fine_tune_zip: string;
}
export interface Version {
id: number;
caption?: string;
description?: string;
published: boolean;
general_prompt?: string;
llm: LLMConfig; // inline yerine LLMConfig
intents: Intent[];
parameters: any[];
last_update_date?: string;
}
export interface Project {
id: number;
name: string;
caption: string;
enabled: boolean;
icon?: string;
versions: Version[];
last_update_date?: string;
deleted?: boolean;
created_date?: string;
created_by?: string;
last_update_user?: string;
}
export interface ParameterCollectionConfig {
max_params_per_question: number;
smart_grouping: boolean;
retry_unanswered: boolean;
collection_prompt: string;
}
export interface Environment {
work_mode: string;
cloud_token: string;
spark_endpoint: string;
internal_prompt?: string;
tts_engine?: string;
tts_engine_api_key?: string;
tts_settings?: TTSSettings;
stt_engine?: string;
stt_engine_api_key?: string;
stt_settings?: STTSettings;
parameter_collection_config?: ParameterCollectionConfig;
}
export interface STTSettings {
speech_timeout_ms: number;
noise_reduction_level: number;
vad_sensitivity: number;
language: string;
model: string;
use_enhanced: boolean;
enable_punctuation: boolean;
interim_results: boolean;
}
export interface TTSSettings {
use_ssml: boolean;
}
@Injectable({
providedIn: 'root'
})
export class ApiService {
private apiUrl = '/api';
constructor(
private http: HttpClient,
private router: Router,
private authService: AuthService
) {}
// ===================== Auth =====================
login(username: string, password: string): Observable<any> {
return this.http.post(`${this.apiUrl}/login`, { username, password }).pipe(
tap((response: any) => {
this.authService.setToken(response.token);
this.authService.setUsername(response.username);
})
);
}
logout(): void {
this.authService.logout();
}
private getAuthHeaders(): HttpHeaders {
const token = this.authService.getToken();
return new HttpHeaders({
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
});
}
// ===================== User =====================
changePassword(currentPassword: string, newPassword: string): Observable<any> {
return this.http.post(
`${this.apiUrl}/change-password`,
{ current_password: currentPassword, new_password: newPassword },
{ headers: this.getAuthHeaders() }
).pipe(
catchError(this.handleError)
);
}
// ===================== Environment =====================
getEnvironment(): Observable<Environment> {
return this.http.get<Environment>(`${this.apiUrl}/environment`, {
headers: this.getAuthHeaders()
}).pipe(
catchError(this.handleError)
);
}
updateEnvironment(data: Environment): Observable<any> {
return this.http.put(`${this.apiUrl}/environment`, data, {
headers: this.getAuthHeaders()
}).pipe(
catchError(this.handleError)
);
}
// ===================== Projects =====================
getProjects(includeDeleted = false): Observable<Project[]> {
return this.http.get<Project[]>(`${this.apiUrl}/projects`, {
headers: this.getAuthHeaders(),
params: { include_deleted: includeDeleted.toString() }
}).pipe(
catchError(this.handleError)
);
}
getProject(id: number): Observable<Project> {
return this.http.get<Project>(`/api/projects/${id}`);
}
createProject(data: any): Observable<any> {
return this.http.post(`${this.apiUrl}/projects`, data, {
headers: this.getAuthHeaders()
}).pipe(
catchError(this.handleError)
);
}
updateProject(id: number, data: any): Observable<any> {
return this.http.put(`${this.apiUrl}/projects/${id}`, data, {
headers: this.getAuthHeaders()
}).pipe(
catchError(this.handleError)
);
}
deleteProject(id: number): Observable<any> {
return this.http.delete(`${this.apiUrl}/projects/${id}`, {
headers: this.getAuthHeaders()
}).pipe(
catchError(this.handleError)
);
}
toggleProject(id: number): Observable<any> {
return this.http.patch(`${this.apiUrl}/projects/${id}/toggle`, {}, {
headers: this.getAuthHeaders()
}).pipe(
catchError(this.handleError)
);
}
exportProject(id: number): Observable<any> {
return this.http.get(`${this.apiUrl}/projects/${id}/export`, {
headers: this.getAuthHeaders()
}).pipe(
catchError(this.handleError)
);
}
importProject(data: any): Observable<any> {
return this.http.post(`${this.apiUrl}/projects/import`, data, {
headers: this.getAuthHeaders()
}).pipe(
catchError(this.handleError)
);
}
// ===================== Versions =====================
createVersion(projectId: number, data: any): Observable<any> {
return this.http.post(`${this.apiUrl}/projects/${projectId}/versions`, data, {
headers: this.getAuthHeaders()
}).pipe(
catchError(this.handleError)
);
}
updateVersion(projectId: number, versionId: number, data: any, force: boolean = false): Observable<any> {
return this.http.put(
`${this.apiUrl}/projects/${projectId}/versions/${versionId}${force ? '?force=true' : ''}`,
data,
{ headers: this.getAuthHeaders() }
).pipe(
catchError(this.handleError)
);
}
deleteVersion(projectId: number, versionId: number): Observable<any> {
return this.http.delete(`${this.apiUrl}/projects/${projectId}/versions/${versionId}`, {
headers: this.getAuthHeaders()
}).pipe(
catchError(this.handleError)
);
}
publishVersion(projectId: number, versionId: number): Observable<any> {
return this.http.post(`${this.apiUrl}/projects/${projectId}/versions/${versionId}/publish`, {}, {
headers: this.getAuthHeaders()
}).pipe(
catchError(this.handleError)
);
}
// ===================== APIs =====================
getAPIs(includeDeleted = false): Observable<API[]> {
return this.http.get<API[]>(`${this.apiUrl}/apis`, {
headers: this.getAuthHeaders(),
params: { include_deleted: includeDeleted.toString() }
}).pipe(
catchError(this.handleError)
);
}
createAPI(data: any): Observable<any> {
return this.http.post(`${this.apiUrl}/apis`, data, {
headers: this.getAuthHeaders()
}).pipe(
catchError(this.handleError)
);
}
updateAPI(name: string, data: any): Observable<any> {
return this.http.put(`${this.apiUrl}/apis/${name}`, data, {
headers: this.getAuthHeaders()
}).pipe(
catchError(this.handleError)
);
}
deleteAPI(name: string): Observable<any> {
return this.http.delete(`${this.apiUrl}/apis/${name}`, {
headers: this.getAuthHeaders()
}).pipe(
catchError(this.handleError)
);
}
testAPI(data: any): Observable<any> {
return this.http.post(`${this.apiUrl}/apis/test`, data, {
headers: this.getAuthHeaders()
}).pipe(
catchError(this.handleError)
);
}
// ===================== Spark Integration =====================
sparkStartup(projectName: string): Observable<any> {
return this.http.post(`${this.apiUrl}/spark/startup`,
{ project_name: projectName },
{ headers: this.getAuthHeaders() }
).pipe(
catchError(this.handleError)
);
}
sparkGetProjects(): Observable<any> {
return this.http.get(`${this.apiUrl}/spark/projects`, {
headers: this.getAuthHeaders()
}).pipe(
catchError(this.handleError)
);
}
sparkEnableProject(projectName: string): Observable<any> {
return this.http.post(`${this.apiUrl}/spark/project/enable`,
{ project_name: projectName },
{ headers: this.getAuthHeaders() }
).pipe(
catchError(this.handleError)
);
}
sparkDisableProject(projectName: string): Observable<any> {
return this.http.post(`${this.apiUrl}/spark/project/disable`,
{ project_name: projectName },
{ headers: this.getAuthHeaders() }
).pipe(
catchError(this.handleError)
);
}
sparkDeleteProject(projectName: string): Observable<any> {
return this.http.delete(`${this.apiUrl}/spark/project/${projectName}`, {
headers: this.getAuthHeaders()
}).pipe(
catchError(this.handleError)
);
}
// ===================== Tests =====================
runTests(testType: string): Observable<any> {
return this.http.post(`${this.apiUrl}/test/run-all`, { test_type: testType }, {
headers: this.getAuthHeaders()
}).pipe(
catchError(this.handleError)
);
}
// ===================== Activity Log =====================
getActivityLog(limit = 50): Observable<any[]> {
return this.http.get<any[]>(`${this.apiUrl}/activity-log`, {
headers: this.getAuthHeaders(),
params: { limit: limit.toString() }
}).pipe(
catchError(this.handleError)
);
}
// ===================== Validation =====================
validateRegex(pattern: string, testValue: string): Observable<any> {
return this.http.post(`${this.apiUrl}/validate/regex`,
{ pattern, test_value: testValue },
{ headers: this.getAuthHeaders() }
).pipe(
catchError(this.handleError)
);
}
// ===================== Chat =====================
/* 1️⃣ Proje isimleri (combo’yu doldurmak için) */
getChatProjects() {
return this.http.get<string[]>(`${this.apiUrl}/projects/names`);
}
/* 2️⃣ Oturum başlat */
startChat(projectName: string) {
return this.http.post<{
session_id: string;
answer: string;
}>(`${this.apiUrl}/start_session`, { project_name: projectName });
}
/* 3️⃣ Mesaj gönder/al */
chat(sessionId: string, text: string) {
const headers = new HttpHeaders().set('X-Session-ID', sessionId);
return this.http.post<{
session_id: string;
answer: string;
}>(
`${this.apiUrl}/chat`,
{ user_input: text },
{ headers }
);
}
// ===================== TTS =====================
generateTTS(text: string, voiceId?: string, modelId?: string, outputFormat: string = 'mp3_44100_128'): Observable<Blob> {
const body = {
text,
voice_id: voiceId,
model_id: modelId,
output_format: outputFormat
};
return this.http.post(`${this.apiUrl}/tts/generate`, body, {
headers: this.getAuthHeaders(),
responseType: 'blob'
}).pipe(
catchError(this.handleError)
);
}
// ===================== Locale =====================
getAvailableLocales(): Observable<any> {
return this.http.get(`${this.apiUrl}/locales`, { headers: this.getAuthHeaders() });
}
getLocaleDetails(code: string): Observable<any> {
return this.http.get(`${this.apiUrl}/locales/${code}`, { headers: this.getAuthHeaders() });
}
// ===================== Error Handler =====================
private handleError(error: any) {
console.error('API Error:', error);
if (error.status === 401) {
// Token expired or invalid
this.authService.logout();
} else if (error.status === 409) {
// Race condition error
const message = error.error?.detail || 'Resource was modified by another user';
return throwError(() => ({
...error,
userMessage: message,
requiresReload: true
}));
}
// Ensure error object has proper structure
const errorResponse = {
status: error.status,
error: error.error || { detail: error.message || 'Unknown error' },
message: error.error?.detail || error.error?.message || error.message || 'Unknown error'
};
return throwError(() => errorResponse);
}
}