jesshewyz commited on
Commit
739f5c1
·
verified ·
1 Parent(s): edb356f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +221 -63
app.py CHANGED
@@ -1,64 +1,222 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
-
62
-
63
- if __name__ == "__main__":
64
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ from gradio import ChatMessage
3
+ import time
4
+ import asyncio
5
+ from functools import partial
6
+ import random
7
+ import logging
8
+
9
+ logging.basicConfig(level=logging.INFO)
10
+
11
+ sleep_time = random.randint(1, 3)
12
+
13
+ thoughts = {
14
+ "questioning_agent": [
15
+ "Read the project document and function list.",
16
+ "Determine if the project needs a chatbot, document extraction, or both.",
17
+ "Map the requirements to the provided functions only.",
18
+ "Classify the project as Chatbot, Document Extraction, or Hybrid.",
19
+ "Output a JSON object with the configuration type and selected functions."
20
+ ],
21
+ "client_initial_question": [
22
+ "Identify key topics like company background, industry, challenges, and workflows.",
23
+ "List the specific client questions provided.",
24
+ "Ensure each question aims to gather clear, measurable information.",
25
+ "Format the questions with sample answers as specified.",
26
+ "Return only the list of questions without extra commentary."
27
+ ],
28
+ "generate_client_follow_up": [
29
+ "Review the initial client responses.",
30
+ "Pinpoint areas needing further clarification, such as project vision and current processes.",
31
+ "Develop follow-up questions to explore these areas in more detail.",
32
+ "Incorporate sample answers to guide the client.",
33
+ "Compile a numbered list of the top follow-up questions."
34
+ ],
35
+ "generate_engage_questions": [
36
+ "Examine the client background and chatbot requirements.",
37
+ "Focus on areas like business outcomes, conversational flow, and technical needs.",
38
+ "Formulate context-aware questions to extract detailed insights.",
39
+ "Include sample answers for clarity.",
40
+ "Present a concise list of targeted questions."
41
+ ],
42
+ "generate_page_questions": [
43
+ "Review the client information related to document processing.",
44
+ "Focus on document types, input/output formats, quality, and workflow mapping.",
45
+ "Develop clear and relevant questions for each area.",
46
+ "Provide sample answers to guide responses.",
47
+ "Return a formatted list of document-focused questions."
48
+ ],
49
+ "generate_hybrid_questions": [
50
+ "Recognize that the project involves both chatbot and document processing needs.",
51
+ "Separate the questions into two groups: one for documents and one for chatbots.",
52
+ "Develop targeted questions for each group using the client context.",
53
+ "Add sample answers to provide clarity.",
54
+ "Combine both sets into one cohesive list."
55
+ ],
56
+ "generate_general_questions": [
57
+ "Review the overall client background and project requirements.",
58
+ "Identify key areas such as integration, performance, and security.",
59
+ "Craft context-aware questions that are precise and actionable.",
60
+ "Include sample answers to illustrate expected responses.",
61
+ "Return a clear list of general questions."
62
+ ],
63
+ "generate_further_follow_up_questions": [
64
+ "Examine the client background and previous responses in detail.",
65
+ "Identify any gaps or unclear points needing further detail.",
66
+ "Formulate direct follow-up questions using techniques like the 5 Whys.",
67
+ "Reference prior responses to maintain context.",
68
+ "List each follow-up question with sample answers for guidance."
69
+ ]
70
+ }
71
+
72
+ async def client_initial_question():
73
+ """Return client information gathering questions."""
74
+ return """
75
+ # Client Information Gathering Questions
76
+
77
+ ### Company Background and Industry
78
+ 1. Can you provide some background about your company?
79
+ 2. Which industry do you operate in, and what is your company's niche or specialization?
80
+ 3. Who are your primary customers?
81
+ 4. What are the main objectives you want to achieve?
82
+ 5. What key features or functionalities do you need?
83
+
84
+ ### Current Challenges
85
+ 6. What are the biggest challenges your firm is currently facing?
86
+ 7. Can you describe your current processes?
87
+
88
+ ### Workflow and System Impact
89
+ 8. How will this solution benefit your firm as a whole?
90
+
91
+ ### Existing Workflow or System
92
+ 9. Can you describe your current workflow or system?
93
+
94
+ ### Pain Point Identification
95
+ 10. Where is your current system falling short or causing delays?
96
+ 11. Are there any parts of the process that are particularly time-consuming/ prone to error?
97
+ """
98
+
99
+ async def simulate_thinking_chat(message, history):
100
+ logging.info(f"Received message: {message}")
101
+ logging.info(f"Initial history: {history}")
102
+ start_time = time.time()
103
+ response = ChatMessage(
104
+ content="",
105
+ metadata={"title": "_Processing_ step-by-step", "id": 0, "status": "pending"}
106
+ )
107
+ yield response, ""
108
+
109
+ # Determine which function to call based on history length
110
+ if len(history) == 0:
111
+ function_name = "client_initial_question"
112
+ current_thoughts = thoughts["client_initial_question"]
113
+ async_func = client_initial_question()
114
+ elif len(history) <= 3: # Overlapping condition for initial questions
115
+ function_name = "generate_general_questions"
116
+ current_thoughts = thoughts["generate_general_questions"]
117
+ async_func = generate_general_questions() # You'll need to implement this
118
+ elif len(history) <= 6: # Overlapping condition for general questions
119
+ function_name = "generate_further_follow_up_questions"
120
+ current_thoughts = thoughts["generate_further_follow_up_questions"]
121
+ async_func = generate_further_follow_up_questions() # You'll need to implement this
122
+ else:
123
+ # Default to client initial questions if no other case matches
124
+ function_name = "client_initial_question"
125
+ current_thoughts = thoughts["client_initial_question"]
126
+ async_func = client_initial_question()
127
+
128
+ # Create a task for getting the appropriate response
129
+ response_task = asyncio.create_task(async_func)
130
+
131
+ # Show thoughts from the global thoughts dictionary
132
+ accumulated_thoughts = ""
133
+ thought_index = 0
134
+ while not response_task.done():
135
+ thought = current_thoughts[thought_index % len(current_thoughts)]
136
+ thought_index += 1
137
+
138
+ await asyncio.sleep(sleep_time)
139
+ accumulated_thoughts += f"- {thought}\n\n"
140
+ response.content = accumulated_thoughts.strip()
141
+ yield response, ""
142
+
143
+ # Get the result from the completed task
144
+ result = await response_task
145
+
146
+ response.metadata["status"] = "done"
147
+ response.metadata["duration"] = time.time() - start_time
148
+ yield response, ""
149
+
150
+ response_list = [
151
+ response,
152
+ ChatMessage(content=result)
153
+ ]
154
+ print(f"Function: {function_name}\nMessage: {message},\nLen: {len(history)},\nHistory: {history}")
155
+
156
+ yield response_list, result
157
+
158
+ # Add new async functions for the additional question types
159
+ async def generate_general_questions():
160
+ await asyncio.sleep(10) # Convert to async sleep
161
+ return """
162
+ # General Integration and Deployment Questions
163
+
164
+ 1. What are your current system integrations?
165
+ Sample: "We use Salesforce for CRM and SAP for ERP"
166
+
167
+ 2. What are your security requirements?
168
+ Sample: "We need SSO integration and data encryption at rest"
169
+
170
+ 3. What is your expected deployment timeline?
171
+ Sample: "We aim to go live within 3 months"
172
+
173
+ 4. Do you have any specific performance requirements?
174
+ Sample: "System should handle 1000 concurrent users"
175
+
176
+ 5. What is your preferred hosting environment?
177
+ Sample: "We prefer AWS cloud hosting"
178
+ """
179
+
180
+ async def generate_further_follow_up_questions():
181
+ await asyncio.sleep(10) # Convert to async sleep
182
+ return """
183
+ # Follow-up Questions Based on Previous Responses
184
+
185
+ 1. Could you elaborate on your current workflow bottlenecks?
186
+ Sample: "Manual data entry takes 4 hours daily"
187
+
188
+ 2. What specific metrics would indicate project success?
189
+ Sample: "50% reduction in processing time"
190
+
191
+ 3. Have you identified any potential risks or challenges?
192
+ Sample: "Data migration from legacy systems"
193
+
194
+ 4. What is your expected ROI timeframe?
195
+ Sample: "We expect to see returns within 6 months"
196
+
197
+ 5. Are there any compliance requirements we should be aware of?
198
+ Sample: "We need to comply with GDPR and HIPAA"
199
+ """
200
+
201
+ chatbot = gr.Chatbot(height=650 ,elem_classes=["chatbot-container"], label="Project Questions")
202
+
203
+ with gr.Blocks(fill_height=True) as demo:
204
+ with gr.Row():
205
+ with gr.Column(scale=1):
206
+ # output = gr.Textbox(label="Output")
207
+ current_question = gr.Textbox(label="Edit Area", lines=30, interactive=True)
208
+ # submit_btn = gr.Button("Submit")
209
+ # clear_btn = gr.Button("Clear Chat")
210
+ with gr.Column(scale=1):
211
+ gr.ChatInterface(
212
+ simulate_thinking_chat,
213
+ chatbot= chatbot,
214
+ type="messages",
215
+ fill_height=True,
216
+ additional_outputs= [current_question],
217
+ flagging_mode= "manual"
218
+ # show_progress= 'minimal',
219
+ # save_history= True
220
+ )
221
+
222
+ demo.launch()