use real MCP data fix
Browse files26 unmodified lines2728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011163 unmodified lines175176177178179180181156 unmodified lines33833934034134234334434534634734834935035135235335435535630 unmodified lines38738838939039139239321 unmodified lines41541641741841942010 unmodified lines43143243343443543643743843944044144244344444544644744844945045145245334 unmodified lines4884894904914924934942 unmodified lines49749849950050150250350450550650750850912 unmodified lines5225235245255265275285295305315325335345355365371 unmodified line5395405415425435445455465475485495505515525534 unmodified lines5585595605615625635645655665675685695705715725735741 unmodified line5765775785795805815823 unmodified lines58658758858959059159259359459559659759859960060160260360460560660760860961061161261361461521 unmodified lines6376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706 unmodified lines67767867968068168268368468568668768868969069169269316 unmodified lines71071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088117 unmodified lines899900901902903904905134 unmodified lines10401041104210431044104510461047104810491050105110521053105410551056105730 unmodified lines10881089109010911092109310947 unmodified lines11021103110411051106110711081109111011111112111311141115111611171118111911201121112212 unmodified lines11351136113711381139114011418 unmodified lines11501151115211531154115511561157115811591160116124 unmodified lines1186118711881189119011911192119330 unmodified lines122412251226122712281229123012311232123334 unmodified lines126812691270127112721273127412751276127742 unmodified lines132013211322132313241325132614 unmodified lines134113421343134413451346134713481349135013511352135363 unmodified lines141714181419142014211422142333 unmodified lines145714581459146014611462146382 unmodified lines154615471548154915501551155216 unmodified lines156915701571157215731574157526 unmodified lines@dataclassclass UserProfile:skills: List[str]experience_level: strtime_available: strinterests: List[str]class UltimateTopcoderMCPEngine:"""FIXED: Real MCP Integration - More Aggressive Connection"""def __init__(self):print("π Initializing ULTIMATE Topcoder MCP Engine...")self.base_url = "https://api.topcoder.com/v6/mcp"self.session_id = Noneself.is_connected = Falseself.mock_challenges = self._create_enhanced_fallback_challenges()print(f"β Loaded fallback system with {len(self.mock_challenges)} premium challenges")def _create_enhanced_fallback_challenges(self) -> List[Challenge]:return [Challenge(id="30174840",title="React Component Library Development",description="Build a comprehensive React component library with TypeScript support and Storybook documentation. Perfect for developers looking to create reusable UI components.",technologies=["React", "TypeScript", "Storybook", "CSS", "Jest"],difficulty="Intermediate",prize="$3,000",time_estimate="14 days",registrants=45),Challenge(id="30174841",title="Python API Performance Optimization",description="Optimize existing Python FastAPI application for better performance and scalability. Focus on database queries, caching strategies, and async processing.",technologies=["Python", "FastAPI", "PostgreSQL", "Redis", "Docker"],difficulty="Advanced",prize="$5,000",time_estimate="21 days",registrants=28),Challenge(id="30174842",title="Mobile App UI/UX Design",description="Design modern, accessible mobile app interface with dark mode support and responsive layouts for both iOS and Android platforms.",technologies=["Figma", "UI/UX", "Mobile Design", "Accessibility", "Prototyping"],difficulty="Beginner",prize="$2,000",time_estimate="10 days",registrants=67),Challenge(id="30174843",title="Blockchain Smart Contract Development",description="Develop secure smart contracts for DeFi applications with comprehensive testing suite and gas optimization techniques.",technologies=["Solidity", "Web3", "JavaScript", "Hardhat", "Testing"],difficulty="Advanced",prize="$7,500",time_estimate="28 days",registrants=19),Challenge(id="30174844",title="Data Visualization Dashboard",description="Create interactive data visualization dashboard using modern charting libraries with real-time data updates and export capabilities.",technologies=["D3.js", "JavaScript", "HTML", "CSS", "Chart.js"],difficulty="Intermediate",prize="$4,000",time_estimate="18 days",registrants=33),Challenge(id="30174845",title="Machine Learning Model Deployment",description="Deploy ML models to production with API endpoints, monitoring, and auto-scaling capabilities using cloud platforms.",technologies=["Python", "TensorFlow", "Docker", "Kubernetes", "AWS"],difficulty="Advanced",prize="$6,000",time_estimate="25 days",registrants=24)]def parse_sse_response(self, sse_text: str) -> Dict[str, Any]:"""Parse Server-Sent Events response"""63 unmodified linesprint("β οΈ MCP connection succeeded but no session ID found")except Exception as e:print(f"β οΈ MCP connection failed, using enhanced fallback: {e}")return False156 unmodified linessort_by: str = None,sort_order: str = None,) -> List[Challenge]:"""FIXED: More aggressive real challenge fetching"""# Always try to connectprint(f"π Attempting to fetch REAL challenges (limit: {limit})")connection_success = await self.initialize_connection()if not connection_success:print("β Could not establish MCP connection, using fallback")return []# Build comprehensive query parametersskill_keywords = self.extract_technologies_from_query(query + " " + " ".join(user_profile.skills + user_profile.interests))mcp_query = {30 unmodified linesresult = await self.call_tool("query-tc-challenges", mcp_query)if not result:print("β No result from MCP tool call")return []print(f"π Raw MCP result type: {type(result)}")if isinstance(result, dict):21 unmodified linesexcept json.JSONDecodeError:passchallenges = []for item in challenge_data_list:if isinstance(item, dict):10 unmodified linesdef calculate_advanced_compatibility_score(self, challenge: Challenge, user_profile: UserProfile, query: str) -> tuple:score = 0.0factors = []user_skills_lower = [skill.lower().strip() for skill in user_profile.skills]challenge_techs_lower = [tech.lower() for tech in challenge.technologies]skill_matches = len(set(user_skills_lower) & set(challenge_techs_lower))if len(challenge.technologies) > 0:exact_match_score = (skill_matches / len(challenge.technologies)) * 30coverage_bonus = min(skill_matches * 10, 10)skill_score = exact_match_score + coverage_bonuselse:skill_score = 30score += skill_scoreif skill_matches > 0:matched_skills = [t for t in challenge.technologies if t.lower() in user_skills_lower]factors.append(f"Strong match: uses your {', '.join(matched_skills[:2])} expertise")elif len(challenge.technologies) > 0:factors.append(f"Growth opportunity: learn {', '.join(challenge.technologies[:2])}")else:factors.append("Versatile challenge suitable for multiple skill levels")level_mapping = {'beginner': 1, 'intermediate': 2, 'advanced': 3}user_level_num = level_mapping.get(user_profile.experience_level.lower(), 2)challenge_level_num = level_mapping.get(challenge.difficulty.lower(), 2)34 unmodified linesreturn min(score, 100.0), factorsdef get_user_insights(self, user_profile: UserProfile) -> Dict:skills = user_profile.skillslevel = user_profile.experience_leveltime_available = user_profile.time_availablefrontend_skills = ['react', 'javascript', 'css', 'html', 'vue', 'angular', 'typescript']2 unmodified linesdevops_skills = ['docker', 'kubernetes', 'aws', 'azure', 'terraform', 'jenkins']design_skills = ['figma', 'ui/ux', 'design', 'prototyping', 'accessibility']blockchain_skills = ['solidity', 'web3', 'ethereum', 'blockchain', 'smart contracts', 'nft']user_skills_lower = [skill.lower() for skill in skills]frontend_count = sum(1 for skill in user_skills_lower if any(fs in skill for fs in frontend_skills))backend_count = sum(1 for skill in user_skills_lower if any(bs in skill for bs in backend_skills))data_count = sum(1 for skill in user_skills_lower if any(ds in skill for ds in data_skills))devops_count = sum(1 for skill in user_skills_lower if any(ds in skill for ds in devops_skills))design_count = sum(1 for skill in user_skills_lower if any(ds in skill for ds in design_skills))blockchain_count = sum(1 for skill in user_skills_lower if any(bs in skill for bs in blockchain_skills))if blockchain_count >= 2:profile_type = "Blockchain Developer"elif frontend_count >= 2 and backend_count >= 1:12 unmodified linesprofile_type = "Versatile Developer"insights = {'profile_type': profile_type,'strengths': f"Strong {profile_type.lower()} with expertise in {', '.join(skills[:3]) if skills else 'multiple technologies'}",'growth_areas': self._suggest_growth_areas(user_skills_lower, frontend_count, backend_count, data_count, devops_count, blockchain_count),'skill_progression': f"Ready for {level.lower()} to advanced challenges based on current skill set",'market_trends': self._get_market_trends(skills),'time_optimization': f"With {time_available}, you can complete 1-2 medium challenges or 1 large project",'success_probability': self._calculate_success_probability(level, len(skills))}return insightsdef _suggest_growth_areas(self, user_skills: List[str], frontend: int, backend: int, data: int, devops: int, blockchain: int) -> str:suggestions = []if blockchain < 1 and (frontend >= 1 or backend >= 1):suggestions.append("blockchain and Web3 technologies")1 unmodified linesuggestions.append("cloud technologies (AWS, Docker)")if data < 1 and backend >= 1:suggestions.append("database optimization and analytics")if frontend >= 1 and "typescript" not in str(user_skills):suggestions.append("TypeScript for enhanced development")if backend >= 1 and "api" not in str(user_skills):suggestions.append("API design and microservices")if not suggestions:suggestions = ["AI/ML integration", "system design", "performance optimization"]return "Consider exploring " + ", ".join(suggestions[:3])def _get_market_trends(self, skills: List[str]) -> str:hot_skills = {'react': 'React dominates frontend with 75% job market share','python': 'Python leads in AI/ML and backend development growth',4 unmodified lines'ai': 'AI integration skills in highest demand for 2024','kubernetes': 'Container orchestration critical for enterprise roles'}for skill in skills:skill_lower = skill.lower()for hot_skill, trend in hot_skills.items():if hot_skill in skill_lower:return trendreturn "Full-stack and cloud skills show strongest market demand"def _calculate_success_probability(self, level: str, skill_count: int) -> str:base_score = {'beginner': 60, 'intermediate': 75, 'advanced': 85}.get(level.lower(), 70)skill_bonus = min(skill_count * 3, 15)total = base_score + skill_bonusif total >= 90:return f"{total}% - Outstanding success potential"elif total >= 80:1 unmodified lineelif total >= 70:return f"{total}% - Good probability of success"else:return f"{total}% - Consider skill development first"async def get_personalized_recommendations(self, user_profile: UserProfile, query: str = "",3 unmodified lineslimit: int = 50) -> Dict[str, Any]:start_time = datetime.now()print(f"π― Analyzing profile: {user_profile.skills} | Level: {user_profile.experience_level}")# FIXED: More aggressive real data fetchingreal_challenges = await self.fetch_real_challenges(user_profile=user_profile,query=query,limit=limit,status=status,prize_min=prize_min,prize_max=prize_max,challenge_type=challenge_type,track=track,sort_by=sort_by,sort_order=sort_order,)if real_challenges:challenges = real_challengesdata_source = "π₯ REAL Topcoder MCP Server (4,596+ challenges)"print(f"π Using {len(challenges)} REAL Topcoder challenges!")else:challenges = self.mock_challengesdata_source = "β¨ Enhanced Intelligence Engine (Premium Dataset)"print(f"β‘ Using {len(challenges)} premium challenges with advanced algorithms")scored_challenges = []for challenge in challenges:21 unmodified lines"session_active": bool(self.session_id),"mcp_connected": self.is_connected,"algorithm_version": "Advanced Multi-Factor v2.0","topcoder_total": "4,596+ live challenges" if real_challenges else "Premium dataset"}}class EnhancedLLMChatbot:"""FIXED: Enhanced LLM Chatbot with OpenAI Integration + HF Secrets"""def __init__(self, mcp_engine):self.mcp_engine = mcp_engineself.conversation_context = []self.user_preferences = {}# FIXED: Use Hugging Face Secrets (environment variables)self.openai_api_key = os.getenv("OPENAI_API_KEY", "")if not self.openai_api_key:print("β οΈ OpenAI API key not found in HF secrets. Using enhanced fallback responses.")self.llm_available = Falseelse:self.llm_available = Trueprint("β OpenAI API key loaded from HF secrets for intelligent responses")async def get_challenge_context(self, query: str, limit: int = 10) -> str:"""Get relevant challenge data for LLM context"""try:# Create a basic profile for contextbasic_profile = UserProfile(skills=['Python', 'JavaScript'],experience_level='Intermediate',time_available='4-8 hours',interests=[query]6 unmodified lineslimit=limit)if not challenges:# Try fallback challengeschallenges = self.mcp_engine.mock_challenges[:limit]context_source = "Enhanced Intelligence Engine"else:context_source = "Real MCP Server"# Create rich context from real datacontext_data = {"total_challenges_available": "4,596+" if challenges == self.mcp_engine.mock_challenges else f"{len(challenges)}+","data_source": context_source,"sample_challenges": []}16 unmodified linesreturn f"Challenge data temporarily unavailable: {str(e)}"async def generate_llm_response(self, user_message: str, chat_history: List) -> str:"""FIXED: Generate intelligent response using OpenAI API with real MCP data"""# Get real challenge contextchallenge_context = await self.get_challenge_context(user_message)# Build conversation contextrecent_history = chat_history[-4:] if len(chat_history) > 4 else chat_historyhistory_text = "\n".join([f"User: {h[0]}\nAssistant: {h[1]}" for h in recent_history])# Create comprehensive prompt for LLMsystem_prompt = f"""You are an expert Topcoder Challenge Intelligence Assistant with REAL-TIME access to live challenge data through MCP integration.REAL CHALLENGE DATA CONTEXT:{challenge_context}Your capabilities:- Access to 4,596+ live Topcoder challenges through real MCP integration- Advanced challenge matching algorithms with multi-factor scoring- Real-time prize information, difficulty levels, and technology requirements- Comprehensive skill analysis and career guidance- Market intelligence and technology trend insightsCONVERSATION HISTORY:{history_text}Guidelines:- Use the REAL challenge data provided above in your responses- Reference actual challenge titles, prizes, and technologies when relevant- Provide specific, actionable advice based on real data- Mention that your data comes from live MCP integration with Topcoder- Be enthusiastic about the real-time data capabilities- If asked about specific technologies, reference actual challenges that use them- For skill questions, suggest real challenges that match their level- Keep responses concise but informative (max 300 words)User's current question: {user_message}Provide a helpful, intelligent response using the real challenge data context."""# FIXED: Try OpenAI API if availableif self.llm_available:try:async with httpx.AsyncClient(timeout=30.0) as client:response = await client.post("https://api.openai.com/v1/chat/completions", # FIXED: Correct OpenAI endpointheaders={"Content-Type": "application/json","Authorization": f"Bearer {self.openai_api_key}" # FIXED: Proper auth header},json={"model": "gpt-4o-mini", # Fast and cost-effective"messages": [{"role": "system", "content": "You are an expert Topcoder Challenge Intelligence Assistant with real MCP data access."},{"role": "user", "content": system_prompt}],"max_tokens": 800,"temperature": 0.7})if response.status_code == 200:data = response.json()llm_response = data["choices"][0]["message"]["content"]# Add real-time data indicatorsllm_response += f"\n\n*π€ Powered by OpenAI GPT-4 + Real MCP Data β’ {len(challenge_context)} chars of live context*"return llm_responseelse:print(f"OpenAI API error: {response.status_code} - {response.text}")return await self.get_fallback_response_with_context(user_message, challenge_context)except Exception as e:print(f"OpenAI API error: {e}")return await self.get_fallback_response_with_context(user_message, challenge_context)# Fallback to enhanced responses with real datareturn await self.get_fallback_response_with_context(user_message, challenge_context)async def get_fallback_response_with_context(self, user_message: str, challenge_context: str) -> str:"""Enhanced fallback using real challenge data"""message_lower = user_message.lower()# Parse challenge context for intelligent responsestry:context_data = json.loads(challenge_context)challenges = context_data.get("sample_challenges", [])except:challenges = []# Technology-specific responses using real datatech_keywords = ['python', 'react', 'javascript', 'blockchain', 'ai', 'ml', 'java', 'nodejs', 'angular', 'vue']matching_tech = [tech for tech in tech_keywords if tech in message_lower]if matching_tech:relevant_challenges = []for challenge in challenges:challenge_techs = [tech.lower() for tech in challenge.get('technologies', [])]if any(tech in challenge_techs for tech in matching_tech):relevant_challenges.append(challenge)if relevant_challenges:response = f"Great question about {', '.join(matching_tech)}! π Based on my real MCP data access, here are actual challenges:\n\n"for i, challenge in enumerate(relevant_challenges[:3], 1):response += f"π― **{challenge['title']}**\n"response += f" π° Prize: {challenge['prize']}\n"response += f" π οΈ Technologies: {', '.join(challenge['technologies'])}\n"response += f" π Difficulty: {challenge['difficulty']}\n"response += f" π₯ Registrants: {challenge['registrants']}\n\n"response += f"*These are REAL challenges from my live MCP connection to Topcoder's database of 4,596+ challenges!*"return response# Prize/earning questions with real dataif any(word in message_lower for word in ['prize', 'money', 'earn', 'pay', 'salary', 'income']):if challenges:response = f"π° Based on real MCP data, current Topcoder challenges offer:\n\n"for i, challenge in enumerate(challenges[:3], 1):response += f"{i}. **{challenge['title']}** - {challenge['prize']}\n"response += f" π Difficulty: {challenge['difficulty']} | π₯ Competition: {challenge['registrants']} registered\n\n"response += f"*This is live prize data from {context_data.get('total_challenges_available', '4,596+')} real challenges!*"return response# Career/skill questionsif any(word in message_lower for word in ['career', 'skill', 'learn', 'beginner', 'advanced', 'help']):if challenges:sample_challenge = challenges[0]return f"""I'm your intelligent Topcoder assistant with REAL MCP integration! πI currently have live access to {context_data.get('total_challenges_available', '4,596+')} real challenges. For example, right now there's:π― **"{sample_challenge['title']}"**π° Prize: **{sample_challenge['prize']}**π οΈ Technologies: {', '.join(sample_challenge['technologies'][:3])}π Difficulty: {sample_challenge['difficulty']}I can help you with:π― Find challenges matching your specific skillsπ° Compare real prize amounts and competition levelsπ Analyze difficulty levels and technology requirementsπ Career guidance based on market demandTry asking me about specific technologies like "Python challenges" or "React opportunities"!*Powered by live MCP connection to Topcoder's challenge database*"""# Default intelligent response with real dataif challenges:return f"""Hi! I'm your intelligent Topcoder assistant! π€I have REAL MCP integration with live access to **{context_data.get('total_challenges_available', '4,596+')} challenges** from Topcoder's database.**Currently active challenges include:**β’ **{challenges[0]['title']}** ({challenges[0]['prize']})β’ **{challenges[1]['title']}** ({challenges[1]['prize']})β’ **{challenges[2]['title']}** ({challenges[2]['prize']})Ask me about:π― Specific technologies (Python, React, blockchain, etc.)π° Prize ranges and earning potentialπ Difficulty levels and skill requirementsπ Career advice and skill development*All responses powered by real-time Topcoder MCP data!*"""return "I'm your intelligent Topcoder assistant with real MCP data access! Ask me about challenges, skills, or career advice and I'll help you using live data from 4,596+ real challenges! π"# FIXED: Properly placed standalone functions with correct signaturesasync def chat_with_enhanced_llm_agent(message: str, history: List[Tuple[str, str]], mcp_engine) -> Tuple[List[Tuple[str, str]], str]:17 unmodified linesreturn history, ""except Exception as e:error_response = f"I encountered an issue processing your request: {str(e)}. However, I can still help you with challenge recommendations using my real MCP data! Try asking about specific technologies or challenge types."history.append((message, error_response))return history, ""134 unmodified lines"""async def get_ultimate_recommendations_async(skills_input: str, experience_level: str, time_available: str, interests: str,status: str, prize_min: int, prize_max: int, challenge_type: str, track: str,sort_by: str, sort_order: str) -> Tuple[str, str]:start_time = time.time()try:skills = [skill.strip() for skill in skills_input.split(',') if skill.strip()]user_profile = UserProfile(skills=skills,experience_level=experience_level,time_available=time_available,interests=[interests] if interests else [])# Pass all new filter params to get_personalized_recommendationsrecommendations_data = await intelligence_engine.get_personalized_recommendations(30 unmodified lines<div style='background:linear-gradient(135deg,#fdcb6e,#e17055);color:white;padding:25px;border-radius:12px;text-align:center;box-shadow:0 8px 25px rgba(253,203,110,0.3);'><div style='font-size:3em;margin-bottom:15px;'>π</div><div style='font-size:1.3em;font-weight:600;margin-bottom:10px;'>No perfect matches found</div><div style='opacity:0.9;font-size:1em;'>Try adjusting your skills, experience level, or interests for better results</div></div>"""# Generate insights panel7 unmodified lineserror_msg = f"""<div style='background:linear-gradient(135deg,#e17055,#d63031);color:white;padding:25px;border-radius:12px;text-align:center;box-shadow:0 8px 25px rgba(225,112,85,0.3);'><div style='font-size:3em;margin-bottom:15px;'>β </div><div style='font-size:1.3em;font-weight:600;margin-bottom:10px;'>Processing Error</div><div style='opacity:0.9;font-size:0.9em;'>{str(e)}</div><div style='opacity:0.8;font-size:0.85em;margin-top:10px;'>Please try again or contact support</div></div>"""print(f"β Error processing ULTIMATE request: {str(e)}")return error_msg, ""def get_ultimate_recommendations_sync(skills_input: str, experience_level: str, time_available: str, interests: str,status: str, prize_min: int, prize_max: int, challenge_type: str, track: str,sort_by: str, sort_order: str) -> Tuple[str, str]:return asyncio.run(get_ultimate_recommendations_async(skills_input, experience_level, time_available, interests,status, prize_min, prize_max, challenge_type, track,sort_by, sort_order))12 unmodified lines# Test 1: MCP Connection Testresults.append("π Test 1: Real MCP Connection Status")start = time.time()mcp_status = "β CONNECTED" if intelligence_engine.is_connected else "β οΈ FALLBACK MODE"session_status = f"Session: {intelligence_engine.session_id[:8]}..." if intelligence_engine.session_id else "No session"test1_time = round(time.time() - start, 3)results.append(f" {mcp_status} ({test1_time}s)")8 unmodified lines# Create async testasync def test_recommendations():test_profile = UserProfile(skills=['Python', 'React', 'AWS'],experience_level='Intermediate',time_available='4-8 hours',interests=['web development', 'cloud computing'])return await intelligence_engine.get_personalized_recommendations(test_profile, 'python react cloud')try:# Run async test24 unmodified linesresults.append(f" π€ LLM Integration: Available")results.append(f" π§ Enhanced Chat: Enabled")else:results.append(f" π€ LLM Integration: Fallback mode")results.append(f" π§ Enhanced Chat: Basic responses")results.append("")# Summary30 unmodified lines# Test basic recommendation speedasync def quick_test():test_profile = UserProfile(skills=['Python', 'React'],experience_level='Intermediate',time_available='4-8 hours',interests=['web development'])return await intelligence_engine.get_personalized_recommendations(test_profile)34 unmodified linesresults.append("π― Features: Real-time challenge data")results.append("β‘ Performance: Sub-second response times")else:results.append("β οΈ Status: FALLBACK MODE")results.append("π Using: Enhanced premium dataset")results.append("π― Features: Advanced algorithms active")results.append("π‘ Note: Still provides excellent recommendations")# Check OpenAI API Keyhas_openai = bool(os.getenv("OPENAI_API_KEY"))42 unmodified lines### **π₯ REAL MCP Integration + Advanced AI Intelligence + OpenAI LLM**Experience the **world's most advanced** Topcoder challenge discovery system! Powered by **live Model Context Protocol integration** with access to **4,596+ real challenges**, **OpenAI GPT-4 intelligence**, and sophisticated AI algorithms that deliver **personalized recommendations** tailored to your exact skills and career goals.**π― What Makes This ULTIMATE:**- **π₯ Real MCP Data**: Live connection to Topcoder's official MCP server14 unmodified lineswith gr.Row():with gr.Column(scale=1):gr.Markdown("**π€ Tell the AI about yourself and filter challenges:**")skills_input = gr.Textbox(label="π οΈ Your Skills & Technologies",placeholder="Python, React, JavaScript, AWS, Docker, Blockchain, UI/UX...",lines=3,value="Python, JavaScript, React")experience_level = gr.Dropdown(choices=["Beginner", "Intermediate", "Advanced"],label="π Experience Level",63 unmodified linesultimate_recommend_btn.click(get_ultimate_recommendations_sync,inputs=[skills_input,experience_level,time_available,interests,33 unmodified lineswith gr.Row():enhanced_chat_input = gr.Textbox(placeholder="Ask me about challenges, skills, career advice, or anything else!",container=False,scale=4,show_label=False82 unmodified lines- **API Key Status**: {"β Configured via HF Secrets" if os.getenv("OPENAI_API_KEY") else "β οΈ Set OPENAI_API_KEY in HF Secrets for full features"}#### π§ **Enhanced AI Intelligence Engine v4.0**- **Multi-Factor Scoring**: 40% skill match + 30% experience + 20% interest + 10% market factors- **Natural Language Processing**: Understands your goals and matches with relevant opportunities- **Enhanced Market Intelligence**: Real-time insights on trending technologies and career paths- **Success Prediction**: Enhanced algorithms calculate your probability of success16 unmodified lines```python# SECURE: Hugging Face Secrets integrationopenai_api_key = os.getenv("OPENAI_API_KEY", "")endpoint = "https://api.openai.com/v1/chat/completions"model = "gpt-4o-mini" # Fast and cost-effectivecontext = "Real MCP challenge data + conversation history"```26 unmodified lines2728293031323334353637383940414243444563 unmodified lines109110111112113114115156 unmodified lines27227327427527627727827928028128228328428528628728828929030 unmodified lines32132232332432532632721 unmodified lines34935035135235335435535635735810 unmodified lines36937037137237337437537637737837938038138238338438538638738838939039139234 unmodified lines4274284294304314324334342 unmodified lines43743843944044144244344444544644744844912 unmodified lines4624634644654664674684694704714724734744754764771 unmodified line4794804814824834844854864874884894904914924934 unmodified lines4984995005015025035045055065075085095105115125135141 unmodified line5165175185195205215223 unmodified lines52652752852953053153253353453553653753853954054154254354454554654754854955055155221 unmodified lines5745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816 unmodified lines68868969069169269369469569669716 unmodified lines71471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776817 unmodified lines786787788789790791792134 unmodified lines92792892993093193293393493593693793893994094194294394430 unmodified lines9759769779789799809817 unmodified lines989990991992993994995996997998999100010011002100310041005100610071008100912 unmodified lines10221023102410251026102710288 unmodified lines1037103810391040104110421043104410451046104724 unmodified lines1072107310741075107610771078107930 unmodified lines11101111111211131114111511161117111834 unmodified lines115311541155115611571158115911601161116242 unmodified lines120512061207120812091210121114 unmodified lines12261227122812291230123163 unmodified lines12951296129712981299130033 unmodified lines133413351336133713381339134082 unmodified lines142314241425142614271428142916 unmodified lines144614471448144914501451145226 unmodified lines@dataclassclass UserProfile:experience_level: strtime_available: strinterests: List[str]class UltimateTopcoderMCPEngine:"""FIXED: Real MCP Integration - No Mock/Fallback Data"""def __init__(self):print("π Initializing ULTIMATE Topcoder MCP Engine...")self.base_url = "https://api.topcoder.com/v6/mcp"self.session_id = Noneself.is_connected = Falseprint(f"β MCP Engine initialized with live data connection")def parse_sse_response(self, sse_text: str) -> Dict[str, Any]:"""Parse Server-Sent Events response"""63 unmodified linesprint("β οΈ MCP connection succeeded but no session ID found")except Exception as e:print(f"β οΈ MCP connection failed: {e}")return False156 unmodified linessort_by: str = None,sort_order: str = None,) -> List[Challenge]:"""FIXED: Only fetch real challenges, no mock/fallback"""# Always try to connectprint(f"π Attempting to fetch REAL challenges (limit: {limit})")connection_success = await self.initialize_connection()if not connection_success:print("β Could not establish MCP connection")raise Exception("Unable to connect to Topcoder MCP server. Please try again later.")# Build comprehensive query parametersskill_keywords = self.extract_technologies_from_query(query + " " + " ".join(user_profile.interests) # FIXED: Only using interests, not skills)mcp_query = {30 unmodified linesresult = await self.call_tool("query-tc-challenges", mcp_query)if not result:print("β No result from MCP tool call")raise Exception("No data received from Topcoder MCP server. Please try again later.")print(f"π Raw MCP result type: {type(result)}")if isinstance(result, dict):21 unmodified linesexcept json.JSONDecodeError:passif not challenge_data_list:print("β No challenge data found in MCP response")raise Exception("No challenges found matching your criteria. Please try different filters.")challenges = []for item in challenge_data_list:if isinstance(item, dict):10 unmodified linesdef calculate_advanced_compatibility_score(self, challenge: Challenge, user_profile: UserProfile, query: str) -> tuple:score = 0.0factors = []# FIXED: Only using interests, not skillsuser_interests_lower = [interest.lower().strip() for interest in user_profile.interests]challenge_techs_lower = [tech.lower() for tech in challenge.technologies]interest_matches = len(set(user_interests_lower) & set(challenge_techs_lower))if len(challenge.technologies) > 0:exact_match_score = (interest_matches / len(challenge.technologies)) * 30coverage_bonus = min(interest_matches * 10, 10)interest_score = exact_match_score + coverage_bonuselse:interest_score = 30score += interest_scoreif interest_matches > 0:matched_interests = [t for t in challenge.technologies if t.lower() in user_interests_lower]factors.append(f"Strong match: uses your {', '.join(matched_interests[:2])} interests")elif len(challenge.technologies) > 0:factors.append(f"Growth opportunity: learn {', '.join(challenge.technologies[:2])}")else:factors.append("Versatile challenge suitable for multiple skill/interest levels")level_mapping = {'beginner': 1, 'intermediate': 2, 'advanced': 3}user_level_num = level_mapping.get(user_profile.experience_level.lower(), 2)challenge_level_num = level_mapping.get(challenge.difficulty.lower(), 2)34 unmodified linesreturn min(score, 100.0), factorsdef get_user_insights(self, user_profile: UserProfile) -> Dict:# FIXED: Only using interests, not skillsinterests = user_profile.interestslevel = user_profile.experience_leveltime_available = user_profile.time_availablefrontend_skills = ['react', 'javascript', 'css', 'html', 'vue', 'angular', 'typescript']2 unmodified linesdevops_skills = ['docker', 'kubernetes', 'aws', 'azure', 'terraform', 'jenkins']design_skills = ['figma', 'ui/ux', 'design', 'prototyping', 'accessibility']blockchain_skills = ['solidity', 'web3', 'ethereum', 'blockchain', 'smart contracts', 'nft']user_interests_lower = [interest.lower() for interest in interests]frontend_count = sum(1 for interest in user_interests_lower if any(fs in interest for fs in frontend_skills))backend_count = sum(1 for interest in user_interests_lower if any(bs in interest for bs in backend_skills))data_count = sum(1 for interest in user_interests_lower if any(ds in interest for ds in data_skills))devops_count = sum(1 for interest in user_interests_lower if any(ds in interest for ds in devops_skills))design_count = sum(1 for interest in user_interests_lower if any(ds in interest for ds in design_skills))blockchain_count = sum(1 for interest in user_interests_lower if any(bs in interest for bs in blockchain_skills))if blockchain_count >= 2:profile_type = "Blockchain Developer"elif frontend_count >= 2 and backend_count >= 1:12 unmodified linesprofile_type = "Versatile Developer"insights = {'profile_type': profile_type,'strengths': f"Strong {profile_type.lower()} with expertise in {', '.join(interests[:3]) if interests else 'multiple technologies'}",'growth_areas': self._suggest_growth_areas(user_interests_lower, frontend_count, backend_count, data_count, devops_count, blockchain_count),'skill_progression': f"Ready for {level.lower()} to advanced challenges based on current skill/interest set",'market_trends': self._get_market_trends(interests),'time_optimization': f"With {time_available}, you can complete 1-2 medium challenges or 1 large project",'success_probability': self._calculate_success_probability(level, len(interests))}return insightsdef _suggest_growth_areas(self, user_interests: List[str], frontend: int, backend: int, data: int, devops: int, blockchain: int) -> str:suggestions = []if blockchain < 1 and (frontend >= 1 or backend >= 1):suggestions.append("blockchain and Web3 technologies")1 unmodified linesuggestions.append("cloud technologies (AWS, Docker)")if data < 1 and backend >= 1:suggestions.append("database optimization and analytics")if frontend >= 1 and "typescript" not in str(user_interests):suggestions.append("TypeScript for enhanced development")if backend >= 1 and "api" not in str(user_interests):suggestions.append("API design and microservices")if not suggestions:suggestions = ["AI/ML integration", "system design", "performance optimization"]return "Consider exploring " + ", ".join(suggestions[:3])def _get_market_trends(self, interests: List[str]) -> str:hot_skills = {'react': 'React dominates frontend with 75% job market share','python': 'Python leads in AI/ML and backend development growth',4 unmodified lines'ai': 'AI integration skills in highest demand for 2024','kubernetes': 'Container orchestration critical for enterprise roles'}for interest in interests:interest_lower = interest.lower()for hot_skill, trend in hot_skills.items():if hot_skill in interest_lower:return trendreturn "Full-stack and cloud skills show strongest market demand"def _calculate_success_probability(self, level: str, interest_count: int) -> str:base_score = {'beginner': 60, 'intermediate': 75, 'advanced': 85}.get(level.lower(), 70)interest_bonus = min(interest_count * 3, 15)total = base_score + interest_bonusif total >= 90:return f"{total}% - Outstanding success potential"elif total >= 80:1 unmodified lineelif total >= 70:return f"{total}% - Good probability of success"else:return f"{total}% - Consider skill/interest development first"async def get_personalized_recommendations(self, user_profile: UserProfile, query: str = "",3 unmodified lineslimit: int = 50) -> Dict[str, Any]:start_time = datetime.now()print(f"π― Analyzing profile: {user_profile.interests} | Level: {user_profile.experience_level}")# FIXED: Only fetch real challenges, no mock/fallbacktry:challenges = await self.fetch_real_challenges(user_profile=user_profile,query=query,limit=limit,status=status,prize_min=prize_min,prize_max=prize_max,challenge_type=challenge_type,track=track,sort_by=sort_by,sort_order=sort_order,)data_source = "π₯ REAL Topcoder MCP Server (4,596+ challenges)"print(f"π Using {len(challenges)} REAL Topcoder challenges!")except Exception as e:print(f"β Error fetching challenges: {str(e)}")raise Exception(f"Unable to fetch challenges from Topcoder MCP: {str(e)}")scored_challenges = []for challenge in challenges:21 unmodified lines"session_active": bool(self.session_id),"mcp_connected": self.is_connected,"algorithm_version": "Advanced Multi-Factor v2.0","topcoder_total": "4,596+ live challenges"}}class EnhancedLLMChatbot:"""FIXED: Enhanced LLM Chatbot with OpenAI Integration + HF Secrets"""LLM_INSTRUCTIONS = """You are an expert Topcoder Challenge Intelligence Assistant with REAL-TIME access to live challenge data through MCP integration.Your capabilities:- Access to 4,596+ live Topcoder challenges through real MCP integration- Advanced challenge matching algorithms with multi-factor scoring- Real-time prize information, difficulty levels, and technology requirements- Comprehensive skill & interest analysis and career guidance- Market intelligence and technology trend insightsGuidelines:- Use the REAL challenge data provided above in your responses- Reference actual challenge titles, prizes, and technologies when relevant- Provide specific, actionable advice based on real data- Mention that your data comes from live MCP integration with Topcoder- Be enthusiastic about the real-time data capabilities- If asked about specific technologies, reference actual challenges that use them- For skill & interest questions, suggest real challenges that match their level- Keep responses concise but informative (max 300 words)Provide a helpful, intelligent response using the real challenge data context."""FOOTER_TEXT = "π€ Powered by OpenAI GPT-4 + Real MCP Data"LLM_TOOLS = [{"type": "function","name": "get_challenge_context","description": "Query challenges via Topcoder API","parameters": {"type": "object","properties": {"query": {"type": "string", "description": "Search query for challenges. e.g. python, react, etc."},"limit": {"type": "integer", "description": "Maximum number of challenges to return", "default": 10}},"required": ["query"]}}]def __init__(self, mcp_engine):self.mcp_engine = mcp_engine# FIXED: Use Hugging Face Secrets (environment variables)self.openai_api_key = os.getenv("OPENAI_API_KEY", "")if not self.openai_api_key:print("β οΈ OpenAI API key not found in HF secrets. Chat will show error messages.")self.llm_available = Falseelse:self.llm_available = Trueprint("β OpenAI API key loaded from HF secrets for intelligent responses")async def generate_openai_response(self, input_list: List[Dict]) -> Dict:"""Reusable function to call the OpenAI API."""headers = {"Content-Type": "application/json","Authorization": f"Bearer {self.openai_api_key}"}body = {"model": "gpt-4o-mini","input": input_list,"store": False,"tools": self.LLM_TOOLS,"instructions": self.LLM_INSTRUCTIONS}print("π Sending request to OpenAI API...")async with httpx.AsyncClient(timeout=30.0) as client:response = await client.post("https://api.openai.com/v1/responses",headers=headers,json=body)print(f"π‘ Received OpenAI response with status: {response.status_code}")if response.status_code == 200:return response.json()else:print(f"OpenAI API error: {response.status_code} - {response.text}")raise Exception(f"β **OpenAI API Error** (Status {response.status_code}): Unable to generate response. Please try again later or check your API key configuration.")def extract_response_text(self, data: Dict) -> str:"""Safely extracts the response text from the API data."""print("π Parsing OpenAI response text...")try:response_text = data["output"][0]["content"][0]["text"]print("β Successfully extracted response text.")return response_textexcept (KeyError, IndexError):print("β οΈ Failed to extract response text, returning default message.")return "I apologize, but I couldn't generate a response. Please try again."async def get_challenge_context(self, query: str, limit: int = 10) -> str:"""Get relevant challenge data for LLM context"""try:# Create a basic profile for contextbasic_profile = UserProfile(experience_level='Intermediate',time_available='4-8 hours',interests=[query]6 unmodified lineslimit=limit)# Create rich context from real datacontext_data = {"total_challenges_available": "4,596+","data_source": "Real MCP Server","sample_challenges": []}16 unmodified linesreturn f"Challenge data temporarily unavailable: {str(e)}"async def generate_llm_response(self, user_message: str, chat_history: List) -> str:"""Send a message to the conversation using Responses API"""if not self.llm_available:raise Exception("OpenAI API key not configured. Please set it in Hugging Face Secrets.")input_list = []for user_msg, bot_resp in chat_history:bot_resp_cleaned = bot_resp.split(f"\n\n*{self.FOOTER_TEXT}")[0]input_list.append({"role": "user", "content": user_msg})input_list.append({"role": "assistant", "content": bot_resp_cleaned})input_list.append({"role": "user", "content": user_message})print("π€ Generating LLM response...")try:data = await self.generate_openai_response(input_list)input_list += data.get("output", [])tool_result = Nonefunction_call_found = Falsefor item in data.get("output", []):if item.get("type") == "function_call" and item.get("name") == "get_challenge_context":print("π Function call detected, processing tool...")function_call_found = Truetool_args = json.loads(item.get("arguments", "{}"))query = tool_args.get("query", "")limit = tool_args.get("limit", 10)tool_result = await self.get_challenge_context(query, limit)print(f"π§ Tool result: {json.dumps(tool_result, indent=2) if tool_result else 'No data returned'}")input_list.append({"type": "function_call_output","call_id": item.get("call_id"),"output": json.dumps({"challenges": tool_result})})if function_call_found:data = await self.generate_openai_response(input_list)llm_response = self.extract_response_text(data)footer_text = self.FOOTER_TEXTif tool_result:footer_text += f" β’ {len(str(tool_result))} chars of live context"llm_response += f"\n\n*{footer_text}*"print("β LLM response generated successfully.")return llm_responseexcept Exception as e:print(f"Chat error: {e}")raise Exception(f"β **Chat Error**: {str(e)}")# FIXED: Properly placed standalone functions with correct signaturesasync def chat_with_enhanced_llm_agent(message: str, history: List[Tuple[str, str]], mcp_engine) -> Tuple[List[Tuple[str, str]], str]:17 unmodified linesreturn history, ""except Exception as e:error_response = f"I encountered an issue processing your request: {str(e)}."history.append((message, error_response))return history, ""134 unmodified lines"""async def get_ultimate_recommendations_async(experience_level: str, time_available: str, interests: str,status: str, prize_min: int, prize_max: int, challenge_type: str, track: str,sort_by: str, sort_order: str) -> Tuple[str, str]:start_time = time.time()try:# FIXED: Removed skills_input parameter, only using interestsinterest_list = [interest.strip() for interest in interests.split(',') if interest.strip()]user_profile = UserProfile(experience_level=experience_level,time_available=time_available,interests=interest_list)# Pass all new filter params to get_personalized_recommendationsrecommendations_data = await intelligence_engine.get_personalized_recommendations(30 unmodified lines<div style='background:linear-gradient(135deg,#fdcb6e,#e17055);color:white;padding:25px;border-radius:12px;text-align:center;box-shadow:0 8px 25px rgba(253,203,110,0.3);'><div style='font-size:3em;margin-bottom:15px;'>π</div><div style='font-size:1.3em;font-weight:600;margin-bottom:10px;'>No perfect matches found</div><div style='opacity:0.9;font-size:1em;'>Try adjusting your interests, experience level, or filters for better results</div></div>"""# Generate insights panel7 unmodified lineserror_msg = f"""<div style='background:linear-gradient(135deg,#e17055,#d63031);color:white;padding:25px;border-radius:12px;text-align:center;box-shadow:0 8px 25px rgba(225,112,85,0.3);'><div style='font-size:3em;margin-bottom:15px;'>β </div><div style='font-size:1.3em;font-weight:600;margin-bottom:10px;'>No recommendations found</div><div style='opacity:0.9;font-size:0.9em;'>{str(e)}</div><div style='opacity:0.8;font-size:0.85em;margin-top:10px;'>If problem persists, contact support.</div></div>"""print(f"β Error processing ULTIMATE request: {str(e)}")return error_msg, ""def get_ultimate_recommendations_sync(experience_level: str, time_available: str, interests: str,status: str, prize_min: int, prize_max: int, challenge_type: str, track: str,sort_by: str, sort_order: str) -> Tuple[str, str]:return asyncio.run(get_ultimate_recommendations_async(experience_level, time_available, interests,status, prize_min, prize_max, challenge_type, track,sort_by, sort_order))12 unmodified lines# Test 1: MCP Connection Testresults.append("π Test 1: Real MCP Connection Status")start = time.time()mcp_status = "β CONNECTED" if intelligence_engine.is_connected else "β οΈ NOT CONNECTED"session_status = f"Session: {intelligence_engine.session_id[:8]}..." if intelligence_engine.session_id else "No session"test1_time = round(time.time() - start, 3)results.append(f" {mcp_status} ({test1_time}s)")8 unmodified lines# Create async testasync def test_recommendations():test_profile = UserProfile(experience_level='Intermediate',time_available='4-8 hours',interests=['python', 'react', 'cloud'])return await intelligence_engine.get_personalized_recommendations(test_profile, 'python')try:# Run async test24 unmodified linesresults.append(f" π€ LLM Integration: Available")results.append(f" π§ Enhanced Chat: Enabled")else:results.append(f" π€ LLM Integration: Not Available")results.append(f" π§ Enhanced Chat: Not Available")results.append("")# Summary30 unmodified lines# Test basic recommendation speedasync def quick_test():test_profile = UserProfile(experience_level='Intermediate',time_available='4-8 hours',interests=['web development', 'Python', 'React'])return await intelligence_engine.get_personalized_recommendations(test_profile)34 unmodified linesresults.append("π― Features: Real-time challenge data")results.append("β‘ Performance: Sub-second response times")else:results.append("β οΈ Status: NOT CONNECTED")results.append("π Using: No data available")results.append("π― Features: MCP connection required")results.append("π‘ Note: Please check your connection")# Check OpenAI API Keyhas_openai = bool(os.getenv("OPENAI_API_KEY"))42 unmodified lines### **π₯ REAL MCP Integration + Advanced AI Intelligence + OpenAI LLM**Experience the **world's most advanced** Topcoder challenge discovery system! Powered by **live Model Context Protocol integration** with access to **4,596+ real challenges**, **OpenAI GPT-4 intelligence**, and sophisticated AI algorithms that deliver **personalized recommendations** tailored to your exact skills, interests and career goals.**π― What Makes This ULTIMATE:**- **π₯ Real MCP Data**: Live connection to Topcoder's official MCP server14 unmodified lineswith gr.Row():with gr.Column(scale=1):gr.Markdown("**π€ Tell the AI about yourself and filter challenges:**")experience_level = gr.Dropdown(choices=["Beginner", "Intermediate", "Advanced"],label="π Experience Level",63 unmodified linesultimate_recommend_btn.click(get_ultimate_recommendations_sync,inputs=[experience_level,time_available,interests,33 unmodified lineswith gr.Row():enhanced_chat_input = gr.Textbox(placeholder="Ask me about challenges, skills, interests, career advice, or anything else!",container=False,scale=4,show_label=False82 unmodified lines- **API Key Status**: {"β Configured via HF Secrets" if os.getenv("OPENAI_API_KEY") else "β οΈ Set OPENAI_API_KEY in HF Secrets for full features"}#### π§ **Enhanced AI Intelligence Engine v4.0**- **Multi-Factor Scoring**: 40% interest match + 30% experience + 20% query + 10% market factors- **Natural Language Processing**: Understands your goals and matches with relevant opportunities- **Enhanced Market Intelligence**: Real-time insights on trending technologies and career paths- **Success Prediction**: Enhanced algorithms calculate your probability of success16 unmodified lines```python# SECURE: Hugging Face Secrets integrationopenai_api_key = os.getenv("OPENAI_API_KEY", "")endpoint = "https://api.openai.com/v1/responses"model = "gpt-4o-mini" # Fast and cost-effectivecontext = "Real MCP challenge data + conversation history"```
app.py+219-342