junaid17 commited on
Commit
21ab7a4
·
verified ·
1 Parent(s): 7ad395b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -22
app.py CHANGED
@@ -76,7 +76,6 @@ async def chat_endpoint(request: ChatRequest):
76
  Robust Streaming Endpoint that logs events to console.
77
  """
78
  config = {"configurable": {"thread_id": request.thread_id}}
79
-
80
  inputs = {
81
  "query": request.query,
82
  "RAG": request.use_rag,
@@ -90,38 +89,69 @@ async def chat_endpoint(request: ChatRequest):
90
  async def event_generator():
91
  print(f"--- 🚀 Starting stream for {request.thread_id} ---")
92
 
93
- # We iterate over ALL events
94
- async for event in rag_app.astream_events(inputs, config=config, version="v1"):
95
-
96
- # [DEBUG] Print event types to your terminal so you can see what's happening
97
- event_type = event.get("event")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
 
99
- # Logic: We don't care about the event name.
100
- # We only care: "Does this event have a chunk with text?"
101
- data = event.get("data", {})
102
- chunk = data.get("chunk")
103
 
104
- # Check if chunk exists and has .content attribute (standard LangChain message chunk)
105
- if chunk and hasattr(chunk, "content"):
106
- content = chunk.content
107
-
108
- # Filter out empty strings or weird artifacts
109
- if content:
110
- # JSON encode the content
111
- chunk_json = json.dumps({"content": content})
112
- yield f"data: {chunk_json}\n\n"
113
-
114
  # End of stream
115
  yield "data: [DONE]\n\n"
116
 
117
  return StreamingResponse(
118
- event_generator(),
119
  media_type="text/event-stream",
120
  headers={
121
  "Cache-Control": "no-cache",
122
  "Connection": "keep-alive",
123
  "Content-Type": "text/event-stream",
124
- "X-Accel-Buffering": "no", # Critical for HF
125
  },
126
  )
127
 
 
76
  Robust Streaming Endpoint that logs events to console.
77
  """
78
  config = {"configurable": {"thread_id": request.thread_id}}
 
79
  inputs = {
80
  "query": request.query,
81
  "RAG": request.use_rag,
 
89
  async def event_generator():
90
  print(f"--- 🚀 Starting stream for {request.thread_id} ---")
91
 
92
+ try:
93
+ # Iterate over all events
94
+ async for event in rag_app.astream_events(inputs, config=config, version="v2"):
95
+ event_type = event.get("event")
96
+ name = event.get("name", "")
97
+
98
+ # Debug: print all events to see what's happening
99
+ print(f"Event: {event_type} | Name: {name}")
100
+
101
+ # Method 1: Check for on_chat_model_stream events (most reliable)
102
+ if event_type == "on_chat_model_stream":
103
+ data = event.get("data", {})
104
+ chunk = data.get("chunk")
105
+
106
+ if chunk and hasattr(chunk, "content"):
107
+ content = chunk.content
108
+ if content:
109
+ chunk_json = json.dumps({"content": content})
110
+ yield f"data: {chunk_json}\n\n"
111
+ print(f"✅ Yielded: {content[:50]}...")
112
+
113
+ # Method 2: Alternative - check for any chunk with content
114
+ elif event_type in ["on_chain_stream", "on_llm_stream"]:
115
+ data = event.get("data", {})
116
+ chunk = data.get("chunk")
117
+
118
+ # Handle different chunk types
119
+ if chunk:
120
+ content = None
121
+
122
+ # AIMessageChunk
123
+ if hasattr(chunk, "content"):
124
+ content = chunk.content
125
+ # String chunk
126
+ elif isinstance(chunk, str):
127
+ content = chunk
128
+ # Dict with content
129
+ elif isinstance(chunk, dict) and "content" in chunk:
130
+ content = chunk["content"]
131
+
132
+ if content:
133
+ chunk_json = json.dumps({"content": content})
134
+ yield f"data: {chunk_json}\n\n"
135
+ print(f"✅ Yielded: {content[:50]}...")
136
 
137
+ print("--- Stream completed ---")
 
 
 
138
 
139
+ except Exception as e:
140
+ print(f"❌ Error in stream: {e}")
141
+ error_json = json.dumps({"error": str(e)})
142
+ yield f"data: {error_json}\n\n"
143
+
 
 
 
 
 
144
  # End of stream
145
  yield "data: [DONE]\n\n"
146
 
147
  return StreamingResponse(
148
+ event_generator(),
149
  media_type="text/event-stream",
150
  headers={
151
  "Cache-Control": "no-cache",
152
  "Connection": "keep-alive",
153
  "Content-Type": "text/event-stream",
154
+ "X-Accel-Buffering": "no",
155
  },
156
  )
157