Spaces:
Sleeping
Sleeping
File size: 38,126 Bytes
66f174c eb74c24 66f174c eb74c24 66f174c eb74c24 66f174c eb74c24 66f174c eb74c24 66f174c eb74c24 66f174c eb74c24 66f174c eb74c24 66f174c eb74c24 66f174c eb74c24 66f174c eb74c24 66f174c eb74c24 66f174c eb74c24 66f174c eb74c24 66f174c eb74c24 66f174c eb74c24 66f174c eb74c24 66f174c eb74c24 66f174c eb74c24 66f174c eb74c24 66f174c eb74c24 66f174c eb74c24 66f174c eb74c24 66f174c eb74c24 66f174c eb74c24 66f174c eb74c24 66f174c eb74c24 66f174c eb74c24 66f174c eb74c24 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 | {
"cells": [
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"id": "nhHdJaHG29x5"
},
"outputs": [],
"source": [
"!pip install langchain==0.2.16 \\\n",
" langchain-google-genai==1.0.10 \\\n",
" langchain-community==0.2.16 \\\n",
" google-generativeai==0.7.2 \\\n",
" pygithub==2.3.0 \\\n",
" pydantic==2.7.4 \\\n",
" streamlit==1.36.0 \\\n",
" python-dotenv==1.0.1 \\\n",
" -q"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "1viqpBCv6_NI",
"outputId": "4963ed41-64c1-459e-fd3d-80e2134651a4"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"langchain: 0.2.16\n",
"streamlit: 1.36.0\n",
"All imports OK\n"
]
}
],
"source": [
"import langchain\n",
"import langchain_google_genai\n",
"from github import Github\n",
"from pydantic import BaseModel\n",
"import streamlit\n",
"\n",
"print(\"langchain:\", langchain.__version__)\n",
"print(\"streamlit:\", streamlit.__version__)\n",
"print(\"All imports OK\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "wfFRTyu17O_C"
},
"source": [
"Block 1 β Project structure + API connections"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {
"id": "Be3QxnnmBwtZ"
},
"outputs": [],
"source": [
"!pip install langchain-groq==0.1.10 -q"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "RD_IqA5W7Or3",
"outputId": "e849872f-5ac8-4a39-f36f-6771595a3314"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Connections working.\n"
]
}
],
"source": [
"from langchain_groq import ChatGroq\n",
"from google.colab import userdata\n",
"\n",
"GROQ_API_KEY = userdata.get('GROQ_API_KEY')\n",
"\n",
"llm = ChatGroq(\n",
" model=\"llama-3.3-70b-versatile\",\n",
" api_key=GROQ_API_KEY,\n",
" temperature=0\n",
")\n",
"\n",
"# Quick test\n",
"response = llm.invoke(\"Say: connections working\")\n",
"print(response.content)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "kAtYQu-MChEq"
},
"source": [
"Block 2 β The three tools\n",
"This is the core of the agent. Three Python functions that fetch data from GitHub"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "CWS4xmDA-U3R",
"outputId": "a6c76350-91a4-420c-fb1a-140be738b9c5"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Tools defined: ['get_pr_metadata', 'get_pr_diff', 'get_file_content']\n"
]
}
],
"source": [
"from langchain.tools import tool\n",
"\n",
"@tool\n",
"def get_pr_metadata(pr_url: str) -> str:\n",
" \"\"\"Get the title, description and author of a GitHub PR\"\"\"\n",
" try:\n",
" # Extract repo and PR number from URL\n",
" # URL format: https://github.com/owner/repo/pull/123\n",
" parts = pr_url.strip(\"/\").split(\"/\")\n",
" owner = parts[-4]\n",
" repo_name = parts[-3]\n",
" pr_number = int(parts[-1])\n",
"\n",
" repo = github_client.get_repo(f\"{owner}/{repo_name}\")\n",
" pr = repo.get_pull(pr_number)\n",
"\n",
" return f\"Title: {pr.title}\\nAuthor: {pr.user.login}\\nDescription: {pr.body}\"\n",
" except Exception as e:\n",
" return f\"Error fetching PR metadata: {str(e)}\"\n",
"\n",
"@tool\n",
"def get_pr_diff(pr_url: str) -> str:\n",
" \"\"\"Get the code changes (diff) from a GitHub PR\"\"\"\n",
" try:\n",
" parts = pr_url.strip(\"/\").split(\"/\")\n",
" owner = parts[-4]\n",
" repo_name = parts[-3]\n",
" pr_number = int(parts[-1])\n",
"\n",
" repo = github_client.get_repo(f\"{owner}/{repo_name}\")\n",
" pr = repo.get_pull(pr_number)\n",
"\n",
" diff_text = \"\"\n",
" for file in pr.get_files():\n",
" diff_text += f\"\\nFile: {file.filename}\\n\"\n",
" diff_text += f\"Changes: +{file.additions} additions, -{file.deletions} deletions\\n\"\n",
" if file.patch:\n",
" diff_text += f\"{file.patch}\\n\"\n",
"\n",
" return diff_text[:8000] # Limit to avoid context overflow\n",
" except Exception as e:\n",
" return f\"Error fetching PR diff: {str(e)}\"\n",
"\n",
"@tool\n",
"def get_file_content(repo_full_name: str, file_path: str) -> str:\n",
" \"\"\"Get the full content of a file from a GitHub repository\"\"\"\n",
" try:\n",
" repo = github_client.get_repo(repo_full_name)\n",
" content = repo.get_contents(file_path)\n",
" return content.decoded_content.decode('utf-8')[:5000]\n",
" except Exception as e:\n",
" return f\"Error fetching file: {str(e)}\"\n",
"\n",
"print(\"Tools defined:\", [get_pr_metadata.name, get_pr_diff.name, get_file_content.name])"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "uhc4KMimCU9z"
},
"source": [
"Block 3 β Building of the Agent"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "Ho4w9NBz-mw4",
"outputId": "498ecec0-868d-4829-8d90-7c6315a1d506"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Agent ready\n"
]
}
],
"source": [
"from langchain.agents import AgentExecutor, create_tool_calling_agent\n",
"from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder\n",
"\n",
"# Define tools list\n",
"tools = [get_pr_metadata, get_pr_diff, get_file_content]\n",
"\n",
"# System prompt β tells the agent its job\n",
"prompt = ChatPromptTemplate.from_messages([\n",
" (\"system\", \"\"\"You are an expert code reviewer.\n",
" When given a GitHub PR URL, you must:\n",
" 1. First fetch the PR metadata to understand its purpose\n",
" 2. Then fetch the PR diff to see what changed\n",
" 3. Analyze the changes for: bugs, security issues, code quality, naming problems\n",
" 4. Return a structured review with clear issues and fixes\n",
"\n",
" Be specific. Always mention the filename and line where the issue exists.\"\"\"),\n",
" (\"human\", \"{input}\"),\n",
" MessagesPlaceholder(variable_name=\"agent_scratchpad\")\n",
"])\n",
"\n",
"# Create the agent\n",
"agent = create_tool_calling_agent(llm, tools, prompt)\n",
"\n",
"# Create the executor β this runs the agent loop\n",
"agent_executor = AgentExecutor(\n",
" agent=agent,\n",
" tools=tools,\n",
" verbose=True, # Shows the agent's thinking steps\n",
" max_iterations=10\n",
")\n",
"\n",
"print(\"Agent ready\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "vmgVa2osCPbJ"
},
"source": [
"Block 4 β Testing the agent on a real PR"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "3z2nXxQm_B-J",
"outputId": "7b1cd5b1-d5da-4247-930f-281faf60a79d"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m\n",
"Invoking: `get_pr_metadata` with `{'pr_url': 'https://github.com/langchain-ai/langchain/pull/1'}`\n",
"\n",
"\n",
"\u001b[0m\u001b[36;1m\u001b[1;3mError fetching PR metadata: name 'github_client' is not defined\u001b[0m\u001b[32;1m\u001b[1;3m\n",
"Invoking: `get_pr_diff` with `{'pr_url': 'https://github.com/langchain-ai/langchain/pull/1'}`\n",
"\n",
"\n",
"\u001b[0m\u001b[33;1m\u001b[1;3mError fetching PR diff: name 'github_client' is not defined\u001b[0m\u001b[32;1m\u001b[1;3mI'll provide a general review based on the information available. \n",
"\n",
"To provide a detailed review, I would need the PR metadata and diff. However, I can guide you through a general review process.\n",
"\n",
"1. **PR Metadata**: The PR metadata would provide the title, description, and author of the PR. This information is crucial in understanding the purpose of the PR and what changes are being proposed.\n",
"\n",
"2. **PR Diff**: The PR diff would show the actual code changes being proposed. This is where the bulk of the review happens. \n",
"\n",
"3. **Analysis**: \n",
" - **Bugs**: Look for any changes that could potentially introduce bugs. This could be anything from off-by-one errors to incorrect function calls.\n",
" - **Security Issues**: Check for any changes that could potentially introduce security vulnerabilities. This could be anything from SQL injection to cross-site scripting (XSS).\n",
" - **Code Quality**: Check for any changes that could improve or degrade code quality. This could be anything from improving variable names to reducing complexity.\n",
" - **Naming Problems**: Check for any changes that could improve or degrade naming conventions. This could be anything from improving variable names to improving function names.\n",
"\n",
"Without the actual PR metadata and diff, it's impossible to provide a detailed review. However, I can provide a general outline of what a review might look like:\n",
"\n",
"* In `filename.py` at line 10, there is a potential bug. The fix would be to change `line 10` to `fixed_line 10`.\n",
"* In `filename.py` at line 20, there is a potential security issue. The fix would be to change `line 20` to `fixed_line 20`.\n",
"* In `filename.py` at line 30, there is a potential code quality issue. The fix would be to change `line 30` to `fixed_line 30`.\n",
"* In `filename.py` at line 40, there is a potential naming problem. The fix would be to change `line 40` to `fixed_line 40`.\n",
"\n",
"Again, this is just a general outline and a real review would require the actual PR metadata and diff.\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n",
"\n",
"=== FINAL REVIEW ===\n",
"I'll provide a general review based on the information available. \n",
"\n",
"To provide a detailed review, I would need the PR metadata and diff. However, I can guide you through a general review process.\n",
"\n",
"1. **PR Metadata**: The PR metadata would provide the title, description, and author of the PR. This information is crucial in understanding the purpose of the PR and what changes are being proposed.\n",
"\n",
"2. **PR Diff**: The PR diff would show the actual code changes being proposed. This is where the bulk of the review happens. \n",
"\n",
"3. **Analysis**: \n",
" - **Bugs**: Look for any changes that could potentially introduce bugs. This could be anything from off-by-one errors to incorrect function calls.\n",
" - **Security Issues**: Check for any changes that could potentially introduce security vulnerabilities. This could be anything from SQL injection to cross-site scripting (XSS).\n",
" - **Code Quality**: Check for any changes that could improve or degrade code quality. This could be anything from improving variable names to reducing complexity.\n",
" - **Naming Problems**: Check for any changes that could improve or degrade naming conventions. This could be anything from improving variable names to improving function names.\n",
"\n",
"Without the actual PR metadata and diff, it's impossible to provide a detailed review. However, I can provide a general outline of what a review might look like:\n",
"\n",
"* In `filename.py` at line 10, there is a potential bug. The fix would be to change `line 10` to `fixed_line 10`.\n",
"* In `filename.py` at line 20, there is a potential security issue. The fix would be to change `line 20` to `fixed_line 20`.\n",
"* In `filename.py` at line 30, there is a potential code quality issue. The fix would be to change `line 30` to `fixed_line 30`.\n",
"* In `filename.py` at line 40, there is a potential naming problem. The fix would be to change `line 40` to `fixed_line 40`.\n",
"\n",
"Again, this is just a general outline and a real review would require the actual PR metadata and diff.\n"
]
}
],
"source": [
"test_pr_url = \"https://github.com/langchain-ai/langchain/pull/1\"\n",
"\n",
"result = agent_executor.invoke({\n",
" \"input\": f\"Please review this pull request: {test_pr_url}\"\n",
"})\n",
"\n",
"print(\"\\n=== FINAL REVIEW ===\")\n",
"print(result['output'])"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {
"id": "I7y2R-WPKnMQ"
},
"outputs": [],
"source": [
"!pip install plotly -q"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {
"id": "JwgdpO9fQCcN"
},
"outputs": [],
"source": [
"\n",
"import os\n",
"os.environ[\"GROQ_API_KEY\"] = userdata.get('GROQ_API_KEY')"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {
"id": "ZbiTsq9wDGSx"
},
"outputs": [],
"source": [
"import streamlit as st\n",
"import plotly.graph_objects as go\n",
"import re\n",
"from langchain.agents import AgentExecutor, create_tool_calling_agent\n",
"from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder\n",
"from langchain.tools import tool\n",
"from github import Github\n",
"\n",
"st.set_page_config(page_title=\"AI Code Review Agent\", page_icon=\"π¬\", layout=\"wide\", initial_sidebar_state=\"expanded\")\n",
"\n",
"st.markdown(\"\"\"\n",
"<style>\n",
" .stApp { background-color: #0d1117; color: #e6edf3; }\n",
" [data-testid=\"stSidebar\"] { background-color: #161b22; border-right: 1px solid #30363d; }\n",
" .stTextInput input { background-color: #21262d !important; color: #e6edf3 !important; border: 1px solid #30363d !important; border-radius: 6px !important; }\n",
" .stButton button { background: linear-gradient(135deg, #238636, #2ea043) !important; color: white !important; border: none !important; border-radius: 6px !important; font-weight: 600 !important; width: 100%; }\n",
" .stButton button:hover { opacity: 0.85 !important; }\n",
" .review-card { background: #161b22; border: 1px solid #30363d; border-radius: 12px; padding: 1.2rem 1.5rem; margin-bottom: 1rem; }\n",
" .high-card { border-left: 4px solid #f85149; }\n",
" .medium-card { border-left: 4px solid #d29922; }\n",
" .low-card { border-left: 4px solid #3fb950; }\n",
" .badge { display: inline-block; padding: 2px 10px; border-radius: 20px; font-size: 0.75rem; font-weight: 700; margin-bottom: 6px; }\n",
" .badge-high { background: #3d1a1a; color: #f85149; border: 1px solid #f85149; }\n",
" .badge-medium { background: #2d2008; color: #d29922; border: 1px solid #d29922; }\n",
" .badge-low { background: #0d2818; color: #3fb950; border: 1px solid #3fb950; }\n",
" .diff-add { background: #0d2818; color: #3fb950; padding: 2px 8px; font-family: monospace; font-size: 0.85rem; }\n",
" .diff-remove { background: #3d1a1a; color: #f85149; padding: 2px 8px; font-family: monospace; font-size: 0.85rem; }\n",
" .diff-ctx { background: #161b22; color: #8b949e; padding: 2px 8px; font-family: monospace; font-size: 0.85rem; }\n",
" .main-title { font-size: 2rem; font-weight: 800; background: linear-gradient(90deg, #58a6ff, #3fb950); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }\n",
" .subtitle { color: #8b949e; font-size: 0.95rem; }\n",
" .metric-box { background: #161b22; border: 1px solid #30363d; border-radius: 10px; padding: 1rem; text-align: center; }\n",
" .metric-value { font-size: 2rem; font-weight: 800; }\n",
" .metric-label { color: #8b949e; font-size: 0.8rem; }\n",
" .saved-badge { color: #3fb950; font-size: 0.8rem; font-weight: 600; }\n",
"</style>\n",
"\"\"\", unsafe_allow_html=True)\n",
"\n",
"# βββ Session state init ββββββββββββββββββββββββββββββββββββββββββ\n",
"for key in [\"saved_provider\", \"saved_model\", \"saved_api_key\", \"saved_github_token\"]:\n",
" if key not in st.session_state:\n",
" st.session_state[key] = \"\"\n",
"\n",
"# βββ LLM factory βββββββββββββββββββββββββββββββββββββββββββββββββ\n",
"def get_llm(provider, api_key, model_name):\n",
" if provider == \"Groq\":\n",
" from langchain_groq import ChatGroq\n",
" return ChatGroq(model=model_name, api_key=api_key, temperature=0)\n",
" elif provider == \"Google Gemini\":\n",
" from langchain_google_genai import ChatGoogleGenerativeAI\n",
" return ChatGoogleGenerativeAI(model=model_name, google_api_key=api_key, temperature=0)\n",
" elif provider == \"OpenAI\":\n",
" from langchain_openai import ChatOpenAI\n",
" return ChatOpenAI(model=model_name, api_key=api_key, temperature=0)\n",
" else:\n",
" raise ValueError(f\"Unknown provider: {provider}\")\n",
"\n",
"# βββ Diff helpers βββββββββββββββββββββββββββββββββββββββββββββββββ\n",
"def render_diff_html(patch_text):\n",
" if not patch_text:\n",
" return \"<p style='color:#8b949e'>No diff available</p>\"\n",
" html = \"\"\n",
" for line in patch_text.split(\"\\n\")[:60]:\n",
" if line.startswith(\"+\") and not line.startswith(\"+++\"):\n",
" html += f'<div class=\"diff-add\">+ {line[1:]}</div>'\n",
" elif line.startswith(\"-\") and not line.startswith(\"---\"):\n",
" html += f'<div class=\"diff-remove\">- {line[1:]}</div>'\n",
" else:\n",
" html += f'<div class=\"diff-ctx\"> {line}</div>'\n",
" return html\n",
"\n",
"def build_diff_graph(files_data):\n",
" fig = go.Figure()\n",
" fig.add_trace(go.Bar(name=\"Additions\", x=[f[\"name\"] for f in files_data], y=[f[\"additions\"] for f in files_data], marker_color=\"#3fb950\", hovertemplate=\"<b>%{x}</b><br>+%{y} lines<extra></extra>\"))\n",
" fig.add_trace(go.Bar(name=\"Deletions\", x=[f[\"name\"] for f in files_data], y=[-f[\"deletions\"] for f in files_data], marker_color=\"#f85149\", hovertemplate=\"<b>%{x}</b><br>-%{y} lines<extra></extra>\"))\n",
" fig.update_layout(barmode=\"relative\", paper_bgcolor=\"#0d1117\", plot_bgcolor=\"#161b22\", font=dict(color=\"#e6edf3\"), xaxis=dict(gridcolor=\"#30363d\", tickangle=-30), yaxis=dict(gridcolor=\"#30363d\", title=\"Lines Changed\"), legend=dict(bgcolor=\"#161b22\"), height=350, margin=dict(t=50,b=80,l=40,r=20), title=dict(text=\"π Changes Per File\", font=dict(color=\"#58a6ff\", size=16)))\n",
" return fig\n",
"\n",
"def build_severity_chart(high, medium, low):\n",
" fig = go.Figure(go.Pie(labels=[\"High\",\"Medium\",\"Low\"], values=[max(high,0),max(medium,0),max(low,0)], hole=0.6, marker=dict(colors=[\"#f85149\",\"#d29922\",\"#3fb950\"], line=dict(color=\"#0d1117\", width=2)), hovertemplate=\"<b>%{label}</b>: %{value} issues<extra></extra>\"))\n",
" fig.update_layout(paper_bgcolor=\"#0d1117\", font=dict(color=\"#e6edf3\"), legend=dict(bgcolor=\"#161b22\"), height=300, margin=dict(t=50,b=20,l=20,r=20), title=dict(text=\"π΄ Issue Severity\", font=dict(color=\"#58a6ff\", size=16)))\n",
" return fig\n",
"\n",
"# βββ Sidebar ββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n",
"with st.sidebar:\n",
" st.markdown(\"## βοΈ Configuration\")\n",
"\n",
" provider = st.selectbox(\n",
" \"π€ LLM Provider\",\n",
" [\"Groq\", \"Google Gemini\", \"OpenAI\"],\n",
" index=[\"Groq\",\"Google Gemini\",\"OpenAI\"].index(st.session_state.saved_provider) if st.session_state.saved_provider in [\"Groq\",\"Google Gemini\",\"OpenAI\"] else 0\n",
" )\n",
"\n",
" model_name = st.text_input(\n",
" \"π¦ Model Name (type any model)\",\n",
" value=st.session_state.saved_model,\n",
" placeholder=\"e.g. llama-3.3-70b-versatile\"\n",
" )\n",
"\n",
" api_key = st.text_input(\n",
" f\"π {provider} API Key\",\n",
" value=st.session_state.saved_api_key,\n",
" type=\"password\",\n",
" placeholder=\"Paste your API key...\"\n",
" )\n",
"\n",
" github_token = st.text_input(\n",
" \"π GitHub Token\",\n",
" value=st.session_state.saved_github_token,\n",
" type=\"password\",\n",
" placeholder=\"ghp_...\"\n",
" )\n",
"\n",
" if st.button(\"πΎ Save Configuration\"):\n",
" st.session_state.saved_provider = provider\n",
" st.session_state.saved_model = model_name\n",
" st.session_state.saved_api_key = api_key\n",
" st.session_state.saved_github_token = github_token\n",
" st.success(\"β
Saved for this session!\")\n",
"\n",
" if st.session_state.saved_api_key:\n",
" st.markdown('<p class=\"saved-badge\">β API key active from session</p>', unsafe_allow_html=True)\n",
" if st.session_state.saved_github_token:\n",
" st.markdown('<p class=\"saved-badge\">β GitHub token active from session</p>', unsafe_allow_html=True)\n",
"\n",
" st.markdown(\"---\")\n",
" st.markdown(\"**π Agent Flow**\")\n",
" st.markdown(\"1. Fetch PR metadata\\n2. Fetch code diff\\n3. Analyze changes\\n4. Generate review\")\n",
" st.caption(\"Built with LangChain + Streamlit\")\n",
"\n",
"# βββ Main UI ββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n",
"st.markdown('<p class=\"main-title\">π¬ AI Code Review Agent</p>', unsafe_allow_html=True)\n",
"st.markdown('<p class=\"subtitle\">Autonomous PR analysis β paste any GitHub PR URL below</p>', unsafe_allow_html=True)\n",
"st.markdown(\"---\")\n",
"\n",
"pr_url = st.text_input(\"GitHub PR URL\", placeholder=\"https://github.com/owner/repo/pull/123\", label_visibility=\"collapsed\")\n",
"\n",
"col_btn, col_info = st.columns([1, 3])\n",
"with col_btn:\n",
" analyze_btn = st.button(\"π Analyze PR\")\n",
"with col_info:\n",
" st.caption(\"The agent autonomously decides which tools to call and in what order.\")\n",
"\n",
"# Use saved values as fallback\n",
"active_api_key = api_key or st.session_state.saved_api_key\n",
"active_github_token = github_token or st.session_state.saved_github_token\n",
"active_model = model_name or st.session_state.saved_model\n",
"active_provider = provider\n",
"\n",
"# βββ Agent execution ββββββββββββββββββββββββββββββββββββββββββββββ\n",
"if analyze_btn:\n",
" if not active_api_key or not active_github_token:\n",
" st.error(\"β οΈ Enter API keys in the sidebar and click πΎ Save Configuration.\")\n",
" elif not active_model:\n",
" st.error(\"β οΈ Enter a model name in the sidebar.\")\n",
" elif not pr_url:\n",
" st.error(\"β οΈ Enter a PR URL.\")\n",
" else:\n",
" @st.cache_resource\n",
" def load_github_client(token):\n",
" return Github(token)\n",
"\n",
" github_client = load_github_client(active_github_token)\n",
" files_data = []\n",
"\n",
" @tool\n",
" def get_pr_metadata(pr_url: str) -> str:\n",
" \"\"\"Get the title, description and author of a GitHub PR\"\"\"\n",
" try:\n",
" parts = pr_url.strip(\"/\").split(\"/\")\n",
" owner, repo_name, pr_number = parts[-4], parts[-3], int(parts[-1])\n",
" repo = github_client.get_repo(f\"{owner}/{repo_name}\")\n",
" pr = repo.get_pull(pr_number)\n",
" return f\"Title: {pr.title}\\nAuthor: {pr.user.login}\\nDescription: {pr.body}\\nBase: {pr.base.ref} -> Head: {pr.head.ref}\"\n",
" except Exception as e:\n",
" return f\"Error: {str(e)}\"\n",
"\n",
" @tool\n",
" def get_pr_diff(pr_url: str) -> str:\n",
" \"\"\"Get the code changes (diff) from a GitHub PR\"\"\"\n",
" try:\n",
" parts = pr_url.strip(\"/\").split(\"/\")\n",
" owner, repo_name, pr_number = parts[-4], parts[-3], int(parts[-1])\n",
" repo = github_client.get_repo(f\"{owner}/{repo_name}\")\n",
" pr = repo.get_pull(pr_number)\n",
" diff_text = \"\"\n",
" for file in pr.get_files():\n",
" files_data.append({\n",
" \"name\": file.filename.split(\"/\")[-1],\n",
" \"additions\": file.additions,\n",
" \"deletions\": file.deletions,\n",
" \"patch\": file.patch or \"\"\n",
" })\n",
" diff_text += f\"\\nFile: {file.filename}\\n+{file.additions} -{file.deletions}\\n\"\n",
" if file.patch:\n",
" diff_text += file.patch + \"\\n\"\n",
" return diff_text[:4000]\n",
" except Exception as e:\n",
" return f\"Error: {str(e)}\"\n",
"\n",
" @tool\n",
" def get_file_content(repo_full_name: str, file_path: str) -> str:\n",
" \"\"\"Get the full content of a file from a GitHub repository\"\"\"\n",
" try:\n",
" repo = github_client.get_repo(repo_full_name)\n",
" content = repo.get_contents(file_path)\n",
" return content.decoded_content.decode(\"utf-8\")[:2000]\n",
" except Exception as e:\n",
" return f\"Error: {str(e)}\"\n",
"\n",
" tools = [get_pr_metadata, get_pr_diff, get_file_content]\n",
"\n",
" try:\n",
" llm = get_llm(active_provider, active_api_key, active_model)\n",
" except Exception as e:\n",
" st.error(f\"Failed to initialize LLM: {e}\")\n",
" st.stop()\n",
"\n",
" prompt = ChatPromptTemplate.from_messages([\n",
" (\"system\", \"\"\"You are an expert code reviewer. When given a GitHub PR URL:\n",
"1. Fetch PR metadata to understand its purpose\n",
"2. Fetch the PR diff to see what changed\n",
"3. Analyze for: bugs, security issues, code quality, naming problems\n",
"4. Return structured review with this exact format for each issue:\n",
"\n",
"ISSUE: [short title]\n",
"FILE: [filename]\n",
"SEVERITY: [High/Medium/Low]\n",
"PROBLEM: [what is wrong]\n",
"FIX: [how to fix it]\n",
"---\n",
"\n",
"IMPORTANT: You MUST put --- on its own line between every single issue. No exceptions.\n",
"\n",
"End with a SUMMARY section.\"\"\"),\n",
" (\"human\", \"{input}\"),\n",
" MessagesPlaceholder(variable_name=\"agent_scratchpad\")\n",
" ])\n",
"\n",
" agent = create_tool_calling_agent(llm, tools, prompt)\n",
" agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=False, max_iterations=10)\n",
"\n",
" status_box = st.empty()\n",
" with status_box.container():\n",
" st.info(\"π€ Agent is analyzing the PR... this may take 15β30 seconds.\")\n",
"\n",
" try:\n",
" result = agent_executor.invoke({\"input\": f\"Review this PR: {pr_url}\"})\n",
" status_box.empty()\n",
" output = result[\"output\"]\n",
"\n",
" import gc\n",
" gc.collect()\n",
"\n",
" high = output.upper().count(\"SEVERITY: HIGH\")\n",
" medium = output.upper().count(\"SEVERITY: MEDIUM\")\n",
" low = output.upper().count(\"SEVERITY: LOW\")\n",
" total = high + medium + low\n",
"\n",
" st.markdown(\"### π Review Summary\")\n",
" m1, m2, m3, m4 = st.columns(4)\n",
" with m1: st.markdown(f'<div class=\"metric-box\"><div class=\"metric-value\" style=\"color:#58a6ff\">{total}</div><div class=\"metric-label\">Total Issues</div></div>', unsafe_allow_html=True)\n",
" with m2: st.markdown(f'<div class=\"metric-box\"><div class=\"metric-value\" style=\"color:#f85149\">{high}</div><div class=\"metric-label\">High Severity</div></div>', unsafe_allow_html=True)\n",
" with m3: st.markdown(f'<div class=\"metric-box\"><div class=\"metric-value\" style=\"color:#d29922\">{medium}</div><div class=\"metric-label\">Medium Severity</div></div>', unsafe_allow_html=True)\n",
" with m4: st.markdown(f'<div class=\"metric-box\"><div class=\"metric-value\" style=\"color:#3fb950\">{low}</div><div class=\"metric-label\">Low Severity</div></div>', unsafe_allow_html=True)\n",
"\n",
" st.markdown(\"<br>\", unsafe_allow_html=True)\n",
"\n",
" c1, c2 = st.columns([3, 2])\n",
" with c1:\n",
" if files_data:\n",
" st.plotly_chart(build_diff_graph(files_data), use_container_width=True)\n",
" with c2:\n",
" if total > 0:\n",
" st.plotly_chart(build_severity_chart(high, medium, low), use_container_width=True)\n",
"\n",
" if files_data:\n",
" st.markdown(\"### ποΈ File Changes\")\n",
" for f in files_data:\n",
" with st.expander(f\"π {f['name']} (+{f['additions']} / -{f['deletions']})\"):\n",
" st.markdown(render_diff_html(f[\"patch\"]), unsafe_allow_html=True)\n",
"\n",
" st.markdown(\"### π Detailed Review\")\n",
" blocks = re.split(r'---|\\n(?=ISSUE:)', output)\n",
" cards_rendered = 0\n",
" for block in blocks:\n",
" block = block.strip()\n",
" if not block or \"SUMMARY\" in block.upper():\n",
" continue\n",
" if \"ISSUE:\" in block.upper():\n",
" sev = \"high\" if \"SEVERITY: HIGH\" in block.upper() else \"medium\" if \"SEVERITY: MEDIUM\" in block.upper() else \"low\"\n",
" st.markdown(\n",
" f'<div class=\"review-card {sev}-card\">'\n",
" f'<span class=\"badge badge-{sev}\">{sev.upper()}</span>'\n",
" f'<pre style=\"white-space:pre-wrap;color:#e6edf3;background:transparent;border:none;padding:0;margin:0\">{block}</pre>'\n",
" f'</div>',\n",
" unsafe_allow_html=True\n",
" )\n",
" cards_rendered += 1\n",
"\n",
" if cards_rendered == 0:\n",
" st.markdown(\n",
" f'<div class=\"review-card low-card\">'\n",
" f'<pre style=\"white-space:pre-wrap;color:#e6edf3;background:transparent;border:none;padding:0;margin:0\">{output}</pre>'\n",
" f'</div>',\n",
" unsafe_allow_html=True\n",
" )\n",
"\n",
" if \"SUMMARY\" in output.upper():\n",
" idx = output.upper().find(\"SUMMARY\")\n",
" st.markdown(\"### π Summary\")\n",
" st.markdown(\n",
" f'<div class=\"review-card\" style=\"border-left:4px solid #58a6ff\">{output[idx:]}</div>',\n",
" unsafe_allow_html=True\n",
" )\n",
"\n",
" except Exception as e:\n",
" status_box.empty()\n",
" st.error(f\"Agent error: {str(e)}\")"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {
"id": "FvvWcmiVGiJ2"
},
"outputs": [],
"source": [
"!pip install pyngrok -q"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "M5osBY-dGmKm",
"outputId": "85309c7f-485b-4a37-a407-3f491730b466"
},
"outputs": [],
"source": [
"from pyngrok import ngrok\n",
"import subprocess\n",
"import time\n",
"\n",
"# Start streamlit\n",
"subprocess.Popen([\"streamlit\", \"run\", \"app.py\", \"--server.port\", \"8501\"])\n",
"time.sleep(3)\n",
"\n",
"# Create public URL\n",
"ngrok.set_auth_token(userdata.get('NGROK_AUTH_TOKEN'))\n",
"public_url = ngrok.connect(8501)\n",
"print(\"App URL:\", public_url)"
]
}
],
"metadata": {
"accelerator": "GPU",
"colab": {
"gpuType": "T4",
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
|