EN ▾
Start now

Use an AI API in GitHub Actions: Secrets and Scripts

A search for tokens and AI on GitHub often turns up shared keys and random repos. The safer route is your own key, kept in a repository secret and called from a short workflow.

Last updated

A key entering a vault slot beside a branching code tree feeding a speech bubble

Summary

  • Keep the key in a GitHub Actions secret named API_KEY and never commit it to the repository.
  • One workflow step can send a pull request diff to the API and post a summary as a comment.
  • A 40,000-character diff costs about $0.0017 per run at $0.15 and $0.50 per 1M tokens.
  • Fork pull requests do not receive secrets, so guard the step to avoid failed runs.

Skip the shared keys, use your own

If you came here by searching unlimited tokens ai github, you probably ran into repositories that promise free or unlimited API access. Treat those with care. A key shared in public is either revoked quickly or abused by others, and prompts sent through somebody else's key can be read by whoever owns it. Your own key costs a few cents to test and stays under your control.

This guide shows the standard setup: save the key as a GitHub Actions secret, read it from an environment variable, and call the API from a Python script that runs on every pull request. The API is OpenAI-compatible, so the official openai package works after you change the base URL and key. If you do not have a key yet, the API key page lets you claim a $0.50 trial after sign-up.

Store the key as a repository secret

  1. Open your repository and go to Settings, then Secrets and variables, then Actions.
  2. Choose New repository secret.
  3. Name it API_KEY and paste the key as the value.
  4. Save. GitHub will not show the value again.

For local runs, export the same variable in your shell and keep any .env file in .gitignore. If a key ever lands in a commit, do not try to scrub history first. Regenerate it on the API key page; the old key stops working at once and you can paste the new one into the secret. Accounts that have topped up can also hold up to 5 labelled keys, which is handy for giving CI its own key that you can revoke without touching anything else.

The script: summarise a diff

Save this as scripts/summarize.py. It reads a diff file, trims it to a size that fits the 100,000-token context window with room left for the answer, and prints a short review summary.

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.unlimitedtokensai.com/v1",
    api_key=os.environ["API_KEY"],
)

MAX_CHARS = 200000  # roughly 50,000 to 65,000 tokens of code

with open("diff.txt", encoding="utf-8", errors="replace") as f:
    diff = f.read()

note = ""
if len(diff) > MAX_CHARS:
    diff = diff[:MAX_CHARS]
    note = "\n\n(The diff was truncated before review.)"

resp = client.chat.completions.create(
    model="uncensored",
    temperature=0.2,
    max_tokens=600,
    messages=[
        {"role": "system", "content": "You review pull requests. Reply with a 3-sentence summary, then a bullet list of risks."},
        {"role": "user", "content": diff},
    ],
)

with open("summary.md", "w", encoding="utf-8") as out:
    out.write(resp.choices[0].message.content + note)

Code averages somewhere around three to four characters per token, which is why the cap is set in characters. A cheap guard like this beats counting tokens exactly.

The workflow file

Put this in .github/workflows/pr-summary.yml. It checks out the full history, writes the diff against the base branch, runs the script, and posts the result as a comment, updating the previous one on later pushes.

name: PR summary
on:
  pull_request:
    types: [opened, synchronize]

permissions:
  contents: read
  pull-requests: write

jobs:
  summarize:
    if: github.event.pull_request.head.repo.full_name == github.repository
    runs-on: ubuntu-latest
    env:
      API_KEY: ${{ secrets.API_KEY }}
      BASE_URL: https://api.unlimitedtokensai.com/v1
      MODEL: uncensored
      GH_TOKEN: ${{ github.token }}
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - run: pip install openai
      - run: git diff --output=diff.txt origin/${{ github.base_ref }}...HEAD
      - run: python scripts/summarize.py
      - run: gh pr comment ${{ github.event.pull_request.number }} --body-file summary.md --edit-last || gh pr comment ${{ github.event.pull_request.number }} --body-file summary.md

The if condition on the job matters. For pull requests opened from forks, GitHub does not pass repository secrets to the workflow, so the key would be empty and the step would fail. Skipping fork runs is the simple answer. Avoid switching to pull_request_target just to get secrets into fork runs unless you understand the risk of running untrusted code with access to them.

What each run costs

At $0.15 per 1M input tokens and $0.50 per 1M output tokens, a pull request review is cheap. Taking four characters per token as a working estimate:

Diff sizeInput tokensOutput tokensCost per run
40,000 characters10,000400$0.0015 + $0.0002 = $0.0017
150,000 characters37,500400$0.005625 + $0.0002 = $0.005825

A repository with 100 pull requests a month, all at the larger size, spends about $0.58. The $0.50 trial alone would cover roughly 294 runs of the smaller size. The pricing page has the top-up options once you outgrow the trial.

Other jobs that fit in Actions

The same pattern works for scheduled and event-driven tasks:

  • Release notes. Feed the commit messages since the last tag and ask for a changelog draft.
  • Issue triage. Send a new issue body and ask for a label and a priority as JSON, using JSON mode.
  • Docs checks. Compare a changed function to its documentation and flag mismatches.

Here is the triage call with curl, using JSON mode so the reply parses cleanly:

curl https://api.unlimitedtokensai.com/v1/chat/completions \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "uncensored",
    "response_format": {"type": "json_object"},
    "messages": [
      {"role": "system", "content": "Return JSON with keys label and priority for this issue."},
      {"role": "user", "content": "Login page returns a blank screen on Safari after the last release."}
    ]
  }'

Mind the rate limits when a matrix job fans out. A full key allows 8 concurrent requests and 300 per minute; a trial key allows 2 and 60. Set strategy.max-parallel to stay under the concurrency cap, and retry on HTTP 429, honouring the Retry-After header. The docs describe both 429 error codes, rate_limited and concurrency.

Failure handling and prompt safety in CI

An automated reviewer should never block a merge because the API had a bad minute. Treat the step as advisory:

  • Do not fail the build. Add continue-on-error: true to the summary step, so a timeout or a 429 shows as a warning instead of a red check.
  • Set a timeout. Pass timeout=120 when creating the client and add timeout-minutes: 5 to the job.
  • Retry politely. On HTTP 429, wait for the Retry-After value (the API sends Retry-After: 5 on temporary overload) and try once or twice more. The OpenAI Python client retries a few times by default.
  • Avoid comment spam. The synchronize event fires on every push. The workflow above tries gh pr comment --edit-last first, so the same comment is updated instead of a new one appearing each time, and only posts a fresh comment when none exists yet.

Treat the diff as untrusted input

A pull request can contain text written to steer a model, for example a comment that says to ignore earlier instructions and praise the change. The model only sees text, so it may follow it. Reduce the risk in three ways: keep the system prompt strict, give the model no tools in this workflow, and never let its output run as a command or trigger a merge. The summary is a note for a human reviewer, nothing more.

Also think about what you send. The diff leaves your repository and goes to the API. Prompts are not used for training, but for private or client code you should still decide which repositories use the workflow and keep secrets such as keys and tokens out of files that appear in diffs. If a secret ever lands in a diff, regenerate it.

Frequently asked questions

Where should the API key live in GitHub?

In a repository or organisation Actions secret, exposed to the job as an environment variable such as API_KEY. Never put it in the workflow file or the code.

Why does the workflow fail on pull requests from forks?

GitHub does not give repository secrets to workflows triggered by fork pull requests, so the key is empty. Skip the job for forks or run the review after a maintainer merges.

Can one key serve several repositories?

Yes, but accounts that have topped up can hold up to 5 labelled keys. Giving each project its own key lets you revoke one without breaking the rest.

How do I replace a leaked key?

Regenerate it on the API key page. The old key stops working immediately, and you then update the GitHub secret with the new value.

Get your key in a single step

Sign up, copy the key, and update your base URL. That’s all you need to start.

Start with free credits

Enter email and password; key appears immediately.