Automation#
gptme can be used to create powerful automated workflows. This page covers non-interactive usage patterns, CI/CD integration, and scheduling strategies.
Non-Interactive Mode#
The simplest way to automate gptme is with the -n/--non-interactive flag,
which runs a prompt non-interactively and exits:
gptme -n "summarize this" README.md
gptme -n "what bugs can you spot?" src/main.py
For longer tasks that involve multiple files or steps, chain prompts with -
separators (each - starts a new turn that triggers another assistant response):
gptme -n "read the failing test" - "fix the implementation" - "run the tests"
Note
The -n / --non-interactive flag skips all confirmation prompts and
exits when done. For interactive sessions that start with a pre-filled prompt,
omit -n.
Capturing Output#
gptme’s non-interactive mode writes assistant responses to stdout:
# Save the output to a file
gptme -n "summarize this codebase in 3 bullet points" README.md > summary.txt
# Use in a pipeline (mapfile avoids word-splitting on paths with spaces)
mapfile -t pyfiles < <(find . -name "*.py")
gptme -n "extract all TODO comments" "${pyfiles[@]}" | tee todos.txt
# Exit code reflects success (0) or failure (non-zero)
if gptme -n "run the tests and report pass/fail"; then
echo "Tests passed"
fi
# --output-format json gives structured output (one JSON object per message)
gptme -n "check the logs" app.log --output-format json
Exit Codes#
0: Task completed successfully1: Task failed (error during execution)2: Invalid arguments
CI/CD Integration#
GitHub Actions#
Run gptme as a step in your GitHub Actions workflow:
name: AI Code Review
on:
pull_request:
types: [opened, synchronize]
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install gptme
run: pipx install gptme
- name: Review PR diff
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
diff=$(gh pr diff ${{ github.event.pull_request.number }})
review=$(echo "$diff" | gptme -n "Review this PR diff for bugs, code quality issues, and security concerns. Be concise.")
body="## AI Code Review"$'\n'"$review"$'\n'"*Generated by gptme*"
gh pr comment ${{ github.event.pull_request.number }} --body "$body"
Note
Store your API key (e.g. ANTHROPIC_API_KEY) as a GitHub secret.
Never hard-code keys in workflow files.
Pre-commit Hook#
Use gptme as a pre-commit hook to catch issues before they land:
# .git/hooks/pre-commit
#!/bin/bash
set -e
# Only run on staged Python files
mapfile -t staged < <(git diff --cached --name-only --diff-filter=ACM | grep '\.py$')
[ ${#staged[@]} -eq 0 ] && exit 0
echo "Running AI review on staged files..."
issues=$(gptme -n "List any bugs or serious issues in these files. Output nothing if clean." "${staged[@]}")
if [ -n "$issues" ]; then
echo "⚠️ Potential issues found:"
echo "$issues"
echo ""
echo "Review and fix before committing, or use git commit --no-verify to skip."
exit 1
fi
Make this executable with chmod +x .git/hooks/pre-commit.
Example: Implement Feature from Issue#
Given a GitHub issue URL, this script checks out a branch, implements the feature, runs tests, and creates a pull request:
#!/bin/bash
# Usage: ./implement-issue.sh <issue-url>
set -e
issue_url=$1
issue_number=$(echo "$issue_url" | grep -oE '[0-9]+$')
gptme -n "Read this GitHub issue: $issue_url" \
- "Create a new branch called fix/issue-$issue_number" \
- "Look up the relevant source files for this issue" \
- "Implement the fix described in the issue" \
- "Run the tests to make sure nothing is broken" \
- "Create a pull request that closes issue #$issue_number"
Example: Automated Code Review
This example demonstrates a simple and composable approach to automated code review using gptme and shell scripting.
Create a script called review_pr.sh:
#!/bin/bash # Usage: ./review_pr.sh <repo> <pr_number> repo=$1 pr_number=$2 # Fetch PR diff diff=$(gh pr view $pr_number --repo $repo --json diffUrl -q .diffUrl | xargs curl -s) # Generate review using gptme review=$(gptme --non-interactive "Review this pull request diff and provide constructive feedback: 1. Identify potential bugs or issues. 2. Suggest improvements for code quality and readability. 3. Check for adherence to best practices. 4. Highlight any security concerns. Pull Request Diff: $diff Format your review as a markdown list with clear, concise points.") # Post review comment gh pr comment $pr_number --repo $repo --body "## Automated Code Review $review *This review was generated automatically by gptme.*"
Make the script executable:
chmod +x review_pr.sh
Set up a GitHub Actions workflow (.github/workflows/code_review.yml):
name: Automated Code Review on: pull_request: types: [opened, synchronize] jobs: review: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Install gptme and GitHub CLI run: | pip install gptme gh auth login --with-token <<< "${{ secrets.GITHUB_TOKEN }}" - name: Run code review env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | ./review_pr.sh ${{ github.repository }} ${{ github.event.pull_request.number }}
This setup provides automated code reviews for your pull requests using gptme. It demonstrates how powerful automation can be achieved with minimal code and high composability.
Key points:
Uses shell scripting for simplicity and ease of understanding
Leverages gptme’s non-interactive mode for automation
Utilizes GitHub CLI (gh) for seamless GitHub integration
Integrates with GitHub Actions for automated workflow
Benefits of this approach:
Easily customizable: Adjust the gptme prompt to focus on specific aspects of code review
Composable: The shell script can be extended or combined with other tools
Minimal dependencies: Relies on widely available tools (bash, curl, gh)
Quick setup: Can be implemented in any GitHub repository with minimal configuration
To customize this for your specific needs:
Modify the gptme prompt in review_pr.sh to focus on your project’s coding standards
Add additional checks or integrations to the shell script as needed
Adjust the GitHub Actions workflow to fit your CI/CD pipeline
This example serves as a starting point for integrating gptme into your development workflow, demonstrating its potential for automating code review tasks.
Example: Daily Activity Summary
Here’s an example of how to use gptme to generate a daily summary based on ActivityWatch data using a shell script:
#!/bin/bash
# Function to get yesterday's date in YYYY-MM-DD format
get_yesterday() {
date -d "yesterday" +%Y-%m-%d
}
# Function to get ActivityWatch report
get_aw_report() {
local date=$1
aw-client report $(hostname) --start $date --stop $(date -d "$date + 1 day" +%Y-%m-%d)
}
# Generate daily summary
generate_daily_summary() {
local yesterday=$(get_yesterday)
local aw_report=$(get_aw_report $yesterday)
# Create a temporary file
local summary_file=$(mktemp)
# Generate summary using gptme
gptme --non-interactive "Based on the following ActivityWatch report for $yesterday, provide a concise summary of yesterday's activities.
Include insights on productivity, time spent on different categories, and any notable patterns.
Suggest areas for improvement if applicable.
ActivityWatch Report:
$aw_report
Please format the summary in a clear, easy-to-read structure.
Save the summary to this file: $summary_file"
# Return the path to the summary file
echo "$summary_file"
}
# Run the summary generation and get the file path
summary_file=$(generate_daily_summary)
# Output the file path (you can use this in other scripts or log it)
echo "Daily summary saved to: $summary_file"
To automate this process to run every day at 8 AM, you could set up a cron job. Here’s an example cron entry:
0 8 * * * /path/to/daily_summary_script.sh
This automation will provide you with daily insights into your computer usage and productivity patterns from the previous day, leveraging the power of gptme to analyze and summarize the data collected by ActivityWatch.
Scheduled Automation#
cron#
Run gptme on a schedule using cron:
# Edit your crontab
crontab -e
# Run a daily summary every day at 8 AM
0 8 * * * cd /path/to/project && gptme -n "summarize yesterday's git activity and open issues" >> /var/log/gptme-daily.log 2>&1
# Weekly dependency audit every Monday at 9 AM
0 9 * * 1 cd /path/to/project && gptme -n "check for outdated dependencies and security advisories. Output a summary." >> /var/log/gptme-weekly.log 2>&1
systemd Timer#
For more robust scheduling, use systemd user timers:
# ~/.config/systemd/user/gptme-daily.service
[Unit]
Description=Daily gptme summary
[Service]
Type=oneshot
WorkingDirectory=%h/myproject
Environment=ANTHROPIC_API_KEY=<your-key>
ExecStart=gptme -n "summarize today's commits and open issues"
StandardOutput=append:%h/logs/gptme-daily.log
# ~/.config/systemd/user/gptme-daily.timer
[Unit]
Description=Run gptme daily summary
[Timer]
OnCalendar=daily
Persistent=true
[Install]
WantedBy=timers.target
Enable with:
systemctl --user enable --now gptme-daily.timer
Multi-Step Pipelines#
String together multiple gptme invocations for complex workflows:
#!/bin/bash
# Automated test-and-fix loop
set -euo pipefail
MAX_ATTEMPTS=3
attempt=0
while [ $attempt -lt $MAX_ATTEMPTS ]; do
attempt=$((attempt + 1))
echo "Attempt $attempt/$MAX_ATTEMPTS"
# Run tests, capture failures
test_output=$(python -m pytest --tb=short 2>&1 || true)
# Check if tests passed
if echo "$test_output" | grep -q "passed" && ! echo "$test_output" | grep -q "failed"; then
echo "✅ All tests pass"
exit 0
fi
# Let gptme diagnose and fix (|| true prevents set -e from aborting the loop on gptme failure)
echo "$test_output" | gptme -n "These tests are failing. Diagnose the root cause and fix it." || true
done
echo "❌ Could not fix tests after $MAX_ATTEMPTS attempts"
exit 1
Using gptme as a Library#
For tighter integration, use the gptme Python API directly:
import subprocess
import json
# Run gptme non-interactively and capture structured output
result = subprocess.run(
["gptme", "-n", "--output-format", "json",
"List the files in the current directory"],
capture_output=True,
text=True,
)
for line in result.stdout.splitlines():
if not line.strip():
continue
msg = json.loads(line)
if msg.get("role") == "assistant":
print(msg.get("content", ""))
See the API Reference reference for the full Python interface.
Best Practices#
Be specific in prompts: Vague prompts lead to vague actions.
Instead of “fix issues”, try “fix the type error in src/user.py line 42”.
Use ``-n`` / ``–non-interactive`` explicitly: When running in scripts,
pass -n to ensure non-interactive mode is always active.
Limit tool access: Use TOOL_ALLOWLIST to restrict which tools
gptme can use in automated contexts:
TOOL_ALLOWLIST=read,shell gptme -n "audit the codebase for security issues"
Log everything: Redirect stdout and stderr to log files so you can review what gptme did:
gptme -n "task" >> /var/log/gptme.log 2>&1
Test your prompts interactively first: Run the prompt interactively to verify it works before automating it.
Handle errors: Always check exit codes in scripts. gptme exits non-zero if it cannot complete the task.