n3ffos commited on
Commit
5614848
·
verified ·
1 Parent(s): 2597329

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -11
app.py CHANGED
@@ -27,17 +27,47 @@ def respond(
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
  """
 
27
 
28
  response = ""
29
 
30
+ try:
31
+ for message in client.chat_completion(
32
+ messages,
33
+ max_tokens=max_tokens,
34
+ stream=True,
35
+ temperature=temperature,
36
+ top_p=top_p,
37
+ ):
38
+ # Ensure the message has a valid structure
39
+ if not message or not isinstance(message, dict):
40
+ continue
41
+
42
+ try:
43
+ # Extract content and finish reason
44
+ content = message.choices[0].delta.content
45
+ finish_reason = message.choices[0].finish_reason
46
+
47
+ # Check if the content is empty
48
+ if content.strip() == "":
49
+ # If the finish reason is 'stop', it's expected and we can break the loop
50
+ if finish_reason == "stop":
51
+ print("Stream ended normally.")
52
+ break
53
+ else:
54
+ print("Received unexpected empty content, skipping...")
55
+ continue
56
+
57
+ response += content
58
+ yield response
59
+
60
+ except (AttributeError, IndexError, KeyError) as e:
61
+ print(f"Error processing message: {e}")
62
+ continue
63
+
64
+ except Exception as e:
65
+ print(f"Unexpected error: {e}")
66
+ yield "An error occurred while generating the response."
67
+
68
+ # Final check if the response is empty
69
+ if response.strip() == "":
70
+ yield "No response generated. Please try again or adjust the settings."
71
 
72
 
73
  """