Spaces:
Runtime error
Runtime error
Download frontend-react/src/services/api.js from Amitkasar/ai-api-testing: direct link, hf CLI and curl.
- Browser
- Download file 9.79 kB
-
https://huggingface.co/spaces/Amitkasar/ai-api-testing/resolve/ff7dddafe7cbd9b07c888ff8cdaca0bd4ff37668/frontend-react/src/services/api.js
- Command line
-
hf download hf://spaces/Amitkasar/ai-api-testing@ff7dddafe7cbd9b07c888ff8cdaca0bd4ff37668/frontend-react/src/services/api.js
-
curl -L -o api.js https://huggingface.co/spaces/Amitkasar/ai-api-testing/resolve/ff7dddafe7cbd9b07c888ff8cdaca0bd4ff37668/frontend-react/src/services/api.js
9.79 kB
| import axios from 'axios'; | |
| const BACKEND_URL = import.meta.env.VITE_BACKEND_URL || 'http://localhost:8001'; | |
| const API_BASE = `${BACKEND_URL}/api/v1`; | |
| const SESSION_KEY = '_jwt'; | |
| // Token lives in module memory AND sessionStorage (survives refresh, clears on tab close) | |
| let _token = null; | |
| function _restoreToken() { | |
| if (!_token) _token = sessionStorage.getItem(SESSION_KEY); | |
| return _token; | |
| } | |
| export const api = axios.create({ | |
| baseURL: API_BASE, | |
| timeout: 60000, | |
| }); | |
| // Attach Bearer token to every request; restore from sessionStorage on first use after refresh | |
| api.interceptors.request.use((config) => { | |
| const tok = _restoreToken(); | |
| if (tok) config.headers.Authorization = `Bearer ${tok}`; | |
| return config; | |
| }); | |
| // Normalize error shape; broadcast logout on 401 | |
| api.interceptors.response.use( | |
| (response) => response, | |
| (error) => { | |
| if (error.response?.status === 401) { | |
| _token = null; | |
| sessionStorage.removeItem(SESSION_KEY); | |
| window.dispatchEvent(new Event('auth:logout')); | |
| } | |
| const msg = | |
| error.response?.data?.error || | |
| error.response?.data?.detail || | |
| error.message || | |
| 'An unexpected error occurred.'; | |
| return Promise.reject(new Error(typeof msg === 'string' ? msg : JSON.stringify(msg))); | |
| } | |
| ); | |
| export const AuthService = { | |
| login: async (username, password) => { | |
| // Uses plain axios (no token needed, no 401 redirect loop) | |
| const response = await axios.post(`${API_BASE}/auth/login`, { username, password }); | |
| _token = response.data.access_token; | |
| sessionStorage.setItem(SESSION_KEY, _token); | |
| return response.data; | |
| }, | |
| logout: () => { | |
| _token = null; | |
| sessionStorage.removeItem(SESSION_KEY); | |
| }, | |
| isAuthenticated: () => !!_restoreToken(), | |
| }; | |
| export const SpecService = { | |
| getAllSpecs: async () => { | |
| const response = await api.get('/specs'); | |
| return response.data; | |
| }, | |
| getSpec: async (id) => { | |
| const response = await api.get(`/specs/${id}`); | |
| return response.data; | |
| }, | |
| deleteSpec: async (id) => { | |
| const response = await api.delete(`/specs/${id}`); | |
| return response.data; | |
| }, | |
| uploadSpec: async (file) => { | |
| const formData = new FormData(); | |
| formData.append('file', file); | |
| const response = await api.post('/upload-spec', formData, { | |
| headers: { 'Content-Type': 'multipart/form-data' }, | |
| }); | |
| return response.data; | |
| }, | |
| updateBaseUrl: async (id, baseUrl) => { | |
| const response = await api.patch(`/specs/${id}`, { base_url: baseUrl }); | |
| return response.data; | |
| } | |
| }; | |
| export const SessionService = { | |
| createSession: async () => { | |
| const response = await api.post('/session'); | |
| return response.data; | |
| }, | |
| clearSession: async (id) => { | |
| const response = await api.delete(`/session/${id}`); | |
| return response.data; | |
| }, | |
| getContext: async (id) => { | |
| const response = await api.get(`/context/${id}`); | |
| return response.data; | |
| }, | |
| updateContext: async (id, key, value) => { | |
| const response = await api.post(`/context/${id}`, { session_id: id, key, value }); | |
| return response.data; | |
| } | |
| }; | |
| export const PlanService = { | |
| generatePlan: async (payload) => { | |
| const response = await api.post('/plan', payload); | |
| return response.data; | |
| }, | |
| /** | |
| * Streaming version of generatePlan. | |
| * Calls the SSE endpoint and fires callbacks for each event. | |
| * onStatus(message) — progress messages while the AI is thinking | |
| * onStep(step) — called once per step as it arrives | |
| * onComplete(data) — { suggested_credentials, token_usage } when done | |
| * onError(message) — on server-side error | |
| */ | |
| streamPlan: async (payload, { onStatus, onStep, onComplete, onError }) => { | |
| const tok = _restoreToken(); | |
| const response = await fetch(`${API_BASE}/plan/stream`, { | |
| method: 'POST', | |
| headers: { | |
| 'Content-Type': 'application/json', | |
| ...(tok ? { Authorization: `Bearer ${tok}` } : {}), | |
| }, | |
| body: JSON.stringify(payload), | |
| }); | |
| if (!response.ok) { | |
| const text = await response.text(); | |
| throw new Error(text || `Plan stream failed: ${response.status}`); | |
| } | |
| const reader = response.body.getReader(); | |
| const decoder = new TextDecoder(); | |
| let buffer = ''; | |
| while (true) { | |
| const { done, value } = await reader.read(); | |
| if (done) break; | |
| buffer += decoder.decode(value, { stream: true }); | |
| const lines = buffer.split('\n'); | |
| buffer = lines.pop(); // keep incomplete last line | |
| for (const line of lines) { | |
| if (!line.startsWith('data: ')) continue; | |
| try { | |
| const event = JSON.parse(line.slice(6)); | |
| if (event.type === 'status') onStatus?.(event.message); | |
| else if (event.type === 'step') onStep?.(event.step); | |
| else if (event.type === 'complete') onComplete?.(event); | |
| else if (event.type === 'error') onError?.(event.message); | |
| } catch { /* ignore malformed SSE line */ } | |
| } | |
| } | |
| }, | |
| executeStep: async (payload) => { | |
| const response = await api.post('/execute-step', payload); | |
| return response.data; | |
| }, | |
| analyzeResponse: async (payload) => { | |
| const response = await api.post('/analyze-response', payload); | |
| return response.data; | |
| }, | |
| }; | |
| export const CredentialService = { | |
| getCredentials: async (specId) => { | |
| const response = await api.get(`/specs/${specId}/credentials`); | |
| return response.data; | |
| }, | |
| saveCredentials: async (specId, payload) => { | |
| const response = await api.post(`/specs/${specId}/credentials`, payload); | |
| return response.data; | |
| } | |
| } | |
| export const AssetService = { | |
| uploadAsset: async (specId, collectionId, file, description = '', tags = []) => { | |
| const formData = new FormData(); | |
| if (specId) formData.append('spec_id', specId); | |
| if (collectionId) formData.append('collection_id', collectionId); | |
| formData.append('file', file); | |
| formData.append('description', description); | |
| formData.append('tags', JSON.stringify(tags)); | |
| const response = await api.post('/assets', formData, { | |
| headers: { 'Content-Type': 'multipart/form-data' }, | |
| }); | |
| return response.data; | |
| }, | |
| getAllAssets: async (specId = null, category = null) => { | |
| const params = {}; | |
| if (specId) params.spec_id = specId; | |
| if (category) params.category = category; | |
| const response = await api.get('/assets', { params }); | |
| return response.data; | |
| }, | |
| deleteAsset: async (id) => { | |
| const response = await api.delete(`/assets/${id}`); | |
| return response.data; | |
| }, | |
| // Collections | |
| getCollections: async (specId = null) => { | |
| const params = {}; | |
| if (specId) params.spec_id = specId; | |
| const response = await api.get('/collections', { params }); | |
| return response.data; | |
| }, | |
| createCollection: async (name, specId = null, description = '') => { | |
| const formData = new FormData(); | |
| formData.append('name', name); | |
| if (specId) formData.append('spec_id', specId); | |
| formData.append('description', description); | |
| const response = await api.post('/collections', formData); | |
| return response.data; | |
| }, | |
| addToCollection: async (collectionId, asset_id) => { | |
| const response = await api.post(`/collections/${collectionId}/assets/${asset_id}`); | |
| return response.data; | |
| }, | |
| deleteCollection: async (id) => { | |
| const response = await api.delete(`/collections/${id}`); | |
| return response.data; | |
| } | |
| }; | |
| export const HistoryService = { | |
| getHistory: async () => { | |
| const response = await api.get('/history'); | |
| return response.data; | |
| }, | |
| async deleteHistorySession(sessionId) { | |
| const response = await api.delete(`/history/${sessionId}`); | |
| return response.data; | |
| }, | |
| async clearAllHistory() { | |
| const response = await api.delete('/history'); | |
| return response.data; | |
| }, | |
| async exportSession(sessionId) { | |
| const response = await api.get(`/history/${sessionId}/export`, { responseType: 'blob' }); | |
| const url = URL.createObjectURL(response.data); | |
| const a = document.createElement('a'); | |
| a.href = url; | |
| a.download = `session_${sessionId.slice(0, 8)}.json`; | |
| a.click(); | |
| URL.revokeObjectURL(url); | |
| }, | |
| }; | |
| export const UsageService = { | |
| getUsage: async (params = {}) => { | |
| const response = await api.get('/usage', { params }); | |
| return response.data; | |
| }, | |
| }; | |
| export const LLMSettingsService = { | |
| get: async () => { | |
| const response = await api.get('/settings/llm'); | |
| return response.data; | |
| }, | |
| saveProviderKey: async (providerId, apiKey) => { | |
| const response = await api.put(`/settings/llm/providers/${providerId}`, { api_key: apiKey }); | |
| return response.data; | |
| }, | |
| deleteProviderKey: async (providerId) => { | |
| const response = await api.delete(`/settings/llm/providers/${providerId}/key`); | |
| return response.data; | |
| }, | |
| saveTaskConfig: async (taskName, config) => { | |
| const response = await api.put(`/settings/llm/tasks/${taskName}`, config); | |
| return response.data; | |
| }, | |
| }; | |
| export const ChatService = { | |
| sendMessage: async (payload) => { | |
| const response = await api.post('/chat', payload); | |
| return response.data; | |
| }, | |
| getSessions: async (specId = null) => { | |
| const params = {}; | |
| if (specId) params.spec_id = specId; | |
| const response = await api.get('/chat-sessions', { params }); | |
| return response.data; | |
| }, | |
| getSession: async (id) => { | |
| const response = await api.get(`/chat-sessions/${id}`); | |
| return response.data; | |
| }, | |
| renameSession: async (id, name) => { | |
| const response = await api.patch(`/chat-sessions/${id}`, { name }); | |
| return response.data; | |
| }, | |
| deleteSession: async (id) => { | |
| const response = await api.delete(`/chat-sessions/${id}`); | |
| return response.data; | |
| }, | |
| clearAll: async () => { | |
| const response = await api.delete('/chat-sessions'); | |
| return response.data; | |
| }, | |
| }; | |