deploy my fast api to hugging face space
Browse filesFiles changed (17)
- .dockerignoreAdded+8
- .env.exampleAdded+2
- .gitignoreAdded+3
- DockerfileAdded+29
- app.pyAdded+224
- components/Event_ai/__init__.pyAdded
- components/Event_ai/config/__init__.pyAdded
- components/Event_ai/config/agents.yamlAdded+13
- components/Event_ai/config/tasks.yamlAdded+34
- components/Event_ai/crew.pyAdded+79
- components/__init__.pyAdded
- components/search/__init__.pyAdded
- components/search/search.pyAdded+311
- events_data.pyAdded+162
- mcp_server.pyAdded+172
- requirements.txtAdded+10
- setup.pyAdded+11
12345678__pycache__*.pyc*.pyo*.pyd.envvenv/.git.DS_Store12GEMINI_API_KEY="Your Gemini API key"SERPER_API_KEY="Your Serper API key"123.enveventhub.egg-info/*__pycache__/1234567891011121314151617181920212223242526272829# Use official Python imageFROM python:3.11-slim
# Set environment variablesENV PYTHONDONTWRITEBYTECODE=1ENV PYTHONUNBUFFERED=1
# Set working directoryWORKDIR /app
# Copy requirements first for cachingCOPY requirements.txt .
# Install dependenciesRUN pip install --upgrade pipRUN pip install --no-cache-dir -r requirements.txt
# Copy app codeCOPY . .
# Expose port (Render uses 10000+ dynamic ports, we'll override with CMD)EXPOSE 7860
# Redirect local storage and cache to /tmpENV HOME=/tmpENV XDG_DATA_HOME=/tmp/.local/share
# Command to run the FastAPI serverCMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224from fastapi import FastAPI, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelimport uvicornimport loggingimport threadingimport timeimport asynciofrom typing import Dict, Optionalimport os# Import core componentsfrom components.search.search import perform_search, get_all_events, initialize_embeddings, refresh_embeddingsfrom components.Event_ai.crew import EventContentCrew
# Import MCP serverfrom mcp_server import SimpleMCPServer
# -----------------------------# Logging# -----------------------------logger = logging.getLogger(__name__)logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# -----------------------------# FastAPI app# -----------------------------app = FastAPI( title="EventHub API", description="Semantic Event Search, Event Creation, and AI-assisted tools API", version="1.1.0", docs_url="/docs")
# -----------------------------# Middleware# -----------------------------app.add_middleware( CORSMiddleware, allow_origins=["https://grad-backend-uaju.onrender.com/"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"],)
_mcp_server_instance: Optional[SimpleMCPServer] = None_mcp_server_started = False
# -----------------------------# Models# -----------------------------class SearchRequest(BaseModel): query: str user_id: str = "default"
class EventInput(BaseModel): description: str title: str
# -----------------------------# Global state tracking# -----------------------------_mcp_server_started = False_mcp_server_instance: Optional[SimpleMCPServer] = None
# -----------------------------# Background task for periodic refresh# -----------------------------def periodic_refresh(): """Refresh embeddings every 30 minutes""" logger.info("→ Starting periodic refresh thread") while True: try: time.sleep(1800) # 30 minutes logger.info("→ Starting periodic embedding refresh...") refresh_embeddings() logger.info("✓ Embeddings refreshed successfully") except Exception as e: logger.error(f"✗ Error during periodic refresh: {e}")
# -----------------------------# Startup# -----------------------------@app.on_event("startup")async def startup_event(): global _mcp_server_started, _mcp_server_instance logger.info("→ Starting EventHub application") # Initialize embeddings asynchronously try: logger.info("→ Initializing embeddings...") loop = asyncio.get_event_loop() await loop.run_in_executor(None, initialize_embeddings) logger.info("✓ Embeddings initialized successfully") except Exception as e: logger.error(f"✗ Error initializing embeddings: {e}") logger.warning("→ Continuing without embeddings (search functionality may be limited)")
# Start background refresh thread try: refresh_thread = threading.Thread(target=periodic_refresh, daemon=True) refresh_thread.start() logger.info("✓ Background refresh thread started") except Exception as e: logger.error(f"✗ Failed to start refresh thread: {e}")
# Launch MCP server instance try: if not _mcp_server_started: logger.info("→ Starting MCP server instance...") _mcp_server_instance = SimpleMCPServer() _mcp_server_started = True logger.info("✓ MCP server instance ready") except Exception as e: logger.error(f"✗ Failed to start MCP server: {e}")
# -----------------------------# Routes# -----------------------------@app.get("/")async def health_check(): return {"status": "healthy", "message": "EventHub API is running"}
@app.post("/search")async def search_endpoint(request: SearchRequest): try: results = perform_search(request.query, request.user_id) if not results: return {"results": [], "message": "No matching events found"} return {"results": results} except Exception as e: logger.error(f"Search endpoint error: {e}") raise HTTPException(status_code=500, detail="Search failed")
@app.post("/generate-event")def generate_event(event: EventInput): try: crew = EventContentCrew() result = crew.eventcrew().kickoff( inputs={"event_description": event.description, "title": event.title} )
# Access tasks_output safely tasks = getattr(result, "tasks_output", []) if tasks: last_task = tasks[-1] # Use vars() to convert TaskOutput object to dict last_task_dict = vars(last_task) if hasattr(last_task, "__dict__") else {} proposals = last_task_dict.get("json_dict", {}).get("proposals", []) else: proposals = getattr(result, "proposals", [])
return {"proposals": proposals}
except Exception as e: logger.error(f"Generate-event error: {e}") raise HTTPException(status_code=500, detail="Event generation failed")
@app.post("/refresh-embeddings")async def manual_refresh(): try: collection = refresh_embeddings() return {"status": "success", "message": "Embeddings refreshed successfully","collection": collection} except Exception as e: logger.error(f"Manual refresh error: {e}") raise HTTPException(status_code=500, detail="Embedding refresh failed")
# -----------------------------# MCP HTTP Bridge Routes# -----------------------------@app.post("/mcp/tools/call")async def mcp_tools_call(request: Dict): global _mcp_server_instance if not _mcp_server_instance: logger.error("✗ MCP server instance not available") raise HTTPException(status_code=503, detail="MCP server not initialized") logger.info(f"→ MCP bridge request: {request.get('method', 'unknown')}") try: response = await _mcp_server_instance.handle_request(request) logger.info("✓ MCP bridge request completed") return response except Exception as e: logger.error(f"✗ MCP bridge error: {e}") raise HTTPException(status_code=500, detail=f"MCP request failed: {str(e)}")
@app.post("/mcp/tools/list") async def mcp_tools_list(): global _mcp_server_instance if not _mcp_server_instance: logger.error("✗ MCP server instance not available") raise HTTPException(status_code=503, detail="MCP server not initialized") logger.info("→ MCP tools list request") try: request = {"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}} response = await _mcp_server_instance.handle_request(request) logger.info("✓ MCP tools list completed") return response except Exception as e: logger.error(f"✗ MCP tools list error: {e}") raise HTTPException(status_code=500, detail=f"MCP tools list failed: {str(e)}")
if __name__ == "__main__": logger.info("→ Starting EventHub server on http://localhost:8000") logger.info("→ API documentation available at http://localhost:8000/docs") try: port = int(os.getenv("PORT", 8000)) uvicorn.run(app, host="0.0.0.0", port=port, reload=True) except Exception as e: logger.error(f"✗ Failed to start server: {e}") raise
12345678910111213event_generator: name: "Event Content Generator" role: "Event copywriter" goal: "Generate 3 polished event titles, short descriptions (≤500 words), and relevant tags." backstory: "You are an expert in event branding and writing catchy content." allow_delegation: false
event_validator: name: "Event Validator" role: "Validator" goal: "Ensure the generated proposals align with the event description." backstory: "You are a meticulous event reviewer ensuring relevance and accuracy." allow_delegation: false12345678910111213141516171819202122232425262728293031323334generate_event_content: description: > Generate up to 3 polished event proposals (title, description ≤500 words, and 5 tags) for the following event: description:{event_description}. title: {title}
Instructions for the LLM: - If the event description mentions any guest, special guest, or speaker, Use SerperDevTool to search online (Google, LinkedIn, Wikipedia). Summarize their role or profession using LLM. include them in the generated description as bullet points. - For each guest/speaker, provide their name and role (e.g., CEO of a company, software developer, market analyst, musician, or related relevant role). - Keep the description engaging and concise. - Ensure each proposal has: 1. A catchy title 2. Polished description ≤500 words 3. 5 relevant tags - Generate up to 3 proposals for the given event description.
expected_output: > JSON object with key "proposals", containing a list of up to 3 event proposals. Each proposal must include: - title (string) - description (string ≤500 words, including bullet points for guests/speakers if any) - tags (list of 5 strings)
validate_event_content: description: > From the generated proposals, analyze and return the 2 that best align with the original event description: {event_description}. expected_output: > JSON object with key "proposals", containing a list of the 2 best validated event proposals.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879from typing import Listfrom crewai import Agent, Crew, Process, Task, LLMfrom crewai.project import CrewBase, agent, task, crewfrom crewai_tools import SerperDevTool, ScrapeWebsiteTool
from pydantic import BaseModel, Fieldfrom dotenv import load_dotenv
_ = load_dotenv()
llm = LLM( model="gemini/gemini-2.0-flash", temperature=0.7,)
class EventProposal(BaseModel): title: str = Field(..., description="The event title") description: str = Field(..., description="Event description, max 200 words") tags: List[str] = Field(..., description="List of 5 suggested tags")
class EventProposals(BaseModel): proposals: List[EventProposal] = Field(..., description="List of event proposals")
@CrewBaseclass EventContentCrew: """Crew for generating and validating event proposals"""
agents_config = "config/agents.yaml" tasks_config = "config/tasks.yaml"
@agent def event_generator(self) -> Agent: return Agent( config=self.agents_config["event_generator"], llm=llm, inject_date=True, tools=[ SerperDevTool() ] )
@agent def event_validator(self) -> Agent: return Agent( config=self.agents_config["event_validator"], llm=llm, inject_date=True, )
@task def generate_event_content(self) -> Task: return Task( config=self.tasks_config["generate_event_content"], agent=self.event_generator(), output_json=EventProposals )
@task def validate_event_content(self) -> Task: return Task( config=self.tasks_config["validate_event_content"], agent=self.event_validator(), output_json=EventProposals )
@crew def eventcrew(self) -> Crew: """Creates the event crew""" return Crew( agents=self.agents, tasks=self.tasks, process=Process.sequential, verbose=True, planning=False, max_rpm=3, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311import loggingfrom datetime import datetime, timedeltaimport reimport numpy as npimport osimport jsonfrom sentence_transformers import SentenceTransformerimport chromadbfrom chromadb.config import Settingsimport requestsfrom events_data import events
# -----------------------------# Logging# -----------------------------logger = logging.getLogger(__name__)
# -----------------------------# Configuration# -----------------------------PERSISTENT_DIRECTORY = "./chroma_db"EVENTS_API_URL = "http://localhost:3000/api/allevents"
EMBEDDINGS_CACHE_FILE = "./embeddings_cache.json"
# -----------------------------# Global collection variable# -----------------------------collection = None
# -----------------------------# Initialize model# -----------------------------try: model = SentenceTransformer('all-MiniLM-L6-v2') logger.info("SentenceTransformer model loaded successfully")except Exception as e: logger.error(f"Error loading model: {e}") raise
# -----------------------------# Initialize ChromaDB with persistent storage# -----------------------------def get_chroma_client(): """Get ChromaDB client with persistent storage""" return chromadb.Client(Settings( persist_directory=PERSISTENT_DIRECTORY ))
def initialize_collection(): """Initialize or get existing collection""" client = get_chroma_client() try: collection = client.get_collection(name="event_content") logger.info("Using existing ChromaDB collection") except: collection = client.create_collection(name="event_content") logger.info("Created new ChromaDB collection") return collection
# -----------------------------# Sample events (fallback)# -----------------------------sample_events = events
# -----------------------------# Embedding management functions# -----------------------------def initialize_embeddings(): """Initialize embeddings on application startup""" global collection collection = initialize_collection() # Check if collection is empty and needs initial population if collection.count() == 0: logger.info("Collection empty, generating initial embeddings...") refresh_embeddings() else: logger.info(f"Collection already has {collection.count()} embeddings")
def refresh_embeddings(): """Refresh embeddings by recreating the collection""" global collection # Get current events (all events, no user filtering at storage level) events = fetch_events() # Recreate the collection try: client = get_chroma_client() try: client.delete_collection(name="event_content") logger.info("Deleted existing collection") except: logger.info("No existing collection to delete") collection = client.create_collection(name="event_content") logger.info("Created new collection") except Exception as e: logger.error(f"Error recreating collection: {e}") raise # Generate new embeddings (store all events with user_id as "global") documents = [] metadatas = [] ids = []
for event in events: search_text = generate_search_text(event) documents.append(search_text)
# Store all events with user_id as "global" - filtering happens during search metadatas.append({ "user_id": "global", # All events stored as global "_id": str(event["_id"]), "title": event.get("title", ""), "location": event.get("location") or "", "createdAt": event.get("createdAt") or "", "imageUrl": event.get("imageUrl") or "", "startDateTime": event.get("startDateTime") or "", "endDateTime": event.get("endDateTime") or "", "price": event.get("price") or "", "isFree": event.get("isFree", False), "category": event.get("category", {}).get("name", ""), "organizer": f"{event.get('organizer', {}).get('firstName','')} {event.get('organizer', {}).get('lastName','')}".strip(), "tags": ", ".join(event.get("tags", [])) })
ids.append(f"global_{event['_id']}")
try: # Process in batches to manage memory batch_size = 20 for i in range(0, len(documents), batch_size): batch_docs = documents[i:i+batch_size] batch_metadatas = metadatas[i:i+batch_size] batch_ids = ids[i:i+batch_size] batch_embeddings = model.encode(batch_docs).tolist() collection.add( documents=batch_docs, embeddings=batch_embeddings, metadatas=batch_metadatas, ids=batch_ids ) logger.info(f"Processed batch {i//batch_size + 1}/{(len(documents)-1)//batch_size + 1}") logger.info(f"Embeddings refreshed successfully for {len(events)} events") return events except Exception as e: logger.error(f"Error refreshing embeddings: {e}") raise
def generate_search_text(event): """Generate search text from event data""" return ( f"Title: {event['title']}. " f"Description: {event.get('description', '')}. " f"Category: {event.get('category', {}).get('name', '')}. " f"Location: {event.get('location', '')}. " f"Tags: {', '.join(event.get('tags', []))}. " f"Organizer: {event.get('organizer', {}).get('firstName', '')} {event.get('organizer', {}).get('lastName', '')}. " f"Start: {event.get('startDateTime', '')}. " f"End: {event.get('endDateTime', '')}. " f"Price: {event.get('price', '')}. " f"Free: {'Yes' if event.get('isFree', False) else 'No'}. " f"URL: {event.get('url', '')}" )
def fetch_events(): # """Fetch events from API with fallback to sample data""" try: response = requests.get(EVENTS_API_URL, timeout=10) response.raise_for_status() events = response.json() logger.info(f"Fetched {len(events)} events from API") # print("Events: ",events) return events['data'] except Exception as e: logger.warning(f"Error fetching events from API, using sample data: {e}") return sample_events
# -----------------------------# Helper: extract filters# -----------------------------def extract_filters_from_query(query: str): filters = {}
# Free / Paid if "free" in query.lower(): filters["isFree"] = True query = re.sub(r"\bfree\b", "", query, flags=re.IGNORECASE) if "paid" in query.lower(): filters["isFree"] = False query = re.sub(r"\bpaid\b", "", query, flags=re.IGNORECASE)
# Location detection location_match = re.search(r"in\s+([A-Za-z\s]+)", query, re.IGNORECASE) if location_match: filters["location"] = location_match.group(1).strip().title() query = re.sub(location_match.group(0), "", query, flags=re.IGNORECASE)
# Date detection today = datetime.now().date() date_patterns = { "today": today, "tomorrow": today + timedelta(days=1), "this weekend": today + timedelta(days=(5 - today.weekday()) % 7), "next week": today + timedelta(days=7), } for pattern, date_value in date_patterns.items(): if pattern in query.lower(): filters["date"] = date_value.strftime("%Y-%m-%d") query = re.sub(pattern, "", query, flags=re.IGNORECASE)
# Category detection categories = ["technology", "music", "business", "sports", "education", "food & drink", "gaming", "health & wellness"] for category in categories: if category in query.lower(): filters["category"] = category.title() query = re.sub(category, "", query, flags=re.IGNORECASE)
query = re.sub(r'\s+', ' ', query).strip() return query, filters
# -----------------------------# Main search function# -----------------------------def perform_search(query: str, user_id: str): n_results = 10
similarity_threshold = 0.2
try: if collection is None: initialize_embeddings()
processed_query, filters = extract_filters_from_query(query)
# Base filter: only return global events where_filter = {"user_id": "global"}
# Add other filters from query parsing other_filters = [] if "isFree" in filters: other_filters.append({"isFree": filters["isFree"]}) if "location" in filters: other_filters.append({"location": filters["location"]}) if "category" in filters: other_filters.append({"category": filters["category"]})
if other_filters: where_filter = { "$and": [ {"user_id": "global"}, *other_filters ] }
# Generate query embedding query_embedding = model.encode([processed_query]).tolist()[0]
# Perform the search results = collection.query( query_embeddings=[query_embedding], n_results=n_results, where=where_filter, include=['metadatas', 'distances'] )
metadatas = results.get("metadatas", [[]])[0] distances = results.get("distances", [[]])[0]
if not metadatas: return []
# Convert distances to similarity scores scored_results = [] for idx, metadata in enumerate(metadatas): distance = distances[idx] similarity_score = 1 / (1 + distance) if distance > 0 else 1.0
# ✅ filter by threshold if similarity_score >= similarity_threshold: scored_results.append({ "metadata": metadata, "score": similarity_score })
# If nothing meets threshold → return empty if not scored_results: return []
# Sort and return scored_results.sort(key=lambda x: x["score"], reverse=True) return [r["metadata"] for r in scored_results]
except Exception as e: logger.error(f"Search error for user {user_id}: {e}") raise
# -----------------------------# Return all events# -----------------------------def get_all_events(): return fetch_events()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162events = [ { "_id": "1", "title": "Tech Conference 2023", "description": "Annual technology conference featuring talks on AI, machine learning, and software development. Join industry leaders for three days of innovation.", "tags": ["technology", "AI", "machine learning", "software", "conference"], "location": "San Francisco, CA", "createdAt": "2023-08-01T00:00:00", "imageUrl": "https://example.com/event1.jpg", "startDateTime": "2023-11-15T09:00:00", "endDateTime": "2023-11-15T17:00:00", "price": "TBD", "isFree": False, "url": "https://example.com/events/1", "category": {"_id": "c1", "name": "Technology"}, "organizer": {"_id": "o1", "firstName": "John", "lastName": "Doe"} }, { "_id": "2", "title": "Jazz Festival", "description": "Weekend jazz festival with performances from world-renowned artists. Food and drinks available throughout the event.", "tags": ["music", "jazz", "festival", "live performance", "food"], "location": "New York, NY", "createdAt": "2023-08-02T00:00:00", "imageUrl": "https://example.com/event2.jpg", "startDateTime": "2023-09-22T10:00:00", "endDateTime": "2023-09-22T22:00:00", "price": "50", "isFree": False, "url": "https://example.com/events/2", "category": {"_id": "c2", "name": "Music"}, "organizer": {"_id": "o2", "firstName": "Alice", "lastName": "Smith"} }, { "_id": "3", "title": "Startup Pitch Competition", "description": "Watch promising startups pitch their ideas to a panel of investors. Great opportunity for networking with entrepreneurs.", "tags": ["business", "startup", "pitching", "investors", "networking"], "location": "Austin, TX", "createdAt": "2023-08-03T00:00:00", "imageUrl": "https://example.com/event3.jpg", "startDateTime": "2023-10-05T14:00:00", "endDateTime": "2023-10-05T18:00:00", "price": "0", "isFree": True, "url": "https://example.com/events/3", "category": {"_id": "c3", "name": "Business"}, "organizer": {"_id": "o3", "firstName": "Bob", "lastName": "Johnson"} }, { "_id": "4", "title": "Marathon for Charity", "description": "Annual marathon raising funds for children's hospitals. All fitness levels welcome with 5K, 10K, and full marathon options.", "tags": ["sports", "marathon", "charity", "fitness", "running"], "location": "Chicago, IL", "createdAt": "2023-08-04T00:00:00", "imageUrl": "https://example.com/event4.jpg", "startDateTime": "2023-10-28T07:00:00", "endDateTime": "2023-10-28T13:00:00", "price": "25", "isFree": False, "url": "https://example.com/events/4", "category": {"_id": "c4", "name": "Sports"}, "organizer": {"_id": "o4", "firstName": "Sarah", "lastName": "Lee"} }, { "_id": "5", "title": "Digital Marketing Workshop", "description": "Hands-on workshop teaching the latest digital marketing strategies, SEO techniques, and social media advertising.", "tags": ["education", "marketing", "SEO", "social media", "workshop"], "location": "Online Event", "createdAt": "2023-08-05T00:00:00", "imageUrl": "https://example.com/event5.jpg", "startDateTime": "2023-09-30T09:00:00", "endDateTime": "2023-09-30T16:00:00", "price": "0", "isFree": True, "url": "https://example.com/events/5", "category": {"_id": "c5", "name": "Education"}, "organizer": {"_id": "o5", "firstName": "David", "lastName": "Kim"} }, { "_id": "6", "title": "Food & Wine Festival", "description": "Sample gourmet foods and fine wines from top chefs and vineyards. Cooking demonstrations and tasting sessions throughout the day.", "tags": ["food", "wine", "festival", "cooking", "tasting"], "location": "Napa Valley, CA", "createdAt": "2023-08-06T00:00:00", "imageUrl": "https://example.com/event6.jpg", "startDateTime": "2023-11-10T11:00:00", "endDateTime": "2023-11-10T20:00:00", "price": "75", "isFree": False, "url": "https://example.com/events/6", "category": {"_id": "c6", "name": "Food & Drink"}, "organizer": {"_id": "o6", "firstName": "Emma", "lastName": "Williams"} }, { "_id": "7", "title": "VR Gaming Expo", "description": "Experience the latest in virtual reality gaming technology. Try new games, meet developers, and participate in tournaments.", "tags": ["gaming", "VR", "virtual reality", "expo", "tournaments"], "location": "Los Angeles, CA", "createdAt": "2023-08-07T00:00:00", "imageUrl": "https://example.com/event7.jpg", "startDateTime": "2023-10-14T10:00:00", "endDateTime": "2023-10-14T18:00:00", "price": "30", "isFree": False, "url": "https://example.com/events/7", "category": {"_id": "c7", "name": "Gaming"}, "organizer": {"_id": "o7", "firstName": "Liam", "lastName": "Brown"} }, { "_id": "8", "title": "Yoga & Wellness Retreat", "description": "Weekend retreat focusing on yoga, meditation, and holistic wellness practices. Suitable for all experience levels.", "tags": ["health", "wellness", "yoga", "meditation", "retreat"], "location": "Sedona, AZ", "createdAt": "2023-08-08T00:00:00", "imageUrl": "https://example.com/event8.jpg", "startDateTime": "2023-11-05T08:00:00", "endDateTime": "2023-11-05T17:00:00", "price": "100", "isFree": False, "url": "https://example.com/events/8", "category": {"_id": "c8", "name": "Health & Wellness"}, "organizer": {"_id": "o8", "firstName": "Sophia", "lastName": "Martinez"} }, { "_id": "9", "title": "Tech Meetup: AI Applications", "description": "Monthly meetup discussing practical applications of artificial intelligence in various industries. Networking session included.", "tags": ["technology", "AI", "meetup", "networking", "applications"], "location": "San Francisco, CA", "createdAt": "2023-08-09T00:00:00", "imageUrl": "https://example.com/event9.jpg", "startDateTime": "2023-10-12T18:00:00", "endDateTime": "2023-10-12T21:00:00", "price": "0", "isFree": True, "url": "https://example.com/events/9", "category": {"_id": "c9", "name": "Technology"}, "organizer": {"_id": "o9", "firstName": "Olivia", "lastName": "Davis"} }, { "_id": "10", "title": "Blockchain Conference", "description": "Exploring the future of blockchain technology, cryptocurrencies, and decentralized applications. Features industry experts.", "tags": ["technology", "blockchain", "crypto", "conference", "decentralized"], "location": "Austin, TX", "createdAt": "2023-08-10T00:00:00", "imageUrl": "https://example.com/event10.jpg", "startDateTime": "2023-11-20T09:00:00", "endDateTime": "2023-11-20T17:00:00", "price": "120", "isFree": False, "url": "https://example.com/events/10", "category": {"_id": "c10", "name": "Technology"}, "organizer": {"_id": "o10", "firstName": "James", "lastName": "Miller"} }]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172"""Simplified MCP Server for EventHub RAG functionalityUses basic JSON-RPC over stdio instead of complex MCP libraries"""
import asyncioimport jsonimport sysimport osfrom typing import Any, Dict
sys.path.append('.')from components.search.search import perform_search, get_all_events, initialize_embeddings
class SimpleMCPServer: def __init__(self): self.tools = { "search_events": { "name": "search_events", "description": "Search for events using natural language query with filters", "inputSchema": { "type": "object", "properties": { "query": {"type": "string", "description": "Natural language query for events"}, "user_id": {"type": "string", "description": "User identifier", "default": "default"} }, "required": ["query"] } }, "get_all_events": { "name": "get_all_events", "description": "Get all available events without filtering", "inputSchema": {"type": "object", "properties": {}} } } async def handle_request(self, request: Dict[str, Any]) -> Dict[str, Any]: """Handle incoming JSON-RPC request""" try: method = request.get("method") params = request.get("params", {}) request_id = request.get("id") if method == "tools/list": result = {"tools": list(self.tools.values())} elif method == "tools/call": tool_name = params.get("name") tool_args = params.get("arguments", {}) if tool_name == "search_events": result = await self.search_events(tool_args) elif tool_name == "get_all_events": result = await self.get_all_events(tool_args) else: raise ValueError(f"Unknown tool: {tool_name}") else: raise ValueError(f"Unknown method: {method}") return { "jsonrpc": "2.0", "id": request_id, "result": result } except Exception as e: return { "jsonrpc": "2.0", "id": request.get("id"), "error": {"code": -1, "message": str(e)} } async def search_events(self, args: Dict[str, Any]) -> Dict[str, Any]: """Handle search_events tool call""" query = args.get("query", "") user_id = args.get("user_id", "default") try: results = perform_search(query, user_id) formatted_results = [] for event in results: formatted_event = { "title": event.get("title", ""), "category": event.get("category", ""), "location": event.get("location", ""), "startDateTime": event.get("startDateTime", ""), "endDateTime": event.get("endDateTime", ""), "price": event.get("price", ""), "isFree": event.get("isFree", False), "organizer": event.get("organizer", ""), "tags": event.get("tags", "") } formatted_results.append(formatted_event) response_data = { "query": query, "results_count": len(formatted_results), "events": formatted_results[:10] } return { "content": [{ "type": "text", "text": json.dumps(response_data, indent=2) }] } except Exception as e: return { "content": [{ "type": "text", "text": f"Error searching events: {str(e)}" }] } async def get_all_events(self, args: Dict[str, Any]) -> Dict[str, Any]: """Handle get_all_events tool call""" try: events = get_all_events() response_data = { "total_events": len(events), "events": events[:20] } return { "content": [{ "type": "text", "text": json.dumps(response_data, indent=2) }] } except Exception as e: return { "content": [{ "type": "text", "text": f"Error getting events: {str(e)}" }] } async def run(self): """Main server loop""" print("✓ Simple MCP Server started", file=sys.stderr) while True: try: line = sys.stdin.readline() if not line: break request = json.loads(line.strip()) response = await self.handle_request(request) print(json.dumps(response)) sys.stdout.flush() except json.JSONDecodeError: continue except Exception as e: error_response = { "jsonrpc": "2.0", "id": None, "error": {"code": -1, "message": str(e)} } print(json.dumps(error_response)) sys.stdout.flush()
async def main(): """Run the simplified MCP server""" try: initialize_embeddings() print("✓ Event embeddings initialized", file=sys.stderr) except Exception as e: print(f"✗ Failed to initialize embeddings: {e}", file=sys.stderr) server = SimpleMCPServer() await server.run()12345678910fastapiuvicorn[standard]sentence-transformerschromadbnumpypydanticpython-dotenvcrewaicrewai[tools]mcp1234567891011from setuptools import setup, find_packages
setup( name="eventhub", version="0.1.0", description="AI Agent and Semantic Event Search using FastAPI and ChromaDB", author="Sintayehu Bikila", author_email="sench729@gmail.com", packages=find_packages(include=["components", "components.*"]), python_requires=">=3.8",).dockerignoreAdded+8
.env.exampleAdded+2
.gitignoreAdded+3
DockerfileAdded+29
app.pyAdded+224
components/Event_ai/__init__.pyAdded
components/Event_ai/config/__init__.pyAdded
components/Event_ai/config/agents.yamlAdded+13
components/Event_ai/config/tasks.yamlAdded+34
components/Event_ai/crew.pyAdded+79
components/__init__.pyAdded
components/search/__init__.pyAdded
components/search/search.pyAdded+311
events_data.pyAdded+162
mcp_server.pyAdded+172
requirements.txtAdded+10
setup.pyAdded+11