Refactor chat API interaction to improve error handling and update conversation history
Browse files
app.py
CHANGED
|
@@ -50,19 +50,32 @@ if not wait_for_fastapi():
|
|
| 50 |
sys.exit(1)
|
| 51 |
|
| 52 |
# Create a Gradio interface that will proxy requests to FastAPI
|
| 53 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
try:
|
|
|
|
| 55 |
response = requests.post(
|
| 56 |
"http://127.0.0.1:8000/chat",
|
| 57 |
json={"message": message, "conversation_id": conversation_id}
|
| 58 |
)
|
|
|
|
| 59 |
if response.status_code == 200:
|
| 60 |
data = response.json()
|
| 61 |
-
|
|
|
|
|
|
|
| 62 |
else:
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
| 64 |
except Exception as e:
|
| 65 |
-
|
|
|
|
|
|
|
| 66 |
|
| 67 |
def build_kb():
|
| 68 |
try:
|
|
|
|
| 50 |
sys.exit(1)
|
| 51 |
|
| 52 |
# Create a Gradio interface that will proxy requests to FastAPI
|
| 53 |
+
def respond(message, history, conversation_id=None):
|
| 54 |
+
"""Handle chat messages and update conversation history"""
|
| 55 |
+
if not message:
|
| 56 |
+
return history, conversation_id
|
| 57 |
+
|
| 58 |
try:
|
| 59 |
+
# Send request to FastAPI backend
|
| 60 |
response = requests.post(
|
| 61 |
"http://127.0.0.1:8000/chat",
|
| 62 |
json={"message": message, "conversation_id": conversation_id}
|
| 63 |
)
|
| 64 |
+
|
| 65 |
if response.status_code == 200:
|
| 66 |
data = response.json()
|
| 67 |
+
# Update conversation history
|
| 68 |
+
history = history + [(message, data["response"])]
|
| 69 |
+
return history, data["conversation_id"]
|
| 70 |
else:
|
| 71 |
+
error_message = f"Error: {response.status_code} - {response.text}"
|
| 72 |
+
history = history + [(message, error_message)]
|
| 73 |
+
return history, conversation_id
|
| 74 |
+
|
| 75 |
except Exception as e:
|
| 76 |
+
error_message = f"Error connecting to API: {str(e)}"
|
| 77 |
+
history = history + [(message, error_message)]
|
| 78 |
+
return history, conversation_id
|
| 79 |
|
| 80 |
def build_kb():
|
| 81 |
try:
|