GithubHelp home page GithubHelp logo

freeedcom / ai-codereviewer Goto Github PK

View Code? Open in Web Editor NEW
355.0 6.0 344.0 210 KB

AI Code Reviewer: Enhance your GitHub workflow with AI-powered code review! Get intelligent feedback and suggestions on pull requests using OpenAI's GPT-4 API, improving code quality and saving developers time.

License: MIT License

TypeScript 100.00%
ai code-review github-actions openai

ai-codereviewer's Introduction

AI Code Reviewer

AI Code Reviewer is a GitHub Action that leverages OpenAI's GPT-4 API to provide intelligent feedback and suggestions on your pull requests. This powerful tool helps improve code quality and saves developers time by automating the code review process.

Features

  • Reviews pull requests using OpenAI's GPT-4 API.
  • Provides intelligent comments and suggestions for improving your code.
  • Filters out files that match specified exclude patterns.
  • Easy to set up and integrate into your GitHub workflow.

Setup

  1. To use this GitHub Action, you need an OpenAI API key. If you don't have one, sign up for an API key at OpenAI.

  2. Add the OpenAI API key as a GitHub Secret in your repository with the name OPENAI_API_KEY. You can find more information about GitHub Secrets here.

  3. Create a .github/workflows/main.yml file in your repository and add the following content:

name: AI Code Reviewer

on:
  pull_request:
    types:
      - opened
      - synchronize
permissions: write-all
jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Repo
        uses: actions/checkout@v3

      - name: AI Code Reviewer
        uses: your-username/ai-code-reviewer@main
        with:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # The GITHUB_TOKEN is there by default so you just need to keep it like it is and not necessarily need to add it as secret as it will throw an error. [More Details](https://docs.github.com/en/actions/security-guides/automatic-token-authentication#about-the-github_token-secret)
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
          OPENAI_API_MODEL: "gpt-4" # Optional: defaults to "gpt-4"
          exclude: "**/*.json, **/*.md" # Optional: exclude patterns separated by commas
  1. Replace your-username with your GitHub username or organization name where the AI Code Reviewer repository is located.

  2. Customize the exclude input if you want to ignore certain file patterns from being reviewed.

  3. Commit the changes to your repository, and AI Code Reviewer will start working on your future pull requests.

How It Works

The AI Code Reviewer GitHub Action retrieves the pull request diff, filters out excluded files, and sends code chunks to the OpenAI API. It then generates review comments based on the AI's response and adds them to the pull request.

Contributing

Contributions are welcome! Please feel free to submit issues or pull requests to improve the AI Code Reviewer GitHub Action.

Let the maintainer generate the final package (yarn build & yarn package).

License

This project is licensed under the MIT License. See the LICENSE file for more information.

ai-codereviewer's People

Contributors

felixanhalt avatar lfsevergnini avatar mohd-e-mustafa avatar villesau avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

ai-codereviewer's Issues

error 404 by octokit

Hi

I am seeing the following error when running this action:
image

This error is being thrown by the @octokit/request library.
I myself have no experience with octokit and unfortunately am unable to examine your usage of the library :(

presumably unrelated but just in case:
I am using the recommended workflow from the README and I use a valid openai api key + github token.

JSON failure w/gpt-4-0125-preview.

When I configure AI Code Reviewer to run against gpt-4-0125-preview (a turbo model), I get the following failure (sometimes on repeat, sometimes only once) in the AI Code Reviewer step every single time it runs โ†’

Error: SyntaxError: Unexpected token ` in JSON at position 0
    at JSON.parse (<anonymous>)
    at /home/runner/work/_actions/freeedcom/ai-codereviewer/main/webpack:/open-ai-reviewer/lib/main.js:151:1
    at Generator.next (<anonymous>)
    at fulfilled (/home/runner/work/_actions/freeedcom/ai-codereviewer/main/webpack:/open-ai-reviewer/lib/main.js:28:1)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

This failure results in no comments being made on the pull request.

Making it run against gpt-4-1106-preview instead resolves the issue and the action works well.

Github action fails for lage PRs

Hi,

for PRs containing 50+ files github action fails due to rate-limiting error received from openAI API., can someone make some improvements in this direction?

Thanks!

Azure GPT support

It would be nice to support Azure GPT private instances which don't leak code inputs.
There is an action from Microsoft, but we have tested it and comments are useless really. It pushes only 1 comment and that's it.

Possibility of adding workflow_dispatch event support?

Hey! I'm wondering if it'd be possible to add workflow_dispatch as a supported event.

Here are my reasons:

  1. My use case is for a unity game that I'm working on. Many of the changes I put into pull requests are just for things like adding image or sound assets, or obligatory meta files for the unity engine that need to be tracked alongside game resources. That means pull requests can get to be hundreds of files big without really doing much with actual code. I really appreciate the exclusion filter and am using it, but it'd be nice to be able to opt in to an AI assisted review when I know my changes are code heavy and need extra eyes, instead of having to opt out of an already running workflow and cancel it when it's not really needed.

  2. Cost savings. Since OpenAI is a paid service, being able to opt in to a review would save money for the user long term.

  3. It would also make it possible to select from multiple different models in the UI. For example:

  workflow_dispatch:
    inputs:
      model:
        description: 'Model'
        required: true
        default: 'gpt-3.5-turbo-16k'
        type: 'choice'
        options:
          - gpt-3.5-turbo
          - gpt-3.5-turbo-0301
          - gpt-3.5-turbo-16k-0613
          - gpt-3.5-turbo-16k
          - gpt-3.5-turbo-0613
          - gpt-4

would make it so if someone felt they needed GPT to have a bigger context to work with for one pull request vs another, they wouldn't have to go into their .yml files or modify their github environment entries.

I've never written an action before, but I can also take a crack at making a pull request when I get a little free time if you're up for this idea!

Workflow failed

Codereviewer workflow failed with obscure error. I have the same problem with public and private forks.

My config:

name: AI Code Reviewer

on:
  pull_request:
    types:
      - opened
      - synchronize
permissions: write-all
jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Repo
        uses: actions/checkout@v3

      - name: AI Code Reviewer
        uses: freeedcom/ai-codereviewer@main
        with:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
          OPENAI_API_MODEL: "gpt-4" # Optional: defaults to "gpt-4"
          exclude: "**/*.json, **/*.md" # Optional: exclude patterns separated by commas

Full log

image

GITHUB_TOKEN

no instructions are given on how to find/generate your github token

facing 404 error in https://api.openai.com/v1/chat/completions api , open api key is added in git hub secret , do i need to pay in open api

response: {
status: 404,
statusText: 'Not Found',
headers: {
date: 'Tue, 21 Nov 2023 11:45:46 GMT',
'content-type': 'application/json; charset=utf-8',
'content-length': '291',
connection: 'close',
vary: 'Origin',
'x-request-id': '141863fc39006e4ba1b203cf094e8c86',
'strict-transport-security': 'max-age=15724800; includeSubDomains',
'cf-cache-status': 'DYNAMIC',
'set-cookie': [Array],
server: 'cloudflare',
'cf-ray': '8298b03bfea90fe8-LAX',
'alt-svc': 'h3=":443"; ma=86400'
},
config: {
transitional: [Object],
adapter: [Function: httpAdapter],
transformRequest: [Array],
transformResponse: [Array],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
validateStatus: [Function: validateStatus],
headers: [Object],
method: 'post',
data: '{"model":"gpt-4","temperature":0.2,"max_tokens":700,"top_p":1,"frequency_penalty":0,"presence_penalty":0,"messages":[{"role":"system","content":"Your task is to review pull requests. Instructions:\n- Provide the response in following JSON format: [{\"lineNumber\": <line_number>, \"reviewComment\": \"\"}]\n- Do not give positive comments or compliments.\n- Provide comments and suggestions ONLY if there is something to improve, otherwise return an empty array.\n- Write the comment in GitHub Markdown format.\n- Use the given description only for the overall context and only comment the code.\n- IMPORTANT: NEVER suggest adding comments to the code.\n\nReview the following code diff in the file \".github/workflows/main.yml\" and take the pull request title and description into account when writing the response.\n \nPull request title: Development\nPull request description:\n\n---\n\n---\n\nGit diff to review:\n\ndiff\\n@@ -0,0 +1,22 @@\\n1 +name: AI Code Reviewer\\n2 +\\n3 +on:\\n4 + pull_request:\\n5 + types:\\n6 + - opened\\n7 + - synchronize\\n8 +permissions: write-all\\n9 +jobs:\\n10 + review:\\n11 + runs-on: ubuntu-latest\\n12 + steps:\\n13 + - name: Checkout Repo\\n14 + uses: actions/checkout@v3\\n15 +\\n16 + - name: AI Code Reviewer\\n17 + uses: santosh-invt/ai-code-reviewer@main\\n18 + with:\\n19 + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\\n20 + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}\\n21 + OPENAI_API_MODEL: \\"gpt-3.5-turbo\\" # Optional: defaults to \\"gpt-4\\"\\n22 + exclude: \\"**/*.json, **/*.md\\" # Optional: exclude patterns separated by commas\\n22 \\\\ No newline at end of file\\n\n"}]}',
url: 'https://api.openai.com/v1/chat/completions'
}

Page not found

hi,
getting an Error: RequestError [HttpError]

my .yml as in https://github.com/marketplace/actions/ai-code-review-action

`name: AI Code Reviewer

on:
pull_request:
types:
- opened
- synchronize
permissions: write-all
jobs:
review:
runs-on: ubuntu-latest
steps:
- name: Checkout Repo
uses: actions/checkout@v3

  - name: AI Code Reviewer
    uses: freeedcom/ai-codereviewer@main
    with:
      GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
      OPENAI_API_MODEL: "gpt-4" # Optional: defaults to "gpt-4"
      exclude: "**/*.json, **/*.md" # Optional: exclude patterns separated by commas`

Multiple comments?

Would it be possible to ask for multiple comments? Ask it to use some kind of syntax that could then be parsed and multiple comments added?

Error: RequestError [HttpError]: Unprocessable Entity: "Pull request review thread path is invalid and Pull request review thread diff hunk can't be blank"

There seems to be an error when submitting the review to github.

Error log:

Error: RequestError [HttpError]: Unprocessable Entity: "Pull request review thread path is invalid and Pull request review thread diff hunk can't be blank"
    at /home/runner/work/_actions/freeedcom/ai-codereviewer/main/webpack:/open-ai-reviewer/node_modules/@octokit/request/dist-node/index.js:7[8](https://github.com/LightConsultingInc/alphaedu-FE/actions/runs/7153530492/job/19480089954#step:3:9):1
    at processTicksAndRejections (node:internal/process/task_queues:[9](https://github.com/LightConsultingInc/alphaedu-FE/actions/runs/7153530492/job/19480089954#step:3:10)6:5) {
  status: 422,
  response: {
    url: 'https://api.github.com/repos/LightConsultingInc/alphaedu-FE/pulls/178/reviews',
    status: 422,
    headers: {
      'access-control-allow-origin': '*',
      'access-control-expose-headers': 'ETag, Link, Location, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Used, X-RateLimit-Resource, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval, X-GitHub-Media-Type, X-GitHub-SSO, X-GitHub-Request-Id, Deprecation, Sunset',
      connection: 'close',
      'content-length': '246',
      'content-security-policy': "default-src 'none'",
      'content-type': 'application/json; charset=utf-8',
      date: 'Sat, 09 Dec 2023 21:07:06 GMT',
      'referrer-policy': 'origin-when-cross-origin, strict-origin-when-cross-origin',
      server: 'GitHub.com',
      'strict-transport-security': 'max-age=31536000; includeSubdomains; preload',
      vary: 'Accept-Encoding, Accept, X-Requested-With',
      'x-accepted-github-permissions': 'pull_requests=write',
      'x-content-type-options': 'nosniff',
      'x-frame-options': 'deny',
      'x-github-api-version-selected': '2022-11-28',
      'x-github-media-type': 'github.v3; format=json',
      'x-github-request-id': '6CE0:9641:32C0EE5:3476A4E:6574D6FA',
      'x-ratelimit-limit': '[10](https://github.com/LightConsultingInc/alphaedu-FE/actions/runs/7153530492/job/19480089954#step:3:11)00',
      'x-ratelimit-remaining': '979',
      'x-ratelimit-reset': '1702158488',
      'x-ratelimit-resource': 'core',
      'x-ratelimit-used': '21',
      'x-xss-protection': '0'
    },
    data: {
      message: 'Unprocessable Entity',
      errors: [Array],
      documentation_url: 'https://docs.github.com/rest/pulls/reviews#create-a-review-for-a-pull-request'
    }
  },
  request: {
    method: 'POST',
    url: 'https://api.github.com/repos/LightConsultingInc/alphaedu-FE/pulls/178/reviews',
    headers: {
      accept: 'application/vnd.github.v3+json',
      'user-agent': 'octokit-rest.js/19.0.7 octokit-core.js/4.2.0 Node.js/[16](https://github.com/LightConsultingInc/alphaedu-FE/actions/runs/7153530492/job/19480089954#step:3:17).[20](https://github.com/LightConsultingInc/alphaedu-FE/actions/runs/7153530492/job/19480089954#step:3:21).2 (linux; x64)',
      authorization: 'token [REDACTED]',
      'content-type': 'application/json; charset=utf-8'
    },
    body: '{"comments":[{"body":"The `permissions: write-all` setting gives all actions run in this workflow write access to all the repository\'s contents. This is a high level of access and could be a security risk. Consider specifying more granular permissions to limit the access of the actions.","path":".github/workflows/pr.yml","line":8},{"body":"The `exclude` parameter is set to exclude all `.json` and `.md` files. If there is a need to review these types of files, consider removing them from the exclude list.","path":".github/workflows/pr.yml","line":[22](https://github.com/LightConsultingInc/alphaedu-FE/actions/runs/7153530492/job/19480089954#step:3:23)}],"event":"COMMENT"}',
    request: { hook: [Function: bound bound register] }
  }
}

Can't find 'action.yml', 'action.yaml' or 'Dockerfile' for action

I am following the step

Replace your-username with your GitHub username or organization name where the AI Code Reviewer repository is located.

My username is xrzhuang and my repo is MrFU. However every combination of this I am trying is not working?

Examples:

uses: xrzhuang/ai-code-reviewer@main
uses: MrFU/ai-code-reviewer@main
uses: xrzhuang/MrFU/ai-code-reviewer@main
uses: xrzhuang/MrFU@main

Can someone please explain what I am doing wrong here? Please help ty

Configuring custom rules

Using this tool to configure custom rules could be a killer feature by allowing projects to teach the AI what the coding guidelines in a repo are.

Is this planned?

404 Not Found on OpenAI API endpoint/Github diff endpoint

Subject:

OpenAI API endpoint causing workflow break

Issue Description:

When using the ai-codereviewer action, which calls the OpenAI API endpoint https://api.openai.com/v1/chat/completions, a "404 Not Found" error is encountered. This error causes the workflow to break during the "AI Code Review" step.

Error Details:

Run freeedcom/[email protected]
Error: Error: Request failed with status code 404
    at createError (/home/runner/work/_actions/freeedcom/ai-codereviewer/v2.4.1/webpack:/open-ai-reviewer/node_modules/axios/lib/core/createError.js:16:1)
    at settle (/home/runner/work/_actions/freeedcom/ai-codereviewer/v2.4.1/webpack:/open-ai-reviewer/node_modules/axios/lib/core/settle.js:17:1)
    at IncomingMessage.handleStreamEnd (/home/runner/work/_actions/freeedcom/ai-codereviewer/v2.4.1/webpack:/open-ai-reviewer/node_modules/axios/lib/adapters/http.js:322:1)
    at IncomingMessage.emit (node:events:539:35)
    at endReadableNT (node:internal/streams/readable:1345:12)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  config: {
    transitional: {
      silentJSONParsing: true,
      forcedJSONParsing: true,
      clarifyTimeoutError: false
    },
    adapter: [Function: httpAdapter],
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    timeout: 0,
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    maxBodyLength: -1,
    validateStatus: [Function: validateStatus],
    headers: {
      Accept: 'application/json, text/plain, */*',
      'Content-Type': 'application/json',
      'User-Agent': 'OpenAI/NodeJS/3.2.1',
      Authorization: '***',
      'Content-Length': 1669
    },
    method: 'post',
    data: '{"model":"gpt-4","temperature":0.2,"max_tokens":700,"top_p":1,"frequency_penalty":0,"presence_penalty":0,"messages":[{"role":"system","content":"Your task is to review pull requests. Instructions:\\n- Provide the response in following JSON format:  [{\\"lineNumber\\":  <line_number>, \\"reviewComment\\": \\"<review comment>\\"}]\\n- Do not give positive comments or compliments.\\n- Provide comments and suggestions ONLY if there is something to improve, otherwise return an empty array.\\n- Write the comment in GitHub Markdown format.\\n- Use the given description only for the overall context and only comment the code.\\n- IMPORTANT: NEVER suggest adding comments to the code.\\n\\nReview the following code diff in the file \\"vue/src/util/formatting.ts\\" and take the pull request title and description into account when writing the response.\\n  \\nPull request title: chore: test new workflow with a dummy PR\\nPull request description:\\n\\n---\\n\\n---\\n\\nGit diff to review:\\n\\n```diff\\n@@ -14,6 +14,13 @@ export const formatNumberWithDecimals = new Intl.NumberFormat(\'en\', {\\n14    maximumFractionDigits: 2,\\n15  }).format;\\n16  \\n17 +/**\\n18 + * Removes all non-alphanumeric characters from the input string.\\n19 + *\\n20 + * @param {string} inputString - The string to remove non-alphanumeric characters from.\\n21 + * @param {string} replacement - The replacement string for removed characters. Defaults to an empty string.\\n22 + * @returns {string} - The input string with non-alphanumeric characters removed.\\n23 + */\\n24  export const stripNonAlphaNumerics = (inputString: string, replacement: string = \'\'): string => {\\n25    let regex = /[^a-zA-Z0-9_]/g;\\n26  \\n```\\n"}]}',
    url: 'https://api.openai.com/v1/chat/completions'
  },
  request: <ref *1> ClientRequest {
    _events: [Object: null prototype] {
      abort: [Function (anonymous)],
      aborted: [Function (anonymous)],
      connect: [Function (anonymous)],
      error: [Function (anonymous)],
      socket: [Function (anonymous)],
      timeout: [Function (anonymous)],
      prefinish: [Function: requestOnPrefinish]
    },
    _eventsCount: 7,
    _maxListeners: undefined,
    outputData: [],
    outputSize: 0,
    writable: true,
    destroyed: false,
    _last: true,
    chunkedEncoding: false,
    shouldKeepAlive: false,
    maxRequestsOnConnectionReached: false,
    _defaultKeepAlive: true,
    useChunkedEncodingByDefault: true,
    sendDate: false,
    _removedConnection: false,
    _removedContLen: false,
    _removedTE: false,
    _contentLength: null,
    _hasBody: true,
    _trailer: '',
    finished: true,
    _headerSent: true,
    _closed: false,
    socket: TLSSocket {
      _tlsOptions: [Object],
      _secureEstablished: true,
      _securePending: false,
      _newSessionPending: false,
      _controlReleased: true,
      secureConnecting: false,
      _SNICallback: null,
      servername: 'api.openai.com',
      alpnProtocol: false,
      authorized: true,
      authorizationError: null,
      encrypted: true,
      _events: [Object: null prototype],
      _eventsCount: 10,
      connecting: false,
      _hadError: false,
      _parent: null,
      _host: 'api.openai.com',
      _readableState: [ReadableState],
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: false,
      _sockname: null,
      _pendingData: null,
      _pendingEncoding: '',
      server: undefined,
      _server: null,
      ssl: [TLSWrap],
      _requestCert: true,
      _rejectUnauthorized: true,
      parser: null,
      _httpMessage: [Circular *1],
      [Symbol(res)]: [TLSWrap],
      [Symbol(verified)]: true,
      [Symbol(pendingSession)]: null,
      [Symbol(async_id_symbol)]: 71,
      [Symbol(kHandle)]: [TLSWrap],
      [Symbol(lastWriteQueueSize)]: 0,
      [Symbol(timeout)]: null,
      [Symbol(kBuffer)]: null,
      [Symbol(kBufferCb)]: null,
      [Symbol(kBufferGen)]: null,
      [Symbol(kCapture)]: false,
      [Symbol(kSetNoDelay)]: false,
      [Symbol(kSetKeepAlive)]: true,
      [Symbol(kSetKeepAliveInitialDelay)]: 60,
      [Symbol(kBytesRead)]: 0,
      [Symbol(kBytesWritten)]: 0,
      [Symbol(connect-options)]: [Object],
      [Symbol(RequestTimeout)]: undefined
    },
    _header: 'POST /v1/chat/completions HTTP/1.1\r\n' +
      'Accept: application/json, text/plain, */*\r\n' +
      'Content-Type: application/json\r\n' +
      'User-Agent: OpenAI/NodeJS/3.2.1\r\n' +
      'Authorization: ***' +
      'Content-Length: 1669\r\n' +
      'Host: api.openai.com\r\n' +
      'Connection: close\r\n' +
      '\r\n',
    _keepAliveTimeout: 0,
    _onPendingData: [Function: nop],
    agent: Agent {
      _events: [Object: null prototype],
      _eventsCount: 2,
      _maxListeners: undefined,
      defaultPort: 443,
      protocol: 'https:',
      options: [Object: null prototype],
      requests: [Object: null prototype] {},
      sockets: [Object: null prototype],
      freeSockets: [Object: null prototype] {},
      keepAliveMsecs: 1000,
      keepAlive: false,
      maxSockets: Infinity,
      maxFreeSockets: 256,
      scheduling: 'lifo',
      maxTotalSockets: Infinity,
      totalSocketCount: 1,
      maxCachedSessions: 100,
      _sessionCache: [Object],
      [Symbol(kCapture)]: false
    },
    socketPath: undefined,
    method: 'POST',
    maxHeaderSize: undefined,
    insecureHTTPParser: undefined,
    path: '/v1/chat/completions',
    _ended: true,
    res: IncomingMessage {
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 4,
      _maxListeners: undefined,
      socket: [TLSSocket],
      httpVersionMajor: 1,
      httpVersionMinor: 1,
      httpVersion: '1.1',
      complete: true,
      rawHeaders: [Array],
      rawTrailers: [],
      aborted: false,
      upgrade: false,
      url: '',
      method: null,
      statusCode: 404,
      statusMessage: 'Not Found',
      client: [TLSSocket],
      _consuming: false,
      _dumped: false,
      req: [Circular *1],
      responseUrl: 'https://api.openai.com/v1/chat/completions',
      redirects: [],
      [Symbol(kCapture)]: false,
      [Symbol(kHeaders)]: [Object],
      [Symbol(kHeadersCount)]: 22,
      [Symbol(kTrailers)]: null,
      [Symbol(kTrailersCount)]: 0,
      [Symbol(RequestTimeout)]: undefined
    },
    aborted: false,
    timeoutCb: null,
    upgradeOrConnect: false,
    parser: null,
    maxHeadersCount: null,
    reusedSocket: false,
    host: 'api.openai.com',
    protocol: 'https:',
    _redirectable: Writable {
      _writableState: [WritableState],
      _events: [Object: null prototype],
      _eventsCount: 3,
      _maxListeners: undefined,
      _options: [Object],
      _ended: true,
      _ending: true,
      _redirectCount: 0,
      _redirects: [],
      _requestBodyLength: 1669,
      _requestBodyBuffers: [],
      _onNativeResponse: [Function (anonymous)],
      _currentRequest: [Circular *1],
      _currentUrl: 'https://api.openai.com/v1/chat/completions',
      [Symbol(kCapture)]: false
    },
    [Symbol(kCapture)]: false,
    [Symbol(kNeedDrain)]: false,
    [Symbol(corked)]: 0,
    [Symbol(kOutHeaders)]: [Object: null prototype] {
      accept: [Array],
      'content-type': [Array],
      'user-agent': [Array],
      authorization: [Array],
      'content-length': [Array],
      host: [Array]
    }
  },
  response: {
    status: 404,
    statusText: 'Not Found',
    headers: {
      date: 'Thu, 06 Jul 2023 21:20:05 GMT',
      'content-type': 'application/json; charset=utf-8',
      'content-length': '179',
      connection: 'close',
      vary: 'Origin',
      'x-request-id': '1b5d343d36cb9611a9c3c11a84a77241',
      'strict-transport-security': 'max-age=15724800; includeSubDomains',
      'cf-cache-status': 'DYNAMIC',
      server: 'cloudflare',
      'cf-ray': '7e2ae3c08d6c0a8d-IAD',
      'alt-svc': 'h3=":443"; ma=86400'
    },
    config: {
      transitional: [Object],
      adapter: [Function: httpAdapter],
      transformRequest: [Array],
      transformResponse: [Array],
      timeout: 0,
      xsrfCookieName: 'XSRF-TOKEN',
      xsrfHeaderName: 'X-XSRF-TOKEN',
      maxContentLength: -1,
      maxBodyLength: -1,
      validateStatus: [Function: validateStatus],
      headers: [Object],
      method: 'post',
      data: '{"model":"gpt-4","temperature":0.2,"max_tokens":700,"top_p":1,"frequency_penalty":0,"presence_penalty":0,"messages":[{"role":"system","content":"Your task is to review pull requests. Instructions:\\n- Provide the response in following JSON format:  [{\\"lineNumber\\":  <line_number>, \\"reviewComment\\": \\"<review comment>\\"}]\\n- Do not give positive comments or compliments.\\n- Provide comments and suggestions ONLY if there is something to improve, otherwise return an empty array.\\n- Write the comment in GitHub Markdown format.\\n- Use the given description only for the overall context and only comment the code.\\n- IMPORTANT: NEVER suggest adding comments to the code.\\n\\nReview the following code diff in the file \\"vue/src/util/formatting.ts\\" and take the pull request title and description into account when writing the response.\\n  \\nPull request title: chore: test new workflow with a dummy PR\\nPull request description:\\n\\n---\\n\\n---\\n\\nGit diff to review:\\n\\n```diff\\n@@ -14,6 +14,13 @@ export const formatNumberWithDecimals = new Intl.NumberFormat(\'en\', {\\n14    maximumFractionDigits: 2,\\n15  }).format;\\n16  \\n17 +/**\\n18 + * Removes all non-alphanumeric characters from the input string.\\n19 + *\\n20 + * @param {string} inputString - The string to remove non-alphanumeric characters from.\\n21 + * @param {string} replacement - The replacement string for removed characters. Defaults to an empty string.\\n22 + * @returns {string} - The input string with non-alphanumeric characters removed.\\n23 + */\\n24  export const stripNonAlphaNumerics = (inputString: string, replacement: string = \'\'): string => {\\n25    let regex = /[^a-zA-Z0-9_]/g;\\n26  \\n```\\n"}]}',
      url: 'https://api.openai.com/v1/chat/completions'
    },
    request: <ref *1> ClientRequest {
      _events: [Object: null prototype],
      _eventsCount: 7,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      destroyed: false,
      _last: true,
      chunkedEncoding: false,
      shouldKeepAlive: false,
      maxRequestsOnConnectionReached: false,
      _defaultKeepAlive: true,
      useChunkedEncodingByDefault: true,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      _contentLength: null,
      _hasBody: true,
      _trailer: '',
      finished: true,
      _headerSent: true,
      _closed: false,
      socket: [TLSSocket],
      _header: 'POST /v1/chat/completions HTTP/1.1\r\n' +
        'Accept: application/json, text/plain, */*\r\n' +
        'Content-Type: application/json\r\n' +
        'User-Agent: OpenAI/NodeJS/3.2.1\r\n' +
        'Authorization: ***' +
        'Content-Length: 1669\r\n' +
        'Host: api.openai.com\r\n' +
        'Connection: close\r\n' +
        '\r\n',
      _keepAliveTimeout: 0,
      _onPendingData: [Function: nop],
      agent: [Agent],
      socketPath: undefined,
      method: 'POST',
      maxHeaderSize: undefined,
      insecureHTTPParser: undefined,
      path: '/v1/chat/completions',
      _ended: true,
      res: [IncomingMessage],
      aborted: false,
      timeoutCb: null,
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      reusedSocket: false,
      host: 'api.openai.com',
      protocol: 'https:',
      _redirectable: [Writable],
      [Symbol(kCapture)]: false,
      [Symbol(kNeedDrain)]: false,
      [Symbol(corked)]: 0,
      [Symbol(kOutHeaders)]: [Object: null prototype]
    },
    data: { error: [Object] }
  },
  isAxiosError: true,
  toJSON: [Function: toJSON]
}

Steps to Reproduce:

  1. Initiate the workflow process.
  2. Observe the error during the "AI Code Reviewer" step.

Expected Behavior:

The workflow should successfully call the OpenAI API endpoint and complete the "AI Code Review" step without any errors.

Actual Behavior:

The workflow breaks during the "AI Code Review" step due to an error when calling the OpenAI API endpoint.

Additional Information:

  • Workflow version: freeedcom/[email protected]
  • OpenAI API endpoint: https://api.openai.com/v1/chat/completions

Any help with this issue would be greatly appreciated.

Getting API errors

First of all thanks for working on this github action - it's an amazing idea! ๐Ÿ‘

I'm having problems getting it to work - on most PRs it throws an API error. It looks like there's an issue generating the comments, which are sent to the github api.

Here is an example error:

Error: SyntaxError: Unexpected token ` in JSON at position 0
    at JSON.parse (<anonymous>)
    at /home/runner/work/_actions/freeedcom/ai-codereviewer/v2.1.0/webpack:/open-ai-reviewer/lib/main.js:146:1
    at Generator.next (<anonymous>)
    at fulfilled (/home/runner/work/_actions/freeedcom/ai-codereviewer/v2.1.0/webpack:/open-ai-reviewer/lib/main.js:28:1)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
Error: RequestError [HttpError]: Unprocessable Entity: "Pull request review thread path is invalid and Pull request review thread diff hunk can't be blank"
    at /home/runner/work/_actions/freeedcom/ai-codereviewer/v2.1.0/webpack:/open-ai-reviewer/node_modules/@octokit/request/dist-node/index.js:78:1
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  status: 422,
...

Workflow Fails [Resource not accessible by personal access token]

name: AI Code Reviewer

on:
  pull_request:
    types:
    - opened
    - synchronize
permissions: write-all
jobs:
  review:
    runs-on: ubuntu-latest
    steps:
    - name: Checkout Repo
      uses: actions/checkout@v3

    - name: AI Code Reviewer
      uses: freeedcom/[email protected]
      with:
        GITHUB_TOKEN: ${{ secrets.TOKEN }}
        OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
        OPENAI_API_MODEL: "gpt-4" # Optional: defaults to "gpt-4"
        exclude: "**/*.json, **/*.md" # Optional: exclude patterns separated by commas

image

write-all permission

Does this need to have the write-all permission? This should be used with caution, so I'm curious if there are more granular permissions that can be given

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.