Streaming version of the chat endpoint using Server-Sent Events (SSE). Streams pipeline steps and LLM tokens as they are generated.
()
| 109 | "history": new_history, |
| 110 | "documents": documents, |
| 111 | "rewritten": rewritten, |
| 112 | "question": prompt, |
| 113 | "fetched_new_documents": fetched_new_documents |
| 114 | } |
| 115 | if provenance_scores is not None: |
| 116 | for i, doc in enumerate(response_dict["documents"]): |
| 117 | response_dict["documents"][i]["provenance"] = provenance_scores[i]["score"] |
| 118 | return jsonify(response_dict) |
| 119 | |
| 120 | @app.route("/chat_stream", methods=['POST']) |
| 121 | def chat_stream(): |
| 122 | """ |
| 123 | Streaming version of the chat endpoint using Server-Sent Events (SSE). |
| 124 | Streams pipeline steps and LLM tokens as they are generated. |
| 125 | """ |
| 126 | json_data = request.get_json() |
| 127 | prompt = json_data.get('prompt') |
| 128 | history = json_data.get('history', []) |
| 129 | original_docs = json_data.get('docs', []) |
| 130 | datasets = json_data.get('datasets', []) |
| 131 | |
| 132 | def generate(): |
| 133 | try: |
| 134 | for event_type, event_data in raghelper.handle_user_interaction_stream(prompt, history, datasets): |
| 135 | if event_type == "step": |
| 136 | yield f"event: step\ndata: {safe_json_dumps({'step': event_data})}\n\n" |
| 137 | elif event_type == "token": |
| 138 | yield f"event: token\ndata: {safe_json_dumps({'token': event_data})}\n\n" |
| 139 | elif event_type == "documents": |
| 140 | yield f"event: documents\ndata: {safe_json_dumps({'documents': event_data})}\n\n" |
| 141 | elif event_type == "done": |
| 142 | metadata = event_data |
| 143 | documents = metadata.get("documents") or original_docs |
| 144 | provenance_scores = metadata.get("provenance_scores") |
| 145 | if provenance_scores is not None and documents: |
| 146 | for i, doc in enumerate(documents): |
| 147 | if i < len(provenance_scores): |
| 148 | documents[i]["provenance"] = provenance_scores[i]["score"] |
| 149 | done_data = { |
| 150 | "reply": metadata["reply"], |
| 151 | "history": metadata["history"], |
| 152 | "documents": documents, |
| 153 | "rewritten": metadata["rewritten"], |
| 154 | "question": prompt, |
| 155 | "fetched_new_documents": metadata["fetched_new_documents"], |
| 156 | } |
| 157 | yield f"event: done\ndata: {safe_json_dumps(done_data)}\n\n" |
| 158 | except Exception as e: |
| 159 | logger.error(f"Streaming error: {e}", exc_info=True) |
nothing calls this directly
no test coverage detected