|
| 1 | +"""Generate AI insights task for Airflow DAG - writes to gold_ai_insights table.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import json |
| 6 | +import logging |
| 7 | +import os |
| 8 | +import re |
| 9 | +import time |
| 10 | +from datetime import datetime |
| 11 | + |
| 12 | +from airflow.decorators import task |
| 13 | + |
| 14 | +logger = logging.getLogger(__name__) |
| 15 | + |
| 16 | +GROQ_API_KEY = os.getenv("GROQ_API_KEY", "") |
| 17 | +DATABRICKS_HOST = os.getenv("DATABRICKS_HOST", "") |
| 18 | +DATABRICKS_TOKEN = os.getenv("DATABRICKS_TOKEN", "") |
| 19 | +DATABRICKS_WAREHOUSE_ID = os.getenv("DATABRICKS_WAREHOUSE_ID", "") |
| 20 | + |
| 21 | +MODEL = "llama-3.1-8b-instant" |
| 22 | +DELAY_BETWEEN_CALLS = 2 |
| 23 | + |
| 24 | +PROMPT_TEMPLATE = """Analyze posts/comments from r/{subreddit}. Return JSON with 3 categories: |
| 25 | +- trending_tools: tools/libs/frameworks mentioned (key: "name") |
| 26 | +- pain_points: problems/frustrations discussed (key: "topic") |
| 27 | +- solutions: recommendations proposed (key: "topic") |
| 28 | +
|
| 29 | +Each item: name/topic (max 5 words), mentions (int), context (1 sentence in Portuguese BR). |
| 30 | +Top 3 per category. Empty array if none. ONLY valid JSON, no markdown. |
| 31 | +
|
| 32 | +Schema: {{"trending_tools":[{{"name":"...","mentions":N,"context":"..."}}],"pain_points":[{{"topic":"...","mentions":N,"context":"..."}}],"solutions":[{{"topic":"...","mentions":N,"context":"..."}}]}} |
| 33 | +
|
| 34 | +--- r/{subreddit} DATA --- |
| 35 | +{content} |
| 36 | +""" |
| 37 | + |
| 38 | + |
| 39 | +def _execute_databricks_query(query: str) -> list[dict]: |
| 40 | + """Execute SQL query on Databricks and return results as dicts.""" |
| 41 | + from databricks import sql |
| 42 | + |
| 43 | + with sql.connect( |
| 44 | + server_hostname=DATABRICKS_HOST, |
| 45 | + http_path=f"/sql/1.0/warehouses/{DATABRICKS_WAREHOUSE_ID}", |
| 46 | + access_token=DATABRICKS_TOKEN, |
| 47 | + ) as conn: |
| 48 | + with conn.cursor() as cursor: |
| 49 | + cursor.execute(query) |
| 50 | + columns = [desc[0] for desc in cursor.description] |
| 51 | + return [dict(zip(columns, row)) for row in cursor.fetchall()] |
| 52 | + |
| 53 | + |
| 54 | +def _get_subreddits_with_data() -> list[str]: |
| 55 | + """Get list of subreddits that have data in Silver.""" |
| 56 | + results = _execute_databricks_query( |
| 57 | + "SELECT subreddit, COUNT(*) as cnt FROM devradar_silver_posts " |
| 58 | + "GROUP BY subreddit HAVING cnt >= 3 ORDER BY cnt DESC" |
| 59 | + ) |
| 60 | + return [r["subreddit"] for r in results] |
| 61 | + |
| 62 | + |
| 63 | +def _get_content_for_subreddit( |
| 64 | + sub: str, |
| 65 | + posts_limit: int = 15, |
| 66 | + comments_limit: int = 20, |
| 67 | + max_chars: int = 6000, |
| 68 | +) -> str: |
| 69 | + """Fetch posts and comments content from Silver tables.""" |
| 70 | + posts = _execute_databricks_query( |
| 71 | + f"SELECT title, selftext FROM devradar_silver_posts " |
| 72 | + f"WHERE subreddit = '{sub}' ORDER BY score DESC LIMIT {posts_limit}" |
| 73 | + ) |
| 74 | + |
| 75 | + comments = _execute_databricks_query( |
| 76 | + f"SELECT body FROM devradar_silver_comments " |
| 77 | + f"WHERE subreddit = '{sub}' ORDER BY score DESC LIMIT {comments_limit}" |
| 78 | + ) |
| 79 | + |
| 80 | + parts = [] |
| 81 | + for p in posts: |
| 82 | + text = p.get("title", "") |
| 83 | + if p.get("selftext"): |
| 84 | + text += f" | {p['selftext'][:150]}" |
| 85 | + parts.append(text) |
| 86 | + |
| 87 | + for c in comments: |
| 88 | + if c.get("body"): |
| 89 | + parts.append(c["body"][:120]) |
| 90 | + |
| 91 | + return "\n".join(parts)[:max_chars] |
| 92 | + |
| 93 | + |
| 94 | +def _call_groq(subreddit: str, content: str) -> dict | None: |
| 95 | + """Call Groq API to generate insights.""" |
| 96 | + from openai import OpenAI |
| 97 | + |
| 98 | + client = OpenAI(base_url="https://api.groq.com/openai/v1", api_key=GROQ_API_KEY) |
| 99 | + prompt = PROMPT_TEMPLATE.format(subreddit=subreddit, content=content) |
| 100 | + |
| 101 | + for attempt in range(3): |
| 102 | + try: |
| 103 | + resp = client.chat.completions.create( |
| 104 | + model=MODEL, |
| 105 | + messages=[{"role": "user", "content": prompt}], |
| 106 | + temperature=0.2, |
| 107 | + max_tokens=800, |
| 108 | + response_format={"type": "json_object"}, |
| 109 | + ) |
| 110 | + text = resp.choices[0].message.content |
| 111 | + parsed = json.loads(text) |
| 112 | + |
| 113 | + if isinstance(parsed, dict) and { |
| 114 | + "trending_tools", "pain_points", "solutions" |
| 115 | + }.intersection(parsed.keys()): |
| 116 | + return parsed |
| 117 | + |
| 118 | + logger.warning(f"r/{subreddit}: Estrutura inesperada, tentativa {attempt+1}") |
| 119 | + continue |
| 120 | + |
| 121 | + except Exception as e: |
| 122 | + err_str = str(e) |
| 123 | + if "429" in err_str: |
| 124 | + wait = 60 |
| 125 | + match = re.search(r"try again in (\d+(?:\.\d+)?)s", err_str) |
| 126 | + if match: |
| 127 | + wait = int(float(match.group(1))) + 1 |
| 128 | + logger.warning(f"r/{subreddit}: Rate limit, aguardando {wait}s...") |
| 129 | + time.sleep(wait) |
| 130 | + continue |
| 131 | + |
| 132 | + logger.error(f"r/{subreddit}: Erro Groq - {err_str[:150]}") |
| 133 | + return None |
| 134 | + |
| 135 | + return None |
| 136 | + |
| 137 | + |
| 138 | +def _write_insights_to_gold(subreddit: str, insights: dict, execution_date: str) -> None: |
| 139 | + """Write insights to gold_ai_insights table.""" |
| 140 | + from databricks import sql |
| 141 | + |
| 142 | + rows = [] |
| 143 | + for insight_type in ["trending_tools", "pain_points", "solutions"]: |
| 144 | + items = insights.get(insight_type, []) |
| 145 | + for item in items: |
| 146 | + if insight_type == "trending_tools": |
| 147 | + item_name = item.get("name", "") |
| 148 | + else: |
| 149 | + item_name = item.get("topic", "") |
| 150 | + |
| 151 | + rows.append(( |
| 152 | + subreddit, |
| 153 | + insight_type, |
| 154 | + item_name, |
| 155 | + item.get("mentions", 0), |
| 156 | + item.get("context", ""), |
| 157 | + datetime.now(), |
| 158 | + execution_date, |
| 159 | + MODEL, |
| 160 | + )) |
| 161 | + |
| 162 | + if not rows: |
| 163 | + logger.warning(f"r/{subreddit}: Nenhum insight para inserir") |
| 164 | + return |
| 165 | + |
| 166 | + with sql.connect( |
| 167 | + server_hostname=DATABRICKS_HOST, |
| 168 | + http_path=f"/sql/1.0/warehouses/{DATABRICKS_WAREHOUSE_ID}", |
| 169 | + access_token=DATABRICKS_TOKEN, |
| 170 | + ) as conn: |
| 171 | + with conn.cursor() as cursor: |
| 172 | + # MERGE para evitar duplicatas |
| 173 | + cursor.executemany( |
| 174 | + """ |
| 175 | + MERGE INTO gold_ai_insights AS target |
| 176 | + USING (VALUES (?, ?, ?, ?, ?, ?, ?, ?)) AS source( |
| 177 | + subreddit, insight_type, item_name, mentions, context, |
| 178 | + generated_at, execution_date, model_version |
| 179 | + ) |
| 180 | + ON target.subreddit = source.subreddit |
| 181 | + AND target.insight_type = source.insight_type |
| 182 | + AND target.item_name = source.item_name |
| 183 | + AND target.execution_date = source.execution_date |
| 184 | + WHEN MATCHED THEN UPDATE SET * |
| 185 | + WHEN NOT MATCHED THEN INSERT * |
| 186 | + """, |
| 187 | + rows |
| 188 | + ) |
| 189 | + |
| 190 | + logger.info(f"r/{subreddit}: {len(rows)} insights inseridos na tabela Gold") |
| 191 | + |
| 192 | + |
| 193 | +@task |
| 194 | +def generate_insights(**context) -> dict: |
| 195 | + """Generate AI insights for all subreddits and write to gold_ai_insights table.""" |
| 196 | + execution_date = context["ds"] |
| 197 | + |
| 198 | + if not GROQ_API_KEY: |
| 199 | + logger.error("GROQ_API_KEY não configurada - pulando geração de insights") |
| 200 | + return {"status": "skipped", "reason": "missing_groq_key"} |
| 201 | + |
| 202 | + if not all([DATABRICKS_HOST, DATABRICKS_TOKEN, DATABRICKS_WAREHOUSE_ID]): |
| 203 | + logger.error("Databricks credentials não configuradas - pulando insights") |
| 204 | + return {"status": "skipped", "reason": "missing_databricks_creds"} |
| 205 | + |
| 206 | + logger.info("Buscando subreddits com dados no Databricks...") |
| 207 | + subreddits = _get_subreddits_with_data() |
| 208 | + logger.info(f"Encontrados {len(subreddits)} subreddits para processar") |
| 209 | + |
| 210 | + processed = 0 |
| 211 | + errors = 0 |
| 212 | + |
| 213 | + for i, sub in enumerate(subreddits, 1): |
| 214 | + logger.info(f"[{i}/{len(subreddits)}] Processando r/{sub}...") |
| 215 | + |
| 216 | + content = _get_content_for_subreddit(sub) |
| 217 | + if len(content) < 100: |
| 218 | + logger.warning(f"r/{sub}: Pouco conteúdo, pulando") |
| 219 | + continue |
| 220 | + |
| 221 | + insights = _call_groq(sub, content) |
| 222 | + if insights: |
| 223 | + _write_insights_to_gold(sub, insights, execution_date) |
| 224 | + processed += 1 |
| 225 | + |
| 226 | + t = len(insights.get("trending_tools", [])) |
| 227 | + p = len(insights.get("pain_points", [])) |
| 228 | + s = len(insights.get("solutions", [])) |
| 229 | + logger.info(f"r/{sub}: OK ({t}t {p}p {s}s)") |
| 230 | + else: |
| 231 | + errors += 1 |
| 232 | + logger.error(f"r/{sub}: Falha ao gerar insights") |
| 233 | + |
| 234 | + if i < len(subreddits): |
| 235 | + time.sleep(DELAY_BETWEEN_CALLS) |
| 236 | + |
| 237 | + logger.info( |
| 238 | + f"Geração de insights completa: {processed} sucesso, {errors} erros" |
| 239 | + ) |
| 240 | + |
| 241 | + return { |
| 242 | + "status": "completed", |
| 243 | + "processed": processed, |
| 244 | + "errors": errors, |
| 245 | + "total": len(subreddits), |
| 246 | + } |
0 commit comments