Trying asyc streaming response API
Browse files
app.py
CHANGED
@@ -78,15 +78,23 @@ Here's the complete Python function implementation:
|
|
78 |
```python
|
79 |
"""
|
80 |
|
81 |
-
def generate():
|
82 |
generated_text = ""
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
90 |
|
91 |
return StreamingResponse(generate(), media_type="text/plain")
|
92 |
|
|
|
78 |
```python
|
79 |
"""
|
80 |
|
81 |
+
async def generate():
|
82 |
generated_text = ""
|
83 |
+
try:
|
84 |
+
for chunk in llm(full_prompt, stream=True, **generation_kwargs):
|
85 |
+
token = chunk["choices"][0]["text"]
|
86 |
+
generated_text += token
|
87 |
+
yield token
|
88 |
+
|
89 |
+
# Optionally send progress updates:
|
90 |
+
progress = len(generated_text) / len(full_prompt)
|
91 |
+
yield {"progress": progress} # Send a progress update
|
92 |
+
|
93 |
+
formatted_code = extract_and_format_code(generated_text)
|
94 |
+
yield formatted_code
|
95 |
+
except Exception as e:
|
96 |
+
# Handle exceptions and return an error message
|
97 |
+
yield {"error": str(e)}
|
98 |
|
99 |
return StreamingResponse(generate(), media_type="text/plain")
|
100 |
|