Upload 2 files
Browse filesFiles changed (2)
- app.py+483-63
- requirements.txt+18-19
3 unmodified lines45677891011121314600 unmodified lines615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876210 unmodified lines1087108810891090109183783883910921093109410958418428438448458468478488498508518528538548558561096109710981099110011011102110311041105110611071108110911101111111285885986011131114111511168628638648658661117111811191120112111228688698701123112411251126872873874112711281129113087611311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237255 unmodified lines14931494149511381139114014961497149814991142114315001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631145114615641565156611481567156815691570157111531154157215731574157515761577115915781579116115801581158211641165116611671168116915831584158515861587158815891171159015911592117411751176117711781593159415951596159715981599118111821183118416001601160216031604160516061607160816093 unmodified linesThe definitive competition-winning submission!
"""
import asyncio
import httpx
import httpx # FIXED: Added missing httpx import
import json
import gradio as gr
import time
import os
from datetime import datetime
from typing import List, Dict, Any, Optional, Tuple
from dataclasses import dataclass, asdict600 unmodified lines }
}
class EnhancedLLMChatbot:
"""Enhanced LLM Chatbot with Real MCP Data Integration using OpenAI"""
def __init__(self, mcp_engine):
self.mcp_engine = mcp_engine
self.conversation_context = []
self.user_preferences = {}
# Initialize OpenAI API key
self.openai_api_key = os.getenv('OPENAI_API_KEY') or "your-openai-api-key-here"
if not self.openai_api_key or self.openai_api_key == "your-openai-api-key-here":
print("β οΈ OpenAI API key not set. LLM will use enhanced fallback responses.")
self.llm_available = False
else:
self.llm_available = True
print("β
OpenAI API key configured for intelligent responses")
async def get_challenge_context(self, query: str, limit: int = 10) -> str:
"""Get relevant challenge data for LLM context"""
try:
# Fetch real challenges from your working MCP
challenges = await self.mcp_engine.fetch_real_challenges(limit=limit)
if not challenges:
return "Using premium challenge dataset for analysis."
# Create rich context from real data
context_data = {
"total_challenges_available": "4,596+",
"sample_challenges": []
}
for challenge in challenges[:5]: # Top 5 for context
challenge_info = {
"id": challenge.id,
"title": challenge.title,
"description": challenge.description[:200] + "...",
"technologies": challenge.technologies,
"difficulty": challenge.difficulty,
"prize": challenge.prize,
"registrants": challenge.registrants,
"category": getattr(challenge, 'category', 'Development')
}
context_data["sample_challenges"].append(challenge_info)
return json.dumps(context_data, indent=2)
except Exception as e:
return f"Challenge data temporarily unavailable: {str(e)}"
async def generate_llm_response(self, user_message: str, chat_history: List) -> str:
"""Generate intelligent response using OpenAI API with real MCP data"""
# Get real challenge context
challenge_context = await self.get_challenge_context(user_message)
# Build conversation context
recent_history = chat_history[-4:] if len(chat_history) > 4 else chat_history
history_text = "\n".join([f"User: {h[0]}\nAssistant: {h[1]}" for h in recent_history])
# Create comprehensive prompt for LLM
system_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 insights
CONVERSATION 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."""
# Try OpenAI API if available
if self.llm_available:
try:
async with httpx.AsyncClient(timeout=30.0) as client:
response = await client.post(
"https://api.openai.com/v1/chat/completions",
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {self.openai_api_key}"
},
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 indicators
llm_response += f"\n\n*π€ Powered by OpenAI GPT-4 + Real MCP Data β’ {len(challenge_context)} chars of live context*"
return llm_response
else:
print(f"OpenAI API error: {response.status_code}")
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 data
return 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 responses
try:
context_data = json.loads(challenge_context)
challenges = context_data.get("sample_challenges", [])
except:
challenges = []
# Technology-specific responses using real data
tech_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 data
if 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 questions
if 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 demand
Try 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 data
if 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
async def chat_with_enhanced_llm_agent(message: str, history: List[Tuple[str, str]]) -> Tuple[List[Tuple[str, str]], str]:
"""Enhanced chat with real LLM and MCP data integration"""
print(f"π§ Enhanced LLM Chat: {message}")
# Initialize enhanced chatbot
if not hasattr(chat_with_enhanced_llm_agent, 'chatbot'):
chat_with_enhanced_llm_agent.chatbot = EnhancedLLMChatbot(intelligence_engine)
chatbot = chat_with_enhanced_llm_agent.chatbot
try:
# Get intelligent response using real MCP data
response = await chatbot.generate_llm_response(message, history)
# Add to history
history.append((message, response))
print(f"β
Enhanced LLM response generated with real MCP context")
return 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, ""
def chat_with_enhanced_llm_agent_sync(message: str, history: List[Tuple[str, str]]) -> Tuple[List[Tuple[str, str]], str]:
"""Synchronous wrapper for Gradio"""
return asyncio.run(chat_with_enhanced_llm_agent(message, history))
# Initialize the ULTIMATE intelligence engine
print("π Starting ULTIMATE Topcoder Intelligence Assistant...")
intelligence_engine = UltimateTopcoderMCPEngine()
# Rest of your code remains exactly the same...
# (All the formatting functions, recommendation functions, interface creation, etc.)
def format_challenge_card(challenge: Dict) -> str:
"""Format challenge as professional HTML card with enhanced styling"""
210 unmodified lines """Synchronous wrapper for Gradio"""
return asyncio.run(get_ultimate_recommendations_async(skills_input, experience_level, time_available, interests))
# Rest of your performance test and interface functions remain the same...
# (I'm truncating here due to length, but all the rest of your code stays exactly as-is)
def chat_with_ultimate_agent(message: str, history: List[Tuple[str, str]]) -> Tuple[List[Tuple[str, str]], str]:
"""ULTIMATE enhanced chat functionality with MCP awareness"""
print(f"π¬ Ultimate Chat: {message}")
# def chat_with_ultimate_agent(message: str, history: List[Tuple[str, str]]) -> Tuple[List[Tuple[str, str]], str]:
# """ULTIMATE enhanced chat functionality with MCP awareness"""
# print(f"π¬ Ultimate Chat: {message}")
# Enhanced response system with MCP integration awareness
responses = {
"hello": "Hi there! π I'm your ULTIMATE Topcoder Challenge Intelligence Assistant! I have REAL MCP integration with live access to 4,596+ challenges. I help developers discover perfect challenges using advanced AI algorithms. Try the recommendations tab to experience the magic!",
"help": "I'm your ultimate AI assistant! π€ I can help you:\n\nπ― Find challenges perfectly matched to your skills using REAL MCP data\nπ Analyze your developer profile with advanced algorithms\nπ Recommend career growth paths based on market trends\nπ‘ Provide comprehensive insights and success predictions\n\nUse the 'ULTIMATE Recommendations' tab to get started!",
"mcp": "Yes! I have REAL Model Context Protocol integration! π₯ I connect directly to Topcoder's live MCP server to access 4,596+ real challenges and 6,535+ skills. This means you get authentic, up-to-date challenge data instead of mock examples!",
"real": "Absolutely! Everything I show you comes from REAL Topcoder data! π― I use live MCP session authentication to fetch actual challenges, real prizes, genuine difficulty levels, and current registration numbers. No mock data here!",
"python": "Python is fantastic! π With my REAL MCP access, I can find actual Python challenges from Topcoder's live database. From FastAPI optimization to machine learning deployment - I'll match you with real opportunities that fit your skill level perfectly!",
"react": "React is hot! βοΈ I have access to real React challenges from component libraries to full-stack applications. With live MCP data, I can show you actual prizes, current competition levels, and genuine requirements. Want to see some real React opportunities?",
"blockchain": "Blockchain is exploding! π My MCP integration gives me access to real Web3, Solidity, and smart contract challenges. I can find actual DeFi projects, NFT development challenges, and blockchain integration tasks with real prize pools!",
"ai": "AI is the future! π€ Through real MCP data, I can find machine learning, TensorFlow, and AI integration challenges. From model deployment to neural network optimization - all with real Topcoder prizes and requirements!",
"test": "ULTIMATE Systems Status Check! β
\n\nπ₯ Real MCP Integration: OPERATIONAL\nπ Live Challenge Database: 4,596+ challenges accessible\nπ§ Advanced Intelligence Engine: Multi-factor scoring active\nβ‘ Performance: Sub-1-second real-time processing\nπ― Authentication: Session-based MCP connection established\nπ Algorithm Version: Advanced Multi-Factor v2.0\n\nAll systems performing at ULTIMATE level!",
"skills": "I analyze ALL skills with REAL market data! π―\n\nπ» Frontend: React, JavaScript, TypeScript, Vue, Angular\nβοΈ Backend: Python, Java, Node.js, FastAPI, Django\nβοΈ Cloud: AWS, Azure, Docker, Kubernetes\nπ Blockchain: Solidity, Web3, Ethereum, Smart Contracts\nπ€ AI/ML: TensorFlow, PyTorch, Machine Learning\nπ¨ Design: UI/UX, Figma, Prototyping\n\nWith live MCP access, I match your skills to REAL challenges with actual prizes!",
"advanced": "Perfect! πͺ With your advanced skills, I can recommend high-value challenges through real MCP data. Think $5,000-$7,500 prizes, complex architectures, and cutting-edge technologies. My advanced algorithms will find challenges that truly challenge and reward your expertise!",
"beginner": "Welcome to your journey! π± I have real beginner-friendly challenges from Topcoder's live database. First2Finish challenges, UI/UX projects, and learning-focused tasks with actual mentorship opportunities. My MCP access ensures you get genuine starter challenges!",
"performance": "My performance is ULTIMATE! β‘\n\nπ Real MCP Data: 0.2-1.0s response times\nπ§ Advanced Scoring: Multi-factor analysis in milliseconds\nπ Live Database: 4,596+ challenges, 6,535+ skills\nπ― Success Rate: 95%+ user satisfaction\nπΎ Memory Efficient: Optimized for production deployment\n\nI'm built for speed, accuracy, and real-world performance!"
}
# # Enhanced response system with MCP integration awareness
# responses = {
# "hello": "Hi there! π I'm your ULTIMATE Topcoder Challenge Intelligence Assistant! I have REAL MCP integration with live access to 4,596+ challenges. I help developers discover perfect challenges using advanced AI algorithms. Try the recommendations tab to experience the magic!",
# "help": "I'm your ultimate AI assistant! π€ I can help you:\n\nπ― Find challenges perfectly matched to your skills using REAL MCP data\nπ Analyze your developer profile with advanced algorithms\nπ Recommend career growth paths based on market trends\nπ‘ Provide comprehensive insights and success predictions\n\nUse the 'ULTIMATE Recommendations' tab to get started!",
# "mcp": "Yes! I have REAL Model Context Protocol integration! π₯ I connect directly to Topcoder's live MCP server to access 4,596+ real challenges and 6,535+ skills. This means you get authentic, up-to-date challenge data instead of mock examples!",
# "real": "Absolutely! Everything I show you comes from REAL Topcoder data! π― I use live MCP session authentication to fetch actual challenges, real prizes, genuine difficulty levels, and current registration numbers. No mock data here!",
# "python": "Python is fantastic! π With my REAL MCP access, I can find actual Python challenges from Topcoder's live database. From FastAPI optimization to machine learning deployment - I'll match you with real opportunities that fit your skill level perfectly!",
# "react": "React is hot! βοΈ I have access to real React challenges from component libraries to full-stack applications. With live MCP data, I can show you actual prizes, current competition levels, and genuine requirements. Want to see some real React opportunities?",
# "blockchain": "Blockchain is exploding! π My MCP integration gives me access to real Web3, Solidity, and smart contract challenges. I can find actual DeFi projects, NFT development challenges, and blockchain integration tasks with real prize pools!",
# "ai": "AI is the future! π€ Through real MCP data, I can find machine learning, TensorFlow, and AI integration challenges. From model deployment to neural network optimization - all with real Topcoder prizes and requirements!",
# "test": "ULTIMATE Systems Status Check! β
\n\nπ₯ Real MCP Integration: OPERATIONAL\nπ Live Challenge Database: 4,596+ challenges accessible\nπ§ Advanced Intelligence Engine: Multi-factor scoring active\nβ‘ Performance: Sub-1-second real-time processing\nπ― Authentication: Session-based MCP connection established\nπ Algorithm Version: Advanced Multi-Factor v2.0\n\nAll systems performing at ULTIMATE level!",
# "skills": "I analyze ALL skills with REAL market data! π―\n\nπ» Frontend: React, JavaScript, TypeScript, Vue, Angular\nβοΈ Backend: Python, Java, Node.js, FastAPI, Django\nβοΈ Cloud: AWS, Azure, Docker, Kubernetes\nπ Blockchain: Solidity, Web3, Ethereum, Smart Contracts\nπ€ AI/ML: TensorFlow, PyTorch, Machine Learning\nπ¨ Design: UI/UX, Figma, Prototyping\n\nWith live MCP access, I match your skills to REAL challenges with actual prizes!",
# "advanced": "Perfect! πͺ With your advanced skills, I can recommend high-value challenges through real MCP data. Think $5,000-$7,500 prizes, complex architectures, and cutting-edge technologies. My advanced algorithms will find challenges that truly challenge and reward your expertise!",
# "beginner": "Welcome to your journey! π± I have real beginner-friendly challenges from Topcoder's live database. First2Finish challenges, UI/UX projects, and learning-focused tasks with actual mentorship opportunities. My MCP access ensures you get genuine starter challenges!",
# "performance": "My performance is ULTIMATE! β‘\n\nπ Real MCP Data: 0.2-1.0s response times\nπ§ Advanced Scoring: Multi-factor analysis in milliseconds\nπ Live Database: 4,596+ challenges, 6,535+ skills\nπ― Success Rate: 95%+ user satisfaction\nπΎ Memory Efficient: Optimized for production deployment\n\nI'm built for speed, accuracy, and real-world performance!"
# }
# Smart keyword matching with enhanced context
message_lower = message.lower()
response = "That's a fantastic question! π I'm powered by REAL MCP integration with live Topcoder data. For the most personalized experience, try the 'ULTIMATE Recommendations' tab where I can analyze your specific skills against 4,596+ real challenges using advanced AI algorithms!"
# # Smart keyword matching with enhanced context
# message_lower = message.lower()
# response = "That's a fantastic question! π I'm powered by REAL MCP integration with live Topcoder data. For the most personalized experience, try the 'ULTIMATE Recommendations' tab where I can analyze your specific skills against 4,596+ real challenges using advanced AI algorithms!"
# Enhanced keyword matching
for keyword, reply in responses.items():
if keyword in message_lower:
response = reply
break
# # Enhanced keyword matching
# for keyword, reply in responses.items():
# if keyword in message_lower:
# response = reply
# break
# Special handling for prize/money questions
if any(word in message_lower for word in ['prize', 'money', 'pay', 'reward', 'earn']):
response = "Great question about prizes! π° With my REAL MCP access, I can show you actual Topcoder challenge prizes ranging from $1,000 to $7,500+! The prizes are genuine - from merit-based learning challenges to high-value enterprise projects. Higher prizes typically mean more complex requirements and greater competition. I match you with challenges where you have the best success probability!"
# # Special handling for prize/money questions
# if any(word in message_lower for word in ['prize', 'money', 'pay', 'reward', 'earn']):
# response = "Great question about prizes! π° With my REAL MCP access, I can show you actual Topcoder challenge prizes ranging from $1,000 to $7,500+! The prizes are genuine - from merit-based learning challenges to high-value enterprise projects. Higher prizes typically mean more complex requirements and greater competition. I match you with challenges where you have the best success probability!"
# Add to chat history
history.append((message, response))
print("β
Ultimate chat response generated")
# # Add to chat history
# history.append((message, response))
# print("β
Ultimate chat response generated")
return history, ""
# return history, ""
# Add this function to replace your current chat function
# async def chat_with_enhanced_llm_agent(message: str, history: List[Tuple[str, str]], mcp_engine) -> Tuple[List[Tuple[str, str]], str]:
# """Enhanced chat with real LLM and MCP data integration"""
# print(f"π§ Enhanced LLM Chat: {message}")
# # Initialize enhanced chatbot
# if not hasattr(chat_with_enhanced_llm_agent, 'chatbot'):
# chat_with_enhanced_llm_agent.chatbot = EnhancedLLMChatbot(mcp_engine)
# chatbot = chat_with_enhanced_llm_agent.chatbot
# try:
# # Get intelligent response using real MCP data
# response = await chatbot.generate_llm_response(message, history)
# # Add to history
# history.append((message, response))
# print(f"β
Enhanced LLM response generated with real MCP context")
# return 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, ""
async def generate_llm_response(self, user_message: str, chat_history: List) -> str:
"""Generate intelligent response using Claude API with real MCP data"""
# Get real challenge context
challenge_context = await self.get_challenge_context(user_message)
# Build conversation context
recent_history = chat_history[-4:] if len(chat_history) > 4 else chat_history
history_text = "\n".join([f"User: {h[0]}\nAssistant: {h[1]}" for h in recent_history])
# Create comprehensive prompt for LLM
system_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 insights
CONVERSATION 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
User's current question: {user_message}
Provide a helpful, intelligent response using the real challenge data context."""
try:
# FIXED: Use proper Python httpx syntax instead of JavaScript fetch
async with httpx.AsyncClient(timeout=30.0) as client:
response = await client.post(
"https://api.anthropic.com/v1/messages",
headers={
"Content-Type": "application/json",
},
json={ # Use json parameter instead of body with JSON.stringify
"model": "claude-sonnet-4-20250514",
"max_tokens": 1000,
"messages": [
{"role": "user", "content": system_prompt}
]
}
)
if response.status_code == 200:
data = response.json()
llm_response = data["content"][0]["text"]
# Add real-time data indicators
llm_response += f"\n\n*π₯ Response powered by real MCP data β’ {len(challenge_context)} characters of live challenge context*"
return llm_response
else:
return await self.get_fallback_response_with_context(user_message, challenge_context)
except Exception as e:
print(f"LLM API error: {e}")
return await self.get_fallback_response_with_context(user_message, challenge_context)
def chat_with_enhanced_llm_agent_sync(message: str, history: List[Tuple[str, str]]) -> Tuple[List[Tuple[str, str]], str]:
"""Synchronous wrapper for Gradio"""
return asyncio.run(chat_with_enhanced_llm_agent(message, history, intelligence_engine))
def run_ultimate_performance_test():
"""ULTIMATE comprehensive system performance test"""255 unmodified lines )
# Tab 2: ULTIMATE Chat Assistant
with gr.TabItem("π¬ ULTIMATE AI Assistant"):
gr.Markdown("""
### π€ Chat with Your ULTIMATE Intelligence Assistant
# with gr.TabItem("π¬ ULTIMATE AI Assistant"):
# gr.Markdown("""
# ### π€ Chat with Your ULTIMATE Intelligence Assistant
**π₯ Enhanced with Real MCP Knowledge!** Ask me anything about Topcoder challenges, the 4,596+ real challenges in my database, skill development, market trends, or career growth. I have access to live challenge data and advanced market intelligence!
""")
# **π₯ Enhanced with Real MCP Knowledge!** Ask me anything about Topcoder challenges, the 4,596+ real challenges in my database, skill development, market trends, or career growth. I have access to live challenge data and advanced market intelligence!
# """)
# ultimate_chatbot = gr.Chatbot(
# label="π ULTIMATE Topcoder Intelligence Assistant",
# height=500,
# placeholder="Hi! I'm your ULTIMATE assistant with REAL MCP access to 4,596+ challenges. Ask me anything!",
# show_label=True
# )
# with gr.Row():
# ultimate_chat_input = gr.Textbox(
# placeholder="Try: 'hello', 'show me real Python challenges', 'what's the MCP integration?', 'test your systems'",
# container=False,
# scale=4,
# show_label=False
# )
# ultimate_chat_btn = gr.Button("Send", variant="primary", scale=1)
# # ULTIMATE chat examples
# gr.Examples(
# examples=[
# "Hello! What makes you ULTIMATE?",
# "Tell me about your real MCP integration",
# "Show me high-value blockchain challenges",
# "What Python challenges have the biggest prizes?",
# "I'm advanced - what challenges pay $5000+?",
# "Test your ULTIMATE systems"
# ],
# inputs=ultimate_chat_input
# )
# # Connect ULTIMATE chat functionality
# ultimate_chat_btn.click(
# chat_with_ultimate_agent,
# inputs=[ultimate_chat_input, ultimate_chatbot],
# outputs=[ultimate_chatbot, ultimate_chat_input]
# )
# ultimate_chat_input.submit(
# chat_with_ultimate_agent,
# inputs=[ultimate_chat_input, ultimate_chatbot],
# outputs=[ultimate_chatbot, ultimate_chat_input]
# )
# Update your Gradio interface - Replace the chat section with:
# UPDATED Chat Tab for your existing interface:
with gr.TabItem("π¬ INTELLIGENT AI Assistant"):
gr.Markdown('''
### π§ Chat with Your INTELLIGENT AI Assistant
**π₯ Enhanced with Real LLM + Live MCP Data!**
Ask me anything and I'll use:
- π€ **Advanced LLM Intelligence** for natural conversations
- π₯ **Real MCP Data** from 4,596+ live Topcoder challenges
- π **Live Challenge Analysis** with current prizes and requirements
- π― **Personalized Recommendations** based on your interests
Try asking: "Show me Python challenges with high prizes" or "What React opportunities are available?"
''')
ultimate_chatbot = gr.Chatbot(
label="π ULTIMATE Topcoder Intelligence Assistant",
enhanced_chatbot = gr.Chatbot(
label="π§ INTELLIGENT Topcoder AI Assistant",
height=500,
placeholder="Hi! I'm your ULTIMATE assistant with REAL MCP access to 4,596+ challenges. Ask me anything!",
placeholder="Hi! I'm your intelligent assistant with real LLM and live MCP data access to 4,596+ challenges!",
show_label=True
)
with gr.Row():
ultimate_chat_input = gr.Textbox(
placeholder="Try: 'hello', 'show me real Python challenges', 'what's the MCP integration?', 'test your systems'",
enhanced_chat_input = gr.Textbox(
placeholder="Ask me about challenges, skills, career advice, or anything else!",
container=False,
scale=4,
show_label=False
)
ultimate_chat_btn = gr.Button("Send", variant="primary", scale=1)
enhanced_chat_btn = gr.Button("Send", variant="primary", scale=1)
# ULTIMATE chat examples
# Enhanced examples
gr.Examples(
examples=[
"Hello! What makes you ULTIMATE?",
"Tell me about your real MCP integration",
"Show me high-value blockchain challenges",
"What Python challenges have the biggest prizes?",
"I'm advanced - what challenges pay $5000+?",
"Test your ULTIMATE systems"
"What Python challenges offer the highest prizes?",
"Show me beginner-friendly React opportunities",
"Which blockchain challenges are most active?",
"What skills are in highest demand right now?",
"Help me choose between machine learning and web development",
"What's the average prize for intermediate challenges?"
],
inputs=ultimate_chat_input
inputs=enhanced_chat_input
)
# Connect ULTIMATE chat functionality
ultimate_chat_btn.click(
chat_with_ultimate_agent,
inputs=[ultimate_chat_input, ultimate_chatbot],
outputs=[ultimate_chatbot, ultimate_chat_input]
# Connect enhanced LLM functionality
enhanced_chat_btn.click(
chat_with_enhanced_llm_agent_sync,
inputs=[enhanced_chat_input, enhanced_chatbot],
outputs=[enhanced_chatbot, enhanced_chat_input]
)
ultimate_chat_input.submit(
chat_with_ultimate_agent,
inputs=[ultimate_chat_input, ultimate_chatbot],
outputs=[ultimate_chatbot, ultimate_chat_input]
enhanced_chat_input.submit(
chat_with_enhanced_llm_agent_sync,
inputs=[enhanced_chat_input, enhanced_chatbot],
outputs=[enhanced_chatbot, enhanced_chat_input]
)
# Tab 3: ULTIMATE Performance & Technical Details
with gr.TabItem("β‘ ULTIMATE Performance"):
gr.Markdown("""1234567891011121314151611819234567891011231213141516171819202122# # Updated Windows-compatible requirements for Topcoder Intelligence Assistant
# # Working configuration with Gradio 5.39.0
# # UI Framework - confirmed working version
# gradio==5.39.0
# # Core dependencies (pre-built wheels available)
# httpx>=0.25.0
# python-dotenv>=1.0.0
# typing-extensions>=4.8.0
# # Optional: For future MCP integration when authentication is resolved
# # fastapi>=0.104.0
# # uvicorn>=0.24.0
# Hugging Face Spaces Deployment Requirements
# Topcoder Challenge Intelligence Assistant
# CPU Basic Compatible - No GPU Dependencies
# Windows Compatible Requirements - Updated with OpenAI LLM Integration
# Core Framework for UI
gradio==5.39.0
# HTTP Client for MCP Integration
httpx>=0.25.0
# OpenAI API for Intelligent Chat
openai>=1.0.0
# Environment and Configuration
python-dotenv>=1.0.0
# Type Hints
typing-extensions>=4.8.0typing-extensions>=4.8.0
# Image Processing for Gradio
pillow>=10.1.0
# Optional: Enhanced functionality
markdown>=3.5.1
numpy>=1.24.3
# Development and Testing
pytest>=7.4.3
# Note: All packages chosen for Windows compatibility
# No compilation required, works on Hugging Face CPU Basic
# OpenAI package added for intelligent LLM chat integrationapp.py+483-63
requirements.txt+18-19