YoniFriedman commited on
Commit
57da107
·
verified ·
1 Parent(s): ca8a587

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +159 -0
app.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ os.environ["OPENAI_API_KEY"]
3
+
4
+ from llama_index.llms.openai import OpenAI
5
+ from llama_index.core.schema import MetadataMode
6
+ import openai
7
+ from openai import OpenAI as OpenAIOG
8
+ import logging
9
+ import sys
10
+ llm = OpenAI(temperature=0.0, model="gpt-3.5-turbo")
11
+ client = OpenAIOG()
12
+
13
+ from deep_translator import GoogleTranslator
14
+
15
+ # Load index
16
+ from llama_index.core import VectorStoreIndex
17
+ from llama_index.core import StorageContext
18
+ from llama_index.core import load_index_from_storage
19
+ storage_context = StorageContext.from_defaults(persist_dir="parse_metadata")
20
+ index = load_index_from_storage(storage_context)
21
+ query_engine = index.as_query_engine(similarity_top_k=3, llm=llm)
22
+ retriever = index.as_retriever(similarity_top_k = 3)
23
+
24
+ import gradio as gr
25
+ import re
26
+ import json
27
+ from datetime import datetime
28
+
29
+ acknowledgment_keywords = ["thanks", "thank you", "thx", "ok", "okay", "great", "got it",
30
+ "appreciate", "good", "makes sense"]
31
+ follow_up_keywords = ["but", "also", "and", "what", "how", "why", "when", "is", "?"]
32
+ greeting_keywords = ["hi", "hello", "hey", "how's it", "what's up", "yo", "howdy"]
33
+
34
+ def contains_exact_word_or_phrase(text, keywords):
35
+ text = text.lower()
36
+ for keyword in keywords:
37
+ if re.search(r'\b' + re.escape(keyword) + r'\b', text):
38
+ return True
39
+ return False
40
+
41
+ def contains_greeting(question):
42
+ # Check if the question contains acknowledgment keywords
43
+ return contains_exact_word_or_phrase(question, greeting_keywords)
44
+
45
+ def contains_acknowledgment(question):
46
+ # Check if the question contains acknowledgment keywords
47
+ return contains_exact_word_or_phrase(question, acknowledgment_keywords)
48
+
49
+ def contains_follow_up(question):
50
+ # Check if the question contains follow-up indicators
51
+ return contains_exact_word_or_phrase(question, follow_up_keywords)
52
+
53
+ def convert_to_date(date_str):
54
+ return datetime.strptime(date_str, "%Y%m%d")
55
+
56
+ def idahun(question: str, conversation_history: list[str]):
57
+
58
+ # Get conversation history
59
+ context = " ".join([item["user"] + " " + item["chatbot"] for item in conversation_history])
60
+
61
+ source0 = "RAG not run"
62
+ source1 = "RAG not run"
63
+ source2 = "RAG not run"
64
+
65
+ ## Process greeting
66
+ # greet_response = process_greeting_response(question)
67
+ if contains_greeting(question) and not contains_follow_up(question):
68
+ greeting = (
69
+ f" The user previously asked and answered the following: {context}. "
70
+ f" The user just provided the following greeting: {question}. "
71
+ "Please respond accordingly."
72
+ )
73
+ completion = client.chat.completions.create(
74
+ model="gpt-4o",
75
+ messages=[
76
+ {"role": "user", "content": greeting}
77
+ ]
78
+ )
79
+ reply_to_user = completion.choices[0].message.content
80
+ conversation_history.append({"user": question, "chatbot": reply_to_user})
81
+ return reply_to_user, source0, source1, source2, conversation_history
82
+
83
+ ## Process acknowledgment
84
+ if contains_acknowledgment(question) and not contains_follow_up(question):
85
+ acknowledgment = (
86
+ f" The user previously asked and answered the following: {context}. "
87
+ f" The user just provided the following acknowledgement: {question}. "
88
+ "Please respond accordingly in English."
89
+ )
90
+ completion = client.chat.completions.create(
91
+ model="gpt-4o",
92
+ messages=[
93
+ {"role": "user", "content": acknowledgment}
94
+ ]
95
+ )
96
+ reply_to_user = completion.choices[0].message.content
97
+ conversation_history.append({"user": question, "chatbot": reply_to_user})
98
+ return reply_to_user, source0, source1, source2, conversation_history
99
+
100
+ ## If not greeting or acknowledgement, then proceed with RAG
101
+
102
+ # Retrieve sources
103
+ sources = retriever.retrieve(question)
104
+ source0 = sources[0].text
105
+ source1 = sources[1].text
106
+ source2 = sources[2].text
107
+
108
+
109
+ background = ("The person who asked the question is a person living with HIV."
110
+ " They are asking questions about HIV. Do not talk about anything that is not related to HIV. "
111
+ " Recognize that they already have HIV and do not suggest that they have to get tested"
112
+ " for HIV or take post-exposure prophylaxis, as that is not relevant, though their partners perhaps should."
113
+ " Do not suggest anything that is not relevant to someone who already has HIV."
114
+ " Do not mention in the response that the person is living with HIV.")
115
+
116
+ # Combine into final prompt - user background, conversation history, new question, retrieved sources
117
+ question_final = (
118
+ f" The user previously asked and answered the following: {context}. "
119
+ f" The user just asked the following question: {question}."
120
+ f" Please use the following content to generate a response: {source0} {source1} {source2}."
121
+ f" Please consider the following background information when generating a response: {background}."
122
+ " Keep answers brief and limited to the question that was asked."
123
+ " If they share a greeting, just greet them in return and ask if they have a question."
124
+ " Do not change the subject or address anything the user didn't directly ask about."
125
+ " If they respond with an acknowledgement, simply thank them."
126
+ " Do not discuss anything other than HIV. If they ask a question that is not about HIV, respond that"
127
+ " you are only able to discuss HIV."
128
+ " Keep the response to under 50 words and use simple language. The person asking the question does not know technical terms."
129
+ )
130
+
131
+ # Generate response
132
+ completion = client.chat.completions.create(
133
+ model="gpt-4o",
134
+ messages=[
135
+ {"role": "user", "content": question_final}
136
+ ]
137
+ )
138
+ # Collect response
139
+ reply_to_user = completion.choices[0].message.content
140
+
141
+ # add question and reply to conversation history
142
+ conversation_history.append({"user": question, "chatbot": reply_to_user})
143
+
144
+ return reply_to_user, source0, source1, source2, conversation_history
145
+
146
+ demo = gr.Interface(
147
+ title = "Idahun Chatbot Demo (English)",
148
+ fn=idahun,
149
+ inputs=["text", gr.State(value=[])],
150
+ outputs = [
151
+ gr.Textbox(label="Chatbot Response", type="text"),
152
+ gr.Textbox(label="Source 1", max_lines = 10, autoscroll = False, type="text"),
153
+ gr.Textbox(label="Source 2", max_lines = 10, autoscroll = False, type="text"),
154
+ gr.Textbox(label="Source 3", max_lines = 10, autoscroll = False, type="text"),
155
+ gr.State()
156
+ ],
157
+ )
158
+
159
+ demo.launch()