Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions apps/chat/serializers/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,11 +187,13 @@ def generate_prompt(self, instance: dict):

def process():
model = get_model_instance_by_model_workspace_id(model_id=model_id, workspace_id=workspace_id,**application.model_params_setting)
for r in model.stream([SystemMessage(content=system_content),
try:
for r in model.stream([SystemMessage(content=system_content),
*[HumanMessage(content=m.get('content')) if m.get('role') == 'user' else AIMessage(
content=m.get('content')) for m in messages]]):
yield 'data: ' + json.dumps({'content': r.content}) + '\n\n'

yield 'data: ' + json.dumps({'content': r.content}) + '\n\n'
except Exception as e:
yield 'data: ' + json.dumps({'error': str(e)}) + '\n\n'
return to_stream_response_simple(process())


Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The provided code has a minor issue with error handling. The try block only handles specific exceptions, but it doesn't catch all possible errors that might occur while streaming the response from the model.

Potential Issues and Optimization Suggestions:

  1. Error Handling Scope: Consider catching more general exceptions (Exception) to ensure that any unexpected errors are handled gracefully.

  2. Stream Response: Ensure that you are calling to_stream_response_simple correctly when returning the processed output. This method should handle writing to stdout or another appropriate stream.

Suggested Changes:

@@ -187,14 +187,16 @@ def generate_prompt(self, instance: dict):

     def process():
         model = get_model_instance_by_model_workspace_id(model_id=model_id,
                                                     workspace_id=workspace_id,
-                                                    **application.model_params_setting)
-        for r in model.stream([SystemMessage(content=system_content),
                                *[HumanMessage(content=m.get('content')) if m.get('role') == 'user'
                                 else AIMessage(content=m.get('content'))
                                 for m in messages]]):
-            yield 'data: ' + json.dumps({'content': r.content}) + '\n\n'
-
+            try:
+                for i, r in enumerate(model.stream([SystemMessage(content=system_content),
                                                  *messages])):
+                    yield f"data: {json.dumps(r)},{i}\n\n"
+            except Exception as e:
+                yield "data: {" \
+                        f"\"error\": \"{str(e)}\"" + \
+                       "}\n\n"
 
     return to_stream_response_simple(process())

Explanation of Changes:

  • Catching More Exceptions: Changed except Exception as e: to catch all types of exceptions.
  • Iterating with Indices (Optional): Added an index variable i inside the loop to differentiate between responses; this is purely optional and can be skipped depending on your application's needs.

These changes improve robustness and make sure that any unforeseen errors during the streaming process result in user-friendly feedback rather than termination of the flow. Make sure to adjust the logging mechanism or other monitoring aspects as needed to address actual issues encountered in production environments.

Expand Down
Loading