├── git_agent ├── __init__.py ├── tools │ ├── __init__.py │ ├── helper.py │ ├── add.py │ ├── restore.py │ └── diff.py └── main.py ├── setup.py ├── README.md ├── LICENSE └── .gitignore /git_agent/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /git_agent/tools/__init__.py: -------------------------------------------------------------------------------- 1 | from git_agent.tools.add import GitAddTool 2 | from git_agent.tools.diff import GitDiffTool 3 | from git_agent.tools.helper import git_status 4 | from git_agent.tools.restore import GitRestoreTool 5 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import find_packages, setup 2 | 3 | setup( 4 | name="git-agent", 5 | version="0.1", 6 | packages=find_packages(), 7 | install_requires=[ 8 | "langchain>=0.0.200", 9 | "openai", 10 | "colorama", 11 | ], 12 | entry_points={ 13 | "console_scripts": [ 14 | "git-agent = git_agent.main:main", 15 | ], 16 | }, 17 | ) 18 | -------------------------------------------------------------------------------- /git_agent/tools/helper.py: -------------------------------------------------------------------------------- 1 | import os 2 | import subprocess 3 | 4 | 5 | def git_status(): 6 | try: 7 | # Change 'your_directory_path' to your git repository path 8 | repo_path = os.getcwd() 9 | 10 | # the "cwd" parameter is used to set the current working directory 11 | result = subprocess.run( 12 | ["git", "status"], cwd=repo_path, capture_output=True, text=True 13 | ) 14 | 15 | # The "stdout" attribute contains the output 16 | return result.stdout 17 | 18 | except Exception as e: 19 | print(f"An error occurred: {e}") 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Git Agent 2 | `git-agent` is a Langchain-based Agent utilizing OpenAI Function calling that enables execution of Git commands using nothing but natural language inputs! 3 | 4 | Watch the video below to see it in action! 5 | 6 | https://github.com/jupyterjazz/git-agent/assets/45267439/c1c524bb-a42f-49b0-940a-7e5a4c722217 7 | 8 | 9 | ## Install 10 | 11 | 1. Install `git-agent` 12 | 13 | ```shell 14 | pip install git+https://github.com/jupyterjazz/git-agent.git 15 | ``` 16 | 17 | 2. Set your OPENAI_API_KEY 18 | 19 | ```shell 20 | export OPENAI_API_KEY= 21 | ``` 22 | 23 | ## Usage 24 | 25 | Move to any repository you have locally, and ask `git-agent` to show diffs, stage/restore files in natural language! 26 | 27 | ```shell 28 | git-agent 29 | ``` 30 | 31 | In this example, `git-agent` will locate files associated with `docarray` and provide the corresponding diffs only for those files. 32 | 33 | Screenshot 2023-06-14 at 13 34 44 34 | 35 | 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Saba Sturua 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /git_agent/main.py: -------------------------------------------------------------------------------- 1 | import json 2 | import sys 3 | 4 | from langchain.chat_models import ChatOpenAI 5 | from langchain.schema import HumanMessage 6 | from langchain.tools import format_tool_to_openai_function 7 | 8 | from git_agent.tools import GitAddTool, GitDiffTool, GitRestoreTool, git_status 9 | 10 | 11 | def execute(prompt, model): 12 | tools = [GitAddTool(), GitDiffTool(), GitRestoreTool()] 13 | functions = [format_tool_to_openai_function(t) for t in tools] 14 | context = git_status() 15 | message = model.predict_messages( 16 | [ 17 | HumanMessage( 18 | content=f'For your output, utilize the provided project status information below. ' 19 | f'This will aid in effectively carrying out the instructions ' 20 | f'requested subsequently: \n """ \n {context} \n """ \n Instruction: {prompt}' 21 | ) 22 | ], 23 | functions=functions, 24 | ) 25 | fn_name = message.additional_kwargs["function_call"]["name"] 26 | files = json.loads(message.additional_kwargs["function_call"]["arguments"]).get("files") 27 | for tool in tools: 28 | if fn_name == tool.name: 29 | tool._run(files) 30 | 31 | 32 | def main(): 33 | prompt = " ".join(sys.argv[1:]) 34 | model = ChatOpenAI(temperature=0, model_name="gpt-3.5-turbo-0613") 35 | execute(prompt, model) 36 | 37 | 38 | if __name__ == "__main__": 39 | main() 40 | -------------------------------------------------------------------------------- /git_agent/tools/add.py: -------------------------------------------------------------------------------- 1 | import os 2 | import subprocess 3 | from typing import List, Optional, Type 4 | 5 | from colorama import Fore, Style 6 | from langchain.callbacks.manager import (AsyncCallbackManagerForToolRun, 7 | CallbackManagerForToolRun) 8 | from langchain.tools.base import BaseTool 9 | from pydantic import BaseModel, Field 10 | 11 | 12 | class GitAddInput(BaseModel): 13 | """Input for GitAddTool.""" 14 | 15 | files: List[str] = Field( 16 | ..., 17 | description="Collection of file paths intended for staging through the 'git add' operation.", 18 | ) 19 | 20 | 21 | class GitAddTool(BaseTool): 22 | name: str = "git_add" 23 | args_schema: Type[BaseModel] = GitAddInput 24 | description: str = "Facilitates the staging of file modifications within your working directory, preparing them for the next git commit." 25 | 26 | def _run( 27 | self, 28 | files: List[str], 29 | run_manager: Optional[CallbackManagerForToolRun] = None, 30 | ) -> None: 31 | try: 32 | repo_path = os.getcwd() 33 | subprocess.run( 34 | ["git", "add", *files], cwd=repo_path, capture_output=True, text=True 35 | ) 36 | 37 | # The "stdout" attribute contains the output 38 | print("Staging:") 39 | for file in files: 40 | print(Fore.GREEN + file) 41 | 42 | except Exception as e: 43 | print(f"An error occurred: {e}") 44 | 45 | async def _arun( 46 | self, 47 | source_path: str, 48 | destination_path: str, 49 | run_manager: Optional[AsyncCallbackManagerForToolRun] = None, 50 | ) -> str: 51 | # TODO: Add aiofiles method 52 | raise NotImplementedError 53 | -------------------------------------------------------------------------------- /git_agent/tools/restore.py: -------------------------------------------------------------------------------- 1 | import os 2 | import subprocess 3 | from typing import List, Optional, Type 4 | 5 | from colorama import Fore, Style 6 | from langchain.callbacks.manager import (AsyncCallbackManagerForToolRun, 7 | CallbackManagerForToolRun) 8 | from langchain.tools.base import BaseTool 9 | from pydantic import BaseModel, Field 10 | 11 | 12 | class GitRestoreInput(BaseModel): 13 | """Input for GitRestoreTool.""" 14 | 15 | files: List[str] = Field( 16 | ..., 17 | description="Collection of file paths intended for restoration to their state in the last commit.", 18 | ) 19 | 20 | 21 | class GitRestoreTool(BaseTool): 22 | name: str = "git_restore" 23 | args_schema: Type[BaseModel] = GitRestoreInput 24 | description: str = ( 25 | "Restores the specified files to their state at the time of the last commit." 26 | ) 27 | 28 | def _run( 29 | self, 30 | files: List[str], 31 | run_manager: Optional[CallbackManagerForToolRun] = None, 32 | ) -> str: 33 | try: 34 | repo_path = os.getcwd() 35 | subprocess.run( 36 | ["git", "restore", *files], 37 | cwd=repo_path, 38 | capture_output=True, 39 | text=True, 40 | ) 41 | print("Restoring:") 42 | for file in files: 43 | print(Fore.GREEN + file) 44 | 45 | except Exception as e: 46 | print(f"An error occurred: {e}") 47 | 48 | async def _arun( 49 | self, 50 | source_path: str, 51 | destination_path: str, 52 | run_manager: Optional[AsyncCallbackManagerForToolRun] = None, 53 | ) -> str: 54 | # TODO: Add aiofiles method 55 | raise NotImplementedError 56 | -------------------------------------------------------------------------------- /git_agent/tools/diff.py: -------------------------------------------------------------------------------- 1 | import os 2 | import subprocess 3 | from typing import List, Optional, Type 4 | 5 | from colorama import Fore, Style 6 | from langchain.callbacks.manager import (AsyncCallbackManagerForToolRun, 7 | CallbackManagerForToolRun) 8 | from langchain.tools.base import BaseTool 9 | from pydantic import BaseModel, Field 10 | 11 | 12 | class GitDiffInput(BaseModel): 13 | """Input for GitDiffTool.""" 14 | 15 | files: Optional[List[str]] = Field( 16 | None, 17 | description="Optional collection of file paths to display differences. If not provided, differences for all tracked files will be shown.", 18 | ) 19 | 20 | 21 | class GitDiffTool(BaseTool): 22 | name: str = "git_diff" 23 | args_schema: Type[BaseModel] = GitDiffInput 24 | description: str = "Generates a summary of changes between the working directory and the last commit, or between specified files if provided." 25 | 26 | def _run( 27 | self, 28 | files: Optional[List[str]] = None, 29 | run_manager: Optional[CallbackManagerForToolRun] = None, 30 | ) -> None: 31 | try: 32 | repo_path = os.getcwd() 33 | if not files: 34 | files = [] 35 | result = subprocess.run( 36 | ["git", "diff", *files], cwd=repo_path, capture_output=True, text=True 37 | ) 38 | 39 | lines = result.stdout.split("\n") 40 | for line in lines: 41 | if line.startswith("diff --git"): 42 | print(Fore.CYAN + line) 43 | elif line.startswith("---") or line.startswith("+++"): 44 | print(Fore.MAGENTA + line) 45 | elif line.startswith("@@"): 46 | print(Fore.YELLOW + line) 47 | elif line.startswith("-"): 48 | print(Fore.RED + line) 49 | elif line.startswith("+"): 50 | print(Fore.GREEN + line) 51 | else: 52 | print(Style.RESET_ALL + line) 53 | 54 | except Exception as e: 55 | print(f"An error occurred: {e}") 56 | 57 | async def _arun( 58 | self, 59 | source_path: str, 60 | destination_path: str, 61 | run_manager: Optional[AsyncCallbackManagerForToolRun] = None, 62 | ) -> str: 63 | # TODO: Add aiofiles method 64 | raise NotImplementedError 65 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ 161 | --------------------------------------------------------------------------------