Spaces:
Sleeping
Sleeping
Upload 4 files
Browse filesFiles changed (4)
- DockerfileAdded+19
- app.pyAdded+223
- fastmcp.jsonAdded+10
- requirements.txtAdded+5
12345678910111213141516171819FROM python:3.11-slim
# Set the working directory in the containerWORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
# Create directory for battle replays with proper permissionsRUN mkdir -p battle_replays && chmod 755 battle_replays
EXPOSE 7860
ENV PORT=7860
CMD ["python", "app.py"] 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223from __future__ import annotations
import osfrom typing import List, Optional, Literal
import httpximport feedparserfrom pydantic import BaseModel, Field, HttpUrl
from fastmcp import FastMCPfrom mistralai import Mistral
mcp = FastMCP( name="reddit-painpoints", description="Monitor r/MistralAI and extract community pain points (with links)", host="0.0.0.0", port=7860,)
MISTRAL_MODEL = "mistral-medium-2508"
class PainPoint(BaseModel): """Structured representation of a user pain point extracted from a Reddit post."""
title: str = Field(..., description="Short title of the pain point") summary: str = Field(..., description="One-sentence summary of the problem") url: HttpUrl = Field(..., description="URL to the original Reddit post") score: int = Field(..., description="Reddit score (upvotes minus downvotes)") created_utc: float = Field(..., description="Post creation time (Unix seconds)") post_id: str = Field(..., description="Reddit post ID") flair: Optional[str] = Field(None, description="Post flair, if present")
class PainPointDecision(BaseModel): decision: Literal["YES", "NO"] reason: Optional[str] = None
class PainPointGenerated(BaseModel): title: str summary: str
def _fetch_subreddit_new(subreddit: str, limit: int) -> list[dict]: """Fetch 'new' posts; fallback to RSS if JSON is blocked.""" json_url = f"https://www.reddit.com/r/{subreddit}/new.json?limit={limit}" headers = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) FastMCP-RedditPainPoints/1.0 (+https://example.com)", "Accept": "application/json, text/plain, */*", "Accept-Language": "en-US,en;q=0.9", }
try: with httpx.Client(timeout=httpx.Timeout(15.0), headers=headers) as client: response = client.get(json_url, follow_redirects=True) response.raise_for_status() payload = response.json() children = payload.get("data", {}).get("children", []) print(f"Reddit fetch source: JSON API ({len(children)} items)") return [child.get("data", {}) for child in children] except Exception: # RSS fallback feed_url = f"https://www.reddit.com/r/{subreddit}/new/.rss" feed = feedparser.parse(feed_url) posts: list[dict] = [] for entry in feed.entries[:limit]: # Attempt to extract id and score if present (RSS is limited) link = entry.get("link") or "" title = entry.get("title") or "" # created: use published_parsed if available created_utc = 0.0 if getattr(entry, "published_parsed", None): try: import calendar
created_utc = float(calendar.timegm(entry.published_parsed)) except Exception: created_utc = 0.0 posts.append( { "title": title, "selftext": "", "score": 0, "created_utc": created_utc, "id": entry.get("id") or "", "permalink": "", "url": link, "link_flair_text": None, } ) print(f"Reddit fetch source: RSS fallback ({len(posts)} items)") return posts
def _get_mistral_client() -> Mistral: api_key = os.environ.get("MISTRAL_API_KEY") if not api_key: raise RuntimeError("MISTRAL_API_KEY environment variable is required for AI-based extraction") return Mistral(api_key=api_key)
def _ai_should_extract_painpoint(client: Mistral, title: str, selftext: str) -> bool: """Use Mistral structured output to decide if the post is a pain point.""" content = ( "You are a strict classifier deciding if a Reddit post describes a concrete pain point " "about Mistral AI usage (APIs, models, SDKs, deployment, errors, performance, limitations).\n\n" "Return JSON with decision YES/NO and a brief reason." )
user_text = ( f"Title: {title}\n\n" f"Body: {selftext or '(none)'}\n\n" "Does this describe a real problem/pain point that warrants tracking?" )
resp = client.chat.parse( model=MISTRAL_MODEL, messages=[ {"role": "system", "content": content}, {"role": "user", "content": user_text}, ], response_format=PainPointDecision, temperature=0, max_tokens=64, )
parsed: PainPointDecision = resp.choices[0].message.parsed # type: ignore[attr-defined] print(f"AI classify: {parsed.decision}") return parsed.decision == "YES"
def _ai_generate_title_summary(client: Mistral, title: str, selftext: str) -> PainPointGenerated: """Use Mistral structured output to produce a concise title and summary.""" content = ( "You generate a clear, concise pain point title and a one-sentence summary that captures the core issue.\n" "Do not add links or metadata. Keep the summary <= 240 characters." ) user_text = ( f"Original Title: {title}\n\n" f"Body: {selftext or '(none)'}\n\n" "If insufficient information, infer a short neutral title and a crisp summary." )
resp = client.chat.parse( model=MISTRAL_MODEL, messages=[ {"role": "system", "content": content}, {"role": "user", "content": user_text}, ], response_format=PainPointGenerated, temperature=0, max_tokens=128, )
return resp.choices[0].message.parsed # type: ignore[return-value, attr-defined]
@mcp.tool(description="Scan r/MistralAI for problem-like posts using AI and return extracted pain points.")def scan_mistralai_pain_points(limit: int = 50, min_score: int = 0) -> List[PainPoint]: """ Fetch recent posts from r/MistralAI and extract a list of pain points using a two-step AI flow: 1) Classify each post as a pain point (YES/NO) 2) If YES, generate a concise title and summary via structured outputs
- limit: Maximum posts to scan (<=100) - min_score: Minimum Reddit score to include
Requires MISTRAL_API_KEY in environment. """ raw_posts = _fetch_subreddit_new("MistralAI", max(1, min(limit, 100))) client = _get_mistral_client()
pain_points: List[PainPoint] = [] for post in raw_posts: title = post.get("title", "").strip() selftext = post.get("selftext", "") or "" score = int(post.get("score", 0) or 0)
if score < min_score: continue
try: should = _ai_should_extract_painpoint(client, title, selftext) except Exception: # On AI failure, skip the post to avoid false positives print("AI classify failed; skipping post") continue
if not should: continue
try: gen = _ai_generate_title_summary(client, title, selftext) ai_title = gen.title.strip() ai_summary = gen.summary.strip() except Exception: # If generation fails, fall back to minimal safe defaults print("AI generation failed; using fallback title/summary") ai_title = title ai_summary = (selftext or title)[:240]
permalink = post.get("permalink") or "" full_url = f"https://www.reddit.com{permalink}" if permalink else post.get("url_overridden_by_dest") or post.get("url") or ""
pain_points.append( PainPoint( title=ai_title or title, summary=ai_summary, url=full_url, score=score, created_utc=float(post.get("created_utc", 0.0) or 0.0), post_id=str(post.get("id", "")), flair=post.get("link_flair_text"), ) )
print(f"Extraction complete: {len(pain_points)} pain points") return pain_points
if __name__ == "__main__": mcp.run(transport="http") 12345678910{ "name": "reddit-painpoints", "description": "MCP server that monitors r/MistralAI and extracts community pain points with links", "entrypoint": "server.py", "transport": "streamable-http", "http": { "host": "0.0.0.0", "port": 7860 }} 12345fastmcp>=2.12.2httpx>=0.27.0pydantic>=2.7.0mistralai>=1.5.0feedparser>=6.0.11 DockerfileAdded+19
app.pyAdded+223
fastmcp.jsonAdded+10
requirements.txtAdded+5