I have the following FastAPI server. Currently there is stand in code simulating sending SSE from an LLM generation then after the generation is complete, the full response is post-processed then sent over SSE. This two phase process shows progress to the user then replaces it with the full processed version when it's available. There's a fall back in the client to send a get request to fetch the response from a temporary cache if an error occurs. Double check the logic in what I've stated to see if it's the best way to handle things and then evaluate the code:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
async def cleanup_expired_responses():
while True:
current_time = time.time()
expired_keys = [
key for key, value in responses.items()
if current_time > value["expires_at"]
]
for key in expired_keys:
responses.pop(key, None)
await asyncio.sleep(60) # Check every minute
@app.get("/processed/{response_id}")
async def get_processed(response_id: str):
response = responses.pop(response_id, None) # Remove on retrieval
if not response or time.time() > response["expires_at"]:
return JSONResponse({"error": "Response not found or expired"}, status_code=404)
return JSONResponse(response["data"])
Assistant
The current implementation effectively streams LLM tokens and provides a post-processed result via SSE, with a fallback mechanism using a temporary cache. However, several improvements and fixes are necessary to ensure robustness and correctness:
Key Issues Identified:
Client Lacks response_id Early Access
The client cannot retrieve the processed response via the fallback GET endpoint if the stream fails before the final event, as it lacks the response_id.
Error Handling During Streaming
Unhandled exceptions during token generation prevent the processed response from being cached, breaking the fallback mechanism.
Concurrency and Scalability
Using a global dictionary for caching is not thread-safe or scalable across multiple instances.
Cache Cleanup Efficiency
The cleanup interval (60s) may leave expired entries lingering beyond their TTL.
Recommended Fixes and Enhancements:
1. Send response_id Early in the Stream
Emit an initial event containing the response_id so the client can use it for fallback retrieval, even if the stream fails afterward.