How to Return SSE Data in Python
Recently, I was using python to call the sse interface of gpt and return it to my front end through sse. I encountered a few problems, and I simply recorded them. There was no amount of code, but it took me more than half a day to get it done.
- how to return sse in python
- why do the newlines in the sse I return always get lost
1 | import json |
There are several key points here, corresponding to the two questions at the beginning:
- The data type returned by the sse interface should be ‘“text/event-stream”’
- The returned data should be formatted ‘id: {}\ nevent: message\ ndata: {}\ n\ n’ .format (id, json.dumps ({‘data’: chunk_message ('content ', ‘’)}))`, This is the sse protocol. One newline character represents different data, two newlines represent a piece of data, and the id should not be repeated.
- data data is best returned with json string, the front end receives it and parses it again, even if your data is originally a string, otherwise you are likely to encounter the problem of missing newlines