show reasoning
Browse filesFiles changed (3)
732 unmodified lines733734735736737738739740741742743744127 unmodified lines872873874875876877878879880881882883884885732 unmodified linesreturn code@app.post("/api/generate")async def generate_code(request: CodeGenerationRequest,authorization: Optional[str] = Header(None)):"""Generate code based on user query - returns streaming response"""# Dev mode: No authentication required - just use server's HF_TOKEN# In production, you would check real OAuth tokens here127 unmodified lines})yield f"data: {event_data}\n\n"# Clean up generated code (remove LLM explanatory text and markdown)generated_code = cleanup_generated_code(generated_code, language)# Send completion event (optimized - no timestamp in hot path)completion_data = json.dumps({"type": "complete","code": generated_code})yield f"data: {completion_data}\n\n"# Auto-deploy after code generation (if authenticated and not skipped)732 unmodified lines733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781127 unmodified lines909910911912913914915916917918919920921922923924925926927928929732 unmodified linesreturn codedef extract_reasoning(code: str, language: str) -> str:"""Extract LLM reasoning/explanatory text that's outside the main code block"""try:if not code:return ""# 1. Check for <think> tags (e.g. from DeepSeek-R1 or newer GLM-4)think_match = re.search(r'<think>([\s\S]*?)</think>', code, re.IGNORECASE)if think_match:return think_match.group(1).strip()# 2. Extract everything outside of markdown code blocksblocks = list(re.finditer(r'```(?:[\w]*)\s*\n([\s\S]*?)(?:\n```|$)', code, re.IGNORECASE))if not blocks:return ""text_parts = []last_end = 0for match in blocks:pre_text = code[last_end:match.start()].strip()if pre_text and len(pre_text) > 10:text_parts.append(pre_text)last_end = match.end()post_text = code[last_end:].strip()if post_text and len(post_text) > 10:text_parts.append(post_text)return "\n\n".join(text_parts).strip()except Exception as e:print(f"[Reasoning Extraction] Error: {e}")return ""@app.post("/api/generate")async def generate_code(request: CodeGenerationRequest,authorization: Optional[str] = Header(None)):"""Generate code based on user query - returns streaming response"""# Dev mode: No authentication required - just use server's HF_TOKEN# In production, you would check real OAuth tokens here127 unmodified lines})yield f"data: {event_data}\n\n"# Extract reasoning before cleaning upreasoning = extract_reasoning(generated_code, language)# Clean up generated code (remove LLM explanatory text and markdown)generated_code = cleanup_generated_code(generated_code, language)# Send completion event (include reasoning for GLM-4.7)completion_dict = {"type": "complete","code": generated_code}if selected_model_id == "zai-org/GLM-4.7" and reasoning:completion_dict["reasoning"] = reasoningcompletion_data = json.dumps(completion_dict)yield f"data: {completion_data}\n\n"# Auto-deploy after code generation (if authenticated and not skipped)
366 unmodified lines367368369370371372373374375376377378379380381382366 unmodified lines});},// onComplete(code: string) => {setGeneratedCode(code);setIsGenerating(false);// Update final message - just show success, not the codesetMessages((prev) => {const newMessages = [...prev];newMessages[newMessages.length - 1] = {...assistantMessage,content: '✅ Code generated successfully! Check the editor →',};return newMessages;});366 unmodified lines367368369370371372373374375376377378379380381382383384385386366 unmodified lines});},// onComplete(code: string, reasoning?: string) => {setGeneratedCode(code);setIsGenerating(false);// Update final message - include reasoning if availablesetMessages((prev) => {const newMessages = [...prev];const content = reasoning? `✅ Code generated successfully!\n\n**Reasoning:**\n${reasoning}\n\nCheck the editor →`: '✅ Code generated successfully! Check the editor →';newMessages[newMessages.length - 1] = {...assistantMessage,content: content,};return newMessages;});
17 unmodified lines181920212223242526272829303132333435363732 unmodified lines707172737475767778798081828384858687888990919223 unmodified lines1161171181191201211221231241251261271281291301311321331343 unmodified lines13813914014114214314416 unmodified lines1611621631641651661671681691701711721731741751761771781791801811821831841851861 unmodified line18818919019119219319414 unmodified lines2092102112122132142152162172182192202212222232242252262272282292302312322332341 unmodified line23623723823924024124230 unmodified lines2732742752762772782792 unmodified lines28228328428528628728828929029129210 unmodified lines3033043053063073083093103113123133143153163173183193203213223231 unmodified line3253263273283293303313323333343353363373383393403413423433442 unmodified lines3473483493503513523531 unmodified line35535635735835936036157 unmodified lines41942042142242342442527 unmodified lines45345445545645745845961 unmodified lines52152252352452552652752852953053153253317 unmodified linesconsole.log('[API Client] Using explicit API URL:', process.env.NEXT_PUBLIC_API_URL);return process.env.NEXT_PUBLIC_API_URL;}// For server-side rendering, always use relative URLsif (typeof window === 'undefined') {console.log('[API Client] SSR mode: using relative URLs');return '';}// On localhost (dev mode), use direct backend URLconst hostname = window.location.hostname;if (hostname === 'localhost' || hostname === '127.0.0.1') {console.log('[API Client] Localhost dev mode: using http://localhost:8000');return 'http://localhost:8000';}// In production (HF Space), use relative URLs (Next.js proxies to backend)console.log('[API Client] Production mode: using relative URLs (proxied by Next.js)');return '';32 unmodified linesif (error.response && error.response.status === 401) {const errorData = error.response.data;const errorMessage = errorData?.detail || errorData?.message || '';// Only log out if it's an authentication/session issue// Don't log out for permission errors on specific resourcesconst shouldLogout =errorMessage.includes('Authentication required') ||errorMessage.includes('Invalid token') ||errorMessage.includes('Token expired') ||errorMessage.includes('Session expired') ||error.config?.url?.includes('/auth/');if (shouldLogout && typeof window !== 'undefined') {// Clear ALL authentication data including session tokenlocalStorage.removeItem('hf_oauth_token');localStorage.removeItem('hf_session_token');localStorage.removeItem('hf_user_info');this.token = null;// Dispatch custom event to notify UI componentswindow.dispatchEvent(new CustomEvent('auth-expired', {detail: { message: 'Your session has expired. Please sign in again.' }23 unmodified lines// Cache helpersprivate getCachedData<T>(key: string, maxAgeMs: number): T | null {if (typeof window === 'undefined') return null;try {const cached = localStorage.getItem(key);if (!cached) return null;const { data, timestamp } = JSON.parse(cached);const age = Date.now() - timestamp;if (age > maxAgeMs) {localStorage.removeItem(key);return null;}return data;} catch (error) {console.error(`Failed to get cached data for ${key}:`, error);3 unmodified linesprivate setCachedData<T>(key: string, data: T): void {if (typeof window === 'undefined') return;try {localStorage.setItem(key, JSON.stringify({data,16 unmodified linesconsole.log('Fetching models from API...');const response = await this.client.get<Model[]>('/api/models');const models = response.data;// Cache the successful responseif (models && models.length > 0) {this.setCachedData('anycoder_models', models);console.log('Cached', models.length, 'models (valid for 24 hours)');}return models;} catch (error: any) {// Handle connection errors gracefullyconst isConnectionError =error.code === 'ECONNABORTED' ||error.code === 'ECONNRESET' ||error.code === 'ECONNREFUSED' ||error.message?.includes('socket hang up') ||error.message?.includes('timeout') ||error.message?.includes('Network Error') ||error.response?.status === 503 ||error.response?.status === 502;if (isConnectionError) {// Try to return stale cache if availableconst staleCache = this.getCachedData<Model[]>('anycoder_models', Infinity);1 unmodified lineconsole.warn('Backend not available, using stale cached models');return staleCache;}console.warn('Backend not available, cannot load models');return [];}14 unmodified linesconsole.log('Fetching languages from API...');const response = await this.client.get<{ languages: Language[] }>('/api/languages');const languages = response.data.languages;// Cache the successful responseif (languages && languages.length > 0) {this.setCachedData('anycoder_languages', languages);console.log('Cached', languages.length, 'languages (valid for 24 hours)');}return response.data;} catch (error: any) {// Handle connection errors gracefullyconst isConnectionError =error.code === 'ECONNABORTED' ||error.code === 'ECONNRESET' ||error.code === 'ECONNREFUSED' ||error.message?.includes('socket hang up') ||error.message?.includes('timeout') ||error.message?.includes('Network Error') ||error.response?.status === 503 ||error.response?.status === 502;if (isConnectionError) {// Try to return stale cache if availableconst staleCache = this.getCachedData<Language[]>('anycoder_languages', Infinity);1 unmodified lineconsole.warn('Backend not available, using stale cached languages');return { languages: staleCache };}// Fall back to default languagesconsole.warn('Backend not available, using default languages');return { languages: ['html', 'gradio', 'transformers.js', 'streamlit', 'comfyui', 'react'] };30 unmodified linesgenerateCodeStream(request: CodeGenerationRequest,onChunk: (content: string) => void,onComplete: (code: string) => void,onError: (error: string) => void,onDeploying?: (message: string) => void,onDeployed?: (message: string, spaceUrl: string) => void,2 unmodified lines// Build the URL correctly whether we have a base URL or notconst baseUrl = API_URL || window.location.origin;const url = new URL('/api/generate', baseUrl);let abortController = new AbortController();let accumulatedCode = '';let buffer = ''; // Buffer for incomplete SSE lines// Use fetch with POST to support large payloadsfetch(url.toString(), {method: 'POST',10 unmodified linesonError('⏱️ Rate limit exceeded. Free tier allows up to 20 requests per minute. Please wait a moment and try again.');return;}if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}if (!response.body) {throw new Error('Response body is null');}const reader = response.body.getReader();const decoder = new TextDecoder();while (true) {const { done, value } = await reader.read();if (done) {console.log('[Stream] Stream ended, total code length:', accumulatedCode.length);if (accumulatedCode) {1 unmodified line}break;}// Decode chunk and add to bufferbuffer += decoder.decode(value, { stream: true });// Process complete SSE messages (ending with \n\n)const messages = buffer.split('\n\n');// Keep the last incomplete message in the bufferbuffer = messages.pop() || '';// Process each complete messagefor (const message of messages) {if (!message.trim()) continue;// Parse SSE format: "data: {...}"const lines = message.split('\n');for (const line of lines) {2 unmodified linesconst jsonStr = line.substring(6);const data = JSON.parse(jsonStr);console.log('[Stream] Received event:', data.type, data.content?.substring(0, 50));if (data.type === 'chunk' && data.content) {accumulatedCode += data.content;onChunk(data.content);1 unmodified lineconsole.log('[Stream] Generation complete, total code length:', data.code?.length || accumulatedCode.length);// Use the complete code from the message if available, otherwise use accumulatedconst finalCode = data.code || accumulatedCode;onComplete(finalCode);// Don't return yet - might have deployment events coming} else if (data.type === 'deploying') {console.log('[Stream] Deployment started:', data.message);57 unmodified linesws.onmessage = (event) => {try {const data = JSON.parse(event.data);if (data.type === 'chunk' && data.content) {onChunk(data.content);} else if (data.type === 'complete' && data.code) {27 unmodified linesspace_name: request.space_name,existing_repo_id: request.existing_repo_id,});try {const response = await this.client.post<DeploymentResponse>('/api/deploy', request);console.log('[API Client] Deploy response:', response.status, response.data);61 unmodified linesconst response = await axios.get('https://huggingface.co/api/spaces', {timeout: 5000,});// Filter for apps with 'anycoder' tag and sort by trendingScoreconst anycoderApps = response.data.filter((space: any) => space.tags && space.tags.includes('anycoder')).sort((a: any, b: any) => (b.trendingScore || 0) - (a.trendingScore || 0)).slice(0, 6);return anycoderApps;} catch (error) {console.error('Failed to fetch trending anycoder apps:', error);17 unmodified lines181920212223242526272829303132333435363732 unmodified lines707172737475767778798081828384858687888990919223 unmodified lines1161171181191201211221231241251261271281291301311321331343 unmodified lines13813914014114214314416 unmodified lines1611621631641651661671681691701711721731741751761771781791801811821831841851861 unmodified line18818919019119219319414 unmodified lines2092102112122132142152162172182192202212222232242252262272282292302312322332341 unmodified line23623723823924024124230 unmodified lines2732742752762772782792 unmodified lines28228328428528628728828929029129210 unmodified lines3033043053063073083093103113123133143153163173183193203213223231 unmodified line3253263273283293303313323333343353363373383393403413423433442 unmodified lines3473483493503513523531 unmodified line35535635735835936036157 unmodified lines41942042142242342442527 unmodified lines45345445545645745845961 unmodified lines52152252352452552652752852953053153253317 unmodified linesconsole.log('[API Client] Using explicit API URL:', process.env.NEXT_PUBLIC_API_URL);return process.env.NEXT_PUBLIC_API_URL;}// For server-side rendering, always use relative URLsif (typeof window === 'undefined') {console.log('[API Client] SSR mode: using relative URLs');return '';}// On localhost (dev mode), use direct backend URLconst hostname = window.location.hostname;if (hostname === 'localhost' || hostname === '127.0.0.1') {console.log('[API Client] Localhost dev mode: using http://localhost:8000');return 'http://localhost:8000';}// In production (HF Space), use relative URLs (Next.js proxies to backend)console.log('[API Client] Production mode: using relative URLs (proxied by Next.js)');return '';32 unmodified linesif (error.response && error.response.status === 401) {const errorData = error.response.data;const errorMessage = errorData?.detail || errorData?.message || '';// Only log out if it's an authentication/session issue// Don't log out for permission errors on specific resourcesconst shouldLogout =errorMessage.includes('Authentication required') ||errorMessage.includes('Invalid token') ||errorMessage.includes('Token expired') ||errorMessage.includes('Session expired') ||error.config?.url?.includes('/auth/');if (shouldLogout && typeof window !== 'undefined') {// Clear ALL authentication data including session tokenlocalStorage.removeItem('hf_oauth_token');localStorage.removeItem('hf_session_token');localStorage.removeItem('hf_user_info');this.token = null;// Dispatch custom event to notify UI componentswindow.dispatchEvent(new CustomEvent('auth-expired', {detail: { message: 'Your session has expired. Please sign in again.' }23 unmodified lines// Cache helpersprivate getCachedData<T>(key: string, maxAgeMs: number): T | null {if (typeof window === 'undefined') return null;try {const cached = localStorage.getItem(key);if (!cached) return null;const { data, timestamp } = JSON.parse(cached);const age = Date.now() - timestamp;if (age > maxAgeMs) {localStorage.removeItem(key);return null;}return data;} catch (error) {console.error(`Failed to get cached data for ${key}:`, error);3 unmodified linesprivate setCachedData<T>(key: string, data: T): void {if (typeof window === 'undefined') return;try {localStorage.setItem(key, JSON.stringify({data,16 unmodified linesconsole.log('Fetching models from API...');const response = await this.client.get<Model[]>('/api/models');const models = response.data;// Cache the successful responseif (models && models.length > 0) {this.setCachedData('anycoder_models', models);console.log('Cached', models.length, 'models (valid for 24 hours)');}return models;} catch (error: any) {// Handle connection errors gracefullyconst isConnectionError =error.code === 'ECONNABORTED' ||error.code === 'ECONNRESET' ||error.code === 'ECONNREFUSED' ||error.message?.includes('socket hang up') ||error.message?.includes('timeout') ||error.message?.includes('Network Error') ||error.response?.status === 503 ||error.response?.status === 502;if (isConnectionError) {// Try to return stale cache if availableconst staleCache = this.getCachedData<Model[]>('anycoder_models', Infinity);1 unmodified lineconsole.warn('Backend not available, using stale cached models');return staleCache;}console.warn('Backend not available, cannot load models');return [];}14 unmodified linesconsole.log('Fetching languages from API...');const response = await this.client.get<{ languages: Language[] }>('/api/languages');const languages = response.data.languages;// Cache the successful responseif (languages && languages.length > 0) {this.setCachedData('anycoder_languages', languages);console.log('Cached', languages.length, 'languages (valid for 24 hours)');}return response.data;} catch (error: any) {// Handle connection errors gracefullyconst isConnectionError =error.code === 'ECONNABORTED' ||error.code === 'ECONNRESET' ||error.code === 'ECONNREFUSED' ||error.message?.includes('socket hang up') ||error.message?.includes('timeout') ||error.message?.includes('Network Error') ||error.response?.status === 503 ||error.response?.status === 502;if (isConnectionError) {// Try to return stale cache if availableconst staleCache = this.getCachedData<Language[]>('anycoder_languages', Infinity);1 unmodified lineconsole.warn('Backend not available, using stale cached languages');return { languages: staleCache };}// Fall back to default languagesconsole.warn('Backend not available, using default languages');return { languages: ['html', 'gradio', 'transformers.js', 'streamlit', 'comfyui', 'react'] };30 unmodified linesgenerateCodeStream(request: CodeGenerationRequest,onChunk: (content: string) => void,onComplete: (code: string, reasoning?: string) => void,onError: (error: string) => void,onDeploying?: (message: string) => void,onDeployed?: (message: string, spaceUrl: string) => void,2 unmodified lines// Build the URL correctly whether we have a base URL or notconst baseUrl = API_URL || window.location.origin;const url = new URL('/api/generate', baseUrl);let abortController = new AbortController();let accumulatedCode = '';let buffer = ''; // Buffer for incomplete SSE lines// Use fetch with POST to support large payloadsfetch(url.toString(), {method: 'POST',10 unmodified linesonError('⏱️ Rate limit exceeded. Free tier allows up to 20 requests per minute. Please wait a moment and try again.');return;}if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}if (!response.body) {throw new Error('Response body is null');}const reader = response.body.getReader();const decoder = new TextDecoder();while (true) {const { done, value } = await reader.read();if (done) {console.log('[Stream] Stream ended, total code length:', accumulatedCode.length);if (accumulatedCode) {1 unmodified line}break;}// Decode chunk and add to bufferbuffer += decoder.decode(value, { stream: true });// Process complete SSE messages (ending with \n\n)const messages = buffer.split('\n\n');// Keep the last incomplete message in the bufferbuffer = messages.pop() || '';// Process each complete messagefor (const message of messages) {if (!message.trim()) continue;// Parse SSE format: "data: {...}"const lines = message.split('\n');for (const line of lines) {2 unmodified linesconst jsonStr = line.substring(6);const data = JSON.parse(jsonStr);console.log('[Stream] Received event:', data.type, data.content?.substring(0, 50));if (data.type === 'chunk' && data.content) {accumulatedCode += data.content;onChunk(data.content);1 unmodified lineconsole.log('[Stream] Generation complete, total code length:', data.code?.length || accumulatedCode.length);// Use the complete code from the message if available, otherwise use accumulatedconst finalCode = data.code || accumulatedCode;onComplete(finalCode, data.reasoning);// Don't return yet - might have deployment events coming} else if (data.type === 'deploying') {console.log('[Stream] Deployment started:', data.message);57 unmodified linesws.onmessage = (event) => {try {const data = JSON.parse(event.data);if (data.type === 'chunk' && data.content) {onChunk(data.content);} else if (data.type === 'complete' && data.code) {27 unmodified linesspace_name: request.space_name,existing_repo_id: request.existing_repo_id,});try {const response = await this.client.post<DeploymentResponse>('/api/deploy', request);console.log('[API Client] Deploy response:', response.status, response.data);61 unmodified linesconst response = await axios.get('https://huggingface.co/api/spaces', {timeout: 5000,});// Filter for apps with 'anycoder' tag and sort by trendingScoreconst anycoderApps = response.data.filter((space: any) => space.tags && space.tags.includes('anycoder')).sort((a: any, b: any) => (b.trendingScore || 0) - (a.trendingScore || 0)).slice(0, 6);return anycoderApps;} catch (error) {console.error('Failed to fetch trending anycoder apps:', error);
backend_api.py+47-3
frontend/src/app/page.tsx+7-3
frontend/src/lib/api.ts+45-45