XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet
公开
关注 0 Fork 0 Star 1
返回提交历史

XFEstudio/gpt4free

Add copilot github action

7f4d9ba8
Heiner Lohaus <hlohaus@users.noreply.github.com>
提交于

代码差异

2 个文件 +248 -0
Added .github/workflows/copilot.yml +33 -0
@@ -0,0 +1,33 @@
1 name: AI Code Reviewer
2
3 on:
4 pull_request:
5 types:
6 - opened
7 - synchronize
8
9 env:
10 GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
11
12 permissions:
13 contents: read
14 pull-requests: write
15
16 jobs:
17 review:
18 runs-on: ubuntu-latest
19 steps:
20 - name: Checkout Repo
21 uses: actions/checkout@v3
22
23 - name: Setup Python
24 uses: actions/setup-python@v4
25 with:
26 python-version: "3.x"
27 cache: 'pip'
28 - name: Install Requirements
29 run: pip install -r requirements.txt
30 - name: Install PyGithub
31 run: pip install PyGithub
32 - name: AI Code Review
33 run: python -m etc.tool.copilot
Added etc/tool/copilot.py +215 -0
@@ -0,0 +1,215 @@
1 import sys
2 from pathlib import Path
3
4 sys.path.append(str(Path(__file__).parent.parent.parent))
5
6 import g4f
7 import json
8 import os
9 import re
10 import requests
11 from typing import Union
12 from github import Github
13 from github.PullRequest import PullRequest
14
15 g4f.debug.logging = True
16 g4f.debug.version_check = False
17
18 GITHUB_TOKEN = os.getenv('GITHUB_TOKEN')
19 G4F_PROVIDER = os.getenv('G4F_PROVIDER') or g4f.Provider.OpenaiChat
20 G4F_MODEL = os.getenv('G4F_MODEL') or g4f.models.gpt_4
21
22 def get_pr_details(github: Github) -> PullRequest:
23 """
24 Rteurns the details of the pull request from GitHub.
25
26 Returns:
27 PullRequest: A PullRequest instance.
28 """
29 with open(os.getenv('GITHUB_EVENT_PATH', ''), 'r') as file:
30 data = json.load(file)
31
32 repo = github.get_repo(f"{data['repository']['owner']['login']}/{data['repository']['name']}")
33 pull = repo.get_pull(data['number'])
34
35 return pull
36
37 def get_diff(diff_url: str) -> str:
38 """
39 Fetches the diff of the pull request.
40
41 Args:
42 pull (PullRequest): Pull request.
43
44 Returns:
45 str or None: The diff of the pull request or None if not available.
46 """
47 response = requests.get(diff_url)
48 response.raise_for_status()
49 return response.text
50
51 def read_json(text: str) -> dict:
52 match = re.search(r"```(json|)\n(?P<code>[\S\s]+?)\n```", text)
53 if match:
54 text = match.group("code")
55 try:
56 return json.loads(text.strip())
57 except json.JSONDecodeError:
58 print("No valid json:", text)
59 return {}
60
61 def read_text(text: str) -> dict:
62 match = re.search(r"```(markdown|)\n(?P<text>[\S\s]+?)\n```", text)
63 if match:
64 return match.group("text")
65 return text
66
67 def get_ai_response(prompt, as_json: bool = True) -> Union[dict, str]:
68 """
69 Gets a response from g4f API based on the prompt.
70
71 Args:
72 prompt (str): The prompt to send to g4f.
73
74 Returns:
75 dict: The parsed response from g4f.
76 """
77 response = g4f.ChatCompletion.create(
78 G4F_MODEL,
79 [{'role': 'user', 'content': prompt}],
80 G4F_PROVIDER,
81 ignore_stream_and_auth=True
82 )
83 if as_json:
84 return read_json(response)
85 return read_text(response)
86
87 def analyze_code(pull: PullRequest, diff: str)-> list:
88 """
89 Analyzes the code changes in the pull request.
90
91 Args:
92 diff (str): The diff of the pull request.
93 pr_details (dict): Details of the pull request.
94
95 Returns:
96 list: List of comments generated by the analysis.
97 """
98 comments = []
99 changed_lines = []
100 current_file_path = None
101 offset_line = 0
102
103 for line in diff.split('\n'):
104 if line.startswith('+++ b/'):
105 current_file_path = line[6:]
106 elif line.startswith('@@'):
107 match = re.search(r'\+([0-9]+?),', line)
108 if match:
109 offset_line = int(match.group(1))
110 elif current_file_path:
111 if line.startswith('\\') or line.startswith('diff'):
112 prompt = create_prompt(changed_lines, pull, current_file_path, offset_line)
113 response = get_ai_response(prompt)
114 for review in response.get('reviews', []):
115 review['path'] = current_file_path
116 comments.append(review)
117 changed_lines = []
118 current_file_path = None
119 elif not line.startswith('-'):
120 changed_lines.append(line)
121
122 return comments
123
124 def create_prompt(changed_lines: list, pull: PullRequest, file_path: str, offset_line: int):
125 """
126 Creates a prompt for the g4f model.
127
128 Args:
129 diff (str): The line of code to analyze.
130 pr_details (dict): Details of the pull request.
131
132 Returns:
133 str: The generated prompt.
134 """
135 code = "\n".join([f"{offset_line+idx}:{line}" for idx, line in enumerate(changed_lines)])
136 print("Code:", code)
137 example = '{"reviews": [{"line": <line_number>, "body": "<review comment>"}]}'
138 return f"""Your task is to review pull requests. Instructions:
139 - Provide the response in following JSON format: {example}
140 - Do not give positive comments or compliments.
141 - Provide comments and suggestions ONLY if there is something to improve, otherwise "reviews" should be an empty array.
142 - Write the comment in GitHub Markdown format.
143 - Use the given description only for the overall context and only comment the code.
144 - IMPORTANT: NEVER suggest adding comments to the code.
145
146 Review the following code diff in the file "{file_path}" and take the pull request title and description into account when writing the response.
147
148 Pull request title: {pull.title}
149 Pull request description:
150 ---
151 {pull.body}
152 ---
153
154 Each line is prefixed by its number. Code to review:
155 ```
156 {code}
157 ```
158 """
159
160 def create_review_prompt(pull: PullRequest, diff: str):
161 """
162 Creates a prompt to create a review.
163
164 Args:
165 diff (str): The line of code to analyze.
166
167 Returns:
168 str: The generated prompt.
169 """
170 return f"""Your task is to review a pull request. Instructions:
171 - Your name / you are copilot.
172 - Write the review in GitHub Markdown format.
173 - Thank the author for contributing to the project.
174 - Point out that you might leave a few comments on the files.
175
176 Pull request author: {pull.user.name}
177 Pull request title: {pull.title}
178 Pull request description:
179 ---
180 {pull.body}
181 ---
182
183 Diff:
184 ```diff
185 {diff}
186 ```
187 """
188
189 def main():
190 try:
191 github = Github(GITHUB_TOKEN)
192 pull = get_pr_details(github)
193 diff = get_diff(pull.diff_url)
194 except Exception as e:
195 print(f"Error get details: {e}")
196 exit(1)
197 try:
198 review = get_ai_response(create_review_prompt(pull, diff), False)
199 except Exception as e:
200 print(f"Error create review: {e}")
201 exit(1)
202 try:
203 comments = analyze_code(pull, diff)
204 except Exception as e:
205 print(f"Error analyze: {e}")
206 exit(1)
207 print("Comments:", comments)
208 try:
209 pull.create_review(body=review, comments=comments)
210 except Exception as e:
211 print(f"Error posting review: {e}")
212 exit(1)
213
214 if __name__ == "__main__":
215 main()