From 8324e9a38d33181964b3b96075876b0699efd66d Mon Sep 17 00:00:00 2001 From: mrT23 Date: Sat, 9 Mar 2024 10:46:36 +0200 Subject: [PATCH 001/226] can_be_split --- docs/REVIEW.md | 1 - pr_agent/algo/utils.py | 37 +++++++++++++++++++++- pr_agent/git_providers/git_provider.py | 7 ++++ pr_agent/git_providers/github_provider.py | 5 +++ pr_agent/settings/configuration.toml | 2 +- pr_agent/settings/pr_reviewer_prompts.toml | 30 ++++++++++++------ pr_agent/tools/pr_reviewer.py | 3 +- 7 files changed, 71 insertions(+), 14 deletions(-) diff --git a/docs/REVIEW.md b/docs/REVIEW.md index 00b3c8ac..98afb085 100644 --- a/docs/REVIEW.md +++ b/docs/REVIEW.md @@ -41,7 +41,6 @@ To edit [configurations](./../pr_agent/settings/configuration.toml#L19) related - `persistent_comment`: if set to true, the review comment will be persistent, meaning that every new review request will edit the previous one. Default is true. #### Enable\\disable features -- `require_focused_review`: if set to true, the tool will add a section - 'is the PR a focused one'. Default is false. - `require_score_review`: if set to true, the tool will add a section that scores the PR. Default is false. - `require_tests_review`: if set to true, the tool will add a section that checks if the PR contains tests. Default is true. - `require_estimate_effort_to_review`: if set to true, the tool will add a section that estimates the effort needed to review the PR. Default is true. diff --git a/pr_agent/algo/utils.py b/pr_agent/algo/utils.py index 6932d7bd..3a467416 100644 --- a/pr_agent/algo/utils.py +++ b/pr_agent/algo/utils.py @@ -70,6 +70,7 @@ def convert_to_markdown(output_data: dict, gfm_supported: bool = True) -> str: """ emojis = { + "Can be split": "๐Ÿ”€", "Possible issues": "๐Ÿ”", "Score": "๐Ÿ…", "Relevant tests": "๐Ÿงช", @@ -90,7 +91,8 @@ def convert_to_markdown(output_data: dict, gfm_supported: bool = True) -> str: for key, value in output_data['review'].items(): if value is None or value == '' or value == {} or value == []: - continue + if key.lower() != 'can_be_split': + continue key_nice = key.replace('_', ' ').capitalize() emoji = emojis.get(key_nice, "") if gfm_supported: @@ -99,6 +101,8 @@ def convert_to_markdown(output_data: dict, gfm_supported: bool = True) -> str: if 'security concerns' in key_nice.lower(): value = emphasize_header(value.strip()) markdown_text += f" {emoji} {key_nice}\n\n{value}\n\n\n" + elif 'can be split' in key_nice.lower(): + markdown_text += process_can_be_split(emoji, value) elif 'possible issues' in key_nice.lower(): value = value.strip() issues = value.split('\n- ') @@ -150,6 +154,37 @@ def convert_to_markdown(output_data: dict, gfm_supported: bool = True) -> str: return markdown_text +def process_can_be_split(emoji, value): + key_nice = "Can this PR be split?" + markdown_text = "" + if not value or isinstance(value, list) and len(value) == 1: + value = "No" + markdown_text += f" {emoji} {key_nice}\n\n{value}\n\n\n" + else: + number_of_splits = len(value) + markdown_text += f" {emoji} {key_nice}\n" + for i, split in enumerate(value): + title = split.get('title', '') + relevant_files = split.get('relevant_files', []) + if i == 0: + markdown_text += f"
\nSub PR theme: {title}\n\n" + markdown_text += f"
\n" + markdown_text += f"Relevant files:\n" + markdown_text += f"\n\n
\n" + else: + markdown_text += f"\n
\nSub PR theme: {title}\n\n" + markdown_text += f"
\n" + markdown_text += f"Relevant files:\n" + markdown_text += f"\n\n
\n" + return markdown_text + + def parse_code_suggestion(code_suggestion: dict, i: int = 0, gfm_supported: bool = True) -> str: """ Convert a dictionary of data into markdown format. diff --git a/pr_agent/git_providers/git_provider.py b/pr_agent/git_providers/git_provider.py index e8a78b4b..a2bd7deb 100644 --- a/pr_agent/git_providers/git_provider.py +++ b/pr_agent/git_providers/git_provider.py @@ -197,6 +197,12 @@ class GitProvider(ABC): def calc_pr_statistics(self, pull_request_data: dict): return {} + def get_num_of_files(self): + try: + return len(self.get_diff_files()) + except Exception as e: + return -1 + def get_main_pr_language(languages, files) -> str: """ @@ -266,6 +272,7 @@ def get_main_pr_language(languages, files) -> str: return main_language_str + class IncrementalPR: def __init__(self, is_incremental: bool = False): self.is_incremental = is_incremental diff --git a/pr_agent/git_providers/github_provider.py b/pr_agent/git_providers/github_provider.py index fab4fd5b..e29c077e 100644 --- a/pr_agent/git_providers/github_provider.py +++ b/pr_agent/git_providers/github_provider.py @@ -112,6 +112,11 @@ class GithubProvider(GitProvider): self.git_files = self.pr.get_files() return self.git_files + def get_num_of_files(self): + if self.git_files: + return self.git_files.totalCount + else: + return -1 @retry(exceptions=RateLimitExceeded, tries=get_settings().github.ratelimit_retries, delay=2, backoff=2, jitter=(1, 3)) diff --git a/pr_agent/settings/configuration.toml b/pr_agent/settings/configuration.toml index b5a0dab1..3038f3df 100644 --- a/pr_agent/settings/configuration.toml +++ b/pr_agent/settings/configuration.toml @@ -22,10 +22,10 @@ ai_disclaimer="" # Pro feature, full text for the AI disclaimer [pr_reviewer] # /review # # enable/disable features -require_focused_review=false require_score_review=false require_tests_review=true require_estimate_effort_to_review=true +require_can_be_split_review=false # soc2 require_soc2_ticket=false soc2_ticket_prompt="Does the PR description include a link to ticket in a project management system (e.g., Jira, Asana, Trello, etc.) ?" diff --git a/pr_agent/settings/pr_reviewer_prompts.toml b/pr_agent/settings/pr_reviewer_prompts.toml index 62068647..326bfb47 100644 --- a/pr_agent/settings/pr_reviewer_prompts.toml +++ b/pr_agent/settings/pr_reviewer_prompts.toml @@ -49,7 +49,13 @@ Extra instructions from the user: The output must be a YAML object equivalent to type $PRReview, according to the following Pydantic definitions: ===== -class Review(BaseModel) +{%- if require_can_be_split_review %} +class SubPR(BaseModel): + title: str = Field(description="short and concise title for a sub-PR composed only from the relevant files") + relevant_files: List[str] = Field(description="the relevant files of the sub-PR") +{%- endif %} + +class Review(BaseModel): {%- if require_estimate_effort_to_review %} estimated_effort_to_review_[1-5]: str = Field(description="Estimate, on a scale of 1-5 (inclusive), the time and effort required to review this PR by an experienced and knowledgeable developer. 1 means short and easy review , 5 means long and hard review. Take into account the size, complexity, quality, and the needed changes of the PR code diff. Explain your answer in a short and concise manner.") {%- endif %} @@ -61,15 +67,15 @@ class Review(BaseModel) {%- endif %} {%- if question_str %} insights_from_user_answers: str = Field(description="shortly summarize the insights you gained from the user's answers to the questions") -{%- endif %} -{%- if require_focused %} - focused_pr: str = Field(description="Is this a focused PR, in the sense that all the PR code diff changes are united under a single focused theme ? If the theme is too broad, or the PR code diff changes are too scattered, then the PR is not focused. Explain your answer shortly.") {%- endif %} possible_issues: str = Field(description="Does this PR code introduce clear issues, bugs, or major performance concerns? If there are no apparent issues, respond with 'No'. If there are any issues, describe them briefly. Use bullet points if more than one issue. Be specific, and provide examples if possible. Start each bullet point with a short specific header, such as: "- Possible Bug: ...", etc.") security_concerns: str = Field(description="does this PR code introduce possible vulnerabilities such as exposure of sensitive information (e.g., API keys, secrets, passwords), or security concerns like SQL injection, XSS, CSRF, and others ? Answer 'No' if there are no possible issues. If there are security concerns or issues, start your answer with a short header, such as: 'Sensitive information exposure: ...', 'SQL injection: ...' etc. Explain your answer. Be specific and give examples if possible") +{%- if require_can_be_split_review %} + can_be_split: List[SubPR] = Field(description="Can this PR, with its {{ num_pr_files }} changed files, be clearly split into smaller sub-PRs, that can be reviewed and merged independently, regardless of the order ? If yes, provide a title and list the relevant files for each sub-PR. Make sure that the sub-PRs are indeed independent, without any code dependencies between them. Try not to create too many sub-PRs. For example, logic changes and corresponding documentation should be grouped together. Output empty list if the PR cannot be split.") +{%- endif %} {%- if num_code_suggestions > 0 %} -class CodeSuggestion(BaseModel) +class CodeSuggestion(BaseModel): relevant_file: str = Field(description="the relevant file full path") language: str = Field(description="the language of the relevant file") suggestion: str = Field(description="a concrete suggestion for meaningfully improving the new PR code. Also describe how, specifically, the suggestion can be applied to new PR code. Add tags with importance measure that matches each suggestion ('important' or 'medium'). Do not make suggestions for updating or adding docstrings, renaming PR title and description, or linter like.") @@ -77,7 +83,7 @@ class CodeSuggestion(BaseModel) {%- endif %} {%- if num_code_suggestions > 0 %} -class PRReview(BaseModel) +class PRReview(BaseModel): review: Review code_feedback: List[CodeSuggestion] {%- else %} @@ -100,14 +106,18 @@ review: {%- endif %} relevant_tests: | No -{%- if require_focused %} - focused_pr: | - no, because ... -{%- endif %} possible_issues: | No security_concerns: | No +{%- if require_can_be_split_review %} + can_be_split: | + title: | + ... + - relevant_files: + - ... + - ... +{%- endif %} {%- if num_code_suggestions > 0 %} code_feedback - relevant_file: | diff --git a/pr_agent/tools/pr_reviewer.py b/pr_agent/tools/pr_reviewer.py index 39eb904e..6d1eb5b9 100644 --- a/pr_agent/tools/pr_reviewer.py +++ b/pr_agent/tools/pr_reviewer.py @@ -56,10 +56,11 @@ class PRReviewer: "description": self.git_provider.get_pr_description(), "language": self.main_language, "diff": "", # empty diff for initial calculation + "num_pr_files": self.git_provider.get_num_of_files(), "require_score": get_settings().pr_reviewer.require_score_review, "require_tests": get_settings().pr_reviewer.require_tests_review, - "require_focused": get_settings().pr_reviewer.require_focused_review, "require_estimate_effort_to_review": get_settings().pr_reviewer.require_estimate_effort_to_review, + 'require_can_be_split_review': get_settings().pr_reviewer.require_can_be_split_review, 'num_code_suggestions': get_settings().pr_reviewer.num_code_suggestions, 'question_str': question_str, 'answer_str': answer_str, From 4810b8549bab578b1f1be715eb39a8f472c6856c Mon Sep 17 00:00:00 2001 From: mrT23 Date: Sun, 10 Mar 2024 16:59:37 +0200 Subject: [PATCH 002/226] docs --- docs/docs/tools/review.md | 1 + pr_agent/servers/help.py | 2 +- pr_agent/settings/pr_reviewer_prompts.toml | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/docs/tools/review.md b/docs/docs/tools/review.md index c0190587..e467c2c4 100644 --- a/docs/docs/tools/review.md +++ b/docs/docs/tools/review.md @@ -28,6 +28,7 @@ To edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agen - `require_score_review`: if set to true, the tool will add a section that scores the PR. Default is false. - `require_tests_review`: if set to true, the tool will add a section that checks if the PR contains tests. Default is true. - `require_estimate_effort_to_review`: if set to true, the tool will add a section that estimates the effort needed to review the PR. Default is true. +- `require_can_be_split_review`: if set to true, the tool will add a section that checks if the PR can be split into smaller PRs. Default is false. #### SOC2 ticket compliance ๐Ÿ’Ž > This feature is available only in PR-Agent Pro diff --git a/pr_agent/servers/help.py b/pr_agent/servers/help.py index d93a6791..89487b4d 100644 --- a/pr_agent/servers/help.py +++ b/pr_agent/servers/help.py @@ -95,7 +95,7 @@ The `review` tool can auto-generate two specific types of labels for a PR: The `review` tool provides a collection of possible feedbacks about a PR. It is recommended to review the [possible options](https://github.com/Codium-ai/pr-agent/blob/main/docs/REVIEW.md#enabledisable-features), and choose the ones relevant for your use case. Some of the feature that are disabled by default are quite useful, and should be considered for enabling. For example: -`require_score_review`, `require_soc2_ticket`, and more. +`require_score_review`, `require_soc2_ticket`, `require_can_be_split_review`, and more. """ output += "\n\n\n\n" diff --git a/pr_agent/settings/pr_reviewer_prompts.toml b/pr_agent/settings/pr_reviewer_prompts.toml index 326bfb47..d8b1e1d4 100644 --- a/pr_agent/settings/pr_reviewer_prompts.toml +++ b/pr_agent/settings/pr_reviewer_prompts.toml @@ -88,7 +88,7 @@ class PRReview(BaseModel): code_feedback: List[CodeSuggestion] {%- else %} -class PRReview(BaseModel) +class PRReview(BaseModel): review: Review {%- endif %} ===== From c876f271a48dbf30bec62dbe51bfe64e8caa6866 Mon Sep 17 00:00:00 2001 From: mrT23 Date: Sun, 10 Mar 2024 17:13:40 +0200 Subject: [PATCH 003/226] contains several themes --- docs/docs/tools/review.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/tools/review.md b/docs/docs/tools/review.md index e467c2c4..ce00a6fe 100644 --- a/docs/docs/tools/review.md +++ b/docs/docs/tools/review.md @@ -28,7 +28,7 @@ To edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agen - `require_score_review`: if set to true, the tool will add a section that scores the PR. Default is false. - `require_tests_review`: if set to true, the tool will add a section that checks if the PR contains tests. Default is true. - `require_estimate_effort_to_review`: if set to true, the tool will add a section that estimates the effort needed to review the PR. Default is true. -- `require_can_be_split_review`: if set to true, the tool will add a section that checks if the PR can be split into smaller PRs. Default is false. +- `require_can_be_split_review`: if set to true, the tool will add a section that checks if the PR contains several themes, and can be split into smaller PRs. Default is false. #### SOC2 ticket compliance ๐Ÿ’Ž > This feature is available only in PR-Agent Pro From 3f66a1f0c970c39bd92d362f757206eb10fcac2d Mon Sep 17 00:00:00 2001 From: koid Date: Wed, 13 Mar 2024 11:10:19 +0900 Subject: [PATCH 004/226] update litellm --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 4d6daa93..6646b2e5 100644 --- a/requirements.txt +++ b/requirements.txt @@ -9,7 +9,7 @@ GitPython==3.1.32 google-cloud-aiplatform==1.35.0 google-cloud-storage==2.10.0 Jinja2==3.1.2 -litellm==1.29.1 +litellm==1.29.7 loguru==0.7.2 msrest==0.7.1 openai==1.13.3 From d62796ac681684fae8407222a6f5b26a5c5990ef Mon Sep 17 00:00:00 2001 From: koid Date: Wed, 13 Mar 2024 11:14:04 +0900 Subject: [PATCH 005/226] update max_tokens --- pr_agent/algo/__init__.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/pr_agent/algo/__init__.py b/pr_agent/algo/__init__.py index 7c537e3a..cd535416 100644 --- a/pr_agent/algo/__init__.py +++ b/pr_agent/algo/__init__.py @@ -23,4 +23,8 @@ MAX_TOKENS = { 'anthropic.claude-v1': 100000, 'anthropic.claude-v2': 100000, 'anthropic/claude-3-opus-20240229': 100000, + 'bedrock/anthropic.claude-instant-v1': 100000, + 'bedrock/anthropic.claude-v2': 100000, + 'bedrock/anthropic.claude-v2:1': 100000, + 'bedrock/anthropic.claude-3-sonnet-20240229-v1:0': 100000, } From 1ed2cd064ab364fa758567528d9933cc175c2402 Mon Sep 17 00:00:00 2001 From: koid Date: Wed, 13 Mar 2024 11:20:02 +0900 Subject: [PATCH 006/226] add config litellm.drop_params --- pr_agent/algo/ai_handlers/litellm_ai_handler.py | 2 ++ pr_agent/settings/configuration.toml | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/pr_agent/algo/ai_handlers/litellm_ai_handler.py b/pr_agent/algo/ai_handlers/litellm_ai_handler.py index 51f72960..5107c74b 100644 --- a/pr_agent/algo/ai_handlers/litellm_ai_handler.py +++ b/pr_agent/algo/ai_handlers/litellm_ai_handler.py @@ -36,6 +36,8 @@ class LiteLLMAIHandler(BaseAiHandler): assert litellm_token, "LITELLM_TOKEN is required" os.environ["LITELLM_TOKEN"] = litellm_token litellm.use_client = True + if get_settings().get("LITELLM.DROP_PARAMS", None): + litellm.drop_params = get_settings().litellm.drop_params if get_settings().get("OPENAI.ORG", None): litellm.organization = get_settings().openai.org if get_settings().get("OPENAI.API_TYPE", None): diff --git a/pr_agent/settings/configuration.toml b/pr_agent/settings/configuration.toml index b5a0dab1..c3861bb0 100644 --- a/pr_agent/settings/configuration.toml +++ b/pr_agent/settings/configuration.toml @@ -192,7 +192,8 @@ pr_commands = [ url = "" [litellm] -#use_client = false +# use_client = false +# drop_params = false [pr_similar_issue] skip_comments = false From f94a0fd7046fa36836958ddb6de86b167259fd4e Mon Sep 17 00:00:00 2001 From: koid Date: Wed, 13 Mar 2024 11:24:51 +0900 Subject: [PATCH 007/226] add Claude3Config --- pr_agent/algo/ai_handlers/litellm_ai_handler.py | 1 + 1 file changed, 1 insertion(+) diff --git a/pr_agent/algo/ai_handlers/litellm_ai_handler.py b/pr_agent/algo/ai_handlers/litellm_ai_handler.py index 5107c74b..1c78c09d 100644 --- a/pr_agent/algo/ai_handlers/litellm_ai_handler.py +++ b/pr_agent/algo/ai_handlers/litellm_ai_handler.py @@ -70,6 +70,7 @@ class LiteLLMAIHandler(BaseAiHandler): ) if get_settings().get("AWS.BEDROCK_REGION", None): litellm.AmazonAnthropicConfig.max_tokens_to_sample = 2000 + litellm.AmazonAnthropicClaude3Config.max_tokens = 2000 self.aws_bedrock_client = boto3.client( service_name="bedrock-runtime", region_name=get_settings().aws.bedrock_region, From 33d2d78bbca5a2640ccdbd82a8606db6c72eb0d8 Mon Sep 17 00:00:00 2001 From: koid Date: Wed, 13 Mar 2024 11:34:54 +0900 Subject: [PATCH 008/226] update docs --- docs/docs/usage-guide/additional_configurations.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/docs/usage-guide/additional_configurations.md b/docs/docs/usage-guide/additional_configurations.md index 4a6224bd..dbdd1ed4 100644 --- a/docs/docs/usage-guide/additional_configurations.md +++ b/docs/docs/usage-guide/additional_configurations.md @@ -162,8 +162,9 @@ To use Amazon Bedrock and its foundational models, add the below configuration: ``` [config] # in configuration.toml -model = "anthropic.claude-v2" -fallback_models="anthropic.claude-instant-v1" +model="bedrock/anthropic.claude-3-sonnet-20240229-v1:0" +model_turbo="bedrock/anthropic.claude-3-sonnet-20240229-v1:0" +fallback_models=["bedrock/anthropic.claude-v2:1"] [aws] # in .secrets.toml bedrock_region = "us-east-1" From 0cdd3bf43694df98a227e24aaefe779f636c3113 Mon Sep 17 00:00:00 2001 From: koid Date: Wed, 13 Mar 2024 14:23:57 +0900 Subject: [PATCH 009/226] update docs --- docs/docs/usage-guide/additional_configurations.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/docs/usage-guide/additional_configurations.md b/docs/docs/usage-guide/additional_configurations.md index dbdd1ed4..1a756252 100644 --- a/docs/docs/usage-guide/additional_configurations.md +++ b/docs/docs/usage-guide/additional_configurations.md @@ -172,6 +172,12 @@ bedrock_region = "us-east-1" Note that you have to add access to foundational models before using them. Please refer to [this document](https://docs.aws.amazon.com/bedrock/latest/userguide/setting-up.html) for more details. +If you are using the claude-3 model, please configure the following settings as there are parameters incompatible with claude-3. +``` +[litellm] +drop_params = true +``` + AWS session is automatically authenticated from your environment, but you can also explicitly set `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` environment variables. From 3bae515e39b886194ff48e15897c07a691440997 Mon Sep 17 00:00:00 2001 From: koid Date: Thu, 14 Mar 2024 16:58:44 +0900 Subject: [PATCH 010/226] add claude-3-haiku --- pr_agent/algo/__init__.py | 1 + requirements.txt | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/pr_agent/algo/__init__.py b/pr_agent/algo/__init__.py index cd535416..9e05ed9f 100644 --- a/pr_agent/algo/__init__.py +++ b/pr_agent/algo/__init__.py @@ -27,4 +27,5 @@ MAX_TOKENS = { 'bedrock/anthropic.claude-v2': 100000, 'bedrock/anthropic.claude-v2:1': 100000, 'bedrock/anthropic.claude-3-sonnet-20240229-v1:0': 100000, + 'bedrock/anthropic.claude-3-haiku-20240307-v1:0': 100000, } diff --git a/requirements.txt b/requirements.txt index 6646b2e5..97df2f93 100644 --- a/requirements.txt +++ b/requirements.txt @@ -9,7 +9,7 @@ GitPython==3.1.32 google-cloud-aiplatform==1.35.0 google-cloud-storage==2.10.0 Jinja2==3.1.2 -litellm==1.29.7 +litellm==1.31.10 loguru==0.7.2 msrest==0.7.1 openai==1.13.3 From 50d0af0372176e8190aa846f686ca32b438a91fa Mon Sep 17 00:00:00 2001 From: Almog Lavi Date: Thu, 14 Mar 2024 13:56:10 +0200 Subject: [PATCH 011/226] Added Google Analytics to mkdocs configuration --- docs/mkdocs.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index 6e8153cf..1062c6c3 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -93,6 +93,9 @@ extra: link: https://twitter.com/CodiumAI - icon: fontawesome/brands/instagram link: https://www.instagram.com/codiumai/ + analytics: + provider: google + property: G-9LJSZ77MJF extra_css: - css/custom.css From b472149714463f8c69ce57745dce2d124160065e Mon Sep 17 00:00:00 2001 From: Almog Lavi Date: Thu, 14 Mar 2024 16:13:08 +0200 Subject: [PATCH 012/226] Replace hardcoded Google Analytics ID with environment variable in mkdocs.yml --- docs/mkdocs.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index 1062c6c3..0a76acf1 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -95,7 +95,7 @@ extra: link: https://www.instagram.com/codiumai/ analytics: provider: google - property: G-9LJSZ77MJF + property: ${{ secrets.GOOGLE_ANALYTICS_ID }} extra_css: - css/custom.css From 1593d8932baf10e9fc044ce45b9b5a6032404ced Mon Sep 17 00:00:00 2001 From: mrT23 Date: Fri, 15 Mar 2024 12:37:50 +0200 Subject: [PATCH 013/226] Refactor code in pr_code_suggestions.py and remove 'use_repo_settings_file' from azure.md and automations_and_usage.md --- docs/docs/installation/azure.md | 1 - docs/docs/usage-guide/automations_and_usage.md | 1 - pr_agent/tools/pr_code_suggestions.py | 8 ++------ 3 files changed, 2 insertions(+), 8 deletions(-) diff --git a/docs/docs/installation/azure.md b/docs/docs/installation/azure.md index 8c111581..e8c11664 100644 --- a/docs/docs/installation/azure.md +++ b/docs/docs/installation/azure.md @@ -4,7 +4,6 @@ To use Azure DevOps provider use the following settings in configuration.toml: ``` [config] git_provider="azure" -use_repo_settings_file=false ``` Azure DevOps provider supports [PAT token](https://learn.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=azure-devops&tabs=Windows) or [DefaultAzureCredential](https://learn.microsoft.com/en-us/azure/developer/python/sdk/authentication-overview#authentication-in-server-environments) authentication. diff --git a/docs/docs/usage-guide/automations_and_usage.md b/docs/docs/usage-guide/automations_and_usage.md index 81f182b5..b39f7e02 100644 --- a/docs/docs/usage-guide/automations_and_usage.md +++ b/docs/docs/usage-guide/automations_and_usage.md @@ -170,7 +170,6 @@ To use Azure DevOps provider use the following settings in configuration.toml: ``` [config] git_provider="azure" -use_repo_settings_file=false ``` Azure DevOps provider supports [PAT token](https://learn.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=azure-devops&tabs=Windows) or [DefaultAzureCredential](https://learn.microsoft.com/en-us/azure/developer/python/sdk/authentication-overview#authentication-in-server-environments) authentication. diff --git a/pr_agent/tools/pr_code_suggestions.py b/pr_agent/tools/pr_code_suggestions.py index 51dbe130..d4f3556a 100644 --- a/pr_agent/tools/pr_code_suggestions.py +++ b/pr_agent/tools/pr_code_suggestions.py @@ -393,11 +393,7 @@ class PRCodeSuggestions: for label, suggestions in suggestions_labels.items(): num_suggestions=len(suggestions) - # pr_body += f"""{label}""" pr_body += f"""{label.capitalize()}\n""" - # pr_body += f"""""" - # pr_body += f"""
{len(suggestions)} suggestions""" - # pr_body += f"""""" for i, suggestion in enumerate(suggestions): relevant_file = suggestion['relevant_file'].strip() @@ -444,11 +440,11 @@ class PRCodeSuggestions: {example_code} """ pr_body += f"" - pr_body += f"" + # pr_body += "" - pr_body += """""" + # pr_body += """""" pr_body += """
""" return pr_body except Exception as e: From 44386573eb95e695dc06b1a97e5772639ce761f8 Mon Sep 17 00:00:00 2001 From: Tom Brews Views Date: Fri, 15 Mar 2024 12:04:07 +0100 Subject: [PATCH 014/226] ad dcorect size logo to the header and adjust title spacing --- docs/docs/assets/logo.svg | 140 ++++++++++++++++++++++++++++++++++++++ docs/docs/css/custom.css | 88 ++---------------------- docs/mkdocs.yml | 2 +- 3 files changed, 145 insertions(+), 85 deletions(-) create mode 100644 docs/docs/assets/logo.svg diff --git a/docs/docs/assets/logo.svg b/docs/docs/assets/logo.svg new file mode 100644 index 00000000..5de22677 --- /dev/null +++ b/docs/docs/assets/logo.svg @@ -0,0 +1,140 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/docs/css/custom.css b/docs/docs/css/custom.css index 0e9b26fe..2f963ccd 100644 --- a/docs/docs/css/custom.css +++ b/docs/docs/css/custom.css @@ -5,94 +5,14 @@ --md-accent-fg-color: #AEA1F1; } .md-nav__title, .md-nav__link { - font-size: 16px; /* Adjust the font size as needed */ + font-size: 16px; } .md-tabs__link { - font-size: 16px; /* Adjust the font size as needed */ + font-size: 16px; } .md-header__title { - font-size: 20px; /* Adjust the font size as needed */ + font-size: 20px; + margin-left: 0px !important; } - -/* -@media (prefers-color-scheme: light) { - body { - --md-primary-fg-color: #00ffee !important; - --md-primary-bg-color: #ff0000 !important; - } - - body, .md-main, .md-content { - background-color: #4312f5 !important; - } -} - -@media (prefers-color-scheme: dark) { - body { - --md-primary-fg-color: #171518 !important; - --md-primary-bg-color: #171518 !important; - } - - body, .md-main, .md-content { - background-color: #171518 !important; - } - - .md-header__title { - color: #ffffff !important; - } - - .md-tabs .md-tabs__link { - color: #ffffff !important; - } - - .md-tabs .md-tabs__link:hover, - .md-tabs .md-tabs__link:focus { - color: #ffffff !important; - } - - .md-header__button { - color: #ffffff !important; - } - - .md-header__button svg { - fill: currentColor !important; - } - - .md-header__button:hover, - .md-header__button:focus { - color: #ffffff !important; - } - - .md-header__button:hover svg, - .md-header__button:focus svg { - fill: currentColor !important; - } - - .md-search__icon svg { - fill: #ffffff !important; - } - - .md-search__input { - color: #ffffff !important; - } - - .md-nav__item--active > .md-nav__link--active, - .md-nav__link--active { - color: #AEA1F1 !important; - } - - .md-nav--secondary .md-nav__title { - background: #171518; - box-shadow: 0 0 0.4rem 0.4rem #171518; - } - - .md-nav--lifted>.md-nav__list>.md-nav__item--active>.md-nav__link { - background: #171518; - box-shadow: 0 0 0.4rem 0.4rem #171518; - } - - .md-content a { - color: #AEA1F1 !important; - } -} */ \ No newline at end of file diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index 0a76acf1..8da53d48 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -35,7 +35,7 @@ nav: - Core Abilities: 'core-abilities/index.md' theme: - logo: assets/logo.png + logo: assets/logo.svg favicon: assets/favicon.ico name: material features: From 74345284bdc537caf2dba073bbeda55f063327d5 Mon Sep 17 00:00:00 2001 From: mrT23 Date: Sat, 16 Mar 2024 13:47:44 +0200 Subject: [PATCH 015/226] Enhance AI handler logging and add main PR language attribute to AI handler in various tools --- pr_agent/algo/ai_handlers/litellm_ai_handler.py | 15 +++++++++++++-- pr_agent/tools/pr_add_docs.py | 2 ++ pr_agent/tools/pr_code_suggestions.py | 1 + pr_agent/tools/pr_description.py | 1 + pr_agent/tools/pr_generate_labels.py | 3 ++- pr_agent/tools/pr_information_from_user.py | 2 ++ pr_agent/tools/pr_line_questions.py | 5 ++++- pr_agent/tools/pr_questions.py | 2 ++ pr_agent/tools/pr_reviewer.py | 2 ++ pr_agent/tools/pr_update_changelog.py | 3 +++ 10 files changed, 32 insertions(+), 4 deletions(-) diff --git a/pr_agent/algo/ai_handlers/litellm_ai_handler.py b/pr_agent/algo/ai_handlers/litellm_ai_handler.py index 51f72960..666db1b1 100644 --- a/pr_agent/algo/ai_handlers/litellm_ai_handler.py +++ b/pr_agent/algo/ai_handlers/litellm_ai_handler.py @@ -125,10 +125,21 @@ class LiteLLMAIHandler(BaseAiHandler): else: resp = response["choices"][0]['message']['content'] finish_reason = response["choices"][0]["finish_reason"] - # usage = response.get("usage") get_logger().debug(f"\nAI response:\n{resp}") - get_logger().debug("Full_response", artifact=response) + # log the full response for debugging, including the system and user prompts + response_log = response.dict() + response_log['system'] = system + response_log['user'] = user + response_log['output'] = resp + response_log['finish_reason'] = finish_reason + if hasattr(self, 'main_pr_language'): + response_log['main_pr_language'] = self.main_pr_language + else: + response_log['main_pr_language'] = 'unknown' + get_logger().debug("Full_response", artifact=response_log) + + # for CLI debugging if get_settings().config.verbosity_level >= 2: get_logger().info(f"\nAI response:\n{resp}") diff --git a/pr_agent/tools/pr_add_docs.py b/pr_agent/tools/pr_add_docs.py index d13a829d..a671dd3b 100644 --- a/pr_agent/tools/pr_add_docs.py +++ b/pr_agent/tools/pr_add_docs.py @@ -26,6 +26,8 @@ class PRAddDocs: ) self.ai_handler = ai_handler() + self.ai_handler.main_pr_language = self.main_language + self.patches_diff = None self.prediction = None self.cli_mode = cli_mode diff --git a/pr_agent/tools/pr_code_suggestions.py b/pr_agent/tools/pr_code_suggestions.py index d4f3556a..33628123 100644 --- a/pr_agent/tools/pr_code_suggestions.py +++ b/pr_agent/tools/pr_code_suggestions.py @@ -46,6 +46,7 @@ class PRCodeSuggestions: num_code_suggestions = get_settings().pr_code_suggestions.num_code_suggestions self.ai_handler = ai_handler() + self.ai_handler.main_pr_language = self.main_language self.patches_diff = None self.prediction = None self.cli_mode = cli_mode diff --git a/pr_agent/tools/pr_description.py b/pr_agent/tools/pr_description.py index 28df555f..7500efa7 100644 --- a/pr_agent/tools/pr_description.py +++ b/pr_agent/tools/pr_description.py @@ -41,6 +41,7 @@ class PRDescription: # Initialize the AI handler self.ai_handler = ai_handler() + self.ai_handler.main_pr_language = self.main_pr_language # Initialize the variables dictionary diff --git a/pr_agent/tools/pr_generate_labels.py b/pr_agent/tools/pr_generate_labels.py index 1d91d5e0..4111f7c2 100644 --- a/pr_agent/tools/pr_generate_labels.py +++ b/pr_agent/tools/pr_generate_labels.py @@ -35,7 +35,8 @@ class PRGenerateLabels: # Initialize the AI handler self.ai_handler = ai_handler() - + self.ai_handler.main_pr_language = self.main_pr_language + # Initialize the variables dictionary self.vars = { "title": self.git_provider.pr.title, diff --git a/pr_agent/tools/pr_information_from_user.py b/pr_agent/tools/pr_information_from_user.py index 1523d737..03537181 100644 --- a/pr_agent/tools/pr_information_from_user.py +++ b/pr_agent/tools/pr_information_from_user.py @@ -21,6 +21,8 @@ class PRInformationFromUser: self.git_provider.get_languages(), self.git_provider.get_files() ) self.ai_handler = ai_handler() + self.ai_handler.main_pr_language = self.main_pr_language + self.vars = { "title": self.git_provider.pr.title, "branch": self.git_provider.get_pr_branch(), diff --git a/pr_agent/tools/pr_line_questions.py b/pr_agent/tools/pr_line_questions.py index e6386fd1..e26e06d5 100644 --- a/pr_agent/tools/pr_line_questions.py +++ b/pr_agent/tools/pr_line_questions.py @@ -22,8 +22,11 @@ class PR_LineQuestions: def __init__(self, pr_url: str, args=None, ai_handler: partial[BaseAiHandler,] = LiteLLMAIHandler): self.question_str = self.parse_args(args) self.git_provider = get_git_provider()(pr_url) - + self.main_pr_language = get_main_pr_language( + self.git_provider.get_languages(), self.git_provider.get_files() + ) self.ai_handler = ai_handler() + self.ai_handler.main_pr_language = self.main_pr_language self.vars = { "title": self.git_provider.pr.title, diff --git a/pr_agent/tools/pr_questions.py b/pr_agent/tools/pr_questions.py index 7d789e2b..3849029d 100644 --- a/pr_agent/tools/pr_questions.py +++ b/pr_agent/tools/pr_questions.py @@ -22,6 +22,8 @@ class PRQuestions: self.git_provider.get_languages(), self.git_provider.get_files() ) self.ai_handler = ai_handler() + self.ai_handler.main_pr_language = self.main_pr_language + self.question_str = question_str self.vars = { "title": self.git_provider.pr.title, diff --git a/pr_agent/tools/pr_reviewer.py b/pr_agent/tools/pr_reviewer.py index 19f9a163..f0475b82 100644 --- a/pr_agent/tools/pr_reviewer.py +++ b/pr_agent/tools/pr_reviewer.py @@ -46,6 +46,8 @@ class PRReviewer: if self.is_answer and not self.git_provider.is_supported("get_issue_comments"): raise Exception(f"Answer mode is not supported for {get_settings().config.git_provider} for now") self.ai_handler = ai_handler() + self.ai_handler.main_pr_language = self.main_language + self.patches_diff = None self.prediction = None diff --git a/pr_agent/tools/pr_update_changelog.py b/pr_agent/tools/pr_update_changelog.py index 4e168d5d..399e0599 100644 --- a/pr_agent/tools/pr_update_changelog.py +++ b/pr_agent/tools/pr_update_changelog.py @@ -26,7 +26,10 @@ class PRUpdateChangelog: ) self.commit_changelog = get_settings().pr_update_changelog.push_changelog_changes self._get_changlog_file() # self.changelog_file_str + self.ai_handler = ai_handler() + self.ai_handler.main_pr_language = self.main_language + self.patches_diff = None self.prediction = None self.cli_mode = cli_mode From 669e0769380f88bb00ac8ace34bcd050bdd4482f Mon Sep 17 00:00:00 2001 From: mrT23 Date: Sat, 16 Mar 2024 13:52:02 +0200 Subject: [PATCH 016/226] Enhance AI handler logging and add main PR language attribute to AI handler in various tools --- .../algo/ai_handlers/litellm_ai_handler.py | 24 +++++++++++-------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/pr_agent/algo/ai_handlers/litellm_ai_handler.py b/pr_agent/algo/ai_handlers/litellm_ai_handler.py index 666db1b1..527a20a8 100644 --- a/pr_agent/algo/ai_handlers/litellm_ai_handler.py +++ b/pr_agent/algo/ai_handlers/litellm_ai_handler.py @@ -73,6 +73,18 @@ class LiteLLMAIHandler(BaseAiHandler): region_name=get_settings().aws.bedrock_region, ) + def prepare_logs(self, response, system, user, resp, finish_reason): + response_log = response.dict().copy() + response_log['system'] = system + response_log['user'] = user + response_log['output'] = resp + response_log['finish_reason'] = finish_reason + if hasattr(self, 'main_pr_language'): + response_log['main_pr_language'] = self.main_pr_language + else: + response_log['main_pr_language'] = 'unknown' + return response_log + @property def deployment_id(self): """ @@ -127,16 +139,8 @@ class LiteLLMAIHandler(BaseAiHandler): finish_reason = response["choices"][0]["finish_reason"] get_logger().debug(f"\nAI response:\n{resp}") - # log the full response for debugging, including the system and user prompts - response_log = response.dict() - response_log['system'] = system - response_log['user'] = user - response_log['output'] = resp - response_log['finish_reason'] = finish_reason - if hasattr(self, 'main_pr_language'): - response_log['main_pr_language'] = self.main_pr_language - else: - response_log['main_pr_language'] = 'unknown' + # log the full response for debugging + response_log = self.prepare_logs(response, system, user, resp, finish_reason) get_logger().debug("Full_response", artifact=response_log) # for CLI debugging From 6d39773a17473e399129da794621bef70cac447e Mon Sep 17 00:00:00 2001 From: mrT23 Date: Sun, 17 Mar 2024 09:12:49 +0200 Subject: [PATCH 017/226] prompt --- pr_agent/algo/utils.py | 5 +++-- pr_agent/settings/pr_reviewer_prompts.toml | 10 +++++----- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/pr_agent/algo/utils.py b/pr_agent/algo/utils.py index d9365546..2530e064 100644 --- a/pr_agent/algo/utils.py +++ b/pr_agent/algo/utils.py @@ -159,7 +159,8 @@ def convert_to_markdown(output_data: dict, gfm_supported: bool = True, increment def process_can_be_split(emoji, value): - key_nice = "Can this PR be split?" + # key_nice = "Can this PR be split?" + key_nice = "Multiple PR themes" markdown_text = "" if not value or isinstance(value, list) and len(value) == 1: value = "No" @@ -171,7 +172,7 @@ def process_can_be_split(emoji, value): title = split.get('title', '') relevant_files = split.get('relevant_files', []) if i == 0: - markdown_text += f"
\nSub PR theme: {title}\n\n" + markdown_text += f"
\nSub-PR theme: {title}\n\n" markdown_text += f"
\n" markdown_text += f"Relevant files:\n" markdown_text += f"
    \n" diff --git a/pr_agent/settings/pr_reviewer_prompts.toml b/pr_agent/settings/pr_reviewer_prompts.toml index d8b1e1d4..aeeef5f8 100644 --- a/pr_agent/settings/pr_reviewer_prompts.toml +++ b/pr_agent/settings/pr_reviewer_prompts.toml @@ -51,8 +51,8 @@ The output must be a YAML object equivalent to type $PRReview, according to the ===== {%- if require_can_be_split_review %} class SubPR(BaseModel): - title: str = Field(description="short and concise title for a sub-PR composed only from the relevant files") - relevant_files: List[str] = Field(description="the relevant files of the sub-PR") + relevant_files: List[str] = Field(description="The relevant files of the sub-PR") + title: str = Field(description="Short and concise title for an independent and meaningful sub-PR, composed only from the relevant files") {%- endif %} class Review(BaseModel): @@ -71,7 +71,7 @@ class Review(BaseModel): possible_issues: str = Field(description="Does this PR code introduce clear issues, bugs, or major performance concerns? If there are no apparent issues, respond with 'No'. If there are any issues, describe them briefly. Use bullet points if more than one issue. Be specific, and provide examples if possible. Start each bullet point with a short specific header, such as: "- Possible Bug: ...", etc.") security_concerns: str = Field(description="does this PR code introduce possible vulnerabilities such as exposure of sensitive information (e.g., API keys, secrets, passwords), or security concerns like SQL injection, XSS, CSRF, and others ? Answer 'No' if there are no possible issues. If there are security concerns or issues, start your answer with a short header, such as: 'Sensitive information exposure: ...', 'SQL injection: ...' etc. Explain your answer. Be specific and give examples if possible") {%- if require_can_be_split_review %} - can_be_split: List[SubPR] = Field(description="Can this PR, with its {{ num_pr_files }} changed files, be clearly split into smaller sub-PRs, that can be reviewed and merged independently, regardless of the order ? If yes, provide a title and list the relevant files for each sub-PR. Make sure that the sub-PRs are indeed independent, without any code dependencies between them. Try not to create too many sub-PRs. For example, logic changes and corresponding documentation should be grouped together. Output empty list if the PR cannot be split.") + can_be_split: List[SubPR] = Field(min_items=0, max_items=3, description="Can this PR, which contains {{ num_pr_files }} changed files in total, be divided into smaller sub-PRs with distinct tasks that can be reviewed and merged independently, regardless of the order ? Make sure that the sub-PRs are indeed independent, with no code dependencies between them, and that each sub-PR represent a meaningfull independent task. Output an empty list if the PR code does not needd to be split.") {%- endif %} {%- if num_code_suggestions > 0 %} @@ -112,11 +112,11 @@ review: No {%- if require_can_be_split_review %} can_be_split: | - title: | - ... - relevant_files: - ... - ... + title: ... + - ... {%- endif %} {%- if num_code_suggestions > 0 %} code_feedback From 498b4cb34e2f889f5c636d6f6f6adf192122d125 Mon Sep 17 00:00:00 2001 From: mrT23 Date: Sun, 17 Mar 2024 09:59:55 +0200 Subject: [PATCH 018/226] readme --- README.md | 5 +++++ pr_agent/algo/utils.py | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index da5159c4..a49077c7 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,11 @@ Making pull requests less painful with an AI agent ## News and Updates +### Jan 17, 2024 +- A new feature is not available for the review tool: [`require_can_be_split_review`](https://pr-agent-docs.codium.ai/tools/review/#enabledisable-features). If set to true, the tool will add a section that checks if the PR contains several themes, and can be split into smaller PRs. + + + ### Jan 10, 2024 - A new [knowledge-base website](https://pr-agent-docs.codium.ai/) for PR-Agent is now available. It includes detailed information about the different tools, usage guides and more, in an accessible and organized format. diff --git a/pr_agent/algo/utils.py b/pr_agent/algo/utils.py index 2530e064..c2b6323c 100644 --- a/pr_agent/algo/utils.py +++ b/pr_agent/algo/utils.py @@ -180,7 +180,7 @@ def process_can_be_split(emoji, value): markdown_text += f"
  • {file}
  • \n" markdown_text += f"
\n\n
\n" else: - markdown_text += f"\n
\nSub PR theme: {title}\n\n" + markdown_text += f"\n
\nSub-PR theme: {title}\n\n" markdown_text += f"
\n" markdown_text += f"Relevant files:\n" markdown_text += f"
    \n" From ac2c06219043866bbbb464cf615a63d5c5f4c046 Mon Sep 17 00:00:00 2001 From: mrT23 Date: Sun, 17 Mar 2024 10:01:30 +0200 Subject: [PATCH 019/226] readme --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index a49077c7..ad3c0407 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,8 @@ Making pull requests less painful with an AI agent ## News and Updates ### Jan 17, 2024 -- A new feature is not available for the review tool: [`require_can_be_split_review`](https://pr-agent-docs.codium.ai/tools/review/#enabledisable-features). If set to true, the tool will add a section that checks if the PR contains several themes, and can be split into smaller PRs. +- A new feature is now available for the review tool: [`require_can_be_split_review`](https://pr-agent-docs.codium.ai/tools/review/#enabledisable-features). +If set to true, the tool will add a section that checks if the PR contains several themes, and can be split into smaller PRs. From b6dd57375f9f4e2943c12ae4dd63857cc87ebad1 Mon Sep 17 00:00:00 2001 From: mrT23 Date: Sun, 17 Mar 2024 11:39:10 +0200 Subject: [PATCH 020/226] Initialize current_labels to empty list if no labels exist in pr_reviewer.py --- pr_agent/tools/pr_reviewer.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pr_agent/tools/pr_reviewer.py b/pr_agent/tools/pr_reviewer.py index 19d1bb94..4d1739a5 100644 --- a/pr_agent/tools/pr_reviewer.py +++ b/pr_agent/tools/pr_reviewer.py @@ -373,6 +373,8 @@ class PRReviewer: review_labels.append('Possible security concern') current_labels = self.git_provider.get_pr_labels(update=True) + if not current_labels: + current_labels = [] get_logger().debug(f"Current labels:\n{current_labels}") if current_labels: current_labels_filtered = [label for label in current_labels if From 8ccb998b82ee3f902e7a82b965b93fc30d5c254d Mon Sep 17 00:00:00 2001 From: mrT23 Date: Sun, 17 Mar 2024 13:11:08 +0200 Subject: [PATCH 021/226] Refactor PR-Agent Pro installation documentation and update navigation links --- docs/docs/installation/index.md | 9 +++++--- .../{gitlab_pro.md => pr_agent_pro.md} | 23 ++++++++++++++++++- docs/mkdocs.yml | 2 +- 3 files changed, 29 insertions(+), 5 deletions(-) rename docs/docs/installation/{gitlab_pro.md => pr_agent_pro.md} (51%) diff --git a/docs/docs/installation/index.md b/docs/docs/installation/index.md index 18b7b056..fc71ecbb 100644 --- a/docs/docs/installation/index.md +++ b/docs/docs/installation/index.md @@ -1,5 +1,6 @@ # Installation +## self-hosted PR-Agent If you choose to host you own PR-Agent, you first need to acquire two tokens: 1. An OpenAI key from [here](https://platform.openai.com/api-keys), with access to GPT-4 (or a key for [other models](../usage-guide/additional_configurations.md/#changing-a-model), if you prefer). @@ -13,7 +14,9 @@ There are several ways to use self-hosted PR-Agent: - [BitBucket](./bitbucket.md) - [Azure DevOps](./azure.md) -___ -Note that [PR-Agent Pro ๐Ÿ’Ž](https://app.codium.ai/), an app for GitHub\GitLab\BitBucket hosted by CodiumAI, is also available. +## PR-Agent Pro ๐Ÿ’Ž +PR-Agent Pro, an app for GitHub\GitLab\BitBucket hosted by CodiumAI, is also available.
    -With PR-Agent Pro Installation is as simple as signing up and adding the PR-Agent app to your relevant repo. \ No newline at end of file +With PR-Agent Pro Installation is as simple as signing up and adding the PR-Agent app to your relevant repo. +
    +See [here](./pr_agent_pro.md) for more details. \ No newline at end of file diff --git a/docs/docs/installation/gitlab_pro.md b/docs/docs/installation/pr_agent_pro.md similarity index 51% rename from docs/docs/installation/gitlab_pro.md rename to docs/docs/installation/pr_agent_pro.md index 20902b74..d7877fb5 100644 --- a/docs/docs/installation/gitlab_pro.md +++ b/docs/docs/installation/pr_agent_pro.md @@ -1,4 +1,25 @@ -## Install Hosted PR-Agent Pro for GitLab (Teams & Enterprise) + +PR-Agent Pro is a versatile application compatible with GitHub, GitLab, and BitBucket, hosted by CodiumAI. +See [here](./https://pr-agent-docs.codium.ai/#pr-agent-pro) for more details about the benefits of using PR-Agent Pro. + +Interested parties can subscribe to PR-Agent Pro through the following [link](https://www.codium.ai/pricing/). +After subscribing, you are granted the ability to install the application across any of your repositories. + + + + + +Each user who wants to use PR-Agent pro needs to buy a seat. +Initially, CodiumAI offers a two-week trial period at no cost, after which continued access requires each user to secure a personal seat. +Once a user acquires a seat, they gain the flexibility to use PR-Agent Pro across any repository where it has been enabled. + +Users without a purchased seat who interact with a repository featuring PR-Agent Pro are entitled to receive up to five complimentary feedbacks. +Beyond this limit, PR-Agent Pro will cease to respond to their inquiries unless a seat is purchased. + + +## Install PR-Agent Pro for GitLab (Teams & Enterprise) + +Since GitLab platform does not support apps, installing PR-Agent Pro for GitLab is a bit more involved, and requires the following steps: ### Step 1 diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index 8da53d48..c3e10abd 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -7,9 +7,9 @@ nav: - Locally: 'installation/locally.md' - GitHub: 'installation/github.md' - GitLab: 'installation/gitlab.md' - - ๐Ÿ’Ž GitLab Pro: 'installation/gitlab_pro.md' - BitBucket: 'installation/bitbucket.md' - Azure DevOps: 'installation/azure.md' + - ๐Ÿ’Ž PR-Agent Pro: 'installation/pr_agent_pro.md' - Usage Guide: - 'usage-guide/index.md' - Introduction: 'usage-guide/introduction.md' From 1db03ccc360a3f943b283243ca3a1a3decb58a4f Mon Sep 17 00:00:00 2001 From: mrT23 Date: Sun, 17 Mar 2024 13:15:21 +0200 Subject: [PATCH 022/226] Refactor PR-Agent Pro installation documentation and update navigation links --- docs/docs/installation/pr_agent_pro.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/docs/installation/pr_agent_pro.md b/docs/docs/installation/pr_agent_pro.md index d7877fb5..cb371df7 100644 --- a/docs/docs/installation/pr_agent_pro.md +++ b/docs/docs/installation/pr_agent_pro.md @@ -1,9 +1,11 @@ +## Getting Started with PR-Agent Pro + PR-Agent Pro is a versatile application compatible with GitHub, GitLab, and BitBucket, hosted by CodiumAI. -See [here](./https://pr-agent-docs.codium.ai/#pr-agent-pro) for more details about the benefits of using PR-Agent Pro. +See [here](https://pr-agent-docs.codium.ai/#pr-agent-pro) for more details about the benefits of using PR-Agent Pro. Interested parties can subscribe to PR-Agent Pro through the following [link](https://www.codium.ai/pricing/). -After subscribing, you are granted the ability to install the application across any of your repositories. +After subscribing, you are granted the ability to easily install the application across any of your repositories. @@ -11,7 +13,7 @@ After subscribing, you are granted the ability to install the application across Each user who wants to use PR-Agent pro needs to buy a seat. Initially, CodiumAI offers a two-week trial period at no cost, after which continued access requires each user to secure a personal seat. -Once a user acquires a seat, they gain the flexibility to use PR-Agent Pro across any repository where it has been enabled. +Once a user acquires a seat, they gain the flexibility to use PR-Agent Pro across any repository where it was enabled. Users without a purchased seat who interact with a repository featuring PR-Agent Pro are entitled to receive up to five complimentary feedbacks. Beyond this limit, PR-Agent Pro will cease to respond to their inquiries unless a seat is purchased. From 008ee0dbc2a6d6b02977e49a4319d8b8a11bc850 Mon Sep 17 00:00:00 2001 From: Almog Lavi Date: Sun, 17 Mar 2024 13:17:01 +0200 Subject: [PATCH 023/226] Replace checkmark emojis with tick emojis in documentation --- docs/docs/index.md | 52 +++++++++++++++++++++++----------------------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/docs/docs/index.md b/docs/docs/index.md index caa52ded..ed02e502 100644 --- a/docs/docs/index.md +++ b/docs/docs/index.md @@ -14,34 +14,34 @@ PR-Agent offers extensive pull request functionalities across various git provid | | | GitHub | Gitlab | Bitbucket | Azure DevOps | |-------|---------------------------------------------------------------------------------------------------------------------|:------:|:------:|:---------:|:------------:| -| TOOLS | Review | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | -| | โฎ‘ Incremental | โœ”๏ธ | | | | -| | โฎ‘ [SOC2 Compliance](https://pr-agent-docs.codium.ai/tools/review/#soc2-ticket-compliance){:target="_blank"} ๐Ÿ’Ž | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | -| | Ask | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | -| | Describe | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | -| | โฎ‘ [Inline file summary](https://pr-agent-docs.codium.ai/tools/describe/#inline-file-summary){:target="_blank"} ๐Ÿ’Ž | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | -| | Improve | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | -| | โฎ‘ Extended | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | -| | [Custom Suggestions](./tools/custom_suggestions.md){:target="_blank"} ๐Ÿ’Ž | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | -| | Reflect and Review | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | -| | Update CHANGELOG.md | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | ๏ธ | -| | Find Similar Issue | โœ”๏ธ | | | ๏ธ | -| | [Add PR Documentation](./tools/documentation.md){:target="_blank"} ๐Ÿ’Ž | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | -| | [Generate Custom Labels](./tools/describe.md#handle-custom-labels-from-the-repos-labels-page-๐Ÿ’Ž){:target="_blank"} ๐Ÿ’Ž | โœ”๏ธ | โœ”๏ธ | | โœ”๏ธ | -| | [Analyze PR Components](./tools/analyze.md){:target="_blank"} ๐Ÿ’Ž | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | +| TOOLS | Review | โœ… | โœ… | โœ… | โœ… | +| | โฎ‘ Incremental | โœ… | | | | +| | โฎ‘ [SOC2 Compliance](https://pr-agent-docs.codium.ai/tools/review/#soc2-ticket-compliance){:target="_blank"} ๐Ÿ’Ž | โœ… | โœ… | โœ… | โœ… | +| | Ask | โœ… | โœ… | โœ… | โœ… | +| | Describe | โœ… | โœ… | โœ… | โœ… | +| | โฎ‘ [Inline file summary](https://pr-agent-docs.codium.ai/tools/describe/#inline-file-summary){:target="_blank"} ๐Ÿ’Ž | โœ… | โœ… | โœ… | โœ… | +| | Improve | โœ… | โœ… | โœ… | โœ… | +| | โฎ‘ Extended | โœ… | โœ… | โœ… | โœ… | +| | [Custom Suggestions](./tools/custom_suggestions.md){:target="_blank"} ๐Ÿ’Ž | โœ… | โœ… | โœ… | โœ… | +| | Reflect and Review | โœ… | โœ… | โœ… | โœ… | +| | Update CHANGELOG.md | โœ… | โœ… | โœ… | ๏ธ | +| | Find Similar Issue | โœ… | | | ๏ธ | +| | [Add PR Documentation](./tools/documentation.md){:target="_blank"} ๐Ÿ’Ž | โœ… | โœ… | โœ… | โœ… | +| | [Generate Custom Labels](./tools/describe.md#handle-custom-labels-from-the-repos-labels-page-๐Ÿ’Ž){:target="_blank"} ๐Ÿ’Ž | โœ… | โœ… | | โœ… | +| | [Analyze PR Components](./tools/analyze.md){:target="_blank"} ๐Ÿ’Ž | โœ… | โœ… | โœ… | โœ… | | | | | | | ๏ธ | -| USAGE | CLI | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | -| | App / webhook | โœ”๏ธ | โœ”๏ธ | | โœ”๏ธ | -| | Tagging bot | โœ”๏ธ | | | โœ”๏ธ | -| | Actions | โœ”๏ธ | | | ๏ธ | +| USAGE | CLI | โœ… | โœ… | โœ… | โœ… | +| | App / webhook | โœ… | โœ… | | โœ… | +| | Tagging bot | โœ… | | | โœ… | +| | Actions | โœ… | | | ๏ธ | | | | | | | -| CORE | PR compression | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | -| | Repo language prioritization | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | -| | Adaptive and token-aware file patch fitting | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | -| | Multiple models support | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | -| | Incremental PR review | โœ”๏ธ | | | | -| | [Static code analysis](./tools/analyze.md/){:target="_blank"} ๐Ÿ’Ž | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | -| | [Multiple configuration options](./usage-guide/configuration_options.md){:target="_blank"} ๐Ÿ’Ž | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | โœ”๏ธ | +| CORE | PR compression | โœ… | โœ… | โœ… | โœ… | +| | Repo language prioritization | โœ… | โœ… | โœ… | โœ… | +| | Adaptive and token-aware file patch fitting | โœ… | โœ… | โœ… | โœ… | +| | Multiple models support | โœ… | โœ… | โœ… | โœ… | +| | Incremental PR review | โœ… | | | | +| | [Static code analysis](./tools/analyze.md/){:target="_blank"} ๐Ÿ’Ž | โœ… | โœ… | โœ… | โœ… | +| | [Multiple configuration options](./usage-guide/configuration_options.md){:target="_blank"} ๐Ÿ’Ž | โœ… | โœ… | โœ… | โœ… | ๐Ÿ’Ž marks a feature available only in [PR-Agent Pro](https://www.codium.ai/pricing/){:target="_blank"} From 80a793a2579dbed2d24d8ce4ebaa3b7af001d40a Mon Sep 17 00:00:00 2001 From: koid Date: Mon, 18 Mar 2024 15:30:16 +0900 Subject: [PATCH 024/226] ignore bot pr option on github app mode --- pr_agent/servers/github_app.py | 6 ++++++ pr_agent/settings/configuration.toml | 1 + 2 files changed, 7 insertions(+) diff --git a/pr_agent/servers/github_app.py b/pr_agent/servers/github_app.py index fbe9db0f..5cbf3175 100644 --- a/pr_agent/servers/github_app.py +++ b/pr_agent/servers/github_app.py @@ -121,6 +121,12 @@ async def handle_new_pr_opened(body: Dict[str, Any], action: str, log_context: Dict[str, Any], agent: PRAgent): + # logic to ignore PRs opened by bot + if get_settings().get("GITHUB_APP.IGNORE_BOT_PR", False): + if re.match('.+\[bot]$', sender) is not None: + get_logger().info(f"Ignoring PR by sender '{sender}' due to github_app.ignore_bot_pr setting") + return {} + title = body.get("pull_request", {}).get("title", "") # logic to ignore PRs with specific titles (e.g. "[Auto] ...") diff --git a/pr_agent/settings/configuration.toml b/pr_agent/settings/configuration.toml index 21ad264b..a1a30ef3 100644 --- a/pr_agent/settings/configuration.toml +++ b/pr_agent/settings/configuration.toml @@ -155,6 +155,7 @@ push_commands = [ "/review --pr_reviewer.num_code_suggestions=0", ] ignore_pr_title = [] +ignore_bot_pr = false [gitlab] url = "https://gitlab.com" # URL to the gitlab service From b71523f13e4ededa7582734e8dba3ac1039eff4f Mon Sep 17 00:00:00 2001 From: koid Date: Mon, 18 Mar 2024 15:42:13 +0900 Subject: [PATCH 025/226] use endswith --- pr_agent/servers/github_app.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pr_agent/servers/github_app.py b/pr_agent/servers/github_app.py index 5cbf3175..ed6e1e73 100644 --- a/pr_agent/servers/github_app.py +++ b/pr_agent/servers/github_app.py @@ -123,7 +123,7 @@ async def handle_new_pr_opened(body: Dict[str, Any], agent: PRAgent): # logic to ignore PRs opened by bot if get_settings().get("GITHUB_APP.IGNORE_BOT_PR", False): - if re.match('.+\[bot]$', sender) is not None: + if sender.endswith('[bot]'): get_logger().info(f"Ignoring PR by sender '{sender}' due to github_app.ignore_bot_pr setting") return {} From d9bf931a58fd88c00186900e6ff3bcf6ac7ace4e Mon Sep 17 00:00:00 2001 From: mrT23 Date: Tue, 19 Mar 2024 08:59:49 +0200 Subject: [PATCH 026/226] Update describe.md: Improve image formatting, restructure content, and enhance descriptions --- docs/docs/tools/describe.md | 164 ++++++++++++++++++++++-------------- 1 file changed, 101 insertions(+), 63 deletions(-) diff --git a/docs/docs/tools/describe.md b/docs/docs/tools/describe.md index bb676f86..b92dae30 100644 --- a/docs/docs/tools/describe.md +++ b/docs/docs/tools/describe.md @@ -7,63 +7,85 @@ The tool can be triggered automatically every time a new PR is [opened](../usage ``` For example: - + + + + + - + + + + + ## Configuration options + +### General configurations To edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/configuration.toml#L46) related to the describe tool (`pr_description` section), use the following template: ``` /describe --pr_description.some_config1=... --pr_description.some_config2=... ``` -### Possible configurations: +!!! example "Possible configurations" -- `publish_labels`: if set to true, the tool will publish the labels to the PR. Default is true. + - `publish_labels`: if set to true, the tool will publish the labels to the PR. Default is true. -- `publish_description_as_comment`: if set to true, the tool will publish the description as a comment to the PR. If false, it will overwrite the origianl description. Default is false. + - `publish_description_as_comment`: if set to true, the tool will publish the description as a comment to the PR. If false, it will overwrite the origianl description. Default is false. -- `add_original_user_description`: if set to true, the tool will add the original user description to the generated description. Default is true. + - `add_original_user_description`: if set to true, the tool will add the original user description to the generated description. Default is true. -- `keep_original_user_title`: if set to true, the tool will keep the original PR title, and won't change it. Default is true. + - `keep_original_user_title`: if set to true, the tool will keep the original PR title, and won't change it. Default is true. -- `extra_instructions`: Optional extra instructions to the tool. For example: "focus on the changes in the file X. Ignore change in ...". + - `extra_instructions`: Optional extra instructions to the tool. For example: "focus on the changes in the file X. Ignore change in ...". -- To enable `custom labels`, apply the configuration changes described [here](./custom_labels.md#configuration-options) + - To enable `custom labels`, apply the configuration changes described [here](./custom_labels.md#configuration-options) -- `enable_pr_type`: if set to false, it will not show the `PR type` as a text value in the description content. Default is true. + - `enable_pr_type`: if set to false, it will not show the `PR type` as a text value in the description content. Default is true. -- `final_update_message`: if set to true, it will add a comment message [`PR Description updated to latest commit...`](https://github.com/Codium-ai/pr-agent/pull/499#issuecomment-1837412176) after finishing calling `/describe`. Default is true. + - `final_update_message`: if set to true, it will add a comment message [`PR Description updated to latest commit...`](https://github.com/Codium-ai/pr-agent/pull/499#issuecomment-1837412176) after finishing calling `/describe`. Default is true. -- `enable_semantic_files_types`: if set to true, "Changes walkthrough" section will be generated. Default is true. -- `collapsible_file_list`: if set to true, the file list in the "Changes walkthrough" section will be collapsible. If set to "adaptive", the file list will be collapsible only if there are more than 8 files. Default is "adaptive". + - `enable_semantic_files_types`: if set to true, "Changes walkthrough" section will be generated. Default is true. + - `collapsible_file_list`: if set to true, the file list in the "Changes walkthrough" section will be collapsible. If set to "adaptive", the file list will be collapsible only if there are more than 8 files. Default is "adaptive". ### Inline file summary ๐Ÿ’Ž -> This feature is available only in PR-Agent Pro -This feature will enable you to quickly understand the changes in each file while reviewing the code changes (diff view). +This feature enables you to copy the `changes walkthrough` table to the "Files changed" tab, so you can quickly understand the changes in each file while reviewing the code changes (diff view). -To add the walkthrough table to the "Files changed" tab, you can click on the checkbox that appears PR Description status message below the main PR Description: +To copy the `changes walkthrough` table to the "Files changed" tab, you can click on the checkbox that appears PR Description status message below the main PR Description: - + + + + + If you prefer to have the file summaries appear in the "Files changed" tab on every PR, change the `pr_description.inline_file_summary` parameter in the configuration file, possible values are: - `'table'`: File changes walkthrough table will be displayed on the top of the "Files changed" tab, in addition to the "Conversation" tab. - + + + + + + - `true`: A collapsable file comment with changes title and a changes summary for each file in the PR. - + + + + + + - `false` (`default`): File changes walkthrough will be added only to the "Conversation" tab. -**Note** that this feature is currently available only for GitHub. +**Note**: that this feature is currently available only for GitHub. ### Handle custom labels from the Repo's labels page ๐Ÿ’Ž -> This feature is available only in PR-Agent Pro You can control the custom labels that will be suggested by the `describe` tool, from the repo's labels page: @@ -71,11 +93,16 @@ You can control the custom labels that will be suggested by the `describe` tool * GitLab : go to `https://gitlab.com/{owner}/{repo}/-/labels` (or click on "Manage" -> "Labels" on the left menu) Now add/edit the custom labels. they should be formatted as follows: + * Label name: The name of the custom label. * Description: Start the description of with prefix `pr_agent:`, for example: `pr_agent: Description of when AI should suggest this label`.
    The description should be comprehensive and detailed, indicating when to add the desired label. For example: - + + + + + ### Markers template @@ -98,11 +125,21 @@ pr_agent:walkthrough ``` The marker `pr_agent:type` will be replaced with the PR type, `pr_agent:summary` will be replaced with the PR summary, and `pr_agent:walkthrough` will be replaced with the PR walkthrough. - -→ - + + + + + -### Configuration params: +→ + + + + + + + +**Configuration params**: - `use_description_markers`: if set to true, the tool will use markers template. It replaces every marker of the form `pr_agent:marker_name` with the relevant content. Default is false. - `include_generated_by_header`: if set to true, the tool will add a dedicated header: 'Generated by PR Agent at ...' to any automatic content. Default is true. @@ -110,44 +147,45 @@ The marker `pr_agent:type` will be replaced with the PR type, `pr_agent:summary` ## Usage Tips -### Automation -- When you first install the app, the [default mode](../usage-guide/automations_and_usage.md#github-app) for the describe tool is: -``` -pr_commands = ["/describe --pr_description.add_original_user_description=true" - "--pr_description.keep_original_user_title=true", ...] -``` -meaning the `describe` tool will run automatically on every PR, will keep the original title, and will add the original user description above the generated description. -
    This default settings aim to strike a good balance between automation and control: -If you want more automation, just give the PR a title, and the tool will auto-write a full description; If you want more control, you can add a detailed description, and the tool will add the complementary description below it. -- For maximal automation, you can change the default mode to: -``` -pr_commands = ["/describe --pr_description.add_original_user_description=false" - "--pr_description.keep_original_user_title=true", ...] -``` -so the title will be auto-generated as well. -- Markers are an alternative way to control the generated description, to give maximal control to the user. If you set: -``` -pr_commands = ["/describe --pr_description.use_description_markers=true", ...] -``` -the tool will replace every marker of the form `pr_agent:marker_name` in the PR description with the relevant content, where `marker_name` is one of the following: - - `type`: the PR type. - - `summary`: the PR summary. - - `walkthrough`: the PR walkthrough. +!!! tip "Automation" + - When you first install PR-Agent app, the [default mode](../usage-guide/automations_and_usage.md#github-app) for the describe tool is: + ``` + pr_commands = ["/describe --pr_description.add_original_user_description=true" + "--pr_description.keep_original_user_title=true", ...] + ``` + meaning the `describe` tool will run automatically on every PR, will keep the original title, and will add the original user description above the generated description. +
    This default settings aim to strike a good balance between automation and control: + - If you want more automation, just give the PR a title, and the tool will auto-write a full description; If you want more control, you can add a detailed description, and the tool will add the complementary description below it. + - For maximal automation, you can change the default mode to: + ``` + pr_commands = ["/describe --pr_description.add_original_user_description=false" + "--pr_description.keep_original_user_title=true", ...] + ``` + so the title will be auto-generated as well. + - Markers are an alternative way to control the generated description, to give maximal control to the user. If you set: + ``` + pr_commands = ["/describe --pr_description.use_description_markers=true", ...] + ``` + the tool will replace every marker of the form `pr_agent:marker_name` in the PR description with the relevant content, where `marker_name` is one of the following: + * `type`: the PR type. + * `summary`: the PR summary. + * `walkthrough`: the PR walkthrough. -Note that when markers are enabled, if the original PR description does not contain any markers, the tool will not alter the description at all. + - Note that when markers are enabled, if the original PR description does not contain any markers, the tool will not alter the description at all. -### Custom labels +!!! tip "Custom labels" -The default labels of the describe tool are quite generic, since they are meant to be used in any repo: [`Bug fix`, `Tests`, `Enhancement`, `Documentation`, `Other`]. + The default labels of the describe tool are quite generic, since they are meant to be used in any repo: [`Bug fix`, `Tests`, `Enhancement`, `Documentation`, `Other`]. + + If you specify [custom labels](#handle-custom-labels-from-the-repos-labels-page) in the repo's labels page, you can get tailored labels for your use cases. + Examples for custom labels: -If you specify [custom labels](#handle-custom-labels-from-the-repos-labels-page) in the repo's labels page, you can get tailored labels for your use cases. -Examples for custom labels: -- `Main topic:performance` - pr_agent:The main topic of this PR is performance -- `New endpoint` - pr_agent:A new endpoint was added in this PR -- `SQL query` - pr_agent:A new SQL query was added in this PR -- `Dockerfile changes` - pr_agent:The PR contains changes in the Dockerfile -- ... - -The list above is eclectic, and aims to give an idea of different possibilities. Define custom labels that are relevant for your repo and use cases. -Note that Labels are not mutually exclusive, so you can add multiple label categories. -
    Make sure to provide proper title, and a detailed and well-phrased description for each label, so the tool will know when to suggest it. \ No newline at end of file + - `Main topic:performance` - pr_agent:The main topic of this PR is performance + - `New endpoint` - pr_agent:A new endpoint was added in this PR + - `SQL query` - pr_agent:A new SQL query was added in this PR + - `Dockerfile changes` - pr_agent:The PR contains changes in the Dockerfile + - ... + + The list above is eclectic, and aims to give an idea of different possibilities. Define custom labels that are relevant for your repo and use cases. + Note that Labels are not mutually exclusive, so you can add multiple label categories. +
    Make sure to provide proper title, and a detailed and well-phrased description for each label, so the tool will know when to suggest it. \ No newline at end of file From edb59744ec49c20ec7fb37b0a6c196acb82eab31 Mon Sep 17 00:00:00 2001 From: mrT23 Date: Tue, 19 Mar 2024 09:03:50 +0200 Subject: [PATCH 027/226] Update describe.md: Improve image formatting, restructure content, and enhance descriptions --- docs/docs/tools/describe.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/docs/tools/describe.md b/docs/docs/tools/describe.md index b92dae30..33c96e96 100644 --- a/docs/docs/tools/describe.md +++ b/docs/docs/tools/describe.md @@ -9,13 +9,13 @@ For example: - + - + @@ -33,7 +33,7 @@ To edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agen - `publish_labels`: if set to true, the tool will publish the labels to the PR. Default is true. - - `publish_description_as_comment`: if set to true, the tool will publish the description as a comment to the PR. If false, it will overwrite the origianl description. Default is false. + - `publish_description_as_comment`: if set to true, the tool will publish the description as a comment to the PR. If false, it will overwrite the original description. Default is false. - `add_original_user_description`: if set to true, the tool will add the original user description to the generated description. Default is true. @@ -58,7 +58,7 @@ To copy the `changes walkthrough` table to the "Files changed" tab, you can clic - + @@ -68,7 +68,7 @@ If you prefer to have the file summaries appear in the "Files changed" tab on ev - + @@ -76,7 +76,7 @@ If you prefer to have the file summaries appear in the "Files changed" tab on ev - + @@ -99,8 +99,8 @@ Now add/edit the custom labels. they should be formatted as follows: The description should be comprehensive and detailed, indicating when to add the desired label. For example: - - + + @@ -127,7 +127,7 @@ The marker `pr_agent:type` will be replaced with the PR type, `pr_agent:summary` - + @@ -135,7 +135,7 @@ The marker `pr_agent:type` will be replaced with the PR type, `pr_agent:summary` - + From ae090405431ab27b90555c811a3b2502a5e2e03e Mon Sep 17 00:00:00 2001 From: mrT23 Date: Tue, 19 Mar 2024 09:27:17 +0200 Subject: [PATCH 028/226] Refactor review.md: Improve image formatting, restructure content, and enhance descriptions --- docs/docs/tools/review.md | 235 ++++++++++++++++++++------------------ 1 file changed, 123 insertions(+), 112 deletions(-) diff --git a/docs/docs/tools/review.md b/docs/docs/tools/review.md index 5094f8f3..9a8a1bb6 100644 --- a/docs/docs/tools/review.md +++ b/docs/docs/tools/review.md @@ -6,46 +6,56 @@ The tool can be triggered automatically every time a new PR is [opened](../usage ``` For example: - + + + + + - + + + + + ## Configuration options +### General configurations + To edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/configuration.toml#L19) related to the review tool (`pr_reviewer` section), use the following template: ``` /review --pr_reviewer.some_config1=... --pr_reviewer.some_config2=... ``` -#### General options -- `num_code_suggestions`: number of code suggestions provided by the 'review' tool. For manual comments, default is 4. For [PR-Agent app](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/configuration.toml#L142) auto tools, default is 0, meaning no code suggestions will be provided by the review tool, unless you manually edit `pr_commands`. -- `inline_code_comments`: if set to true, the tool will publish the code suggestions as comments on the code diff. Default is false. -- `persistent_comment`: if set to true, the review comment will be persistent, meaning that every new review request will edit the previous one. Default is true. -- `extra_instructions`: Optional extra instructions to the tool. For example: "focus on the changes in the file X. Ignore change in ...". +!!! example "General options" + - `num_code_suggestions`: number of code suggestions provided by the 'review' tool. For manual comments, default is 4. For [PR-Agent app](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/configuration.toml#L142) auto tools, default is 0, meaning no code suggestions will be provided by the review tool, unless you manually edit `pr_commands`. + - `inline_code_comments`: if set to true, the tool will publish the code suggestions as comments on the code diff. Default is false. + - `persistent_comment`: if set to true, the review comment will be persistent, meaning that every new review request will edit the previous one. Default is true. + - `extra_instructions`: Optional extra instructions to the tool. For example: "focus on the changes in the file X. Ignore change in ...". -#### Enable\\disable features -- `require_focused_review`: if set to true, the tool will add a section - 'is the PR a focused one'. Default is false. -- `require_score_review`: if set to true, the tool will add a section that scores the PR. Default is false. -- `require_tests_review`: if set to true, the tool will add a section that checks if the PR contains tests. Default is true. -- `require_estimate_effort_to_review`: if set to true, the tool will add a section that estimates the effort needed to review the PR. Default is true. +!!! example "Enable\\disable sub-sections" + - `require_score_review`: if set to true, the tool will add a section that scores the PR. Default is false. + - `require_tests_review`: if set to true, the tool will add a section that checks if the PR contains tests. Default is true. + - `require_estimate_effort_to_review`: if set to true, the tool will add a section that estimates the effort needed to review the PR. Default is true. + - `require_can_be_split_review`: if set to true, the tool will add a section that checks if the PR contains several themes, and can be split into smaller PRs. Default is false. -#### SOC2 ticket compliance ๐Ÿ’Ž -> This feature is available only in PR-Agent Pro +!!! example "SOC2 ticket compliance ๐Ÿ’Ž" -This sub-tool checks if the PR description properly contains a ticket to a project management system (e.g., Jira, Asana, Trello, etc.), as required by SOC2 compliance. If not, it will add a label to the PR: "Missing SOC2 ticket". -- `require_soc2_ticket`: If set to true, the SOC2 ticket checker sub-tool will be enabled. Default is false. -- `soc2_ticket_prompt`: The prompt for the SOC2 ticket review. Default is: `Does the PR description include a link to ticket in a project management system (e.g., Jira, Asana, Trello, etc.) ?`. Edit this field if your compliance requirements are different. + This sub-tool checks if the PR description properly contains a ticket to a project management system (e.g., Jira, Asana, Trello, etc.), as required by SOC2 compliance. If not, it will add a label to the PR: "Missing SOC2 ticket". + + - `require_soc2_ticket`: If set to true, the SOC2 ticket checker sub-tool will be enabled. Default is false. + - `soc2_ticket_prompt`: The prompt for the SOC2 ticket review. Default is: `Does the PR description include a link to ticket in a project management system (e.g., Jira, Asana, Trello, etc.) ?`. Edit this field if your compliance requirements are different. -#### Adding PR labels -- `enable_review_labels_security`: if set to true, the tool will publish a 'possible security issue' label if it detects a security issue. Default is true. -- `enable_review_labels_effort`: if set to true, the tool will publish a 'Review effort [1-5]: x' label. Default is true. +!!! example Adding PR labels + - `enable_review_labels_security`: if set to true, the tool will publish a 'possible security issue' label if it detects a security issue. Default is true. + - `enable_review_labels_effort`: if set to true, the tool will publish a 'Review effort [1-5]: x' label. Default is true. -#### Auto-approval -- `enable_auto_approval`: if set to true, the tool will approve the PR when invoked with the 'auto_approve' command. Default is false. This flag can be changed only from configuration file. -- `maximal_review_effort`: maximal effort level for auto-approval. If the PR's estimated review effort is above this threshold, the auto-approval will not run. Default is 5. +!!! example "Auto-approval" + - `enable_auto_approval`: if set to true, the tool will approve the PR when invoked with the 'auto_approve' command. Default is false. This flag can be changed only from configuration file. + - `maximal_review_effort`: maximal effort level for auto-approval. If the PR's estimated review effort is above this threshold, the auto-approval will not run. Default is 5. -#### Incremental Mode +### Incremental Mode Incremental review only considers changes since the last PR-Agent review. This can be useful when working on the PR in an iterative manner, and you want to focus on the changes since the last review instead of reviewing the entire PR again. For invoking the incremental mode, the following command can be used: ``` @@ -53,23 +63,13 @@ For invoking the incremental mode, the following command can be used: ``` Note that the incremental mode is only available for GitHub. - + + + + + -Under the section 'pr_reviewer', the [configuration file](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/configuration.toml#L19) contains options to customize the 'review -i' tool. -These configurations can be used to control the rate at which the incremental review tool will create new review comments when invoked automatically, to prevent making too much noise in the PR. -- `minimal_commits_for_incremental_review`: Minimal number of commits since the last review that are required to create incremental review. -If there are less than the specified number of commits since the last review, the tool will not perform any action. -Default is 0 - the tool will always run, no matter how many commits since the last review. -- `minimal_minutes_for_incremental_review`: Minimal number of minutes that need to pass since the last reviewed commit to create incremental review. -If less than the specified number of minutes have passed between the last reviewed commit and running this command, the tool will not perform any action. -Default is 0 - the tool will always run, no matter how much time have passed since the last reviewed commit. -- `require_all_thresholds_for_incremental_review`: If set to true, all the previous thresholds must be met for incremental review to run. If false, only one is enough to run the tool. -For example, if `minimal_commits_for_incremental_review=2` and `minimal_minutes_for_incremental_review=2`, and we have 3 commits since the last review, but the last reviewed commit is from 1 minute ago: -When `require_all_thresholds_for_incremental_review=true` the incremental review __will not__ run, because only 1 out of 2 conditions were met (we have enough commits but the last review is too recent), -but when `require_all_thresholds_for_incremental_review=false` the incremental review __will__ run, because one condition is enough (we have 3 commits which is more than the configured 2). -Default is false - the tool will run as long as at least once conditions is met. - -#### PR Reflection +### PR Reflection By invoking: ``` @@ -77,92 +77,103 @@ By invoking: ``` The tool will first ask the author questions about the PR, and will guide the review based on their answers. - + + + + + - - - + + + + + + + + + + ## Usage Tips -### General guidelines +!!! tip "General guidelines" -The `review` tool provides a collection of possible feedbacks about a PR. -It is recommended to review the [Configuration options](#configuration-options) section, and choose the relevant options for your use case. + The `review` tool provides a collection of possible feedbacks about a PR. + It is recommended to review the [Configuration options](#configuration-options) section, and choose the relevant options for your use case. + + Some of the features that are disabled by default are quite useful, and should be considered for enabling. For example: + `require_score_review`, `require_soc2_ticket`, and more. + + On the other hand, if you find one of the enabled features to be irrelevant for your use case, disable it. No default configuration can fit all use cases. -Some of the features that are disabled by default are quite useful, and should be considered for enabling. For example: -`require_score_review`, `require_soc2_ticket`, and more. +!!! tip "Automation" + - When you first install PR-Agent app, the [default mode](../usage-guide/automations_and_usage.md#github-app-automatic-tools-when-a-new-pr-is-opened) for the `review` tool is: + ``` + pr_commands = ["/review --pr_reviewer.num_code_suggestions=0", ...] + ``` + Meaning the `review` tool will run automatically on every PR, without providing code suggestions. + Edit this field to enable/disable the tool, or to change the used configurations. -On the other hand, if you find one of the enabled features to be irrelevant for your use case, disable it. No default configuration can fit all use cases. +!!! tip "Code suggestions" -### Code suggestions + If you set `num_code_suggestions`>0 , the `review` tool will also provide code suggestions. + + Notice If you are interested **only** in the code suggestions, it is recommended to use the [`improve`](./improve.md) feature instead, since it is a dedicated only to code suggestions, and usually gives better results. + Use the `review` tool if you want to get more comprehensive feedback, which includes code suggestions as well. -If you set `num_code_suggestions`>0 , the `review` tool will also provide code suggestions. +!!! tip "Possible labels from the review tool" -Notice If you are interested **only** in the code suggestions, it is recommended to use the [`improve`](./improve.md) feature instead, since it is a dedicated only to code suggestions, and usually gives better results. -Use the `review` tool if you want to get more comprehensive feedback, which includes code suggestions as well. + The `review` tool can auto-generate two specific types of labels for a PR: + + - a `possible security issue` label that detects if a possible [security issue](https://github.com/Codium-ai/pr-agent/blob/tr/user_description/pr_agent/settings/pr_reviewer_prompts.toml#L136) exists in the PR code (`enable_review_labels_security` flag) + - a `Review effort [1-5]: x` label, where x is the estimated effort to review the PR (`enable_review_labels_effort` flag) + + Both modes are useful, and we recommended to enable them. -### Automation -- When you first install the app, the [default mode](../usage-guide/automations_and_usage.md#github-app-automatic-tools-when-a-new-pr-is-opened) for the `review` tool is: -``` -pr_commands = ["/review", ...] -``` -Meaning the `review` tool will run automatically on every PR, with the default configuration. -Edit this field to enable/disable the tool, or to change the used configurations. +!!! tip "Extra instructions" -### Auto-labels - -The `review` tool can auto-generate two specific types of labels for a PR: - -- a `possible security issue` label that detects a possible [security issue](https://github.com/Codium-ai/pr-agent/blob/tr/user_description/pr_agent/settings/pr_reviewer_prompts.toml#L136) (`enable_review_labels_security` flag) -- a `Review effort [1-5]: x` label, where x is the estimated effort to review the PR (`enable_review_labels_effort` flag) - -Both modes are useful, and we recommended to enable them. - -### Extra instructions - -Extra instructions are important. -The `review` tool can be configured with extra instructions, which can be used to guide the model to a feedback tailored to the needs of your project. - -Be specific, clear, and concise in the instructions. With extra instructions, you are the prompter. Specify the relevant sub-tool, and the relevant aspects of the PR that you want to emphasize. - -Examples for extra instructions: -``` -[pr_reviewer] # /review # -extra_instructions=""" -In the code feedback section, emphasize the following: -- Does the code logic cover relevant edge cases? -- Is the code logic clear and easy to understand? -- Is the code logic efficient? -... -""" -``` -Use triple quotes to write multi-line instructions. Use bullet points to make the instructions more readable. + Extra instructions are important. + The `review` tool can be configured with extra instructions, which can be used to guide the model to a feedback tailored to the needs of your project. + + Be specific, clear, and concise in the instructions. With extra instructions, you are the prompter. Specify the relevant sub-tool, and the relevant aspects of the PR that you want to emphasize. + + Examples for extra instructions: + ``` + [pr_reviewer] # /review # + extra_instructions=""" + In the code feedback section, emphasize the following: + - Does the code logic cover relevant edge cases? + - Is the code logic clear and easy to understand? + - Is the code logic efficient? + ... + """ + ``` + Use triple quotes to write multi-line instructions. Use bullet points to make the instructions more readable. -### Auto-approval +!!! tip "Auto-approval" -PR-Agent can approve a PR when a specific comment is invoked. - -To ensure safety, the auto-approval feature is disabled by default. To enable auto-approval, you need to actively set in a pre-defined configuration file the following: -``` -[pr_reviewer] -enable_auto_approval = true -``` -(this specific flag cannot be set with a command line argument, only in the configuration file, committed to the repository) - - -After enabling, by commenting on a PR: -``` -/review auto_approve -``` -PR-Agent will automatically approve the PR, and add a comment with the approval. - - -You can also enable auto-approval only if the PR meets certain requirements, such as that the `estimated_review_effort` label is equal or below a certain threshold, by adjusting the flag: -``` -[pr_reviewer] -maximal_review_effort = 5 -``` \ No newline at end of file + PR-Agent can approve a PR when a specific comment is invoked. + + To ensure safety, the auto-approval feature is disabled by default. To enable auto-approval, you need to actively set in a pre-defined configuration file the following: + ``` + [pr_reviewer] + enable_auto_approval = true + ``` + (this specific flag cannot be set with a command line argument, only in the configuration file, committed to the repository) + + + After enabling, by commenting on a PR: + ``` + /review auto_approve + ``` + PR-Agent will automatically approve the PR, and add a comment with the approval. + + + You can also enable auto-approval only if the PR meets certain requirements, such as that the `estimated_review_effort` label is equal or below a certain threshold, by adjusting the flag: + ``` + [pr_reviewer] + maximal_review_effort = 5 + ``` \ No newline at end of file From 1db58fd0284d2ca41093ddad1f2c208734ff2960 Mon Sep 17 00:00:00 2001 From: mrT23 Date: Tue, 19 Mar 2024 09:56:10 +0200 Subject: [PATCH 029/226] Refactor improve.md: Improve image formatting, restructure content, and enhance descriptions --- docs/docs/tools/improve.md | 84 ++++++++++++++++++++++---------------- docs/docs/tools/review.md | 10 ++++- 2 files changed, 57 insertions(+), 37 deletions(-) diff --git a/docs/docs/tools/improve.md b/docs/docs/tools/improve.md index b4f16d17..2393d3ce 100644 --- a/docs/docs/tools/improve.md +++ b/docs/docs/tools/improve.md @@ -9,12 +9,20 @@ The tool can be triggered automatically every time a new PR is [opened](../usage The code suggestions can be presented as a single comment (via `pr_code_suggestions.summarize=true`): - + + + + + Or as a separate commitable code comment for each suggestion: - + + + + + Note that a single comment has a significantly smaller PR footprint. We recommend this mode for most cases. Also note that collapsible are not supported in _Bitbucket_. Hence, the suggestions are presented there as code comments. @@ -43,47 +51,53 @@ To edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agen /improve --pr_code_suggestions.some_config1=... --pr_code_suggestions.some_config2=... ``` -### General options +!!! example "General options" -- `num_code_suggestions`: number of code suggestions provided by the 'improve' tool. Default is 4. -- `extra_instructions`: Optional extra instructions to the tool. For example: "focus on the changes in the file X. Ignore change in ...". -- `rank_suggestions`: if set to true, the tool will rank the suggestions, based on importance. Default is false. -- `summarize`: if set to true, the tool will display the suggestions in a single comment. Default is false. -- `enable_help_text`: if set to true, the tool will display a help text in the comment. Default is true. + - `num_code_suggestions`: number of code suggestions provided by the 'improve' tool. Default is 4. + - `extra_instructions`: Optional extra instructions to the tool. For example: "focus on the changes in the file X. Ignore change in ...". + - `rank_suggestions`: if set to true, the tool will rank the suggestions, based on importance. Default is false. + - `summarize`: if set to true, the tool will display the suggestions in a single comment. Default is false. + - `enable_help_text`: if set to true, the tool will display a help text in the comment. Default is true. -### params for '/improve --extended' mode +!!! example "params for '/improve --extended' mode" -- `auto_extended_mode`: enable extended mode automatically (no need for the `--extended` option). Default is true. -- `num_code_suggestions_per_chunk`: number of code suggestions provided by the 'improve' tool, per chunk. Default is 8. -- `rank_extended_suggestions`: if set to true, the tool will rank the suggestions, based on importance. Default is true. -- `max_number_of_calls`: maximum number of chunks. Default is 5. -- `final_clip_factor`: factor to remove suggestions with low confidence. Default is 0.9. + - `auto_extended_mode`: enable extended mode automatically (no need for the `--extended` option). Default is true. + - `num_code_suggestions_per_chunk`: number of code suggestions provided by the 'improve' tool, per chunk. Default is 8. + - `rank_extended_suggestions`: if set to true, the tool will rank the suggestions, based on importance. Default is true. + - `max_number_of_calls`: maximum number of chunks. Default is 5. + - `final_clip_factor`: factor to remove suggestions with low confidence. Default is 0.9. ## Usage Tips -### Extra instructions +!!! tip "Extra instructions" -Extra instructions are very important for the `imrpove` tool, since they enable you to guide the model to suggestions that are more relevant to the specific needs of the project. - -Be specific, clear, and concise in the instructions. With extra instructions, you are the prompter. Specify relevant aspects that you want the model to focus on. - -Examples for extra instructions: -``` -[pr_code_suggestions] # /improve # -extra_instructions=""" -Emphasize the following aspects: -- Does the code logic cover relevant edge cases? -- Is the code logic clear and easy to understand? -- Is the code logic efficient? -... -""" -``` -Use triple quotes to write multi-line instructions. Use bullet points to make the instructions more readable. + Extra instructions are very important for the `imrpove` tool, since they enable you to guide the model to suggestions that are more relevant to the specific needs of the project. + + Be specific, clear, and concise in the instructions. With extra instructions, you are the prompter. Specify relevant aspects that you want the model to focus on. + + Examples for extra instructions: + ``` + [pr_code_suggestions] # /improve # + extra_instructions=""" + Emphasize the following aspects: + - Does the code logic cover relevant edge cases? + - Is the code logic clear and easy to understand? + - Is the code logic efficient? + ... + """ + ``` + Use triple quotes to write multi-line instructions. Use bullet points to make the instructions more readable. ### A note on code suggestions quality -- While the current AI for code is getting better and better (GPT-4), it's not flawless. Not all the suggestions will be perfect, and a user should not accept all of them automatically. -- Suggestions are not meant to be [simplistic](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/pr_code_suggestions_prompts.toml#L34). Instead, they aim to give deep feedback and raise questions, ideas and thoughts to the user, who can then use his judgment, experience, and understanding of the code base. -- Recommended to use the `exra_instructions` field to guide the model to suggestions that are more relevant to the specific needs of the project. -- Consider also trying the [Custom Suggestions Tool](./custom_suggestions.md) ๐Ÿ’Ž, that will **only** propose suggestions that follow specific guidelines defined by user. \ No newline at end of file +- While the current AI for code is getting better and better (GPT-4), it's not flawless. Not all the suggestions will be perfect, and a user should not accept all of them automatically. Critical reading and judgment are required. +- While mistakes of the AI are rare but can happen, a real benefit of the tool is to catch, with high probability, **mistakes or bugs done by the PR author**, when they happen. So, it's a good practice to spend the needed ~30-60 seconds to review the suggestions, even if not all of them are relevant. +- The hierarchical structure of the suggestions UI-UX is designed to help the user to _quickly_ understand them, and to decide which ones are relevant and which are not: + + - Only if the `Category` header is relevant, the user should move to the summarized suggestion description + - Only if the summarized suggestion description is relevant, the user should click on the collpasible, to read the full suggestion description with a code preview example. + +In addition, we recommend to use the `exra_instructions` field to guide the model to suggestions that are more relevant to the specific needs of the project. +
    +Consider also trying the [Custom Suggestions Tool](./custom_suggestions.md) ๐Ÿ’Ž, that will **only** propose suggestions that follow specific guidelines defined by user. \ No newline at end of file diff --git a/docs/docs/tools/review.md b/docs/docs/tools/review.md index 9a8a1bb6..79dd7b2b 100644 --- a/docs/docs/tools/review.md +++ b/docs/docs/tools/review.md @@ -35,6 +35,8 @@ To edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agen - `extra_instructions`: Optional extra instructions to the tool. For example: "focus on the changes in the file X. Ignore change in ...". !!! example "Enable\\disable sub-sections" + You can enable or disable specific sub-sections of the review tool: + - `require_score_review`: if set to true, the tool will add a section that scores the PR. Default is false. - `require_tests_review`: if set to true, the tool will add a section that checks if the PR contains tests. Default is true. - `require_estimate_effort_to_review`: if set to true, the tool will add a section that estimates the effort needed to review the PR. Default is true. @@ -47,11 +49,15 @@ To edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agen - `require_soc2_ticket`: If set to true, the SOC2 ticket checker sub-tool will be enabled. Default is false. - `soc2_ticket_prompt`: The prompt for the SOC2 ticket review. Default is: `Does the PR description include a link to ticket in a project management system (e.g., Jira, Asana, Trello, etc.) ?`. Edit this field if your compliance requirements are different. -!!! example Adding PR labels +!!! example "Adding PR labels" + You can enable the tool to add specific labels to the PR: + - `enable_review_labels_security`: if set to true, the tool will publish a 'possible security issue' label if it detects a security issue. Default is true. - `enable_review_labels_effort`: if set to true, the tool will publish a 'Review effort [1-5]: x' label. Default is true. !!! example "Auto-approval" + The review tool can approve a PR when a specific comment, `/review auto_approve` is invoked. + - `enable_auto_approval`: if set to true, the tool will approve the PR when invoked with the 'auto_approve' command. Default is false. This flag can be changed only from configuration file. - `maximal_review_effort`: maximal effort level for auto-approval. If the PR's estimated review effort is above this threshold, the auto-approval will not run. Default is 5. @@ -109,7 +115,7 @@ The tool will first ask the author questions about the PR, and will guide the re On the other hand, if you find one of the enabled features to be irrelevant for your use case, disable it. No default configuration can fit all use cases. !!! tip "Automation" - - When you first install PR-Agent app, the [default mode](../usage-guide/automations_and_usage.md#github-app-automatic-tools-when-a-new-pr-is-opened) for the `review` tool is: + When you first install PR-Agent app, the [default mode](../usage-guide/automations_and_usage.md#github-app-automatic-tools-when-a-new-pr-is-opened) for the `review` tool is: ``` pr_commands = ["/review --pr_reviewer.num_code_suggestions=0", ...] ``` From 0aea45ec9ce9fcb0a87dd1929eb02d4b4a54dce5 Mon Sep 17 00:00:00 2001 From: mrT23 Date: Tue, 19 Mar 2024 10:00:04 +0200 Subject: [PATCH 030/226] type --- docs/docs/tools/improve.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/docs/tools/improve.md b/docs/docs/tools/improve.md index 2393d3ce..7fce2be5 100644 --- a/docs/docs/tools/improve.md +++ b/docs/docs/tools/improve.md @@ -19,8 +19,8 @@ The code suggestions can be presented as a single comment (via `pr_code_suggesti Or as a separate commitable code comment for each suggestion: - - + + From 2a76e77ba2199c37a960e0070353dfa186c3c5b7 Mon Sep 17 00:00:00 2001 From: Tal Date: Tue, 19 Mar 2024 12:02:38 +0200 Subject: [PATCH 031/226] Update build-and-test.yaml --- .github/workflows/build-and-test.yaml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/build-and-test.yaml b/.github/workflows/build-and-test.yaml index 114bbb7e..960da61b 100644 --- a/.github/workflows/build-and-test.yaml +++ b/.github/workflows/build-and-test.yaml @@ -2,8 +2,6 @@ name: Build-and-test on: push: - pull_request: - types: [ opened, reopened ] jobs: build-and-test: From 7254211ed343d795271b0252705a98d9b25da653 Mon Sep 17 00:00:00 2001 From: Hussam Lawen Date: Tue, 19 Mar 2024 13:38:54 +0200 Subject: [PATCH 032/226] Update review.md --- docs/docs/tools/review.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/docs/tools/review.md b/docs/docs/tools/review.md index 79dd7b2b..094737ff 100644 --- a/docs/docs/tools/review.md +++ b/docs/docs/tools/review.md @@ -70,8 +70,8 @@ For invoking the incremental mode, the following command can be used: Note that the incremental mode is only available for GitHub. - - + + @@ -182,4 +182,4 @@ The tool will first ask the author questions about the PR, and will guide the re ``` [pr_reviewer] maximal_review_effort = 5 - ``` \ No newline at end of file + ``` From 158370e66c63298cacb0731c50455454a6fc4881 Mon Sep 17 00:00:00 2001 From: Tal Date: Tue, 19 Mar 2024 14:36:16 +0200 Subject: [PATCH 033/226] Update build-and-test.yaml --- .github/workflows/build-and-test.yaml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/build-and-test.yaml b/.github/workflows/build-and-test.yaml index 960da61b..114bbb7e 100644 --- a/.github/workflows/build-and-test.yaml +++ b/.github/workflows/build-and-test.yaml @@ -2,6 +2,8 @@ name: Build-and-test on: push: + pull_request: + types: [ opened, reopened ] jobs: build-and-test: From a39ff5d2ddda933118fb7d8bc9fea4cc5f3b9a16 Mon Sep 17 00:00:00 2001 From: mrT23 Date: Tue, 19 Mar 2024 16:16:22 +0200 Subject: [PATCH 034/226] Review vs. Improve tools comparison --- docs/docs/tools/improve.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/docs/tools/improve.md b/docs/docs/tools/improve.md index 7fce2be5..6b062040 100644 --- a/docs/docs/tools/improve.md +++ b/docs/docs/tools/improve.md @@ -89,6 +89,13 @@ To edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agen ``` Use triple quotes to write multi-line instructions. Use bullet points to make the instructions more readable. +!!! tip "Review vs. Improve tools comparison" + + The [`review` tool](https://pr-agent-docs.codium.ai/tools/review/) includes a section called 'Possible issues', that also provide feedback on the PR Code. + In this section, the model is instructed to focus **only** on [major bugs and issues](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/pr_reviewer_prompts.toml#L71). + The 'improve' tool, on the other hand, has a broader mandate, and in addition to bugs and issues, it makes suggestions for improving code quality and making the code more efficient, readable, and maintainable.(see [here](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/pr_code_suggestions_prompts.toml#L34)). + Hence, if you are interested only in feedback about clear bugs, the `review` tool might suffice. If you want more detailed feedback, including broader suggestions for improving the code, also enable the `improve` tool to run on each PR. + ### A note on code suggestions quality - While the current AI for code is getting better and better (GPT-4), it's not flawless. Not all the suggestions will be perfect, and a user should not accept all of them automatically. Critical reading and judgment are required. From cf15f768fcb86b49a3e557614ef1f5225257f949 Mon Sep 17 00:00:00 2001 From: mrT23 Date: Tue, 19 Mar 2024 16:33:43 +0200 Subject: [PATCH 035/226] Review vs. Improve tools comparison --- docs/docs/tools/improve.md | 10 +++++----- docs/docs/tools/review.md | 4 ++-- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/docs/tools/improve.md b/docs/docs/tools/improve.md index 6b062040..a58e8d78 100644 --- a/docs/docs/tools/improve.md +++ b/docs/docs/tools/improve.md @@ -91,16 +91,16 @@ To edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agen !!! tip "Review vs. Improve tools comparison" - The [`review` tool](https://pr-agent-docs.codium.ai/tools/review/) includes a section called 'Possible issues', that also provide feedback on the PR Code. + - The [`review`](https://pr-agent-docs.codium.ai/tools/review/) tool includes a section called 'Possible issues', that also provide feedback on the PR Code. In this section, the model is instructed to focus **only** on [major bugs and issues](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/pr_reviewer_prompts.toml#L71). - The 'improve' tool, on the other hand, has a broader mandate, and in addition to bugs and issues, it makes suggestions for improving code quality and making the code more efficient, readable, and maintainable.(see [here](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/pr_code_suggestions_prompts.toml#L34)). - Hence, if you are interested only in feedback about clear bugs, the `review` tool might suffice. If you want more detailed feedback, including broader suggestions for improving the code, also enable the `improve` tool to run on each PR. + - The `improve` tool, on the other hand, has a broader mandate, and in addition to bugs and issues, it can also give suggestions for improving code quality and making the code more efficient, readable, and maintainable (see [here](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/pr_code_suggestions_prompts.toml#L34)). + - Hence, if you are interested only in feedback about clear bugs, the `review` tool might suffice. If you want a more detailed feedback, including broader suggestions for improving the PR code, also enable the `improve` tool to run on each PR. ### A note on code suggestions quality - While the current AI for code is getting better and better (GPT-4), it's not flawless. Not all the suggestions will be perfect, and a user should not accept all of them automatically. Critical reading and judgment are required. -- While mistakes of the AI are rare but can happen, a real benefit of the tool is to catch, with high probability, **mistakes or bugs done by the PR author**, when they happen. So, it's a good practice to spend the needed ~30-60 seconds to review the suggestions, even if not all of them are relevant. -- The hierarchical structure of the suggestions UI-UX is designed to help the user to _quickly_ understand them, and to decide which ones are relevant and which are not: +- While mistakes of the AI are rare but can happen, a real benefit from the suggestions of the `improve` (and [`review`](https://pr-agent-docs.codium.ai/tools/review/)) tool is to catch, with high probability, **mistakes or bugs done by the PR author**, when they happen. So, it's a good practice to spend the needed ~30-60 seconds to review the suggestions, even if not all of them are always relevant. +- The hierarchical structure of the suggestions is designed to help the user to _quickly_ understand them, and to decide which ones are relevant and which are not: - Only if the `Category` header is relevant, the user should move to the summarized suggestion description - Only if the summarized suggestion description is relevant, the user should click on the collpasible, to read the full suggestion description with a code preview example. diff --git a/docs/docs/tools/review.md b/docs/docs/tools/review.md index 094737ff..8a571983 100644 --- a/docs/docs/tools/review.md +++ b/docs/docs/tools/review.md @@ -13,8 +13,8 @@ For example: - - + + From f121652e4df8e38582d3559c4438e479e8e7fbf2 Mon Sep 17 00:00:00 2001 From: Tal Date: Tue, 19 Mar 2024 17:29:21 +0200 Subject: [PATCH 036/226] Update improve.md --- docs/docs/tools/improve.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/docs/tools/improve.md b/docs/docs/tools/improve.md index a58e8d78..d642a1b1 100644 --- a/docs/docs/tools/improve.md +++ b/docs/docs/tools/improve.md @@ -96,15 +96,15 @@ To edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agen - The `improve` tool, on the other hand, has a broader mandate, and in addition to bugs and issues, it can also give suggestions for improving code quality and making the code more efficient, readable, and maintainable (see [here](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/pr_code_suggestions_prompts.toml#L34)). - Hence, if you are interested only in feedback about clear bugs, the `review` tool might suffice. If you want a more detailed feedback, including broader suggestions for improving the PR code, also enable the `improve` tool to run on each PR. -### A note on code suggestions quality +## A note on code suggestions quality - While the current AI for code is getting better and better (GPT-4), it's not flawless. Not all the suggestions will be perfect, and a user should not accept all of them automatically. Critical reading and judgment are required. - While mistakes of the AI are rare but can happen, a real benefit from the suggestions of the `improve` (and [`review`](https://pr-agent-docs.codium.ai/tools/review/)) tool is to catch, with high probability, **mistakes or bugs done by the PR author**, when they happen. So, it's a good practice to spend the needed ~30-60 seconds to review the suggestions, even if not all of them are always relevant. - The hierarchical structure of the suggestions is designed to help the user to _quickly_ understand them, and to decide which ones are relevant and which are not: - Only if the `Category` header is relevant, the user should move to the summarized suggestion description - - Only if the summarized suggestion description is relevant, the user should click on the collpasible, to read the full suggestion description with a code preview example. + - Only if the summarized suggestion description is relevant, the user should click on the collapsible, to read the full suggestion description with a code preview example. In addition, we recommend to use the `exra_instructions` field to guide the model to suggestions that are more relevant to the specific needs of the project.
    -Consider also trying the [Custom Suggestions Tool](./custom_suggestions.md) ๐Ÿ’Ž, that will **only** propose suggestions that follow specific guidelines defined by user. \ No newline at end of file +Consider also trying the [Custom Suggestions Tool](./custom_suggestions.md) ๐Ÿ’Ž, that will **only** propose suggestions that follow specific guidelines defined by user. From b70225294c0a178462c8b6b0004340524c498ec9 Mon Sep 17 00:00:00 2001 From: mrT23 Date: Wed, 20 Mar 2024 08:14:08 +0200 Subject: [PATCH 037/226] Update 'improve' tool documentation and functionality: Add persistent comment option, adjust default values, and enhance comment handling in pr_code_suggestions.py --- docs/docs/tools/improve.md | 7 ++++--- pr_agent/settings/configuration.toml | 1 + pr_agent/tools/pr_code_suggestions.py | 16 +++++++++++++--- 3 files changed, 18 insertions(+), 6 deletions(-) diff --git a/docs/docs/tools/improve.md b/docs/docs/tools/improve.md index d642a1b1..f5808139 100644 --- a/docs/docs/tools/improve.md +++ b/docs/docs/tools/improve.md @@ -53,16 +53,17 @@ To edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agen !!! example "General options" - - `num_code_suggestions`: number of code suggestions provided by the 'improve' tool. Default is 4. + - `num_code_suggestions`: number of code suggestions provided by the 'improve' tool. Default is 4 for CLI, 0 for auto tools. - `extra_instructions`: Optional extra instructions to the tool. For example: "focus on the changes in the file X. Ignore change in ...". - `rank_suggestions`: if set to true, the tool will rank the suggestions, based on importance. Default is false. - - `summarize`: if set to true, the tool will display the suggestions in a single comment. Default is false. + - `summarize`: if set to true, the tool will display the suggestions in a single comment. Default is true. + - `persistent_comment`: if set to true, the improve comment will be persistent, meaning that every new improve request will edit the previous one. Default is false. - `enable_help_text`: if set to true, the tool will display a help text in the comment. Default is true. !!! example "params for '/improve --extended' mode" - `auto_extended_mode`: enable extended mode automatically (no need for the `--extended` option). Default is true. - - `num_code_suggestions_per_chunk`: number of code suggestions provided by the 'improve' tool, per chunk. Default is 8. + - `num_code_suggestions_per_chunk`: number of code suggestions provided by the 'improve' tool, per chunk. Default is 5. - `rank_extended_suggestions`: if set to true, the tool will rank the suggestions, based on importance. Default is true. - `max_number_of_calls`: maximum number of chunks. Default is 5. - `final_clip_factor`: factor to remove suggestions with low confidence. Default is 0.9. diff --git a/pr_agent/settings/configuration.toml b/pr_agent/settings/configuration.toml index 21ad264b..886fad1a 100644 --- a/pr_agent/settings/configuration.toml +++ b/pr_agent/settings/configuration.toml @@ -82,6 +82,7 @@ summarize = true extra_instructions = "" rank_suggestions = false enable_help_text=true +persistent_comment=false # params for '/improve --extended' mode auto_extended_mode=true num_code_suggestions_per_chunk=5 diff --git a/pr_agent/tools/pr_code_suggestions.py b/pr_agent/tools/pr_code_suggestions.py index 33628123..cb4dc835 100644 --- a/pr_agent/tools/pr_code_suggestions.py +++ b/pr_agent/tools/pr_code_suggestions.py @@ -117,10 +117,20 @@ class PRCodeSuggestions: pr_body += HelpMessage.get_improve_usage_guide() pr_body += "\n
\n" - if self.progress_response: - self.git_provider.edit_comment(self.progress_response, body=pr_body) + if get_settings().pr_code_suggestions.persistent_comment: + final_update_message = False + self.git_provider.publish_persistent_comment(pr_body, + initial_header="## PR Code Suggestions", + update_header=True, + final_update_message=final_update_message, ) + if self.progress_response: + self.progress_response.delete() else: - self.git_provider.publish_comment(pr_body) + + if self.progress_response: + self.git_provider.edit_comment(self.progress_response, body=pr_body) + else: + self.git_provider.publish_comment(pr_body) else: self.push_inline_code_suggestions(data) From 29a2412de61ad881f8ad54ad68d1661381193e1a Mon Sep 17 00:00:00 2001 From: mrT23 Date: Wed, 20 Mar 2024 08:36:46 +0200 Subject: [PATCH 038/226] name --- pr_agent/tools/pr_code_suggestions.py | 1 + 1 file changed, 1 insertion(+) diff --git a/pr_agent/tools/pr_code_suggestions.py b/pr_agent/tools/pr_code_suggestions.py index cb4dc835..aa119f2a 100644 --- a/pr_agent/tools/pr_code_suggestions.py +++ b/pr_agent/tools/pr_code_suggestions.py @@ -122,6 +122,7 @@ class PRCodeSuggestions: self.git_provider.publish_persistent_comment(pr_body, initial_header="## PR Code Suggestions", update_header=True, + name="suggestions", final_update_message=final_update_message, ) if self.progress_response: self.progress_response.delete() From a969d1038105f6a148bb8520eb69a1a056ef92e6 Mon Sep 17 00:00:00 2001 From: Tal Date: Wed, 20 Mar 2024 09:07:52 +0200 Subject: [PATCH 039/226] Update build-and-test.yaml --- .github/workflows/build-and-test.yaml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build-and-test.yaml b/.github/workflows/build-and-test.yaml index 114bbb7e..3bf08cb5 100644 --- a/.github/workflows/build-and-test.yaml +++ b/.github/workflows/build-and-test.yaml @@ -2,8 +2,11 @@ name: Build-and-test on: push: + branches: + - main pull_request: - types: [ opened, reopened ] + branches: + - main jobs: build-and-test: From 31bb72d65d5d48e770e9fbf7017533de37df965c Mon Sep 17 00:00:00 2001 From: "Hussam.lawen" Date: Wed, 20 Mar 2024 11:09:23 +0200 Subject: [PATCH 040/226] add enable help text to documentation --- docs/docs/tools/describe.md | 3 ++- docs/docs/tools/review.md | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/docs/tools/describe.md b/docs/docs/tools/describe.md index 33c96e96..3351b802 100644 --- a/docs/docs/tools/describe.md +++ b/docs/docs/tools/describe.md @@ -49,7 +49,8 @@ To edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agen - `enable_semantic_files_types`: if set to true, "Changes walkthrough" section will be generated. Default is true. - `collapsible_file_list`: if set to true, the file list in the "Changes walkthrough" section will be collapsible. If set to "adaptive", the file list will be collapsible only if there are more than 8 files. Default is "adaptive". - + - `enable_help_text`: if set to true, the tool will display a help text in the comment. Default is true. + ### Inline file summary ๐Ÿ’Ž This feature enables you to copy the `changes walkthrough` table to the "Files changed" tab, so you can quickly understand the changes in each file while reviewing the code changes (diff view). diff --git a/docs/docs/tools/review.md b/docs/docs/tools/review.md index 8a571983..a8bd5a66 100644 --- a/docs/docs/tools/review.md +++ b/docs/docs/tools/review.md @@ -33,6 +33,7 @@ To edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agen - `inline_code_comments`: if set to true, the tool will publish the code suggestions as comments on the code diff. Default is false. - `persistent_comment`: if set to true, the review comment will be persistent, meaning that every new review request will edit the previous one. Default is true. - `extra_instructions`: Optional extra instructions to the tool. For example: "focus on the changes in the file X. Ignore change in ...". + - `enable_help_text`: if set to true, the tool will display a help text in the comment. Default is true. !!! example "Enable\\disable sub-sections" You can enable or disable specific sub-sections of the review tool: From 61b2a1a053ad447a8e45c539ad36ab9ed9d99e15 Mon Sep 17 00:00:00 2001 From: "Hussam.lawen" Date: Wed, 20 Mar 2024 11:11:06 +0200 Subject: [PATCH 041/226] update default --- docs/docs/tools/describe.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/tools/describe.md b/docs/docs/tools/describe.md index 3351b802..cf7ccdfb 100644 --- a/docs/docs/tools/describe.md +++ b/docs/docs/tools/describe.md @@ -49,7 +49,7 @@ To edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agen - `enable_semantic_files_types`: if set to true, "Changes walkthrough" section will be generated. Default is true. - `collapsible_file_list`: if set to true, the file list in the "Changes walkthrough" section will be collapsible. If set to "adaptive", the file list will be collapsible only if there are more than 8 files. Default is "adaptive". - - `enable_help_text`: if set to true, the tool will display a help text in the comment. Default is true. + - `enable_help_text`: if set to true, the tool will display a help text in the comment. Default is false. ### Inline file summary ๐Ÿ’Ž From cae0b9605413c8c9a393e98beaa02593fc3f7828 Mon Sep 17 00:00:00 2001 From: koid Date: Thu, 21 Mar 2024 12:06:46 +0900 Subject: [PATCH 042/226] use sender_type on bot check --- pr_agent/servers/github_app.py | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/pr_agent/servers/github_app.py b/pr_agent/servers/github_app.py index ed6e1e73..80a673d7 100644 --- a/pr_agent/servers/github_app.py +++ b/pr_agent/servers/github_app.py @@ -118,14 +118,14 @@ async def handle_new_pr_opened(body: Dict[str, Any], event: str, sender: str, sender_id: str, + sender_type: str, action: str, log_context: Dict[str, Any], agent: PRAgent): # logic to ignore PRs opened by bot - if get_settings().get("GITHUB_APP.IGNORE_BOT_PR", False): - if sender.endswith('[bot]'): - get_logger().info(f"Ignoring PR by sender '{sender}' due to github_app.ignore_bot_pr setting") - return {} + if get_settings().get("GITHUB_APP.IGNORE_BOT_PR", False) and sender_type == "Bot": + get_logger().info(f"Ignoring PR from '{sender=}' due to github_app.ignore_bot_pr setting") + return {} title = body.get("pull_request", {}).get("title", "") @@ -230,9 +230,11 @@ def handle_closed_pr(body, event, action, log_context): def get_log_context(body, event, action, build_number): sender = "" sender_id = "" + sender_type = "" try: sender = body.get("sender", {}).get("login") sender_id = body.get("sender", {}).get("id") + sender_type = body.get("sender", {}).get("type") repo = body.get("repository", {}).get("full_name", "") git_org = body.get("organization", {}).get("login", "") app_name = get_settings().get("CONFIG.APP_NAME", "Unknown") @@ -242,7 +244,7 @@ def get_log_context(body, event, action, build_number): except Exception as e: get_logger().error("Failed to get log context", e) log_context = {} - return log_context, sender, sender_id + return log_context, sender, sender_id, sender_type async def handle_request(body: Dict[str, Any], event: str): @@ -257,7 +259,7 @@ async def handle_request(body: Dict[str, Any], event: str): if not action: return {} agent = PRAgent() - log_context, sender, sender_id = get_log_context(body, event, action, build_number) + log_context, sender, sender_id, sender_type = get_log_context(body, event, action, build_number) # handle comments on PRs if action == 'created': @@ -266,7 +268,7 @@ async def handle_request(body: Dict[str, Any], event: str): # handle new PRs elif event == 'pull_request' and action != 'synchronize' and action != 'closed': get_logger().debug(f'Request body', artifact=body, event=event) - await handle_new_pr_opened(body, event, sender, sender_id, action, log_context, agent) + await handle_new_pr_opened(body, event, sender, sender_id, sender_type, action, log_context, agent) # handle pull_request event with synchronize action - "push trigger" for new commits elif event == 'pull_request' and action == 'synchronize': get_logger().debug(f'Request body', artifact=body, event=event) From 92fbf21bd3abe07bfb79e29e289ba172d006d115 Mon Sep 17 00:00:00 2001 From: veryyet Date: Thu, 21 Mar 2024 14:41:29 +0800 Subject: [PATCH 043/226] chore: fix some typos Signed-off-by: veryyet --- docs/docs/installation/azure.md | 10 +++++----- docs/docs/usage-guide/automations_and_usage.md | 10 +++++----- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/docs/installation/azure.md b/docs/docs/installation/azure.md index e8c11664..d6ffaa6b 100644 --- a/docs/docs/installation/azure.md +++ b/docs/docs/installation/azure.md @@ -7,12 +7,12 @@ git_provider="azure" ``` Azure DevOps provider supports [PAT token](https://learn.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=azure-devops&tabs=Windows) or [DefaultAzureCredential](https://learn.microsoft.com/en-us/azure/developer/python/sdk/authentication-overview#authentication-in-server-environments) authentication. -PAT is faster to create, but has build in experation date, and will use the user identity for API calls. -Using DefaultAzureCredential you can use managed identity or Service principle, which are more secure and will create seperate ADO user identity (via AAD) to the agent. +PAT is faster to create, but has build in expiration date, and will use the user identity for API calls. +Using DefaultAzureCredential you can use managed identity or Service principle, which are more secure and will create separate ADO user identity (via AAD) to the agent. -If PAT was choosen, you can assign the value in .secrets.toml. -If DefaultAzureCredential was choosen, you can assigned the additional env vars like AZURE_CLIENT_SECRET directly, -or use managed identity/az cli (for local develpment) without any additional configuration. +If PAT was chosen, you can assign the value in .secrets.toml. +If DefaultAzureCredential was chosen, you can assigned the additional env vars like AZURE_CLIENT_SECRET directly, +or use managed identity/az cli (for local development) without any additional configuration. in any case, 'org' value must be assigned in .secrets.toml: ``` [azure_devops] diff --git a/docs/docs/usage-guide/automations_and_usage.md b/docs/docs/usage-guide/automations_and_usage.md index b39f7e02..ba21b998 100644 --- a/docs/docs/usage-guide/automations_and_usage.md +++ b/docs/docs/usage-guide/automations_and_usage.md @@ -173,12 +173,12 @@ git_provider="azure" ``` Azure DevOps provider supports [PAT token](https://learn.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=azure-devops&tabs=Windows) or [DefaultAzureCredential](https://learn.microsoft.com/en-us/azure/developer/python/sdk/authentication-overview#authentication-in-server-environments) authentication. -PAT is faster to create, but has build in experation date, and will use the user identity for API calls. -Using DefaultAzureCredential you can use managed identity or Service principle, which are more secure and will create seperate ADO user identity (via AAD) to the agent. +PAT is faster to create, but has build in expiration date, and will use the user identity for API calls. +Using DefaultAzureCredential you can use managed identity or Service principle, which are more secure and will create separate ADO user identity (via AAD) to the agent. -If PAT was choosen, you can assign the value in .secrets.toml. -If DefaultAzureCredential was choosen, you can assigned the additional env vars like AZURE_CLIENT_SECRET directly, -or use managed identity/az cli (for local develpment) without any additional configuration. +If PAT was chosen, you can assign the value in .secrets.toml. +If DefaultAzureCredential was chosen, you can assigned the additional env vars like AZURE_CLIENT_SECRET directly, +or use managed identity/az cli (for local development) without any additional configuration. in any case, 'org' value must be assigned in .secrets.toml: ``` [azure_devops] From 0816370b1adb02f9def5bf1f882fc8e6b5232525 Mon Sep 17 00:00:00 2001 From: mrT23 Date: Fri, 22 Mar 2024 20:11:26 +0200 Subject: [PATCH 044/226] adjustments to pypi --- MANIFEST.in | 2 ++ README.md | 65 ++++++++++++++++++------------------ pr_agent/servers/__init__.py | 0 pyproject.toml | 28 ++++++++-------- requirements.txt | 10 +++--- 5 files changed, 55 insertions(+), 50 deletions(-) create mode 100644 MANIFEST.in create mode 100644 pr_agent/servers/__init__.py diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 00000000..ccb17336 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include pr_agent *.toml +recursive-exclude pr_agent *.secrets.toml \ No newline at end of file diff --git a/README.md b/README.md index ad3c0407..80cde6f2 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,8 @@ - logo + logo +
Making pull requests less painful with an AI agent @@ -59,7 +60,7 @@ If set to true, the tool will add a section that checks if the PR contains sever ## Overview
-CodiumAI PR-Agent is an open-source tool to help efficiently review and handle pull requests. +CodiumAI PR-Agent aims to help efficiently review and handle pull requests, by providing AI feedbacks and suggestions - See the [Installation Guide](https://pr-agent-docs.codium.ai/installation/) for instructions on installing and running the tool on different git platforms. @@ -71,38 +72,38 @@ Supported commands per platform: | | | GitHub | Gitlab | Bitbucket | Azure DevOps | |-------|-------------------------------------------------------------------------------------------------------------------|:--------------------:|:--------------------:|:--------------------:|:--------------------:| -| TOOLS | Review | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | -| | โฎ‘ Incremental | :white_check_mark: | | | | -| | โฎ‘ [SOC2 Compliance](https://pr-agent-docs.codium.ai/tools/review/#soc2-ticket-compliance) ๐Ÿ’Ž | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | -| | Describe | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | -| | โฎ‘ [Inline File Summary](https://pr-agent-docs.codium.ai/tools/describe#inline-file-summary) ๐Ÿ’Ž | :white_check_mark: | | | | -| | Improve | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | -| | โฎ‘ Extended | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | -| | Ask | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | -| | โฎ‘ [Ask on code lines](https://pr-agent-docs.codium.ai/tools/ask#ask-lines) | :white_check_mark: | :white_check_mark: | | | -| | [Custom Suggestions](https://pr-agent-docs.codium.ai/tools/custom_suggestions/) ๐Ÿ’Ž | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | -| | [Test](https://pr-agent-docs.codium.ai/tools/test/) ๐Ÿ’Ž | :white_check_mark: | :white_check_mark: | | :white_check_mark: | -| | Reflect and Review | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | -| | Update CHANGELOG.md | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | -| | Find Similar Issue | :white_check_mark: | | | | -| | [Add PR Documentation](https://pr-agent-docs.codium.ai/tools/documentation/) ๐Ÿ’Ž | :white_check_mark: | :white_check_mark: | | :white_check_mark: | -| | [Custom Labels](https://pr-agent-docs.codium.ai/tools/custom_labels/) ๐Ÿ’Ž | :white_check_mark: | :white_check_mark: | | :white_check_mark: | -| | [Analyze](https://pr-agent-docs.codium.ai/tools/analyze/) ๐Ÿ’Ž | :white_check_mark: | :white_check_mark: | | :white_check_mark: | -| | [CI Feedback](https://pr-agent-docs.codium.ai/tools/ci_feedback/) ๐Ÿ’Ž | :white_check_mark: | | | | -| | [Similar Code](https://pr-agent-docs.codium.ai/tools/similar_code/) ๐Ÿ’Ž | :white_check_mark: | | | | +| TOOLS | Review | โœ… | โœ… | โœ… | โœ… | +| | โฎ‘ Incremental | โœ… | | | | +| | โฎ‘ [SOC2 Compliance](https://pr-agent-docs.codium.ai/tools/review/#soc2-ticket-compliance) ๐Ÿ’Ž | โœ… | โœ… | โœ… | โœ… | +| | Describe | โœ… | โœ… | โœ… | โœ… | +| | โฎ‘ [Inline File Summary](https://pr-agent-docs.codium.ai/tools/describe#inline-file-summary) ๐Ÿ’Ž | โœ… | | | | +| | Improve | โœ… | โœ… | โœ… | โœ… | +| | โฎ‘ Extended | โœ… | โœ… | โœ… | โœ… | +| | Ask | โœ… | โœ… | โœ… | โœ… | +| | โฎ‘ [Ask on code lines](https://pr-agent-docs.codium.ai/tools/ask#ask-lines) | โœ… | โœ… | | | +| | [Custom Suggestions](https://pr-agent-docs.codium.ai/tools/custom_suggestions/) ๐Ÿ’Ž | โœ… | โœ… | โœ… | โœ… | +| | [Test](https://pr-agent-docs.codium.ai/tools/test/) ๐Ÿ’Ž | โœ… | โœ… | | โœ… | +| | Reflect and Review | โœ… | โœ… | โœ… | โœ… | +| | Update CHANGELOG.md | โœ… | โœ… | โœ… | โœ… | +| | Find Similar Issue | โœ… | | | | +| | [Add PR Documentation](https://pr-agent-docs.codium.ai/tools/documentation/) ๐Ÿ’Ž | โœ… | โœ… | | โœ… | +| | [Custom Labels](https://pr-agent-docs.codium.ai/tools/custom_labels/) ๐Ÿ’Ž | โœ… | โœ… | | โœ… | +| | [Analyze](https://pr-agent-docs.codium.ai/tools/analyze/) ๐Ÿ’Ž | โœ… | โœ… | | โœ… | +| | [CI Feedback](https://pr-agent-docs.codium.ai/tools/ci_feedback/) ๐Ÿ’Ž | โœ… | | | | +| | [Similar Code](https://pr-agent-docs.codium.ai/tools/similar_code/) ๐Ÿ’Ž | โœ… | | | | | | | | | | | -| USAGE | CLI | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | -| | App / webhook | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | -| | Tagging bot | :white_check_mark: | | | | -| | Actions | :white_check_mark: | | :white_check_mark: | | +| USAGE | CLI | โœ… | โœ… | โœ… | โœ… | +| | App / webhook | โœ… | โœ… | โœ… | โœ… | +| | Tagging bot | โœ… | | | | +| | Actions | โœ… | | โœ… | | | | | | | | | -| CORE | PR compression | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | -| | Repo language prioritization | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | -| | Adaptive and token-aware file patch fitting | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | -| | Multiple models support | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | -| | [Static code analysis](https://pr-agent-docs.codium.ai/core-abilities/#static-code-analysis) ๐Ÿ’Ž | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | -| | [Global and wiki configurations](https://pr-agent-docs.codium.ai/usage-guide/configuration_options/) ๐Ÿ’Ž | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | -| | [PR interactive actions](https://www.codium.ai/images/pr_agent/pr-actions.mp4) ๐Ÿ’Ž | :white_check_mark: | | | | +| CORE | PR compression | โœ… | โœ… | โœ… | โœ… | +| | Repo language prioritization | โœ… | โœ… | โœ… | โœ… | +| | Adaptive and token-aware file patch fitting | โœ… | โœ… | โœ… | โœ… | +| | Multiple models support | โœ… | โœ… | โœ… | โœ… | +| | [Static code analysis](https://pr-agent-docs.codium.ai/core-abilities/#static-code-analysis) ๐Ÿ’Ž | โœ… | โœ… | โœ… | โœ… | +| | [Global and wiki configurations](https://pr-agent-docs.codium.ai/usage-guide/configuration_options/) ๐Ÿ’Ž | โœ… | โœ… | โœ… | โœ… | +| | [PR interactive actions](https://www.codium.ai/images/pr_agent/pr-actions.mp4) ๐Ÿ’Ž | โœ… | | | | - ๐Ÿ’Ž means this feature is available only in [PR-Agent Pro](https://www.codium.ai/pricing/) [//]: # (- Support for additional git providers is described in [here](./docs/Full_environments.md)) diff --git a/pr_agent/servers/__init__.py b/pr_agent/servers/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/pyproject.toml b/pyproject.toml index 37be93e3..f4be6371 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -3,44 +3,44 @@ requires = ["setuptools>=61.0"] build-backend = "setuptools.build_meta" [project] -name = "pr_agent" -version = "0.0.1" +name = "pr-agent" +version = "0.2.0" + +authors = [{name= "CodiumAI", email = "tal.r@codium.ai"}] -authors = [ - {name = "Itamar Friedman", email = "itamar.f@codium.ai"}, -] maintainers = [ - {name = "Ori Kotek", email = "ori.k@codium.ai"}, {name = "Tal Ridnik", email = "tal.r@codium.ai"}, + {name = "Ori Kotek", email = "ori.k@codium.ai"}, {name = "Hussam Lawen", email = "hussam.l@codium.ai"}, - {name = "Sagi Medina", email = "sagi.m@codium.ai"} ] -description = "CodiumAI PR-Agent is an open-source tool to automatically analyze a pull request and provide several types of feedback" + +description = "CodiumAI PR-Agent aims to help efficiently review and handle pull requests, by providing AI feedbacks and suggestions." readme = "README.md" requires-python = ">=3.10" -keywords = ["ai", "tool", "developer", "review", "agent"] -license = {file = "LICENSE", name = "Apache 2.0 License"} +keywords = ["AI", "Agents", "Pull Request", "Automation", "Code Review"] +license = {name = "Apache 2.0", file = "LICENSE"} + classifiers = [ - "Development Status :: 3 - Alpha", "Intended Audience :: Developers", - "Operating System :: Independent", "Programming Language :: Python :: 3", ] dynamic = ["dependencies"] + [tool.setuptools.dynamic] dependencies = {file = ["requirements.txt"]} [project.urls] "Homepage" = "https://github.com/Codium-ai/pr-agent" +"Documentation" = "https://pr-agent-docs.codium.ai/" [tool.setuptools] -include-package-data = false +include-package-data = true license-files = ["LICENSE"] [tool.setuptools.packages.find] where = ["."] -include = ["pr_agent"] +include = ["pr_agent*"] # include pr_agent and any sub-packages it finds under it. [project.scripts] pr-agent = "pr_agent.cli:run" diff --git a/requirements.txt b/requirements.txt index 97df2f93..924d2bb2 100644 --- a/requirements.txt +++ b/requirements.txt @@ -13,9 +13,6 @@ litellm==1.31.10 loguru==0.7.2 msrest==0.7.1 openai==1.13.3 -pinecone-client -pinecone-datasets @ git+https://github.com/mrT23/pinecone-datasets.git@main -lancedb==0.5.1 pytest==7.4.0 PyGithub==1.59.* PyYAML==6.0.1 @@ -26,4 +23,9 @@ tiktoken==0.5.2 ujson==5.8.0 uvicorn==0.22.0 tenacity==8.2.3 -# langchain==0.0.349 # uncomment this to support language LangChainOpenAIHandler +# Uncomment the following lines to enable the 'similar issue' tool +# pinecone-client +# pinecone-datasets @ git+https://github.com/mrT23/pinecone-datasets.git@main +# lancedb==0.5.1 +# uncomment this to support language LangChainOpenAIHandler +# langchain==0.0.349 From 2fccadc469512b4b47ab528c8539b5698fc94533 Mon Sep 17 00:00:00 2001 From: mrT23 Date: Fri, 22 Mar 2024 21:43:41 +0200 Subject: [PATCH 045/226] adjustments to pypi --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 80cde6f2..831d67de 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ - logo + logo
From 9a466901214fb1d10a832bf62fa3185d3722de77 Mon Sep 17 00:00:00 2001 From: mrT23 Date: Sat, 23 Mar 2024 09:55:08 +0200 Subject: [PATCH 046/226] adjustments to pypi --- docs/docs/installation/locally.md | 43 ++++++++++++++ .../docs/usage-guide/automations_and_usage.md | 2 +- pr_agent/cli.py | 58 ++++++++++--------- pr_agent/cli_pip.py | 30 ++++++++++ pr_agent/tools/pr_questions.py | 3 +- pr_agent/tools/pr_similar_issue.py | 14 +++-- 6 files changed, 117 insertions(+), 33 deletions(-) create mode 100644 pr_agent/cli_pip.py diff --git a/docs/docs/installation/locally.md b/docs/docs/installation/locally.md index 32ba77ae..13f7d5d4 100644 --- a/docs/docs/installation/locally.md +++ b/docs/docs/installation/locally.md @@ -1,3 +1,46 @@ +## Using Pip package + +1. Install the package: + +``` +pip install pr-agent +``` + +2. Run the relevant tool. Make sure to fill in the required parameters (`user_token`, `openai_key`, `pr_url`, `command`): + +```python +from pr_agent import cli +from pr_agent.config_loader import get_settings +from pr_agent.log import setup_logger + +setup_logger() + + +def main(): + # Fill in the following values + provider = "github" # GitHub provider + user_token = "..." # GitHub user token + openai_key = "..." # OpenAI key + pr_url = "..." # PR URL, for example 'https://github.com/Codium-ai/pr-agent/pull/809' + command = "/review" # Command to run (e.g. '/review', '/describe', '/ask="What is the purpose of this PR?"', ...) + + # Setting the configurations + get_settings().set("CONFIG.git_provider", provider) + get_settings().set("openai.key", openai_key) + get_settings().set("github.user_token", user_token) + + # Preparing the command + run_command = f"--pr_url={pr_url} {command.lstrip('/')}" + args = cli.set_parser().parse_args(run_command.split()) + + # Run the command. Feedback will appear in GitHub PR comments + cli.run(args=args) + + +if __name__ == '__main__': + main() +``` + ## Use Docker image (no installation required) A list of the relevant tools can be found in the [tools guide](../tools/ask.md). diff --git a/docs/docs/usage-guide/automations_and_usage.md b/docs/docs/usage-guide/automations_and_usage.md index ba21b998..d20516fd 100644 --- a/docs/docs/usage-guide/automations_and_usage.md +++ b/docs/docs/usage-guide/automations_and_usage.md @@ -1,5 +1,5 @@ ## Local repo (CLI) -When running from your local repo (CLI), your local configuration file will be used. +When running from your locally cloned PR-Agent repo (CLI), your local configuration file will be used. Examples of invoking the different tools via the CLI: - **Review**: `python -m pr_agent.cli --pr_url= review` diff --git a/pr_agent/cli.py b/pr_agent/cli.py index 83faaf8e..53feeb74 100644 --- a/pr_agent/cli.py +++ b/pr_agent/cli.py @@ -9,48 +9,52 @@ from pr_agent.log import setup_logger log_level = os.environ.get("LOG_LEVEL", "INFO") setup_logger(log_level) - - -def run(inargs=None): +def set_parser(): parser = argparse.ArgumentParser(description='AI based pull request analyzer', usage= -"""\ -Usage: cli.py --pr-url= []. -For example: -- cli.py --pr_url=... review -- cli.py --pr_url=... describe -- cli.py --pr_url=... improve -- cli.py --pr_url=... ask "write me a poem about this PR" -- cli.py --pr_url=... reflect -- cli.py --issue_url=... similar_issue + """\ + Usage: cli.py --pr-url= []. + For example: + - cli.py --pr_url=... review + - cli.py --pr_url=... describe + - cli.py --pr_url=... improve + - cli.py --pr_url=... ask "write me a poem about this PR" + - cli.py --pr_url=... reflect + - cli.py --issue_url=... similar_issue -Supported commands: -- review / review_pr - Add a review that includes a summary of the PR and specific suggestions for improvement. + Supported commands: + - review / review_pr - Add a review that includes a summary of the PR and specific suggestions for improvement. -- ask / ask_question [question] - Ask a question about the PR. + - ask / ask_question [question] - Ask a question about the PR. -- describe / describe_pr - Modify the PR title and description based on the PR's contents. + - describe / describe_pr - Modify the PR title and description based on the PR's contents. -- improve / improve_code - Suggest improvements to the code in the PR as pull request comments ready to commit. -Extended mode ('improve --extended') employs several calls, and provides a more thorough feedback + - improve / improve_code - Suggest improvements to the code in the PR as pull request comments ready to commit. + Extended mode ('improve --extended') employs several calls, and provides a more thorough feedback -- reflect - Ask the PR author questions about the PR. + - reflect - Ask the PR author questions about the PR. -- update_changelog - Update the changelog based on the PR's contents. + - update_changelog - Update the changelog based on the PR's contents. -- add_docs + - add_docs -- generate_labels + - generate_labels -Configuration: -To edit any configuration parameter from 'configuration.toml', just add -config_path=. -For example: 'python cli.py --pr_url=... review --pr_reviewer.extra_instructions="focus on the file: ..."' -""") + Configuration: + To edit any configuration parameter from 'configuration.toml', just add -config_path=. + For example: 'python cli.py --pr_url=... review --pr_reviewer.extra_instructions="focus on the file: ..."' + """) parser.add_argument('--pr_url', type=str, help='The URL of the PR to review', default=None) parser.add_argument('--issue_url', type=str, help='The URL of the Issue to review', default=None) parser.add_argument('command', type=str, help='The', choices=commands, default='review') parser.add_argument('rest', nargs=argparse.REMAINDER, default=[]) - args = parser.parse_args(inargs) + return parser + + +def run(inargs=None, args=None): + parser = set_parser() + if not args: + args = parser.parse_args(inargs) if not args.pr_url and not args.issue_url: parser.print_help() return diff --git a/pr_agent/cli_pip.py b/pr_agent/cli_pip.py new file mode 100644 index 00000000..cdab37e9 --- /dev/null +++ b/pr_agent/cli_pip.py @@ -0,0 +1,30 @@ +from pr_agent import cli +from pr_agent.config_loader import get_settings +from pr_agent.log import setup_logger + +setup_logger() + + +def main(): + # Fill in the following values + provider = "github" # GitHub provider + user_token = "..." # GitHub user token + openai_key = "..." # OpenAI key + pr_url = "..." # PR URL, for example 'https://github.com/Codium-ai/pr-agent/pull/809' + command = "/review" # Command to run (e.g. '/review', '/describe', '/ask="What is the purpose of this PR?"') + + # Setting the configurations + get_settings().set("CONFIG.git_provider", provider) + get_settings().set("openai.key", openai_key) + get_settings().set("github.user_token", user_token) + + # Preparing the command + run_command = f"--pr_url={pr_url} {command.lstrip('/')}" + args = cli.set_parser().parse_args(run_command.split()) + + # Run the command. Feedback will appear in GitHub PR comments + cli.run(args=args) + + +if __name__ == '__main__': + main() diff --git a/pr_agent/tools/pr_questions.py b/pr_agent/tools/pr_questions.py index 3849029d..4e1d3c1e 100644 --- a/pr_agent/tools/pr_questions.py +++ b/pr_agent/tools/pr_questions.py @@ -17,6 +17,7 @@ from pr_agent.servers.help import HelpMessage class PRQuestions: def __init__(self, pr_url: str, args=None, ai_handler: partial[BaseAiHandler,] = LiteLLMAIHandler): question_str = self.parse_args(args) + self.pr_url = pr_url self.git_provider = get_git_provider()(pr_url) self.main_pr_language = get_main_pr_language( self.git_provider.get_languages(), self.git_provider.get_files() @@ -49,7 +50,7 @@ class PRQuestions: return question_str async def run(self): - get_logger().info('Answering a PR question...') + get_logger().info(f'Answering a PR question about the PR {self.pr_url} ') relevant_configs = {'pr_questions': dict(get_settings().pr_questions), 'config': dict(get_settings().config)} get_logger().debug("Relevant configs", artifacts=relevant_configs) diff --git a/pr_agent/tools/pr_similar_issue.py b/pr_agent/tools/pr_similar_issue.py index 485331c0..1a4d794a 100644 --- a/pr_agent/tools/pr_similar_issue.py +++ b/pr_agent/tools/pr_similar_issue.py @@ -3,9 +3,6 @@ from enum import Enum from typing import List import openai -import pandas as pd -import pinecone -from pinecone_datasets import Dataset, DatasetMetadata from pydantic import BaseModel, Field from pr_agent.algo import MAX_TOKENS @@ -36,6 +33,12 @@ class PRSimilarIssue: index_name = self.index_name = "codium-ai-pr-agent-issues" if get_settings().pr_similar_issue.vectordb == "pinecone": + try: + import pinecone + from pinecone_datasets import Dataset, DatasetMetadata + import pandas as pd + except: + raise Exception("Please install 'pinecone' and 'pinecone_datasets' to use pinecone as vectordb") # assuming pinecone api key and environment are set in secrets file try: api_key = get_settings().pinecone.api_key @@ -107,7 +110,10 @@ class PRSimilarIssue: get_logger().info('No new issues to update') elif get_settings().pr_similar_issue.vectordb == "lancedb": - import lancedb # import lancedb only if needed + try: + import lancedb # import lancedb only if needed + except: + raise Exception("Please install lancedb to use lancedb as vectordb") self.db = lancedb.connect(get_settings().lancedb.uri) self.table = None From cfea8caf1c5d0540ecceca037cb10aa30501d5ff Mon Sep 17 00:00:00 2001 From: mrT23 Date: Sat, 23 Mar 2024 11:13:20 +0200 Subject: [PATCH 047/226] adjustments to pypi --- README.md | 3 +++ docs/docs/installation/locally.md | 14 ++++++-------- requirements-dev.txt | 2 ++ 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 831d67de..d5cfb7a2 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,9 @@ Making pull requests less painful with an AI agent ## News and Updates +### Jan 24, 2024 +PR-Agent is now available for easy installation via [pip](https://pr-agent-docs.codium.ai/installation/locally/#using-pip-package). + ### Jan 17, 2024 - A new feature is now available for the review tool: [`require_can_be_split_review`](https://pr-agent-docs.codium.ai/tools/review/#enabledisable-features). If set to true, the tool will add a section that checks if the PR contains several themes, and can be split into smaller PRs. diff --git a/docs/docs/installation/locally.md b/docs/docs/installation/locally.md index 13f7d5d4..e493862a 100644 --- a/docs/docs/installation/locally.md +++ b/docs/docs/installation/locally.md @@ -1,20 +1,18 @@ -## Using Pip package +## Using pip package -1. Install the package: +Install the package: ``` pip install pr-agent ``` -2. Run the relevant tool. Make sure to fill in the required parameters (`user_token`, `openai_key`, `pr_url`, `command`): +Then run the relevant tool with the script below. +
+Make sure to fill in the required parameters (`user_token`, `openai_key`, `pr_url`, `command`): ```python from pr_agent import cli from pr_agent.config_loader import get_settings -from pr_agent.log import setup_logger - -setup_logger() - def main(): # Fill in the following values @@ -41,7 +39,7 @@ if __name__ == '__main__': main() ``` -## Use Docker image (no installation required) +## Using Docker image A list of the relevant tools can be found in the [tools guide](../tools/ask.md). diff --git a/requirements-dev.txt b/requirements-dev.txt index 70613be0..1af82d00 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1 +1,3 @@ pytest==7.4.0 +poetry +twine \ No newline at end of file From 8e39394bcfa8ab8555c27ae8d38e0c2960c700a7 Mon Sep 17 00:00:00 2001 From: mrT23 Date: Sat, 23 Mar 2024 11:16:21 +0200 Subject: [PATCH 048/226] adjustments to pypi --- README.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index d5cfb7a2..0f107870 100644 --- a/README.md +++ b/README.md @@ -33,19 +33,19 @@ Making pull requests less painful with an AI agent ## News and Updates -### Jan 24, 2024 +### March 24, 2024 PR-Agent is now available for easy installation via [pip](https://pr-agent-docs.codium.ai/installation/locally/#using-pip-package). -### Jan 17, 2024 +### March 17, 2024 - A new feature is now available for the review tool: [`require_can_be_split_review`](https://pr-agent-docs.codium.ai/tools/review/#enabledisable-features). If set to true, the tool will add a section that checks if the PR contains several themes, and can be split into smaller PRs. -### Jan 10, 2024 +### March 10, 2024 - A new [knowledge-base website](https://pr-agent-docs.codium.ai/) for PR-Agent is now available. It includes detailed information about the different tools, usage guides and more, in an accessible and organized format. -### Jan 8, 2024 +### March 8, 2024 - A new tool, [Find Similar Code](https://pr-agent-docs.codium.ai/tools/similar_code/) ๐Ÿ’Ž is now available.
This tool retrieves the most similar code components from inside the organization's codebase, or from open-source code: @@ -244,7 +244,8 @@ To use your own version of PR-Agent, you first need to acquire two tokens: There are several ways to use PR-Agent: **Locally** -- [Use Docker image (no installation required)](https://pr-agent-docs.codium.ai/installation/locally/#use-docker-image-no-installation-required) +- [Using pip package](https://pr-agent-docs.codium.ai/installation/locally/#using-pip-package) +- [Using Docker image](https://pr-agent-docs.codium.ai/installation/locally/#using-docker-image) - [Run from source](https://pr-agent-docs.codium.ai/installation/locally/#run-from-source) **GitHub specific methods** From ee4798accaf1f8050410ba3634d278d765e41b5e Mon Sep 17 00:00:00 2001 From: mrT23 Date: Sat, 23 Mar 2024 16:16:32 +0200 Subject: [PATCH 049/226] adjustments to pypi --- docs/docs/installation/locally.md | 6 +----- pr_agent/cli.py | 7 +++++++ pr_agent/cli_pip.py | 9 +-------- pyproject.toml | 2 +- 4 files changed, 10 insertions(+), 14 deletions(-) diff --git a/docs/docs/installation/locally.md b/docs/docs/installation/locally.md index e493862a..123a6c03 100644 --- a/docs/docs/installation/locally.md +++ b/docs/docs/installation/locally.md @@ -27,12 +27,8 @@ def main(): get_settings().set("openai.key", openai_key) get_settings().set("github.user_token", user_token) - # Preparing the command - run_command = f"--pr_url={pr_url} {command.lstrip('/')}" - args = cli.set_parser().parse_args(run_command.split()) - # Run the command. Feedback will appear in GitHub PR comments - cli.run(args=args) + cli.run_command(pr_url, command) if __name__ == '__main__': diff --git a/pr_agent/cli.py b/pr_agent/cli.py index 53feeb74..88759e16 100644 --- a/pr_agent/cli.py +++ b/pr_agent/cli.py @@ -50,6 +50,13 @@ def set_parser(): parser.add_argument('rest', nargs=argparse.REMAINDER, default=[]) return parser +def run_command(pr_url, command): + # Preparing the command + run_command = f"--pr_url={pr_url} {command.lstrip('/')}" + args = set_parser().parse_args(run_command.split()) + + # Run the command. Feedback will appear in GitHub PR comments + run(args=args) def run(inargs=None, args=None): parser = set_parser() diff --git a/pr_agent/cli_pip.py b/pr_agent/cli_pip.py index cdab37e9..caa56f0c 100644 --- a/pr_agent/cli_pip.py +++ b/pr_agent/cli_pip.py @@ -1,8 +1,5 @@ from pr_agent import cli from pr_agent.config_loader import get_settings -from pr_agent.log import setup_logger - -setup_logger() def main(): @@ -18,12 +15,8 @@ def main(): get_settings().set("openai.key", openai_key) get_settings().set("github.user_token", user_token) - # Preparing the command - run_command = f"--pr_url={pr_url} {command.lstrip('/')}" - args = cli.set_parser().parse_args(run_command.split()) - # Run the command. Feedback will appear in GitHub PR comments - cli.run(args=args) + cli.run_command(pr_url, command) if __name__ == '__main__': diff --git a/pyproject.toml b/pyproject.toml index f4be6371..651d8a4f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "pr-agent" -version = "0.2.0" +version = "0.2.1" authors = [{name= "CodiumAI", email = "tal.r@codium.ai"}] From 07f5025b03395fd3c59e5932f6791bff4fd9bfd5 Mon Sep 17 00:00:00 2001 From: mrT23 Date: Mon, 25 Mar 2024 08:51:59 +0200 Subject: [PATCH 050/226] Refactor help text for clarity and update configuration links in help.py; standardize variable naming in cli.py --- pr_agent/cli.py | 4 +- pr_agent/servers/help.py | 167 ++------------------------------------- 2 files changed, 10 insertions(+), 161 deletions(-) diff --git a/pr_agent/cli.py b/pr_agent/cli.py index 88759e16..209d3641 100644 --- a/pr_agent/cli.py +++ b/pr_agent/cli.py @@ -52,8 +52,8 @@ def set_parser(): def run_command(pr_url, command): # Preparing the command - run_command = f"--pr_url={pr_url} {command.lstrip('/')}" - args = set_parser().parse_args(run_command.split()) + run_command_str = f"--pr_url={pr_url} {command.lstrip('/')}" + args = set_parser().parse_args(run_command_str.split()) # Run the command. Feedback will appear in GitHub PR comments run(args=args) diff --git a/pr_agent/servers/help.py b/pr_agent/servers/help.py index 835ad8b9..cee506fc 100644 --- a/pr_agent/servers/help.py +++ b/pr_agent/servers/help.py @@ -22,116 +22,22 @@ class HelpMessage: @staticmethod def get_review_usage_guide(): output ="**Overview:**\n" - output +="The `review` tool scans the PR code changes, and generates a PR review. The tool can be triggered [automatically](https://pr-agent-docs.codium.ai/usage-guide/automations_and_usage/#github-app-automatic-tools-when-a-new-pr-is-opened) every time a new PR is opened, or can be invoked manually by commenting on any PR.\n" + output +=("The `review` tool scans the PR code changes, and generates a PR review which includes several types of feedbacks, such as possible issues, security issues, relevant test in the PR. More feedbacks can be [added](https://pr-agent-docs.codium.ai/tools/review/#general-configurations) by configuring the tool.\n\n" + "The tool can be triggered [automatically](https://pr-agent-docs.codium.ai/usage-guide/automations_and_usage/#github-app-automatic-tools-when-a-new-pr-is-opened) every time a new PR is opened, or can be invoked manually by commenting on any PR.\n") output +="""\ -When commenting, to edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/configuration.toml#L19) related to the review tool (`pr_reviewer` section), use the following template: +- When commenting, to edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/configuration.toml#L23) related to the review tool (`pr_reviewer` section), use the following template: ``` /review --pr_reviewer.some_config1=... --pr_reviewer.some_config2=... ``` -With a [configuration file](https://pr-agent-docs.codium.ai/usage-guide/configuration_options/), use the following template: +- With a [configuration file](https://pr-agent-docs.codium.ai/usage-guide/configuration_options/), use the following template: ``` [pr_reviewer] some_config1=... some_config2=... ``` """ - output +="\n\n" - # extra instructions - output += "\n\n" - - # automation - output += "\n\n" - -# # code feedback -# output += "\n\n" - - # auto-labels - output += "\n\n" - - # extra sub-tools - output += "\n\n" - - output += "\n\n" - - # general - output += "\n\n\n\n" - - output += "
Utilizing extra instructions
\n\n" - output += '''\ -The `review` tool can be configured with extra instructions, which can be used to guide the model to a feedback tailored to the needs of your project. - -Be specific, clear, and concise in the instructions. With extra instructions, you are the prompter. Specify the relevant sub-tool, and the relevant aspects of the PR that you want to emphasize. - -Examples for extra instructions: -``` -[pr_reviewer] # /review # -extra_instructions=""" -In the 'possible issues' section, emphasize the following: -- Does the code logic cover relevant edge cases? -- Is the code logic clear and easy to understand? -- Is the code logic efficient? -... -""" -``` -Use triple quotes to write multi-line instructions. Use bullet points to make the instructions more readable. - ''' - output += "\n\n
How to enable\\disable automation
\n\n" - output += """\ -- When you first install PR-Agent app, the [default mode](https://pr-agent-docs.codium.ai/usage-guide/automations_and_usage/#github-app-automatic-tools-when-a-new-pr-is-opened) for the `review` tool is: -``` -pr_commands = ["/review", ...] -``` -meaning the `review` tool will run automatically on every PR, with the default configuration. -Edit this field to enable/disable the tool, or to change the used configurations - """ - output += "\n\n
About the 'Code feedback' section
\n\n" -# output+="""\ -# The `review` tool provides several type of feedbacks, one of them is code suggestions. -# If you are interested **only** in the code suggestions, it is recommended to use the [`improve`](https://github.com/Codium-ai/pr-agent/blob/main/docs/IMPROVE.md) feature instead, since it dedicated only to code suggestions, and usually gives better results. -# Use the `review` tool if you want to get a more comprehensive feedback, which includes code suggestions as well. -# """ -# output += "\n\n
Auto-labels
\n\n" - output+="""\ -The `review` tool can auto-generate two specific types of labels for a PR: -- a `possible security issue` label, that detects possible [security issues](https://github.com/Codium-ai/pr-agent/blob/tr/user_description/pr_agent/settings/pr_reviewer_prompts.toml#L136) (`enable_review_labels_security` flag) -- a `Review effort [1-5]: x` label, where x is the estimated effort to review the PR (`enable_review_labels_effort` flag) -""" - output += "\n\n
Extra sub-tools
\n\n" - output += """\ -The `review` tool provides a collection of possible feedbacks about a PR. -It is recommended to review the [possible options](https://pr-agent-docs.codium.ai/tools/review/#enabledisable-features), and choose the ones relevant for your use case. -Some of the feature that are disabled by default are quite useful, and should be considered for enabling. For example: -`require_score_review`, `require_soc2_ticket`, `require_can_be_split_review`, and more. -""" - output += "\n\n
Auto-approve PRs
\n\n" - output += '''\ -By invoking: -``` -/review auto_approve -``` -The tool will automatically approve the PR, and add a comment with the approval. - - -To ensure safety, the auto-approval feature is disabled by default. To enable auto-approval, you need to actively set in a pre-defined configuration file the following: -``` -[pr_reviewer] -enable_auto_approval = true -``` -(this specific flag cannot be set with a command line argument, only in the configuration file, committed to the repository) - - -You can also enable auto-approval only if the PR meets certain requirements, such as that the `estimated_review_effort` is equal or below a certain threshold, by adjusting the flag: -``` -[pr_reviewer] -maximal_review_effort = 5 -``` -''' - output += "\n\n
More PR-Agent commands
\n\n" - output += HelpMessage.get_general_bot_help_text() - output += "\n\n
" - - output += f"\n\nSee the [review usage](https://pr-agent-docs.codium.ai/tools/review/) page for a comprehensive guide on using this tool.\n\n" + output += f"\n\nSee the review [usage page](https://pr-agent-docs.codium.ai/tools/review/) for a comprehensive guide on using this tool.\n\n" return output @@ -276,13 +182,13 @@ Note that the tool does not have "memory" of previous questions, and answers eac output += "The `improve` tool scans the PR code changes, and automatically generates suggestions for improving the PR code. " output += "The tool can be triggered [automatically](https://pr-agent-docs.codium.ai/usage-guide/automations_and_usage/#github-app-automatic-tools-when-a-new-pr-is-opened) every time a new PR is opened, or can be invoked manually by commenting on a PR.\n" output += """\ -When commenting, to edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/configuration.toml#L69) related to the improve tool (`pr_code_suggestions` section), use the following template: +- When commenting, to edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/configuration.toml#L78) related to the improve tool (`pr_code_suggestions` section), use the following template: ``` /improve --pr_code_suggestions.some_config1=... --pr_code_suggestions.some_config2=... ``` -With a [configuration file](https://pr-agent-docs.codium.ai/usage-guide/configuration_options/), use the following template: +- With a [configuration file](https://pr-agent-docs.codium.ai/usage-guide/configuration_options/), use the following template: ``` [pr_code_suggestions] @@ -291,64 +197,7 @@ some_config2=... ``` """ - output += "\n\n" - # automation - output += "\n\n" - - # extra instructions - output += "\n\n" - - # suggestions quality - output += "\n\n\n\n"\ - - # general - output += "\n\n\n\n" - - output += "
Enabling\\disabling automation
\n\n" - output += """\ -When you first install the app, the [default mode](https://pr-agent-docs.codium.ai/usage-guide/automations_and_usage/#github-app-automatic-tools-when-a-new-pr-is-opened) for the improve tool is: - -``` -pr_commands = ["/improve --pr_code_suggestions.summarize=true", ...] -``` - -meaning the `improve` tool will run automatically on every PR, with summarization enabled. Delete this line to disable the tool from running automatically. -""" - output += "\n\n
Utilizing extra instructions
\n\n" - output += '''\ -Extra instructions are very important for the `improve` tool, since they enable to guide the model to suggestions that are more relevant to the specific needs of the project. - -Be specific, clear, and concise in the instructions. With extra instructions, you are the prompter. Specify relevant aspects that you want the model to focus on. - -Examples for extra instructions: - -``` -[pr_code_suggestions] # /improve # -extra_instructions=""" -Emphasize the following aspects: -- Does the code logic cover relevant edge cases? -- Is the code logic clear and easy to understand? -- Is the code logic efficient? -... -""" -``` - -Use triple quotes to write multi-line instructions. Use bullet points to make the instructions more readable. - ''' - output += "\n\n
A note on code suggestions quality
\n\n" - output += """\ -- While the current AI for code is getting better and better (GPT-4), it's not flawless. Not all the suggestions will be perfect, and a user should not accept all of them automatically. -- Suggestions are not meant to be simplistic. Instead, they aim to give deep feedback and raise questions, ideas and thoughts to the user, who can then use his judgment, experience, and understanding of the code base. -- Recommended to use the 'extra_instructions' field to guide the model to suggestions that are more relevant to the specific needs of the project, or use the [custom suggestions :gem:](https://pr-agent-docs.codium.ai/tools/custom_suggestions/) tool -- With large PRs, best quality will be obtained by using 'improve --extended' mode. - - -""" - output += "\n\n
More PR-Agent commands
\n\n" - output += HelpMessage.get_general_bot_help_text() - output += "\n\n
" - - output += f"\n\nSee the [improve usage](https://pr-agent-docs.codium.ai/tools/improve/) page for a more comprehensive guide on using this tool.\n\n" + output += f"\n\nSee the improve [usage page](https://pr-agent-docs.codium.ai/tools/improve/) for a comprehensive guide on using this tool.\n\n" return output \ No newline at end of file From 695f0706a8668b0d260da00c4418a846fa7f0b5b Mon Sep 17 00:00:00 2001 From: mrT23 Date: Mon, 25 Mar 2024 08:53:13 +0200 Subject: [PATCH 051/226] Refactor help text for clarity and update configuration links in help.py; standardize variable naming in cli.py --- pr_agent/servers/help.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pr_agent/servers/help.py b/pr_agent/servers/help.py index cee506fc..364088ec 100644 --- a/pr_agent/servers/help.py +++ b/pr_agent/servers/help.py @@ -22,7 +22,7 @@ class HelpMessage: @staticmethod def get_review_usage_guide(): output ="**Overview:**\n" - output +=("The `review` tool scans the PR code changes, and generates a PR review which includes several types of feedbacks, such as possible issues, security issues, relevant test in the PR. More feedbacks can be [added](https://pr-agent-docs.codium.ai/tools/review/#general-configurations) by configuring the tool.\n\n" + output +=("The `review` tool scans the PR code changes, and generates a PR review which includes several types of feedbacks, such as possible PR issues, security threats and relevant test in the PR. More feedbacks can be [added](https://pr-agent-docs.codium.ai/tools/review/#general-configurations) by configuring the tool.\n\n" "The tool can be triggered [automatically](https://pr-agent-docs.codium.ai/usage-guide/automations_and_usage/#github-app-automatic-tools-when-a-new-pr-is-opened) every time a new PR is opened, or can be invoked manually by commenting on any PR.\n") output +="""\ - When commenting, to edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/configuration.toml#L23) related to the review tool (`pr_reviewer` section), use the following template: From 3cdadb3ad18fb62799646fe42b4ff1f52cb79206 Mon Sep 17 00:00:00 2001 From: mrT23 Date: Mon, 25 Mar 2024 09:04:07 +0200 Subject: [PATCH 052/226] always ignore bot --- pr_agent/servers/github_app.py | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/pr_agent/servers/github_app.py b/pr_agent/servers/github_app.py index 80a673d7..9c0a5cee 100644 --- a/pr_agent/servers/github_app.py +++ b/pr_agent/servers/github_app.py @@ -118,15 +118,9 @@ async def handle_new_pr_opened(body: Dict[str, Any], event: str, sender: str, sender_id: str, - sender_type: str, action: str, log_context: Dict[str, Any], agent: PRAgent): - # logic to ignore PRs opened by bot - if get_settings().get("GITHUB_APP.IGNORE_BOT_PR", False) and sender_type == "Bot": - get_logger().info(f"Ignoring PR from '{sender=}' due to github_app.ignore_bot_pr setting") - return {} - title = body.get("pull_request", {}).get("title", "") # logic to ignore PRs with specific titles (e.g. "[Auto] ...") @@ -261,6 +255,11 @@ async def handle_request(body: Dict[str, Any], event: str): agent = PRAgent() log_context, sender, sender_id, sender_type = get_log_context(body, event, action, build_number) + # logic to ignore PRs opened by bot + if get_settings().get("GITHUB_APP.IGNORE_BOT_PR", False) and sender_type == "Bot": + get_logger().info(f"Ignoring PR from '{sender=}' due to github_app.ignore_bot_pr setting") + return {} + # handle comments on PRs if action == 'created': get_logger().debug(f'Request body', artifact=body, event=event) @@ -268,7 +267,7 @@ async def handle_request(body: Dict[str, Any], event: str): # handle new PRs elif event == 'pull_request' and action != 'synchronize' and action != 'closed': get_logger().debug(f'Request body', artifact=body, event=event) - await handle_new_pr_opened(body, event, sender, sender_id, sender_type, action, log_context, agent) + await handle_new_pr_opened(body, event, sender, sender_id, action, log_context, agent) # handle pull_request event with synchronize action - "push trigger" for new commits elif event == 'pull_request' and action == 'synchronize': get_logger().debug(f'Request body', artifact=body, event=event) From 903d74b2f791a888849a62174815f8f4ac10c116 Mon Sep 17 00:00:00 2001 From: mrT23 Date: Mon, 25 Mar 2024 11:42:24 +0200 Subject: [PATCH 053/226] ignore_bot_pr = true --- pr_agent/settings/configuration.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pr_agent/settings/configuration.toml b/pr_agent/settings/configuration.toml index 627e2161..837c71d3 100644 --- a/pr_agent/settings/configuration.toml +++ b/pr_agent/settings/configuration.toml @@ -156,7 +156,7 @@ push_commands = [ "/review --pr_reviewer.num_code_suggestions=0", ] ignore_pr_title = [] -ignore_bot_pr = false +ignore_bot_pr = true [gitlab] url = "https://gitlab.com" # URL to the gitlab service From 9c284e64cfa04f588dcdfc4f3b4a36935f5e9d8e Mon Sep 17 00:00:00 2001 From: mrT23 Date: Mon, 25 Mar 2024 12:27:45 +0200 Subject: [PATCH 054/226] dont log pr-agent bot --- pr_agent/servers/github_app.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pr_agent/servers/github_app.py b/pr_agent/servers/github_app.py index 9c0a5cee..2e14051b 100644 --- a/pr_agent/servers/github_app.py +++ b/pr_agent/servers/github_app.py @@ -257,7 +257,8 @@ async def handle_request(body: Dict[str, Any], event: str): # logic to ignore PRs opened by bot if get_settings().get("GITHUB_APP.IGNORE_BOT_PR", False) and sender_type == "Bot": - get_logger().info(f"Ignoring PR from '{sender=}' due to github_app.ignore_bot_pr setting") + if 'pr-agent' not in sender: + get_logger().info(f"Ignoring PR from '{sender=}' because it is a bot") return {} # handle comments on PRs From d064a352ad37ed3bb234b1891d1b24f5f353d03e Mon Sep 17 00:00:00 2001 From: Yuta Nishi Date: Tue, 26 Mar 2024 14:47:05 +0900 Subject: [PATCH 055/226] feat(pr_agent): add support for gpt-4-turbo-preview model and update default settings --- pr_agent/algo/__init__.py | 1 + pr_agent/settings/configuration.toml | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/pr_agent/algo/__init__.py b/pr_agent/algo/__init__.py index 9e05ed9f..19968be5 100644 --- a/pr_agent/algo/__init__.py +++ b/pr_agent/algo/__init__.py @@ -10,6 +10,7 @@ MAX_TOKENS = { 'gpt-4-32k': 32000, 'gpt-4-1106-preview': 128000, # 128K, but may be limited by config.max_model_tokens 'gpt-4-0125-preview': 128000, # 128K, but may be limited by config.max_model_tokens + 'gpt-4-turbo-preview': 128000, # 128K, but may be limited by config.max_model_tokens 'claude-instant-1': 100000, 'claude-2': 100000, 'command-nightly': 4096, diff --git a/pr_agent/settings/configuration.toml b/pr_agent/settings/configuration.toml index 837c71d3..07ebdcce 100644 --- a/pr_agent/settings/configuration.toml +++ b/pr_agent/settings/configuration.toml @@ -1,6 +1,6 @@ [config] -model="gpt-4" # "gpt-4-0125-preview" -model_turbo="gpt-4-0125-preview" +model="gpt-4" # "gpt-4-turbo-preview" +model_turbo="gpt-4-turbo-preview" fallback_models=["gpt-3.5-turbo-16k"] git_provider="github" publish_output=true From 1491bcba961bb6b65d9a8faacdeefb7ed2b17afd Mon Sep 17 00:00:00 2001 From: mrT23 Date: Tue, 26 Mar 2024 08:09:33 +0200 Subject: [PATCH 056/226] logs --- pr_agent/servers/github_app.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pr_agent/servers/github_app.py b/pr_agent/servers/github_app.py index 2e14051b..bc7042b1 100644 --- a/pr_agent/servers/github_app.py +++ b/pr_agent/servers/github_app.py @@ -231,10 +231,11 @@ def get_log_context(body, event, action, build_number): sender_type = body.get("sender", {}).get("type") repo = body.get("repository", {}).get("full_name", "") git_org = body.get("organization", {}).get("login", "") + installation_id = body.get("installation", {}).get("id", "") app_name = get_settings().get("CONFIG.APP_NAME", "Unknown") log_context = {"action": action, "event": event, "sender": sender, "server_type": "github_app", "request_id": uuid.uuid4().hex, "build_number": build_number, "app_name": app_name, - "repo": repo, "git_org": git_org} + "repo": repo, "git_org": git_org, "installation_id": installation_id} except Exception as e: get_logger().error("Failed to get log context", e) log_context = {} From a7494746dfd6504d419252a355d33494fb4a8e94 Mon Sep 17 00:00:00 2001 From: Riya Amemiya Date: Tue, 26 Mar 2024 16:21:30 +0900 Subject: [PATCH 057/226] revert default model --- pr_agent/settings/configuration.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pr_agent/settings/configuration.toml b/pr_agent/settings/configuration.toml index 07ebdcce..837c71d3 100644 --- a/pr_agent/settings/configuration.toml +++ b/pr_agent/settings/configuration.toml @@ -1,6 +1,6 @@ [config] -model="gpt-4" # "gpt-4-turbo-preview" -model_turbo="gpt-4-turbo-preview" +model="gpt-4" # "gpt-4-0125-preview" +model_turbo="gpt-4-0125-preview" fallback_models=["gpt-3.5-turbo-16k"] git_provider="github" publish_output=true From 736c8a695306830bdcff445d07ba901960e060d9 Mon Sep 17 00:00:00 2001 From: Almog Lavi Date: Tue, 26 Mar 2024 23:00:57 +0200 Subject: [PATCH 058/226] Refactor markdown image syntax and enhance documentation presentation --- .github/workflows/docs-ci.yaml | 1 + docs/docs/core-abilities/index.md | 2 +- docs/docs/css/custom.css | 9 ++ docs/docs/index.md | 90 ++++--------------- docs/docs/installation/pr_agent_pro.md | 16 ++-- docs/docs/tools/analyze.md | 12 ++- docs/docs/tools/ask.md | 6 +- docs/docs/tools/ci_feedback.md | 9 +- docs/docs/tools/custom_labels.md | 7 +- docs/docs/tools/custom_suggestions.md | 7 +- docs/docs/tools/describe.md | 49 ++-------- docs/docs/tools/documentation.md | 6 +- docs/docs/tools/improve.md | 14 +-- docs/docs/tools/review.md | 36 ++------ docs/docs/tools/similar_code.md | 12 +-- docs/docs/tools/similar_issues.md | 6 +- docs/docs/tools/test.md | 6 +- docs/docs/tools/update_changelog.md | 5 +- .../docs/usage-guide/configuration_options.md | 2 +- docs/docs/usage-guide/mail_notifications.md | 4 +- docs/mkdocs.yml | 2 + 21 files changed, 96 insertions(+), 205 deletions(-) diff --git a/.github/workflows/docs-ci.yaml b/.github/workflows/docs-ci.yaml index 1648fd44..b260039e 100644 --- a/.github/workflows/docs-ci.yaml +++ b/.github/workflows/docs-ci.yaml @@ -29,4 +29,5 @@ jobs: mkdocs-material- - run: pip install mkdocs-material - run: pip install "mkdocs-material[imaging]" + - run: pip install mkdocs-glightbox - run: mkdocs gh-deploy -f docs/mkdocs.yml --force diff --git a/docs/docs/core-abilities/index.md b/docs/docs/core-abilities/index.md index 074d4c09..0a97aaf3 100644 --- a/docs/docs/core-abilities/index.md +++ b/docs/docs/core-abilities/index.md @@ -43,7 +43,7 @@ We use [tiktoken](https://github.com/openai/tiktoken) to tokenize the patches af #### Example - +![Core Abilities](https://codium.ai/images/git_patch_logic.png){width=768} ## YAML Prompting TBD diff --git a/docs/docs/css/custom.css b/docs/docs/css/custom.css index 2f963ccd..e79736b4 100644 --- a/docs/docs/css/custom.css +++ b/docs/docs/css/custom.css @@ -16,3 +16,12 @@ font-size: 20px; margin-left: 0px !important; } + +.md-content img { + border-width: 1px; + border-style: solid; + border-color: black; + outline-width: 3px; + outline-style: solid; + outline-color: darkgray; + } \ No newline at end of file diff --git a/docs/docs/index.md b/docs/docs/index.md index ed02e502..246680df 100644 --- a/docs/docs/index.md +++ b/docs/docs/index.md @@ -47,83 +47,25 @@ PR-Agent offers extensive pull request functionalities across various git provid ## Example results -
-

/describe

-
-

- -

-
-
+#### [/describe](https://github.com/Codium-ai/pr-agent/pull/530) +
+![/describe](https://www.codium.ai/images/pr_agent/describe_new_short_main.png){width=512} +
-

/review

-
-

- - - -

-
-
+#### [/review](https://github.com/Codium-ai/pr-agent/pull/732#issuecomment-1975099151) +
+![/review](https://www.codium.ai/images/pr_agent/review_new_short_main.png){width=512} +
-

/improve

-
-

- - - -

-
-
- -

/generate_labels

-
-

- -

-
- -[//]: # (

/reflect_and_review:

) - -[//]: # (
) - -[//]: # (

) - -[//]: # () - -[//]: # (

) - -[//]: # (
) - -[//]: # (

/ask:

) - -[//]: # (
) - -[//]: # (

) - -[//]: # () - -[//]: # (

) - -[//]: # (
) - -[//]: # (

/improve:

) - -[//]: # (
) - -[//]: # (

) - -[//]: # () - -[//]: # (

) - -[//]: # (
) -
- - -
-
+#### [/improve](https://github.com/Codium-ai/pr-agent/pull/732#issuecomment-1975099159) +
+![/improve](https://www.codium.ai/images/pr_agent/improve_new_short_main.png){width=512} +
+#### [/generate_labels](https://github.com/Codium-ai/pr-agent/pull/530) +
+![/generate_labels](https://www.codium.ai/images/pr_agent/geneare_custom_labels_main_short.png){width=300} +
## How it works diff --git a/docs/docs/installation/pr_agent_pro.md b/docs/docs/installation/pr_agent_pro.md index cb371df7..bf3f32de 100644 --- a/docs/docs/installation/pr_agent_pro.md +++ b/docs/docs/installation/pr_agent_pro.md @@ -7,9 +7,7 @@ See [here](https://pr-agent-docs.codium.ai/#pr-agent-pro) for more details about Interested parties can subscribe to PR-Agent Pro through the following [link](https://www.codium.ai/pricing/). After subscribing, you are granted the ability to easily install the application across any of your repositories. - - - +![PR Agent Pro](https://codium.ai/images/pr_agent/pr_agent_pro_install.png){width=468} Each user who wants to use PR-Agent pro needs to buy a seat. Initially, CodiumAI offers a two-week trial period at no cost, after which continued access requires each user to secure a personal seat. @@ -27,7 +25,9 @@ Since GitLab platform does not support apps, installing PR-Agent Pro for GitLab Acquire a personal, project or group level access token. Enable the โ€œapiโ€ scope in order to allow PR-Agent to read pull requests, comment and respond to requests. - +
+![Step 1](https://www.codium.ai/images/pr_agent/gitlab_pro_pat.png){width=750} +
Store the token in a safe place, you wonโ€™t be able to access it again after it was generated. @@ -42,7 +42,9 @@ You should see "Success!" displayed above the Submit button, and a shared secret Install a webhook for your repository or groups, by clicking โ€œwebhooksโ€ on the settings menu. Click the โ€œAdd new webhookโ€ button. - +
+![Step 3.1](https://www.codium.ai/images/pr_agent/gitlab_pro_add_webhook.png) +
In the webhook definition form, fill in the following fields: URL: https://pro.gitlab.pr-agent.codium.ai/webhook @@ -51,7 +53,9 @@ Secret token: Your CodiumAI key Trigger: Check the โ€˜commentsโ€™ and โ€˜merge request eventsโ€™ boxes. Enable SSL verification: Check the box. - +
+![Step 3.2](https://www.codium.ai/images/pr_agent/gitlab_pro_webhooks.png){width=750} +
### Step 4 diff --git a/docs/docs/tools/analyze.md b/docs/docs/tools/analyze.md index 1264be7f..3b7c6d58 100644 --- a/docs/docs/tools/analyze.md +++ b/docs/docs/tools/analyze.md @@ -11,13 +11,11 @@ It can be invoked manually by commenting on any PR: ## Example usage An example [result](https://github.com/Codium-ai/pr-agent/pull/546#issuecomment-1868524805): - - - - - - - +![Analyze 1](https://codium.ai/images/pr_agent/analyze_1.png){width=750} +→ +![Analyze 2](https://codium.ai/images/pr_agent/analyze_2.png){width=750} +→ +![Analyze 3](https://codium.ai/images/pr_agent/analyze_3.png){width=750} **Notes** diff --git a/docs/docs/tools/ask.md b/docs/docs/tools/ask.md index e6e02160..453807fd 100644 --- a/docs/docs/tools/ask.md +++ b/docs/docs/tools/ask.md @@ -7,9 +7,9 @@ It can be invoked manually by commenting on any PR: ``` For example: - +![Ask Comment](https://codium.ai/images/pr_agent/ask_comment.png){width=768} - +![Ask](https://codium.ai/images/pr_agent/ask.png){width=768} ## Ask lines @@ -18,6 +18,6 @@ You can run `/ask` on specific lines of code in the PR from the PR's diff view. - To select multiple lines, click on the '+' sign of the first line and then hold and drag to select the rest of the lines. - write `/ask "..."` in the comment box and press `Add single comment` button. - +![Ask Line](https://codium.ai/images/pr_agent/Ask_line.png){width=768} Note that the tool does not have "memory" of previous questions, and answers each question independently. diff --git a/docs/docs/tools/ci_feedback.md b/docs/docs/tools/ci_feedback.md index 2949f138..998fef56 100644 --- a/docs/docs/tools/ci_feedback.md +++ b/docs/docs/tools/ci_feedback.md @@ -8,13 +8,10 @@ The tool analyzes the failed checks and provides several feedbacks: - Failure summary - Relevant error logs - - - +![Failed Check 1](https://www.codium.ai/images/pr_agent/failed_check1.png){width=768} + → - - - +![Failed Check 2](https://www.codium.ai/images/pr_agent/failed_check2.png){width=768} ___ diff --git a/docs/docs/tools/custom_labels.md b/docs/docs/tools/custom_labels.md index d8dbb1a1..29f1a9e2 100644 --- a/docs/docs/tools/custom_labels.md +++ b/docs/docs/tools/custom_labels.md @@ -9,11 +9,11 @@ For example: If we wish to add detect changes to SQL queries in a given PR, we can add the following custom label along with its description: - +![Custom labels list](https://codium.ai/images/pr_agent/custom_labels_list.png){width=768} When running the `generate_labels` tool on a PR that includes changes in SQL queries, it will automatically suggest the custom label: - +![Custom labels published](https://codium.ai/images/pr_agent/custom_label_published.png){width=768} Note that in addition to the dedicated tool `generate_labels`, the custom labels will also be used by the `describe` tool. @@ -36,7 +36,8 @@ b. Add/edit the custom labels. It should be formatted as follows: * Label name: The name of the custom label. * Description: Start the description of with prefix `pr_agent:`, for example: `pr_agent: Description of when AI should suggest this label`.
The description should be comprehensive and detailed, indicating when to add the desired label. - + +![Add native custom labels](https://codium.ai/images/pr_agent/add_native_custom_labels.png){width=880} c. Now the custom labels will be included in the `generate_labels` tool. diff --git a/docs/docs/tools/custom_suggestions.md b/docs/docs/tools/custom_suggestions.md index 0b19ecef..85720c11 100644 --- a/docs/docs/tools/custom_suggestions.md +++ b/docs/docs/tools/custom_suggestions.md @@ -43,10 +43,9 @@ The instructions above are just an example. We want to emphasize that the prompt Results obtained with the prompt above: - - - - +![Custom suggestions prompt](https://codium.ai/images/pr_agent/custom_suggestions_prompt.png){width=512} +→ +![Custom suggestions results](https://codium.ai/images/pr_agent/custom_suggestions_result.png){width=768} ## Configuration options diff --git a/docs/docs/tools/describe.md b/docs/docs/tools/describe.md index cf7ccdfb..e0de5153 100644 --- a/docs/docs/tools/describe.md +++ b/docs/docs/tools/describe.md @@ -7,17 +7,9 @@ The tool can be triggered automatically every time a new PR is [opened](../usage ``` For example: - - - - - +![Describe comment](https://codium.ai/images/pr_agent/describe_comment.png){width=512} - - - - - +![Describe New](https://codium.ai/images/pr_agent/describe_new.png){width=512} @@ -57,29 +49,17 @@ This feature enables you to copy the `changes walkthrough` table to the "Files c To copy the `changes walkthrough` table to the "Files changed" tab, you can click on the checkbox that appears PR Description status message below the main PR Description: - - - - - +![Add table checkbox](https://codium.ai/images/pr_agent/add_table_checkbox.png){width=512} If you prefer to have the file summaries appear in the "Files changed" tab on every PR, change the `pr_description.inline_file_summary` parameter in the configuration file, possible values are: - `'table'`: File changes walkthrough table will be displayed on the top of the "Files changed" tab, in addition to the "Conversation" tab. - - - - - +![Diffview table](https://codium.ai/images/pr_agent/diffview-table.png){width=512} - `true`: A collapsable file comment with changes title and a changes summary for each file in the PR. - - - - - +![Diffview changes](https://codium.ai/images/pr_agent/diffview_changes.png){width=512} - `false` (`default`): File changes walkthrough will be added only to the "Conversation" tab. @@ -99,11 +79,7 @@ Now add/edit the custom labels. they should be formatted as follows: * Description: Start the description of with prefix `pr_agent:`, for example: `pr_agent: Description of when AI should suggest this label`.
The description should be comprehensive and detailed, indicating when to add the desired label. For example: - - - - - +![Add native custom labels](https://codium.ai/images/pr_agent/add_native_custom_labels.png){width=768} ### Markers template @@ -126,19 +102,12 @@ pr_agent:walkthrough ``` The marker `pr_agent:type` will be replaced with the PR type, `pr_agent:summary` will be replaced with the PR summary, and `pr_agent:walkthrough` will be replaced with the PR walkthrough. - - - - - +![Describe markers before](https://codium.ai/images/pr_agent/describe_markers_before.png){width=512} → - - - - - +![Describe markers after](https://codium.ai/images/pr_agent/describe_markers_after.png){width=512} + **Configuration params**: diff --git a/docs/docs/tools/documentation.md b/docs/docs/tools/documentation.md index b3fb0ba4..4318ee45 100644 --- a/docs/docs/tools/documentation.md +++ b/docs/docs/tools/documentation.md @@ -7,11 +7,11 @@ It can be invoked manually by commenting on any PR: ``` For example: - +![Docs command](https://codium.ai/images/pr_agent/docs_command.png){width=768} - +![Docs component](https://codium.ai/images/pr_agent/docs_components.png){width=768} - +![Docs single component](https://codium.ai/images/pr_agent/docs_single_component.png){width=768} ## Configuration options - `docs_style`: The exact style of the documentation (for python docstring). you can choose between: `google`, `numpy`, `sphinx`, `restructuredtext`, `plain`. Default is `sphinx`. diff --git a/docs/docs/tools/improve.md b/docs/docs/tools/improve.md index f5808139..40945775 100644 --- a/docs/docs/tools/improve.md +++ b/docs/docs/tools/improve.md @@ -9,20 +9,12 @@ The tool can be triggered automatically every time a new PR is [opened](../usage The code suggestions can be presented as a single comment (via `pr_code_suggestions.summarize=true`): - - - - - - +![code suggestions as comment](https://codium.ai/images/pr_agent/code_suggestions_as_comment.png){width=512} Or as a separate commitable code comment for each suggestion: - - - - - +![imporove](https://codium.ai/images/pr_agent/improve.png){width=512} + Note that a single comment has a significantly smaller PR footprint. We recommend this mode for most cases. Also note that collapsible are not supported in _Bitbucket_. Hence, the suggestions are presented there as code comments. diff --git a/docs/docs/tools/review.md b/docs/docs/tools/review.md index a8bd5a66..32314b5c 100644 --- a/docs/docs/tools/review.md +++ b/docs/docs/tools/review.md @@ -6,17 +6,9 @@ The tool can be triggered automatically every time a new PR is [opened](../usage ``` For example: - - - - - +![review comment](https://codium.ai/images/pr_agent/review_comment.png){width=512} - - - - - +![review](https://codium.ai/images/pr_agent/review_comment.png){width=512} ## Configuration options @@ -70,11 +62,7 @@ For invoking the incremental mode, the following command can be used: ``` Note that the incremental mode is only available for GitHub. - - - - - +![incremental review](https://codium.ai/images/pr_agent/incremental_review_2.png){width=512} ### PR Reflection @@ -84,23 +72,11 @@ By invoking: ``` The tool will first ask the author questions about the PR, and will guide the review based on their answers. - - - - - +![reflection questions](https://codium.ai/images/pr_agent/reflection_questions.png){width=512} - - - - - +![reflection answers](https://codium.ai/images/pr_agent/reflection_answers.png){width=512} - - - - - +![reflection insights](https://codium.ai/images/pr_agent/reflection_insights.png){width=512} ## Usage Tips diff --git a/docs/docs/tools/similar_code.md b/docs/docs/tools/similar_code.md index a35111d7..5f2af5c8 100644 --- a/docs/docs/tools/similar_code.md +++ b/docs/docs/tools/similar_code.md @@ -5,7 +5,8 @@ For example: `Global Search` for a method called `chat_completion`: - +![similar code global](https://codium.ai/images/pr_agent/similar_code_global2.png){width=768} + PR-Agent will examine the code component and will extract the most relevant keywords to search for similar code: @@ -16,11 +17,12 @@ PR-Agent will examine the code component and will extract the most relevant keyw Search result link example: - +![code search result single](https://codium.ai/images/pr_agent/code_search_result_single.png){width=768} + `Organization Search`: - +![similar code org](https://codium.ai/images/pr_agent/similar_code_org.png){width=768} ## How to use @@ -47,11 +49,11 @@ It can be invoked automatically from the analyze table, can be accessed by: /analyze ``` Choose the components you want to find similar code for, and click on the `similar` checkbox. - +![analyze similar](https://codium.ai/images/pr_agent/analyze_similar.png){width=768} If you are looking to search for similar code in the organization's codebase, you can click on the `Organization` checkbox, and it will invoke a new search command just for the organization's codebase. - +![similar code global](https://codium.ai/images/pr_agent/similar_code_global.png){width=768} ## Configuration options diff --git a/docs/docs/tools/similar_issues.md b/docs/docs/tools/similar_issues.md index 3d492c0a..239b4e90 100644 --- a/docs/docs/tools/similar_issues.md +++ b/docs/docs/tools/similar_issues.md @@ -6,11 +6,11 @@ It can be invoked manually by commenting on any PR: ``` For example: - +![similar_issue_original_issue](https://codium.ai/images/pr_agent/similar_issue_original_issue.png){width=768} - +![similar_issue_comment](https://codium.ai/images/pr_agent/similar_issue_comment.png){width=768} - +![similar_issue](https://codium.ai/images/pr_agent/similar_issue.png){width=768} Note that to perform retrieval, the `similar_issue` tool indexes all the repo previous issues (once). diff --git a/docs/docs/tools/test.md b/docs/docs/tools/test.md index a45f6faf..6c1901b1 100644 --- a/docs/docs/tools/test.md +++ b/docs/docs/tools/test.md @@ -10,11 +10,11 @@ To get a list of the components that changed in the PR, use the [`analyze`](./an An example [result](https://github.com/Codium-ai/pr-agent/pull/598#issuecomment-1913679429): - +![test1](https://codium.ai/images/pr_agent/test1.png){width=704} - +![test2](https://codium.ai/images/pr_agent/test2.png){width=768} - +![test3](https://codium.ai/images/pr_agent/test3.png){width=768} **Notes** - Language that are currently supported by the tool: Python, Java, C++, JavaScript, TypeScript. diff --git a/docs/docs/tools/update_changelog.md b/docs/docs/tools/update_changelog.md index 4c423a3e..4f4de235 100644 --- a/docs/docs/tools/update_changelog.md +++ b/docs/docs/tools/update_changelog.md @@ -6,10 +6,9 @@ It can be invoked manually by commenting on any PR: ``` For example: - - - +![update_changelog_comment](https://codium.ai/images/pr_agent/update_changelog_comment.png){width=768} +![update_changelog](https://codium.ai/images/pr_agent/update_changelog.png){width=768} ## Configuration options diff --git a/docs/docs/usage-guide/configuration_options.md b/docs/docs/usage-guide/configuration_options.md index 9b15babb..1d56baa2 100644 --- a/docs/docs/usage-guide/configuration_options.md +++ b/docs/docs/usage-guide/configuration_options.md @@ -16,7 +16,7 @@ In terms of precedence, wiki configurations will override local configurations, Specifically for GitHub, with PR-Agent-Pro you can set configurations by creating a page called `.pr_agent.toml` in the [wiki](https://github.com/Codium-ai/pr-agent/wiki/pr_agent.toml) of the repo. The advantage of this method is that it allows to set configurations without needing to commit new content to the repo - just edit the wiki page and **save**. - +![wiki_configuration](https://codium.ai/images/pr_agent/wiki_configuration.png){width=512} Click [here](https://codium.ai/images/pr_agent/wiki_configuration_pr_agent.mp4) to see a short instructional video. We recommend surrounding the configuration content with triple-quotes, to allow better presentation when displayed in the wiki as markdown. An example content: diff --git a/docs/docs/usage-guide/mail_notifications.md b/docs/docs/usage-guide/mail_notifications.md index 1e5b2e8a..82dc10a0 100644 --- a/docs/docs/usage-guide/mail_notifications.md +++ b/docs/docs/usage-guide/mail_notifications.md @@ -2,8 +2,8 @@ Unfortunately, it is not possible in GitHub to disable mail notifications from a specific user. If you are subscribed to notifications for a repo with PR-Agent, we recommend turning off notifications for PR comments, to avoid lengthy emails: - +![notifications](https://codium.ai/images/pr_agent/notifications.png){width=512} As an alternative, you can filter in your mail provider the notifications specifically from the PR-Agent bot, [see how](https://www.quora.com/How-can-you-filter-emails-for-specific-people-in-Gmail#:~:text=On%20the%20Filters%20and%20Blocked,the%20body%20of%20the%20email). - \ No newline at end of file +![filter_mail_notifications](https://codium.ai/images/pr_agent/filter_mail_notifications.png){width=512} diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index c3e10abd..bcf39b36 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -77,6 +77,7 @@ theme: plugins: - social - search + - glightbox extra: generator: false @@ -112,6 +113,7 @@ markdown_extensions: - pymdownx.details - pymdownx.superfences - pymdownx.mark + - md_in_html - attr_list - pymdownx.emoji: emoji_index: !!python/name:material.extensions.emoji.twemoji From 2f823fb4e1091dc24c3c3ebaf77051336d42a45e Mon Sep 17 00:00:00 2001 From: Almog Lavi Date: Tue, 26 Mar 2024 23:06:07 +0200 Subject: [PATCH 059/226] update deprecated plugin --- docs/mkdocs.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index bcf39b36..b7e6864d 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -117,7 +117,7 @@ markdown_extensions: - attr_list - pymdownx.emoji: emoji_index: !!python/name:material.extensions.emoji.twemoji - emoji_generator: !!python/name:materialx.emoji.to_svg + emoji_generator: !!python/name:material.extensions.emoji.to_svg - toc: title: On this page toc_depth: 3 From c97702982c282bae5138e3b61ca0f0a187e56f0f Mon Sep 17 00:00:00 2001 From: Almog Lavi Date: Tue, 26 Mar 2024 23:09:37 +0200 Subject: [PATCH 060/226] fix image --- docs/docs/tools/review.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/tools/review.md b/docs/docs/tools/review.md index 32314b5c..41ef75ed 100644 --- a/docs/docs/tools/review.md +++ b/docs/docs/tools/review.md @@ -8,7 +8,7 @@ For example: ![review comment](https://codium.ai/images/pr_agent/review_comment.png){width=512} -![review](https://codium.ai/images/pr_agent/review_comment.png){width=512} +![review](https://codium.ai/images/pr_agent/review3.png){width=512} ## Configuration options From d250cb46f4b275a3e9126a95560fc7860b820ffa Mon Sep 17 00:00:00 2001 From: Diogo Simoes Date: Tue, 26 Mar 2024 22:28:19 +0000 Subject: [PATCH 061/226] fix: missing requirements.txt on lambda dockerfile --- docker/Dockerfile.lambda | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker/Dockerfile.lambda b/docker/Dockerfile.lambda index 59e78a54..058f84d1 100644 --- a/docker/Dockerfile.lambda +++ b/docker/Dockerfile.lambda @@ -4,7 +4,7 @@ RUN yum update -y && \ yum install -y gcc python3-devel && \ yum clean all -ADD pyproject.toml . +ADD pyproject.toml requirements.txt . RUN pip install . && rm pyproject.toml RUN pip install mangum==0.17.0 COPY pr_agent/ ${LAMBDA_TASK_ROOT}/pr_agent/ From 0241fe5c131242a94e36add32b091d83e53f347d Mon Sep 17 00:00:00 2001 From: Diogo Simoes Date: Tue, 26 Mar 2024 23:58:07 +0000 Subject: [PATCH 062/226] fix: missing git binary on lambda dockerfile --- docker/Dockerfile.lambda | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker/Dockerfile.lambda b/docker/Dockerfile.lambda index 058f84d1..54aa1374 100644 --- a/docker/Dockerfile.lambda +++ b/docker/Dockerfile.lambda @@ -1,7 +1,7 @@ FROM public.ecr.aws/lambda/python:3.10 RUN yum update -y && \ - yum install -y gcc python3-devel && \ + yum install -y gcc python3-devel git && \ yum clean all ADD pyproject.toml requirements.txt . From fa889fbb064d2f36e0bc2fdcae79a4718a3558af Mon Sep 17 00:00:00 2001 From: idubnori Date: Wed, 27 Mar 2024 12:00:24 +0900 Subject: [PATCH 063/226] docs: add pull request event types --- docs/docs/installation/github.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/docs/installation/github.md b/docs/docs/installation/github.md index b405b020..f19590f1 100644 --- a/docs/docs/installation/github.md +++ b/docs/docs/installation/github.md @@ -7,6 +7,7 @@ You can use our pre-built Github Action Docker image to run PR-Agent as a Github ```yaml on: pull_request: + types: [opened,reopened,ready_for_review,review_requested] issue_comment: jobs: pr_agent_job: @@ -28,6 +29,7 @@ jobs: ```yaml on: pull_request: + types: [opened,reopened,ready_for_review,review_requested] issue_comment: jobs: From 493f73f1ce5e0625026cd0ebbcb0bac098990b62 Mon Sep 17 00:00:00 2001 From: idubnori Date: Wed, 27 Mar 2024 12:03:27 +0900 Subject: [PATCH 064/226] chore: add logging the reason not execute --- pr_agent/servers/github_action_runner.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pr_agent/servers/github_action_runner.py b/pr_agent/servers/github_action_runner.py index d4278156..5382d051 100644 --- a/pr_agent/servers/github_action_runner.py +++ b/pr_agent/servers/github_action_runner.py @@ -101,6 +101,8 @@ async def run_action(): await PRReviewer(pr_url).run() if auto_improve is None or is_true(auto_improve): await PRCodeSuggestions(pr_url).run() + else: + get_logger().info(f"Skipping action: {action}") # Handle issue comment event elif GITHUB_EVENT_NAME == "issue_comment" or GITHUB_EVENT_NAME == "pull_request_review_comment": From 82d9c77489562997126efe10da4741920bb007d0 Mon Sep 17 00:00:00 2001 From: Tal Date: Wed, 27 Mar 2024 12:40:47 +0200 Subject: [PATCH 065/226] Update github.md --- docs/docs/installation/github.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/docs/installation/github.md b/docs/docs/installation/github.md index b405b020..afe15517 100644 --- a/docs/docs/installation/github.md +++ b/docs/docs/installation/github.md @@ -159,6 +159,9 @@ cp pr_agent/settings/.secrets_template.toml pr_agent/settings/.secrets.toml ## Deploy as a Lambda Function +Note that since AWS Lambda env vars cannot have "." in the name, you can replace each "." in an env variable with "__".
+For example: `GITHUB.WEBHOOK_SECRET` --> `GITHUB__WEBHOOK_SECRET` + 1. Follow steps 1-5 from [here](#run-as-a-github-app). 2. Build a docker image that can be used as a lambda function ```shell @@ -246,4 +249,4 @@ After you set up AWS CodeCommit using the instructions above, here is an example PYTHONPATH="/PATH/TO/PROJECTS/pr-agent" python pr_agent/cli.py \ --pr_url https://us-east-1.console.aws.amazon.com/codesuite/codecommit/repositories/MY_REPO_NAME/pull-requests/321 \ review -``` \ No newline at end of file +``` From a8bee89ae969d581a6a7b692c3a2712455eac2b5 Mon Sep 17 00:00:00 2001 From: Tal Date: Wed, 27 Mar 2024 13:00:16 +0200 Subject: [PATCH 066/226] Update custom.css --- docs/docs/css/custom.css | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/docs/css/custom.css b/docs/docs/css/custom.css index e79736b4..8b0879a0 100644 --- a/docs/docs/css/custom.css +++ b/docs/docs/css/custom.css @@ -21,7 +21,7 @@ border-width: 1px; border-style: solid; border-color: black; - outline-width: 3px; + outline-width: 1px; outline-style: solid; outline-color: darkgray; - } \ No newline at end of file + } From 020a29ebb8c3794b0768ef3ab13ce19b69fd00ef Mon Sep 17 00:00:00 2001 From: idubnori Date: Wed, 27 Mar 2024 20:53:46 +0900 Subject: [PATCH 067/226] docs: optimize condition of github actions --- docs/docs/installation/github.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/docs/installation/github.md b/docs/docs/installation/github.md index f19590f1..edaaf24f 100644 --- a/docs/docs/installation/github.md +++ b/docs/docs/installation/github.md @@ -7,10 +7,11 @@ You can use our pre-built Github Action Docker image to run PR-Agent as a Github ```yaml on: pull_request: - types: [opened,reopened,ready_for_review,review_requested] + types: [opened, reopened, ready_for_review] issue_comment: jobs: pr_agent_job: + if: ${{ github.event.sender.type != 'Bot' }} runs-on: ubuntu-latest permissions: issues: write @@ -29,11 +30,12 @@ jobs: ```yaml on: pull_request: - types: [opened,reopened,ready_for_review,review_requested] + types: [opened, reopened, ready_for_review] issue_comment: jobs: pr_agent_job: + if: ${{ github.event.sender.type != 'Bot' }} runs-on: ubuntu-latest permissions: issues: write From 79bdb9a69f3dd732142053fea6065d3504a8848f Mon Sep 17 00:00:00 2001 From: mrT23 Date: Wed, 27 Mar 2024 19:56:27 +0200 Subject: [PATCH 068/226] bugfix: validate output publishing with progress condition in pr_code_suggestions --- pr_agent/tools/pr_code_suggestions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pr_agent/tools/pr_code_suggestions.py b/pr_agent/tools/pr_code_suggestions.py index aa119f2a..926edf00 100644 --- a/pr_agent/tools/pr_code_suggestions.py +++ b/pr_agent/tools/pr_code_suggestions.py @@ -76,7 +76,7 @@ class PRCodeSuggestions: relevant_configs = {'pr_code_suggestions': dict(get_settings().pr_code_suggestions), 'config': dict(get_settings().config)} get_logger().debug("Relevant configs", artifacts=relevant_configs) - if get_settings().config.publish_output: + if get_settings().config.publish_output and get_settings().config.publish_output_progress: if self.git_provider.is_supported("gfm_markdown"): self.progress_response = self.git_provider.publish_comment(self.progress) else: From aae6869964000578ccecc5e4ee9ee5919f06b7c8 Mon Sep 17 00:00:00 2001 From: mrT23 Date: Thu, 28 Mar 2024 09:37:29 +0200 Subject: [PATCH 069/226] docs: Update PR-Agent usage guide --- docs/docs/installation/github.md | 24 ++++--------------- .../docs/usage-guide/automations_and_usage.md | 13 +++++----- 2 files changed, 12 insertions(+), 25 deletions(-) diff --git a/docs/docs/installation/github.md b/docs/docs/installation/github.md index 2e5a2824..4f7be99a 100644 --- a/docs/docs/installation/github.md +++ b/docs/docs/installation/github.md @@ -26,29 +26,14 @@ jobs: OPENAI_KEY: ${{ secrets.OPENAI_KEY }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} ``` -** if you want to pin your action to a specific release (v0.7 for example) for stability reasons, use: +** if you want to pin your action to a specific release (v2.0 for example) for stability reasons, use: ```yaml -on: - pull_request: - types: [opened, reopened, ready_for_review] - issue_comment: - -jobs: - pr_agent_job: - if: ${{ github.event.sender.type != 'Bot' }} - runs-on: ubuntu-latest - permissions: - issues: write - pull-requests: write - contents: write - name: Run pr agent on every pull request, respond to user comments +... steps: - name: PR Agent action step id: pragent - uses: Codium-ai/pr-agent@v0.7 - env: - OPENAI_KEY: ${{ secrets.OPENAI_KEY }} - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + uses: Codium-ai/pr-agent@v2.0 +... ``` 2) Add the following secret to your repository under `Settings > Secrets and variables > Actions > New repository secret > Add secret`: @@ -70,6 +55,7 @@ When you open your next PR, you should see a comment from `github-actions` bot w PR_REVIEWER.REQUIRE_TESTS_REVIEW: "false" # Disable tests review PR_CODE_SUGGESTIONS.NUM_CODE_SUGGESTIONS: 6 # Increase number of code suggestions ``` +See detailed usage instructions in the [USAGE GUIDE](https://pr-agent-docs.codium.ai/usage-guide/automations_and_usage/#github-action) --- diff --git a/docs/docs/usage-guide/automations_and_usage.md b/docs/docs/usage-guide/automations_and_usage.md index d20516fd..f718e9bd 100644 --- a/docs/docs/usage-guide/automations_and_usage.md +++ b/docs/docs/usage-guide/automations_and_usage.md @@ -59,7 +59,7 @@ The configuration parameter `pr_commands` defines the list of tools that will be [github_app] pr_commands = [ "/describe --pr_description.add_original_user_description=true --pr_description.keep_original_user_title=true --pr_description.final_update_message=false", - "/review --pr_reviewer.num_code_suggestions=0 --pr_reviewer.final_update_message=false", + "/review --pr_reviewer.num_code_suggestions=0", "/improve", ] ``` @@ -99,13 +99,13 @@ The configuration parameter `push_commands` defines the list of tools that will handle_push_trigger = true push_commands = [ "/describe --pr_description.add_original_user_description=true --pr_description.keep_original_user_title=true", - "/review --pr_reviewer.num_code_suggestions=0", + "/review --pr_reviewer.num_code_suggestions=0 --pr_reviewer.final_update_message=false", ] ``` This means that when new code is pushed to the PR, the PR-Agent will run the `describe` and `review` tools, with the specified parameters. ## GitHub Action -`GitHub Action` is a different way to trigger PR-Agent tools, and uses a different configuration mechanism than `GitHub App`. +`GitHub Action` is a different way to trigger PR-Agent tools, and uses a different configuration mechanism than `GitHub App`.
You can configure settings for `GitHub Action` by adding environment variables under the env section in `.github/workflows/pr_agent.yml` file. Specifically, start by setting the following environment variables: ```yaml @@ -119,13 +119,14 @@ Specifically, start by setting the following environment variables: `github_action_config.auto_review`, `github_action_config.auto_describe` and `github_action_config.auto_improve` are used to enable/disable automatic tools that run when a new PR is opened. If not set, the default configuration is for all three tools to run automatically when a new PR is opened. -Note that you can give additional config parameters by adding environment variables to `.github/workflows/pr_agent.yml`, or by using a `.pr_agent.toml` file in the root of your repo, similar to the GitHub App usage. +Note that you can give additional config parameters by adding environment variables to `.github/workflows/pr_agent.yml`, or by using a `.pr_agent.toml` [configuration file](https://pr-agent-docs.codium.ai/usage-guide/configuration_options/#global-configuration-file) in the root of your repo -For example, you can set an environment variable: `pr_description.add_original_user_description=false`, or add a `.pr_agent.toml` file with the following content: +For example, you can set an environment variable: `pr_description.publish_labels=false`, or add a `.pr_agent.toml` file with the following content: ``` [pr_description] -add_original_user_description = false +publish_labels = false ``` +to prevent PR-Agent from publishing labels when running the `describe` tool. ## GitLab Webhook After setting up a GitLab webhook, to control which commands will run automatically when a new PR is opened, you can set the `pr_commands` parameter in the configuration file, similar to the GitHub App: From 7e84acc63cd1d382212b1ab9d45c36ce9e3f46ec Mon Sep 17 00:00:00 2001 From: mrT23 Date: Fri, 29 Mar 2024 13:34:23 +0300 Subject: [PATCH 070/226] docs: Refine project description and reorganize documentation links in README --- README.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 0f107870..0d75489c 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@
-Making pull requests less painful with an AI agent +CodiumAI PR-Agent aims to help efficiently review and handle pull requests, by providing AI feedbacks and suggestions
[![GitHub license](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://github.com/Codium-ai/pr-agent/blob/main/LICENSE) @@ -21,6 +21,14 @@ Making pull requests less painful with an AI agent +### [Documentation](https://pr-agent-docs.codium.ai/) +- See the [Installation Guide](https://pr-agent-docs.codium.ai/installation/) for instructions on installing PR-Agent on different platforms. + +- See the [Usage Guide](https://pr-agent-docs.codium.ai/usage-guide/) for instructions on running PR-Agent tools via different interfaces, such as CLI, PR Comments, or by automatically triggering them when a new PR is opened. + +- See the [Tools Guide](https://pr-agent-docs.codium.ai/tools/) for a detailed description of the different tools, and the available configurations for each tool. + + ## Table of Contents - [News and Updates](#news-and-updates) - [Overview](#overview) @@ -63,14 +71,6 @@ If set to true, the tool will add a section that checks if the PR contains sever ## Overview
-CodiumAI PR-Agent aims to help efficiently review and handle pull requests, by providing AI feedbacks and suggestions - -- See the [Installation Guide](https://pr-agent-docs.codium.ai/installation/) for instructions on installing and running the tool on different git platforms. - -- See the [Usage Guide](https://pr-agent-docs.codium.ai/usage-guide/) for instructions on running the PR-Agent commands via different interfaces, including _CLI_, _online usage_, or by _automatically triggering_ them when a new PR is opened. - -- See the [Tools Guide](https://pr-agent-docs.codium.ai/tools/) for a detailed description of the different tools. - Supported commands per platform: | | | GitHub | Gitlab | Bitbucket | Azure DevOps | From c3b3651769c8b42abf82dacf69cca9c988473c28 Mon Sep 17 00:00:00 2001 From: mrT23 Date: Sun, 31 Mar 2024 11:43:00 +0300 Subject: [PATCH 071/226] refine help --- pr_agent/tools/pr_help_message.py | 47 ++++++++++++++++++------------- 1 file changed, 27 insertions(+), 20 deletions(-) diff --git a/pr_agent/tools/pr_help_message.py b/pr_agent/tools/pr_help_message.py index f7a5ff13..df2698cf 100644 --- a/pr_agent/tools/pr_help_message.py +++ b/pr_agent/tools/pr_help_message.py @@ -27,12 +27,13 @@ class PRHelpMessage: tool_names.append(f"[DESCRIBE]({base_path}/describe/)") tool_names.append(f"[REVIEW]({base_path}/review/)") tool_names.append(f"[IMPROVE]({base_path}/improve/)") - tool_names.append(f"[ANALYZE]({base_path}/analyze/) ๐Ÿ’Ž") tool_names.append(f"[UPDATE CHANGELOG]({base_path}/update_changelog/)") - tool_names.append(f"[ADD DOCUMENTATION]({base_path}/documentation/) ๐Ÿ’Ž") - tool_names.append(f"[ASK]({base_path}/ask/)") - tool_names.append(f"[GENERATE CUSTOM LABELS]({base_path}/custom_labels/)") + tool_names.append(f"[ADD DOCS]({base_path}/documentation/) ๐Ÿ’Ž") tool_names.append(f"[TEST]({base_path}/test/) ๐Ÿ’Ž") + tool_names.append(f"[IMPROVE COMPONENT]({base_path}/improve_component/) ๐Ÿ’Ž") + tool_names.append(f"[ANALYZE]({base_path}/analyze/) ๐Ÿ’Ž") + tool_names.append(f"[ASK]({base_path}/ask/)") + tool_names.append(f"[GENERATE CUSTOM LABELS]({base_path}/custom_labels/) ๐Ÿ’Ž") tool_names.append(f"[CI FEEDBACK]({base_path}/ci_feedback/) ๐Ÿ’Ž") tool_names.append(f"[CUSTOM SUGGESTIONS]({base_path}/custom_suggestions/) ๐Ÿ’Ž") tool_names.append(f"[SIMILAR ISSUE]({base_path}/similar_issues/)") @@ -40,27 +41,29 @@ class PRHelpMessage: descriptions = [] descriptions.append("Generates PR description - title, type, summary, code walkthrough and labels") descriptions.append("Adjustable feedback about the PR, possible issues, security concerns, review effort and more") - descriptions.append("Code suggestions for improving the PR.") - descriptions.append("Identifies code components that changed in the PR, and enables to interactively generate tests, docs, and code suggestions for each component.") - descriptions.append("Automatically updates the changelog.") - descriptions.append("Generates documentation to methods/functions/classes that changed in the PR.") - descriptions.append("Answering free-text questions about the PR.") + descriptions.append("Code suggestions for improving the PR") + descriptions.append("Automatically updates the changelog") + descriptions.append("Generates documentation to methods/functions/classes that changed in the PR") + descriptions.append("Generates unit tests for a specific component, based on the PR code change") + descriptions.append("Code suggestions for a specific component that changed in the PR") + descriptions.append("Identifies code components that changed in the PR, and enables to interactively generate tests, docs, and code suggestions for each component") + descriptions.append("Answering free-text questions about the PR") descriptions.append("Generates custom labels for the PR, based on specific guidelines defined by the user") - descriptions.append("Generates unit tests for a specific component, based on the PR code change.") - descriptions.append("Generates feedback and analysis for a failed CI job.") - descriptions.append("Generates custom suggestions for improving the PR code, based on specific guidelines defined by the user.") - descriptions.append("Automatically retrieves and presents similar issues.") + descriptions.append("Generates feedback and analysis for a failed CI job") + descriptions.append("Generates custom suggestions for improving the PR code, based only on specific guidelines defined by the user") + descriptions.append("Automatically retrieves and presents similar issues") commands =[] commands.append("`/describe`") commands.append("`/review`") commands.append("`/improve`") - commands.append("`/analyze`") commands.append("`/update_changelog`") commands.append("`/add_docs`") + commands.append("`/test`") + commands.append("`/improve_component`") + commands.append("`/analyze`") commands.append("`/ask`") commands.append("`/generate_labels`") - commands.append("`/test`") commands.append("`/checks`") commands.append("`/custom_suggestions`") commands.append("`/similar_issue`") @@ -69,9 +72,13 @@ class PRHelpMessage: checkbox_list.append(" - [ ] Run ") checkbox_list.append(" - [ ] Run ") checkbox_list.append(" - [ ] Run ") - checkbox_list.append(" - [ ] Run ") checkbox_list.append(" - [ ] Run ") checkbox_list.append(" - [ ] Run ") + checkbox_list.append(" - [ ] Run ") + checkbox_list.append(" - [ ] Run ") + checkbox_list.append(" - [ ] Run ") + checkbox_list.append("[*]") + checkbox_list.append("[*]") checkbox_list.append("[*]") checkbox_list.append("[*]") checkbox_list.append("[*]") @@ -80,16 +87,16 @@ class PRHelpMessage: checkbox_list.append("[*]") if isinstance(self.git_provider, GithubProvider): - pr_comment += f"" + pr_comment += f"
ToolDescriptionInvoke Interactively :gem:
" for i in range(len(tool_names)): - pr_comment += f"\n\n\n" + pr_comment += f"\n\n\n" pr_comment += "
ToolDescriptionTrigger Interactively :gem:
\n\n{tool_names[i]}{descriptions[i]}\n\n{checkbox_list[i]}\n
\n\n{tool_names[i]}{descriptions[i]}\n\n{checkbox_list[i]}\n
\n\n" pr_comment += f"""\n\n(1) Note that each tool be [triggered automatically](https://github.com/Codium-ai/pr-agent/blob/main/Usage.md#github-app-automatic-tools-for-pr-actions) when a new PR is opened, or called manually by [commenting on a PR](https://github.com/Codium-ai/pr-agent/blob/main/Usage.md#online-usage).""" pr_comment += f"""\n\n(2) Tools marked with [*] require additional parameters to be passed. For example, to invoke the `/ask` tool, you need to comment on a PR: `/ask ""`. See the relevant documentation for each tool for more details.""" else: - pr_comment += f"" + pr_comment += f"
ToolCommandDescription
" for i in range(len(tool_names)): - pr_comment += f"\n" + pr_comment += f"\n" pr_comment += "
ToolCommandDescription
\n\n{tool_names[i]}{commands[i]}{descriptions[i]}
\n\n{tool_names[i]}{commands[i]}{descriptions[i]}
\n\n" pr_comment += f"""\n\nNote that each tool be [invoked automatically](https://pr-agent-docs.codium.ai/usage-guide/automations_and_usage/) when a new PR is opened, or called manually by [commenting on a PR](https://pr-agent-docs.codium.ai/usage-guide/automations_and_usage/#online-usage).""" if get_settings().config.publish_output: From 8bda365636576c518e2e13f2f2107d483c8c5a62 Mon Sep 17 00:00:00 2001 From: mrT23 Date: Sun, 31 Mar 2024 12:13:25 +0300 Subject: [PATCH 072/226] docs: Add "Improve Component" tool documentation and update related guides --- docs/docs/tools/improve_component.md | 24 +++++++++++++++++++++++ docs/docs/tools/index.md | 29 ++++++++++++++-------------- docs/docs/tools/test.md | 2 +- docs/mkdocs.yml | 1 + pr_agent/settings/configuration.toml | 5 +++++ 5 files changed, 46 insertions(+), 15 deletions(-) create mode 100644 docs/docs/tools/improve_component.md diff --git a/docs/docs/tools/improve_component.md b/docs/docs/tools/improve_component.md new file mode 100644 index 00000000..d7e0e787 --- /dev/null +++ b/docs/docs/tools/improve_component.md @@ -0,0 +1,24 @@ +## Overview +The `improve_component` tool generates code suggestions for a specific code component that changed in the PR. +it can be invoked manually by commenting on any PR: +``` +/improve_component component_name +``` + +To get a list of the components that changed in the PR and choose the relevant component interactively, use the [`analyze`](./analyze.md) tool. + + +Example result: + +![improve_component1](https://codium.ai/images/pr_agent/improve_component1.png){width=768} + +![improve_component2](https://codium.ai/images/pr_agent/improve_component2.png){width=768} + +**Notes** +- Language that are currently supported by the tool: Python, Java, C++, JavaScript, TypeScript. + +## Configuration options +- `num_code_suggestions`: number of code suggestions to provide. Default is 4 +- `extra_instructions`: Optional extra instructions to the tool. For example: "focus on ...". +- `file`: in case there are several components with the same name, you can specify the relevant file. +- `class_name`: in case there are several methods with the same name in the same file, you can specify the relevant class name. \ No newline at end of file diff --git a/docs/docs/tools/index.md b/docs/docs/tools/index.md index bcd9ed9d..b77097b3 100644 --- a/docs/docs/tools/index.md +++ b/docs/docs/tools/index.md @@ -2,19 +2,20 @@ Here is a list of PR-Agent tools, each with a dedicated page that explains how to use it: -| Tool | Description | -|-------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------| -| **[PR Description (`/describe`](./describe.md))** | Automatically generating PR description - title, type, summary, code walkthrough and labels | -| **[PR Review (`/review`](./review.md))** | Adjustable feedback about the PR, possible issues, security concerns, review effort and more | -| **[Code Suggestions (`/improve`](./improve.md))** | Code suggestions for improving the PR | -| **[Question Answering (`/ask ...`](./ask.md))** | Answering free-text questions about the PR, or on specific code lines | -| **[Update Changelog (`/update_changelog`](./update_changelog.md))** | Automatically updating the CHANGELOG.md file with the PR changes | -| **[Find Similar Issue (`/similar_issue`](./similar_issues.md))** | Automatically retrieves and presents similar issues | -| **๐Ÿ’Ž [Add Documentation (`/add_docs`](./documentation.md))** | Generates documentation to methods/functions/classes that changed in the PR | -| **๐Ÿ’Ž [Generate Custom Labels (`/generate_labels`](./custom_labels.md))** | Generates custom labels for the PR, based on specific guidelines defined by the user | -| **๐Ÿ’Ž [Analyze (`/analyze`](./analyze.md))** | Identify code components that changed in the PR, and enables to interactively generate tests, docs, and code suggestions for each component | -| **๐Ÿ’Ž [Custom Suggestions (`/custom_suggestions`](./custom_suggestions.md))** | Automatically generates custom suggestions for improving the PR code, based on specific guidelines defined by the user | -| **๐Ÿ’Ž [Generate Tests (`/test component_name`](./test.md))** | Automatically generates unit tests for a selected component, based on the PR code changes | -| **๐Ÿ’Ž [CI Feedback (`/checks ci_job`](./ci_feedback.md))** | Automatically generates feedback and analysis for a failed CI job | +| Tool | Description | +|------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------| +| **[PR Description (`/describe`](./describe.md))** | Automatically generating PR description - title, type, summary, code walkthrough and labels | +| **[PR Review (`/review`](./review.md))** | Adjustable feedback about the PR, possible issues, security concerns, review effort and more | +| **[Code Suggestions (`/improve`](./improve.md))** | Code suggestions for improving the PR | +| **[Question Answering (`/ask ...`](./ask.md))** | Answering free-text questions about the PR, or on specific code lines | +| **[Update Changelog (`/update_changelog`](./update_changelog.md))** | Automatically updating the CHANGELOG.md file with the PR changes | +| **[Find Similar Issue (`/similar_issue`](./similar_issues.md))** | Automatically retrieves and presents similar issues | +| **๐Ÿ’Ž [Add Documentation (`/add_docs`](./documentation.md))** | Generates documentation to methods/functions/classes that changed in the PR | +| **๐Ÿ’Ž [Generate Custom Labels (`/generate_labels`](./custom_labels.md))** | Generates custom labels for the PR, based on specific guidelines defined by the user | +| **๐Ÿ’Ž [Analyze (`/analyze`](./analyze.md))** | Identify code components that changed in the PR, and enables to interactively generate tests, docs, and code suggestions for each component | +| **๐Ÿ’Ž [Custom Suggestions (`/custom_suggestions`](./custom_suggestions.md))** | Automatically generates custom suggestions for improving the PR code, based on specific guidelines defined by the user | +| **๐Ÿ’Ž [Generate Tests (`/test component_name`](./test.md))** | Automatically generates unit tests for a selected component, based on the PR code changes | +| **๐Ÿ’Ž [Improve Component (`/improve_component component_name`](./improve_component.md))** | Generates code suggestions for a specific code component that changed in the PR | +| **๐Ÿ’Ž [CI Feedback (`/checks ci_job`](./ci_feedback.md))** | Automatically generates feedback and analysis for a failed CI job | Note that the tools marked with ๐Ÿ’Ž are available only for PR-Agent Pro users. \ No newline at end of file diff --git a/docs/docs/tools/test.md b/docs/docs/tools/test.md index 6c1901b1..4cb46bac 100644 --- a/docs/docs/tools/test.md +++ b/docs/docs/tools/test.md @@ -5,7 +5,7 @@ It can be invoked manually by commenting on any PR: /test component_name ``` where 'component_name' is the name of a specific component in the PR. -To get a list of the components that changed in the PR, use the [`analyze`](./analyze.md) tool. +To get a list of the components that changed in the PR and choose the relevant component interactively, use the [`analyze`](./analyze.md) tool. An example [result](https://github.com/Codium-ai/pr-agent/pull/598#issuecomment-1913679429): diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index b7e6864d..e67712e1 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -27,6 +27,7 @@ nav: - Similar Issues: 'tools/similar_issues.md' - ๐Ÿ’Ž Analyze: 'tools/analyze.md' - ๐Ÿ’Ž Test: 'tools/test.md' + - ๐Ÿ’Ž Improve Component: 'tools/improve_component.md' - ๐Ÿ’Ž Documentation: 'tools/documentation.md' - ๐Ÿ’Ž Custom Labels: 'tools/custom_labels.md' - ๐Ÿ’Ž Custom Suggestions: 'tools/custom_suggestions.md' diff --git a/pr_agent/settings/configuration.toml b/pr_agent/settings/configuration.toml index 837c71d3..765c8342 100644 --- a/pr_agent/settings/configuration.toml +++ b/pr_agent/settings/configuration.toml @@ -110,6 +110,11 @@ file = "" # in case there are several components with the same name class_name = "" # in case there are several methods with the same name in the same file, you can specify the relevant class name enable_help_text=true +[pr_improve_component] # /improve_component # +num_code_suggestions=4 +extra_instructions = "" +file = "" # in case there are several components with the same name, you can specify the relevant file +class_name = "" [checks] # /checks (pro feature) # enable_auto_checks_feedback=true From ce47adf986593bff404ae06b613c5909fadab72f Mon Sep 17 00:00:00 2001 From: mrT23 Date: Sun, 31 Mar 2024 12:15:29 +0300 Subject: [PATCH 073/226] C# --- docs/docs/tools/analyze.md | 2 +- docs/docs/tools/documentation.md | 2 +- docs/docs/tools/improve_component.md | 2 +- docs/docs/tools/test.md | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/docs/tools/analyze.md b/docs/docs/tools/analyze.md index 3b7c6d58..0255e759 100644 --- a/docs/docs/tools/analyze.md +++ b/docs/docs/tools/analyze.md @@ -19,4 +19,4 @@ An example [result](https://github.com/Codium-ai/pr-agent/pull/546#issuecomment- **Notes** -- Language that are currently supported: Python, Java, C++, JavaScript, TypeScript. \ No newline at end of file +- Language that are currently supported: Python, Java, C++, JavaScript, TypeScript, C#. \ No newline at end of file diff --git a/docs/docs/tools/documentation.md b/docs/docs/tools/documentation.md index 4318ee45..9c56386f 100644 --- a/docs/docs/tools/documentation.md +++ b/docs/docs/tools/documentation.md @@ -19,6 +19,6 @@ For example: **Notes** -- Language that are currently fully supported: Python, Java, C++, JavaScript, TypeScript. +- Language that are currently fully supported: Python, Java, C++, JavaScript, TypeScript, C#. - For languages that are not fully supported, the tool will suggest documentation only for new components in the PR. - A previous version of the tool, that offered support only for new components, was deprecated. \ No newline at end of file diff --git a/docs/docs/tools/improve_component.md b/docs/docs/tools/improve_component.md index d7e0e787..321114b4 100644 --- a/docs/docs/tools/improve_component.md +++ b/docs/docs/tools/improve_component.md @@ -15,7 +15,7 @@ Example result: ![improve_component2](https://codium.ai/images/pr_agent/improve_component2.png){width=768} **Notes** -- Language that are currently supported by the tool: Python, Java, C++, JavaScript, TypeScript. +- Language that are currently supported by the tool: Python, Java, C++, JavaScript, TypeScript, C#. ## Configuration options - `num_code_suggestions`: number of code suggestions to provide. Default is 4 diff --git a/docs/docs/tools/test.md b/docs/docs/tools/test.md index 4cb46bac..52e447ce 100644 --- a/docs/docs/tools/test.md +++ b/docs/docs/tools/test.md @@ -17,7 +17,7 @@ An example [result](https://github.com/Codium-ai/pr-agent/pull/598#issuecomment- ![test3](https://codium.ai/images/pr_agent/test3.png){width=768} **Notes** -- Language that are currently supported by the tool: Python, Java, C++, JavaScript, TypeScript. +- Language that are currently supported by the tool: Python, Java, C++, JavaScript, TypeScript, C#. ## Configuration options From b86b37e6a2bfd8104c786420e9239568f765190a Mon Sep 17 00:00:00 2001 From: Almog Lavi <42740235+almog-lv@users.noreply.github.com> Date: Mon, 1 Apr 2024 09:54:59 +0300 Subject: [PATCH 074/226] analytics --- docs/overrides/main.html | 10 ++++++++++ .../partials/integrations/analytics/custom.html | 7 +++++++ 2 files changed, 17 insertions(+) create mode 100644 docs/overrides/main.html create mode 100644 docs/overrides/partials/integrations/analytics/custom.html diff --git a/docs/overrides/main.html b/docs/overrides/main.html new file mode 100644 index 00000000..93a67950 --- /dev/null +++ b/docs/overrides/main.html @@ -0,0 +1,10 @@ +{% extends "base.html" %} + +{% block scripts %} + {{ super() }} + + + + +{% endblock %} \ No newline at end of file diff --git a/docs/overrides/partials/integrations/analytics/custom.html b/docs/overrides/partials/integrations/analytics/custom.html new file mode 100644 index 00000000..9a0785d2 --- /dev/null +++ b/docs/overrides/partials/integrations/analytics/custom.html @@ -0,0 +1,7 @@ + + + \ No newline at end of file From a53ba4596efffa7beb2cb3776ce81ac29b77aed5 Mon Sep 17 00:00:00 2001 From: Almog Lavi <42740235+almog-lv@users.noreply.github.com> Date: Mon, 1 Apr 2024 10:03:36 +0300 Subject: [PATCH 075/226] fix custom analytics --- docs/mkdocs.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index e67712e1..c045d8e4 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -96,7 +96,7 @@ extra: - icon: fontawesome/brands/instagram link: https://www.instagram.com/codiumai/ analytics: - provider: google + provider: custom property: ${{ secrets.GOOGLE_ANALYTICS_ID }} extra_css: From 3d86430f18f8d769db66413be3b7ce6c28bb960e Mon Sep 17 00:00:00 2001 From: Tal Date: Mon, 1 Apr 2024 18:46:08 +0300 Subject: [PATCH 076/226] Update automations_and_usage.md --- docs/docs/usage-guide/automations_and_usage.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/docs/usage-guide/automations_and_usage.md b/docs/docs/usage-guide/automations_and_usage.md index f718e9bd..f32863eb 100644 --- a/docs/docs/usage-guide/automations_and_usage.md +++ b/docs/docs/usage-guide/automations_and_usage.md @@ -154,11 +154,11 @@ Each time you invoke a `/review` tool, it will use inline code comments. ### BitBucket Self-Hosted App automatic tools -to control which commands will run automatically when a new PR is opened, you can set the `pr_commands` parameter in the configuration file: +To control which commands will run automatically when a new PR is opened, you can set the `pr_commands` parameter in the configuration file: Specifically, set the following values: -[bitbucket_app] ``` +[bitbucket_app] pr_commands = [ "/review --pr_reviewer.num_code_suggestions=0", "/improve --pr_code_suggestions.summarize=false", @@ -197,4 +197,4 @@ pr_commands = [ "/review --pr_reviewer.num_code_suggestions=0", "/improve", ] -``` \ No newline at end of file +``` From 27cdd419e57b78c37508dcbf3fdee1b9a0bae78f Mon Sep 17 00:00:00 2001 From: Tal Date: Mon, 1 Apr 2024 18:56:36 +0300 Subject: [PATCH 077/226] Update index.md --- docs/docs/index.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/docs/docs/index.md b/docs/docs/index.md index 246680df..3919feae 100644 --- a/docs/docs/index.md +++ b/docs/docs/index.md @@ -19,20 +19,19 @@ PR-Agent offers extensive pull request functionalities across various git provid | | โฎ‘ [SOC2 Compliance](https://pr-agent-docs.codium.ai/tools/review/#soc2-ticket-compliance){:target="_blank"} ๐Ÿ’Ž | โœ… | โœ… | โœ… | โœ… | | | Ask | โœ… | โœ… | โœ… | โœ… | | | Describe | โœ… | โœ… | โœ… | โœ… | -| | โฎ‘ [Inline file summary](https://pr-agent-docs.codium.ai/tools/describe/#inline-file-summary){:target="_blank"} ๐Ÿ’Ž | โœ… | โœ… | โœ… | โœ… | +| | โฎ‘ [Inline file summary](https://pr-agent-docs.codium.ai/tools/describe/#inline-file-summary){:target="_blank"} ๐Ÿ’Ž | โœ… | โœ… | | โœ… | | | Improve | โœ… | โœ… | โœ… | โœ… | | | โฎ‘ Extended | โœ… | โœ… | โœ… | โœ… | | | [Custom Suggestions](./tools/custom_suggestions.md){:target="_blank"} ๐Ÿ’Ž | โœ… | โœ… | โœ… | โœ… | | | Reflect and Review | โœ… | โœ… | โœ… | โœ… | | | Update CHANGELOG.md | โœ… | โœ… | โœ… | ๏ธ | | | Find Similar Issue | โœ… | | | ๏ธ | -| | [Add PR Documentation](./tools/documentation.md){:target="_blank"} ๐Ÿ’Ž | โœ… | โœ… | โœ… | โœ… | +| | [Add PR Documentation](./tools/documentation.md){:target="_blank"} ๐Ÿ’Ž | โœ… | โœ… | | โœ… | | | [Generate Custom Labels](./tools/describe.md#handle-custom-labels-from-the-repos-labels-page-๐Ÿ’Ž){:target="_blank"} ๐Ÿ’Ž | โœ… | โœ… | | โœ… | -| | [Analyze PR Components](./tools/analyze.md){:target="_blank"} ๐Ÿ’Ž | โœ… | โœ… | โœ… | โœ… | +| | [Analyze PR Components](./tools/analyze.md){:target="_blank"} ๐Ÿ’Ž | โœ… | โœ… | | โœ… | | | | | | | ๏ธ | | USAGE | CLI | โœ… | โœ… | โœ… | โœ… | -| | App / webhook | โœ… | โœ… | | โœ… | -| | Tagging bot | โœ… | | | โœ… | +| | App / webhook | โœ… | โœ… | โœ… | โœ… | | | Actions | โœ… | | | ๏ธ | | | | | | | | CORE | PR compression | โœ… | โœ… | โœ… | โœ… | From 501b0595759c47549ae3fc155ad79b5a29bf4835 Mon Sep 17 00:00:00 2001 From: gregoryboue Date: Tue, 2 Apr 2024 11:01:45 +0200 Subject: [PATCH 078/226] feat: allows ollama usage Fix https://github.com/Codium-ai/pr-agent/issues/657 --- pr_agent/algo/ai_handlers/litellm_ai_handler.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/pr_agent/algo/ai_handlers/litellm_ai_handler.py b/pr_agent/algo/ai_handlers/litellm_ai_handler.py index ce4d1db0..d07542f6 100644 --- a/pr_agent/algo/ai_handlers/litellm_ai_handler.py +++ b/pr_agent/algo/ai_handlers/litellm_ai_handler.py @@ -61,6 +61,9 @@ class LiteLLMAIHandler(BaseAiHandler): if get_settings().get("HUGGINGFACE.API_BASE", None) and 'huggingface' in get_settings().config.model: litellm.api_base = get_settings().huggingface.api_base self.api_base = get_settings().huggingface.api_base + if get_settings().get("OLLAMA.API_BASE", None) : + litellm.api_base = get_settings().ollama.api_base + self.api_base = get_settings().ollama.api_base if get_settings().get("HUGGINGFACE.REPITITION_PENALTY", None): self.repetition_penalty = float(get_settings().huggingface.repetition_penalty) if get_settings().get("VERTEXAI.VERTEX_PROJECT", None): @@ -150,4 +153,4 @@ class LiteLLMAIHandler(BaseAiHandler): if get_settings().config.verbosity_level >= 2: get_logger().info(f"\nAI response:\n{resp}") - return resp, finish_reason \ No newline at end of file + return resp, finish_reason From 3ebb72e3f12b3fb4404513f49ce1c908e4d1f652 Mon Sep 17 00:00:00 2001 From: mrT23 Date: Tue, 2 Apr 2024 17:52:34 +0300 Subject: [PATCH 079/226] feat: add persistent comment option for PR descriptions --- pr_agent/settings/configuration.toml | 4 +++- pr_agent/tools/pr_description.py | 9 ++++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/pr_agent/settings/configuration.toml b/pr_agent/settings/configuration.toml index 765c8342..c5c4a440 100644 --- a/pr_agent/settings/configuration.toml +++ b/pr_agent/settings/configuration.toml @@ -52,7 +52,6 @@ maximal_review_effort=5 [pr_description] # /describe # publish_labels=true -publish_description_as_comment=false add_original_user_description=true keep_original_user_title=true use_bullet_points=true @@ -61,6 +60,9 @@ enable_pr_type=true final_update_message = true enable_help_text=false enable_help_comment=true +# describe as comment +publish_description_as_comment=false +publish_description_as_comment_persistent=true ## changes walkthrough section enable_semantic_files_types=true collapsible_file_list='adaptive' # true, false, 'adaptive' diff --git a/pr_agent/tools/pr_description.py b/pr_agent/tools/pr_description.py index 7500efa7..8526642f 100644 --- a/pr_agent/tools/pr_description.py +++ b/pr_agent/tools/pr_description.py @@ -132,7 +132,14 @@ class PRDescription: # publish description if get_settings().pr_description.publish_description_as_comment: full_markdown_description = f"## Title\n\n{pr_title}\n\n___\n{pr_body}" - self.git_provider.publish_comment(full_markdown_description) + if get_settings().pr_description.publish_description_as_comment_persistent: + self.git_provider.publish_persistent_comment(full_markdown_description, + initial_header="## Title", + update_header=True, + name="describe", + final_update_message=False, ) + else: + self.git_provider.publish_comment(full_markdown_description) else: self.git_provider.publish_description(pr_title, pr_body) From 9614f619e83d20d9b86a18b95f5fbb634ac4a187 Mon Sep 17 00:00:00 2001 From: mrT23 Date: Tue, 2 Apr 2024 17:54:37 +0300 Subject: [PATCH 080/226] feat: add persistent comment option for PR descriptions --- docs/docs/tools/describe.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/docs/tools/describe.md b/docs/docs/tools/describe.md index e0de5153..bbd03ab7 100644 --- a/docs/docs/tools/describe.md +++ b/docs/docs/tools/describe.md @@ -27,6 +27,8 @@ To edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agen - `publish_description_as_comment`: if set to true, the tool will publish the description as a comment to the PR. If false, it will overwrite the original description. Default is false. + - `publish_description_as_comment_persistent`: if set to true and `publish_description_as_comment` is true, the tool will publish the description as a persistent comment to the PR. Default is true. + - `add_original_user_description`: if set to true, the tool will add the original user description to the generated description. Default is true. - `keep_original_user_title`: if set to true, the tool will keep the original PR title, and won't change it. Default is true. From 9c3673209dd7dd80d652c04dcec6131bdb3d048a Mon Sep 17 00:00:00 2001 From: mrT23 Date: Wed, 3 Apr 2024 08:42:50 +0300 Subject: [PATCH 081/226] TokenEncoder --- pr_agent/algo/token_handler.py | 23 ++++++++++++++++++----- pr_agent/algo/utils.py | 4 ++-- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/pr_agent/algo/token_handler.py b/pr_agent/algo/token_handler.py index d7eff9d7..9cc3b41f 100644 --- a/pr_agent/algo/token_handler.py +++ b/pr_agent/algo/token_handler.py @@ -1,12 +1,25 @@ from jinja2 import Environment, StrictUndefined from tiktoken import encoding_for_model, get_encoding - from pr_agent.config_loader import get_settings +from threading import Lock -def get_token_encoder(): - return encoding_for_model(get_settings().config.model) if "gpt" in get_settings().config.model else get_encoding( - "cl100k_base") +class TokenEncoder: + _encoder_instance = None + _model = None + _lock = Lock() # Create a lock object + + @classmethod + def get_token_encoder(cls): + model = get_settings().config.model + if cls._encoder_instance is None or model != cls._model: # Check without acquiring the lock for performance + with cls._lock: # Lock acquisition to ensure thread safety + if cls._encoder_instance is None or model != cls._model: + cls._model = model + cls._encoder_instance = encoding_for_model(cls._model) if "gpt" in cls._model else get_encoding( + "cl100k_base") + return cls._encoder_instance + class TokenHandler: """ @@ -31,7 +44,7 @@ class TokenHandler: - system: The system string. - user: The user string. """ - self.encoder = get_token_encoder() + self.encoder = TokenEncoder.get_token_encoder() if pr is not None: self.prompt_tokens = self._get_system_user_tokens(pr, self.encoder, vars, system, user) diff --git a/pr_agent/algo/utils.py b/pr_agent/algo/utils.py index c2b6323c..b017f0aa 100644 --- a/pr_agent/algo/utils.py +++ b/pr_agent/algo/utils.py @@ -12,7 +12,7 @@ import yaml from starlette_context import context from pr_agent.algo import MAX_TOKENS -from pr_agent.algo.token_handler import get_token_encoder +from pr_agent.algo.token_handler import TokenEncoder from pr_agent.config_loader import get_settings, global_settings from pr_agent.algo.types import FilePatchInfo from pr_agent.log import get_logger @@ -566,7 +566,7 @@ def clip_tokens(text: str, max_tokens: int, add_three_dots=True) -> str: return text try: - encoder = get_token_encoder() + encoder = TokenEncoder.get_token_encoder() num_input_tokens = len(encoder.encode(text)) if num_input_tokens <= max_tokens: return text From d7b19af117dc71d60154682c1871f00e65ace2e4 Mon Sep 17 00:00:00 2001 From: Almog Lavi <42740235+almog-lv@users.noreply.github.com> Date: Wed, 3 Apr 2024 14:53:56 +0300 Subject: [PATCH 082/226] Update README.md --- docs/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/README.md b/docs/README.md index 68867ce4..a06f01af 100644 --- a/docs/README.md +++ b/docs/README.md @@ -13,3 +13,4 @@ The deployment is managed on the gh-pages branches. After each merge to main the deplloyment will be taken care of by GH action automatically and the new version will be available at: [Docs](https://codium-ai.github.io/docs/) Github action is located in `.github/workflows/ci.yml` file. + From 877aeffbb3cfaebe923a86c916f9f0b12c1d8156 Mon Sep 17 00:00:00 2001 From: Almog Lavi <42740235+almog-lv@users.noreply.github.com> Date: Wed, 3 Apr 2024 14:59:53 +0300 Subject: [PATCH 083/226] Update describe.md --- docs/docs/tools/describe.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/docs/tools/describe.md b/docs/docs/tools/describe.md index bbd03ab7..1510b2e8 100644 --- a/docs/docs/tools/describe.md +++ b/docs/docs/tools/describe.md @@ -5,6 +5,7 @@ The tool can be triggered automatically every time a new PR is [opened](../usage ``` /describe ``` + For example: ![Describe comment](https://codium.ai/images/pr_agent/describe_comment.png){width=512} @@ -160,4 +161,4 @@ The marker `pr_agent:type` will be replaced with the PR type, `pr_agent:summary` The list above is eclectic, and aims to give an idea of different possibilities. Define custom labels that are relevant for your repo and use cases. Note that Labels are not mutually exclusive, so you can add multiple label categories. -
Make sure to provide proper title, and a detailed and well-phrased description for each label, so the tool will know when to suggest it. \ No newline at end of file +
Make sure to provide proper title, and a detailed and well-phrased description for each label, so the tool will know when to suggest it. From bbd302360f475129e8b890ddc3d9bb553a77c56f Mon Sep 17 00:00:00 2001 From: Tal Date: Fri, 5 Apr 2024 17:22:54 +0300 Subject: [PATCH 084/226] Update additional_configurations.md --- .../usage-guide/additional_configurations.md | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/docs/docs/usage-guide/additional_configurations.md b/docs/docs/usage-guide/additional_configurations.md index 1a756252..e1128817 100644 --- a/docs/docs/usage-guide/additional_configurations.md +++ b/docs/docs/usage-guide/additional_configurations.md @@ -7,10 +7,10 @@ To ignore files or directories, edit the **[ignore.toml](https://github.com/Codi - `IGNORE.GLOB` - `IGNORE.REGEX` -For example, to ignore python files in a PR with online usage, comment on a PR: +For example, to ignore Python files in a PR with online usage, comment on a PR: `/review --ignore.glob=['*.py']` -To ignore python files in all PRs, set in a configuration file: +To ignore Python files in all PRs, set in a configuration file: ``` [ignore] glob = ['*.py'] @@ -26,13 +26,13 @@ All PR-Agent tools have a parameter called `extra_instructions`, that enables to ## Working with large PRs The default mode of CodiumAI is to have a single call per tool, using GPT-4, which has a token limit of 8000 tokens. -This mode provide a very good speed-quality-cost tradeoff, and can handle most PRs successfully. +This mode provides a very good speed-quality-cost tradeoff, and can handle most PRs successfully. When the PR is above the token limit, it employs a [PR Compression strategy](../core-abilities/index.md). -However, for very large PRs, or in case you want to emphasize quality over speed and cost, there are 2 possible solutions: +However, for very large PRs, or in case you want to emphasize quality over speed and cost, there are two possible solutions: 1) [Use a model](https://codium-ai.github.io/Docs-PR-Agent/usage-guide/#changing-a-model) with larger context, like GPT-32K, or claude-100K. This solution will be applicable for all the tools. 2) For the `/improve` tool, there is an ['extended' mode](https://codium-ai.github.io/Docs-PR-Agent/tools/#improve) (`/improve --extended`), -which divides the PR to chunks, and process each chunk separately. With this mode, regardless of the model, no compression will be done (but for large PRs, multiple model calls may occur) +which divides the PR to chunks, and processes each chunk separately. With this mode, regardless of the model, no compression will be done (but for large PRs, multiple model calls may occur) ## Changing a model @@ -79,6 +79,7 @@ MAX_TOKENS={ [config] # in configuration.toml model = "ollama/llama2" +model_turbo = "ollama/llama2" [ollama] # in .secrets.toml api_base = ... # the base url for your huggingface inference endpoint @@ -101,6 +102,7 @@ MAX_TOKENS={ } [config] # in configuration.toml model = "huggingface/meta-llama/Llama-2-7b-chat-hf" +model_turbo = "huggingface/meta-llama/Llama-2-7b-chat-hf" [huggingface] # in .secrets.toml key = ... # your huggingface api key @@ -114,13 +116,14 @@ To use Llama2 model with Replicate, for example, set: ``` [config] # in configuration.toml model = "replicate/llama-2-70b-chat:2c1608e18606fad2812020dc541930f2d0495ce32eee50074220b87300bc16e1" +model_turbo = "replicate/llama-2-70b-chat:2c1608e18606fad2812020dc541930f2d0495ce32eee50074220b87300bc16e1" [replicate] # in .secrets.toml key = ... ``` (you can obtain a Llama2 key from [here](https://replicate.com/replicate/llama-2-70b-chat/api)) -Also review the [AiHandler](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/algo/ai_handler.py) file for instruction how to set keys for other models. +Also, review the [AiHandler](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/algo/ai_handler.py) file for instructions on how to set keys for other models. ### Vertex AI @@ -129,6 +132,7 @@ To use Google's Vertex AI platform and its associated models (chat-bison/codecha ``` [config] # in configuration.toml model = "vertex_ai/codechat-bison" +model_turbo = "vertex_ai/codechat-bison" fallback_models="vertex_ai/codechat-bison" [vertexai] # in .secrets.toml @@ -183,7 +187,7 @@ AWS session is automatically authenticated from your environment, but you can al ## Patch Extra Lines -By default, around any change in your PR, git patch provides 3 lines of context above and below the change. +By default, around any change in your PR, git patch provides three lines of context above and below the change. ``` @@ -12,5 +12,5 @@ def func1(): code line that already existed in the file... From 4dc160bc1684a6dbfb8df306113bb9b9fc10126a Mon Sep 17 00:00:00 2001 From: mrT23 Date: Sun, 7 Apr 2024 09:08:40 +0300 Subject: [PATCH 085/226] readme --- README.md | 50 ++++++++++++------- docs/docs/index.md | 10 ++-- docs/docs/installation/index.md | 2 +- .../docs/usage-guide/automations_and_usage.md | 4 ++ docs/mkdocs.yml | 2 +- 5 files changed, 44 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index 0d75489c..de3f51e5 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,6 @@ CodiumAI PR-Agent aims to help efficiently review and handle pull requests, by p - [Overview](#overview) - [Example results](#example-results) - [Try it now](#try-it-now) -- [Installation](#installation) - [PR-Agent Pro ๐Ÿ’Ž](#pr-agent-pro-) - [How it works](#how-it-works) - [Why use PR-Agent?](#why-use-pr-agent) @@ -235,32 +234,47 @@ Note that when you set your own PR-Agent or use CodiumAI hosted PR-Agent, there --- -## Installation -To use your own version of PR-Agent, you first need to acquire two tokens: +[//]: # (## Installation) -1. An OpenAI key from [here](https://platform.openai.com/), with access to GPT-4. -2. A GitHub personal access token (classic) with the repo scope. +[//]: # (To use your own version of PR-Agent, you first need to acquire two tokens:) -There are several ways to use PR-Agent: +[//]: # () +[//]: # (1. An OpenAI key from [here](https://platform.openai.com/), with access to GPT-4.) -**Locally** -- [Using pip package](https://pr-agent-docs.codium.ai/installation/locally/#using-pip-package) -- [Using Docker image](https://pr-agent-docs.codium.ai/installation/locally/#using-docker-image) -- [Run from source](https://pr-agent-docs.codium.ai/installation/locally/#run-from-source) +[//]: # (2. A GitHub personal access token (classic) with the repo scope.) -**GitHub specific methods** -- [Run as a GitHub Action](https://pr-agent-docs.codium.ai/installation/github/#run-as-a-github-action) -- [Run as a GitHub App](https://pr-agent-docs.codium.ai/installation/github/#run-as-a-github-app) +[//]: # () +[//]: # (There are several ways to use PR-Agent:) -**GitLab specific methods** -- [Run a GitLab webhook server](https://pr-agent-docs.codium.ai/installation/gitlab/) +[//]: # () +[//]: # (**Locally**) -**BitBucket specific methods** -- [Run as a Bitbucket Pipeline](https://pr-agent-docs.codium.ai/installation/bitbucket/) +[//]: # (- [Using pip package](https://pr-agent-docs.codium.ai/installation/locally/#using-pip-package)) + +[//]: # (- [Using Docker image](https://pr-agent-docs.codium.ai/installation/locally/#using-docker-image)) + +[//]: # (- [Run from source](https://pr-agent-docs.codium.ai/installation/locally/#run-from-source)) + +[//]: # () +[//]: # (**GitHub specific methods**) + +[//]: # (- [Run as a GitHub Action](https://pr-agent-docs.codium.ai/installation/github/#run-as-a-github-action)) + +[//]: # (- [Run as a GitHub App](https://pr-agent-docs.codium.ai/installation/github/#run-as-a-github-app)) + +[//]: # () +[//]: # (**GitLab specific methods**) + +[//]: # (- [Run a GitLab webhook server](https://pr-agent-docs.codium.ai/installation/gitlab/)) + +[//]: # () +[//]: # (**BitBucket specific methods**) + +[//]: # (- [Run as a Bitbucket Pipeline](https://pr-agent-docs.codium.ai/installation/bitbucket/)) ## PR-Agent Pro ๐Ÿ’Ž [PR-Agent Pro](https://www.codium.ai/pricing/) is a hosted version of PR-Agent, provided by CodiumAI. It is available for a monthly fee, and provides the following benefits: -1. **Fully managed** - We take care of everything for you - hosting, models, regular updates, and more. Installation is as simple as signing up and adding the PR-Agent app to your GitHub\BitBucket repo. +1. **Fully managed** - We take care of everything for you - hosting, models, regular updates, and more. Installation is as simple as signing up and adding the PR-Agent app to your GitHub\GitLab\BitBucket repo. 2. **Improved privacy** - No data will be stored or used to train models. PR-Agent Pro will employ zero data retention, and will use an OpenAI account with zero data retention. 3. **Improved support** - PR-Agent Pro users will receive priority support, and will be able to request new features and capabilities. 4. **Extra features** -In addition to the benefits listed above, PR-Agent Pro will emphasize more customization, and the usage of static code analysis, in addition to LLM logic, to improve results. diff --git a/docs/docs/index.md b/docs/docs/index.md index 3919feae..cec35b45 100644 --- a/docs/docs/index.md +++ b/docs/docs/index.md @@ -45,7 +45,7 @@ PR-Agent offers extensive pull request functionalities across various git provid ๐Ÿ’Ž marks a feature available only in [PR-Agent Pro](https://www.codium.ai/pricing/){:target="_blank"} -## Example results +## Example Results #### [/describe](https://github.com/Codium-ai/pr-agent/pull/530)
![/describe](https://www.codium.ai/images/pr_agent/describe_new_short_main.png){width=512} @@ -66,7 +66,7 @@ PR-Agent offers extensive pull request functionalities across various git provid ![/generate_labels](https://www.codium.ai/images/pr_agent/geneare_custom_labels_main_short.png){width=300}
-## How it works +## How it Works The following diagram illustrates PR-Agent tools and their flow: @@ -80,7 +80,7 @@ Check out the [PR Compression strategy](core-abilities/index.md) page for more d [PR-Agent Pro](https://www.codium.ai/pricing/) is a hosted version of PR-Agent, provided by CodiumAI. It is available for a monthly fee, and provides the following benefits: -1. **Fully managed** - We take care of everything for you - hosting, models, regular updates, and more. Installation is as simple as signing up and adding the PR-Agent app to your GitHub\BitBucket repo. +1. **Fully managed** - We take care of everything for you - hosting, models, regular updates, and more. Installation is as simple as signing up and adding the PR-Agent app to your GitHub\GitLab\BitBucket repo. 2. **Improved privacy** - No data will be stored or used to train models. PR-Agent Pro will employ zero data retention, and will use an OpenAI account with zero data retention. 3. **Improved support** - PR-Agent Pro users will receive priority support, and will be able to request new features and capabilities. 4. **Extra features** -In addition to the benefits listed above, PR-Agent Pro will emphasize more customization, and the usage of static code analysis, in addition to LLM logic, to improve results. It has the following additional tools and features: @@ -88,13 +88,15 @@ Check out the [PR Compression strategy](core-abilities/index.md) page for more d - [**Custom Code Suggestions**](./tools/custom_suggestions.md/) - [**Tests**](./tools/test.md/) - [**PR documentation**](./tools/documentation.md/) + - [**Improve Component**](https://pr-agent-docs.codium.ai/tools/improve_component/) + - [**Similar code search**](https://pr-agent-docs.codium.ai/tools/similar_code/) - [**CI feedback**](./tools/ci_feedback.md/) - [**SOC2 compliance check**](./tools/review.md/#soc2-ticket-compliance) - [**Custom labels**](./tools/describe.md/#handle-custom-labels-from-the-repos-labels-page) - [**Global and wiki configuration**](./usage-guide/configuration_options.md/#wiki-configuration-file) -## Data privacy +## Data Privacy If you host PR-Agent with your OpenAI API key, it is between you and OpenAI. You can read their API data privacy policy here: https://openai.com/enterprise-privacy diff --git a/docs/docs/installation/index.md b/docs/docs/installation/index.md index fc71ecbb..f8b64a27 100644 --- a/docs/docs/installation/index.md +++ b/docs/docs/installation/index.md @@ -1,6 +1,6 @@ # Installation -## self-hosted PR-Agent +## Self-hosted PR-Agent If you choose to host you own PR-Agent, you first need to acquire two tokens: 1. An OpenAI key from [here](https://platform.openai.com/api-keys), with access to GPT-4 (or a key for [other models](../usage-guide/additional_configurations.md/#changing-a-model), if you prefer). diff --git a/docs/docs/usage-guide/automations_and_usage.md b/docs/docs/usage-guide/automations_and_usage.md index f32863eb..3d23c491 100644 --- a/docs/docs/usage-guide/automations_and_usage.md +++ b/docs/docs/usage-guide/automations_and_usage.md @@ -50,6 +50,10 @@ Any configuration value in [configuration file](https://github.com/Codium-ai/pr- ## GitHub App +!!! note "Configurations for PR-Agent Pro" + PR-Agent Pro for GitHub is an App, hosted by CodiumAI. So all the instructions below are relevant also for PR-Agent Pro users. + Same goes for [GitLab webhook](#gitlab-webhook) and [BitBucket App](#bitbucket-app) sections. + ### GitHub app automatic tools when a new PR is opened The [github_app](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/configuration.toml#L108) section defines GitHub app specific configurations. diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index c045d8e4..a34c1bc0 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -14,7 +14,7 @@ nav: - 'usage-guide/index.md' - Introduction: 'usage-guide/introduction.md' - Configuration Options: 'usage-guide/configuration_options.md' - - Managing email notifications: 'usage-guide/mail_notifications.md' + - Managing Mail Notifications: 'usage-guide/mail_notifications.md' - Usage and Automation: 'usage-guide/automations_and_usage.md' - Additional Configurations: 'usage-guide/additional_configurations.md' - Tools: From d9efc441df3941513793f8d22b559174dbb135af Mon Sep 17 00:00:00 2001 From: mrT23 Date: Sun, 7 Apr 2024 09:28:22 +0300 Subject: [PATCH 086/226] readme --- docs/docs/index.md | 22 ++++++++++++---------- docs/docs/tools/analyze.md | 10 +++------- docs/docs/tools/help.md | 13 +++++++++++++ docs/docs/tools/index.md | 1 + 4 files changed, 29 insertions(+), 17 deletions(-) create mode 100644 docs/docs/tools/help.md diff --git a/docs/docs/index.md b/docs/docs/index.md index cec35b45..198bee22 100644 --- a/docs/docs/index.md +++ b/docs/docs/index.md @@ -84,16 +84,18 @@ Check out the [PR Compression strategy](core-abilities/index.md) page for more d 2. **Improved privacy** - No data will be stored or used to train models. PR-Agent Pro will employ zero data retention, and will use an OpenAI account with zero data retention. 3. **Improved support** - PR-Agent Pro users will receive priority support, and will be able to request new features and capabilities. 4. **Extra features** -In addition to the benefits listed above, PR-Agent Pro will emphasize more customization, and the usage of static code analysis, in addition to LLM logic, to improve results. It has the following additional tools and features: - - [**Analyze PR components**](./tools/analyze.md/) - - [**Custom Code Suggestions**](./tools/custom_suggestions.md/) - - [**Tests**](./tools/test.md/) - - [**PR documentation**](./tools/documentation.md/) - - [**Improve Component**](https://pr-agent-docs.codium.ai/tools/improve_component/) - - [**Similar code search**](https://pr-agent-docs.codium.ai/tools/similar_code/) - - [**CI feedback**](./tools/ci_feedback.md/) - - [**SOC2 compliance check**](./tools/review.md/#soc2-ticket-compliance) - - [**Custom labels**](./tools/describe.md/#handle-custom-labels-from-the-repos-labels-page) - - [**Global and wiki configuration**](./usage-guide/configuration_options.md/#wiki-configuration-file) + - (Tool): [**Analyze PR components**](./tools/analyze.md/) + - (Tool): [**Custom Code Suggestions**](./tools/custom_suggestions.md/) + - (Tool): [**Tests**](./tools/test.md/) + - (Tool): [**PR documentation**](./tools/documentation.md/) + - (Tool): [**Improve Component**](https://pr-agent-docs.codium.ai/tools/improve_component/) + - (Tool): [**Similar code search**](https://pr-agent-docs.codium.ai/tools/similar_code/) + - (Tool): [**CI feedback**](./tools/ci_feedback.md/) + - (Feature): [**Interactive triggering**](./usage-guide/automations_and_usage.md/#interactive-triggering) + - (Feature): [**SOC2 compliance check**](./tools/review.md/#soc2-ticket-compliance) + - (Feature): [**Custom labels**](./tools/describe.md/#handle-custom-labels-from-the-repos-labels-page) + - (Feature): [**Global and wiki configuration**](./usage-guide/configuration_options.md/#wiki-configuration-file) + - (Feature): [**Inline file summary**](https://pr-agent-docs.codium.ai/tools/describe/#inline-file-summary) ## Data Privacy diff --git a/docs/docs/tools/analyze.md b/docs/docs/tools/analyze.md index 0255e759..7af0546e 100644 --- a/docs/docs/tools/analyze.md +++ b/docs/docs/tools/analyze.md @@ -1,7 +1,7 @@ ## Overview -The `analyze` tool combines static code analysis with LLM capabilities to provide a comprehensive analysis of the PR code changes. +The `analyze` tool combines advanced static code analysis with LLM capabilities to provide a comprehensive analysis of the PR code changes. -The tool scans the PR code changes, find the code components (methods, functions, classes) that changed, and summarizes the changes in each component. +The tool scans the PR code changes, find the code components (methods, functions, classes) that changed, and enables to interactively generate tests, docs, code suggestions and similar code search for each component. It can be invoked manually by commenting on any PR: ``` @@ -9,13 +9,9 @@ It can be invoked manually by commenting on any PR: ``` ## Example usage -An example [result](https://github.com/Codium-ai/pr-agent/pull/546#issuecomment-1868524805): +An example result: ![Analyze 1](https://codium.ai/images/pr_agent/analyze_1.png){width=750} -→ -![Analyze 2](https://codium.ai/images/pr_agent/analyze_2.png){width=750} -→ -![Analyze 3](https://codium.ai/images/pr_agent/analyze_3.png){width=750} **Notes** diff --git a/docs/docs/tools/help.md b/docs/docs/tools/help.md new file mode 100644 index 00000000..ac66d158 --- /dev/null +++ b/docs/docs/tools/help.md @@ -0,0 +1,13 @@ +## Overview +The `help` tool provides a list of all the available tools and their descriptions. +For PR-Agent Pro users, it also enables to trigger each tool by checking the relevant box. +``` +/help +``` + +## Example usage +An example [result](https://github.com/Codium-ai/pr-agent/pull/546#issuecomment-1868524805): + +![Help 1](https://codium.ai/images/pr_agent/help1.png){width=750} +→ +![Analyze 2](https://codium.ai/images/pr_agent/help2.png){width=750} diff --git a/docs/docs/tools/index.md b/docs/docs/tools/index.md index b77097b3..49c31a8f 100644 --- a/docs/docs/tools/index.md +++ b/docs/docs/tools/index.md @@ -10,6 +10,7 @@ Here is a list of PR-Agent tools, each with a dedicated page that explains how t | **[Question Answering (`/ask ...`](./ask.md))** | Answering free-text questions about the PR, or on specific code lines | | **[Update Changelog (`/update_changelog`](./update_changelog.md))** | Automatically updating the CHANGELOG.md file with the PR changes | | **[Find Similar Issue (`/similar_issue`](./similar_issues.md))** | Automatically retrieves and presents similar issues | +| **[Help (`/help`](./help.md))** | Provides a list of all the available tools. Also enables to trigger them interactively (๐Ÿ’Ž) | | **๐Ÿ’Ž [Add Documentation (`/add_docs`](./documentation.md))** | Generates documentation to methods/functions/classes that changed in the PR | | **๐Ÿ’Ž [Generate Custom Labels (`/generate_labels`](./custom_labels.md))** | Generates custom labels for the PR, based on specific guidelines defined by the user | | **๐Ÿ’Ž [Analyze (`/analyze`](./analyze.md))** | Identify code components that changed in the PR, and enables to interactively generate tests, docs, and code suggestions for each component | From 60fd1c67fa4894f7c5e0092f579ec52d1b9e0415 Mon Sep 17 00:00:00 2001 From: mrT23 Date: Sun, 7 Apr 2024 09:35:41 +0300 Subject: [PATCH 087/226] readme --- docs/docs/usage-guide/index.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/docs/usage-guide/index.md b/docs/docs/usage-guide/index.md index e784d1b0..ce714c70 100644 --- a/docs/docs/usage-guide/index.md +++ b/docs/docs/usage-guide/index.md @@ -1,8 +1,10 @@ # Usage guide +This page provides a detailed guide on how to use PR-Agent. It includes information on how to adjust PR-Agent configurations, define which tools will run automatically, manage mail notifications, and other advanced configurations. + + - [Introduction](./introduction.md) - [Configuration Options](./configuration_options.md) -- [Managing Mail Notifications](./mail_notifications.md) - [Usage and Automation](./automations_and_usage.md) - [Local Repo (CLI)](./automations_and_usage.md#local-repo-cli) - [Online Usage](./automations_and_usage.md#online-usage) @@ -11,6 +13,7 @@ - [GitLab Webhook](./automations_and_usage.md#gitlab-webhook) - [BitBucket App](./automations_and_usage.md#bitbucket-app) - [Azure DevOps Provider](./automations_and_usage.md#azure-devops-provider) +- [Managing Mail Notifications](./mail_notifications.md) - [Additional Configurations Walkthrough](./additional_configurations.md) - [Ignoring files from analysis](./additional_configurations.md#ignoring-files-from-analysis) - [Extra instructions](./additional_configurations.md#extra-instructions) From f3b46956173441320bb29df3921b14acfbdb1ff3 Mon Sep 17 00:00:00 2001 From: mrT23 Date: Sun, 7 Apr 2024 10:43:56 +0300 Subject: [PATCH 088/226] readme --- docs/docs/tools/help.md | 4 ++++ docs/docs/usage-guide/mail_notifications.md | 8 ++++++++ docs/mkdocs.yml | 1 + 3 files changed, 13 insertions(+) diff --git a/docs/docs/tools/help.md b/docs/docs/tools/help.md index ac66d158..5cfc1e81 100644 --- a/docs/docs/tools/help.md +++ b/docs/docs/tools/help.md @@ -1,6 +1,8 @@ ## Overview The `help` tool provides a list of all the available tools and their descriptions. For PR-Agent Pro users, it also enables to trigger each tool by checking the relevant box. + +It can be invoked manually by commenting on any PR: ``` /help ``` @@ -9,5 +11,7 @@ For PR-Agent Pro users, it also enables to trigger each tool by checking the rel An example [result](https://github.com/Codium-ai/pr-agent/pull/546#issuecomment-1868524805): ![Help 1](https://codium.ai/images/pr_agent/help1.png){width=750} + → + ![Analyze 2](https://codium.ai/images/pr_agent/help2.png){width=750} diff --git a/docs/docs/usage-guide/mail_notifications.md b/docs/docs/usage-guide/mail_notifications.md index 82dc10a0..4c2ee64e 100644 --- a/docs/docs/usage-guide/mail_notifications.md +++ b/docs/docs/usage-guide/mail_notifications.md @@ -7,3 +7,11 @@ If you are subscribed to notifications for a repo with PR-Agent, we recommend tu As an alternative, you can filter in your mail provider the notifications specifically from the PR-Agent bot, [see how](https://www.quora.com/How-can-you-filter-emails-for-specific-people-in-Gmail#:~:text=On%20the%20Filters%20and%20Blocked,the%20body%20of%20the%20email). ![filter_mail_notifications](https://codium.ai/images/pr_agent/filter_mail_notifications.png){width=512} + + +Another option to reduce the mail overload is disable the help collapsible section in PR-Agent bot comments, by adding the relevant configurations to the `.pr_agent.toml` file. +For example, to disable the help text for the `pr_reviewer` tool, add to the configuration file: +``` +[pr_reviewer] +enable_help_text = false +``` \ No newline at end of file diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index a34c1bc0..717f42bf 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -25,6 +25,7 @@ nav: - Ask: 'tools/ask.md' - Update Changelog: 'tools/update_changelog.md' - Similar Issues: 'tools/similar_issues.md' + - Help: 'tools/help.md' - ๐Ÿ’Ž Analyze: 'tools/analyze.md' - ๐Ÿ’Ž Test: 'tools/test.md' - ๐Ÿ’Ž Improve Component: 'tools/improve_component.md' From 45eefaa4f0068e596cb330fcf1861292be58b206 Mon Sep 17 00:00:00 2001 From: mrT23 Date: Sun, 7 Apr 2024 11:04:23 +0300 Subject: [PATCH 089/226] readme --- docs/docs/usage-guide/mail_notifications.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/docs/usage-guide/mail_notifications.md b/docs/docs/usage-guide/mail_notifications.md index 4c2ee64e..1d6f6dcb 100644 --- a/docs/docs/usage-guide/mail_notifications.md +++ b/docs/docs/usage-guide/mail_notifications.md @@ -9,8 +9,9 @@ As an alternative, you can filter in your mail provider the notifications specif ![filter_mail_notifications](https://codium.ai/images/pr_agent/filter_mail_notifications.png){width=512} -Another option to reduce the mail overload is disable the help collapsible section in PR-Agent bot comments, by adding the relevant configurations to the `.pr_agent.toml` file. -For example, to disable the help text for the `pr_reviewer` tool, add to the configuration file: +Another option to reduce the mail overload, yet still receive notifications on PR-Agent tools, is to disable the help collapsible section in PR-Agent bot comments. +This can done by setting `enable_help_text=false` configuration to the relevant tool in the configuration file. +For example, to disable the help text for the `pr_reviewer` tool, set: ``` [pr_reviewer] enable_help_text = false From d6b037a63a9244ab32eeb3da9f5c40aa501d530a Mon Sep 17 00:00:00 2001 From: mrT23 Date: Sun, 7 Apr 2024 11:51:06 +0300 Subject: [PATCH 090/226] readme --- docs/docs/tools/describe.md | 70 ++++++++++++++------------- pr_agent/tools/pr_code_suggestions.py | 41 +++++++++------- 2 files changed, 61 insertions(+), 50 deletions(-) diff --git a/docs/docs/tools/describe.md b/docs/docs/tools/describe.md index 1510b2e8..50d2af0a 100644 --- a/docs/docs/tools/describe.md +++ b/docs/docs/tools/describe.md @@ -69,22 +69,6 @@ If you prefer to have the file summaries appear in the "Files changed" tab on ev **Note**: that this feature is currently available only for GitHub. -### Handle custom labels from the Repo's labels page ๐Ÿ’Ž - -You can control the custom labels that will be suggested by the `describe` tool, from the repo's labels page: - -* GitHub : go to `https://github.com/{owner}/{repo}/labels` (or click on the "Labels" tab in the issues or PRs page) -* GitLab : go to `https://gitlab.com/{owner}/{repo}/-/labels` (or click on "Manage" -> "Labels" on the left menu) - -Now add/edit the custom labels. they should be formatted as follows: - -* Label name: The name of the custom label. -* Description: Start the description of with prefix `pr_agent:`, for example: `pr_agent: Description of when AI should suggest this label`.
- -The description should be comprehensive and detailed, indicating when to add the desired label. For example: -![Add native custom labels](https://codium.ai/images/pr_agent/add_native_custom_labels.png){width=768} - - ### Markers template To enable markers, set `pr_description.use_description_markers=true`. @@ -117,6 +101,43 @@ The marker `pr_agent:type` will be replaced with the PR type, `pr_agent:summary` - `use_description_markers`: if set to true, the tool will use markers template. It replaces every marker of the form `pr_agent:marker_name` with the relevant content. Default is false. - `include_generated_by_header`: if set to true, the tool will add a dedicated header: 'Generated by PR Agent at ...' to any automatic content. Default is true. +## Custom labels + +The default labels of the describe tool are quite generic, since they are meant to be used in any repo: [`Bug fix`, `Tests`, `Enhancement`, `Documentation`, `Other`]. + +You can define custom labels that are relevant for your repo and use cases. +Custom labels can be defined in a [configuration file](https://pr-agent-docs.codium.ai/tools/custom_labels/#configuration-options), or directly in the repo's [labels page](#handle-custom-labels-from-the-repos-labels-page). + +Examples for custom labels: + + - `Main topic:performance` - pr_agent:The main topic of this PR is performance + - `New endpoint` - pr_agent:A new endpoint was added in this PR + - `SQL query` - pr_agent:A new SQL query was added in this PR + - `Dockerfile changes` - pr_agent:The PR contains changes in the Dockerfile + - ... + +The list above is eclectic, and aims to give an idea of different possibilities. Define custom labels that are relevant for your repo and use cases. +Note that Labels are not mutually exclusive, so you can add multiple label categories. +
+Make sure to provide proper title, and a detailed and well-phrased description for each label, so the tool will know when to suggest it. +Each label description should be a **conditional statement**, that indicates if to add the label to the PR or not, according to the PR content. + + +### Handle custom labels from the Repo's labels page ๐Ÿ’Ž + +You can control the custom labels that will be suggested by the `describe` tool, from the repo's labels page: + +* GitHub : go to `https://github.com/{owner}/{repo}/labels` (or click on the "Labels" tab in the issues or PRs page) +* GitLab : go to `https://gitlab.com/{owner}/{repo}/-/labels` (or click on "Manage" -> "Labels" on the left menu) + +Now add/edit the custom labels. they should be formatted as follows: + +* Label name: The name of the custom label. +* Description: Start the description of with prefix `pr_agent:`, for example: `pr_agent: Description of when AI should suggest this label`.
+ +The description should be comprehensive and detailed, indicating when to add the desired label. For example: +![Add native custom labels](https://codium.ai/images/pr_agent/add_native_custom_labels.png){width=768} + ## Usage Tips @@ -145,20 +166,3 @@ The marker `pr_agent:type` will be replaced with the PR type, `pr_agent:summary` * `walkthrough`: the PR walkthrough. - Note that when markers are enabled, if the original PR description does not contain any markers, the tool will not alter the description at all. - -!!! tip "Custom labels" - - The default labels of the describe tool are quite generic, since they are meant to be used in any repo: [`Bug fix`, `Tests`, `Enhancement`, `Documentation`, `Other`]. - - If you specify [custom labels](#handle-custom-labels-from-the-repos-labels-page) in the repo's labels page, you can get tailored labels for your use cases. - Examples for custom labels: - - - `Main topic:performance` - pr_agent:The main topic of this PR is performance - - `New endpoint` - pr_agent:A new endpoint was added in this PR - - `SQL query` - pr_agent:A new SQL query was added in this PR - - `Dockerfile changes` - pr_agent:The PR contains changes in the Dockerfile - - ... - - The list above is eclectic, and aims to give an idea of different possibilities. Define custom labels that are relevant for your repo and use cases. - Note that Labels are not mutually exclusive, so you can add multiple label categories. -
Make sure to provide proper title, and a detailed and well-phrased description for each label, so the tool will know when to suggest it. diff --git a/pr_agent/tools/pr_code_suggestions.py b/pr_agent/tools/pr_code_suggestions.py index 926edf00..ed14d225 100644 --- a/pr_agent/tools/pr_code_suggestions.py +++ b/pr_agent/tools/pr_code_suggestions.py @@ -196,24 +196,31 @@ class PRCodeSuggestions: suggestion_list = [] one_sentence_summary_list = [] for i, suggestion in enumerate(data['code_suggestions']): - if get_settings().pr_code_suggestions.summarize: - if not suggestion or 'one_sentence_summary' not in suggestion or 'label' not in suggestion or 'relevant_file' not in suggestion: - get_logger().debug(f"Skipping suggestion {i + 1}, because it is invalid: {suggestion}") - continue - - if suggestion['one_sentence_summary'] in one_sentence_summary_list: - get_logger().debug(f"Skipping suggestion {i + 1}, because it is a duplicate: {suggestion}") - continue - - if ('existing_code' in suggestion) and ('improved_code' in suggestion) and ( - suggestion['existing_code'] != suggestion['improved_code']): - suggestion = self._truncate_if_needed(suggestion) + try: if get_settings().pr_code_suggestions.summarize: - one_sentence_summary_list.append(suggestion['one_sentence_summary']) - suggestion_list.append(suggestion) - else: - get_logger().debug( - f"Skipping suggestion {i + 1}, because existing code is equal to improved code {suggestion['existing_code']}") + if not suggestion or 'one_sentence_summary' not in suggestion or 'label' not in suggestion or 'relevant_file' not in suggestion: + get_logger().debug(f"Skipping suggestion {i + 1}, because it is invalid: {suggestion}") + continue + + if suggestion['one_sentence_summary'] in one_sentence_summary_list: + get_logger().debug(f"Skipping suggestion {i + 1}, because it is a duplicate: {suggestion}") + continue + + if 'const' in suggestion['suggestion_content'] and 'instead' in suggestion['suggestion_content'] and 'let' in suggestion['suggestion_content']: + get_logger().debug(f"Skipping suggestion {i + 1}, because it uses 'const instead let': {suggestion}") + continue + + if ('existing_code' in suggestion) and ('improved_code' in suggestion) and ( + suggestion['existing_code'] != suggestion['improved_code']): + suggestion = self._truncate_if_needed(suggestion) + if get_settings().pr_code_suggestions.summarize: + one_sentence_summary_list.append(suggestion['one_sentence_summary']) + suggestion_list.append(suggestion) + else: + get_logger().debug( + f"Skipping suggestion {i + 1}, because existing code is equal to improved code {suggestion['existing_code']}") + except Exception as e: + get_logger().error(f"Error processing suggestion {i + 1}: {suggestion}, error: {e}") data['code_suggestions'] = suggestion_list return data From 68f29a41eff80a109ab971101267b33835ec3e04 Mon Sep 17 00:00:00 2001 From: mrT23 Date: Sun, 7 Apr 2024 11:52:42 +0300 Subject: [PATCH 091/226] readme --- docs/docs/usage-guide/mail_notifications.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/usage-guide/mail_notifications.md b/docs/docs/usage-guide/mail_notifications.md index 1d6f6dcb..f25c7eaa 100644 --- a/docs/docs/usage-guide/mail_notifications.md +++ b/docs/docs/usage-guide/mail_notifications.md @@ -10,7 +10,7 @@ As an alternative, you can filter in your mail provider the notifications specif Another option to reduce the mail overload, yet still receive notifications on PR-Agent tools, is to disable the help collapsible section in PR-Agent bot comments. -This can done by setting `enable_help_text=false` configuration to the relevant tool in the configuration file. +This can done by setting `enable_help_text=false` for the relevant tool in the configuration file. For example, to disable the help text for the `pr_reviewer` tool, set: ``` [pr_reviewer] From dc14b876578765c2da32eaf026771df5330e02a8 Mon Sep 17 00:00:00 2001 From: Charles Uneze Date: Sun, 7 Apr 2024 10:06:05 +0100 Subject: [PATCH 092/226] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index de3f51e5..1ac8b7da 100644 --- a/README.md +++ b/README.md @@ -135,7 +135,7 @@ ___ \ โ€ฃ **CI Feedback ๐Ÿ’Ž ([`/checks ci_job`](https://pr-agent-docs.codium.ai/tools/ci_feedback/))**: Automatically generates feedback and analysis for a failed CI job. \ -โ€ฃ **Similar Code ๐Ÿ’Ž ([`/find_similar_component`](https://pr-agent-docs.codium.ai/tools/similar_code//))**: Retrieves the most similar code components from inside the organization's codebase, or from open-source code. +โ€ฃ **Similar Code ๐Ÿ’Ž ([`/find_similar_component`](https://pr-agent-docs.codium.ai/tools/similar_code/))**: Retrieves the most similar code components from inside the organization's codebase, or from open-source code. ___ ## Example results From aa2121a48def2f05e2e85e373063259999b1955b Mon Sep 17 00:00:00 2001 From: mrT23 Date: Sun, 7 Apr 2024 16:28:30 +0300 Subject: [PATCH 093/226] readme --- docs/docs/tools/improve.md | 2 +- docs/docs/tools/review.md | 4 ++-- docs/docs/usage-guide/configuration_options.md | 2 +- pr_agent/servers/help.py | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/docs/tools/improve.md b/docs/docs/tools/improve.md index 40945775..b62fd649 100644 --- a/docs/docs/tools/improve.md +++ b/docs/docs/tools/improve.md @@ -72,7 +72,7 @@ To edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agen Examples for extra instructions: ``` [pr_code_suggestions] # /improve # - extra_instructions=""" + extra_instructions="""\ Emphasize the following aspects: - Does the code logic cover relevant edge cases? - Is the code logic clear and easy to understand? diff --git a/docs/docs/tools/review.md b/docs/docs/tools/review.md index 41ef75ed..c5681bb4 100644 --- a/docs/docs/tools/review.md +++ b/docs/docs/tools/review.md @@ -124,8 +124,8 @@ The tool will first ask the author questions about the PR, and will guide the re Examples for extra instructions: ``` - [pr_reviewer] # /review # - extra_instructions=""" + [pr_reviewer] + extra_instructions="""\ In the code feedback section, emphasize the following: - Does the code logic cover relevant edge cases? - Is the code logic clear and easy to understand? diff --git a/docs/docs/usage-guide/configuration_options.md b/docs/docs/usage-guide/configuration_options.md index 1d56baa2..ee908b76 100644 --- a/docs/docs/usage-guide/configuration_options.md +++ b/docs/docs/usage-guide/configuration_options.md @@ -22,7 +22,7 @@ Click [here](https://codium.ai/images/pr_agent/wiki_configuration_pr_agent.mp4) An example content: ``` -[pr_description] # /describe # +[pr_description] keep_original_user_title=false ``` diff --git a/pr_agent/servers/help.py b/pr_agent/servers/help.py index 364088ec..9e85887d 100644 --- a/pr_agent/servers/help.py +++ b/pr_agent/servers/help.py @@ -128,7 +128,7 @@ Be specific, clear, and concise in the instructions. With extra instructions, yo Examples for extra instructions: ``` [pr_description] -extra_instructions=""" +extra_instructions="""\ - The PR title should be in the format: ': ' - The title should be short and concise (up to 10 words) - ... From 2be0e9108e531c2d39bfdd7f05ae76e0e2c0d4c3 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sun, 7 Apr 2024 17:00:40 +0300 Subject: [PATCH 094/226] readme --- pr_agent/algo/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pr_agent/algo/utils.py b/pr_agent/algo/utils.py index b017f0aa..5a1e332d 100644 --- a/pr_agent/algo/utils.py +++ b/pr_agent/algo/utils.py @@ -575,7 +575,7 @@ def clip_tokens(text: str, max_tokens: int, add_three_dots=True) -> str: num_output_chars = int(chars_per_token * max_tokens) clipped_text = text[:num_output_chars] if add_three_dots: - clipped_text += "...(truncated)" + clipped_text += " ...(truncated)" return clipped_text except Exception as e: get_logger().warning(f"Failed to clip tokens: {e}") From a5a68c2a733d1b34f343af70c0b99aaaf1ff2022 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sun, 7 Apr 2024 17:02:37 +0300 Subject: [PATCH 095/226] readme --- tests/unittest/test_clip_tokens.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unittest/test_clip_tokens.py b/tests/unittest/test_clip_tokens.py index cc52ab7e..2405a06b 100644 --- a/tests/unittest/test_clip_tokens.py +++ b/tests/unittest/test_clip_tokens.py @@ -15,5 +15,5 @@ class TestClipTokens: max_tokens = 10 result = clip_tokens(text, max_tokens) - expected_results = 'line1\nline2\nline3\nli...(truncated)' + expected_results = 'line1\nline2\nline3\nli ...(truncated)' assert result == expected_results From 09f76f45effd7cbce4d6b36a98a03f31fb593beb Mon Sep 17 00:00:00 2001 From: Almog Lavi <42740235+almog-lv@users.noreply.github.com> Date: Mon, 8 Apr 2024 08:18:33 +0300 Subject: [PATCH 096/226] Update docs readme --- docs/README.md | 17 +---------------- 1 file changed, 1 insertion(+), 16 deletions(-) diff --git a/docs/README.md b/docs/README.md index a06f01af..42154c96 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,16 +1 @@ -# To install: -pip install mkdocs -pip install mkdocs-material -pip install mkdocs-material-extensions -pip install "mkdocs-material[imaging]" - -# docs -To run localy: `mkdocs serve` - -To expand and customize the theme: [Material MKDocs](https://squidfunk.github.io/mkdocs-material/) - -The deployment is managed on the gh-pages branches. -After each merge to main the deplloyment will be taken care of by GH action automatically and the new version will be available at: [Docs](https://codium-ai.github.io/docs/) - -Github action is located in `.github/workflows/ci.yml` file. - +# [Visit Our Docs Portal](https://pr-agent-docs.codium.ai/) From a543d7ed1adfd888969da697b61143154c746623 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Mon, 8 Apr 2024 09:12:50 +0300 Subject: [PATCH 097/226] readme --- docs/docs/index.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/docs/index.md b/docs/docs/index.md index 198bee22..80b62e11 100644 --- a/docs/docs/index.md +++ b/docs/docs/index.md @@ -46,25 +46,31 @@ PR-Agent offers extensive pull request functionalities across various git provid ## Example Results +<hr> + #### [/describe](https://github.com/Codium-ai/pr-agent/pull/530) <figure markdown="1"> ![/describe](https://www.codium.ai/images/pr_agent/describe_new_short_main.png){width=512} </figure> +<hr> #### [/review](https://github.com/Codium-ai/pr-agent/pull/732#issuecomment-1975099151) <figure markdown="1"> ![/review](https://www.codium.ai/images/pr_agent/review_new_short_main.png){width=512} </figure> +<hr> #### [/improve](https://github.com/Codium-ai/pr-agent/pull/732#issuecomment-1975099159) <figure markdown="1"> ![/improve](https://www.codium.ai/images/pr_agent/improve_new_short_main.png){width=512} </figure> +<hr> #### [/generate_labels](https://github.com/Codium-ai/pr-agent/pull/530) <figure markdown="1"> ![/generate_labels](https://www.codium.ai/images/pr_agent/geneare_custom_labels_main_short.png){width=300} </figure> +<hr> ## How it Works From 84d8f78d0c6215d3d10acfdd9c25074800ddc639 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Mon, 8 Apr 2024 14:00:41 +0300 Subject: [PATCH 098/226] publish_output --- pr_agent/algo/utils.py | 2 +- pr_agent/tools/pr_reviewer.py | 3 +++ tests/unittest/test_clip_tokens.py | 2 +- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/pr_agent/algo/utils.py b/pr_agent/algo/utils.py index 5a1e332d..4c87c038 100644 --- a/pr_agent/algo/utils.py +++ b/pr_agent/algo/utils.py @@ -575,7 +575,7 @@ def clip_tokens(text: str, max_tokens: int, add_three_dots=True) -> str: num_output_chars = int(chars_per_token * max_tokens) clipped_text = text[:num_output_chars] if add_three_dots: - clipped_text += " ...(truncated)" + clipped_text += "\n...(truncated)" return clipped_text except Exception as e: get_logger().warning(f"Failed to clip tokens: {e}") diff --git a/pr_agent/tools/pr_reviewer.py b/pr_agent/tools/pr_reviewer.py index 4d1739a5..c257c30a 100644 --- a/pr_agent/tools/pr_reviewer.py +++ b/pr_agent/tools/pr_reviewer.py @@ -357,6 +357,9 @@ class PRReviewer: return True def set_review_labels(self, data): + if not get_settings().config.publish_output: + return + if (get_settings().pr_reviewer.enable_review_labels_security or get_settings().pr_reviewer.enable_review_labels_effort): try: diff --git a/tests/unittest/test_clip_tokens.py b/tests/unittest/test_clip_tokens.py index 2405a06b..a56ff92f 100644 --- a/tests/unittest/test_clip_tokens.py +++ b/tests/unittest/test_clip_tokens.py @@ -15,5 +15,5 @@ class TestClipTokens: max_tokens = 10 result = clip_tokens(text, max_tokens) - expected_results = 'line1\nline2\nline3\nli ...(truncated)' + expected_results = 'line1\nline2\nline3\nli\n...(truncated)' assert result == expected_results From 8a5b01b4657d5522b6b4d44592f66cf3150f1836 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Mon, 8 Apr 2024 14:49:00 +0300 Subject: [PATCH 099/226] empty calc_pr_statistics --- pr_agent/git_providers/github_provider.py | 20 +------------------- 1 file changed, 1 insertion(+), 19 deletions(-) diff --git a/pr_agent/git_providers/github_provider.py b/pr_agent/git_providers/github_provider.py index de54ec3f..574e28cf 100644 --- a/pr_agent/git_providers/github_provider.py +++ b/pr_agent/git_providers/github_provider.py @@ -745,22 +745,4 @@ class GithubProvider(GitProvider): return False def calc_pr_statistics(self, pull_request_data: dict): - try: - out = {} - from datetime import datetime - created_at = pull_request_data['created_at'] - closed_at = pull_request_data['closed_at'] - closed_at_datetime = datetime.strptime(closed_at, "%Y-%m-%dT%H:%M:%SZ") - created_at_datetime = datetime.strptime(created_at, "%Y-%m-%dT%H:%M:%SZ") - difference = closed_at_datetime - created_at_datetime - out['hours'] = difference.total_seconds() / 3600 - out['commits'] = pull_request_data['commits'] - out['comments'] = pull_request_data['comments'] - out['review_comments'] = pull_request_data['review_comments'] - out['changed_files'] = pull_request_data['changed_files'] - out['additions'] = pull_request_data['additions'] - out['deletions'] = pull_request_data['deletions'] - except Exception as e: - get_logger().exception(f"Failed to calculate PR statistics, error: {e}") - return {} - return out + return {} From 0257b619ff6507729ea2345a753ec9ac10716efb Mon Sep 17 00:00:00 2001 From: phuongvietnamlab <phuongpv@vietnamlab.vn> Date: Tue, 9 Apr 2024 15:47:54 +0700 Subject: [PATCH 100/226] Failed to review PR: name 'is_valid_file' is not defined --- pr_agent/git_providers/codecommit_provider.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pr_agent/git_providers/codecommit_provider.py b/pr_agent/git_providers/codecommit_provider.py index f035351d..41de6bb3 100644 --- a/pr_agent/git_providers/codecommit_provider.py +++ b/pr_agent/git_providers/codecommit_provider.py @@ -10,7 +10,7 @@ from ..algo.utils import load_large_diff from .git_provider import GitProvider from ..config_loader import get_settings from ..log import get_logger - +from pr_agent.algo.language_handler import is_valid_file class PullRequestCCMimic: """ From 75c4befadf901d6e214aacf779ed904505566028 Mon Sep 17 00:00:00 2001 From: idubnori <i.dub.nori@gmail.com> Date: Tue, 9 Apr 2024 22:51:02 +0900 Subject: [PATCH 101/226] feat: set review data to github actions output --- pr_agent/algo/utils.py | 10 ++++++++ pr_agent/servers/github_action_runner.py | 2 ++ pr_agent/settings/configuration.toml | 1 + pr_agent/tools/pr_reviewer.py | 3 ++- tests/unittest/test_github_output.py | 31 ++++++++++++++++++++++++ 5 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 tests/unittest/test_github_output.py diff --git a/pr_agent/algo/utils.py b/pr_agent/algo/utils.py index c2b6323c..8d3c9c01 100644 --- a/pr_agent/algo/utils.py +++ b/pr_agent/algo/utils.py @@ -2,6 +2,7 @@ from __future__ import annotations import difflib import json +import os import re import textwrap from datetime import datetime @@ -661,3 +662,12 @@ def find_line_number_of_relevant_line_in_file(diff_files: List[FilePatchInfo], absolute_position = start2 + delta - 1 break return position, absolute_position + +def github_output(output_data: dict, key_name: str): + if get_settings().github_action_config.enable_output is False: + return + + output = os.getenv('GITHUB_OUTPUT') + key_data = output_data.get(key_name, {}) + with open(output, 'w') as f: + f.write(f"{key_name}={json.dumps(key_data, indent=None, ensure_ascii=False)}") diff --git a/pr_agent/servers/github_action_runner.py b/pr_agent/servers/github_action_runner.py index d4278156..6f9b6275 100644 --- a/pr_agent/servers/github_action_runner.py +++ b/pr_agent/servers/github_action_runner.py @@ -59,6 +59,8 @@ async def run_action(): get_settings().set("OPENAI.ORG", OPENAI_ORG) get_settings().set("GITHUB.USER_TOKEN", GITHUB_TOKEN) get_settings().set("GITHUB.DEPLOYMENT_TYPE", "user") + enable_output = get_setting_or_env("GITHUB_ACTION_CONFIG.ENABLE_OUTPUT", False) + get_settings().set("GITHUB_ACTION_CONFIG.ENABLE_OUTPUT", enable_output) # Load the event payload try: diff --git a/pr_agent/settings/configuration.toml b/pr_agent/settings/configuration.toml index 837c71d3..0f43ccd8 100644 --- a/pr_agent/settings/configuration.toml +++ b/pr_agent/settings/configuration.toml @@ -133,6 +133,7 @@ try_fix_invalid_inline_comments = true # auto_review = true # set as env var in .github/workflows/pr-agent.yaml # auto_describe = true # set as env var in .github/workflows/pr-agent.yaml # auto_improve = true # set as env var in .github/workflows/pr-agent.yaml +# enable_output = true # set as env var in .github/workflows/pr-agent.yaml [github_app] # these toggles allows running the github app from custom deployments diff --git a/pr_agent/tools/pr_reviewer.py b/pr_agent/tools/pr_reviewer.py index 4d1739a5..38c2ef5c 100644 --- a/pr_agent/tools/pr_reviewer.py +++ b/pr_agent/tools/pr_reviewer.py @@ -8,7 +8,7 @@ from pr_agent.algo.ai_handlers.base_ai_handler import BaseAiHandler from pr_agent.algo.ai_handlers.litellm_ai_handler import LiteLLMAIHandler from pr_agent.algo.pr_processing import get_pr_diff, retry_with_fallback_models from pr_agent.algo.token_handler import TokenHandler -from pr_agent.algo.utils import convert_to_markdown, load_yaml, ModelType +from pr_agent.algo.utils import convert_to_markdown, github_output, load_yaml, ModelType from pr_agent.config_loader import get_settings from pr_agent.git_providers import get_git_provider from pr_agent.git_providers.git_provider import IncrementalPR, get_main_pr_language @@ -192,6 +192,7 @@ class PRReviewer: data = load_yaml(self.prediction.strip(), keys_fix_yaml=["estimated_effort_to_review_[1-5]:", "security_concerns:", "possible_issues:", "relevant_file:", "relevant_line:", "suggestion:"]) + github_output(data, 'review') if 'code_feedback' in data: code_feedback = data['code_feedback'] diff --git a/tests/unittest/test_github_output.py b/tests/unittest/test_github_output.py new file mode 100644 index 00000000..2ac3d2c7 --- /dev/null +++ b/tests/unittest/test_github_output.py @@ -0,0 +1,31 @@ +import os +import json +from pr_agent.algo.utils import get_settings, github_output + +class TestGitHubOutput: + def test_github_output_enabled(self, monkeypatch, tmp_path): + get_settings().set('GITHUB_ACTION_CONFIG.ENABLE_OUTPUT', True) + monkeypatch.setenv('GITHUB_OUTPUT', str(tmp_path / 'output')) + output_data = {'key1': {'value1': 1, 'value2': 2}} + key_name = 'key1' + + github_output(output_data, key_name) + + with open(str(tmp_path / 'output'), 'r') as f: + env_value = f.read() + + actual_key = env_value.split('=')[0] + actual_data = json.loads(env_value.split('=')[1]) + + assert actual_key == key_name + assert actual_data == output_data[key_name] + + def test_github_output_disabled(self, monkeypatch, tmp_path): + get_settings().set('GITHUB_ACTION_CONFIG.ENABLE_OUTPUT', False) + monkeypatch.setenv('GITHUB_OUTPUT', str(tmp_path / 'output')) + output_data = {'key1': {'value1': 1, 'value2': 2}} + key_name = 'key1' + + github_output(output_data, key_name) + + assert not os.path.exists(str(tmp_path / 'output')) \ No newline at end of file From 45176ab8932a07ba32cb226f340301a1003dc4fa Mon Sep 17 00:00:00 2001 From: idubnori <i.dub.nori@gmail.com> Date: Wed, 10 Apr 2024 09:17:29 +0900 Subject: [PATCH 102/226] test: add config not set case --- tests/unittest/test_github_output.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tests/unittest/test_github_output.py b/tests/unittest/test_github_output.py index 2ac3d2c7..a046ec7d 100644 --- a/tests/unittest/test_github_output.py +++ b/tests/unittest/test_github_output.py @@ -28,4 +28,13 @@ class TestGitHubOutput: github_output(output_data, key_name) + assert not os.path.exists(str(tmp_path / 'output')) + + def test_github_output_notset(self, monkeypatch, tmp_path): + monkeypatch.setenv('GITHUB_OUTPUT', str(tmp_path / 'output')) + output_data = {'key1': {'value1': 1, 'value2': 2}} + key_name = 'key1' + + github_output(output_data, key_name) + assert not os.path.exists(str(tmp_path / 'output')) \ No newline at end of file From 3412095d81844f97abc6146603ceea1d584ea279 Mon Sep 17 00:00:00 2001 From: idubnori <i.dub.nori@gmail.com> Date: Wed, 10 Apr 2024 09:18:21 +0900 Subject: [PATCH 103/226] chore: change default to true, if use in github actions --- pr_agent/servers/github_action_runner.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pr_agent/servers/github_action_runner.py b/pr_agent/servers/github_action_runner.py index 6f9b6275..ad16958e 100644 --- a/pr_agent/servers/github_action_runner.py +++ b/pr_agent/servers/github_action_runner.py @@ -59,7 +59,7 @@ async def run_action(): get_settings().set("OPENAI.ORG", OPENAI_ORG) get_settings().set("GITHUB.USER_TOKEN", GITHUB_TOKEN) get_settings().set("GITHUB.DEPLOYMENT_TYPE", "user") - enable_output = get_setting_or_env("GITHUB_ACTION_CONFIG.ENABLE_OUTPUT", False) + enable_output = get_setting_or_env("GITHUB_ACTION_CONFIG.ENABLE_OUTPUT", True) get_settings().set("GITHUB_ACTION_CONFIG.ENABLE_OUTPUT", enable_output) # Load the event payload From 108b1afa0ee8d853517a10e75ea4aef63f8db2bd Mon Sep 17 00:00:00 2001 From: Yuta Nishi <riyaamemiya@gmail.com> Date: Wed, 10 Apr 2024 14:44:38 +0900 Subject: [PATCH 104/226] add new models --- pr_agent/algo/__init__.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pr_agent/algo/__init__.py b/pr_agent/algo/__init__.py index 19968be5..1357db29 100644 --- a/pr_agent/algo/__init__.py +++ b/pr_agent/algo/__init__.py @@ -11,6 +11,8 @@ MAX_TOKENS = { 'gpt-4-1106-preview': 128000, # 128K, but may be limited by config.max_model_tokens 'gpt-4-0125-preview': 128000, # 128K, but may be limited by config.max_model_tokens 'gpt-4-turbo-preview': 128000, # 128K, but may be limited by config.max_model_tokens + 'gpt-4-turbo-2024-04-09': 128000, # 128K, but may be limited by config.max_model_tokens + 'gpt-4-turbo': 128000, # 128K, but may be limited by config.max_model_tokens 'claude-instant-1': 100000, 'claude-2': 100000, 'command-nightly': 4096, From 97dcb34d771f0b8bb50e7d953cb23eb81487c761 Mon Sep 17 00:00:00 2001 From: idubnori <i.dub.nori@gmail.com> Date: Wed, 10 Apr 2024 22:16:09 +0900 Subject: [PATCH 105/226] clean: rename to github_action_output --- pr_agent/algo/utils.py | 2 +- pr_agent/tools/pr_reviewer.py | 4 ++-- tests/unittest/test_github_output.py | 14 +++++++------- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/pr_agent/algo/utils.py b/pr_agent/algo/utils.py index 8d3c9c01..c719c240 100644 --- a/pr_agent/algo/utils.py +++ b/pr_agent/algo/utils.py @@ -663,7 +663,7 @@ def find_line_number_of_relevant_line_in_file(diff_files: List[FilePatchInfo], break return position, absolute_position -def github_output(output_data: dict, key_name: str): +def github_action_output(output_data: dict, key_name: str): if get_settings().github_action_config.enable_output is False: return diff --git a/pr_agent/tools/pr_reviewer.py b/pr_agent/tools/pr_reviewer.py index 38c2ef5c..53f7b0c0 100644 --- a/pr_agent/tools/pr_reviewer.py +++ b/pr_agent/tools/pr_reviewer.py @@ -8,7 +8,7 @@ from pr_agent.algo.ai_handlers.base_ai_handler import BaseAiHandler from pr_agent.algo.ai_handlers.litellm_ai_handler import LiteLLMAIHandler from pr_agent.algo.pr_processing import get_pr_diff, retry_with_fallback_models from pr_agent.algo.token_handler import TokenHandler -from pr_agent.algo.utils import convert_to_markdown, github_output, load_yaml, ModelType +from pr_agent.algo.utils import convert_to_markdown, github_action_output, load_yaml, ModelType from pr_agent.config_loader import get_settings from pr_agent.git_providers import get_git_provider from pr_agent.git_providers.git_provider import IncrementalPR, get_main_pr_language @@ -192,7 +192,7 @@ class PRReviewer: data = load_yaml(self.prediction.strip(), keys_fix_yaml=["estimated_effort_to_review_[1-5]:", "security_concerns:", "possible_issues:", "relevant_file:", "relevant_line:", "suggestion:"]) - github_output(data, 'review') + github_action_output(data, 'review') if 'code_feedback' in data: code_feedback = data['code_feedback'] diff --git a/tests/unittest/test_github_output.py b/tests/unittest/test_github_output.py index a046ec7d..10a2a02e 100644 --- a/tests/unittest/test_github_output.py +++ b/tests/unittest/test_github_output.py @@ -1,15 +1,15 @@ import os import json -from pr_agent.algo.utils import get_settings, github_output +from pr_agent.algo.utils import get_settings, github_action_output class TestGitHubOutput: - def test_github_output_enabled(self, monkeypatch, tmp_path): + def test_github_action_output_enabled(self, monkeypatch, tmp_path): get_settings().set('GITHUB_ACTION_CONFIG.ENABLE_OUTPUT', True) monkeypatch.setenv('GITHUB_OUTPUT', str(tmp_path / 'output')) output_data = {'key1': {'value1': 1, 'value2': 2}} key_name = 'key1' - github_output(output_data, key_name) + github_action_output(output_data, key_name) with open(str(tmp_path / 'output'), 'r') as f: env_value = f.read() @@ -20,21 +20,21 @@ class TestGitHubOutput: assert actual_key == key_name assert actual_data == output_data[key_name] - def test_github_output_disabled(self, monkeypatch, tmp_path): + def test_github_action_output_disabled(self, monkeypatch, tmp_path): get_settings().set('GITHUB_ACTION_CONFIG.ENABLE_OUTPUT', False) monkeypatch.setenv('GITHUB_OUTPUT', str(tmp_path / 'output')) output_data = {'key1': {'value1': 1, 'value2': 2}} key_name = 'key1' - github_output(output_data, key_name) + github_action_output(output_data, key_name) assert not os.path.exists(str(tmp_path / 'output')) - def test_github_output_notset(self, monkeypatch, tmp_path): + def test_github_action_output_notset(self, monkeypatch, tmp_path): monkeypatch.setenv('GITHUB_OUTPUT', str(tmp_path / 'output')) output_data = {'key1': {'value1': 1, 'value2': 2}} key_name = 'key1' - github_output(output_data, key_name) + github_action_output(output_data, key_name) assert not os.path.exists(str(tmp_path / 'output')) \ No newline at end of file From ae633b3cea456c9a6d155e9311b05b494249683f Mon Sep 17 00:00:00 2001 From: idubnori <i.dub.nori@gmail.com> Date: Wed, 10 Apr 2024 22:30:16 +0900 Subject: [PATCH 106/226] refine: github_action_output --- pr_agent/algo/utils.py | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/pr_agent/algo/utils.py b/pr_agent/algo/utils.py index c719c240..a1aaf50a 100644 --- a/pr_agent/algo/utils.py +++ b/pr_agent/algo/utils.py @@ -664,10 +664,13 @@ def find_line_number_of_relevant_line_in_file(diff_files: List[FilePatchInfo], return position, absolute_position def github_action_output(output_data: dict, key_name: str): - if get_settings().github_action_config.enable_output is False: - return - - output = os.getenv('GITHUB_OUTPUT') - key_data = output_data.get(key_name, {}) - with open(output, 'w') as f: - f.write(f"{key_name}={json.dumps(key_data, indent=None, ensure_ascii=False)}") + try: + if not get_settings().get('github_action_config.enable_output', False): + return + + key_data = output_data.get(key_name, {}) + with open(os.environ['GITHUB_OUTPUT'], 'a') as fh: + print(f"{key_name}={json.dumps(key_data, indent=None, ensure_ascii=False)}", file=fh) + except Exception as e: + get_logger().error(f"Failed to write to GitHub Action output: {e}") + return \ No newline at end of file From 5e5ead98dea6598459833d750b9ca76829b1f447 Mon Sep 17 00:00:00 2001 From: idubnori <i.dub.nori@gmail.com> Date: Wed, 10 Apr 2024 22:36:15 +0900 Subject: [PATCH 107/226] test: rename & add error case --- ...t_github_output.py => test_github_action_output.py} | 10 ++++++++++ 1 file changed, 10 insertions(+) rename tests/unittest/{test_github_output.py => test_github_action_output.py} (77%) diff --git a/tests/unittest/test_github_output.py b/tests/unittest/test_github_action_output.py similarity index 77% rename from tests/unittest/test_github_output.py rename to tests/unittest/test_github_action_output.py index 10a2a02e..2b8e0db1 100644 --- a/tests/unittest/test_github_output.py +++ b/tests/unittest/test_github_action_output.py @@ -31,10 +31,20 @@ class TestGitHubOutput: assert not os.path.exists(str(tmp_path / 'output')) def test_github_action_output_notset(self, monkeypatch, tmp_path): + # not set config monkeypatch.setenv('GITHUB_OUTPUT', str(tmp_path / 'output')) output_data = {'key1': {'value1': 1, 'value2': 2}} key_name = 'key1' github_action_output(output_data, key_name) + assert not os.path.exists(str(tmp_path / 'output')) + + def test_github_action_output_error_case(self, monkeypatch, tmp_path): + monkeypatch.setenv('GITHUB_OUTPUT', str(tmp_path / 'output')) + output_data = None # invalid data + key_name = 'key1' + + github_action_output(output_data, key_name) + assert not os.path.exists(str(tmp_path / 'output')) \ No newline at end of file From aef1c6ecde14c367662e6bce34b1d489fa567847 Mon Sep 17 00:00:00 2001 From: idubnori <i.dub.nori@gmail.com> Date: Wed, 10 Apr 2024 23:04:29 +0900 Subject: [PATCH 108/226] docs: add feature spec and config --- docs/docs/usage-guide/automations_and_usage.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/docs/usage-guide/automations_and_usage.md b/docs/docs/usage-guide/automations_and_usage.md index d20516fd..15b52402 100644 --- a/docs/docs/usage-guide/automations_and_usage.md +++ b/docs/docs/usage-guide/automations_and_usage.md @@ -115,10 +115,15 @@ Specifically, start by setting the following environment variables: github_action_config.auto_review: "true" # enable\disable auto review github_action_config.auto_describe: "true" # enable\disable auto describe github_action_config.auto_improve: "true" # enable\disable auto improve + github_action_config.enable_output: "true" # enable\disable github actions output parameter ``` `github_action_config.auto_review`, `github_action_config.auto_describe` and `github_action_config.auto_improve` are used to enable/disable automatic tools that run when a new PR is opened. If not set, the default configuration is for all three tools to run automatically when a new PR is opened. +`github_action_config.enable_output` are used to enable/disable github actions [output parameter](https://docs.github.com/en/actions/creating-actions/metadata-syntax-for-github-actions#outputs-for-docker-container-and-javascript-actions) (default is `true`). +Review result is output as JSON to `steps.{step-id}.outputs.review` property. +The JSON structure is equivalent to the yaml data structure defined in [pr_reviewer_prompts.toml](https://github.com/idubnori/pr-agent/blob/main/pr_agent/settings/pr_reviewer_prompts.toml). + Note that you can give additional config parameters by adding environment variables to `.github/workflows/pr_agent.yml`, or by using a `.pr_agent.toml` file in the root of your repo, similar to the GitHub App usage. For example, you can set an environment variable: `pr_description.add_original_user_description=false`, or add a `.pr_agent.toml` file with the following content: From 4c83bf695d4fc1e3f5a14a4002c7e70e55f314ae Mon Sep 17 00:00:00 2001 From: Pavel Kvach <pavel.kvach@gmail.com> Date: Fri, 12 Apr 2024 10:50:00 +0300 Subject: [PATCH 109/226] Handle OPENAI_KEY not set error in github_action_runner.py Fixes https://github.com/Codium-ai/pr-agent/issues/855 --- pr_agent/servers/github_action_runner.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/pr_agent/servers/github_action_runner.py b/pr_agent/servers/github_action_runner.py index 53b54a29..1aafcaae 100644 --- a/pr_agent/servers/github_action_runner.py +++ b/pr_agent/servers/github_action_runner.py @@ -46,15 +46,16 @@ async def run_action(): if not GITHUB_EVENT_PATH: print("GITHUB_EVENT_PATH not set") return - if not OPENAI_KEY: - print("OPENAI_KEY not set") - return if not GITHUB_TOKEN: print("GITHUB_TOKEN not set") return # Set the environment variables in the settings - get_settings().set("OPENAI.KEY", OPENAI_KEY) + if OPENAI_KEY: + get_settings().set("OPENAI.KEY", OPENAI_KEY) + else: + # Might not be set if the user is using models not from OpenAI + print("OPENAI_KEY not set") if OPENAI_ORG: get_settings().set("OPENAI.ORG", OPENAI_ORG) get_settings().set("GITHUB.USER_TOKEN", GITHUB_TOKEN) From a4680ded939401c60e61ab8192da989ad283ad8a Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Fri, 12 Apr 2024 20:32:47 +0300 Subject: [PATCH 110/226] protections --- pr_agent/agent/pr_agent.py | 3 ++ pr_agent/algo/pr_processing.py | 62 +++++++++++++++++++++------------- 2 files changed, 42 insertions(+), 23 deletions(-) diff --git a/pr_agent/agent/pr_agent.py b/pr_agent/agent/pr_agent.py index 5be0f779..d2542cf2 100644 --- a/pr_agent/agent/pr_agent.py +++ b/pr_agent/agent/pr_agent.py @@ -73,6 +73,9 @@ class PRAgent: args = update_settings_from_args(args) action = action.lstrip("/").lower() + if action not in command2class: + get_logger().debug(f"Unknown command: {action}") + return False with get_logger().contextualize(command=action): get_logger().info("PR-Agent request handler started", analytics=True) if action == "reflect_and_review": diff --git a/pr_agent/algo/pr_processing.py b/pr_agent/algo/pr_processing.py index 90482a02..2c5a2957 100644 --- a/pr_agent/algo/pr_processing.py +++ b/pr_agent/algo/pr_processing.py @@ -9,7 +9,7 @@ from pr_agent.algo.git_patch_processing import convert_to_hunks_with_lines_numbe from pr_agent.algo.language_handler import sort_files_by_main_languages from pr_agent.algo.file_filter import filter_ignored from pr_agent.algo.token_handler import TokenHandler -from pr_agent.algo.utils import get_max_tokens, ModelType +from pr_agent.algo.utils import get_max_tokens, clip_tokens, ModelType from pr_agent.config_loader import get_settings from pr_agent.git_providers.git_provider import GitProvider from pr_agent.algo.types import EDIT_TYPE, FilePatchInfo @@ -87,22 +87,34 @@ def get_pr_diff(git_provider: GitProvider, token_handler: TokenHandler, model: s # if we are over the limit, start pruning get_logger().info(f"Tokens: {total_tokens}, total tokens over limit: {get_max_tokens(model)}, " f"pruning diff.") - patches_compressed, modified_file_names, deleted_file_names, added_file_names = \ + patches_compressed, modified_file_names, deleted_file_names, added_file_names, total_tokens_new = \ pr_generate_compressed_diff(pr_languages, token_handler, model, add_line_numbers_to_hunks) + # Insert additional information about added, modified, and deleted files if there is enough space + max_tokens = get_max_tokens(model) - OUTPUT_BUFFER_TOKENS_HARD_THRESHOLD + curr_token = total_tokens_new # == token_handler.count_tokens(final_diff)+token_handler.prompt_tokens final_diff = "\n".join(patches_compressed) - if added_file_names: + delta_tokens = 10 + if added_file_names and (max_tokens - curr_token) > delta_tokens: added_list_str = ADDED_FILES_ + "\n".join(added_file_names) - final_diff = final_diff + "\n\n" + added_list_str - if modified_file_names: + added_list_str = clip_tokens(added_list_str, max_tokens - curr_token) + if added_list_str: + final_diff = final_diff + "\n\n" + added_list_str + curr_token += token_handler.count_tokens(added_list_str) + 2 + if modified_file_names and (max_tokens - curr_token) > delta_tokens: modified_list_str = MORE_MODIFIED_FILES_ + "\n".join(modified_file_names) - final_diff = final_diff + "\n\n" + modified_list_str - if deleted_file_names: + modified_list_str = clip_tokens(modified_list_str, max_tokens - curr_token) + if modified_list_str: + final_diff = final_diff + "\n\n" + modified_list_str + curr_token += token_handler.count_tokens(modified_list_str) + 2 + if deleted_file_names and (max_tokens - curr_token) > delta_tokens: deleted_list_str = DELETED_FILES_ + "\n".join(deleted_file_names) - final_diff = final_diff + "\n\n" + deleted_list_str + deleted_list_str = clip_tokens(deleted_list_str, max_tokens - curr_token) + if deleted_list_str: + final_diff = final_diff + "\n\n" + deleted_list_str try: get_logger().debug(f"After pruning, added_list_str: {added_list_str}, modified_list_str: {modified_list_str}, " - f"deleted_list_str: {deleted_list_str}") + f"deleted_list_str: {deleted_list_str}") except Exception as e: pass return final_diff @@ -149,7 +161,7 @@ def pr_generate_extended_diff(pr_languages: list, def pr_generate_compressed_diff(top_langs: list, token_handler: TokenHandler, model: str, - convert_hunks_to_line_numbers: bool) -> Tuple[list, list, list, list]: + convert_hunks_to_line_numbers: bool) -> Tuple[list, list, list, list, int]: """ Generate a compressed diff string for a pull request, using diff minimization techniques to reduce the number of tokens used. @@ -195,10 +207,11 @@ def pr_generate_compressed_diff(top_langs: list, token_handler: TokenHandler, mo patch = handle_patch_deletions(patch, original_file_content_str, new_file_content_str, file.filename, file.edit_type) if patch is None: - if not deleted_files_list: - total_tokens += token_handler.count_tokens(DELETED_FILES_) - deleted_files_list.append(file.filename) - total_tokens += token_handler.count_tokens(file.filename) + 1 + # if not deleted_files_list: + # total_tokens += token_handler.count_tokens(DELETED_FILES_) + if file.filename not in deleted_files_list: + deleted_files_list.append(file.filename) + # total_tokens += token_handler.count_tokens(file.filename) + 1 continue if convert_hunks_to_line_numbers: @@ -219,14 +232,17 @@ def pr_generate_compressed_diff(top_langs: list, token_handler: TokenHandler, mo if get_settings().config.verbosity_level >= 2: get_logger().warning(f"Patch too large, minimizing it, {file.filename}") if file.edit_type == EDIT_TYPE.ADDED: - if not added_files_list: - total_tokens += token_handler.count_tokens(ADDED_FILES_) - added_files_list.append(file.filename) + # if not added_files_list: + # total_tokens += token_handler.count_tokens(ADDED_FILES_) + if file.filename not in added_files_list: + added_files_list.append(file.filename) + # total_tokens += token_handler.count_tokens(file.filename) + 1 else: - if not modified_files_list: - total_tokens += token_handler.count_tokens(MORE_MODIFIED_FILES_) - modified_files_list.append(file.filename) - total_tokens += token_handler.count_tokens(file.filename) + 1 + # if not modified_files_list: + # total_tokens += token_handler.count_tokens(MORE_MODIFIED_FILES_) + if file.filename not in modified_files_list: + modified_files_list.append(file.filename) + # total_tokens += token_handler.count_tokens(file.filename) + 1 continue if patch: @@ -239,7 +255,7 @@ def pr_generate_compressed_diff(top_langs: list, token_handler: TokenHandler, mo if get_settings().config.verbosity_level >= 2: get_logger().info(f"Tokens: {total_tokens}, last filename: {file.filename}") - return patches, modified_files_list, deleted_files_list, added_files_list + return patches, modified_files_list, deleted_files_list, added_files_list, total_tokens async def retry_with_fallback_models(f: Callable, model_type: ModelType = ModelType.REGULAR): @@ -382,4 +398,4 @@ def get_pr_multi_diffs(git_provider: GitProvider, final_diff = "\n".join(patches) final_diff_list.append(final_diff) - return final_diff_list + return final_diff_list \ No newline at end of file From 8f0f08006f405bfab3cf8f8f353e4a216ffc5426 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sun, 14 Apr 2024 12:00:19 +0300 Subject: [PATCH 111/226] s --- pr_agent/algo/ai_handlers/base_ai_handler.py | 2 +- .../algo/ai_handlers/litellm_ai_handler.py | 12 +++++++- pr_agent/servers/github_app.py | 9 ++++-- pr_agent/settings/configuration.toml | 6 ++-- pr_agent/tools/pr_questions.py | 29 +++++++++++++++++-- 5 files changed, 49 insertions(+), 9 deletions(-) diff --git a/pr_agent/algo/ai_handlers/base_ai_handler.py b/pr_agent/algo/ai_handlers/base_ai_handler.py index c8473fb3..b5166b8e 100644 --- a/pr_agent/algo/ai_handlers/base_ai_handler.py +++ b/pr_agent/algo/ai_handlers/base_ai_handler.py @@ -15,7 +15,7 @@ class BaseAiHandler(ABC): pass @abstractmethod - async def chat_completion(self, model: str, system: str, user: str, temperature: float = 0.2): + async def chat_completion(self, model: str, system: str, user: str, temperature: float = 0.2, img_path: str = None): """ This method should be implemented to return a chat completion from the AI model. Args: diff --git a/pr_agent/algo/ai_handlers/litellm_ai_handler.py b/pr_agent/algo/ai_handlers/litellm_ai_handler.py index d07542f6..536faf41 100644 --- a/pr_agent/algo/ai_handlers/litellm_ai_handler.py +++ b/pr_agent/algo/ai_handlers/litellm_ai_handler.py @@ -102,13 +102,23 @@ class LiteLLMAIHandler(BaseAiHandler): retry=retry_if_exception_type((openai.APIError, openai.APIConnectionError, openai.Timeout)), # No retry on RateLimitError stop=stop_after_attempt(OPENAI_RETRIES) ) - async def chat_completion(self, model: str, system: str, user: str, temperature: float = 0.2): + async def chat_completion(self, model: str, system: str, user: str, temperature: float = 0.2, img_path: str = None): try: resp, finish_reason = None, None deployment_id = self.deployment_id if self.azure: model = 'azure/' + model messages = [{"role": "system", "content": system}, {"role": "user", "content": user}] + if img_path: + import requests + r = requests.get(img_path, allow_redirects=True) + if r.status_code == 404: + error_msg = "The image link is not alive. Please repost the image, get a new address, and send the question again." + get_logger().error(error_msg) + return f"{error_msg}", "error" + messages[1]["content"] = [{"type": "text", "text": messages[1]["content"]}, + {"type": "image_url", "image_url": {"url": img_path}}] + kwargs = { "model": model, "deployment_id": deployment_id, diff --git a/pr_agent/servers/github_app.py b/pr_agent/servers/github_app.py index bc7042b1..6d942289 100644 --- a/pr_agent/servers/github_app.py +++ b/pr_agent/servers/github_app.py @@ -86,8 +86,13 @@ async def handle_comments_on_pr(body: Dict[str, Any], return {} comment_body = body.get("comment", {}).get("body") if comment_body and isinstance(comment_body, str) and not comment_body.lstrip().startswith("/"): - get_logger().info("Ignoring comment not starting with /") - return {} + if '/ask' in comment_body and comment_body.strip().startswith('> ![image]'): + comment_body_split = comment_body.split('/ask') + comment_body = '/ask' + comment_body_split[1] +'/n' +comment_body_split[0].strip() + get_logger().info(f"Reformatting comment_body so command is at the beginning: {comment_body}") + else: + get_logger().info("Ignoring comment not starting with /") + return {} disable_eyes = False if "issue" in body and "pull_request" in body["issue"] and "url" in body["issue"]["pull_request"]: api_url = body["issue"]["pull_request"]["url"] diff --git a/pr_agent/settings/configuration.toml b/pr_agent/settings/configuration.toml index 39282706..d49b345c 100644 --- a/pr_agent/settings/configuration.toml +++ b/pr_agent/settings/configuration.toml @@ -1,7 +1,7 @@ [config] -model="gpt-4" # "gpt-4-0125-preview" -model_turbo="gpt-4-0125-preview" -fallback_models=["gpt-3.5-turbo-16k"] +model="gpt-4-turbo" # "gpt-4-0125-preview" +model_turbo="gpt-4-turbo" +fallback_models=["gpt-4-0125-preview"] git_provider="github" publish_output=true publish_output_progress=true diff --git a/pr_agent/tools/pr_questions.py b/pr_agent/tools/pr_questions.py index 4e1d3c1e..1e2a360e 100644 --- a/pr_agent/tools/pr_questions.py +++ b/pr_agent/tools/pr_questions.py @@ -56,6 +56,12 @@ class PRQuestions: get_logger().debug("Relevant configs", artifacts=relevant_configs) if get_settings().config.publish_output: self.git_provider.publish_comment("Preparing answer...", is_temporary=True) + + # identify image + img_path = self.idenfity_image_in_comment() + if img_path: + get_logger().debug(f"Image path identified", artifact=img_path) + await retry_with_fallback_models(self._prepare_prediction) pr_comment = self._prepare_pr_answer() @@ -71,6 +77,19 @@ class PRQuestions: self.git_provider.remove_initial_comment() return "" + def idenfity_image_in_comment(self): + img_path = '' + if '![image]' in self.question_str: + # assuming structure: + # /ask question ... > ![image](img_path) + img_path = self.question_str.split('![image]')[1].strip().strip('()') + self.vars['img_path'] = img_path + elif 'https://' in self.question_str and '.png' in self.question_str: # direct image link + # include https:// in the image path + img_path = 'https://' + self.question_str.split('https://')[1] + self.vars['img_path'] = img_path + return img_path + async def _prepare_prediction(self, model: str): self.patches_diff = get_pr_diff(self.git_provider, self.token_handler, model) if self.patches_diff: @@ -86,8 +105,14 @@ class PRQuestions: environment = Environment(undefined=StrictUndefined) system_prompt = environment.from_string(get_settings().pr_questions_prompt.system).render(variables) user_prompt = environment.from_string(get_settings().pr_questions_prompt.user).render(variables) - response, finish_reason = await self.ai_handler.chat_completion(model=model, temperature=0.2, - system=system_prompt, user=user_prompt) + if 'img_path' in variables: + img_path = self.vars['img_path'] + response, finish_reason = await self.ai_handler.chat_completion(model=model, temperature=0.2, + system=system_prompt, user=user_prompt, + img_path=img_path) + else: + response, finish_reason = await self.ai_handler.chat_completion(model=model, temperature=0.2, + system=system_prompt, user=user_prompt) return response def _prepare_pr_answer(self) -> str: From 4683a29819be315268e922dd3652fca53a50cec8 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sun, 14 Apr 2024 12:34:14 +0300 Subject: [PATCH 112/226] s --- docs/docs/tools/ask.md | 35 +++++++++++++++++-- .../algo/ai_handlers/litellm_ai_handler.py | 2 +- pr_agent/servers/github_app.py | 2 +- 3 files changed, 34 insertions(+), 5 deletions(-) diff --git a/docs/docs/tools/ask.md b/docs/docs/tools/ask.md index 453807fd..79c4f00f 100644 --- a/docs/docs/tools/ask.md +++ b/docs/docs/tools/ask.md @@ -7,9 +7,9 @@ It can be invoked manually by commenting on any PR: ``` For example: -![Ask Comment](https://codium.ai/images/pr_agent/ask_comment.png){width=768} +![Ask Comment](https://codium.ai/images/pr_agent/ask_comment.png){width=512} -![Ask](https://codium.ai/images/pr_agent/ask.png){width=768} +![Ask](https://codium.ai/images/pr_agent/ask.png){width=512} ## Ask lines @@ -18,6 +18,35 @@ You can run `/ask` on specific lines of code in the PR from the PR's diff view. - To select multiple lines, click on the '+' sign of the first line and then hold and drag to select the rest of the lines. - write `/ask "..."` in the comment box and press `Add single comment` button. -![Ask Line](https://codium.ai/images/pr_agent/Ask_line.png){width=768} +![Ask Line](https://codium.ai/images/pr_agent/Ask_line.png){width=512} Note that the tool does not have "memory" of previous questions, and answers each question independently. + +## Ask on images (using the PR code as context) + +You can also ask questions about images that appear in the comment, where the entire PR is considered as the context. The tool will answer questions based on the images in the PR. +The basic syntax is: +``` +/ask "..." + +[Image](https://real_link_to_image) +``` + +Note that GitHub has a mecahnism of pasting images in comments. However, pasted image does not provide a direct link. +To get a direct link to the image, we recommend using the following steps: +1) send a comment that contains only the image: + +![Ask image1](https://codium.ai/images/pr_agent/ask_images1.png){width=512} + +2) quote reply to that comment: + +![Ask image2](https://codium.ai/images/pr_agent/ask_images2.png){width=512} + +3) type the question below the image: + +![Ask image3](https://codium.ai/images/pr_agent/ask_images3.png){width=512} +![Ask image4](https://codium.ai/images/pr_agent/ask_images3.png){width=512} + +4) post the comment, and receive the answer: + +![Ask image5](https://codium.ai/images/pr_agent/ask_images5.png){width=512} \ No newline at end of file diff --git a/pr_agent/algo/ai_handlers/litellm_ai_handler.py b/pr_agent/algo/ai_handlers/litellm_ai_handler.py index 536faf41..a547d956 100644 --- a/pr_agent/algo/ai_handlers/litellm_ai_handler.py +++ b/pr_agent/algo/ai_handlers/litellm_ai_handler.py @@ -113,7 +113,7 @@ class LiteLLMAIHandler(BaseAiHandler): import requests r = requests.get(img_path, allow_redirects=True) if r.status_code == 404: - error_msg = "The image link is not alive. Please repost the image, get a new address, and send the question again." + error_msg = f"The image link is not [alive](img_path).\nPlease repost the original image as a comment, and send the question again with 'quote reply' (see [instructions](https://pr-agent-docs.codium.ai/tools/ask/#ask-on-images-using-the-pr-code-as-context))." get_logger().error(error_msg) return f"{error_msg}", "error" messages[1]["content"] = [{"type": "text", "text": messages[1]["content"]}, diff --git a/pr_agent/servers/github_app.py b/pr_agent/servers/github_app.py index 6d942289..f0d1340d 100644 --- a/pr_agent/servers/github_app.py +++ b/pr_agent/servers/github_app.py @@ -88,7 +88,7 @@ async def handle_comments_on_pr(body: Dict[str, Any], if comment_body and isinstance(comment_body, str) and not comment_body.lstrip().startswith("/"): if '/ask' in comment_body and comment_body.strip().startswith('> ![image]'): comment_body_split = comment_body.split('/ask') - comment_body = '/ask' + comment_body_split[1] +'/n' +comment_body_split[0].strip() + comment_body = '/ask' + comment_body_split[1] +' \n' +comment_body_split[0].strip().lstrip('>') get_logger().info(f"Reformatting comment_body so command is at the beginning: {comment_body}") else: get_logger().info("Ignoring comment not starting with /") From f0230fce79dbb2fcba44fde112e042b282f034e4 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sun, 14 Apr 2024 12:37:54 +0300 Subject: [PATCH 113/226] gpt-4-turbo-2024-04-09 --- pr_agent/settings/configuration.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pr_agent/settings/configuration.toml b/pr_agent/settings/configuration.toml index d49b345c..4ab511c1 100644 --- a/pr_agent/settings/configuration.toml +++ b/pr_agent/settings/configuration.toml @@ -1,6 +1,6 @@ [config] -model="gpt-4-turbo" # "gpt-4-0125-preview" -model_turbo="gpt-4-turbo" +model="gpt-4-turbo-2024-04-09" +model_turbo="gpt-4-turbo-2024-04-09" fallback_models=["gpt-4-0125-preview"] git_provider="github" publish_output=true From 86e64501dfb69ff87aa2b165035902ccae6d2b2f Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sun, 14 Apr 2024 12:43:26 +0300 Subject: [PATCH 114/226] ask --- pr_agent/servers/help.py | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/pr_agent/servers/help.py b/pr_agent/servers/help.py index 9e85887d..d76f70a4 100644 --- a/pr_agent/servers/help.py +++ b/pr_agent/servers/help.py @@ -160,16 +160,17 @@ It can be invoked manually by commenting on any PR: /ask "..." ``` -Note that the tool does not have "memory" of previous questions, and answers each question independently. +Note that the tool does not have "memory" of previous questions, and answers each question independently. +You can ask questions about the entire PR, about specific code lines, or about an image related to the PR code changes. """ - output += "\n\n<table>" - - # general - output += "\n\n<tr><td><details> <summary><strong> More PR-Agent commands</strong></summary><hr> \n\n" - output += HelpMessage.get_general_bot_help_text() - output += "\n\n</details></td></tr>\n\n" - - output += "</table>" + # output += "\n\n<table>" + # + # # # general + # # output += "\n\n<tr><td><details> <summary><strong> More PR-Agent commands</strong></summary><hr> \n\n" + # # output += HelpMessage.get_general_bot_help_text() + # # output += "\n\n</details></td></tr>\n\n" + # + # output += "</table>" output += f"\n\nSee the [ask usage](https://pr-agent-docs.codium.ai/tools/ask/) page for a comprehensive guide on using this tool.\n\n" From 92ef2b4464ce6fed2ab68d901428cc7cc03eb752 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sun, 14 Apr 2024 14:09:58 +0300 Subject: [PATCH 115/226] ask --- README.md | 5 +++++ .../algo/ai_handlers/litellm_ai_handler.py | 18 +++++++++++------- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 1ac8b7da..91f7a5ef 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,11 @@ CodiumAI PR-Agent aims to help efficiently review and handle pull requests, by p ## News and Updates +### April 14, 2024 +You can now ask questions about images that appear in the comment, where the entire PR is considered as the context. +see [here](https://pr-agent-docs.codium.ai/tools/ask/#ask-on-images-using-the-pr-code-as-context). +![Ask image5](https://codium.ai/images/pr_agent/ask_images5.png){width=512} + ### March 24, 2024 PR-Agent is now available for easy installation via [pip](https://pr-agent-docs.codium.ai/installation/locally/#using-pip-package). diff --git a/pr_agent/algo/ai_handlers/litellm_ai_handler.py b/pr_agent/algo/ai_handlers/litellm_ai_handler.py index a547d956..4acd55ea 100644 --- a/pr_agent/algo/ai_handlers/litellm_ai_handler.py +++ b/pr_agent/algo/ai_handlers/litellm_ai_handler.py @@ -1,5 +1,5 @@ import os - +import requests import boto3 import litellm import openai @@ -110,12 +110,16 @@ class LiteLLMAIHandler(BaseAiHandler): model = 'azure/' + model messages = [{"role": "system", "content": system}, {"role": "user", "content": user}] if img_path: - import requests - r = requests.get(img_path, allow_redirects=True) - if r.status_code == 404: - error_msg = f"The image link is not [alive](img_path).\nPlease repost the original image as a comment, and send the question again with 'quote reply' (see [instructions](https://pr-agent-docs.codium.ai/tools/ask/#ask-on-images-using-the-pr-code-as-context))." - get_logger().error(error_msg) - return f"{error_msg}", "error" + try: + # check if the image link is alive + r = requests.head(img_path, allow_redirects=True) + if r.status_code == 404: + error_msg = f"The image link is not [alive](img_path).\nPlease repost the original image as a comment, and send the question again with 'quote reply' (see [instructions](https://pr-agent-docs.codium.ai/tools/ask/#ask-on-images-using-the-pr-code-as-context))." + get_logger().error(error_msg) + return f"{error_msg}", "error" + except Exception as e: + get_logger().error(f"Error fetching image: {img_path}", e) + return f"Error fetching image: {img_path}", "error" messages[1]["content"] = [{"type": "text", "text": messages[1]["content"]}, {"type": "image_url", "image_url": {"url": img_path}}] From 506e3007c4549262b82c2478ca0c83afccfca569 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sun, 14 Apr 2024 14:11:04 +0300 Subject: [PATCH 116/226] ask --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 91f7a5ef..40453d37 100644 --- a/README.md +++ b/README.md @@ -42,8 +42,9 @@ CodiumAI PR-Agent aims to help efficiently review and handle pull requests, by p ### April 14, 2024 You can now ask questions about images that appear in the comment, where the entire PR is considered as the context. -see [here](https://pr-agent-docs.codium.ai/tools/ask/#ask-on-images-using-the-pr-code-as-context). -![Ask image5](https://codium.ai/images/pr_agent/ask_images5.png){width=512} +see [here](https://pr-agent-docs.codium.ai/tools/ask/#ask-on-images-using-the-pr-code-as-context) for more details. + +<kbd><img src="https://codium.ai/images/pr_agent/ask_images5.png" width="512"></kbd> ### March 24, 2024 PR-Agent is now available for easy installation via [pip](https://pr-agent-docs.codium.ai/installation/locally/#using-pip-package). From 44eb0b4f237d68df03955082c8338464bdf478ee Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sun, 14 Apr 2024 14:12:48 +0300 Subject: [PATCH 117/226] ask --- pr_agent/tools/pr_questions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pr_agent/tools/pr_questions.py b/pr_agent/tools/pr_questions.py index 1e2a360e..d78d0880 100644 --- a/pr_agent/tools/pr_questions.py +++ b/pr_agent/tools/pr_questions.py @@ -84,7 +84,7 @@ class PRQuestions: # /ask question ... > ![image](img_path) img_path = self.question_str.split('![image]')[1].strip().strip('()') self.vars['img_path'] = img_path - elif 'https://' in self.question_str and '.png' in self.question_str: # direct image link + elif 'https://' in self.question_str and ('.png' in self.question_str or 'jpg' in self.question_str): # direct image link # include https:// in the image path img_path = 'https://' + self.question_str.split('https://')[1] self.vars['img_path'] = img_path From 8168ce0c8eedda9c1ae212b7a098957d27f8743e Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sun, 14 Apr 2024 14:45:15 +0300 Subject: [PATCH 118/226] ask --- docs/docs/tools/ask.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/docs/tools/ask.md b/docs/docs/tools/ask.md index 79c4f00f..f7678337 100644 --- a/docs/docs/tools/ask.md +++ b/docs/docs/tools/ask.md @@ -22,7 +22,7 @@ You can run `/ask` on specific lines of code in the PR from the PR's diff view. Note that the tool does not have "memory" of previous questions, and answers each question independently. -## Ask on images (using the PR code as context) +## Ask on images You can also ask questions about images that appear in the comment, where the entire PR is considered as the context. The tool will answer questions based on the images in the PR. The basic syntax is: @@ -34,6 +34,7 @@ The basic syntax is: Note that GitHub has a mecahnism of pasting images in comments. However, pasted image does not provide a direct link. To get a direct link to the image, we recommend using the following steps: + 1) send a comment that contains only the image: ![Ask image1](https://codium.ai/images/pr_agent/ask_images1.png){width=512} @@ -45,8 +46,11 @@ To get a direct link to the image, we recommend using the following steps: 3) type the question below the image: ![Ask image3](https://codium.ai/images/pr_agent/ask_images3.png){width=512} -![Ask image4](https://codium.ai/images/pr_agent/ask_images3.png){width=512} +![Ask image4](https://codium.ai/images/pr_agent/ask_images4.png){width=512} 4) post the comment, and receive the answer: -![Ask image5](https://codium.ai/images/pr_agent/ask_images5.png){width=512} \ No newline at end of file +![Ask image5](https://codium.ai/images/pr_agent/ask_images5.png){width=512} + + +See a full video tutorial [here](https://codium.ai/images/pr_agent/ask_image_video.mov) \ No newline at end of file From 93d153bae109ea85aca4509bd959701770046b9d Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Mon, 15 Apr 2024 10:12:19 +0300 Subject: [PATCH 119/226] ask --- README.md | 2 +- docs/docs/tools/ask.md | 16 +++++++++------- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 40453d37..43ce7efc 100644 --- a/README.md +++ b/README.md @@ -42,7 +42,7 @@ CodiumAI PR-Agent aims to help efficiently review and handle pull requests, by p ### April 14, 2024 You can now ask questions about images that appear in the comment, where the entire PR is considered as the context. -see [here](https://pr-agent-docs.codium.ai/tools/ask/#ask-on-images-using-the-pr-code-as-context) for more details. +see [here](https://pr-agent-docs.codium.ai/tools/ask/#ask-on-images) for more details. <kbd><img src="https://codium.ai/images/pr_agent/ask_images5.png" width="512"></kbd> diff --git a/docs/docs/tools/ask.md b/docs/docs/tools/ask.md index f7678337..0d477934 100644 --- a/docs/docs/tools/ask.md +++ b/docs/docs/tools/ask.md @@ -24,31 +24,33 @@ Note that the tool does not have "memory" of previous questions, and answers eac ## Ask on images -You can also ask questions about images that appear in the comment, where the entire PR is considered as the context. The tool will answer questions based on the images in the PR. +You can also ask questions about images that appear in the comment, where the entire PR code will be used as context. +<br> The basic syntax is: ``` /ask "..." [Image](https://real_link_to_image) ``` +where `https://real_link_to_image` is the direct link to the image. -Note that GitHub has a mecahnism of pasting images in comments. However, pasted image does not provide a direct link. -To get a direct link to the image, we recommend using the following steps: +Note that GitHub has a built-in mechanism of pasting images in comments. However, pasted image does not provide a direct link. +To get a direct link to an image, we recommend using the following scheme: -1) send a comment that contains only the image: +1) First, post a comment that contains **only** the image: ![Ask image1](https://codium.ai/images/pr_agent/ask_images1.png){width=512} -2) quote reply to that comment: +2) Quote reply to that comment: ![Ask image2](https://codium.ai/images/pr_agent/ask_images2.png){width=512} -3) type the question below the image: +3) In the screen opened, type the question below the image: ![Ask image3](https://codium.ai/images/pr_agent/ask_images3.png){width=512} ![Ask image4](https://codium.ai/images/pr_agent/ask_images4.png){width=512} -4) post the comment, and receive the answer: +4) Post the comment, and receive the answer: ![Ask image5](https://codium.ai/images/pr_agent/ask_images5.png){width=512} From 1481796d6ac475075a26c3c47fbef1a5f6b62b62 Mon Sep 17 00:00:00 2001 From: Almog Lavi <42740235+almog-lv@users.noreply.github.com> Date: Mon, 15 Apr 2024 13:32:05 +0300 Subject: [PATCH 120/226] Add GitHub repository URL to MkDocs configuration --- docs/mkdocs.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index c045d8e4..5e6940d1 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -1,4 +1,5 @@ site_name: PR-Agent +repo_url: https://github.com/Codium-ai/pr-agent nav: - Overview: 'index.md' From fe231929aefdac34d56c9e1de130cd2964b69686 Mon Sep 17 00:00:00 2001 From: Almog Lavi <42740235+almog-lv@users.noreply.github.com> Date: Mon, 15 Apr 2024 13:33:22 +0300 Subject: [PATCH 121/226] Update mkdocs.yml to include site description and rename site --- docs/mkdocs.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index 5e6940d1..9854ca14 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -1,4 +1,5 @@ -site_name: PR-Agent +site_name: PR-Agent Documentation +description: Documentation for PR-Agent, the AI-powered Pull Request tool. repo_url: https://github.com/Codium-ai/pr-agent nav: From d5262f24ca42941e89db29ca79d23e75b4a30f70 Mon Sep 17 00:00:00 2001 From: Almog Lavi <42740235+almog-lv@users.noreply.github.com> Date: Mon, 15 Apr 2024 13:37:50 +0300 Subject: [PATCH 122/226] add name + github icon --- docs/mkdocs.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index 9854ca14..c11965d0 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -1,7 +1,7 @@ site_name: PR-Agent Documentation description: Documentation for PR-Agent, the AI-powered Pull Request tool. repo_url: https://github.com/Codium-ai/pr-agent - +repo_name: Codium-ai/pr-agent nav: - Overview: 'index.md' - Installation: @@ -41,6 +41,8 @@ theme: logo: assets/logo.svg favicon: assets/favicon.ico name: material + icon: + repo: fontawesome/brands/github features: - navigation.tabs - navigation.expand From 32fd03bd556bdbb2ae5f566b640fb4fa853c12c8 Mon Sep 17 00:00:00 2001 From: Almog Lavi <42740235+almog-lv@users.noreply.github.com> Date: Mon, 15 Apr 2024 13:42:36 +0300 Subject: [PATCH 123/226] Add repository URL to MkDocs configuration --- docs/mkdocs.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index c11965d0..66a702ac 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -1,7 +1,7 @@ site_name: PR-Agent Documentation -description: Documentation for PR-Agent, the AI-powered Pull Request tool. repo_url: https://github.com/Codium-ai/pr-agent repo_name: Codium-ai/pr-agent + nav: - Overview: 'index.md' - Installation: From 6c78f4fd8899c473da3f6a72dab30382dddaf87c Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Wed, 17 Apr 2024 09:02:54 +0300 Subject: [PATCH 124/226] Example usage --- docs/docs/tools/describe.md | 39 ++++++++++++++++++++++++++++++------- 1 file changed, 32 insertions(+), 7 deletions(-) diff --git a/docs/docs/tools/describe.md b/docs/docs/tools/describe.md index 50d2af0a..50d927a8 100644 --- a/docs/docs/tools/describe.md +++ b/docs/docs/tools/describe.md @@ -6,22 +6,47 @@ The tool can be triggered automatically every time a new PR is [opened](../usage /describe ``` -For example: +## Example usage + +### Manual invocation + +Invoke the tool manually by commenting `/describe` on any PR: ![Describe comment](https://codium.ai/images/pr_agent/describe_comment.png){width=512} +After ~30 seconds, the tool will generate a description for the PR: + ![Describe New](https://codium.ai/images/pr_agent/describe_new.png){width=512} - - -## Configuration options - -### General configurations -To edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/configuration.toml#L46) related to the describe tool (`pr_description` section), use the following template: +If you want to edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/configuration.toml#L46), add the relevant ones to the command: ``` /describe --pr_description.some_config1=... --pr_description.some_config2=... ``` +### Automatic invocation + +To run the `describe` automatically when a PR is opened, define in a [configuration file](https://pr-agent-docs.codium.ai/usage-guide/configuration_options/#wiki-configuration-file): +``` +[github_app] +pr_commands = [ + "/describe", + ... +] + +[pr_description] +publish_labels = ... +... + +``` + +- The `pr_commands` lists commands that will be executed on every PR. +- The `[pr_description]` section contains the configurations for the `describe` tool you want to edit. + + +## Configuration options + +### General configurations + !!! example "Possible configurations" - `publish_labels`: if set to true, the tool will publish the labels to the PR. Default is true. From e878dcb6b1ba99b4adedad26c7523edfaad157ea Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Wed, 17 Apr 2024 09:12:49 +0300 Subject: [PATCH 125/226] Example usage --- docs/docs/tools/describe.md | 5 ++--- docs/docs/tools/review.md | 37 +++++++++++++++++++++++++++++++------ 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/docs/docs/tools/describe.md b/docs/docs/tools/describe.md index 50d927a8..62a7eb34 100644 --- a/docs/docs/tools/describe.md +++ b/docs/docs/tools/describe.md @@ -18,7 +18,7 @@ After ~30 seconds, the tool will generate a description for the PR: ![Describe New](https://codium.ai/images/pr_agent/describe_new.png){width=512} -If you want to edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/configuration.toml#L46), add the relevant ones to the command: +If you want to edit [configurations](#configuration-options), add the relevant ones to the command: ``` /describe --pr_description.some_config1=... --pr_description.some_config2=... ``` @@ -36,10 +36,9 @@ pr_commands = [ [pr_description] publish_labels = ... ... - ``` -- The `pr_commands` lists commands that will be executed on every PR. +- The `pr_commands` lists commands that will be executed automatically when a PR is opened. - The `[pr_description]` section contains the configurations for the `describe` tool you want to edit. diff --git a/docs/docs/tools/review.md b/docs/docs/tools/review.md index c5681bb4..9ba34b69 100644 --- a/docs/docs/tools/review.md +++ b/docs/docs/tools/review.md @@ -4,22 +4,47 @@ The tool can be triggered automatically every time a new PR is [opened](../usage ``` /review ``` -For example: + +## Example usage + +### Manual invocation + +Invoke the tool manually by commenting `/review` on any PR: ![review comment](https://codium.ai/images/pr_agent/review_comment.png){width=512} +After ~30 seconds, the tool will generate a review for the PR: + ![review](https://codium.ai/images/pr_agent/review3.png){width=512} +If you want to edit [configurations](#configuration-options), add the relevant ones to the command: +``` +/review --pr_reviewer.some_config1=... --pr_reviewer.some_config2=... +``` + +### Automatic invocation + +To run the `review` automatically when a PR is opened, define in a [configuration file](https://pr-agent-docs.codium.ai/usage-guide/configuration_options/#wiki-configuration-file): +``` +[github_app] +pr_commands = [ + "/review", + ... +] + +[pr_reviewer] +publish_labels = ... +... +``` + +- The `pr_commands` lists commands that will be executed automatically when a PR is opened. +- The `[pr_reviewer]` section contains the configurations for the `review` tool you want to edit. + ## Configuration options ### General configurations -To edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/configuration.toml#L19) related to the review tool (`pr_reviewer` section), use the following template: -``` -/review --pr_reviewer.some_config1=... --pr_reviewer.some_config2=... -``` - !!! example "General options" - `num_code_suggestions`: number of code suggestions provided by the 'review' tool. For manual comments, default is 4. For [PR-Agent app](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/configuration.toml#L142) auto tools, default is 0, meaning no code suggestions will be provided by the review tool, unless you manually edit `pr_commands`. - `inline_code_comments`: if set to true, the tool will publish the code suggestions as comments on the code diff. Default is false. From e2e0bea8fd6f47d631ec3147495b768800b2a146 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Wed, 17 Apr 2024 09:13:53 +0300 Subject: [PATCH 126/226] num_code_suggestions --- docs/docs/tools/review.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/tools/review.md b/docs/docs/tools/review.md index 9ba34b69..92a642f4 100644 --- a/docs/docs/tools/review.md +++ b/docs/docs/tools/review.md @@ -33,7 +33,7 @@ pr_commands = [ ] [pr_reviewer] -publish_labels = ... +num_code_suggestions = ... ... ``` From b076c33351c5a622aa73fd54996e710adeff895f Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Wed, 17 Apr 2024 15:32:45 +0300 Subject: [PATCH 127/226] commitable_code_suggestions --- .pr_agent.toml | 2 +- docs/docs/tools/improve.md | 6 +++--- docs/docs/usage-guide/automations_and_usage.md | 2 +- pr_agent/settings/configuration.toml | 8 ++++---- pr_agent/tools/pr_code_suggestions.py | 8 ++++---- 5 files changed, 13 insertions(+), 13 deletions(-) diff --git a/.pr_agent.toml b/.pr_agent.toml index 29c5489a..0d1d9914 100644 --- a/.pr_agent.toml +++ b/.pr_agent.toml @@ -4,4 +4,4 @@ enable_auto_approval = true [pr_code_suggestions] -summarize=true +commitable_code_suggestions=false diff --git a/docs/docs/tools/improve.md b/docs/docs/tools/improve.md index b62fd649..2869b180 100644 --- a/docs/docs/tools/improve.md +++ b/docs/docs/tools/improve.md @@ -7,11 +7,11 @@ The tool can be triggered automatically every time a new PR is [opened](../usage ### Summarized vs committable code suggestions -The code suggestions can be presented as a single comment (via `pr_code_suggestions.summarize=true`): +The code suggestions can be presented as a single comment ![code suggestions as comment](https://codium.ai/images/pr_agent/code_suggestions_as_comment.png){width=512} -Or as a separate commitable code comment for each suggestion: +Or as a separate commitable code comment for each suggestion (via `pr_code_suggestions.commitable_code_suggestions=true`):: ![imporove](https://codium.ai/images/pr_agent/improve.png){width=512} @@ -58,7 +58,7 @@ To edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agen - `num_code_suggestions_per_chunk`: number of code suggestions provided by the 'improve' tool, per chunk. Default is 5. - `rank_extended_suggestions`: if set to true, the tool will rank the suggestions, based on importance. Default is true. - `max_number_of_calls`: maximum number of chunks. Default is 5. - - `final_clip_factor`: factor to remove suggestions with low confidence. Default is 0.9. + - `final_clip_factor`: factor to remove suggestions with low confidence. Default is 0.9.; ## Usage Tips diff --git a/docs/docs/usage-guide/automations_and_usage.md b/docs/docs/usage-guide/automations_and_usage.md index 14992611..d7a009e0 100644 --- a/docs/docs/usage-guide/automations_and_usage.md +++ b/docs/docs/usage-guide/automations_and_usage.md @@ -170,7 +170,7 @@ Specifically, set the following values: [bitbucket_app] pr_commands = [ "/review --pr_reviewer.num_code_suggestions=0", - "/improve --pr_code_suggestions.summarize=false", + "/improve --pr_code_suggestions.commitable_code_suggestions=true", ] ``` diff --git a/pr_agent/settings/configuration.toml b/pr_agent/settings/configuration.toml index 4ab511c1..01646ff4 100644 --- a/pr_agent/settings/configuration.toml +++ b/pr_agent/settings/configuration.toml @@ -80,7 +80,7 @@ enable_help_text=true [pr_code_suggestions] # /improve # max_context_tokens=8000 num_code_suggestions=4 -summarize = true +commitable_code_suggestions = false extra_instructions = "" rank_suggestions = false enable_help_text=true @@ -150,7 +150,7 @@ handle_pr_actions = ['opened', 'reopened', 'ready_for_review'] pr_commands = [ "/describe --pr_description.add_original_user_description=true --pr_description.keep_original_user_title=true", "/review --pr_reviewer.num_code_suggestions=0", - "/improve --pr_code_suggestions.summarize=true", + "/improve", ] # settings for "pull_request" event with "synchronize" action - used to detect and handle push triggers for new commits handle_push_trigger = false @@ -171,13 +171,13 @@ url = "https://gitlab.com" # URL to the gitlab service pr_commands = [ "/describe --pr_description.add_original_user_description=true --pr_description.keep_original_user_title=true", "/review --pr_reviewer.num_code_suggestions=0", - "/improve --pr_code_suggestions.summarize=true", + "/improve", ] [bitbucket_app] pr_commands = [ "/review --pr_reviewer.num_code_suggestions=0", - "/improve --pr_code_suggestions.summarize=false", + "/improve --pr_code_suggestions.commitable_code_suggestions=true", ] diff --git a/pr_agent/tools/pr_code_suggestions.py b/pr_agent/tools/pr_code_suggestions.py index ed14d225..813ccbfa 100644 --- a/pr_agent/tools/pr_code_suggestions.py +++ b/pr_agent/tools/pr_code_suggestions.py @@ -57,7 +57,7 @@ class PRCodeSuggestions: "language": self.main_language, "diff": "", # empty diff for initial calculation "num_code_suggestions": num_code_suggestions, - "summarize_mode": get_settings().pr_code_suggestions.summarize, + "commitable_code_suggestions_mode": get_settings().pr_code_suggestions.commitable_code_suggestions, "extra_instructions": get_settings().pr_code_suggestions.extra_instructions, "commit_messages_str": self.git_provider.get_commit_messages(), } @@ -105,7 +105,7 @@ class PRCodeSuggestions: if get_settings().config.publish_output: self.git_provider.remove_initial_comment() - if get_settings().pr_code_suggestions.summarize and self.git_provider.is_supported("gfm_markdown"): + if (not get_settings().pr_code_suggestions.commitable_code_suggestions) and self.git_provider.is_supported("gfm_markdown"): # generate summarized suggestions pr_body = self.generate_summarized_suggestions(data) @@ -197,7 +197,7 @@ class PRCodeSuggestions: one_sentence_summary_list = [] for i, suggestion in enumerate(data['code_suggestions']): try: - if get_settings().pr_code_suggestions.summarize: + if not get_settings().pr_code_suggestions.commitable_code_suggestions: if not suggestion or 'one_sentence_summary' not in suggestion or 'label' not in suggestion or 'relevant_file' not in suggestion: get_logger().debug(f"Skipping suggestion {i + 1}, because it is invalid: {suggestion}") continue @@ -213,7 +213,7 @@ class PRCodeSuggestions: if ('existing_code' in suggestion) and ('improved_code' in suggestion) and ( suggestion['existing_code'] != suggestion['improved_code']): suggestion = self._truncate_if_needed(suggestion) - if get_settings().pr_code_suggestions.summarize: + if not get_settings().pr_code_suggestions.commitable_code_suggestions: one_sentence_summary_list.append(suggestion['one_sentence_summary']) suggestion_list.append(suggestion) else: From 2f4e40860ded05a7227399b3ba64e32d18cdb53c Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Wed, 17 Apr 2024 16:29:12 +0300 Subject: [PATCH 128/226] Replace `keep_original_user_title` with `generate_ai_title` for PR description customization and update documentation accordingly --- docs/docs/tools/describe.md | 11 +++++------ docs/docs/usage-guide/automations_and_usage.md | 11 +++++------ docs/docs/usage-guide/configuration_options.md | 2 +- pr_agent/servers/help.py | 5 ++--- pr_agent/settings/configuration.toml | 8 ++++---- pr_agent/tools/pr_description.py | 2 +- 6 files changed, 18 insertions(+), 21 deletions(-) diff --git a/docs/docs/tools/describe.md b/docs/docs/tools/describe.md index 62a7eb34..80e2adb4 100644 --- a/docs/docs/tools/describe.md +++ b/docs/docs/tools/describe.md @@ -56,7 +56,7 @@ publish_labels = ... - `add_original_user_description`: if set to true, the tool will add the original user description to the generated description. Default is true. - - `keep_original_user_title`: if set to true, the tool will keep the original PR title, and won't change it. Default is true. + - `generate_ai_title`: if set to true, the tool will also generate an AI title for the PR. Default is false. - `extra_instructions`: Optional extra instructions to the tool. For example: "focus on the changes in the file X. Ignore change in ...". @@ -168,18 +168,17 @@ The description should be comprehensive and detailed, indicating when to add the !!! tip "Automation" - When you first install PR-Agent app, the [default mode](../usage-guide/automations_and_usage.md#github-app) for the describe tool is: ``` - pr_commands = ["/describe --pr_description.add_original_user_description=true" - "--pr_description.keep_original_user_title=true", ...] + pr_commands = ["/describe --pr_description.add_original_user_description=true ..."] ``` - meaning the `describe` tool will run automatically on every PR, will keep the original title, and will add the original user description above the generated description. + meaning the `describe` tool will run automatically on every PR, and will add the original user description above the generated description. <br> This default settings aim to strike a good balance between automation and control: - If you want more automation, just give the PR a title, and the tool will auto-write a full description; If you want more control, you can add a detailed description, and the tool will add the complementary description below it. - For maximal automation, you can change the default mode to: ``` pr_commands = ["/describe --pr_description.add_original_user_description=false" - "--pr_description.keep_original_user_title=true", ...] + " --pr_description.generate_ai_tile=true", ...] ``` - so the title will be auto-generated as well. + so the title of the PR will be auto-generated as well. - Markers are an alternative way to control the generated description, to give maximal control to the user. If you set: ``` pr_commands = ["/describe --pr_description.use_description_markers=true", ...] diff --git a/docs/docs/usage-guide/automations_and_usage.md b/docs/docs/usage-guide/automations_and_usage.md index d7a009e0..a69c0851 100644 --- a/docs/docs/usage-guide/automations_and_usage.md +++ b/docs/docs/usage-guide/automations_and_usage.md @@ -62,20 +62,19 @@ The configuration parameter `pr_commands` defines the list of tools that will be ``` [github_app] pr_commands = [ - "/describe --pr_description.add_original_user_description=true --pr_description.keep_original_user_title=true --pr_description.final_update_message=false", + "/describe --pr_description.add_original_user_description=true --pr_description.final_update_message=false", "/review --pr_reviewer.num_code_suggestions=0", "/improve", ] ``` This means that when a new PR is opened/reopened or marked as ready for review, PR-Agent will run the `describe`, `review` and `improve` tools. -For the `describe` tool, for example, the `add_original_user_description` and `keep_original_user_title` parameters will be set to true. +For the `describe` tool, for example, the `add_original_user_description` parameter will be set to true. You can override the default tool parameters by using one the three options for a [configuration file](https://codium-ai.github.io/Docs-PR-Agent/usage-guide/#configuration-options): **wiki**, **local**, or **global**. For example, if your local `.pr_agent.toml` file contains: ``` [pr_description] add_original_user_description = false -keep_original_user_title = false ``` When a new PR is opened, PR-Agent will run the `describe` tool with the above parameters. @@ -102,7 +101,7 @@ The configuration parameter `push_commands` defines the list of tools that will [github_app] handle_push_trigger = true push_commands = [ - "/describe --pr_description.add_original_user_description=true --pr_description.keep_original_user_title=true", + "/describe --pr_description.add_original_user_description=true", "/review --pr_reviewer.num_code_suggestions=0 --pr_reviewer.final_update_message=false", ] ``` @@ -142,7 +141,7 @@ After setting up a GitLab webhook, to control which commands will run automatica ``` [gitlab] pr_commands = [ - "/describe --pr_description.add_original_user_description=true --pr_description.keep_original_user_title=true", + "/describe --pr_description.add_original_user_description=true", "/review --pr_reviewer.num_code_suggestions=0", "/improve", ] @@ -202,7 +201,7 @@ To control which commands will run automatically when a new PR is opened, you ca ``` [azure_devops_server] pr_commands = [ - "/describe --pr_description.add_original_user_description=true --pr_description.keep_original_user_title=true", + "/describe --pr_description.add_original_user_description=true", "/review --pr_reviewer.num_code_suggestions=0", "/improve", ] diff --git a/docs/docs/usage-guide/configuration_options.md b/docs/docs/usage-guide/configuration_options.md index ee908b76..54a37a86 100644 --- a/docs/docs/usage-guide/configuration_options.md +++ b/docs/docs/usage-guide/configuration_options.md @@ -23,7 +23,7 @@ An example content: ``` [pr_description] -keep_original_user_title=false +generate_ai_title=true ``` PR-Agent will know to remove the triple-quotes when reading the configuration content. diff --git a/pr_agent/servers/help.py b/pr_agent/servers/help.py index d76f70a4..b37cedc3 100644 --- a/pr_agent/servers/help.py +++ b/pr_agent/servers/help.py @@ -68,10 +68,9 @@ some_config2=... output += """\ - When you first install the app, the [default mode](https://pr-agent-docs.codium.ai/usage-guide/automations_and_usage/#github-app-automatic-tools-when-a-new-pr-is-opened) for the describe tool is: ``` -pr_commands = ["/describe --pr_description.add_original_user_description=true" - "--pr_description.keep_original_user_title=true", ...] +pr_commands = ["/describe --pr_description.add_original_user_description=true ..."] ``` -meaning the `describe` tool will run automatically on every PR, will keep the original title, and will add the original user description above the generated description. +meaning the `describe` tool will run automatically on every PR, and will add the original user description above the generated description. - Markers are an alternative way to control the generated description, to give maximal control to the user. If you set: ``` diff --git a/pr_agent/settings/configuration.toml b/pr_agent/settings/configuration.toml index 01646ff4..bd85b0fe 100644 --- a/pr_agent/settings/configuration.toml +++ b/pr_agent/settings/configuration.toml @@ -53,7 +53,7 @@ maximal_review_effort=5 [pr_description] # /describe # publish_labels=true add_original_user_description=true -keep_original_user_title=true +generate_ai_title=false use_bullet_points=true extra_instructions = "" enable_pr_type=true @@ -148,7 +148,7 @@ override_deployment_type = true # settings for "pull_request" event handle_pr_actions = ['opened', 'reopened', 'ready_for_review'] pr_commands = [ - "/describe --pr_description.add_original_user_description=true --pr_description.keep_original_user_title=true", + "/describe --pr_description.add_original_user_description=true", "/review --pr_reviewer.num_code_suggestions=0", "/improve", ] @@ -160,7 +160,7 @@ push_trigger_wait_for_initial_review = true push_trigger_pending_tasks_backlog = true push_trigger_pending_tasks_ttl = 300 push_commands = [ - "/describe --pr_description.add_original_user_description=true --pr_description.keep_original_user_title=true", + "/describe --pr_description.add_original_user_description=true", "/review --pr_reviewer.num_code_suggestions=0", ] ignore_pr_title = [] @@ -169,7 +169,7 @@ ignore_bot_pr = true [gitlab] url = "https://gitlab.com" # URL to the gitlab service pr_commands = [ - "/describe --pr_description.add_original_user_description=true --pr_description.keep_original_user_title=true", + "/describe --pr_description.add_original_user_description=true", "/review --pr_reviewer.num_code_suggestions=0", "/improve", ] diff --git a/pr_agent/tools/pr_description.py b/pr_agent/tools/pr_description.py index 8526642f..fa662464 100644 --- a/pr_agent/tools/pr_description.py +++ b/pr_agent/tools/pr_description.py @@ -301,7 +301,7 @@ class PRDescription: # Remove the 'PR Title' key from the dictionary ai_title = self.data.pop('title', self.vars["title"]) - if get_settings().pr_description.keep_original_user_title: + if (not get_settings().pr_description.generate_ai_title): # Assign the original PR title to the 'title' variable title = self.vars["title"] else: From 8242b10d8e531c0ea010293ca500224f444e3616 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Thu, 18 Apr 2024 07:31:33 +0300 Subject: [PATCH 129/226] Replace `summarize_mode` with `commitable_code_suggestions_mode` in pr_code_suggestions_prompts.toml to enhance PR suggestion mechanism --- pr_agent/settings/pr_code_suggestions_prompts.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pr_agent/settings/pr_code_suggestions_prompts.toml b/pr_agent/settings/pr_code_suggestions_prompts.toml index aae955a3..cdf4ebdc 100644 --- a/pr_agent/settings/pr_code_suggestions_prompts.toml +++ b/pr_agent/settings/pr_code_suggestions_prompts.toml @@ -54,7 +54,7 @@ class CodeSuggestion(BaseModel): relevant_file: str = Field(description="the relevant file full path") language: str = Field(description="the code language of the relevant file") suggestion_content: str = Field(description="an actionable suggestion for meaningfully improving the new code introduced in the PR") -{%- if summarize_mode %} +{%- if commitable_code_suggestions_mode %} existing_code: str = Field(description="a short code snippet from a '__new hunk__' section to illustrate the relevant existing code. Don't show the line numbers.") improved_code: str = Field(description="a short code snippet to illustrate the improved code, after applying the suggestion.") one_sentence_summary:str = Field(description="a short summary of the suggestion action, in a single sentence. Focus on the 'what'. Be general, and avoid method or variable names.") @@ -80,7 +80,7 @@ code_suggestions: python suggestion_content: | ... -{%- if summarize_mode %} +{%- if commitable_code_suggestions_mode %} existing_code: | ... improved_code: | From ad963268328fd75c71b31d204821160708b4ff1c Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Thu, 18 Apr 2024 07:53:37 +0300 Subject: [PATCH 130/226] not --- pr_agent/settings/pr_code_suggestions_prompts.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pr_agent/settings/pr_code_suggestions_prompts.toml b/pr_agent/settings/pr_code_suggestions_prompts.toml index cdf4ebdc..278f0117 100644 --- a/pr_agent/settings/pr_code_suggestions_prompts.toml +++ b/pr_agent/settings/pr_code_suggestions_prompts.toml @@ -54,7 +54,7 @@ class CodeSuggestion(BaseModel): relevant_file: str = Field(description="the relevant file full path") language: str = Field(description="the code language of the relevant file") suggestion_content: str = Field(description="an actionable suggestion for meaningfully improving the new code introduced in the PR") -{%- if commitable_code_suggestions_mode %} +{%- if not commitable_code_suggestions_mode %} existing_code: str = Field(description="a short code snippet from a '__new hunk__' section to illustrate the relevant existing code. Don't show the line numbers.") improved_code: str = Field(description="a short code snippet to illustrate the improved code, after applying the suggestion.") one_sentence_summary:str = Field(description="a short summary of the suggestion action, in a single sentence. Focus on the 'what'. Be general, and avoid method or variable names.") @@ -80,7 +80,7 @@ code_suggestions: python suggestion_content: | ... -{%- if commitable_code_suggestions_mode %} +{%- if not commitable_code_suggestions_mode %} existing_code: | ... improved_code: | From 7563af08a03a45f9598a4cf3d80bc22aa5fc438e Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Thu, 18 Apr 2024 08:44:08 +0300 Subject: [PATCH 131/226] docs --- docs/docs/tools/describe.md | 32 ++++++++----------- .../docs/usage-guide/automations_and_usage.md | 14 ++++---- pr_agent/servers/github_app.py | 2 +- pr_agent/servers/help.py | 4 +-- pr_agent/settings/configuration.toml | 6 ++-- 5 files changed, 26 insertions(+), 32 deletions(-) diff --git a/docs/docs/tools/describe.md b/docs/docs/tools/describe.md index 80e2adb4..dee6f204 100644 --- a/docs/docs/tools/describe.md +++ b/docs/docs/tools/describe.md @@ -168,24 +168,18 @@ The description should be comprehensive and detailed, indicating when to add the !!! tip "Automation" - When you first install PR-Agent app, the [default mode](../usage-guide/automations_and_usage.md#github-app) for the describe tool is: ``` - pr_commands = ["/describe --pr_description.add_original_user_description=true ..."] + pr_commands = ["/describe", ...] ``` - meaning the `describe` tool will run automatically on every PR, and will add the original user description above the generated description. - <br> This default settings aim to strike a good balance between automation and control: - - If you want more automation, just give the PR a title, and the tool will auto-write a full description; If you want more control, you can add a detailed description, and the tool will add the complementary description below it. - - For maximal automation, you can change the default mode to: - ``` - pr_commands = ["/describe --pr_description.add_original_user_description=false" - " --pr_description.generate_ai_tile=true", ...] - ``` - so the title of the PR will be auto-generated as well. - - Markers are an alternative way to control the generated description, to give maximal control to the user. If you set: - ``` - pr_commands = ["/describe --pr_description.use_description_markers=true", ...] - ``` - the tool will replace every marker of the form `pr_agent:marker_name` in the PR description with the relevant content, where `marker_name` is one of the following: - * `type`: the PR type. - * `summary`: the PR summary. - * `walkthrough`: the PR walkthrough. + meaning the `describe` tool will run automatically on every PR, with the default configurations. - - Note that when markers are enabled, if the original PR description does not contain any markers, the tool will not alter the description at all. + + - Markers are an alternative way to control the generated description, to give maximal control to the user. If you set: + ``` + pr_commands = ["/describe --pr_description.use_description_markers=true", ...] + ``` + the tool will replace every marker of the form `pr_agent:marker_name` in the PR description with the relevant content, where `marker_name` is one of the following: + * `type`: the PR type. + * `summary`: the PR summary. + * `walkthrough`: the PR walkthrough. + + - Note that when markers are enabled, if the original PR description does not contain any markers, the tool will not alter the description at all. diff --git a/docs/docs/usage-guide/automations_and_usage.md b/docs/docs/usage-guide/automations_and_usage.md index a69c0851..aa969755 100644 --- a/docs/docs/usage-guide/automations_and_usage.md +++ b/docs/docs/usage-guide/automations_and_usage.md @@ -62,21 +62,21 @@ The configuration parameter `pr_commands` defines the list of tools that will be ``` [github_app] pr_commands = [ - "/describe --pr_description.add_original_user_description=true --pr_description.final_update_message=false", + "/describe --pr_description.final_update_message=false", "/review --pr_reviewer.num_code_suggestions=0", "/improve", ] ``` This means that when a new PR is opened/reopened or marked as ready for review, PR-Agent will run the `describe`, `review` and `improve` tools. -For the `describe` tool, for example, the `add_original_user_description` parameter will be set to true. +For the `review` tool, for example, the `num_code_suggestions` parameter will be set to 0. You can override the default tool parameters by using one the three options for a [configuration file](https://codium-ai.github.io/Docs-PR-Agent/usage-guide/#configuration-options): **wiki**, **local**, or **global**. For example, if your local `.pr_agent.toml` file contains: ``` [pr_description] -add_original_user_description = false +generate_ai_title = true ``` -When a new PR is opened, PR-Agent will run the `describe` tool with the above parameters. +Every time you run the `describe` tool, including automatic runs, the PR title will be generated by the AI. To cancel the automatic run of all the tools, set: ``` @@ -101,7 +101,7 @@ The configuration parameter `push_commands` defines the list of tools that will [github_app] handle_push_trigger = true push_commands = [ - "/describe --pr_description.add_original_user_description=true", + "/describe", "/review --pr_reviewer.num_code_suggestions=0 --pr_reviewer.final_update_message=false", ] ``` @@ -141,7 +141,7 @@ After setting up a GitLab webhook, to control which commands will run automatica ``` [gitlab] pr_commands = [ - "/describe --pr_description.add_original_user_description=true", + "/describe", "/review --pr_reviewer.num_code_suggestions=0", "/improve", ] @@ -201,7 +201,7 @@ To control which commands will run automatically when a new PR is opened, you ca ``` [azure_devops_server] pr_commands = [ - "/describe --pr_description.add_original_user_description=true", + "/describe", "/review --pr_reviewer.num_code_suggestions=0", "/improve", ] diff --git a/pr_agent/servers/github_app.py b/pr_agent/servers/github_app.py index f0d1340d..be141084 100644 --- a/pr_agent/servers/github_app.py +++ b/pr_agent/servers/github_app.py @@ -140,7 +140,7 @@ async def handle_new_pr_opened(body: Dict[str, Any], if not (pull_request and api_url): get_logger().info(f"Invalid PR event: {action=} {api_url=}") return {} - if action in get_settings().github_app.handle_pr_actions: # ['opened', 'reopened', 'ready_for_review', 'review_requested'] + if action in get_settings().github_app.handle_pr_actions: # ['opened', 'reopened', 'ready_for_review'] if get_identity_provider().verify_eligibility("github", sender_id, api_url) is not Eligibility.NOT_ELIGIBLE: await _perform_auto_commands_github("pr_commands", agent, body, api_url, log_context) else: diff --git a/pr_agent/servers/help.py b/pr_agent/servers/help.py index b37cedc3..07ade44c 100644 --- a/pr_agent/servers/help.py +++ b/pr_agent/servers/help.py @@ -68,9 +68,9 @@ some_config2=... output += """\ - When you first install the app, the [default mode](https://pr-agent-docs.codium.ai/usage-guide/automations_and_usage/#github-app-automatic-tools-when-a-new-pr-is-opened) for the describe tool is: ``` -pr_commands = ["/describe --pr_description.add_original_user_description=true ..."] +pr_commands = ["/describe", ...] ``` -meaning the `describe` tool will run automatically on every PR, and will add the original user description above the generated description. +meaning the `describe` tool will run automatically on every PR. - Markers are an alternative way to control the generated description, to give maximal control to the user. If you set: ``` diff --git a/pr_agent/settings/configuration.toml b/pr_agent/settings/configuration.toml index bd85b0fe..22ed6ccc 100644 --- a/pr_agent/settings/configuration.toml +++ b/pr_agent/settings/configuration.toml @@ -148,7 +148,7 @@ override_deployment_type = true # settings for "pull_request" event handle_pr_actions = ['opened', 'reopened', 'ready_for_review'] pr_commands = [ - "/describe --pr_description.add_original_user_description=true", + "/describe", "/review --pr_reviewer.num_code_suggestions=0", "/improve", ] @@ -160,7 +160,7 @@ push_trigger_wait_for_initial_review = true push_trigger_pending_tasks_backlog = true push_trigger_pending_tasks_ttl = 300 push_commands = [ - "/describe --pr_description.add_original_user_description=true", + "/describe", "/review --pr_reviewer.num_code_suggestions=0", ] ignore_pr_title = [] @@ -169,7 +169,7 @@ ignore_bot_pr = true [gitlab] url = "https://gitlab.com" # URL to the gitlab service pr_commands = [ - "/describe --pr_description.add_original_user_description=true", + "/describe", "/review --pr_reviewer.num_code_suggestions=0", "/improve", ] From f913f02ea6d5069d9f3b668777ab6f61854fa49b Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Thu, 18 Apr 2024 08:53:43 +0300 Subject: [PATCH 132/226] docs --- docs/docs/tools/describe.md | 6 ++-- docs/docs/tools/improve.md | 64 ++++++++++++++++++++++++++----------- docs/docs/tools/review.md | 6 ++-- 3 files changed, 51 insertions(+), 25 deletions(-) diff --git a/docs/docs/tools/describe.md b/docs/docs/tools/describe.md index dee6f204..756c6adc 100644 --- a/docs/docs/tools/describe.md +++ b/docs/docs/tools/describe.md @@ -8,7 +8,7 @@ The tool can be triggered automatically every time a new PR is [opened](../usage ## Example usage -### Manual invocation +### Manual triggering Invoke the tool manually by commenting `/describe` on any PR: @@ -23,7 +23,7 @@ If you want to edit [configurations](#configuration-options), add the relevant o /describe --pr_description.some_config1=... --pr_description.some_config2=... ``` -### Automatic invocation +### Automatic triggering To run the `describe` automatically when a PR is opened, define in a [configuration file](https://pr-agent-docs.codium.ai/usage-guide/configuration_options/#wiki-configuration-file): ``` @@ -39,7 +39,7 @@ publish_labels = ... ``` - The `pr_commands` lists commands that will be executed automatically when a PR is opened. -- The `[pr_description]` section contains the configurations for the `describe` tool you want to edit. +- The `[pr_description]` section contains the configurations for the `describe` tool you want to edit (if any). ## Configuration options diff --git a/docs/docs/tools/improve.md b/docs/docs/tools/improve.md index 2869b180..af4eae78 100644 --- a/docs/docs/tools/improve.md +++ b/docs/docs/tools/improve.md @@ -5,43 +5,51 @@ The tool can be triggered automatically every time a new PR is [opened](../usage /improve ``` -### Summarized vs committable code suggestions +## Example usage -The code suggestions can be presented as a single comment +### Manual triggering + +Invoke the tool manually by commenting `/improve` on any PR. The code suggestions by default are presented as a single comment: ![code suggestions as comment](https://codium.ai/images/pr_agent/code_suggestions_as_comment.png){width=512} -Or as a separate commitable code comment for each suggestion (via `pr_code_suggestions.commitable_code_suggestions=true`):: +To edit [configurations](#configuration-options) related to the improve tool, use the following template: +``` +/improve --pr_code_suggestions.some_config1=... --pr_code_suggestions.some_config2=... +``` -![imporove](https://codium.ai/images/pr_agent/improve.png){width=512} +For example, you can choose to present the suggestions as commitable code comments, by running the following command: +``` +/improve --pr_code_suggestions.commitable_code_suggestions=true +``` + +![improve](https://codium.ai/images/pr_agent/improve.png){width=512} Note that a single comment has a significantly smaller PR footprint. We recommend this mode for most cases. Also note that collapsible are not supported in _Bitbucket_. Hence, the suggestions are presented there as code comments. -### Extended mode +### Automatic triggering -An extended mode, which does not involve PR Compression and provides more comprehensive suggestions, can be invoked by commenting on any PR: -``` -/improve --extended +To run the `improve` automatically when a PR is opened, define in a [configuration file](https://pr-agent-docs.codium.ai/usage-guide/configuration_options/#wiki-configuration-file): ``` +[github_app] +pr_commands = [ + "/improve", + ... +] -or by setting: -``` [pr_code_suggestions] -auto_extended_mode=true +num_code_suggestions = ... +... ``` -(True by default). -Note that the extended mode divides the PR code changes into chunks, up to the token limits, where each chunk is handled separately (might use multiple calls to GPT-4 for large PRs). -Hence, the total number of suggestions is proportional to the number of chunks, i.e., the size of the PR. +- The `pr_commands` lists commands that will be executed automatically when a PR is opened. +- The `[pr_code_suggestions]` section contains the configurations for the `improve` tool you want to edit (if any) -### Configuration options -To edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/configuration.toml#L66) related to the improve tool (`pr_code_suggestions` section), use the following template: -``` -/improve --pr_code_suggestions.some_config1=... --pr_code_suggestions.some_config2=... -``` + +## Configuration options !!! example "General options" @@ -60,6 +68,24 @@ To edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agen - `max_number_of_calls`: maximum number of chunks. Default is 5. - `final_clip_factor`: factor to remove suggestions with low confidence. Default is 0.9.; +## Extended mode + +An extended mode, which does not involve PR Compression and provides more comprehensive suggestions, can be invoked by commenting on any PR: +``` +/improve --extended +``` + +or by setting: +``` +[pr_code_suggestions] +auto_extended_mode=true +``` +(True by default). + +Note that the extended mode divides the PR code changes into chunks, up to the token limits, where each chunk is handled separately (might use multiple calls to GPT-4 for large PRs). +Hence, the total number of suggestions is proportional to the number of chunks, i.e., the size of the PR. + + ## Usage Tips diff --git a/docs/docs/tools/review.md b/docs/docs/tools/review.md index 92a642f4..4c65c7b8 100644 --- a/docs/docs/tools/review.md +++ b/docs/docs/tools/review.md @@ -7,7 +7,7 @@ The tool can be triggered automatically every time a new PR is [opened](../usage ## Example usage -### Manual invocation +### Manual triggering Invoke the tool manually by commenting `/review` on any PR: @@ -22,7 +22,7 @@ If you want to edit [configurations](#configuration-options), add the relevant o /review --pr_reviewer.some_config1=... --pr_reviewer.some_config2=... ``` -### Automatic invocation +### Automatic triggering To run the `review` automatically when a PR is opened, define in a [configuration file](https://pr-agent-docs.codium.ai/usage-guide/configuration_options/#wiki-configuration-file): ``` @@ -38,7 +38,7 @@ num_code_suggestions = ... ``` - The `pr_commands` lists commands that will be executed automatically when a PR is opened. -- The `[pr_reviewer]` section contains the configurations for the `review` tool you want to edit. +- The `[pr_reviewer]` section contains the configurations for the `review` tool you want to edit (if any). ## Configuration options From 0f99db65a9f05a9fe3344c2966d9d074ef454fe3 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Thu, 18 Apr 2024 09:10:14 +0300 Subject: [PATCH 133/226] docs --- docs/docs/tools/ask.md | 3 ++- docs/docs/tools/review.md | 30 +++++++++++++++--------------- 2 files changed, 17 insertions(+), 16 deletions(-) diff --git a/docs/docs/tools/ask.md b/docs/docs/tools/ask.md index 0d477934..fca5b725 100644 --- a/docs/docs/tools/ask.md +++ b/docs/docs/tools/ask.md @@ -5,7 +5,8 @@ It can be invoked manually by commenting on any PR: ``` /ask "..." ``` -For example: + +## Example usage ![Ask Comment](https://codium.ai/images/pr_agent/ask_comment.png){width=512} diff --git a/docs/docs/tools/review.md b/docs/docs/tools/review.md index 4c65c7b8..2e5c4bb6 100644 --- a/docs/docs/tools/review.md +++ b/docs/docs/tools/review.md @@ -46,38 +46,38 @@ num_code_suggestions = ... ### General configurations !!! example "General options" - - `num_code_suggestions`: number of code suggestions provided by the 'review' tool. For manual comments, default is 4. For [PR-Agent app](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/configuration.toml#L142) auto tools, default is 0, meaning no code suggestions will be provided by the review tool, unless you manually edit `pr_commands`. - - `inline_code_comments`: if set to true, the tool will publish the code suggestions as comments on the code diff. Default is false. - - `persistent_comment`: if set to true, the review comment will be persistent, meaning that every new review request will edit the previous one. Default is true. - - `extra_instructions`: Optional extra instructions to the tool. For example: "focus on the changes in the file X. Ignore change in ...". - - `enable_help_text`: if set to true, the tool will display a help text in the comment. Default is true. + - <a name="num_code_suggestions"></a>`num_code_suggestions`: number of code suggestions provided by the 'review' tool. For manual comments, default is 4. For [PR-Agent app](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/configuration.toml#L142) auto tools, default is 0, meaning no code suggestions will be provided by the review tool, unless you manually edit `pr_commands`. + - <a name="inline_code_comments"></a>`inline_code_comments`: if set to true, the tool will publish the code suggestions as comments on the code diff. Default is false. + - <a name="persistent_comment"></a>`persistent_comment`: if set to true, the review comment will be persistent, meaning that every new review request will edit the previous one. Default is true. + - <a name="extra_instructions"></a>`extra_instructions`: Optional extra instructions to the tool. For example: "focus on the changes in the file X. Ignore change in ...". + - <a name="enable_help_text"></a>`enable_help_text`: if set to true, the tool will display a help text in the comment. Default is true. !!! example "Enable\\disable sub-sections" You can enable or disable specific sub-sections of the review tool: - - `require_score_review`: if set to true, the tool will add a section that scores the PR. Default is false. - - `require_tests_review`: if set to true, the tool will add a section that checks if the PR contains tests. Default is true. - - `require_estimate_effort_to_review`: if set to true, the tool will add a section that estimates the effort needed to review the PR. Default is true. - - `require_can_be_split_review`: if set to true, the tool will add a section that checks if the PR contains several themes, and can be split into smaller PRs. Default is false. + - <a name="require_score_review"></a>`require_score_review`: if set to true, the tool will add a section that scores the PR. Default is false. + - <a name="require_tests_review"></a>`require_tests_review`: if set to true, the tool will add a section that checks if the PR contains tests. Default is true. + - <a name="require_estimate_effort_to_review"></a>`require_estimate_effort_to_review`: if set to true, the tool will add a section that estimates the effort needed to review the PR. Default is true. + - <a name="require_can_be_split_review"></a>`require_can_be_split_review`: if set to true, the tool will add a section that checks if the PR contains several themes, and can be split into smaller PRs. Default is false. !!! example "SOC2 ticket compliance ๐Ÿ’Ž" This sub-tool checks if the PR description properly contains a ticket to a project management system (e.g., Jira, Asana, Trello, etc.), as required by SOC2 compliance. If not, it will add a label to the PR: "Missing SOC2 ticket". - - `require_soc2_ticket`: If set to true, the SOC2 ticket checker sub-tool will be enabled. Default is false. - - `soc2_ticket_prompt`: The prompt for the SOC2 ticket review. Default is: `Does the PR description include a link to ticket in a project management system (e.g., Jira, Asana, Trello, etc.) ?`. Edit this field if your compliance requirements are different. + - <a name="require_soc2_ticket"></a>`require_soc2_ticket`: If set to true, the SOC2 ticket checker sub-tool will be enabled. Default is false. + - <a name="soc2_ticket_prompt"></a>`soc2_ticket_prompt`: The prompt for the SOC2 ticket review. Default is: `Does the PR description include a link to ticket in a project management system (e.g., Jira, Asana, Trello, etc.) ?`. Edit this field if your compliance requirements are different. !!! example "Adding PR labels" You can enable the tool to add specific labels to the PR: - - `enable_review_labels_security`: if set to true, the tool will publish a 'possible security issue' label if it detects a security issue. Default is true. - - `enable_review_labels_effort`: if set to true, the tool will publish a 'Review effort [1-5]: x' label. Default is true. + - <a name="enable_review_labels_security"></a>`enable_review_labels_security`: if set to true, the tool will publish a 'possible security issue' label if it detects a security issue. Default is true. + - <a name="enable_review_labels_effort"></a>`enable_review_labels_effort`: if set to true, the tool will publish a 'Review effort [1-5]: x' label. Default is true. !!! example "Auto-approval" The review tool can approve a PR when a specific comment, `/review auto_approve` is invoked. - - `enable_auto_approval`: if set to true, the tool will approve the PR when invoked with the 'auto_approve' command. Default is false. This flag can be changed only from configuration file. - - `maximal_review_effort`: maximal effort level for auto-approval. If the PR's estimated review effort is above this threshold, the auto-approval will not run. Default is 5. + - <a name="enable_auto_approval"></a>`enable_auto_approval`: if set to true, the tool will approve the PR when invoked with the 'auto_approve' command. Default is false. This flag can be changed only from configuration file. + - <a name="maximal_review_effort"></a>`maximal_review_effort`: maximal effort level for auto-approval. If the PR's estimated review effort is above this threshold, the auto-approval will not run. Default is 5. ### Incremental Mode Incremental review only considers changes since the last PR-Agent review. This can be useful when working on the PR in an iterative manner, and you want to focus on the changes since the last review instead of reviewing the entire PR again. From ea4d4ab618bfd50b728f22ca34cbf4d6d84dae48 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Thu, 18 Apr 2024 10:04:38 +0300 Subject: [PATCH 134/226] ## Example usage --- docs/docs/tools/analyze.md | 1 + docs/docs/tools/ci_feedback.md | 2 ++ docs/docs/tools/custom_labels.md | 3 ++- docs/docs/tools/custom_suggestions.md | 25 +++++++++++++++---------- docs/docs/tools/documentation.md | 15 ++++++++++++--- docs/docs/tools/improve.md | 2 +- docs/docs/tools/improve_component.md | 7 ++++++- docs/docs/tools/similar_issues.md | 4 +++- docs/docs/tools/test.md | 8 +++++++- docs/docs/tools/update_changelog.md | 5 +++-- 10 files changed, 52 insertions(+), 20 deletions(-) diff --git a/docs/docs/tools/analyze.md b/docs/docs/tools/analyze.md index 7af0546e..68bf674b 100644 --- a/docs/docs/tools/analyze.md +++ b/docs/docs/tools/analyze.md @@ -9,6 +9,7 @@ It can be invoked manually by commenting on any PR: ``` ## Example usage + An example result: ![Analyze 1](https://codium.ai/images/pr_agent/analyze_1.png){width=750} diff --git a/docs/docs/tools/ci_feedback.md b/docs/docs/tools/ci_feedback.md index 998fef56..61115e7f 100644 --- a/docs/docs/tools/ci_feedback.md +++ b/docs/docs/tools/ci_feedback.md @@ -8,6 +8,8 @@ The tool analyzes the failed checks and provides several feedbacks: - Failure summary - Relevant error logs +## Example usage + ![Failed Check 1](https://www.codium.ai/images/pr_agent/failed_check1.png){width=768} → diff --git a/docs/docs/tools/custom_labels.md b/docs/docs/tools/custom_labels.md index 29f1a9e2..b9d85fa2 100644 --- a/docs/docs/tools/custom_labels.md +++ b/docs/docs/tools/custom_labels.md @@ -5,7 +5,8 @@ It can be invoked manually by commenting on any PR: ``` /generate_labels ``` -For example: + +## Example usage If we wish to add detect changes to SQL queries in a given PR, we can add the following custom label along with its description: diff --git a/docs/docs/tools/custom_suggestions.md b/docs/docs/tools/custom_suggestions.md index 85720c11..158ff398 100644 --- a/docs/docs/tools/custom_suggestions.md +++ b/docs/docs/tools/custom_suggestions.md @@ -1,13 +1,18 @@ ## Overview -The `custom_suggestions` tool scans the PR code changes, and automatically generates custom suggestions for improving the PR code. -It shares similarities with the `improve` tool, but with one main difference: the `custom_suggestions` tool will only propose suggestions that follow specific guidelines defined by the prompt in: `pr_custom_suggestions.prompt` configuration. +The `custom_suggestions` tool scans the PR code changes, and automatically generates suggestions for improving the PR code. +It shares similarities with the `improve` tool, but with one main difference: the `custom_suggestions` tool will **only propose suggestions that follow specific guidelines defined by the prompt** in: `pr_custom_suggestions.prompt` configuration. The tool can be triggered [automatically](../usage-guide/automations_and_usage.md#github-app-automatic-tools-when-a-new-pr-is-opened) every time a new PR is opened, or can be invoked manually by commenting on a PR. When commenting, use the following template: ``` -/custom_suggestions --pr_custom_suggestions.prompt="The suggestions should focus only on the following:\n-...\n-...\n-..." +/custom_suggestions --pr_custom_suggestions.prompt=" +The suggestions should focus only on the following: +- ... +- ... + +" ``` With a [configuration file](../usage-guide/automations_and_usage.md#github-app), use the following template: @@ -18,17 +23,16 @@ prompt="""\ The suggestions should focus only on the following: -... -... --... + """ ``` -Using a configuration file is recommended, since it allows to use multi-line instructions. -Don't forget - with this tool, you are the prompter. Be specific, clear, and concise in the instructions. Specify relevant aspects that you want the model to focus on. \ +Remmeber - with this tool, you are the prompter. Be specific, clear, and concise in the instructions. Specify relevant aspects that you want the model to focus on. \ You might benefit from several trial-and-error iterations, until you get the correct prompt for your use case. ## Example usage -Here is an example of a possible prompt: +Here is an example of a possible prompt, defined in the configuration file: ``` [pr_custom_suggestions] prompt="""\ @@ -39,12 +43,13 @@ The suggestions should focus only on the following: """ ``` -The instructions above are just an example. We want to emphasize that the prompt should be specific and clear, and be tailored to the needs of your project. +(The instructions above are just an example. We want to emphasize that the prompt should be specific and clear, and be tailored to the needs of your project) Results obtained with the prompt above: -![Custom suggestions prompt](https://codium.ai/images/pr_agent/custom_suggestions_prompt.png){width=512} -→ +[//]: # (![Custom suggestions prompt](https://codium.ai/images/pr_agent/custom_suggestions_prompt.png){width=512}) + +[//]: # (→) ![Custom suggestions results](https://codium.ai/images/pr_agent/custom_suggestions_result.png){width=768} ## Configuration options diff --git a/docs/docs/tools/documentation.md b/docs/docs/tools/documentation.md index 9c56386f..bb1330d1 100644 --- a/docs/docs/tools/documentation.md +++ b/docs/docs/tools/documentation.md @@ -5,14 +5,24 @@ It can be invoked manually by commenting on any PR: ``` /add_docs ``` -For example: + +## Example usage + +Invoke the tool manually by commenting `/add_docs` on any PR: ![Docs command](https://codium.ai/images/pr_agent/docs_command.png){width=768} +The tool will generate documentation for all the components that changed in the PR: + ![Docs component](https://codium.ai/images/pr_agent/docs_components.png){width=768} ![Docs single component](https://codium.ai/images/pr_agent/docs_single_component.png){width=768} +You can state a name of a specific component in the PR to get documentation only for that component: +``` +/add_docs component_name +``` + ## Configuration options - `docs_style`: The exact style of the documentation (for python docstring). you can choose between: `google`, `numpy`, `sphinx`, `restructuredtext`, `plain`. Default is `sphinx`. - `extra_instructions`: Optional extra instructions to the tool. For example: "focus on the changes in the file X. Ignore change in ...". @@ -20,5 +30,4 @@ For example: **Notes** - Language that are currently fully supported: Python, Java, C++, JavaScript, TypeScript, C#. -- For languages that are not fully supported, the tool will suggest documentation only for new components in the PR. -- A previous version of the tool, that offered support only for new components, was deprecated. \ No newline at end of file +- This tool can also be triggered interactively by using the [`analyze`](./analyze.md) tool. \ No newline at end of file diff --git a/docs/docs/tools/improve.md b/docs/docs/tools/improve.md index af4eae78..5980b955 100644 --- a/docs/docs/tools/improve.md +++ b/docs/docs/tools/improve.md @@ -56,7 +56,7 @@ num_code_suggestions = ... - `num_code_suggestions`: number of code suggestions provided by the 'improve' tool. Default is 4 for CLI, 0 for auto tools. - `extra_instructions`: Optional extra instructions to the tool. For example: "focus on the changes in the file X. Ignore change in ...". - `rank_suggestions`: if set to true, the tool will rank the suggestions, based on importance. Default is false. - - `summarize`: if set to true, the tool will display the suggestions in a single comment. Default is true. + - `commitable_code_suggestions`: if set to true, the tool will display the suggestions as commitable code comments. Default is false. - `persistent_comment`: if set to true, the improve comment will be persistent, meaning that every new improve request will edit the previous one. Default is false. - `enable_help_text`: if set to true, the tool will display a help text in the comment. Default is true. diff --git a/docs/docs/tools/improve_component.md b/docs/docs/tools/improve_component.md index 321114b4..4e0c8890 100644 --- a/docs/docs/tools/improve_component.md +++ b/docs/docs/tools/improve_component.md @@ -8,14 +8,19 @@ it can be invoked manually by commenting on any PR: To get a list of the components that changed in the PR and choose the relevant component interactively, use the [`analyze`](./analyze.md) tool. -Example result: +## Example usage + +Invoke the tool manually by commenting `/improve_component` on any PR: ![improve_component1](https://codium.ai/images/pr_agent/improve_component1.png){width=768} +The tool will generate code suggestions for the selected component (if no component is stated, it will generate code suggestions for the largest component): + ![improve_component2](https://codium.ai/images/pr_agent/improve_component2.png){width=768} **Notes** - Language that are currently supported by the tool: Python, Java, C++, JavaScript, TypeScript, C#. +- This tool can also be triggered interactively by using the [`analyze`](./analyze.md) tool. ## Configuration options - `num_code_suggestions`: number of code suggestions to provide. Default is 4 diff --git a/docs/docs/tools/similar_issues.md b/docs/docs/tools/similar_issues.md index 239b4e90..b73adc64 100644 --- a/docs/docs/tools/similar_issues.md +++ b/docs/docs/tools/similar_issues.md @@ -4,7 +4,9 @@ It can be invoked manually by commenting on any PR: ``` /similar_issue ``` -For example: + + +## Example usage ![similar_issue_original_issue](https://codium.ai/images/pr_agent/similar_issue_original_issue.png){width=768} diff --git a/docs/docs/tools/test.md b/docs/docs/tools/test.md index 52e447ce..dc93e55c 100644 --- a/docs/docs/tools/test.md +++ b/docs/docs/tools/test.md @@ -7,17 +7,23 @@ It can be invoked manually by commenting on any PR: where 'component_name' is the name of a specific component in the PR. To get a list of the components that changed in the PR and choose the relevant component interactively, use the [`analyze`](./analyze.md) tool. +## Example usage -An example [result](https://github.com/Codium-ai/pr-agent/pull/598#issuecomment-1913679429): +Invoke the tool manually by commenting `/test` on any PR: ![test1](https://codium.ai/images/pr_agent/test1.png){width=704} +The tool will generate tests for the selected component (if no component is stated, it will generate tests for largest component): + ![test2](https://codium.ai/images/pr_agent/test2.png){width=768} ![test3](https://codium.ai/images/pr_agent/test3.png){width=768} +(Example taken from [here](https://github.com/Codium-ai/pr-agent/pull/598#issuecomment-1913679429)): + **Notes** - Language that are currently supported by the tool: Python, Java, C++, JavaScript, TypeScript, C#. +- This tool can also be triggered interactively by using the [`analyze`](./analyze.md) tool. ## Configuration options diff --git a/docs/docs/tools/update_changelog.md b/docs/docs/tools/update_changelog.md index 4f4de235..0c1bfda5 100644 --- a/docs/docs/tools/update_changelog.md +++ b/docs/docs/tools/update_changelog.md @@ -4,7 +4,8 @@ It can be invoked manually by commenting on any PR: ``` /update_changelog ``` -For example: + +## Example usage ![update_changelog_comment](https://codium.ai/images/pr_agent/update_changelog_comment.png){width=768} @@ -12,7 +13,7 @@ For example: ## Configuration options -Under the section 'pr_update_changelog', the [configuration file](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/configuration.toml#L50) contains options to customize the 'update changelog' tool: +Under the section `pr_update_changelog`, the [configuration file](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/configuration.toml#L50) contains options to customize the 'update changelog' tool: - `push_changelog_changes`: whether to push the changes to CHANGELOG.md, or just print them. Default is false (print only). - `extra_instructions`: Optional extra instructions to the tool. For example: "focus on the changes in the file X. Ignore change in ... \ No newline at end of file From a9d30c1d106a6afe168271e46053407a1830495d Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Thu, 18 Apr 2024 10:11:19 +0300 Subject: [PATCH 135/226] Remember --- docs/docs/tools/custom_suggestions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/tools/custom_suggestions.md b/docs/docs/tools/custom_suggestions.md index 158ff398..902a4d25 100644 --- a/docs/docs/tools/custom_suggestions.md +++ b/docs/docs/tools/custom_suggestions.md @@ -27,7 +27,7 @@ The suggestions should focus only on the following: """ ``` -Remmeber - with this tool, you are the prompter. Be specific, clear, and concise in the instructions. Specify relevant aspects that you want the model to focus on. \ +Remember - with this tool, you are the prompter. Be specific, clear, and concise in the instructions. Specify relevant aspects that you want the model to focus on. \ You might benefit from several trial-and-error iterations, until you get the correct prompt for your use case. ## Example usage From 1c8aeb2b647cefc335c8c545a45df8d33927cfc4 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Thu, 18 Apr 2024 16:31:41 +0300 Subject: [PATCH 136/226] docs: Add option to disable automatic CI feedback in configuration --- docs/docs/tools/ci_feedback.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/docs/tools/ci_feedback.md b/docs/docs/tools/ci_feedback.md index 61115e7f..10f024fa 100644 --- a/docs/docs/tools/ci_feedback.md +++ b/docs/docs/tools/ci_feedback.md @@ -23,6 +23,14 @@ In addition to being automatically triggered, the tool can also be invoked manua ``` where `{repo_name}` is the name of the repository, `{run_number}` is the run number of the failed check, and `{job_number}` is the job number of the failed check. +## Disabling the tool from running automatically + +If you wish to disable the tool from running automatically, you can do so by adding the following configuration to the configuration file: +``` +[checks] +enable_auto_checks_feedback = false +``` + ## Configuration options - `enable_auto_checks_feedback` - if set to true, the tool will automatically provide feedback when a check is failed. Default is true. - `excluded_checks_list` - a list of checks to exclude from the feedback, for example: ["check1", "check2"]. Default is an empty list. From 7a9e73702d9342e39e4ca5c17c979275347de726 Mon Sep 17 00:00:00 2001 From: "Randy, Huang" <gg875437@gmail.com> Date: Sun, 21 Apr 2024 14:47:25 +0900 Subject: [PATCH 137/226] Fix duplicate assignment of replicate_key in LiteLLMAIHandler --- pr_agent/algo/ai_handlers/litellm_ai_handler.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/pr_agent/algo/ai_handlers/litellm_ai_handler.py b/pr_agent/algo/ai_handlers/litellm_ai_handler.py index 4acd55ea..76e1639e 100644 --- a/pr_agent/algo/ai_handlers/litellm_ai_handler.py +++ b/pr_agent/algo/ai_handlers/litellm_ai_handler.py @@ -54,8 +54,6 @@ class LiteLLMAIHandler(BaseAiHandler): litellm.cohere_key = get_settings().cohere.key if get_settings().get("REPLICATE.KEY", None): litellm.replicate_key = get_settings().replicate.key - if get_settings().get("REPLICATE.KEY", None): - litellm.replicate_key = get_settings().replicate.key if get_settings().get("HUGGINGFACE.KEY", None): litellm.huggingface_key = get_settings().huggingface.key if get_settings().get("HUGGINGFACE.API_BASE", None) and 'huggingface' in get_settings().config.model: From 0a53f09a7f9721811685ab77e961c1403fd973bd Mon Sep 17 00:00:00 2001 From: "Randy, Huang" <gg875437@gmail.com> Date: Sun, 21 Apr 2024 15:21:45 +0900 Subject: [PATCH 138/226] Add GROQ.KEY support in LiteLLMAIHandler --- pr_agent/algo/__init__.py | 2 ++ pr_agent/algo/ai_handlers/litellm_ai_handler.py | 2 ++ 2 files changed, 4 insertions(+) diff --git a/pr_agent/algo/__init__.py b/pr_agent/algo/__init__.py index 1357db29..484ed045 100644 --- a/pr_agent/algo/__init__.py +++ b/pr_agent/algo/__init__.py @@ -31,4 +31,6 @@ MAX_TOKENS = { 'bedrock/anthropic.claude-v2:1': 100000, 'bedrock/anthropic.claude-3-sonnet-20240229-v1:0': 100000, 'bedrock/anthropic.claude-3-haiku-20240307-v1:0': 100000, + 'groq/llama3-8b-8192': 8192, + 'groq/llama3-70b-8192': 8192, } diff --git a/pr_agent/algo/ai_handlers/litellm_ai_handler.py b/pr_agent/algo/ai_handlers/litellm_ai_handler.py index 4acd55ea..a7b2497d 100644 --- a/pr_agent/algo/ai_handlers/litellm_ai_handler.py +++ b/pr_agent/algo/ai_handlers/litellm_ai_handler.py @@ -52,6 +52,8 @@ class LiteLLMAIHandler(BaseAiHandler): litellm.anthropic_key = get_settings().anthropic.key if get_settings().get("COHERE.KEY", None): litellm.cohere_key = get_settings().cohere.key + if get_settings().get("GROQ.KEY", None): + litellm.api_key = get_settings().groq.key if get_settings().get("REPLICATE.KEY", None): litellm.replicate_key = get_settings().replicate.key if get_settings().get("REPLICATE.KEY", None): From d430604dfe8598854f5c486ad1b342ce3fa46796 Mon Sep 17 00:00:00 2001 From: "Randy, Huang" <gg875437@gmail.com> Date: Sun, 21 Apr 2024 15:22:19 +0900 Subject: [PATCH 139/226] Add Groq Llama3 model configuration instructions to usage guide --- docs/docs/usage-guide/additional_configurations.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/docs/docs/usage-guide/additional_configurations.md b/docs/docs/usage-guide/additional_configurations.md index e1128817..8785a580 100644 --- a/docs/docs/usage-guide/additional_configurations.md +++ b/docs/docs/usage-guide/additional_configurations.md @@ -125,6 +125,19 @@ key = ... Also, review the [AiHandler](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/algo/ai_handler.py) file for instructions on how to set keys for other models. +### Groq + +To use Llama3 model with Groq, for example, set: +``` +[config] # in configuration.toml +model = "llama3-70b-8192" +model_turbo = "llama3-70b-8192" +fallback_models = ["groq/llama3-70b-8192"] +[groq] # in .secrets.toml +key = ... # your Groq api key +``` +(you can obtain a Groq key from [here](https://console.groq.com/keys)) + ### Vertex AI To use Google's Vertex AI platform and its associated models (chat-bison/codechat-bison) set: From d457fa2b9feaa965618955cd597a845e65da9a6d Mon Sep 17 00:00:00 2001 From: "Randy, Huang" <gg875437@gmail.com> Date: Sun, 21 Apr 2024 15:22:40 +0900 Subject: [PATCH 140/226] Add Groq API key configuration to .secrets_template.toml --- pr_agent/settings/.secrets_template.toml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/pr_agent/settings/.secrets_template.toml b/pr_agent/settings/.secrets_template.toml index 8735d962..b5aa352f 100644 --- a/pr_agent/settings/.secrets_template.toml +++ b/pr_agent/settings/.secrets_template.toml @@ -29,6 +29,9 @@ key = "" # Optional, uncomment if you want to use Cohere. Acquire through https: [replicate] key = "" # Optional, uncomment if you want to use Replicate. Acquire through https://replicate.com/ +[groq] +key = "" # Acquire through https://console.groq.com/keys + [huggingface] key = "" # Optional, uncomment if you want to use Huggingface Inference API. Acquire through https://huggingface.co/docs/api-inference/quicktour api_base = "" # the base url for your huggingface inference endpoint From 2e344365896dce4e6c694456ca77ff91b5c19fa8 Mon Sep 17 00:00:00 2001 From: tacascer <trandangtrithanh2000@gmail.com> Date: Mon, 22 Apr 2024 20:25:32 -0400 Subject: [PATCH 141/226] chore: update GPT3.5 models --- pr_agent/algo/__init__.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/pr_agent/algo/__init__.py b/pr_agent/algo/__init__.py index 484ed045..cab47378 100644 --- a/pr_agent/algo/__init__.py +++ b/pr_agent/algo/__init__.py @@ -1,8 +1,9 @@ MAX_TOKENS = { 'text-embedding-ada-002': 8000, - 'gpt-3.5-turbo': 4000, + 'gpt-3.5-turbo': 16000, + 'gpt-3.5-turbo-0125': 16000, 'gpt-3.5-turbo-0613': 4000, - 'gpt-3.5-turbo-0301': 4000, + 'gpt-3.5-turbo-1106': 16000, 'gpt-3.5-turbo-16k': 16000, 'gpt-3.5-turbo-16k-0613': 16000, 'gpt-4': 8000, From 0b10f88b84b19dfe3ee742128a6a8845bc6ee983 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Thu, 2 May 2024 21:08:12 +0300 Subject: [PATCH 142/226] toolbar --- README.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/README.md b/README.md index 43ce7efc..d6cd3074 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,17 @@ CodiumAI PR-Agent aims to help efficiently review and handle pull requests, by p ## News and Updates +### May 2, 2024 +Check out the new [PR-Agent Chrome Extension](https://www.youtube.com/watch?v=gT5tli7X4H4) ๐Ÿš€๐Ÿš€๐Ÿš€ + +This toolbar integrates seamlessly with your GitHub environment, allowing you to access and configure PR-Agent tools directly from the GitHub interface. + +<kbd><img src="https://codium.ai/images/pr_agent/toolbar1.png" width="512"></kbd> + +<kbd><img src="https://codium.ai/images/pr_agent/toolbar2.png" width="512"></kbd> + + + ### April 14, 2024 You can now ask questions about images that appear in the comment, where the entire PR is considered as the context. see [here](https://pr-agent-docs.codium.ai/tools/ask/#ask-on-images) for more details. From 92cde2ef9996788f1097793c9f9676272e59c2b3 Mon Sep 17 00:00:00 2001 From: Tal <tal.r@codium.ai> Date: Fri, 3 May 2024 08:32:39 +0300 Subject: [PATCH 143/226] Update README.md --- README.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index d6cd3074..fd4e2451 100644 --- a/README.md +++ b/README.md @@ -41,16 +41,15 @@ CodiumAI PR-Agent aims to help efficiently review and handle pull requests, by p ## News and Updates ### May 2, 2024 -Check out the new [PR-Agent Chrome Extension](https://www.youtube.com/watch?v=gT5tli7X4H4) ๐Ÿš€๐Ÿš€๐Ÿš€ +Check out the new [PR-Agent Chrome Extension](https://chromewebstore.google.com/detail/pr-agent-chrome-extension/ephlnjeghhogofkifjloamocljapahnl]) ๐Ÿš€๐Ÿš€๐Ÿš€ -This toolbar integrates seamlessly with your GitHub environment, allowing you to access and configure PR-Agent tools directly from the GitHub interface. +This toolbar integrates seamlessly with your GitHub environment, allowing you to access and configure PR-Agent tools [directly from the GitHub interface]((https://www.youtube.com/watch?v=gT5tli7X4H4)). <kbd><img src="https://codium.ai/images/pr_agent/toolbar1.png" width="512"></kbd> <kbd><img src="https://codium.ai/images/pr_agent/toolbar2.png" width="512"></kbd> - ### April 14, 2024 You can now ask questions about images that appear in the comment, where the entire PR is considered as the context. see [here](https://pr-agent-docs.codium.ai/tools/ask/#ask-on-images) for more details. From 3c76230f612a1edbcf744e5691fb03bf009da484 Mon Sep 17 00:00:00 2001 From: Tal <tal.r@codium.ai> Date: Fri, 3 May 2024 14:52:19 +0300 Subject: [PATCH 144/226] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index fd4e2451..4a8c02eb 100644 --- a/README.md +++ b/README.md @@ -41,9 +41,10 @@ CodiumAI PR-Agent aims to help efficiently review and handle pull requests, by p ## News and Updates ### May 2, 2024 -Check out the new [PR-Agent Chrome Extension](https://chromewebstore.google.com/detail/pr-agent-chrome-extension/ephlnjeghhogofkifjloamocljapahnl]) ๐Ÿš€๐Ÿš€๐Ÿš€ +Check out the new [PR-Agent Chrome Extension](https://chromewebstore.google.com/detail/pr-agent-chrome-extension/ephlnjeghhogofkifjloamocljapahnl) ๐Ÿš€๐Ÿš€๐Ÿš€ -This toolbar integrates seamlessly with your GitHub environment, allowing you to access and configure PR-Agent tools [directly from the GitHub interface]((https://www.youtube.com/watch?v=gT5tli7X4H4)). +This toolbar integrates seamlessly with your GitHub environment, allowing you to access PR-Agent tools [directly from the GitHub interface](https://www.youtube.com/watch?v=gT5tli7X4H4). +You can also easily export your chosen configuration, and use it for the automatic commands. <kbd><img src="https://codium.ai/images/pr_agent/toolbar1.png" width="512"></kbd> From 34ad5f2aa29bea735c60d94f06d4dd179a509217 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sun, 5 May 2024 13:33:54 +0300 Subject: [PATCH 145/226] toolbar emojis in pr-agent feedbacks --- pr_agent/algo/utils.py | 8 ++++---- pr_agent/git_providers/git_provider.py | 6 +++--- pr_agent/servers/help.py | 2 +- pr_agent/settings/configuration.toml | 8 ++++---- pr_agent/tools/pr_code_suggestions.py | 10 +++++----- pr_agent/tools/pr_description.py | 10 +++++++--- pr_agent/tools/pr_questions.py | 6 +++--- pr_agent/tools/pr_reviewer.py | 4 ++-- pr_agent/tools/pr_update_changelog.py | 4 ++-- tests/unittest/test_convert_to_markdown.py | 2 +- 10 files changed, 32 insertions(+), 28 deletions(-) diff --git a/pr_agent/algo/utils.py b/pr_agent/algo/utils.py index a3fd82bd..b877106d 100644 --- a/pr_agent/algo/utils.py +++ b/pr_agent/algo/utils.py @@ -68,11 +68,11 @@ def convert_to_markdown(output_data: dict, gfm_supported: bool = True, increment output_data (dict): A dictionary containing data to be converted to markdown format. Returns: str: The markdown formatted text generated from the input dictionary. - """ + """ emojis = { "Can be split": "๐Ÿ”€", - "Possible issues": "๐Ÿ”", + "Possible issues": "โšก", "Score": "๐Ÿ…", "Relevant tests": "๐Ÿงช", "Focused PR": "โœจ", @@ -83,9 +83,9 @@ def convert_to_markdown(output_data: dict, gfm_supported: bool = True, increment } markdown_text = "" if not incremental_review: - markdown_text += f"## PR Review\n\n" + markdown_text += f"## PR Review ๐Ÿ”\n\n" else: - markdown_text += f"## Incremental PR Review\n\n" + markdown_text += f"## Incremental PR Review ๐Ÿ” \n\n" markdown_text += f"โฎ๏ธ Review for commits since previous PR-Agent review {incremental_review}.\n\n" if gfm_supported: markdown_text += "<table>\n<tr>\n" diff --git a/pr_agent/git_providers/git_provider.py b/pr_agent/git_providers/git_provider.py index a7d772b7..0ff5caf1 100644 --- a/pr_agent/git_providers/git_provider.py +++ b/pr_agent/git_providers/git_provider.py @@ -71,7 +71,7 @@ class GitProvider(ABC): # if the existing description was generated by the pr-agent, but it doesn't contain a user description, # return nothing (empty string) because it means there is no user description - user_description_header = "## **user description**" + user_description_header = "### **user description**" if user_description_header not in description_lowercase: get_logger().info(f"Existing description was generated by the pr-agent, but it doesn't contain a user description") return "" @@ -102,8 +102,8 @@ class GitProvider(ABC): return original_user_description def _possible_headers(self): - return ("## **user description**", "## **pr type**", "## **pr description**", "## **pr labels**", "## **type**", "## **description**", - "## **labels**", "### ๐Ÿค– generated by pr agent") + return ("### **user description**", "### **pr type**", "### **pr description**", "### **pr labels**", "### **type**", "### **description**", + "### **labels**", "### ๐Ÿค– generated by pr agent") def _is_generated_by_pr_agent(self, description_lowercase: str) -> bool: possible_headers = self._possible_headers() diff --git a/pr_agent/servers/help.py b/pr_agent/servers/help.py index 07ade44c..5578fb0f 100644 --- a/pr_agent/servers/help.py +++ b/pr_agent/servers/help.py @@ -179,7 +179,7 @@ You can ask questions about the entire PR, about specific code lines, or about a @staticmethod def get_improve_usage_guide(): output = "**Overview:**\n" - output += "The `improve` tool scans the PR code changes, and automatically generates suggestions for improving the PR code. " + output += "The code suggestions tool, named `improve`, scans the PR code changes, and automatically generates code suggestions for improving the PR." output += "The tool can be triggered [automatically](https://pr-agent-docs.codium.ai/usage-guide/automations_and_usage/#github-app-automatic-tools-when-a-new-pr-is-opened) every time a new PR is opened, or can be invoked manually by commenting on a PR.\n" output += """\ - When commenting, to edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/configuration.toml#L78) related to the improve tool (`pr_code_suggestions` section), use the following template: diff --git a/pr_agent/settings/configuration.toml b/pr_agent/settings/configuration.toml index 22ed6ccc..b2c65a3d 100644 --- a/pr_agent/settings/configuration.toml +++ b/pr_agent/settings/configuration.toml @@ -44,7 +44,7 @@ enable_review_labels_effort=true require_all_thresholds_for_incremental_review=false minimal_commits_for_incremental_review=0 minimal_minutes_for_incremental_review=0 -enable_help_text=true # Determines whether to include help text in the PR review. Enabled by default. +enable_help_text=false # Determines whether to include help text in the PR review. Enabled by default. # auto approval enable_auto_approval=false maximal_review_effort=5 @@ -74,7 +74,7 @@ include_generated_by_header=true #custom_labels = ['Bug fix', 'Tests', 'Bug fix with tests', 'Enhancement', 'Documentation', 'Other'] [pr_questions] # /ask # -enable_help_text=true +enable_help_text=false [pr_code_suggestions] # /improve # @@ -83,7 +83,7 @@ num_code_suggestions=4 commitable_code_suggestions = false extra_instructions = "" rank_suggestions = false -enable_help_text=true +enable_help_text=false persistent_comment=false # params for '/improve --extended' mode auto_extended_mode=true @@ -110,7 +110,7 @@ num_tests=3 # number of tests to generate. max 5. avoid_mocks=true # if true, the generated tests will prefer to use real objects instead of mocks file = "" # in case there are several components with the same name, you can specify the relevant file class_name = "" # in case there are several methods with the same name in the same file, you can specify the relevant class name -enable_help_text=true +enable_help_text=false [pr_improve_component] # /improve_component # num_code_suggestions=4 diff --git a/pr_agent/tools/pr_code_suggestions.py b/pr_agent/tools/pr_code_suggestions.py index 813ccbfa..ff4eb96f 100644 --- a/pr_agent/tools/pr_code_suggestions.py +++ b/pr_agent/tools/pr_code_suggestions.py @@ -90,7 +90,7 @@ class PRCodeSuggestions: if (not data) or (not 'code_suggestions' in data) or (not data['code_suggestions']): get_logger().error('No code suggestions found for PR.') - pr_body = "## PR Code Suggestions\n\nNo code suggestions found for PR." + pr_body = "## PR Code Suggestions โœจ\n\nNo code suggestions found for PR." get_logger().debug(f"PR output", artifact=pr_body) if self.progress_response: self.git_provider.edit_comment(self.progress_response, body=pr_body) @@ -113,14 +113,14 @@ class PRCodeSuggestions: # add usage guide if get_settings().pr_code_suggestions.enable_help_text: - pr_body += "<hr>\n\n<details> <summary><strong>โœจ Improve tool usage guide:</strong></summary><hr> \n\n" + pr_body += "<hr>\n\n<details> <summary><strong>๐Ÿ’ก Tool usage guide:</strong></summary><hr> \n\n" pr_body += HelpMessage.get_improve_usage_guide() pr_body += "\n</details>\n" if get_settings().pr_code_suggestions.persistent_comment: final_update_message = False self.git_provider.publish_persistent_comment(pr_body, - initial_header="## PR Code Suggestions", + initial_header="## PR Code Suggestions โœจ", update_header=True, name="suggestions", final_update_message=final_update_message, ) @@ -382,7 +382,7 @@ class PRCodeSuggestions: def generate_summarized_suggestions(self, data: Dict) -> str: try: - pr_body = "## PR Code Suggestions\n\n" + pr_body = "## PR Code Suggestions โœจ\n\n" if len(data.get('code_suggestions', [])) == 0: pr_body += "No suggestions found to improve this PR." @@ -394,7 +394,7 @@ class PRCodeSuggestions: for ext in extensions: extension_to_language[ext] = language - pr_body = "## PR Code Suggestions\n\n" + pr_body = "## PR Code Suggestions โœจ\n\n" pr_body += "<table>" header = f"Suggestions" diff --git a/pr_agent/tools/pr_description.py b/pr_agent/tools/pr_description.py index fa662464..661d9dd8 100644 --- a/pr_agent/tools/pr_description.py +++ b/pr_agent/tools/pr_description.py @@ -113,7 +113,7 @@ class PRDescription: pr_body += HelpMessage.get_describe_usage_guide() pr_body += "\n</details>\n" elif get_settings().pr_description.enable_help_comment: - pr_body += "\n\n___\n\n> โœจ **PR-Agent usage**:" + pr_body += "\n\n___\n\n> ๐Ÿ’ก **PR-Agent usage**:" pr_body += "\n>Comment `/help` on the PR to get a list of all available PR-Agent tools and their descriptions\n\n" if get_settings().config.publish_output: @@ -317,7 +317,11 @@ class PRDescription: value = self.file_label_dict else: key_publish = key.rstrip(':').replace("_", " ").capitalize() - pr_body += f"## **{key_publish}**\n" + if key_publish== "Type": + key_publish = "PR Type" + # elif key_publish == "Description": + # key_publish = "PR Description" + pr_body += f"### **{key_publish}**\n" if 'walkthrough' in key.lower(): if self.git_provider.is_supported("gfm_markdown"): pr_body += "<details> <summary>files:</summary>\n\n" @@ -329,7 +333,7 @@ class PRDescription: pr_body += "</details>\n" elif 'pr_files' in key.lower(): changes_walkthrough, pr_file_changes = self.process_pr_files_prediction(changes_walkthrough, value) - changes_walkthrough = f"## **Changes walkthrough**\n{changes_walkthrough}" + changes_walkthrough = f"### **Changes walkthrough** ๐Ÿ“\n{changes_walkthrough}" else: # if the value is a list, join its items by comma if isinstance(value, list): diff --git a/pr_agent/tools/pr_questions.py b/pr_agent/tools/pr_questions.py index d78d0880..78db1452 100644 --- a/pr_agent/tools/pr_questions.py +++ b/pr_agent/tools/pr_questions.py @@ -68,7 +68,7 @@ class PRQuestions: get_logger().debug(f"PR output", artifact=pr_comment) if self.git_provider.is_supported("gfm_markdown") and get_settings().pr_questions.enable_help_text: - pr_comment += "<hr>\n\n<details> <summary><strong>โœจ Ask tool usage guide:</strong></summary><hr> \n\n" + pr_comment += "<hr>\n\n<details> <summary><strong>๐Ÿ’ก Tool usage guide:</strong></summary><hr> \n\n" pr_comment += HelpMessage.get_ask_usage_guide() pr_comment += "\n</details>\n" @@ -116,6 +116,6 @@ class PRQuestions: return response def _prepare_pr_answer(self) -> str: - answer_str = f"Question: {self.question_str}\n\n" - answer_str += f"Answer:\n{self.prediction.strip()}\n\n" + answer_str = f"### **Ask**โ“\n{self.question_str}\n\n" + answer_str += f"### **Answer:**\n{self.prediction.strip()}\n\n" return answer_str diff --git a/pr_agent/tools/pr_reviewer.py b/pr_agent/tools/pr_reviewer.py index 33149cad..46036816 100644 --- a/pr_agent/tools/pr_reviewer.py +++ b/pr_agent/tools/pr_reviewer.py @@ -137,7 +137,7 @@ class PRReviewer: if get_settings().pr_reviewer.persistent_comment and not self.incremental.is_incremental: final_update_message = get_settings().pr_reviewer.final_update_message self.git_provider.publish_persistent_comment(pr_review, - initial_header="## PR Review", + initial_header="## PR Review ๐Ÿ”", update_header=True, final_update_message=final_update_message, ) else: @@ -234,7 +234,7 @@ class PRReviewer: # Add help text if gfm_markdown is supported if self.git_provider.is_supported("gfm_markdown") and get_settings().pr_reviewer.enable_help_text: - markdown_text += "<hr>\n\n<details> <summary><strong>โœจ Review tool usage guide:</strong></summary><hr> \n\n" + markdown_text += "<hr>\n\n<details> <summary><strong>๐Ÿ’ก Tool usage guide:</strong></summary><hr> \n\n" markdown_text += HelpMessage.get_review_usage_guide() markdown_text += "\n</details>\n" diff --git a/pr_agent/tools/pr_update_changelog.py b/pr_agent/tools/pr_update_changelog.py index 399e0599..1475d9f2 100644 --- a/pr_agent/tools/pr_update_changelog.py +++ b/pr_agent/tools/pr_update_changelog.py @@ -81,7 +81,7 @@ class PRUpdateChangelog: if self.commit_changelog: self._push_changelog_update(new_file_content, answer) else: - self.git_provider.publish_comment(f"**Changelog updates:**\n\n{answer}") + self.git_provider.publish_comment(f"**Changelog updates:** ๐Ÿ”„\n\n{answer}") async def _prepare_prediction(self, model: str): self.patches_diff = get_pr_diff(self.git_provider, self.token_handler, model) @@ -141,7 +141,7 @@ class PRUpdateChangelog: self.git_provider.pr.create_review(commit=last_commit_id, comments=[d]) except Exception: # we can't create a review for some reason, let's just publish a comment - self.git_provider.publish_comment(f"**Changelog updates:**\n\n{answer}") + self.git_provider.publish_comment(f"**Changelog updates: ๐Ÿ”„**\n\n{answer}") def _get_default_changelog(self): example_changelog = \ diff --git a/tests/unittest/test_convert_to_markdown.py b/tests/unittest/test_convert_to_markdown.py index 9b071a74..ad8f4973 100644 --- a/tests/unittest/test_convert_to_markdown.py +++ b/tests/unittest/test_convert_to_markdown.py @@ -52,7 +52,7 @@ class TestConvertToMarkdown: 'suggestion': "Consider raising an exception or logging a warning when 'pr_url' attribute is not found. This can help in debugging issues related to the absence of 'pr_url' in instances where it's expected. [important]\n", 'relevant_line': '[return ""](https://github.com/Codium-ai/pr-agent-pro/pull/102/files#diff-52d45f12b836f77ed1aef86e972e65404634ea4e2a6083fb71a9b0f9bb9e062fR199)'}]} - expected_output = '## PR Review\n\n<table>\n<tr>\n<tr><td> โฑ๏ธ <strong>Estimated effort to review [1-5]</strong></td><td>\n\n1, because the changes are minimal and straightforward, focusing on a single functionality addition.\n\n\n</td></tr>\n<tr><td> ๐Ÿงช <strong>Relevant tests</strong></td><td>\n\nNo\n\n\n</td></tr>\n<tr><td> ๐Ÿ” <strong>Possible issues</strong></td><td>\n\nNo\n\n</td></tr>\n<tr><td> ๐Ÿ”’ <strong>Security concerns</strong></td><td>\n\nNo\n\n</td></tr>\n</table>\n\n\n<details><summary> <strong>Code feedback:</strong></summary>\n\n<hr><table><tr><td>relevant file</td><td>pr_agent/git_providers/git_provider.py\n</td></tr><tr><td>suggestion      </td><td>\n\n<strong>\n\nConsider raising an exception or logging a warning when \'pr_url\' attribute is not found. This can help in debugging issues related to the absence of \'pr_url\' in instances where it\'s expected. [important]\n\n</strong>\n</td></tr><tr><td>relevant line</td><td><a href=\'https://github.com/Codium-ai/pr-agent-pro/pull/102/files#diff-52d45f12b836f77ed1aef86e972e65404634ea4e2a6083fb71a9b0f9bb9e062fR199\'>return ""</a></td></tr></table><hr>\n\n</details>' + expected_output = '## PR Review ๐Ÿ”\n\n<table>\n<tr>\n<tr><td> โฑ๏ธ <strong>Estimated effort to review [1-5]</strong></td><td>\n\n1, because the changes are minimal and straightforward, focusing on a single functionality addition.\n\n\n</td></tr>\n<tr><td> ๐Ÿงช <strong>Relevant tests</strong></td><td>\n\nNo\n\n\n</td></tr>\n<tr><td> ๐Ÿ” <strong>Possible issues</strong></td><td>\n\nNo\n\n</td></tr>\n<tr><td> ๐Ÿ”’ <strong>Security concerns</strong></td><td>\n\nNo\n\n</td></tr>\n</table>\n\n\n<details><summary> <strong>Code feedback:</strong></summary>\n\n<hr><table><tr><td>relevant file</td><td>pr_agent/git_providers/git_provider.py\n</td></tr><tr><td>suggestion      </td><td>\n\n<strong>\n\nConsider raising an exception or logging a warning when \'pr_url\' attribute is not found. This can help in debugging issues related to the absence of \'pr_url\' in instances where it\'s expected. [important]\n\n</strong>\n</td></tr><tr><td>relevant line</td><td><a href=\'https://github.com/Codium-ai/pr-agent-pro/pull/102/files#diff-52d45f12b836f77ed1aef86e972e65404634ea4e2a6083fb71a9b0f9bb9e062fR199\'>return ""</a></td></tr></table><hr>\n\n</details>' assert convert_to_markdown(input_data).strip() == expected_output.strip() From e4157d2efc676e4fe388a7b840496caec2dc66fb Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sun, 5 May 2024 13:36:34 +0300 Subject: [PATCH 146/226] toolbar emojis in pr-agent feedbacks --- tests/unittest/test_convert_to_markdown.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unittest/test_convert_to_markdown.py b/tests/unittest/test_convert_to_markdown.py index ad8f4973..676d0eea 100644 --- a/tests/unittest/test_convert_to_markdown.py +++ b/tests/unittest/test_convert_to_markdown.py @@ -52,7 +52,7 @@ class TestConvertToMarkdown: 'suggestion': "Consider raising an exception or logging a warning when 'pr_url' attribute is not found. This can help in debugging issues related to the absence of 'pr_url' in instances where it's expected. [important]\n", 'relevant_line': '[return ""](https://github.com/Codium-ai/pr-agent-pro/pull/102/files#diff-52d45f12b836f77ed1aef86e972e65404634ea4e2a6083fb71a9b0f9bb9e062fR199)'}]} - expected_output = '## PR Review ๐Ÿ”\n\n<table>\n<tr>\n<tr><td> โฑ๏ธ <strong>Estimated effort to review [1-5]</strong></td><td>\n\n1, because the changes are minimal and straightforward, focusing on a single functionality addition.\n\n\n</td></tr>\n<tr><td> ๐Ÿงช <strong>Relevant tests</strong></td><td>\n\nNo\n\n\n</td></tr>\n<tr><td> ๐Ÿ” <strong>Possible issues</strong></td><td>\n\nNo\n\n</td></tr>\n<tr><td> ๐Ÿ”’ <strong>Security concerns</strong></td><td>\n\nNo\n\n</td></tr>\n</table>\n\n\n<details><summary> <strong>Code feedback:</strong></summary>\n\n<hr><table><tr><td>relevant file</td><td>pr_agent/git_providers/git_provider.py\n</td></tr><tr><td>suggestion      </td><td>\n\n<strong>\n\nConsider raising an exception or logging a warning when \'pr_url\' attribute is not found. This can help in debugging issues related to the absence of \'pr_url\' in instances where it\'s expected. [important]\n\n</strong>\n</td></tr><tr><td>relevant line</td><td><a href=\'https://github.com/Codium-ai/pr-agent-pro/pull/102/files#diff-52d45f12b836f77ed1aef86e972e65404634ea4e2a6083fb71a9b0f9bb9e062fR199\'>return ""</a></td></tr></table><hr>\n\n</details>' + expected_output = '## PR Review ๐Ÿ”\n\n<table>\n<tr>\n<tr><td> โฑ๏ธ <strong>Estimated effort to review [1-5]</strong></td><td>\n\n1, because the changes are minimal and straightforward, focusing on a single functionality addition.\n\n\n</td></tr>\n<tr><td> ๐Ÿงช <strong>Relevant tests</strong></td><td>\n\nNo\n\n\n</td></tr>\n<tr><td> โšก <strong>Possible issues</strong></td><td>\n\nNo\n\n</td></tr>\n<tr><td> ๐Ÿ”’ <strong>Security concerns</strong></td><td>\n\nNo\n\n</td></tr>\n</table>\n\n\n<details><summary> <strong>Code feedback:</strong></summary>\n\n<hr><table><tr><td>relevant file</td><td>pr_agent/git_providers/git_provider.py\n</td></tr><tr><td>suggestion      </td><td>\n\n<strong>\n\nConsider raising an exception or logging a warning when \'pr_url\' attribute is not found. This can help in debugging issues related to the absence of \'pr_url\' in instances where it\'s expected. [important]\n\n</strong>\n</td></tr><tr><td>relevant line</td><td><a href=\'https://github.com/Codium-ai/pr-agent-pro/pull/102/files#diff-52d45f12b836f77ed1aef86e972e65404634ea4e2a6083fb71a9b0f9bb9e062fR199\'>return ""</a></td></tr></table><hr>\n\n</details>' assert convert_to_markdown(input_data).strip() == expected_output.strip() From 097637d7c08ce670c06d718ead66d7bf1cec09fb Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sun, 5 May 2024 13:48:45 +0300 Subject: [PATCH 147/226] toolbar emojis in pr-agent feedbacks --- pr_agent/tools/pr_help_message.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pr_agent/tools/pr_help_message.py b/pr_agent/tools/pr_help_message.py index df2698cf..9f76434d 100644 --- a/pr_agent/tools/pr_help_message.py +++ b/pr_agent/tools/pr_help_message.py @@ -18,8 +18,8 @@ class PRHelpMessage: relevant_configs = {'pr_help': dict(get_settings().pr_help), 'config': dict(get_settings().config)} get_logger().debug("Relevant configs", artifacts=relevant_configs) - pr_comment = "## PR Agent Walkthrough\n\n" - pr_comment += "๐Ÿค– Welcome to the PR Agent, an AI-powered tool for automated pull request analysis, feedback, suggestions and more.""" + pr_comment = "## PR Agent Walkthrough ๐Ÿค–\n\n" + pr_comment += "Welcome to the PR Agent, an AI-powered tool for automated pull request analysis, feedback, suggestions and more.""" pr_comment += "\n\nHere is a list of tools you can use to interact with the PR Agent:\n" base_path = "https://pr-agent-docs.codium.ai/tools" From 253f77f4d9047b581f8cf259ad827fdb787f619f Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sun, 5 May 2024 16:01:07 +0300 Subject: [PATCH 148/226] privacy --- README.md | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index d6cd3074..40ae7ac6 100644 --- a/README.md +++ b/README.md @@ -321,11 +321,22 @@ Here are some advantages of PR-Agent: ## Data privacy -If you host PR-Agent with your OpenAI API key, it is between you and OpenAI. You can read their API data privacy policy here: +### Self-hosted PR-Agent + +- If you host PR-Agent with your OpenAI API key, it is between you and OpenAI. You can read their API data privacy policy here: https://openai.com/enterprise-privacy -When using PR-Agent Pro ๐Ÿ’Ž, hosted by CodiumAI, we will not store any of your data, nor will we use it for training. -You will also benefit from an OpenAI account with zero data retention. +### CodiumAI-hosted PR-Agent Pro ๐Ÿ’Ž + +- When using PR-Agent Pro ๐Ÿ’Ž, hosted by CodiumAI, we will not store any of your data, nor will we use it for training. You will also benefit from an OpenAI account with zero data retention. + +- For certain clients, CodiumAI-hosted PR-Agent Pro will use CodiumAIโ€™s proprietary models โ€” if this is the case, you will be notified. + +- No passive collection of Code and Pull Requestsโ€™ data โ€” PR-Agent will be active only when you invoke it, and it will then extract and analyze only data relevant to the executed command and queried pull request. + +### PR-Agent Chrome extension + +- The [PR-Agent Chrome extension](https://chromewebstore.google.com/detail/pr-agent-chrome-extension/ephlnjeghhogofkifjloamocljapahnl) will only act to alter the visual appearance of a GitHub PR screen. It will not communicate any user's repo or pull request code by itself. Only when the user actually sends a GitHub comment that triggers a PR-Agent command, will a code be sent to processing, according to the standard privacy policy of PR-Agent. ## Links From 7bb1917be7a047d5ca325ffcbb3655eae8be8a5b Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sun, 5 May 2024 16:09:07 +0300 Subject: [PATCH 149/226] privacy --- README.md | 2 +- docs/docs/index.md | 19 +++++++++++++++---- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 40ae7ac6..39fa8fac 100644 --- a/README.md +++ b/README.md @@ -336,7 +336,7 @@ https://openai.com/enterprise-privacy ### PR-Agent Chrome extension -- The [PR-Agent Chrome extension](https://chromewebstore.google.com/detail/pr-agent-chrome-extension/ephlnjeghhogofkifjloamocljapahnl) will only act to alter the visual appearance of a GitHub PR screen. It will not communicate any user's repo or pull request code by itself. Only when the user actually sends a GitHub comment that triggers a PR-Agent command, will a code be sent to processing, according to the standard privacy policy of PR-Agent. +- The [PR-Agent Chrome extension](https://chromewebstore.google.com/detail/pr-agent-chrome-extension/ephlnjeghhogofkifjloamocljapahnl) will only act to alter the visual appearance of a GitHub PR screen. It will not communicate any user's repo or pull request code by itself. Only when the user actually sends a GitHub comment that triggers a PR-Agent tool, will a code be sent to processing, according to the standard privacy policy of PR-Agent. ## Links diff --git a/docs/docs/index.md b/docs/docs/index.md index 80b62e11..5042aca9 100644 --- a/docs/docs/index.md +++ b/docs/docs/index.md @@ -104,10 +104,21 @@ Check out the [PR Compression strategy](core-abilities/index.md) page for more d - (Feature): [**Inline file summary**](https://pr-agent-docs.codium.ai/tools/describe/#inline-file-summary) -## Data Privacy +## Data privacy -If you host PR-Agent with your OpenAI API key, it is between you and OpenAI. You can read their API data privacy policy here: +### Self-hosted PR-Agent + +- If you host PR-Agent with your OpenAI API key, it is between you and OpenAI. You can read their API data privacy policy here: https://openai.com/enterprise-privacy -When using PR-Agent Pro ๐Ÿ’Ž, hosted by CodiumAI, we will not store any of your data, nor will we use it for training. -You will also benefit from an OpenAI account with zero data retention. +### CodiumAI-hosted PR-Agent Pro ๐Ÿ’Ž + +- When using PR-Agent Pro ๐Ÿ’Ž, hosted by CodiumAI, we will not store any of your data, nor will we use it for training. You will also benefit from an OpenAI account with zero data retention. + +- For certain clients, CodiumAI-hosted PR-Agent Pro will use CodiumAIโ€™s proprietary models โ€” if this is the case, you will be notified. + +- No passive collection of Code and Pull Requestsโ€™ data โ€” PR-Agent will be active only when you invoke it, and it will then extract and analyze only data relevant to the executed command and queried pull request. + +### PR-Agent Chrome extension + +- The [PR-Agent Chrome extension](https://chromewebstore.google.com/detail/pr-agent-chrome-extension/ephlnjeghhogofkifjloamocljapahnl) will only act to alter the visual appearance of a GitHub PR screen. It will not communicate any user's repo or pull request code by itself. Only when the user actually sends a GitHub comment that triggers a PR-Agent tool, will a code be sent to processing, according to the standard privacy policy of PR-Agent. \ No newline at end of file From edb230c993dd52111a3966f95839195d4d143e67 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sun, 5 May 2024 16:11:03 +0300 Subject: [PATCH 150/226] privacy --- docs/docs/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/index.md b/docs/docs/index.md index 5042aca9..b4c3ce94 100644 --- a/docs/docs/index.md +++ b/docs/docs/index.md @@ -104,7 +104,7 @@ Check out the [PR Compression strategy](core-abilities/index.md) page for more d - (Feature): [**Inline file summary**](https://pr-agent-docs.codium.ai/tools/describe/#inline-file-summary) -## Data privacy +## Data Privacy ### Self-hosted PR-Agent From 4645cd7cf9676868cbe165fcf260104c461b652c Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sun, 5 May 2024 16:13:28 +0300 Subject: [PATCH 151/226] privacy --- README.md | 2 +- docs/docs/index.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 39fa8fac..b1060ae8 100644 --- a/README.md +++ b/README.md @@ -336,7 +336,7 @@ https://openai.com/enterprise-privacy ### PR-Agent Chrome extension -- The [PR-Agent Chrome extension](https://chromewebstore.google.com/detail/pr-agent-chrome-extension/ephlnjeghhogofkifjloamocljapahnl) will only act to alter the visual appearance of a GitHub PR screen. It will not communicate any user's repo or pull request code by itself. Only when the user actually sends a GitHub comment that triggers a PR-Agent tool, will a code be sent to processing, according to the standard privacy policy of PR-Agent. +- The [PR-Agent Chrome extension](https://chromewebstore.google.com/detail/pr-agent-chrome-extension/ephlnjeghhogofkifjloamocljapahnl) serves solely to modify the visual appearance of a GitHub PR screen. It does not transmit any user's repo or pull request code. Code is only sent for processing when a user submits a GitHub comment that activates a PR-Agent tool, in accordance with the standard privacy policy of PR-Agent. ## Links diff --git a/docs/docs/index.md b/docs/docs/index.md index b4c3ce94..06021105 100644 --- a/docs/docs/index.md +++ b/docs/docs/index.md @@ -121,4 +121,4 @@ https://openai.com/enterprise-privacy ### PR-Agent Chrome extension -- The [PR-Agent Chrome extension](https://chromewebstore.google.com/detail/pr-agent-chrome-extension/ephlnjeghhogofkifjloamocljapahnl) will only act to alter the visual appearance of a GitHub PR screen. It will not communicate any user's repo or pull request code by itself. Only when the user actually sends a GitHub comment that triggers a PR-Agent tool, will a code be sent to processing, according to the standard privacy policy of PR-Agent. \ No newline at end of file +- The [PR-Agent Chrome extension](https://chromewebstore.google.com/detail/pr-agent-chrome-extension/ephlnjeghhogofkifjloamocljapahnl) serves solely to modify the visual appearance of a GitHub PR screen. It does not transmit any user's repo or pull request code. Code is only sent for processing when a user submits a GitHub comment that activates a PR-Agent tool, in accordance with the standard privacy policy of PR-Agent. \ No newline at end of file From e8f4a45774cf8451df63995a8ece40973b5eadce Mon Sep 17 00:00:00 2001 From: Tal <tal.r@codium.ai> Date: Wed, 8 May 2024 13:54:31 +0300 Subject: [PATCH 152/226] Update configuration_options.md --- docs/docs/usage-guide/configuration_options.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/docs/usage-guide/configuration_options.md b/docs/docs/usage-guide/configuration_options.md index 54a37a86..99287957 100644 --- a/docs/docs/usage-guide/configuration_options.md +++ b/docs/docs/usage-guide/configuration_options.md @@ -11,6 +11,12 @@ There are three ways to set persistent configurations: In terms of precedence, wiki configurations will override local configurations, and local configurations will override global configurations. +!!! tip "Edit only what you need" + + Your configuration file should be minimal, and edit only the relevant values. Don't copy the entire configuration options, since it can lead to legacy problems when something changes. + + + ## Wiki configuration file ๐Ÿ’Ž Specifically for GitHub, with PR-Agent-Pro you can set configurations by creating a page called `.pr_agent.toml` in the [wiki](https://github.com/Codium-ai/pr-agent/wiki/pr_agent.toml) of the repo. @@ -53,4 +59,4 @@ Parameters from a local `.pr_agent.toml` file, in a specific repo, will override For example, in the GitHub organization `Codium-ai`: - The repo [`https://github.com/Codium-ai/pr-agent-settings`](https://github.com/Codium-ai/pr-agent-settings/blob/main/.pr_agent.toml) contains a `.pr_agent.toml` file that serves as a global configuration file for all the repos in the GitHub organization `Codium-ai`. -- The repo [`https://github.com/Codium-ai/pr-agent`](https://github.com/Codium-ai/pr-agent/blob/main/.pr_agent.toml) inherits the global configuration file from `pr-agent-settings`. \ No newline at end of file +- The repo [`https://github.com/Codium-ai/pr-agent`](https://github.com/Codium-ai/pr-agent/blob/main/.pr_agent.toml) inherits the global configuration file from `pr-agent-settings`. From 738eb055ff91aaa3ae5b3d530a2a5dc4636ccd6d Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Wed, 8 May 2024 14:28:38 +0300 Subject: [PATCH 153/226] s --- docs/docs/tools/review.md | 133 +++++++++++++----- .../docs/usage-guide/configuration_options.md | 7 +- 2 files changed, 96 insertions(+), 44 deletions(-) diff --git a/docs/docs/tools/review.md b/docs/docs/tools/review.md index 2e5c4bb6..97ea5e9f 100644 --- a/docs/docs/tools/review.md +++ b/docs/docs/tools/review.md @@ -40,45 +40,6 @@ num_code_suggestions = ... - The `pr_commands` lists commands that will be executed automatically when a PR is opened. - The `[pr_reviewer]` section contains the configurations for the `review` tool you want to edit (if any). - -## Configuration options - -### General configurations - -!!! example "General options" - - <a name="num_code_suggestions"></a>`num_code_suggestions`: number of code suggestions provided by the 'review' tool. For manual comments, default is 4. For [PR-Agent app](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/configuration.toml#L142) auto tools, default is 0, meaning no code suggestions will be provided by the review tool, unless you manually edit `pr_commands`. - - <a name="inline_code_comments"></a>`inline_code_comments`: if set to true, the tool will publish the code suggestions as comments on the code diff. Default is false. - - <a name="persistent_comment"></a>`persistent_comment`: if set to true, the review comment will be persistent, meaning that every new review request will edit the previous one. Default is true. - - <a name="extra_instructions"></a>`extra_instructions`: Optional extra instructions to the tool. For example: "focus on the changes in the file X. Ignore change in ...". - - <a name="enable_help_text"></a>`enable_help_text`: if set to true, the tool will display a help text in the comment. Default is true. - -!!! example "Enable\\disable sub-sections" - You can enable or disable specific sub-sections of the review tool: - - - <a name="require_score_review"></a>`require_score_review`: if set to true, the tool will add a section that scores the PR. Default is false. - - <a name="require_tests_review"></a>`require_tests_review`: if set to true, the tool will add a section that checks if the PR contains tests. Default is true. - - <a name="require_estimate_effort_to_review"></a>`require_estimate_effort_to_review`: if set to true, the tool will add a section that estimates the effort needed to review the PR. Default is true. - - <a name="require_can_be_split_review"></a>`require_can_be_split_review`: if set to true, the tool will add a section that checks if the PR contains several themes, and can be split into smaller PRs. Default is false. - -!!! example "SOC2 ticket compliance ๐Ÿ’Ž" - - This sub-tool checks if the PR description properly contains a ticket to a project management system (e.g., Jira, Asana, Trello, etc.), as required by SOC2 compliance. If not, it will add a label to the PR: "Missing SOC2 ticket". - - - <a name="require_soc2_ticket"></a>`require_soc2_ticket`: If set to true, the SOC2 ticket checker sub-tool will be enabled. Default is false. - - <a name="soc2_ticket_prompt"></a>`soc2_ticket_prompt`: The prompt for the SOC2 ticket review. Default is: `Does the PR description include a link to ticket in a project management system (e.g., Jira, Asana, Trello, etc.) ?`. Edit this field if your compliance requirements are different. - -!!! example "Adding PR labels" - You can enable the tool to add specific labels to the PR: - - - <a name="enable_review_labels_security"></a>`enable_review_labels_security`: if set to true, the tool will publish a 'possible security issue' label if it detects a security issue. Default is true. - - <a name="enable_review_labels_effort"></a>`enable_review_labels_effort`: if set to true, the tool will publish a 'Review effort [1-5]: x' label. Default is true. - -!!! example "Auto-approval" - The review tool can approve a PR when a specific comment, `/review auto_approve` is invoked. - - - <a name="enable_auto_approval"></a>`enable_auto_approval`: if set to true, the tool will approve the PR when invoked with the 'auto_approve' command. Default is false. This flag can be changed only from configuration file. - - <a name="maximal_review_effort"></a>`maximal_review_effort`: maximal effort level for auto-approval. If the PR's estimated review effort is above this threshold, the auto-approval will not run. Default is 5. - ### Incremental Mode Incremental review only considers changes since the last PR-Agent review. This can be useful when working on the PR in an iterative manner, and you want to focus on the changes since the last review instead of reviewing the entire PR again. For invoking the incremental mode, the following command can be used: @@ -104,6 +65,100 @@ The tool will first ask the author questions about the PR, and will guide the re ![reflection insights](https://codium.ai/images/pr_agent/reflection_insights.png){width=512} + +## Configuration options + +!!! example "General options" + +<table> + <tr> + <td><b>num_code_suggestions</b></td> + <td>Number of code suggestions provided by the 'review' tool. For manual comments, default is 4. For PR-Agent app auto tools, default is 0, meaning no code suggestions will be provided by the review tool, unless you manually edit pr_commands.</td> + </tr> + <tr> + <td><b>inline_code_comments</b></td> + <td>If set to true, the tool will publish the code suggestions as comments on the code diff. Default is false.</td> + </tr> + <tr> + <td><b>persistent_comment</b></td> + <td>If set to true, the review comment will be persistent, meaning that every new review request will edit the previous one. Default is true.</td> + </tr> + <tr> + <td><b>extra_instructions</b></td> + <td>Optional extra instructions to the tool. For example: "focus on the changes in the file X. Ignore change in ...".</td> + </tr> + <tr> + <td><b>enable_help_text</b></td> + <td>If set to true, the tool will display a help text in the comment. Default is true.</td> + </tr> +</table> + +!!! example "Enable\\disable specific sub-sections" + +<table> + <tr> + <td><b>require_score_review</b></td> + <td>If set to true, the tool will add a section that scores the PR. Default is false.</td> + </tr> + <tr> + <td><b>require_tests_review</b></td> + <td>If set to true, the tool will add a section that checks if the PR contains tests. Default is true.</td> + </tr> + <tr> + <td><b>require_estimate_effort_to_review</b></td> + <td>If set to true, the tool will add a section that estimates the effort needed to review the PR. Default is true.</td> + </tr> + <tr> + <td><b>require_can_be_split_review</b></td> + <td>If set to true, the tool will add a section that checks if the PR contains several themes, and can be split into smaller PRs. Default is false.</td> + </tr> +</table> + +!!! example "SOC2 ticket compliance ๐Ÿ’Ž" + +This sub-tool checks if the PR description properly contains a ticket to a project management system (e.g., Jira, Asana, Trello, etc.), as required by SOC2 compliance. If not, it will add a label to the PR: "Missing SOC2 ticket". + +<table> + <tr> + <td><b>require_soc2_ticket</b></td> + <td>If set to true, the SOC2 ticket checker sub-tool will be enabled. Default is false.</td> + </tr> + <tr> + <td><b>soc2_ticket_prompt</b></td> + <td>The prompt for the SOC2 ticket review. Default is: `Does the PR description include a link to ticket in a project management system (e.g., Jira, Asana, Trello, etc.) ?`. Edit this field if your compliance requirements are different.</td> + </tr> +</table> + +!!! example "Adding PR labels" + +You can enable\disable the `review` tool to add specific labels to the PR: + +<table> + <tr> + <td><b>enable_review_labels_security</b></td> + <td>If set to true, the tool will publish a 'possible security issue' label if it detects a security issue. Default is true.</td> + </tr> + <tr> + <td><b>enable_review_labels_effort</b></td> + <td>If set to true, the tool will publish a 'Review effort [1-5]: x' label. Default is true.</td> + </tr> +</table> + +!!! example "Auto-approval" + +If enabled, the `review` tool can approve a PR when a specific comment, `/review auto_approve`, is invoked. + +<table> + <tr> + <td><b>enable_auto_approval</b></td> + <td>If set to true, the tool will approve the PR when invoked with the 'auto_approve' command. Default is false. This flag can be changed only from configuration file.</td> + </tr> + <tr> + <td><b>maximal_review_effort</b></td> + <td>Maximal effort level for auto-approval. If the PR's estimated review effort is above this threshold, the auto-approval will not run. Default is 5.</td> + </tr> +</table> + ## Usage Tips !!! tip "General guidelines" diff --git a/docs/docs/usage-guide/configuration_options.md b/docs/docs/usage-guide/configuration_options.md index 99287957..68a8492b 100644 --- a/docs/docs/usage-guide/configuration_options.md +++ b/docs/docs/usage-guide/configuration_options.md @@ -11,11 +11,8 @@ There are three ways to set persistent configurations: In terms of precedence, wiki configurations will override local configurations, and local configurations will override global configurations. -!!! tip "Edit only what you need" - - Your configuration file should be minimal, and edit only the relevant values. Don't copy the entire configuration options, since it can lead to legacy problems when something changes. - - +!!! tip "Tip: edit only what you need" + Your configuration file should be minimal, and edit only the relevant values. Don't copy the entire configuration options, since it can lead to legacy problems when something changes. ## Wiki configuration file ๐Ÿ’Ž From 38051f79b7d068c13e0cbc476ab483d752b024fa Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Wed, 8 May 2024 14:38:28 +0300 Subject: [PATCH 154/226] s --- docs/docs/tools/improve.md | 96 +++++++++++++++++++++++++------------- 1 file changed, 63 insertions(+), 33 deletions(-) diff --git a/docs/docs/tools/improve.md b/docs/docs/tools/improve.md index 5980b955..96001490 100644 --- a/docs/docs/tools/improve.md +++ b/docs/docs/tools/improve.md @@ -40,52 +40,82 @@ pr_commands = [ ] [pr_code_suggestions] -num_code_suggestions = ... +num_code_suggestions_per_chunk = ... ... ``` - The `pr_commands` lists commands that will be executed automatically when a PR is opened. - The `[pr_code_suggestions]` section contains the configurations for the `improve` tool you want to edit (if any) +### Extended mode + +An extended mode, which does not involve PR Compression and provides more comprehensive suggestions, can be invoked by commenting on any PR by setting: +``` +[pr_code_suggestions] +auto_extended_mode=true +``` +(This mode is true by default). + +Note that the extended mode divides the PR code changes into chunks, up to the token limits, where each chunk is handled separately (might use multiple calls to GPT-4 for large PRs). +Hence, the total number of suggestions is proportional to the number of chunks, i.e., the size of the PR. + ## Configuration options !!! example "General options" - - `num_code_suggestions`: number of code suggestions provided by the 'improve' tool. Default is 4 for CLI, 0 for auto tools. - - `extra_instructions`: Optional extra instructions to the tool. For example: "focus on the changes in the file X. Ignore change in ...". - - `rank_suggestions`: if set to true, the tool will rank the suggestions, based on importance. Default is false. - - `commitable_code_suggestions`: if set to true, the tool will display the suggestions as commitable code comments. Default is false. - - `persistent_comment`: if set to true, the improve comment will be persistent, meaning that every new improve request will edit the previous one. Default is false. - - `enable_help_text`: if set to true, the tool will display a help text in the comment. Default is true. - -!!! example "params for '/improve --extended' mode" - - - `auto_extended_mode`: enable extended mode automatically (no need for the `--extended` option). Default is true. - - `num_code_suggestions_per_chunk`: number of code suggestions provided by the 'improve' tool, per chunk. Default is 5. - - `rank_extended_suggestions`: if set to true, the tool will rank the suggestions, based on importance. Default is true. - - `max_number_of_calls`: maximum number of chunks. Default is 5. - - `final_clip_factor`: factor to remove suggestions with low confidence. Default is 0.9.; - -## Extended mode - -An extended mode, which does not involve PR Compression and provides more comprehensive suggestions, can be invoked by commenting on any PR: -``` -/improve --extended -``` - -or by setting: -``` -[pr_code_suggestions] -auto_extended_mode=true -``` -(True by default). - -Note that the extended mode divides the PR code changes into chunks, up to the token limits, where each chunk is handled separately (might use multiple calls to GPT-4 for large PRs). -Hence, the total number of suggestions is proportional to the number of chunks, i.e., the size of the PR. +<table> + <tr> + <td><b>num_code_suggestions</b></td> + <td>Number of code suggestions provided by the 'improve' tool. Default is 4 for CLI, 0 for auto tools.</td> + </tr> + <tr> + <td><b>extra_instructions</b></td> + <td>Optional extra instructions to the tool. For example: "focus on the changes in the file X. Ignore change in ...".</td> + </tr> + <tr> + <td><b>rank_suggestions</b></td> + <td>If set to true, the tool will rank the suggestions, based on importance. Default is false.</td> + </tr> + <tr> + <td><b>commitable_code_suggestions</b></td> + <td>If set to true, the tool will display the suggestions as commitable code comments. Default is false.</td> + </tr> + <tr> + <td><b>persistent_comment</b></td> + <td>If set to true, the improve comment will be persistent, meaning that every new improve request will edit the previous one. Default is false.</td> + </tr> + <tr> + <td><b>enable_help_text</b></td> + <td>If set to true, the tool will display a help text in the comment. Default is true.</td> + </tr> +</table> +!!! example "params for 'extended' mode" +<table> + <tr> + <td><b>auto_extended_mode</b></td> + <td>Enable extended mode automatically (no need for the --extended option). Default is true.</td> + </tr> + <tr> + <td><b>num_code_suggestions_per_chunk</b></td> + <td>Number of code suggestions provided by the 'improve' tool, per chunk. Default is 5.</td> + </tr> + <tr> + <td><b>rank_extended_suggestions</b></td> + <td>If set to true, the tool will rank the suggestions, based on importance. Default is true.</td> + </tr> + <tr> + <td><b>max_number_of_calls</b></td> + <td>Maximum number of chunks. Default is 5.</td> + </tr> + <tr> + <td><b>final_clip_factor</b></td> + <td>Factor to remove suggestions with low confidence. Default is 0.9.</td> + </tr> +</table> ## Usage Tips @@ -110,7 +140,7 @@ Hence, the total number of suggestions is proportional to the number of chunks, !!! tip "Review vs. Improve tools comparison" - - The [`review`](https://pr-agent-docs.codium.ai/tools/review/) tool includes a section called 'Possible issues', that also provide feedback on the PR Code. + - The [review](https://pr-agent-docs.codium.ai/tools/review/) tool includes a section called 'Possible issues', that also provide feedback on the PR Code. In this section, the model is instructed to focus **only** on [major bugs and issues](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/pr_reviewer_prompts.toml#L71). - The `improve` tool, on the other hand, has a broader mandate, and in addition to bugs and issues, it can also give suggestions for improving code quality and making the code more efficient, readable, and maintainable (see [here](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/pr_code_suggestions_prompts.toml#L34)). - Hence, if you are interested only in feedback about clear bugs, the `review` tool might suffice. If you want a more detailed feedback, including broader suggestions for improving the PR code, also enable the `improve` tool to run on each PR. From c92c26448fad0cc5535e79e518184c0bd40e41f7 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Wed, 8 May 2024 15:42:00 +0300 Subject: [PATCH 155/226] s --- docs/docs/tools/describe.md | 72 ++++++++++++++++++++++++------------- 1 file changed, 48 insertions(+), 24 deletions(-) diff --git a/docs/docs/tools/describe.md b/docs/docs/tools/describe.md index 756c6adc..cd8c7015 100644 --- a/docs/docs/tools/describe.md +++ b/docs/docs/tools/describe.md @@ -44,33 +44,57 @@ publish_labels = ... ## Configuration options -### General configurations - !!! example "Possible configurations" - - `publish_labels`: if set to true, the tool will publish the labels to the PR. Default is true. +<table> + <tr> + <td><b>publish_labels</b></td> + <td>If set to true, the tool will publish the labels to the PR. Default is true.</td> + </tr> + <tr> + <td><b>publish_description_as_comment</b></td> + <td>If set to true, the tool will publish the description as a comment to the PR. If false, it will overwrite the original description. Default is false.</td> + </tr> + <tr> + <td><b>publish_description_as_comment_persistent</b></td> + <td>If set to true and `publish_description_as_comment` is true, the tool will publish the description as a persistent comment to the PR. Default is true.</td> + </tr> + <tr> + <td><b>add_original_user_description</b></td> + <td>If set to true, the tool will add the original user description to the generated description. Default is true.</td> + </tr> + <tr> + <td><b>generate_ai_title</b></td> + <td>If set to true, the tool will also generate an AI title for the PR. Default is false.</td> + </tr> + <tr> + <td><b>extra_instructions</b></td> + <td>Optional extra instructions to the tool. For example: "focus on the changes in the file X. Ignore change in ..."</td> + </tr> + <tr> + <td><b>enable_pr_type</b></td> + <td>If set to false, it will not show the `PR type` as a text value in the description content. Default is true.</td> + </tr> + <tr> + <td><b>final_update_message</b></td> + <td>If set to true, it will add a comment message [`PR Description updated to latest commit...`](https://github.com/Codium-ai/pr-agent/pull/499#issuecomment-1837412176) after finishing calling `/describe`. Default is true.</td> + </tr> + <tr> + <td><b>enable_semantic_files_types</b></td> + <td>If set to true, "Changes walkthrough" section will be generated. Default is true.</td> + </tr> + <tr> + <td><b>collapsible_file_list</b></td> + <td>If set to true, the file list in the "Changes walkthrough" section will be collapsible. If set to "adaptive", the file list will be collapsible only if there are more than 8 files. Default is "adaptive".</td> + </tr> + <tr> + <td><b>enable_help_text</b></td> + <td>If set to true, the tool will display a help text in the comment. Default is false.</td> + </tr> +</table> - - `publish_description_as_comment`: if set to true, the tool will publish the description as a comment to the PR. If false, it will overwrite the original description. Default is false. - - `publish_description_as_comment_persistent`: if set to true and `publish_description_as_comment` is true, the tool will publish the description as a persistent comment to the PR. Default is true. - - - `add_original_user_description`: if set to true, the tool will add the original user description to the generated description. Default is true. - - - `generate_ai_title`: if set to true, the tool will also generate an AI title for the PR. Default is false. - - - `extra_instructions`: Optional extra instructions to the tool. For example: "focus on the changes in the file X. Ignore change in ...". - - - To enable `custom labels`, apply the configuration changes described [here](./custom_labels.md#configuration-options) - - - `enable_pr_type`: if set to false, it will not show the `PR type` as a text value in the description content. Default is true. - - - `final_update_message`: if set to true, it will add a comment message [`PR Description updated to latest commit...`](https://github.com/Codium-ai/pr-agent/pull/499#issuecomment-1837412176) after finishing calling `/describe`. Default is true. - - - `enable_semantic_files_types`: if set to true, "Changes walkthrough" section will be generated. Default is true. - - `collapsible_file_list`: if set to true, the file list in the "Changes walkthrough" section will be collapsible. If set to "adaptive", the file list will be collapsible only if there are more than 8 files. Default is "adaptive". - - `enable_help_text`: if set to true, the tool will display a help text in the comment. Default is false. - -### Inline file summary ๐Ÿ’Ž +## Inline file summary ๐Ÿ’Ž This feature enables you to copy the `changes walkthrough` table to the "Files changed" tab, so you can quickly understand the changes in each file while reviewing the code changes (diff view). @@ -93,7 +117,7 @@ If you prefer to have the file summaries appear in the "Files changed" tab on ev **Note**: that this feature is currently available only for GitHub. -### Markers template +## Markers template To enable markers, set `pr_description.use_description_markers=true`. Markers enable to easily integrate user's content and auto-generated content, with a template-like mechanism. From 1ebc20b76125f146bc6353780efabc055fde8662 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Fri, 10 May 2024 19:44:26 +0300 Subject: [PATCH 156/226] self_reflect --- format_importance.py | 8 + pr_agent/config_loader.py | 1 + pr_agent/settings/configuration.toml | 3 +- .../settings/pr_code_suggestions_prompts.toml | 27 ++- .../pr_code_suggestions_reflect_prompts.toml | 93 ++++++++ pr_agent/tools/pr_code_suggestions.py | 219 ++++++++++++------ 6 files changed, 267 insertions(+), 84 deletions(-) create mode 100644 format_importance.py create mode 100644 pr_agent/settings/pr_code_suggestions_reflect_prompts.toml diff --git a/format_importance.py b/format_importance.py new file mode 100644 index 00000000..6eca65fb --- /dev/null +++ b/format_importance.py @@ -0,0 +1,8 @@ +import numpy as np + +from pr_agent.tools.pr_code_suggestions import PRCodeSuggestions + +data = np.load('/Users/talrid/Git/pr-agent/data.npy', allow_pickle=True).tolist() +cls=PRCodeSuggestions(pr_url=None) +res = cls.generate_summarized_suggestions(data) +print(res) diff --git a/pr_agent/config_loader.py b/pr_agent/config_loader.py index ad4d0ae7..224a1c04 100644 --- a/pr_agent/config_loader.py +++ b/pr_agent/config_loader.py @@ -21,6 +21,7 @@ global_settings = Dynaconf( "settings/pr_line_questions_prompts.toml", "settings/pr_description_prompts.toml", "settings/pr_code_suggestions_prompts.toml", + "settings/pr_code_suggestions_reflect_prompts.toml", "settings/pr_sort_code_suggestions_prompts.toml", "settings/pr_information_from_user_prompts.toml", "settings/pr_update_changelog_prompts.toml", diff --git a/pr_agent/settings/configuration.toml b/pr_agent/settings/configuration.toml index b2c65a3d..c1d0dded 100644 --- a/pr_agent/settings/configuration.toml +++ b/pr_agent/settings/configuration.toml @@ -85,9 +85,10 @@ extra_instructions = "" rank_suggestions = false enable_help_text=false persistent_comment=false +self_reflect_on_suggestions=true # params for '/improve --extended' mode auto_extended_mode=true -num_code_suggestions_per_chunk=5 +num_code_suggestions_per_chunk=4 max_number_of_calls = 3 parallel_calls = true rank_extended_suggestions = false diff --git a/pr_agent/settings/pr_code_suggestions_prompts.toml b/pr_agent/settings/pr_code_suggestions_prompts.toml index 278f0117..10b95c92 100644 --- a/pr_agent/settings/pr_code_suggestions_prompts.toml +++ b/pr_agent/settings/pr_code_suggestions_prompts.toml @@ -1,8 +1,9 @@ [pr_code_suggestions_prompt] -system="""You are PR-Reviewer, a language model that specializes in suggesting code improvements for a Pull Request (PR). -Your task is to provide meaningful and actionable code suggestions, to improve the new code presented in a PR diff (lines starting with '+'). +system="""You are PR-Reviewer, a language model that specializes in suggesting ways to improve for a Pull Request (PR) code. +Your task is to provide meaningful and actionable code suggestions, to improve the new code presented in a PR diff. -Example for the PR Diff format: + +The format we will use to present the PR code diff: ====== ## file: 'src/file1.py' @@ -26,22 +27,26 @@ __old hunk__ ## file: 'src/file2.py' ... ====== +- In this format, we separated each hunk of code to '__new hunk__' and '__old hunk__' sections. The '__new hunk__' section contains the new code of the chunk, and the '__old hunk__' section contains the old code that was removed. +- Code lines are prefixed symbols ('+', '-', ' '). The '+' symbol indicates new code added in the PR, the '-' symbol indicates code removed in the PR, and the ' ' symbol indicates unchanged code. +- We also added line numbers for the '__new hunk__' sections, to help you refer to the code lines in your suggestions. These line numbers are not part of the actual code, and are only used for reference. -Specific instructions: +Specific instructions for generating code suggestions: - Provide up to {{ num_code_suggestions }} code suggestions. The suggestions should be diverse and insightful. -- The suggestions should refer only to code from the '__new hunk__' sections, and focus on new lines of code (lines starting with '+'). -- Prioritize suggestions that address major problems, issues and bugs in the PR code. As a second priority, suggestions should focus on enhancement, best practice, performance, maintainability, and other aspects. +- The suggestions should focus on ways to improve the new code in the PR, meaning focusing on lines from '__new hunk__' sections, starting with '+'. Use the '__old hunk__' sections to understand the context of the code changes. +- Prioritize suggestions that address major problems, issues and possible bugs in the PR code. - Don't suggest to add docstring, type hints, or comments, or to remove unused imports. - Suggestions should not repeat code already present in the '__new hunk__' sections. -- Provide the exact line numbers range (inclusive) for each suggestion. +- Provide the exact line numbers range (inclusive) for each suggestion. Use the line numbers from the '__new hunk__' sections. - When quoting variables or names from the code, use backticks (`) instead of single quote ('). +- Be aware that you are reviewing a PR code diff, and that the entire codebase is not available for you as context. Hence, don't suggest changes that require knowledge of the entire codebase. {%- if extra_instructions %} -Extra instructions from the user: +Extra instructions from the user, that should be taken into account with high priority: ====== {{ extra_instructions }} ====== @@ -59,12 +64,12 @@ class CodeSuggestion(BaseModel): improved_code: str = Field(description="a short code snippet to illustrate the improved code, after applying the suggestion.") one_sentence_summary:str = Field(description="a short summary of the suggestion action, in a single sentence. Focus on the 'what'. Be general, and avoid method or variable names.") {%- else %} - existing_code: str = Field(description="a code snippet, demonstrating the relevant code lines from a '__new hunk__' section. It must be contiguous, correctly formatted and indented, and without line numbers") - improved_code: str = Field(description="a new code snippet, that can be used to replace the relevant lines in '__new hunk__' code. Replacement suggestions should be complete, correctly formatted and indented, and without line numbers") + existing_code: str = Field(description="a code snippet, demonstrating the relevant code lines from a '__new hunk__' section. It must be contiguous, correctly formatted and indented, and without line numbers. Use abbreviations if needed") + improved_code: str = Field(description="If relevant, a new code snippet, that can be used to replace the relevant lines in '__new hunk__' code. Replacement suggestions should be complete, correctly formatted and indented, and without line numbers". Retrun '...' if not applicable") {%- endif %} relevant_lines_start: int = Field(description="The relevant line number, from a '__new hunk__' section, where the suggestion starts (inclusive). Should be derived from the hunk line numbers, and correspond to the 'existing code' snippet above") relevant_lines_end: int = Field(description="The relevant line number, from a '__new hunk__' section, where the suggestion ends (inclusive). Should be derived from the hunk line numbers, and correspond to the 'existing code' snippet above") - label: str = Field(description="a single label for the suggestion, to help the user understand the suggestion type. For example: 'security', 'bug', 'performance', 'enhancement', 'possible issue', 'best practice', 'maintainability', etc. Other labels are also allowed") + label: str = Field(description="a single label for the suggestion, to help the user understand the suggestion type. For example: 'security', 'possible bug', 'possible issue', 'performance', 'enhancement', 'best practice', 'maintainability', etc. Other labels are also allowed") class PRCodeSuggestions(BaseModel): code_suggestions: List[CodeSuggestion] diff --git a/pr_agent/settings/pr_code_suggestions_reflect_prompts.toml b/pr_agent/settings/pr_code_suggestions_reflect_prompts.toml new file mode 100644 index 00000000..5a85d743 --- /dev/null +++ b/pr_agent/settings/pr_code_suggestions_reflect_prompts.toml @@ -0,0 +1,93 @@ +[pr_code_suggestions_reflect_prompt] +system="""You are a language model that specializes in reviewing and evaluating suggestions for a Pull Request (PR) code. + +Your input is a PR code, and a list of code suggestions that were generated for the PR. +Your goal is to inspect, review and score the suggestsions. +Be aware - the suggestions may not always be correct or accurate, and you should evaluate them in relation to the actual PR code diff presented. Sometimes the suggestion may ignore parts of the actual code diff, and in that case, you should give a score of 0. + +Specific instructions: +- Carefully review both the suggestion content, and the related PR code diff. Mistakes in the suggestions can occur. Make sure the suggestions are correct, and properly derived from the PR code diff. +- In addition to the exact code lines mentioned in each suggestion, review the code around them, to ensure that the suggestions are contextually accurate. +- Also check that the 'existing_code' and 'improved_code' fields correctly reflect the suggested changes. +- High scores (8 to 10) should be given to correct suggestions that address major bugs and issues, or security concerns. Lower scores (3 to 7) should be for correct suggestions addressing minor issues, code style, code readability, maintainability, etc. Don't give high scores to suggestions that are not crucial, and bring only small improvement or optimization. +- Order the feedback the same way the suggestions are ordered in the input. + + +The format that is used to present the PR code diff is as follows: +====== +## file: 'src/file1.py' + +@@ ... @@ def func1(): +__new hunk__ +12 code line1 that remained unchanged in the PR +13 +new hunk code line2 added in the PR +14 code line3 that remained unchanged in the PR +__old hunk__ + code line1 that remained unchanged in the PR +-old hunk code line2 that was removed in the PR + code line3 that remained unchanged in the PR + +@@ ... @@ def func2(): +__new hunk__ +... +__old hunk__ +... + + +## file: 'src/file2.py' +... +====== +- In this format, we separated each hunk of code to '__new hunk__' and '__old hunk__' sections. The '__new hunk__' section contains the new code of the chunk, and the '__old hunk__' section contains the old code that was removed. +- Code lines are prefixed symbols ('+', '-', ' '). The '+' symbol indicates new code added in the PR, the '-' symbol indicates code removed in the PR, and the ' ' symbol indicates unchanged code. +- We also added line numbers for the '__new hunk__' sections, to help you refer to the code lines in your suggestions. These line numbers are not part of the actual code, and are only used for reference. + + +The output must be a YAML object equivalent to type $PRCodeSuggestionsFeedback, according to the following Pydantic definitions: +===== +class CodeSuggestionFeedback(BaseModel): +{%- if not commitable_code_suggestions_mode %} + suggestion_summary: str = Field(description="repeated from the input") +{%- endif %} + relevant_file: str = Field(description="repeated from the input") + suggestion_score: int = Field(description="The actual output - the score of the suggestion, from 0 to 10. Give 0 if the suggestion is plain wrong. Otherwise, give a score from 1 to 10 (inclusive), where 1 is the lowest and 10 is the highest.") + why: str = Field(description="Short and concise explanation of why the suggestion received the score (one to two sentences).") + +class PRCodeSuggestionsFeedback(BaseModel): + code_suggestions: List[CodeSuggestionFeedback] +===== + + +Example output: +```yaml +code_suggestions: +{%- if not commitable_code_suggestions_mode %} +- suggestion_content: | + Use a more descriptive variable name here + relevant_file: "src/file1.py" +{%- else %} +- relevant_file: "src/file1.py" +{%- endif %} + suggestion_score: 6 + why: | + The variable name 't' is not descriptive enough +``` + + +Each YAML output MUST be after a newline, indented, with block scalar indicator ('|'). +""" + +user="""You are given a Pull Request (PR) code diff: +====== +{{ diff|trim }} +====== + + +And here is a list of corresponding {{ num_code_suggestions }} code suggestions to improve this Pull Request code: +====== +{{ suggestion_str|trim }} +====== + + +Response (should be a valid YAML, and nothing else): +```yaml +""" diff --git a/pr_agent/tools/pr_code_suggestions.py b/pr_agent/tools/pr_code_suggestions.py index ff4eb96f..1e4d3a0f 100644 --- a/pr_agent/tools/pr_code_suggestions.py +++ b/pr_agent/tools/pr_code_suggestions.py @@ -22,53 +22,54 @@ class PRCodeSuggestions: def __init__(self, pr_url: str, cli_mode=False, args: list = None, ai_handler: partial[BaseAiHandler,] = LiteLLMAIHandler): - self.git_provider = get_git_provider()(pr_url) - self.main_language = get_main_pr_language( - self.git_provider.get_languages(), self.git_provider.get_files() - ) + if pr_url: + self.git_provider = get_git_provider()(pr_url) + self.main_language = get_main_pr_language( + self.git_provider.get_languages(), self.git_provider.get_files() + ) - # limit context specifically for the improve command, which has hard input to parse: - if get_settings().pr_code_suggestions.max_context_tokens: - MAX_CONTEXT_TOKENS_IMPROVE = get_settings().pr_code_suggestions.max_context_tokens - if get_settings().config.max_model_tokens > MAX_CONTEXT_TOKENS_IMPROVE: - get_logger().info(f"Setting max_model_tokens to {MAX_CONTEXT_TOKENS_IMPROVE} for PR improve") - get_settings().config.max_model_tokens = MAX_CONTEXT_TOKENS_IMPROVE + # limit context specifically for the improve command, which has hard input to parse: + if get_settings().pr_code_suggestions.max_context_tokens: + MAX_CONTEXT_TOKENS_IMPROVE = get_settings().pr_code_suggestions.max_context_tokens + if get_settings().config.max_model_tokens > MAX_CONTEXT_TOKENS_IMPROVE: + get_logger().info(f"Setting max_model_tokens to {MAX_CONTEXT_TOKENS_IMPROVE} for PR improve") + get_settings().config.max_model_tokens = MAX_CONTEXT_TOKENS_IMPROVE - # extended mode - try: - self.is_extended = self._get_is_extended(args or []) - except: - self.is_extended = False - if self.is_extended: - num_code_suggestions = get_settings().pr_code_suggestions.num_code_suggestions_per_chunk - else: - num_code_suggestions = get_settings().pr_code_suggestions.num_code_suggestions + # extended mode + try: + self.is_extended = self._get_is_extended(args or []) + except: + self.is_extended = False + if self.is_extended: + num_code_suggestions = get_settings().pr_code_suggestions.num_code_suggestions_per_chunk + else: + num_code_suggestions = get_settings().pr_code_suggestions.num_code_suggestions - self.ai_handler = ai_handler() - self.ai_handler.main_pr_language = self.main_language - self.patches_diff = None - self.prediction = None - self.cli_mode = cli_mode - self.vars = { - "title": self.git_provider.pr.title, - "branch": self.git_provider.get_pr_branch(), - "description": self.git_provider.get_pr_description(), - "language": self.main_language, - "diff": "", # empty diff for initial calculation - "num_code_suggestions": num_code_suggestions, - "commitable_code_suggestions_mode": get_settings().pr_code_suggestions.commitable_code_suggestions, - "extra_instructions": get_settings().pr_code_suggestions.extra_instructions, - "commit_messages_str": self.git_provider.get_commit_messages(), - } - self.token_handler = TokenHandler(self.git_provider.pr, - self.vars, - get_settings().pr_code_suggestions_prompt.system, - get_settings().pr_code_suggestions_prompt.user) + self.ai_handler = ai_handler() + self.ai_handler.main_pr_language = self.main_language + self.patches_diff = None + self.prediction = None + self.cli_mode = cli_mode + self.vars = { + "title": self.git_provider.pr.title, + "branch": self.git_provider.get_pr_branch(), + "description": self.git_provider.get_pr_description(), + "language": self.main_language, + "diff": "", # empty diff for initial calculation + "num_code_suggestions": num_code_suggestions, + "commitable_code_suggestions_mode": get_settings().pr_code_suggestions.commitable_code_suggestions, + "extra_instructions": get_settings().pr_code_suggestions.extra_instructions, + "commit_messages_str": self.git_provider.get_commit_messages(), + } + self.token_handler = TokenHandler(self.git_provider.pr, + self.vars, + get_settings().pr_code_suggestions_prompt.system, + get_settings().pr_code_suggestions_prompt.user) - self.progress = f"## Generating PR code suggestions\n\n" - self.progress += f"""\nWork in progress ...<br>\n<img src="https://codium.ai/images/pr_agent/dual_ball_loading-crop.gif" width=48>""" - self.progress_response = None + self.progress = f"## Generating PR code suggestions\n\n" + self.progress += f"""\nWork in progress ...<br>\n<img src="https://codium.ai/images/pr_agent/dual_ball_loading-crop.gif" width=48>""" + self.progress_response = None async def run(self): try: @@ -83,12 +84,11 @@ class PRCodeSuggestions: self.git_provider.publish_comment("Preparing suggestions...", is_temporary=True) if not self.is_extended: - await retry_with_fallback_models(self._prepare_prediction, ModelType.TURBO) - data = self._prepare_pr_code_suggestions() + data = await retry_with_fallback_models(self._prepare_prediction, ModelType.TURBO) else: data = await retry_with_fallback_models(self._prepare_prediction_extended, ModelType.TURBO) - if (not data) or (not 'code_suggestions' in data) or (not data['code_suggestions']): + if not data or not data.get('code_suggestions'): get_logger().error('No code suggestions found for PR.') pr_body = "## PR Code Suggestions โœจ\n\nNo code suggestions found for PR." get_logger().debug(f"PR output", artifact=pr_body) @@ -148,7 +148,7 @@ class PRCodeSuggestions: except Exception as e: pass - async def _prepare_prediction(self, model: str): + async def _prepare_prediction(self, model: str) -> dict: self.patches_diff = get_pr_diff(self.git_provider, self.token_handler, model, @@ -162,7 +162,10 @@ class PRCodeSuggestions: get_logger().error(f"Error getting PR diff") self.prediction = None - async def _get_prediction(self, model: str, patches_diff: str): + data = self._prepare_pr_code_suggestions(self.prediction) + return data + + async def _get_prediction(self, model: str, patches_diff: str) -> dict: variables = copy.deepcopy(self.vars) variables["diff"] = patches_diff # update diff environment = Environment(undefined=StrictUndefined) @@ -171,7 +174,21 @@ class PRCodeSuggestions: response, finish_reason = await self.ai_handler.chat_completion(model=model, temperature=0.2, system=system_prompt, user=user_prompt) - return response + # load suggestions from the AI response + data = self._prepare_pr_code_suggestions(response) + + # self-reflect on suggestions + if get_settings().pr_code_suggestions.self_reflect_on_suggestions: + response_reflect = await self.self_reflect_on_suggestions(data["code_suggestions"], patches_diff) + if response_reflect: + response_reflect_yaml = load_yaml(response_reflect) + code_suggestions_feedback = response_reflect_yaml["code_suggestions"] + if len(code_suggestions_feedback) == len(data["code_suggestions"]): + for i, suggestion in enumerate(data["code_suggestions"]): + suggestion["score"] = code_suggestions_feedback[i]["suggestion_score"] + suggestion["score_why"] = code_suggestions_feedback[i]["why"] + + return data @staticmethod def _truncate_if_needed(suggestion): @@ -185,14 +202,13 @@ class PRCodeSuggestions: f"characters to {max_code_suggestion_length} characters") return suggestion - def _prepare_pr_code_suggestions(self) -> Dict: - review = self.prediction.strip() - data = load_yaml(review, + def _prepare_pr_code_suggestions(self, predictions: str) -> Dict: + data = load_yaml(predictions.strip(), keys_fix_yaml=["relevant_file", "suggestion_content", "existing_code", "improved_code"]) if isinstance(data, list): data = {'code_suggestions': data} - # remove invalid suggestions + # remove or edit invalid suggestions suggestion_list = [] one_sentence_summary_list = [] for i, suggestion in enumerate(data['code_suggestions']): @@ -210,15 +226,17 @@ class PRCodeSuggestions: get_logger().debug(f"Skipping suggestion {i + 1}, because it uses 'const instead let': {suggestion}") continue - if ('existing_code' in suggestion) and ('improved_code' in suggestion) and ( - suggestion['existing_code'] != suggestion['improved_code']): + if ('existing_code' in suggestion) and ('improved_code' in suggestion): + if suggestion['existing_code'] == suggestion['improved_code']: + get_logger().debug(f"skipping improved suggestion {i + 1}, because equal to existing code: {suggestion['existing_code']}") + suggestion['existing_code'] = "" suggestion = self._truncate_if_needed(suggestion) if not get_settings().pr_code_suggestions.commitable_code_suggestions: one_sentence_summary_list.append(suggestion['one_sentence_summary']) suggestion_list.append(suggestion) else: - get_logger().debug( - f"Skipping suggestion {i + 1}, because existing code is equal to improved code {suggestion['existing_code']}") + get_logger().info( + f"Skipping suggestion {i + 1}, because it does not contain 'existing_code' or 'improved_code': {suggestion}") except Exception as e: get_logger().error(f"Error processing suggestion {i + 1}: {suggestion}, error: {e}") data['code_suggestions'] = suggestion_list @@ -309,14 +327,24 @@ class PRCodeSuggestions: prediction = await self._get_prediction(model, patches_diff) prediction_list.append(prediction) - data = {} - for prediction in prediction_list: - self.prediction = prediction - data_per_chunk = self._prepare_pr_code_suggestions() - if "code_suggestions" in data: - data["code_suggestions"].extend(data_per_chunk["code_suggestions"]) - else: - data.update(data_per_chunk) + + data = {"code_suggestions": []} + for i, prediction in enumerate(prediction_list): + try: + if "code_suggestions" in prediction: + if get_settings().pr_code_suggestions.self_reflect_on_suggestions: + score = int(prediction["code_suggestions"][0]["score"]) + if score > 0: + data["code_suggestions"].extend(prediction["code_suggestions"]) + else: + get_logger().info(f"Skipping suggestions from call {i + 1}, because score is {score}") + else: + data["code_suggestions"].extend(prediction["code_suggestions"]) + else: + get_logger().error(f"Error getting PR diff, no code suggestions found in call {i + 1}") + except Exception as e: + get_logger().error(f"Error getting PR diff, error: {e}") + data = None self.data = data else: get_logger().error(f"Error getting PR diff") @@ -397,10 +425,13 @@ class PRCodeSuggestions: pr_body = "## PR Code Suggestions โœจ\n\n" pr_body += "<table>" - header = f"Suggestions" - delta = 76 + header = f"Suggestion" + delta = 68 header += "  " * delta - pr_body += f"""<thead><tr><td>Category</td><td align=left>{header}</td></tr></thead>""" + if get_settings().pr_code_suggestions.self_reflect_on_suggestions: + pr_body += f"""<thead><tr><td>Category</td><td align=left>{header}</td><td align=center>Score</td></tr>""" + else: + pr_body += f"""<thead><tr><td>Category</td><td align=left>{header}</td></tr>""" pr_body += """<tbody>""" suggestions_labels = dict() # add all suggestions related to each label @@ -410,6 +441,11 @@ class PRCodeSuggestions: suggestions_labels[label] = [] suggestions_labels[label].append(suggestion) + # sort suggestions_labels by the suggestion with the highest score + if get_settings().pr_code_suggestions.self_reflect_on_suggestions: + suggestions_labels = dict(sorted(suggestions_labels.items(), key=lambda x: max([s['score'] for s in x[1]]), reverse=True)) + + for label, suggestions in suggestions_labels.items(): num_suggestions=len(suggestions) pr_body += f"""<tr><td rowspan={num_suggestions}><strong>{label.capitalize()}</strong></td>\n""" @@ -423,8 +459,12 @@ class PRCodeSuggestions: range_str = f"[{relevant_lines_start}]" else: range_str = f"[{relevant_lines_start}-{relevant_lines_end}]" - code_snippet_link = self.git_provider.get_line_link(relevant_file, relevant_lines_start, - relevant_lines_end) + + try: + code_snippet_link = self.git_provider.get_line_link(relevant_file, relevant_lines_start, + relevant_lines_end) + except: + code_snippet_link = "" # add html table for each suggestion suggestion_content = suggestion['suggestion_content'].rstrip().rstrip() @@ -445,12 +485,11 @@ class PRCodeSuggestions: pr_body += f"""<td>\n\n""" else: pr_body += f"""<tr><td>\n\n""" - suggestion_summary = suggestion['one_sentence_summary'].strip() + suggestion_summary = suggestion['one_sentence_summary'].strip().rstrip('.') if '`' in suggestion_summary: suggestion_summary = replace_code_tags(suggestion_summary) - # suggestion_summary = suggestion_summary + max((77-len(suggestion_summary)), 0)*" " - pr_body += f"""\n\n<details><summary>{suggestion_summary}</summary>\n\n___\n\n""" + pr_body += f"""\n\n<details><summary>{suggestion_summary}</summary>\n\n___\n\n""" pr_body += f""" **{suggestion_content}** @@ -458,6 +497,15 @@ class PRCodeSuggestions: {example_code} """ + if get_settings().pr_code_suggestions.self_reflect_on_suggestions: + pr_body +=f"\n\n<details><summary><b>Suggestion importance[1-10]: {suggestion['score']}</b></summary>\n\n" + pr_body += f"Why: {suggestion['score_why']}\n\n" + pr_body += f"</details>" + + # # add another column for 'score' + if get_settings().pr_code_suggestions.self_reflect_on_suggestions: + pr_body += f"</td><td align=center>{suggestion['score']}\n\n" + pr_body += f"</details>" pr_body += f"</td></tr>" @@ -469,3 +517,30 @@ class PRCodeSuggestions: except Exception as e: get_logger().info(f"Failed to publish summarized code suggestions, error: {e}") return "" + + async def self_reflect_on_suggestions(self, suggestion_list: List, patches_diff: str) -> str: + if not suggestion_list: + return "" + + try: + suggestion_str = "" + for i, suggestion in enumerate(suggestion_list): + suggestion_str += f"suggestion {i + 1}: " + str(suggestion) + '\n\n' + + variables = {'suggestion_list': suggestion_list, + 'suggestion_str': suggestion_str, + "diff": patches_diff, + 'num_code_suggestions': len(suggestion_list), + 'commitable_code_suggestions_mode': get_settings().pr_code_suggestions.commitable_code_suggestions,} + model = get_settings().config.model + environment = Environment(undefined=StrictUndefined) + system_prompt_reflect = environment.from_string(get_settings().pr_code_suggestions_reflect_prompt.system).render( + variables) + user_prompt_reflect = environment.from_string(get_settings().pr_code_suggestions_reflect_prompt.user).render(variables) + response_reflect, finish_reason_reflect = await self.ai_handler.chat_completion(model=model, + system=system_prompt_reflect, + user=user_prompt_reflect) + except Exception as e: + get_logger().info(f"Could not reflect on suggestions, error: {e}") + return "" + return response_reflect \ No newline at end of file From 7627e651ea45296c96a945199c8cd17dcd70a844 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sun, 12 May 2024 13:50:10 +0300 Subject: [PATCH 157/226] s --- format_importance.py | 8 -------- 1 file changed, 8 deletions(-) delete mode 100644 format_importance.py diff --git a/format_importance.py b/format_importance.py deleted file mode 100644 index 6eca65fb..00000000 --- a/format_importance.py +++ /dev/null @@ -1,8 +0,0 @@ -import numpy as np - -from pr_agent.tools.pr_code_suggestions import PRCodeSuggestions - -data = np.load('/Users/talrid/Git/pr-agent/data.npy', allow_pickle=True).tolist() -cls=PRCodeSuggestions(pr_url=None) -res = cls.generate_summarized_suggestions(data) -print(res) From a588e9f2bbb6881d8576b0c9f080b3f70c83332a Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sun, 12 May 2024 13:55:12 +0300 Subject: [PATCH 158/226] s --- .../settings/pr_code_suggestions_prompts.toml | 2 +- .../pr_code_suggestions_reflect_prompts.toml | 2 +- pr_agent/tools/pr_code_suggestions.py | 85 +++++++++---------- 3 files changed, 44 insertions(+), 45 deletions(-) diff --git a/pr_agent/settings/pr_code_suggestions_prompts.toml b/pr_agent/settings/pr_code_suggestions_prompts.toml index 10b95c92..93c2ace9 100644 --- a/pr_agent/settings/pr_code_suggestions_prompts.toml +++ b/pr_agent/settings/pr_code_suggestions_prompts.toml @@ -35,7 +35,7 @@ __old hunk__ Specific instructions for generating code suggestions: - Provide up to {{ num_code_suggestions }} code suggestions. The suggestions should be diverse and insightful. - The suggestions should focus on ways to improve the new code in the PR, meaning focusing on lines from '__new hunk__' sections, starting with '+'. Use the '__old hunk__' sections to understand the context of the code changes. -- Prioritize suggestions that address major problems, issues and possible bugs in the PR code. +- Prioritize suggestions that address possible issues, major problems, and bugs in the PR code. - Don't suggest to add docstring, type hints, or comments, or to remove unused imports. - Suggestions should not repeat code already present in the '__new hunk__' sections. - Provide the exact line numbers range (inclusive) for each suggestion. Use the line numbers from the '__new hunk__' sections. diff --git a/pr_agent/settings/pr_code_suggestions_reflect_prompts.toml b/pr_agent/settings/pr_code_suggestions_reflect_prompts.toml index 5a85d743..b0e163b3 100644 --- a/pr_agent/settings/pr_code_suggestions_reflect_prompts.toml +++ b/pr_agent/settings/pr_code_suggestions_reflect_prompts.toml @@ -3,7 +3,7 @@ system="""You are a language model that specializes in reviewing and evaluating Your input is a PR code, and a list of code suggestions that were generated for the PR. Your goal is to inspect, review and score the suggestsions. -Be aware - the suggestions may not always be correct or accurate, and you should evaluate them in relation to the actual PR code diff presented. Sometimes the suggestion may ignore parts of the actual code diff, and in that case, you should give a score of 0. +Be aware - the suggestions may not always be correct or accurate, and you should evaluate them in relation to the actual PR code diff presented. Sometimes the suggestion may ignore parts of the actual code diff, and in that case, you should give it a score of 0. Specific instructions: - Carefully review both the suggestion content, and the related PR code diff. Mistakes in the suggestions can occur. Make sure the suggestions are correct, and properly derived from the PR code diff. diff --git a/pr_agent/tools/pr_code_suggestions.py b/pr_agent/tools/pr_code_suggestions.py index 1e4d3a0f..97b8f483 100644 --- a/pr_agent/tools/pr_code_suggestions.py +++ b/pr_agent/tools/pr_code_suggestions.py @@ -22,54 +22,53 @@ class PRCodeSuggestions: def __init__(self, pr_url: str, cli_mode=False, args: list = None, ai_handler: partial[BaseAiHandler,] = LiteLLMAIHandler): - if pr_url: - self.git_provider = get_git_provider()(pr_url) - self.main_language = get_main_pr_language( - self.git_provider.get_languages(), self.git_provider.get_files() - ) + self.git_provider = get_git_provider()(pr_url) + self.main_language = get_main_pr_language( + self.git_provider.get_languages(), self.git_provider.get_files() + ) - # limit context specifically for the improve command, which has hard input to parse: - if get_settings().pr_code_suggestions.max_context_tokens: - MAX_CONTEXT_TOKENS_IMPROVE = get_settings().pr_code_suggestions.max_context_tokens - if get_settings().config.max_model_tokens > MAX_CONTEXT_TOKENS_IMPROVE: - get_logger().info(f"Setting max_model_tokens to {MAX_CONTEXT_TOKENS_IMPROVE} for PR improve") - get_settings().config.max_model_tokens = MAX_CONTEXT_TOKENS_IMPROVE + # limit context specifically for the improve command, which has hard input to parse: + if get_settings().pr_code_suggestions.max_context_tokens: + MAX_CONTEXT_TOKENS_IMPROVE = get_settings().pr_code_suggestions.max_context_tokens + if get_settings().config.max_model_tokens > MAX_CONTEXT_TOKENS_IMPROVE: + get_logger().info(f"Setting max_model_tokens to {MAX_CONTEXT_TOKENS_IMPROVE} for PR improve") + get_settings().config.max_model_tokens = MAX_CONTEXT_TOKENS_IMPROVE - # extended mode - try: - self.is_extended = self._get_is_extended(args or []) - except: - self.is_extended = False - if self.is_extended: - num_code_suggestions = get_settings().pr_code_suggestions.num_code_suggestions_per_chunk - else: - num_code_suggestions = get_settings().pr_code_suggestions.num_code_suggestions + # extended mode + try: + self.is_extended = self._get_is_extended(args or []) + except: + self.is_extended = False + if self.is_extended: + num_code_suggestions = get_settings().pr_code_suggestions.num_code_suggestions_per_chunk + else: + num_code_suggestions = get_settings().pr_code_suggestions.num_code_suggestions - self.ai_handler = ai_handler() - self.ai_handler.main_pr_language = self.main_language - self.patches_diff = None - self.prediction = None - self.cli_mode = cli_mode - self.vars = { - "title": self.git_provider.pr.title, - "branch": self.git_provider.get_pr_branch(), - "description": self.git_provider.get_pr_description(), - "language": self.main_language, - "diff": "", # empty diff for initial calculation - "num_code_suggestions": num_code_suggestions, - "commitable_code_suggestions_mode": get_settings().pr_code_suggestions.commitable_code_suggestions, - "extra_instructions": get_settings().pr_code_suggestions.extra_instructions, - "commit_messages_str": self.git_provider.get_commit_messages(), - } - self.token_handler = TokenHandler(self.git_provider.pr, - self.vars, - get_settings().pr_code_suggestions_prompt.system, - get_settings().pr_code_suggestions_prompt.user) + self.ai_handler = ai_handler() + self.ai_handler.main_pr_language = self.main_language + self.patches_diff = None + self.prediction = None + self.cli_mode = cli_mode + self.vars = { + "title": self.git_provider.pr.title, + "branch": self.git_provider.get_pr_branch(), + "description": self.git_provider.get_pr_description(), + "language": self.main_language, + "diff": "", # empty diff for initial calculation + "num_code_suggestions": num_code_suggestions, + "commitable_code_suggestions_mode": get_settings().pr_code_suggestions.commitable_code_suggestions, + "extra_instructions": get_settings().pr_code_suggestions.extra_instructions, + "commit_messages_str": self.git_provider.get_commit_messages(), + } + self.token_handler = TokenHandler(self.git_provider.pr, + self.vars, + get_settings().pr_code_suggestions_prompt.system, + get_settings().pr_code_suggestions_prompt.user) - self.progress = f"## Generating PR code suggestions\n\n" - self.progress += f"""\nWork in progress ...<br>\n<img src="https://codium.ai/images/pr_agent/dual_ball_loading-crop.gif" width=48>""" - self.progress_response = None + self.progress = f"## Generating PR code suggestions\n\n" + self.progress += f"""\nWork in progress ...<br>\n<img src="https://codium.ai/images/pr_agent/dual_ball_loading-crop.gif" width=48>""" + self.progress_response = None async def run(self): try: From 39c0733d6fee9988932b95abd127e781ce13d9d1 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sun, 12 May 2024 14:00:30 +0300 Subject: [PATCH 159/226] s --- pr_agent/tools/pr_code_suggestions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pr_agent/tools/pr_code_suggestions.py b/pr_agent/tools/pr_code_suggestions.py index 97b8f483..019e41b4 100644 --- a/pr_agent/tools/pr_code_suggestions.py +++ b/pr_agent/tools/pr_code_suggestions.py @@ -161,7 +161,7 @@ class PRCodeSuggestions: get_logger().error(f"Error getting PR diff") self.prediction = None - data = self._prepare_pr_code_suggestions(self.prediction) + data = self.prediction return data async def _get_prediction(self, model: str, patches_diff: str) -> dict: From 8e0435d9a00a3eed9b0a0ab008521a768bd75248 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sun, 12 May 2024 14:40:25 +0300 Subject: [PATCH 160/226] s --- pr_agent/tools/pr_code_suggestions.py | 30 +++++++++++++-------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/pr_agent/tools/pr_code_suggestions.py b/pr_agent/tools/pr_code_suggestions.py index 019e41b4..908bce3a 100644 --- a/pr_agent/tools/pr_code_suggestions.py +++ b/pr_agent/tools/pr_code_suggestions.py @@ -328,22 +328,20 @@ class PRCodeSuggestions: data = {"code_suggestions": []} - for i, prediction in enumerate(prediction_list): - try: - if "code_suggestions" in prediction: - if get_settings().pr_code_suggestions.self_reflect_on_suggestions: - score = int(prediction["code_suggestions"][0]["score"]) - if score > 0: - data["code_suggestions"].extend(prediction["code_suggestions"]) + for i, predictions in enumerate(prediction_list): + if "code_suggestions" in predictions: + for prediction in predictions["code_suggestions"]: + try: + if get_settings().pr_code_suggestions.self_reflect_on_suggestions: + score = int(prediction["score"]) + if score > 0: + data["code_suggestions"].append(prediction) + else: + get_logger().info(f"Skipping suggestions from call {i + 1}, because score is {score}") else: - get_logger().info(f"Skipping suggestions from call {i + 1}, because score is {score}") - else: - data["code_suggestions"].extend(prediction["code_suggestions"]) - else: - get_logger().error(f"Error getting PR diff, no code suggestions found in call {i + 1}") - except Exception as e: - get_logger().error(f"Error getting PR diff, error: {e}") - data = None + get_logger().error(f"Error getting PR diff, no code suggestions found in call {i + 1}") + except Exception as e: + get_logger().error(f"Error getting PR diff, error: {e}") self.data = data else: get_logger().error(f"Error getting PR diff") @@ -428,7 +426,7 @@ class PRCodeSuggestions: delta = 68 header += "  " * delta if get_settings().pr_code_suggestions.self_reflect_on_suggestions: - pr_body += f"""<thead><tr><td>Category</td><td align=left>{header}</td><td align=center>Score</td></tr>""" + pr_body += f"""<thead><tr><td>Category</td><td align=left>{header}</td><td align=center>Importance</td></tr>""" else: pr_body += f"""<thead><tr><td>Category</td><td align=left>{header}</td></tr>""" pr_body += """<tbody>""" From a55fa753b9744b8754d2f2a4a7ef61518b3a1250 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sun, 12 May 2024 14:54:35 +0300 Subject: [PATCH 161/226] s --- .../settings/pr_code_suggestions_reflect_prompts.toml | 1 + pr_agent/tools/pr_code_suggestions.py | 11 ++++++++--- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/pr_agent/settings/pr_code_suggestions_reflect_prompts.toml b/pr_agent/settings/pr_code_suggestions_reflect_prompts.toml index b0e163b3..96e0ea1c 100644 --- a/pr_agent/settings/pr_code_suggestions_reflect_prompts.toml +++ b/pr_agent/settings/pr_code_suggestions_reflect_prompts.toml @@ -9,6 +9,7 @@ Specific instructions: - Carefully review both the suggestion content, and the related PR code diff. Mistakes in the suggestions can occur. Make sure the suggestions are correct, and properly derived from the PR code diff. - In addition to the exact code lines mentioned in each suggestion, review the code around them, to ensure that the suggestions are contextually accurate. - Also check that the 'existing_code' and 'improved_code' fields correctly reflect the suggested changes. +- Make sure the suggestions focus on new code introduced in the PR, and not on existing code that was not changed. - High scores (8 to 10) should be given to correct suggestions that address major bugs and issues, or security concerns. Lower scores (3 to 7) should be for correct suggestions addressing minor issues, code style, code readability, maintainability, etc. Don't give high scores to suggestions that are not crucial, and bring only small improvement or optimization. - Order the feedback the same way the suggestions are ordered in the input. diff --git a/pr_agent/tools/pr_code_suggestions.py b/pr_agent/tools/pr_code_suggestions.py index 908bce3a..46d74d9f 100644 --- a/pr_agent/tools/pr_code_suggestions.py +++ b/pr_agent/tools/pr_code_suggestions.py @@ -86,8 +86,10 @@ class PRCodeSuggestions: data = await retry_with_fallback_models(self._prepare_prediction, ModelType.TURBO) else: data = await retry_with_fallback_models(self._prepare_prediction_extended, ModelType.TURBO) + if not data: + data = {"code_suggestions": []} - if not data or not data.get('code_suggestions'): + if data is None or 'code_suggestions' not in data or not data['code_suggestions']: get_logger().error('No code suggestions found for PR.') pr_body = "## PR Code Suggestions โœจ\n\nNo code suggestions found for PR." get_logger().debug(f"PR output", artifact=pr_body) @@ -423,10 +425,10 @@ class PRCodeSuggestions: pr_body += "<table>" header = f"Suggestion" - delta = 68 + delta = 64 header += "  " * delta if get_settings().pr_code_suggestions.self_reflect_on_suggestions: - pr_body += f"""<thead><tr><td>Category</td><td align=left>{header}</td><td align=center>Importance</td></tr>""" + pr_body += f"""<thead><tr><td>Category</td><td align=left>{header}</td><td align=center>Score</td></tr>""" else: pr_body += f"""<thead><tr><td>Category</td><td align=left>{header}</td></tr>""" pr_body += """<tbody>""" @@ -441,6 +443,9 @@ class PRCodeSuggestions: # sort suggestions_labels by the suggestion with the highest score if get_settings().pr_code_suggestions.self_reflect_on_suggestions: suggestions_labels = dict(sorted(suggestions_labels.items(), key=lambda x: max([s['score'] for s in x[1]]), reverse=True)) + # sort the suggestions inside each label group by score + for label, suggestions in suggestions_labels.items(): + suggestions_labels[label] = sorted(suggestions, key=lambda x: x['score'], reverse=True) for label, suggestions in suggestions_labels.items(): From c04ab933cd6a0bb44b5e588bf0ad58b53223e062 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sun, 12 May 2024 15:04:36 +0300 Subject: [PATCH 162/226] s --- pr_agent/tools/pr_code_suggestions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pr_agent/tools/pr_code_suggestions.py b/pr_agent/tools/pr_code_suggestions.py index 46d74d9f..6d095d8a 100644 --- a/pr_agent/tools/pr_code_suggestions.py +++ b/pr_agent/tools/pr_code_suggestions.py @@ -425,7 +425,7 @@ class PRCodeSuggestions: pr_body += "<table>" header = f"Suggestion" - delta = 64 + delta = 66 header += "  " * delta if get_settings().pr_code_suggestions.self_reflect_on_suggestions: pr_body += f"""<thead><tr><td>Category</td><td align=left>{header}</td><td align=center>Score</td></tr>""" From d348cffbaee8176873683c4ee0a23fac02b803f2 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sun, 12 May 2024 15:52:59 +0300 Subject: [PATCH 163/226] Enhance error handling and logging in pr_code_suggestions with default scores and contextualized self_reflection --- pr_agent/tools/pr_code_suggestions.py | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/pr_agent/tools/pr_code_suggestions.py b/pr_agent/tools/pr_code_suggestions.py index 6d095d8a..1d828fa5 100644 --- a/pr_agent/tools/pr_code_suggestions.py +++ b/pr_agent/tools/pr_code_suggestions.py @@ -186,8 +186,20 @@ class PRCodeSuggestions: code_suggestions_feedback = response_reflect_yaml["code_suggestions"] if len(code_suggestions_feedback) == len(data["code_suggestions"]): for i, suggestion in enumerate(data["code_suggestions"]): - suggestion["score"] = code_suggestions_feedback[i]["suggestion_score"] - suggestion["score_why"] = code_suggestions_feedback[i]["why"] + try: + suggestion["score"] = code_suggestions_feedback[i]["suggestion_score"] + suggestion["score_why"] = code_suggestions_feedback[i]["why"] + except Exception as e: # + get_logger().error(f"Error processing suggestion score {i}", + artifact={"suggestion": suggestion, + "code_suggestions_feedback": code_suggestions_feedback[i]}) + suggestion["score"] = 7 + suggestion["score_why"] = "" + else: + get_logger().error(f"Could not self-reflect on suggestions. using default score 7") + for i, suggestion in enumerate(data["code_suggestions"]): + suggestion["score"] = 7 + suggestion["score_why"] = "" return data @@ -539,9 +551,10 @@ class PRCodeSuggestions: system_prompt_reflect = environment.from_string(get_settings().pr_code_suggestions_reflect_prompt.system).render( variables) user_prompt_reflect = environment.from_string(get_settings().pr_code_suggestions_reflect_prompt.user).render(variables) - response_reflect, finish_reason_reflect = await self.ai_handler.chat_completion(model=model, - system=system_prompt_reflect, - user=user_prompt_reflect) + with get_logger().contextualize(command="self_reflect_on_suggestions"): + response_reflect, finish_reason_reflect = await self.ai_handler.chat_completion(model=model, + system=system_prompt_reflect, + user=user_prompt_reflect) except Exception as e: get_logger().info(f"Could not reflect on suggestions, error: {e}") return "" From 4f6490b17caf47252303ca06b4d47b19c8cf3aee Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sun, 12 May 2024 16:17:47 +0300 Subject: [PATCH 164/226] Integrate self-reflection feature in PR-Agent, enhancing code suggestions with scoring and sorting, and update documentation accordingly --- README.md | 9 +++++++++ docs/docs/tools/improve.md | 4 ++++ pr_agent/tools/pr_code_suggestions.py | 3 ++- 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 097eb37b..3dca2fa2 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,15 @@ CodiumAI PR-Agent aims to help efficiently review and handle pull requests, by p ## News and Updates +### May 12, 2024 +Inspired by [AlphaCodium](https://github.com/Codium-ai/AlphaCodium) flow engineering scheme, PR-Agent now performs **self-reflection** on the code suggestions it provides, +enabling to remove invalid suggestions, and score the valid ones. The suggestions will be presented sorted by their score, enabling to focus on the most important ones first. + +<kbd><img src="https://codium.ai/images/pr_agent/self_reflection1.png" width="512"></kbd> + +<kbd><img src="https://codium.ai/images/pr_agent/self_reflection2.png" width="512"></kbd> + + ### May 2, 2024 Check out the new [PR-Agent Chrome Extension](https://chromewebstore.google.com/detail/pr-agent-chrome-extension/ephlnjeghhogofkifjloamocljapahnl) ๐Ÿš€๐Ÿš€๐Ÿš€ diff --git a/docs/docs/tools/improve.md b/docs/docs/tools/improve.md index 96001490..e8b4dd6f 100644 --- a/docs/docs/tools/improve.md +++ b/docs/docs/tools/improve.md @@ -86,6 +86,10 @@ Hence, the total number of suggestions is proportional to the number of chunks, <td><b>persistent_comment</b></td> <td>If set to true, the improve comment will be persistent, meaning that every new improve request will edit the previous one. Default is false.</td> </tr> + <tr> + <td><b>self_reflect_on_suggestions</b></td> + <td>If set to true, the improve tool will calculate an importance score for each suggestion [1-10], and sort the suggestion labels group based on this score. Default is true.</td> + </tr> <tr> <td><b>enable_help_text</b></td> <td>If set to true, the tool will display a help text in the comment. Default is true.</td> diff --git a/pr_agent/tools/pr_code_suggestions.py b/pr_agent/tools/pr_code_suggestions.py index 1d828fa5..77a4280e 100644 --- a/pr_agent/tools/pr_code_suggestions.py +++ b/pr_agent/tools/pr_code_suggestions.py @@ -351,7 +351,8 @@ class PRCodeSuggestions: if score > 0: data["code_suggestions"].append(prediction) else: - get_logger().info(f"Skipping suggestions from call {i + 1}, because score is {score}") + get_logger().info(f"Removing suggestions {i}, because score is {score}", + artifact={"prediction": prediction}) else: get_logger().error(f"Error getting PR diff, no code suggestions found in call {i + 1}") except Exception as e: From 61ba015a5597b3358c474853a84b319d6b06d3c4 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sun, 12 May 2024 16:22:40 +0300 Subject: [PATCH 165/226] artifact --- pr_agent/tools/pr_code_suggestions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pr_agent/tools/pr_code_suggestions.py b/pr_agent/tools/pr_code_suggestions.py index 77a4280e..a192e80d 100644 --- a/pr_agent/tools/pr_code_suggestions.py +++ b/pr_agent/tools/pr_code_suggestions.py @@ -352,7 +352,7 @@ class PRCodeSuggestions: data["code_suggestions"].append(prediction) else: get_logger().info(f"Removing suggestions {i}, because score is {score}", - artifact={"prediction": prediction}) + artifact=prediction) else: get_logger().error(f"Error getting PR diff, no code suggestions found in call {i + 1}") except Exception as e: From fbacc7c765f7ad329c4eed66e50669309f139ab8 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Mon, 13 May 2024 09:19:08 +0300 Subject: [PATCH 166/226] artifact --- docs/docs/tools/improve.md | 4 ++++ pr_agent/settings/configuration.toml | 2 ++ pr_agent/tools/pr_code_suggestions.py | 8 +++++--- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/docs/docs/tools/improve.md b/docs/docs/tools/improve.md index e8b4dd6f..7906f426 100644 --- a/docs/docs/tools/improve.md +++ b/docs/docs/tools/improve.md @@ -90,6 +90,10 @@ Hence, the total number of suggestions is proportional to the number of chunks, <td><b>self_reflect_on_suggestions</b></td> <td>If set to true, the improve tool will calculate an importance score for each suggestion [1-10], and sort the suggestion labels group based on this score. Default is true.</td> </tr> + <tr> + <td><b>suggestions_score_threshold</b></td> + <td> Any suggestion with importance score less than this threshold will be removed. Default is 0. Highly recommend not to set this value above 7-8, since above it may clip relevant suggestions that can be useful. </td> + </tr> <tr> <td><b>enable_help_text</b></td> <td>If set to true, the tool will display a help text in the comment. Default is true.</td> diff --git a/pr_agent/settings/configuration.toml b/pr_agent/settings/configuration.toml index c1d0dded..b84bce61 100644 --- a/pr_agent/settings/configuration.toml +++ b/pr_agent/settings/configuration.toml @@ -85,7 +85,9 @@ extra_instructions = "" rank_suggestions = false enable_help_text=false persistent_comment=false +# suggestions scoring self_reflect_on_suggestions=true +suggestions_score_threshold=0 # [0-10]. highly recommend not to set this value above 8, since above it may clip highly relevant suggestions # params for '/improve --extended' mode auto_extended_mode=true num_code_suggestions_per_chunk=4 diff --git a/pr_agent/tools/pr_code_suggestions.py b/pr_agent/tools/pr_code_suggestions.py index a192e80d..8ea9b595 100644 --- a/pr_agent/tools/pr_code_suggestions.py +++ b/pr_agent/tools/pr_code_suggestions.py @@ -344,14 +344,15 @@ class PRCodeSuggestions: data = {"code_suggestions": []} for i, predictions in enumerate(prediction_list): if "code_suggestions" in predictions: + score_threshold = max(1,get_settings().pr_code_suggestions.suggestions_score_threshold) for prediction in predictions["code_suggestions"]: try: if get_settings().pr_code_suggestions.self_reflect_on_suggestions: score = int(prediction["score"]) - if score > 0: + if score >= score_threshold: data["code_suggestions"].append(prediction) else: - get_logger().info(f"Removing suggestions {i}, because score is {score}", + get_logger().info(f"Removing suggestions {i}, because score is {score}, and score_threshold is {score_threshold}", artifact=prediction) else: get_logger().error(f"Error getting PR diff, no code suggestions found in call {i + 1}") @@ -517,11 +518,12 @@ class PRCodeSuggestions: pr_body += f"Why: {suggestion['score_why']}\n\n" pr_body += f"</details>" + pr_body += f"</details>" + # # add another column for 'score' if get_settings().pr_code_suggestions.self_reflect_on_suggestions: pr_body += f"</td><td align=center>{suggestion['score']}\n\n" - pr_body += f"</details>" pr_body += f"</td></tr>" From 6c0837491c9ea355d28565bbd343c1218014f903 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Mon, 13 May 2024 09:21:55 +0300 Subject: [PATCH 167/226] Update README.md to include info on filtering suggestions by score threshold --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 3dca2fa2..03a076fa 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,7 @@ CodiumAI PR-Agent aims to help efficiently review and handle pull requests, by p ### May 12, 2024 Inspired by [AlphaCodium](https://github.com/Codium-ai/AlphaCodium) flow engineering scheme, PR-Agent now performs **self-reflection** on the code suggestions it provides, enabling to remove invalid suggestions, and score the valid ones. The suggestions will be presented sorted by their score, enabling to focus on the most important ones first. +You can also choose to remove suggestions below a certain importance score threshold, by setting the `pr_code_suggestions.suggestions_score_threshold` [configuration](https://pr-agent-docs.codium.ai/tools/improve/#configuration-options). <kbd><img src="https://codium.ai/images/pr_agent/self_reflection1.png" width="512"></kbd> From 5fed21ce37f09a4792215b954a77ca912b1b8582 Mon Sep 17 00:00:00 2001 From: Tal <tal.r@codium.ai> Date: Mon, 13 May 2024 09:44:59 +0300 Subject: [PATCH 168/226] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 03a076fa..f7cf77e1 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,8 @@ CodiumAI PR-Agent aims to help efficiently review and handle pull requests, by p ### May 12, 2024 Inspired by [AlphaCodium](https://github.com/Codium-ai/AlphaCodium) flow engineering scheme, PR-Agent now performs **self-reflection** on the code suggestions it provides, enabling to remove invalid suggestions, and score the valid ones. The suggestions will be presented sorted by their score, enabling to focus on the most important ones first. -You can also choose to remove suggestions below a certain importance score threshold, by setting the `pr_code_suggestions.suggestions_score_threshold` [configuration](https://pr-agent-docs.codium.ai/tools/improve/#configuration-options). + +You can also choose to automatically remove suggestions below a certain importance score threshold, by setting the `pr_code_suggestions.suggestions_score_threshold` [configuration](https://pr-agent-docs.codium.ai/tools/improve/#configuration-options). <kbd><img src="https://codium.ai/images/pr_agent/self_reflection1.png" width="512"></kbd> From efd906ccf1174686246f05462d67a1e1f065fb54 Mon Sep 17 00:00:00 2001 From: Tal <tal.r@codium.ai> Date: Mon, 13 May 2024 17:52:09 +0300 Subject: [PATCH 169/226] Update .pr_agent.toml --- .pr_agent.toml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/.pr_agent.toml b/.pr_agent.toml index 0d1d9914..1b3a00ee 100644 --- a/.pr_agent.toml +++ b/.pr_agent.toml @@ -1,7 +1,3 @@ [pr_reviewer] enable_review_labels_effort = true enable_auto_approval = true - - -[pr_code_suggestions] -commitable_code_suggestions=false From 95c7b3f55c0bbdf03f6e848d62c69bf66a60ea3e Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Mon, 13 May 2024 18:03:13 +0300 Subject: [PATCH 170/226] Refactor pr_code_suggestions logic and update prompts for clarity and consistency --- .../settings/pr_code_suggestions_prompts.toml | 16 +------ .../pr_code_suggestions_reflect_prompts.toml | 6 --- pr_agent/tools/pr_code_suggestions.py | 46 +++++++++++-------- 3 files changed, 27 insertions(+), 41 deletions(-) diff --git a/pr_agent/settings/pr_code_suggestions_prompts.toml b/pr_agent/settings/pr_code_suggestions_prompts.toml index 93c2ace9..39ad5cb4 100644 --- a/pr_agent/settings/pr_code_suggestions_prompts.toml +++ b/pr_agent/settings/pr_code_suggestions_prompts.toml @@ -40,7 +40,7 @@ Specific instructions for generating code suggestions: - Suggestions should not repeat code already present in the '__new hunk__' sections. - Provide the exact line numbers range (inclusive) for each suggestion. Use the line numbers from the '__new hunk__' sections. - When quoting variables or names from the code, use backticks (`) instead of single quote ('). -- Be aware that you are reviewing a PR code diff, and that the entire codebase is not available for you as context. Hence, don't suggest changes that require knowledge of the entire codebase. +- Take into account that you are reviewing a PR code diff, and that the entire codebase is not available for you as context. Hence, avoid suggestions that might conflict with unseen parts of the codebase." {%- if extra_instructions %} @@ -59,14 +59,9 @@ class CodeSuggestion(BaseModel): relevant_file: str = Field(description="the relevant file full path") language: str = Field(description="the code language of the relevant file") suggestion_content: str = Field(description="an actionable suggestion for meaningfully improving the new code introduced in the PR") -{%- if not commitable_code_suggestions_mode %} existing_code: str = Field(description="a short code snippet from a '__new hunk__' section to illustrate the relevant existing code. Don't show the line numbers.") improved_code: str = Field(description="a short code snippet to illustrate the improved code, after applying the suggestion.") one_sentence_summary:str = Field(description="a short summary of the suggestion action, in a single sentence. Focus on the 'what'. Be general, and avoid method or variable names.") -{%- else %} - existing_code: str = Field(description="a code snippet, demonstrating the relevant code lines from a '__new hunk__' section. It must be contiguous, correctly formatted and indented, and without line numbers. Use abbreviations if needed") - improved_code: str = Field(description="If relevant, a new code snippet, that can be used to replace the relevant lines in '__new hunk__' code. Replacement suggestions should be complete, correctly formatted and indented, and without line numbers". Retrun '...' if not applicable") -{%- endif %} relevant_lines_start: int = Field(description="The relevant line number, from a '__new hunk__' section, where the suggestion starts (inclusive). Should be derived from the hunk line numbers, and correspond to the 'existing code' snippet above") relevant_lines_end: int = Field(description="The relevant line number, from a '__new hunk__' section, where the suggestion ends (inclusive). Should be derived from the hunk line numbers, and correspond to the 'existing code' snippet above") label: str = Field(description="a single label for the suggestion, to help the user understand the suggestion type. For example: 'security', 'possible bug', 'possible issue', 'performance', 'enhancement', 'best practice', 'maintainability', etc. Other labels are also allowed") @@ -85,7 +80,6 @@ code_suggestions: python suggestion_content: | ... -{%- if not commitable_code_suggestions_mode %} existing_code: | ... improved_code: | @@ -94,14 +88,6 @@ code_suggestions: ... relevant_lines_start: 12 relevant_lines_end: 13 -{%- else %} - existing_code: | - ... - relevant_lines_start: 12 - relevant_lines_end: 13 - improved_code: | - ... -{%- endif %} label: | ... ``` diff --git a/pr_agent/settings/pr_code_suggestions_reflect_prompts.toml b/pr_agent/settings/pr_code_suggestions_reflect_prompts.toml index 96e0ea1c..7c0cb785 100644 --- a/pr_agent/settings/pr_code_suggestions_reflect_prompts.toml +++ b/pr_agent/settings/pr_code_suggestions_reflect_prompts.toml @@ -46,9 +46,7 @@ __old hunk__ The output must be a YAML object equivalent to type $PRCodeSuggestionsFeedback, according to the following Pydantic definitions: ===== class CodeSuggestionFeedback(BaseModel): -{%- if not commitable_code_suggestions_mode %} suggestion_summary: str = Field(description="repeated from the input") -{%- endif %} relevant_file: str = Field(description="repeated from the input") suggestion_score: int = Field(description="The actual output - the score of the suggestion, from 0 to 10. Give 0 if the suggestion is plain wrong. Otherwise, give a score from 1 to 10 (inclusive), where 1 is the lowest and 10 is the highest.") why: str = Field(description="Short and concise explanation of why the suggestion received the score (one to two sentences).") @@ -61,13 +59,9 @@ class PRCodeSuggestionsFeedback(BaseModel): Example output: ```yaml code_suggestions: -{%- if not commitable_code_suggestions_mode %} - suggestion_content: | Use a more descriptive variable name here relevant_file: "src/file1.py" -{%- else %} -- relevant_file: "src/file1.py" -{%- endif %} suggestion_score: 6 why: | The variable name 't' is not descriptive enough diff --git a/pr_agent/tools/pr_code_suggestions.py b/pr_agent/tools/pr_code_suggestions.py index 8ea9b595..5d5d5b0f 100644 --- a/pr_agent/tools/pr_code_suggestions.py +++ b/pr_agent/tools/pr_code_suggestions.py @@ -57,7 +57,6 @@ class PRCodeSuggestions: "language": self.main_language, "diff": "", # empty diff for initial calculation "num_code_suggestions": num_code_suggestions, - "commitable_code_suggestions_mode": get_settings().pr_code_suggestions.commitable_code_suggestions, "extra_instructions": get_settings().pr_code_suggestions.extra_instructions, "commit_messages_str": self.git_provider.get_commit_messages(), } @@ -106,7 +105,8 @@ class PRCodeSuggestions: if get_settings().config.publish_output: self.git_provider.remove_initial_comment() - if (not get_settings().pr_code_suggestions.commitable_code_suggestions) and self.git_provider.is_supported("gfm_markdown"): + if ((not get_settings().pr_code_suggestions.commitable_code_suggestions) and + self.git_provider.is_supported("gfm_markdown")): # generate summarized suggestions pr_body = self.generate_summarized_suggestions(data) @@ -226,14 +226,14 @@ class PRCodeSuggestions: one_sentence_summary_list = [] for i, suggestion in enumerate(data['code_suggestions']): try: - if not get_settings().pr_code_suggestions.commitable_code_suggestions: - if not suggestion or 'one_sentence_summary' not in suggestion or 'label' not in suggestion or 'relevant_file' not in suggestion: - get_logger().debug(f"Skipping suggestion {i + 1}, because it is invalid: {suggestion}") - continue + if (not suggestion or 'one_sentence_summary' not in suggestion or + 'label' not in suggestion or 'relevant_file' not in suggestion): + get_logger().debug(f"Skipping suggestion {i + 1}, because it is invalid: {suggestion}") + continue - if suggestion['one_sentence_summary'] in one_sentence_summary_list: - get_logger().debug(f"Skipping suggestion {i + 1}, because it is a duplicate: {suggestion}") - continue + if suggestion['one_sentence_summary'] in one_sentence_summary_list: + get_logger().debug(f"Skipping suggestion {i + 1}, because it is a duplicate: {suggestion}") + continue if 'const' in suggestion['suggestion_content'] and 'instead' in suggestion['suggestion_content'] and 'let' in suggestion['suggestion_content']: get_logger().debug(f"Skipping suggestion {i + 1}, because it uses 'const instead let': {suggestion}") @@ -241,11 +241,14 @@ class PRCodeSuggestions: if ('existing_code' in suggestion) and ('improved_code' in suggestion): if suggestion['existing_code'] == suggestion['improved_code']: - get_logger().debug(f"skipping improved suggestion {i + 1}, because equal to existing code: {suggestion['existing_code']}") - suggestion['existing_code'] = "" + get_logger().debug( + f"edited improved suggestion {i + 1}, because equal to existing code: {suggestion['existing_code']}") + if get_settings().pr_code_suggestions.commitable_code_suggestions: + suggestion['improved_code'] = "" # we need 'existing_code' to locate the code in the PR + else: + suggestion['existing_code'] = "" suggestion = self._truncate_if_needed(suggestion) - if not get_settings().pr_code_suggestions.commitable_code_suggestions: - one_sentence_summary_list.append(suggestion['one_sentence_summary']) + one_sentence_summary_list.append(suggestion['one_sentence_summary']) suggestion_list.append(suggestion) else: get_logger().info( @@ -278,7 +281,10 @@ class PRCodeSuggestions: if new_code_snippet: new_code_snippet = self.dedent_code(relevant_file, relevant_lines_start, new_code_snippet) - body = f"**Suggestion:** {content} [{label}]\n```suggestion\n" + new_code_snippet + "\n```" + if d.get('score'): + body = f"**Suggestion:** {content} [{label}, importance: {d.get('score')}]\n```suggestion\n" + new_code_snippet + "\n```" + else: + body = f"**Suggestion:** {content} [{label}]\n```suggestion\n" + new_code_snippet + "\n```" code_suggestions.append({'body': body, 'relevant_file': relevant_file, 'relevant_lines_start': relevant_lines_start, 'relevant_lines_end': relevant_lines_end}) @@ -327,7 +333,8 @@ class PRCodeSuggestions: self.patches_diff_list = get_pr_multi_diffs(self.git_provider, self.token_handler, model, max_calls=get_settings().pr_code_suggestions.max_number_of_calls) if self.patches_diff_list: - get_logger().debug(f"PR diff", artifact=self.patches_diff_list) + get_logger().info(f"Number of PR chunk calls: {len(self.patches_diff_list)}") + get_logger().debug(f"PR diff:", artifact=self.patches_diff_list) # parallelize calls to AI: if get_settings().pr_code_suggestions.parallel_calls: @@ -342,10 +349,10 @@ class PRCodeSuggestions: data = {"code_suggestions": []} - for i, predictions in enumerate(prediction_list): - if "code_suggestions" in predictions: + for predictions in enumerate(prediction_list): + if "code_suggestions" in enumerate(predictions): score_threshold = max(1,get_settings().pr_code_suggestions.suggestions_score_threshold) - for prediction in predictions["code_suggestions"]: + for i, prediction in predictions["code_suggestions"]: try: if get_settings().pr_code_suggestions.self_reflect_on_suggestions: score = int(prediction["score"]) @@ -547,8 +554,7 @@ class PRCodeSuggestions: variables = {'suggestion_list': suggestion_list, 'suggestion_str': suggestion_str, "diff": patches_diff, - 'num_code_suggestions': len(suggestion_list), - 'commitable_code_suggestions_mode': get_settings().pr_code_suggestions.commitable_code_suggestions,} + 'num_code_suggestions': len(suggestion_list)} model = get_settings().config.model environment = Environment(undefined=StrictUndefined) system_prompt_reflect = environment.from_string(get_settings().pr_code_suggestions_reflect_prompt.system).render( From b0aac4ec5d15a9ba25ddff42cb6c427793a034dc Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Mon, 13 May 2024 18:13:37 +0300 Subject: [PATCH 171/226] Refactor pr_code_suggestions logic and update prompts for clarity and consistency --- pr_agent/tools/pr_code_suggestions.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/pr_agent/tools/pr_code_suggestions.py b/pr_agent/tools/pr_code_suggestions.py index 5d5d5b0f..9b46dabe 100644 --- a/pr_agent/tools/pr_code_suggestions.py +++ b/pr_agent/tools/pr_code_suggestions.py @@ -347,22 +347,22 @@ class PRCodeSuggestions: prediction = await self._get_prediction(model, patches_diff) prediction_list.append(prediction) - data = {"code_suggestions": []} - for predictions in enumerate(prediction_list): - if "code_suggestions" in enumerate(predictions): - score_threshold = max(1,get_settings().pr_code_suggestions.suggestions_score_threshold) - for i, prediction in predictions["code_suggestions"]: + for j, predictions in enumerate(prediction_list): # each call adds an element to the list + if "code_suggestions" in predictions: + score_threshold = max(1, get_settings().pr_code_suggestions.suggestions_score_threshold) + for i, prediction in enumerate(predictions["code_suggestions"]): try: if get_settings().pr_code_suggestions.self_reflect_on_suggestions: score = int(prediction["score"]) if score >= score_threshold: data["code_suggestions"].append(prediction) else: - get_logger().info(f"Removing suggestions {i}, because score is {score}, and score_threshold is {score_threshold}", - artifact=prediction) + get_logger().info( + f"Removing suggestions {i} from call {j}, because score is {score}, and score_threshold is {score_threshold}", + artifact=prediction) else: - get_logger().error(f"Error getting PR diff, no code suggestions found in call {i + 1}") + data["code_suggestions"].append(prediction) except Exception as e: get_logger().error(f"Error getting PR diff, error: {e}") self.data = data From f3eb74d71883d670857527d8fe6f1c7b6f34cc7d Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Mon, 13 May 2024 18:18:17 +0300 Subject: [PATCH 172/226] Refactor pr_code_suggestions logic and update prompts for clarity and consistency --- pr_agent/tools/pr_code_suggestions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pr_agent/tools/pr_code_suggestions.py b/pr_agent/tools/pr_code_suggestions.py index 9b46dabe..e6b8c217 100644 --- a/pr_agent/tools/pr_code_suggestions.py +++ b/pr_agent/tools/pr_code_suggestions.py @@ -364,7 +364,7 @@ class PRCodeSuggestions: else: data["code_suggestions"].append(prediction) except Exception as e: - get_logger().error(f"Error getting PR diff, error: {e}") + get_logger().error(f"Error getting PR diff for suggestion {i} in call {j}, error: {e}") self.data = data else: get_logger().error(f"Error getting PR diff") From 05876afc02df2108206a999d484a8de9cb06e085 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Mon, 13 May 2024 18:21:31 +0300 Subject: [PATCH 173/226] Refactor pr_code_suggestions logic and update prompts for clarity and consistency --- pr_agent/settings/pr_code_suggestions_prompts.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pr_agent/settings/pr_code_suggestions_prompts.toml b/pr_agent/settings/pr_code_suggestions_prompts.toml index 39ad5cb4..f3a1089b 100644 --- a/pr_agent/settings/pr_code_suggestions_prompts.toml +++ b/pr_agent/settings/pr_code_suggestions_prompts.toml @@ -40,7 +40,7 @@ Specific instructions for generating code suggestions: - Suggestions should not repeat code already present in the '__new hunk__' sections. - Provide the exact line numbers range (inclusive) for each suggestion. Use the line numbers from the '__new hunk__' sections. - When quoting variables or names from the code, use backticks (`) instead of single quote ('). -- Take into account that you are reviewing a PR code diff, and that the entire codebase is not available for you as context. Hence, avoid suggestions that might conflict with unseen parts of the codebase." +- Take into account that you are reviewing a PR code diff, and that the entire codebase is not available for you as context. Hence, avoid suggestions that might conflict with unseen parts of the codebase. {%- if extra_instructions %} From 9dd2520dbd97629d8c1b9682f2ebbe9519f234d2 Mon Sep 17 00:00:00 2001 From: KennyDizi <xamarindevelopervietnam@outlook.com> Date: Tue, 14 May 2024 08:21:41 +0700 Subject: [PATCH 174/226] Update tiktoken to 0.7.0 --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 924d2bb2..283a319a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -19,7 +19,7 @@ PyYAML==6.0.1 python-gitlab==3.15.0 retry==0.9.2 starlette-context==0.3.6 -tiktoken==0.5.2 +tiktoken==0.7.0 ujson==5.8.0 uvicorn==0.22.0 tenacity==8.2.3 From 36ad8935ad47e2362ca1a4d498b8c31867457db9 Mon Sep 17 00:00:00 2001 From: KennyDizi <xamarindevelopervietnam@outlook.com> Date: Tue, 14 May 2024 08:24:34 +0700 Subject: [PATCH 175/226] Add gpt-4o models --- pr_agent/algo/__init__.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pr_agent/algo/__init__.py b/pr_agent/algo/__init__.py index cab47378..f22eb97c 100644 --- a/pr_agent/algo/__init__.py +++ b/pr_agent/algo/__init__.py @@ -11,6 +11,8 @@ MAX_TOKENS = { 'gpt-4-32k': 32000, 'gpt-4-1106-preview': 128000, # 128K, but may be limited by config.max_model_tokens 'gpt-4-0125-preview': 128000, # 128K, but may be limited by config.max_model_tokens + 'gpt-4o': 128000, # 128K, but may be limited by config.max_model_tokens + 'gpt-4o-2024-05-13': 128000, # 128K, but may be limited by config.max_model_tokens 'gpt-4-turbo-preview': 128000, # 128K, but may be limited by config.max_model_tokens 'gpt-4-turbo-2024-04-09': 128000, # 128K, but may be limited by config.max_model_tokens 'gpt-4-turbo': 128000, # 128K, but may be limited by config.max_model_tokens From e4565f7106f64c10f43740916900e318d719264d Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Tue, 14 May 2024 21:43:14 +0300 Subject: [PATCH 176/226] Refactor Azure DevOps provider to use PR iterations for change detection, improving accuracy of diff file identification --- .../git_providers/azuredevops_provider.py | 76 ++++++++++++------- 1 file changed, 50 insertions(+), 26 deletions(-) diff --git a/pr_agent/git_providers/azuredevops_provider.py b/pr_agent/git_providers/azuredevops_provider.py index a710c254..048a2a95 100644 --- a/pr_agent/git_providers/azuredevops_provider.py +++ b/pr_agent/git_providers/azuredevops_provider.py @@ -26,6 +26,7 @@ try: CommentThread, GitVersionDescriptor, GitPullRequest, + GitPullRequestIterationChanges, ) except ImportError: AZURE_DEVOPS_AVAILABLE = False @@ -230,29 +231,56 @@ class AzureDevopsProvider(GitProvider): base_sha = self.pr.last_merge_target_commit head_sha = self.pr.last_merge_source_commit - commits = self.azure_devops_client.get_pull_request_commits( - project=self.workspace_slug, + # Get PR iterations + iterations = self.azure_devops_client.get_pull_request_iterations( repository_id=self.repo_slug, pull_request_id=self.pr_num, + project=self.workspace_slug ) + changes = [] + if iterations: + iteration_id = iterations[-1].id # Get the last iteration (most recent changes) + # Get changes for the iteration + changes: GitPullRequestIterationChanges = self.azure_devops_client.get_pull_request_iteration_changes( + repository_id=self.repo_slug, + pull_request_id=self.pr_num, + iteration_id=iteration_id, + project=self.workspace_slug + ) diff_files = [] diffs = [] diff_types = {} + if changes: + for change in changes.change_entries: + c = change.additional_properties['item'] + diffs.append(c['path']) + diff_types[c['path']] = change.additional_properties['changeType'] - for c in commits: - changes_obj = self.azure_devops_client.get_changes( - project=self.workspace_slug, - repository_id=self.repo_slug, - commit_id=c.commit_id, - ) - for i in changes_obj.changes: - if i["item"]["gitObjectType"] == "tree": - continue - diffs.append(i["item"]["path"]) - diff_types[i["item"]["path"]] = i["changeType"] + # wrong implementation - gets all the files that were changed in any commit in the PR + # commits = self.azure_devops_client.get_pull_request_commits( + # project=self.workspace_slug, + # repository_id=self.repo_slug, + # pull_request_id=self.pr_num, + # ) + # + # diff_files = [] + # diffs = [] + # diff_types = {} - diffs = list(set(diffs)) + # for c in commits: + # changes_obj = self.azure_devops_client.get_changes( + # project=self.workspace_slug, + # repository_id=self.repo_slug, + # commit_id=c.commit_id, + # ) + # for i in changes_obj.changes: + # if i["item"]["gitObjectType"] == "tree": + # continue + # diffs.append(i["item"]["path"]) + # diff_types[i["item"]["path"]] = i["changeType"] + # + # diffs = list(set(diffs)) for file in diffs: if not is_valid_file(file): @@ -273,12 +301,13 @@ class AzureDevopsProvider(GitProvider): new_file_content_str = new_file_content_str.content except Exception as error: - get_logger().error( - "Failed to retrieve new file content of %s at version %s. Error: %s", - file, - version, - str(error), - ) + get_logger().error(f"Failed to retrieve new file content of {file} at version {version}. Error: {str(error)}") + # get_logger().error( + # "Failed to retrieve new file content of %s at version %s. Error: %s", + # file, + # version, + # str(error), + # ) new_file_content_str = "" edit_type = EDIT_TYPE.MODIFIED @@ -303,12 +332,7 @@ class AzureDevopsProvider(GitProvider): ) original_file_content_str = original_file_content_str.content except Exception as error: - get_logger().error( - "Failed to retrieve original file content of %s at version %s. Error: %s", - file, - version, - str(error), - ) + get_logger().error(f"Failed to retrieve original file content of {file} at version {version}. Error: {str(error)}") original_file_content_str = "" patch = load_large_diff( From e56320540b8f696cbd74b45daf5e85d24718dbc5 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Wed, 15 May 2024 09:05:01 +0300 Subject: [PATCH 177/226] Refactor Azure DevOps provider to use PR iterations for change detection, improving accuracy of diff file identification --- pr_agent/algo/utils.py | 4 ++-- pr_agent/git_providers/azuredevops_provider.py | 8 ++++---- pr_agent/settings/configuration.toml | 8 ++++---- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/pr_agent/algo/utils.py b/pr_agent/algo/utils.py index b877106d..e2f7f8ba 100644 --- a/pr_agent/algo/utils.py +++ b/pr_agent/algo/utils.py @@ -356,7 +356,7 @@ def convert_str_to_datetime(date_str): return datetime.strptime(date_str, datetime_format) -def load_large_diff(filename, new_file_content_str: str, original_file_content_str: str) -> str: +def load_large_diff(filename, new_file_content_str: str, original_file_content_str: str, show_warning: bool = True) -> str: """ Generate a patch for a modified file by comparing the original content of the file with the new content provided as input. @@ -375,7 +375,7 @@ def load_large_diff(filename, new_file_content_str: str, original_file_content_s try: diff = difflib.unified_diff(original_file_content_str.splitlines(keepends=True), new_file_content_str.splitlines(keepends=True)) - if get_settings().config.verbosity_level >= 2: + if get_settings().config.verbosity_level >= 2 and show_warning: get_logger().warning(f"File was modified, but no patch was found. Manually creating patch: {filename}.") patch = ''.join(diff) except Exception: diff --git a/pr_agent/git_providers/azuredevops_provider.py b/pr_agent/git_providers/azuredevops_provider.py index 048a2a95..1129bd8a 100644 --- a/pr_agent/git_providers/azuredevops_provider.py +++ b/pr_agent/git_providers/azuredevops_provider.py @@ -237,12 +237,12 @@ class AzureDevopsProvider(GitProvider): pull_request_id=self.pr_num, project=self.workspace_slug ) - changes = [] + changes = None if iterations: iteration_id = iterations[-1].id # Get the last iteration (most recent changes) # Get changes for the iteration - changes: GitPullRequestIterationChanges = self.azure_devops_client.get_pull_request_iteration_changes( + changes = self.azure_devops_client.get_pull_request_iteration_changes( repository_id=self.repo_slug, pull_request_id=self.pr_num, iteration_id=iteration_id, @@ -336,8 +336,8 @@ class AzureDevopsProvider(GitProvider): original_file_content_str = "" patch = load_large_diff( - file, new_file_content_str, original_file_content_str - ) + file, new_file_content_str, original_file_content_str, show_warning=False + ).rstrip() diff_files.append( FilePatchInfo( diff --git a/pr_agent/settings/configuration.toml b/pr_agent/settings/configuration.toml index b84bce61..691faec8 100644 --- a/pr_agent/settings/configuration.toml +++ b/pr_agent/settings/configuration.toml @@ -2,10 +2,10 @@ model="gpt-4-turbo-2024-04-09" model_turbo="gpt-4-turbo-2024-04-09" fallback_models=["gpt-4-0125-preview"] -git_provider="github" -publish_output=true +git_provider="azure" +publish_output=false publish_output_progress=true -verbosity_level=0 # 0,1,2 +verbosity_level=2 # 0,1,2 use_extra_bad_extensions=false use_wiki_settings_file=true use_repo_settings_file=true @@ -80,7 +80,7 @@ enable_help_text=false [pr_code_suggestions] # /improve # max_context_tokens=8000 num_code_suggestions=4 -commitable_code_suggestions = false +commitable_code_suggestions = true extra_instructions = "" rank_suggestions = false enable_help_text=false From 4231a84e7a6d3b10b5dc15ea89c79eeeb81420c5 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Wed, 15 May 2024 09:15:12 +0300 Subject: [PATCH 178/226] Refactor Azure DevOps provider to use PR iterations for change detection, improving accuracy of diff file identification --- pr_agent/git_providers/azuredevops_provider.py | 8 +++++--- pr_agent/settings/configuration.toml | 8 ++++---- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/pr_agent/git_providers/azuredevops_provider.py b/pr_agent/git_providers/azuredevops_provider.py index 1129bd8a..ee3a116f 100644 --- a/pr_agent/git_providers/azuredevops_provider.py +++ b/pr_agent/git_providers/azuredevops_provider.py @@ -253,9 +253,11 @@ class AzureDevopsProvider(GitProvider): diff_types = {} if changes: for change in changes.change_entries: - c = change.additional_properties['item'] - diffs.append(c['path']) - diff_types[c['path']] = change.additional_properties['changeType'] + item = change.additional_properties.get('item', {}) + path = item.get('path', None) + if path: + diffs.append(path) + diff_types[path] = change.additional_properties.get('changeType', 'Unknown') # wrong implementation - gets all the files that were changed in any commit in the PR # commits = self.azure_devops_client.get_pull_request_commits( diff --git a/pr_agent/settings/configuration.toml b/pr_agent/settings/configuration.toml index 691faec8..b84bce61 100644 --- a/pr_agent/settings/configuration.toml +++ b/pr_agent/settings/configuration.toml @@ -2,10 +2,10 @@ model="gpt-4-turbo-2024-04-09" model_turbo="gpt-4-turbo-2024-04-09" fallback_models=["gpt-4-0125-preview"] -git_provider="azure" -publish_output=false +git_provider="github" +publish_output=true publish_output_progress=true -verbosity_level=2 # 0,1,2 +verbosity_level=0 # 0,1,2 use_extra_bad_extensions=false use_wiki_settings_file=true use_repo_settings_file=true @@ -80,7 +80,7 @@ enable_help_text=false [pr_code_suggestions] # /improve # max_context_tokens=8000 num_code_suggestions=4 -commitable_code_suggestions = true +commitable_code_suggestions = false extra_instructions = "" rank_suggestions = false enable_help_text=false From 589b865db5e2b9b9ed2113afe83f5dc905493531 Mon Sep 17 00:00:00 2001 From: Tal <tal.r@codium.ai> Date: Wed, 15 May 2024 10:31:57 +0300 Subject: [PATCH 179/226] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index f7cf77e1..410957c2 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ CodiumAI PR-Agent aims to help efficiently review and handle pull requests, by p </div> [![GitHub license](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://github.com/Codium-ai/pr-agent/blob/main/LICENSE) +[![Static Badge](https://img.shields.io/badge/Chrome-Extension-violet)](https://chromewebstore.google.com/detail/pr-agent-chrome-extension/ephlnjeghhogofkifjloamocljapahnl) [![Discord](https://badgen.net/badge/icon/discord?icon=discord&label&color=purple)](https://discord.com/channels/1057273017547378788/1126104260430528613) [![Twitter](https://img.shields.io/twitter/follow/codiumai)](https://twitter.com/codiumai) <a href="https://github.com/Codium-ai/pr-agent/commits/main"> From 0ab19b84b2ee24f489aa5fb2135deeb8339acd37 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Thu, 16 May 2024 09:12:55 +0300 Subject: [PATCH 180/226] Add documentation for PR-Agent Chrome Extension and update mkdocs.yml to include new section --- docs/docs/chrome-extension/index.md | 22 ++++++++++++++++++++++ docs/mkdocs.yml | 1 + 2 files changed, 23 insertions(+) create mode 100644 docs/docs/chrome-extension/index.md diff --git a/docs/docs/chrome-extension/index.md b/docs/docs/chrome-extension/index.md new file mode 100644 index 00000000..6e338f15 --- /dev/null +++ b/docs/docs/chrome-extension/index.md @@ -0,0 +1,22 @@ +## PR-Agent chrome extension + +- PR-Agent Chrome extension ia a toolbar that integrates seamlessly with your GitHub environment, allowing you to access PR-Agent tools directly from the GitHub interface. +- With PR-Agent Chrome extension, it's [easier than ever](https://www.youtube.com/watch?v=gT5tli7X4H4) to interactively configuring and experimenting with the different tools and configuration options. +- After you found the setup that works for you, you can also easily export it as a persistent configuration file, and use it for the automatic commands. + +<kbd><img src="https://codium.ai/images/pr_agent/toolbar1.png" width="512"></kbd> + +<kbd><img src="https://codium.ai/images/pr_agent/toolbar2.png" width="512"></kbd> + +## Installation + +Go to the marketplace and install the extension: +[PR-Agent Chrome Extension](https://chromewebstore.google.com/detail/pr-agent-chrome-extension/ephlnjeghhogofkifjloamocljapahnl) + +## Pre-requisites + +The PR-Agent Chrome extension will work on any repo where you have previously [installed PR-Agent](https://pr-agent-docs.codium.ai/installation/). + +## Data privacy and security + +The PR-Agent Chrome extension only modifies the visual appearance of a GitHub PR screen. It does not transmit any user's repo or pull request code. Code is only sent for processing when a user submits a GitHub comment that activates a PR-Agent tool, in accordance with the standard privacy policy of PR-Agent. diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index 4e6ad2ca..272d5394 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -37,6 +37,7 @@ nav: - ๐Ÿ’Ž CI Feedback: 'tools/ci_feedback.md' - ๐Ÿ’Ž Similar Code: 'tools/similar_code.md' - Core Abilities: 'core-abilities/index.md' + - Chrome Extension: 'chrome-extension/index.md' theme: logo: assets/logo.svg From 8599c0fed4e1edc2923d54873bff9135b14d9f40 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Thu, 16 May 2024 09:17:26 +0300 Subject: [PATCH 181/226] Add documentation for PR-Agent Chrome Extension and update mkdocs.yml to include new section --- docs/docs/chrome-extension/index.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/docs/chrome-extension/index.md b/docs/docs/chrome-extension/index.md index 6e338f15..9095b7fa 100644 --- a/docs/docs/chrome-extension/index.md +++ b/docs/docs/chrome-extension/index.md @@ -1,7 +1,7 @@ ## PR-Agent chrome extension -- PR-Agent Chrome extension ia a toolbar that integrates seamlessly with your GitHub environment, allowing you to access PR-Agent tools directly from the GitHub interface. -- With PR-Agent Chrome extension, it's [easier than ever](https://www.youtube.com/watch?v=gT5tli7X4H4) to interactively configuring and experimenting with the different tools and configuration options. +- PR-Agent Chrome extension is a toolbar that integrates seamlessly with your GitHub environment, allowing you to access PR-Agent tools directly from the GitHub interface. +- With PR-Agent Chrome extension, it's [easier than ever](https://www.youtube.com/watch?v=gT5tli7X4H4) to interactively experiment with the different tools and configuration options. - After you found the setup that works for you, you can also easily export it as a persistent configuration file, and use it for the automatic commands. <kbd><img src="https://codium.ai/images/pr_agent/toolbar1.png" width="512"></kbd> @@ -15,8 +15,8 @@ Go to the marketplace and install the extension: ## Pre-requisites -The PR-Agent Chrome extension will work on any repo where you have previously [installed PR-Agent](https://pr-agent-docs.codium.ai/installation/). +The PR-Agent Chrome extension will work on any repo where you have previously [installed PR-Agent](https://pr-agent-docs.codium.ai/installation/) (both for free and pro users). ## Data privacy and security -The PR-Agent Chrome extension only modifies the visual appearance of a GitHub PR screen. It does not transmit any user's repo or pull request code. Code is only sent for processing when a user submits a GitHub comment that activates a PR-Agent tool, in accordance with the standard privacy policy of PR-Agent. +The PR-Agent Chrome extension only modifies the visual appearance of a GitHub PR screen. It does not transmit any user's repo or pull request code. Code is only sent for processing when a user submits a GitHub comment that activates a PR-Agent tool, in accordance with the standard [privacy policy of PR-Agent](https://pr-agent-docs.codium.ai/#pr-agent-chrome-extension). From 570f7d6dcf7a19277cdb6a8c79696a3561cf38fe Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Thu, 16 May 2024 10:55:51 +0300 Subject: [PATCH 182/226] Add roadmap section to Chrome Extension documentation with visual preview --- docs/docs/chrome-extension/index.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/docs/chrome-extension/index.md b/docs/docs/chrome-extension/index.md index 9095b7fa..59623046 100644 --- a/docs/docs/chrome-extension/index.md +++ b/docs/docs/chrome-extension/index.md @@ -20,3 +20,9 @@ The PR-Agent Chrome extension will work on any repo where you have previously [i ## Data privacy and security The PR-Agent Chrome extension only modifies the visual appearance of a GitHub PR screen. It does not transmit any user's repo or pull request code. Code is only sent for processing when a user submits a GitHub comment that activates a PR-Agent tool, in accordance with the standard [privacy policy of PR-Agent](https://pr-agent-docs.codium.ai/#pr-agent-chrome-extension). + +## Roadmap + +Stay tuned ... + +<kbd><img src="https://codium.ai/images/pr_agent/chrome_extension_roadmap.png" width="512"></kbd> From cc08394e51e5ae573d550c9d15c9318c7739e70e Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Thu, 16 May 2024 21:49:06 +0300 Subject: [PATCH 183/226] Refine field descriptions in pr_code_suggestions_prompts.toml and comment out default scoring error log in pr_code_suggestions.py --- pr_agent/settings/pr_code_suggestions_prompts.toml | 4 ++-- pr_agent/tools/pr_code_suggestions.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pr_agent/settings/pr_code_suggestions_prompts.toml b/pr_agent/settings/pr_code_suggestions_prompts.toml index f3a1089b..bf8b4dc7 100644 --- a/pr_agent/settings/pr_code_suggestions_prompts.toml +++ b/pr_agent/settings/pr_code_suggestions_prompts.toml @@ -59,8 +59,8 @@ class CodeSuggestion(BaseModel): relevant_file: str = Field(description="the relevant file full path") language: str = Field(description="the code language of the relevant file") suggestion_content: str = Field(description="an actionable suggestion for meaningfully improving the new code introduced in the PR") - existing_code: str = Field(description="a short code snippet from a '__new hunk__' section to illustrate the relevant existing code. Don't show the line numbers.") - improved_code: str = Field(description="a short code snippet to illustrate the improved code, after applying the suggestion.") + existing_code: str = Field(description="a short code snippet, demonstrating the relevant code lines from a '__new hunk__' section. It must without line numbers. Use abbreviations if needed") + improved_code: str = Field(description="a new code snippet, that can be used to replace the relevant 'existing_code' lines in '__new hunk__' code after applying the suggestion") one_sentence_summary:str = Field(description="a short summary of the suggestion action, in a single sentence. Focus on the 'what'. Be general, and avoid method or variable names.") relevant_lines_start: int = Field(description="The relevant line number, from a '__new hunk__' section, where the suggestion starts (inclusive). Should be derived from the hunk line numbers, and correspond to the 'existing code' snippet above") relevant_lines_end: int = Field(description="The relevant line number, from a '__new hunk__' section, where the suggestion ends (inclusive). Should be derived from the hunk line numbers, and correspond to the 'existing code' snippet above") diff --git a/pr_agent/tools/pr_code_suggestions.py b/pr_agent/tools/pr_code_suggestions.py index e6b8c217..a3f0abd1 100644 --- a/pr_agent/tools/pr_code_suggestions.py +++ b/pr_agent/tools/pr_code_suggestions.py @@ -196,7 +196,7 @@ class PRCodeSuggestions: suggestion["score"] = 7 suggestion["score_why"] = "" else: - get_logger().error(f"Could not self-reflect on suggestions. using default score 7") + # get_logger().error(f"Could not self-reflect on suggestions. using default score 7") for i, suggestion in enumerate(data["code_suggestions"]): suggestion["score"] = 7 suggestion["score_why"] = "" From 46e934772c9ce418ee8bb41f5b0be3ed862d8dc0 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Thu, 16 May 2024 21:55:02 +0300 Subject: [PATCH 184/226] Rename "Custom Suggestions" feature to "Custom Prompt" across documentation, README, and tool references --- README.md | 48 +++++++-------- docs/docs/index.md | 58 +++++++++---------- ...custom_suggestions.md => custom_prompt.md} | 21 +++---- docs/docs/tools/improve.md | 2 +- docs/docs/tools/index.md | 4 +- docs/mkdocs.yml | 2 +- pr_agent/tools/pr_help_message.py | 8 +-- 7 files changed, 70 insertions(+), 73 deletions(-) rename docs/docs/tools/{custom_suggestions.md => custom_prompt.md} (64%) diff --git a/README.md b/README.md index 03a076fa..2bf293b7 100644 --- a/README.md +++ b/README.md @@ -99,40 +99,40 @@ If set to true, the tool will add a section that checks if the PR contains sever Supported commands per platform: -| | | GitHub | Gitlab | Bitbucket | Azure DevOps | -|-------|-------------------------------------------------------------------------------------------------------------------|:--------------------:|:--------------------:|:--------------------:|:--------------------:| -| TOOLS | Review | โœ… | โœ… | โœ… | โœ… | -| | โฎ‘ Incremental | โœ… | | | | +| | | GitHub | Gitlab | Bitbucket | Azure DevOps | +|-------|---------------------------------------------------------------------------------------------------------|:--------------------:|:--------------------:|:--------------------:|:--------------------:| +| TOOLS | Review | โœ… | โœ… | โœ… | โœ… | +| | โฎ‘ Incremental | โœ… | | | | | | โฎ‘ [SOC2 Compliance](https://pr-agent-docs.codium.ai/tools/review/#soc2-ticket-compliance) ๐Ÿ’Ž | โœ… | โœ… | โœ… | โœ… | -| | Describe | โœ… | โœ… | โœ… | โœ… | +| | Describe | โœ… | โœ… | โœ… | โœ… | | | โฎ‘ [Inline File Summary](https://pr-agent-docs.codium.ai/tools/describe#inline-file-summary) ๐Ÿ’Ž | โœ… | | | | -| | Improve | โœ… | โœ… | โœ… | โœ… | -| | โฎ‘ Extended | โœ… | โœ… | โœ… | โœ… | -| | Ask | โœ… | โœ… | โœ… | โœ… | +| | Improve | โœ… | โœ… | โœ… | โœ… | +| | โฎ‘ Extended | โœ… | โœ… | โœ… | โœ… | +| | Ask | โœ… | โœ… | โœ… | โœ… | | | โฎ‘ [Ask on code lines](https://pr-agent-docs.codium.ai/tools/ask#ask-lines) | โœ… | โœ… | | | -| | [Custom Suggestions](https://pr-agent-docs.codium.ai/tools/custom_suggestions/) ๐Ÿ’Ž | โœ… | โœ… | โœ… | โœ… | +| | [Custom Prompt](https://pr-agent-docs.codium.ai/tools/custom_prompt/) ๐Ÿ’Ž | โœ… | โœ… | โœ… | โœ… | | | [Test](https://pr-agent-docs.codium.ai/tools/test/) ๐Ÿ’Ž | โœ… | โœ… | | โœ… | -| | Reflect and Review | โœ… | โœ… | โœ… | โœ… | -| | Update CHANGELOG.md | โœ… | โœ… | โœ… | โœ… | -| | Find Similar Issue | โœ… | | | | +| | Reflect and Review | โœ… | โœ… | โœ… | โœ… | +| | Update CHANGELOG.md | โœ… | โœ… | โœ… | โœ… | +| | Find Similar Issue | โœ… | | | | | | [Add PR Documentation](https://pr-agent-docs.codium.ai/tools/documentation/) ๐Ÿ’Ž | โœ… | โœ… | | โœ… | | | [Custom Labels](https://pr-agent-docs.codium.ai/tools/custom_labels/) ๐Ÿ’Ž | โœ… | โœ… | | โœ… | | | [Analyze](https://pr-agent-docs.codium.ai/tools/analyze/) ๐Ÿ’Ž | โœ… | โœ… | | โœ… | | | [CI Feedback](https://pr-agent-docs.codium.ai/tools/ci_feedback/) ๐Ÿ’Ž | โœ… | | | | | | [Similar Code](https://pr-agent-docs.codium.ai/tools/similar_code/) ๐Ÿ’Ž | โœ… | | | | -| | | | | | | -| USAGE | CLI | โœ… | โœ… | โœ… | โœ… | -| | App / webhook | โœ… | โœ… | โœ… | โœ… | -| | Tagging bot | โœ… | | | | -| | Actions | โœ… | | โœ… | | -| | | | | | | -| CORE | PR compression | โœ… | โœ… | โœ… | โœ… | -| | Repo language prioritization | โœ… | โœ… | โœ… | โœ… | -| | Adaptive and token-aware file patch fitting | โœ… | โœ… | โœ… | โœ… | -| | Multiple models support | โœ… | โœ… | โœ… | โœ… | +| | | | | | | +| USAGE | CLI | โœ… | โœ… | โœ… | โœ… | +| | App / webhook | โœ… | โœ… | โœ… | โœ… | +| | Tagging bot | โœ… | | | | +| | Actions | โœ… | | โœ… | | +| | | | | | | +| CORE | PR compression | โœ… | โœ… | โœ… | โœ… | +| | Repo language prioritization | โœ… | โœ… | โœ… | โœ… | +| | Adaptive and token-aware file patch fitting | โœ… | โœ… | โœ… | โœ… | +| | Multiple models support | โœ… | โœ… | โœ… | โœ… | | | [Static code analysis](https://pr-agent-docs.codium.ai/core-abilities/#static-code-analysis) ๐Ÿ’Ž | โœ… | โœ… | โœ… | โœ… | | | [Global and wiki configurations](https://pr-agent-docs.codium.ai/usage-guide/configuration_options/) ๐Ÿ’Ž | โœ… | โœ… | โœ… | โœ… | -| | [PR interactive actions](https://www.codium.ai/images/pr_agent/pr-actions.mp4) ๐Ÿ’Ž | โœ… | | | | +| | [PR interactive actions](https://www.codium.ai/images/pr_agent/pr-actions.mp4) ๐Ÿ’Ž | โœ… | | | | - ๐Ÿ’Ž means this feature is available only in [PR-Agent Pro](https://www.codium.ai/pricing/) [//]: # (- Support for additional git providers is described in [here](./docs/Full_environments.md)) @@ -156,7 +156,7 @@ ___ \ โ€ฃ **Analyze ๐Ÿ’Ž ([`/analyze`](https://pr-agent-docs.codium.ai/tools/analyze/))**: Identify code components that changed in the PR, and enables to interactively generate tests, docs, and code suggestions for each component. \ -โ€ฃ **Custom Suggestions ๐Ÿ’Ž ([`/custom_suggestions`](https://pr-agent-docs.codium.ai/tools/custom_suggestions/))**: Automatically generates custom suggestions for improving the PR code, based on specific guidelines defined by the user. +โ€ฃ **Custom Prompt ๐Ÿ’Ž ([`/custom_prompt`](https://pr-agent-docs.codium.ai/tools/custom_prompt/))**: Automatically generates custom suggestions for improving the PR code, based on specific guidelines defined by the user. \ โ€ฃ **Generate Tests ๐Ÿ’Ž ([`/test component_name`](https://pr-agent-docs.codium.ai/tools/test/))**: Generates unit tests for a selected component, based on the PR code changes. \ diff --git a/docs/docs/index.md b/docs/docs/index.md index 06021105..a131bd51 100644 --- a/docs/docs/index.md +++ b/docs/docs/index.md @@ -12,35 +12,35 @@ CodiumAI PR-Agent is an open-source tool to help efficiently review and handle p ## PR-Agent Features PR-Agent offers extensive pull request functionalities across various git providers. -| | | GitHub | Gitlab | Bitbucket | Azure DevOps | -|-------|---------------------------------------------------------------------------------------------------------------------|:------:|:------:|:---------:|:------------:| -| TOOLS | Review | โœ… | โœ… | โœ… | โœ… | -| | โฎ‘ Incremental | โœ… | | | | -| | โฎ‘ [SOC2 Compliance](https://pr-agent-docs.codium.ai/tools/review/#soc2-ticket-compliance){:target="_blank"} ๐Ÿ’Ž | โœ… | โœ… | โœ… | โœ… | -| | Ask | โœ… | โœ… | โœ… | โœ… | -| | Describe | โœ… | โœ… | โœ… | โœ… | -| | โฎ‘ [Inline file summary](https://pr-agent-docs.codium.ai/tools/describe/#inline-file-summary){:target="_blank"} ๐Ÿ’Ž | โœ… | โœ… | | โœ… | -| | Improve | โœ… | โœ… | โœ… | โœ… | -| | โฎ‘ Extended | โœ… | โœ… | โœ… | โœ… | -| | [Custom Suggestions](./tools/custom_suggestions.md){:target="_blank"} ๐Ÿ’Ž | โœ… | โœ… | โœ… | โœ… | -| | Reflect and Review | โœ… | โœ… | โœ… | โœ… | -| | Update CHANGELOG.md | โœ… | โœ… | โœ… | ๏ธ | -| | Find Similar Issue | โœ… | | | ๏ธ | -| | [Add PR Documentation](./tools/documentation.md){:target="_blank"} ๐Ÿ’Ž | โœ… | โœ… | | โœ… | +| | | GitHub | Gitlab | Bitbucket | Azure DevOps | +|-------|-----------------------------------------------------------------------------------------------------------------------|:------:|:------:|:---------:|:------------:| +| TOOLS | Review | โœ… | โœ… | โœ… | โœ… | +| | โฎ‘ Incremental | โœ… | | | | +| | โฎ‘ [SOC2 Compliance](https://pr-agent-docs.codium.ai/tools/review/#soc2-ticket-compliance){:target="_blank"} ๐Ÿ’Ž | โœ… | โœ… | โœ… | โœ… | +| | Ask | โœ… | โœ… | โœ… | โœ… | +| | Describe | โœ… | โœ… | โœ… | โœ… | +| | โฎ‘ [Inline file summary](https://pr-agent-docs.codium.ai/tools/describe/#inline-file-summary){:target="_blank"} ๐Ÿ’Ž | โœ… | โœ… | | โœ… | +| | Improve | โœ… | โœ… | โœ… | โœ… | +| | โฎ‘ Extended | โœ… | โœ… | โœ… | โœ… | +| | [Custom Prompt](./tools/custom_prompt.md){:target="_blank"} ๐Ÿ’Ž | โœ… | โœ… | โœ… | โœ… | +| | Reflect and Review | โœ… | โœ… | โœ… | โœ… | +| | Update CHANGELOG.md | โœ… | โœ… | โœ… | ๏ธ | +| | Find Similar Issue | โœ… | | | ๏ธ | +| | [Add PR Documentation](./tools/documentation.md){:target="_blank"} ๐Ÿ’Ž | โœ… | โœ… | | โœ… | | | [Generate Custom Labels](./tools/describe.md#handle-custom-labels-from-the-repos-labels-page-๐Ÿ’Ž){:target="_blank"} ๐Ÿ’Ž | โœ… | โœ… | | โœ… | -| | [Analyze PR Components](./tools/analyze.md){:target="_blank"} ๐Ÿ’Ž | โœ… | โœ… | | โœ… | -| | | | | | ๏ธ | -| USAGE | CLI | โœ… | โœ… | โœ… | โœ… | -| | App / webhook | โœ… | โœ… | โœ… | โœ… | -| | Actions | โœ… | | | ๏ธ | -| | | | | | -| CORE | PR compression | โœ… | โœ… | โœ… | โœ… | -| | Repo language prioritization | โœ… | โœ… | โœ… | โœ… | -| | Adaptive and token-aware file patch fitting | โœ… | โœ… | โœ… | โœ… | -| | Multiple models support | โœ… | โœ… | โœ… | โœ… | -| | Incremental PR review | โœ… | | | | -| | [Static code analysis](./tools/analyze.md/){:target="_blank"} ๐Ÿ’Ž | โœ… | โœ… | โœ… | โœ… | -| | [Multiple configuration options](./usage-guide/configuration_options.md){:target="_blank"} ๐Ÿ’Ž | โœ… | โœ… | โœ… | โœ… | +| | [Analyze PR Components](./tools/analyze.md){:target="_blank"} ๐Ÿ’Ž | โœ… | โœ… | | โœ… | +| | | | | | ๏ธ | +| USAGE | CLI | โœ… | โœ… | โœ… | โœ… | +| | App / webhook | โœ… | โœ… | โœ… | โœ… | +| | Actions | โœ… | | | ๏ธ | +| | | | | | +| CORE | PR compression | โœ… | โœ… | โœ… | โœ… | +| | Repo language prioritization | โœ… | โœ… | โœ… | โœ… | +| | Adaptive and token-aware file patch fitting | โœ… | โœ… | โœ… | โœ… | +| | Multiple models support | โœ… | โœ… | โœ… | โœ… | +| | Incremental PR review | โœ… | | | | +| | [Static code analysis](./tools/analyze.md/){:target="_blank"} ๐Ÿ’Ž | โœ… | โœ… | โœ… | โœ… | +| | [Multiple configuration options](./usage-guide/configuration_options.md){:target="_blank"} ๐Ÿ’Ž | โœ… | โœ… | โœ… | โœ… | ๐Ÿ’Ž marks a feature available only in [PR-Agent Pro](https://www.codium.ai/pricing/){:target="_blank"} @@ -91,7 +91,7 @@ Check out the [PR Compression strategy](core-abilities/index.md) page for more d 3. **Improved support** - PR-Agent Pro users will receive priority support, and will be able to request new features and capabilities. 4. **Extra features** -In addition to the benefits listed above, PR-Agent Pro will emphasize more customization, and the usage of static code analysis, in addition to LLM logic, to improve results. It has the following additional tools and features: - (Tool): [**Analyze PR components**](./tools/analyze.md/) - - (Tool): [**Custom Code Suggestions**](./tools/custom_suggestions.md/) + - (Tool): [**Custom Prompt Suggestions**](./tools/custom_prompt.md/) - (Tool): [**Tests**](./tools/test.md/) - (Tool): [**PR documentation**](./tools/documentation.md/) - (Tool): [**Improve Component**](https://pr-agent-docs.codium.ai/tools/improve_component/) diff --git a/docs/docs/tools/custom_suggestions.md b/docs/docs/tools/custom_prompt.md similarity index 64% rename from docs/docs/tools/custom_suggestions.md rename to docs/docs/tools/custom_prompt.md index 902a4d25..675bed69 100644 --- a/docs/docs/tools/custom_suggestions.md +++ b/docs/docs/tools/custom_prompt.md @@ -1,14 +1,14 @@ ## Overview -The `custom_suggestions` tool scans the PR code changes, and automatically generates suggestions for improving the PR code. -It shares similarities with the `improve` tool, but with one main difference: the `custom_suggestions` tool will **only propose suggestions that follow specific guidelines defined by the prompt** in: `pr_custom_suggestions.prompt` configuration. +The `custom_prompt` tool scans the PR code changes, and automatically generates suggestions for improving the PR code. +It shares similarities with the `improve` tool, but with one main difference: the `custom_prompt` tool will **only propose suggestions that follow specific guidelines defined by the prompt** in: `pr_custom_prompt.prompt` configuration. The tool can be triggered [automatically](../usage-guide/automations_and_usage.md#github-app-automatic-tools-when-a-new-pr-is-opened) every time a new PR is opened, or can be invoked manually by commenting on a PR. When commenting, use the following template: ``` -/custom_suggestions --pr_custom_suggestions.prompt=" -The suggestions should focus only on the following: +/custom_prompt --pr_custom_prompt.prompt=" +The code suggestions should focus only on the following: - ... - ... @@ -18,7 +18,7 @@ The suggestions should focus only on the following: With a [configuration file](../usage-guide/automations_and_usage.md#github-app), use the following template: ``` -[pr_custom_suggestions] +[pr_custom_prompt] prompt="""\ The suggestions should focus only on the following: -... @@ -34,9 +34,9 @@ You might benefit from several trial-and-error iterations, until you get the cor Here is an example of a possible prompt, defined in the configuration file: ``` -[pr_custom_suggestions] +[pr_custom_prompt] prompt="""\ -The suggestions should focus only on the following: +The code suggestions should focus only on the following: - look for edge cases when implementing a new function - make sure every variable has a meaningful name - make sure the code is efficient @@ -47,15 +47,12 @@ The suggestions should focus only on the following: Results obtained with the prompt above: -[//]: # (![Custom suggestions prompt](https://codium.ai/images/pr_agent/custom_suggestions_prompt.png){width=512}) - -[//]: # (→) -![Custom suggestions results](https://codium.ai/images/pr_agent/custom_suggestions_result.png){width=768} +![Custom prompt results](https://codium.ai/images/pr_agent/custom_suggestions_result.png){width=768} ## Configuration options `prompt`: the prompt for the tool. It should be a multi-line string. -`num_code_suggestions`: number of code suggestions provided by the 'custom_suggestions' tool. Default is 4. +`num_code_suggestions`: number of code suggestions provided by the 'custom_prompt' tool. Default is 4. `enable_help_text`: if set to true, the tool will display a help text in the comment. Default is true. \ No newline at end of file diff --git a/docs/docs/tools/improve.md b/docs/docs/tools/improve.md index 7906f426..bf27b17e 100644 --- a/docs/docs/tools/improve.md +++ b/docs/docs/tools/improve.md @@ -164,4 +164,4 @@ Hence, the total number of suggestions is proportional to the number of chunks, In addition, we recommend to use the `exra_instructions` field to guide the model to suggestions that are more relevant to the specific needs of the project. <br> -Consider also trying the [Custom Suggestions Tool](./custom_suggestions.md) ๐Ÿ’Ž, that will **only** propose suggestions that follow specific guidelines defined by user. +Consider also trying the [Custom Prompt Tool](./custom_prompt.md) ๐Ÿ’Ž, that will **only** propose code suggestions that follow specific guidelines defined by user. diff --git a/docs/docs/tools/index.md b/docs/docs/tools/index.md index 49c31a8f..10aaf88a 100644 --- a/docs/docs/tools/index.md +++ b/docs/docs/tools/index.md @@ -10,11 +10,11 @@ Here is a list of PR-Agent tools, each with a dedicated page that explains how t | **[Question Answering (`/ask ...`](./ask.md))** | Answering free-text questions about the PR, or on specific code lines | | **[Update Changelog (`/update_changelog`](./update_changelog.md))** | Automatically updating the CHANGELOG.md file with the PR changes | | **[Find Similar Issue (`/similar_issue`](./similar_issues.md))** | Automatically retrieves and presents similar issues | -| **[Help (`/help`](./help.md))** | Provides a list of all the available tools. Also enables to trigger them interactively (๐Ÿ’Ž) | +| **[Help (`/help`](./help.md))** | Provides a list of all the available tools. Also enables to trigger them interactively (๐Ÿ’Ž) | | **๐Ÿ’Ž [Add Documentation (`/add_docs`](./documentation.md))** | Generates documentation to methods/functions/classes that changed in the PR | | **๐Ÿ’Ž [Generate Custom Labels (`/generate_labels`](./custom_labels.md))** | Generates custom labels for the PR, based on specific guidelines defined by the user | | **๐Ÿ’Ž [Analyze (`/analyze`](./analyze.md))** | Identify code components that changed in the PR, and enables to interactively generate tests, docs, and code suggestions for each component | -| **๐Ÿ’Ž [Custom Suggestions (`/custom_suggestions`](./custom_suggestions.md))** | Automatically generates custom suggestions for improving the PR code, based on specific guidelines defined by the user | +| **๐Ÿ’Ž [Custom Prompt (`/custom_prompt`](./custom_prompt.md))** | Automatically generates custom suggestions for improving the PR code, based on specific guidelines defined by the user | | **๐Ÿ’Ž [Generate Tests (`/test component_name`](./test.md))** | Automatically generates unit tests for a selected component, based on the PR code changes | | **๐Ÿ’Ž [Improve Component (`/improve_component component_name`](./improve_component.md))** | Generates code suggestions for a specific code component that changed in the PR | | **๐Ÿ’Ž [CI Feedback (`/checks ci_job`](./ci_feedback.md))** | Automatically generates feedback and analysis for a failed CI job | diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index 272d5394..bd6ecaa0 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -33,7 +33,7 @@ nav: - ๐Ÿ’Ž Improve Component: 'tools/improve_component.md' - ๐Ÿ’Ž Documentation: 'tools/documentation.md' - ๐Ÿ’Ž Custom Labels: 'tools/custom_labels.md' - - ๐Ÿ’Ž Custom Suggestions: 'tools/custom_suggestions.md' + - ๐Ÿ’Ž Custom Prompt: 'tools/custom_prompt.md' - ๐Ÿ’Ž CI Feedback: 'tools/ci_feedback.md' - ๐Ÿ’Ž Similar Code: 'tools/similar_code.md' - Core Abilities: 'core-abilities/index.md' diff --git a/pr_agent/tools/pr_help_message.py b/pr_agent/tools/pr_help_message.py index 9f76434d..f0563bf6 100644 --- a/pr_agent/tools/pr_help_message.py +++ b/pr_agent/tools/pr_help_message.py @@ -35,7 +35,7 @@ class PRHelpMessage: tool_names.append(f"[ASK]({base_path}/ask/)") tool_names.append(f"[GENERATE CUSTOM LABELS]({base_path}/custom_labels/) ๐Ÿ’Ž") tool_names.append(f"[CI FEEDBACK]({base_path}/ci_feedback/) ๐Ÿ’Ž") - tool_names.append(f"[CUSTOM SUGGESTIONS]({base_path}/custom_suggestions/) ๐Ÿ’Ž") + tool_names.append(f"[CUSTOM PROMPT]({base_path}/custom_prompt/) ๐Ÿ’Ž") tool_names.append(f"[SIMILAR ISSUE]({base_path}/similar_issues/)") descriptions = [] @@ -50,7 +50,7 @@ class PRHelpMessage: descriptions.append("Answering free-text questions about the PR") descriptions.append("Generates custom labels for the PR, based on specific guidelines defined by the user") descriptions.append("Generates feedback and analysis for a failed CI job") - descriptions.append("Generates custom suggestions for improving the PR code, based only on specific guidelines defined by the user") + descriptions.append("Generates custom suggestions for improving the PR code, derived only from a specific guidelines prompt defined by the user") descriptions.append("Automatically retrieves and presents similar issues") commands =[] @@ -65,7 +65,7 @@ class PRHelpMessage: commands.append("`/ask`") commands.append("`/generate_labels`") commands.append("`/checks`") - commands.append("`/custom_suggestions`") + commands.append("`/custom_prompt`") commands.append("`/similar_issue`") checkbox_list = [] @@ -86,7 +86,7 @@ class PRHelpMessage: checkbox_list.append("[*]") checkbox_list.append("[*]") - if isinstance(self.git_provider, GithubProvider): + if isinstance(self.git_provider, GithubProvider) and not get_settings().config.get('disable_checkboxes', False): pr_comment += f"<table><tr align='left'><th align='left'>Tool</th><th align='left'>Description</th><th align='left'>Trigger Interactively :gem:</th></tr>" for i in range(len(tool_names)): pr_comment += f"\n<tr><td align='left'>\n\n<strong>{tool_names[i]}</strong></td>\n<td>{descriptions[i]}</td>\n<td>\n\n{checkbox_list[i]}\n</td></tr>" From f9af9e4a9131140bc357f9046c71c2eae4180328 Mon Sep 17 00:00:00 2001 From: Tal <tal.r@codium.ai> Date: Thu, 16 May 2024 21:59:00 +0300 Subject: [PATCH 185/226] Update pr_code_suggestions_prompts.toml --- pr_agent/settings/pr_code_suggestions_prompts.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pr_agent/settings/pr_code_suggestions_prompts.toml b/pr_agent/settings/pr_code_suggestions_prompts.toml index bf8b4dc7..ab20a341 100644 --- a/pr_agent/settings/pr_code_suggestions_prompts.toml +++ b/pr_agent/settings/pr_code_suggestions_prompts.toml @@ -59,9 +59,9 @@ class CodeSuggestion(BaseModel): relevant_file: str = Field(description="the relevant file full path") language: str = Field(description="the code language of the relevant file") suggestion_content: str = Field(description="an actionable suggestion for meaningfully improving the new code introduced in the PR") - existing_code: str = Field(description="a short code snippet, demonstrating the relevant code lines from a '__new hunk__' section. It must without line numbers. Use abbreviations if needed") + existing_code: str = Field(description="a short code snippet, demonstrating the relevant code lines from a '__new hunk__' section. It must be without line numbers. Use abbreviations if needed") improved_code: str = Field(description="a new code snippet, that can be used to replace the relevant 'existing_code' lines in '__new hunk__' code after applying the suggestion") - one_sentence_summary:str = Field(description="a short summary of the suggestion action, in a single sentence. Focus on the 'what'. Be general, and avoid method or variable names.") + one_sentence_summary: str = Field(description="a short summary of the suggestion action, in a single sentence. Focus on the 'what'. Be general, and avoid method or variable names.") relevant_lines_start: int = Field(description="The relevant line number, from a '__new hunk__' section, where the suggestion starts (inclusive). Should be derived from the hunk line numbers, and correspond to the 'existing code' snippet above") relevant_lines_end: int = Field(description="The relevant line number, from a '__new hunk__' section, where the suggestion ends (inclusive). Should be derived from the hunk line numbers, and correspond to the 'existing code' snippet above") label: str = Field(description="a single label for the suggestion, to help the user understand the suggestion type. For example: 'security', 'possible bug', 'possible issue', 'performance', 'enhancement', 'best practice', 'maintainability', etc. Other labels are also allowed") From ea4ee1adbc53f593488160142fa30dff8d976dd2 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sat, 18 May 2024 13:09:50 +0300 Subject: [PATCH 186/226] Add show_relevant_configurations function and integrate it across tools to output relevant configurations if enabled --- pr_agent/algo/utils.py | 24 +++++++++++++++++++++++- pr_agent/settings/configuration.toml | 1 + pr_agent/tools/pr_code_suggestions.py | 6 +++++- pr_agent/tools/pr_description.py | 6 +++++- pr_agent/tools/pr_reviewer.py | 7 ++++++- pr_agent/tools/pr_update_changelog.py | 7 ++++++- 6 files changed, 46 insertions(+), 5 deletions(-) diff --git a/pr_agent/algo/utils.py b/pr_agent/algo/utils.py index e2f7f8ba..61510b8d 100644 --- a/pr_agent/algo/utils.py +++ b/pr_agent/algo/utils.py @@ -673,4 +673,26 @@ def github_action_output(output_data: dict, key_name: str): print(f"{key_name}={json.dumps(key_data, indent=None, ensure_ascii=False)}", file=fh) except Exception as e: get_logger().error(f"Failed to write to GitHub Action output: {e}") - return \ No newline at end of file + return + + +def show_relevant_configurations(relevant_section: str) -> str: + forbidden_keys = ['ai_disclaimer', 'ai_disclaimer_title', 'ANALYTICS_FOLDER', 'secret_provider'] + + markdown_text = "" + markdown_text += "\n<hr>\n<details> <summary><strong>๐Ÿ› ๏ธ Relevant configurations:</strong></summary> \n\n" + markdown_text +="<br>These are the relevant [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/configuration.toml) for this tool:\n\n" + markdown_text += f"**[config**]\n```yaml\n\n" + for key, value in get_settings().config.items(): + if key in forbidden_keys: + continue + markdown_text += f"{key}: {value}\n" + markdown_text += "\n```\n" + markdown_text += f"\n**[{relevant_section}]**\n```yaml\n\n" + for key, value in get_settings().get(relevant_section, {}).items(): + if key in forbidden_keys: + continue + markdown_text += f"{key}: {value}\n" + markdown_text += "\n```" + markdown_text += "\n</details>\n" + return markdown_text diff --git a/pr_agent/settings/configuration.toml b/pr_agent/settings/configuration.toml index b84bce61..fa9b1afd 100644 --- a/pr_agent/settings/configuration.toml +++ b/pr_agent/settings/configuration.toml @@ -19,6 +19,7 @@ secret_provider="google_cloud_storage" cli_mode=false ai_disclaimer_title="" # Pro feature, title for a collapsible disclaimer to AI outputs ai_disclaimer="" # Pro feature, full text for the AI disclaimer +output_relevant_configurations=false [pr_reviewer] # /review # # enable/disable features diff --git a/pr_agent/tools/pr_code_suggestions.py b/pr_agent/tools/pr_code_suggestions.py index a3f0abd1..6dead2be 100644 --- a/pr_agent/tools/pr_code_suggestions.py +++ b/pr_agent/tools/pr_code_suggestions.py @@ -9,7 +9,7 @@ from pr_agent.algo.ai_handlers.base_ai_handler import BaseAiHandler from pr_agent.algo.ai_handlers.litellm_ai_handler import LiteLLMAIHandler from pr_agent.algo.pr_processing import get_pr_diff, get_pr_multi_diffs, retry_with_fallback_models from pr_agent.algo.token_handler import TokenHandler -from pr_agent.algo.utils import load_yaml, replace_code_tags, ModelType +from pr_agent.algo.utils import load_yaml, replace_code_tags, ModelType, show_relevant_configurations from pr_agent.config_loader import get_settings from pr_agent.git_providers import get_git_provider from pr_agent.git_providers.git_provider import get_main_pr_language @@ -118,6 +118,10 @@ class PRCodeSuggestions: pr_body += HelpMessage.get_improve_usage_guide() pr_body += "\n</details>\n" + # Output the relevant configurations if enabled + if get_settings().get('config', {}).get('output_relevant_configurations', False): + pr_body += show_relevant_configurations(relevant_section='pr_code_suggestions') + if get_settings().pr_code_suggestions.persistent_comment: final_update_message = False self.git_provider.publish_persistent_comment(pr_body, diff --git a/pr_agent/tools/pr_description.py b/pr_agent/tools/pr_description.py index 661d9dd8..0de93c9c 100644 --- a/pr_agent/tools/pr_description.py +++ b/pr_agent/tools/pr_description.py @@ -9,7 +9,7 @@ from pr_agent.algo.ai_handlers.base_ai_handler import BaseAiHandler from pr_agent.algo.ai_handlers.litellm_ai_handler import LiteLLMAIHandler from pr_agent.algo.pr_processing import get_pr_diff, retry_with_fallback_models from pr_agent.algo.token_handler import TokenHandler -from pr_agent.algo.utils import load_yaml, set_custom_labels, get_user_labels, ModelType +from pr_agent.algo.utils import load_yaml, set_custom_labels, get_user_labels, ModelType, show_relevant_configurations from pr_agent.config_loader import get_settings from pr_agent.git_providers import get_git_provider from pr_agent.git_providers.git_provider import get_main_pr_language @@ -116,6 +116,10 @@ class PRDescription: pr_body += "\n\n___\n\n> ๐Ÿ’ก **PR-Agent usage**:" pr_body += "\n>Comment `/help` on the PR to get a list of all available PR-Agent tools and their descriptions\n\n" + # Output the relevant configurations if enabled + if get_settings().get('config', {}).get('output_relevant_configurations', False): + pr_body += show_relevant_configurations(relevant_section='pr_description') + if get_settings().config.publish_output: # publish labels if get_settings().pr_description.publish_labels and self.git_provider.is_supported("get_labels"): diff --git a/pr_agent/tools/pr_reviewer.py b/pr_agent/tools/pr_reviewer.py index 46036816..33adab39 100644 --- a/pr_agent/tools/pr_reviewer.py +++ b/pr_agent/tools/pr_reviewer.py @@ -8,7 +8,8 @@ from pr_agent.algo.ai_handlers.base_ai_handler import BaseAiHandler from pr_agent.algo.ai_handlers.litellm_ai_handler import LiteLLMAIHandler from pr_agent.algo.pr_processing import get_pr_diff, retry_with_fallback_models from pr_agent.algo.token_handler import TokenHandler -from pr_agent.algo.utils import convert_to_markdown, github_action_output, load_yaml, ModelType +from pr_agent.algo.utils import convert_to_markdown, github_action_output, load_yaml, ModelType, \ + show_relevant_configurations from pr_agent.config_loader import get_settings from pr_agent.git_providers import get_git_provider from pr_agent.git_providers.git_provider import IncrementalPR, get_main_pr_language @@ -238,6 +239,10 @@ class PRReviewer: markdown_text += HelpMessage.get_review_usage_guide() markdown_text += "\n</details>\n" + # Output the relevant configurations if enabled + if get_settings().get('config', {}).get('output_relevant_configurations', False): + markdown_text += show_relevant_configurations(relevant_section='pr_reviewer') + # Add custom labels from the review prediction (effort, security) self.set_review_labels(data) diff --git a/pr_agent/tools/pr_update_changelog.py b/pr_agent/tools/pr_update_changelog.py index 1475d9f2..404b886c 100644 --- a/pr_agent/tools/pr_update_changelog.py +++ b/pr_agent/tools/pr_update_changelog.py @@ -8,7 +8,7 @@ from pr_agent.algo.ai_handlers.base_ai_handler import BaseAiHandler from pr_agent.algo.ai_handlers.litellm_ai_handler import LiteLLMAIHandler from pr_agent.algo.pr_processing import get_pr_diff, retry_with_fallback_models from pr_agent.algo.token_handler import TokenHandler -from pr_agent.algo.utils import ModelType +from pr_agent.algo.utils import ModelType, show_relevant_configurations from pr_agent.config_loader import get_settings from pr_agent.git_providers import get_git_provider, GithubProvider from pr_agent.git_providers.git_provider import get_main_pr_language @@ -74,6 +74,11 @@ class PRUpdateChangelog: await retry_with_fallback_models(self._prepare_prediction, model_type=ModelType.TURBO) new_file_content, answer = self._prepare_changelog_update() + + # Output the relevant configurations if enabled + if get_settings().get('config', {}).get('output_relevant_configurations', False): + answer += show_relevant_configurations(relevant_section='pr_update_changelog') + get_logger().debug(f"PR output", artifact=answer) if get_settings().config.publish_output: From 3432d377c76946aa6642560f3da1268a4b2cc262 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sat, 18 May 2024 13:14:16 +0300 Subject: [PATCH 187/226] Update configuration_options.md to include tip on showing relevant configurations --- docs/docs/usage-guide/configuration_options.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/docs/usage-guide/configuration_options.md b/docs/docs/usage-guide/configuration_options.md index 68a8492b..92bf42ee 100644 --- a/docs/docs/usage-guide/configuration_options.md +++ b/docs/docs/usage-guide/configuration_options.md @@ -11,8 +11,10 @@ There are three ways to set persistent configurations: In terms of precedence, wiki configurations will override local configurations, and local configurations will override global configurations. -!!! tip "Tip: edit only what you need" +!!! tip "Tip1: edit only what you need" Your configuration file should be minimal, and edit only the relevant values. Don't copy the entire configuration options, since it can lead to legacy problems when something changes. +!!! tip "Tip2: show relevant configurations" + If you set `config.output_relevant_configurations=true`, each tool will also output in a collapsible section its relevant configurations. This can be useful for debugging, or getting to know the configurations better. ## Wiki configuration file ๐Ÿ’Ž From dcd188193b27ba1072765f58c6b9a05f91e17614 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sun, 19 May 2024 08:20:15 +0300 Subject: [PATCH 188/226] Update configuration_options.md to include tip on showing relevant configurations --- pr_agent/algo/utils.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pr_agent/algo/utils.py b/pr_agent/algo/utils.py index 61510b8d..f2ef00a5 100644 --- a/pr_agent/algo/utils.py +++ b/pr_agent/algo/utils.py @@ -677,7 +677,8 @@ def github_action_output(output_data: dict, key_name: str): def show_relevant_configurations(relevant_section: str) -> str: - forbidden_keys = ['ai_disclaimer', 'ai_disclaimer_title', 'ANALYTICS_FOLDER', 'secret_provider'] + forbidden_keys = ['ai_disclaimer', 'ai_disclaimer_title', 'ANALYTICS_FOLDER', 'secret_provider', + 'trial_prefix_message', 'no_eligible_message', 'identity_provider'] markdown_text = "" markdown_text += "\n<hr>\n<details> <summary><strong>๐Ÿ› ๏ธ Relevant configurations:</strong></summary> \n\n" From 9b56c83c1de4bb28e18437423a0b83d92c9a66f2 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sun, 19 May 2024 12:18:22 +0300 Subject: [PATCH 189/226] APP_NAME --- pr_agent/algo/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pr_agent/algo/utils.py b/pr_agent/algo/utils.py index f2ef00a5..0888a15a 100644 --- a/pr_agent/algo/utils.py +++ b/pr_agent/algo/utils.py @@ -678,7 +678,7 @@ def github_action_output(output_data: dict, key_name: str): def show_relevant_configurations(relevant_section: str) -> str: forbidden_keys = ['ai_disclaimer', 'ai_disclaimer_title', 'ANALYTICS_FOLDER', 'secret_provider', - 'trial_prefix_message', 'no_eligible_message', 'identity_provider'] + 'trial_prefix_message', 'no_eligible_message', 'identity_provider', 'ALLOWED_REPOS','APP_NAME'] markdown_text = "" markdown_text += "\n<hr>\n<details> <summary><strong>๐Ÿ› ๏ธ Relevant configurations:</strong></summary> \n\n" From 2880e4886090c6d42428cd33efa108cf3247de3a Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sun, 19 May 2024 12:29:06 +0300 Subject: [PATCH 190/226] Refactor model selection logic for PR tools and update turbo model to gpt-4o --- pr_agent/settings/configuration.toml | 2 +- pr_agent/tools/pr_code_suggestions.py | 10 +++++----- pr_agent/tools/pr_description.py | 2 +- pr_agent/tools/pr_questions.py | 3 ++- pr_agent/tools/pr_reviewer.py | 2 +- 5 files changed, 10 insertions(+), 9 deletions(-) diff --git a/pr_agent/settings/configuration.toml b/pr_agent/settings/configuration.toml index fa9b1afd..448dfb57 100644 --- a/pr_agent/settings/configuration.toml +++ b/pr_agent/settings/configuration.toml @@ -1,6 +1,6 @@ [config] model="gpt-4-turbo-2024-04-09" -model_turbo="gpt-4-turbo-2024-04-09" +model_turbo="gpt-4o" fallback_models=["gpt-4-0125-preview"] git_provider="github" publish_output=true diff --git a/pr_agent/tools/pr_code_suggestions.py b/pr_agent/tools/pr_code_suggestions.py index 6dead2be..358f2992 100644 --- a/pr_agent/tools/pr_code_suggestions.py +++ b/pr_agent/tools/pr_code_suggestions.py @@ -82,9 +82,9 @@ class PRCodeSuggestions: self.git_provider.publish_comment("Preparing suggestions...", is_temporary=True) if not self.is_extended: - data = await retry_with_fallback_models(self._prepare_prediction, ModelType.TURBO) + data = await retry_with_fallback_models(self._prepare_prediction) else: - data = await retry_with_fallback_models(self._prepare_prediction_extended, ModelType.TURBO) + data = await retry_with_fallback_models(self._prepare_prediction_extended) if not data: data = {"code_suggestions": []} @@ -184,7 +184,8 @@ class PRCodeSuggestions: # self-reflect on suggestions if get_settings().pr_code_suggestions.self_reflect_on_suggestions: - response_reflect = await self.self_reflect_on_suggestions(data["code_suggestions"], patches_diff) + model = get_settings().config.model_turbo # use turbo model for self-reflection, since it is an easier task + response_reflect = await self.self_reflect_on_suggestions(data["code_suggestions"], patches_diff, model=model) if response_reflect: response_reflect_yaml = load_yaml(response_reflect) code_suggestions_feedback = response_reflect_yaml["code_suggestions"] @@ -546,7 +547,7 @@ class PRCodeSuggestions: get_logger().info(f"Failed to publish summarized code suggestions, error: {e}") return "" - async def self_reflect_on_suggestions(self, suggestion_list: List, patches_diff: str) -> str: + async def self_reflect_on_suggestions(self, suggestion_list: List, patches_diff: str, model: str) -> str: if not suggestion_list: return "" @@ -559,7 +560,6 @@ class PRCodeSuggestions: 'suggestion_str': suggestion_str, "diff": patches_diff, 'num_code_suggestions': len(suggestion_list)} - model = get_settings().config.model environment = Environment(undefined=StrictUndefined) system_prompt_reflect = environment.from_string(get_settings().pr_code_suggestions_reflect_prompt.system).render( variables) diff --git a/pr_agent/tools/pr_description.py b/pr_agent/tools/pr_description.py index 0de93c9c..96f6512d 100644 --- a/pr_agent/tools/pr_description.py +++ b/pr_agent/tools/pr_description.py @@ -82,7 +82,7 @@ class PRDescription: if get_settings().config.publish_output: self.git_provider.publish_comment("Preparing PR description...", is_temporary=True) - await retry_with_fallback_models(self._prepare_prediction, ModelType.TURBO) # turbo model because larger context + await retry_with_fallback_models(self._prepare_prediction, ModelType.TURBO) if self.prediction: self._prepare_data() diff --git a/pr_agent/tools/pr_questions.py b/pr_agent/tools/pr_questions.py index 78db1452..3e6355f5 100644 --- a/pr_agent/tools/pr_questions.py +++ b/pr_agent/tools/pr_questions.py @@ -7,6 +7,7 @@ from pr_agent.algo.ai_handlers.base_ai_handler import BaseAiHandler from pr_agent.algo.ai_handlers.litellm_ai_handler import LiteLLMAIHandler from pr_agent.algo.pr_processing import get_pr_diff, retry_with_fallback_models from pr_agent.algo.token_handler import TokenHandler +from pr_agent.algo.utils import ModelType from pr_agent.config_loader import get_settings from pr_agent.git_providers import get_git_provider from pr_agent.git_providers.git_provider import get_main_pr_language @@ -62,7 +63,7 @@ class PRQuestions: if img_path: get_logger().debug(f"Image path identified", artifact=img_path) - await retry_with_fallback_models(self._prepare_prediction) + await retry_with_fallback_models(self._prepare_prediction, model_type=ModelType.TURBO) pr_comment = self._prepare_pr_answer() get_logger().debug(f"PR output", artifact=pr_comment) diff --git a/pr_agent/tools/pr_reviewer.py b/pr_agent/tools/pr_reviewer.py index 33adab39..3a127f4c 100644 --- a/pr_agent/tools/pr_reviewer.py +++ b/pr_agent/tools/pr_reviewer.py @@ -125,7 +125,7 @@ class PRReviewer: if get_settings().config.publish_output: self.git_provider.publish_comment("Preparing review...", is_temporary=True) - await retry_with_fallback_models(self._prepare_prediction, model_type=ModelType.TURBO) + await retry_with_fallback_models(self._prepare_prediction) if not self.prediction: self.git_provider.remove_initial_comment() return None From 8921d9eb0ebe1a2ab966d0522b126945494590ee Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sun, 19 May 2024 12:35:19 +0300 Subject: [PATCH 191/226] Refactor model selection logic for PR tools and update turbo model to gpt-4o --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index bdac3fc0..401b87af 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,9 @@ CodiumAI PR-Agent aims to help efficiently review and handle pull requests, by p ## News and Updates +### May 19, 2024 +GPT-4o is now the default fast model ("Turbo"). This model will be used for all command except `review` and `improve`, which will still use "GPT-4-turbo-2024-04-09", since they are harder and would still benefit from the larger model. + ### May 12, 2024 Inspired by [AlphaCodium](https://github.com/Codium-ai/AlphaCodium) flow engineering scheme, PR-Agent now performs **self-reflection** on the code suggestions it provides, enabling to remove invalid suggestions, and score the valid ones. The suggestions will be presented sorted by their score, enabling to focus on the most important ones first. From 985b4f05cf90556babebc7b06d3427e45ea2e50b Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sun, 19 May 2024 12:37:06 +0300 Subject: [PATCH 192/226] Refactor model selection logic for PR tools and update turbo model to gpt-4o --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 401b87af..85d0c8fc 100644 --- a/README.md +++ b/README.md @@ -42,7 +42,7 @@ CodiumAI PR-Agent aims to help efficiently review and handle pull requests, by p ## News and Updates ### May 19, 2024 -GPT-4o is now the default fast model ("Turbo"). This model will be used for all command except `review` and `improve`, which will still use "GPT-4-turbo-2024-04-09", since they are harder and would still benefit from the larger model. +GPT-4o is now the default fast model ("Turbo"). This model will be used for all command except `review` and `improve`, which will still use "GPT-4-2024-04-09", since they are harder and would still benefit from the larger model. ### May 12, 2024 Inspired by [AlphaCodium](https://github.com/Codium-ai/AlphaCodium) flow engineering scheme, PR-Agent now performs **self-reflection** on the code suggestions it provides, From c3dca2ef5ae4027502eeb77eb9911cbf767aab9b Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Sun, 19 May 2024 12:37:31 +0300 Subject: [PATCH 193/226] Refactor model selection logic for PR tools and update turbo model to gpt-4o --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 85d0c8fc..3845ab56 100644 --- a/README.md +++ b/README.md @@ -42,7 +42,7 @@ CodiumAI PR-Agent aims to help efficiently review and handle pull requests, by p ## News and Updates ### May 19, 2024 -GPT-4o is now the default fast model ("Turbo"). This model will be used for all command except `review` and `improve`, which will still use "GPT-4-2024-04-09", since they are harder and would still benefit from the larger model. +GPT-4o is now the default fast model ("Turbo"). This model will be used for all commands except `review` and `improve`, which will still use "GPT-4-2024-04-09", since they are harder and would still benefit from the larger model. ### May 12, 2024 Inspired by [AlphaCodium](https://github.com/Codium-ai/AlphaCodium) flow engineering scheme, PR-Agent now performs **self-reflection** on the code suggestions it provides, From e5bbb701d3295c6d31f0b4feb0c03cf50aa45f48 Mon Sep 17 00:00:00 2001 From: Tal <tal.r@codium.ai> Date: Sun, 19 May 2024 13:03:30 +0300 Subject: [PATCH 194/226] Update README.md --- README.md | 34 ---------------------------------- 1 file changed, 34 deletions(-) diff --git a/README.md b/README.md index 3845ab56..3df1aa52 100644 --- a/README.md +++ b/README.md @@ -65,40 +65,6 @@ You can also easily export your chosen configuration, and use it for the automat <kbd><img src="https://codium.ai/images/pr_agent/toolbar2.png" width="512"></kbd> - -### April 14, 2024 -You can now ask questions about images that appear in the comment, where the entire PR is considered as the context. -see [here](https://pr-agent-docs.codium.ai/tools/ask/#ask-on-images) for more details. - -<kbd><img src="https://codium.ai/images/pr_agent/ask_images5.png" width="512"></kbd> - -### March 24, 2024 -PR-Agent is now available for easy installation via [pip](https://pr-agent-docs.codium.ai/installation/locally/#using-pip-package). - -### March 17, 2024 -- A new feature is now available for the review tool: [`require_can_be_split_review`](https://pr-agent-docs.codium.ai/tools/review/#enabledisable-features). -If set to true, the tool will add a section that checks if the PR contains several themes, and can be split into smaller PRs. - -<kbd><img src="https://codium.ai/images/pr_agent/multiple_pr_themes.png" width="512"></kbd> - -### March 10, 2024 -- A new [knowledge-base website](https://pr-agent-docs.codium.ai/) for PR-Agent is now available. It includes detailed information about the different tools, usage guides and more, in an accessible and organized format. - -### March 8, 2024 - -- A new tool, [Find Similar Code](https://pr-agent-docs.codium.ai/tools/similar_code/) ๐Ÿ’Ž is now available. -<br>This tool retrieves the most similar code components from inside the organization's codebase, or from open-source code: - -<kbd><a href="https://codium.ai/images/pr_agent/similar_code.mp4"><img src="https://codium.ai/images/pr_agent/similar_code_global2.png" width="512"></a></kbd> - -(click on the image to see an instructional video) - -### Feb 29, 2024 -- You can now use the repo's [wiki page](https://pr-agent-docs.codium.ai/usage-guide/configuration_options/) to set configurations for PR-Agent ๐Ÿ’Ž - -<kbd><img src="https://codium.ai/images/pr_agent/wiki_configuration.png" width="512"></kbd> - - ## Overview <div style="text-align:left;"> From a13cb14e9f3880f3c07a6bd8edf86492183bc7c5 Mon Sep 17 00:00:00 2001 From: Tal <tal.r@codium.ai> Date: Mon, 20 May 2024 09:28:05 +0300 Subject: [PATCH 195/226] Update pyproject.toml --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 651d8a4f..fd9e8e3e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "pr-agent" -version = "0.2.1" +version = "0.2.2" authors = [{name= "CodiumAI", email = "tal.r@codium.ai"}] From 71770f3c049f5a809ad1881ef64e53b88802ec6d Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Mon, 20 May 2024 14:25:51 +0300 Subject: [PATCH 196/226] Update default setting of `final_update_message` to false in describe.md and configuration.toml --- docs/docs/tools/describe.md | 2 +- pr_agent/settings/configuration.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/docs/tools/describe.md b/docs/docs/tools/describe.md index cd8c7015..b4e40c8f 100644 --- a/docs/docs/tools/describe.md +++ b/docs/docs/tools/describe.md @@ -77,7 +77,7 @@ publish_labels = ... </tr> <tr> <td><b>final_update_message</b></td> - <td>If set to true, it will add a comment message [`PR Description updated to latest commit...`](https://github.com/Codium-ai/pr-agent/pull/499#issuecomment-1837412176) after finishing calling `/describe`. Default is true.</td> + <td>If set to true, it will add a comment message [`PR Description updated to latest commit...`](https://github.com/Codium-ai/pr-agent/pull/499#issuecomment-1837412176) after finishing calling `/describe`. Default is false.</td> </tr> <tr> <td><b>enable_semantic_files_types</b></td> diff --git a/pr_agent/settings/configuration.toml b/pr_agent/settings/configuration.toml index 448dfb57..8ecf04ab 100644 --- a/pr_agent/settings/configuration.toml +++ b/pr_agent/settings/configuration.toml @@ -58,7 +58,7 @@ generate_ai_title=false use_bullet_points=true extra_instructions = "" enable_pr_type=true -final_update_message = true +final_update_message = false enable_help_text=false enable_help_comment=true # describe as comment From 63340eb75ef636431535842982f665cf6ca77ab4 Mon Sep 17 00:00:00 2001 From: Tal <tal.r@codium.ai> Date: Tue, 21 May 2024 11:04:37 +0300 Subject: [PATCH 197/226] Cover-Agent --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 3df1aa52..cb1a7381 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,9 @@ CodiumAI PR-Agent aims to help efficiently review and handle pull requests, by p ## News and Updates +### May 21, 2024 +Check out CodiumAI new project, [**Cover-Agent**](https://github.com/Codium-ai/cover-agent), that can automatically generate qualified tests to enhance existing test suites to efficiently increase code coverage, + ### May 19, 2024 GPT-4o is now the default fast model ("Turbo"). This model will be used for all commands except `review` and `improve`, which will still use "GPT-4-2024-04-09", since they are harder and would still benefit from the larger model. From 66dc9349bd8942d1acfa3a39549596e5e93c368e Mon Sep 17 00:00:00 2001 From: Tal <tal.r@codium.ai> Date: Tue, 21 May 2024 11:05:33 +0300 Subject: [PATCH 198/226] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cb1a7381..e0a798dc 100644 --- a/README.md +++ b/README.md @@ -42,7 +42,7 @@ CodiumAI PR-Agent aims to help efficiently review and handle pull requests, by p ## News and Updates ### May 21, 2024 -Check out CodiumAI new project, [**Cover-Agent**](https://github.com/Codium-ai/cover-agent), that can automatically generate qualified tests to enhance existing test suites to efficiently increase code coverage, +Check out CodiumAI new project, [**Cover-Agent**](https://github.com/Codium-ai/cover-agent), that can automatically generate qualified tests to enhance existing test suites, aiming to increase code and behavior coverage efficiently. ### May 19, 2024 GPT-4o is now the default fast model ("Turbo"). This model will be used for all commands except `review` and `improve`, which will still use "GPT-4-2024-04-09", since they are harder and would still benefit from the larger model. From 39fe6f69d0fd142855e856f16c2a58a60ebec4d5 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Wed, 22 May 2024 14:37:15 +0300 Subject: [PATCH 199/226] Expand and enhance documentation for PR-Agent Chrome Extension, adding detailed feature descriptions and updated images --- docs/docs/chrome-extension/index.md | 47 +++++++++++++++++++++-------- 1 file changed, 34 insertions(+), 13 deletions(-) diff --git a/docs/docs/chrome-extension/index.md b/docs/docs/chrome-extension/index.md index 59623046..e00a42c2 100644 --- a/docs/docs/chrome-extension/index.md +++ b/docs/docs/chrome-extension/index.md @@ -1,12 +1,39 @@ ## PR-Agent chrome extension +PR-Agent Chrome extension ia a collection of tools that integrates seamlessly with your GitHub environment, aiming to enhance your PR-Agent usage experience, and providing additional features. -- PR-Agent Chrome extension is a toolbar that integrates seamlessly with your GitHub environment, allowing you to access PR-Agent tools directly from the GitHub interface. -- With PR-Agent Chrome extension, it's [easier than ever](https://www.youtube.com/watch?v=gT5tli7X4H4) to interactively experiment with the different tools and configuration options. -- After you found the setup that works for you, you can also easily export it as a persistent configuration file, and use it for the automatic commands. +## Features -<kbd><img src="https://codium.ai/images/pr_agent/toolbar1.png" width="512"></kbd> +### Toolbar extension +With PR-Agent Chrome extension, it's [easier than ever](https://www.youtube.com/watch?v=gT5tli7X4H4) to interactively configuring and experimenting with the different tools and configuration options. -<kbd><img src="https://codium.ai/images/pr_agent/toolbar2.png" width="512"></kbd> +After you found the setup that works for you, you can also easily export it as a persistent configuration file, and use it for automatic commands. + +<img src="https://codium.ai/images/pr_agent/toolbar1.png" width="512"> + +<img src="https://codium.ai/images/pr_agent/toolbar2.png" width="512"> + +### PR-Agent filters + +PR-Agent filters is a sidepanel option. that allow you to filter different message in the conversation tab. + +For example, you can choose to present only message from PR-Agent, or filter those messages, focusing only on user's comments. + +<img src="https://codium.ai/images/pr_agent/pr_agent_filters1.png" width="256"> + +<img src="https://codium.ai/images/pr_agent/pr_agent_filters2.png" width="256"> + + +### Enhanced code suggestions + +PR-Agent Chrome extension adds the following capabilities to code suggestions tool's comments: + +- Auto-expand the table when you are viewing a code block, to avoid clipping. +- Adding a "quote-and-reply" button, that enables to address and comment on a specific suggestion (for example, asking the author to fix the issue) + + +<img src="https://codium.ai/images/pr_agent/chrome_extension_code_suggestion1.png" width="512"> + +<img src="https://codium.ai/images/pr_agent/chrome_extension_code_suggestion2.png" width="512"> ## Installation @@ -15,14 +42,8 @@ Go to the marketplace and install the extension: ## Pre-requisites -The PR-Agent Chrome extension will work on any repo where you have previously [installed PR-Agent](https://pr-agent-docs.codium.ai/installation/) (both for free and pro users). +The PR-Agent Chrome extension will work on any repo where you have previously [installed PR-Agent](https://pr-agent-docs.codium.ai/installation/). ## Data privacy and security -The PR-Agent Chrome extension only modifies the visual appearance of a GitHub PR screen. It does not transmit any user's repo or pull request code. Code is only sent for processing when a user submits a GitHub comment that activates a PR-Agent tool, in accordance with the standard [privacy policy of PR-Agent](https://pr-agent-docs.codium.ai/#pr-agent-chrome-extension). - -## Roadmap - -Stay tuned ... - -<kbd><img src="https://codium.ai/images/pr_agent/chrome_extension_roadmap.png" width="512"></kbd> +The PR-Agent Chrome extension only modifies the visual appearance of a GitHub PR screen. It does not transmit any user's repo or pull request code. Code is only sent for processing when a user submits a GitHub comment that activates a PR-Agent tool, in accordance with the standard privacy policy of PR-Agent. From 811965d8411c094aabcd2ffcaedd58f9613524cb Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Wed, 22 May 2024 14:40:31 +0300 Subject: [PATCH 200/226] grammar --- docs/docs/chrome-extension/index.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/docs/chrome-extension/index.md b/docs/docs/chrome-extension/index.md index e00a42c2..2f75e74d 100644 --- a/docs/docs/chrome-extension/index.md +++ b/docs/docs/chrome-extension/index.md @@ -1,10 +1,10 @@ ## PR-Agent chrome extension -PR-Agent Chrome extension ia a collection of tools that integrates seamlessly with your GitHub environment, aiming to enhance your PR-Agent usage experience, and providing additional features. +PR-Agent Chrome extension is a collection of tools that integrates seamlessly with your GitHub environment, aiming to enhance your PR-Agent usage experience, and providing additional features. ## Features ### Toolbar extension -With PR-Agent Chrome extension, it's [easier than ever](https://www.youtube.com/watch?v=gT5tli7X4H4) to interactively configuring and experimenting with the different tools and configuration options. +With PR-Agent Chrome extension, it's [easier than ever](https://www.youtube.com/watch?v=gT5tli7X4H4) to interactively configure and experiment with the different tools and configuration options. After you found the setup that works for you, you can also easily export it as a persistent configuration file, and use it for automatic commands. @@ -14,7 +14,7 @@ After you found the setup that works for you, you can also easily export it as a ### PR-Agent filters -PR-Agent filters is a sidepanel option. that allow you to filter different message in the conversation tab. +PR-Agent filters is a sidepanel option. that allows you to filter different message in the conversation tab. For example, you can choose to present only message from PR-Agent, or filter those messages, focusing only on user's comments. From 4cd9626217e65fb484ff0a89cb1b58a5400e395b Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Wed, 22 May 2024 21:47:49 +0300 Subject: [PATCH 201/226] grammar --- pr_agent/algo/git_patch_processing.py | 5 ++++- pr_agent/algo/pr_processing.py | 3 +++ pr_agent/settings/language_extensions.toml | 1 + 3 files changed, 8 insertions(+), 1 deletion(-) diff --git a/pr_agent/algo/git_patch_processing.py b/pr_agent/algo/git_patch_processing.py index 383d488f..5ca4e12b 100644 --- a/pr_agent/algo/git_patch_processing.py +++ b/pr_agent/algo/git_patch_processing.py @@ -23,7 +23,10 @@ def extend_patch(original_file_str, patch_str, num_lines) -> str: return patch_str if type(original_file_str) == bytes: - original_file_str = original_file_str.decode('utf-8') + try: + original_file_str = original_file_str.decode('utf-8') + except UnicodeDecodeError: + return "" original_lines = original_file_str.splitlines() patch_lines = patch_str.splitlines() diff --git a/pr_agent/algo/pr_processing.py b/pr_agent/algo/pr_processing.py index 2c5a2957..d02110c7 100644 --- a/pr_agent/algo/pr_processing.py +++ b/pr_agent/algo/pr_processing.py @@ -146,6 +146,9 @@ def pr_generate_extended_diff(pr_languages: list, # extend each patch with extra lines of context extended_patch = extend_patch(original_file_content_str, patch, num_lines=patch_extra_lines) + if not extend_patch: + get_logger().warning(f"Failed to extend patch for file: {file.filename}") + continue full_extended_patch = f"\n\n## {file.filename}\n\n{extended_patch}\n" if add_line_numbers_to_hunks: diff --git a/pr_agent/settings/language_extensions.toml b/pr_agent/settings/language_extensions.toml index eadb80c8..c13992ec 100644 --- a/pr_agent/settings/language_extensions.toml +++ b/pr_agent/settings/language_extensions.toml @@ -44,6 +44,7 @@ default = [ 'ss', 'svg', 'tar', + 'tgz', 'tsv', 'ttf', 'war', From 83ff9a0b9b02774cbf53d20a276afb226e32679e Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Wed, 22 May 2024 21:49:33 +0300 Subject: [PATCH 202/226] final_update_message --- pr_agent/settings/configuration.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pr_agent/settings/configuration.toml b/pr_agent/settings/configuration.toml index 8ecf04ab..c50ab0f7 100644 --- a/pr_agent/settings/configuration.toml +++ b/pr_agent/settings/configuration.toml @@ -58,7 +58,7 @@ generate_ai_title=false use_bullet_points=true extra_instructions = "" enable_pr_type=true -final_update_message = false +final_update_message = true enable_help_text=false enable_help_comment=true # describe as comment @@ -152,7 +152,7 @@ override_deployment_type = true # settings for "pull_request" event handle_pr_actions = ['opened', 'reopened', 'ready_for_review'] pr_commands = [ - "/describe", + "/describe --pr_description.final_update_message=false", "/review --pr_reviewer.num_code_suggestions=0", "/improve", ] From da44bd7d5ec22f9c8822979d484be39db0270177 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Wed, 22 May 2024 21:50:00 +0300 Subject: [PATCH 203/226] extended_patch --- pr_agent/algo/pr_processing.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pr_agent/algo/pr_processing.py b/pr_agent/algo/pr_processing.py index d02110c7..59b9da26 100644 --- a/pr_agent/algo/pr_processing.py +++ b/pr_agent/algo/pr_processing.py @@ -146,7 +146,7 @@ def pr_generate_extended_diff(pr_languages: list, # extend each patch with extra lines of context extended_patch = extend_patch(original_file_content_str, patch, num_lines=patch_extra_lines) - if not extend_patch: + if not extended_patch: get_logger().warning(f"Failed to extend patch for file: {file.filename}") continue full_extended_patch = f"\n\n## {file.filename}\n\n{extended_patch}\n" From b7225c1d101889ca97f868ecb7165550a19483d6 Mon Sep 17 00:00:00 2001 From: Tal <tal.r@codium.ai> Date: Thu, 23 May 2024 16:53:00 +0300 Subject: [PATCH 204/226] Update README.md --- README.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index e0a798dc..a82605d7 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,16 @@ CodiumAI PR-Agent aims to help efficiently review and handle pull requests, by p ## News and Updates +### May 23, 2024 + +We released a new version of [PR-Agent Chrome extension](https://chromewebstore.google.com/detail/pr-agent-chrome-extension/ephlnjeghhogofkifjloamocljapahnl), with two new features: + +- PR-Agent filters ๐ŸŽจ +- Code suggestions interactions ๐Ÿ”— + +See more [here](https://www.youtube.com/watch?v=v9bJ1frtPcg) + + ### May 21, 2024 Check out CodiumAI new project, [**Cover-Agent**](https://github.com/Codium-ai/cover-agent), that can automatically generate qualified tests to enhance existing test suites, aiming to increase code and behavior coverage efficiently. @@ -58,16 +68,6 @@ You can also choose to automatically remove suggestions below a certain importan <kbd><img src="https://codium.ai/images/pr_agent/self_reflection2.png" width="512"></kbd> -### May 2, 2024 -Check out the new [PR-Agent Chrome Extension](https://chromewebstore.google.com/detail/pr-agent-chrome-extension/ephlnjeghhogofkifjloamocljapahnl) ๐Ÿš€๐Ÿš€๐Ÿš€ - -This toolbar integrates seamlessly with your GitHub environment, allowing you to access PR-Agent tools [directly from the GitHub interface](https://www.youtube.com/watch?v=gT5tli7X4H4). -You can also easily export your chosen configuration, and use it for the automatic commands. - -<kbd><img src="https://codium.ai/images/pr_agent/toolbar1.png" width="512"></kbd> - -<kbd><img src="https://codium.ai/images/pr_agent/toolbar2.png" width="512"></kbd> - ## Overview <div style="text-align:left;"> From 2a691167679f6b90a0d8742983d512c7f3c1aed7 Mon Sep 17 00:00:00 2001 From: Ikko Eltociear Ashimine <eltociear@gmail.com> Date: Tue, 28 May 2024 12:52:35 +0900 Subject: [PATCH 205/226] docs: update additional_configurations.md Huggingface -> Hugging Face --- docs/docs/usage-guide/additional_configurations.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/docs/usage-guide/additional_configurations.md b/docs/docs/usage-guide/additional_configurations.md index 8785a580..4deca211 100644 --- a/docs/docs/usage-guide/additional_configurations.md +++ b/docs/docs/usage-guide/additional_configurations.md @@ -59,12 +59,12 @@ and set in your configuration file: model="" # the OpenAI model you've deployed on Azure (e.g. gpt-3.5-turbo) ``` -### Huggingface +### Hugging Face **Local** -You can run Huggingface models locally through either [VLLM](https://docs.litellm.ai/docs/providers/vllm) or [Ollama](https://docs.litellm.ai/docs/providers/ollama) +You can run Hugging Face models locally through either [VLLM](https://docs.litellm.ai/docs/providers/vllm) or [Ollama](https://docs.litellm.ai/docs/providers/ollama) -E.g. to use a new Huggingface model locally via Ollama, set: +E.g. to use a new Hugging Face model locally via Ollama, set: ``` [__init__.py] MAX_TOKENS = { @@ -82,14 +82,14 @@ model = "ollama/llama2" model_turbo = "ollama/llama2" [ollama] # in .secrets.toml -api_base = ... # the base url for your huggingface inference endpoint +api_base = ... # the base url for your Hugging Face inference endpoint # e.g. if running Ollama locally, you may use: api_base = "http://localhost:11434/" ``` ### Inference Endpoints -To use a new model with Huggingface Inference Endpoints, for example, set: +To use a new model with Hugging Face Inference Endpoints, for example, set: ``` [__init__.py] MAX_TOKENS = { @@ -105,8 +105,8 @@ model = "huggingface/meta-llama/Llama-2-7b-chat-hf" model_turbo = "huggingface/meta-llama/Llama-2-7b-chat-hf" [huggingface] # in .secrets.toml -key = ... # your huggingface api key -api_base = ... # the base url for your huggingface inference endpoint +key = ... # your Hugging Face api key +api_base = ... # the base url for your Hugging Face inference endpoint ``` (you can obtain a Llama2 key from [here](https://replicate.com/replicate/llama-2-70b-chat/api)) From 17f46bb53bee3d48c341017103b3c2c971130b82 Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Wed, 29 May 2024 13:42:44 +0300 Subject: [PATCH 206/226] Add large_patch_policy configuration and implement patch clipping logic --- pr_agent/algo/pr_processing.py | 22 +++++++++++++++++++--- pr_agent/algo/utils.py | 4 +++- pr_agent/settings/configuration.toml | 1 + 3 files changed, 23 insertions(+), 4 deletions(-) diff --git a/pr_agent/algo/pr_processing.py b/pr_agent/algo/pr_processing.py index 59b9da26..bc17aedd 100644 --- a/pr_agent/algo/pr_processing.py +++ b/pr_agent/algo/pr_processing.py @@ -377,9 +377,25 @@ def get_pr_multi_diffs(git_provider: GitProvider, patch = convert_to_hunks_with_lines_numbers(patch, file) new_patch_tokens = token_handler.count_tokens(patch) - if patch and (token_handler.prompt_tokens + new_patch_tokens) > get_max_tokens(model) - OUTPUT_BUFFER_TOKENS_SOFT_THRESHOLD: - get_logger().warning(f"Patch too large, skipping: {file.filename}") - continue + if patch and (token_handler.prompt_tokens + new_patch_tokens) > get_max_tokens( + model) - OUTPUT_BUFFER_TOKENS_SOFT_THRESHOLD: + if get_settings().config.get('large_patch_policy', 'skip') == 'skip': + get_logger().warning(f"Patch too large, skipping: {file.filename}") + continue + elif get_settings().config.get('large_patch_policy') == 'clip': + delta_tokens = int(0.9*(get_max_tokens(model) - OUTPUT_BUFFER_TOKENS_SOFT_THRESHOLD - token_handler.prompt_tokens)) + patch_clipped = clip_tokens(patch,delta_tokens, delete_last_line=True) + new_patch_tokens = token_handler.count_tokens(patch_clipped) + if patch_clipped and (token_handler.prompt_tokens + new_patch_tokens) > get_max_tokens( + model) - OUTPUT_BUFFER_TOKENS_SOFT_THRESHOLD: + get_logger().warning(f"Patch too large, skipping: {file.filename}") + continue + else: + get_logger().info(f"Clipped large patch for file: {file.filename}") + patch = patch_clipped + else: + get_logger().warning(f"Patch too large, skipping: {file.filename}") + continue if patch and (total_tokens + new_patch_tokens > get_max_tokens(model) - OUTPUT_BUFFER_TOKENS_SOFT_THRESHOLD): final_diff = "\n".join(patches) diff --git a/pr_agent/algo/utils.py b/pr_agent/algo/utils.py index 0888a15a..d24d4244 100644 --- a/pr_agent/algo/utils.py +++ b/pr_agent/algo/utils.py @@ -552,7 +552,7 @@ def get_max_tokens(model): return max_tokens_model -def clip_tokens(text: str, max_tokens: int, add_three_dots=True) -> str: +def clip_tokens(text: str, max_tokens: int, add_three_dots=True, delete_last_line=False) -> str: """ Clip the number of tokens in a string to a maximum number of tokens. @@ -575,6 +575,8 @@ def clip_tokens(text: str, max_tokens: int, add_three_dots=True) -> str: chars_per_token = num_chars / num_input_tokens num_output_chars = int(chars_per_token * max_tokens) clipped_text = text[:num_output_chars] + if delete_last_line: + clipped_text = clipped_text.rsplit('\n', 1)[0] if add_three_dots: clipped_text += "\n...(truncated)" return clipped_text diff --git a/pr_agent/settings/configuration.toml b/pr_agent/settings/configuration.toml index c50ab0f7..98d14414 100644 --- a/pr_agent/settings/configuration.toml +++ b/pr_agent/settings/configuration.toml @@ -20,6 +20,7 @@ cli_mode=false ai_disclaimer_title="" # Pro feature, title for a collapsible disclaimer to AI outputs ai_disclaimer="" # Pro feature, full text for the AI disclaimer output_relevant_configurations=false +large_patch_policy = "clip" # "clip", "skip" [pr_reviewer] # /review # # enable/disable features From 911c1268fcaf098b06f69ca4aaea6d1fa0eb48ea Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Wed, 29 May 2024 13:52:44 +0300 Subject: [PATCH 207/226] Add large_patch_policy configuration and implement patch clipping logic --- pr_agent/algo/pr_processing.py | 4 +- pr_agent/algo/utils.py | 90 +++++++++++++++++++++++++++++----- 2 files changed, 80 insertions(+), 14 deletions(-) diff --git a/pr_agent/algo/pr_processing.py b/pr_agent/algo/pr_processing.py index bc17aedd..731af5a2 100644 --- a/pr_agent/algo/pr_processing.py +++ b/pr_agent/algo/pr_processing.py @@ -383,8 +383,8 @@ def get_pr_multi_diffs(git_provider: GitProvider, get_logger().warning(f"Patch too large, skipping: {file.filename}") continue elif get_settings().config.get('large_patch_policy') == 'clip': - delta_tokens = int(0.9*(get_max_tokens(model) - OUTPUT_BUFFER_TOKENS_SOFT_THRESHOLD - token_handler.prompt_tokens)) - patch_clipped = clip_tokens(patch,delta_tokens, delete_last_line=True) + delta_tokens = get_max_tokens(model) - OUTPUT_BUFFER_TOKENS_SOFT_THRESHOLD - token_handler.prompt_tokens + patch_clipped = clip_tokens(patch, delta_tokens, delete_last_line=True, num_input_tokens=new_patch_tokens) new_patch_tokens = token_handler.count_tokens(patch_clipped) if patch_clipped and (token_handler.prompt_tokens + new_patch_tokens) > get_max_tokens( model) - OUTPUT_BUFFER_TOKENS_SOFT_THRESHOLD: diff --git a/pr_agent/algo/utils.py b/pr_agent/algo/utils.py index d24d4244..f9798277 100644 --- a/pr_agent/algo/utils.py +++ b/pr_agent/algo/utils.py @@ -5,6 +5,7 @@ import json import os import re import textwrap +import time from datetime import datetime from enum import Enum from typing import Any, List, Tuple @@ -76,6 +77,7 @@ def convert_to_markdown(output_data: dict, gfm_supported: bool = True, increment "Score": "๐Ÿ…", "Relevant tests": "๐Ÿงช", "Focused PR": "โœจ", + "Relevant ticket": "๐ŸŽซ", "Security concerns": "๐Ÿ”’", "Insights from user's answers": "๐Ÿ“", "Code feedback": "๐Ÿค–", @@ -85,7 +87,7 @@ def convert_to_markdown(output_data: dict, gfm_supported: bool = True, increment if not incremental_review: markdown_text += f"## PR Review ๐Ÿ”\n\n" else: - markdown_text += f"## Incremental PR Review ๐Ÿ” \n\n" + markdown_text += f"## Incremental PR Review ๐Ÿ”\n\n" markdown_text += f"โฎ๏ธ Review for commits since previous PR-Agent review {incremental_review}.\n\n" if gfm_supported: markdown_text += "<table>\n<tr>\n" @@ -470,7 +472,8 @@ def try_fix_yaml(response_text: str, keys_fix_yaml: List[str] = []) -> dict: except: pass - # third fallback - try to remove leading and trailing curly brackets + + # third fallback - try to remove leading and trailing curly brackets response_text_copy = response_text.strip().rstrip().removeprefix('{').removesuffix('}').rstrip(':\n') try: data = yaml.safe_load(response_text_copy) @@ -552,7 +555,7 @@ def get_max_tokens(model): return max_tokens_model -def clip_tokens(text: str, max_tokens: int, add_three_dots=True, delete_last_line=False) -> str: +def clip_tokens(text: str, max_tokens: int, add_three_dots=True, num_input_tokens=None, delete_last_line=False) -> str: """ Clip the number of tokens in a string to a maximum number of tokens. @@ -567,18 +570,30 @@ def clip_tokens(text: str, max_tokens: int, add_three_dots=True, delete_last_lin return text try: - encoder = TokenEncoder.get_token_encoder() - num_input_tokens = len(encoder.encode(text)) + if num_input_tokens is None: + encoder = TokenEncoder.get_token_encoder() + num_input_tokens = len(encoder.encode(text)) if num_input_tokens <= max_tokens: return text + if max_tokens < 0: + return "" + + # calculate the number of characters to keep num_chars = len(text) chars_per_token = num_chars / num_input_tokens - num_output_chars = int(chars_per_token * max_tokens) - clipped_text = text[:num_output_chars] - if delete_last_line: - clipped_text = clipped_text.rsplit('\n', 1)[0] - if add_three_dots: - clipped_text += "\n...(truncated)" + factor = 0.9 # reduce by 10% to be safe + num_output_chars = int(factor * chars_per_token * max_tokens) + + # clip the text + if num_output_chars > 0: + clipped_text = text[:num_output_chars] + if delete_last_line: + clipped_text = clipped_text.rsplit('\n', 1)[0] + if add_three_dots: + clipped_text += "\n...(truncated)" + else: # if the text is empty + clipped_text = "" + return clipped_text except Exception as e: get_logger().warning(f"Failed to clip tokens: {e}") @@ -665,11 +680,62 @@ def find_line_number_of_relevant_line_in_file(diff_files: List[FilePatchInfo], break return position, absolute_position +def validate_and_await_rate_limit(rate_limit_status=None, git_provider=None, get_rate_limit_status_func=None): + if git_provider and not rate_limit_status: + rate_limit_status = {'resources': git_provider.github_client.get_rate_limit().raw_data} + + if not rate_limit_status: + rate_limit_status = get_rate_limit_status_func() + # validate that the rate limit is not exceeded + is_rate_limit = False + for key, value in rate_limit_status['resources'].items(): + if value['remaining'] == 0: + print(f"key: {key}, value: {value}") + is_rate_limit = True + sleep_time_sec = value['reset'] - datetime.now().timestamp() + sleep_time_hour = sleep_time_sec / 3600.0 + print(f"Rate limit exceeded. Sleeping for {sleep_time_hour} hours") + if sleep_time_sec > 0: + time.sleep(sleep_time_sec+1) + + if git_provider: + rate_limit_status = {'resources': git_provider.github_client.get_rate_limit().raw_data} + else: + rate_limit_status = get_rate_limit_status_func() + + return is_rate_limit + + +def get_largest_component(pr_url): + from pr_agent.tools.pr_analyzer import PRAnalyzer + publish_output = get_settings().config.publish_output + get_settings().config.publish_output = False # disable publish output + analyzer = PRAnalyzer(pr_url) + methods_dict_files = analyzer.run_sync() + get_settings().config.publish_output = publish_output + max_lines_changed = 0 + file_b = "" + component_name_b = "" + for file in methods_dict_files: + for method in methods_dict_files[file]: + try: + if methods_dict_files[file][method]['num_plus_lines'] > max_lines_changed: + max_lines_changed = methods_dict_files[file][method]['num_plus_lines'] + file_b = file + component_name_b = method + except: + pass + if component_name_b: + get_logger().info(f"Using the largest changed component: '{component_name_b}'") + return component_name_b, file_b + else: + return None, None + def github_action_output(output_data: dict, key_name: str): try: if not get_settings().get('github_action_config.enable_output', False): return - + key_data = output_data.get(key_name, {}) with open(os.environ['GITHUB_OUTPUT'], 'a') as fh: print(f"{key_name}={json.dumps(key_data, indent=None, ensure_ascii=False)}", file=fh) From 6e6f54933ee4968bdd23cb1490980d1d161f5fcc Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Wed, 29 May 2024 14:00:04 +0300 Subject: [PATCH 208/226] Add large_patch_policy configuration and implement patch clipping logic --- tests/unittest/test_clip_tokens.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unittest/test_clip_tokens.py b/tests/unittest/test_clip_tokens.py index a56ff92f..79de6294 100644 --- a/tests/unittest/test_clip_tokens.py +++ b/tests/unittest/test_clip_tokens.py @@ -15,5 +15,5 @@ class TestClipTokens: max_tokens = 10 result = clip_tokens(text, max_tokens) - expected_results = 'line1\nline2\nline3\nli\n...(truncated)' + expected_results = 'line1\nline2\nline3\n\n...(truncated)' assert result == expected_results From ee90f385011164c7e05912dac18c82ec6bde1ef1 Mon Sep 17 00:00:00 2001 From: MarkRx <MarkRx@users.noreply.github.com> Date: Thu, 30 May 2024 10:05:00 -0400 Subject: [PATCH 209/226] BB Server fixes. Fix ID not being retrieved, inline comments, url generation, and pr review not working --- .../bitbucket_server_provider.py | 49 +++++++++++-------- 1 file changed, 29 insertions(+), 20 deletions(-) diff --git a/pr_agent/git_providers/bitbucket_server_provider.py b/pr_agent/git_providers/bitbucket_server_provider.py index 0f9e58d4..f1c0a956 100644 --- a/pr_agent/git_providers/bitbucket_server_provider.py +++ b/pr_agent/git_providers/bitbucket_server_provider.py @@ -1,13 +1,13 @@ import json from typing import Optional, Tuple -from urllib.parse import urlparse +from urllib.parse import quote_plus, urlparse import requests from atlassian.bitbucket import Bitbucket from starlette_context import context from .git_provider import GitProvider -from pr_agent.algo.types import FilePatchInfo +from pr_agent.algo.types import EDIT_TYPE, FilePatchInfo from ..algo.utils import load_large_diff, find_line_number_of_relevant_line_in_file from ..config_loader import get_settings from ..log import get_logger @@ -58,6 +58,9 @@ class BitbucketServerProvider(GitProvider): return contents except Exception: return "" + + def get_pr_id(self): + return self.pr_num def publish_code_suggestions(self, code_suggestions: list) -> bool: """ @@ -140,14 +143,8 @@ class BitbucketServerProvider(GitProvider): if self.diff_files: return self.diff_files - commits_in_pr = self.bitbucket_client.get_pull_requests_commits( - self.workspace_slug, - self.repo_slug, - self.pr_num - ) - - commit_list = list(commits_in_pr) - base_sha, head_sha = commit_list[0]['parents'][0]['id'], commit_list[-1]['id'] + base_sha = self.pr.toRef['latestCommit'] + head_sha = self.pr.fromRef['latestCommit'] diff_files = [] original_file_content_str = "" @@ -242,7 +239,7 @@ class BitbucketServerProvider(GitProvider): } response = requests.post(url=self._get_pr_comments_url(), json=payload, headers=self.headers) - return response + response.raise_for_status() def generate_link_to_relevant_line_number(self, suggestion) -> str: try: @@ -256,7 +253,7 @@ class BitbucketServerProvider(GitProvider): (diff_files, relevant_file, relevant_line_str) if absolute_position != -1 and self.pr_url: - link = f"{self.pr_url}/#L{relevant_file}T{absolute_position}" + link = f"{self.pr_url}/diff#{quote_plus(relevant_file)}?t={absolute_position}" return link except Exception as e: if get_settings().config.verbosity_level >= 2: @@ -266,7 +263,15 @@ class BitbucketServerProvider(GitProvider): def publish_inline_comments(self, comments: list[dict]): for comment in comments: - self.publish_inline_comment(comment['body'], comment['position'], comment['path']) + if 'position' in comment: + self.publish_inline_comment(comment['body'], comment['position'], comment['path']) + elif 'start_line' in comment: # multi-line comment + # note that bitbucket does not seem to support range - only a comment on a single line - https://community.developer.atlassian.com/t/api-post-endpoint-for-inline-pull-request-comments/60452 + self.publish_inline_comment(comment['body'], comment['start_line'], comment['path']) + elif 'line' in comment: # single-line comment + self.publish_inline_comment(comment['body'], comment['line'], comment['path']) + else: + get_logger().error(f"Could not publish inline comment {comment}") def get_title(self): return self.pr.title @@ -278,7 +283,10 @@ class BitbucketServerProvider(GitProvider): return self.pr.fromRef['displayId'] def get_pr_description_full(self): - return self.pr.description + if hasattr(self.pr, "description"): + return self.pr.description + else: + return None def get_user_id(self): return 0 @@ -334,13 +342,14 @@ class BitbucketServerProvider(GitProvider): raise NotImplementedError("Get commit messages function not implemented yet.") # bitbucket does not support labels def publish_description(self, pr_title: str, description: str): - payload = json.dumps({ + payload = { + "version": self.pr.version, "description": description, - "title": pr_title - }) - - response = requests.put(url=self.bitbucket_pull_request_api_url, headers=self.headers, data=payload) - return response + "title": pr_title, + "reviewers": self.pr.reviewers # needs to be sent otherwise gets wiped + } + + self.bitbucket_client.update_pull_request(self.workspace_slug, self.repo_slug, str(self.pr_num), payload) # bitbucket does not support labels def publish_labels(self, pr_types: list): From e6c52361563b30581fa9027887089974a644831b Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Thu, 30 May 2024 17:05:30 +0300 Subject: [PATCH 210/226] Add logging for skipping non-code files in GitHub provider --- pr_agent/git_providers/github_provider.py | 1 + 1 file changed, 1 insertion(+) diff --git a/pr_agent/git_providers/github_provider.py b/pr_agent/git_providers/github_provider.py index 574e28cf..99b8521b 100644 --- a/pr_agent/git_providers/github_provider.py +++ b/pr_agent/git_providers/github_provider.py @@ -147,6 +147,7 @@ class GithubProvider(GitProvider): for file in files: if not is_valid_file(file.filename): + get_logger().info(f"Skipping a non-code file: {file.filename}") continue new_file_content_str = self._get_pr_file_content(file, self.pr.head.sha) # communication with GitHub From c11ee8643e6da1f5d1479e5a508095233b3312b3 Mon Sep 17 00:00:00 2001 From: MarkRx <MarkRx@users.noreply.github.com> Date: Thu, 30 May 2024 11:34:39 -0400 Subject: [PATCH 211/226] Bitbucket server filter out globally ignored files before attempting diff --- .gitignore | 4 +++- pr_agent/git_providers/bitbucket_server_provider.py | 5 +++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 47683742..9fcb9193 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,6 @@ .idea/ +.lsp/ +.vscode/ venv/ pr_agent/settings/.secrets.toml __pycache__ @@ -6,4 +8,4 @@ dist/ *.egg-info/ build/ .DS_Store -docs/.cache/ +docs/.cache/ \ No newline at end of file diff --git a/pr_agent/git_providers/bitbucket_server_provider.py b/pr_agent/git_providers/bitbucket_server_provider.py index 0f9e58d4..632f87d9 100644 --- a/pr_agent/git_providers/bitbucket_server_provider.py +++ b/pr_agent/git_providers/bitbucket_server_provider.py @@ -8,6 +8,7 @@ from starlette_context import context from .git_provider import GitProvider from pr_agent.algo.types import FilePatchInfo +from ..algo.language_handler import is_valid_file from ..algo.utils import load_large_diff, find_line_number_of_relevant_line_in_file from ..config_loader import get_settings from ..log import get_logger @@ -156,6 +157,10 @@ class BitbucketServerProvider(GitProvider): changes = self.bitbucket_client.get_pull_requests_changes(self.workspace_slug, self.repo_slug, self.pr_num) for change in changes: file_path = change['path']['toString'] + if not is_valid_file(file_path.split("/")[-1]): + get_logger().info(f"Skipping a non-code file: {file_path}") + continue + match change['type']: case 'ADD': edit_type = EDIT_TYPE.ADDED From bd2f2b3a870b7218627b31d5a5ec8ac850ca685f Mon Sep 17 00:00:00 2001 From: MarkRx <MarkRx@users.noreply.github.com> Date: Thu, 30 May 2024 17:31:46 -0400 Subject: [PATCH 212/226] Improve bb server error logging --- .../bitbucket_server_provider.py | 32 +++++++++++++++---- 1 file changed, 25 insertions(+), 7 deletions(-) diff --git a/pr_agent/git_providers/bitbucket_server_provider.py b/pr_agent/git_providers/bitbucket_server_provider.py index f1c0a956..a7a41f78 100644 --- a/pr_agent/git_providers/bitbucket_server_provider.py +++ b/pr_agent/git_providers/bitbucket_server_provider.py @@ -238,8 +238,11 @@ class BitbucketServerProvider(GitProvider): } } - response = requests.post(url=self._get_pr_comments_url(), json=payload, headers=self.headers) - response.raise_for_status() + try: + requests.post(url=self._get_pr_comments_url(), json=payload, headers=self.headers).raise_for_status() + except Exception as e: + get_logger().error(f"Failed to publish inline comment to '{file}' at line {from_line}, error: {e}") + raise e def generate_link_to_relevant_line_number(self, suggestion) -> str: try: @@ -252,12 +255,23 @@ class BitbucketServerProvider(GitProvider): position, absolute_position = find_line_number_of_relevant_line_in_file \ (diff_files, relevant_file, relevant_line_str) + if absolute_position != -1: + if self.pr: + link = f"{self.pr_url}/diff#{quote_plus(relevant_file)}?t={absolute_position}" + return link + else: + if get_settings().config.verbosity_level >= 2: + get_logger().info(f"Failed adding line link to '{relevant_file}' since PR not set") + else: + if get_settings().config.verbosity_level >= 2: + get_logger().info(f"Failed adding line link to '{relevant_file}' since position not found") + if absolute_position != -1 and self.pr_url: link = f"{self.pr_url}/diff#{quote_plus(relevant_file)}?t={absolute_position}" return link except Exception as e: if get_settings().config.verbosity_level >= 2: - get_logger().info(f"Failed adding line link, error: {e}") + get_logger().info(f"Failed adding line link to '{relevant_file}', error: {e}") return "" @@ -271,7 +285,7 @@ class BitbucketServerProvider(GitProvider): elif 'line' in comment: # single-line comment self.publish_inline_comment(comment['body'], comment['line'], comment['path']) else: - get_logger().error(f"Could not publish inline comment {comment}") + get_logger().error(f"Could not publish inline comment: {comment}") def get_title(self): return self.pr.title @@ -313,7 +327,7 @@ class BitbucketServerProvider(GitProvider): path_parts = parsed_url.path.strip("/").split("/") if len(path_parts) < 6 or path_parts[4] != "pull-requests": raise ValueError( - "The provided URL does not appear to be a Bitbucket PR URL" + f"The provided URL '{pr_url}' does not appear to be a Bitbucket PR URL" ) workspace_slug = path_parts[1] @@ -321,7 +335,7 @@ class BitbucketServerProvider(GitProvider): try: pr_number = int(path_parts[5]) except ValueError as e: - raise ValueError("Unable to convert PR number to integer") from e + raise ValueError(f"Unable to convert PR number '{path_parts[5]}' to integer") from e return workspace_slug, repo_slug, pr_number @@ -348,8 +362,12 @@ class BitbucketServerProvider(GitProvider): "title": pr_title, "reviewers": self.pr.reviewers # needs to be sent otherwise gets wiped } + try: + self.bitbucket_client.update_pull_request(self.workspace_slug, self.repo_slug, str(self.pr_num), payload) + except Exception as e: + get_logger().error(f"Failed to update pull request, error: {e}") + raise e - self.bitbucket_client.update_pull_request(self.workspace_slug, self.repo_slug, str(self.pr_num), payload) # bitbucket does not support labels def publish_labels(self, pr_types: list): From c9c14c10b013eebe1b7c27ec673694bcb0bb0781 Mon Sep 17 00:00:00 2001 From: MarkRx <MarkRx@users.noreply.github.com> Date: Thu, 30 May 2024 20:16:21 -0400 Subject: [PATCH 213/226] Fix some server implementations not properly logging context --- pr_agent/servers/azuredevops_server_webhook.py | 11 ++++++++--- pr_agent/servers/bitbucket_server_webhook.py | 11 ++++++++--- pr_agent/servers/gitlab_webhook.py | 8 ++++++-- 3 files changed, 22 insertions(+), 8 deletions(-) diff --git a/pr_agent/servers/azuredevops_server_webhook.py b/pr_agent/servers/azuredevops_server_webhook.py index 2b926886..b97ae9c7 100644 --- a/pr_agent/servers/azuredevops_server_webhook.py +++ b/pr_agent/servers/azuredevops_server_webhook.py @@ -26,8 +26,9 @@ from pr_agent.git_providers.utils import apply_repo_settings from pr_agent.log import get_logger from fastapi import Request, Depends from fastapi.security import HTTPBasic, HTTPBasicCredentials -from pr_agent.log import get_logger +from pr_agent.log import LoggingFormat, get_logger, setup_logger +setup_logger(fmt=LoggingFormat.JSON, level="DEBUG") security = HTTPBasic() router = APIRouter() available_commands_rgx = re.compile(r"^\/(" + "|".join(command2class.keys()) + r")\s*") @@ -40,8 +41,12 @@ def handle_request( ): log_context["action"] = body log_context["api_url"] = url - with get_logger().contextualize(**log_context): - background_tasks.add_task(PRAgent().handle_request, url, body) + + async def inner(): + with get_logger().contextualize(**log_context): + await PRAgent().handle_request(url, body) + + background_tasks.add_task(inner) # currently only basic auth is supported with azure webhooks diff --git a/pr_agent/servers/bitbucket_server_webhook.py b/pr_agent/servers/bitbucket_server_webhook.py index 74c2158a..c70cb01c 100644 --- a/pr_agent/servers/bitbucket_server_webhook.py +++ b/pr_agent/servers/bitbucket_server_webhook.py @@ -13,9 +13,10 @@ from starlette_context.middleware import RawContextMiddleware from pr_agent.agent.pr_agent import PRAgent from pr_agent.config_loader import get_settings -from pr_agent.log import get_logger +from pr_agent.log import LoggingFormat, get_logger, setup_logger from pr_agent.servers.utils import verify_signature +setup_logger(fmt=LoggingFormat.JSON, level="DEBUG") router = APIRouter() @@ -24,8 +25,12 @@ def handle_request( ): log_context["action"] = body log_context["api_url"] = url - with get_logger().contextualize(**log_context): - background_tasks.add_task(PRAgent().handle_request, url, body) + + async def inner(): + with get_logger().contextualize(**log_context): + await PRAgent().handle_request(url, body) + + background_tasks.add_task(inner) @router.post("/") diff --git a/pr_agent/servers/gitlab_webhook.py b/pr_agent/servers/gitlab_webhook.py index 715185a8..8839c4f0 100644 --- a/pr_agent/servers/gitlab_webhook.py +++ b/pr_agent/servers/gitlab_webhook.py @@ -27,8 +27,12 @@ def handle_request(background_tasks: BackgroundTasks, url: str, body: str, log_c log_context["action"] = body log_context["event"] = "pull_request" if body == "/review" else "comment" log_context["api_url"] = url - with get_logger().contextualize(**log_context): - background_tasks.add_task(PRAgent().handle_request, url, body) + + async def inner(): + with get_logger().contextualize(**log_context): + await PRAgent().handle_request(url, body) + + background_tasks.add_task(inner) async def _perform_commands_gitlab(commands_conf: str, agent: PRAgent, api_url: str, log_context: dict): From d9a7dae6c4ac3fb07602c6989e7ebcb43bd47853 Mon Sep 17 00:00:00 2001 From: MarkRx <MarkRx@users.noreply.github.com> Date: Thu, 30 May 2024 20:22:58 -0400 Subject: [PATCH 214/226] Better error handling on backgrounp task thread --- pr_agent/servers/azuredevops_server_webhook.py | 7 +++++-- pr_agent/servers/bitbucket_server_webhook.py | 7 +++++-- pr_agent/servers/gitlab_webhook.py | 7 +++++-- 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/pr_agent/servers/azuredevops_server_webhook.py b/pr_agent/servers/azuredevops_server_webhook.py index b97ae9c7..e65ee86e 100644 --- a/pr_agent/servers/azuredevops_server_webhook.py +++ b/pr_agent/servers/azuredevops_server_webhook.py @@ -43,8 +43,11 @@ def handle_request( log_context["api_url"] = url async def inner(): - with get_logger().contextualize(**log_context): - await PRAgent().handle_request(url, body) + try: + with get_logger().contextualize(**log_context): + await PRAgent().handle_request(url, body) + except Exception as e: + get_logger().error(f"Failed to handle webhook: {e}") background_tasks.add_task(inner) diff --git a/pr_agent/servers/bitbucket_server_webhook.py b/pr_agent/servers/bitbucket_server_webhook.py index c70cb01c..079af995 100644 --- a/pr_agent/servers/bitbucket_server_webhook.py +++ b/pr_agent/servers/bitbucket_server_webhook.py @@ -27,8 +27,11 @@ def handle_request( log_context["api_url"] = url async def inner(): - with get_logger().contextualize(**log_context): - await PRAgent().handle_request(url, body) + try: + with get_logger().contextualize(**log_context): + await PRAgent().handle_request(url, body) + except Exception as e: + get_logger().error(f"Failed to handle webhook: {e}") background_tasks.add_task(inner) diff --git a/pr_agent/servers/gitlab_webhook.py b/pr_agent/servers/gitlab_webhook.py index 8839c4f0..777e184f 100644 --- a/pr_agent/servers/gitlab_webhook.py +++ b/pr_agent/servers/gitlab_webhook.py @@ -29,8 +29,11 @@ def handle_request(background_tasks: BackgroundTasks, url: str, body: str, log_c log_context["api_url"] = url async def inner(): - with get_logger().contextualize(**log_context): - await PRAgent().handle_request(url, body) + try: + with get_logger().contextualize(**log_context): + await PRAgent().handle_request(url, body) + except Exception as e: + get_logger().error(f"Failed to handle webhook: {e}") background_tasks.add_task(inner) From c34144601566a3f8eec0e4a59508b21e6e91893f Mon Sep 17 00:00:00 2001 From: mrT23 <tal.r@codium.ai> Date: Fri, 31 May 2024 16:09:34 +0300 Subject: [PATCH 215/226] Add documentation for PR-Agent code fine-tuning benchmark and update mkdocs.yml --- docs/docs/finetuning_benchmark/index.md | 193 ++++++++++++++++++++++++ docs/mkdocs.yml | 1 + 2 files changed, 194 insertions(+) create mode 100644 docs/docs/finetuning_benchmark/index.md diff --git a/docs/docs/finetuning_benchmark/index.md b/docs/docs/finetuning_benchmark/index.md new file mode 100644 index 00000000..b624cb1d --- /dev/null +++ b/docs/docs/finetuning_benchmark/index.md @@ -0,0 +1,193 @@ +# PR-Agent Code Fine-tuning Benchmark + +On coding tasks, the gap between open-source models and top closed-source models such as GPT4 is significant. +<br> +In practice, open-source models are unsuitable for most real-world code tasks, and require further fine-tuning to produce acceptable results. + +_PR-Agent fine-tuning benchmark_ aims to benchmark open-source models on their ability to be fine-tuned for a code task. +Specifically, we chose to fine-tune open-source models on the task of analyzing a pull request, and providing useful feedback and code suggestions. + +Here are the results: +<br> +<br> + +<head> + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <style> + td, th { + font-size: 16px; /* Adjust this value to your preference */ + } + table { + width: 100%; + border-collapse: collapse; + } + th { + background-color: #f2f2f2; + border: 1px solid #dddddd; + text-align: center; + padding: 8px; + } + td { + border: 1px solid #dddddd; + text-align: center; + padding: 8px; + } + tr:nth-child(even) { + background-color: #f9f9f9; + text-align: center; + } + </style> + <title>Model Performance Table + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Model nameModel size [B]Better than gpt-4 rate, after fine-tuning [%]
DeepSeek 34B-instruct3440.7
DeepSeek 34B-base3438.2
Phind-34b3438
Granite-34B3437.6
Codestral-22B-v0.12232.7
QWEN-1.5-32B3229
CodeQwen1.5-7B735.4
Granite-8b-code-instruct834.2
CodeLlama-7b-hf731.8
Gemma-7B727.2
DeepSeek coder-7b-instruct726.8
Llama-3-8B-Instruct826.8
Mistral-7B-v0.1716.1
+ + + +
+ +**Fine-tuning impact:** + + + + + + + + + + + + + + + + + + + + +
Model nameModel size [B]Fine-tunedBetter than gpt-4 rate [%]
DeepSeek 34B-instruct34yes40.7
DeepSeek 34B-instruct34no3.6
+ + + + +## Results analysis + +- **Fine-tuning is a must** - without fine-tuning, open-source models provide poor results on most real-world code tasks, which include complicated prompt and lengthy context. We clearly see that without fine-tuning, deepseek model was 96.4% of the time inferior to GPT-4, while after fine-tuning, it is better 40.7% of the time. +- **Always start from a code-dedicated model** โ€” When fine-tuning, always start from a code-dedicated model, and not from a general-usage model. The gaps in downstream results are very big. +- **Don't believe the hype** โ€”newer models, or models from big-tech companies (Llama3, Gemma, Mistral), are not always better for fine-tuning. +- **The best large model** - For large 34B code-dedicated models, the gaps when doing proper fine-tuning are small. The current top model is **DeepSeek 34B-instruct** +- **The best small model** - For small 7B code-dedicated models, the gaps when fine-tuning are much larger. **CodeQWEN 1.5-7B** is by far the best model for fine-tuning. +- **Base vs. instruct** - For the top model (deepseek), we saw small advantage when starting from the instruct version. However, we recommend testing both versions on each specific task, as the base model is generally considered more suitable for fine-tuning. + + +## The dataset + +### Training dataset + +Our training dataset is comprised of 25,000 pull requests, aggregated from permissive license repos. For each pull request, we generated responses for the three main tools of PR-Agent: +[Describe](https://pr-agent-docs.codium.ai/tools/describe/), [Review](https://pr-agent-docs.codium.ai/tools/improve/) and [Improve](https://pr-agent-docs.codium.ai/tools/improve/). + +On the raw data collected, we employed various automatic and manual cleaning techniques to ensure the outputs were of the highest quality, and suitable for instruct-tuning. +An example input prompt can be found [here](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/pr_code_suggestions_prompts.toml), and an example output can be found [here](https://github.com/Codium-ai/pr-agent/pull/910#issuecomment-2118761309). + +### Evaluation dataset +- For each tool, we aggregated 100 additional examples to be used for evaluation. These examples were not used in the training dataset, and were manually selected to represent diverse real-world use-cases. +- For each test example, we generated two responses: one from the fine-tuned model, and one from the best code model in the world, `gpt-4-turbo-2024-04-09`. + +- We used a third LLM to judge which response better answers the prompt, and will likely be perceived by a human as better response. +
+We experimented with three model as judges: `gpt-4-turbo-2024-04-09`, `gpt-4o`, and `claude-3-opus-20240229`. All three produced similar results, with the same ranking order. This strengthens the validity of our testing protocol. + +Here is an example for a judge model feedback: + +``` +command: improve +model1_score: 9, +model2_score: 6, +why: | + Response 1 is better because it provides more actionable and specific suggestions that directly + enhance the code's maintainability, performance, and best practices. For example, it suggests + using a variable for reusable widget instances and using named routes for navigation, which + are practical improvements. In contrast, Response 2 focuses more on general advice and less + actionable suggestions, such as changing variable names and adding comments, which are less + critical for immediate code improvement." +``` \ No newline at end of file diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index bd6ecaa0..01d8ce65 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -38,6 +38,7 @@ nav: - ๐Ÿ’Ž Similar Code: 'tools/similar_code.md' - Core Abilities: 'core-abilities/index.md' - Chrome Extension: 'chrome-extension/index.md' + - Code Fine-tuning Benchmark: 'finetuning_benchmark/index.md' theme: logo: assets/logo.svg From 731c8de4eac412205ce2573c04514ca594c1aae6 Mon Sep 17 00:00:00 2001 From: mrT23 Date: Fri, 31 May 2024 16:12:25 +0300 Subject: [PATCH 216/226] Add documentation for PR-Agent code fine-tuning benchmark and update mkdocs.yml --- docs/docs/finetuning_benchmark/index.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/docs/finetuning_benchmark/index.md b/docs/docs/finetuning_benchmark/index.md index b624cb1d..21217b33 100644 --- a/docs/docs/finetuning_benchmark/index.md +++ b/docs/docs/finetuning_benchmark/index.md @@ -82,6 +82,7 @@ Here are the results: + CodeQwen1.5-7B 7 From dc6ae9fa7e22213ac2e5973d25ccaed48859270e Mon Sep 17 00:00:00 2001 From: Tal Date: Fri, 31 May 2024 16:25:00 +0300 Subject: [PATCH 217/226] Update README.md --- README.md | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index a82605d7..79c75520 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,7 @@ CodiumAI PR-Agent aims to help efficiently review and handle pull requests, by p [![GitHub license](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://github.com/Codium-ai/pr-agent/blob/main/LICENSE) [![Static Badge](https://img.shields.io/badge/Chrome-Extension-violet)](https://chromewebstore.google.com/detail/pr-agent-chrome-extension/ephlnjeghhogofkifjloamocljapahnl) +[![Static Badge](https://img.shields.io/badge/Code-Benchmark-blue)](https://pr-agent-docs.codium.ai/finetuning_benchmark/) [![Discord](https://badgen.net/badge/icon/discord?icon=discord&label&color=purple)](https://discord.com/channels/1057273017547378788/1126104260430528613) [![Twitter](https://img.shields.io/twitter/follow/codiumai)](https://twitter.com/codiumai) @@ -41,6 +42,10 @@ CodiumAI PR-Agent aims to help efficiently review and handle pull requests, by p ## News and Updates +### May 31, 2024 + +Check out the new [**PR-Agent Code Fine-tuning Benchmark**](https://pr-agent-docs.codium.ai/finetuning_benchmark/) + ### May 23, 2024 We released a new version of [PR-Agent Chrome extension](https://chromewebstore.google.com/detail/pr-agent-chrome-extension/ephlnjeghhogofkifjloamocljapahnl), with two new features: @@ -54,19 +59,6 @@ See more [here](https://www.youtube.com/watch?v=v9bJ1frtPcg) ### May 21, 2024 Check out CodiumAI new project, [**Cover-Agent**](https://github.com/Codium-ai/cover-agent), that can automatically generate qualified tests to enhance existing test suites, aiming to increase code and behavior coverage efficiently. -### May 19, 2024 -GPT-4o is now the default fast model ("Turbo"). This model will be used for all commands except `review` and `improve`, which will still use "GPT-4-2024-04-09", since they are harder and would still benefit from the larger model. - -### May 12, 2024 -Inspired by [AlphaCodium](https://github.com/Codium-ai/AlphaCodium) flow engineering scheme, PR-Agent now performs **self-reflection** on the code suggestions it provides, -enabling to remove invalid suggestions, and score the valid ones. The suggestions will be presented sorted by their score, enabling to focus on the most important ones first. - -You can also choose to automatically remove suggestions below a certain importance score threshold, by setting the `pr_code_suggestions.suggestions_score_threshold` [configuration](https://pr-agent-docs.codium.ai/tools/improve/#configuration-options). - - - - - ## Overview
From ea7a84901da66f0eb0f9574a663f4e09a9cb2f81 Mon Sep 17 00:00:00 2001 From: KennyDizi Date: Sat, 1 Jun 2024 08:05:37 +0700 Subject: [PATCH 218/226] Simplify model performance table --- docs/docs/finetuning_benchmark/index.md | 128 ++++-------------------- 1 file changed, 17 insertions(+), 111 deletions(-) diff --git a/docs/docs/finetuning_benchmark/index.md b/docs/docs/finetuning_benchmark/index.md index 21217b33..b33deae3 100644 --- a/docs/docs/finetuning_benchmark/index.md +++ b/docs/docs/finetuning_benchmark/index.md @@ -11,116 +11,22 @@ Here are the results:

- - - - - Model Performance Table - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Model nameModel size [B]Better than gpt-4 rate, after fine-tuning [%]
DeepSeek 34B-instruct3440.7
DeepSeek 34B-base3438.2
Phind-34b3438
Granite-34B3437.6
Codestral-22B-v0.12232.7
QWEN-1.5-32B3229
CodeQwen1.5-7B735.4
Granite-8b-code-instruct834.2
CodeLlama-7b-hf731.8
Gemma-7B727.2
DeepSeek coder-7b-instruct726.8
Llama-3-8B-Instruct826.8
Mistral-7B-v0.1716.1
- - +| Model name | Model size [B] | Better than gpt-4 rate, after fine-tuning [%] | +|-----------------------------|----------------|----------------------------------------------| +| **DeepSeek 34B-instruct** | **34** | **40.7** | +| DeepSeek 34B-base | 34 | 38.2 | +| Phind-34b | 34 | 38 | +| Granite-34B | 34 | 37.6 | +| Codestral-22B-v0.1 | 22 | 32.7 | +| QWEN-1.5-32B | 32 | 29 | +| | | | +| **CodeQwen1.5-7B** | **7** | **35.4** | +| Granite-8b-code-instruct | 8 | 34.2 | +| CodeLlama-7b-hf | 7 | 31.8 | +| Gemma-7B | 7 | 27.2 | +| DeepSeek coder-7b-instruct | 7 | 26.8 | +| Llama-3-8B-Instruct | 8 | 26.8 | +| Mistral-7B-v0.1 | 7 | 16.1 |
@@ -191,4 +97,4 @@ why: | are practical improvements. In contrast, Response 2 focuses more on general advice and less actionable suggestions, such as changing variable names and adding comments, which are less critical for immediate code improvement." -``` \ No newline at end of file +``` From b9aeb8e4438bf3ab8ab44b18a5ff2f852a4aed4d Mon Sep 17 00:00:00 2001 From: KennyDizi Date: Sat, 1 Jun 2024 08:09:41 +0700 Subject: [PATCH 219/226] Fix all markdownlint violations --- docs/docs/finetuning_benchmark/index.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/docs/finetuning_benchmark/index.md b/docs/docs/finetuning_benchmark/index.md index b33deae3..6305b732 100644 --- a/docs/docs/finetuning_benchmark/index.md +++ b/docs/docs/finetuning_benchmark/index.md @@ -1,8 +1,8 @@ # PR-Agent Code Fine-tuning Benchmark -On coding tasks, the gap between open-source models and top closed-source models such as GPT4 is significant. +On coding tasks, the gap between open-source models and top closed-source models such as GPT4 is significant.
-In practice, open-source models are unsuitable for most real-world code tasks, and require further fine-tuning to produce acceptable results. +In practice, open-source models are unsuitable for most real-world code tasks, and require further fine-tuning to produce acceptable results. _PR-Agent fine-tuning benchmark_ aims to benchmark open-source models on their ability to be fine-tuned for a code task. Specifically, we chose to fine-tune open-source models on the task of analyzing a pull request, and providing useful feedback and code suggestions. @@ -11,6 +11,8 @@ Here are the results:

+**Model performance:** + | Model name | Model size [B] | Better than gpt-4 rate, after fine-tuning [%] | |-----------------------------|----------------|----------------------------------------------| | **DeepSeek 34B-instruct** | **34** | **40.7** | @@ -55,7 +57,6 @@ Here are the results: - ## Results analysis - **Fine-tuning is a must** - without fine-tuning, open-source models provide poor results on most real-world code tasks, which include complicated prompt and lengthy context. We clearly see that without fine-tuning, deepseek model was 96.4% of the time inferior to GPT-4, while after fine-tuning, it is better 40.7% of the time. @@ -65,10 +66,9 @@ Here are the results: - **The best small model** - For small 7B code-dedicated models, the gaps when fine-tuning are much larger. **CodeQWEN 1.5-7B** is by far the best model for fine-tuning. - **Base vs. instruct** - For the top model (deepseek), we saw small advantage when starting from the instruct version. However, we recommend testing both versions on each specific task, as the base model is generally considered more suitable for fine-tuning. +## The dataset -## The dataset - -### Training dataset +### Training dataset Our training dataset is comprised of 25,000 pull requests, aggregated from permissive license repos. For each pull request, we generated responses for the three main tools of PR-Agent: [Describe](https://pr-agent-docs.codium.ai/tools/describe/), [Review](https://pr-agent-docs.codium.ai/tools/improve/) and [Improve](https://pr-agent-docs.codium.ai/tools/improve/). @@ -77,11 +77,13 @@ On the raw data collected, we employed various automatic and manual cleaning tec An example input prompt can be found [here](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/pr_code_suggestions_prompts.toml), and an example output can be found [here](https://github.com/Codium-ai/pr-agent/pull/910#issuecomment-2118761309). ### Evaluation dataset + - For each tool, we aggregated 100 additional examples to be used for evaluation. These examples were not used in the training dataset, and were manually selected to represent diverse real-world use-cases. - For each test example, we generated two responses: one from the fine-tuned model, and one from the best code model in the world, `gpt-4-turbo-2024-04-09`. - We used a third LLM to judge which response better answers the prompt, and will likely be perceived by a human as better response.
+ We experimented with three model as judges: `gpt-4-turbo-2024-04-09`, `gpt-4o`, and `claude-3-opus-20240229`. All three produced similar results, with the same ranking order. This strengthens the validity of our testing protocol. Here is an example for a judge model feedback: From 85f6353d15d899af0ab52bdd3a1ee9c4eb3d7665 Mon Sep 17 00:00:00 2001 From: KennyDizi Date: Sat, 1 Jun 2024 08:11:34 +0700 Subject: [PATCH 220/226] Optimize for fine-tuning impact table --- docs/docs/finetuning_benchmark/index.md | 27 +++++-------------------- 1 file changed, 5 insertions(+), 22 deletions(-) diff --git a/docs/docs/finetuning_benchmark/index.md b/docs/docs/finetuning_benchmark/index.md index 6305b732..a09bb593 100644 --- a/docs/docs/finetuning_benchmark/index.md +++ b/docs/docs/finetuning_benchmark/index.md @@ -33,29 +33,12 @@ Here are the results:
**Fine-tuning impact:** - - - - - - - - - - - - - - - - - - - - -
Model nameModel size [B]Fine-tunedBetter than gpt-4 rate [%]
DeepSeek 34B-instruct34yes40.7
DeepSeek 34B-instruct34no3.6
+**Fine-tuning impact:** - +| Model name | Model size [B] | Fine-tuned | Better than gpt-4 rate [%] | +|---------------------------|----------------|------------|----------------------------| +| DeepSeek 34B-instruct | 34 | yes | 40.7 | +| DeepSeek 34B-instruct | 34 | no | 3.6 | ## Results analysis From 40658cfb7cc9ad52efcb55d49bde1cace4b23d6b Mon Sep 17 00:00:00 2001 From: KennyDizi Date: Sat, 1 Jun 2024 08:14:25 +0700 Subject: [PATCH 221/226] Removed duplicaiton line --- docs/docs/finetuning_benchmark/index.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/docs/finetuning_benchmark/index.md b/docs/docs/finetuning_benchmark/index.md index a09bb593..b41660d1 100644 --- a/docs/docs/finetuning_benchmark/index.md +++ b/docs/docs/finetuning_benchmark/index.md @@ -32,7 +32,6 @@ Here are the results:
-**Fine-tuning impact:** **Fine-tuning impact:** | Model name | Model size [B] | Fine-tuned | Better than gpt-4 rate [%] | From 416b150d666939837725d5df92d9431053eee2dc Mon Sep 17 00:00:00 2001 From: mrT23 Date: Sun, 2 Jun 2024 11:28:48 +0300 Subject: [PATCH 222/226] Add documentation for PR-Agent code fine-tuning benchmark and update mkdocs.yml --- docs/docs/finetuning_benchmark/index.md | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/docs/docs/finetuning_benchmark/index.md b/docs/docs/finetuning_benchmark/index.md index b41660d1..a89eb93d 100644 --- a/docs/docs/finetuning_benchmark/index.md +++ b/docs/docs/finetuning_benchmark/index.md @@ -52,11 +52,18 @@ Here are the results: ### Training dataset -Our training dataset is comprised of 25,000 pull requests, aggregated from permissive license repos. For each pull request, we generated responses for the three main tools of PR-Agent: +Our training dataset comprises 25,000 pull requests, aggregated from permissive license repos. For each pull request, we generated responses for the three main tools of PR-Agent: [Describe](https://pr-agent-docs.codium.ai/tools/describe/), [Review](https://pr-agent-docs.codium.ai/tools/improve/) and [Improve](https://pr-agent-docs.codium.ai/tools/improve/). On the raw data collected, we employed various automatic and manual cleaning techniques to ensure the outputs were of the highest quality, and suitable for instruct-tuning. -An example input prompt can be found [here](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/pr_code_suggestions_prompts.toml), and an example output can be found [here](https://github.com/Codium-ai/pr-agent/pull/910#issuecomment-2118761309). + +Here are the prompts, and example outputs, used to fine-tune the models: + +| Tool | Prompt | Example output | +|----------|------------------------------------------------------------------------------------------------------------|----------------| +| Describe | [link](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/pr_description_prompts.toml) | [link](https://github.com/Codium-ai/pr-agent/pull/910#issue-2303989601) | +| Review | [link](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/pr_reviewer_prompts.toml) | [link](https://github.com/Codium-ai/pr-agent/pull/910#issuecomment-2118761219) | +| Improve | [link](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/pr_code_suggestions_prompts.toml) | [link](https://github.com/Codium-ai/pr-agent/pull/910#issuecomment-2118761309) | ### Evaluation dataset From f3aa9c02ccf8cd268fb4eeb7947b684dcee8b7f5 Mon Sep 17 00:00:00 2001 From: mrT23 Date: Sun, 2 Jun 2024 11:30:56 +0300 Subject: [PATCH 223/226] Add documentation for PR-Agent code fine-tuning benchmark and update mkdocs.yml --- docs/docs/finetuning_benchmark/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/finetuning_benchmark/index.md b/docs/docs/finetuning_benchmark/index.md index a89eb93d..35ec064b 100644 --- a/docs/docs/finetuning_benchmark/index.md +++ b/docs/docs/finetuning_benchmark/index.md @@ -57,7 +57,7 @@ Our training dataset comprises 25,000 pull requests, aggregated from permissive On the raw data collected, we employed various automatic and manual cleaning techniques to ensure the outputs were of the highest quality, and suitable for instruct-tuning. -Here are the prompts, and example outputs, used to fine-tune the models: +Here are the prompts, and example outputs, used as input-output paris to fine-tune the models: | Tool | Prompt | Example output | |----------|------------------------------------------------------------------------------------------------------------|----------------| From 962bb1c23ddd21d87ebde57c1fc77cd29c6b8336 Mon Sep 17 00:00:00 2001 From: Tal Date: Sun, 2 Jun 2024 11:35:33 +0300 Subject: [PATCH 224/226] Update index.md --- docs/docs/finetuning_benchmark/index.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/docs/finetuning_benchmark/index.md b/docs/docs/finetuning_benchmark/index.md index 35ec064b..b39b7d80 100644 --- a/docs/docs/finetuning_benchmark/index.md +++ b/docs/docs/finetuning_benchmark/index.md @@ -4,7 +4,7 @@ On coding tasks, the gap between open-source models and top closed-source models
In practice, open-source models are unsuitable for most real-world code tasks, and require further fine-tuning to produce acceptable results. -_PR-Agent fine-tuning benchmark_ aims to benchmark open-source models on their ability to be fine-tuned for a code task. +_PR-Agent fine-tuning benchmark_ aims to benchmark open-source models on their ability to be fine-tuned for a coding task. Specifically, we chose to fine-tune open-source models on the task of analyzing a pull request, and providing useful feedback and code suggestions. Here are the results: @@ -57,7 +57,7 @@ Our training dataset comprises 25,000 pull requests, aggregated from permissive On the raw data collected, we employed various automatic and manual cleaning techniques to ensure the outputs were of the highest quality, and suitable for instruct-tuning. -Here are the prompts, and example outputs, used as input-output paris to fine-tune the models: +Here are the prompts, and example outputs, used as input-output pairs to fine-tune the models: | Tool | Prompt | Example output | |----------|------------------------------------------------------------------------------------------------------------|----------------| @@ -75,7 +75,7 @@ Here are the prompts, and example outputs, used as input-output paris to fine-tu We experimented with three model as judges: `gpt-4-turbo-2024-04-09`, `gpt-4o`, and `claude-3-opus-20240229`. All three produced similar results, with the same ranking order. This strengthens the validity of our testing protocol. -Here is an example for a judge model feedback: +Here is an example of a judge model feedback: ``` command: improve From 4f130072679ec0249af3c8b6a9f5c2b4821fdc9d Mon Sep 17 00:00:00 2001 From: mrT23 Date: Mon, 3 Jun 2024 08:15:36 +0300 Subject: [PATCH 225/226] Disable final update message when auto_describe is enabled in GitHub Action Runner --- docs/docs/usage-guide/automations_and_usage.md | 1 - pr_agent/servers/github_action_runner.py | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/usage-guide/automations_and_usage.md b/docs/docs/usage-guide/automations_and_usage.md index aa969755..35c95099 100644 --- a/docs/docs/usage-guide/automations_and_usage.md +++ b/docs/docs/usage-guide/automations_and_usage.md @@ -118,7 +118,6 @@ Specifically, start by setting the following environment variables: github_action_config.auto_review: "true" # enable\disable auto review github_action_config.auto_describe: "true" # enable\disable auto describe github_action_config.auto_improve: "true" # enable\disable auto improve - github_action_config.enable_output: "true" # enable\disable github actions output parameter ``` `github_action_config.auto_review`, `github_action_config.auto_describe` and `github_action_config.auto_improve` are used to enable/disable automatic tools that run when a new PR is opened. If not set, the default configuration is for all three tools to run automatically when a new PR is opened. diff --git a/pr_agent/servers/github_action_runner.py b/pr_agent/servers/github_action_runner.py index 1aafcaae..8067187b 100644 --- a/pr_agent/servers/github_action_runner.py +++ b/pr_agent/servers/github_action_runner.py @@ -99,6 +99,7 @@ async def run_action(): # invoke by default all three tools if auto_describe is None or is_true(auto_describe): + get_settings().pr_description.final_update_message = False # No final update message when auto_describe is enabled await PRDescription(pr_url).run() if auto_review is None or is_true(auto_review): await PRReviewer(pr_url).run() From 09190efb650dd0d43c1ea8f117af33f952b4fe4e Mon Sep 17 00:00:00 2001 From: mrT23 Date: Mon, 3 Jun 2024 11:35:39 +0300 Subject: [PATCH 226/226] Add PR evaluation prompt and link to fine-tuning benchmark documentation --- docs/docs/finetuning_benchmark/index.md | 1 + .../settings/pr_evaluate_prompt_response.toml | 68 +++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 pr_agent/settings/pr_evaluate_prompt_response.toml diff --git a/docs/docs/finetuning_benchmark/index.md b/docs/docs/finetuning_benchmark/index.md index b39b7d80..dc7cfa6b 100644 --- a/docs/docs/finetuning_benchmark/index.md +++ b/docs/docs/finetuning_benchmark/index.md @@ -74,6 +74,7 @@ Here are the prompts, and example outputs, used as input-output pairs to fine-tu
We experimented with three model as judges: `gpt-4-turbo-2024-04-09`, `gpt-4o`, and `claude-3-opus-20240229`. All three produced similar results, with the same ranking order. This strengthens the validity of our testing protocol. +The evaluation prompt can be found [here](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/pr_evaluate_prompt_response.toml) Here is an example of a judge model feedback: diff --git a/pr_agent/settings/pr_evaluate_prompt_response.toml b/pr_agent/settings/pr_evaluate_prompt_response.toml new file mode 100644 index 00000000..2cc0c6e7 --- /dev/null +++ b/pr_agent/settings/pr_evaluate_prompt_response.toml @@ -0,0 +1,68 @@ +[pr_evaluate_prompt] +prompt="""\ +You are the PR-task-evaluator, a language model that compares and ranks the quality of two responses provided in response to a lengthy task regarding a Pull Request (PR) code diff. + + +The task to be evaluated is: + +***** Start of Task ***** +{{pr_task|trim}} + +***** End of Task ***** + + + +Response 1 to the task is: + +***** Start of Response 1 ***** + +{{pr_response1|trim}} + +***** End of Response 1 ***** + + + +Response 2 to the task is: + +***** Start of Response 2 ***** + +{{pr_response2|trim}} + +***** End of Response 2 ***** + + + +Guidelines to evaluate the responses: +- Thoroughly read the 'Task' part. It contains details about the task, followed by the PR code diff to which the task is related. +- Thoroughly read 'Response1' and 'Response2' parts. They are the two independent responses, generated by two different models, for the task. + +After that, rank each response. Criterions to rank each response: +- How well does the response follow the specific task instructions and requirements? +- How well does the response analyze and understand the PR code diff? +- How well will a person perceive it as a good response that correctly addresses the task? +- How well does the reponse prioritize key feedback, related to the task instructions, that a human reader seeing that feedback would also consider as important? +- Don't neccessarily rank higher a response that is longer. A shorter response might be better if it is more concise, and still addresses the task better. + + +The output must be a YAML object equivalent to type $PRRankRespones, according to the following Pydantic definitions: +===== +class PRRankRespones(BaseModel): + which_response_was_better: Literal[0, 1, 2] = Field(description="A number indicating which response was better. 0 means both responses are equally good.") + why: str = Field(description="In a short and concise manner, explain why the chosen response is better than the other. Be specific and give examples if relevant.") + score_response1: int = Field(description="A score between 1 and 10, indicating the quality of the response1, based on the criterions mentioned in the prompt.") + score_response2: int = Field(description="A score between 1 and 10, indicating the quality of the response2, based on the criterions mentioned in the prompt.") +===== + + +Example output: +```yaml +which_response_was_better: "X" +why: "Response X is better because it is more practical, and addresses the task requirements better since ..." +score_response1: ... +score_response2: ... +``` + + +Response (should be a valid YAML, and nothing else): +```yaml +"""