rushankg's picture
Update app.py
d29bc99 verified
raw
history blame
3.23 kB
## (c) 2024
import streamlit as st
import requests
import json
import os
from openai import OpenAI
# Get the API key from the environment variable
API_KEY = os.getenv('PPX_KEY')
# Function to get dollar estimates for damaged objects
# Function to get dollar estimates for damaged objects
def get_damaged_object_estimates(damage_description):
# Check if API key is available
if not API_KEY:
st.error("API key not found. Make sure it's set in the environment variables.")
return None
# Messages to send
messages = [
{
"role": "system",
"content": (
"You are an artificial intelligence assistant to help hurricane-afflicted homeowners file for insurance."
),
},
{
"role": "user",
"content": (
f"Can you use this general list of damages to my home to prepare an organized, itemized list with dollar estimates that I can submit to my insurance company? \n\n {damage_description}"
),
},
]
# Prepare the request payload
payload = {
"model": "llama-3.1-sonar-small-128k-chat",
"messages": messages,
}
# Make a POST request to the Perplexity API
response = requests.post(
"https://api.perplexity.ai/chat/completions",
headers={
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
},
json=payload
)
# Check if the request was successful
if response.status_code != 200:
st.error(f"Error: {response.status_code} - {response.text}")
return None
# Process the response
return postprocess_message_text(response.json())
def postprocess_message_text(api_response):
"""
Extracts and formats the message content from the API response JSON.
Args:
api_response (dict): JSON response from the API.
Returns:
str: Formatted message content.
"""
st.error(api_response)
# Extract the content from the choices
message_content = api_response["choices"][0]["message"]["content"]
# Clean the message content (remove unnecessary escape characters)
formatted_content = message_content.replace("\\n", "\n")
# Fix dollar sign markdown
formatted_content = formatted_content.replace("$", "\\$")
return formatted_content
# Streamlit interface
st.title("Disaster Damage Cost Estimator")
# Input textbox for the user to enter the damage description
damage_description = st.text_area("Enter the damage description:")
# Button to trigger the API call
if st.button("Get Estimated Costs"):
if damage_description:
with st.spinner("Fetching cost estimates..."):
# Call the function to get estimates
estimated_costs = postprocess_message_text(get_damaged_object_estimates(damage_description))
if estimated_costs:
st.success("Here are the estimated costs:")
st.write(estimated_costs)
else:
st.error("Failed to retrieve estimates.")
else:
st.error("Please enter a damage description before making a request.")