├── .gitignore ├── LICENSE ├── README.md ├── add_document.py ├── chat.py ├── create_index.py ├── crypto_tracker.py ├── smartcontract_build.py └── utils.py /.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 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 deagentAI 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Agent3 2 | === 3 | 4 | A Framework for Distributed Decision Process for AI Agents. 5 | -------------------------------------------------------------------------------- /add_document.py: -------------------------------------------------------------------------------- 1 | from langchain.embeddings.huggingface import HuggingFaceEmbeddings 2 | from utils import load_documents, load_db, save_db, load_embeddings 3 | 4 | db = load_db(embedding_function=load_embeddings()) 5 | db.add_documents(load_documents("new_document/")) 6 | save_db(db) -------------------------------------------------------------------------------- /chat.py: -------------------------------------------------------------------------------- 1 | import os 2 | from dotenv import load_dotenv 3 | from langchain.chains import RetrievalQA 4 | from langchain.chat_models import ChatOpenAI 5 | from utils import load_embeddings, load_db 6 | from crypto_tracker import get_crypto_prices 7 | 8 | load_dotenv() 9 | 10 | class RetrievalChat: 11 | def __init__(self, api_key) -> None: 12 | # Set the OpenAI API key 13 | os.environ["OPENAI_API_KEY"] = api_key 14 | 15 | # Initialize bot components 16 | embedding_function = load_embeddings() 17 | db = load_db(embedding_function) 18 | self.qa = RetrievalQA.from_llm(llm=ChatOpenAI(temperature=0.1), retriever=db.as_retriever(kwargs={"k": 7}), return_source_documents=True) 19 | 20 | # Initialize conversation history 21 | self.conversation_history = "" 22 | 23 | def answer_question(self, question: str): 24 | # Update conversation history 25 | self.conversation_history += f"User: {question}\n" 26 | 27 | # Get bot's response 28 | output = self.qa({"query": self.conversation_history}) 29 | 30 | # Extract the bot's response from the output 31 | bot_response = output["result"].replace("Ella: ", "") # Remove the prefix 32 | 33 | # Update conversation history with the bot's response 34 | self.conversation_history += f"Ella: {bot_response}\n" 35 | 36 | return bot_response 37 | 38 | def welcome(self): 39 | print("Ella: Welcome! What are we exploring today?") 40 | 41 | if __name__ == "__main__": 42 | import constants 43 | api_key = constants.API_KEY 44 | # Initialize the bot with the API key 45 | qa = RetrievalChat(api_key) 46 | 47 | # Display the initial welcome message 48 | qa.welcome() 49 | 50 | while True: 51 | query = input("User: ") # Add "User" as an identifier 52 | if query.lower() == "exit": 53 | confirmation = input("Ella: Are you sure you want to exit the chat? (y/n): ") 54 | if confirmation.lower() == "y": 55 | break 56 | elif query.lower() == "reset": 57 | qa.conversation_history = "" 58 | print("Ella: Conversation reset.") 59 | elif query.lower() == "check crypto": 60 | # Call the cryptocurrency report logic 61 | crypto_report = get_crypto_prices() 62 | print(crypto_report) 63 | elif query.lower() == "new contract": 64 | # Prompt the user to select the contract type 65 | print("Available contract types:") 66 | print("1. Smart Contract") 67 | print("0. Quit") 68 | user_input = input("Ella: Please enter the corresponding number: ") 69 | 70 | if user_input == "1": 71 | # Launch the smart contract template 72 | os.system("python smartcontract_build.py") 73 | elif user_input == "0": 74 | # Return to the chat menu 75 | continue 76 | else: 77 | print("Ella: Invalid input. Please enter a valid number.") 78 | print() # Add a blank line for separation 79 | else: 80 | response = qa.answer_question(query) 81 | print(f"Ella: {response}") 82 | print() 83 | -------------------------------------------------------------------------------- /create_index.py: -------------------------------------------------------------------------------- 1 | from langchain.vectorstores import FAISS 2 | from utils import load_documents, save_db, load_embeddings 3 | 4 | embedding_function = load_embeddings() 5 | documents = load_documents("data/") 6 | 7 | db = FAISS.from_documents(documents, embedding_function) 8 | print("Index Created") 9 | save_db(db) 10 | 11 | print(db.similarity_search("ISO/IEC 27001 standard")) -------------------------------------------------------------------------------- /crypto_tracker.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from constants import CRYPTO_APIKEY 3 | 4 | API_KEY = CRYPTO_APIKEY 5 | BASE_URL = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest' 6 | 7 | portfolio_cryptos = ['BTC', 'ETH', 'DOT', 'AXS', 'MATIC', 'GALA', 'ALU', 'PBR', 'UFO', 'SHIB', 'ARB', 'DERC', 'FTM', 'LTC', 'PHA'] 8 | 9 | def get_crypto_data(symbol): 10 | headers = { 11 | 'Accepts': 'application/json', 12 | 'X-CMC_PRO_API_KEY': API_KEY 13 | } 14 | 15 | params = { 16 | 'symbol': symbol 17 | } 18 | 19 | try: 20 | response = requests.get(BASE_URL, headers=headers, params=params) 21 | data = response.json() 22 | return data['data'][symbol] 23 | except requests.exceptions.RequestException as e: 24 | print(f"Error retrieving data for {symbol}: {e}") 25 | return None 26 | 27 | def get_crypto_prices(): 28 | crypto_data = [] 29 | for crypto_symbol in portfolio_cryptos: 30 | crypto_info = get_crypto_data(crypto_symbol) 31 | if crypto_info: 32 | crypto_data.append(crypto_info) 33 | 34 | response = "" 35 | for crypto in crypto_data: 36 | name = crypto['name'] 37 | symbol = crypto['symbol'] 38 | current_price = crypto['quote']['USD']['price'] 39 | percent_change_1h = crypto['quote']['USD']['percent_change_1h'] 40 | percent_change_24h = crypto['quote']['USD']['percent_change_24h'] 41 | percent_change_7d = crypto['quote']['USD']['percent_change_7d'] 42 | market_cap = crypto['quote']['USD']['market_cap'] 43 | 44 | response += f"{name} ({symbol}):\n" 45 | response += f"Current Price: ${current_price:.2f}\n" 46 | response += f"Percent Change (1 hour): {percent_change_1h:.2f}%\n" 47 | response += f"Percent Change (24 hours): {percent_change_24h:.2f}%\n" 48 | response += f"Percent Change (7 days): {percent_change_7d:.2f}%\n" 49 | response += f"Market Cap: ${market_cap:.2f}\n\n" 50 | 51 | return response 52 | -------------------------------------------------------------------------------- /smartcontract_build.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | # Path to your Visual Studio Code executable 4 | VSCODE_PATH = "code" 5 | 6 | def launch_smart_contract_template(contract_type): 7 | # Define the directory where your smart contract templates are stored 8 | templates_directory = "smart_contracts" 9 | 10 | # Map contract types to their corresponding template filenames 11 | template_mapping = { 12 | "ERC20": "ERC20.sol", 13 | "ERC721": "ERC721.sol", 14 | "ERC1155": "ERC1155.sol" 15 | } 16 | 17 | if contract_type in template_mapping: 18 | template_filename = template_mapping[contract_type] 19 | template_path = os.path.join(templates_directory, template_filename) 20 | 21 | # Launch Visual Studio Code with the smart contract template 22 | os.system(f"{VSCODE_PATH} {template_path}") 23 | return "Smart contract template launched in Visual Studio Code. You can start editing now!" 24 | else: 25 | return "Invalid contract type. Please choose a valid contract type." 26 | 27 | # Prompt the user to select the contract type 28 | def prompt_contract_type(): 29 | while True: 30 | print("Available contract types:") 31 | print("1. ERC20") 32 | print("2. ERC721") 33 | print("3. ERC1155") 34 | print("0. Quit") 35 | 36 | user_input = input("Ella: Please enter the corresponding number: ") 37 | 38 | if user_input == "0": 39 | return None # Return None to indicate going back to the previous menu 40 | 41 | if user_input.isdigit(): 42 | index = int(user_input) - 1 43 | contract_types = ["ERC20", "ERC721", "ERC1155"] 44 | 45 | if 0 <= index < len(contract_types): 46 | return contract_types[index] 47 | else: 48 | print("Invalid input. Please enter a valid number.") 49 | else: 50 | print("Invalid input. Please enter a valid number.") 51 | 52 | # Main entry point of the script 53 | def main(): 54 | while True: 55 | contract_type = prompt_contract_type() 56 | 57 | if contract_type is None: 58 | # User selected to go back to the previous menu 59 | break # Exit the loop and return to the previous menu 60 | 61 | response = launch_smart_contract_template(contract_type) 62 | print(response) 63 | 64 | if __name__ == "__main__": 65 | main() 66 | 67 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | from langchain.text_splitter import RecursiveCharacterTextSplitter 2 | from langchain.embeddings.huggingface import HuggingFaceEmbeddings 3 | from langchain.document_loaders import PyPDFLoader 4 | from langchain.vectorstores import FAISS 5 | from glob import glob 6 | from tqdm import tqdm 7 | import yaml 8 | 9 | def load_config(): 10 | with open('config.yaml', 'r') as file: 11 | config = yaml.safe_load(file) 12 | return config 13 | 14 | config = load_config() 15 | 16 | def load_embeddings(model_name=config["embeddings"]["name"], 17 | model_kwargs = {'device': config["embeddings"]["device"]}): 18 | return HuggingFaceEmbeddings(model_name=model_name, model_kwargs = model_kwargs) 19 | 20 | def load_documents(directory : str): 21 | """Loads all documents from a directory and returns a list of Document objects 22 | args: directory format = directory/ 23 | """ 24 | text_splitter = RecursiveCharacterTextSplitter(chunk_size = config["TextSplitter"]["chunk_size"], 25 | chunk_overlap = config["TextSplitter"]["chunk_overlap"]) 26 | documents = [] 27 | for item_path in tqdm(glob(directory + "*.pdf")): 28 | loader = PyPDFLoader(item_path) 29 | documents.extend(loader.load_and_split(text_splitter=text_splitter)) 30 | 31 | return documents 32 | 33 | def load_db(embedding_function, save_path=config["faiss_indexstore"]["save_path"], index_name=config["faiss_indexstore"]["index_name"]): 34 | db = FAISS.load_local(folder_path=save_path, index_name=index_name, embeddings = embedding_function) 35 | return db 36 | 37 | def save_db(db, save_path=config["faiss_indexstore"]["save_path"], index_name=config["faiss_indexstore"]["index_name"]): 38 | db.save_local(save_path, index_name) 39 | print("Saved db to " + save_path + index_name) --------------------------------------------------------------------------------