chore: import upstream snapshot with attribution
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
<p align="center">
|
||||
<a href="https://superagi.com//#gh-light-mode-only">
|
||||
<img src="https://superagi.com/wp-content/uploads/2023/05/Logo-dark.svg" width="318px" alt="SuperAGI logo" />
|
||||
</a>
|
||||
<a href="https://superagi.com//#gh-dark-mode-only">
|
||||
<img src="https://superagi.com/wp-content/uploads/2023/05/Logo-light.svg" width="318px" alt="SuperAGI logo" />
|
||||
</a>
|
||||
</p>
|
||||
|
||||
# SuperAGI GitHub Tool
|
||||
|
||||
The SuperAGI GitHub Tool enables users to perform various operations on GitHub repositories which include adding files or folders, deleting files, and searching for files or folders within a repository.
|
||||
|
||||
## 💡 Features
|
||||
|
||||
1. **Add Files or Folders:** With SuperAGI's GitHub Tool, you can easily add files or folders to a GitHub repository
|
||||
2. **Delete Files:** Remove files from a GitHub repository effortlessly using SuperAGI's GitHub Tool.
|
||||
3. **Search for Files or Folders:** Find specific files or folders within a GitHub repository using SuperAGI's GitHub Tool.
|
||||
|
||||
## ⚙️ Installation
|
||||
|
||||
### 🛠 **Setting Up SuperAGI**
|
||||
|
||||
Set up SuperAGI by following the instructions provided in the [SuperAGI repository's README file](https://github.com/TransformerOptimus/SuperAGI/blob/main/README.md).
|
||||
|
||||
### 🔧 **Add GitHub Configuration Settings in SuperAGI Dashboard**
|
||||
|
||||
Add the following configuration settings to the GitHub Toolkit Page:
|
||||
|
||||
1. _GitHub Access Token:_
|
||||
- Obtain a GitHub access token with the necessary permissions for accessing and modifying repositories.
|
||||
- Go to Settings in your GitHub Account. Then go to Developer Settings.
|
||||
- Click on "Personal access tokens". Then click on "Tokens (classic)".
|
||||

|
||||
- Click on "Generate new token". Then choose "Generate new token (classic)".
|
||||

|
||||
- Write a Note about what the token is for and choose an appropriate expiration date.
|
||||

|
||||
- Select all the scopes (In this way, users won't have to create new Access Tokens every time we add new scopes to the code).
|
||||
- Click on Generate New Token.
|
||||
- Copy the token and save it as a separate file.
|
||||
|
||||
2. _Github User Name:_
|
||||
- You can find your GitHub username on your GitHub Profile.
|
||||
|
||||
3. _Configuring in SuperAGI Dashboard:_
|
||||
-You can add your Generated Token and your Username to the GitHub Toolkit Page.
|
||||
|
||||
## Running SuperAGI GitHub Tool
|
||||
|
||||
1. **Add Files or Folders:**
|
||||
|
||||
To add a file or folder to a GitHub repository, specify the repository and the owner's UserName and the path where the file/folder should be added to your goal. SuperAGI will upload it to the repository and automatically raise a PR for it. By default, it'll pick the main branch, if you want to add it to any other branch you have to mention it in the goal.
|
||||
|
||||
2. **Delete Files:**
|
||||
|
||||
To delete a file from a GitHub repository, mention the repository, owner's UserName and provide the path to the file you want to delete in your goal. SuperAGI will handle the deletion process and raise a PR for it. By default, it'll pick the main branch, if you want to delete it to any other branch you have to mention it in the goal.
|
||||
|
||||
3. **Search for Files or Folders**
|
||||
|
||||
To search for files or folders within a GitHub repository, specify the repository, and owner's UserName and provide the name or path of the file/folder you're looking for in your goal. SuperAGI will provide you with the search results. By default, it'll pick the main branch, if you want to search in any other branch you have to mention it in the goal.
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
from typing import Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from superagi.helper.github_helper import GithubHelper
|
||||
from superagi.tools.base_tool import BaseTool
|
||||
|
||||
|
||||
class GithubAddFileSchema(BaseModel):
|
||||
# """Input for CopyFileTool."""
|
||||
repository_name: str = Field(
|
||||
...,
|
||||
description="Repository name in which file hase to be added",
|
||||
)
|
||||
base_branch: str = Field(
|
||||
...,
|
||||
description="branch to interact with",
|
||||
)
|
||||
file_name: str = Field(
|
||||
...,
|
||||
description="file name to be added to repository",
|
||||
)
|
||||
folder_path: str = Field(
|
||||
...,
|
||||
description="folder path for the file to be stored",
|
||||
)
|
||||
commit_message: str = Field(
|
||||
...,
|
||||
description="clear description of the contents of file",
|
||||
)
|
||||
repository_owner: str = Field(
|
||||
...,
|
||||
description="Owner of the github repository",
|
||||
)
|
||||
|
||||
|
||||
class GithubAddFileTool(BaseTool):
|
||||
"""
|
||||
Add File tool
|
||||
|
||||
Attributes:
|
||||
name : The name.
|
||||
description : The description.
|
||||
args_schema : The args schema.
|
||||
"""
|
||||
name: str = "Github Add File"
|
||||
args_schema: Type[BaseModel] = GithubAddFileSchema
|
||||
description: str = "Add a file or folder to a particular github repository"
|
||||
agent_id: int = None
|
||||
agent_execution_id: int = None
|
||||
|
||||
def _execute(self, repository_name: str, base_branch: str, commit_message: str, repository_owner: str,
|
||||
file_name='.gitkeep', folder_path=None) -> str:
|
||||
"""
|
||||
Execute the add file tool.
|
||||
|
||||
Args:
|
||||
repository_name : The name of the repository to add file to.
|
||||
base_branch : The branch to interact with.
|
||||
commit_message : Clear description of the contents of file.
|
||||
repository_owner : Owner of the GitHub repository.
|
||||
file_name : The name of the file to add.
|
||||
folder_path : The path of the folder to add the file to.
|
||||
|
||||
Returns:
|
||||
Pull request success message if pull request is created successfully else error message.
|
||||
"""
|
||||
session = self.toolkit_config.session
|
||||
try:
|
||||
github_access_token = self.get_tool_config("GITHUB_ACCESS_TOKEN")
|
||||
github_username = self.get_tool_config("GITHUB_USERNAME")
|
||||
github_helper = GithubHelper(github_access_token, github_username)
|
||||
head_branch = 'new-file'
|
||||
headers = {
|
||||
"Authorization": f"token {github_access_token}" if github_access_token else None,
|
||||
"Content-Type": "application/vnd.github+json"
|
||||
}
|
||||
if repository_owner != github_username:
|
||||
fork_response = github_helper.make_fork(repository_owner, repository_name, base_branch, headers)
|
||||
|
||||
branch_response = github_helper.create_branch(repository_name, base_branch, head_branch, headers)
|
||||
file_response = github_helper.add_file(repository_owner, repository_name, file_name, folder_path,
|
||||
head_branch, base_branch, headers, commit_message, self.agent_id, self.agent_execution_id, session)
|
||||
pr_response = github_helper.create_pull_request(repository_owner, repository_name, head_branch, base_branch,
|
||||
headers)
|
||||
if (pr_response == 201 or pr_response == 422) and (file_response == 201 or file_response == 422):
|
||||
return "Pull request to add file/folder has been created"
|
||||
else:
|
||||
return "Error while adding file."
|
||||
except Exception as err:
|
||||
return f"Error: Unable to add file/folder to repository {err}"
|
||||
@@ -0,0 +1,92 @@
|
||||
from typing import Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from superagi.tools.base_tool import BaseTool
|
||||
from superagi.helper.github_helper import GithubHelper
|
||||
from superagi.lib.logger import logger
|
||||
|
||||
|
||||
class GithubDeleteFileSchema(BaseModel):
|
||||
# """Input for CopyFileTool."""
|
||||
repository_name: str = Field(
|
||||
...,
|
||||
description="Repository name in which file hase to be deleted",
|
||||
)
|
||||
base_branch: str = Field(
|
||||
...,
|
||||
description="branch to interact with",
|
||||
)
|
||||
file_name: str = Field(
|
||||
...,
|
||||
description="file name to be deleted in the repository",
|
||||
)
|
||||
folder_path: str = Field(
|
||||
...,
|
||||
description="folder path in which file to be deleted is present",
|
||||
)
|
||||
commit_message: str = Field(
|
||||
...,
|
||||
description="clear description of files that are being deleted",
|
||||
)
|
||||
repository_owner: str = Field(
|
||||
...,
|
||||
description="Owner of the github repository",
|
||||
)
|
||||
|
||||
|
||||
class GithubDeleteFileTool(BaseTool):
|
||||
"""
|
||||
Delete File tool
|
||||
|
||||
Attributes:
|
||||
name : The name.
|
||||
description : The description.
|
||||
args_schema : The args schema.
|
||||
"""
|
||||
name: str = "Github Delete File"
|
||||
args_schema: Type[BaseModel] = GithubDeleteFileSchema
|
||||
description: str = "Delete a file or folder inside a particular github repository"
|
||||
|
||||
def _execute(self, repository_name: str, base_branch: str, file_name: str, commit_message: str,
|
||||
repository_owner: str, folder_path=None) -> str:
|
||||
"""
|
||||
Execute the delete file tool.
|
||||
|
||||
Args:
|
||||
repository_name : The name of the repository to delete file from.
|
||||
base_branch : The branch to interact with.
|
||||
file_name : The name of the file to delete.
|
||||
commit_message : Clear description of the contents of file.
|
||||
repository_owner : Owner of the GitHub repository.
|
||||
folder_path : The path of the folder to delete the file from.
|
||||
|
||||
Returns:
|
||||
success message mentioning the pull request name for the delete file operation. or error message.
|
||||
"""
|
||||
|
||||
try:
|
||||
github_access_token = self.get_tool_config("GITHUB_ACCESS_TOKEN")
|
||||
github_username = self.get_tool_config("GITHUB_USERNAME")
|
||||
github_helper = GithubHelper(github_access_token, github_username)
|
||||
head_branch = 'new-file'
|
||||
headers = {
|
||||
"Authorization": f"token {github_access_token}" if github_access_token else None,
|
||||
"Content-Type": "application/vnd.github+json"
|
||||
}
|
||||
if repository_owner != github_username:
|
||||
fork_response = github_helper.make_fork(repository_owner, repository_name, base_branch, headers)
|
||||
branch_response = github_helper.create_branch(repository_name, base_branch, head_branch, headers)
|
||||
logger.info("branch_response", branch_response)
|
||||
if branch_response == 201 or branch_response == 422:
|
||||
github_helper.sync_branch(github_username, repository_name, base_branch, head_branch, headers)
|
||||
|
||||
file_response = github_helper.delete_file(repository_name, file_name, folder_path, commit_message,
|
||||
head_branch, headers)
|
||||
pr_response = github_helper.create_pull_request(repository_owner, repository_name, head_branch, base_branch,
|
||||
headers)
|
||||
if (pr_response == 201 or pr_response == 422) and (file_response == 200):
|
||||
return f"Pull request to Delete {file_name} has been created"
|
||||
else:
|
||||
return "Error while deleting file"
|
||||
except Exception as err:
|
||||
return f"Error: Unable to delete file {file_name} in {repository_name} repository"
|
||||
@@ -0,0 +1,66 @@
|
||||
from typing import Type, Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from superagi.helper.github_helper import GithubHelper
|
||||
from superagi.llms.base_llm import BaseLlm
|
||||
from superagi.tools.base_tool import BaseTool
|
||||
|
||||
|
||||
class GithubFetchPullRequestSchema(BaseModel):
|
||||
repository_name: str = Field(
|
||||
...,
|
||||
description="Repository name in which file hase to be added",
|
||||
)
|
||||
repository_owner: str = Field(
|
||||
...,
|
||||
description="Owner of the github repository",
|
||||
)
|
||||
time_in_seconds: int = Field(
|
||||
...,
|
||||
description="Gets pull requests from last `time_in_seconds` seconds",
|
||||
)
|
||||
|
||||
|
||||
class GithubFetchPullRequest(BaseTool):
|
||||
"""
|
||||
Fetch pull request tool
|
||||
|
||||
Attributes:
|
||||
name : The name.
|
||||
description : The description.
|
||||
args_schema : The args schema.
|
||||
agent_id: The agent id.
|
||||
agent_execution_id: The agent execution id.
|
||||
"""
|
||||
llm: Optional[BaseLlm] = None
|
||||
name: str = "Github Fetch Pull Requests"
|
||||
args_schema: Type[BaseModel] = GithubFetchPullRequestSchema
|
||||
description: str = "Fetch pull requests from github"
|
||||
agent_id: int = None
|
||||
agent_execution_id: int = None
|
||||
|
||||
def _execute(self, repository_name: str, repository_owner: str, time_in_seconds: int = 86400) -> str:
|
||||
"""
|
||||
Execute the add file tool.
|
||||
|
||||
Args:
|
||||
repository_name: The name of the repository to add file to.
|
||||
repository_owner: Owner of the GitHub repository.
|
||||
time_in_seconds: Gets pull requests from last `time_in_seconds` seconds
|
||||
|
||||
Returns:
|
||||
List of all pull request ids
|
||||
"""
|
||||
try:
|
||||
github_access_token = self.get_tool_config("GITHUB_ACCESS_TOKEN")
|
||||
github_username = self.get_tool_config("GITHUB_USERNAME")
|
||||
github_helper = GithubHelper(github_access_token, github_username)
|
||||
|
||||
pull_request_urls = github_helper.get_pull_requests_created_in_last_x_seconds(repository_owner,
|
||||
repository_name,
|
||||
time_in_seconds)
|
||||
|
||||
return "Pull requests: " + str(pull_request_urls)
|
||||
except Exception as err:
|
||||
return f"Error: Unable to fetch pull requests {err}"
|
||||
@@ -0,0 +1,26 @@
|
||||
from abc import ABC
|
||||
from typing import List
|
||||
from superagi.tools.base_tool import BaseTool, BaseToolkit, ToolConfiguration
|
||||
from superagi.tools.github.add_file import GithubAddFileTool
|
||||
from superagi.tools.github.delete_file import GithubDeleteFileTool
|
||||
from superagi.tools.github.fetch_pull_request import GithubFetchPullRequest
|
||||
from superagi.tools.github.search_repo import GithubRepoSearchTool
|
||||
from superagi.tools.github.review_pull_request import GithubReviewPullRequest
|
||||
from superagi.types.key_type import ToolConfigKeyType
|
||||
|
||||
|
||||
class GitHubToolkit(BaseToolkit, ABC):
|
||||
name: str = "GitHub Toolkit"
|
||||
description: str = "GitHub Tool Kit contains all github related to tool"
|
||||
|
||||
def get_tools(self) -> List[BaseTool]:
|
||||
return [GithubAddFileTool(), GithubDeleteFileTool(), GithubRepoSearchTool(), GithubReviewPullRequest(),
|
||||
GithubFetchPullRequest()]
|
||||
|
||||
def get_env_keys(self) -> List[ToolConfiguration]:
|
||||
return [
|
||||
ToolConfiguration(key="GITHUB_ACCESS_TOKEN", key_type=ToolConfigKeyType.STRING, is_required= True, is_secret = True),
|
||||
ToolConfiguration(key="GITHUB_USERNAME", key_type=ToolConfigKeyType.STRING, is_required=True, is_secret=False)
|
||||
]
|
||||
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
Your purpose is to act as a highly experienced software engineer and provide a thorough review of the code chunks and suggest code snippets to improve key areas such as:
|
||||
- Logic
|
||||
- Modularity
|
||||
- Maintainability
|
||||
- Complexity
|
||||
|
||||
Do not comment on minor code style issues, missing comments/documentation. Identify and resolve significant concerns to improve overall code quality while deliberately disregarding minor issues
|
||||
|
||||
Following is the github pull request diff content:
|
||||
```
|
||||
{{DIFF_CONTENT}}
|
||||
```
|
||||
|
||||
Instructions:
|
||||
1. Do not comment on existing lines and deleted lines.
|
||||
2. Ignore the lines start with '-'.
|
||||
3. Only consider lines starting with '+' for review.
|
||||
4. Do not comment on frontend and graphql code.
|
||||
|
||||
Respond with only valid JSON conforming to the following schema:
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"comments": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"file_path": {
|
||||
"type": "string",
|
||||
"description": "The path to the file where the comment should be added."
|
||||
},
|
||||
"line": {
|
||||
"type": "integer",
|
||||
"description": "The line number where the comment should be added. "
|
||||
},
|
||||
"comment": {
|
||||
"type": "string",
|
||||
"description": "The content of the comment."
|
||||
}
|
||||
},
|
||||
"required": ["file_name", "line", "comment"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": ["comments"]
|
||||
}
|
||||
|
||||
Ensure response is valid JSON conforming to the following schema.
|
||||
@@ -0,0 +1,149 @@
|
||||
import ast
|
||||
from typing import Type, Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from superagi.helper.error_handler import ErrorHandler
|
||||
|
||||
from superagi.helper.github_helper import GithubHelper
|
||||
from superagi.helper.json_cleaner import JsonCleaner
|
||||
from superagi.helper.prompt_reader import PromptReader
|
||||
from superagi.helper.token_counter import TokenCounter
|
||||
from superagi.llms.base_llm import BaseLlm
|
||||
from superagi.models.agent import Agent
|
||||
from superagi.models.agent_execution import AgentExecution
|
||||
from superagi.models.agent_execution_feed import AgentExecutionFeed
|
||||
from superagi.tools.base_tool import BaseTool
|
||||
|
||||
|
||||
class GithubReviewPullRequestSchema(BaseModel):
|
||||
repository_name: str = Field(
|
||||
...,
|
||||
description="Repository name in which file hase to be added",
|
||||
)
|
||||
repository_owner: str = Field(
|
||||
...,
|
||||
description="Owner of the github repository",
|
||||
)
|
||||
pull_request_number: int = Field(
|
||||
...,
|
||||
description="Pull request number",
|
||||
)
|
||||
|
||||
|
||||
class GithubReviewPullRequest(BaseTool):
|
||||
"""
|
||||
Reviews the github pull request and adds comments inline
|
||||
|
||||
Attributes:
|
||||
name : The name.
|
||||
description : The description.
|
||||
args_schema : The args schema.
|
||||
"""
|
||||
llm: Optional[BaseLlm] = None
|
||||
name: str = "Github Review Pull Request"
|
||||
args_schema: Type[BaseModel] = GithubReviewPullRequestSchema
|
||||
description: str = "Add pull request for the github repository"
|
||||
agent_id: int = None
|
||||
agent_execution_id: int = None
|
||||
|
||||
def _execute(self, repository_name: str, repository_owner: str, pull_request_number: int) -> str:
|
||||
"""
|
||||
Execute the add file tool.
|
||||
|
||||
Args:
|
||||
repository_name: The name of the repository to add file to.
|
||||
repository_owner: Owner of the GitHub repository.
|
||||
pull_request_number: pull request number
|
||||
|
||||
Returns:
|
||||
Pull request success message if pull request is created successfully else error message.
|
||||
"""
|
||||
try:
|
||||
github_access_token = self.get_tool_config("GITHUB_ACCESS_TOKEN")
|
||||
github_username = self.get_tool_config("GITHUB_USERNAME")
|
||||
github_helper = GithubHelper(github_access_token, github_username)
|
||||
|
||||
pull_request_content = github_helper.get_pull_request_content(repository_owner, repository_name,
|
||||
pull_request_number)
|
||||
latest_commit_id = github_helper.get_latest_commit_id_of_pull_request(repository_owner, repository_name,
|
||||
pull_request_number)
|
||||
|
||||
pull_request_arr = pull_request_content.split("diff --git")
|
||||
organisation = Agent.find_org_by_agent_id(session=self.toolkit_config.session, agent_id=self.agent_id)
|
||||
|
||||
model_token_limit = TokenCounter(session=self.toolkit_config.session,
|
||||
organisation_id=organisation.id).token_limit(self.llm.get_model())
|
||||
pull_request_arr_parts = self.split_pull_request_content_into_multiple_parts(model_token_limit, pull_request_arr)
|
||||
for content in pull_request_arr_parts:
|
||||
self.run_code_review(github_helper, content, latest_commit_id, organisation, pull_request_number,
|
||||
repository_name, repository_owner)
|
||||
return "Added comments to the pull request:" + str(pull_request_number)
|
||||
except Exception as err:
|
||||
return f"Error: Unable to add comments to the pull request {err}"
|
||||
|
||||
def run_code_review(self, github_helper, content, latest_commit_id, organisation, pull_request_number,
|
||||
repository_name, repository_owner):
|
||||
prompt = PromptReader.read_tools_prompt(__file__, "code_review.txt")
|
||||
prompt = prompt.replace("{{DIFF_CONTENT}}", content)
|
||||
messages = [{"role": "system", "content": prompt}]
|
||||
total_tokens = TokenCounter.count_message_tokens(messages, self.llm.get_model())
|
||||
token_limit = TokenCounter(session=self.toolkit_config.session,
|
||||
organisation_id=organisation.id).token_limit(self.llm.get_model())
|
||||
result = self.llm.chat_completion(messages, max_tokens=(token_limit - total_tokens - 100))
|
||||
|
||||
if 'error' in result and result['message'] is not None:
|
||||
ErrorHandler.handle_openai_errors(self.toolkit_config.session, self.agent_id, self.agent_execution_id, result['message'])
|
||||
response = result["content"]
|
||||
if response.startswith("```") and response.endswith("```"):
|
||||
response = "```".join(response.split("```")[1:-1])
|
||||
response = JsonCleaner.extract_json_section(response)
|
||||
comments = ast.literal_eval(response)
|
||||
|
||||
# Add comments in the pull request
|
||||
for comment in comments['comments']:
|
||||
line_number = self.get_exact_line_number(content, comment["file_path"], comment["line"])
|
||||
github_helper.add_line_comment_to_pull_request(repository_owner, repository_name, pull_request_number,
|
||||
latest_commit_id, comment["file_path"], line_number,
|
||||
comment["comment"])
|
||||
|
||||
def split_pull_request_content_into_multiple_parts(self, model_token_limit: int, pull_request_arr):
|
||||
pull_request_arr_parts = []
|
||||
current_part = ""
|
||||
for part in pull_request_arr:
|
||||
total_tokens = TokenCounter.count_message_tokens([{"role": "user", "content": current_part}],
|
||||
self.llm.get_model())
|
||||
# we are using 60% of the model token limit
|
||||
if total_tokens >= model_token_limit * 0.6:
|
||||
# Add the current part to pull_request_arr_parts and reset current_sum and current_part
|
||||
pull_request_arr_parts.append(current_part)
|
||||
current_part = "diff --git" + part
|
||||
else:
|
||||
current_part += "diff --git" + part
|
||||
|
||||
pull_request_arr_parts.append(current_part)
|
||||
return pull_request_arr_parts
|
||||
|
||||
def get_exact_line_number(self, diff_content, file_path, line_number):
|
||||
last_content = diff_content[diff_content.index(file_path):]
|
||||
last_content = last_content[last_content.index('@@'):]
|
||||
return self.find_position_in_diff(last_content, line_number)
|
||||
|
||||
def find_position_in_diff(self, diff_content, target_line):
|
||||
# Split the diff by lines and initialize variables
|
||||
diff_lines = diff_content.split('\n')
|
||||
position = 0
|
||||
current_file_line_number = 0
|
||||
|
||||
# Loop through each line in the diff
|
||||
for line in diff_lines:
|
||||
position += 1 # Increment position for each line
|
||||
if line.startswith('@@'):
|
||||
# Reset the current file line number when encountering a new hunk
|
||||
current_file_line_number = int(line.split('+')[1].split(',')[0]) - 1
|
||||
elif not line.startswith('-'):
|
||||
# Increment the current file line number for lines that are not deletions
|
||||
current_file_line_number += 1
|
||||
if current_file_line_number >= target_line:
|
||||
# Return the position when the target line number is reached
|
||||
return position
|
||||
return position
|
||||
@@ -0,0 +1,62 @@
|
||||
from typing import Type
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from superagi.helper.github_helper import GithubHelper
|
||||
from superagi.tools.base_tool import BaseTool
|
||||
|
||||
|
||||
class GithubSearchRepoSchema(BaseModel):
|
||||
repository_name: str = Field(
|
||||
...,
|
||||
description="Repository name in which we have to search",
|
||||
)
|
||||
repository_owner: str = Field(
|
||||
...,
|
||||
description="Owner of the github repository",
|
||||
)
|
||||
file_name: str = Field(
|
||||
...,
|
||||
description="Name of the file we need to fetch from the repository",
|
||||
)
|
||||
folder_path: str = Field(
|
||||
...,
|
||||
description="folder path in which file is present",
|
||||
)
|
||||
|
||||
|
||||
class GithubRepoSearchTool(BaseTool):
|
||||
"""
|
||||
Search File tool
|
||||
|
||||
Attributes:
|
||||
name : The name.
|
||||
description : The description.
|
||||
args_schema : The args schema.
|
||||
"""
|
||||
name = "GithubRepo Search"
|
||||
description = (
|
||||
"Search for a file inside a Github repository"
|
||||
)
|
||||
args_schema: Type[GithubSearchRepoSchema] = GithubSearchRepoSchema
|
||||
|
||||
def _execute(self, repository_owner: str, repository_name: str, file_name: str, folder_path=None) -> str:
|
||||
"""
|
||||
Execute the search file tool.
|
||||
|
||||
Args:
|
||||
repository_owner : The owner of the repository to search file in.
|
||||
repository_name : The name of the repository to search file in.
|
||||
file_name : The name of the file to search.
|
||||
folder_path : The path of the folder to search the file in.
|
||||
|
||||
Returns:
|
||||
The content of the github file.
|
||||
"""
|
||||
github_access_token = self.get_tool_config("GITHUB_ACCESS_TOKEN")
|
||||
github_username = self.get_tool_config("GITHUB_USERNAME")
|
||||
github_repo_search = GithubHelper(github_access_token, github_username)
|
||||
try:
|
||||
content = github_repo_search.get_content_in_file(repository_owner, repository_name, file_name, folder_path)
|
||||
return content
|
||||
except:
|
||||
return "File not found"
|
||||
Reference in New Issue
Block a user