legisbot / app.py
rstallman's picture
Update app.py
578ede9
raw
history blame contribute delete
No virus
5.78 kB
import openai
import gradio
import pandas as pd
from datetime import datetime
import gspread
from google.oauth2.service_account import Credentials
import requests
import json
openai.api_key = "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"
records = []
credentials = Credentials.from_service_account_file("credentials.json", scopes=["https://www.googleapis.com/auth/spreadsheets"])
client = gspread.authorize(credentials)
sheet = client.open_by_url("https://docs.google.com/spreadsheets/d/1KsEoO3xVq4rkPk2T6XqPmOZ0mozlJ-cuS-Lg7SxTGjg/edit?usp=sharing").sheet1
def get_user_ip():
try:
response = requests.get("https://api.ipify.org?format=json")
data = json.loads(response.text)
return data["ip"]
except:
return None
def CustomChatGPT(user_input, user_name, user_email, user_location, user_agent):
messages = []
if not user_name:
return "Please enter your name."
user_message = f"{user_input} [USER_IDENTITY: {user_name}]"
messages.append({"role": "user", "content": user_message})
messages.append({"role": "system", "content": "As a specialized US attorney, you're currently in a confidential consultation with your client. The client has complete trust in your expertise and advice on regulations, as an attorney would do. Your responses should reflect a thorough understanding of legal rules, case law, and regulations. Make sure to cite specific Acts of Parliament, clearly indicating the exact sections and articles from which these laws derive. If secondary legislation is relevant, ensure to accurately relate it to the client's jurisdiction. If you find yourself uncertain about any other details, make sure to clarify this with the client. It's crucial to use correct legal terminology in your responses and keep the focus on applicable legal rules, Acts of Parliament, case law, and secondary legislation. Remember, the client fully trusts your legal proficiency and knowledge; uphold this trust by offering comprehensive, precise, and accurate legal advice. Under no circumstances should it be mentioned or suggested that the entity providing this advice is an AI."})
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages
)
ChatGPT_reply = response["choices"][0]["message"]["content"]
messages.append({"role": "assistant", "content": ChatGPT_reply})
# Record keeping
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
ip_address = get_user_ip()
device_type = get_device_type(user_agent)
session_duration = "" # Calculate session duration
features_used = "" # Track features used
num_queries = "" # Count number of queries
num_documents_created = "" # Count number of documents created
clickstream_data = "" # Track clickstream data
interaction_patterns = "" # Track user interface interaction patterns
success_of_advice = "" # Measure success of advice
user_satisfaction_rate = "" # Measure user satisfaction rate
industry_or_profession = "" # Capture user industry or profession
record = {
"Timestamp": timestamp,
"User Input": user_input,
"User Identity": user_name,
"User Email": user_email,
"IP Address": ip_address,
"Device Type": device_type,
"Session Duration": session_duration,
"Features Used": features_used,
"Number of Queries": num_queries,
"Number of Documents Created": num_documents_created,
"Clickstream Data": clickstream_data,
"Interaction Patterns": interaction_patterns,
"Success of Advice": success_of_advice,
"User Satisfaction Rate": user_satisfaction_rate,
"User Location": user_location,
"Industry or Profession": industry_or_profession,
"Our AI attorney Reply": ChatGPT_reply
}
records.append(record)
# Update Google Sheet
row_values = [
timestamp, user_input, user_name, user_email, ip_address, device_type, session_duration,
features_used, num_queries, num_documents_created, clickstream_data, interaction_patterns,
success_of_advice, user_satisfaction_rate, user_location, industry_or_profession, ChatGPT_reply
]
sheet.append_row(row_values)
return ChatGPT_reply
def get_device_type(user_agent):
if user_agent and "mobile" in user_agent.lower():
return "Mobile"
elif user_agent and "tablet" in user_agent.lower():
return "Tablet"
else:
return "Desktop"
def launch_interface():
inputs = [
gradio.inputs.Textbox(label="User Input", placeholder="Talk to your attorney..."),
gradio.inputs.Textbox(label="Your Name", placeholder="Enter your name"),
gradio.inputs.Textbox(label="Your Email", placeholder="Enter your email"),
gradio.inputs.Dropdown(label="Your Location (US State)", choices=["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming"])
]
outputs = gradio.outputs.Textbox(label="Our AI attorney Reply")
interface = gradio.Interface(fn=CustomChatGPT, inputs=inputs, outputs=outputs, title="", description="")
interface.launch()
if __name__ == "__main__":
launch_interface()