File size: 15,647 Bytes
83c8d2b
 
 
 
 
 
 
 
 
 
 
4c1add8
 
 
83c8d2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c1add8
 
 
 
 
83c8d2b
 
4c1add8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83c8d2b
 
4c1add8
 
 
 
 
 
 
 
 
 
 
 
 
83c8d2b
4c1add8
 
 
 
83c8d2b
4c1add8
 
 
 
83c8d2b
4c1add8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83c8d2b
4c1add8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83c8d2b
 
 
 
4c1add8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83c8d2b
 
4c1add8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83c8d2b
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# Chat_Workflows.py
# Description: UI for Chat Workflows
#
# Imports
import json
import logging
from pathlib import Path
#
# External Imports
import gradio as gr
#
from App_Function_Libraries.Gradio_UI.Chat_ui import chat_wrapper, search_conversations, \
    load_conversation
from App_Function_Libraries.Chat import save_chat_history_to_db_wrapper
#
############################################################################################################
#
# Functions:

# Load workflows from a JSON file
json_path = Path('./Helper_Scripts/Workflows/Workflows.json')
with json_path.open('r') as f:
    workflows = json.load(f)


# FIXME - broken Completely. Doesn't work.
def chat_workflows_tab():
    with gr.TabItem("Chat Workflows"):
        gr.Markdown("# Workflows using LLMs")
        chat_history = gr.State([])
        media_content = gr.State({})
        selected_parts = gr.State([])
        conversation_id = gr.State(None)
        workflow_state = gr.State({"current_step": 0, "max_steps": 0, "conversation_id": None})

        with gr.Row():
            with gr.Column():
                workflow_selector = gr.Dropdown(label="Select Workflow", choices=[wf['name'] for wf in workflows])
                api_selector = gr.Dropdown(
                    label="Select API Endpoint",
                    choices=["OpenAI", "Anthropic", "Cohere", "Groq", "DeepSeek", "Mistral", "OpenRouter",
                             "Llama.cpp", "Kobold", "Ooba", "Tabbyapi", "VLLM", "ollama", "HuggingFace"],
                    value="OpenAI"
                )
                api_key_input = gr.Textbox(label="API Key (optional)", type="password")
                temperature = gr.Slider(label="Temperature", minimum=0.00, maximum=1.0, step=0.05, value=0.7)
                save_conversation = gr.Checkbox(label="Save Conversation", value=False)
            with gr.Column():
                gr.Markdown("Placeholder")
        with gr.Row():
            with gr.Column():
                conversation_search = gr.Textbox(label="Search Conversations")
                search_conversations_btn = gr.Button("Search Conversations")
            with gr.Column():
                previous_conversations = gr.Dropdown(label="Select Conversation", choices=[], interactive=True)
                load_conversations_btn = gr.Button("Load Selected Conversation")
        with gr.Row():
            with gr.Column():
                context_input = gr.Textbox(label="Initial Context", lines=5)
                chatbot = gr.Chatbot(label="Workflow Chat")
                msg = gr.Textbox(label="Your Input")
                submit_btn = gr.Button("Submit")
                clear_btn = gr.Button("Clear Chat")
                chat_media_name = gr.Textbox(label="Custom Chat Name(optional)")
                save_btn = gr.Button("Save Chat to Database")

        def update_workflow_ui(workflow_name):
            if not workflow_name:
                return {"current_step": 0, "max_steps": 0, "conversation_id": None}, "", []
            selected_workflow = next((wf for wf in workflows if wf['name'] == workflow_name), None)
            if selected_workflow:
                num_prompts = len(selected_workflow['prompts'])
                context = selected_workflow.get('context', '')
                first_prompt = selected_workflow['prompts'][0]
                initial_chat = [(None, f"{first_prompt}")]
                logging.info(f"Initializing workflow: {workflow_name} with {num_prompts} steps")
                return {"current_step": 0, "max_steps": num_prompts, "conversation_id": None}, context, initial_chat
            else:
                logging.error(f"Selected workflow not found: {workflow_name}")
                return {"current_step": 0, "max_steps": 0, "conversation_id": None}, "", []

        def process_workflow_step(message, history, context, workflow_name, api_endpoint, api_key, workflow_state,

                                  save_conv, temp):
            logging.info(f"Process workflow step called with message: {message}")
            logging.info(f"Current workflow state: {workflow_state}")
            try:
                selected_workflow = next((wf for wf in workflows if wf['name'] == workflow_name), None)
                if not selected_workflow:
                    logging.error(f"Selected workflow not found: {workflow_name}")
                    return history, workflow_state, gr.update(interactive=True)

                current_step = workflow_state["current_step"]
                max_steps = workflow_state["max_steps"]

                logging.info(f"Current step: {current_step}, Max steps: {max_steps}")

                if current_step >= max_steps:
                    logging.info("Workflow completed, disabling input")
                    return history, workflow_state, gr.update(interactive=False)

                prompt = selected_workflow['prompts'][current_step]
                full_message = f"{context}\n\nStep {current_step + 1}: {prompt}\nUser: {message}"

                logging.info(f"Calling chat_wrapper with full_message: {full_message[:100]}...")
                bot_message, new_history, new_conversation_id = chat_wrapper(
                    full_message, history, media_content.value, selected_parts.value,
                    api_endpoint, api_key, "", workflow_state["conversation_id"],
                    save_conv, temp, "You are a helpful assistant guiding through a workflow."
                )

                logging.info(f"Received bot_message: {bot_message[:100]}...")

                next_step = current_step + 1
                new_workflow_state = {
                    "current_step": next_step,
                    "max_steps": max_steps,
                    "conversation_id": new_conversation_id
                }

                if next_step >= max_steps:
                    logging.info("Workflow completed after this step")
                    return new_history, new_workflow_state, gr.update(interactive=False)
                else:
                    next_prompt = selected_workflow['prompts'][next_step]
                    new_history.append((None, f"Step {next_step + 1}: {next_prompt}"))
                    logging.info(f"Moving to next step: {next_step}")
                    return new_history, new_workflow_state, gr.update(interactive=True)
            except Exception as e:
                logging.error(f"Error in process_workflow_step: {str(e)}")
                return history, workflow_state, gr.update(interactive=True)

        workflow_selector.change(
            update_workflow_ui,
            inputs=[workflow_selector],
            outputs=[workflow_state, context_input, chatbot]
        )

        submit_btn.click(
            process_workflow_step,
            inputs=[msg, chatbot, context_input, workflow_selector, api_selector, api_key_input, workflow_state,
                    save_conversation, temperature],
            outputs=[chatbot, workflow_state, msg]
        ).then(
            lambda: gr.update(value=""),
            outputs=[msg]
        )

        clear_btn.click(
            lambda: ([], {"current_step": 0, "max_steps": 0, "conversation_id": None}, ""),
            outputs=[chatbot, workflow_state, context_input]
        )

        save_btn.click(
            save_chat_history_to_db_wrapper,
            inputs=[chatbot, conversation_id, media_content, chat_media_name],
            outputs=[conversation_id, gr.Textbox(label="Save Status")]
        )

        search_conversations_btn.click(
            search_conversations,
            inputs=[conversation_search],
            outputs=[previous_conversations]
        )

        load_conversations_btn.click(
            lambda: ([], {"current_step": 0, "max_steps": 0, "conversation_id": None}, ""),
            outputs=[chatbot, workflow_state, context_input]
        ).then(
            load_conversation,
            inputs=[previous_conversations],
            outputs=[chatbot, conversation_id]
        )

    return workflow_selector, api_selector, api_key_input, context_input, chatbot, msg, submit_btn, clear_btn, save_btn
# def chat_workflows_tab():
#     with gr.TabItem("Chat Workflows"):
#         gr.Markdown("# Workflows using LLMs")
#         chat_history = gr.State([])
#         media_content = gr.State({})
#         selected_parts = gr.State([])
#         conversation_id = gr.State(None)
#         workflow_state = gr.State({"current_step": 0, "max_steps": 0, "conversation_id": None})
#
#         with gr.Row():
#             workflow_selector = gr.Dropdown(label="Select Workflow", choices=[wf['name'] for wf in workflows])
#             api_selector = gr.Dropdown(
#                 label="Select API Endpoint",
#                 choices=["OpenAI", "Anthropic", "Cohere", "Groq", "DeepSeek", "Mistral", "OpenRouter",
#                          "Llama.cpp", "Kobold", "Ooba", "Tabbyapi", "VLLM", "ollama", "HuggingFace"],
#                 value="OpenAI"
#             )
#             api_key_input = gr.Textbox(label="API Key (optional)", type="password")
#
#         context_input = gr.Textbox(label="Initial Context (optional)", lines=5)
#
#         with gr.Row():
#             temperature = gr.Slider(label="Temperature", minimum=0.00, maximum=1.0, step=0.05, value=0.7)
#             save_conversation = gr.Checkbox(label="Save Conversation", value=False)
#
#         chatbot = gr.Chatbot(label="Workflow Chat")
#         msg = gr.Textbox(label="Your Input")
#         submit_btn = gr.Button("Submit")
#         clear_btn = gr.Button("Clear Chat")
#         save_btn = gr.Button("Save Chat to Database")
#
#         with gr.Row():
#             conversation_search = gr.Textbox(label="Search Conversations")
#             search_conversations_btn = gr.Button("Search Conversations")
#         previous_conversations = gr.Dropdown(label="Select Conversation", choices=[], interactive=True)
#         load_conversations_btn = gr.Button("Load Selected Conversation")
#
#         def update_workflow_ui(workflow_name):
#             if not workflow_name:
#                 return {"current_step": 0, "max_steps": 0, "conversation_id": None}
#             selected_workflow = next((wf for wf in workflows if wf['name'] == workflow_name), None)
#             if selected_workflow:
#                 num_prompts = len(selected_workflow['prompts'])
#                 logging.info(f"Initializing workflow: {workflow_name} with {num_prompts} steps")
#                 return {"current_step": 0, "max_steps": num_prompts, "conversation_id": None}
#             else:
#                 logging.error(f"Selected workflow not found: {workflow_name}")
#                 return {"current_step": 0, "max_steps": 0, "conversation_id": None}
#
#         def process_workflow_step(message, history, context, workflow_name, api_endpoint, api_key, workflow_state,
#                                   save_conv, temp):
#             logging.info(f"Process workflow step called with message: {message}")
#             logging.info(f"Current workflow state: {workflow_state}")
#             try:
#                 selected_workflow = next((wf for wf in workflows if wf['name'] == workflow_name), None)
#                 if not selected_workflow:
#                     logging.error(f"Selected workflow not found: {workflow_name}")
#                     return history, workflow_state, gr.update(interactive=True)
#
#                 current_step = workflow_state["current_step"]
#                 max_steps = workflow_state["max_steps"]
#
#                 logging.info(f"Current step: {current_step}, Max steps: {max_steps}")
#
#                 if current_step >= max_steps:
#                     logging.info("Workflow completed, disabling input")
#                     return history, workflow_state, gr.update(interactive=False)
#
#                 prompt = selected_workflow['prompts'][current_step]
#                 full_message = f"{context}\n\nStep {current_step + 1}: {prompt}\nUser: {message}"
#
#                 logging.info(f"Calling chat_wrapper with full_message: {full_message[:100]}...")
#                 bot_message, new_history, new_conversation_id = chat_wrapper(
#                     full_message, history, media_content.value, selected_parts.value,
#                     api_endpoint, api_key, "", workflow_state["conversation_id"],
#                     save_conv, temp, "You are a helpful assistant guiding through a workflow."
#                 )
#
#                 logging.info(f"Received bot_message: {bot_message[:100]}...")
#
#                 next_step = current_step + 1
#                 new_workflow_state = {
#                     "current_step": next_step,
#                     "max_steps": max_steps,
#                     "conversation_id": new_conversation_id
#                 }
#
#                 if next_step >= max_steps:
#                     logging.info("Workflow completed after this step")
#                     return new_history, new_workflow_state, gr.update(interactive=False)
#                 else:
#                     next_prompt = selected_workflow['prompts'][next_step]
#                     new_history.append((None, f"Step {next_step + 1}: {next_prompt}"))
#                     logging.info(f"Moving to next step: {next_step}")
#                     return new_history, new_workflow_state, gr.update(interactive=True)
#             except Exception as e:
#                 logging.error(f"Error in process_workflow_step: {str(e)}")
#                 return history, workflow_state, gr.update(interactive=True)
#
#         workflow_selector.change(
#             update_workflow_ui,
#             inputs=[workflow_selector],
#             outputs=[workflow_state]
#         )
#
#         submit_btn.click(
#             process_workflow_step,
#             inputs=[msg, chatbot, context_input, workflow_selector, api_selector, api_key_input, workflow_state,
#                     save_conversation, temperature],
#             outputs=[chatbot, workflow_state, msg]
#         ).then(
#             lambda: gr.update(value=""),
#             outputs=[msg]
#         )
#
#         clear_btn.click(
#             lambda: ([], {"current_step": 0, "max_steps": 0, "conversation_id": None}),
#             outputs=[chatbot, workflow_state]
#         )
#
#         save_btn.click(
#             save_chat_history_to_db_wrapper,
#             inputs=[chatbot, conversation_id, media_content],
#             outputs=[conversation_id, gr.Textbox(label="Save Status")]
#         )
#
#         search_conversations_btn.click(
#             search_conversations,
#             inputs=[conversation_search],
#             outputs=[previous_conversations]
#         )
#
#         load_conversations_btn.click(
#             lambda: ([], {"current_step": 0, "max_steps": 0, "conversation_id": None}),
#             outputs=[chatbot, workflow_state]
#         ).then(
#             load_conversation,
#             inputs=[previous_conversations],
#             outputs=[chatbot, conversation_id]
#         )
#
#     return workflow_selector, api_selector, api_key_input, context_input, chatbot, msg, submit_btn, clear_btn, save_btn

#
# End of script
############################################################################################################