Technical Documentation: The-PR-Agent/pr-agent
ℹ️ Provenance: Multi-Tier Ingestion · CodeWiki Reference
Overview (`README.md`)
This repository contains the open-source PR Agent Project.
It is not the Qodo offering for open-source projects.
PR-Agent is an open-source, AI-powered code review agent and a community-maintained legacy project of Qodo. It is distinct from Qodo's primary AI code review offering, which provides a feature-rich, context-aware experience. Qodo offers a free version for open-source projects and integrates seamlessly with GitHub, GitLab, Bitbucket, and Azure DevOps for high-quality automated reviews.
Sponsors
PR-Agent is a community-maintained open-source project, with its ongoing development supported by our sponsors. If you'd like to support the project, consider becoming a sponsor.
Table of Contents
Getting Started
[!NOTE]
Docker Hub namespace migration. Releases0.34.2and later are published underpragent/pr-agent. Older releases (up to and includingv0.31) remain available at the legacycodiumai/pr-agentnamespace as a frozen archive — no new images are pushed there. Update any pinnedimage:/docker pull/uses: docker://references when upgrading to0.34.2+.
🚀 Quick Start for PR-Agent
1. GitHub Action (Recommended)
Add automated PR reviews to your repository with a simple workflow file:
# .github/workflows/pr-agent.yml
name: PR Agent
on:
pull_request:
# PR-Agent skips synchronize by default. Include it in github_action_config.pr_actions
# for auto commands, or enable github_action_config.handle_push_trigger for push_commands (takes precedence).
types: [opened, synchronize]
jobs:
pr_agent_job:
runs-on: ubuntu-latest
permissions:
contents: read
issues: write
pull-requests: 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 }}Full GitHub Action setup guide
2. CLI Usage (Local Development)
Run PR-Agent locally on your repository:
pip install "pr-agent[github]"
export OPENAI__KEY=your_openai_key
export GITHUB__USER_TOKEN=your_github_token
pr-agent --pr_url https://github.com/owner/repo/pull/123 reviewGit provider SDKs are optional extras: install the one for your provider (list), or pr-agent[all] for every integration.
Complete CLI setup guide
3. Other Platforms
News and Updates
Full notes for every release are on the Releases page.
Why Use PR-Agent?
🎯 Built for Real Development Teams
Fast & Affordable: Simple /review and /ask requests can use one LLM call; retries, fallbacks, and larger reviews may need more.
Handles Any PR Size: Our PR Compression strategy effectively processes both small and large PRs
Highly Customizable: JSON-based prompting allows easy customization of review categories and behavior via configuration files
Platform Agnostic:
- Git Providers: GitHub, GitLab, BitBucket, Azure DevOps, Gitea
- Deployment: CLI, GitHub Actions, Docker, self-hosted, webhooks
- AI Models: OpenAI GPT, Anthropic Claude, Google Gemini, DeepSeek, Mistral, and any other model reachable through LiteLLM (Azure OpenAI, AWS Bedrock, Vertex AI, Databricks, OpenRouter, Ollama, and more) — see Changing a model
Open Source Benefits:
- Full control over your data and infrastructure
- Customize prompts and behavior for your team's needs
- No vendor lock-in
- Community-driven development
Features
See the current feature and git provider support matrix in the PR-Agent documentation.
⚠️ /help_docs is temporarily disabled since v0.36.1 pending a fix for a credential-exposure issue (#2445).
See It in Action
[/describe](https://github.com/the-pr-agent/pr-agent/pull/530)
[/review](https://github.com/the-pr-agent/pr-agent/pull/732#issuecomment-1975099151)
After v0.50.0, /improve was folded into /review rather than generating standalone code suggestions. See fixes and committable suggestions for the new behavior, or the v0.50.0 documentation for the previous behavior.
Usage Examples
PR-Agent commands run as a comment on a PR or from the CLI. A few common ones:
# Comment on a PR (GitHub/GitLab/Bitbucket/…):
/describe
/review
/ask "What does this PR change?" # free-text Q&A about the PR
# Issue-scoped commands run on an issue instead of a PR:
/similar_issue # find similar issues in the repository
# Or locally via the CLI:
pr-agent --pr_url <PR_URL> review
pr-agent --issue_url <ISSUE_URL> similar_issueSee the Commands docs for the full list of commands with example commands, and each command's page for screenshots and options.
How It Works
The following diagram illustrates PR-Agent commands and their flow:
Data Privacy
Self-hosted PR-Agent
- If you host PR-Agent with your OpenAI API key, it is between you and OpenAI. You can read their API data privacy policy here:
https://openai.com/enterprise-privacy
Contributing
To contribute to the project, get started by reading our Contributing Guide.
For local verification, run PYTHONPATH=. uv run pytest from the repository root; it discovers the unit-test suite under tests/unittest by default. End-to-end tests under tests/e2e_tests require provider credentials and should be invoked explicitly, for example PYTHONPATH=. uv run pytest tests/e2e_tests/test_github_app.py.
Big News for PR-Agent
PR-Agent has a new home!
After years of building this tool alongside the community, Qodo has donated PR-Agent to the open-source community - and we couldn't be more excited about what comes next.
The project now lives in the PR-Agent org on GitHub, is fully community-owned, and is open for contributions and additional maintainers.
What else changed:
- Docs moved to - docs.pr-agent.ai
- Qodo Merge (Qodo 1.0), the hosted URL, which was the enterprise version of PR-Agent, has been rebranded and evolved into Qodo (Qodo 2.0), a full AI code review platform.
❤️ Community
This open-source release remains here as a community contribution from Qodo — the origin of modern AI-powered code collaboration. We’re proud to share it and inspire developers worldwide.
The project now has its first external maintainer, Naor (@naorpeled), and is currently in the process of being donated to an open-source foundation.
Overview (`docs/README.md`)
[Visit Our Docs Portal](https://docs.pr-agent.ai/)
Overview (`docker/mosaico/README.md`)
PR-Agent — MOSAICO solution-agent deployment bundle
Deployment assets for running PR-Agent as a MOSAICO A2A
solution agent. This directory contains no Python and no pr-agent source — it consumes
PR-Agent as a published, version-pinned Docker image. The agent's source lives inThe-PR-Agent/pr-agent, under pr_agent/mosaico/;
it is merged into main and ships in every release wheel and image starting at v0.36.0.
Relationship to the PR-Agent repository
This is not a fork and it never becomes one:
- The MOSAICO A2A server is PR-Agent code, released in tags
v0.36.0onwards. This bundle
holds zero Python — a compose overlay, registration and env templates, a smoke test,
and this README. - The release workflow publishes
pragent/pr-agent:<version>-mosaico_agentfor every release,
from the same CI matrix that builds its other images — the MOSAICO target cannot silently
stop being built without the whole release failing. - Eclipse CI
republishes the existing0.41.0-mosaico_agentimage, pinned by its upstream index digest,
asregistry.eclipse.org/eclipse-research-labs/mosaico-project/qodo-pr-agent:0.41.0-mosaico_agent.
Same-project merge requests publishmr--<full-commit-sha>previews. Only a push to
the default branch publishes the stable version tag, after the preceding CI checks.
The initial stable tag becomes available after the Eclipse CI change is merged and its
publication succeeds; validate its preview withIMAGE= ./smoke_test.shmeanwhile. - Shared deployment files are maintained here, under
docker/mosaico/ingithub.com/The-PR-Agent/pr-agent. Apply matching focused edits to the Eclipse deployment
mirror. Its rootDockerfileand.gitlab-ci.ymlbelong to Eclipse and are maintained there. - To upgrade, change the upstream version and index digest in Eclipse's
Dockerfileand
the stableIMAGE_TAGin its.gitlab-ci.yml. Update the matching image references in
the compose overlay, smoke default, and README here and in Eclipse, then validate the
published preview with the existing smoke script before merging the release change.
Quick start (standalone, no demonstrator)
Boots from a bare docker pull in a couple of seconds — no repo clone, no build:
docker pull registry.eclipse.org/eclipse-research-labs/mosaico-project/qodo-pr-agent:0.41.0-mosaico_agent
docker run -d --name pr-agent-mosaico -p 9000:9000 \
-e API_BASE=https://your-openai-compatible-endpoint/v1 \
-e API_KEY=sk-... \
-e MODEL_NAME=openai/your-model-slug \
registry.eclipse.org/eclipse-research-labs/mosaico-project/qodo-pr-agent:0.41.0-mosaico_agent
curl -s http://localhost:9000/.well-known/agent-card.json | python3 -m json.toolEndpoints (port 9000):
GET /.well-known/agent-card.json— the A2A agent cardPOST /— A2A 1.0 JSON-RPC. Send theSendMessagemethod with anA2A-Version: 1.0header; the header is required, as the server treats a request
without it as protocol 0.3 and rejects it. The reply comes back as a task artifact
(result.task.artifacts[].parts[].text), not as a status message.GET /health— a live LLM connectivity probe (200 healthy / 503 unhealthy)
Env-var contract (MOSAICO agent requirements are defined in the demonstrator'sdocs/agent-requirements.md):
API_BASE,API_KEY,MODEL_NAME— the LLM connectionHOST(default0.0.0.0),PORT(default9000) — bind addressAGENT_CARD_HOST,AGENT_CARD_PORT— see below; unset by defaultMODEL_MAX_TOKENS(default32000) — token budget for models whose context size
pr-agent does not already knowLANGFUSE_HOST,LANGFUSE_PUBLIC_KEY,LANGFUSE_SECRET_KEY— optional observability
Expect a card whose top level carries name: "PR-Agent Solution Agent" and version equal to
the image tag's version (it is derived from the running build, never hand-maintained), with
skills review, improve, describe, ask, and the requiredhttps://mosaico-project.eu/extensions/mosaico-observability extension.
Caller authentication and request limits
Configure MOSAICO__BEARER_TOKENS='@json {"reference-agent":"replace-with-generated-secret"}'
in the agent's secret environment to require bearer authentication for JSON-RPC and the
live /health probe. Each configured principal has a distinct secret and its own tasks,
histories and artifacts. The public agent card advertises this requirement. Configure the
reference caller to send Authorization: Bearer <secret> over your HTTPS ingress.
The default empty map permits anonymous shared ownership; use it only on a trusted,
single-tenant network.
For smoke_test.sh, also set the client-side MOSAICO_BEARER_TOKEN in the script's environment.
For the overlay, add the server's MOSAICO__BEARER_TOKENS to the service environment through
your secret configuration, and set PR_AGENT_BEARER_TOKEN for its healthcheck. The reference
caller needs its own credential configuration. Missing/invalid credentials produce HTTP 401;
the agent-card GET remains public. Anonymous-mode probes need no token.
The shared config.max_webhook_request_body_bytes cap defaults to 5 MiB and returns HTTP 413
before parsing oversized bodies. mosaico.routing_scan_max_chars defaults to 65536 characters
for PR URL and command detection per segment; put those near the start of a message or its
surrounding prose. Diffs remain complete. Invalid observability UUIDs are ignored individually.
These controls do not impose task eviction, request rates, concurrency quotas or health caching.
`AGENT_CARD_HOST` / `AGENT_CARD_PORT` — the one thing to get right
These two variables set the URL the agent advertises in supportedInterfaces. Leave them
unset and the card advertises http://localhost:9000/, which is reachable only from inside
the container itself. The failure this causes is silent and late: registration with
MOSAICO succeeds, the repository stores the unreachable URL, and the reference agent only
fails to dereference it once it tries to route a task to this agent.
In the demonstrator overlay below, these are already wired correctly:
AGENT_CARD_HOST: ${PR_AGENT_HOST:-${DEFAULT_TASK_AGENT_HOST}}
AGENT_CARD_PORT: ${PR_AGENT_PORT:-23000}Standalone, set them explicitly to whatever host/port the caller will use to reach the
container. Verify with:
curl -s http://<host>:<port>/.well-known/agent-card.json \
| python3 -c "import sys,json; print(json.load(sys.stdin)['supportedInterfaces'][0]['url'])"If that prints a localhost URL, the deployment is wrong.
Deploy into the mosaico-demonstrator
- Copy
docker-compose.pr-agent.ymlinto the demonstrator'scompose/directory, next tobase-definitions.yml— the overlay'sextends:references resolve relative to that
directory. - Copy
pr-agent-solution-agent.jsoninto the demonstrator'sdocker/agent-registrations/directory. - Append the "demonstrator overlay" block from
pr-agent.env.exampleto the demonstrator'senv/llm.envand fill inPR_AGENT_MODEL(PR_AGENT_HOSTmay stay empty to use the
demonstrator's auto-detected LAN IP;PR_AGENT_PORTdefaults to23000). - Add
-f compose/docker-compose.pr-agent.ymlto the demonstrator's01-compose.sh, next to
the other task-agent overlays. ./01-compose.sh up -d.
Registration
The demonstrator's register-agent.py reads pr-agent-solution-agent.json and injects, at
registration time: name (from the overlay's AGENT_NAME), a2aAgentCardUrl (fromAGENT_CARD_URL), and deployment.mode = ENDPOINT. That is why the template carries only
four fields: description, role, objective, version.
Two names are intentionally different, so don't "fix" the mismatch:
- The MOSAICO repository entry's
nameispr-agent-solution-agent(kebab-case, whatregister-agent.pylooks the agent up by). - The A2A card's own
namefield is"PR-Agent Solution Agent"(a display string, asserted
bysmoke_test.sh).
Verify
./smoke_test.shTwo outcomes:
SMOKE PASSED— no LLM creds available; the script pulled the pinned image, booted it,
and validated the agent card only.FULL ROUND-TRIP PASSED— LLM creds were present (via a.envfile beside the script,
copied frompr-agent.env.example); the script additionally exercisedGET /healthand an A2ASendMessagereview over an inline diff.
Troubleshooting
- Container stays
unhealthy, registration never runs./healthis a live LLM probe and
returns503on bad/missing credentials — this is intended: a registered card backed by
a dead LLM is worse than no registration. Images with health-probe hardening returnUnhealthy: LLM probe failedfor provider failures. The health check's own warning logs only the exception type,
not the provider's error text.mosaico.health_timeout_secondssets the deadline for cooperative asynchronous work
(default: 10 seconds; must be a finite positive number). Synchronous
handler construction and blocking SDK work can still exceed it. Existing image tags may
predate this behavior and expose provider error details.
SetMOSAICO__HEALTH_TIMEOUT_SECONDSin the agent container's environment to override
the default; with Compose, add it to the service'senvironmentmapping.
Invalid values make/healthreturn the generic unhealthy response (503), not the default timeout.
The bundled Compose probe has its own 25-second HTTP timeout. Stream cleanup may continue
after/healthtimes out without delaying its unhealthy response; it has no separate
wait budget or local stream admission limit. Allow a margin over the health timeout in
the HTTP timeout and Docker'shealthcheck.timeoutso registration can run.
CheckAPI_BASE/API_KEY/MODEL_NAME, not the compose file. - Agent registers but the reference agent never reaches it. The advertised card URL is
localhost; see theAGENT_CARD_HOST/AGENT_CARD_PORTsection above. - The registration container itself can't fetch the agent card.
01-compose.shfalls back
toget_fallback_ip, which can resolve tolocalhost— reachable from the host, but not
from inside thepr-agent-solution-agent-registrationcontainer on the Docker network. If
registration fails to fetchAGENT_CARD_URL, setPR_AGENT_HOSTexplicitly to an address
reachable from inside Docker (e.g. the host's LAN IP, orhost.docker.internal). Every peer
task agent shares this same exposure; it is not specific to PR-Agent.
License
MIT — see the bundled LICENSE. The-PR-Agent/pr-agent is MIT-licensed too.
Overview (`scripts/review_context/README.md`)
Diff-scoped code context for pr-agent's `[artifacts]` slot
A starting point, not a finished tool. graph_bundle_ts.py builds a review-context bundle for one PR with tree-sitter, and instructions.txt tells the model how to read it. Together they are the setup measured in The-PR-Agent/pr-agent#2499.
The builder, instructions and original hardening tests were imported from IsmaelMartinez/pr-agent, review-context-builder, commit 3dcc022.
The bundle holds the changed symbols (signature plus the body lines the diff does not show), module constants and callees they use, inbound callers (hub callers ranked, under a cap), sibling implementations and sibling config/prompt/doc files, sites still using a pattern the PR removed, similar code and same-pattern sites, tests that exercise the change, and importers. It is capped at about 12k tokens.
Every language is handled by one class driven by tree-sitter tags queries, covering the 30 languages detected by its extension list with tree-sitter-language-pack 1.22.1 (Python, JavaScript, TypeScript, Go, Java, C, C++, C#, Rust, Ruby, PHP, Kotlin and more). It has only been scored on Python; Go and TypeScript were smoke-tested. --generic remains accepted for existing workflow invocations and has no effect; tags queries are always used.
Run
The pinned builder environment targets CPython 3.12 on Linux x86_64. Install its two wheels with hash checking and verify the versioned grammar archive before extracting it (GNU tar and zstd are required):
uv venv --python 3.12 /tmp/review-context-venv
uv pip install --python /tmp/review-context-venv/bin/python --require-hashes --only-binary :all: \
-r scripts/review_context/requirements.txt
mkdir -p /tmp/review-context-grammars
curl --fail --location --max-time 60 \
https://github.com/xberg-io/tree-sitter-language-pack/releases/download/v1.22.1/parsers-linux-x86_64.tar.zst \
--output /tmp/review-context-grammars/parsers-linux-x86_64.tar.zst
(cd /tmp/review-context-grammars && sha256sum --check "$OLDPWD/scripts/review_context/grammars.sha256" && \
tar --zstd --extract --file parsers-linux-x86_64.tar.zst --no-same-owner)
/tmp/review-context-venv/bin/python -I scripts/review_context/graph_bundle_ts.py \
--repo "$PWD" --base "$BASE_SHA" --head "$HEAD_SHA" --pr "$PR_NUMBER" \
--out-dir /tmp/review-context --generic --grammar-cache /tmp/review-context-grammarsrequirements.txt pins tree-sitter-language-pack==1.22.1 and tree-sitter==0.26.0, including their wheel hashes. grammars.sha256 pins the Linux x86_64 grammar bundle from the same language-pack release. Updating a dependency or grammar bundle requires updating the checked-in hashes. No native libraries are restored from an Actions cache.
--repo is any clone that holds both commits; the head does not need to be checked out, because every file is read from git. The bundle is written to <out-dir>/pr<N>.G6.md and a summary JSON goes to stdout. --grammar-cache must point directly to the verified libraries. The builder uses a local LanguageRegistry, which never downloads missing grammars; it does not use the package's global auto-downloading loaders. Its --timeout covers grammar initialization, building and writing the staged bundle (120 s by default); an expired deadline prints a diagnostic to stderr and exits 2 without publishing a new bundle. The temporary file remains owner-only while it is written, then receives normal file-creation permissions before the final atomic rename. The rename and stdout output follow deadline reconciliation; the workflow's outer GNU timeout bounds those operations. The Git subprocess stays in the builder's process group so an external SIGTERM can still terminate both. Callers must remove stale output before each run and use the bundle only after a successful exit.
Hand the bundle to pr-agent, here for /review only:
export ARTIFACT_PATH=/tmp/review-context/pr$PR_NUMBER.G6.md
export ARTIFACT_INSTRUCTIONS="$(cat scripts/review_context/instructions.txt)"
export ARTIFACTS__TARGET_COMMANDS='["pr_reviewer"]'
# pr-agent 0.50.0 and earlier read the old name
export ARTIFACTS__TARGET_TOOLS='["pr_reviewer"]'In the GitHub Action, set the same three on the action step's env (or its artifact_path input), and write the bundle inside GITHUB_WORKSPACE, because paths outside it are rejected.
Untrusted PRs
The builder treats the PR as hostile input:
- It never imports or executes the target repo's code; files are parsed with tree-sitter only.
- It reads only regular files tracked at the head commit, as git blobs (
git ls-treeplus onegit cat-file --batch). Symlinks, submodules and untracked files never reach the bundle, so a PR cannot pull in a file from outside the repo. - It skips files over 1 MB and secret-looking names (
.env*,secrets.toml,.secrets.toml,*.pem,*.key, SSH keys,.netrc,.npmrc,.pypirc,credentials*, Terraform state). pr-agent also redacts common credential shapes in artifact content. - It runs git with
--no-ext-diff --no-textconv,core.fsmonitor=false,core.hooksPath=/dev/nullandprotocol.allow=never, so no diff driver, monitor or hook program from a poisoned config runs and a partial clone cannot fetch. - A file nested too deeply to walk is left out, the whole build has a wall-clock limit, and the output is written atomically, so a failure leaves no partial bundle.
test_hardening.py checks these against a hostile repository (symlink out of the tree, untracked file, .env, secrets.toml, a .pem, an oversized file, 30,000-deep nesting, and a local config with a textconv driver, an fsmonitor and a hooks path):
uv sync
uv pip install --python .venv/bin/python --require-hashes --only-binary :all: \
-r scripts/review_context/requirements.txt
GRAMMAR_CACHE=/tmp/review-context-grammars PYTHONPATH=. uv run pytest scripts/review_context -qPaths in headings and file lists use Markdown code spans with delimiters longer than any embedded backtick run. Control characters are rendered visibly so a path cannot introduce another heading or line.
Self-review workflow
.github/workflows/pr-agent-review.yaml builds context for ready PR-open events, authorized /review comments, and both manual replay forms. /describe, /improve and other comment commands do not build a bundle; the artifact is restricted to pr_reviewer when an opened event runs all three tools.
The workflow separates three jobs:
prepare_reviewauthorizes the event and resolves the PR base/head SHAs. It checks out the repository's default branch to record the tooling commit and reading instructions. Manual replay event data is uploaded separately here.review_contexthas onlycontents: readpermission and no secrets. It checks out that recorded default-branch commit, installs the hash-pinned wheels, verifies/extracts the pinned grammar archive, then fetches the PR objects and verifies the head SHA without checking out either the PR head or its target branch. The builder runs only here. A successful build uploads onlyreview-context/bundle.md; this job exports no outputs or reading instructions.pr_agent_jobruns on a fresh runner with the sponsored key and posting token. It downloads the bundle as data, verifies the fixed path is a non-empty regular file within the size bound, and sets the Docker-visibleARTIFACT_PATHto/github/workspace/review-context/bundle.md. Reading instructions come fromprepare_review, outside the parser job. Parser writes toGITHUB_ENVorGITHUB_OUTPUTcannot affect this runner.
Failed context preparation, dependency verification, fetching, parsing, upload/download, or artifact validation preserves diff-only review. The first deployment also falls back while the default branch lacks the tooling. The parse step has a 150-second outer limit; dependency setup has its own two-minute limit. The keyed job still requires successful authorization even when the context job fails or is skipped.
Run the workflow shell tests with PYTHONPATH=. uv run pytest tests/unittest/test_review_context_workflow.py -q. They require Bash, Git, jq and GNU timeout; shell cases skip with a reason when a tool is missing, including jq in the minimal Docker test image. The workflow structure check still runs there. The tests execute real workflow scripts against a local Git remote with a modified target-branch builder, stub the API/installer, and exercise authorization, replay, SHA mismatch, stale output, checksum failure, invalid artifacts and untrusted artifact contents. Builder tests use verified native grammars and hostile repositories, including path escaping. The build-and-test workflow runs them in a dedicated Python 3.12 job on every PR to main, using the hash-pinned wheels and verified grammar archive; setup or test failures fail the job. Local tests do not validate live GitHub event delivery or the sponsored Docker action.
Docs Index (`docs/docs/index.mdx`)
title: "Overview" sidebar_position: 1 hide_title: true hide_table_of_contents: true displayed_sidebar: null custom_edit_url: null pagination_prev: null pagination_next: null
import Hero from '@site/src/components/Hero';
import MaintainerAvatars from '@site/src/components/MaintainerAvatars';
Quick start
Review a pull request from your terminal. All you need is an OpenAI key and a GitHub token.
docker run --rm -it \
-e OPENAI__KEY=<your_openai_key> \
-e GITHUB__USER_TOKEN=<your_github_token> \
pragent/pr-agent:latest --pr_url <pr_url> reviewInstall it on your repositories Other ways to run it locally
Already installed? Comment /help "your question" on a pull request and PR-Agent answers from these docs.
Maintained by
Docs Commands Index (`docs/docs/commands/index.md`)
title: "Commands" sidebar_position: 1
Each PR-Agent command has a dedicated page that explains its behavior and usage:
| Command | Description |
|---|---|
PR Description (/describe) |
Generate a PR title, type, summary, code walkthrough and labels. |
PR Review (/review) |
Generate a PR review with feedback on possible issues, security concerns, tests and review effort. |
Code Suggestions (/improve) |
Runs /review, whose findings can carry committable code fixes. |
Question Answering (/ask ...) |
Answering free-text questions about the PR, or on specific code lines |
Add Documentation (/add_docs) |
Generate documentation for code components that are missing it |
Generate Labels (/generate_labels) |
Generate custom labels for the PR based on the code changes |
Similar Issues (/similar_issue) |
Find similar issues in the repository based on the current issue |
Help (/help) |
Provides a list of all the available commands |
Help Docs (/help_docs) |
Temporarily disabled. Answers questions about a Git repository’s documentation. |
Update Changelog (/update_changelog) |
Automatically updating the CHANGELOG.md file with the PR changes |
Usage examples
Each command can be triggered in two ways:
- As a comment — write the command (e.g.
/review) as a comment, and PR-Agent replies. Most commands are commented on a PR; issue-scoped commands such assimilar_issueare commented on an issue. - From the CLI — run
python -m pr_agent.cli --pr_url= <command>. Issue-scoped commands take--issue_url=instead of--pr_url. The module form works only from an environment where thepr_agentpackage is importable (for example, the venv created byuv sync). Ifpr-agentis on yourPATH, run it directly.
Both accept the same command arguments and configuration overrides.
| Command | Comment | CLI |
|---|---|---|
| Describe | /describe |
python -m pr_agent.cli --pr_url= describe |
| Review | /review |
python -m pr_agent.cli --pr_url= review |
| Improve | /improve |
python -m pr_agent.cli --pr_url= improve |
| Ask | /ask "How does X work?" |
python -m pr_agent.cli --pr_url= ask "How does X work?" |
| Add Docs | /add_docs |
python -m pr_agent.cli --pr_url= add_docs |
| Generate Labels | /generate_labels |
python -m pr_agent.cli --pr_url= generate_labels |
| Similar Issues | /similar_issue |
python -m pr_agent.cli --issue_url= similar_issue |
| Help | /help |
python -m pr_agent.cli --pr_url= help |
| Update Changelog | /update_changelog |
python -m pr_agent.cli --pr_url= update_changelog |
/help_docs is temporarily disabled (see #2445) and is therefore omitted from the table above.
For screenshots, arguments, and a walkthrough of a typical use case, see the Example usage section on each command's page linked above.
Docs Core Abilities Index (`docs/docs/core-abilities/index.md`)
title: "Core Abilities" sidebar_position: 1
PR-Agent utilizes a variety of core abilities to provide a comprehensive and efficient code review experience. These abilities include:
Blogs
Here are some additional technical blogs from Qodo, that delve deeper into the core capabilities and features of Large Language Models (LLMs) when applied to coding tasks.
These resources provide more comprehensive insights into leveraging LLMs for software development.
Code Generation and LLMs
- Effective AI code suggestions: less is more
- State-of-the-art Code Generation with AlphaCodium – From Prompt Engineering to Flow Engineering
- RAG for a Codebase with 10k Repos
Development Processes
- Understanding the Challenges and Pain Points of the Pull Request Cycle
- Introduction to Code Coverage Testing
Cost Optimization
Docs Faq Index (`docs/docs/faq/index.md`)
title: "FAQ" sidebar_position: 1
Q: Can PR-Agent serve as a substitute for a human reviewer?
Answer:1
PR-Agent is designed to assist, not replace, human reviewers.
Reviewing PRs is a tedious and time-consuming task often seen as a "chore". In addition, the longer the PR – the shorter the relative feedback, since long PRs can overwhelm reviewers, both in terms of technical difficulty, and the actual review time.
PR-Agent aims to address these pain points, and to assist and empower both the PR author and reviewer.
However, PR-Agent has built-in safeguards to ensure the developer remains in the driver's seat. For example:
- Preserves user's original PR header
- Places user's description above the AI-generated PR description
- Won't approve PRs by default. Gated auto-approval is a host-only opt-in (
config.enable_auto_approval). When enabled,/reviewcan approve a reviewed commit on GitHub or GitLab only when deterministic verdict checks pass (CI, head freshness, human authors, no sensitive/risky changes, size cap) and the model does not veto with a stricter recommendation or risk level. PR-Agent withdraws its own approval on new runs/pushes and never merges. - The code suggestions are optional, and aim to:
- Encourage self-review and self-reflection
- Highlight potential bugs or oversights
- Enhance code quality and promote best practices
Read more about this issue in our blog
Q: I received an incorrect or irrelevant suggestion. Why?
Answer:2
Modern AI models, like Claude Sonnet and GPT-5, are improving rapidly but remain imperfect. Users should critically evaluate all suggestions rather than accepting them automatically.
AI errors are rare, but possible. A main value from reviewing the code suggestions lies in their high probability of catching mistakes or bugs made by the PR author. We believe it's worth spending 30-60 seconds reviewing suggestions, even if some aren't relevant, as this practice can enhance code quality and prevent bugs in production.
The hierarchical structure of the suggestions is designed to help the user quickly understand them, and to decide which ones are relevant and which are not:
- Only if the
Categoryheader is relevant, the user should move to the summarized suggestion description. - Only if the summarized suggestion description is relevant, the user should click on the collapsible, to read the full suggestion description with a code preview example.
- Only if the
In addition, we recommend to use the
extra_instructionsfield to guide the model to suggestions that are more relevant to the specific needs of the project.
Q: How can I get more tailored suggestions?
Answer:3
See here for more information on how to use the extra_instructions configuration option, to guide the model to more tailored suggestions.
Q: Will you store my code? Are you using my code to train models?
Answer:4
When self-hosting PR-Agent, code is sent to your configured LLM provider. Storage and training policies depend on that provider and your deployment configuration.
For a detailed overview of our data privacy policy, please refer to this link
Q: Can PR-Agent review draft/offline PRs?
Answer:6
Yes. The GitHub App and GitLab webhook skip draft PRs and MRs by default; enable automatic draft feedback with feedback_on_draft_pr. The GitHub Action applies this setting to pull_request_review events, while Gitea, Azure DevOps, and Bitbucket do not skip drafts automatically. You can also get feedback on a supported draft by manually requesting it through online commenting.
For active PRs, you can customize the automatic feedback settings here to match your team's workflow.
Q: Can the 'Review effort' feedback be calibrated or customized?
Answer:7
Yes, you can customize review effort estimates using the extra_instructions configuration option (see documentation).
Example mapping:
- Effort 1: < 30 minutes review time
- Effort 2: 30-60 minutes review time
- Effort 3: 60-90 minutes review time
- ...
Note: The effort levels (1-5) are primarily meant for comparative purposes, helping teams prioritize reviewing smaller PRs first. The actual review duration may vary, as the focus is on providing consistent relative effort estimates.
Q: How to reduce the noise generated by PR-Agent?
Answer:3
The default configuration of PR-Agent is designed to balance helpful feedback with noise reduction. It reduces noise through several approaches:
- Auto-feedback uses two highly structured commands (
/describeand/review;/improveruns/review), designed to be accessible at a glance without creating large visual overload - Review findings are capped by
pr_reviewer.num_max_findings(6 by default), and fixes are posted as committable suggestions only ifpr_code_suggestions.committable_code_suggestionsis enabled - The 'File Walkthrough' section is folded by default, as it tends to be verbose
- Intermediate comments are avoided when creating new PRs (like "PR-Agent is now reviewing your PR..."), which would generate email noise
From our experience, especially in large teams or organizations, complaints about "noise" sometimes stem from the following issues:
- Feedback from multiple bots: When multiple bots provide feedback on the same PR, it creates confusion and noise. We recommend using PR-Agent as the primary feedback tool to streamline the process and reduce redundancy.
- Getting familiar with the tool: Unlike many tools that provide feedback only on demand, PR-Agent automatically analyzes and suggests improvements for every code change. While this proactive approach can feel intimidating at first, it's designed to continuously enhance code quality and catch bugs and problems when they occur. We recommend reviewing this guide to help align expectations and maximize the value of PR-Agent's auto-feedback.
Therefore, at a global configuration level, we recommend using the default configuration, which is designed to reduce noise while providing valuable feedback.
However, if you still find the feedback too noisy, you can adjust the configuration. Since each user and team has different needs, it's definitely possible - and even recommended - to adjust configurations for specific repos as needed.
Ways to adjust the configuration for noise reduction include for example:
- Utilizing the
extra_instructionsfield for more tailored feedback - Controlling which commands run automatically
Note that some users may prefer the opposite - more thorough and detailed feedback. PR-Agent is designed to be flexible and customizable, allowing you to tailor the feedback to your team's specific needs and preferences.
Examples of ways to increase feedback include:
Docs Installation Index (`docs/docs/installation/index.md`)
title: "Installation" sidebar_position: 1
There are several ways to use PR-Agent:
GitHub polling HTTP requests
When GitHub polling needs to look back through PR comments, it reuses the polling
HTTP session rather than blocking the event loop with a synchronous request.github.polling_request_timeout sets the total timeout for the entire fallback
comment-history scan, including any follow-up page requests
(default: 10 seconds; positive values are capped at 60). Invalid values use the
default with a warning. Set it in the host configuration or throughGITHUB__POLLING_REQUEST_TIMEOUT; repository settings do not control this limit.
This does not change the other polling requests or the sequential notification
scan. The fallback now follows the existing aiohttp session's proxy and TLS
behavior, not Requests-specific environment settings.
GitHub polling only processes mention notifications from repositories listed ingithub.polling_repositories (for example ["org/repo"]). The list is
host-only; repository settings and comment arguments cannot widen it. The empty
default ignores every polling notification and still marks it as read, so
configure it in the host configuration or through GITHUB__POLLING_REPOSITORIES
before enabling polling or upgrading.
The command after the first mention of the polling account is kept intact,
including later mentions in plain or double-quoted questions. Replace @your-bot
with the polling account's username:
@your-bot /ask Why does @your-bot appear in this workflow?
@your-bot /ask "Why does @your-bot appear in this workflow?"Sizing a self-hosted webhook server
The GitHub, GitLab, Gitea and Bitbucket Server webhook servers (the github_app, gitlab_webhook, gitea_app and bitbucket_server_webhook Docker targets) run under gunicorn with multiple worker processes, so that a worker busy handling a request cannot block the health check served by another. The other deployments — Bitbucket Cloud, Azure DevOps, GitHub polling, and the Lambda variants — do not use this gunicorn worker configuration.
| Variable | Default | Description |
|---|---|---|
GUNICORN_WORKERS |
(unset) | Pins the worker count exactly. Overrides the derived count and GUNICORN_MAX_WORKERS. |
GUNICORN_MAX_WORKERS |
4 |
Upper bound on the automatically derived worker count. |
PORT |
3000 |
Port the server binds to. |
When GUNICORN_WORKERS is unset, the worker count is derived from the CPUs actually available to the container (the stricter of the cgroup CPU limit and CPU affinity, using whichever is available), clamped to between 2 and GUNICORN_MAX_WORKERS, except that an explicit GUNICORN_MAX_WORKERS=1 permits one worker. Note that a CPU request without a limit leaves no cgroup quota to read, so affinity and the cap are what bound the worker count there.
Sizing memory: importing the application costs roughly 250MB. The app is imported once in the gunicorn master and workers are forked from it, so they share most of that baseline copy-on-write rather than each paying it in full — total memory grows with worker count, but by noticeably less than 250MB per worker. Start from about 1Gi for the default of 4 workers and adjust against your own metrics.
If the container is OOMKilled during startup, lower the worker count:
GUNICORN_WORKERS=2GitHub polling workers
GitHub polling uses one polling process and a separate child process for each
accepted comment. At most 10 of these child workers may be active across all
polling iterations. If an earlier batch still fills the limit, accepted work
waits for a free slot without blocking the event loop. This can delay the next
notification poll under sustained load.
The existing per-batch limit is unchanged: only the first 10 queued comments in
a batch are accepted; excess work is logged and dropped. Waiting work is held in
memory only. Notification acknowledgement is unchanged, so shutdown or startup
failures do not guarantee redelivery. Dispatch interruptions log the remaining
count. A worker startup failure stops polling rather than risking further
dispatch with an untracked child; inspect the failure before restarting.
Completed children are joined without waiting and closed each iteration;
live children are not terminated on cancellation. This is not a durable queue,
a model-call deadline, or a host-wide memory limit.
Docker image names and version tags
:::note[Docker Hub namespace migration]
Releases 0.34.2 and later are published under pragent/pr-agent. Older releases (up to and including v0.31) remain at the legacy codiumai/pr-agent namespace as a frozen archive — no new images are pushed there. The examples on this site reference the new namespace; if you are pinning to a release before 0.34.2, swap pragent/pr-agent for codiumai/pr-agent in your image: / docker pull / uses: docker:// references.
:::
:::note[Immutable releases and version tags]
What you pin is what you get. Version-numbered artifacts can never change after publication:
- GitHub releases — the Git tag cannot be moved or deleted, and attached assets cannot be added, replaced, or removed. The protection also survives repository deletion, so a tag from an immutable release can never be reused by a repository recreated under the same name. (Release titles and notes stay editable; immutability covers the tag and the assets.)
- Docker images — version tags such as
0.40.0and0.40.0-github_appalways resolve to the same image. Once pushed, they cannot be overwritten or repointed. Only thecliimage installs thepr-agentconsole script; on service images runpython -m pr_agent.cli …(orpython /app/pr_agent/cli.py …) instead — see CLI Health Check.
Rolling tags stay mutable by design. latest, github_action, github_lambda, gitlab_lambda, gitlab_webhook, gitea_app, mosaico_agent and bitbucket_server_webhook move to the newest build on every release. They are convenient for trying things out, but a docker pull of the same rolling tag on two different days can give you two different images.
For anything you depend on — CI, production webhooks, pinned Action steps — reference a version tag (or a digest) rather than a rolling one. Upgrading then becomes a deliberate change you make, not something that happens underneath you.
:::
Docs Usage Guide Index (`docs/docs/usage-guide/index.md`)
title: "Usage guide" sidebar_position: 1
This section provides a detailed guide on how to use PR-Agent.
It includes information on how to adjust PR-Agent configurations, define which commands will run automatically, and other advanced configurations.
- Introduction
- Configuration File
- Configuration Reference
- Usage and Automation
- Managing Mail Notifications
- Push Outputs
- Changing a Model
- Additional Configurations
- FAQ
Package.Json (`docs/package.json`)
{
"name": "pr-agent-docs",
"version": "0.0.0",
"private": true,
"scripts": {
"docusaurus": "docusaurus",
"start": "docusaurus start",
"build": "docusaurus build",
"swizzle": "docusaurus swizzle",
"deploy": "docusaurus deploy",
"clear": "docusaurus clear",
"serve": "docusaurus serve",
"write-translations": "docusaurus write-translations",
"write-heading-ids": "docusaurus write-heading-ids"
},
"dependencies": {
"@docusaurus/core": "3.10.2",
"@docusaurus/plugin-client-redirects": "3.10.2",
"@docusaurus/preset-classic": "3.10.2",
"@easyops-cn/docusaurus-search-local": "^0.55.3",
"@fontsource-variable/geist": "^5.3.0",
"@fontsource-variable/geist-mono": "^5.3.0",
"@mdx-js/react": "^3.0.0",
"docusaurus-plugin-image-zoom": "^3.0.1",
"prism-react-renderer": "^2.3.0",
"react": "^19.3.1",
"react-dom": "^19.3.1"
},
"devDependencies": {
"@docusaurus/module-type-aliases": "3.10.2",
"@docusaurus/types": "3.10.2"
},
"browserslist": {
"production": [
">0.5%",
"not dead",
"not op_mini all"
],
"development": [
"last 3 chrome version",
"last 3 firefox version",
"last 5 safari version"
]
},
"engines": {
"node": ">=22.0"
}
}
Docs Commands Add Docs (`docs/docs/commands/add_docs.md`)
title: "Add Docs" sidebar_position: 6
Overview
The add_docs command scans the PR code changes and suggests documentation for any code components that are missing documentation, such as functions, classes, and methods.
It can be invoked manually by commenting on any PR:
/add_docsExample usage
Invoke the command manually by commenting /add_docs on any PR:
The command will generate documentation suggestions as inline code suggestions.
Language-specific documentation styles
The command automatically detects the programming language and generates documentation in the appropriate format:
| Language | Documentation Format |
|---|---|
| Python | Docstrings (Sphinx, Google, Numpy styles) |
| Java | Javadocs |
| JavaScript/TypeScript | JSdocs |
| C++ | Doxygen |
| Other | Generic documentation |
Configuration options
Under the section [pr_add_docs], the following options are available:
| Option | Type | Default | Description |
|---|---|---|---|
extra_instructions |
string | "" |
Additional instructions for the AI model |
docs_style |
string | "Sphinx" |
Documentation style for Python. Options: "Sphinx", "Google Style with Args, Returns, Attributes...etc", "Numpy Style", "PEP257", "reStructuredText" |
use_repo_context |
boolean | true |
Apply conventions from configured repository instruction files (for example AGENTS.md); set to false to opt out |
Example configuration
To customize the documentation style, add the following to your configuration file:
[pr_add_docs]
docs_style = "Google Style with Args, Returns, Attributes...etc"
extra_instructions = "Focus on documenting public methods and include usage examples"By default, /add_docs follows the shared config.repo_context_files selection (["AGENTS.md"] by default,
read from the repository default branch). To disable repository instructions for /add_docs only:
[pr_add_docs]
use_repo_context = falseStructured sibling-repository entries in config.repo_context_files are excluded from /add_docs to avoid publishing private sibling guidance in PR suggestions. Local repository entries remain in effect.
Setting config.repo_context_files = [] disables repository instructions across commands. Repository instructions
are optional prompt context: if they do not fit the selected model's input budget, they are omitted without shortening
the PR diff. Explicit extra_instructions and docs_style take precedence. Repository instructions may add file
reads and prompt tokens, but do not introduce another model call.
Repository instructions are appended to the rendered system prompt, including with custom [pr_add_docs_prompt]
templates. Existing template variables and diff rendering are left unchanged.
Command line options
You can pass configuration options directly in the command:
/add_docs --pr_add_docs.docs_style="Numpy Style"How it works
- The command analyzes the PR diff to identify code components (functions, classes, methods) that lack documentation
- It uses AI to generate appropriate documentation based on the code context and language
- Documentation suggestions are published as inline code suggestions that can be applied with a single click
Model response failures
Each model response is validated before it is accepted. Missing content or an
invalid documentation structure triggers the next model in CONFIG.FALLBACK_MODELS,
if configured. An explicit empty list or Code Documentation: null is a valid
empty result and does not trigger another model call.
If all model attempts fail, PR-Agent records the command as failed and removes
the temporary progress comment. With CONFIG.PUBLISH_OUTPUT enabled, it also
attempts to post Failed to generate code documentation for this PR.
Publication failures
Suggestions are skipped if their original source line cannot be reliably retained,
including when file content is unavailable or incomplete. Valid suggestions in the
same response can still be published.
With CONFIG.PUBLISH_OUTPUT enabled, PR-Agent retries unsuccessful batch
publication one suggestion at a time. If the batch and every individual retry
explicitly report failure, it attempts to post Failed to publish code
documentation for this PR. and records the command as failed. Partial success
or an unconfirmed provider result does not trigger this all-failed outcome.
Docs Commands Ask (`docs/docs/commands/ask.md`)
title: "Ask" sidebar_position: 5
Overview
The ask command answers questions about the PR, based on the PR code changes. Make sure to be specific and clear in your questions.
It can be invoked manually by commenting on any PR:
/ask "..."CLI JSON output
The CLI can write a single JSON file containing the question, answer, and available token usage:
python -m pr_agent.cli --pr_url https://github.com/org/repo/pull/123 \
--json-output answer.json ask "What changed?"This also works with ask_question and in Plain Diff mode:
git diff | python -m pr_agent.cli --stdin --json-output answer.json ask "What changed?"Place --json-output before the command. The file is overwritten for each invocation and hasquestion, answer, and usage fields. usage is an empty object when token counts are unavailable,
including when the command explains that no changed files could be analyzed without calling a model.
For PR URLs, setting config.publish_output = false in the host configuration suppresses PR
comments without suppressing the requested JSON file. The existing
push outputs feature serves a different purpose: it delivers
opt-in Ask records to operator-configured sinks and requires publishing to be enabled.
Example usage
Repository instructions
Both top-level /ask and inline /ask_line can use the same repository instruction files as /review, /describe, and /improve.
For example, ask whether a migration follows the rollback rules in an existing architecture decision record:
[config]
repo_context_files = ["AGENTS.md", "docs/adr/database-migrations.md"]/ask "Does this migration follow our rollback and compatibility rules?"Like /review, /describe, and /improve, both Ask modes read AGENTS.md from the repository root by default.
Set config.repo_context_files = [] in the root repository settings to disable repository instructions for all commands.
Comment arguments cannot change the configured file list.
The existing repository context settings
control file selection, source branches, imports, and line limits. Files come from the repository's default branch unless
configured otherwise. Providers without repository file access skip this context; missing or empty files are also skipped.
The question, selected discussion history, and packed diff keep their existing token budget. The instruction block,
already bounded by repo_context_max_lines, is included only if it fits in the remaining model context in full.
Otherwise, the corresponding Ask mode keeps its original prompt and adds a short omission notice to the answer. It does not retry another model
just to fit instructions. Normal model retries reconsider the original instruction block without reading the files again.
For /ask_line, the selected lines, complete diff hunk, and fitted thread history likewise take precedence over
repository instructions. No instruction files are read when the requested diff hunk is unavailable.
Including repository instructions can add repository API reads and input tokens, but does not add a separate model request.
Ask lines
You can run /ask on specific lines of code in the PR from the PR's diff view. The command will answer questions based on the code changes in the selected lines.
For line comments handled by the GitHub App, GitHub Actions, or GitLab webhook, /ask_question is an alias of /ask.
Start the comment with /ask, /ask_question, or /ask_line after any leading whitespace;
these command names are case-insensitive. Other tokens such as /asking are not Ask commands.
Azure DevOps accepts lowercase /ask_question for the same thread and line handling as /ask;
its webhook command names remain case-sensitive.
- Click on the '+' sign next to the line number to select the line.
- To select multiple lines, click on the '+' sign of the first line and then hold and drag to select the rest of the lines.
- write
/ask "..."in the comment box and pressAdd single commentbutton.
If no matching diff hunk is found for the selected lines, the command explains this without calling a model.
In the GitHub App, GitHub Actions, and GitLab webhook, a file comment whose first non-whitespace token is /ask or/ask_question uses that file's complete diff as context. These two command names are case-insensitive.
The existing file filters and input budgets still apply. If the file has no analyzable diff, or the question cannot
be prepared within the configured input budget, the command explains this without calling a model.
The answer is posted in the original file-comment thread with a link to the question.
Earlier replies are included when pr_questions.use_conversation_history is enabled and the input budget allows.
Text resembling command options is treated as part of the question.
In the Azure DevOps webhook, /ask, /ask_question, or a mention of PR-Agent in a thread on a whole file also uses
that file's complete diff, with the same filters, input budgets, and notes. The answer is posted in that thread with a
link to the question, and earlier comments in the thread are included as described above.
With pr_questions.use_conversation_history=true (the default), line questions on GitHub, GitLab, and Azure DevOps
can include earlier comments from the same thread. Azure DevOps also supports history for threaded top-level questions.
Other questions are answered independently.
On GitLab, this reads the selected discussion before answering, adding an API request and potentially more model input
tokens, but no separate model request. Set pr_questions.use_conversation_history=false to answer without earlier
comments. Line questions still require a matching hunk in the current diff.
Ask on images
You can also ask questions about images that appear in the comment, where the entire PR code will be used as context.
The basic syntax is:
/ask "..."
[Image](https://real_link_to_image)where https://real_link_to_image is the direct link to the image.
Note that GitHub has a built-in mechanism of pasting images in comments. However, pasted image does not provide a direct link.
To get a direct link to an image, we recommend using the following scheme:
First, post a comment that contains only the image:
Quote reply to that comment:
In the screen opened, type the question below the image:
Post the comment, and receive the answer:
See a full video tutorial here
Linked ticket context
Enable linked ticket context when asking how a PR satisfies an issue's requirements or acceptance criteria:
[pr_questions]
use_ticket_context = trueSet this in host or root repository configuration. PR comment/CLI arguments and per-directory files
cannot enable it because ticket integrations use the operator's credentials.
This is disabled by default and applies to top-level /ask and ask_question, not inline /ask_line questions.
It uses the same ticket integrations, credentials, reference formats,
access checks and fetch limits as /review and /describe. Tickets are discovered from the PR/MR metadata;
links written only in the question are not additional ticket sources. This option is independent ofpr_reviewer.require_ticket_analysis_review.
Ticket integrations use the operator's configured access policy, not the asker's personal ticket credentials.
For Jira, the host-controlled jira.project_keys allowlist still applies ([] disables lookups);
configure only projects whose ticket content may appear in PR answers.
Ticket content is fetched once per command, after an analyzable diff fits. It adds API reads and input tokens
when enabled and uses the existing model request. Unavailable tickets are skipped. Each model attempt includes only
whole ticket records that fit after the existing question, conversation history and selected diff, so ticket
context does not displace code already selected for the answer. Large tickets may be omitted, including all
tickets when there is no room. The usual diff-based answer remains available in that case.
Configuration options
General options
| ask_heading | Plain-text heading for top-level /ask answers. The default is Ask.
Markdown renderers escape punctuation to keep the surrounding formatting and ❓ emoji fixed,
while plain-text converters publish the configured text without escape characters.
This does not affect /ask_line replies or the Answer section heading. |
| --- | --- |
| extra_instructions | Optional extra instructions to the command. For example: "Do not answer questions that ask to rate PR quality on a scale of 1 to 10. Instead, tell the user this type of question is not allowed." |
| enable_help_text | If set to true, the command will display a help text in the comment. Default is false. |
| use_conversation_history | If set to true, the command will use the conversation history from the same thread when answering questions on specific code lines (GitHub, GitLab, and Azure DevOps) or threaded top-level questions (Azure DevOps only). Default is true. |
| use_ticket_context | Include linked ticket content in top-level questions using the remaining prompt budget. Default is false. See Linked ticket context. |
Example usage in a configuration file:
[pr_questions]
ask_heading = "Architecture Question"
extra_instructions = "Do not answer questions that ask to rate PR quality on a scale of 1 to 10."The heading above renders as ### **Architecture Question** ❓.
Example usage in a PR comment:
/ask "What does this change do?" --pr_questions.extra_instructions="Answer in one short paragraph."Docs Commands Describe (`docs/docs/commands/describe.md`)
title: "Describe" sidebar_position: 2
Overview
Generate a PR title, type, summary, code walkthrough and labels.
The command can be triggered automatically every time a new PR is opened, or it can be invoked manually by commenting on any PR:
/describeExample usage
Manual triggering
Invoke the command manually by commenting /describe on any PR:
After ~30 seconds, the command will generate a description for the PR:
While a large PR's chunks run, the temporary Preparing PR description... comment is rewritten in place, for example Preparing PR description... analyzed 2 of 3 chunks; once every chunk has settled, , 1 chunk failed is added if a chunk gave up. This needs config.publish_output_progress and a provider that can edit and remove comments; single-chunk runs keep the plain placeholder.
If you want to edit configurations, add the relevant ones to the command:
/describe --pr_description.some_config1=... --pr_description.some_config2=...From the CLI, save the generated description and token usage as JSON for a later CI step:
pr-agent --pr_url https://github.com/org/repo/pull/123 --json-output describe.json describeThe JSON file is written after the description is assembled. Place --json-output before describe or describe_pr; it works with --pr_url or with plain-diff input (--stdin or --diff-file).
Automatic triggering
To run the describe automatically when a PR is opened, define in a configuration file:
[github_app]
pr_commands = [
"/describe",
...
]
[pr_description]
publish_labels = true
...- The
pr_commandslists commands that will be executed automatically when a PR is opened. - The
[pr_description]section contains the configurations for thedescribecommand you want to edit (if any).
File walkthrough summaries
On providers that support the HTML walkthrough, short file summaries appear on a new line after the filename.
When detailed changes are available, expanding the file entry reveals them while the short summary stays visible when collapsed.
GitLab descriptions no longer use description-list indentation for these summaries.
The description reader can extract file summaries from both the current and legacy walkthrough formats.
If separate PR-Agent installations generate walkthroughs and reuse their file summaries (for example, /describe and /review), upgrade them together; older readers cannot extract file summaries from the new format.
Preserving the original user description
By default, PR-Agent tries to preserve your original PR description by placing it above the generated content.
This requires including your description during the initial PR creation.
"PR-Agent removed the original description from the PR. Why"?
From our experience, there are two possible reasons:
If you edit the description while the automated command is running, a race condition may occur, potentially causing your original description to be lost. Hence, create a description before launching the PR.
When updating a description previously generated by PR-Agent,
/describepreserves text after the first recognized### **User description**heading until the next recognized boundary heading, trimming surrounding whitespace and a trailing___. If no boundary heading follows, it stops at the first___substring, or at the end if none is present, and trims surrounding whitespace. If the generated description has no recognized### **User description**heading, add that heading before your manual text; otherwise that text can be lost on the next body update.Boundary headings are lines starting with
### **PR type**,### **PR description**,### **PR labels**,### **Type**,### **Description**,### **Labels**, or### 🤖 Generated by PR Agent, matched case-insensitively outside fenced code blocks. Manual headings with these prefixes also end preservation, even if more text follows the prefix. Keep manual edits inside these boundaries; edits to generated sections are replaced.
Flowchart Support {#sequence-diagram-support}
The /describe command includes a Mermaid flowchart summarizing the main PR changes on providers that support gfm_markdown.
This option is enabled by default via the pr_description.enable_pr_diagram param.
The direction of the diagram adapts to its shape. A diagram whose longest chain of nodes exceeds pr_description.pr_diagram_direction_threshold is drawn top-down rather than left-to-right, so that wide diagrams are not scaled down until they become unreadable. Set pr_description.pr_diagram_direction to LR or TD to pin the direction instead.
Configuration options
The descriptions below explain each option's behavior. See the relevant sections inconfiguration.toml
for the authoritative default values.
Possible configurations
| publish_labels | If set to true, the command will publish labels to the PR. |
|---|---|
| publish_description_as_comment | If set to true, the command will publish the description as a comment to the PR. If false, it will overwrite the original description. |
| publish_description_as_comment_persistent | If set to true and publish_description_as_comment is true, the command will publish the description as a persistent comment to the PR. |
| add_original_user_description | If set to true, the command will add the original user description to the generated description. |
| generate_ai_title | If set to true, the command will also generate an AI title for the PR. |
| extra_instructions | Optional extra instructions to the command. For example: "focus on the changes in the file X. Ignore change in ..." |
| enable_pr_type | If set to false, it will not show the PR type as a text value in the description content. |
| enable_pr_description | If set to false, the AI-generated summary section will not be requested from the model, nor shown in the description content. The other sections (diagram, changes walkthrough) are unaffected. |
| final_update_message | If set to true, it will add a comment message PR Description updated to latest commit... after finishing calling /describe. |
| enable_semantic_files_types | If set to true, "Changes walkthrough" section will be generated. |
| file_table_collapsible_open_by_default | Controls whether the file list in the "Changes walkthrough" section is initially open or closed. |
| collapsible_file_list | If set to true, the file list in the "Changes walkthrough" section will be collapsible. If set to "adaptive", the file list will be collapsible only when the number of files exceeds collapsible_file_list_threshold. |
| enable_large_pr_handling | If set to true, in case of a large PR the command will make several calls to the AI and combine them to be able to cover more files. |
| enable_help_text | If set to true, the command will display a help text in the comment. |
| enable_pr_diagram | If set to true, the command will generate a Mermaid flowchart summarizing the main pull request changes. This field remains empty if not applicable. |
| pr_diagram_direction | Direction of the generated Mermaid flowchart: adaptive, LR or TD. With adaptive, the direction is chosen from the shape of the diagram. |
| pr_diagram_direction_threshold | With adaptive direction, a diagram whose longest chain exceeds this many nodes is drawn top-down instead of left-to-right. |
Markers template
To enable markers, set pr_description.use_description_markers=true.
Markers enable to easily integrate user's content and auto-generated content, with a template-like mechanism.
For example, if the PR original description was:
User content...
## PR Type:
pr_agent:type
## PR Description:
pr_agent:summary
## PR Walkthrough:
pr_agent:walkthrough
## PR Diagram:
pr_agent:diagramThe marker pr_agent:type will be replaced with the PR type, pr_agent:summary will be replaced with the PR summary, pr_agent:walkthrough will be replaced with the PR walkthrough, and pr_agent:diagram will be replaced with the flowchart (if enabled).
becomes
Configuration params:
use_description_markers: if set to true, the command will use markers template. It replaces every marker of the formpr_agent:marker_namewith the relevant content. Default is false.include_generated_by_header: only applies whenuse_description_markersis true. If true (default), the command adds a 'Generated by PR Agent at ...' header to automatic content when the provider supplies a head commit SHA, otherwise the header is 'Generated by PR Agent' (or usesconfig.bot_display_namewhen configured). If false, no header is added.diagram: if present as a marker, will be replaced by the PR flowchart (if enabled).
Custom labels
The default labels of the describe command are quite generic, since they are meant to be used in any repo: [Bug fix, Tests, Enhancement, Documentation, Other].
You can define custom labels that are relevant for your repo and use cases.
Custom labels can be defined in the PR-Agent host configuration, or directly in the repo's
labels page. The host configuration options cannot be set from
the repository's .pr_agent.toml or comment arguments.
Make sure to provide proper title, and a detailed and well-phrased description for each label, so the command will know when to suggest it.
Each label description should be a conditional statement, that indicates if to add the label to the PR or not, according to the PR content.
Auto-remove custom label when no longer relevant
If the custom label is no longer relevant, it will be automatically removed from the PR by running the generate_labels command or the describe command.
Handle custom labels from a configuration file
Example for a custom labels configuration setup in the PR-Agent host configuration:
[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"
...Handle custom labels from the Repo's labels page
You can also control the custom labels that will be suggested by the describe command from the repo's labels page:
- GitHub : go to
https://github.com/{owner}/{repo}/labels(or click on the "Labels" tab in the issues or PRs page) - GitLab : go to
https://gitlab.com/{owner}/{repo}/-/labels(or click on "Manage" -> "Labels" on the left menu)
Now add/edit the custom labels. they should be formatted as follows:
- Label name: The name of the custom label.
- Description: Start the description of with prefix
pr_agent:, for example:pr_agent: Description of when AI should suggest this label.
Examples for custom labels:
Main topic:performance- pr_agent:The main topic of this PR is performanceNew endpoint- pr_agent:A new endpoint was added in this PRSQL query- pr_agent:A new SQL query was added in this PRDockerfile changes- pr_agent:The PR contains changes in the Dockerfile- ...
The description should be comprehensive and detailed, indicating when to add the desired label. For example:
Usage Tips
:::tip[Automation]
When you first install PR-Agent app, the default mode for the describe command is:
pr_commands = ["/describe", ...]meaning the describe command will run automatically on every PR, with the default configurations.
:::
Markers are an alternative way to control the generated description, to give maximal control to the user. If you set:
textpr_commands = ["/describe --pr_description.use_description_markers=true", ...]the command will replace every marker of the form
pr_agent:marker_namein the PR description with the relevant content, wheremarker_nameis one of the following:type: the PR type.summary: the PR summary.walkthrough: the PR walkthrough.
Note that when markers are enabled, if the original PR description does not contain any markers, the command will not alter the description at all.
Docs Commands Generate Labels (`docs/docs/commands/generate_labels.md`)
title: "Generate Labels" sidebar_position: 7
Overview
The generate_labels command scans the PR code changes and generates custom labels for the PR based on the content and context of the changes.
It can be invoked manually by commenting on any PR:
/generate_labelsExample usage
Invoke the command manually by commenting /generate_labels on any PR.
The command will analyze the PR and add appropriate labels.
For local or CI workflows that need label suggestions without a hosting-provider token,
pass a unified diff and write the filtered labels to a JSON artifact:
python -m pr_agent.cli --diff-file changes.diff --json-output labels.json generate_labelsThe JSON result contains a labels list and a usage object (empty when token usage
is unavailable). Only model-generated labels that pass the existing allowlist are included;
labels already on a hosted PR are not included. A PR without analyzable changes produces
an empty list. This option does not change the normal label publication behavior.
Check the command's exit status before consuming the artifact: a failed run does not delete a previous JSON file.
Configuration options
The generate_labels command uses configurations from the [pr_description] section for custom labels.
Enabling custom labels
To use custom labels, you need to enable them in the configuration:
Set these options in the PR-Agent host configuration. Repository .pr_agent.toml files and comment arguments cannot
change them.
[config]
enable_custom_labels = trueDefining custom labels
You can define your own custom labels in the [custom_labels] section. See the custom_labels.toml file for examples.
Example configuration:
[custom_labels."Bug fix"]
description = "A fix for a bug in the codebase"
[custom_labels."Feature"]
description = "A new feature or enhancement"
[custom_labels."Documentation"]
description = "Documentation changes only"
[custom_labels."Tests"]
description = "Adding or modifying tests"
[custom_labels."Refactoring"]
description = "Code refactoring without functional changes"How labels are applied
- The command analyzes the PR diff and commit messages
- It uses AI to determine which labels best match the PR content
- Labels are automatically applied to the PR (if the git provider supports it)
- If labels cannot be applied directly, they are published as a comment
Both /generate_labels and /describe filter model-generated labels before publishing.
The allowed set contains the built-in PR types (Bug fix, Tests, Enhancement,Documentation, Other) plus the configured custom label names when custom labels
are enabled. With custom labels enabled but no custom set configured, the default
set also includes Bug fix with tests. Matching ignores case, and unknown generated
labels are dropped with a warning. Existing human-added labels are preserved and
are not restricted by this filter.
Prompt enum keys such as bug_fix and RELEASE_READY are resolved to their
allowed display names, ignoring case. If a nonempty model response contains only
rejected labels, /generate_labels leaves the current labels unchanged. An
explicit labels: [] response retains the existing behavior of clearing old
bot-owned labels while preserving human-added labels.
If the current labels cannot be read, /generate_labels skips publication and
records the command as failed. A known provider failure while publishing labels
also marks the command as failed. With config.propagate_command_errors = true, these
failures raise an error after temporary-comment cleanup.
A successful provider acknowledgement means its label operation completed normally;
it does not verify the final remote label set. Providers apply labels differently,
and a failure can leave some changes applied. The command does not retry or roll
back those changes. Labels generated by /describe and /review remain auxiliary
to their primary output.
Comparison with `/describe` labels
The /describe command also generates labels as part of its output. The key differences are:
| Feature | /generate_labels |
/describe |
|---|---|---|
| Purpose | Dedicated label generation | Full PR description with labels |
| Output | Labels only | Title, summary, walkthrough, and labels |
| Custom labels | ✅ Supported | ✅ Supported |
| Use case | When you only need labels | When you want a complete PR description |
Tips
- Use custom labels that match your team's workflow and labeling conventions
- Combine with automation to automatically label PRs when they are opened
- Review the generated labels and adjust custom label descriptions if the AI consistently misclassifies PRs
Docs Commands Help (`docs/docs/commands/help.md`)
title: "Help" sidebar_position: 9
Overview
The help command provides a list of all the available commands and their descriptions.
Invoke commands by posting their slash commands. The checkboxes shown on GitHub do not execute commands when checked.
On Bitbucket Cloud, Gerrit and CodeCommit, /help without a question displays an unsupported-format notice instead of the command list. /help <question> can still answer questions from the documentation.
Local mode only displays the unsupported-format notice for /help. Plain-diff mode supports the command list, but /help <question> is currently unavailable in both local and plain-diff modes.
It can be invoked manually by commenting on any PR:
/helpCalling /help without a question displays the command list, where supported, without initializing an AI handler,
so errors during that initialization do not block the list./help <question> still uses the configured AI model.
When answering a question, the command tries the configured fallback models if a model returns an invalid response format
or an empty answer. If all attempts fail, no answer is published and the command records a failure.
A response that reports no relevant information is still shown normally.
Example usage
Invoke the help command by commenting on a PR with:
Response will include a list of available commands:
Docs Commands Help Docs (`docs/docs/commands/help_docs.md`)
title: "Help Docs" sidebar_position: 10
:::warning[/help_docs is currently disabled]
As of v0.36.1, the /help_docs command is temporarily disabled as a mitigation for a
credential-exposure vulnerability (#2445):
the command accepted an untrusted runtime override of its git clone target, and the clone-URL
host validation only checked substring containment, so a host that merely contained the
allowed host could receive the git provider token.
The command is not registered in PRAgent, so invoking it has no effect on any provider. The
page below documents the command as it behaves once it is re-enabled.
:::
Overview
The help_docs command can answer a free-text question based on a git documentation folder.
It can be invoked manually by commenting on any PR or Issue:
/help_docs "..."Or configured to be triggered automatically when a new issue is opened.
The command assumes by default that the documentation is located in the root of the repository, at /docs folder.
However, this can be customized by setting the docs_path configuration option:
[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 overwrittenSee more configuration options in the Configuration options section.
Example usage
Asking a question about another repository
Response:
Run automatically when a new issue is opened
You can configure PR-Agent to run help_docs automatically on any newly created issue.
This can be useful, for example, for providing immediate feedback to users who open issues with questions on open-source projects with extensive documentation.
Here's how:
Follow the steps depicted under Run as a GitHub Action to create a new workflow, such as:
.github/workflows/help_docs.yml:Edit your yaml file to the following:
text
/* Detailed source-code truncated for AI context efficiency. */
3. Following completion of the remaining steps (such as adding secrets and relevant configurations, such as `repo_url` and `docs_path`) merge this change to your main branch.
When a new issue is opened, you should see a comment from `github-actions` bot with an auto response, assuming the question is related to the documentation of the repository.
---
## Configuration options
Under the section `pr_help_docs`, the [configuration file](https://github.com/the-pr-agent/pr-agent/blob/main/pr_agent/settings/configuration.toml) contains options to customize the 'help docs' command:
- `repo_url`: If not overwritten, will use the repo from where the context came from (issue or PR), otherwise - use the given repo as context.
- `repo_default_branch`: The branch to use in case repo_url overwritten, otherwise - has no effect.
- `docs_path`: Relative path from root of repository (either the one this PR has been issued for, or above repo url).
- `exclude_root_readme`: Whether or not to exclude the root README file for querying the model.
- `supported_doc_exts` : Which file extensions should be included for the purpose of querying the model.
---
---
### Docs Commands Improve (`docs/docs/commands/improve.mdx`)
---
title: "Improve"
sidebar_position: 4
---
## Overview
Runs /review, whose findings can carry committable code fixes.
:::note
`/improve` and `/improve_code` run [`/review`](./review.md) as of 0.51, with a one-line notice under the review heading.
A command list that names both runs a single review. Findings that carry a fix are described in
[Fixes and committable suggestions](./review.md#fixes-and-committable-suggestions).
:::
---
### Docs Commands Review (`docs/docs/commands/review.md`)
---
title: "Review"
sidebar_position: 3
---
## Overview
Generate a PR review with feedback on possible issues, security concerns, tests and review effort.
The command can be triggered automatically every time a new PR is [opened](../usage-guide/automations_and_usage.md#github-app-automatic-commands-when-a-new-pr-is-opened), or can be invoked manually by commenting on any PR:/review
Note that the main purpose of the `review` command is to provide the **PR reviewer** with useful feedback and insights. Findings can also carry a fix, which GitHub and the other supported providers offer as a [committable suggestion](#fixes-and-committable-suggestions).
(Read more about the different personas in the PR process and how PR-Agent aims to assist them in our [blog](https://www.qodo.ai/blog/understanding-the-challenges-and-pain-points-of-the-pull-request-cycle/))
:::note
`/improve` runs `/review` as of 0.51. See [Improve](./improve.mdx).
:::
## Example usage
### Manual triggering
Invoke the command manually by commenting `/review` on any PR:
After ~30 seconds, the command will generate a review for the PR:
If you want to edit [configurations](#configuration-options), add the relevant ones to the command:/review --pr_reviewer.some_config1=... --pr_reviewer.some_config2=...
From the CLI, save the parsed review and token usage as JSON for a later CI step:
```bash
pr-agent --pr_url https://github.com/org/repo/pull/123 --json-output review.json reviewThe JSON file is written after the review completes. Place --json-output before review or review_pr.
Its coverage object lists files omitted by the token budget or chunk-call limit, as well as
deletions represented only by filename notices (files_not_reviewed), and those whose patches
were clipped to fit the token budget (files_partially_reviewed).
Files excluded by file-type filtering are not included in these coverage lists.
Filename notices are optional context, not reviewed source; filtered-file notices take priority
when both kinds compete for the remaining request budget.
Filename notices supplement source changes and do not trigger a model call on their own.
A deletion-only PR without source changes to analyze is skipped, even when deletion patches are available.
The JSON includes the full lists even when the Markdown footer summarizes them.
It also includes total_chunks and failed_chunks for the final analysis plan, after fallback recovery.
These count analysis chunks, not model requests or retry attempts. A nonzero failed_chunks means that the
review is partial even if both file lists are empty; findings from successful chunks are retained.
Automatic triggering
To run the review automatically when a PR is opened, define in a configuration file:
[github_app]
pr_commands = [
"/review",
...
]
[pr_reviewer]
extra_instructions = "..."
...- The
pr_commandslists commands that will be executed automatically when a PR is opened. - The
[pr_reviewer]section contains the configurations for thereviewcommand you want to edit (if any).
Configuration options
The descriptions below explain each option's behavior. See the relevant sections inconfiguration.toml
for the authoritative default values.
General options
| persistent_comment | If set to true, the review comment will be persistent, meaning that every new review request will edit the previous one. |
|---|---|
| per_commit_review | If set to true, each commit of the PR is reviewed on its own diff and commit message, and one review comment is published per commit. See Reviewing each commit separately. It can't be turned on from a command argument, only from a configuration file or environment variable. Default is false. |
| max_commits_per_review | Maximum number of commits per_commit_review reviews one by one. When more commits than that are not reviewed yet, the whole PR is reviewed in one review instead, with a notice. It can't be set from a command argument or a per directory configuration file. Default is 0, no limit. |
| publish_review_failure_comment | Set to false to suppress the "Failed to review PR" comment, including when a persistent review comment |
cannot be updated. Successful review output and the command's failure status are unchanged. Default is true.
On GitHub, GitLab, and Azure DevOps, when the comment author can be verified, repeated failures update one
comment instead of adding another, and the next review that completes removes it. If the provider rejects
that edit or removal, the earlier comment stays and no other is added. A review in which some chunks failed
keeps it; files left out for the token budget do not. With
`gitlab.reply_to_trigger_comment`, each failure still replies to its own command, and a persistent
review comment that cannot be updated gets a comment of its own each time. Those are removed the same way,
and so are the failure comments of earlier versions. || publish_error_details | If set to true, a failed manual review comment includes a deterministic, sanitized failure reason for known
provider and runtime errors. The failure formatter does not call an AI model, never publishes raw exception
text, and falls back to a generic internal-error message. Default is false. |
| review_heading | Visible base heading for review comments, without the Markdown prefix or incremental label.
For example, review_heading = "Guideline Compliance Check" renders
## Guideline Compliance Check 🔍 for a full review and
## Incremental Guideline Compliance Check 🔍 for an incremental review.
On GitHub, GitLab, Azure DevOps, and Bitbucket Cloud, changing this value updates the same
persistent review comment; it does not create a separate review channel. |
| persistent_finding_state | If set to true, PR-Agent persists structured review finding state across complete review runs, so findings can be resolved and reopened. Resolved findings retain the original Markdown formatting of their description. Incremental and partial reviews do not resolve absent findings. Default is true. |
| max_previous_findings_chars | Character budget for the findings stored by earlier reviews (requires persistent_finding_state). They are given to the model so it repeats a still-valid finding with its earlier wording instead of re-raising it reworded, and does not re-raise a resolved one unless the code reintroduces it. On GitHub and GitLab, an inline key-issue thread that someone other than PR-Agent resolved is given as dismissed, with its last reply, so the model does not re-raise it unless the code makes it worse. Set to 0 to disable. Default is 8000.
On Azure DevOps, verified PR-Agent inline key issues with wontFix or byDesign
are also passed as dismissed when the status differs from azure_devops.default_comment_status.
A matching default stays an ordinary prior finding. This infers a human decision; Azure does not identify
the status-changing actor here, and the current default may differ from the default used at creation.
PR-Agent resolves its posting identity through Azure DevOps. Set
azure_devops_server.agent_identity to override it or when automatic lookup is unavailable. |
| final_update_message | When set to true, updating a persistent review comment during online commenting will automatically add a short comment with a link to the updated review in the pull request. |
| extra_instructions | Optional extra instructions to the command. For example: "focus on the changes in the file X. Ignore change in ...". |
| enable_help_text | If set to true, the command will display a help text in the comment. |
| enable_review_coverage_footer | If set to true, the command will display a review coverage footer when source changes were not reviewed or were only partially reviewed, including deleted files represented by filename notices. |
| enable_large_pr_chunking | If set to true, and the token budget leaves files out of the review, the diff is split into chunks, each chunk is reviewed separately, and the per-chunk results are merged into one review. See Reviewing a PR that does not fit in one call. Default is false. |
| max_number_of_calls | Maximum number of chunk review calls, used only when enable_large_pr_chunking is true. Default is 3. |
| num_max_findings | Maximum number of returned findings. Default is 6. |
| inline_key_issues | If set to true (the default), each key issue is published as an inline comment where the provider supports verified inline-comment publication (GitHub, Bitbucket Cloud, Azure DevOps, GitLab, Gitea). A finding leaves the review summary when a matching comment exists or the provider accepts the new comment. Findings that cannot be anchored or published stay in the summary. A finding that carries a fix is published as a committable suggestion when pr_code_suggestions.committable_code_suggestions is true, the fix is at most ten lines and its existing_code matches the file at the finding's lines; otherwise the fix appears as a code block in the comment. |
| min_finding_confidence | When above 0, the model reports an integer confidence from 0 to 10 for each finding, shown in its header in the review summary (inline comments do not show it). Findings below this value are dropped before publishing, and in a chunked review they are dropped before the num_max_findings cut, so they cannot displace a more confident finding. A run that dropped findings does not mark earlier findings as resolved. A missing or out-of-range confidence is treated as absent: the finding is kept. A threshold outside 0-10 is treated as 0 (disabled). Default is 0: keep all findings, and the model is not asked for a confidence. |
Enable\disable specific sub-sections
| require_score_review | If set to true, the command will add a section that scores the PR. |
|---|---|
| require_tests_review | If set to true, the command will add a section that checks if the PR contains tests. |
| require_estimate_effort_to_review | If set to true, the command will add a section that estimates the effort needed to review the PR. |
| require_estimate_contribution_time_cost | If set to true, the command will add a section that estimates the time required for a senior developer to create and submit such changes. |
| require_can_be_split_review | If set to true, the command will add a section that checks if the PR contains several themes, and can be split into smaller PRs. |
| require_security_review | If set to true, the command will add a section that checks if the PR contains a possible security or vulnerability issue. |
| require_todo_scan | If set to true, the command will add a section that lists TODO comments found in the PR code changes. |
| require_ticket_analysis_review | If set to true and ticket context is available, the command adds a ticket-compliance section to the review comment |
that checks whether the PR fulfills the ticket requirements. Supported sources include GitHub and GitLab issues,
linked Azure DevOps work items, Jira Cloud tickets, and Asana tasks. || require_risk_assessment | If set to true, the command will add a section that rates the overall risk of the PR as low, medium or high. |
| require_merge_recommendation | If set to true, the command publishes a recommendation computed from deterministic checks. Only passing checks
allow no_concerns_found; needs_review means a check did not pass or could not be evaluated, and changes_required
reflects a model veto. The value reports the review's findings, not a guarantee about the code. See
Merge recommendation. |
| publish_merge_recommendation_status | If set to true with require_merge_recommendation, publishes the verdict on the reviewed commit.
GitHub uses the PR Agent - Review check; GitLab uses a commit status. needs_review
publishes as neutral on GitHub and skipped on GitLab, so it does not block a merge; changes_required
publishes as a failure. |
| max_changed_lines | Host-only changed-line cap for no_concerns_found. A larger diff makes the recommendation
needs_review at best. The cap counts added and removed lines. |
| require_failure_modes | Off by default. If enabled, adds up to three concrete failure scenarios, each with what could break,
where, its trigger, how it could be detected, and whether a test or check in this PR covers it.
These scenarios guide human review; they do not gate merging or prove that the PR is safe. |
| require_artifact_findings | Off by default, and only active when a CI artifact reaches /review.
If enabled, adds a "CI artifact findings" section with up to five neutral facts from the artifact: destroyed or replaced
resources, failed jobs (including allowed-to-fail ones), failed tests, vulnerabilities and notable warnings. Each fact
carries a short quote from the artifact; a quote that cannot be found in the artifact is marked, and credentials in
facts and quotes are redacted. The section reports what the artifact shows and leaves the decision to the reviewer.
Host configuration only: a repository settings file or comment cannot set it. |
| require_priority_files | If set to true, the command will add a section listing the files a human reviewer should inspect first. |
| structural_reach_input_file | Path to a JSON file with structural reach facts, written by a build-graph tool earlier in CI. When the file
exists, adds a deterministic change-risk row (Low, Moderate, High or Critical) with no model call. Relative to
GITHUB_WORKSPACE when that is set, otherwise to the working directory. Host configuration only: a
repository settings file or a comment cannot set it, because the file is read from the host. See
Structural reach. |
| enable_risk_checks | If set to true, deterministically scans diff files and unfiltered PR files for sensitive paths, destructive SQL,
cache flushes, and authentication/secrets patterns without making model calls. Findings are rendered as a risk-checks
row in the review summary table. When no findings are detected, nothing is added. Default is true. See
Deterministic risk checks. |
| sensitive_paths | List of glob patterns identifying files considered sensitive (such as CI workflows, package manifests, lockfiles,
migrations, and infrastructure configurations). Changes to matching files flag a deterministic review risk finding.
Default includes common CI/CD, package manager, container, infrastructure, and migration paths. |
| extra_risky_shapes | List of custom regular expression patterns to scan within added and removed lines in diff hunks. Patterns matching a
line flag a deterministic risk finding. Patterns longer than 200 characters, or with a quantified group that holds a
nested quantifier or an alternation (such as (a+)+ or (a b)+), are skipped with a logged warning. Host
configuration only: a repository settings file or comment cannot set it. Default is empty. |
Adding PR labels
You can enable\disable the review command to add specific labels to the PR:
| enable_review_labels_security | If set to true, the command will publish a 'Possible security concern' label if it detects a security issue. |
|---|---|
| enable_review_labels_effort | If set to true, the command will publish a 'Review effort x/5' label (1–5 scale). Existing effort labels are kept when this option or effort estimation is disabled, or when the review has no valid replacement estimate. Security labels follow their own settings. |
Usage Tips
General guidelines
:::tip
The review command provides a collection of configurable feedbacks about a PR.
It is recommended to review the Configuration options section, and choose the relevant options for your use case.
Some of the features that are disabled by default are quite useful, and should be considered for enabling. For example:require_score_review, and more.
On the other hand, if you find one of the enabled features to be irrelevant for your use case, disable it. No default configuration can fit all use cases.
:::
Automation
:::tip
When you first install PR-Agent app, the default mode for the review command is:
pr_commands = ["/review", ...]Meaning the review command will run automatically on every PR, without any additional configurations.
Edit this field to enable/disable the command, or to change the configurations used.
:::
Auto-generated PR labels by the Review Command
:::tip
The review command can automatically add labels to your Pull Requests:
Possible security concern: This label is applied if the command detects a potential security vulnerability in the PR's code. This feedback is controlled by the 'enable_review_labels_security' flag (default is true).Review effort 3/5: This label estimates the effort required to review the PR on a scale of 1 to 5. This feedback is controlled by the 'enable_review_labels_effort' flag (default is true).
The command matches these label names and earlier 1–5 effort formats case-insensitively.
Other labels, such as Review effort::high, are left unchanged.
Ticket compliance is reported in the review comment, not as a PR label. It is controlled bypr_reviewer.require_ticket_analysis_review and requires available ticket context. The command does not add
ticket-compliance labels or a "No ticket found" label. See
Fetching ticket context for linking and authentication details.
:::
Auto-blocking PRs from being merged based on the generated labels
:::tip
You can configure a CI/CD Action to prevent merging PRs with specific labels. For example, implement a dedicated GitHub Action.
This approach helps ensure PRs with potential security issues will not be merged without further review.
Since AI may make mistakes or lack complete context, use this feature judiciously. For flexibility, users with appropriate permissions can remove generated labels when necessary. When a label is removed, this action will be automatically documented in the PR discussion, clearly indicating it was a deliberate override by an authorized user to allow the merge.
:::
Extra instructions
:::tip
Extra instructions are important.
The review command can be configured with extra instructions, which can be used to guide the model to a feedback tailored to the needs of your project.
Be specific, clear, and concise in the instructions. With extra instructions, you are the prompter. Specify the relevant sub-command, and the relevant aspects of the PR that you want to emphasize.
Examples of extra instructions:
[pr_reviewer]
extra_instructions="""\
In the code feedback section, emphasize the following:
- Does the code logic cover relevant edge cases?
- Is the code logic clear and easy to understand?
- Is the code logic efficient?
...
"""Use triple quotes to write multi-line instructions. Use bullet points to make the instructions more readable.
:::
Fixes and committable suggestions
A finding can carry a fix: the model adds existing_code (the lines it wants to change, copied from the file) andimproved_code (their replacement) when a concrete change resolves the issue. A finding without a clear fix has neither field.
When inline_key_issues is on (the default) and the provider can verify inline comments (GitHub, Bitbucket Cloud, Azure DevOps,
GitLab, Gitea), each finding is posted as an inline comment. If pr_code_suggestions.committable_code_suggestions is true andexisting_code matches the file at the finding's lines, the fix is posted as a committable suggestion that you can apply from the
PR page. Otherwise the fix is shown as a text block in the comment. A finding that is not posted inline (the provider cannot verify
inline comments, inline_key_issues is off, or publishing failed) stays in the review summary, and its fix appears there as a text
block. Findings are capped by pr_reviewer.num_max_findings (6 by default), and chunked reviews keep the same cap.
Three pr_code_suggestions settings are honoured: committable_code_suggestions, extra_instructions
(added to the review's extra instructions when it differs from pr_reviewer.extra_instructions) andsuggestions_heading (the base heading for code-suggestion comments). Other pr_code_suggestions keys have no effect.
/review --pr_code_suggestions.committable_code_suggestions=trueReviewing each commit separately
:::tip
Projects that keep one logical change per commit can ask for a review of every commit instead of the combined PR diff,
in a configuration file:
[pr_reviewer]
per_commit_review = trueEach commit is reviewed against its own parent, with its commit message in the prompt, and gets its own
incremental review comment that names and links the commit. These comments are never the persistent
review comment, and they do not change the review labels.
Each run reviews only the commits of the PR that were not reviewed yet, so -i is not needed in pr_commands orpush_commands, and the first run reviews every commit. A commit is identified by a fingerprint of its own changes
(file names and patch lines, without line numbers), and counts as reviewed once its review succeeds: the fingerprint
is kept in a hidden marker in the commit's review comment or, when no comment is published for it, in one record
comment that is edited in place. A commit whose review failed is reviewed again on the next run; automatic runs stop
retrying it after 3 failed attempts, while a manual /review always retries.minimal_commits_for_incremental_review and minimal_minutes_for_incremental_review do not apply to per commit
review, since each run picks the commits to review from these markers instead of the -i thresholds.
The commit list is read from the git provider on every run, so after a force push the review follows the rewritten
history: a commit that was rebased without changing its own patch is not reviewed again, a commit that was amended or
had fixups folded into it (for example with git rebase --autosquash) is reviewed again, and fixup commits that no
longer exist are not reviewed. Markers count only in comments PR-Agent wrote; when the git provider cannot confirm
that, the whole PR is reviewed in one review with a notice instead.
On GitLab, a commit with a collapsed, too large or rename only file is reviewed again after a rebase, since its
fingerprint includes its SHA.
Set publish_output_no_suggestions = false in the [pr_reviewer] section
(--pr_reviewer.publish_output_no_suggestions=false on the command line) to skip the comment of a commit where
nothing was found.
With inline_key_issues = true, each finding is published as an inline comment on the commit it was found in,
anchored to that commit's own diff, so GitHub and GitLab show it as outdated once a later commit changes those lines.
A finding that cannot be anchored there, for example because its line is outside that commit's diff or the provider
rejects it, stays in that commit's review comment instead of being moved to a nearby line.
Merge commits, empty commits and the root commit of a history have no diff of their own and are skipped. A commit that
fails to review is reported like a failed review and does not stop the remaining commits. Every reviewed commit is a
separate model call, so the first review of a PR with many commits costs accordingly; later runs review only the new
commits.
Hosts that want to bound that cost can set max_commits_per_review (default 0, no limit): when more commits than that
are not reviewed yet, the whole PR is reviewed in one review with a notice, and its commits count as reviewed.
The markers live only in PR-Agent's own comments, so if those comments are removed, the next run reviews every commit
of the PR again, unless max_commits_per_review is set and the PR has more commits than that, in which case the whole
PR gets one review.
Both settings belong to the operator, so a command argument such as --pr_reviewer.per_commit_review=true is
rejected.
Each commit's comment shows its own run details, while the --json-output file and the GitHub Action review output
describe the last reviewed commit only.
Per commit review is available on GitHub and GitLab. Other git providers fall back to a regular review of the whole PR.
GitHub lists at most 250 commits of a PR, so a PR with more commits than that is also reviewed as a whole, with a
notice explaining why.
:::
Reviewing a PR that does not fit in one call
:::tip
When a PR diff is larger than the model's token budget, the review command drops whole files
until the diff fits, and lists the dropped files in the review coverage footer.
Setting enable_large_pr_chunking = true changes what happens next: the diff is split into up
to max_number_of_calls chunks, each chunk is reviewed on its own, and the answers are merged
into a single review that says how many chunks it was built from. Files that do not fit even
after chunking are still listed in the coverage footer. Every chunk is a separate model call,
so a chunked review costs roughly max_number_of_calls times a normal one.
While the chunks run, the temporary Preparing review... comment is rewritten in place with the
number of chunks already analyzed, for example Preparing review... analyzed 2 of 3 chunks, plus... 1 chunk failed when a chunk gives up. The updates requireconfig.publish_output_progress and a provider that supports both editing and removing a
comment, so plain-diff runs keep the frozen placeholder. Automatic commands publish no progress
comment, but while github.publish_as_check_run is enabled their in-progress check run shows the
same chunk count. The comment stays
temporary and is still removed before the merged review is published. A fallback model restores
the placeholder before it starts, so the visible count never moves backward.
If a chunk fails or returns malformed output, successful chunks are retained and fallback
models retry only the pending work. Pending chunks can be split for a smaller model, within
the call limit; a larger model can also include previously omitted files. Chunks that still
exceed the model's budget are not sent to it.
If every fallback is exhausted, successful chunks are published as a partial review with a
failed-chunk coverage warning, even when publish_output_no_suggestions = false. Incomplete
reviews cannot resolve absent persistent findings. If no chunk succeeds, the review fails.
With config.propagate_command_errors = true, an exhausted fallback chain still signals failure
to the caller after publishing the partial review and removing the progress comment.
Optional run details list all models that contributed to the merged review.
Each chunk answers the same questions about a different part of the PR, so the answers are
merged field by field:
| Field | Merge rule |
|---|---|
key_issues_to_review |
Union over the chunks, dropping findings that repeat the same file, header and text |
security_concerns |
Every chunk that reported a concern is kept; "No" only when every chunk said no |
todo_sections, review_priority_files, can_be_split |
Union, de-duplicated, in chunk order (can_be_split keeps at most 3 sub-PRs) |
relevant_tests |
Yes if any chunk found tests |
score |
The lowest score any chunk gave |
risk_level, merge_recommendation |
The most conservative value any chunk gave |
failure_modes |
Concatenate valid cases in chunk order, dropping exact duplicates and keeping at most three |
estimated_effort_to_review_[1-5] |
The highest value any chunk gave |
contribution_time_cost_estimate |
The sum over the chunks, per case |
ticket_compliance_check |
One entry per ticket, with its bullet lists unioned across chunks |
When require_todo_scan is enabled, the TODO union includes both located findings and prose
summaries. Prose without a file location is shown as text without a source link.
The merged verdict is deliberately never less alarming than the worst chunk: a clean chunk
cannot raise a score, clear a security concern, or soften a risk level set by another chunk.
:::
Structural reach
:::tip
When structural_reach_input_file points at a file that exists, the review gets one row at the top that rates how
far a defect in the change could spread. The row is computed from that file, not by the model, so the same input
always gets the same rating.
🔗 Structural reach: Critical
Reach: 40 projects, cross-domain
Dependents: billing-api, payments-worker, web-app, admin-app, reports (+35 more)
Sensitivity: payments
Rating driven by sensitive domain (escalates regardless of size)Rating. Two facts from the input file set the band:
- Reach is the number of downstream projects a defect in the change can break. Only a build-graph tool knows
it. - Sensitivity flags changes to areas the repository marks as high-criticality, such as authentication,
payments or secrets. A one-line auth change outranks a wide styling sweep.
Reach is narrow up to 3 projects, moderate up to 25 and wide above that. The band then follows these rules:
| Condition | Band |
|---|---|
| Wide reach | At least Moderate |
| Cross-domain change | At least Moderate |
| Any sensitive domain | At least High |
| Sensitive domain with wide reach | Critical |
| Anything else | Low |
The row lists each factor and names the one that set the band. It also lists the first five names independents, in the order the producer wrote them.
The reach bands are defined for projects only. When reach_unit is modules or files, the row shows the count
and the dependents without a band, because no threshold separates a change to a shared utility from a real spread.
A cross-domain or sensitive change still gets a band from the rules above. The Reach line still shows the
number, but it does not affect the band.
Change size is not part of the rating, becauseestimated_effort_to_review_[1-5] already reflects it. That row and require_risk_assessment are the model's
judgement; this row adds the structural and sensitivity facts the model cannot see in the diff.
Input file. Any build-graph tool (Nx, Bazel, Gradle, Turborepo, and so on) can write the reach facts in an
earlier CI step, so pr-agent needs no adapter per tool. Point structural_reach_input_file at the file in host
configuration, for example the PR_REVIEWER__STRUCTURAL_REACH_INPUT_FILE environment variable. Every field is
optional:
{
"version": 1,
"reach": 12,
"reach_unit": "projects",
"dependents": ["billing-api", "web-app"],
"domains": ["billing", "web"],
"cross_domain": true,
"sensitive_domains": ["billing"]
}| Field | Type | Meaning |
|---|---|---|
version |
integer | Schema version. Only 1 is accepted. |
reach |
integer, 0 or more | Number of units affected by the change, including transitive dependents. Defaults to the length of dependents. |
reach_unit |
string | What reach counts: projects (the default), modules or files. Only projects gets a reach band. |
dependents |
list of strings | Names of the affected units, most relevant first. |
domains |
list of strings | Distinct domains or areas the affected projects belong to. |
cross_domain |
boolean | Whether the change spans more than one domain. |
sensitive_domains |
list of strings | Affected domains the repository treats as sensitive. |
Unknown fields are ignored. Strings are limited to 200 characters and the file to 1 MB.
Trust. The file is read from inside GITHUB_WORKSPACE (or the working directory), so in the GitHub Action a
checkout of the pull request could already contain a file at that path, written by the pull request's author.
Generate the file in the same job, right before the review step, and delete any existing copy first. Take the
project tags and graph configuration the producer reads from the base commit, not from the pull request. Treat the
band as advisory context for reviewers, never as a merge gate.
Example producer: Nx. nx show projects --affected lists every project the change affects, including
transitive dependents. This step writes them as dependents, and lists affected projects tagged sensitive assensitive_domains:
affected() { npx nx show projects --affected --base="$BASE_SHA" --head="$HEAD_SHA" --json "$@"; }
affected | jq --argjson sensitive "$(affected -p 'tag:sensitive')" \
'{version: 1, reach_unit: "projects", dependents: ., sensitive_domains: $sensitive}' > structural-reach.jsonThen set PR_REVIEWER__STRUCTURAL_REACH_INPUT_FILE=structural-reach.json for the review step. Another tool
needs only a query that lists the affected projects or packages.
Example producer: tree-sitter. For a repository without a build-graph tool,scripts/structural_reach_producer.py builds a reverse-import graph of the Python, TypeScript and JavaScript
files at the base commit and follows importers from the changed files. Test files are left out of reach and
domains, because counting them makes most changes to a shared module read wide. It writes reach_unit asmodules (directories) by default, so the row shows the count and the first dependents without a band. Run it as
a CI step before the review; it is not a pr-agent dependency:
pip install "tree-sitter-language-pack==1.22.1"
python scripts/structural_reach_producer.py --repo . --base "$BASE_SHA" --head "$HEAD_SHA" \
--unit module --out structural-reach.jsonOn this repository, the change merged in pull request 4420 gives:
🔗 Structural reach
Reach: 9 modules
Dependents: pr_agent/git_providers, pr_agent/commands, pr_agent/servers, pr_agent/algo, pr_agent/mosaico (+4 more)dependents is ordered by the number of affected files in each unit. The graph does not see imports built at
run time, files loaded by name such as settings, or dependencies declared only in a manifest, such as a sharedtsconfig package used through extends. In a monorepo with Nx, Turborepo or Bazel, use that tool instead.
Failure handling. The row never blocks a review. If the setting is empty, the input file is missing or does
not match the schema, or anything fails while computing the row, the review is published without it.
Sources.
- Beyer, B. et al. Site Reliability Engineering (Google, 2016), and the AWS Well-Architected Framework: blast
radius as the scope of impact of a change or failure. - OWASP guidance on sensitive functionality: authentication, session management, cryptography and payments.
:::
Deterministic risk checks
:::tip
When enable_risk_checks is enabled (the default), PR-Agent scans changed files and diff hunks for known risk patterns
without making model calls. Incremental and per-commit reviews scope unfiltered path checks to the active incremental
file set unless require_merge_recommendation is enabled. Findings are rendered as a dedicated row in the review table:
⚠️ Risk checks: 3 finding(s) detected
Sensitive paths (1): .github/workflows/deploy.yml
Risky shapes (1): `Privilege revocation` in db/migrations/002_revoke.sql
Deleted files (1): old_auth.pyWhen no findings are detected, the row is omitted completely so clean reviews stay uncluttered.
Checks performed.
- Sensitive paths: Flags changes to files matching glob patterns in
sensitive_paths. By default, this covers
CI/CD pipelines and local composite actions, package manager manifests and lockfiles, Dockerfiles, Terraform and
infrastructure configs, and database migrations. - Risky change shapes: Scans added and removed lines in diff hunks for destructive SQL (
DROP TABLE,ALTER ... RENAME,REVOKE ... ON/FROM,TRUNCATE), authentication and secrets keywords, cache invalidations, and any custom patterns
configured inextra_risky_shapes. Removed lines are also checked for removed function signatures (Python, JS/TS, Go,
Rust) and, in.toml,.yaml,.yml,.json,.iniand.envfiles, removed configuration defaults. Changes to
prompt files (*prompt*.toml,*prompt*.yaml, or files under a*prompts*/directory) are flagged as well. - Deleted files: Flags removed files.
Custom patterns. Additional regular expressions can be configured via extra_risky_shapes. Because regex execution
has security implications, extra_risky_shapes must be configured through host configuration (such as environment
variables or host settings) and cannot be overridden by repository .pr_agent.toml files. Each search with a custom
pattern has a 50 ms limit, and each custom pattern has 1 s in total per review. If a pattern exceeds either one,
PR-Agent logs a warning and skips that pattern for the rest of the review.
:::
Merge recommendation
When require_merge_recommendation is enabled, PR-Agent computes the published verdict from deterministic checks.
The model can only make the verdict more cautious: it can lower a clean verdict, or raise needs_review tochanges_required, but it cannot override a failed deterministic check.
Checks and sources
CI on reviewed head(deterministic): requires passing CI for the reviewed head. Unavailable CI status fails
closed.Head is current with its base(deterministic): requires the reviewed head to be current with its base for
reviewed files. Unavailable staleness status fails closed.Human authors(deterministic): requires all authors to be human. Bot/unlinked or unavailable author data fails
closed.No sensitive paths or risky changes(deterministic): requires no findings from deterministic risk checks
(sensitive_paths, risky diff shapes, deleted files). Unavailable risk-check data fails closed.Changed lines within cap(deterministic): requires total added/removed lines withinpr_reviewer.max_changed_lines. Unavailable line counts fail closed.Model merge recommendation(model, veto only): if the model returnsneeds_revieworchanges_required, the
verdict cannot beno_concerns_found.Model risk level(model, veto only): if the model returnsmediumorhighrisk, the verdict cannot beno_concerns_found.
no_concerns_found requires all deterministic checks to pass and no model veto. If any deterministic check cannot be
evaluated, the verdict fails closed. The review includes each check and its result.
Configuration and status publishing
pr_reviewer.sensitive_paths: glob patterns for files treated as sensitive by deterministic risk checks.
Host-only.pr_reviewer.max_changed_lines: host-only changed-line cap forno_concerns_found. Counts added and removed
lines.pr_reviewer.extra_risky_shapes: host-only custom regex patterns scanned in added and removed diff lines.publish_merge_recommendation_status: publishes the verdict for the exact reviewed head SHA. GitHub uses thePR Agent - Reviewcheck run; GitLab uses a commit status.
needs_review publishes as neutral on GitHub and skipped on GitLab, so it does not block merges by itself.changes_required publishes as failure/failed and blocks merges when that status is required. To require it, addPR Agent - Review as a required status/check in your GitHub branch protection rule or ruleset, or require the
PR-Agent commit status in your GitLab project's merge rules. A new commit has no PR-Agent verdict status until it is
reviewed.
The verdict scans the complete PR diff, including ignored paths and files already reviewed by an incremental review.
If the full diff or a trustworthy CI timestamp is unavailable, the verdict cannot be no_concerns_found.
Gated auto-approval
:::warning
Off by default and host-only (config.enable_auto_approval). An approval counts toward a protected branch's
required reviews, so enable it only where an automated approval of small, clean changes is acceptable. PR-Agent
never merges.
:::
When the host sets config.enable_auto_approval (for example CONFIG__ENABLE_AUTO_APPROVAL=true), /review on
GitHub and GitLab approves the exact commit it reviewed only when all of these hold:
- the computed merge recommendation is
no_concerns_found; - the model returned both a merge recommendation and a risk level, so
require_merge_recommendationandrequire_risk_assessmentmust be enabled; - the review covered the whole pull request: not an incremental review, no file left out by the ignore rules or the
file-type filter, no file left out or cut short to fit the model's context, and no part of the diff failed; - the review completed and its finding state could be updated.
Each /review run withdraws the approval PR-Agent gave when it starts, and approves again only when it ends with all
of these holding, so a run that fails or finds a concern leaves no approval behind. On a push, the GitHub App, the
GitHub Action, and the GitLab webhook dismiss it before any other event filter runs. A change of base branch also
dismisses it, and on GitHub so does a reopen. On GitHub, PR-Agent only dismisses approvals it gave automatically;
manual approvals from the same account are left alone. On GitLab, an approval belongs to the token's account, so use
an account reserved for PR-Agent. With publish_output off, nothing is approved or dismissed.
enable_auto_approval is host-only: a repository .pr_agent.toml or a comment argument cannot turn it on.
Required repository settings.
- On GitHub, turn on "Dismiss stale pull request approvals when new commits are pushed" in the branch protection
rule or ruleset. PR-Agent can miss a push (a failed webhook delivery, a polling deployment, or a workflow that
does not listen tosynchronize), and GitHub only removes a stale approval itself when this is on. - On GitLab, enable merge request approvals for the project and keep approvals reset on push in the project's
approval settings, so a missed webhook does not leave a stale approval behind. - For the GitHub Action, allow "GitHub Actions to create and approve pull requests" in the repository's Actions
settings. Pull requests from forks get a read-only token, so they cannot be approved. - If the rule restricts who can dismiss reviews, include PR-Agent's account; otherwise it cannot withdraw its own
approval, and only logs an error.
GitHub does not let an account approve a pull request it opened. GitLab can also reject approval by the merge
request author according to the project's approval settings. Other git providers are not supported yet.
Suggested rollout
- Enable
require_merge_recommendation,require_risk_assessment, andpublish_merge_recommendation_statuson
the host. Tunesensitive_pathsandmax_changed_linesas needed. - Require the published verdict status in branch protection or merge rules, and verify verdicts on representative
PRs. - Enable
config.enable_auto_approvalfor a limited scope first (or a pilot environment), confirm approvals are
dismissed on push/base changes, and monitor outcomes. - Expand gradually once the behavior matches your repository's review policy. Keep PR-Agent's account permissions
and stale-approval settings in place.
Docs Commands Similar Issues (`docs/docs/commands/similar_issues.md`)
title: "Similar Issues" sidebar_position: 8
Overview
Note:
/similar_issueis an experimental feature. It works only on GitHub, carries a disproportionately large share of the project's dependency and configuration surface for a single-provider command, and is therefore excluded from the v1 stability guarantees. No backend is tested against its real driver.
The similar issue command retrieves the most similar issues to the current issue.
It is an issue-scoped command: comment /similar_issue on the issue (served by the GitHub Action; the GitHub App webhook only dispatches comments on pull requests), or run it from the CLI with --issue_url:
/similar_issueExample usage
Indexing and re-runs
To perform retrieval, the similar_issue command indexes the repository's issues in the configured vector database. On every backend:
- The first run indexes up to
max_issues_to_scanissues (default500). - Later runs check the newest
max_issues_to_scanissues and index any that are missing, so previously-indexed issues are not re-embedded. force_update_dataset = truemakes every run re-index up tomax_issues_to_scanissues: LanceDB replaces the repository's rows, Pinecone and Qdrant upsert over the existing rows.skip_comments = trueskips issue comments and embeds only the issue title and body.
Embedding inputs are limited to 8,191 tokens (one token below the model's
8,192-token context). Issues or comments exceeding this limit are skipped during
indexing; an oversized issue also excludes its comments. Long similarity queries
are truncated to their first 8,191 tokens, so later content does not influence
the results.
These keys live under the [pr_similar_issue] section. Each backend section below describes its own configuration and re-run behaviour.
If the embedding service rejects the credentials (HTTP 401) or denies access (HTTP 403), indexing stops immediately on every vector database backend.
Correct the embedding API key or access permissions before running the command again; other embedding errors retain the existing batch and per-item fallback behavior.
Selecting a Vector Database
Configure your preferred database by setting the vectordb parameter under [pr_similar_issue] in configuration.toml:
[pr_similar_issue]
vectordb = "lancedb" # options: "pinecone", "lancedb", "qdrant"Available Options
Choose from the following Vector Databases:
- LanceDB
- Pinecone
- Qdrant
LanceDB Configuration
LanceDB is the default backend (vectordb = "lancedb") and needs no external credentials. The index is stored in a local directory given by the [lancedb] uri key (default ./lancedb). A single table (codium-ai-pr-agent-issues) is shared by every repository indexed into the same directory; rows are tagged with the repository name in the metadata.
As described in Indexing and re-runs, the first run creates the table and indexes up to max_issues_to_scan issues; later runs index any missing issue among the newest max_issues_to_scan; force_update_dataset = true replaces the repository's rows with a fresh index of up to max_issues_to_scan issues.
Pinecone Configuration
To use Pinecone with the similar issue command, add these credentials to .secrets.toml (or set as environment variables):
[pinecone]
api_key = "..."
cloud = "aws"
region = "us-east-1"The cloud value must be one of aws, gcp or azure, and region must be an
availability region offered by that cloud. These parameters can be obtained by
registering to Pinecone. Note that the
command uses Pinecone's serverless index API; the former environment setting from the
gcp-starter pod tier is no longer supported.
cloud and region are only used when the index does not exist yet and needs to be
created. An existing index is opened by name and is never recreated, so moving an
existing deployment to the new configuration does not lose the stored vectors.
On re-runs, the first run creates the index and upserts up to max_issues_to_scan issues; later runs index any missing issue among the newest max_issues_to_scan; force_update_dataset = true re-indexes up to max_issues_to_scan issues.
:::note[No backend is tested against its real driver]
The similar-issue dependency group is not installed in CI, so the pinecone tests run
against a faked module, the qdrant tests never construct a client, and the lancedb tests
run against a fake table.
:::
:::note[Default vector database]
vectordb defaults to lancedb, which works with no external credentials. To use
qdrant or pinecone, set vectordb = "qdrant" or vectordb = "pinecone" under[pr_similar_issue].
:::
Qdrant Configuration
To use Qdrant with the similar issue command, add these credentials to .secrets.toml (or set as environment variables):
[qdrant]
url = "https://YOUR-QDRANT-URL" # e.g., https://xxxxxxxx-xxxxxxxx.eu-central-1-0.aws.cloud.qdrant.io
api_key = "..."Then select Qdrant in configuration.toml:
[pr_similar_issue]
vectordb = "qdrant"You can get a free managed Qdrant instance from Qdrant Cloud.
api_key must be present even when the server does not enforce authentication (an empty string is accepted): the command reads both url and api_key and raises when either is absent. A re-index uploads the records from up to max_issues_to_scan issues.
Qdrant points are stored in a collection named codium-ai-pr-agent-issues-v2, derived by appending a -v2 suffix to the shared index name (codium-ai-pr-agent-issues). The suffix is an implementation detail of the Qdrant backend only; pinecone and lancedb use the unsuffixed name.
On re-runs, the first run creates the collection and stores up to max_issues_to_scan issues; later runs index any missing issue among the newest max_issues_to_scan; force_update_dataset = true re-indexes up to max_issues_to_scan issues.
:::note[Upgrading an index created before the point-id fix]
Earlier versions derived the point id from the issue id alone, so the same issue number collided
across repositories. The id is now seeded with the repository name, which means points written by
an earlier version are never rewritten or deleted - they still carry a matching metadata.repo
payload, so they stay queryable and can surface alongside their replacements.
The -v2 collection suffix sidesteps this: the new index is written tocodium-ai-pr-agent-issues-v2, leaving the pre-existing codium-ai-pr-agent-issues collection
untouched. Nothing is deleted, and the first run after the upgrade re-indexes the repository into
the new collection. Once you are satisfied with the results, you can delete the oldcodium-ai-pr-agent-issues collection from Qdrant by hand to reclaim the storage.
:::
How to use
Install the command's extra dependencies (vector databases and datasets), which a bare
uv syncdoes not include:uv sync --group similar-issueTo invoke the 'similar issue' command from CLI, run:
uv run pr-agent --issue_url=... similar_issueTo invoke the 'similar' issue command via online usage, comment on an issue:
/similar_issueTo run automatically when an issue is opened, create a GitHub Actions workflow for the
issues: openedevent that invokes the CLI with that issue's URL. Adding/similar_issuetogithub_app.pr_commandsdoes not handle issue-opened events.With the default LanceDB backend, restore the configured
[lancedb] uridirectory (default./lancedb, relative to the CLI working directory) before running the CLI and save the updated directory afterward, or use a persistent remote Qdrant or Pinecone backend. On ephemeral hosted runners, an unpreserved local index is rebuilt on each run, repeating embedding costs for up tomax_issues_to_scanissues (default500) and leaving previously indexed issues outside that batch unavailable for retrieval.
Docs Commands Update Changelog (`docs/docs/commands/update_changelog.md`)
title: "Update Changelog" sidebar_position: 11
Overview
The update_changelog command automatically updates a Markdown changelog with the PR changes.
It uses CHANGELOG.md at the repository root by default; pr_update_changelog.changelog_path selects a different file.
It can be invoked manually by commenting on any PR:
/update_changelogEmpty or fence-only model responses are retried with the configured fallback models. If no model returns usable content, the command stops without writing to the changelog or publishing an update comment.
Host operators can also opt in to forwarding the newly generated entry to the existing
push outputs destinations by selecting update_changelog inpush_outputs.commands. These notifications contain a draft, not confirmation of a repository write.
Example usage
Configuration options
Under the section pr_update_changelog, the configuration file contains options to customize the 'update changelog' command:
changelog_path: repository-relative path to the Markdown changelog, such asHISTORY.mdordocs/CHANGELOG.md. Default isCHANGELOG.md. Set it in the root.pr_agent.tomlor host configuration; comment/CLI arguments and per-directory settings cannot override it.push_changelog_changes: whether to push the changes to the selected changelog, or just publish them as a comment. Default is false (publish as comment). Before pushing, the command requires a confirmed read of that file; a confirmed missing file is treated as empty, while other read failures skip the repository write, attempt to publish a not-pushed fallback comment, and surface the original error. If the repository write itself fails, the command makes one best-effort attempt to publish the generated changelog as a fallback and surfaces the original write error. Because a transport failure may happen after a completed remote write, this fallback reports the repository update as unconfirmed rather than promising it was not pushed.extra_instructions: Optional extra instructions to the command. For example: "Use the following structure: ..."add_pr_link: whether the model should try to add a link to the PR in the changelog. Default is true.skip_ci_on_push: whether the commit message (whenpush_changelog_changesis true) will include the term "[skip ci]", preventing CI tests to be triggered on the changelog commit. Default is true.
Custom changelog location
For a changelog stored under docs/, add this to the repository's root .pr_agent.toml:
[pr_update_changelog]
changelog_path = "docs/CHANGELOG.md"Then invoke /update_changelog as usual. The command reads that file to follow its existing structure and,
when push_changelog_changes is enabled, prepends the new entry to the same file on the PR branch.
Comment-only output also uses the selected file as context and names it in the commit instructions.
The path must be a non-empty repository-relative file path using / separators, without empty,. or .. components, Windows drive prefixes, backslashes, or control characters. Invalid values stop
the command before reading repository content. Spaces and Unicode names are accepted and kept exactly as written. The command updates
one Markdown changelog per command; it does not discover files, expand globs, or select a file per package.
The filename need not end in .md, but the generated content remains Markdown.
Docs Core Abilities Agent Skills (`docs/docs/core-abilities/agent_skills.md`)
title: "Agent Skills" sidebar_position: 2
Supported Commands: Review, Describe, Ask
Overview
Agent Skills let you distribute curated, reusable review guidance to PR-Agent using the agent-skills (SKILL.md) format. A skill is a directory containing a SKILL.md file with YAML frontmatter (name + description) followed by a markdown body:
---
name: terraform-standards
description: Use when reviewing Terraform code — checks state safety and risky deletions.
---
# Terraform Review Guidance
- Flag any resource deletion that is not explicitly called out in the PR description.
- Require `prevent_destroy` on stateful resources.
- ...When enabled, PR-Agent discovers every SKILL.md under the configured paths, parses it, and injects the skill's name, description, and body into the /review, /describe, and /ask prompts (including questions on a specific line) alongside extra_instructions. The model applies the guidance it judges relevant to the PR or question, using each skill's description as the signal for when the skill applies.
The value proposition is org-wide, host-level skill libraries: install one curated set of skills on your PR-Agent deployment and reuse it across many repositories, without checking guidance into each repo.
Configuration
Skills are disabled by default and configured in configuration.toml (or any host-level config source):
[skills]
enabled = false
paths = [] # directories scanned recursively for "*/SKILL.md"; supports ~ and $VAR
max_skills_tokens = 8000 # token budget for the combined skills blockenabled— turn the feature on.paths— a list of directories (scanned recursively for*/SKILL.md) or direct paths to aSKILL.mdfile.~and$VAR/${VAR}are expanded. A plain string is read as a single path, with a warning that it should be a list.max_skills_tokens— caps the combined size of the injected skills block. Skills past the cap are dropped from the end with a warning; if the first skill alone exceeds the budget it is clipped and marked[truncated].
:::warning[skills.paths is host-level only]skills.paths cannot be set from a repository's .pr_agent.toml and is configurable only where the deployment is administered. Because it reads files from the PR-Agent host's filesystem, allowing a repository to set it would let a malicious repo point PR-Agent at sensitive host files (e.g. ~/.ssh/*) and exfiltrate their contents into the model prompt. A repo-supplied skills.paths is ignored with a warning.
A repository may set the safe per-repo preferences skills.enabled and skills.max_skills_tokens in its own .pr_agent.toml — e.g. to opt in to (or size) the host's admin-curated skill library for that repo. It can never redirect the filesystem scan.
:::
Bundled resources
The agent-skills standard supports bundled files alongside SKILL.md. PR-Agent inlines the text ones:
- All
*.mdfiles in the skill directory tree (including areferences/subdirectory) are appended after theSKILL.mdbody. Individual resource files larger than 256 KB are skipped with a warning. scripts/andassets/subdirectories are skipped: PR-Agent runs single-shot model calls with no tool-use loop, so it cannot execute scripts or load binary assets on demand.- A nested directory that contains its own
SKILL.mdis treated as a separate skill and not inlined into its parent.
In short, PR-Agent supports text-only agent skills.
Limitations
PR-Agent dispatches single-shot model calls, so the agent-skills standard's progressive disclosure model (the model reads SKILL.md only after selecting it by description, and reads references/*.md only on demand) is not implementable on the current architecture — an architecture change to support this is planned for the future. Until then, every enabled skill's text is loaded into every PR's prompt, bounded by max_skills_tokens. Skills that depend on script execution or binary assets will not work.
Docs Core Abilities Compression Strategy (`docs/docs/core-abilities/compression_strategy.md`)
title: "Compression Strategy" sidebar_position: 3
Supported Git Platforms: GitHub, GitLab, Bitbucket, Azure DevOps, Gitea
Overview
There are two scenarios:
- The PR is small enough to fit in a single prompt (including system and user prompt)
- The PR is too large to fit in a single prompt (including system and user prompt)
For both scenarios, we first use the following strategy
Repo language prioritization strategy
We prioritize the languages of the repo based on the following criteria:
- Exclude binary files and non code files (e.g. images, pdfs, etc)
- Given the main languages used in the repo
- We sort the PR files by the most common languages in the repo (in descending order):
[[file.py, file2.py],[file3.js, file4.jsx],[readme.md]]
Small PR
In this case, we can fit the entire PR in a single prompt:
- Exclude binary files and non code files (e.g. images, pdfs, etc)
- We Expand the surrounding context of each patch using
config.patch_extra_lines_beforeandconfig.patch_extra_lines_after(5 extra lines before and 1 after by default). Dynamic context can extend the preceding context further when an enclosing function or class is found.
Large PR
Motivation
Pull Requests can be very long and contain a lot of information with varying degree of relevance to the pr-agent.
We want to be able to pack as much information as possible in a single LMM prompt, while keeping the information relevant to the pr-agent.
Compression strategy
We prioritize additions over deletions:
- Combine all deleted files into a single list (
deleted files) - File patches are a list of hunks, remove all hunks of type deletion-only from the hunks in the file patch
Adaptive and token-aware file patch fitting
We use tiktoken to tokenize the patches after the modifications described above, and we use the following strategy to fit the patches into the prompt:
- Within each language we sort the files by the number of tokens in the file (in descending order):
[[file2.py, file.py],[file4.jsx, file3.js],[readme.md]]
- Iterate through the patches in the order described above
- Add the patches to the prompt until the prompt reaches a certain buffer from the max token length
- If there are still patches left, add the remaining patches as a list called
other modified filesto the prompt until the prompt reaches the max token length (hard stop), skip the rest of the patches. - If we haven't reached the max token length, add the
deleted filesto the prompt until the prompt reaches the max token length (hard stop), skip the rest of the patches.
Example
Docs Core Abilities Dynamic Context (`docs/docs/core-abilities/dynamic_context.md`)
title: "Dynamic Context" sidebar_position: 4
Supported Git Platforms: GitHub, GitLab, Bitbucket, Azure DevOps, Gitea
PR-Agent uses an asymmetric and dynamic context strategy to improve AI analysis of code changes in pull requests.
It provides more context before changes than after, and dynamically adjusts the context based on code structure (e.g., enclosing functions or classes).
This approach balances providing sufficient context for accurate analysis, while avoiding needle-in-the-haystack information overload that could degrade AI performance or exceed token limits.
Introduction
Pull request code changes are retrieved in a unified diff format, showing three lines of context before and after each modified section, with additions marked by '+' and deletions by '-'.
@@ -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():
...This unified diff format can be challenging for AI models to interpret accurately, as it provides limited context for understanding the full scope of code changes.
The presentation of code using '+', '-', and ' ' symbols to indicate additions, deletions, and unchanged lines respectively also differs from the standard code formatting typically used to train AI models.
Challenges of expanding the context window
While expanding the context window is technically feasible, it presents a more fundamental trade-off:
Pros:
- Enhanced context allows the model to better comprehend and localize the code changes, results (potentially) in more precise analysis and suggestions. Without enough context, the model may struggle to understand the code changes and provide relevant feedback.
Cons:
Excessive context may overwhelm the model with extraneous information, creating a "needle in a haystack" scenario where focusing on the relevant details (the code that actually changed) becomes challenging.
LLM quality is known to degrade when the context gets larger.
Pull requests often encompass multiple changes across many files, potentially spanning hundreds of lines of modified code. This complexity presents a genuine risk of overwhelming the model with excessive context.Increased context expands the token count, increasing processing time and cost, and may prevent the model from processing the entire pull request in a single pass.
Asymmetric and dynamic context
To address these challenges, PR-Agent employs an asymmetric and dynamic context strategy, providing the model with more focused and relevant context information for each code change.
Asymmetric:
We start by recognizing that the context preceding a code change is typically more crucial for understanding the modification than the context following it.
Consequently, PR-Agent implements an asymmetric context policy, decoupling the context window into two distinct segments: one for the code before the change and another for the code after.
By independently adjusting each context window, PR-Agent can supply the model with a more tailored and pertinent context for individual code changes.
Dynamic:
We also employ a "dynamic" context strategy.
We start by recognizing that the optimal context for a code change often corresponds to its enclosing code component (e.g., function, class), rather than a fixed number of lines.
Consequently, we dynamically adjust the context window based on the code's structure, ensuring the model receives the most pertinent information for each modification.
To prevent overwhelming the model with excessive context, we impose a limit on the number of lines searched when identifying the enclosing component.
This balance allows for comprehensive understanding while maintaining efficiency and limiting context token usage.
Appendix - relevant configuration options
[config]
patch_extension_skip_types =[".md",".txt"] # Skip files with these extensions when trying to extend the context
allow_dynamic_context=true # Allow dynamic context extension
max_extra_lines_before_dynamic_context = 10 # will try to include up to X extra lines before the hunk in the patch, until we reach an enclosing function or class
patch_extra_lines_before = 5 # Number of extra lines (+3 default ones) to include before each hunk in the patch
patch_extra_lines_after = 1 # Number of extra lines (+3 default ones) to include after each hunk in the patchDocs Core Abilities Fetching Ticket Context (`docs/docs/core-abilities/fetching_ticket_context.md`)
title: "Fetching Ticket Context for PRs" sidebar_position: 5
Supported Git Platforms: GitHub, GitLab, Bitbucket, Azure DevOps, Gitea
:::note[Branch-name linking: Jira keys on all providers; numeric issues on GitHub and GitLab]
Jira ticket keys (e.g. ABC-123) are extracted from the branch name on every git provider.
GitHub extracts numeric issue references from branch names, with optional branch_issue_regex customization.
GitLab also recognizes same-project MR branches prefixed with an issue number and hyphen (e.g. 123-fix-bug).
:::
Overview
PR-Agent streamlines code review workflows by seamlessly connecting with multiple ticket management systems.
This integration enriches the review process by automatically surfacing relevant ticket information and context alongside code changes.
Ticket systems supported:
Ticket data fetched:
- Ticket Title
- Ticket Description
- Acceptance criteria (configured Jira custom fields and Azure DevOps work items)
- GitHub sub-issues
- Labels
Image attachments are not fetched or sent to the model as images by the ticket integration.
Affected Commands
Ticket Recognition Requirements:
- GitHub/GitLab issue references can appear in the PR/MR title or description. Both platforms also recognize their supported numeric issue branch patterns.
- For Jira tickets, you should follow the instructions in Jira Integration in order to authenticate with Jira.
- For Asana tickets, see Asana Integration.
Describe command
PR-Agent will recognize the ticket and use the ticket content (title, description, labels) to provide additional context for the code changes.
By understanding the reasoning and intent behind modifications, the LLM can offer more insightful and relevant code analysis.
Review command
Similarly to the describe command, the review command will use the ticket content to provide additional context for the code changes.
In addition, this feature will evaluate how well a Pull Request (PR) adheres to its original purpose/intent as defined by the associated ticket or issue.
Each ticket will be assigned a compliance assessment in the review comment, indicating the degree to which the PR fulfills its original purpose. These assessments are not added as PR labels:
- Fully Compliant
- Partially Compliant
- Not Compliant
- PR Code Verified
A PR Code Verified assessment indicates the PR code meets ticket requirements, but requires additional manual testing beyond the code scope. For example - validating UI display across different environments (Mac, Windows, mobile, etc.).
Configuration options
By default, the
reviewcommand will automatically validate if the PR complies with the referenced ticket.
If you want to disable this feedback, add the following line to your configuration file:toml[pr_reviewer] require_ticket_analysis_review=false
Ask command
Set pr_questions.use_ticket_context=true to include linked ticket content in top-level /ask questions.
This is disabled by default and is independent of pr_reviewer.require_ticket_analysis_review.
It reuses the ticket integrations below and fits complete ticket records into the space left after the question,
conversation history and selected diff. See Linked ticket context
for usage and limits.
GitHub/GitLab Issues Integration
PR-Agent will automatically recognize GitHub/GitLab issues mentioned in the PR/MR title or description and fetch the issue content.
Examples of valid GitHub/GitLab issue references:
https://github.com/<ORG_NAME>/<REPO_NAME>/issues/orhttps://gitlab.com/<ORG_NAME>/<REPO_NAME>/-/issues/#<ORG_NAME>/<REPO_NAME>#
Full GitHub issue URLs are recognized on the configured instance's HTTPS web origin, including GitHub Enterprise URLs such as https://github.example.com/<ORG_NAME>/<REPO_NAME>/issues/.
Full GitHub issue URLs on other origins are ignored.
GitHub processes references from the description first, then the branch name, then the title. GitLab processes
description references first, then title references, then eligible branch references. Repeated identical references do
not add lookups, and branch references use the existing ticket lookup and result limits without displacing earlier sources.
The optional config.description_issue_regex setting applies only to the GitHub PR description. Built-in matching on
GitHub and GitLab recognizes local # references of up to six digits.
Branch names can also be used to link issues, for example:
123-fix-bug(where123is the issue number)
On GitHub, matching also supports feature/123-fix-bug and the optional config.branch_issue_regex setting.
The custom regex must have a capturing group for the issue number; an invalid regex disables branch detection,
while a regex without a capturing group falls back to the default pattern (up to six digits after a slash or at the start).
A custom regex that runs longer than 50 ms on the branch name, is longer than 1024 characters, or has counted repeats
such as {100} that multiply to more than 10,000 finds no issue, and the reason is logged.
On GitLab, only branches starting with a 1–6 digit ASCII issue number (no leading zeros) followed by a
hyphen are recognized.
The source and target projects must be the same; fork MRs and patterns such as feature/123-fix-bug are not inferred.
Date prefixes such as 2026-11-15 are excluded, while 2024-upgrade-deps remains a valid issue prefix.
GitLab uses its native prefix rule rather than the GitHub-only branch_issue_regex setting. Setconfig.extract_issue_from_branch=false to disable branch-based issue recognition on either platform.
For branch-only issues, the project's Issues and Merge Requests access levels must also be known and eligible;
otherwise the inferred reference is skipped. This reuses the project metadata already fetched for GitLab ticket
visibility checks, without an additional metadata request for branch inference.
By default, GitHub and GitLab ticket context is limited to the PR's or MR's own repository. Issues and
sub-issues in another repository require explicit host approval through config.repo_context_sibling_repos:
[config]
repo_context_sibling_repos = ["myorg/shared-tickets"]Only canonical repositories under the PR repository's resolved owner are accepted on GitHub; on GitLab the
project must share the MR project's top-level namespace. For private or internal repositories, the command
requester must also have read access; CLI runs use the PR author when no command actor is available. Repository
settings and comment arguments cannot change this allowlist. An empty list disables cross-repository ticket
reads, including public repositories. Approve only content that may be included in the consuming PR's review or
description. Ticket lookup limits are separate from the sibling-file limit. PyGithub may follow an issue transfer,
but results from a different repository are discarded before prompt use. Reference a transferred issue by its
current repository and number.
For GitLab, ticket extraction checks project visibility and issues_access_level once per project per run.
Member-only issues in the MR's own project are included when the project is private or the MR itself is member-only;
they are skipped for broadly visible MRs in public and internal projects. Disabled, unknown, or unreadable issue
access settings are skipped. Approved sibling issues must have Issues enabled and be public.
Internal and private sibling projects cannot guarantee that every MR reader can see their issues and are skipped.
Confidential issues are skipped in every project.
For GitHub, PR-Agent skips sub-issue lookup only when the parent issue's fetched summary explicitly reports zero
sub-issues; nonzero, missing, or invalid totals use the usual lookup.
This uses the parent response as a snapshot, so a stale zero count or sub-issues added after that read may leave
child tickets out of the current run's context.
Linear Integration
PR-Agent reads Linear issue links from the user-written PR description and includes their titles, descriptions,
and labels in the existing ticket context. This works across git providers, including providers without native
issue support. Enable pr_reviewer.require_ticket_analysis_review to use ticket analysis.
Link an issue as https://linear.app/your-workspace/issue/TEAM-123 or include its optional title slug.
Query strings and fragments do not change issue identity. Repeated links to the same workspace and issue are
deduplicated in description order. Bare identifiers, PR titles and branch names are not scanned for Linear issues.
Create a Linear personal API key with read access to the intended issues.
Set LINEAR__API_TOKEN in the deployment environment, or add it to your private .secrets.toml:
[linear]
api_token = "your-personal-api-key"Do not put the token in repository .pr_agent.toml files. Existing credential protections prevent repositories
and review-command arguments from overriding it. Fetched ticket content enters the review model's context;
choose credential access appropriate for the repositories using the integration.
The key is sent directly in the Authorization header to https://api.linear.app/graphql, without a Bearer
prefix. Requests do not follow redirects. No OAuth application or additional service is required.
PR-Agent attempts the first three unique issue references, concurrently and in description order, with no
replacement attempts for failed issues. Results are appended after existing native, Asana and Jira tickets,
without reducing their limits. Descriptions are truncated to 10,000 characters and at most 20 labels are fetched.
The shared prompt-token budget may further reduce ticket context.
Missing credentials, inaccessible issues, HTTP errors and GraphQL errors cause the affected issues to be skipped
with a warning; successful tickets and the code review continue. No placeholder ticket or separate failure verdict
is published. An API response for a different workspace or issue is rejected. Configure linear.request_timeout
to change the default 10-second per-request timeout (maximum 60 seconds). Existing review-local ticket caching applies.
Asana Integration
PR-Agent can detect Asana task references in PR descriptions, fetch the referenced tasks through the
Asana API, and include their titles, descriptions, and tags in the
ticket compliance check.
Supported reference formats:
- Legacy links:
https://app.asana.com/0/{project_gid}/{task_gid} - Current permalinks:
https://app.asana.com/1/{workspace_gid}/task/{task_gid} - Current project links:
https://app.asana.com/1/{workspace_gid}/project/{project_gid}/task/{task_gid} - Current Home links:
https://app.asana.com/1/{workspace_gid}/home/task/{task_gid} - Task comment links ending in
/comment/{comment_gid}(the parent task is fetched)
How to link a PR to an Asana task:
Include an Asana task URL in your PR description. PR-Agent will detect it automatically and include it in the related
tickets list.
Authentication
Create an Asana personal access token with access to the
tasks that PR-Agent should read. Configure it in .secrets.toml:
[asana]
api_token = "YOUR_PERSONAL_ACCESS_TOKEN"For environment-based deployments, set the equivalent Dynaconf environment variable:
ASANA__API_TOKEN="YOUR_PERSONAL_ACCESS_TOKEN"The token is sent only to Asana's fixed task API endpoint as a Bearer token. When no token is configured or a task is
not accessible to that token, PR-Agent skips that Asana task instead of evaluating compliance against placeholder
content. API request timeout can be adjusted with asana.request_timeout (10 seconds by default, capped at 60 seconds).
Ticket limits
PR-Agent fetches the first three detected Asana tasks at most, preserving their description order. This is an
additive, provider-specific limit, with native tickets listed before Asana tasks:
- On GitHub, the existing limit of three GitHub issues is preserved, plus up to three Asana tasks.
- On Azure DevOps, all linked work items are preserved, plus up to three Asana tasks.
- On other providers, up to three detected Asana tasks can supply ticket context.
Keeping these limits separate prevents Asana references from silently displacing native tickets and avoids changing
the established ticket-extraction behavior of existing providers.
Jira Integration
Jira lookup needs the bitbucket extra: pip install "pr-agent[bitbucket]". Without it the lookup is skipped with a warning.
Only Jira Cloud is supported. The base URL is derived from a validated site name
(jira_site → https://<site>.atlassian.net) rather than taken as a free-form URL, so
the configured destination is always an Atlassian Cloud host. Jira Server / Data Center
(self-hosted) uses a free-form host and is not supported yet; it can be added once
base-URL handling for the self-hosted case is settled.
Jira Cloud
Email/Token Authentication
You can create an API token from your Atlassian account:
Log in to https://id.atlassian.com/manage-profile/security/api-tokens.
Click Create API token.
From the dialog that appears, enter a name for your new token and click Create.
Click Copy to clipboard.
In the PR-Agent host configuration (the secrets file or environment variables such as
JIRA__JIRA_SITE) add the following lines. A repository's.pr_agent.tomlcannot set them:toml[jira] jira_site = "<JIRA_SITE>" # the "<site>" in https://<site>.atlassian.net (e.g. "mycompany") cloud_id = "<CLOUD_ID>" # optional UUID for scoped or service-account tokens jira_api_email = "YOUR_EMAIL" jira_api_token = "YOUR_API_TOKEN"jira_siteis your Jira Cloud site name — the part before.atlassian.net(forhttps://mycompany.atlassian.net, the site ismycompany). PR-Agent builds the base URL
ashttps://<jira_site>.atlassian.net; it does not accept a full URL, so configuration
cannot redirect the authenticated request to another host. Storejira_api_emailandjira_api_tokenas secrets (environment variables or the secrets file), not in
repository-committed configuration.For scoped or service-account API tokens, set
cloud_idto the UUID of the Jira Cloud site. Requests then usehttps://api.atlassian.com/ex/jira/<cloud_id>while ticket links continue to usejira_site. Leavecloud_id
empty for classic API tokens and the site-specific URL. The value is host-only and invalid values disable Jira
lookup without logging the value.To find the cloud ID, open
https://<site>.atlassian.net/_edge/tenant_infoand read thecloudIdvalue from the
JSON response. It is also the value after/s/in theadmin.atlassian.comURL. Use the cloud ID, not the Jira
organization ID, because Atlassian's API gateway expects the site cloud ID.
Acceptance criteria / requirements (optional)
To include a ticket's acceptance criteria in the analysis, set jira_requirements_field
to the id of the custom field that holds it. The field id is specific to your Jira
instance (for example customfield_10127); leave it empty to skip requirements.
[jira]
jira_requirements_field = "customfield_10127"Project key allowlist (optional)
Ticket detection matches any PROJECT-123 shaped text, so strings like SHA-256,UTF-8 or ISO-8601 in a title or description each cost an authenticated lookup that
returns 404. If your deployment works with a known set of Jira projects, list their keys
in the host's project_keys; keys with any other prefix are then dropped before any lookup (they are
named once at debug level in the log). By default, project_keys = ["*"] looks up every key found.
Set project_keys = [] to disable Jira ticket lookups.cloud_id, project_keys, jira_site and jira_api_email are host-only: a repository's .pr_agent.toml
or a comment command cannot change them.
[jira]
project_keys = ["PROJ", "OPS"]Entries are plain upper-case project keys as Jira writes them (a letter, then letters or digits,
such as PROJ or B2B) or "*" to allow all keys.
Anything else (a lower-case label, a full ticket key, a URL, a blank entry) is ignored with a
warning. If the list is set but none of its entries is valid, no Jira lookup is made at all
until it is fixed, so a typo cannot silently widen the lookup again.
How to link a PR to a Jira ticket
To integrate with Jira, you can link your PR to a ticket using either of these methods:
Method 1: Description Reference:
Include a ticket reference in your PR description, using either the complete URL format https://<JIRA_SITE>.atlassian.net/browse/ISSUE-123 or the shortened ticket ID ISSUE-123 (without prefix or suffix for the shortened ID).
Method 2: Branch Name Detection:
Name your branch with the ticket ID as a prefix (e.g., ISSUE-123-feature-description or ISSUE-123/feature-description).
Docs Core Abilities Metadata (`docs/docs/core-abilities/metadata.md`)
title: "Local and global metadata injection with multi-stage analysis" sidebar_position: 6
Supported Git Platforms: GitHub, GitLab, Bitbucket, Azure DevOps, Gitea
PR-Agent initially retrieves for each PR the following data:
- PR title and branch name
- PR original description
- Commit messages history (GitHub, GitLab, Gitea and Gerrit; the other providers send none).
/reviewand/improveget them too; setconfig.max_commits_tokens = -1to leave them out. - PR diff patches, in hunk diff format
- The entire content of the files that were modified in the PR
:::note[Tip: Organization-level metadata]
In addition to the inputs above, PR-Agent can incorporate supplementary preferences provided by the user, likeextra_instructions. This information can be used to enhance the PR analysis.
:::By default, the first command that PR-Agent executes is
describe, which generates three types of outputs:- PR Type (e.g. bug fix, feature, refactor, etc)
- PR Description - a bullet point summary of the PR
- Changes walkthrough - for each modified file, provide a one-line summary followed by a detailed bullet point list of the changes.
These AI-generated outputs are now considered as part of the PR metadata, and can be used in subsequent commands like
reviewandimprove.
This effectively enables multi-stage chain-of-thought analysis, without doing any additional API calls which will cost time and money.For example, when generating code suggestions for different files, PR-Agent can inject the AI-generated "Changes walkthrough" file summary in the prompt:
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__ ...The entire PR files that were retrieved are also used to expand and enhance the PR context (see Dynamic Context).
All the metadata described above represents several level of cumulative analysis - ranging from hunk level, to file level, to PR level, to organization level.
This comprehensive approach enables PR-Agent AI models to generate more precise and contextually relevant suggestions and feedback.
Docs Core Abilities Self Reflection (`docs/docs/core-abilities/self_reflection.md`)
title: "Self-Reflection" sidebar_position: 7
Self-reflection was a follow-up model call in which /improve scored and re-ranked its own code suggestions.
Since 0.51, /improve runs /review, which does not make that call. The oldpr_code_suggestions scoring and reflection settings have been removed.
A /review finding that carries a fix is described in
Fixes and committable suggestions.
Docs Installation Azure (`docs/docs/installation/azure.md`)
title: "Azure DevOps Integration" sidebar_position: 7
Azure DevOps Pipeline
You can use a pre-built Action Docker image to run PR-Agent as an Azure DevOps pipeline.
Add the following file to your repository under azure-pipelines.yml:
# Opt out of CI triggers
trigger: none
# Configure PR trigger
# pr:
# branches:
# include:
# - '*'
# autoCancel: true
# drafts: false
# NOTE for Azure Repos Git:
# Azure Repos does not honor YAML pr: triggers. Configure Build Validation
# via Branch Policies instead (see note below). You can safely omit pr:.
stages:
- stage: pr_agent
displayName: 'PR Agent Stage'
jobs:
- job: pr_agent_job
displayName: 'PR Agent Job'
pool:
vmImage: 'ubuntu-latest'
container:
image: pragent/pr-agent:latest
options: --entrypoint ""
variables:
- group: pr_agent
steps:
- script: |
echo "Running PR Agent action step"
# Construct PR_URL
PR_URL="${SYSTEM_COLLECTIONURI}${SYSTEM_TEAMPROJECT}/_git/${BUILD_REPOSITORY_NAME}/pullrequest/${SYSTEM_PULLREQUEST_PULLREQUESTID}"
echo "PR_URL=$PR_URL"
# Extract organization URL from System.CollectionUri
ORG_URL=$(echo "$(System.CollectionUri)" | sed 's/\/$//') # Remove trailing slash if present
echo "Organization URL: $ORG_URL"
export azure_devops__org="$ORG_URL"
export config__git_provider="azure"
pr-agent --pr_url="$PR_URL" describe
pr-agent --pr_url="$PR_URL" review
env:
azure_devops__pat: $(azure_devops_pat)
openai__key: $(OPENAI_KEY)
displayName: 'Run PR-Agent'This script will run PR-Agent on every new merge request, with the review and describe commands.
Note that you need to add the azure_devops_pat and OPENAI_KEY variables to the pr_agent variable group in the Azure DevOps pipeline settings (Pipelines -> Library -> + Variable group). The pipeline maps azure_devops_pat to the azure_devops__pat environment variable:
Make sure to give pipeline permissions to the pr_agent variable group.
Note that Azure Pipelines lacks support for triggering workflows from PR comments. If you find a viable solution, please contribute it to our issue tracker
Azure Repos Git PR triggers and Build Validation
Azure Repos Git does not use YAML pr: triggers for pipelines. Instead, configure Build Validation on the target branch to run the PR Agent pipeline for pull requests:
- Go to Project Settings → Repositories → Branches.
- Select the target branch and open Branch Policies.
- Under Build Validation, add a policy:
- Select the PR Agent pipeline (the
azure-pipelines.ymlabove). - Set it as Required.
- Select the PR Agent pipeline (the
- Remove the
pr:section from your YAML (not needed for Azure Repos Git).
This distinction applies specifically to Azure Repos Git. Other providers like GitHub and Bitbucket Cloud can use YAML-based PR triggers.
Azure DevOps from CLI
To use Azure DevOps provider use the following settings in configuration.toml:
[config]
git_provider="azure"Azure DevOps provider supports PAT token or DefaultAzureCredential authentication.
PAT is faster to create, but has built-in expiration date, and will use the user identity for API calls.
Using DefaultAzureCredential you can use managed identity or Service principle, which are more secure and will create separate ADO user identity (via AAD) to the agent.
If PAT was chosen, you can assign the value in .secrets.toml.
If DefaultAzureCredential was chosen, you can assigned the additional env vars like AZURE_CLIENT_SECRET directly,
or use managed identity/az cli (for local development) without any additional configuration.
in any case, 'org' value must be assigned in .secrets.toml:
[azure_devops]
org = "https://dev.azure.com/YOUR_ORGANIZATION/"
# pat = "YOUR_PAT_TOKEN" needed only if using PAT for authenticationPersistent reviews resolve the posting account through Azure DevOps using the same credentials as comment writes.
Repeated /review runs update that account's existing review without requiring an agent_identity setting,
including when Jira ticket context is enabled. This applies to pipelines, CLI runs, and webhook deployments.
If identity lookup is unavailable, configure azure_devops_server.agent_identity in the host environment or settings
with the posting account's GUID, unique name, or descriptor. Repository settings and comment arguments cannot set it.
An explicit setting takes precedence over automatic resolution; display names
do not prove comment ownership. If ownership cannot be verified, an existing review is preserved and a standalone
result is posted.
Azure DevOps Webhook
To trigger from an Azure webhook, you need to manually
add a webhook.
Build the webhook Docker image from the repository root and deploy it:
docker build . -t pr-agent:azure_devops_webhook --target azure_devops_webhook -f docker/DockerfilePoint the webhook at the server's HTTPS root URL (for example, https://pr-agent.example.com/);
the server receives requests at POST / and listens on the port set by PORT (default 3000).
Use the "Pull request created" type to trigger a review, or "Pull request commented on" to trigger a supported/<command> <args> comment. API v2.0 is required for comment events.
Questions can also address the agent without a slash command. Mention the Azure DevOps identity used by PR-Agent at
the start of a PR or line comment. PR-Agent discovers that identity from its earlier comments, answers in the same
thread, and uses the existing thread discussion as context. Generic phrases such as hi agent do not trigger a
response.
For the first mention before PR-Agent has posted on the pull request, or when its Azure DevOps identity changes,
configure a stable identity (GUID/ID, unique name, or descriptor). A list can be used during an identity transition:
[azure_devops_server]
agent_identity = "<agent identity>"Webhook authentication is required. Create a username/password pair and configure the same values on the server and in the Azure DevOps webhook's Basic authentication settings. Azure DevOps sends these credentials with each request:
[azure_devops_server]
webhook_username = "<basic auth user>"
webhook_password = "<basic auth password>"The server rejects webhook requests with HTTP 403 if either setting is missing or empty. With both settings configured, requests without valid Basic credentials receive HTTP 401.
:warning: Ensure that the webhook endpoint is only accessible over HTTPS to mitigate the risk of credential interception when using basic authentication.
Docs Installation Bitbucket (`docs/docs/installation/bitbucket.md`)
title: "BitBucket Integration" sidebar_position: 6
Run as a Bitbucket Pipeline
You can use the Bitbucket Pipeline system to run PR-Agent on every pull request open or update.
Add the following file in your repository bitbucket-pipelines.yml
yamlpipelines: pull-requests: '**': - step: name: PR Agent Review image: pragent/pr-agent:latest script: - pr-agent --pr_url=https://bitbucket.org/$BITBUCKET_WORKSPACE/$BITBUCKET_REPO_SLUG/pull-requests/$BITBUCKET_PR_ID reviewAdd the following secure variables to your repository under Repository settings > Pipelines > Repository variables.
- CONFIG__GIT_PROVIDER:
bitbucket - OPENAI__KEY:
<your key> - BITBUCKET__AUTH_TYPE:
basicorbearer(default isbearer) - BITBUCKET__BEARER_TOKEN:
<your token>(required when auth_type is bearer) - BITBUCKET__BASIC_TOKEN:
<your token>(required when auth_type is basic)
You can get a Bitbucket token for your repository by following Repository Settings -> Security -> Access Tokens.
For basic auth, you can generate a base64 encoded token from your username:password combination.- CONFIG__GIT_PROVIDER:
Note that comments on a PR are not supported in Bitbucket Pipeline.
Bitbucket Cloud behavior
Persistent comments on Bitbucket Cloud
Review and code-suggestion identity markers use invisible Markdown link references on Bitbucket Cloud.
Existing comments with older HTML identity markers are still recognized and updated in place.
No configuration change is required.
Incomplete pull-request diff
PR-Agent stops when Bitbucket Cloud returns a different number of patches than
entries in the filtered changed-file list, instead of treating the diff as empty.
An affected /add_docs, /generate_labels, /describe, or /review
run may post PR-Agent command was not run with a Bitbucket-specific explanation
when CONFIG.PUBLISH_OUTPUT is enabled. This provider-specific notice replaces the
generic /review failure output to avoid duplicate comments.
Retry the command. If the problem persists, check the pull request's diff in
Bitbucket. PR-Agent does not recover missing patches automatically.
Bitbucket Server and Data Center
Login into your on-prem instance of Bitbucket with your service account username and password.
Navigate to Manage account, HTTP Access tokens, Create Token.
Generate the token and add it to pr_agent/settings/.secrets.toml under bitbucket_server section
[bitbucket_server]
bearer_token = "<your key>"Don't forget to also set the URL of your Bitbucket Server instance (either in .secrets.toml or in configuration.toml):
[bitbucket_server]
url = "<full URL to your Bitbucket instance, e.g.: https://git.bitbucket.com>"Run it as CLI
In configuration.toml, change git_provider in the [config] section:
[config]
git_provider = "bitbucket_server"and pass the Pull request URL:
uv run pr-agent --pr_url https://git.on-prem-instance-of-bitbucket.com/projects/PROJECT/repos/REPO/pull-requests/1 reviewRun it as service
To run PR-Agent as webhook, build the docker image:
docker build . -t pr-agent:bitbucket_server_webhook --target bitbucket_server_webhook -f docker/Dockerfile
# Optional, to push it to your own Docker repository:
docker tag pr-agent:bitbucket_server_webhook <your-registry>/pr-agent:bitbucket_server_webhook
docker push <your-registry>/pr-agent:bitbucket_server_webhookNavigate to Projects or Repositories, Settings, Webhooks, Create Webhook.
Fill in the name and URL. Configure a webhook Secret and set the same value in PR-Agent's .secrets.toml:
[bitbucket_server]
webhook_secret = "<webhook secret>"Bitbucket signs webhook payloads with this secret in the X-Hub-Signature header. PR-Agent requires the secret and rejects webhook requests with HTTP 403 if it is missing or empty. Normal webhook deliveries without a valid signature also receive HTTP 403. Bitbucket's connection test remains available after the secret is configured.
The separate Authentication option can remain 'None' because this server verifies the secret-based signature rather than Basic authentication. Select the 'Pull Request Opened' checkbox to receive that event as a webhook.
The URL should end with /webhook, for example: https://domain.com/webhook
The webhook server runs under gunicorn with multiple worker processes. See Sizing a self-hosted webhook server for the GUNICORN_WORKERS / GUNICORN_MAX_WORKERS knobs and memory guidance — worth reading before setting a memory limit.
Docs Installation Gitea (`docs/docs/installation/gitea.md`)
title: "Gitea Integration" sidebar_position: 8
Run a Gitea webhook server
In Gitea create a new user and give it write access to the intended repositories, either as a collaborator or through an organization team. See Gitea repository permissions.
For the user from step 1. generate a personal access token under User Settings → Applications, with
write:repositoryandwrite:issuescopes for reading pull requests and publishing descriptions, reviews, comments, and labels. See Gitea API token permissions.Generate a random secret for your app, and save it for later (
webhook_secret). For example, you can use:bashWEBHOOK_SECRET=$(python -c "import secrets; print(secrets.token_hex(10))")The webhook secret is required: if
GITEA.WEBHOOK_SECRETis not configured, the server rejects every incoming webhook with HTTP 403.Clone this repository:
bashgit clone https://github.com/the-pr-agent/pr-agent.git cd pr-agentPrepare variables and secrets. Skip this step if you plan on setting these as environment variables when running the agent:
- In the configuration file/variables:
- Set
config.git_providerto "gitea"
- Set
- In the secrets file/variables:
- Set your AI model key in the respective section
- In the [Gitea] section, set
personal_access_token(with token from step 2) andwebhook_secret(with secret from step 3)
- In the configuration file/variables:
Build a Docker image for the app and optionally push it to a Docker repository. We'll use Dockerhub as an example:
bashdocker build . -t pr-agent:gitea_app --target gitea_app -f docker/Dockerfile # Optional, to push it to your own Docker repository: docker tag pr-agent:gitea_app <your-registry>/pr-agent:gitea_app docker push <your-registry>/pr-agent:gitea_appSet the environmental variables, the method depends on your docker runtime. Secrets can also be provided through a mounted
.secrets.tomlfile. The supported secrets files are excluded from the Docker build context; do not bake secrets into the image.bashCONFIG__GIT_PROVIDER=gitea GITEA__PERSONAL_ACCESS_TOKEN=<personal_access_token> GITEA__WEBHOOK_SECRET=<webhook_secret> GITEA__URL=https://gitea.com # Or self host # GITEA__WEB_URL=https://git.example.com # Optional: user-facing URL for links published in comments (see below) OPENAI__KEY=<your_openai_api_key> GITEA__SKIP_SSL_VERIFICATION=false # GITEA__SSL_CA_CERT=/path/to/cacert.pem # Only for a custom CA certificateNote: SSL verification can be disabled by setting
GITEA__SKIP_SSL_VERIFICATION=true, although this is not
recommended.Links published in comments are built from
GITEA__WEB_URLwhen set, else fromGITEA__URL
when it differs from the shipped default (https://gitea.com), else derived from the PR's
html_url(which Gitea/Forgejo builds from its ownROOT_URL).
SetGITEA__WEB_URLexplicitly whenGITEA__URLis an internal address users cannot browse
(e.g. a Docker service name), or when the server'sROOT_URLis misconfigured.Create a webhook in your Gitea repository. Set the URL to
http[s]:///api/v1/gitea_webhooks, the secret token to the generated secret from step 3, and enable pull request and pull request comment events. To run commands after new commits, also enable pull request synchronization events and setgitea.handle_push_trigger = true. The server handles normalizedpull_requestandissue_commentevents, not standalonepushevents.Test your installation by opening a pull request or commenting on a pull request using one of PR Agent's commands.
The webhook server runs under gunicorn with multiple worker processes. See Sizing a self-hosted webhook server for the
GUNICORN_WORKERS/GUNICORN_MAX_WORKERSknobs and memory guidance — worth reading before setting a memory limit.
Incomplete pull-request files
PR-Agent stops the command when Gitea cannot supply complete, valid changed-file data, rather than analyzing a partial change set.
When CONFIG.PUBLISH_OUTPUT is enabled, PR-Agent attempts to post a PR-Agent command was not run notice with a Gitea-specific explanation. Publishing this notice is best effort; it may not appear if the provider cannot post it.
Retry the command. If the problem persists, inspect the pull request's changed files and diff in Gitea.
Docs Installation Github (`docs/docs/installation/github.md`)
title: "GitHub Integration" sidebar_position: 4
In this page we will cover how to install and run PR-Agent as a GitHub Action or GitHub App, and how to configure it for your needs.
Run as a GitHub Action
You can use our pre-built GitHub Action Docker image to run PR-Agent as a GitHub Action.
Add the following file to your repository under
.github/workflows/pr_agent.yml:yamlon: pull_request: # PR-Agent skips synchronize by default. Include it in github_action_config.pr_actions # for auto commands, or enable github_action_config.handle_push_trigger for push_commands (takes precedence). types: [opened, reopened, ready_for_review, synchronize] issue_comment: jobs: pr_agent_job: if: ${{ github.event.sender.type != 'Bot' }} runs-on: ubuntu-latest permissions: contents: read issues: write pull-requests: 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 }}Add the following secret to your repository under
Settings > Secrets and variables > Actions > New repository secret > Add secret:textName = OPENAI_KEY Secret = <your key>The
GITHUB_TOKENsecret is automatically created by GitHub, but you must pass it to the action throughenvas shown above.
If it is missing or empty, events with a PR or issue target fail with a nonzero exit status and aGITHUB_TOKEN not setmessage.
Ignored comments and events without a target still skip successfully.Merge this change to your main branch.
When you open your next PR, you should see a comment fromgithub-actionsbot with a review of your PR, and instructions on how to use the rest of the commands.You may configure PR-Agent by adding environment variables under the env section corresponding to any configurable property in the configuration file. Some examples:
yamlenv: # ... previous environment values OPENAI.ORG: "<Your organization name under your OpenAI account>" PR_REVIEWER.REQUIRE_TESTS_REVIEW: "false" # Disable tests review PR_REVIEWER.NUM_MAX_FINDINGS: 5 # Increase number of review findings
See detailed usage instructions in the USAGE GUIDE
When a PR opens with a reviewer already requested, GitHub can send both opened andreview_requested. With both actions enabled, the Action skips the initialreview_requested event when the PR's creation and update timestamps match, so the
commands run once for the opening event stream. A configuration that enables onlyreview_requested still runs that event.
Later review requests still run the enabled commands when review_requested is listed ingithub_action_config.pr_actions. This applies to both pull_request and pull_request_target.
Using with pull_request_target (fork/contribution support)
By default, the pull_request event does not have access to repository or organization secrets when the PR originates from a forked repository, which means PR-Agent won't be able to access secrets such as OPENAI_KEY. The workflow still receives a GITHUB_TOKEN, but it has read-only permissions for fork pull requests by default. For private repositories, administrators can enable Send secrets to workflows from pull requests to make secrets available, but doing so exposes those secrets to workflows triggered by fork pull requests.
To support PRs from external contributors (forks), use the pull_request_target event instead. This event runs in the context of the base repository and has access to its secrets and GITHUB_TOKEN permissions. PR-Agent uses the GitHub API to fetch PR data and does not require a local checkout of the PR code.
name: PR Agent
on:
pull_request_target:
types: [opened, reopened, synchronize, ready_for_review, review_requested]
issue_comment:
jobs:
pr_agent_job:
if: ${{ github.event.sender.type != 'Bot' && (github.event_name == 'pull_request_target' || github.event.issue.pull_request) }}
runs-on: ubuntu-latest
permissions:
contents: read
issues: write
pull-requests: 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 }}
github_action_config.pr_actions: '["opened", "reopened", "synchronize", "ready_for_review", "review_requested"]':::tip[No local checkout needed]
PR-Agent uses the GitHub API to fetch PR data directly from the event payload — it does not require a local checkout of the PR code. This means you can safely omit the actions/checkout step entirely, avoiding common pitfalls with pull_request_target like the issue_comment event lacking a pull_request.head.sha ref.
:::
:::warning[Security considerations]
Using pull_request_target gives the workflow access to repository secrets. Neither event checks out code on its own, but under pull_request_target a plain actions/checkout fetches the default branch rather than the pull request, which is a security feature. Checking out the pull request head alone does not execute untrusted code, but do not build, test, install, or otherwise execute that content in the same job with secrets or elevated token permissions. If local files are required, review the GitHub security guide on pull_request_target before checking out the pull request head.
:::
Configuration Examples
This section provides detailed, step-by-step examples for configuring PR-Agent with different models and advanced options in GitHub Actions.
:::note[Fallback models]config.fallback_models should not repeat config.model: a fallback-eligible failure would just run the same model again. The examples below use '[]' for no backup model, or a different model when one is shown. To retry a failed call on the primary model instead, set config.num_retries.
:::
Quick Start Examples
Basic Setup (OpenAI Default)
Copy this minimal workflow to get started with the default OpenAI models:
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:
contents: read
issues: write
pull-requests: 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 }}Gemini Setup
Ready-to-use workflow for Gemini models:
name: PR Agent (Gemini)
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:
contents: read
issues: write
pull-requests: write
steps:
- name: PR Agent action step
uses: the-pr-agent/pr-agent@main
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
config.model: "gemini/gemini-3.8-flash"
config.fallback_models: '[]'
GOOGLE_AI_STUDIO.GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
github_action_config.auto_review: "true"
github_action_config.auto_describe: "true"
github_action_config.auto_improve: "true"Claude Setup
Ready-to-use workflow for Claude models:
name: PR Agent (Claude)
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:
contents: read
issues: write
pull-requests: write
steps:
- name: PR Agent action step
uses: the-pr-agent/pr-agent@main
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
config.model: "anthropic/claude-opus-5"
config.fallback_models: '["anthropic/claude-haiku-4-5-20251001"]'
ANTHROPIC.KEY: ${{ secrets.ANTHROPIC_KEY }}
github_action_config.auto_review: "true"
github_action_config.auto_describe: "true"
github_action_config.auto_improve: "true"Basic Configuration with Command Controls
Start with this enhanced workflow that includes command configuration:
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:
contents: read
issues: write
pull-requests: 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 commands
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"]'Switching Models
Using Gemini (Google AI Studio)
To use Gemini models instead of the default OpenAI models:
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Set the model to Gemini
config.model: "gemini/gemini-3.8-flash"
config.fallback_models: '[]'
# Add your Gemini API key
GOOGLE_AI_STUDIO.GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
# Command configuration
github_action_config.auto_review: "true"
github_action_config.auto_describe: "true"
github_action_config.auto_improve: "true"Required Secrets:
- Add
GEMINI_API_KEYto your repository secrets (get it from Google AI Studio)
Note: When using non-OpenAI models like Gemini, you don't need to set OPENAI_KEY - only the model-specific API key is required.
Using Claude (Anthropic)
To use Claude models:
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Set the model to Claude
config.model: "anthropic/claude-opus-5"
config.fallback_models: '["anthropic/claude-haiku-4-5-20251001"]'
# Add your Anthropic API key
ANTHROPIC.KEY: ${{ secrets.ANTHROPIC_KEY }}
# Command configuration
github_action_config.auto_review: "true"
github_action_config.auto_describe: "true"
github_action_config.auto_improve: "true"Required Secrets:
- Add
ANTHROPIC_KEYto your repository secrets (get it from Anthropic Console)
Note: When using non-OpenAI models like Claude, you don't need to set OPENAI_KEY - only the model-specific API key is required.
Using Azure OpenAI
To use Azure OpenAI services:
env:
OPENAI_KEY: ${{ secrets.AZURE_OPENAI_KEY }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Azure OpenAI configuration
OPENAI.API_TYPE: "azure"
OPENAI.API_VERSION: "2023-05-15"
OPENAI.API_BASE: ${{ secrets.AZURE_OPENAI_ENDPOINT }}
OPENAI.DEPLOYMENT_ID: ${{ secrets.AZURE_OPENAI_DEPLOYMENT }}
# Set the model to match your Azure deployment
config.model: "gpt-4o"
config.fallback_models: '[]'
# Command configuration
github_action_config.auto_review: "true"
github_action_config.auto_describe: "true"
github_action_config.auto_improve: "true"Required Secrets:
AZURE_OPENAI_KEY: Your Azure OpenAI API keyAZURE_OPENAI_ENDPOINT: Your Azure OpenAI endpoint URLAZURE_OPENAI_DEPLOYMENT: Your deployment name
Using Local Models (Ollama)
To use local models via Ollama:
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Set the model to a local Ollama model
config.model: "ollama/qwen3.8:27b"
config.fallback_models: '[]'
config.reasoning_effort: "none"
config.additional_reasoning_effort_models: '["ollama/qwen3.8:27b"]'
config.custom_model_max_tokens: "32768" # match the Ollama server context for this example
# Ollama configuration
OLLAMA.API_BASE: "http://<ollama-host-reachable-from-container>:11434"
# Command configuration
github_action_config.auto_review: "true"
github_action_config.auto_describe: "true"
github_action_config.auto_improve: "true"Note: Ollama must be reachable from the action's Docker container. localhost inside that container refers to the container itself, not the runner host. If Ollama runs on a self-hosted runner, configure a host address and Ollama network binding that the action container can reach.
For a local Ollama endpoint, no OPENAI_KEY is needed. Follow the Ollama model configuration guide for the thinking controls and to size the server context and adjust config.custom_model_max_tokens accordingly.
Using Amazon Bedrock
To use Amazon Bedrock models with static IAM credentials:
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
config.model: "bedrock/us.anthropic.claude-sonnet-4-6"
config.fallback_models: '[]'
aws.AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws.AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws.AWS_REGION_NAME: "us-east-1"Recommended: IAM Role Credentials on AWS Compute
When the GitHub Actions runner is on AWS infrastructure (EC2, ECS, EKS), use the instance/task IAM role directly — no secrets required:
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
config.model: "bedrock/us.anthropic.claude-sonnet-4-6"
config.fallback_models: '[]'
AWS_USE_IMDS: "true"
AWS_REGION_NAME: us-east-1 # source region for the US inference profileThe IAM role must have bedrock:InvokeModel on the inference profile and its destination foundation models. See Bedrock model configuration for the full IAM policy example and supported models.
To route calls through a VPC interface endpoint, add AWS_BEDROCK_RUNTIME_ENDPOINT alongside the credentials above:
env:
AWS_BEDROCK_RUNTIME_ENDPOINT: "https://bedrock-runtime.us-east-1.amazonaws.com"Advanced Configuration Options
Custom Review Instructions
Add specific instructions for the review process:
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."
# Command configuration
github_action_config.auto_review: "true"
github_action_config.auto_describe: "true"
github_action_config.auto_improve: "true"Language-Specific Configuration
Configure for specific programming languages:
env:
OPENAI_KEY: ${{ secrets.OPENAI_KEY }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Language-specific settings
pr_reviewer.extra_instructions: "Focus on Python best practices, type hints, and docstrings."
pr_reviewer.num_max_findings: "5"
# Command configuration
github_action_config.auto_review: "true"
github_action_config.auto_describe: "true"
github_action_config.auto_improve: "true"Selective Command Execution
Run only specific commands automatically:
env:
OPENAI_KEY: ${{ secrets.OPENAI_KEY }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Only run review and describe; the review also runs when auto_improve is enabled
github_action_config.auto_review: "true"
github_action_config.auto_describe: "true"
github_action_config.auto_improve: "false"
# Only trigger on PR open and reopen
github_action_config.pr_actions: '["opened", "reopened"]'CI artifact context
A file produced by an earlier CI step — a test report, a coverage summary, a linter or SAST output — can be injected into the prompts of /review and /describe, so the model reviews the PR with your pipeline's own findings in hand.
Point the action at the file with the artifact_path input. The path is resolved relative to GITHUB_WORKSPACE (an absolute path also works), so the file must already exist in the workspace when PR-Agent runs — produce it in a previous step, or download it with actions/download-artifact:
steps:
- uses: actions/checkout@v4
- name: Run tests
run: pytest --junitxml=reports/pytest.xml || true
- name: PR Agent action step
uses: the-pr-agent/pr-agent@main
env:
OPENAI_KEY: ${{ secrets.OPENAI_KEY }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
artifact_path: reports/pytest.xml
artifact_instructions: "These are the failing tests from this PR's CI run. Call out any suggestion that would not fix them."Setting artifact_path turns the feature on by itself; there is no separate enable switch to flip in the workflow. Supported target commands receive a dedicated artifact section in their prompt. The label and file contents are explicitly marked as untrusted data, while artifact_instructions appears separately as subordinate analysis guidance. The supported targets are pr_reviewer, pr_description, pr_code_suggestions and pr_questions; unsupported names are skipped with a warning.
When overriding a supported command's prompt, keep artifact_context.instructions in the system prompt and renderartifact_context.label, artifact_context.content, artifact_context.start_marker, and artifact_context.end_marker in
a clearly marked, untrusted section of the user prompt. This replaces the legacy extra_instructions behavior for CI
artifacts.
The remaining knobs live in the [artifacts] section of your configuration:
[artifacts]
enable = true # required when configuring paths here
artifact_path = [
{ path = "reports/pytest.xml" },
{ path = "reports/coverage.xml" },
]
artifact_instructions = "" # empty = a generic "treat this as CI context" instruction
artifact_label = "" # shared label; empty = each file's name
target_commands = ["pr_reviewer", "pr_description", "pr_code_suggestions", "pr_questions"]
max_artifact_size = 50000 # characters; longer files are truncated with a markerartifact_path may also be a single string. For multiple files, each entry can setpath, artifact_label, artifact_instructions, target_commands, and truncate_from on
its own line; a shared artifact_label applies only to a single file, otherwise each file falls
back to its name.
Automatic enabling applies to the action's artifact_path input or the ARTIFACT_PATH / PR_AGENT_ARTIFACT_PATH environment variables. A path set only in [artifacts] requires enable = true.
CI artifacts are checked for recognizable URL credentials, authorization headers, standard GitLab tokens, AWS access keys, and common credential assignments before model submission, with redaction matches logged only by type and count; this pattern-based check does not recognize every secret format, so use sanitized CI logs as input.
:::note
A path that resolves outside GITHUB_WORKSPACE is rejected, and a missing or unreadable file is skipped with a warning — in both cases the commands still run, just without the artifact context.
:::
The same settings apply when PR-Agent runs as a CLI from another CI system, with ARTIFACT_PATH set in the job's environment; see the GitLab pipeline example.
Using Configuration Files
Instead of setting all options via environment variables, you can use a .pr_agent.toml file in your repository root:
Create a
.pr_agent.tomlfile in your repository root:toml[config] model = "gemini/gemini-3.8-flash" fallback_models = ["anthropic/claude-opus-5"] [pr_reviewer] extra_instructions = "Focus on security issues and code quality." [pr_code_suggestions] committable_code_suggestions = trueUse a simpler workflow file:
yamlon: 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: contents: read issues: write pull-requests: 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"
Troubleshooting Common Issues
Model Not Found Errors
If you get model not found errors:
Check model name format: Use the correct provider prefix (e.g.,
gemini/for Google AI Studio orvertex_ai/for Vertex AI).Verify API keys: Make sure your API keys are correctly set as repository secrets
Check model availability: Some models may not be available in all regions or may require specific access
Environment Variable Format
Remember these key points about environment variables:
- Use dots (
.) or double underscores (__) to separate sections and keys - Boolean values should be strings:
"true"or"false" - Arrays should be JSON strings:
'["item1", "item2"]' - Model names are case-sensitive
Rate Limiting
If you encounter rate limiting (HTTP 429 responses):
env:
OPENAI_KEY: ${{ secrets.OPENAI_KEY }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Add a fallback model for better reliability
config.fallback_models: '["your-fallback-model"]'
# Same-model retries of a 429, 5xx or connection error before fallback_models (default 4, max 10),
# each waiting for the provider's Retry-After or backing off. A quota error is retried but never recovers.
config.num_retries: "6"
# Increase timeout for slower models (does not help pure 429 rate-limit responses)
config.ai_timeout: "300"
github_action_config.auto_review: "true"
github_action_config.auto_describe: "true"
github_action_config.auto_improve: "true"A 429 is returned immediately; raising config.ai_timeout only bounds the duration of each individual request and does not change rate-limit behavior. Use config.num_retries (see pr_agent/settings/configuration.toml) for transient provider errors. Each model listed in config.fallback_models receives its own independent retry budget.
Common Error Messages and Solutions
Error: "Model not found"
- Solution: Check the model name format and ensure it matches the exact identifier. See the Changing a model in PR-Agent guide for supported models and their correct identifiers.
Error: "API key not found"
- Solution: Verify that your API key is correctly set as a repository secret and the environment variable name matches exactly
- Note: For non-OpenAI models (Gemini, Claude, etc.), you only need the model-specific API key, not
OPENAI_KEY
Error: "Incorrect API key provided: dummy_key"
- Cause: No usable key for the active model's provider reached the run. For automatic runs and commands other than bare
/help,/config, or/settings, the step log now showsStopping before any command runswith the missing variable named, and the job fails at once; older versions loggedOPENAI_KEY not setnear the top and carried on, so the request went out with PR-Agent's placeholder key instead and failed a full run later. - Note: For PR
issue_commentandpull_request_review_commentevents, bare/help,/config, and/settingsskip this model-key check (ignoring case and surrounding whitespace). They still needGITHUB_TOKEN; commands with arguments, including/help <question>, retain the check. - Solution: Check which of the three causes applies:
- The run gets no secrets. On the
pull_requestevent, runs triggered from a fork receive no repository secrets, so${{ secrets.OPENAI_KEY }}is empty. Use thepull_request_targetsetup instead. Dependabot pull requests are the same case: their secrets live under Dependabot secrets, not Actions secrets, and thegithub.event.sender.type != 'Bot'condition in the examples above keeps those runs from starting at all. - The secret is missing or misnamed. A reference to a secret that does not exist expands to an empty string rather than failing the workflow, so compare the name in the repository secrets with the one used in
env. - Another provider's key is set, but the model is not. Keys alone do not switch provider: set
config.model(andconfig.fallback_models) as well, otherwise the default OpenAI model is used and only an OpenAI key counts. See Changing a model in PR-Agent.
- The run gets no secrets. On the
Error: "Rate limit exceeded"
- Solution: Add fallback models and/or set
config.num_retries(recommended for transient 429s). Raisingconfig.ai_timeoutonly helps with timeouts, not pure rate-limit responses. For a manual/reviewfailure, you can also setpr_reviewer.publish_error_details: "true"in the workflowenv(it cannot be enabled via.pr_agent.toml) to surface a sanitized failure reason. See the Review command docs.
Error: "Permission denied"
- Solution: Ensure your workflow has the correct permissions set:The default commands need no additional scopes. Addyaml
permissions: contents: read issues: write pull-requests: writechecks: writewhengithub.publish_as_check_runorpr_reviewer.publish_merge_recommendation_statusis enabled. Features that push repository contents, such aspr_update_changelog.push_changelog_changes, requirecontents: write, and so doespr_questions.resolve_threads, because GitHub gates thread resolution on that scope. If you omitcontents: write, enableconfig.restricted_modeso operations that need it are skipped or fall
back safely, and keeppr_questions.resolve_threadsoff, since restricted mode does not cover it.
See the Restricted Mode guide for details.
Error: "PR-Agent command was not run" for incomplete GitHub files
- Cause: GitHub limits pull-request changed-file responses to 3,000 files. A mismatch can also occur when GitHub
returns inconsistent file-count metadata. - Solution: If the pull request changes more than 3,000 files, split it into smaller pull requests and run the
command again. Otherwise, retry the command.
Error: "Invalid JSON format"
- Solution: Check that arrays are properly formatted as JSON strings:
Correct:
config.fallback_models: '["model1", "model2"]'
Incorrect (interpreted as a YAML list, not a string):
config.fallback_models: ["model1", "model2"]Debugging Tips
- Enable verbose logging: Add
config.verbosity_level: "2"to see detailed logs - Check GitHub Actions logs: Look at the step output for specific error messages
- Test with minimal configuration: Start with just the basic setup and add options one by one
- Verify secrets: Double-check that all required secrets are set in your repository settings
Performance Optimization
For better performance with large repositories:
env:
OPENAI_KEY: ${{ secrets.OPENAI_KEY }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Optimize for large PRs
config.large_patch_policy: "clip"
config.patch_extra_lines_before: "3"
config.patch_extra_lines_after: "1"
github_action_config.auto_review: "true"
github_action_config.auto_describe: "true"
github_action_config.auto_improve: "true"Reference
For more detailed configuration options, see:
Using a specific release
:::tip
if you want to pin your action to a specific release (v0.41.0 for example) for stability reasons, use:
...
steps:
- name: PR Agent action step
id: pragent
uses: docker://pragent/pr-agent:0.41.0-github_action
...For enhanced security, you can also specify the Docker image by its digest. Resolve the digest for the version you are pinning with docker buildx imagetools inspect pragent/pr-agent:0.41.0-github_action --format '{{.Manifest.Digest}}', then use it in place of the tag:
...
steps:
- name: PR Agent action step
id: pragent
uses: docker://pragent/pr-agent@sha256:<digest>
...Official Docker Hub release images also publish GitHub Artifact Attestations, so you can verify that a pinned digest was built from this repository before using it:
gh attestation verify \
"oci://index.docker.io/pragent/pr-agent@sha256:<digest>" \
--repo The-PR-Agent/pr-agent:::
Action for GitHub enterprise server or GHE.com
:::tip
To use the action with a GitHub enterprise server, add an environment variable GITHUB__BASE_URL with the API URL of your GitHub server.
For example, if your GitHub server is at https://github.mycompany.com, add the following to your workflow file:
env:
# ... previous environment values
GITHUB__BASE_URL: "https://github.mycompany.com/api/v3"For GitHub Enterprise Cloud with data residency (GHE.com), set GITHUB__BASE_URL to the API host https://api.<subdomain>.ghe.com, which the workflow exposes as github.api_url:
env:
# ... previous environment values
GITHUB__BASE_URL: ${{ github.api_url }} # e.g. https://api.mycompany.ghe.com:::
Run as a GitHub App
Allowing you to automate the review process on your private or public repositories.
Create a GitHub App from the GitHub Developer Portal.
- Set the following permissions:
- Pull requests: Read & write
- Issues: Read & write
- Metadata: Read-only
- Contents: Read-only (or Read & write if using
resolve_threads— see note below)
- Set the following events:
- Issue comment
- Pull request
- Pull request review
- Push (if you need to enable triggering on PR update)
- Pull request review comment (required for
/askon review threads)
Note: If you enable
pr_questions.resolve_threads, the GitHub App requires Contents: Read & write permission. GitHub'sresolveReviewThreadGraphQL mutation is gated behind the Contents permission, even though it only modifies PR thread metadata. See GitHub community discussion for details.Important: When enabled, the LLM may resolve threads started by
human reviewers — not only bot-generated threads. Use this setting
only when your team is comfortable with AI-driven thread resolution.
The feature is opt-in and defaults to off.- Set the following permissions:
Generate a random secret for your app, and save it for later. The webhook secret is required: if
GITHUB.WEBHOOK_SECRETis not configured, the server rejects every incoming webhook with HTTP 403. For example, you can use:bashWEBHOOK_SECRET=$(python -c "import secrets; print(secrets.token_hex(10))")Acquire the following pieces of information from your app's settings page:
- App private key (click "Generate a private key" and save the file)
- App ID
Clone this repository:
bashgit clone https://github.com/the-pr-agent/pr-agent.git cd pr-agentCopy the secrets template file and fill in the following:
bashcp pr_agent/settings/.secrets_template.toml pr_agent/settings/.secrets.toml # Edit .secrets.toml file- Your OpenAI key.
- Copy your app's private key to the private_key field.
- Copy your app's ID to the app_id field.
- Copy your app's webhook secret to the webhook_secret field (required).
- The GitHub App sets
deployment_typetoappautomatically by default. No manual configuration is needed unlessgithub_app.override_deployment_typeis disabled.
The local
.secrets.tomlfile is excluded from the Docker build context. Never bake secrets into a container image.
For container deployments, provide secrets at runtime through environment variables or a mounted secret volume.
For example, in order to inject a secrets file as a volume in a Kubernetes environment you can update your pod spec to include the following,
assuming you have a secret namedpr-agent-settingswith a key named.secrets.toml:textvolumes: - name: settings-volume secret: secretName: pr-agent-settings // ... containers: // ... volumeMounts: - mountPath: /app/pr_agent/settings_prod name: settings-volumeService images run as UID/GID
10001: mounted secrets must be readable, and mounted data paths writable, by that user.
Home-relative mounts belong under/home/pragent.Another option is to set the secrets as environment variables in your deployment environment, for example
OPENAI__KEY,GITHUB__APP_ID,GITHUB__PRIVATE_KEY, andGITHUB__WEBHOOK_SECRET.Build a Docker image for the app and optionally push it to a Docker repository. We'll use Dockerhub as an example:
bashdocker build . -t pr-agent:github_app --target github_app -f docker/Dockerfile # Optional, to push it to your own Docker repository: docker tag pr-agent:github_app <your-registry>/pr-agent:github_app docker push <your-registry>/pr-agent:github_appHost the app using a server, serverless function, or container environment. Alternatively, for development and
debugging, you may use tools like smee.io to forward webhooks to your local machine.
You can check Deploy as a Lambda FunctionGo back to your app's settings, and set the following:
- Webhook URL:
https:///api/v1/github_webhooks, or your smee.io channel URL with forwarding configured to that endpoint. - Webhook secret: The secret you generated earlier.
- Webhook URL:
Install the app by navigating to the "Install App" tab and selecting your desired repositories.
The app runs under gunicorn with multiple worker processes. See Sizing a self-hosted webhook server for the
GUNICORN_WORKERS/GUNICORN_MAX_WORKERSknobs and memory guidance — worth reading before setting a memory limit.
Note: When running PR-Agent from GitHub app, the default configuration file (configuration.toml) will be loaded.
However, you can override the default command parameters by uploading a local configuration file.pr_agent.toml
To use organization-level global configuration, setconfig.global_settings_repo = "pr-agent-settings", create<organization>/pr-agent-settingswith a.pr_agent.tomlfile, and install the GitHub App on that repository too.
The app needs read access to the settings repository as well as the pull request repositories. This applies to both GitHub.com and GitHub Enterprise Server.
For more information please check out the USAGE GUIDE
Additional deployment methods
Deploy as a Lambda Function
Note that since AWS Lambda env vars cannot have "." in the name, you can replace each "." in an env variable with "__".
For example: GITHUB.WEBHOOK_SECRET --> GITHUB__WEBHOOK_SECRET
Follow steps 1-5 from here.
Build a docker image that can be used as a lambda function
shelldocker buildx build --platform=linux/amd64 . -t pr-agent:github_lambda --target github_lambda -f docker/Dockerfile.lambda(Note: --target github_lambda is optional as it's the default target)
Push image to ECR
shelldocker tag pr-agent:github_lambda <AWS_ACCOUNT>.dkr.ecr.<AWS_REGION>.amazonaws.com/pr-agent:github_lambda docker push <AWS_ACCOUNT>.dkr.ecr.<AWS_REGION>.amazonaws.com/pr-agent:github_lambdaCreate a lambda function that uses the uploaded image. Add the IAM permission
lambda:InvokeFunctionon the function itself to the execution role: the webhook is acknowledged as soon as its signature is verified, and the review runs in a second, asynchronous invocation of the same function. Set the lambda timeout for the review length (for example 5m) — it no longer needs to cover the webhook acknowledgement. Lambda retries a timed-out or failed asynchronous invocation twice by default, which would run the review again; set the function's asynchronous invocation retry attempts to 0 if you do not want that.Configure the lambda function to have a Function URL.
Go back to steps 8-9 of Method 5 with the function url as your Webhook URL.
The Webhook URL would look likehttps://<LAMBDA_FUNCTION_URL>/api/v1/github_webhooks
Using AWS Secrets Manager
For production Lambda deployments, use AWS Secrets Manager instead of environment variables:
Create a secret in AWS Secrets Manager with JSON format like this:
json{ "openai.key": "sk-proj-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "github.app_id": 123456, "github.webhook_secret": "your-webhook-secret-from-step-2", "github.private_key": "-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA...\n-----END RSA PRIVATE KEY-----" }Add IAM permission
secretsmanager:GetSecretValueto your Lambda execution roleSet these environment variables in your Lambda:
bashAWS_SECRETS_MANAGER__SECRET_ARN=arn:aws:secretsmanager:us-east-1:123456789012:secret:pr-agent-secrets-AbCdEf CONFIG__SECRET_PROVIDER=aws_secrets_manager
AWS CodeCommit Setup
Not all features have been added to CodeCommit yet. As of right now, CodeCommit has been implemented to run the PR-Agent CLI on the command line, using AWS credentials stored in environment variables. CodeCommit pull requests with multiple targets are reviewed across every target repository and commit comparison; single-target pull requests keep the same behavior. The following is a set of instructions to have PR-Agent do a review of your CodeCommit pull request from the command line:
- Create an IAM user that you will use to read CodeCommit pull requests and post comments
- Note: That user should have CLI access only, not Console access
- Add IAM permissions to that user, to allow access to CodeCommit (see IAM Role example below)
- Generate an Access Key for your IAM user
- Set the Access Key and Secret using environment variables (see Access Key example below)
- Set the
git_providervalue tocodecommitin thepr_agent/settings/configuration.tomlsettings file - Set the
PYTHONPATHto include yourpr-agentproject directory- Option A: Run
export PYTHONPATH="/PATH/TO/PROJECTS/pr-agent"in your shell. PR-Agent does not automatically load.envfiles. - Option B: Set
PYTHONPATHand run the CLI in one command, for example:PYTHONPATH="/PATH/TO/PROJECTS/pr-agent" python pr_agent/cli.py [--ARGS]
- Option A: Run
AWS CodeCommit IAM Role Example
Example IAM permissions to that user to allow access to CodeCommit:
- Note: The following is a working example of IAM permissions that has read access to the repositories and write access to allow posting comments
- Note: If you only want pr-agent to review your pull requests, you can tighten the IAM permissions further, however this IAM example will work, and allow the pr-agent to post comments to the PR
- Note: You may want to replace the
"Resource": "*"with your list of repos, to limit access to only those repos
{
"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:UpdateComment",
"codecommit:UpdatePullRequestDescription",
"codecommit:UpdatePullRequestTitle"
],
"Resource": "*"
}
]
}AWS CodeCommit Access Key and Secret
Example setting the Access Key and Secret using environment variables
export AWS_ACCESS_KEY_ID="XXXXXXXXXXXXXXXX"
export AWS_SECRET_ACCESS_KEY="XXXXXXXXXXXXXXXX"
export AWS_DEFAULT_REGION="us-east-1"AWS CodeCommit CLI Example
After you set up AWS CodeCommit using the instructions above, here is an example CLI run that tells pr-agent to review a given pull request.
(Replace your specific PYTHONPATH and PR URL in the example)
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 \
reviewDocs Installation Gitlab (`docs/docs/installation/gitlab.md`)
title: "GitLab Integration" sidebar_position: 5
Merge request diff limits
PR-Agent requires GitLab 15.7 or later and retrieves all pages from the merge request/diffs endpoint.
Pagination does not bypass GitLab's server-side diff limits. PR-Agent raises a provider
error if the returned file count disagrees with an exact changes_count, or that count
indicates overflow or is not ready. A file whose patch GitLab omits (too_large, orcollapsed before GitLab 19.2) is diffed locally from its two revisions instead.
When CONFIG.PUBLISH_OUTPUT is enabled, PR-Agent attempts to post a fixed, deduplicated
PR-Agent command was not run notice after this error reaches the command boundary.
Publishing is best effort and never includes internal GitLab response details.
The /diffs endpoint must be available. PR-Agent does not fall back to the deprecated/changes endpoint or its raw-diff retry.
PR-Agent reads fresh merge request metadata before and after collecting the diff pages.
If the revision or file count changes during collection, it retries once, then raises a
provider error if they change again. Non-empty results also require usable base/head
references for loading file content. If the merge request moves after incremental
setup, PR-Agent falls back to a full review instead of mixing revisions.
Optional submodule diff expansion
When GITLAB.EXPAND_SUBMODULE_DIFFS is enabled, PR-Agent compares submodule commits
to add child-file patches. If the comparison times out or a child patch is omitted
(collapsed or too_large), it logs a warning and skips that optional expansion.
The parent submodule gitlink remains in the merge request diff. This repository
comparison fallback is separate from the merge-request /diffs behavior above.
Run as a GitLab Pipeline
You can use a pre-built Action Docker image to run PR-Agent as a GitLab pipeline. This is a simple way to get started with PR-Agent without setting up your own server.
Pipeline mode runs configured commands automatically when GitLab creates a merge request pipeline. It does not receive GitLab comment events. If you want users to invoke commands such as /review or /improve in merge request comments, deploy the GitLab webhook server instead and enable the Comments webhook trigger.
Step 1: Configure the pipeline
Add the following file to your repository under .gitlab-ci.yml:
stages:
- pr_agent
pr_agent_job:
stage: pr_agent
image:
name: pragent/pr-agent:latest
entrypoint: [""]
script:
- cd /app
- echo "Running PR Agent action step"
- export MR_URL="$CI_MERGE_REQUEST_PROJECT_URL/merge_requests/$CI_MERGE_REQUEST_IID"
- echo "MR_URL=$MR_URL"
- export gitlab__url=$CI_SERVER_PROTOCOL://$CI_SERVER_FQDN
- export gitlab__PERSONAL_ACCESS_TOKEN=$GITLAB_PERSONAL_ACCESS_TOKEN
- export config__git_provider="gitlab"
- export openai__key=$OPENAI_KEY
- python -m pr_agent.cli --pr_url="$MR_URL" describe
- python -m pr_agent.cli --pr_url="$MR_URL" review
- python -m pr_agent.cli --pr_url="$MR_URL" improve
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'For published PR-Agent releases through v0.50.0, review identifies
potential issues and improve provides separate code suggestions. In newer
versions, both commands produce a review that may include suggested fixes.
If your version has this behavior, remove the improve step above to avoid
reviewing the same merge request twice.
This script runs PR-Agent when a merge request pipeline is created, including when a merge request is opened and when new commits are pushed to its source branch. You can modify the rules section to run PR-Agent on different events.
You can also modify the script section to run different PR-Agent commands, or with different parameters by exporting different environment variables.
Step 2: Configure CI/CD variables
Add the following masked variables to your GitLab repository (CI/CD -> Variables):
GITLAB_PERSONAL_ACCESS_TOKEN: Your GitLab personal access token.OPENAI_KEY: Your OpenAI key.
Note that if your base branches are not protected, don't set the variables as protected, since the pipeline will not have access to them.
Note: The
$CI_SERVER_FQDNvariable is available starting from GitLab version 16.10. If you're using an earlier version, this variable will not be available. However, you can combine$CI_SERVER_HOSTand$CI_SERVER_PORTto achieve the same result. Please ensure you're using a compatible version or adjust your configuration.
Note: The
gitlab__SSL_VERIFYenvironment variable can be used to specify the path to a custom CA certificate bundle for SSL verification. GitLab exposes the$CI_SERVER_TLS_CA_FILEvariable, which points to the custom CA certificate file configured in your GitLab instance.
Alternatively, SSL verification can be disabled entirely by settinggitlab__SSL_VERIFY=false, although this is not recommended.
This setting affects only the GitLab API client. For certificate issues with LLM calls or git clone operations, see Custom CA and Self-Signed Certificates.
Optional pipeline configurations
CI artifact context
A file produced by an earlier job — a test report, a coverage summary, a linter or SAST output — can be handed to /review, /describe and /ask as extra context, so the model reviews the merge request with your pipeline's own findings in hand. Save the file as a job artifact, make the PR-Agent job depend on that job with needs:, and point PR-Agent at it with ARTIFACT_PATH. The job above runs from /app, so give the path in full:
pr_agent_job:
stage: pr_agent
needs: ["test_job"]
image:
name: pragent/pr-agent:latest
entrypoint: [""]
script:
- cd /app
- export ARTIFACT_PATH="$CI_PROJECT_DIR/reports/pytest.xml"
- export ARTIFACT_INSTRUCTIONS="These are the failing tests from this MR's pipeline. Call out any suggestion that would not fix them."
- python -m pr_agent.cli --pr_url="$MR_URL" reviewSetting ARTIFACT_PATH turns the feature on by itself. The remaining knobs — which commands receive the context, the label, the size limit — are the [artifacts] settings described under CI artifact context for the GitHub Action, and they apply to the CLI in the same way.
Ignore bot-created merge requests
Dependency update bots usually use predictable source branch prefixes. Add a higher-priority when: never rule before the general merge request rule to skip those branches:
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_SOURCE_BRANCH_NAME =~ /^(dependabot|renovate)\//'
when: never
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'Adjust the regular expression to match the branch naming conventions used by your bots. Filtering on CI_MERGE_REQUEST_SOURCE_BRANCH_NAME is more reliable than GITLAB_USER_LOGIN, because GITLAB_USER_LOGIN identifies the user who started the pipeline and can change when a pipeline is run manually.
The webhook server can apply the equivalent filter to automatic merge request events through a repository-level .pr_agent.toml file:
[config]
ignore_pr_source_branches = ["^(dependabot|renovate)/"]For all supported filters, see Ignoring automatic commands in PRs.
Run a GitLab webhook server
In GitLab create a new user and give it "Developer" role for the intended group or project.
Note: "Reporter" role is sufficient for adding comments for
/improveor/reviewfor example,
but "Developer" role is required to update the Merge Request description when using the/describecommand.For the user from step 1, generate a
personal_access_tokenwithapiaccess.Generate a random secret for your app, and save it for later (
shared_secret). For example, you can use:bashSHARED_SECRET=$(python -c "import secrets; print(secrets.token_hex(10))")Clone this repository:
bashgit clone https://github.com/the-pr-agent/pr-agent.git cd pr-agentPrepare variables and secrets. Skip this step if you plan on setting these as environment variables when running the agent:
In the configuration file/variables:
- Set
config.git_providerto "gitlab"
- Set
In the secrets file/variables:
- Set your AI model key in the respective section
- In the [gitlab] section, set
personal_access_token(with token from step 2) andshared_secret(with secret from step 3) - Authentication type: Set
auth_typeto"private_token"to send the token in thePRIVATE-TOKENheader, or use the default"oauth_token"for theAuthorization: Bearerheader. Both are supported on GitLab.com and self-managed instances.
Build a Docker image for the app and optionally push it to a Docker repository. We'll use Dockerhub as an example:
bashdocker build . -t pr-agent:gitlab_webhook --target gitlab_webhook -f docker/Dockerfile # Optional, to push it to your own Docker repository: docker tag pr-agent:gitlab_webhook <your-registry>/pr-agent:gitlab_webhook docker push <your-registry>/pr-agent:gitlab_webhookSet the environmental variables, the method depends on your docker runtime. Secrets can also be provided through a mounted
.secrets.tomlfile. The supported secrets files are excluded from the Docker build context; do not bake secrets into the image.bashCONFIG__GIT_PROVIDER=gitlab GITLAB__PERSONAL_ACCESS_TOKEN=<personal_access_token> GITLAB__SHARED_SECRET=<shared_secret> GITLAB__URL=https://gitlab.com GITLAB__AUTH_TYPE=oauth_token # Use "private_token" for the PRIVATE-TOKEN header OPENAI__KEY=<your_openai_api_key> PORT=3000 # Optional: override the webhook server portCreate a webhook in your GitLab project. Set the URL to
http[s]:///webhook, the secret token to the generated secret from step 3, and enable thecommentsandmerge request eventstriggers. The separatepushtrigger is not required for merge request push commands.Test your installation by opening a merge request or commenting on a merge request using one of PR Agent's commands.
The webhook server runs under gunicorn with multiple worker processes. See Sizing a self-hosted webhook server for the
GUNICORN_WORKERS/GUNICORN_MAX_WORKERSknobs and memory guidance — worth reading before setting a memory limit.
Deploy as a Lambda Function
Note that since AWS Lambda env vars cannot have "." in the name, you can replace each "." in an env variable with "__".
For example: GITLAB.PERSONAL_ACCESS_TOKEN --> GITLAB__PERSONAL_ACCESS_TOKEN
Follow steps 1-5 from Run a GitLab webhook server.
Build a docker image that can be used as a lambda function
shelldocker buildx build --platform=linux/amd64 . -t pr-agent:gitlab_lambda --target gitlab_lambda -f docker/Dockerfile.lambdaPush image to ECR
shelldocker tag pr-agent:gitlab_lambda <AWS_ACCOUNT>.dkr.ecr.<AWS_REGION>.amazonaws.com/pr-agent:gitlab_lambda docker push <AWS_ACCOUNT>.dkr.ecr.<AWS_REGION>.amazonaws.com/pr-agent:gitlab_lambdaCreate a lambda function that uses the uploaded image. Add the IAM permission
lambda:InvokeFunctionon the function itself to the execution role: the webhook is acknowledged as soon as its token is validated, and the review runs in a second, asynchronous invocation of the same function. Set the lambda timeout for the review length (for example 5m) — it no longer needs to cover the webhook acknowledgement. Lambda retries a timed-out or failed asynchronous invocation twice by default, which would run the review again; set the function's asynchronous invocation retry attempts to 0 if you do not want that.Configure the lambda function to have a Function URL.
Go back to steps 8-9 of Run a GitLab webhook server with the function URL as your Webhook URL.
The Webhook URL would look likehttps://<LAMBDA_FUNCTION_URL>/webhook
The asynchronous hand-off carries the verified payload, event UUID and authentication
outcome, without forwarding X-Gitlab-Token or the GitLab personal access token. For
secret-provider authentication it carries only the resolved secret name; the worker
loads the current API credential from that secret. Shared-secret deliveries use the
worker's host configuration. Accepted deliveries are not re-authenticated against the
original webhook token, so webhook-token rotation does not cancel queued work. Removing
the project secret or its API credential prevents that work from being dispatched.
Only trusted IAM principals should have lambda:InvokeFunction permission: the worker
trusts the authentication outcome of direct hand-off events. Public Function URL requests
still pass through webhook authentication and cannot supply this internal event envelope.
Hand-offs queued by older versions contain the webhook token and lack the new authentication
outcome. They are rejected after upgrading; drain pending invocations before deployment.
Existing retry queues, dead-letter queues and on-failure destinations may still contain
old token-bearing payloads; account for their access controls and retention when rotating
webhook credentials. New hand-offs do not forward those credentials to failure destinations.
Using AWS Secrets Manager
For production Lambda deployments, use AWS Secrets Manager instead of environment variables:
Generate a separate random webhook token for each project, for example with
openssl rand -hex 32.
Create an individual secret for each GitLab webhook with this JSON format (e.g., secret name:project-webhook-secret-001):json{ "gitlab_token": "glpat-xxxxxxxxxxxxxxxxxxxxxxxx", "webhook_token": "<generated-random-webhook-token>", "token_name": "project-webhook-001" }Create a main configuration secret for common settings (e.g., secret name:
pr-agent-main-config)json{ "openai.key": "sk-proj-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" }Set these environment variables in your Lambda:
bashCONFIG__SECRET_PROVIDER=aws_secrets_manager AWS_SECRETS_MANAGER__SECRET_ARN=arn:aws:secretsmanager:us-east-1:123456789012:secret:pr-agent-main-config-AbCdEfIn your GitLab webhook configuration, set the Secret Token to
<secret-name>:<webhook-token>:- Example:
project-webhook-secret-001:<generated-random-webhook-token> - Use the random token stored in the
webhook_tokenfield, not the GitLab personal access token. - The final colon separates the token from the secret name, so the webhook token must not contain colons.
- Example:
PR-Agent retrieves the JSON by secret name and compares the supplied token with webhook_token before
using gitlab_token. Both fields must be nonempty strings. The secret name alone is not a credential.
- Add IAM permission
secretsmanager:GetSecretValueto your Lambda execution role
:::important Migration for existing secret-provider deployments
Add webhook_token to each project secret and update the corresponding GitLab Secret Token to<secret-name>:<webhook-token> when deploying this version. Existing name-only tokens are rejected with
HTTP 401; coordinate the server and webhook updates to avoid interrupted deliveries. The same format
applies to the Google Cloud Storage secret provider.
Deployments using GITLAB.SHARED_SECRET keep their existing token. A matching shared secret is checked
first and uses the configured GITLAB.PERSONAL_ACCESS_TOKEN without contacting the cloud provider.
:::
Docs Installation Locally (`docs/docs/installation/locally.md`)
title: "Locally" sidebar_position: 3
To run PR-Agent locally, you first need to acquire two keys:
Local execution has two distinct cases: use the hosted-provider examples below for an existing PR/MR URL, or use the Local Git Provider guide for branch comparisons without a hosted PR/MR.
- An API key for your configured language model provider. For OpenAI, create one here.
- A personal access token from your Git platform (GitHub, GitLab, BitBucket, Gitea) with repo scope. GitHub token, for example, can be issued from here
Using Docker image
A list of the relevant commands can be found in the commands guide.
To invoke a command (for example review), you can run PR-Agent directly from the Docker image. Here's how:
For GitHub:
bashdocker run --rm -it -e OPENAI__KEY=<your_openai_key> -e GITHUB__USER_TOKEN=<your_github_token> pragent/pr-agent:latest --pr_url <pr_url> reviewIf you are using GitHub enterprise server, you need to specify the custom url as variable.
For example, if your GitHub server is athttps://github.mycompany.com, add the following to the command:bash-e GITHUB__BASE_URL=https://github.mycompany.com/api/v3For GitHub Enterprise Cloud with data residency (GHE.com), use the API host instead:
bash-e GITHUB__BASE_URL=https://api.mycompany.ghe.comFor GitLab:
bashdocker run --rm -it -e OPENAI__KEY=<your key> -e CONFIG__GIT_PROVIDER=gitlab -e GITLAB__PERSONAL_ACCESS_TOKEN=<your token> pragent/pr-agent:latest --pr_url <pr_url> reviewIf you have a dedicated GitLab instance, you need to specify the custom url as variable:
bash-e GITLAB__URL=<your gitlab instance url>For BitBucket:
bashdocker 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=<pr_url> reviewFor Gitea:
bashdocker run --rm -it -e OPENAI__KEY=<your key> -e CONFIG__GIT_PROVIDER=gitea -e GITEA__PERSONAL_ACCESS_TOKEN=<your token> pragent/pr-agent:latest --pr_url <pr_url> reviewIf you have a dedicated Gitea instance, you need to specify the custom url as variable:
bash-e GITEA__URL=<your gitea instance url>
For other git providers, update CONFIG__GIT_PROVIDER accordingly and check the pr_agent/settings/.secrets_template.toml file for environment variables expected names and values.
Utilizing environment variables
It is also possible to provide or override the configuration by setting the corresponding environment variables.
You can define the corresponding environment variables by following this convention: __<KEY>=<VALUE> or .<KEY>=<VALUE>.
The `` refers to a table/section in a configuration file and <KEY>=<VALUE> refers to the key/value pair of a setting in the configuration file.
For example, suppose you want to run pr_agent that connects to a self-hosted GitLab instance similar to an example above.
You can define the environment variables in a plain text file named .env with the following content:
CONFIG__GIT_PROVIDER="gitlab"
GITLAB__URL="<your url>"
GITLAB__PERSONAL_ACCESS_TOKEN="<your token>"
OPENAI__KEY="<your key>"Then, you can run pr_agent using Docker with the following command:
docker run --rm -it --env-file .env pragent/pr-agent:latest --pr_url <pr_url> <command> <command parameter>I get an error when running the Docker image. What should I do?
If you encounter an error when running the Docker image, it is almost always due to a misconfiguration of api keys or tokens.
Note that litellm, which is used by pr-agent, sometimes returns non-informative error messages such as APIError: OpenAIException - Connection error.
Carefully check the api keys and tokens you provided and make sure they are correct.
Adjustments may be needed depending on your llm provider.
For example, for Azure OpenAI, additional keys are needed.
Same goes for other providers, make sure to check the documentation
Using pip package
Install the package:
pip install "pr-agent[github]"Git provider SDKs are optional extras, so install the one for your provider: github, gitlab, bitbucket (Bitbucket Cloud, Bitbucket Server and Jira), azure, codecommit or gitea.google adds Vertex AI, mosaico adds the Mosaico server, and pr-agent[all] installs every integration.
Then run the relevant command with the script below.
Make sure to fill in the required parameters (user_token, openai_key, pr_url, command):
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
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
return cli.run_command(pr_url, command)
if __name__ == '__main__':
raise SystemExit(main())For other providers, change provider to its provider ID (for example, gitlab, bitbucket, or azure) and replace github.user_token with that provider's required credentials and connection settings.
Forwarding the return value through SystemExit makes this script exit with status 1 when the request fails or a command records a failure, whether or not config.propagate_command_errors is enabled.
The Python helper accepts quoted arguments, for examplecli.run_command(pr_url, "/review --pr_reviewer.extra_instructions='be concise please'").
It uses the same quoting rules as configured automation commands: explicitly
quoted setting values stay strings, and unquoted values retain their normal
types. For questions containing apostrophes, use double quotes around the
question, such as command = '/ask "What\'s changed?"'.
This does not change how interactive PR comments are parsed.
Run from source
Clone this repository:
bashgit clone https://github.com/the-pr-agent/pr-agent.gitNavigate to the
/pr-agentfolder and install dependencies with uv (creates a.venvfromuv.lock):bashuv syncNote: If you get an error related to Rust in the dependency installation then make sure Rust is installed and in your
PATH, instructions: https://rustup.rsCopy the secrets template file and fill in your OpenAI key and your GitHub user token:
bashcp pr_agent/settings/.secrets_template.toml pr_agent/settings/.secrets.toml chmod 600 pr_agent/settings/.secrets.toml # Edit .secrets.toml fileRun the cli.py script:
bashuv run pr-agent --pr_url <pr_url> review uv run pr-agent --pr_url <pr_url> ask "<your question>" uv run pr-agent --pr_url <pr_url> describe uv run pr-agent --pr_url <pr_url> add_docs uv run pr-agent --pr_url <pr_url> generate_labels uv run pr-agent --issue_url <issue_url> similar_issue ...Note: the
similar_issuecommand needs extra dependencies that a bareuv syncdoes not install. Install them withuv sync --group similar-issuebefore running it.
Save a hosted PR review without publishing
To inspect a real GitHub PR or GitLab MR locally, save the review as Markdown
without posting comments, labels, or approvals to the hosting platform:
uv run pr-agent --pr_url https://github.com/owner/repo/pull/123 --output review.md reviewThe --output option must appear before the command. It works with review,review_pr, improve, and improve_code (improve runs review). The command
runs a single full-PR review even when per-commit review is configured. It
still requires the normal Git provider and model credentials and makes the
usual read-only API and model requests. It creates the Markdown file only after
a completed review with valid repository settings; missing results, invalid
settings, or file-write failures return a nonzero exit without replacing an
existing Markdown file. Plain-diff commands retain their existing --output
behavior; other hosted commands do not accept this option.
When running from a checkout that contains untrusted changes (such as a CI job),
choose an output directory that PR contributors cannot modify. Existing output
symlinks are followed, so the destination path must be trusted.
[Optional] Add the pr_agent folder to your PYTHONPATH
export PYTHONPATH=$PYTHONPATH:<PATH to pr_agent folder>Docs Installation Mosaico Server (`docs/docs/installation/mosaico_server.md`)
title: "MOSAICO A2A Server" sidebar_position: 9
PR-Agent can run as an A2A 1.0 solution agent for the
MOSAICO ecosystem: a small Starlette server that exposes the
standard A2A surface (agent card + JSON-RPC) plus a health probe. It is not a fork or a
separate project — the server is PR-Agent code under pr_agent/mosaico/,
ships in every release wheel, and ships as its own Docker image (<version>-mosaico_agent)
starting at v0.36.0. The server is unbiased about the git provider: every request carries
either a PR URL or a raw diff. Follow-up messages can refer to that input by reusing the
returned contextId; the server considers up to 100 prior tasks in the same context by default
to find the latest PR URL or diff. Set mosaico.context_history_max_tasks (1 to 1000) to change
this limit. Task history is kept in memory, so send the input again after a restart or
when routing a follow-up to a different server replica.
What the mode is
The A2A server exposes three endpoints:
| Path | Method | Purpose |
|---|---|---|
/.well-known/agent-card.json |
GET | The A2A agent card |
/ |
POST | A2A 1.0 JSON-RPC. Sends the SendMessage method with an A2A-Version: 1.0 header (the header is required: the server treats a request without it as protocol 0.3 and rejects it). The reply arrives as a task artifact (result.task.artifacts[].parts[].text), not as a status message. |
/health |
GET | A live LLM connectivity probe — 200 when an LLM round-trip succeeds, 503 otherwise |
Images with health-probe hardening return Unhealthy: LLM probe failed for provider
failures; the health check's own warning records only the exception type.mosaico.health_timeout_seconds sets a finite positive deadline in seconds (default: 10)
for cooperative asynchronous preparation, dispatch, stream consumption, and cleanup waiting.
Stream cleanup can continue in the background after this deadline. Synchronous
initialization and blocking SDK work can still exceed it.
Older images may predate these protections.
Set MOSAICO__HEALTH_TIMEOUT_SECONDS in the server's environment to override the default.
Invalid values produce the generic unhealthy response (503), rather than using the default.
When increasing the budget, also allow sufficient time in any external health-check client
and container healthcheck; the bundled Compose probe uses a separate 25-second HTTP timeout.
Chat and health-probe streams attempt cleanup on completion, failure, or cancellation.
Consumer cancellation does not interrupt stream cleanup, which may continue after /health
times out while the event loop remains active. Cleanup has no separate wait budget or
configuration key and does not impose a local stream admission limit.
The advertised agent card carries the skills review, improve, describe, and ask, the
name "PR-Agent Solution Agent", a version derived from the running build (never
hand-maintained), and the requiredhttps://mosaico-project.eu/extensions/mosaico-observability extension. Streaming is
advertised as disabled, which is load-bearing: the reference agent selectsmessage/send vs message/stream from that capability.
Request limits and caller authentication
MOSAICO uses the shared config.max_webhook_request_body_bytes limit (5 MiB by default),
including streamed bodies without a valid Content-Length. Oversized requests return HTTP 413
before JSON-RPC parsing or command execution. mosaico.routing_scan_max_chars (default: 65536,
a positive integer) bounds PR URL and command detection per text segment. An incomplete token
at the boundary is ignored; supplied diffs are still processed in full. Put the PR URL or
command near the start of the message or its surrounding prose.
Configure mosaico.bearer_tokens as a map of stable principal names to distinct opaque secrets
in secret settings, or as a TOML inline table in the environment:
export MOSAICO__BEARER_TOKENS='{"reference-agent"="replace-with-generated-secret"}'The container does not inherit host exports; pass the map when you start it, for example with-e MOSAICO__BEARER_TOKENS or --env-file. An env file takes the value literally, so write it
without the surrounding shell quotes.
With a nonempty map, JSON-RPC and /health require Authorization: Bearer <secret>.
Missing or invalid credentials return HTTP 401 before reading the body or running the LLM.
The agent-card GET stays public and advertises the bearer requirement without exposing secrets.
Use HTTPS at your ingress and configure the caller to send its credential. Tasks, artifacts,
histories and context follow-ups are scoped to the configured principal; callers sharing a
secret share that principal. Keep principal names stable when rotating secrets. Invalid
credential maps, including duplicate secrets, fail app construction.
The default empty map preserves anonymous access and shared task ownership for a trusted,
single-tenant network. Configure authentication before exposing the service to other callers.
The in-memory store retains up to mosaico.task_store_max_tasks_per_owner tasks per owner and
evicts the oldest tasks beyond that limit; evicted tasks lose follow-up history. This is not a
rate limit or concurrency quota, and retained tasks are still lost on restart. Each authorized
health probe performs a live completion.
Observability root/super task IDs must be canonical UUIDs. Invalid IDs are omitted independently;
valid IDs are normalized to lowercase before producing Langfuse trace context. A metadata error
does not fail the review.
For the bundled smoke test, provide the client credential as MOSAICO_BEARER_TOKEN in the
script's environment when the server map is configured. For the Compose overlay, supplyPR_AGENT_BEARER_TOKEN for the healthcheck and add MOSAICO__BEARER_TOKENS to the service'senvironment mapping through your secret configuration. Configure the reference caller's
credential separately. Both probes continue to work without a token in anonymous mode.
Run the standalone container
The server boots from a bare docker pull in a couple of seconds — no repo clone, no build:
docker pull pragent/pr-agent:0.50.0-mosaico_agent
docker run -d --name pr-agent-mosaico -p 9000:9000 \
-e API_BASE=https://your-openai-compatible-endpoint/v1 \
-e API_KEY=sk-... \
-e MODEL_NAME=openai/your-model-slug \
pragent/pr-agent:0.50.0-mosaico_agent
curl -s http://localhost:9000/.well-known/agent-card.json | python3 -m json.toolPin a version tag in production (see the "Immutable releases and version tags" note on the
installation page); the plain mosaico_agent
rolling tag moves to the newest build on every release.
Environment variables
| Variable | Default | Purpose |
|---|---|---|
API_BASE |
— | Base URL of the OpenAI-compatible LLM endpoint |
API_KEY |
— | API key for that endpoint |
MODEL_NAME |
— | Model slug to call |
HOST |
0.0.0.0 |
Bind address |
PORT |
9000 |
Bind port |
AGENT_CARD_HOST, AGENT_CARD_PORT |
unset | URL advertised in the card's supportedInterfaces; see the warning below |
MODEL_MAX_TOKENS |
32000 |
Token budget for models whose context size pr-agent does not already know |
LANGFUSE_HOST, LANGFUSE_PUBLIC_KEY, LANGFUSE_SECRET_KEY |
unset | Optional Langfuse observability |
:::warning[AGENT_CARD_HOST / AGENT_CARD_PORT — the one thing to get right]
These two variables set the URL the agent advertises in supportedInterfaces. Leave them
unset and the card advertises http://localhost:9000/, which is reachable only from
inside the container itself. The failure this causes is silent and late: registration
with MOSAICO succeeds, the repository stores the unreachable URL, and the reference agent
only fails to dereference it once it tries to route a task to this agent. Set them to
whatever host/port the caller will use to reach the container, and verify with:
curl -s http://<host>:<port>/.well-known/agent-card.json \
| python3 -c "import sys,json; print(json.load(sys.stdin)['supportedInterfaces'][0]['url'])"If that prints a localhost URL, the deployment is wrong.
:::
Deploy into the mosaico-demonstrator
The docker/mosaico/
directory is a full deployment bundle (compose overlay, registration template, env template,
smoke test, LICENSE, and the canonical README). To run the agent as a task agent in the
mosaico-demonstrator:
- Copy
docker-compose.pr-agent.ymlinto the demonstrator'scompose/directory, next tobase-definitions.yml(the overlay'sextends:references resolve relative to that
directory). - Copy
pr-agent-solution-agent.jsoninto the demonstrator'sdocker/agent-registrations/directory. - Append the "demonstrator overlay" block from
pr-agent.env.exampleto the demonstrator'senv/llm.envand fill inPR_AGENT_MODEL(PR_AGENT_HOSTmay stay empty to use the
demonstrator's auto-detected LAN IP;PR_AGENT_PORTdefaults to23000). - Add
-f compose/docker-compose.pr-agent.ymlto the demonstrator's01-compose.sh, next to
the other task-agent overlays. - Run
./01-compose.sh up -d.
The registration template carries only description, role, objective, version; the
demonstrator's register-agent.py injects name, a2aAgentCardUrl, anddeployment.mode = ENDPOINT at registration time. Two names are intentionally different and
should not be "fixed": the repository entry is pr-agent-solution-agent (whatregister-agent.py looks the agent up by), while the card's own name is"PR-Agent Solution Agent" (a display string).
Verify
./smoke_test.shin the bundle directory gives one of two outcomes:
SMOKE PASSED— no LLM credentials were available; the script pulled the pinned image,
booted it, and validated the agent card only.FULL ROUND-TRIP PASSED— credentials were present (via a.envfile beside the script,
copied frompr-agent.env.example); the script additionally exercisedGET /healthand an
A2ASendMessagereview over an inline diff.
Troubleshooting
- The container stays
unhealthyand registration never runs./healthis a live LLM
probe and returns503on bad or missing credentials — this is intended. CheckAPI_BASE/API_KEY/MODEL_NAME, not the compose file. - The agent registers but the reference agent never reaches it. The advertised card URL is
localhost; see theAGENT_CARD_HOST/AGENT_CARD_PORTwarning above. - The registration container itself cannot fetch the agent card.
01-compose.shfalls back
toget_fallback_ip, which can resolve tolocalhost— reachable from the host but not from
inside the registration container on the Docker network. SetPR_AGENT_HOSTexplicitly to an
address reachable from inside Docker (for example the host's LAN IP, orhost.docker.internal).
Keep reading
The bundle README
is the canonical deep dive for this surface and the source of the summary above; it covers the
upgrade procedure, the registration flow, and the full env-var contract in one place.
Docs Overview Data Privacy (`docs/docs/overview/data_privacy.md`)
title: "Data Privacy" sidebar_position: 2
Self-hosted PR-Agent
- If you self-host PR-Agent with your OpenAI (or other LLM provider) API key, it is between you and the provider.
Docs Overview Supported Platforms (`docs/docs/overview/supported_platforms.md`)
title: "Supported platforms" sidebar_position: 3
Which commands, triggers and core abilities work on each git provider.
| GitHub | GitLab | Bitbucket Cloud | Bitbucket Server | Azure DevOps | Gitea | ||
|---|---|---|---|---|---|---|---|
| COMMANDS | Describe | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Review | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | |
| Improve | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | |
| Ask | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | |
| Ask on code lines | ✅ | ✅ | ✅ | ||||
| Add Docs | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | |
| Generate Labels | ✅ | ✅ | 💬 | 💬 | ✅ | ✅ | |
| Similar Issues | ✅ | ||||||
| Help | ✅ | ✅ | ✅[^help] | ✅ | ✅ | ✅ | |
| Help Docs ⚠️ | |||||||
| Update CHANGELOG | ✅ | ✅ | ✅ | 💬 | 💬 | 💬 | |
| USAGE | CLI | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| App / webhook | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | |
| Tagging bot | ✅ | ✅ | |||||
| Actions GitLab pipeline Bitbucket pipeline Azure DevOps pipeline | ✅ | ✅ | ✅ | ✅ | |||
| CORE | Adaptive and token-aware file patch fitting | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
Agent skills (SKILL.md) |
✅ | ✅ | ✅ | ✅ | ✅ | ✅ | |
Repo context files (AGENTS.md) |
✅ | ✅ | ✅ | ✅ | ✅ | ✅ | |
| Compression strategy | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | |
| Dynamic context | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | |
| Fetching ticket context | ✅ | ✅ | ✅[^tickets] | ✅[^tickets] | ✅ | ✅[^tickets] | |
| Local and global metadata | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | |
| Multiple models support | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
⚠️ /help_docs is temporarily disabled since v0.36.1 pending a fix for a credential-exposure issue (#2445); see Help Docs.
Legend: ✅ = supported. 💬 = the command runs, but its output is posted as a PR comment instead of being applied (Update CHANGELOG where the provider cannot push files, Generate Labels where it cannot set labels). Blank = not supported.
[^tickets]: On Bitbucket Cloud, Bitbucket Server, and Gitea, fetching ticket context means the Jira, Asana, and Linear integrations. Native issue links are used on GitHub and GitLab, and work items on Azure DevOps.
[^help]: /help <question> is supported, but /help without a question displays an unsupported-format notice instead of the command list on Bitbucket Cloud, Gerrit and CodeCommit.
[^help-list]: Plain-diff mode supports the /help command list only. /help <question> is currently unavailable in both local and plain-diff modes; local mode displays an unsupported-format notice for /help without a question.
Diff-only providers
The local, plain-diff, and MOSAICO modes do not use a hosting platform. The local provider compares branches in a local checkout, plain-diff reads a unified diff from stdin or a file, and the MOSAICO A2A server accepts a PR URL or diff over A2A. They write results to files or stdout, or return them as a task artifact, instead of publishing comments or applying changes.
| Local | Plain diff | MOSAICO | ||
|---|---|---|---|---|
| COMMANDS | Describe, Review, Improve, Ask | ✅ | ✅ | ✅ |
| Add Docs | ✅ | ✅ | ||
| Generate Labels | 💬 | 💬 | ||
| Similar Issues | ||||
| Help | ✅[^help-list] | |||
| Update CHANGELOG | 💬 | 💬 | ||
| USAGE | CLI | ✅ | ✅ | |
| A2A server | ✅ |
Core abilities that work from the diff itself, such as compression, multiple models, and self reflection, apply to all three modes. Dynamic context cannot add lines absent from a supplied diff unless matching working-tree files are available in plain-diff mode; local mode uses the checkout's file contents. Repo context files apply only to local mode. Output marked 💬 is written to the local output instead of a PR comment.
Gerrit and CodeCommit
Gerrit and CodeCommit are registered providers but are kept out of the main table to keep it readable. Support is:
| Gerrit | CodeCommit | ||
|---|---|---|---|
| COMMANDS | Describe, Review, Improve, Ask, Add Docs | ✅ | ✅ |
| Help | ✅[^help] | ✅[^help] | |
| Ask on code lines | |||
| Generate Labels | 💬 | 💬 | |
| Update CHANGELOG | 💬 | 💬 | |
| Similar Issues | |||
| USAGE | CLI | ✅ | ✅ |
| App / webhook | ✅ | ||
| Tagging bot / Actions and pipelines | |||
| CORE | Agent skills (SKILL.md) and other core abilities |
✅ | ✅ |
Repo context files (AGENTS.md) |
Gerrit and CodeCommit do not support gfm_markdown, so /describe omits semantic file types and a few other sections. CodeCommit setup notes currently live in the GitHub installation page; Gerrit has no dedicated installation page yet.
For Gerrit, the changed-file list and reviewed diff both respect ignore.glob and ignore.regex. Renamed files use their destination path, while deleted files retain their original path. Files with non-UTF-8 content remain in filename-based language detection but are omitted from the model diff.
Docs Usage Guide Additional Configurations (`docs/docs/usage-guide/additional_configurations.md`)
title: "Additional Configurations" sidebar_position: 10
Show possible configurations
The possible configurations of PR-Agent are stored in here.
In the commands page you can find explanations on how to use these configurations for each command.
To print all the available configurations as a comment on your PR, you can use the following command:
/configTo view the actual configurations used for a specific command after all user settings are applied,
an authorized operator can set config.output_relevant_configurations=true in .pr_agent.toml.
Comment-supplied arguments cannot enable this output because it may disclose host-controlled settings.
Showing the agent run details
To see which model actually answered, how many tokens the run consumed, and how long the AI processing phase took, enable config.output_run_details:
/review --config.output_run_details=trueAPI-cost collection is a separate, default-off option controlled by config.output_run_cost. Enable both flags to collect it and add it inside the run-details section:
/review --config.output_run_details=true --config.output_run_cost=trueconfig.output_run_details remains the public-output gate: setting only config.output_run_cost=true collects run-level cost data but never adds it to a PR comment.
On providers that support GitHub-Flavored Markdown this appends a collapsible section to the generated comment; elsewhere the same information is appended as plain text:
⚙️ Agent run details
- Model: provider/fallback-model (fallback)
- Tokens: 12,340 in / 1,205 out / 13,545 total
- Time cost: 8.2s
- AI calls: 1
- Estimated API cost: $0.08 USD
- anthropic/claude-opus-5: $0.07 USD
- anthropic/claude-sonnet-5: $0.01 USDModel shows the model that produced the answer, marked (fallback) when the primary model failed and a fallback took over. A fallback run also adds a visible one-line note naming the fallback model, even when config.output_run_details is off, because its output quality can differ from the configured model. The note appears wherever the section below can appear. The Tokens line appears only when the model provider reports usage. AI calls counts the successful LLM invocations made during the run. The flag is disabled by default.
Estimated API cost is derived synchronously from each completed LiteLLM response and its finalized usage. LiteLLM can account for cache reads, cache writes, reasoning tokens, and provider-specific usage categories when the response and its pricing data include them. Multi-model runs show a compact breakdown of the known costs. Exact Decimal values are retained for aggregation, while public currency output is rounded to two decimal places; a tiny positive value that would round to zero is shown as <$0.01 instead of $0.00. If only some successful calls can be priced, the total is marked partial with the priced-call count; if none can be priced, the line reports unavailable. Missing pricing is never rendered as $0.
The amount is an estimate based on LiteLLM's pricing data, not provider-invoice-authoritative billing. Reconcile it with the provider's billing records before using it for accounting or chargeback. Streaming responses are priced only after finalized usage is available; asynchronous callbacks and transient response_cost callback metadata are not treated as the sole source of truth. The public section contains only aggregate costs and configured model names, never prompts, response bodies, API keys, or provider request IDs.
Notes:
/ask,/ask_line, and/help <question>append the section to the published answer./update_changelogappends it to its comment only; the content committed toCHANGELOG.mdand the review comment that points at it never include it, so a push whose review succeeds shows no section. Messages that need no AI call, such as the static/helpwalkthrough or an/ask_linequestion that matches no diff lines, carry no section.- With
pr_description.use_description_markers=true, repeated/describeruns accumulate one run details block per run because the existing PR description is preserved and only the markers are replaced.
Ignoring files from analysis
In some cases, you may want to exclude specific files or directories from the analysis performed by PR-Agent. This can be useful, for example, when you have files that are generated automatically or files that shouldn't be reviewed, like vendor code.
The built-in generated-file filter matches .min.js, .min.css, .js.map, .ts.map, and .css.map suffixes case-insensitively; exact lockfile basenames such as package-lock.json keep their existing case-sensitive matching.
Gradle build scripts (build.gradle, settings.gradle, and build.gradle.kts) are eligible for analysis by default,
at the repository root and in subdirectories. Explicit ignore rules and custom extension exclusions still apply.
For example, ignore.glob = ['*.gradle', '*.gradle.kts'] excludes both script forms at any depth.
You can ignore files or folders using the following methods:
IGNORE.GLOBIGNORE.REGEX
which you can edit to ignore files or folders based on glob or regex patterns.
Pattern list entries must be strings. A non-string entry in ignore.regex, ignore.glob, or an enabled generated-code glob list is skipped with a warning; the remaining valid rules still apply.
Example usage
Let's look at an example where we want to ignore all files with .py extension from the analysis.
To ignore Python files in a PR with online usage, comment on a PR:/review --ignore.glob="['*.py']"
To ignore Python files in all PRs using glob pattern, set in a configuration file:
[ignore]
glob = ['*.py']And to ignore Python files in all PRs using regex pattern, set in a configuration file:
[ignore]
regex = ['.*\.py$']Each regex pattern is matched with a time limit: a match that takes longer than 50 ms counts as no match, logs a
warning and skips that pattern for the rest of the PR, and the patterns share a budget of one second per filter pass.
The result is then marked incomplete, as it is for a pattern that does not compile. A pattern longer than 1024
characters, or whose counted repeats such as {100} multiply to more than 10,000, is skipped the same way,
before it is compiled.
A **/ segment in a glob pattern matches zero or more directories, so src/**/generated_*.py also ignores src/generated_pb.py and not only src/api/generated_pb.py. Note that * still matches across /, as in ['*.py'] above.
Each ignore-glob list keeps at most 256 additional, distinct zero-directory regexes. Patterns with more than six standalone **/ segments or more than 256 characters are not expanded. Configured patterns and the existing root-level form of a leading **/ are always kept and do not count toward the limit. Skipped variants are reported once per list; files only those variants match are still analyzed.
The limit applies separately to ignore.glob and each enabled ignore_language_framework list. Globs made entirely of stars and separators, such as **/**/**, can match every file after zero-directory expansion.
Extra instructions
All PR-Agent commands have a parameter called extra_instructions that adds free-text instructions. Example usage:
/update_changelog --pr_update_changelog.extra_instructions="Make sure to update also the version ..."Repository settings and command arguments can replace extra_instructions for a command. For mandatory
organization-wide guidance that must apply to every command, host operators can set config.system_instructions:
[config]
system_instructions = """
Never evaluate the performance, competence, or quality of individual contributors.
Follow the organization's security and privacy policies.
"""PR-Agent appends this value to each command's own system prompt, after the command-specific instructions. It is
host-only: repository settings, namespace settings repositories, per-directory settings, and/command --config.system_instructions=... arguments cannot set or replace it.extra_instructions retains its existing behavior; use system_instructions when a rule must not be
overridable by a repository or comment author.
Custom comment footer
extra_instructions and system_instructions guide the model; they do not insert fixed text. To add the same
literal text to the bot's output in every repository, for example how to opt out or where to send feedback, host
operators can set config.custom_comment_footer (Markdown):
[config]
custom_comment_footer = """
To disable PR-Agent on this PR, add the label `no-pr-agent`.
For feedback on the AI results, open a ticket in the internal tracker.
"""PR-Agent adds the text after a horizontal rule at the end of the result of /review (and /improve, which runs/review), /describe, /ask, /ask_line, /help, /help_docs, /update_changelog, /config,/similar_issue, and the labels comment /generate_labels posts on providers without label support. When/describe updates the PR description rather than posting a comment, the footer becomes part of the PR
description. Progress, temporary and failure notices are left unchanged, and so are inline code suggestions
(posted one per line, so a footer would repeat on every suggestion). If a /review comment and its persistent
review state do not fit the provider's comment size limit together with the footer, the footer is omitted so the
review is not cut short.
The setting is host-only: repository settings, namespace settings repositories, per-directory settings, and/command --config.custom_comment_footer=... arguments cannot set or remove it. An empty value disables it.
Language Settings
The default response language for PR-Agent is U.S. English. However, some development teams may prefer to display information in a different language. For example, your team's workflow might improve if PR descriptions and code suggestions are set to your country's native language.
To configure this, set the response_language parameter in the configuration file. This will prompt the model to respond in the specified language. Use a standard locale code based on ISO 3166 (country codes) and ISO 639 (language codes) to define a language-country pair. See this comprehensive list of locale codes.
Example:
[config]
response_language = "it-IT"This will set the response language globally for all the commands to Italian.
Command arguments override the repository's language setting, for example /review --config.response_language=fr-FR. To select English, use /review --config.response_language=en-us.
Generated language guidance applies only while the command runs. Earlier generated directives do not override a later language selection, and user-authored extra_instructions are preserved.
Important: The model you are using must have good support for the specified language.
Fixed text
Some text in PR-Agent comments is written by PR-Agent, not by the model: labels, table headers and status lines. PR-Agent translates this text when it ships a catalog for the language of response_language. The tag is matched without regard to case or to - versus _, and region subtags are dropped until a catalog matches: es-AR uses the es catalog. When no catalog matches, or a catalog has no translation for a text, that text stays in U.S. English.
Catalogs ship for the following languages and regional variants:
| Language | Catalog code |
|---|---|
| Arabic | ar |
| Bengali | bn |
| Chinese, Simplified (China) | zh-cn |
| Chinese, Traditional (Taiwan) | zh-tw |
| Czech | cs |
| Danish | da |
| Dutch | nl |
| English | en |
| Finnish | fi |
| French | fr |
| German | de |
| Hebrew | he |
| Hindi | hi |
| Hungarian | hu |
| Indonesian | id |
| Italian | it |
| Japanese | ja |
| Korean | ko |
| Persian | fa |
| Polish | pl |
| Portuguese (Brazil) | pt-br |
| Portuguese (Portugal) | pt-pt |
| Romanian | ro |
| Russian | ru |
| Spanish | es |
| Swedish | sv |
| Thai | th |
| Turkish | tr |
| Ukrainian | uk |
| Vietnamese | vi |
The 28 new catalogs were drafted and cross-checked with multiple frontier LLMs and an automated code-review
harness. The Chinese catalogs (zh-cn and zh-tw) also received human review by the contributor.
The other 26 catalogs were machine-drafted and AI-reviewed, but have not undergone native-speaker human review.
Corrections from native speakers are welcome.
Use zh-CN or zh-TW for Chinese, and pt-BR or pt-PT for Portuguese. There is no shared zh or pt catalog. Chinese and Mandarin script tags (zh-Hans, zh-Hant, cmn-Hans, cmn-Hant, and the extended zh-cmn forms) fall back to the corresponding zh-cn and zh-tw catalogs, including tags with other regions (for example, zh-Hant-HK). Other Chinese varieties without a shipped catalog (such as zh-yue) and the tag zh alone still fall back to English.
In the /review comment, the intro line, the effort, tests, security and key-issue labels, the resolved-findings section, the finding lifecycle summary, the suggested-fix label, the persistent-review update lines and the "Preparing review..." message are translated. /improve and /improve_code now run /review; their one-line notice is also translated. The agent run details section is translated for every command. Other fixed text stays in U.S. English: the review heading (set it with pr_reviewer.review_heading), the other /review fields (ticket compliance, risk level, failure modes and the other opt-in fields), the review coverage footer, chunk progress, other commands' comments outside their run details, and the labels added to the PR. Numbers keep the U.S. format.
To add a language, copy pr_agent/settings/i18n/en.toml to a file named after the language code, such as pt.toml or pt-br.toml, and translate its values. Keep each {placeholder} unchanged.
Expand GitLab submodule diffs
By default, GitLab merge requests show submodule updates as Subproject commit lines. To include the actual file-level changes from those submodules in PR-Agent analysis, enable:
[gitlab]
expand_submodule_diffs = trueWhen enabled, PR-Agent will fetch and attach diffs from the submodule repositories. The default is false to avoid extra GitLab API calls.
Submodule URLs in .gitmodules may be absolute (https://, ssh://, git@host:) or relative (../group/repo.git). Relative URLs are resolved against the merge request's project path the same way git does.
Because .gitmodules comes from the merge request head, the target project is chosen by whoever opened it. PR-Agent therefore authorizes each submodule target the same way it authorizes a sibling repository: the target must be listed in config.repo_context_sibling_repos, must sit in the merge request project's own top-level namespace, and must be readable by the user who triggered the command. Targets that fail any of these checks are skipped with a warning and the parent gitlink change is left in place. Add each submodule you want expanded to the allowlist:
[config]
repo_context_sibling_repos = ["my-group/my-submodule"]Post the review as a GitLab thread
By default, PR-Agent posts the /review summary as a plain note. To post it as a resolvable thread (GitLab discussion) instead, enable (default: false):
[gitlab]
publish_review_as_thread = true- With
pr_reviewer.persistent_comment=true(the default), each run updates the existing review thread and reopens it if it was resolved, so the refreshed review gets another look. - Enabling the flag does not convert a review that was already posted as a plain note: it keeps being updated in place, and GitLab cannot promote a note to a thread. Only MRs whose first review runs after the flag is set get a thread.
- Set
pr_reviewer.persistent_comment=falseto open a new review thread on each run instead.
Reply to the triggering GitLab discussion
By default, /review, /improve, and /ask publish new comments. To reply inside the GitLab discussion
that triggered the command, enable (default: false):
[gitlab]
reply_to_trigger_comment = trueThis is opt-in and GitLab-only. The webhook supplies the discussion ID for top-level /review and /improve
notes, and for /ask (including /ask_question) in top-level notes or existing discussions. Diff-line /ask
still uses /ask_line and its existing reply behavior. If the ID is unavailable or the reply fails, PR-Agent
falls back to a normal note so output is not lost. GitHub Conversation comments do not expose a compatible
reply endpoint.
With persistent_comment=true (the default for both commands), a rerun updates the earlier result where it was first posted, which may be a different discussion; /review also posts a short link to it in the new command's discussion.
Resolve outdated GitLab inline threads
Each inline suggestion is anchored to the MR head commit it was posted against. When a later push moves the head, GitLab marks that thread as belonging to an outdated diff version: it renders empty, loses its Resolve control, and can then only be closed through the API, so superseded suggestions pile up on a long-lived MR. To have PR-Agent resolve those threads before it publishes a fresh batch of inline suggestions, enable (default: false):
[gitlab]
resolve_outdated_inline_threads = trueA thread is only resolved when all of the following hold, so a thread with any human reply is never closed:
- the thread was opened by PR-Agent itself, judged from the body: it carries a dedup marker (proof, and present on every inline review finding), or it opens with the
**Suggestion:**lead that inline suggestions are published with (a strong hint rather than proof, since a person could type it). This is what keeps the cleanup off hand-written comments made from the same account, which matters because the GitLab token often belongs to a person rather than a dedicated bot user; - every non-system note in it was written by that same user, so a single human reply leaves the thread alone. GitLab system notes are ignored, because the "changed this line in version N of the diff" note that marks a thread outdated is authored by whoever pushed;
- the thread is unresolved and anchored to a line of the diff;
- the head SHA recorded in that anchor differs from the MR's current diff head SHA.
Anything that cannot be confirmed (an unreadable position, an unknown current head SHA, an unresolvable bot identity) is skipped rather than resolved.
Note that the anchor's recorded head SHA never changes after the thread is created, so any PR-Agent thread older than the latest push qualifies, including ones GitLab still renders on unchanged lines. With config.persistent_inline_comments enabled the next run re-posts a suggestion that still applies, so the effect is resolve-and-repost rather than removal.
Log Level
PR-Agent allows you to control the verbosity of logging by using the log_level configuration parameter. This is particularly useful for troubleshooting and debugging issues with your PR workflows.
[config]
log_level = "INFO" # Options: "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"The default log level is "INFO". Set it to "DEBUG" when troubleshooting to include detailed operation logs.
Tokenizer files without internet access
PR-Agent counts tokens with tiktoken, which normally downloads its encoding files from openaipublic.blob.core.windows.net. Unless TIKTOKEN_CACHE_DIR, DATA_GYM_CACHE_DIR or CUSTOM_TIKTOKEN_CACHE_DIR is set, PR-Agent points tiktoken at the o200k_base and cl100k_base files bundled with LiteLLM, so no download is needed.
If you use your own cache directory, set CUSTOM_TIKTOKEN_CACHE_DIR (LiteLLM overwrites TIKTOKEN_CACHE_DIR) and place the encoding files there yourself; tiktoken names each file after the SHA-1 of its original download URL.
Attributing requests to a PR on the provider side
When add_user_to_requests is enabled, PR-Agent sends the current command and PR URL in the
OpenAI-compatible user request field, as a compact JSON string:
{"command":"improve","pr_url":"https://gitlab.example.com/group/project/-/merge_requests/171"}Providers that record this field per request (for example OpenRouter, which shows it asexternal_user in the generation details and includes it in the activity export) can then
attribute every request, its cost and its outcome to a specific PR and command, without
timestamp correlation.
[config]
add_user_to_requests = trueThe setting is disabled by default, since it shares request-attribution data with the model
provider: enabling it is an explicit operator choice.
Grouping requests by PR in LiteLLM
When add_session_id_to_requests is enabled, PR-Agent sends a stablex-litellm-session-id header with every request. LiteLLM stores the value in thesession_id column of its spend logs, so all commands run against the same PR can be
found and grouped together, even when they arrive as separate requests.
[litellm]
add_session_id_to_requests = trueThe value is derived from the PR URL and normalized to the character set LiteLLM accepts,
for example pr-agent-github-com-owner-repo-pull-123-b065a0b1d1c7b721. A header set explicitly throughLITELLM.EXTRA_HEADERS takes precedence, and the setting is disabled by default.
The same value is passed to LiteLLM as litellm_session_id, which LiteLLM forwards as the
provider's session header where one exists, such as OpenCode Go's required x-opencode-session.
The value includes the PR's host and repository path, so enabling the setting sends them to that provider.
Requests without a PR, such as the doctor model ping and the MOSAICO health probe, use a randompr-agent- value generated once per process instead.
Integrating with Logging Observability Platforms
Various logging observability tools can be used out-of-the box when using the default LiteLLM AI Handler. Simply configure the LiteLLM callback settings in configuration.toml and set environment variables according to the LiteLLM documentation.
The callback lists are process-wide LiteLLM settings, so only the deployment's own configuration and environment set them; a repository's
.pr_agent.tomldoes not. In the GitHub Action, set them asenventries in the workflow, for exampleLITELLM.SUCCESS_CALLBACK: '["langsmith"]'andLITELLM.FAILURE_CALLBACK: '["langsmith"]'.
For example, to use LangSmith you can add the following to your configuration.toml file:
[litellm]
enable_callbacks = true
success_callback = ["langsmith"]
failure_callback = ["langsmith"]
service_callback = []Then set the following environment variables:
LANGSMITH_API_KEY=<api_key>
LANGSMITH_PROJECT=<project>
LANGSMITH_BASE_URL=<url>To use Langfuse for utilization and adoption tracking (LLM cost, token usage, latency, and unique repo adoption), add the following to your configuration:
[litellm]
enable_callbacks = true
success_callback = ["langfuse_otel"]
failure_callback = ["langfuse_otel"]Note: use
langfuse_otel, the OpenTelemetry-based integration also used by MOSAICO.
Then set the following environment variables:
LANGFUSE_HOST=https://cloud.langfuse.com
LANGFUSE_PUBLIC_KEY=<public_key>
LANGFUSE_SECRET_KEY=<secret_key>Each LLM call is traced with the command name, git provider, PR URL, model, token counts, and version as tags — giving you full visibility into how pr-agent is being used across your repositories.
LLM telemetry via LiteLLM's OpenTelemetry integration
To emit OpenTelemetry traces and metrics for the LLM calls themselves — cost in USD, call duration, time to first token, and the input/output token split, on standard gen_ai.* semantic-convention names — enable LiteLLM's built-in otel callback:
[litellm]
success_callback = ["otel"]
failure_callback = ["otel"]
turn_off_message_logging = trueSet
turn_off_message_logging = true. LiteLLM attaches full prompt and response content to what its
callbacks emit, which here means the entire PR diff. This also suppresses PR-Agent's own full prompt/response
diagnostics in the LiteLLM and OpenAI handlers, even atDEBUGlog level or verbosity level 2. It does not sanitize
unrelated application logs or third-party callback errors. The default isfalseto preserve existing
behavior for Langfuse and LangSmith users. A deployment-level opt-out cannot be disabled by repository
settings. Unpublished CLI commands with verbosity level 2 still print model responses to stdout, which
may be captured separately; treat that explicit output as sensitive.
The integration is configured through environment variables:
OTEL_EXPORTER=otlp_http # or "console", "otlp_grpc"
OTEL_EXPORTER_OTLP_ENDPOINT=https://collector:4318
OTEL_EXPORTER_OTLP_HEADERS=...
OTEL_SERVICE_NAME=pr-agent
LITELLM_OTEL_INTEGRATION_ENABLE_METRICS=true # metrics are off by defaultPending callbacks are flushed before the CLI and the GitHub Action runner exit, bounded by callback_timeout_seconds (see Custom callbacks).
Custom callbacks
If you embed PR-Agent in your own code, you can also register callbacks programmatically — for example alitellm.CustomLogger that records per-call token usage and cost:
import litellm
from pr_agent import cli
class UsageLogger(litellm.integrations.custom_logger.CustomLogger):
async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):
record_usage(kwargs.get("model"), response_obj)
litellm.callbacks = [UsageLogger()]
cli.run_command("<pr_url>", "/review")LiteLLM dispatches these callbacks asynchronously, after the completion call has already returned. PR-Agent
flushes any pending callbacks before the CLI (and the GitHub Action runner) exits, so they are not lost when
the event loop is torn down — no configuration required. Use callback_timeout_seconds to bound how long
that flush may take:
[litellm]
callback_timeout_seconds = 30 # defaultBuilt-in OpenTelemetry command telemetry
PR-Agent can emit its own OpenTelemetry signals for utilization and adoption tracking. These cover the command layer — how often each command runs, on which git provider, whether it succeeded, and how many tokens it consumes — which no LLM-level integration can report, because many failures happen before any model call:
- Traces: one span per request, named
pr_agent <command>(for examplepr_agent review), carryingpr_agent.command,pr_agent.args_count,vcs.provider.name, a span status, and a boundederror.typeon failure. Prompt and response content is never attached. - Metrics:
pr_agent.commands, a counter of executed commands labeled by command and git provider.pr_agent.tokenscounts consumed tokens, labeled by command, git provider,pr_agent.fallback_used(true or false), andgen_ai.token.type(input,output,cache_read, orcache_creation).pr_agent.ai_callscounts successful model calls, labeled by command, git provider, andpr_agent.fallback_used. Zero values are skipped, so providers that do not report usage add no token timeseries (pr_agent.ai_callsstill counts their calls).
Two independent layers
Command telemetry (this section) and LLM telemetry are separate toggles with separate configuration, so you can enable either alone and aggregate them independently. When both are on, the LLM spans are children of the command span in the same trace, so a single command's model calls stay attributable to it.
Telemetry is disabled by default. To enable it, set in configuration.toml:
[otel]
is_enabled = true
exporter_type = "console" # "console", "otlp", "prometheus", or "none"
service_name = "pr-agent"
environment = "development" # e.g. "development", "staging", "production"To export to an OpenTelemetry collector instead of the console, set exporter_type = "otlp" and configure the endpoint and any authentication headers in .secrets.toml (they are secrets — keep them out of configuration.toml):
[otel]
otlp_endpoint = "http://my-collector:4318"
otlp_headers = "x-honeycomb-team=YOUR_API_KEY" # optional, "key1=value1,key2=value2"Export uses OTLP over HTTP by default; otlp_endpoint is the base URL, and the /v1/traces and /v1/metrics paths are appended automatically. To use OTLP over gRPC instead, install the optional exporter and select the protocol — the endpoint is then used as-is (gRPC collectors typically listen on port 4317):
pip install pr-agent[otel-grpc][otel]
otlp_protocol = "grpc" # default: "http"This is the recommended topology for fleets: point every PR-Agent instance at the same collector and aggregate there. Each process creates its own exporter connection; use the service_name and environment resource attributes to slice instances apart on the backend.
Exposing native Prometheus metrics
Instead of pushing to a collector, set exporter_type = "prometheus" to expose a native GET /metrics scrape endpoint on the server apps (github_app, gitlab_webhook, azuredevops_server_webhook, gitea_app). The command, token, and AI-call counters are translated into the Prometheus text format, and every gunicorn worker's values are merged at scrape time, so counters stay correct across the process workers:
[otel]
exporter_type = "prometheus"
prometheus_multiproc_dir = "/tmp/pr-agent-prometheus" # shared, writable by every workerThe exporter is metrics-only: command spans are not exported in this mode.
/metricsis mounted only when this exporter is selected, so nothing is exposed by default. It does not depend on an OTLP collector or endpoint.gunicorn prepares the multiprocess state directory at
when_readyand callsmark_process_deadfromchild_exit. The client removes live-gauge files, but retains counter and default-gauge files; retained values remain visible until the directory is cleared or replaced.With OpenTelemetry SDK 1.45.2, each metric stream tracks up to 2,000 distinct attribute sets by default; measurements for additional sets go into an overflow point. PR-Agent's synchronous DELTA counters start tracking attribute sets again after each collection, while exported Prometheus counters continue accumulating. The built-in counters use bounded labels; high-cardinality custom metrics using the same provider can reach this limit.
Normal series use the first normal data point's label set. Later attributes that do not fit are dropped, and missing ones are back-filled with an empty string. Overflow points use
otel_metric_overflow="true"; normal attribute values still use their usual string representation, includingTruefor a boolean. Normal labels whose Prometheus text output isotel_metric_overflowor starts withpr_agent_escaped_receive the prefixpr_agent_escaped_, including names containing:that the client renders as_. Update queries that use those labels.Different attribute names that map to the same label can still collide. Prometheus treats an empty label value as equivalent to an absent label, including across workers. An attribute set identical to the SDK's
otel.metric.overflow = truemarker cannot be distinguished from overflow.Gauge values, including overflow points, can remain visible after the SDK stops reporting them. This exporter does not currently expire stale gauge series.
Use the same exporter version across workers sharing a multiprocess state directory: older workers and their retained state files can still collide with overflow series when their final label values match, including through
:label escaping. For example, an old normal boolean valueTruestays distinct from the new overflow valuetrue, but an old string valuetruecan collide. Stop all workers using the state directory before clearing it, or switch to a fresh directory as part of a coordinated worker restart; replacing the directory resets the stored counters. Even with a new directory, an old normal series and a new overflow series with the same metric name and labels share Prometheus history across the upgrade.The exporter ships with PR-Agent (it depends on
prometheus-client); no extra package is required. Scrape it like any exporter:yamlscrape_configs: - job_name: pr-agent static_configs: - targets: ["pr-agent:3000"]
Privacy and lifecycle
Privacy controls (both off by default):
include_pr_url = trueattaches PR URLs to spans. Off by default because URLs expose private repo names.include_error_details = trueattaches exception messages and rejected-command text to error spans. Off by default because that content can embed PR URLs, repo names, or other request-specific text. Bounded values (the exception class name and error category) are always attached.
Notes:
- Telemetry configuration is process-level: it is read once at startup from the global configuration or environment, and cannot be enabled or reconfigured per-repo via
.pr_agent.toml. In a multi-tenant server, telemetry is a shared process resource — configure it where the process is deployed. - PR-Agent keeps its own OpenTelemetry providers and never registers the process-global one, so embedding PR-Agent in an application that already uses OpenTelemetry will not interfere with the host's telemetry. Pending spans and metrics are flushed automatically on process exit.
- Each OTLP export call is bounded by
otlp_timeout(default 3 seconds, retries included), so an unreachable collector cannot hang CLI exit or request completion. Raise it for slow collectors at the cost of longer worst-case stalls. - If
exporter_type = "otlp"is set but no endpoint is configured, telemetry is disabled entirely (fail closed) — it never falls back to another exporter, so a missing secret cannot redirect telemetry into process logs. - With
exporter_type = "prometheus", Gunicorn provisionsprometheus_multiproc_dirbefore workers fork. It must be shared and writable by every worker and defaults to/tmp/pr-agent-prometheus. Direct single-process Uvicorn deployments use their own registry when no multiprocess environment signal is present; configuring the directory path alone does not activate shared state. Custom multiprocess launchers can setPROMETHEUS_MULTIPROC_DIRbeforeprometheus-clientis imported. When explicitly signaled, PR-Agent validates and uses the configuredprometheus_multiproc_dir(or its default), which takes precedence over the environment's path. - Serverless deployments (e.g. the AWS Lambda webhooks) are supported: buffered spans and metrics are force-flushed at the end of every handled request, because frozen execution environments stop background export threads and are reaped without running exit handlers. No extra configuration is needed.
Bringing per-repo context files to PR-Agent
Platforms supported: GitHub, GitLab, Gitea, Bitbucket, Azure DevOps, Local
To give PR-Agent's commands additional project context, you can have it include repository instruction files — such as AGENTS.md or CLAUDE.md — in the prompts for the /review, /describe, /improve, /ask, /ask_line, and /add_docs commands.
Both Ask modes add instructions only after fitting their existing question, diff, and history context, and report when the instruction block does not fit.
See Ask: Repository instructions.
The /add_docs command uses configured local repository files by default; structured sibling-repository entries are excluded because generated documentation suggestions may be published. Set pr_add_docs.use_repo_context = false to opt out for that command.
By default, PR-Agent includes the AGENTS.md file at the repository root:
[config]
repo_context_files = ["AGENTS.md"]A nested list is a group of repository-relative path alternatives: only the first one that yields content is used. This is opt-in, for repositories that keep the same instructions under several conventions (or symlink them) and want them sent once:
[config]
repo_context_files = [["AGENTS.md", "CLAUDE.md", ".kiro/steering/*.md"]]You can list any repository-relative paths. By default the files are read from the repository's default branch, so only trusted, already-merged content is used and a PR cannot influence the guidance used to review it. A file that is missing is silently skipped. For example, to include several files:
[config]
repo_context_files = ["AGENTS.md", "CLAUDE.md", "docs/conventions.md"]Set the option to an empty list (repo_context_files = []) to disable the feature entirely.
To include architecture decision records (ADRs) or other rule files without listing each one, an entry may use a glob in its file name. On GitHub and GitLab the directory is listed and up to repo_context_max_glob_matches matches (default 20, at most 100) are included in name order; other providers skip glob entries with a warning. Wildcards are only allowed in the last path segment, so docs/**/*.md is not supported.
[config]
repo_context_files = ["AGENTS.md", "docs/adr/*.md"]:::note[Which branch the files are read from]
By default (repo_context_from_default_branch = true), instruction files are read from the repository's default branch — a single trusted source — so neither the PR nor its target branch can alter the guidance used to review it. This matches how Qodo Merge reads these files.
Set repo_context_from_default_branch = false to instead read from the PR's target (base) branch. This respects branch-specific instructions (for example a release branch, or a stacked PR that carries its own AGENTS.md), at the cost of trusting whoever can write to that target branch. Even then, files are never read from the PR's own head.
The local git provider has no separate default branch, so it always reads instruction files from the committed target branch (the branch passed as --pr_url), never from HEAD or uncommitted changes.
[config]
repo_context_from_default_branch = false:::
To bound how much of this context is sent to the model, repo_context_max_lines (default 500) caps the total number of rendered lines, including the wrapper tags. Content beyond the budget is truncated safely:
[config]
repo_context_max_lines = 500Expanding @path imports
Local context files can import other repository files with Claude Code's @path/to/file syntax. Imports are off by default. Enable them in host or repository configuration; comment arguments cannot enable them:
[config]
repo_context_expand_imports = trueA file such as CLAUDE.md that only contains @AGENTS.md then sends the referenced file's content too. Relative paths resolve from the file that contains the import, using the same revision. A backslash escapes a space in the path, as in @Design\ Docs/rules.md. Imports inside code spans and fenced code blocks, URL-shaped tokens, and paths that escape the repository root are ignored. Each file is included once, even when several entries reference it, and nesting stops after four hops. Import expansion makes at most 20 provider fetch attempts per context build. Imported lines share repo_context_max_lines with the rest of the context. Sibling entries do not expand imports.
Context from sibling repositories
The host operator must first approve repositories in the deployment configuration:
[config]
repo_context_sibling_repos = ["my-group/library"]
repo_context_max_sibling_files = 5Approve only repositories whose contents may appear in reviews of consuming repositories.
This allowlist and the fetch limit cannot be changed by repository settings or comment arguments.
An empty allowlist disables sibling reads.
A consuming repository can then select files in its .pr_agent.toml as structuredrepo_context_files entries:
[config]
repo_context_files = [
"AGENTS.md",
{repo_id = "my-group/library", file_path = "src/api.py"},
]Use owner/repository on GitHub or a full project path on GitLab. GitLab also accepts numeric
project IDs as strings, provided the same identifier is in the host allowlist. Resolved repositories
must share the current repository's owning namespace: the GitHub owner or GitLab top-level group,
including projects in different subgroups. Renamed or redirected paths must be updated to their
canonical names in both settings.
Sibling files always come from their default branch and share repo_context_max_lines with local
files. Private and internal repositories also require requester access. Comment arguments cannot
override repo_context_files at all; a repository's .pr_agent.toml may still set it.
Ignoring automatic commands in PRs
PR-Agent allows you to automatically ignore certain PRs based on various criteria:
- PRs with specific titles (using regex matching)
- PRs between specific branches (using regex matching)
- PRs from specific repositories (using regex matching)
- PRs not from specific folders
- PRs containing specific labels
- PRs opened by specific users
The title, author, label, repository, source-branch, and target-branch ignore_* rules also apply to
comment commands such as /review and /ask, and to CLI --pr_url runs. In these paths,ignore_pr_authors matches the PR author, not the person posting the command. An ignored CLI
request exits successfully without running the command. Plain-diff CLI inputs (--diff-file and--stdin) have no PR metadata and are not excluded by these rules.
For automatic PR/MR webhooks in GitHub App, GitLab, Gitea, and Bitbucket Cloud,
host exclusions are evaluated before repository settings.
A repository cannot clear a host exclusion already matched at this stage; it can still
exclude additional requests. Manual commands and CLI runs use their effective repository policy.
An automatic webhook may now read CONFIG.EXTRA_CONFIG_URL even when the host policy
rejects the event, adding a configuration fetch that would previously have been skipped.
On these webhooks, ignore_pr_authors checks the PR/MR author rather than the event actor;
unavailable author metadata retains the existing best-effort policy behavior.
GitLab may also make an extra MR-author API request for relevant events when Host author
filtering is enabled and the event actor differs from the MR author.
For GitHub App webhooks, github_app.override_deployment_type defaults to true
to preserve App authentication after trusted external Host settings are loaded.
Trusted Host settings may set it to false to retain their configured deployment
type; repository settings cannot control this option.
For GitHub Actions, matching PRs also skip automatic review, description, and improve commands
on pull_request, pull_request_target, and workflow_run events.
Ignoring PRs with specific titles
To ignore PRs with a specific title such as "[Bump]: ...", you can add the following to your configuration.toml file:
[config]
ignore_pr_title = ["\\[Bump\\]"]Where the ignore_pr_title is a list of regex patterns to match the PR title you want to ignore. Default is ignore_pr_title = ["^\\[Auto\\]"].
Ignoring PRs between specific branches
To ignore PRs from specific source or target branches, you can add the following to your configuration.toml file:
[config]
ignore_pr_source_branches = ['develop', 'main', 'master', 'stage']
ignore_pr_target_branches = ["qa"]Where the ignore_pr_source_branches and ignore_pr_target_branches are lists of regex patterns to match the source and target branches you want to ignore.
They are not mutually exclusive, you can use them together or separately.
Ignoring PRs from specific repositories
To ignore PRs from specific repositories, you can add the following to your configuration.toml file:
[config]
ignore_repositories = ["my-org/my-repo1", "my-org/my-repo2"]Where the ignore_repositories is a list of regex patterns to match the repositories you want to ignore. This is useful when you have multiple repositories and want to exclude certain ones from analysis.
The regex patterns of ignore_repositories, ignore_pr_authors, ignore_pr_title, ignore_pr_source_branches andignore_pr_target_branches are matched with a time limit of 50 ms per match and one second for all of them together;
a pattern that runs out of time counts as not matching, so the PR is processed, and a warning is logged.
A pattern longer than 1024 characters, or whose counted repeats such as {100} multiply to more than 10,000, is
treated like one that does not compile.
Ignoring PRs not from specific folders
To allow only specific folders (often needed in large monorepos) for automatic PR-open and push feedback in the Bitbucket Server/Data Center webhook, set:
[config]
allow_only_specific_folders=['folder1/','folder2/']When changed files are available, automatic feedback will only be triggered when the PR changes include files whose path starts with folder1/ or folder2/. This filter does not apply to comment commands or other providers.
Ignoring PRs containing specific labels
To ignore PRs containing specific labels, you can add the following to your configuration.toml file:
[config]
ignore_pr_labels = ["do-not-merge"]Where the ignore_pr_labels is a list of labels that when present in the PR, the PR will be ignored.
Processing only PRs with selected labels
To opt in only selected PRs or MRs to PR-Agent, specify one or more label names:
[config]
include_pr_labels = ["ai-review"]When the list is nonempty, a PR must have at least one matching label to be processed.
Names are matched exactly (case-sensitive), not as regular expressions. The default empty
list leaves all PRs eligible. If a label appears in both include_pr_labels andignore_pr_labels, the exclusion wins. This applies to automatic runs, comment commands,
and CLI --pr_url requests, just like the existing exclusion rules. Repository settings
may select the labels; individual comment or CLI command arguments cannot override this gate.
If the labels cannot be read, PR-Agent skips the request while this opt-in gate is enabled;
GitHub, GitLab, Gitea and Azure DevOps supply labels through their PR/MR APIs. Inputs
without hosted PR labels, including Bitbucket Cloud/Server, local, and plain-diff mode,
will not pass this gate. The setting selects eligible PRs; it does not itself trigger
a run when a label is assigned after the PR was opened.
Ignoring PRs from specific users
PR-Agent tries to automatically identify and ignore pull requests created by bots using:
- GitHub's native bot detection system
- Name-based pattern matching
While this detection is robust, it may not catch all cases, particularly when:
- Bots are registered as regular user accounts
- Bot names don't match common patterns
To supplement the automatic bot detection, you can manually specify users to ignore. Add the following to your configuration.toml file to ignore PRs from specific users:
[config]
ignore_pr_authors = ["my-special-bot-user", ...]Where the ignore_pr_authors is a regex list of usernames that you want to ignore.
:::note
The GitHub App does not currently trigger commands in response to failed check_run webhook events.
:::
Ignoring Generated Files by Language/Framework
To automatically exclude files generated by specific languages or frameworks, you can add the following to your configuration.toml file:
[config]
ignore_language_framework = ['protobuf', ...]You can view the list of auto-generated file patterns in generated_code_ignore.toml.
Files matching these glob patterns will be automatically excluded from PR Agent analysis.
Restricted Mode
When running PR-Agent with limited GitHub/GitLab permissions, set restricted_mode to true to gracefully skip operations that require elevated access (e.g., pushing changelog changes):
[config]
restricted_mode = trueFor the default commands in GitHub Actions, use:
permissions:
contents: read
issues: write
pull-requests: writeRestricted mode disables the provider's push_code capability, but does not remove the need for contents: read to fetch repository content. Add checks: write when github.publish_as_check_run is enabled. Keep pr_questions.resolve_threads off unless you grant contents: write, since thread resolution requires that scope and is not covered by restricted mode.
Note: any scope not listed in an explicit
permissions:block is set tonone. If you omit thepermissions:block entirely, the effective defaults are governed by your repository/organization GitHub Actions settings and may grant broader access.
Docs Usage Guide Automations And Usage (`docs/docs/usage-guide/automations_and_usage.md`)
title: "Usage and Automation" sidebar_position: 5
Local repo (CLI)
When running from your locally cloned PR-Agent repo (CLI), your local configuration file will be used.
Examples of invoking the different commands via the CLI:
- Review:
python -m pr_agent.cli --pr_url= review - Describe:
python -m pr_agent.cli --pr_url= describe - Improve:
python -m pr_agent.cli --pr_url= improve - Ask:
python -m pr_agent.cli --pr_url= ask "Write me a poem about this PR" - Update Changelog:
python -m pr_agent.cli --pr_url= update_changelog
The commands above assume the pr_agent package is importable — use the venv created by uv sync, or install PR-Agent.
`` is the url of the relevant PR (for example: #50).
Notes:
In addition to editing your local configuration file, you can also change repository-configurable values by adding them to the command line:
textpython -m pr_agent.cli --pr_url=<pr_url> review --pr_reviewer.extra_instructions='"focus on the file: ..."'Host-controlled values, including provider authentication, TLS, and endpoint settings, are rejected in command arguments. See Configuration Options for details.
You can print results locally, without publishing them, by setting in
configuration.toml:text[config] publish_output=false verbosity_level=2This is useful for debugging or experimenting with different commands.
git provider: The git_provider field in a configuration file determines the GIT provider that will be used by PR-Agent. Currently, the following providers are supported:
github(default),gitlab,bitbucket,bitbucket_server,azure,codecommit,local,gerrit,gitea, andplain-diff.A failed request returns a non-zero process status, so scripts and CI jobs can detect it. The installed
pr-agentcommand,python -m pr_agent.cli, and the customizable pip script exit with status 1 when the request fails or a command records a failure even though it returns successfully (for example, when no model produced a prediction). In the latter case, the CLI logs a warning explaining the non-zero exit.This does not depend on
config.propagate_command_errors, which controls whether a command re-raises an internal error instead of swallowing it. A review that was published as a partial result after its fallback chain was exhausted still exits with status 0 unless that setting is enabled (see/review). Argparse parse and usage errors continue to exit with status 2.
CLI Health Check
For a quick preflight that needs no token and no PR, run:
pr-agent doctorIt checks that config.model is set and that a completion against the configured model succeeds. Where required, it also checks for a real static API key. The check reads the host configuration files and environment variables only: overrides such as --config.model=... are ignored after doctor and rejected before it, and neither the repository's .pr_agent.toml nor --extra_config_url is loaded. It can therefore validate a different model than a PR command would use, so set the model and the other options in a host configuration file or through environment variables. Azure AD, Bedrock IAM, Anthropic bearer tokens without captured API keys, keyless local endpoints, and custom endpoints defer authentication validation to the completion. For Watsonx, an API URL alone is insufficient: configure an API key, WATSONX_TOKEN, WATSONX_ZENAPIKEY, or an explicit Authorization header. Watsonx checks these credentials in header, bearer-token, Zen-key, then API-key order; placeholder credentials are not accepted. An Anthropic bearer token must also be non-placeholder. Keyless local providers and eligible OpenRouter gateway fallbacks defer placeholder-key validation to the model completion. Native providers that require a real key still reject placeholders. For Databricks, if the optional databricks-sdk package is installed and DATABRICKS_HOST is set with DATABRICKS_TOKEN (PAT) or DATABRICKS_CLIENT_ID and DATABRICKS_CLIENT_SECRET (OAuth M2M), preflight also defers to the completion when no native API key is set. If both PAT and OAuth settings are present, set DATABRICKS_AUTH_TYPE to the matching authentication method. Other SDK credential sources are not inspected by the static check. The exit code is 0 only when every check passes, so CI setups can gate on it. It ships with the package, unlike the fuller health check below, which exercises real commands on a real PR.
In Docker, run it from the CLI image (pragent/pr-agent:<version> or pragent/pr-agent:latest), whose entrypoint takes the command directly:
docker run --rm --env-file .env pragent/pr-agent:latest doctorService images such as pragent/pr-agent:<version>-github_app are intended for long-running servers and do not install the pr-agent console script. To run the check from one of them, override the command with python -m pr_agent.cli doctor.
When host-configured push_outputs is enabled, doctor adds a fourth check for the selected output destinations: registered channel names, a nonempty file path, HTTPS scheme and hostname for webhook/Slack URLs, and a nonempty Telegram token string and a chat ID that is a nonempty string or nonzero integer. An omitted file path uses the normal default. Distinct custom sink names receive recognition-only checks; their private settings are not validated.
push_outputs.enable accepts booleans or strings. String values false, 0, no, off, and the empty string disable it (ignoring case and surrounding whitespace); other strings enable it. Disabled output keeps the existing three checks and output unchanged.
The output check reads the active host settings but does not construct sinks, send output, access files, or contact destinations. It checks only the fields listed above; URL ports and other URL components are not validated. Success does not establish delivery, file writability, destination reachability, authentication, or permissions. The existing model ping still contacts the configured model before the output check. No PR URL or git-provider setup is needed.
To verify that PR-Agent has been configured correctly end to end, you can also run this health check command from the repository root:
python -m tests.health_test.mainIf the health check passes, you will see the following output:
========
Health test passed successfully
========At the end of the run.
Before running the health check, ensure you have:
- Configured your LLM provider
- Added a valid GitHub token to your configuration file
Online usage
Online usage means invoking PR-Agent commands by comments on a PR.
Commands for invoking the different commands via comments:
- Review:
/review - Describe:
/describe - Improve:
/improve(or/improve_codefor bitbucket, since/improveis sometimes reserved). Runs/review; a list that names both runs one review. - Ask:
/ask "..." - Update Changelog:
/update_changelog
To edit a specific configuration value, just add --<section>.<key>=<value> to any command.
For example, if you want to edit the review command configurations, you can run:
/review --pr_reviewer.extra_instructions="..." --pr_reviewer.require_score_review=falseMost values in the configuration file can be similarly edited. Host-controlled settings, including provider connection locations and credentials, cannot be changed through PR comments. Comment /config to see the list of available configurations.
PR-Agent Automatic Feedback
Disabling all automatic feedback
To easily disable all automatic feedback from PR-Agent (GitHub App, GitHub Action, GitLab Webhook, BitBucket App, Azure DevOps Webhook), set in a configuration file:
[config]
disable_auto_feedback = trueWhen this parameter is set to true, PR-Agent will not run any automatic commands (like describe and review) when a new PR is opened, or when new code is pushed to an open PR.
Skipping runs when nothing changed
Rebases, reopened PRs and CI pipelines that re-run when the target branch moves can run /review and /describe again on a PR that has not changed. To skip those runs, set:
[config]
skip_unchanged_diff = trueAn automatic or CLI /review or /describe run is then skipped, with no model calls, when, since that command last succeeded on the PR, either of these holds:
- The head commit and the target branch name are the same. The branch is compared by name, not by its latest commit, so new commits on the target branch do not trigger a run. This check needs the provider to report the target branch.
- The diff is the same, for example after a rebase that changed no content. Hunk line numbers are ignored, so a rebase that only moves the changes within their files counts as the same diff. This check is off when a file has no patch, such as a binary file, because its content can change without changing the diff.
PR-Agent keeps its record in one comment on the PR, and edits it to say when a run was skipped and why. The record is written only after a command finishes cleanly, so a failed, partial, or degraded run is retried next time, and clears that command's earlier record if it attempted to update the PR's output or labels.
- A command typed in a PR comment, such as
/review, always runs. It takes down that command's skip notice but does not update the record, because arguments typed with it can change what the review covers. - Incremental review (
/review -i) and per commit review always run. - Output that belongs to one head commit is never left behind by a skip.
/reviewalways runs whileconfig.enable_auto_approvalorpr_reviewer.publish_merge_recommendation_statusis on, and both commands always run whilegithub.publish_as_check_runis on. - Some automatic runs are requested by a person: assigning PR-Agent as a GitLab reviewer (
gitlab.reviewer_commands), a GitHub review request, or a GitHub review submitted with changes requested (review_commands). These are skipped too when nothing has changed; comment the command to run it. - Changing the configuration or model does not count as a change. Comment the command to run it again.
- The setting works only on providers that can verify which comments PR-Agent wrote: GitHub, GitLab, and Azure DevOps when its identity is configured. On other providers every run goes ahead.
GitHub App
:::note[Configurations for PR-Agent]
These settings apply to self-hosted GitHub App, GitLab webhook, and Bitbucket App deployments.
:::
GitHub app automatic commands when a new PR is opened
The github_app section defines GitHub app specific configurations.
The configuration parameter pr_commands defines the list of commands that will be run automatically when a new PR is opened:
[github_app]
pr_commands = [
"/describe",
"/review",
]This means that when a new PR is opened/reopened or marked as ready for review, PR-Agent will run the describe and review commands (improve runs review, so a list naming both runs one review).
Draft PRs:
By default, the GitHub App does not consider draft PRs for automatic commands. You can change this by setting the feedback_on_draft_pr parameter to true in the configuration file. The GitHub Action applies the same setting to pull_request_review events. The GitLab webhook also skips draft MRs by default, while Gitea, Azure DevOps, and Bitbucket do not apply a draft check.
When enabled, marking the PR as ready does not run pr_commands a second time.
Because this setting can be overridden per repository, draft PR events, including each synchronize event caused by a push, still fetch the repository configuration before being skipped.
[github_app]
feedback_on_draft_pr = trueChanging default command parameters:
You can override the default command parameters by using one the three options for a configuration file: local, global, or external URL.
For example, if your configuration file contains:
[pr_description]
generate_ai_title = trueEvery time you run the describe command (including automatic runs) the PR title will be generated by the AI.
Parameters for automated runs:
You can customize configurations specifically for automated runs by using the --<section>.<key>=<value> parameter.
For App and webhook automatic commands, accepted parameters can affect the command's later repository-settings load and take precedence for command execution. GitHub Actions apply command parameters after loading repository settings.
Some repository-configurable settings cannot be set this way: pr_reviewer.enable_risk_checks, for example, is rejected as a command argument, while a repository's .pr_agent.toml can still set it.
App and webhook deployments load repository settings for the event before preparing the automatic command, so parameters cannot change that first load. Set options needed before repository files are read in host configuration.
The root .pr_agent.toml can override config.enable_per_directory_settings before nested files are read, including during the later command load; set it in the root file when it must control that load.
For instance, to modify the review command settings only for newly opened PRs, use:
[github_app]
pr_commands = [
"/describe",
"/review --pr_reviewer.extra_instructions='focus on the file: ...'",
]Automatic commands for push actions (commits to an open PR)
In addition to running automatic commands when a PR is opened, PR-Agent can also respond to new code that is pushed to an open PR. This works for both GitHub App and GitHub Action deployments.
The configuration toggle handle_push_trigger can be used to enable this feature.
The configuration parameter push_commands defines the list of commands that will be run automatically when new code is pushed to the PR.
[github_app]
handle_push_trigger = true
push_commands = [
"/describe",
"/review",
]For GitHub Action, settings fall back from github_action_config.* to github_app.*, so you can set either section.
This means that when new code is pushed to the PR, PR-Agent will run the describe and review commands, with the specified parameters.
The push_trigger_pending_tasks_backlog and push_trigger_pending_tasks_ttl settings apply to the GitHub App only; the GitLab, Gitea, and Bitbucket servers use fixed values.
GitHub Action
GitHub Action is a different way to trigger PR-Agent commands, and uses a different configuration mechanism than GitHub App.
You can configure settings for GitHub Action by adding environment variables under the env section in .github/workflows/pr_agent.yml file.
:::tip[Fork/contribution support]
To support PRs from forked repositories, use the pull_request_target event instead of pull_request. See the fork contribution guide for a complete example and security considerations.
:::
Specifically, start by setting the following environment variables:
env:
OPENAI_KEY: ${{ secrets.OPENAI_KEY }} # Make sure to add your OpenAI key to your repo secrets
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Make sure to add your GitHub token to your repo secrets
github_action_config.auto_review: "true" # enable\disable auto review
github_action_config.auto_describe: "true" # enable\disable auto describe
github_action_config.auto_improve: "true" # enable\disable auto improve
github_action_config.pr_actions: '["opened", "reopened", "ready_for_review", "review_requested"]'github_action_config.auto_review, github_action_config.auto_describe and github_action_config.auto_improve are used to enable/disable automatic commands that run when a new PR is opened./improve runs /review, so the review runs when either auto_review or auto_improve is enabled, and only once. If not set, describe and review run automatically when a new PR is opened.
github_action_config.pr_actions is used to configure which pull_requests events will trigger the enabled auto flags
If not set, the default configuration is ["opened", "reopened", "ready_for_review", "review_requested"]
Adding "synchronize" to this list enables auto commands on new commits pushed to an open PR. You must also add synchronize to the workflow pull_request: types: list.
github_action_config.handle_push_trigger controls whether synchronize events run the push commands (default false). Settings fall back to github_app.* if not set under github_action_config. Since it defaults to false, synchronize is opt-in — you must explicitly enable it by either adding "synchronize" to pr_actions or setting handle_push_trigger = true.
github_action_config.push_commands defines which commands run on synchronize events when handle_push_trigger is enabled (fallback to github_app.push_commands).
github_action_config.push_trigger_ignore_merge_commits (default true) skips processing when the push only merges the base branch into the PR, as "Update branch" does, avoiding duplicate reviews on those clicks. The pushed head must be a merge commit whose first parent is the previous head and whose second parent is on the base branch. Any other push is processed, including one that adds commits before the merge or merges another branch.
github_action_config.push_trigger_ignore_bot_commits (default true) skips processing when the push author is a bot, avoiding redundant runs on automated commits.
github_action_config.fail_on_command_errors (default true) makes the Action exit non-zero when a command recorded a swallowed failure (the default propagate_command_errors = false case), instead of finishing green on a pull request that got no review. Set it to false to restore the previous behavior of ignoring recorded command failures. Set it in the workflow configuration; comment arguments such as /review --github_action_config.fail_on_command_errors=false are rejected.
Automatic commands after a submitted GitHub review
The GitHub App can run configured commands after a human reviewer submits a native GitHub review. This is opt-in: review_commands is empty by default. By default, only reviews submitted with the changes_requested state by a User review author trigger the commands. This conservative default avoids running on the repository's high-volume commented reviews; set review_states or review_author_types explicitly when a different workflow is needed.
[github_app]
review_states = ["changes_requested"]
review_author_types = ["User"]
review_commands = [
"/review",
]The event must be submitted; edited or dismissed reviews do not trigger commands. The review author's user.type must match review_author_types, which defaults to User and prevents bot reviews from triggering commands. Existing repository filtering, draft-PR handling, eligibility checks, and config.disable_auto_feedback still apply. The review text is not treated as a command; each configured command runs with the normal pull-request context.
For GitHub Action, add the review event to the workflow and configure the equivalent settings. github_action_config.* overrides the corresponding github_app.* setting when present.
on:
pull_request_review:
types: [submitted]
env:
github_action_config.review_states: '["changes_requested"]'
github_action_config.review_author_types: '["User"]'
github_action_config.review_commands: '["/review"]'Output and Check Run settings
github_action_config.enable_output are used to enable/disable github actions output parameter (default is true).
Review result is output as JSON to steps.{step-id}.outputs.review property.
The JSON structure is equivalent to the yaml data structure defined in pr_reviewer_prompts.toml.
github.publish_as_check_run controls whether command output (review, describe) is published as a GitHub Check Run instead of a PR comment (default is false). When enabled, results appear in the "Checks" tab of the PR. Requires checks: write permission in the workflow YAML. On the GitHub App, each automatic command opens its check run as in progress before the command runs, so the author sees that PR-Agent picked the pull request up before any output exists; while a chunked command runs, that in-progress run also shows the analyzed chunk count, for example PR-Agent is running /review analyzed 2 of 3 chunks. The run is completed with the command's output, or marked failed if the command did not finish.
Note that you can give additional config parameters by adding environment variables to .github/workflows/pr_agent.yml, or by using a .pr_agent.toml configuration file in the root of your repo
For example, you can set an environment variable: pr_description.publish_labels=false, or add a .pr_agent.toml file with the following content:
[pr_description]
publish_labels = falseto prevent PR-Agent from publishing labels when running the describe command.
Enable using commands in PR
You can configure your GitHub Actions workflow to trigger on issue_comment events (created and edited).
Example GitHub Actions workflow configuration:
on:
issue_comment:
types: [created, edited]When this is configured, PR-Agent can be invoked by commenting on the PR.
Quick Reference: Model Configuration in GitHub Actions
For detailed step-by-step examples of configuring different models (Gemini, Claude, Azure OpenAI, etc.) in GitHub Actions, see the Configuration Examples section in the installation guide.
Common Model Configuration Patterns:
- OpenAI: Set
config.model: "<openai-model>"andOPENAI_KEY - Gemini: Set
config.modelto agemini/model ID andGOOGLE_AI_STUDIO.GEMINI_API_KEY(noOPENAI_KEYneeded) - Claude: Set
config.modelto ananthropic/model ID andANTHROPIC.KEY(noOPENAI_KEYneeded) - Azure OpenAI: Set
OPENAI.API_TYPE: "azure",OPENAI.API_BASE, andOPENAI.DEPLOYMENT_ID - Local Models: Set
config.model: "ollama/model-name"andOLLAMA.API_BASE
Environment Variable Format:
- Use dots (
.) to separate sections and keys:config.model,pr_reviewer.extra_instructions - Boolean values as strings:
"true"or"false" - Arrays as JSON strings:
'["item1", "item2"]'
For complete model configuration details, see Changing a model in PR-Agent.
GitLab Webhook
After setting up a GitLab webhook, to control which commands will run automatically when a new MR is opened, you can set the pr_commands parameter in the configuration file, similar to the GitHub App:
[gitlab]
pr_commands = [
"/describe",
"/review",
]Draft MRs are skipped by default. Set feedback_on_draft_pr = true under [gitlab] to enable automatic feedback.
When enabled, marking the MR as ready does not run pr_commands a second time.
Because this setting can be overridden per repository, draft MR events still fetch the repository configuration before being skipped.
For environment-based deployments, set GITLAB__FEEDBACK_ON_DRAFT_PR=true.
the GitLab webhook can also respond to new code that is pushed to an open MR.
The configuration toggle handle_push_trigger can be used to enable this feature.
The configuration parameter push_commands defines the list of commands that will be run automatically when new code is pushed to the MR.
[gitlab]
handle_push_trigger = true
push_commands = [
"/describe",
"/review",
]To use handle_push_trigger, enable GitLab Merge request events. New commits trigger a merge request update event with oldrev; the separate Push events trigger is not required.
The GitLab webhook can also respond to the bot being assigned or explicitly re-requested as a reviewer on an open MR.
The configuration toggle handle_reviewer_assignment can be used to enable this feature.
The configuration parameter reviewer_commands defines the list of commands that will be run automatically for these events.
[gitlab]
handle_reviewer_assignment = true
reviewer_commands = [
"/review",
]The commands run when the bot is newly added to the reviewer list or its review is explicitly re-requested, so re-saving an MR without either change does not run them again.
Review re-request webhook events require GitLab 18.6 or later.
The bot is identified by the user behind gitlab.personal_access_token, which must therefore be set for this feature to work.
Draft MRs and MRs matching the ignore settings are skipped.
BitBucket App
Similar to GitHub app, when running PR-Agent from BitBucket App, the default configuration file will be initially loaded.
By uploading a local .pr_agent.toml file to the root of the repo's default branch, you can customize parameters that support repository-level overrides. Note that you need to upload .pr_agent.toml prior to creating a PR, in order for the configuration to take effect.
Provider endpoint settings are host-controlled. Values for the endpoint keys listed in the local configuration guide are ignored when set in repository-local .pr_agent.toml and must be configured on the host.
For example, if your local .pr_agent.toml file contains:
[pr_reviewer]
extra_instructions = "Answer in japanese"Each time you invoke a /review command, it will use the extra instructions you set in the local configuration file.
Note that among other limitations, BitBucket provides relatively low rate-limits for applications (up to 1000 requests per hour), and does not provide an API to track the actual rate-limit usage.
If you experience a lack of responses from PR-Agent, you might want to set: bitbucket_app.avoid_full_files=true in your configuration file.
This will prevent PR-Agent from acquiring the full file content, and will only use the diff content. This will reduce the number of requests made to BitBucket, at the cost of small decrease in accuracy, as dynamic context will not be applicable.
For self-hosted BitBucket App deployments, bitbucket_app.request_timeout sets both the connection timeout and
response-read inactivity timeout, in positive seconds, for offloaded BitBucket HTTP requests. It defaults to 30 and
is read from host-level configuration or the BITBUCKET_APP__REQUEST_TIMEOUT environment variable; repository.pr_agent.toml overrides do not apply to this host resource limit.
BitBucket Self-Hosted App automatic commands
To control which commands will run automatically when a new PR is opened, you can set the pr_commands parameter in the configuration file:
Specifically, set the following values:
[bitbucket_app]
pr_commands = [
"/review --pr_code_suggestions.committable_code_suggestions=true",
]Since this platform only supports inline code suggestions, /review posts each finding inline and limits their number with pr_reviewer.num_max_findings (6 by default).
To enable BitBucket app to respond to each push to the PR, set (for example):
[bitbucket_app]
handle_push_trigger = true
push_commands = [
"/describe",
"/review",
]BitBucket Server webhook
For a BitBucket Server webhook deployment, new commits pushed to an open PR arrive as pr:from_ref_updated ("Source branch updated" in the webhook settings) and run no commands by default. The repository "Push" event (repo:refs_changed) carries no pull request and is ignored. To run commands on each push, subscribe the webhook to pr:from_ref_updated and set (for example):
[bitbucket_server]
handle_push_trigger = true
push_commands = [
"/describe",
"/review",
]Azure DevOps provider
To use Azure DevOps provider use the following settings in configuration.toml:
[config]
git_provider="azure"Azure DevOps provider supports PAT token or DefaultAzureCredential authentication.
PAT is faster to create, but has build in expiration date, and will use the user identity for API calls.
Using DefaultAzureCredential you can use managed identity or Service principle, which are more secure and will create separate ADO user identity (via AAD) to the agent.
If PAT was chosen, you can assign the value in .secrets.toml.
If DefaultAzureCredential was chosen, you can assigned the additional env vars like AZURE_CLIENT_SECRET directly,
or use managed identity/az cli (for local development) without any additional configuration.
in any case, 'org' value must be assigned in .secrets.toml:
[azure_devops]
org = "https://dev.azure.com/YOUR_ORGANIZATION/"
# pat = "YOUR_PAT_TOKEN" needed only if using PAT for authenticationAzure DevOps Webhook
To control which commands will run automatically when a new PR is opened, you can set the pr_commands parameter in the configuration file, similar to the GitHub App:
[azure_devops_server]
pr_commands = [
"/describe",
"/review",
]Gitea Webhook
After setting up a Gitea webhook, to control which commands will run automatically when a new MR is opened, you can set the pr_commands parameter in the configuration file, similar to the GitHub App:
[gitea]
pr_commands = [
"/describe",
"/review",
]Docs Usage Guide Changing A Model (`docs/docs/usage-guide/changing_a_model.md`)
title: "Changing a Model" sidebar_position: 8
Changing a model in PR-Agent
See here for a list of supported models in PR-Agent.
The current default model and fallback tier are defined in the configuration file.
To use different models, edit these fields in that file:
[config]
model = "..."
fallback_models = ["..."]Keep fallback_models different from model, or set it to [] for no backup model. Listing the
primary model again only runs a failed call on the same model, so each fallback-eligible failure
repeats. A request the provider rejects (a 429, a 5xx answer or a connection error) is already
retried on the same model up to config.num_retries times (default 4) before the fallback models
are tried, waiting for the provider's Retry-After (up to 30 seconds) or with exponential backoff
between attempts. Set it to 0 to move to the fallback models at once.
/describe, /add_docs, /generate_labels, /update_changelog, /ask, /ask_line, and /help
reject responses withfinish_reason="length" before publication and use the existing failure and fallback handling.
If every model attempt fails, they do not publish the truncated result. For large-PR /describe,
successful chunks can still produce an output with an incomplete-coverage notice when other chunks
fail. If all chunks fail or the final description is truncated, the overall attempt must recover
through a fallback model before publication. Normal completed responses keep the same model-call count;
fallback attempts can increase latency and token cost.
To see which of these models actually handled a given PR, enable config.output_run_details (see Additional configurations).
To send small pull requests to a cheaper model, see Routing small pull requests to a cheaper model.
PR-Agent supports LiteLLM's native model providers and third-party endpoints that implement
the OpenAI-compatible or Anthropic-compatible API. These compatible endpoints need no
provider-specific integration in PR-Agent: configure the endpoint and credentials under the
matching LiteLLM provider, and use that provider's model prefix.
For OpenAI-compatible endpoints, use the openai/ prefix and set the endpoint URL and key:
[config]
model = "openai/<provider-model-id>"
fallback_models = []
custom_model_max_tokens = 32000 # set this when the model is not in PR-Agent's token-limit table
[openai] # in .secrets.toml
api_base = "https://api.example.com/v1"
key = "..."For Anthropic-compatible endpoints, use the anthropic/ prefix and the [anthropic]
settings instead:
[config]
model = "anthropic/<provider-model-id>"
fallback_models = []
custom_model_max_tokens = 32000 # set this when the model is not in PR-Agent's token-limit table
[anthropic] # in .secrets.toml
key = "..."The endpoint must support the corresponding API protocol and request features PR-Agent uses.
The model ID, API base URL, required version/path, and supported parameters are provider-specific;
check that provider's API documentation. For OpenAI-compatible endpoints, the settings can also
be supplied as OPENAI__API_BASE and OPENAI__KEY. For Anthropic-compatible endpoints, setANTHROPIC_API_BASE (or ANTHROPIC_BASE_URL) for the endpoint and ANTHROPIC__KEY for
authentication.
If no reliable model limit can be resolved, set config.custom_model_max_tokens to
the endpoint's supported input limit. Official OpenRouter routes can also use
model context discovery.
:::note[Model-specific environment variables]
See litellm documentation for the environment variables needed per model, as they may vary and change over time. Our documentation per-model may not always be up-to-date with the latest changes.
Failing to set the needed keys of a specific model will usually result in litellm not identifying the model type, and failing to utilize it.
:::
:::warning[Credential isolation boundary]
PR-Agent captures request settings and supported provider environment values per handler. Deployment-owned LiteLLM secret managers are outside this request-isolation boundary; their credentials are not snapshotted by PR-Agent. Keep process environment variables and LiteLLM globals stable while requests run. The handler does not isolate arbitrary changes made by embedding applications during a request. Use separate processes when workloads require different deployment-owned credential sources or mutable global authentication and routing state.
Process-wide routing fallbacks such as litellm.api_base, litellm.api_version, litellm.organization, litellm.vertex_project, and litellm.vertex_location can be rejected even when unchanged. Use the corresponding PR-Agent settings (OPENAI.API_BASE, OPENAI.API_VERSION, OPENAI.ORG, VERTEXAI.VERTEX_PROJECT, and VERTEXAI.VERTEX_LOCATION) or supported provider environment variables, and clear the corresponding LiteLLM globals even when they match the intended routing. Use LITELLM.EXTRA_HEADERS instead of litellm.headers.
:::
OpenAI Flex Processing
To reduce costs for non-urgent/background tasks, enable Flex Processing:
[litellm]
extra_body='{"service_tier": "flex"}'See OpenAI Flex Processing docs for details.
Chat template options
For OpenAI-compatible endpoints that accept chat_template_kwargs, such as a
vLLM deployment serving Qwen,
pass a JSON object through the existing global option:
[litellm]
extra_body='{"chat_template_kwargs": {"enable_thinking": false}}'PR-Agent sends this object in the request body and preserves generated OpenRouter
routing, reasoning, and request-attribution fields. The setting applies to every
configured model, including fallback models, so use it only when all selected
endpoints support the field. Existing service_tier and processing_mode options
can be included in the same JSON object.
An endpoint that accepts thinking_token_budget, such as vLLM, can limit the reasoning tokens of a model:
[litellm]
extra_body='{"thinking_token_budget": 4000}'PR-Agent also sends this field to fallback models.
Azure
To use Azure, set in your .secrets.toml (working from CLI), or in the GitHub Settings > Secrets and variables (working from GitHub App or GitHub Action):
[openai]
key = "" # your azure api key
api_type = "azure"
api_version = '2023-05-15' # Check Azure documentation for the current API version
api_base = "" # The base URL for your Azure OpenAI resource. e.g. "https://<your resource name>.openai.azure.com"
deployment_id = "" # The deployment name you chose when you deployed the engineand set in your configuration file:
[config]
model="" # the OpenAI model you've deployed on Azure (e.g. gpt-4o)
fallback_models=["..."]Azure AD authentication needs the azure extra (pip install "pr-agent[azure]"). To use Azure AD (Entra id) based authentication set in your .secrets.toml (working from CLI), or in the GitHub Settings > Secrets and variables (working from GitHub App or GitHub Action):
[azure_ad]
client_id = "" # Your Azure AD application client ID
client_secret = "" # Your Azure AD application client secret
tenant_id = "" # Your Azure AD tenant ID
api_base = "" # Your Azure OpenAI service base URL (e.g., https://openai.xyz.com/)The request-local Azure OIDC bridge captures AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_AUTHORITY_HOST, AZURE_SCOPE, and competing AZURE_CLIENT_SECRET / AZURE_USERNAME / AZURE_PASSWORD settings when the handler is initialized. It preserves native authentication precedence while binding companion credentials and their cache identity to the captured authority; an absent authority uses the Azure public-cloud default, while an empty authority is rejected for companion credentials. LiteLLM's native assertion and secret-selector resolvers still control updates and source selection; their underlying deployment-owned credential chains are not request-isolated. Keep those sources scoped to the intended workload identity, or use separate processes for distinct identities.
For native Azure SDK routes other than Cloudflare gateways, ordinary AD tokens use the same captured companion settings and SDK client-cache isolation. Azure Responses routes also bind ordinary AD companion selection to the captured settings. Complete companion credentials can also be selected without an initial AD token, including on native Azure AI raw HTTP routes. Captured companion providers retain callable token refresh and native authentication precedence. If SDK initialization or Responses token resolution reaches LiteLLM's implicit credential discovery with enable_azure_ad_token_refresh=True, the request is rejected: that fallback re-reads process-wide identity settings. Configure complete client-secret or username/password companion credentials instead. Managed identity, certificate, and default credential-chain discovery through this fallback are intentionally unsupported; an already cached, isolated SDK client can still be reused without entering discovery.
Passing custom headers to the underlying LLM Model API can be done by setting extra_headers parameter to litellm.
[litellm]
extra_headers='{"projectId": "<authorized projectId >"}' #The value of this setting should be a JSON string representing the desired headers, a ValueError is thrown otherwise.This enables users to pass authorization tokens or API keys, when routing requests through an API management gateway.
Requests that would otherwise inherit non-empty process-wide litellm.headers are rejected, even for non-authentication headers; configure headers through LITELLM.EXTRA_HEADERS instead.
Ollama
You can run models locally through either VLLM or Ollama
E.g. to use a new model locally via Ollama, set in .secrets.toml or in a configuration file:
[config]
model = "ollama/qwen3.8:27b"
fallback_models=[]
reasoning_effort = "none" # disable thinking for this example
additional_reasoning_effort_models = ["ollama/qwen3.8:27b"]
custom_model_max_tokens=32768 # match the Ollama server's effective context window
duplicate_prompt_examples=true # will duplicate the examples in the prompt, to help the model to generate structured output
[ollama]
api_base = "http://localhost:11434" # or whatever port you're running Ollama onOllama's context window may be too small for PR-Agent prompts and pull-request diffs. Set OLLAMA_CONTEXT_LENGTH to suit your model and available memory. For the qwen3.8:27b tag used above, start the server with OLLAMA_CONTEXT_LENGTH=32768 ollama serve to match the example's 32K budget rather than assuming the tag's full 256K context is available. Ollama's context-length guide recommends at least 64K for coding and agent workloads when the model and available memory allow it.
Verify the effective context with ollama ps and set custom_model_max_tokens no higher than that context or the model's supported limit.
Qwen3.8 enables thinking by default. The example explicitly registers the tagged model for reasoning_effort forwarding even when LiteLLM lacks matching metadata; "none" maps to Ollama's think: false. If you enable thinking, allow additional time and output-token headroom.
:::note[Evaluating local and hosted models]
PR-Agent can use many AI models, but complex code analysis requires reliable instruction following,
structured output, and sufficient context for the prompts and pull-request diffs.
Earlier PR-Agent testing found that the local models tested were better suited to experimentation
and learning (particularly the ask command) than to production-level code analysis. These findings
reflect the models available at the time (January 2025), not every newer model or deployment.
For production workflows, use a model that has demonstrated reliable results on your workload.
Hosted commercial models such as GPT-5, Claude Sonnet, and Gemini are established options. Before
using a local model in production, evaluate it on representative pull requests with the intended
PR-Agent commands. Check the quality and correctness of findings, structured-output reliability,
effective context budget, and latency. Local deployment also requires sufficient memory and compute;
model size, quantization, and serving configuration can affect the results.
:::
Hugging Face
To use a model deployed with Hugging Face Inference Endpoints, such as Gemma 4 12B IT, set:
[config] # in configuration.toml
model = "huggingface/google/gemma-4-12B-it"
fallback_models=[]
reasoning_effort = "none" # avoid requesting thinking when forwarded
custom_model_max_tokens=32768 # example; use your deployed endpoint's supported input-token limit
[huggingface] # in .secrets.toml
key = "..." # your Hugging Face API key
api_base = "..." # the base URL for your Hugging Face inference endpointDeploy the selected model first (see the verified Inference Endpoints deployment recipe), accept its access terms if required, and adjust custom_model_max_tokens to the endpoint's supported input-token limit, not its total context window.
Gemma 4's vLLM reasoning mode is opt-in by default. PR-Agent only forwards reasoning_effort when reasoning support is recognized or explicitly configured; "none" avoids enabling thinking if the parameter is forwarded.
(you can obtain a Hugging Face access token from here)
Replicate
To use Llama 3 with Replicate, for example, set:
[config] # in configuration.toml
model = "replicate/meta/meta-llama-3-8b-instruct"
fallback_models=[]
custom_model_max_tokens=8000 # Set an explicit limit because the locked LiteLLM version has no metadata for this model.
[replicate] # in .secrets.toml
key = "..."(you can obtain a Replicate API token from here)
Also, review the .secrets_template.toml file for instructions on how to set keys for other models.
Groq
To use a GroqCloud model, prefix its model ID with groq/:
[config] # in configuration.toml
model = "groq/openai/gpt-oss-120b"
fallback_models = []
[groq] # in .secrets.toml
key = "..." # your Groq API key(you can obtain a Groq key from here)
SambaNova
To use an available model on SambaCloud, set:
[config] # in configuration.toml
model = "sambanova/<model-id>"
fallback_models = []
[sambanova] # in .secrets.toml
key = "..." # your SambaNova api keyReplace <model-id> with an available chat model ID from the SambaCloud model catalog, keeping the sambanova/ prefix. If neither PR-Agent nor LiteLLM can resolve the model's input-token limit, set config.custom_model_max_tokens to its verified positive input-token limit. The empty fallback list disables fallback models; if you configure any, use models available through their respective providers and configure the required credentials and endpoints. You can obtain a SambaNova key from here.
xAI
To use xAI's models with PR-Agent, set:
[config] # in configuration.toml
model = "xai/grok-4.6"
fallback_models = [] # or any other model as fallback
[xai] # in .secrets.toml
key = "..." # your xAI API keyYou can obtain an xAI API key from xAI's console by creating an account and navigating to the developer settings page.
Grok 4.5 and Grok 4.6 are registered with a 500K token context window (xai/grok-4.5, xai/grok-4.5-latest, xai/grok-build-latest, xai/grok-4.6, openrouter/x-ai/grok-4.5, openrouter/x-ai/grok-4.6). xAI publishes grok-4.5-latest and grok-build-latest aliases for Grok 4.5; Grok 4.6 currently has no published alias.
Grok 4.5 and Grok 4.6 are always-on reasoning models and honor config.reasoning_effort (low, medium, high; "xhigh" is supported on Grok 4.6 and later). PR-Agent sends medium by default; set "high" to restore xAI's native default. This setting is global, so changing it also affects other registered reasoning models. Unsupported values are clamped to the closest accepted level (none/minimal → "low"; "max"/"xhigh" on Grok 4.5 → "high"; "max" on Grok 4.6 → "xhigh").
OpenRouter routes (openrouter/x-ai/grok-4.5, openrouter/x-ai/grok-4.6) apply the same clamping after the OpenRouter effort value is resolved but before the none-versus-budget decision. An explicit openrouter.reasoning_effort overrides the global effort; a positive openrouter.reasoning_max_tokens remains budget-only and suppresses effort, including a clamped "none" value. Routing suffixes such as :nitro require custom_model_max_tokens because token lookup currently uses exact model IDs.
Vertex AI
Vertex AI needs the google extra (pip install "pr-agent[google]"). To use Gemini 3.8 Flash on Google's Vertex AI platform, set:
[config] # in configuration.toml
model = "vertex_ai/gemini-3.8-flash"
fallback_models=[]
no_temperature_models=["gemini-3.8-flash"] # Omit temperature for this model.
[vertexai] # in .secrets.toml
vertex_project = "my-google-cloud-project"
vertex_location = "global"Your application default credentials will be used for authentication so there is no need to set explicit credentials in most environments.
If you do want to set explicit credentials, then you can use the GOOGLE_APPLICATION_CREDENTIALS environment variable set to a path to a json credentials file.
Each handler captures the selected Cloud SDK ADC file and its resource project configuration, including CLOUDSDK_CONFIG, the active named configuration, and CLOUDSDK_CORE_PROJECT. Later changes apply to new handlers, not existing ones. The quota project remains separate from the resource project. When no ADC file exists at initialization, the handler retains managed-runtime discovery rather than adopting a file created later.
AWS-backed Vertex workload identity federation captures environment credentials and region per handler. Different captured identities use separate credential caches even when they share the same WIF configuration; identical snapshots can reuse a cache entry. Metadata-backed credentials continue refreshing through the captured metadata source.
Vertex external-account credentials with an executable source are intentionally unsupported, including when GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES=1. The helper and its cached output can change identity after a handler captures its configuration, so Vertex requests reject this source before using it for authentication. Use a non-executable credential source configured for the intended identity instead; normal credential refresh remains enabled for supported sources.
Google AI Studio
To use Google AI Studio models, set the relevant models in the configuration section of the configuration file:
[config] # in configuration.toml
model="gemini/gemini-3.8-flash"
fallback_models=[]
[google_ai_studio] # in .secrets.toml
gemini_api_key = "..."If you don't want to set the API key in the .secrets.toml file, you can set the GOOGLE_AI_STUDIO.GEMINI_API_KEY environment variable.
Gemini 4 Argon (gemini/gemini-4-argon, vertex_ai/gemini-4-argon) accepts the config.reasoning_effort levels low, medium, and high; minimal is normalized to low and xhigh/max are normalized to high before the request is sent. Gemini 4 Hydrogen (gemini/gemini-4-hydrogen, vertex_ai/gemini-4-hydrogen) accepts low, medium, high, and xhigh; minimal is normalized to low and max is normalized to xhigh. Both share a 1,048,576-token context window across input and output.
Anthropic
To use Anthropic models, set the relevant models in the configuration section of the configuration file:
[config]
model="anthropic/claude-opus-5"
fallback_models=[]And also set the api key in the .secrets.toml file:
[anthropic]
KEY = "..."See litellm documentation for more information about the environment variables required for Anthropic.
Amazon Bedrock
To use Amazon Bedrock and its foundational models, add the below configuration:
[config] # in configuration.toml
model="bedrock/us.anthropic.claude-sonnet-4-6"
fallback_models=[]
[aws]
AWS_ACCESS_KEY_ID="..."
AWS_SECRET_ACCESS_KEY="..."
AWS_REGION_NAME="us-east-1"This example uses the US cross-region inference profile for Claude Sonnet 4.6. Enable model access and allow invocation of the profile and its destination foundation models as shown below.
You can also use the new Meta Llama 4 models available on Amazon Bedrock:
[config] # in configuration.toml
model="bedrock/us.meta.llama4-scout-17b-instruct-v1:0"
fallback_models=["bedrock/us.meta.llama4-maverick-17b-instruct-v1:0"]Kimi K3 is also available on Amazon Bedrock:
[config] # in configuration.toml
model="bedrock/moonshotai.kimi-k3"
fallback_models=["bedrock/us.moonshotai.kimi-k3"]Use the bare bedrock/moonshotai.kimi-k3 id where it's directly available, the us. cross-region
prefix to route across US regions, or the global. prefix to let Bedrock route across all
supported regions. To call it through the Bedrock Converse API instead of the classic runtime,
prefix the model id with bedrock/converse/, e.g. bedrock/converse/us.moonshotai.kimi-k3.
Grok 4.3 is available through Amazon Bedrock Mantle rather than the classic Bedrock runtime:
[config] # in configuration.toml
model="bedrock_mantle/xai.grok-4.3"
fallback_models=[]Bedrock Mantle uses the same AWS credential sources, but its IAM permissions differ from the classic runtime. See
the AWS Mantle inference permissions.
Using IAM Role Credentials (Recommended on AWS Compute)
When running PR-Agent on AWS infrastructure (EC2, ECS/Fargate, EKS with IRSA, Lambda, or any self-hosted GitHub Actions runner on AWS), the instance or task already has an IAM role attached. You can use those ambient credentials directly instead of storing long-lived static keys.
Set AWS_USE_IMDS=true in the environment. PR-Agent will resolve credentials via boto3's standard provider chain, which handles all AWS compute contexts transparently:
| Compute context | Mechanism |
|---|---|
| EC2 instance with IAM role | IMDSv2 (169.254.169.254) |
| ECS / Fargate task role | Task metadata endpoint |
| EKS pod with IRSA | Web identity token + STS |
| Lambda function | Runtime-injected credentials |
Credential discovery runs during handler initialization. Before each eligible SigV4 request, refresh through the
same boto3 credentials object runs in a background thread. Non-AWS and bearer-authenticated requests do not trigger
this refresh. PR-Agent passes a request-local snapshot to LiteLLM without writing credentials into the process
environment. Constructor discovery and credential-file fingerprinting remain synchronous.
AWS calls using this provider chain remain serialized within a handler, including any static-credential retry.
Cancelling a request does not stop an already-running boto3 refresh, but its result cannot overwrite the handler's
credentials or static-fallback decision. A separate lock serializes SDK refreshes, including cancelled callers'
unfinished work. Refresh uses the event loop's shared default executor: blocked operations and workers waiting for
the SDK lock after repeated cancellations can delay unrelated executor work and process shutdown. No service-wide
worker quota or additional SDK timeout is introduced.
The same opt-in is required for other boto3 provider-chain sources, including AWS_PROFILE and shared credentials
files. LiteLLM-specific AWS_PROFILE_NAME and AWS_ROLE_NAME selectors are not supported because they can override
request-local credentials; unset them and use AWS_USE_IMDS=true instead.
When upgrading from implicit LiteLLM credential-chain discovery, set AWS_USE_IMDS=true explicitly. Without this
opt-in, PR-Agent only uses complete static credentials from settings or environment credentials captured when the
handler is initialized; it does not ask LiteLLM to discover a role or profile at request time.
For classic Bedrock, a supported model ARN supplies the request region ahead of environment/settings regions, including during static-credential retries. Converse also uses a captured litellm.model_id ARN, or a region/model path when model_id is absent; Invoke does not derive its region from the separate model_id. Otherwise, without AWS_USE_IMDS=true, set aws.AWS_REGION_NAME, AWS_REGION_NAME, AWS_REGION, or AWS_DEFAULT_REGION. Complete environment credentials alone do not enable region discovery from boto3 profiles or LiteLLM's default region. Static credentials in [aws] still require AWS_REGION_NAME.
For Bedrock Mantle without IMDS or complete static credentials, the region comes from BEDROCK_MANTLE_REGION, AWS_REGION_NAME, aws.AWS_REGION_NAME, or AWS_REGION, then defaults to us-east-1; AWS_DEFAULT_REGION alone does not change that default. A BEDROCK_MANTLE_API_BASE on the standard host https://bedrock-mantle.<region>.api.aws supplies the region and overrides these sources; a custom endpoint host does not. Complete static credentials and opted-in boto3 discovery retain the AWS region policy described above.
Without AWS_USE_IMDS=true, environment authentication follows LiteLLM's AWS_SESSION_TOKEN selection. The legacy AWS_SECURITY_TOKEN alias is recognized only by the opted-in boto3 chain, which prefers it over AWS_SESSION_TOKEN when both are nonempty.
Bedrock bearer tokens must come from handler-captured credentials rather than process-wide LiteLLM fallback, and AWS_BEARER_TOKEN_BEDROCK must be unset for sagemaker_chat and sagemaker_nova routes.
When resolving credentials through profiles with AWS_USE_IMDS=true, PR-Agent does not executecredential_process in the selected profile or its source_profile chain. If such a process is configured,
PR-Agent uses complete static credentials from [aws] (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, andAWS_REGION_NAME, plus AWS_SESSION_TOKEN when required) instead; without them, credential resolution fails.
This restriction does not apply when using complete environment credentials captured at handler initialization.
Workload token files selected by AWS_WEB_IDENTITY_TOKEN_FILE, profile web_identity_token_file, orAWS_CONTAINER_AUTHORIZATION_TOKEN_FILE must be controlled by the deployment, not switched between tenants.
PR-Agent retains native token reload and credential refresh from the selected source; it does not freeze token
contents or detect a different identity replacing the contents at the same path. Use separately controlled
credential sources and appropriate process/container isolation for distinct workload identities, or supply
explicit request-local credentials. Request-local configuration is not an isolation boundary against arbitrary
code running in the same process.
Minimal GitHub Actions step for review only (no AWS secret keys required):
- uses: the-pr-agent/pr-agent@main
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
AWS_USE_IMDS: "true"
CONFIG__MODEL: "bedrock/us.anthropic.claude-sonnet-4-6"
CONFIG__FALLBACK_MODELS: "[]"
GITHUB_ACTION_CONFIG__AUTO_DESCRIBE: "false"
GITHUB_ACTION_CONFIG__AUTO_IMPROVE: "false"
# AWS_REGION_NAME: us-east-1 # optional if the instance metadata provides itThe IAM role must have bedrock:InvokeModel permission on the inference profile and its destination foundation models. For the US profile invoked from us-east-1, replace 123456789012 with your AWS account ID:
{
"Effect": "Allow",
"Action": "bedrock:InvokeModel",
"Resource": [
"arn:aws:bedrock:us-east-1:123456789012:inference-profile/us.anthropic.claude-sonnet-4-6",
"arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-sonnet-4-6",
"arn:aws:bedrock:us-east-2::foundation-model/anthropic.claude-sonnet-4-6",
"arn:aws:bedrock:us-west-2::foundation-model/anthropic.claude-sonnet-4-6"
]
}If you also configure static keys in [aws], they serve as an automatic fallback when ambient credentials cannot be resolved or a SigV4 call using the opted-in provider chain raises an authentication or permission error. Transient service errors, timeouts, and rate limits keep the ambient credentials for the normal retry path. This applies to Bedrock, Bedrock Mantle, and SageMaker routes, using only the static credentials captured by the handler.
Custom Inference Profiles
To invoke an application inference profile with a classic bedrock/ model (for cost allocation tags and other configuration settings), set model_id to the profile ARN in your configuration:
[config] # in configuration.toml
model="bedrock/us.anthropic.claude-sonnet-4-6"
fallback_models=[]
[aws]
AWS_ACCESS_KEY_ID="..."
AWS_SECRET_ACCESS_KEY="..."
AWS_REGION_NAME="..."
[litellm]
model_id = "your-application-inference-profile-arn"The litellm.model_id parameter applies only to classic bedrock/ calls made through the bedrock-runtime APIs. It does not apply to bedrock_mantle/; for cost allocation with the Mantle Chat Completions and Responses APIs, use Amazon Bedrock Projects.
The profile is sent only with requests for the model set in config.model. Models in config.fallback_models do not use it, so a fallback is never routed to the primary model's inference profile.
To give a fallback its own application inference profile, list it in litellm.model_ids, keyed by the exact model name. An entry in model_ids takes priority for that model; model_id still applies to config.model when it has no entry. A model that is in neither gets no profile.
[litellm]
model_ids = {"bedrock/us.anthropic.claude-sonnet-4-6" = "your-primary-profile-arn", "bedrock/qwen.qwen3-235b-a22b-2507-v1:0" = "your-fallback-profile-arn"}Prompt caching and run cost with an ARN
Prompt caching and run-cost estimation identify the model by name, so an opaque application
inference profile ARN needs extra configuration:
- Add the ARN to
claude_adaptive_thinking_models_override(orclaude_extended_thinking_models_overridefor extended thinking) so PR-Agent treats it as
Claude and forwardscache_control_injection_points. See Claude 5 thinking with an
application inference profile ARN. - Map the ARN to a LiteLLM-priced model id in
[litellm] base_models, so run cost is estimated
instead of reported as unavailable:
[litellm.base_models]
"bedrock/converse/arn:aws:bedrock:eu-central-1:<account-id>:application-inference-profile/<profile-id>" = "bedrock/anthropic.claude-sonnet-4-5-20250929-v1:0"Claude 5 thinking with an application inference profile ARN
Claude Sonnet 5 on Bedrock is invoked through an inference profile rather than a direct
foundation-model id. When that profile is an application inference profile, its ARN is an
opaque value that carries no model name. Add that ARN toclaude_adaptive_thinking_models_override so PR-Agent and LiteLLM both treat it as an
adaptive-thinking model:
Use the ARN as the model id and repeat that exact value in the override:
[config] # in configuration.toml
model = "bedrock/converse/arn:aws:bedrock:eu-central-1:<account-id>:application-inference-profile/<profile-id>"
enable_claude_adaptive_thinking = true
claude_adaptive_thinking_models_override = [
"bedrock/converse/arn:aws:bedrock:eu-central-1:<account-id>:application-inference-profile/<profile-id>"
]The override is additive, so named Claude models in the same fallback chain continue to use
built-in detection. PR-Agent also registers each override with LiteLLM, preventing LiteLLM from
converting the adaptive payload to the legacy budget_tokens shape that Bedrock rejects.
ARNs only need the override when the suffix is opaque. An ARN that embeds the model family,
for example ...:inference-profile/us.anthropic.claude-sonnet-5, normalises to a string the
adaptive regex already matches.
Using a Custom VPC Endpoint (PrivateLink)
To route Bedrock traffic through a VPC interface endpoint instead of the public bedrock-runtime endpoint, set AWS_BEDROCK_RUNTIME_ENDPOINT either as an environment variable or in [aws]:
[aws]
AWS_BEDROCK_RUNTIME_ENDPOINT="https://bedrock-runtime.us-east-1.amazonaws.com"Guardrails
To apply an Amazon Bedrock Guardrail to every request, use a bedrock/converse/ model and set:
[bedrock]
guardrail_identifier = "your-guardrail-id"
guardrail_version = "1"
guardrail_trace = "disabled" # or "enabled" / "enabled_full"or the equivalent environment variables BEDROCK__GUARDRAIL_IDENTIFIER and BEDROCK__GUARDRAIL_VERSION. The [bedrock] section is host-only and cannot be overridden from a repository's .pr_agent.toml. When a guardrail is configured, every Bedrock model (including fallback models) must use the explicit bedrock/converse/ prefix; other Bedrock routes (bedrock/invoke/, unprefixed bedrock/<model>, bedrock_mantle/) fail instead of running without the guardrail. A fallback model on a non-Bedrock provider runs without the guardrail.
See litellm documentation for more information about the environment variables required for Amazon Bedrock.
DeepSeek
To use deepseek-v4 model with DeepSeek, for example, set:
[config] # in configuration.toml
model = "deepseek/deepseek-v4-pro"
fallback_models=["deepseek/deepseek-v4-flash"]and fill up your key
[deepseek] # in .secrets.toml
key = "..."(you can obtain a deepseek-v4 key from here)
CompactifAI
To use CompactifAI, select a model with LiteLLM'scompactifai/ prefix, for example:
[config] # in configuration.toml
model = "compactifai/glm-5-3"
fallback_models = ["compactifai/glm-5-2"]
reasoning_effort = "high"
additional_reasoning_effort_models = ["compactifai/glm-5-3", "compactifai/glm-5-2"]Set config.custom_model_max_tokens to a positive limit for PR-Agent's
context-window budgeting, within the verified limits of your CompactifAI
deployment. This is required until the selected model's input limit is available
in PR-Agent's registry or the installed LiteLLM metadata.
CompactifAI's public model pages do not currently specify those limits.
PR-Agent also caps the effective budget with config.max_model_tokens. To use a
larger verified budget, raise both config.custom_model_max_tokens andconfig.max_model_tokens as needed; the effective limit is the smaller value.
This budgeting limit is not the amount of space available for the changed-code diff.
PR-Agent reserves output tokens and subtracts fixed prompt tokens before fitting
the diff, so its usable capacity is lower. Account for these reservations when
choosing your verified limits.
Provide your API key in .secrets.toml:
[compactifai]
key = "..."Alternatively, set COMPACTIFAI__KEY or LiteLLM's native COMPACTIFAI_API_KEY
environment variable. The configured key takes precedence over the native
environment variable. LiteLLM uses https://api.compactif.ai/v1 automatically;
no OpenAI API key or endpoint override is required.
Other available models includecompactifai/quasar-438b. When selecting it, include that model ID inconfig.additional_reasoning_effort_models as well. The explicit list enables
reasoning when the installed LiteLLM metadata does not yet recognize these models.
Use "high", which is supported by GLM-5.2, GLM-5.3 and Quasar-438B; PR-Agent's
default "medium" is not a supported effort for these models. See the
GLM-5.3,
GLM-5.2 and
Quasar-438B documentation.
GLM (Z.AI)
To use GLM models with Z.AI (Zhipu), for example, set:
[config] # in configuration.toml
model = "zai/glm-5.2"
fallback_models=[]and fill up your key
[zai] # in .secrets.toml
key = "..."(you can obtain a Z.AI API key from here)
Kimi (Moonshot)
To use Kimi models with Moonshot, for example, set:
[config] # in configuration.toml
model = "moonshot/kimi-k3"
fallback_models=[]and fill up your key
[moonshot] # in .secrets.toml
key = "..."(you can obtain a Moonshot API key from here)
If you are on the China endpoint instead, add api_base = "https://api.moonshot.cn/v1" under [moonshot].
Qwen (DashScope)
To use Qwen models with Alibaba DashScope, for example, set:
[config] # in configuration.toml
model = "dashscope/qwen3.8-max"
fallback_models=[]and fill up your key
[dashscope] # in .secrets.toml
key = "..."(you can obtain a DashScope API key from here)
Xiaomi MiMo
To use Xiaomi MiMo models, for example, set:
[config] # in configuration.toml
model = "xiaomi_mimo/mimo-v2.5"
fallback_models=[]and fill up your key
[xiaomi_mimo] # in .secrets.toml
key = "..."(you can obtain a Xiaomi MiMo API key from here)
OpenCode Go
To use models from an OpenCode Go subscription, for example, set:
[config] # in configuration.toml
model = "opencode_go/deepseek-v4.1-flash"
fallback_models=[]
[litellm] # in configuration.toml
add_session_id_to_requests = trueOpenCode Go rejects requests without an x-opencode-session header (MissingSessionID). add_session_id_to_requests sends one per PR, see Grouping requests by PR in LiteLLM. To use a fixed session instead, set extra_headers='{"x-opencode-session": "<session id>"}' in the [litellm] section.
and fill up your key
[opencode_go] # in .secrets.toml
key = "..."You can also set the OPENCODE_API_KEY (or OPENCODE_GO_API_KEY) environment variable instead.
:::note[Reasoning models can stall on OpenCode Go]
On large PRs, deepseek-v4.1-flash and deepseek-v4-pro have been seen streaming reasoning for over 10 minutes without returning an answer, so the request ends in litellm.Timeout. Using a different model such as opencode_go/glm-5.3-flash, or setting reasoning_effort = "none" in the [config] section, avoids it.
:::
DeepInfra
To use DeepSeek model with DeepInfra, for example, set:
[config] # in configuration.toml
model = "deepinfra/deepseek-ai/DeepSeek-R1-Distill-Llama-70B"
fallback_models = ["deepinfra/deepseek-ai/DeepSeek-R1-Distill-Qwen-32B"]
[deepinfra] # in .secrets.toml
key = "..." # your DeepInfra api key(you can obtain a DeepInfra key from here)
Mistral
To use models like Mistral or Codestral with Mistral, for example, set:
[config] # in configuration.toml
model = "mistral/mistral-small-latest"
fallback_models = ["mistral/mistral-medium-latest"]
[mistral] # in .secrets.toml
key = "..." # your Mistral api key(you can obtain a Mistral key from here)
Codestral
To use Codestral model with Codestral, for example, set:
[config] # in configuration.toml
model = "codestral/codestral-latest"
fallback_models = []
[codestral] # in .secrets.toml
key = "..." # your Codestral api key(you can obtain a Codestral key from here)
Databricks
To use a model hosted on Databricks (e.g. an Azure Databricks serving endpoint), set:
[config] # in configuration.toml
model = "databricks/<endpoint-name>"
fallback_models = []
[databricks] # in .secrets.toml
api_key = "..." # your Databricks personal access token (PAT)
api_base = "https://adb-xxxx.azuredatabricks.net/serving-endpoints" # your workspace serving-endpoints URLReplace <endpoint-name> with the name of an available chat model serving endpoint in your workspace. For Databricks-hosted models, consult the model catalog for your cloud (Azure, AWS, or Google Cloud) and confirm that the model can be queried through a serving endpoint in your workspace. If neither PR-Agent nor LiteLLM can resolve the endpoint's input-token limit, set config.custom_model_max_tokens to its verified positive input-token limit. See LiteLLM's Databricks provider docs for details.
The configured PAT and endpoint are captured per handler. When both DATABRICKS_CLIENT_ID and DATABRICKS_CLIENT_SECRET are set, LiteLLM performs an OAuth M2M exchange even if a PAT is supplied. An exchange failure can abort the request; after a successful exchange, the supplied PAT replaces the OAuth token in the final Authorization header. Without OAuth M2M credentials or a PAT, optional Databricks SDK authentication remains available. These deployment-owned credentials and profile selection are not request-isolated. Do not change those sources between tenants in a shared process; use request-specific PATs with OAuth M2M credentials unset, or separate processes for distinct workload identities.
Openrouter
To use model from Openrouter, for example, set:
[config] # in configuration.toml
model="openrouter/anthropic/claude-sonnet-5"
fallback_models=["openrouter/deepseek/deepseek-chat"]
custom_model_max_tokens=20000
[openrouter] # in .secrets.toml or passed an environment variable openrouter__key
key = "..." # your openrouter api key(you can obtain an Openrouter API key from here)
OpenRouter's router models can be selected directly without setting custom_model_max_tokens:
[config]
model = "openrouter/auto"
fallback_models = ["openrouter/free"]PR-Agent also registers openrouter/fusion and openrouter/pareto-code. Provider routing, reasoning, and output-cap
settings are optional for all four router models; omit them to use OpenRouter's defaults. See OpenRouter's documentation
for the Auto,
Free,
Fusion, and
Pareto routers.
OpenRouter model context discovery
The built-in LiteLLM handler can fill context-window metadata gaps on its captured
official OpenRouter global route. Existing built-in, custom, alias and SDK limits
take precedence; positive SDK limits are not corrected. Gateways, unproven routes
and custom handler subclasses keep their existing behavior.
Network requests: If no positive limit is resolved, PR-Agent makes an anonymous
GET to OpenRouter's public single-model endpoint.
It sends no inference keys or custom headers, follows no redirects, and is limited
to five seconds and one MiB. Completed lookups are reused within a command, not across commands.
How to opt out: LITELLM_OFFLINE_MODE=true disables this public lookup.
A verified positive config.custom_model_max_tokens avoids metadata lookup.LITELLM_LOCAL_MODEL_COST_MAP selects LiteLLM's cost-map source; it does not disable public discovery.config.max_model_tokens caps a resolved window but cannot supply a missing one./help ignores this cap when fitting documentation.
Limits and failures: If other sources fail and no API record matches the exact
model ID, set a verified positive config.custom_model_max_tokens. Suffixes such as:nitro or :floor are not stripped to inherit a base model's window.
Transport failures, HTTP 408/429/5xx and preparation timeouts try configured fallback
models; without a working fallback, the command fails.
context_length is the total window, not an independent input ceiling or a backend
guarantee. Output headroom is reserved separately.
With custom_llm_provider = "openrouter" in [litellm], native-looking IDs such asopenai/... may need OpenRouter metadata or a verified custom limit rather than
native-provider SDK fallback. Offline mode does not restore that fallback.
Programmatic callers can await pr_agent.algo.token_budget.prepare_model_token_limits(handler, model)
before using handler.get_model_token_limits(model) or a handler-backed AttemptTokenBudget.
The standalone get_max_tokens(model) does not use the handler cache.
Openrouter provider routing, reasoning and output cap
For openrouter/... models you can optionally restrict which upstream providers Openrouter uses, control reasoning, and cap the completion length. All keys live in the [openrouter] section of configuration.toml. Reasoning-capable models are those litellm's bundled reasoning metadata flags over the model id and its provider-prefixed/xai/-forms (plus gemini//vertex_ai/ for documented Gemini 4 openrouter/google/... models), the maintained Grok registry, or config.additional_reasoning_effort_models; they inherit config.reasoning_effort unless an Openrouter-specific effort or token budget is set.
[openrouter]
# Uncomment and adjust the keys you need; unset keys keep Openrouter's defaults.
# provider_only = ["z-ai"] # hard allowlist of upstream providers; empty = default routing
# provider_order = ["z-ai", "novita"] # preferred order instead of an allowlist; ignored when provider_only is set
# allow_fallbacks = true # when provider_order is set, allow routing beyond the list
# reasoning_effort = "low" # override global effort: "none", "minimal", "low", "medium", "high", "xhigh" or "max"
# reasoning_max_tokens = 2048 # explicit budget; ignored only when final effort remains "none"
# max_tokens = 16000 # hard cap on completion tokens for the requestprovider_only and reasoning_effort = "none" are useful to pin a specific provider and to bound the cost of reasoning models. Because Openrouter treats effort and token budgets as mutually exclusive, an explicit Openrouter-specific "none" keeps reasoning disabled when the model supports disabling it. Grok 4.5/4.6, Gemini 3.7/3.8 Flash, Gemini 4 Argon/Hydrogen, and the GPT-6 models whose pages omit "none" (GPT-6 Astra and GPT-6.1 Sol) clamp it to "low" before precedence is applied, so a positive budget wins for those models. For Gemini 3.7/3.8 Flash and Gemini 4 Argon, "xhigh" and "max" are clamped to "high", and for Gemini 4 Hydrogen "max" is clamped to "xhigh"; explicit Openrouter "minimal" remains unchanged for Gemini. Otherwise a positive reasoning_max_tokens value takes precedence over the global effort and other Openrouter-specific values. Invalid Openrouter-specific effort values are warned about and treated as unset, so registered reasoning models fall back to config.reasoning_effort. After model-specific clamps, Openrouter normalizes any remaining "max" to "xhigh" in this path for LiteLLM/OpenRouter compatibility. Supported effort values vary by model. For models not covered by these clamps, do not assume "none" disables reasoning; check the selected model and provider's support. For Anthropic models using a reasoning budget, set the effective output max_tokens higher than reasoning_max_tokens so the final answer has output headroom. See the Openrouter provider routing and reasoning tokens docs.
GitHub Copilot
Models under an active GitHub Copilot subscription are available through litellm's github_copilot provider, which authenticates as your GitHub identity rather than with a dedicated API key:
[config]
model = "github_copilot/<model-id>"
fallback_models = []Replace <model-id> with a model ID supported by the LiteLLM GitHub Copilot provider and available for your Copilot plan and model policies. Optionally list other available github_copilot/ model IDs in fallback_models.
The GitHub identity behind the model needs an active Copilot subscription. LiteLLM resolves token budgets for models with known metadata automatically, so custom_model_max_tokens is not required for those models. PR-Agent still caps the effective window at config.max_model_tokens; raise that setting only if it is below the selected model's supported input limit.
Authentication uses the GitHub Copilot provider flow:
- litellm first looks for a pre-seeded GitHub access token in
access-tokenunderGITHUB_COPILOT_TOKEN_DIR(default~/.config/litellm/github_copilot; the filename is overridable withGITHUB_COPILOT_ACCESS_TOKEN_FILE). In a CI runner, write that token before the job runs - for example, mount a secret into the directory or point the variable at a mounted secret directory - and the flow never becomes interactive. - Only when the file is missing or empty does litellm fall back to the interactive device-code flow (
POST https://github.com/login/device/code, up to three attempts), which does not suit unattended runners. - The Copilot API key (
api-key.jsonin the same directory) is refreshed automatically againsthttps://api.github.com/copilot_internal/v2/token, using the pre-seeded access token.
Whether Copilot's terms permit this programmatic use is a question for GitHub rather than a guarantee this project can make, so confirm before relying on the route.
Custom models
If the relevant model doesn't appear here, you can still use it as a custom model:
Set the model name in the configuration file:
toml[config] model="custom_model_name" fallback_models=[]Set the model or endpoint's supported input-token limit (replace the example value below):
toml[config] custom_model_max_tokens = 32000 # example; use the model or endpoint's supported input-token limitGo to litellm documentation, find the model you want to use, and set the relevant environment variables.
Most reasoning models do not support chat-style inputs (
systemandusermessages) or temperature settings.
To bypass chat templates and temperature controls, setconfig.custom_reasoning_model = truein your configuration file.
Dedicated parameters
OpenAI models
[config]
reasoning_effort = "medium" # "none", "minimal", "low", "medium", "high", "xhigh", "max"With the OpenAI models that support reasoning effort (eg: gpt-6-luna), you can specify its reasoning effort via config section. The default value is medium. You can change it to any supported value based on your usage. Available values depend on the model and provider. Where litellm marks minimal unsupported for a GPT-5 model, PR-Agent sends low instead. For native OpenAI GPT-6 requests, PR-Agent maps minimal to low for all supported GPT-6 models. It also maps none to low for GPT-6.1 Sol; GPT-6 Luna and GPT-6.1 Terra accept none.
For a model served through an OpenAI-compatible endpoint that litellm does not recognize as reasoning-capable, add its ID to config.additional_reasoning_effort_models. For known models support is decided by litellm's bundled reasoning metadata plus the maintained Grok registry (Grok ids resolve through their xai/ prefix) with Claude models left out of the metadata path (their reasoning comes from the dedicated extended/adaptive thinking settings; an explicit entry in the list above still applies to them). Config IDs match exactly or through any provider prefix (e.g. "deepseek-v4-flash-0731" matches "openai/deepseek-v4-flash-0731"). When LiteLLM does not recognize the model, PR-Agent sets allowed_openai_params = ["reasoning_effort"] so the parameter reaches the endpoint. Note the default "medium" may be rejected by providers that accept a different subset (e.g. "none"/"low"/"high"/"max"); adding a custom model ID surfaces that provider-side error instead of silently dropping the setting.
For GPT-6 Sol, Luna, or GPT-6.1 Sol hosted outside OpenAI, Azure, or OpenRouter under the same
model ID, add the ID to this list to explicitly enable reasoning_effort.
To use GPT-6 Sol or
GPT-6 Luna:
[config]
model = "gpt-6-sol" # or "gpt-6-luna"
reasoning_effort = "medium" # "none", "low", "medium", "high", "xhigh", "max"For recognized native Sol-tier GPT-6 IDs on OpenAI, Azure, and OpenRouter routes,
PR-Agent omits temperature.
GPT-6 Sol and GPT-6 Luna accept none: OpenAI routes pass it through unchanged, Azure routes
preserve it, and OpenRouter maps it to disabled reasoning.
GPT-6.1 Sol omits none from its supported levels, so PR-Agent clamps it to low instead; see
its own section below.
All three map max to xhigh on Azure and OpenRouter, and the legacy minimal setting is
mapped to low.
Each has a 1,050,000-token context window, a 922,000-token input ceiling,
and support up to 128,000 output tokens. PR-Agent also applies config.max_model_tokens unless
a command bypasses that configured cap, as /help does; the native input ceiling still applies.
The existing Chat Completions path is used for PR-Agent's
text requests. For GPT-6 Sol and Luna, OpenAI requires the Responses API for built-in tools and
function calling with reasoning; Chat Completions function calling is limited toreasoning_effort = "none".
Unrecognized OpenRouter _thinking variants, such as _thinking:batch or _thinking:free,
keep their literal IDs without native GPT-6 temperature or effort normalization.
Add the full ID to config.additional_reasoning_effort_models to explicitly enable reasoning.
For unregistered literal IDs, prompt budgeting requires usable LiteLLM metadata orconfig.custom_model_max_tokens.
For bare Sol-tier GPT-6 IDs on non-native custom providers, a positive config.custom_model_max_tokens
takes precedence over the native registry value.
To use GPT-6.1 Sol:
[config]
model = "gpt-6.1-sol"
reasoning_effort = "medium" # "low", "medium", "high", "xhigh", "max"GPT-6.1 Sol shares the routing above: same temperature handling, same max/minimal mapping,
and the same 1,050,000-token context window, 922,000-token input ceiling, and 128,000-token
output limit. Its model page lists low, medium (default), high, xhigh, and max only,
so none is not supported and PR-Agent clamps a configured none to low.
For config.reasoning_effort, this covers the OpenAI, Azure, Azure AI, aiohttp
and OpenRouter routes. On OpenRouter, it also applies to an explicitopenrouter.reasoning_effort = "none"; a positive openrouter.reasoning_max_tokens
then takes precedence.
On a non-native custom provider the ID is treated as an unknown model: nothing is sent unless
you list it in config.additional_reasoning_effort_models, and if you do, the configured
effort is forwarded verbatim. Register it only for an endpoint that accepts this model's full
effort set.
Its model page also requires the Responses API for tool calling and describes Chat Completions
as supported without tool calling, so unlike GPT-6 Sol and Luna this model has no Chat
Completions tool-calling path at any effort.
GPT-6.1 Terra uses model = "gpt-6.1-terra" and shares Sol's native token limits.
For custom gateways (including Ollama), set config.custom_model_max_tokens to the actual deployment limit unless LiteLLM has exact-model metadata; custom OpenRouter and Azure-compatible gateways require an explicit limit.
To use GPT-6 Astra:
[config]
model = "gpt-6-astra"
reasoning_effort = "medium" # "low", "medium", "high", "xhigh", "max"PR-Agent omits temperature for GPT-6 Astra and maps none or minimal reasoning effort to low.
Its 1,050,000-token context window remains subject to config.max_model_tokens.
The existing Chat Completions path is used; access depends on your OpenAI account.
Anthropic models
PR-Agent registers existing Claude Sonnet 4.6, Opus 4.6, and Fable 5.2 aliases with a 1,000,000-token context window. config.max_model_tokens still caps the usable prompt budget unless a command explicitly bypasses that cap.
[config]
enable_claude_extended_thinking = false # Set to true to enable extended thinking feature
extended_thinking_budget_tokens = 2048
extended_thinking_max_output_tokens = 4096By default, PR-Agent applies the extended-thinking payload only to a built-in list of Claude models
(see CLAUDE_EXTENDED_THINKING_MODELS in pr_agent/algo/__init__.py). If you use a newer or custom
Claude model that is not in that list, you can override it:
[config]
claude_extended_thinking_models_override = ["anthropic/claude-my-new-model"]When claude_extended_thinking_models_override is non-empty, it fully replaces the built-in list, so
include every model that should receive extended thinking. Leave it empty (the default) to use the
built-in defaults.
:::note[Only models that accept a thinking budget are supported]
PR-Agent enables extended thinking through the manualthinking={"type": "enabled", "budget_tokens": ...} request. Adaptive-only Claude models
(e.g. Opus 4.7/4.8, Opus 5/5.5, Sonnet 5/5.5, Haiku 5.5, Fable 5, Fable 5.1/5.2) reject budget_tokens, so they are
intentionally excluded from the built-in defaults. If you add one toclaude_extended_thinking_models_override anyway, PR-Agent skips the extended-thinking payload
for it and logs a warning rather than sending a request the provider would reject — useenable_claude_adaptive_thinking for those models instead.
:::
Both thinking gates only fire when the model id itself is recognizable: an opaque id such as a
Bedrock application inference profile ARN matches neither gate, and PR-Agent logs a warning
instead of silently sending nothing. See Claude 5 thinking with an application inference
profile ARN.
Output token limit
[config]
max_output_tokens = 0 # 0 = unset (default)By default PR-Agent does not send an output token limit on model calls, so the
provider's own default applies. On some providers that default is low — for example, AWS Bedrock
(Converse API) can cap Claude reasoning models at 4096 output tokens, and since reasoning tokens
count against that budget, the visible answer can come back empty or truncated. Setconfig.max_output_tokens to a positive value (e.g. 16000) to send it to LiteLLM asmax_completion_tokens for native OpenAI/Azure GPT-6 models and recognized Astra IDs,
including bare Astra IDs on custom providers. OpenRouter Astra uses this parameter only
without a routing suffix or with :nitro/:floor. Other routes use max_tokens, and
the azure_text and text-completion-openai routes always use max_tokens.
Use a value supported by the selected model. GPT-6 Astra, Sol, Luna, and GPT-6.1 Sol support
at most 128,000 output tokens, including reasoning tokens.
PR-Agent does not automatically clamp this setting to the model's output limit.
Values below 4096 are raised to 4096, and non-numeric or negative values are ignored; both log a warning.
When Claude extended thinking is enabled, extended_thinking_max_output_tokens takes precedence.
For models with small context windows, keep in mind that prompt and completion tokens share the
model's context window: size config.max_model_tokens so the packed prompt leaves room for the
configured output limit.
Routing small pull requests to a cheaper model
Without routing, regular-model calls use config.model, however small the pull request. In this example,
the first rule selects Luna for smaller pull requests; the second selects Sol for larger ones.config.fallback_models still apply after the selected primary:
[model_routing]
enable = true
[[model_routing.rules]]
max_hunks = 3
max_patch_chars = 10000
model = "gpt-6-luna"
[[model_routing.rules]]
max_hunks = 15
max_files = 6
model = "gpt-6.1-sol"Rules are checked in order, and the first one whose limits the pull request fits selects the primary model for
the call. A pull request that fits no rule uses config.model. Size is measured by the number of diff hunks
(max_hunks) and changed files (max_files) left after the [ignore] rules. Every git provider reports both,
and neither depends on a model's tokenizer, so a threshold means the same thing whichever model it selects.
A rule can also set max_patch_chars, an inclusive ceiling on the sum of Python character counts in the supplied
patch strings. All limits named by a rule must match. This can distinguish a long single-line change from a
short change with the same file and hunk counts. Headers and line endings count too: LF is one character,
CRLF is two, and a combining character counts separately from its base character.
If any file has a missing or non-string patch, or its content could not be fetched, the character count is
unknown. Rules with max_patch_chars are then skipped; later rules without it can still match. An explicit
empty patch counts as zero. An incomplete head file alone does not invalidate its supplied patch string.
The limit measures the text the provider supplies, including any normalization or undetectable clipping;
it does not measure tokens, complete files, or a guaranteed complete diff. Rules without this field keep
using their existing file and hunk limits.
The retry chain starts as [config.model] + config.fallback_models, with a deployment paired to each model.
A matched rule replaces the first pair. If the routed (model, deployment) pair also appears among the
configured fallbacks, the effective chain removes duplicate pairs while preserving their order and adds
the displaced configured primary pair at the end, unless it is already present. This avoids retrying the
same endpoint while retaining the configured primary in this collision case. For example, withconfig.model = "gpt-6.1-sol", no deployment configured, and the first rule above:
config.fallback_models |
retry order if earlier attempts fail |
|---|---|
["gpt-6-luna"] |
gpt-6-luna, gpt-6.1-sol |
["gpt-6-luna", "other-model"] |
gpt-6-luna, other-model, gpt-6.1-sol |
The first successful attempt returns immediately; later entries are attempted only after fallback-eligible
failures. An empty fallback list adds no backup, and a noncolliding route still replaces the primary without
adding it back. The same model with distinct deployment IDs is treated as distinct endpoints. /review
uses this effective chain to recover failed chunks without rerunning successful chunks. Its defensive
uniqueness checks remain: repeated complete pairs in unchanged, noncolliding or unrouted chains can still
disable chunk recovery; those chains are not deduplicated by this routing-specific repair.
Routing applies only to calls that ask for the regular model: /review (which /improve runs), /generate_labels and/add_docs. Commands that already use config.model_weak (/describe, /ask, /update_changelog) are left
alone, and config.model_reasoning is no longer used by any command, since /improve and its self-reflection call were folded into /review. With config.output_run_details
enabled, the run details show which model a routed pull request ended up on.
:::note[Azure deployments]
An Azure deployment is tied to one model, so when openai.deployment_id is set each rule also needs its owndeployment_id. A rule without one is skipped with a warning and the next rule is tried.
:::
Docs Usage Guide Configuration Options (`docs/docs/usage-guide/configuration_options.md`)
title: "Configuration File" sidebar_position: 3
The different commands and sub-commands used by PR-Agent are adjustable via a Git configuration file.
There are three main ways to set persistent configurations:
- Local configuration file
- Global configuration file
- External configuration URL (CLI flag)
In terms of precedence, local configurations will override global configurations, and global configurations will override an external configuration URL.
For a list of all possible configurations, see the configuration options page, or the rendered Configuration Reference which lists every option grouped by section.
In addition to general configuration options, each command has its own configurations. For example, the review command will use parameters from the pr_reviewer section in the configuration file.
:::tip[Tip1: Edit only what you need]
Your configuration file should be minimal, and edit only the relevant values. Don't copy the entire configuration options, since it can lead to legacy problems when something changes.
:::
:::tip[Tip2: Show relevant configurations]
If you set config.output_relevant_configurations to True, each command will also output in a collapsible section its relevant configurations. This can be useful for debugging, or getting to know the configurations better.
:::
Local configuration file
Platforms supported: GitHub, GitLab, Bitbucket Cloud, Bitbucket Server, Azure DevOps, Gitea, Gerrit, CodeCommit
By placing a local .pr_agent.toml file at the repository root on the ref read by your Git provider (usually the default branch; see the provider branch behavior below), you can customize parameters that support repository-level overrides. Note that you need to upload or update .pr_agent.toml before using the PR Agent commands (either at PR creation or via manual trigger) for the configuration to take effect.
Provider endpoint settings are host-controlled: openai.api_base, openai.api_type, openai.api_version, azure_ad.api_base, databricks.api_base, huggingface.api_base, moonshot.api_base, ollama.api_base, and openrouter.api_base are ignored when set in repository-local .pr_agent.toml and must be configured on the host. The same restriction applies to provider authentication and TLS settings: github.deployment_type, bitbucket.auth_type, gitlab.auth_type, gitlab.ssl_verify, gitea.skip_ssl_verification, and gitea.ssl_ca_cert. Jira ticket lookups run with the host's Atlassian credentials, so jira.cloud_id, jira.jira_site, jira.jira_api_email, and jira.project_keys are host-controlled as well. These settings are also rejected in command arguments.
For Gitea, enable repository-local settings in the host environment with GITEA__REPO_SETTING=.pr_agent.toml; this setting is unset by default.
For example, if you set in .pr_agent.toml:
[pr_reviewer]
extra_instructions="""\
- instruction a
- instruction b
...
"""Then you can give a list of extra instructions to the review command.
Loading the local configuration from a non-default branch
Platforms supported: GitHub, GitLab
By default, the local .pr_agent.toml is read from the repo's default branch. When running PR-Agent from the CLI (or any wrapper that exposes its arguments), you can point it at a different branch — for example to test configuration changes from a feature branch before merging them:
python -m pr_agent.cli \
--pr_url=<PR URL> \
--config-branch=<branch name> \
reviewEquivalently, set the PR_AGENT_CONFIG_BRANCH environment variable. The CLI flag takes precedence over the environment variable, and whitespace-only values are ignored.
If .pr_agent.toml cannot be loaded from the requested branch (e.g. the branch or file does not exist), PR-Agent logs a warning and falls back to the default branch.
:::danger[Security: treat the config branch as privileged]
By default, configuration is read from the default branch, so only users who can merge to it can change how PR-Agent behaves. --config-branch / PR_AGENT_CONFIG_BRANCH move that trust boundary to whatever branch you name.
Never set the config branch from untrusted or PR-derived input (e.g. --config-branch=$GITHUB_HEAD_REF / ${{ github.head_ref }} in CI). Doing so lets anyone who can push a branch to the repository supply their own .pr_agent.toml and change repository-configurable review settings — for example injecting extra_instructions, ignoring changed files, or disabling automatic feedback. Host-only settings remain filtered. Always pin the config branch to a fixed, maintainer-controlled branch.
:::
:::note[Provider branch behavior]
Branch selection is currently implemented for GitHub and GitLab. Gitea ignores these options and reads
the local .pr_agent.toml from the pull request target ref, which may differ from the default branch.
Gerrit also ignores these options, but reads the file from the cloned default branch. CodeCommit reads
it from the first pull request target's destination commit, including on multi-target pull requests.
Other platforms retain their provider-specific settings source.
:::
Global configuration file
Platforms supported: GitHub, GitLab, Bitbucket (cloud), Bitbucket Server, Azure DevOps, Gitea
Name an organization-level settings repository with global_settings_repo in the deployment's own configuration; its .pr_agent.toml (read from that repo's default branch) is used as a global configuration for every repository under the same organization. The setting is empty by default, which turns this off, and a repository's .pr_agent.toml or a comment cannot set it. With global_settings_repo = "pr-agent-settings", the repository read is:
- GitHub:
<organization>/pr-agent-settings - GitLab:
<top-level-group>/pr-agent-settings, optionally followed by the closest matching subgroup settings when explicitly enabled below (both GitLab.com and self-hosted GitLab) - Bitbucket (cloud):
<workspace>/pr-agent-settings - Bitbucket Server:
/pr-agent-settings - Azure DevOps:
<org>//pr-agent-settings(looked up in the same project as the current repository) - Gitea:
<owner>/pr-agent-settings
Parameters from a local .pr_agent.toml file, in a specific repo, will override the global configuration parameters (the global file is merged beneath the repo-local one).
For GitHub Enterprise Server, use the same organization-level repository on your GHES host.
The app installation or token used by PR-Agent must have read access to both the pull request repository and the settings repository; otherwise, PR-Agent will skip the global configuration and continue with repository-local settings.
:::note[Caching]
In long-running deployments (the GitHub App / webhook server), the fetched global settings are cached in-process for up to 15 minutes to avoid re-fetching on every webhook event, so a change to the settings repository may take up to that long to take effect there. CLI and CI (GitHub Action) runs are short-lived processes, so they fetch the global settings once per invocation and always see the latest version.
:::
Loading the global settings file is controlled by the use_global_settings_file flag, which is enabled by default but reads nothing until global_settings_repo is set. To opt out and rely only on each repo's local .pr_agent.toml, set:
[config]
use_global_settings_file = falseFor example, with global_settings_repo = "pr-agent-settings" in a GitHub organization named my-org:
The file
my-org/pr-agent-settings/.pr_agent.toml(read from that repository's default branch) serves as a global configuration file for all the repos in the organization.A repository such as
my-org/my-repoinherits that global configuration file, and may override its repository-configurable values in its own.pr_agent.toml.
Project/Group level configuration file
Platforms supported: GitLab, Bitbucket Data Center
For Bitbucket Data Center, the repository named by global_settings_repo within the project supplies the project's shared configuration. Its behavior is unchanged.
GitLab subgroup inheritance
GitLab subgroup inheritance is disabled by default (config.use_group_settings_file = false). Upgrading does not automatically load subgroup settings, even if global_settings_repo is already configured: the existing global-plus-local behavior is preserved until the operator explicitly opts in.
GitLab uses the same host-only global_settings_repo name for top-level and subgroup settings; there is no new subgroup repository naming option. It defaults to an empty string, disabling both lookups. To opt in, set the bare repository name and both enable flags in the deployment's own configuration:
[config]
global_settings_repo = "pr-agent-settings"
use_global_settings_file = true
use_group_settings_file = trueAlternatively, enable the subgroup gate with the host environment variable CONFIG__USE_GROUP_SETTINGS_FILE=true; use_global_settings_file must still be true and global_settings_repo nonempty. use_group_settings_file is a host-only boolean: shared or repository-local .pr_agent.toml files and command/comment arguments cannot enable it.
With subgroup inheritance enabled, a merge request in company/platform/backend/service receives settings in this order:
- Global:
company/pr-agent-settings/.pr_agent.toml. - Group: the closest available subgroup file, starting at
company/platform/backend/pr-agent-settings/.pr_agent.toml, then tryingcompany/platform/pr-agent-settings/.pr_agent.tomlif the nearer file or repository is unavailable. Only one subgroup file is selected; intermediate subgroup files are not all merged. - Local: the reviewed repository's
.pr_agent.toml, using the existing repository configuration branch rules.
Each later source overrides matching keys from earlier sources and retains keys it does not override. All shared files are read from their settings repository's default branch, independent of the reviewed repository's configuration branch. A project directly under the top-level group has only global and local sources; the top-level settings file is not applied twice. GitLab.com, self-hosted instances, and numeric project IDs use the same hierarchy.
A present but empty closest subgroup file selects that subgroup without adding overrides; it does not cause more distant subgroup files to be loaded. Malformed TOML is reported as a group settings error with shared file contents omitted from the comment; it is not a reason to select a different subgroup. Other valid sources still apply.
Missing or inaccessible shared settings are optional, matching existing global-settings behavior. PR-Agent needs read access to the applicable settings repositories. Shared configuration is not an enforcement boundary: a local file can override repository-configurable keys, and the host-only key restrictions continue to apply to every source. Whoever can create a project with the global_settings_repo name in a subgroup sets the defaults for every project beneath it that has no closer subgroup settings file, so treat project creation rights in those subgroups as control over their review settings.
The existing bounded, 15-minute in-process cache is reused. GitLab entries are isolated by host, full group path, configured repository name, and credential context; when a safe credential scope is unavailable, lookup bypasses the shared cache. Missing-file/access results are cached too; transient API/transport failures are not cached. Therefore, adding or editing a settings file may take up to 15 minutes to affect a running webhook process.
Set use_group_settings_file = false to disable subgroup lookups while preserving global and local settings. Set use_global_settings_file = false or leave global_settings_repo empty to disable both global and subgroup lookups; the subgroup opt-in does not bypass these prerequisites. As with existing global configuration, use_repo_settings_file = false bypasses the repository-settings loading flow entirely. The optional per-directory configuration layer inside a repository remains separate and unchanged.
External configuration URL
Platforms supported: GitHub, GitLab, Bitbucket Cloud, Bitbucket Server, Azure DevOps, Gitea, Gerrit, CodeCommit
When running PR-Agent from the CLI (or any wrapper that exposes its arguments), you can merge an additional .pr_agent.toml from any URL or local path before the repo-local and global configurations are applied. This is useful when:
- You want a shared configuration source outside the namespace hierarchy used by GitLab subgroup inheritance.
- The shared configuration is published outside of a Git host (a static site, an internal artifact server, an S3 bucket, etc.).
- You want CI-time control over which defaults are layered in, without committing a file to the target repository.
Usage
Pass --extra_config_url to the CLI, or set the PR_AGENT_EXTRA_CONFIG_URL environment variable:
python -m pr_agent.cli \
--pr_url=<MR/PR URL> \
--extra_config_url=https://config.example.com/pr-agent/shared.toml \
reviewAccepted values:
https://…orhttp://…— fetched at runtimefile:///path/to/shared.toml— read from the local filesystem- A bare filesystem path — same as
file://
GitLab comment webhooks apply this host layer before their first provider lookup; repository and per-directory settings remain part of normal command dispatch.
For automatic PR/MR webhooks in GitHub App, GitLab, Gitea, Bitbucket Cloud, Azure DevOps Server, and Bitbucket Server, an external source that cannot be read (for example a failed fetch, an oversized file, or a path that is not a .toml file) skips the event and logs a warning, because the host exclusions and system_instructions could not be applied. The next webhook tries the source again. Manual commands and CLI runs keep running with the settings that did load.
GitLab tokens obtained from a secret provider during webhook authentication remain bound to that request. External files and environment reapplication cannot replace those authenticated credentials.
Authentication for private endpoints
For private endpoints (e.g. a GitLab API URL pointing at a private pr-agent-settings file), provide a single header via the PR_AGENT_EXTRA_CONFIG_AUTH_HEADER environment variable, formatted as <HeaderName>: <value>:
# GitLab Personal Access Token
export PR_AGENT_EXTRA_CONFIG_AUTH_HEADER="PRIVATE-TOKEN: <your-personal-access-token>"
# GitLab CI job token
export PR_AGENT_EXTRA_CONFIG_AUTH_HEADER="JOB-TOKEN: $CI_JOB_TOKEN"
# Generic bearer token
export PR_AGENT_EXTRA_CONFIG_AUTH_HEADER="Authorization: Bearer <your-token>"Precedence
External-URL settings are applied first, so every other layer overrides them:
built-in defaults
< --extra_config_url
< global pr-agent-settings
< local .pr_agent.toml (provider-specific ref)
< environment variables (SECTION__KEY)This means an external URL acts as an organization-wide default that any team can still override with their own pr-agent-settings or repo-local .pr_agent.toml.
Security and limits
The external file is loaded through the same secure loader as the repo-local .pr_agent.toml: includes, preloads, custom loaders, and other directives that could execute code or read arbitrary files are rejected. The fetcher additionally:
- Limits the response size to 1 MB
- Uses a 10-second request timeout
- Only accepts
http,https,fileschemes (or a bare local path)
Docs Usage Guide Configuration Reference (`docs/docs/usage-guide/configuration_reference.md`)
title: "Configuration Reference" sidebar_position: 4
This page is auto-generated and should not be edited by hand.
Regenerate it from the TOML source with:bashpython scripts/generate_config_reference.py
Every configuration option PR-Agent supports, grouped by section. The configuration.toml
file is the single source of truth for defaults and inline comments; this page renders the same
list for easy searching and linking.
Rows with an empty Description are keys whose TOML entry carries no explanatory comment yet.
They are listed deliberately rather than hidden, so the gaps double as the documentation
to-do list.
`[config]` {#config}
| Key | Default | Description |
|---|---|---|
max_webhook_request_body_bytes |
5242880 | maximum request body accepted by webhook servers (5 MiB) |
bot_display_name |
"PR-Agent" | product name shown in user-visible PR comments; host-only, repo settings and comment args cannot set it |
models
| Key | Default | Description |
|---|---|---|
model |
"gpt-6.1-sol" | |
fallback_models |
["gpt-6-luna"] |
CLI
| Key | Default | Description |
|---|---|---|
git_provider |
"github" | |
publish_output |
true | |
publish_output_progress |
true | |
verbosity_level |
0 | 0,1,2 |
use_extra_bad_extensions |
false |
Log
| Key | Default | Description |
|---|---|---|
log_level |
"INFO" |
Configurations
| Key | Default | Description |
|---|---|---|
use_repo_settings_file |
true | |
use_global_settings_file |
true | |
use_group_settings_file |
false | host-only opt-in to GitLab closest-subgroup settings; also requires use_global_settings_file and a nonempty global_settings_repo |
global_settings_repo |
"" | host-only name of the repository, in the owning org/group/workspace, whose .pr_agent.toml applies to every repository there. Empty disables namespace-wide settings; set "pr-agent-settings" to keep the previous behaviour |
enable_per_directory_settings |
false | when true, merge per-directory .pr_agent.toml files found by walking up from the PR's changed files (monorepo support). Adds bounded recursive tree discovery per MR; per-directory files may only override non-critical sections (see REPO_PER_DIRECTORY_OVERRIDABLE_SECTIONS). Nearest (deepest) directory wins on shared keys; equal-depth siblings resolve to the lexicographically-last path; when more files match than the per_directory_settings_max_files cap, shallower files are applied first and a partially capped depth keeps its later-path (winning) siblings; any overlap is logged as a warning. |
per_directory_settings_max_files |
20 | hard ceiling on the number of per-directory .pr_agent.toml files applied per MR (deeper configs beyond the cap are skipped with a warning) |
per_directory_settings_max_tree_pages |
10 | maximum GitLab recursive-tree pages (100 entries each); skip nested settings if discovery is incomplete. Root/host-controlled, independent of the settings-file cap. |
extra_config_url |
"" | optional URL or path to an additional .pr_agent.toml merged before the repo-local config; also settable via --extra_config_url or PR_AGENT_EXTRA_CONFIG_URL. See docs/docs/usage-guide/configuration_options.md#external-configuration-url. |
disable_auto_feedback |
false | |
enable_auto_approval |
false | host-only. /review approves or withdraws its approval of the reviewed GitHub or GitLab commit; see docs/docs/commands/review.md |
ai_timeout |
120 | 2 minutes |
http_request_timeout |
60 | host-only connect/read inactivity seconds for GitLab/Gitea and direct Bitbucket/Gerrit HTTP attempts; capped at 600 |
retry_same_model_on_timeout |
true | when false, a timed-out call is not retried on the same model and moves on to fallback_models |
retry_same_model_on_length |
false | when true, an empty response truncated by the output cap is retried on the same model instead of moving straight to fallback_models |
num_retries |
4 | same-model retries of a request the provider rejects (429, 5xx, connection error) before fallback_models, waiting for its Retry-After (up to 30 s) or with exponential backoff; 0 falls back at once. Timeouts and empty responses use retry_same_model_on_timeout / retry_same_model_on_length instead |
skip_keys |
[] | |
custom_reasoning_model |
false | when true, disables system messages and temperature controls for models that don't support chat-style inputs |
system_instructions |
"" | Host-only instructions appended to every command's system prompt; repository settings and comment arguments cannot set it. |
custom_comment_footer |
"" | Host-only Markdown text added to the end of command results, including /describe PR descriptions. See docs. |
response_language |
"en-US" | PR response locale (e.g., "en-US", "it-IT"), also used for fixed comment text; applies only during each command. See additional_configurations.md. |
repo_context_files |
["AGENTS.md"] | Prompt context files: paths, alternatives, globs, sibling entries; [] disables. See docs. |
repo_context_from_default_branch |
true | Read repo context files from the repository default branch (trusts only default-branch content). Set to false to read from the PR target branch instead. |
repo_context_max_lines |
500 | Maximum total rendered lines for repo context, including wrapper tags |
repo_context_expand_imports |
false | Expand @path imports in local context files; comment arguments cannot set it. See docs. |
repo_context_max_glob_matches |
20 | Maximum number of files one repo_context_files glob entry (e.g. "docs/adr/*.md") expands to, in name order; each match is one file fetch. A repository's .pr_agent.toml may set it, comment arguments cannot. Clamped to 100. Matches still share the repo_context_max_lines budget. |
repo_context_sibling_repos |
[] | Host-only list of approved sibling repository identifiers (GitHub owner/repo, GitLab group/project or numeric ID strings) that repo_context_files sibling entries may select. On GitHub and GitLab, this also approves repositories for cross-repository issue and ticket context. Empty disables sibling reads. Approve only repositories whose content may be disclosed in consuming PRs, because the actor check bounds who triggers a read, not who chose the target or where the output lands. Repository settings and comment arguments cannot change this list. Canonical identities and owning namespaces are checked after resolution |
repo_context_sibling_namespaces |
[] | Host-only list of additional org/group/workspace names an approved repo_context_sibling_repos entry (or an expanded gitlab.expand_submodule_diffs gitlink) may resolve into. Empty, the default, keeps the reviewed repository's own namespace as the only approved one. Set it where a project's dependencies live in sibling groups rather than its own, e.g. a submodule in a shared library group. It widens namespaces only: a repository still has to be in repo_context_sibling_repos, and the requester's read access is still checked. Repository settings and comment arguments cannot change this list |
repo_context_max_sibling_files |
5 | Maximum number of sibling-repository files fetched per repo-context build. The fetch count is bounded separately from repo_context_max_lines so selected sibling files cannot trigger an unbounded number of cross-repository calls; sibling files still compete for the repo_context_max_lines budget. Host-only (cannot be raised by a repository's .pr_agent.toml or a comment command) and clamped to a hard ceiling of 20 fetches per build. |
token limits
| Key | Default | Description |
|---|---|---|
max_description_tokens |
500 | |
max_commits_tokens |
500 | Token cap on the commit messages sent to the model by /describe, /review, /improve and other commands. 0 means no limit; -1 sends none. |
max_model_tokens |
256000 | Limits the maximum number of tokens that can be used by any model, regardless of the model's default capabilities. |
custom_model_max_tokens |
-1 | Override unknown models or Sol-tier GPT-6 on non-native custom providers. |
max_output_tokens |
0 | 0 = unset (the provider's own default applies) |
model_token_count_estimate_factor |
0.3 | factor to increase the token count estimate, in order to reduce likelihood of model failure due to too many tokens - applicable only when requesting an accurate estimate. |
image_input_token_allowance |
4096 | reserve tokens per image when provider counting omits or underestimates image cost |
patch extension logic
| Key | Default | Description |
|---|---|---|
patch_extension_skip_types |
[".md", ".txt"] | |
allow_dynamic_context |
true | |
max_extra_lines_before_dynamic_context |
10 | will try to include up to 10 extra lines before the hunk in the patch, until we reach an enclosing function or class |
patch_extra_lines_before |
5 | Number of extra lines (+3 default ones) to include before each hunk in the patch |
patch_extra_lines_after |
1 | Number of extra lines (+3 default ones) to include after each hunk in the patch |
secret_provider |
"" | "" (disabled), "google_cloud_storage", or "aws_secrets_manager" for secure secret management |
cli_mode |
false | |
output_relevant_configurations |
false | |
output_run_details |
false | if true, append an agent run details section (model, tokens, time cost, AI calls) to generated PR comments |
output_run_cost |
false | if true, collect estimated LiteLLM API cost and include it inside the enabled run details section |
large_patch_policy |
"clip" | "clip" (default) or "skip"; a missing value is treated as "clip" |
duplicate_prompt_examples |
false | |
persistent_inline_comments |
false | Enable persistent inline comments (issue #2037) to fingerprint each inline comment and embed a provider-compatible marker, then skip re-posting suggestions already present on the PR/MR across runs. |
seed
| Key | Default | Description |
|---|---|---|
seed |
-1 | set positive value to fix the seed (and ensure temperature=0) |
temperature |
0.2 |
ignore logic
| Key | Default | Description |
|---|---|---|
ignore_pr_title |
["^\[Auto\]"] | a list of regular expressions to match against the PR title to ignore the PR agent |
ignore_pr_target_branches |
[] | a list of regular expressions of target branches to ignore from PR agent when an PR is created |
ignore_pr_source_branches |
[] | a list of regular expressions of source branches to ignore from PR agent when an PR is created |
ignore_pr_labels |
[] | labels to ignore from PR agent when an PR is created |
include_pr_labels |
[] | PR label allowlist (exact match; empty disables); see details |
ignore_pr_authors |
[] | authors to ignore from PR agent when an PR is created |
reaction_on_start |
"eyes" | added before the command runs |
reaction_on_success |
"" | replaces the start reaction when the command succeeded (GitHub App, GitLab webhook) |
reaction_on_failure |
"" | replaces the start reaction when the command failed (GitHub App, GitLab webhook) |
ignore_repositories |
[] | a list of regular expressions of repository full names (e.g. "org/repo") to ignore from PR agent processing |
ignore_language_framework |
[] | a list of code-generation languages or frameworks (e.g. 'protobuf', 'go_gen') whose auto-generated source files will be excluded from analysis |
bot_user_indicators |
["codium", "bot_", "bot-", "_bot", "-bot"] | Substring indicators used to skip bot users on webhook events. Currently consumed by the GitLab webhook (is_bot_user); other providers may adopt this list in future. The match is case-insensitive against the sender's display name. Overriding this setting REPLACES the default list — include the entries below in your override if you want to keep them (e.g. ["codium", "bot_", "bot-", "_bot", "-bot", "renovate"]). |
restricted_mode |
false | when true, skip operations that require elevated permissions (e.g. pushing code to the repository) |
is_auto_command |
false | will be auto-set to true if the command is triggered by an automation |
skip_unchanged_diff |
false | skip automatic or CLI /review and /describe when the PR is unchanged since their last successful run. See docs/docs/usage-guide/automations_and_usage.md |
propagate_command_errors |
false | when true, a command re-raises instead of swallowing an internal error, so a caller can tell a failed run from an empty one |
enable_ai_metadata |
false | will enable adding ai metadata |
add_user_to_requests |
false | send the current command and PR URL in the OpenAI-compatible "user" request field, for provider-side attribution of requests (e.g. OpenRouter "external_user") |
reasoning_effort |
"medium" | "none", "minimal", "low", "medium", "high", "xhigh", "max" |
additional_reasoning_effort_models |
[] | Optional: additional model IDs that accept config.reasoning_effort. Reasoning support is otherwise decided by litellm's bundled model metadata (and the maintained Grok registry), so add an ID here when litellm does not know the model (custom OpenAI-compatible endpoints), or when another provider hosts a Sol-tier GPT-6 model under the same ID. Model IDs match exactly or through any provider prefix (e.g. "deepseek-v4-flash-0731" matches "openai/deepseek-v4-flash-0731"). LiteLLM whitelists reasoning_effort through allowed_openai_params for OpenAI-compatible models it does not recognize, so the parameter reaches the endpoint. The default "medium" may be rejected by providers that accept a different subset (e.g. "none"/"low"/"high"/"max"); adding a custom model id now surfaces a provider-side error instead of the previous silent drop. |
no_temperature_models |
["deepseek/deepseek-reasoner", "o1-mini", "o1-mini-2024-09-12", "o1", "o1-2024-12-17", "o3-mini", "o3-mini-2025-01-31", "o3", "o3-2025-04-16", "o4-mini", "o4-mini-2025-04-16", "gpt-5.1-codex", "gpt-5.1-codex-mini", "gpt-5.2-codex", "gpt-5.3-codex", "gpt-5-mini", "moonshotai.kimi-k3", "us.moonshotai.kimi-k3", "global.moonshotai.kimi-k3", "kimi-k3", "kimi-k3.1-pro", "zai.glm-5"] | Optional: model IDs that must never receive the temperature parameter, on top of what litellm's parameter metadata reports. Temperature support is otherwise decided by litellm.get_supported_openai_params() (mirroring reasoning_effort), so add an ID here when litellm reports temperature as supported but the provider rejects it, or when an OpenAI-compatible endpoint accepts but you still want it dropped. Adaptive-thinking Claude models (Opus 4.7/4.8, Opus/Sonnet/Fable 5.x and Haiku 5.5) never receive temperature. Match model IDs exactly or through any provider prefix. For OpenRouter :nitro and :floor routing shortcuts, also match the suffix-free base ID (for example, match future-model to openrouter/vendor/future-model:nitro). Keep other model variants at their full ID. Preserve the former static registry entries below when litellm's metadata still marks them temperature-capable; see #3611 (Derive temperature support from LiteLLM metadata and retire NO_SUPPORT_TEMPERATURE_MODELS) for the probe diff. Bedrock rejects temperature for Kimi K3 and GLM-5 ("This model doesn't support the temperature field"); Moonshot/Kimi reasoning endpoints reject custom temperature. |
extended thinking for Claude reasoning models
| Key | Default | Description |
|---|---|---|
enable_claude_extended_thinking |
false | Set to true to enable extended thinking feature |
extended_thinking_budget_tokens |
2048 | Thinking budget used when enable_claude_extended_thinking is true. |
extended_thinking_max_output_tokens |
4096 | Output cap in extended-thinking mode; it replaces max_output_tokens and must be at least the thinking budget. |
enable_claude_adaptive_thinking |
false | Adaptive thinking for Claude Opus 4.7/4.8 and Claude 5 models. When enabled, these models receive thinking={"type": "adaptive"} and an output_config effort. Do not add adaptive-only models to claude_extended_thinking_models_override; when both features are enabled, adaptive thinking takes precedence. |
claude_adaptive_thinking_models_override |
[] | Optional model ids to treat as adaptive-only Claude models, including opaque Bedrock ARNs. See changing a model. |
claude_extended_thinking_models_override |
[] | Optional: override the built-in list of Claude models that receive the extended-thinking payload. When non-empty, this list fully replaces the built-in defaults (see CLAUDE_EXTENDED_THINKING_MODELS in pr_agent/algo/init.py). Leave empty to use the defaults. |
extract_issue_from_branch |
true | Infer branch issues on GitHub and same-project GitLab (123-...); false disables. See https://docs.pr-agent.ai/core-abilities/fetching_ticket_context/. |
branch_issue_regex |
"" | Optional: custom regex with one or more capturing groups for the issue number (validated at runtime); only the first group is used. If the regex has no capturing group, the default pattern is used; if it does not compile, no branch tickets are extracted. If empty, uses default pattern: first 1-6 digits at start of branch or after a slash, followed by hyphen or end (e.g. feature/1-test, 123-fix), skipping date prefixes such as release/2026-11-15. GitHub only; other providers planned for later. |
description_issue_regex |
"" | Configure a regex replacing bare #N references, with exactly one capturing group for an ASCII issue number. Leave empty for default matching (up to six digits); fall back with a warning on invalid patterns. Set the custom digit limit in the pattern; use only integer-parseable captures. Keep full URLs and owner/repo#N references. Use TOML literal quotes to preserve backslashes, e.g. description_issue_regex = '(?i)(?:fixes|closes|resolves)\s+#(\d+)' |
`[pr_reviewer]` — /review {#pr_reviewer-review}
See Review.
enable/disable features
| Key | Default | Description |
|---|---|---|
require_score_review |
false | |
require_tests_review |
true | |
require_estimate_effort_to_review |
true | |
require_can_be_split_review |
false | |
require_security_review |
true | |
require_estimate_contribution_time_cost |
false | |
require_todo_scan |
false | |
require_ticket_analysis_review |
true | |
require_risk_assessment |
false | ask the model for an overall risk level (low/medium/high) |
require_merge_recommendation |
false | ask the model for a merge recommendation: no_concerns_found (no important blockers or risks identified), needs_review (seems acceptable but deserves focused reviewer attention) or changes_required (clear issues to fix before merge) |
max_changed_lines |
100 | Host-only changed-line cap; a larger diff vetoes no_concerns_found. See docs/docs/commands/review.md |
publish_merge_recommendation_status |
false | Publish the computed verdict as a SHA-scoped check/commit status. See docs/docs/commands/review.md |
require_failure_modes |
false | ask for up to three concrete failure scenarios and their detection/coverage |
require_artifact_findings |
false | with a CI artifact, list up to five neutral facts from it, each with a quote checked against the artifact. See docs/docs/commands/review.md |
require_priority_files |
false | ask the model which files a human should inspect first |
structural_reach_input_file |
"" | JSON reach facts from a build-graph tool; when the file exists, adds a deterministic change-risk row. See docs/docs/commands/review.md |
enable_risk_checks |
true | Flag sensitive paths and risky change shapes; adds nothing when clean. See docs/docs/commands/review.md |
sensitive_paths |
[".github/workflows/", ".github/actions/", ".gitlab-ci.yml", "Jenkinsfile*", ".circleci/", "azure-pipelines.yml", ".travis.yml", "bitbucket-pipelines.yml", "CODEOWNERS", ".pr_agent.toml", "package.json", "package-lock.json", "yarn.lock", "pnpm-lock.yaml", "requirements.txt", "Pipfile", "Pipfile.lock", "pyproject.toml", "poetry.lock", "uv.lock", "Cargo.toml", "Cargo.lock", "go.mod", "go.sum", "pom.xml", "build.gradle", "Gemfile", "Gemfile.lock", "composer.json", "composer.lock", "Dockerfile", "docker-compose*.yml", "docker-compose*.yaml", ".dockerfile", ".tf", ".tfvars", ".hcl", "migrations/", "migration", "db/migrate/", "alembic/**"] | Glob patterns of sensitive paths flagging deterministic review risk findings. See docs/docs/commands/review.md |
extra_risky_shapes |
[] | Custom regex patterns flagging risky changes in diff hunks. See docs/docs/commands/review.md |
general options
| Key | Default | Description |
|---|---|---|
publish_output_no_suggestions |
true | Set to "false" if you only need the reviewer's remarks (not labels, not "security audit", etc.) and want to avoid noisy "No major issues detected" comments. |
publish_review_failure_comment |
true | Set to false to suppress review failure comments without changing the command's failure status. |
publish_error_details |
false | Publish a deterministic, sanitized failure reason in manual review comments. No AI call is used. |
persistent_comment |
true | |
per_commit_review |
false | Review each PR commit on its own diff and message, one review per commit. See per commit review. |
max_commits_per_review |
0 | Optional cap on the commits per_commit_review reviews one by one; above it, the whole PR is reviewed in one review. 0 means no limit. |
review_heading |
"PR Reviewer Guide" | Visible base heading for full and incremental review comments. Identity is tracked separately. |
persistent_finding_state |
true | Persist review finding state across complete review runs. |
max_previous_findings_chars |
8000 | Character budget for the findings stored by earlier reviews, given to /review as context so it keeps their wording instead of re-raising them reworded, and skips findings whose GitHub or GitLab inline thread someone other than PR-Agent resolved (needs persistent_finding_state); 0 disables it. |
show_previous_findings_summary |
true | Show a 'Since the last review' section at the top of the review: addressed, reappeared, still-open and new findings (needs persistent_finding_state). |
inline_key_issues |
true | Publish each review finding as an inline comment where the provider can verify inline-comment publication (GitHub, Bitbucket Cloud, Azure DevOps, GitLab, Gitea). Findings with a fix become committable suggestions when pr_code_suggestions.committable_code_suggestions is on. Set to false to keep every finding in the review summary. |
min_finding_confidence |
0 | Drop findings below this model-reported confidence (0-10); 0 keeps every finding and does not ask the model for one. |
extra_instructions |
"" | |
num_max_findings |
6 | maximum number of key issues /review reports (integer; default 6) |
final_update_message |
true |
Azure DevOps also supplies verified PR-Agent inline key issues as dismissed when their status is wontFix
or byDesign and differs from azure_devops.default_comment_status. Matching defaults, fixed, closed,
active, and pending threads do not count as dismissals. PR-Agent resolves its posting identity through Azure DevOps;azure_devops_server.agent_identity can override it. This infers a human decision from the current configuration;
it cannot verify the status-changing actor or historical defaults. Dismissed findings share the existingmax_previous_findings_chars budget and may be reported again if the code makes them worse.
review labels
| Key | Default | Description |
|---|---|---|
enable_review_labels_security |
true | |
enable_review_labels_effort |
true |
specific configurations for incremental review (/review -i)
| Key | Default | Description |
|---|---|---|
require_all_thresholds_for_incremental_review |
false | |
minimal_commits_for_incremental_review |
0 | |
minimal_minutes_for_incremental_review |
0 | |
enable_intro_text |
true | |
enable_help_text |
false | Determines whether to include help text in the PR review. |
enable_review_coverage_footer |
true | |
enable_large_pr_chunking |
false | large-diff chunking (opt-in). When the token budget leaves files out of the review, split the diff into chunks, review each chunk, and merge the per-chunk results into one review. |
max_number_of_calls |
3 | maximum number of chunk review calls, used only when enable_large_pr_chunking is true |
`[pr_description]` — /describe {#pr_description-describe}
See Describe.
| Key | Default | Description |
|---|---|---|
publish_labels |
false | |
add_original_user_description |
true | |
generate_ai_title |
false | |
extra_instructions |
"" | |
enable_pr_type |
true | |
enable_pr_description |
true | adds a section with an AI-generated summary of the PR changes |
final_update_message |
true | |
enable_help_text |
false | |
enable_help_comment |
false | |
enable_pr_diagram |
true | adds a section with a diagram of the PR changes |
pr_diagram_direction |
"adaptive" | 'adaptive', 'LR', 'TD'. 'adaptive' picks the direction from the shape of the diagram |
pr_diagram_direction_threshold |
5 | with 'adaptive', a chain longer than this many nodes is drawn top-down |
describe as comment
| Key | Default | Description |
|---|---|---|
publish_description_as_comment |
false | When true, publish a comment; local Git writes it to local.description_path. |
publish_description_as_comment_persistent |
true |
changes walkthrough section
| Key | Default | Description |
|---|---|---|
enable_semantic_files_types |
true | |
collapsible_file_list |
"adaptive" | true, false, 'adaptive' |
collapsible_file_list_threshold |
6 | |
file_table_collapsible_open_by_default |
false |
markers
| Key | Default | Description |
|---|---|---|
use_description_markers |
false | |
enable_large_pr_handling |
true | |
include_generated_by_header |
true | Add a "Generated by <config.bot_display_name>" header (with the head SHA when available). Only read when use_description_markers is true. |
max_ai_calls |
4 | Not settable from a per-directory .pr_agent.toml. Caps the /describe AI calls for a large PR (one is kept for the summary). |
async_ai_calls |
true | Not settable from a per-directory .pr_agent.toml. Run a large PR's /describe calls concurrently when enable_large_pr_handling is on. |
`[pr_questions]` — /ask {#pr_questions-ask}
See Ask.
| Key | Default | Description |
|---|---|---|
enable_help_text |
false | |
use_conversation_history |
true | |
use_ticket_context |
false | Include linked ticket context in top-level /ask when true; default false. See commands/ask.md#linked-ticket-context. |
ask_heading |
"Ask" | Set the plain-text heading for top-level /ask answers; provider-specific presentation is added automatically. |
resolve_threads |
false | Enable to let /ask_line resolve the review thread when the LLM judges the issue addressed. Note: also resolves threads started by human reviewers. |
extra_instructions |
"" |
`[pr_code_suggestions]` — /improve {#pr_code_suggestions-improve}
See Fixes and committable suggestions.
| Key | Default | Description |
|---|---|---|
committable_code_suggestions |
false | Deprecated alias still accepted until 1.0: pr_code_suggestions.commitable_code_suggestions |
extra_instructions |
"" | |
suggestions_heading |
"PR Code Suggestions" | Visible base heading for code-suggestion comments. Identity is tracked separately. |
`[pr_add_docs]` — /add_docs {#pr_add_docs-add_docs}
See Add Docs.
| Key | Default | Description |
|---|---|---|
extra_instructions |
"" | |
docs_style |
"Sphinx" | Docstring style: Google Style with Args, Returns, Attributes...etc; Numpy Style; Sphinx; PEP257; reStructuredText. See docs/docs/commands/add_docs.md. |
use_repo_context |
true | Include repository instructions in /add_docs when they fit (true/false); see commands/add_docs.md. |
`[pr_update_changelog]` — /update_changelog {#pr_update_changelog-update_changelog}
See Update Changelog.
| Key | Default | Description |
|---|---|---|
changelog_path |
"CHANGELOG.md" | Repository-relative Markdown changelog path. Root .pr_agent.toml or host settings only; see commands/update_changelog.md. |
push_changelog_changes |
false | |
extra_instructions |
"" | |
add_pr_link |
true | |
skip_ci_on_push |
true |
`[pr_config]` — /config {#pr_config-config}
See Show possible configurations.
This section only documents commented-out examples; see the TOML source for details.
`[pr_help_docs]` {#pr_help_docs}
See Help Docs.
| Key | Default | Description |
|---|---|---|
repo_url |
"" | If not overwritten, will use the repo from where the context came from (issue or PR) |
repo_default_branch |
"main" | |
docs_path |
"docs" | |
exclude_root_readme |
false | |
supported_doc_exts |
[".md", ".mdx", ".rst"] | |
enable_help_text |
false |
`[github]` {#github}
See GitHub.
| Key | Default | Description |
|---|---|---|
deployment_type |
"user" | The type of deployment to create. Valid values are 'app' or 'user'. |
agent_login |
"" | Host-only login PR-Agent posts as when its token cannot call GET /user, e.g. <app-slug>[bot] for a GitHub App installation token in GitHub Actions. Empty falls back to github-actions[bot] under Actions. Repository settings and comment arguments cannot change it |
ratelimit_retries |
5 | Host-only total attempts for retryable GitHub diff collection failures, including rate limits and transient API errors. Integer-valued floats and integer strings are accepted. Zero returns None without collecting a diff. A negative integer attempt limit retries indefinitely. Boolean, non-finite, non-integral float, and unparseable values fall back to 5 with a warning. |
seconds_between_requests |
0 | seconds between API requests; 0 = no pacing (1.59 behaviour) |
seconds_between_writes |
0 | seconds between write calls; 0 = no pacing (1.59 behaviour) |
api_retries |
0 | max retries per request with backoff; 0 = no retries (1.59 behaviour), but the first PR read retries a 5xx or connection error 3 times |
polling_request_timeout |
10 | total seconds for comment-history fallback; positive values capped at 60 |
polling_repositories |
[] | Host-only allowlist of GitHub repositories ("owner/repo") whose mention notifications polling may process. Empty disables all polling notifications. Repository settings and comment arguments cannot change this list |
base_url |
"https://api.github.com" | |
try_fix_invalid_inline_comments |
true | |
ignore_bot_pr |
true | |
publish_as_check_run |
false | when true, publish review/description output as GitHub Checks instead of PR comments |
`[github_action_config]` {#github_action_config}
See GitHub Actions.
This section only documents commented-out examples; see the TOML source for details.
`[github_app]` {#github_app}
See GitHub App.
| Key | Default | Description |
|---|---|---|
override_deployment_type |
true | these toggles allows running the github app from custom deployments |
settings for "pull_request" event
| Key | Default | Description |
|---|---|---|
handle_pr_actions |
["opened", "reopened", "ready_for_review"] | |
feedback_on_draft_pr |
false | |
review_states |
["changes_requested"] | A submitted GitHub review can optionally trigger these commands. The empty default preserves current behavior. |
review_author_types |
["User"] | |
review_commands |
[] | |
webhook_delivery_deduplication |
false | Opt in to in-memory deduplication by X-GitHub-Delivery within each worker process. Active work stays protected; completed IDs expire after the deployment's push_trigger_pending_tasks_ttl (read at startup, 300 seconds by default). Failed or cancelled work can retry immediately. Repeated deliveries do not extend the TTL. Manual redeliveries are also suppressed during this w |