davidfearne commited on
Commit
564b273
·
verified ·
1 Parent(s): 7673f6b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +135 -91
app.py CHANGED
@@ -1,121 +1,165 @@
1
  import os
2
  import streamlit as st
3
  from datetime import datetime
 
4
  import requests
5
  import uuid
6
- from pydantic import BaseModel
 
 
 
7
 
8
- # Placeholder personas
9
  placeHolderPersona1 = """## Mission Statement
10
- My mission is to utilize my expertise to aid in the medical triaging process by providing a clear, concise, and accurate assessment of potential arthritis related conditions."""
 
 
 
 
 
 
 
 
11
 
12
  placeHolderPersona2 = """## Mission
13
- To analyse a clinical triaging discussion between a patient and AI doctor interactions with a focus on Immunology symptoms, medical history, and test results to deduce the most probable Immunology diagnosis."""
 
 
 
 
 
 
 
 
 
 
 
14
 
15
- # Mock API call function
16
  class ChatRequestClient(BaseModel):
 
17
  user_id: str
18
  user_input: str
19
  numberOfQuestions: int
20
- persona1SystemMessage: str
21
- persona2SystemMessage: str
22
  llm1: str
23
  tokens1: int
24
  temperature1: float
 
 
25
  userMessage2: str
26
  llm2: str
27
  tokens2: int
28
  temperature2: float
29
 
30
  def call_chat_api(data: ChatRequestClient):
31
- return {
32
- "content": f"Response to: {data.user_input}",
33
- "elapsed_time": 0.5,
34
- "count": 1,
35
- "response_tokens": len(data.user_input.split()) # Mock token count
36
- }
 
 
 
 
 
 
 
 
37
 
38
  def format_elapsed_time(time):
 
39
  return "{:.2f}".format(time)
40
 
41
- # Layout with three columns
42
- col1, col2, col3 = st.columns([1, 6, 1], gap="small") # Adjusted width ratios for better centering
43
-
44
- # Left Column: Variables and Settings
45
- with col1:
46
- st.sidebar.image('cognizant_logo.jpg')
47
- st.sidebar.header("RAG Query Designer")
48
- st.sidebar.subheader("Query Translation Prompt")
49
- numberOfQuestions = st.sidebar.slider("Number of Questions", 0, 10, 5, 1)
50
- persona1SystemMessage = st.sidebar.text_area("Define Query Translation Prompt", value=placeHolderPersona1, height=300)
51
- llm1 = st.sidebar.selectbox("Model Selection", ['GPT-4', 'GPT3.5'])
52
- temp1 = st.sidebar.slider("Temperature", 0.0, 1.0, 0.6, 0.1)
53
- tokens1 = st.sidebar.slider("Tokens", 0, 4000, 500, 100)
54
-
55
 
56
- # Middle Column: Chat Interface
57
- with col2:
58
- st.markdown("<div style='text-align: left;'><h1>Experiment With Queries</h1></div>", unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
- # User ID Input
61
- user_id = st.text_input("User ID:", key="user_id")
62
-
63
- if not user_id:
64
- st.warning("Please provide an experiment ID to start the chat.")
65
- else:
66
- # Initialize chat history
67
- if "messages" not in st.session_state:
68
- st.session_state.messages = []
69
-
70
- # Display chat history in a container
71
- with st.container():
72
- for message in st.session_state.messages:
73
- role = "User" if message["role"] == "user" else "Agent"
74
- with st.chat_message(message["role"]):
75
- st.markdown(message["content"])
76
-
77
- # Chat input at the bottom
78
- if user_input := st.chat_input("Start Chat:"):
79
- # Add user message
80
- st.session_state.messages.append({"role": "user", "content": user_input})
81
- st.chat_message("user").markdown(user_input)
82
-
83
- # Prepare data for API call
84
- data = ChatRequestClient(
85
- user_id=user_id,
86
- user_input=user_input,
87
- numberOfQuestions=numberOfQuestions,
88
- persona1SystemMessage=persona1SystemMessage,
89
- persona2SystemMessage=persona2SystemMessage,
90
- llm1=llm1,
91
- tokens1=tokens1,
92
- temperature1=0.0,
93
- userMessage2="",
94
- llm2="GPT-4",
95
- tokens2=500,
96
- temperature2=0.1,
97
- )
98
-
99
- # Call the API
100
- response = call_chat_api(data)
101
-
102
- # Process response
103
- agent_message = response["content"]
104
- elapsed_time = response["elapsed_time"]
105
- count = response["count"]
106
- response_tokens = response["response_tokens"]
107
-
108
- # Add agent response
109
- st.session_state.messages.append({"role": "assistant", "content": agent_message})
110
- st.chat_message("assistant").markdown(agent_message)
111
-
112
- # Right Column: Stats
113
- with col3:
114
- st.header("Stats")
115
- if "elapsed_time" in locals() and "count" in locals():
116
- st.markdown(f"**Time taken:** {format_elapsed_time(elapsed_time)} seconds")
117
- st.markdown(f"**Question Count:** {count} of {numberOfQuestions}")
118
- st.markdown(f"**Response Tokens:** {response_tokens}")
119
- else:
120
- st.markdown("No stats available yet.")
121
 
 
1
  import os
2
  import streamlit as st
3
  from datetime import datetime
4
+ import json
5
  import requests
6
  import uuid
7
+ from datetime import date, datetime
8
+ import requests
9
+ from pydantic import BaseModel, Field
10
+ from typing import Optional
11
 
 
12
  placeHolderPersona1 = """## Mission Statement
13
+ My mission is to utilize my expertise to aid in the medical triaging process by providing a clear, concise, and accurate assessment of potential arthritis related conditions.
14
+
15
+ # Triaging process
16
+ Ensure you stay on the topic of asking questions to triage the potential of Rheumatoid arthritis.
17
+ Ask only one question at a time.
18
+ Provide some context or clarification around the follow-up questions you ask.
19
+ Do not converse with the customer.
20
+ Be as concise as possible.
21
+ Do not give a diagnosis """
22
 
23
  placeHolderPersona2 = """## Mission
24
+ To analyse a clinical triaging discussion between a patient and AI doctor interactions with a focus on Immunology symptoms, medical history, and test results to deduce the most probable Immunology diagnosis.
25
+
26
+ ## Diagnostic Process
27
+ Upon receipt of the clinical notes, I will follow a systematic approach to arrive at a diagnosis:
28
+ 1. Review the patient's presenting symptoms and consider their relevance to immunopathology.
29
+ 2. Cross-reference the gathered information with my knowledge base of immunology to identify patterns or indicators of specific immune disorders.
30
+ 3. Formulate a diagnosis from the potential conditions.
31
+ 4. Determine the most likely diagnosis and assign a confidence score from 1-100, with 100 being absolute certainty.
32
+
33
+ # Limitations
34
+ While I am specialized in immunology, I understand that not all cases will fall neatly within my domain. In instances where the clinical notes point to a condition outside of my expertise, I will provide the best possible diagnosis with the acknowledgment that my confidence score will reflect the limitations of my specialization in those cases"""
35
+
36
 
 
37
  class ChatRequestClient(BaseModel):
38
+
39
  user_id: str
40
  user_input: str
41
  numberOfQuestions: int
42
+ welcomeMessage: str
 
43
  llm1: str
44
  tokens1: int
45
  temperature1: float
46
+ persona1SystemMessage: str
47
+ persona2SystemMessage: str
48
  userMessage2: str
49
  llm2: str
50
  tokens2: int
51
  temperature2: float
52
 
53
  def call_chat_api(data: ChatRequestClient):
54
+ url = "https://agent-builder-api.greensea-b20be511.northeurope.azurecontainerapps.io/chat/"
55
+ # Validate and convert the data to a dictionary
56
+ validated_data = data.dict()
57
+
58
+ # Make the POST request to the FastAPI server
59
+ response = requests.post(url, json=validated_data)
60
+
61
+ if response.status_code == 200:
62
+ return response.json() # Return the JSON response if successful
63
+ else:
64
+ return "An error occured" # Return the raw response text if not successful
65
+
66
+ def genuuid ():
67
+ return uuid.uuid4()
68
 
69
  def format_elapsed_time(time):
70
+ # Format the elapsed time to two decimal places
71
  return "{:.2f}".format(time)
72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
 
74
+ # Title of the application
75
+ # st.image('agentBuilderLogo.png')
76
+ st.title('LLM-Powered Agent Interaction')
77
+
78
+ # Sidebar for inputting personas
79
+ st.sidebar.image('cognizant_logo.jpg')
80
+ st.sidebar.header("Agent Personas Design")
81
+ # st.sidebar.subheader("Welcome Message")
82
+ # welcomeMessage = st.sidebar.text_area("Define Intake Persona", value=welcomeMessage, height=300)
83
+ st.sidebar.subheader("Intake AI")
84
+ numberOfQuestions = st.sidebar.slider("Number of Questions", min_value=0, max_value=10, step=1, value=5, key='persona1_questions')
85
+ persona1SystemMessage = st.sidebar.text_area("Define Intake Persona", value=placeHolderPersona1, height=300)
86
+ with st.sidebar.expander("See explanation"):
87
+ st.write("This AI persona will converse with the patient to gather their symptoms. 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 diagnosis. However this AI should never give a diagnosis")
88
+ st.image("agentPersona1.png")
89
+ llm1 = st.sidebar.selectbox("Model Selection", ['GPT-4', 'GPT3.5'], key='persona1_size')
90
+ temp1 = st.sidebar.slider("Temperature", min_value=0.0, max_value=1.0, step=0.1, value=0.6, key='persona1_temp')
91
+ tokens1 = st.sidebar.slider("Tokens", min_value=0, max_value=4000, step=100, value=500, key='persona1_tokens')
92
+
93
+ # Persona 2
94
+ st.sidebar.subheader("Recommendation and Next Best Action AI")
95
+ persona2SystemMessage = st.sidebar.text_area("Define Recommendation Persona", value=placeHolderPersona2, height=300)
96
+ with st.sidebar.expander("See explanation"):
97
+ st.write("This AI persona uses the output of the symptom intake AI as its input. This AI’s job is to augment a health professional by assisting with a diagnosis and possible next best action. The teams will need to determine if this should be a tool used directly by the patient, as an assistant to the health professional or a hybrid of the two. ")
98
+ st.image("agentPersona2.png")
99
+ llm2 = st.sidebar.selectbox("Model Selection", ['GPT-4', 'GPT3.5'], key='persona2_size')
100
+ temp2 = st.sidebar.slider("Temperature", min_value=0.0, max_value=1.0, step=0.1, value=0.5, key='persona2_temp')
101
+ tokens2 = st.sidebar.slider("Tokens", min_value=0, max_value=4000, step=100, value=500, key='persona2_tokens')
102
+ userMessage2 = st.sidebar.text_area("Define User Message", value="This is the conversation todate, ", height=150)
103
+ st.sidebar.caption(f"Session ID: {genuuid()}")
104
+
105
+
106
+ # Main chat interface
107
+ st.header("Chat with the Agents")
108
+
109
+ # User ID Input
110
+ user_id = st.text_input("User ID:", key="user_id")
111
+
112
+ # Ensure user_id is defined or fallback to a default value
113
+ if not user_id:
114
+ st.warning("Please provide a User ID to start the chat.")
115
+ else:
116
+ # Initialize chat history in session state
117
+ if "messages" not in st.session_state:
118
+ st.session_state.messages = []
119
+
120
+ # Display chat messages from history on app rerun
121
+ for message in st.session_state.messages:
122
+ with st.chat_message(message["role"]):
123
+ st.markdown(message["content"])
124
+
125
+ # Collect user input
126
+ if user_input := st.chat_input("Write your message here:"):
127
+ # Add user message to the chat history
128
+ st.session_state.messages.append({"role": "user", "content": user_input})
129
+ st.chat_message("user").markdown(user_input)
130
+
131
+ # Prepare data for API call
132
+ data = ChatRequestClient(
133
+ user_id=user_id, # Ensure user_id is passed correctly
134
+ user_input=user_input,
135
+ numberOfQuestions=numberOfQuestions,
136
+ welcomeMessage="",
137
+ llm1=llm1,
138
+ tokens1=tokens1,
139
+ temperature1=temp1,
140
+ persona1SystemMessage=persona1SystemMessage,
141
+ persona2SystemMessage=persona2SystemMessage,
142
+ userMessage2=userMessage2,
143
+ llm2=llm2,
144
+ tokens2=tokens2,
145
+ temperature2=temp2
146
+ )
147
+
148
+ # Call the API
149
+ response = call_chat_api(data)
150
+
151
+ # Process the API response
152
+ agent_message = response.get("content", "No response received from the agent.")
153
+ elapsed_time = response.get("elapsed_time", 0)
154
+ count = response.get("count", 0)
155
+
156
+ # Add agent response to the chat history
157
+ st.session_state.messages.append({"role": "assistant", "content": agent_message})
158
+ with st.chat_message("assistant"):
159
+ st.markdown(agent_message)
160
+
161
+ # Display additional metadata
162
+ st.markdown(f"##### Time taken: {format_elapsed_time(elapsed_time)} seconds")
163
+ st.markdown(f"##### Question Count: {count} of {numberOfQuestions}")
164
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165