implement streaming to the chat
Browse files
app.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
from dotenv import load_dotenv
|
|
|
|
| 4 |
|
| 5 |
from implementation.chat import answer_question
|
| 6 |
|
|
@@ -46,13 +47,29 @@ def chat(history):
|
|
| 46 |
})
|
| 47 |
|
| 48 |
answer, context = answer_question(last_message, clean_history)
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
except Exception as e:
|
| 52 |
import traceback
|
| 53 |
traceback.print_exc()
|
| 54 |
history.append({"role": "assistant", "content": f"Error: {str(e)}"})
|
| 55 |
-
|
| 56 |
|
| 57 |
|
| 58 |
|
|
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
from dotenv import load_dotenv
|
| 4 |
+
import time
|
| 5 |
|
| 6 |
from implementation.chat import answer_question
|
| 7 |
|
|
|
|
| 47 |
})
|
| 48 |
|
| 49 |
answer, context = answer_question(last_message, clean_history)
|
| 50 |
+
|
| 51 |
+
# Stream the final answer into the UI (typewriter-style).
|
| 52 |
+
# This is robust even when the backend does routing/tool-calls.
|
| 53 |
+
history.append({"role": "assistant", "content": ""})
|
| 54 |
+
context_md = ""
|
| 55 |
+
yield history, context_md
|
| 56 |
+
|
| 57 |
+
chunk_size = int(os.getenv("STREAM_CHUNK_SIZE", "24"))
|
| 58 |
+
delay_s = float(os.getenv("STREAM_DELAY_S", "0.01"))
|
| 59 |
+
built = ""
|
| 60 |
+
for i in range(0, len(answer), max(1, chunk_size)):
|
| 61 |
+
built = answer[: i + chunk_size]
|
| 62 |
+
history[-1]["content"] = built
|
| 63 |
+
yield history, context_md
|
| 64 |
+
if delay_s > 0:
|
| 65 |
+
time.sleep(delay_s)
|
| 66 |
+
|
| 67 |
+
yield history, format_context(context)
|
| 68 |
except Exception as e:
|
| 69 |
import traceback
|
| 70 |
traceback.print_exc()
|
| 71 |
history.append({"role": "assistant", "content": f"Error: {str(e)}"})
|
| 72 |
+
yield history, "Error occurred."
|
| 73 |
|
| 74 |
|
| 75 |
|