This tutorial demonstrates how to build an intelligent GitHub PR review bot that automatically reviews pull requests when triggered by labels. The bot uses Codegen’s GitHub integration and AI capabilities to provide comprehensive code reviews with actionable feedback.
First, we set up a Modal application to handle GitHub webhooks:
Copy
Ask AI
import modalfrom codegen.extensions.events.app import CodegenAppfrom fastapi import Request# Set up the base image with required dependenciesbase_image = ( modal.Image.debian_slim(python_version="3.12") .apt_install("git") .pip_install( "codegen>=0.18", "openai>=1.1.0", "fastapi[standard]", "slack_sdk", ))# Initialize the Codegen app with GitHub integrationapp = CodegenApp(name="github", image=base_image)@app.function(secrets=[modal.Secret.from_dotenv()])@modal.web_endpoint(method="POST")def entrypoint(event: dict, request: Request): return app.github.handle(event, request)
The Modal app provides a webhook endpoint that GitHub can call when PR events occur.
Make sure to configure your GitHub repository’s webhook settings to point to your Modal endpoint.
Finally, we implement the AI-powered review agent:
Copy
Ask AI
from codegen import Codebase, CodeAgentfrom codegen.extensions.langchain.tools import ( GithubViewPRTool, GithubCreatePRCommentTool, GithubCreatePRReviewCommentTool,)def pr_review_agent(event: PullRequestLabeledEvent) -> None: """Run the PR review agent.""" # Initialize codebase for the repository repo_str = f"{event.organization.login}/{event.repository.name}" codebase = Codebase.from_repo( repo_str, language='python', secrets=SecretsConfig(github_token=os.environ["GITHUB_TOKEN"]) ) # Create a temporary comment to show the bot is working review_message = "CodegenBot is starting to review the PR please wait..." comment = codebase._op.create_pr_comment(event.number, review_message) # Set up PR review tools pr_tools = [ GithubViewPRTool(codebase), GithubCreatePRCommentTool(codebase), GithubCreatePRReviewCommentTool(codebase), ] # Create and run the review agent agent = CodeAgent(codebase=codebase, tools=pr_tools) prompt = f"""Review this pull request like a senior engineer:{event.pull_request.url}Be explicit about the changes, produce a short summary, and point out possible improvements.Focus on facts and technical details, using code snippets where helpful.""" result = agent.run(prompt) # Clean up the temporary comment comment.delete()