|
6 | 6 | from pathlib import Path |
7 | 7 | from typing import AsyncIterator |
8 | 8 |
|
| 9 | +import httpx |
9 | 10 | from prefect import get_run_logger, task |
10 | 11 | from prefect.blocks.system import Secret |
11 | 12 | from prefect.logging.loggers import get_logger |
|
20 | 21 | from turbopuffer import NotFoundError |
21 | 22 |
|
22 | 23 | from slackbot.assets import store_user_facts |
| 24 | +from slackbot.github import ( |
| 25 | + GitHubAuthError, |
| 26 | + GitHubError, |
| 27 | + GitHubNotFoundError, |
| 28 | + GitHubRateLimitError, |
| 29 | + create_discussion_from_thread, |
| 30 | + format_discussions_summary, |
| 31 | + search_discussions, |
| 32 | +) |
23 | 33 | from slackbot.research_agent import ( |
24 | 34 | research_prefect_topic, |
25 | 35 | ) |
|
73 | 83 |
|
74 | 84 | 1. **For Technical/Conceptual Questions:** Use `research_prefect_topic`. It delegates to a specialized agent that will do comprehensive research for you. |
75 | 85 | 2. **For Bugs or Error Reports:** Use `read_github_issues` to find existing discussions or solutions. |
76 | | -3. **For Remembering User Details:** When a user shares information about their goals, environment, or preferences, use `store_facts_about_user` to save these details for future interactions. |
77 | | -4. **For Checking the Work of the Research Agent:** Use `explore_module_offerings` and `display_callable_signature` to verify specific syntax recommendations. |
78 | | -5. **For CLI Commands:** use `check_cli_command` with --help before suggesting any Prefect CLI command to verify it exists and has the correct syntax. This prevents suggesting non-existent commands. |
| 86 | +3. **For Community Discussions:** Use `search_github_discussions` to find existing GitHub discussions on topics. |
| 87 | +4. **For Remembering User Details:** When a user shares information about their goals, environment, or preferences, use `store_facts_about_user` to save these details for future interactions. |
| 88 | +5. **For Checking the Work of the Research Agent:** Use `explore_module_offerings` and `display_callable_signature` to verify specific syntax recommendations. |
| 89 | +6. **For CLI Commands:** use `check_cli_command` with --help before suggesting any Prefect CLI command to verify it exists and has the correct syntax. This prevents suggesting non-existent commands. |
79 | 90 | - **IMPORTANT:** When checking commands that require optional dependencies (e.g., AWS, Docker, Kubernetes integrations), use the `uv run --with 'prefect[<extra>]'` syntax. |
80 | 91 | - Examples: `uv run --with 'prefect[aws]'`, `uv run --with 'prefect[docker]'`, `uv run --with 'prefect[kubernetes]'` |
81 | 92 | - This ensures the command runs with the necessary dependencies installed. |
| 93 | +7. **For Creating GitHub Discussions (USE SPARINGLY):** Use `create_discussion_and_notify` only when: |
| 94 | + - The thread contains valuable insights, solutions, or patterns not documented elsewhere |
| 95 | + - You've searched both issues and discussions and found no existing coverage of the topic |
| 96 | + - The conversation would clearly benefit the broader Prefect community |
| 97 | + - The thread has reached a meaningful conclusion or solution |
| 98 | + - **NEVER** create discussions for simple Q&A that's already well-documented |
82 | 99 | """ |
83 | 100 |
|
84 | 101 |
|
@@ -255,4 +272,140 @@ def delete_facts_about_user(ctx: RunContext[UserContext], related_to: str) -> st |
255 | 272 | print(message) |
256 | 273 | return message |
257 | 274 |
|
| 275 | + @agent.tool |
| 276 | + async def create_discussion_and_notify( |
| 277 | + ctx: RunContext[UserContext], |
| 278 | + title: str, |
| 279 | + summary: str, |
| 280 | + repo: str = "prefecthq/prefect", |
| 281 | + ) -> str: |
| 282 | + """ |
| 283 | + Create a GitHub discussion from a Slack thread and notify admin. |
| 284 | +
|
| 285 | + Use this SPARINGLY and only when: |
| 286 | + 1. The thread contains valuable insights or solutions not found elsewhere |
| 287 | + 2. You've searched discussions and found no existing similar topic |
| 288 | + 3. The conversation would benefit the broader Prefect community |
| 289 | +
|
| 290 | + Args: |
| 291 | + title: Clear, descriptive title for the discussion |
| 292 | + summary: Comprehensive summary synthesizing the key insights from the thread |
| 293 | + repo: Repository to create discussion in (default: prefecthq/prefect) |
| 294 | + """ |
| 295 | + print(f"Creating discussion: {title}") |
| 296 | + |
| 297 | + result = await create_discussion_from_thread(ctx, title, summary, repo) |
| 298 | + |
| 299 | + if settings.admin_slack_user_id: |
| 300 | + try: |
| 301 | + await _notify_admin_about_discussion(ctx, title, result) |
| 302 | + except (httpx.RequestError, httpx.HTTPStatusError) as e: |
| 303 | + print(f"Failed to notify admin via Slack: {e}") |
| 304 | + except Exception as e: |
| 305 | + print(f"Unexpected error during admin notification: {e}") |
| 306 | + |
| 307 | + return result |
| 308 | + |
| 309 | + @agent.tool |
| 310 | + async def search_github_discussions( |
| 311 | + ctx: RunContext[UserContext], |
| 312 | + query: str, |
| 313 | + repo: str = "prefecthq/prefect", |
| 314 | + n: int = 5, |
| 315 | + ) -> str: |
| 316 | + """ |
| 317 | + Search for GitHub discussions in a repository. Call this ONCE per search query. |
| 318 | +
|
| 319 | + Use this to find existing discussions before creating new ones. |
| 320 | +
|
| 321 | + IMPORTANT: This searches ALL discussions for your query terms. |
| 322 | + Call it ONCE and review the results. Do NOT call repeatedly with the same query. |
| 323 | + If no results are found, that means there are no matching discussions. |
| 324 | +
|
| 325 | + Args: |
| 326 | + query: Search terms for discussions (e.g. "redis", "deployment", "workers") |
| 327 | + repo: Repository to search (default: prefecthq/prefect) |
| 328 | + n: Number of results to return (default: 5) |
| 329 | + """ |
| 330 | + try: |
| 331 | + discussions = await search_discussions(query, repo=repo, n=n) |
| 332 | + return await format_discussions_summary(discussions) |
| 333 | + except GitHubNotFoundError: |
| 334 | + return "Sorry, I couldn't find any discussions. The repository might not have discussions enabled." |
| 335 | + except GitHubAuthError: |
| 336 | + await _notify_admin_about_error( |
| 337 | + ctx, "GitHub authentication failed while searching discussions" |
| 338 | + ) |
| 339 | + return f"Sorry, I'm having trouble accessing GitHub right now. <@{settings.admin_slack_user_id}> has been notified." |
| 340 | + except GitHubRateLimitError: |
| 341 | + return "Sorry, I've hit GitHub's rate limit. Please try again in a few minutes." |
| 342 | + except GitHubError as e: |
| 343 | + await _notify_admin_about_error( |
| 344 | + ctx, f"GitHub API error while searching discussions: {str(e)}" |
| 345 | + ) |
| 346 | + return f"Sorry, I encountered an error while searching discussions. <@{settings.admin_slack_user_id}> has been notified." |
| 347 | + except Exception as e: |
| 348 | + import traceback |
| 349 | + |
| 350 | + error_details = traceback.format_exc() |
| 351 | + await _notify_admin_about_error( |
| 352 | + ctx, |
| 353 | + f"Unexpected error in search_github_discussions: {str(e)}\n{error_details}", |
| 354 | + ) |
| 355 | + return f"Error searching discussions: {str(e)}" |
| 356 | + |
258 | 357 | return agent |
| 358 | + |
| 359 | + |
| 360 | +async def _notify_admin_about_discussion( |
| 361 | + ctx: RunContext[UserContext], title: str, creation_result: str |
| 362 | +) -> None: |
| 363 | + """Send a notification to the admin about the created discussion.""" |
| 364 | + thread_link = f"https://{ctx.deps['workspace_name']}.slack.com/archives/{ctx.deps['channel_id']}/p{ctx.deps['thread_ts'].replace('.', '')}" |
| 365 | + |
| 366 | + message = ( |
| 367 | + f"🤖 Marvin created a GitHub discussion:\n" |
| 368 | + f"*{title}*\n\n" |
| 369 | + f"{creation_result}\n\n" |
| 370 | + f"Original thread: {thread_link}" |
| 371 | + ) |
| 372 | + |
| 373 | + await _send_admin_notification(message) |
| 374 | + |
| 375 | + |
| 376 | +async def _notify_admin_about_error( |
| 377 | + ctx: RunContext[UserContext], error_message: str |
| 378 | +) -> None: |
| 379 | + """Send a notification to the admin about an error.""" |
| 380 | + if not settings.admin_slack_user_id: |
| 381 | + return # No admin configured |
| 382 | + |
| 383 | + thread_link = f"https://{ctx.deps['workspace_name']}.slack.com/archives/{ctx.deps['channel_id']}/p{ctx.deps['thread_ts'].replace('.', '')}" |
| 384 | + |
| 385 | + message = ( |
| 386 | + f"🚨 Marvin encountered an error:\n" |
| 387 | + f"*{error_message}*\n\n" |
| 388 | + f"Thread: {thread_link}\n" |
| 389 | + f"User: <@{ctx.deps['user_id']}>" |
| 390 | + ) |
| 391 | + |
| 392 | + await _send_admin_notification(message) |
| 393 | + |
| 394 | + |
| 395 | +async def _send_admin_notification(message: str) -> None: |
| 396 | + """Send a notification message to the admin.""" |
| 397 | + if not settings.admin_slack_user_id: |
| 398 | + return |
| 399 | + |
| 400 | + headers = { |
| 401 | + "Authorization": f"Bearer {settings.slack_api_token}", |
| 402 | + "Content-Type": "application/json", |
| 403 | + } |
| 404 | + |
| 405 | + payload = {"channel": settings.admin_slack_user_id, "text": message} |
| 406 | + |
| 407 | + async with httpx.AsyncClient() as client: |
| 408 | + response = await client.post( |
| 409 | + "https://slack.com/api/chat.postMessage", headers=headers, json=payload |
| 410 | + ) |
| 411 | + response.raise_for_status() |
0 commit comments