Introduction
Keeping up with compliance and regulations is essential for any organization in today’s complicated business environment. Legal documents can be intimidating due to their sheer volume, complexity, and legal jargon. Contracts, laws, rules, and other legal documents that may have an impact on a business’s operations, risks, and prospects must all be understood and complied with by that business. However, reading and implementing these documents can be expensive, time-consuming, and prone to mistakes, particularly when there are several domains and jurisdictions involved.
For individuals new to the world of law and jurisdiction, the mere task of understanding the legalese is daunting. With every country having different types of rules and regulations that a business must comply with, it can be tough to know if your business is in line with your country’s laws and it becomes even more complex if it is a multinational business – making sure you are complying with different government laws to define a unified compliance system for your business is no easy task. You’ll have to hire legal experts from all over to reach a consensus. The process is not only time-consuming but also complicated.
To address this issue we present the Corporate Compliance and Regulation Advisor – your ultimate solution for navigating through legal requirements. This AI advisor leverages the capabilities of GPT and Streamlit for interpreting legal documents. With its ability to comprehend natural language, users can interact with the Advisor by presenting a document containing their existing policies and seeking validation on compliance.
Key Features of Corporate Compliance and Regulation Advisor:
- Legal Jargon
If you find yourself tired of going through complicated documents, the AI advisor is capable of understanding and breaking down complex legal language across various industries. It identifies critical compliance criteria and extracts necessary information to guide you. - Industry-Specific Recommendations
No cookie-cutter approach here! The AI Advisor tailors its guidance to your specific industry. With unique compliance regulations per sector, the AI will provide customized advice to help you stay on track. - Have an Engaging Q&A Experience
Have an interactive Q&A session where you can seek clarification on any compliance matters. Get clear and concise answers to your queries. - Real-time Updates
The advisor can stay updated on regulatory changes and provide real-time information to users. This assures that businesses are aware of the latest compliance requirements concerning their operations. - Get Compliance Checklists
The AI advisor can offer personalized compliance checklists specific to your industry and business activities. These practical guides are essential for organizations to meet all requirements.
In the subsequent sections of this tutorial, we will guide you through the step-by-step process of creating and deploying the Corporate Compliance and Regulation Advisor.
Prerequisites
Before you begin, ensure you have an Open AI API key. You’ll also need Python and Streamlit installed on your system.
Insight on the Technology
Our Corporate Compliance and Regulations Advisor comprises two key components:
Streamlit
Streamlit serves as the perfect tool for creating a user-friendly web application to communicate with the AI advisor. Through its streamlined process of transforming data scripts into shareable web apps, it is the ideal platform for developing interactive interfaces.
OpenAI’s GPT
With its capacity to comprehend and generate human-like text, it is the optimal choice for analyzing legal documents and offering context-specific guidance.
Let’s start building the Corporate Compliance and Regulation Advisor
Acquire an OpenAI API Key
Head over to the OpenAI API Keys page: https://help.openai.com/en/articles/4936850-where-do-i-find-my-api-key
If you don’t already have an API key Click on the “+ Create new secret key” button.
Setting Up the Environment
To ensure a smooth setup, follow these steps:
- Install Git:
Git lets you keep track of changes made to your code using a version control system. https://git-scm.com/book/en/v2/Getting-Started-Installing-Git
Clone the repository from GitHub: git clone https://github.com/aiproduct-creators/compliance-advisor-ai
- Install Python:
Python is used in the development of the Business Process Optimisation Bot. Install the most recent version of Python by downloading it from Python Downloads. You will need Python 3.8 or higher.
- Install Streamlit:
Streamlit is a Python package that makes it easy to create web apps. Utilising the following command, install Streamlit:
pip install streamlit |
- Set up OpenAI API Key:
Once you have the key, set it as an environment variable or configure it in your code.
export OPENAI_KEY=your_api_key |
Now that we have set our development environment, it’s time to start the real coding. Let’s start with the imports.
User Interface and Document Processing
import streamlit as st import os from os import getenv from PyPDF2 import PdfReader from dotenv import load_dotenv |
Sets up the user interface using Streamlit including necessary libraries for processing PDF documents.
Main Function and Configuration
def main(): load_dotenv() st.set_page_config(page_title=”Compliance Advisor AI”) st.header(“Compliance Advisor AI”) |
The `main()` function is the entry point. Loads the environment variables, sets up the Streamlit page, and displays a header for our Advisor AI.
Session State Initialization
if “conversation” not in st.session_state: st.session_state.conversation = None if “chat_history” not in st.session_state: st.session_state.chat_history = None if “processComplete” not in st.session_state: st.session_state.processComplete = None |
This part of the code initializes session state variables for the conversation, chat history, and process completion.
Document Upload and Processing
with st.sidebar: uploaded_files = st.file_uploader( “Upload your compliant document”, type=[“pdf”], accept_multiple_files=False, ) process = st.button(“Process”) if process: files_text = get_files_text(uploaded_files) text_chunks = get_text_chunks(files_text) vetorestore = get_vectorstore(text_chunks) st.session_state.conversation = get_conversation_chain( vetorestore, getenv(“OPENAI_KEY”) ) st.session_state.processComplete = True |
Constructs a sidebar for uploading PDF documents containing our current policies. Upon clicking “Process,” it extracts text, sets up a conversation chain, and then marks the process as complete.
User Interaction
if st.session_state.processComplete == True: user_question = st.chat_input(“type your message here…”) if user_question: handel_userinput(user_question) |
If the document processing is complete, users can then type questions in an input box. The application then handles user input and displays AI responses.
PDF Text Extraction
def get_files_text(uploaded_file): text = “” split_tup = os.path.splitext(uploaded_file.name) file_extension = split_tup[1] if file_extension == “.pdf”: text += get_pdf_text(uploaded_file) return text |
Function to extract text from the uploaded PDF files.
PDF Text Reading
def get_pdf_text(pdf): pdf_reader = PdfReader(pdf) text = “” for page in pdf_reader.pages: text += page.extract_text() return text |
Function to read text from the PDF pages.
Text Chunking
def get_text_chunks(text): text_splitter = CharacterTextSplitter( separator=”\n”, chunk_size=900, chunk_overlap=100, length_function=len ) chunks = text_splitter.split_text(text) return chunks |
Split text into manageable chunks.
Vector Store Creation
def get_vectorstore(text_chunks): embeddings = HuggingFaceEmbeddings() knowledge_base = FAISS.from_texts(text_chunks, embeddings) return knowledge_base |
Function to create a vector store from previous text chunks.
Conversation Chain Setup
def get_conversation_chain(vetorestore, openai_api_key): general_system_template = r””” You are an AI advisor to help businesses navigate compliance and regulations. You should interpret complex legal documents and offer guidance on compliance matters in various industries, ensuring regulatory adherence. —- {context} —- “”” general_user_template = “Question:“`{question}“`” messages = [ SystemMessagePromptTemplate.from_template(general_system_template), HumanMessagePromptTemplate.from_template(general_user_template), ] qa_prompt = ChatPromptTemplate.from_messages(messages) llm = ChatOpenAI( openai_api_key=openai_api_key, model_name=”gpt-4-0125-preview”, temperature=0, ) memory = ConversationBufferMemory(memory_key=”chat_history”, return_messages=True) conversation_chain = ConversationalRetrievalChain.from_llm( llm=llm, retriever=vetorestore.as_retriever(), memory=memory, combine_docs_chain_kwargs={“prompt”: qa_prompt}, ) return conversation_chain |
This function sets up a conversation chain using GPT for AI interaction.
User Input Handling and Display
def handel_userinput(user_question): with get_openai_callback() as cb: response = st.session_state.conversation({“question”: user_question}) st.session_state.chat_history = response[“chat_history”] response_container = st.container() with response_container: for i, messages in enumerate(st.session_state.chat_history): if i % 2 == 0: message(messages.content, is_user=True, key=str(i)) else: message(messages.content, key=str(i)) |
This function handles user input, sends it to GPT, and displays responses in a chat-like interface.
Run the Advisor
streamlit run app.py |
Open your browser and go to http://localhost:8501 to see the app.
Note: the port can be different, based on how you set it.
Now let’s put our Advisor to the test!
Real-World Application
It can be a real challenge to figure out if the solution your team worked hard on is compliant with industry-related laws and regulations. No matter how hard you try, as a human without involving a whole team of subject matter experts, it is unlikely to not miss out on a point or two.
In the scenario below we will first provide the Advisor with a personal document with information.
After uploading our document, we will ask the Compliance Advisor how can we make it HIPAA compliant.
As seen above, it advises that we need to ensure our document adheres to the standards set by the Health Insurance Probability and Accountability Act (HIPAA), particularly if the document contains Personal Health Information (PHI). It then provides us with steps and guidance on achieving HIPPA compliance; Understand PHI, Limit PHI Disclosure, and Use Secure Methods for Storing and Sharing.
Conclusion
The Corporate Compliance and Regulations Advisor is a powerful tool designed to help organizations navigate complex regulatory landscapes. By utilizing OpenAI’s GPT for contextual advice the application offers users insightful information on compliance issues in a variety of industries.
Feedback
The Corporate Compliance and Regulation Advisor can be modified to fit different industries, with a detailed walkthrough on how to build your AI Advisor feel free to modify it and utilize its AI capabilities according to your needs. Explore more and share your modifications and experiences with us!