davidfearne's picture
Update app.py
3062d69 verified
import os
import streamlit as st
from datetime import datetime
import json
import requests
import uuid
from datetime import date, datetime
import requests
from pydantic import BaseModel, Field
from typing import Optional
placeHolderPersona1 = """ ## Objective - You are a Car Selection Assistant AI designed to help the user find the perfect car based on their needs, preferences, and lifestyle. Your role is to guide the user through a conversational journey by asking thoughtful, relevant questions. Your ultimate goal is to build a complete understanding of the user’s requirements and preferences to recommend the ideal car.
## Guidelines:
** Conversation Focus: Only ask questions that are directly relevant to car selection and build upon the user's responses. Do not offer recommendations until explicitly requested.
** Personalization: Tailor your questions to the user’s answers to better understand their priorities, such as budget, lifestyle, driving habits, and aesthetic preferences.
** Prioritize Clarity: Ask clear and concise questions, avoiding jargon unless the user demonstrates expertise in cars.
** Avoid Bias: Do not push a specific car brand or model unless the user provides clear preferences or constraints.
** Progressive Inquiry: Start with broad questions and narrow down to specifics based on the user's responses (e.g., from "What will you primarily use the car for?" to "Do you need all-wheel drive for winter conditions?").
** Budget Sensitivity: Gently uncover budget constraints without making the user feel pressured or uncomfortable.
## End Goal: Use the conversation to identify the perfect car, ensuring the recommendation aligns with the user’s stated needs and preferences.
## Examples of Topics to Explore:
** Purpose: Commuting, family use, off-road adventures, etc.
** Preferences: Brand loyalty, new vs. used, color, design, etc.
** Budget: Purchase price, financing, long-term costs (fuel efficiency, maintenance).
** Features: Technology, safety, comfort, storage, performance.
** Lifestyle: Family size, hobbies, travel habits, local weather.
## Expected Output:
At the end of the conversation, synthesize the user's responses into a clear and concise profile of their ideal car and provide a personalized recommendation only when explicitly asked. """
placeHolderPersona2 = """## objective - You are a Car Selection Justifier AI tasked with selecting the best car for the user from a provided list based on a detailed conversation profile. Your role is to analyze the conversation data, match the user’s preferences and requirements to the cars in the list, and justify your selection with clear reasoning.
## Guidelines:
** Input Understanding: Carefully analyze the conversation summary or profile provided. Identify key factors such as purpose, preferences, budget, required features, and lifestyle needs.
** Car Matching: Review the list of cars and evaluate each option against the user’s stated requirements. Eliminate unsuitable options and focus on the best matches.
## Weighted Justification:
Justify your selection by explicitly linking the car’s features, specifications, and qualities to the user’s needs.
Highlight why the chosen car is better suited than other options in the list.
If multiple cars are equally suitable, present them as alternatives and explain the pros and cons of each.
Clarity and Relevance: Keep your reasoning concise, easy to understand, and directly tied to the user's preferences. Avoid technical jargon unless necessary for the explanation.
## Recommendation Format:
** Selected Car: State the recommended car(s) from the list.
** Justification: Provide a detailed explanation of how the car(s) align with the user’s profile.
** Alternative Options (if any): Suggest additional options and why they could also work, if appropriate.
## Expected Output:
A structured recommendation including:
** Selected Car(s): Name the car(s) from the list.
** Justification: Describe how the car meets the user’s stated needs and preferences, citing specific features or attributes.
** Alternative(s) (Optional): Mention any close alternatives with a brief comparison."""
placeHolderUser2 = """This is the conversation to date,
"""
class ChatRequestClient(BaseModel):
user_id: str
user_input: str
numberOfQuestions: int
welcomeMessage: str
llm1: str
tokens1: int
temperature1: float
persona1SystemMessage: str
persona2SystemMessage: str
userMessage2: str
llm2: str
tokens2: int
temperature2: float
def call_chat_api(data: ChatRequestClient):
url = "https://agent-builder-api.greensea-b20be511.northeurope.azurecontainerapps.io/chat/"
# Validate and convert the data to a dictionary
validated_data = data.dict()
# Make the POST request to the FastAPI server
response = requests.post(url, json=validated_data)
if response.status_code == 200:
return response.json() # Return the JSON response if successful
else:
return "An error occured" # Return the raw response text if not successful
def genuuid ():
return uuid.uuid4()
def format_elapsed_time(time):
# Format the elapsed time to two decimal places
return "{:.2f}".format(time)
# Title of the application
# st.image('agentBuilderLogo.png')
st.title('LLM-Powered Agent Interaction')
# Sidebar for inputting personas
st.sidebar.image('agentBuilderLogo.png')
st.sidebar.header("Agent Personas Design")
# st.sidebar.subheader("Welcome Message")
# welcomeMessage = st.sidebar.text_area("Define Triaging Persona", value=welcomeMessage, height=300)
st.sidebar.subheader("AI Sales Person")
numberOfQuestions = st.sidebar.slider("Number of Questions", min_value=0, max_value=10, step=1, value=5, key='persona1_questions')
persona1SystemMessage = st.sidebar.text_area("AI Sales Persona", value=placeHolderPersona1, height=300)
with st.sidebar.expander("See explanation"):
st.write("This AI persona will converse with the customer to gather their requirements. With each round of chat, the object of the AI is to ask more specific follow up questions as it narrows down to the specific requirements. However this AI should never give a selection")
st.image("agentPersona1.png")
llm1 = st.sidebar.selectbox("Model Selection", ['GPT3.5','GPT-4'], key='persona1_size')
temp1 = st.sidebar.slider("Tempreature", min_value=0.0, max_value=1.0, step=0.1, value=0.5, key='persona1_temp')
tokens1 = st.sidebar.slider("Tokens", min_value=0, max_value=4000, step=100, value=500, key='persona1_tokens')
# Persona 2
st.sidebar.subheader("Car Selection AI")
persona2SystemMessage = st.sidebar.text_area("Define Diagnosis Persona", value=placeHolderPersona2, height=300)
with st.sidebar.expander("See explanation"):
st.write("This AI persona uses the output of the sales AI as its input. This AI’s job is to augment a sales professional by assisting with a car selection and justification.")
st.image("agentPersona2.png")
llm2 = st.sidebar.selectbox("Model Selection", ['GPT-4', 'GPT3.5'], key='persona2_size')
temp2 = st.sidebar.slider("Tempreature", min_value=0.0, max_value=1.0, step=0.1, value=0.3, key='persona2_temp')
tokens2 = st.sidebar.slider("Tokens", min_value=0, max_value=4000, step=100, value=2000, key='persona2_tokens')
userMessage2 = st.sidebar.text_area("Define User Message", value=placeHolderUser2, height=150)
st.sidebar.caption(f"Session ID: {genuuid()}")
# Main chat interface
st.header("Chat with the Agents")
user_id = st.text_input("User ID:", key="user_id")
user_input = st.text_input("Write your message here:", key="user_input")
if 'history' not in st.session_state:
st.session_state.history = []
if st.button("Send"):
# Placeholder for processing the input and generating a response
data = ChatRequestClient(
user_id=user_id,
user_input=user_input,
numberOfQuestions=numberOfQuestions,
welcomeMessage="",
llm1=llm1,
tokens1=tokens1,
temperature1=temp1,
persona1SystemMessage=persona1SystemMessage,
persona2SystemMessage=persona2SystemMessage,
userMessage2=userMessage2,
llm2=llm2,
tokens2=tokens2,
temperature2=temp2
)
response = call_chat_api(data)
st.markdown(f"##### Time take: {format_elapsed_time(response['elapsed_time'])}")
st.markdown(f"##### Question Count : {response['count']} of {numberOfQuestions}")
# {"count":count, "user_id":user_id,"time_stamp":time_stamp, "elapsed_time":elapsed_time, "content":content}
st.session_state.history.append("You: " + user_input)
st.session_state.history.append("Agent: " + response['content']) # Using 'response' after it's defined
for message in st.session_state.history:
st.write(message)