### Run PR-Agent CLI commands from source Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/installation/locally.md Execute various PR-Agent commands directly from the command line after setting up the source installation. Examples include reviewing, asking questions, describing, and improving PRs. ```bash python3 -m pr_agent.cli --pr_url review python3 -m pr_agent.cli --pr_url ask python3 -m pr_agent.cli --pr_url describe python3 -m pr_agent.cli --pr_url improve python3 -m pr_agent.cli --pr_url add_docs python3 -m pr_agent.cli --pr_url generate_labels python3 -m pr_agent.cli --issue_url similar_issue ... ``` -------------------------------- ### Example Local Configuration for Review Instructions Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/usage-guide/configuration_options.md This example shows how to configure extra instructions for the review tool using a local .pr_agent.toml file. The instructions are provided as a multi-line string. ```toml ``` [pr_reviewer] extra_instructions=""" - instruction a - instruction b ... """ ``` ``` -------------------------------- ### Install PR-Agent using pip Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/installation/locally.md Install the PR-Agent package using pip. This is the simplest way to get started. ```bash pip install pr-agent ``` -------------------------------- ### Serve Documentation Locally Source: https://github.com/the-pr-agent/pr-agent/blob/main/AGENTS.md Generate and serve documentation locally for preview using MkDocs. Ensure MkDocs and necessary extras are installed. ```bash mkdocs serve -f docs/mkdocs.yml ``` -------------------------------- ### Example Wiki Configuration Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/usage-guide/configuration_options.md This is an example of how to structure a TOML configuration for the PR description tool when using a wiki page. PR-Agent automatically removes surrounding triple quotes. ```toml ```toml [pr_description] generate_ai_title=true ``` ``` -------------------------------- ### Configure Custom Labels in a File Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/tools/describe.md Example configuration for enabling and defining custom labels in a configuration file. Ensure 'enable_custom_labels' is set to true. ```ini [config] enable_custom_labels=true [custom_labels."sql_changes"] description = "Use when a PR contains changes to SQL queries" [custom_labels."test"] description = "use when a PR primarily contains new tests" ... ``` -------------------------------- ### Install PR-Agent from source Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/installation/locally.md Install the PR-Agent package in editable mode after cloning the repository. This command requires navigating to the '/pr-agent' directory and may require Rust to be installed. ```bash pip install -e . ``` -------------------------------- ### Example of AI-generated file summary in diff format Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/core-abilities/metadata.md This example shows how PR-Agent can inject AI-generated file summaries into the prompt for code suggestions. It includes a summary of changes for a specific file and a diff patch. ```diff ## File: 'src/file1.py' ### AI-generated file summary: - edited function `func1` that does X - Removed function `func2` that was not used - .... @@ ... @@ def func1(): __new hunk__ 11 unchanged code line0 12 unchanged code line1 13 +new code line2 added 14 unchanged code line3 __old hunk__ unchanged code line0 unchanged code line1 -old code line2 removed unchanged code line3 @@ ... @@ def func2(): __new hunk__ ... __old hunk__ ... ``` -------------------------------- ### Run PR-Agent using Python script (pip install) Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/installation/locally.md Execute PR-Agent commands by running a Python script after installing via pip. Ensure all required parameters like user token, OpenAI key, and PR URL are provided. ```python from pr_agent import cli from pr_agent.config_loader import get_settings def main(): # Fill in the following values provider = "github" # github/gitlab/bitbucket/azure_devops user_token = "..." # user token openai_key = "..." # OpenAI key pr_url = "..." # PR URL, for example 'https://github.com/the-pr-agent/pr-agent/pull/809' command = "/review" # Command to run (e.g. '/review', '/describe', '/ask="What is the purpose of this PR?"', ...) # Setting the configurations get_settings().set("CONFIG.git_provider", provider) get_settings().set("openai.key", openai_key) get_settings().set("github.user_token", user_token) # Run the command. Feedback will appear in GitHub PR comments cli.run_command(pr_url, command) if __name__ == '__main__': main() ``` -------------------------------- ### PR Description Markers Template Example Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/tools/describe.md This example shows how to use markers in a PR description to integrate user content with auto-generated sections like PR type, summary, walkthrough, and diagram. Ensure `pr_description.use_description_markers` is set to true to enable this functionality. ```yaml User content... ## PR Type: pr_agent:type ## PR Description: pr_agent:summary ## PR Walkthrough: pr_agent:walkthrough ## PR Diagram: pr_agent:diagram ``` -------------------------------- ### Define Custom Labels on GitHub/GitLab Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/tools/describe.md Examples of custom labels and their descriptions as they should be formatted on the repository's labels page. Descriptions must start with 'pr_agent:'. ```text - Main topic:performance - pr_agent:The main topic of this PR is performance - New endpoint - pr_agent:A new endpoint was added in this PR - SQL query - pr_agent:A new SQL query was added in this PR - Dockerfile changes - pr_agent:The PR contains changes in the Dockerfile - ... ``` -------------------------------- ### Command Line Option for Documentation Style Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/tools/add_docs.md Pass configuration options directly via the command line when invoking the add_docs tool. This example sets the documentation style to 'Numpy Style'. ```bash /add_docs --pr_add_docs.docs_style="Numpy Style" ``` -------------------------------- ### Add Extra Instructions to a Tool Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/usage-guide/additional_configurations.md The `extra_instructions` parameter allows you to add free-text instructions to any PR-Agent tool. Example shown for the `/update_changelog` tool. ```bash /update_changelog --pr_update_changelog.extra_instructions="Make sure to update also the version ..." ``` -------------------------------- ### Set PYTHONPATH and Run CLI Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/installation/github.md Example command to set the PYTHONPATH environment variable to include the pr-agent project directory and then run the CLI. ```sh PYTHONPATH="/PATH/TO/PROJECTS/pr-agent python pr_agent/cli.py [--ARGS]" ``` -------------------------------- ### Kubernetes Volume Mount for Secrets Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/installation/github.md Example Kubernetes pod specification demonstrating how to mount a secret containing the .secrets.toml file as a volume. ```yaml volumes: - name: settings-volume secret: secretName: pr-agent-settings // ... containers: // ... volumeMounts: - mountPath: /app/pr_agent/settings_prod name: settings-volume ``` -------------------------------- ### Basic GitHub Action Workflow (OpenAI Default) Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/installation/github.md A minimal workflow for PR-Agent using default OpenAI models. It's a simplified version of the main setup, suitable for quick integration. ```yaml name: PR Agent on: pull_request: types: [opened, reopened, ready_for_review] issue_comment: jobs: pr_agent_job: if: ${{ github.event.sender.type != 'Bot' }} runs-on: ubuntu-latest permissions: issues: write pull-requests: write contents: write steps: - name: PR Agent action step uses: the-pr-agent/pr-agent@main env: OPENAI_KEY: ${{ secrets.OPENAI_KEY }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} ``` -------------------------------- ### Override Configuration via Comment Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/usage-guide/automations_and_usage.md This example shows how to override configuration values, such as 'pr_reviewer.extra_instructions' and 'pr_reviewer.require_score_review', directly in a comment command. ```markdown /review --pr_reviewer.extra_instructions="..." --pr_reviewer.require_score_review=false ``` -------------------------------- ### Example Usage of Environment Variables for Secrets Source: https://github.com/the-pr-agent/pr-agent/blob/main/AGENTS.md Demonstrates how secrets are supplied through environment variables, as shown in test files. Do not persist secrets in code or configuration files. ```python TOKEN_GITHUB TOKEN_GITLAB BITBUCKET_USERNAME BITBUCKET_PASSWORD ``` -------------------------------- ### Configure add_docs Documentation Style Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/tools/add_docs.md Customize the documentation style for Python code by setting the 'docs_style' option in the '[pr_add_docs]' section of your configuration file. This example sets the style to 'Google Style with Args, Returns, Attributes...etc'. ```toml [pr_add_docs] docs_style = "Google Style with Args, Returns, Attributes...etc" extra_instructions = "Focus on documenting public methods and include usage examples" ``` -------------------------------- ### Override Configuration via CLI Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/usage-guide/automations_and_usage.md This example shows how to override a specific configuration value, such as 'pr_reviewer.extra_instructions', directly on the command line when invoking the review tool. ```bash python -m pr_agent.cli --pr_url= /review --pr_reviewer.extra_instructions="focus on the file: ..." ``` -------------------------------- ### Customize Improve Tool with Extra Instructions Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/tools/improve.md Provide custom, multi-line instructions to the AI model for the 'improve' tool. Use this to guide the AI's suggestion generation process, specifying desired output formats or constraints. ```toml [pr_code_suggestions] extra_instructions=""" (1) Answer in Japanese (2) Don't suggest to add try-except block (3) Ignore changes in toml files ...""" ``` -------------------------------- ### Configure PR Agent with Custom Review Instructions Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/installation/github.md Add custom instructions to guide the PR Agent's review process, focusing on specific areas like security vulnerabilities and performance issues. This snippet also shows how to enable automatic review, description, and improvement. ```yaml env: OPENAI_KEY: ${{ secrets.OPENAI_KEY }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Custom review instructions pr_reviewer.extra_instructions: "Focus on security vulnerabilities and performance issues. Check for proper error handling." # Tool configuration github_action_config.auto_review: "true" github_action_config.auto_describe: "true" github_action_config.auto_improve: "true" ``` -------------------------------- ### Describe Tool Default Mode Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/tools/describe.md Shows the default command for the describe tool when PR-Agent is first installed, indicating automatic execution on every PR. ```yaml pr_commands = ["/describe", ...] ``` -------------------------------- ### Local CLI Usage for PR Reviews Source: https://github.com/the-pr-agent/pr-agent/blob/main/README.md Run PR-Agent locally using the command-line interface for development or direct review. Install the package and set your OpenAI API key as an environment variable. ```bash pip install pr-agent export OPENAI_KEY=your_key_here pr-agent --pr_url https://github.com/owner/repo/pull/123 review ``` -------------------------------- ### Customize Automated PR Commands with Parameters Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/usage-guide/automations_and_usage.md Modify the 'pr_commands' to include specific parameters for tools during automated runs. This example customizes the 'review' tool to focus on a specific file. ```toml [github_app] pr_commands = [ "/describe", "/review --pr_reviewer.extra_instructions='focus on the file: ...'", "/improve", ] ``` -------------------------------- ### Customize PR-Agent Configuration with .pr_agent.toml (BitBucket) Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/usage-guide/automations_and_usage.md Override default PR-Agent settings by uploading a local '.pr_agent.toml' file to the root of your repository's default branch. This example sets custom instructions for the PR reviewer. ```toml [pr_reviewer] extra_instructions = "Answer in japanese" ``` -------------------------------- ### Push Docker Image to Repository Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/installation/gitea.md Pushes the built Docker image to a Docker repository, using Dockerhub as an example. Ensure you replace 'pragent/pr-agent:gitea_webhook' with your desired repository and tag. ```bash docker push pragent/pr-agent:gitea_webhook # Push to your Docker repository ``` -------------------------------- ### Simplified GitHub Actions Workflow with TOML Configuration Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/installation/github.md A simplified GitHub Actions workflow file that utilizes a `.pr_agent.toml` configuration file. This setup ensures the PR Agent runs on pull request events and responds to user comments, with environment variables for API keys and tool configurations. ```yaml on: pull_request: types: [opened, reopened, ready_for_review] issue_comment: jobs: pr_agent_job: if: ${{ github.event.sender.type != 'Bot' }} runs-on: ubuntu-latest permissions: issues: write pull-requests: write contents: write name: Run pr agent on every pull request, respond to user comments steps: - name: PR Agent action step id: pragent uses: the-pr-agent/pr-agent@main env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GOOGLE_AI_STUDIO.GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} ANTHROPIC.KEY: ${{ secrets.ANTHROPIC_KEY }} github_action_config.auto_review: "true" github_action_config.auto_describe: "true" github_action_config.auto_improve: "true" ``` -------------------------------- ### Print All Available Configurations Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/usage-guide/additional_configurations.md To display all possible configurations as a comment on your PR, use the `/config` command. ```bash /config ``` -------------------------------- ### Validate Basic Authentication for Jira Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/core-abilities/fetching_ticket_context.md Use this Python script to validate your Basic Authentication setup with Jira. Ensure you have installed the 'jira' library. Replace placeholders with your actual Jira server URL, credentials, and ticket ID. ```python from jira import JIRA if __name__ == "__main__": try: # Jira server URL server = "https://..." # Basic auth username = "..." password = "..." # Jira ticket code (e.g. "PROJ-123") ticket_id = "..." print("Initializing JiraServerTicketProvider with JIRA server") # Initialize JIRA client jira = JIRA( server=server, basic_auth=(username, password), timeout=30 ) if jira: print(f"JIRA client initialized successfully") else: print("Error initializing JIRA client") # Fetch ticket details ticket = jira.issue(ticket_id) print(f"Ticket title: {ticket.fields.summary}") except Exception as e: print(f"Error fetching JIRA ticket details: {e}") ``` -------------------------------- ### Deploy Documentation with MkDocs Source: https://github.com/the-pr-agent/pr-agent/blob/main/AGENTS.md Generate and deploy documentation to a static site using MkDocs. This command is used for publication. ```bash mkdocs gh-deploy -f docs/mkdocs.yml ``` -------------------------------- ### Validate PAT Token for Jira Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/core-abilities/fetching_ticket_context.md Use this Python script to validate your Personal Access Token (PAT) setup with Jira. Ensure you have installed the 'jira' library. Replace placeholders with your Jira server URL, PAT, and ticket ID. ```python from jira import JIRA if __name__ == "__main__": try: # Jira server URL server = "https://..." # Jira PAT token token_auth = "..." # Jira ticket code (e.g. "PROJ-123") ticket_id = "..." print("Initializing JiraServerTicketProvider with JIRA server") # Initialize JIRA client jira = JIRA( server=server, token_auth=token_auth, timeout=30 ) if jira: print(f"JIRA client initialized successfully") else: print("Error initializing JIRA client") # Fetch ticket details ticket = jira.issue(ticket_id) print(f"Ticket title: {ticket.fields.summary}") except Exception as e: print(f"Error fetching JIRA ticket details: {e}") ``` -------------------------------- ### AWS Secrets Manager Secret Example Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/installation/github.md Example JSON structure for a secret stored in AWS Secrets Manager, containing API keys and webhook secrets. ```json { "openai.key": "sk-proj-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "github.webhook_secret": "your-webhook-secret-from-step-2", "github.private_key": "-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA...\n-----END RSA PRIVATE KEY-----" } ``` -------------------------------- ### Run Full Unit Test Suite Source: https://github.com/the-pr-agent/pr-agent/blob/main/AGENTS.md Execute the entire unit test suite for the project. Ensure PYTHONPATH is set correctly for imports. ```bash PYTHONPATH=. ./.venv/bin/pytest tests/unittest -v ``` -------------------------------- ### Lexical Scoping Example in Python Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/usage-guide/EXAMPLE_BEST_PRACTICE.md Demonstrates the use of lexical scoping (closures) in Python. This example shows how an inner function `adder` can access and use variables from its enclosing scope `get_adder`. ```python def get_adder(summand1: float) -> Callable[[float], float]: """Returns a function that adds numbers to a given number.""" def adder(summand2: float) -> float: return summand1 + summand2 return adder ``` -------------------------------- ### Configure OpenAI-like API via Environment Variables Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/usage-guide/changing_a_model.md Set up connection details for an OpenAI-like API endpoint using environment variables. Note the use of double underscores. ```bash OPENAI__API_BASE=https://api.openai.com/v1 OPENAI__KEY=sk-... ``` -------------------------------- ### AWS CodeCommit IAM Role Example Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/installation/github.md Example IAM policy granting the necessary permissions for PR-Agent to interact with AWS CodeCommit repositories, including reading pull requests and posting comments. ```json { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "codecommit:BatchDescribe*", "codecommit:BatchGet*", "codecommit:Describe*", "codecommit:EvaluatePullRequestApprovalRules", "codecommit:Get*", "codecommit:List*", "codecommit:PostComment*", "codecommit:PutCommentReaction", "codecommit:UpdatePullRequestDescription", "codecommit:UpdatePullRequestTitle" ], "Resource": "*" } ] } ``` -------------------------------- ### Configuring Help Docs Tool Path Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/tools/help_docs.md Customize the documentation folder path within the PR-Agent configuration file. ```toml [pr_help_docs] repo_url = "" # The repository to use as context docs_path = "docs" # The documentation folder repo_default_branch = "main" # The branch to use in case repo_url overwritten ``` -------------------------------- ### Qdrant Configuration for Similar Issues Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/tools/similar_issues.md Configure Qdrant URL and API key in .secrets.toml, then select 'qdrant' in configuration.toml to use Qdrant with the similar issue tool. ```toml [qdrant] url = "https://YOUR-QDRANT-URL" # e.g., https://xxxxxxxx-xxxxxxxx.eu-central-1-0.aws.cloud.qdrant.io api_key = "..." ``` ```toml [pr_similar_issue] vectordb = "qdrant" ``` -------------------------------- ### Build and Push Docker Image Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/installation/github.md Builds a Docker image for the GitHub App deployment and pushes it to Dockerhub. ```bash docker build . -t pragent/pr-agent:github_app --target github_app -f docker/Dockerfile docker push pragent/pr-agent:github_app # Push to your Docker repository ``` -------------------------------- ### Enable BitBucket App Push Trigger and Commands Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/usage-guide/automations_and_usage.md Configure 'handle_push_trigger' to true and 'push_commands' to specify commands that run automatically when new code is pushed to a PR. This allows PR-Agent to respond to code updates. ```toml [bitbucket_app] handle_push_trigger = true push_commands = [ "/describe", "/review", ] ``` -------------------------------- ### Configure BitBucket App for Automatic PR Commands Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/usage-guide/automations_and_usage.md Set the 'pr_commands' parameter in the '[bitbucket_app]' section of your configuration file to define commands that run automatically when a new PR is opened. Includes specific recommendations for BitBucket. ```toml [bitbucket_app] pr_commands = [ "/review", "/improve --pr_code_suggestions.commitable_code_suggestions=true --pr_code_suggestions.suggestions_score_threshold=7", ] ``` -------------------------------- ### Unified Diff Format Example Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/core-abilities/dynamic_context.md This shows the standard unified diff format used to represent code changes in pull requests, including additions and deletions. ```diff @@ -12,5 +12,5 @@ def func1(): code line that already existed in the file... code line that already existed in the file... code line that already existed in the file.... -code line that was removed in the PR +new code line added in the PR code line that already existed in the file... code line that already existed in the file... code line that already existed in the file... @@ -26,2 +26,4 @@ def func2(): ... ``` -------------------------------- ### Build Docker Image for GitLab Lambda Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/installation/gitlab.md Builds a Docker image optimized for AWS Lambda deployment, targeting the GitLab integration. Ensure you have Docker installed and configured. ```shell docker buildx build --platform=linux/amd64 . -t pragent/pr-agent:gitlab_lambda --target gitlab_lambda -f docker/Dockerfile.lambda ``` -------------------------------- ### Ignore PRs from Specific Repositories Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/usage-guide/additional_configurations.md Exclude PRs originating from specific repositories by providing a list of regex patterns. This is helpful in monorepo setups or when managing multiple projects. ```toml [config] ignore_repositories = ["my-org/my-repo1", "my-org/my-repo2"] ``` -------------------------------- ### Configure xAI Model Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/usage-guide/changing_a_model.md Use xAI's models, such as grok-2-latest. Set the model name and provide your xAI API key. ```toml [config] model = "xai/grok-2-latest" fallback_models = ["xai/grok-2-latest"] [xai] key = "..." # your xAI API key ``` -------------------------------- ### IAM Policy for Bedrock Access Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/usage-guide/changing_a_model.md Example IAM policy granting 'bedrock:InvokeModel' permission for a specific Bedrock foundation model. This is required when using IAM roles for authentication. ```json { "Effect": "Allow", "Action": "bedrock:InvokeModel", "Resource": "arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-3-5-sonnet-20240620-v1:0" } ``` -------------------------------- ### Run PR-Agent with BitBucket Docker Image Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/installation/locally.md Execute this command to run PR-Agent with BitBucket. Ensure your API keys and PR URL are correctly substituted. ```bash docker run --rm -it -e CONFIG.GIT_PROVIDER=bitbucket -e OPENAI.KEY=$OPENAI_API_KEY -e BITBUCKET.BEARER_TOKEN=$BITBUCKET_BEARER_TOKEN pragent/pr-agent:latest --pr_url= review ``` -------------------------------- ### Configure PR Agent using a TOML Configuration File Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/installation/github.md This snippet demonstrates how to use a `.pr_agent.toml` file in your repository root for configuration, which can simplify your workflow file. It shows settings for models, review instructions, and code suggestions. ```toml [config] model = "gemini/gemini-1.5-flash" fallback_models = ["anthropic/claude-3-opus-20240229"] [pr_reviewer] extra_instructions = "Focus on security issues and code quality." [pr_code_suggestions] num_code_suggestions = 6 suggestions_score_threshold = 7 ``` -------------------------------- ### Override Default Tool Parameters for Describe Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/usage-guide/automations_and_usage.md Example of overriding a default tool parameter to enable AI-generated PR titles for the 'describe' tool. This applies to both manual and automatic runs. ```toml [pr_description] generate_ai_title = true ``` -------------------------------- ### Basic PR Agent Configuration with Tool Controls Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/installation/github.md This snippet shows a basic GitHub Actions workflow configuration for the PR Agent, enabling automatic review, description, and improvement tools. ```yaml on: pull_request: types: [opened, reopened, ready_for_review] issue_comment: jobs: pr_agent_job: if: ${{ github.event.sender.type != 'Bot' }} runs-on: ubuntu-latest permissions: issues: write pull-requests: write contents: write name: Run pr agent on every pull request, respond to user comments steps: - name: PR Agent action step id: pragent uses: the-pr-agent/pr-agent@main env: OPENAI_KEY: ${{ secrets.OPENAI_KEY }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Enable/disable automatic tools github_action_config.auto_review: "true" github_action_config.auto_describe: "true" github_action_config.auto_improve: "true" # Configure which PR events trigger the action github_action_config.pr_actions: '["opened", "reopened", "ready_for_review", "review_requested"]' ``` -------------------------------- ### PR-Agent Main Configuration Secret (JSON) Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/installation/gitlab.md Example JSON structure for a main configuration secret in AWS Secrets Manager, used for common settings like OpenAI API keys. ```json { "openai.key": "sk-proj-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" } ``` -------------------------------- ### Configuration for Bitbucket Server CLI Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/installation/bitbucket.md Modify configuration.toml to set the git provider to bitbucket_server for CLI usage. ```toml git_provider="bitbucket_server" ``` -------------------------------- ### CLI Execution for Bitbucket Server Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/installation/bitbucket.md Run PR-Agent from the command line for Bitbucket Server, providing the pull request URL. ```shell python cli.py --pr_url https://git.on-prem-instance-of-bitbucket.com/projects/PROJECT/repos/REPO/pull-requests/1 review ``` -------------------------------- ### Prefer Implicit Boolean Evaluations in Python Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/usage-guide/EXAMPLE_BEST_PRACTICE.md Use the implicit boolean evaluation of objects in conditional statements when possible. For example, use `if foo:` instead of `if foo != []:` for checking if a list is not empty. ```python Use the “implicit” false if possible, e.g., `if foo:` rather than `if foo != []:` ``` -------------------------------- ### Using External Configuration URL via CLI Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/usage-guide/configuration_options.md Demonstrates how to specify an external configuration file using the --extra_config_url argument when running PR-Agent from the CLI. This allows for shared configurations that can be layered before local or global settings. ```bash python -m pr_agent.cli \ --pr_url= \ --extra_config_url=https://config.example.com/pr-agent/shared.toml \ review ``` -------------------------------- ### Cloud Dry-Run Probe - With Repository Baseline Source: https://github.com/the-pr-agent/pr-agent/blob/main/docker/mosaico/README.md Runs the PR-Agent MOSAICO probe, including an optional registry baseline check. This is best-effort and may not reach internal repositories. ```bash # optional registry baseline (best-effort; repo may be internal-only) MOSAICO_REPOSITORY_URL=http://116.203.57.210:8080 PYTHONPATH=. python -m pr_agent.mosaico.probe ``` -------------------------------- ### Configure Model and Fallback Models Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/usage-guide/changing_a_model.md Specify the primary model and fallback models in the configuration file. ```toml [config] model = "..." fallback_models = ["..."] ``` -------------------------------- ### Preserve Ordering When Merging Collections Source: https://github.com/the-pr-agent/pr-agent/wiki/.pr_agent_auto_best_practices Avoid non-deterministic behavior by preserving order when merging collections. This example shows how to merge two lists while prioritizing elements from the first list and avoiding duplicates. ```python items = primary + [x for x in secondary if x not in primary] items = items[:3] ``` -------------------------------- ### Output Relevant Configurations for a Specific Tool Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/usage-guide/additional_configurations.md To view the actual configurations used for a specific tool after all user settings are applied, append `--config.output_relevant_configurations=true` to the tool's command. ```bash /improve --config.output_relevant_configurations=true ``` -------------------------------- ### Configure PR Agent to Use Local Models with Ollama Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/installation/github.md Use local models with the PR Agent by setting `config.model` to an Ollama model and configuring `OLLAMA.API_BASE`. This requires a self-hosted runner with Ollama installed. ```yaml env: OPENAI_KEY: ${{ secrets.OPENAI_KEY }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Set the model to a local Ollama model config.model: "ollama/qwen2.5-coder:32b" config.fallback_models: '["ollama/qwen2.5-coder:32b"]' config.custom_model_max_tokens: "128000" # Ollama configuration OLLAMA.API_BASE: "http://localhost:11434" # Tool configuration github_action_config.auto_review: "true" github_action_config.auto_describe: "true" github_action_config.auto_improve: "true" ``` -------------------------------- ### Configure GitHub App Automatic PR Commands Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/usage-guide/automations_and_usage.md Define the list of tools to run automatically when a new PR is opened or reopened. These commands are executed sequentially. ```toml [github_app] pr_commands = [ "/describe", "/review", "/improve", ] ``` -------------------------------- ### Set AWS CodeCommit Access Key and Secret Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/installation/github.md Example of setting AWS access key ID, secret access key, and default region as environment variables for CLI authentication with AWS CodeCommit. ```sh export AWS_ACCESS_KEY_ID="XXXXXXXXXXXXXXXX" export AWS_SECRET_ACCESS_KEY="XXXXXXXXXXXXXXXX" export AWS_DEFAULT_REGION="us-east-1" ``` -------------------------------- ### Enable OpenAI Flex Processing Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/usage-guide/changing_a_model.md Configure PR-Agent to use OpenAI's Flex Processing for cost reduction on non-urgent tasks. This setting is applied via the main configuration file. ```toml [litellm] extra_body='{"processing_mode": "flex"}' ``` -------------------------------- ### Serialize Environment Variable Access with Lock Source: https://github.com/the-pr-agent/pr-agent/wiki/.pr_agent_auto_best_practices Avoids relying on process-global mutable state like os.environ in async paths. This example uses an asyncio.Lock to serialize access to environment variables, preventing cross-request races. ```python _lock = asyncio.Lock() async def call_provider(): async with _lock: os.environ["AWS_ACCESS_KEY_ID"] = creds.access_key return await client.request() ``` -------------------------------- ### Run Pre-commit Hooks Source: https://github.com/the-pr-agent/pr-agent/blob/main/AGENTS.md Enforce code style and quality checks using pre-commit hooks. Run this command before submitting patches. ```bash pre-commit run --all-files ``` -------------------------------- ### Configure OpenAI-like API via TOML Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/usage-guide/changing_a_model.md Set up connection details for an OpenAI-like API endpoint using a TOML secrets file. ```toml [openai] api_base = "https://api.openai.com/v1" api_key = "sk-..." ``` -------------------------------- ### GitLab Webhook Secret Configuration (JSON) Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/installation/gitlab.md Example JSON structure for creating individual secrets in AWS Secrets Manager for GitLab webhooks. This includes the GitLab personal access token and a unique token name. ```json { "gitlab_token": "glpat-xxxxxxxxxxxxxxxxxxxxxxxx", "token_name": "project-webhook-001" } ``` -------------------------------- ### Specify Strict Host URL Format for GitLab Source: https://github.com/the-pr-agent/pr-agent/wiki/.pr_agent_auto_best_practices Explicitly states the required URL format for the Host Address to prevent failures. It guides users to include the scheme and avoid trailing slashes for self-hosted GitLab instances. ```diff - - **Host Address**: Leave empty if using gitlab.com ([for self-hosted GitLab servers](#gitlab-server), enter your GitLab instance URL) + - **Host Address**: Leave empty if using gitlab.com ([for self-hosted GitLab servers](#gitlab-server), enter your GitLab base URL including scheme (e.g., https://gitlab.mycorp-inc.com) without trailing slash. Do not include paths or query strings. ``` ```diff - - **Host Address**: Leave empty if using gitlab.com ([for self-hosted GitLab servers](#gitlab-server), enter your GitLab instance URL) + - **Host Address**: Leave empty for gitlab.com. For self-hosted, enter the full base URL including scheme, no trailing slash (e.g., `https://gitlab.mycorp.com`). ``` -------------------------------- ### Validate and Normalize Boundary Inputs Source: https://github.com/the-pr-agent/pr-agent/wiki/.pr_agent_auto_best_practices Ensure boundary inputs like ports and status strings are validated and normalized to prevent errors. This example shows handling potential `ValueError` for port conversion and enforcing valid status strings. ```python try: port = int(os.environ.get("PORT", "3000")) except ValueError: logger.warning("Invalid PORT; using 3000") port = 3000 status = (getattr(settings.azure_devops, "default_comment_status", "") or "closed").strip().lower() status = status if status in {"active", "closed"} else "closed" ``` -------------------------------- ### Review Pull Request with AWS CodeCommit CLI Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/installation/github.md Example CLI command to instruct PR Agent to review a specific pull request on AWS CodeCommit. Ensure to replace placeholder paths and URLs with your actual project details. ```bash PYTHONPATH="/PATH/TO/PROJECTS/pr-agent" python pr_agent/cli.py \ --pr_url https://us-east-1.console.aws.amazon.com/codesuite/codecommit/repositories/MY_REPO_NAME/pull-requests/321 \ review ``` -------------------------------- ### Configure PR-Agent using Environment Variables in a .env file Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/installation/locally.md Define environment variables in a .env file for PR-Agent configuration, such as Git provider, URLs, and API keys. ```bash CONFIG__GIT_PROVIDER="gitlab" GITLAB__URL="" GITLAB__PERSONAL_ACCESS_TOKEN="" OPENAI__KEY="" ``` -------------------------------- ### Set Ollama API Key Directly from Configuration Source: https://github.com/the-pr-agent/pr-agent/wiki/.pr_agent_auto_best_practices When making Ollama Cloud requests, set the `api_key` directly from the Ollama configuration (e.g., `get_settings().ollama.api_key`) instead of relying on the process-global `litellm.api_key`. This prevents authentication issues in multi-provider setups. ```python In the Ollama Cloud block, set `kwargs["api_key"]` from the Ollama configuration directly (e.g., `get_settings().ollama.api_key` or `get_settings().get("OLLAMA.API_KEY")`) instead of `litellm.api_key`. ``` -------------------------------- ### Configure GitHub App Automatic Push Commands Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/usage-guide/automations_and_usage.md Enable and define tools to run automatically when new code is pushed to an open PR. This allows for continuous feedback on code changes. ```toml [github_app] handle_push_trigger = true push_commands = [ "/describe", "/review", ] ``` -------------------------------- ### Build Gitea App Docker Image Source: https://github.com/the-pr-agent/pr-agent/blob/main/docs/docs/installation/gitea.md Builds a Docker image specifically for the Gitea application using the provided Dockerfile. It targets the 'gitea_app' stage. ```bash docker build -f /docker/Dockerfile -t pr-agent:gitea_app --target gitea_app . ```