### Install Ultralytics Actions Python Package Source: https://github.com/ultralytics/actions/blob/main/README.md This command installs the 'ultralytics-actions' Python package using pip. This package provides programmatic access to various action utilities, including AI-powered PR review, PR summarization, PR scanning, and handling first interactions with new contributors. It simplifies the integration of these functionalities into Python-based workflows. ```bash pip install ultralytics-actions ``` -------------------------------- ### Install Ultralytics Actions Package (Bash) Source: https://context7.com/ultralytics/actions/llms.txt Installs the ultralytics-actions Python package using pip. This command is essential for accessing the CLI functionalities provided by the package. ```bash # Install package pip install ultralytics-actions ``` -------------------------------- ### Complete Workflow with Disk Cleanup (YAML) Source: https://github.com/ultralytics/actions/blob/main/cleanup-disk/README.md This example showcases a complete GitHub Actions workflow (CI) that includes the disk cleanup action. It first checks out the code, then runs the cleanup action, and finally proceeds with building and testing the project. This ensures ample disk space is available for subsequent build and test steps. ```yaml name: CI on: [push, pull_request] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: ultralytics/actions/cleanup-disk@main - name: Build and test run: | pip install -e . pytest ``` -------------------------------- ### Ultralytics Actions Workflow Setup (YAML) Source: https://github.com/ultralytics/actions/blob/main/README.md This YAML configuration sets up the main Ultralytics GitHub Action. It triggers on push and pull request events, enabling features like code formatting, AI reviews, and auto-labeling. It requires an API key for AI provider integration and specifies the runner environment. ```yaml # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license # Ultralytics Actions https://github.com/ultralytics/actions name: Ultralytics Actions # Controls when the action will run. # For more information see: https://docs.github.com/en/actions/using-workflows/triggering-workflows on: push: branches: ['main'] pull_request: types: [opened, synchronize, reopened, "labeled", "unlabeled"] issues: types: [opened, synchronize, reopened, "labeled", "unlabeled"] jobs: ultralytics-actions: runs-on: ubuntu-latest permissions: contents: read pull-requests: write issues: write steps: - name: Checkout code uses: actions/checkout@v4 - name: Ultralytics Actions uses: ultralytics/actions@main env: # NOTE: Add your OpenAI API key to the repository secrets. Add it as an "openai_api_key" secret. # https://github.com/ultralytics/actions/settings/secrets/actions openai_api_key: ${{ secrets.openai_api_key }} # ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} ``` -------------------------------- ### Python Shell Retry Action Example (YAML) Source: https://github.com/ultralytics/actions/blob/main/retry/README.md Shows how to use the retry action with the Python shell, including a Python code snippet to fetch data and raise an error on failure. ```yaml steps: - uses: ultralytics/actions/retry@main with: shell: python retries: 5 run: | import requests response = requests.get('https://api.example.com/data') response.raise_for_status() ``` -------------------------------- ### GraphQL API - Get Repository Labels Source: https://context7.com/ultralytics/actions/llms.txt Fetches labels for a given repository, including their IDs, names, and descriptions. ```APIDOC ## POST /graphql ### Description Retrieves labels associated with a GitHub repository. ### Method POST ### Endpoint /graphql ### Parameters #### Query Parameters None #### Request Body - **query** (String!) - The GraphQL query string to fetch repository labels. - **variables** (Object!) - Variables for the query, including 'owner' and 'name' of the repository. ### Request Example ```json { "query": "query($owner: String!, $name: String!) {\n repository(owner: $owner, name: $name) {\n labels(first: 100) {\n nodes {\n id\n name\n description\n }\n }\n }\n}", "variables": { "owner": "ultralytics", "name": "yolo" } } ``` ### Response #### Success Response (200) - **data** (Object) - The result of the GraphQL query. - **repository** (Object) - Repository data. - **labels** (Object) - Labels data. - **nodes** (Array) - An array of label objects. - **id** (ID) - The unique identifier for the label. - **name** (String) - The name of the label. - **description** (String) - The description of the label. #### Response Example ```json { "data": { "repository": { "labels": { "nodes": [ { "id": "LABEL_ID_1", "name": "bug", "description": "Something isn't working" }, { "id": "LABEL_ID_2", "name": "enhancement", "description": "New feature or improvement" } ] } } } } ``` ``` -------------------------------- ### GraphQL API - Get PR Contributors and Closing Issues Source: https://context7.com/ultralytics/actions/llms.txt Fetches details about a pull request, including its author, closing issues, reviews, and commits. ```APIDOC ## POST /graphql ### Description Retrieves information about a specific pull request, including related issues, reviews, and commits. ### Method POST ### Endpoint /graphql ### Parameters #### Query Parameters None #### Request Body - **query** (String!) - The GraphQL query string to fetch pull request details. - **variables** (Object!) - Variables for the query, including 'owner', 'repo', and 'pr_number'. ### Request Example ```json { "query": "query($owner: String!, $repo: String!, $pr_number: Int!) {\n repository(owner: $owner, name: $repo) {\n pullRequest(number: $pr_number) {\n closingIssuesReferences(first: 50) { nodes { number } }\n author { login }\n reviews(first: 50) { nodes { author { login } } }\n commits(first: 100) { nodes { commit { author { user { login } } } } }\n }\n }\n}", "variables": { "owner": "ultralytics", "repo": "yolo", "pr_number": 123 } } ``` ### Response #### Success Response (200) - **data** (Object) - The result of the GraphQL query. - **repository** (Object) - Repository data. - **pullRequest** (Object) - Pull request details. - **closingIssuesReferences** (Object) - Issues closed by this PR. - **nodes** (Array) - An array of issue objects, each with a 'number'. - **author** (Object) - The author of the pull request. - **login** (String) - The login name of the author. - **reviews** (Object) - Reviews for the pull request. - **nodes** (Array) - An array of review objects, each with an author's login. - **commits** (Object) - Commits in the pull request. - **nodes** (Array) - An array of commit objects, each with commit author information. #### Response Example ```json { "data": { "repository": { "pullRequest": { "closingIssuesReferences": { "nodes": [ { "number": 456 }, { "number": 457 } ] }, "author": { "login": "octocat" }, "reviews": { "nodes": [ { "author": { "login": "reviewer1" } }, { "author": { "login": "reviewer2" } } ] }, "commits": { "nodes": [ { "commit": { "author": { "user": { "login": "commitAuthor1" } } } }, { "commit": { "author": { "user": { "login": "commitAuthor2" } } } } ] } } } } } ``` ``` -------------------------------- ### GitHub Actions Workflow Configuration Source: https://context7.com/ultralytics/actions/llms.txt Example GitHub Actions workflow file (.github/workflows/ultralytics-actions.yml) to orchestrate various automation features. It defines triggers for issues and pull requests, sets necessary permissions, and configures jobs to run the Ultralytics Actions. It accepts parameters for enabling features like Python formatting, AI summaries, code reviews, and spell checking, along with API keys for OpenAI or Anthropic. ```yaml # .github/workflows/ultralytics-actions.yml name: Ultralytics Actions on: issues: types: [opened] pull_request: branches: [main] types: [opened, closed, synchronize, review_requested] permissions: contents: write pull-requests: write issues: write jobs: actions: runs-on: ubuntu-latest steps: - name: Run Ultralytics Actions uses: ultralytics/actions@main with: token: ${{ secrets.GITHUB_TOKEN }} labels: true python: true python_docstrings: true biome: true prettier: true spelling: true links: true summary: true review: true # AI API keys - provide OpenAI OR Anthropic (auto-detected) openai_api_key: ${{ secrets.OPENAI_API_KEY }} # anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} model: "gpt-5.2-2025-12-11" # Optional: override default review_model: "gpt-5-codex" # Optional: override PR review model ``` -------------------------------- ### Retry Failed Commands with Exponential Backoff Source: https://github.com/ultralytics/actions/blob/main/README.md This standalone action, 'retry', allows for retrying commands that may fail during CI/CD pipelines. It supports specifying the command to run, the maximum number of retry attempts, and a timeout in minutes for each attempt. This is useful for transient failures during tasks like package installations. ```yaml - uses: ultralytics/actions/retry@main with: command: npm install max_attempts: 3 timeout_minutes: 5 ``` -------------------------------- ### Format Markdown Code Blocks (Bash) Source: https://context7.com/ultralytics/actions/llms.txt Updates and formats code blocks within Markdown files. This command ensures consistency and correctness of code examples in documentation. ```bash # Format markdown code blocks ultralytics-actions-update-markdown-code-blocks ``` -------------------------------- ### Get Repository Labels with IDs (Python GraphQL) Source: https://context7.com/ultralytics/actions/llms.txt Fetches labels from a specified GitHub repository along with their IDs and descriptions. This function uses the GitHub GraphQL API and requires the repository owner and name as input. ```python query = """ query($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { labels(first: 100) { nodes { id name description } } } } """ result = action.graphql_request(query, variables={"owner": "ultralytics", "name": "yolo"}) labels = result["data"]["repository"]["labels"]["nodes"] ``` -------------------------------- ### Scan PRs GitHub Action Usage Example Source: https://github.com/ultralytics/actions/blob/main/scan-prs/README.md This YAML snippet demonstrates how to integrate the 'ultralytics/actions/scan-prs' action into a GitHub Actions workflow. It specifies the trigger (workflow_dispatch and schedule), required permissions, and job configuration, including the action's inputs like the GitHub token, organization name, and repository visibility. ```yaml name: Scan PRs on: workflow_dispatch: schedule: - cron: "0 3 * * *" # daily at 03:00 UTC permissions: contents: write pull-requests: write jobs: scan-prs: runs-on: ubuntu-latest steps: - uses: ultralytics/actions/scan-prs@main with: token: ${{ secrets.GITHUB_TOKEN }} org: ultralytics # Optional: defaults to ultralytics visibility: private,internal # Optional: public, private, internal, all, or comma-separated ``` -------------------------------- ### Python Action Class for GitHub API Interaction Source: https://context7.com/ultralytics/actions/llms.txt Demonstrates the usage of the `Action` class from `actions.utils` in Python for interacting with the GitHub API. This class provides methods for fetching PR diffs, updating PR descriptions, applying labels, adding comments, checking user authorization, and querying GraphQL for label IDs. It includes example initializations with token and event data, and illustrates common API operations. ```python from actions.utils import Action # Initialize with GitHub token and event data action = Action( token="ghp_xxxxxxxxxxxx", event_name="pull_request", event_data={"pull_request": {"number": 123}, "repository": {"full_name": "owner/repo"}}, ) # Get PR diff with automatic caching diff = action.get_pr_diff() print(f"Diff length: {len(diff)} characters") # Update PR description with AI summary summary = "## 🛠️ PR Summary\n\n### 🌟 Summary\nAdded new feature" action.update_pr_description(123, summary) # Apply labels to issue/PR action.apply_labels( number=123, node_id="PR_kwDOAbc123", labels=["bug", "enhancement"], issue_type="pull request", ) # Add comment action.add_comment( number=123, node_id="PR_kwDOAbc123", comment="Thanks for your contribution!", issue_type="pull request" ) # Check authorization username = action.get_username() is_member = action.is_org_member("contributor-username") should_skip = action.should_skip_pr_author() # GraphQL query for label IDs label_ids = action.get_label_ids(["bug", "enhancement"]) ``` -------------------------------- ### Get PR Contributors and Closing Issues (Python GraphQL) Source: https://context7.com/ultralytics/actions/llms.txt Retrieves information about a pull request, including its author, associated closing issues, reviews, and commits. This function utilizes the GitHub GraphQL API and requires repository owner, repository name, and pull request number. ```python contributors_query = """ query($owner: String!, $repo: String!, $pr_number: Int!) { repository(owner: $owner, name: $repo) { pullRequest(number: $pr_number) { closingIssuesReferences(first: 50) { nodes { number } } author { login } reviews(first: 50) { nodes { author { login } } } commits(first: 100) { nodes { commit { author { user { login } } } } } } } } """ result = action.graphql_request( contributors_query, variables={"owner": "ultralytics", "repo": "yolo", "pr_number": 123} ) ``` -------------------------------- ### CLI - ultralytics-actions-summarize-release Source: https://context7.com/ultralytics/actions/llms.txt Generates release notes based on tags. ```APIDOC ## Command: ultralytics-actions-summarize-release ### Description Generates release notes by comparing changes between two Git tags. Requires authentication tokens. ### Usage ```bash GITHUB_TOKEN=ghp_xxx CURRENT_TAG=v1.0.0 PREVIOUS_TAG=v0.9.0 ultralytics-actions-summarize-release ``` ### Environment Variables - **GITHUB_TOKEN** (String!) - Required - A GitHub Personal Access Token with appropriate permissions. - **CURRENT_TAG** (String!) - Required - The current tag for which to generate release notes. - **PREVIOUS_TAG** (String!) - Required - The previous tag to compare against for generating release notes. ``` -------------------------------- ### Integrating Disk Cleanup with Other Actions (YAML) Source: https://github.com/ultralytics/actions/blob/main/cleanup-disk/README.md This YAML snippet illustrates how to incorporate the cleanup-disk action alongside other common GitHub Actions, such as `actions/checkout` and `docker/setup-buildx-action`. Placing the cleanup action before resource-intensive tasks like Docker image builds helps prevent potential disk space issues. ```yaml steps: - uses: actions/checkout@v4 - uses: ultralytics/actions/cleanup-disk@main - uses: docker/setup-buildx-action@v3 - name: Build Docker image run: docker build -t myapp . ``` -------------------------------- ### Handle First Interaction on GitHub (Bash) Source: https://context7.com/ultralytics/actions/llms.txt Manages the first interaction with a new contributor or user on GitHub, potentially by applying labels and adding a comment. Requires GITHUB_TOKEN and OPENAI_API_KEY. ```bash # Handle first interaction (labels + comment) GITHUB_TOKEN=ghp_xxx OPENAI_API_KEY=sk-xxx ultralytics-actions-first-interaction ``` -------------------------------- ### Disk Space Before and After Cleanup (Shell Output) Source: https://github.com/ultralytics/actions/blob/main/cleanup-disk/README.md This output demonstrates the effect of the disk cleanup action. It displays the free disk space report before and after the action has run, highlighting the reclaimed space. This is useful for verifying the action's effectiveness in environments where disk space is a constraint. ```text Free space before deletion: Filesystem Size Used Avail Use% Mounted on /dev/root 84G 60G 24G 72% / Free space after deletion: Filesystem Size Used Avail Use% Mounted on /dev/root 84G 41G 43G 49% / ``` -------------------------------- ### Show GitHub Actions Environment Info (Bash) Source: https://context7.com/ultralytics/actions/llms.txt Displays information about the current GitHub Actions environment, including the event name, repository, and pull request number. This command helps in debugging and understanding the context of the action. ```bash # Show GitHub Actions environment info ultralytics-actions-info # Output: # Ultralytics Actions 0.2.11 Information # github.event_name pull_request # github.repository ultralytics/yolo # github.event.pull_request.number 123 ``` -------------------------------- ### Release Notes Generation (Python) Source: https://context7.com/ultralytics/actions/llms.txt Automates the creation of comprehensive release notes by extracting information from commits and merged PRs between version tags. It uses functions like `get_release_diff`, `get_prs_between_tags`, `get_new_contributors`, `generate_release_summary`, and `create_github_release`. Environment variables for `CURRENT_TAG` and `PREVIOUS_TAG` are required. ```python from actions.summarize_release import ( get_release_diff, get_prs_between_tags, get_new_contributors, generate_release_summary, create_github_release, ) import os # Set environment variables os.environ["CURRENT_TAG"] = "v1.2.0" os.environ["PREVIOUS_TAG"] = "v1.1.0" action = Action() # Get diff between tags diff = get_release_diff(action, "v1.1.0", "v1.2.0") # Get all merged PRs prs = get_prs_between_tags(action, "v1.1.0", "v1.2.0") ``` -------------------------------- ### CLI - ultralytics-actions-info Source: https://context7.com/ultralytics/actions/llms.txt Displays information about the GitHub Actions environment. ```APIDOC ## Command: ultralytics-actions-info ### Description Prints details about the current GitHub Actions environment, including event name, repository, and relevant event data. ### Usage ```bash ultralytics-actions-info ``` ### Output Example ``` Ultralytics Actions 0.2.11 Information github.event_name pull_request github.repository ultralytics/yolo github.event.pull_request.number 123 ``` ``` -------------------------------- ### Generate Release Notes (Bash) Source: https://context7.com/ultralytics/actions/llms.txt Generates release notes based on commits between two specified tags. Requires GITHUB_TOKEN, CURRENT_TAG, and PREVIOUS_TAG environment variables. ```bash # Generate release notes GITHUB_TOKEN=ghp_xxx CURRENT_TAG=v1.0.0 PREVIOUS_TAG=v0.9.0 ultralytics-actions-summarize-release ``` -------------------------------- ### Basic Disk Cleanup Action Usage (YAML) Source: https://github.com/ultralytics/actions/blob/main/cleanup-disk/README.md This snippet demonstrates the basic integration of the cleanup-disk action into a GitHub Actions workflow. It should be added as an early step in jobs that anticipate high disk usage. No specific inputs are required for basic functionality. ```yaml steps: - uses: ultralytics/actions/cleanup-disk@main ``` -------------------------------- ### CLI - ultralytics-actions-summarize-pr Source: https://context7.com/ultralytics/actions/llms.txt Generates a summary for a Pull Request using GitHub and OpenAI APIs. ```APIDOC ## Command: ultralytics-actions-summarize-pr ### Description Generates a concise summary of a Pull Request by leveraging GitHub API for PR details and OpenAI API for summarization. Requires authentication tokens. ### Usage ```bash GITHUB_TOKEN=ghp_xxx OPENAI_API_KEY=sk-xxx ultralytics-actions-summarize-pr ``` ### Environment Variables - **GITHUB_TOKEN** (String!) - Required - A GitHub Personal Access Token with appropriate permissions. - **OPENAI_API_KEY** (String!) - Required - An OpenAI API key for text summarization. ``` -------------------------------- ### Generate Pull Request Summary (Bash) Source: https://context7.com/ultralytics/actions/llms.txt Generates a summary of a pull request using OpenAI API. Requires GITHUB_TOKEN and OPENAI_API_KEY environment variables. This command helps in quickly understanding the changes introduced in a PR. ```bash # Generate PR summary GITHUB_TOKEN=ghp_xxx OPENAI_API_KEY=sk-xxx ultralytics-actions-summarize-pr ``` -------------------------------- ### Code Review with GPT-5-Codex and Anthropic Claude Source: https://context7.com/ultralytics/actions/llms.txt Demonstrates how to use different AI models for code review. It shows setting up system and user messages and calling a completion function with various model options like 'gpt-5-codex', 'claude-sonnet-4-5-20250929', 'claude-haiku-4-5-20251001', and 'claude-opus-4-5-20251101'. The output may include token usage information. ```python messages = [ {"role": "system", "content": "You are a code reviewer.",}, {"role": "user", "content": "Review this code: def add(a,b): return a+b",}, ] review = get_completion(messages, reasoning_effort="low", model="gpt-5-codex") # Output includes token usage: gpt-5-codex (1234→567 = 1801 tokens, $0.00801, 2.3s) # Anthropic Claude models review = get_completion(messages, model="claude-sonnet-4-5-20250929") review = get_completion(messages, model="claude-haiku-4-5-20251001") # Faster, cheaper review = get_completion(messages, model="claude-opus-4-5-20251101") # Most capable ``` -------------------------------- ### PR Review Engine (Python) Source: https://context7.com/ultralytics/actions/llms.txt Implements an advanced AI-powered code review for pull requests. The `review_pr.generate_pr_review` function takes repository information, diff text, and PR title/description to produce a review including an overall summary and a list of comments. Each comment contains details like file, line, side, severity, message, and a suggested code snippet. The reviews can then be posted using helper functions like `dismiss_previous_reviews` and `post_review_summary`. ```python from actions import review_pr # Generate comprehensive PR review review_data = review_pr.generate_pr_review( repository="ultralytics/yolo", diff_text="""diff --git a/train.py b/train.py R 123 +def train_model(data, epochs=100): R 124 + for i in range(epochs): R 125 + print(f"Epoch {i}") R 126 + model.train()""", pr_title="Add training loop", pr_description="Implements basic training functionality", ) # Review data structure print(review_data["summary"]) # "Overall assessment of changes" print(f"Found {len(review_data['comments'])} issues") # Example comment structure comment = review_data["comments"][0] print(comment) # { # "file": "train.py", # "line": 126, # "side": "RIGHT", # "severity": "MEDIUM", # "message": "Consider adding error handling for model.train() failures", # "suggestion": " try:\n model.train()\n except Exception as e:\n print(f'Training failed: {e}')" # } # Post review as GitHub PR review action = Action() review_number = review_pr.dismiss_previous_reviews(action) review_pr.post_review_summary(action, review_data, review_number) ``` -------------------------------- ### Unified PR Open Response Generation (Python) Source: https://context7.com/ultralytics/actions/llms.txt Generates a summary, labels, and a first comment for a pull request in a single API call. It utilizes `get_pr_open_response` from `openai_utils` and requires repository details, diff text, PR title, username, and available labels. The output is a dictionary containing 'summary', 'labels', and 'first_comment', which can then be applied to the PR. ```python from actions.utils.openai_utils import get_pr_open_response # Available labels from repository available_labels = { "bug": "Something isn't working", "enhancement": "New feature or request", "documentation": "Improvements or additions to documentation", "question": "Further information is requested", } # Generate unified response for new PR response = get_pr_open_response( repository="ultralytics/ultralytics", diff_text="diff --git a/utils.py b/utils.py\n+def new_function():\n+ pass", title="Add new utility function", username="contributor", available_labels=available_labels, ) # Response contains all three outputs print(response["summary"]) # "### 🌟 Summary\n..." print(response["labels"]) # ["enhancement"] print(response["first_comment"]) # "👋 Hello @contributor..." # Apply to PR action = Action() action.update_pr_description(123, f"## 🛠️ PR Summary\n\n{response['summary']}") action.apply_labels(123, "PR_id", response["labels"], "pull request") action.add_comment(123, "PR_id", response["first_comment"], "pull request") ``` -------------------------------- ### Python AI Completion with OpenAI/Anthropic Support Source: https://context7.com/ultralytics/actions/llms.txt Shows how to use the `get_completion` function from `actions.utils.openai_utils` to interact with AI models, supporting both OpenAI and Anthropic providers. It demonstrates basic text completion and how to request responses in JSON format. The function automatically detects the provider based on the provided API key and includes features like retry logic and token tracking. ```python from actions.utils.openai_utils import get_completion # Basic completion (auto-detects provider from API key) messages = [ {"role": "system", "content": "You are a helpful AI assistant."}, {"role": "user", "content": "Explain how to export a YOLO11 model to CoreML."}, ] response = get_completion(messages, temperature=1.0) print(response) # JSON response format messages = [ {"role": "system", "content": "You are an AI that returns structured data."}, {"role": "user", "content": "List 3 Python best practices as JSON array."}, ] json_response = get_completion(messages, temperature=1.0, response_format={"type": "json_object"}) print(json_response) # Returns dict ``` -------------------------------- ### CLI - ultralytics-actions-format-python-docstrings Source: https://context7.com/ultralytics/actions/llms.txt Formats Python docstrings within a specified project directory. ```APIDOC ## Command: ultralytics-actions-format-python-docstrings ### Description Formats the docstrings in Python files within a given project path according to a standard convention. ### Usage ```bash ultralytics-actions-format-python-docstrings /path/to/project ``` ### Parameters #### Path Parameters - **path_to_project** (String) - Required - The absolute or relative path to the project directory containing Python files. ``` -------------------------------- ### CLI - ultralytics-actions-first-interaction Source: https://context7.com/ultralytics/actions/llms.txt Handles the first interaction on a Pull Request, including labeling and commenting. ```APIDOC ## Command: ultralytics-actions-first-interaction ### Description Automates the initial response to a new Pull Request by applying relevant labels and posting an initial comment. Requires authentication tokens. ### Usage ```bash GITHUB_TOKEN=ghp_xxx OPENAI_API_KEY=sk-xxx ultralytics-actions-first-interaction ``` ### Environment Variables - **GITHUB_TOKEN** (String!) - Required - A GitHub Personal Access Token with appropriate permissions. - **OPENAI_API_KEY** (String!) - Required - An OpenAI API key, potentially used for generating comment content. ``` -------------------------------- ### Generate Release Summary and GitHub Release Source: https://context7.com/ultralytics/actions/llms.txt Generates a release summary from pull request data and creates a GitHub release. It identifies new contributors and formats a detailed release body including key changes and impact. ```python new_contributors = get_new_contributors(action, prs) print(f"New contributors: {new_contributors}") summary = generate_release_summary(action, diff, prs, "v1.2.0", "v1.1.0") create_github_release( action, tag_name="v1.2.0", name="v1.2.0 - Bug fixes and improvements", body=summary ) ``` -------------------------------- ### Run Ultralytics Actions for Code Formatting and PR Management Source: https://github.com/ultralytics/actions/blob/main/README.md This snippet configures the main Ultralytics Actions workflow to automatically format code (Python, JS/TS, YAML, JSON, Markdown, CSS, Swift, Dart), check spelling, validate links, and generate AI-powered PR summaries. It utilizes GitHub Secrets for API keys and tokens, and allows customization of features like docstring formatting and AI model selection. ```yaml name: Ultralytics Actions on: issues: types: [opened] pull_request: branches: [main] types: [opened, closed, synchronize, review_requested] permissions: contents: write # Modify code in PRs pull-requests: write # Add comments and labels to PRs issues: write # Add comments and labels to issues jobs: actions: runs-on: ubuntu-latest steps: - name: Run Ultralytics Actions uses: ultralytics/actions@main with: token: ${{ secrets.GITHUB_TOKEN }} # Auto-generated token labels: true # Auto-label issues/PRs using AI python: true # Format Python with Ruff python_docstrings: false # Format Python docstrings (default: false) biome: true # Format JS/TS with Biome (auto-detected via biome.json) prettier: true # Format YAML, JSON, Markdown, CSS swift: false # Format Swift (requires macos-latest) dart: false # Format Dart/Flutter spelling: true # Check spelling with codespell links: true # Check broken links with Lychee summary: true # Generate AI-powered PR summaries # AI API keys - provide OpenAI OR Anthropic (model auto-detected from key) openai_api_key: ${{ secrets.OPENAI_API_KEY }} # anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} # model: claude-haiku-4-5-20251001 # Optional: override default model # review_model: claude-opus-4-5-20251101 # Optional: override PR review model brave_api_key: ${{ secrets.BRAVE_API_KEY }} # Used for broken link resolution ``` -------------------------------- ### Cleanup Disk Space on GitHub Runners Source: https://github.com/ultralytics/actions/blob/main/README.md The 'cleanup-disk' action is a reusable composite action designed to free up disk space on GitHub runners. By default, it removes unnecessary packages and files, helping to prevent build failures due to insufficient disk space. It can be included in workflows to maintain a clean build environment. ```yaml - uses: ultralytics/actions/cleanup-disk@main ``` -------------------------------- ### Perform Pull Request Review (Bash) Source: https://context7.com/ultralytics/actions/llms.txt Automates the process of performing a review on a pull request. This command leverages AI for suggestions and requires GITHUB_TOKEN and OPENAI_API_KEY. ```bash # Perform PR review GITHUB_TOKEN=ghp_xxx OPENAI_API_KEY=sk-xxx ultralytics-actions-review-pr ``` -------------------------------- ### GraphQL Queries (Python) Source: https://context7.com/ultralytics/actions/llms.txt Executes GraphQL operations for advanced GitHub API features, such as managing discussions and labels, using the Action class. ```python from actions.utils import Action action = Action() ``` -------------------------------- ### Format Python Docstrings (Bash) Source: https://context7.com/ultralytics/actions/llms.txt Formats Python docstrings within a specified project directory. This command helps in maintaining code style and readability. ```bash # Format Python docstrings ultralytics-actions-format-python-docstrings /path/to/project ``` -------------------------------- ### CLI - ultralytics-actions-headers Source: https://context7.com/ultralytics/actions/llms.txt Updates file headers across the repository. ```APIDOC ## Command: ultralytics-actions-headers ### Description Automates the process of updating file headers within the repository. This command typically scans files and applies a consistent header format. ### Usage ```bash ultralytics-actions-headers ``` ``` -------------------------------- ### Update File Headers Across Repository (Bash) Source: https://context7.com/ultralytics/actions/llms.txt Automates the process of updating file headers throughout a repository. This command is useful for maintaining consistency in project files. ```bash # Update file headers across repository ultralytics-actions-headers ``` -------------------------------- ### PR Summary Generation (Python) Source: https://context7.com/ultralytics/actions/llms.txt Automates the creation of concise PR summaries for merged or closed PRs. It includes standard sections like 'Summary', 'Key Changes', and 'Purpose & Impact'. The `generate_pr_summary` function takes repository and diff information, while `generate_merge_message` can be used for merged PRs to thank contributors. Additionally, `label_fixed_issues` can automatically find, label, and comment on issues closed by the PR. ```python from actions.summarize_pr import generate_pr_summary, generate_merge_message, label_fixed_issues # Generate PR summary action = Action() diff = action.get_pr_diff() summary = generate_pr_summary(repository="ultralytics/yolo", diff_text=diff) print(summary) # Output: # ## 🛠️ PR Summary # # ### 🌟 Summary # Added new training features with improved error handling # # ### 📊 Key Changes # - Implemented training loop with epoch tracking # - Added model validation after each epoch # # ### 🎯 Purpose & Impact # - Users can now train models with better feedback # - Improved reliability through error handling # Update PR description action.update_pr_description(123, summary) # For merged PRs, thank contributors pr_credit, pr_data = action.get_pr_contributors() merge_msg = generate_merge_message(summary, pr_credit, f"https://github.com/owner/repo/pull/123") action.add_comment(123, None, merge_msg, "pull request") # Label and notify fixed issues label_fixed_issues(action, summary) # Automatically: # - Finds issues closed by PR (from PR description) # - Adds "fixed" label # - Posts AI-generated comment explaining the fix ``` -------------------------------- ### Basic Retry Action Usage (YAML) Source: https://github.com/ultralytics/actions/blob/main/retry/README.md Demonstrates the basic usage of the retry action to run a command. By default, it retries a failed step up to 3 times. ```yaml steps: - uses: ultralytics/actions/retry@main with: run: python train.py ``` -------------------------------- ### First Interaction Handler: Labeling and Responding to Issues Source: https://context7.com/ultralytics/actions/llms.txt Processes new issues or discussions by identifying relevant labels using AI and generating custom responses. It applies labels to issues and can add comments to GitHub issues. ```python from actions.first_interaction import ( get_relevant_labels, get_first_interaction_response, apply_and_check_labels, ) action = Action() # For issues/discussions - get relevant labels available_labels = { "bug": "Something isn't working", "enhancement": "New feature or request", "documentation": "Improvements to documentation", "question": "Further information is requested", } labels = get_relevant_labels( issue_type="issue", title="Training fails with CUDA error", body="I'm getting CUDA out of memory when training YOLO11", available_labels=available_labels, current_labels=[], ) print(labels) # ["bug"] # Apply labels with alert handling apply_and_check_labels( event=action, number=456, node_id="I_kwDOAbc456", issue_type="issue", username="reporter", labels=labels, label_descriptions=available_labels, ) # Generate custom first response response = get_first_interaction_response( event=action, issue_type="issue", title="Training fails with CUDA error", body="I'm getting CUDA out of memory", username="reporter", ) print(response) # Returns customized message requesting MRE, environment details, etc. # Add comment action.add_comment(456, "I_kwDOAbc456", response, "issue") ``` -------------------------------- ### Python Docstring Formatter Source: https://context7.com/ultralytics/actions/llms.txt Automates the formatting of Python docstrings to adhere to Google-style conventions. It handles section ordering, indentation, and validation, supporting both directory-wide and single-file operations. ```python from actions.format_python_docstrings import format_docstrings, format_file # Format all Python files in directory format_docstrings("/path/to/project", verbose=True) # Format single file changes = format_file("/path/to/file.py") if changes: print(f"Formatted {len(changes)} docstrings") # Command line usage # python -m actions.format_python_docstrings /path/to/project ``` -------------------------------- ### Advanced Retry Action Configuration (YAML) Source: https://github.com/ultralytics/actions/blob/main/retry/README.md Illustrates advanced configuration options for the retry action, including custom retry counts, timeout per attempt, delay between retries, and specifying the shell. ```yaml steps: - uses: ultralytics/actions/retry@main with: run: | python setup.py install pytest tests/ retries: 2 # Retry twice after initial attempt (3 total runs) timeout_minutes: 30 # Each attempt times out after 30 minutes retry_delay_seconds: 60 # Wait 60 seconds between retries shell: bash # Use python or bash shell ``` -------------------------------- ### Scan and Merge Organization Pull Requests Source: https://github.com/ultralytics/actions/blob/main/README.md This action, 'scan-prs', scans open pull requests across an organization and can automatically merge eligible Dependabot PRs. It requires a GitHub token for authentication and allows filtering by repository visibility (public, private, internal, all). This streamlines the management of dependencies and PRs. ```yaml - uses: ultralytics/actions/scan-prs@main with: token: ${{ secrets.GITHUB_TOKEN }} org: ultralytics # Optional: defaults to ultralytics visibility: private,internal # Optional: public, private, internal, all, or comma-separated ``` -------------------------------- ### GraphQL API - Update Discussion Source: https://context7.com/ultralytics/actions/llms.txt Updates an existing discussion with a new title and body content. ```APIDOC ## POST /graphql ### Description Updates the title and body of a specified GitHub discussion. ### Method POST ### Endpoint /graphql ### Parameters #### Query Parameters None #### Request Body - **mutation** (String!) - The GraphQL mutation string to update a discussion. - **variables** (Object!) - Variables for the mutation, including 'discussionId', 'title', and 'body'. ### Request Example ```json { "mutation": "mutation($discussionId: ID!, $title: String!, $body: String!) {\n updateDiscussion(input: {discussionId: $discussionId, title: $title, body: $body}) {\n discussion { id }\n }\n}", "variables": { "discussionId": "D_kwDOAbc123", "title": "Updated Title", "body": "New content" } } ``` ### Response #### Success Response (200) - **data** (Object) - The result of the GraphQL mutation. - **updateDiscussion** (Object) - The result of the update operation. - **discussion** (Object) - The updated discussion object. - **id** (ID) - The unique identifier of the updated discussion. #### Response Example ```json { "data": { "updateDiscussion": { "discussion": { "id": "D_kwDOAbc123" } } } } ``` ``` -------------------------------- ### Format Markdown Code Blocks (Python) Source: https://context7.com/ultralytics/actions/llms.txt Formats Python and Bash code blocks within markdown documentation. It extracts code blocks, formats them using tools like Ruff and Prettier, and updates the markdown file in-place, preserving original indentation. ```python from actions.update_markdown_code_blocks import ( extract_code_blocks, format_code_with_ruff, format_bash_with_prettier, update_markdown_code_blocks, ) # Extract code blocks from markdown markdown_content = """ Some text here. ```python def hello( ): print( \"world\" ) ``` More text. ```bash echo \"Hello\" ls -la ``` """ code_blocks = extract_code_blocks(markdown_content, "python") print(code_blocks) # [{"code": 'def hello( ):\n print( \"world\" )', "start": 16, "end": 70, "indent": 0}] # Format Python code formatted = format_code_with_ruff('def hello( ):\n print( \"world\" )') print(formatted) # 'def hello():\n print("world")' # Update all code blocks in markdown file # python -m actions.update_markdown_code_blocks # Processes: # - Python: ```python, ```py, ```{.py.annotate} # - Bash: ```bash, ```sh, ```shell # - Preserves original indentation # - Updates markdown in-place ``` -------------------------------- ### CLI - ultralytics-actions-review-pr Source: https://context7.com/ultralytics/actions/llms.txt Performs a code review on a Pull Request using AI. ```APIDOC ## Command: ultralytics-actions-review-pr ### Description Analyzes a Pull Request and generates review comments using AI. Requires authentication tokens for GitHub and potentially an AI service. ### Usage ```bash GITHUB_TOKEN=ghp_xxx OPENAI_API_KEY=sk-xxx ultralytics-actions-review-pr ``` ### Environment Variables - **GITHUB_TOKEN** (String!) - Required - A GitHub Personal Access Token with appropriate permissions. - **OPENAI_API_KEY** (String!) - Required - An OpenAI API key for generating review suggestions. ``` -------------------------------- ### Organization PR Scanner and Auto-Merge Source: https://context7.com/ultralytics/actions/llms.txt Scans all repositories within a GitHub organization for open pull requests and automatically merges eligible Dependabot PRs. It provides visibility into PRs across repositories and validates status checks. ```python from actions.scan_prs import run # Scan organization PRs (uses environment variables) import os os.environ["ORG"] = "ultralytics" os.environ["VISIBILITY"] = "public,private" # public, private, internal, all, or comma-separated os.environ["REPO_VISIBILITY"] = "public" # Current repo visibility (for security checks) run() ``` -------------------------------- ### File Header Updates Source: https://context7.com/ultralytics/actions/llms.txt Updates license and copyright headers in files across a project. It supports custom headers defined via environment variables while preserving existing special content within the files. ```python from actions.update_file_headers import update_headers # Environment variable controls custom header import os os.environ["HEADER"] = """MyCompany 2025 License https://example.com/license""" # Assuming update_headers is called elsewhere or implicitly triggered ``` -------------------------------- ### CLI - ultralytics-actions-update-markdown-code-blocks Source: https://context7.com/ultralytics/actions/llms.txt Updates markdown code blocks in the repository. ```APIDOC ## Command: ultralytics-actions-update-markdown-code-blocks ### Description Scans markdown files within the repository and updates any code blocks, ensuring consistency and correctness. ### Usage ```bash ultralytics-actions-update-markdown-code-blocks ``` ``` -------------------------------- ### Dispatch CI Workflow (Python) Source: https://context7.com/ultralytics/actions/llms.txt Triggers CI workflows from PR comments using the keyword `@ultralytics/run-ci`. This action monitors issue_comment events on PRs and dispatches a repository_dispatch event to trigger a CI workflow. ```python from actions.dispatch_actions import dispatch_workflow_on_comment # Monitors issue_comment events on PRs # When authorized user comments: "@ultralytics/run-ci" # Action will: # 1. Verify user is organization member # 2. Create temporary branch for fork PRs # 3. Trigger repository_dispatch event # 4. Poll for workflow completion # 5. Update comment with workflow status links # 6. Clean up temporary branches # Usage in PR comment: # "@ultralytics/run-ci please run tests" # Configuration in workflow: """ on: repository_dispatch: types: [run-ci] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 with: ref: ${{ github.event.client_payload.ref }} - name: Run tests run: pytest tests/ """ ``` -------------------------------- ### Parse PR Diff Files (Python) Source: https://context7.com/ultralytics/actions/llms.txt Parses unified diff format to track line numbers for both old (LEFT) and new (RIGHT) file versions. It facilitates precise inline code review comments by providing a mapping of line changes. ```python from actions.review_pr import parse_diff_files diff_text = """diff --git a/utils.py b/utils.py\nindex abc123..def456 100644\n--- a/utils.py\n+++ b/utils.py\n@@ -10,3 +10,5 @@ def old_function():\n return \"old\"\n\n-def removed_function():\n- pass\n+def new_function():\n+ return \"new\"\n+ """ files, augmented_diff = parse_diff_files(diff_text) # File mapping with line numbers print(files) # { # "utils.py": { # "RIGHT": {13: "def new_function():", 14: ' return \"new\"', 15: ""}, # "LEFT": {12: "def removed_function():", 13: " pass"} # } # } # Augmented diff with explicit line numbers print(augmented_diff) # diff --git a/utils.py b/utils.py # @@ -10,3 +10,5 @@ def old_function(): # return "old" # # L 12 -def removed_function(): # L 13 - pass # R 13 +def new_function(): # R 14 + return "new" # R 15 + ```