added stream interrupt logic by socket close for llm wrapper
This commit is contained in:
@@ -2,7 +2,7 @@ from openai import OpenAI, APIConnectionError
|
||||
from openai import AsyncOpenAI
|
||||
from .. import config
|
||||
from typing import Optional, Dict, Any
|
||||
|
||||
import asyncio
|
||||
def call(
|
||||
system_prompt: str,
|
||||
user_prompt: str,
|
||||
@@ -62,7 +62,7 @@ def _get_response_format(schema, schema_name: Optional[str] = None) -> Dict[str,
|
||||
async def call_stream(
|
||||
system_prompt: str,
|
||||
user_prompt: str,
|
||||
emit, # EventCallback
|
||||
emit,
|
||||
model: str = None,
|
||||
json_schema=None,
|
||||
schema_name=None,
|
||||
@@ -98,15 +98,26 @@ async def call_stream(
|
||||
stream=True,
|
||||
)
|
||||
|
||||
async for chunk in stream:
|
||||
delta = chunk.choices[0].delta.content
|
||||
if delta:
|
||||
full_content += delta
|
||||
await emit({"type": "llm_chunk", "content": delta})
|
||||
try:
|
||||
async for chunk in stream:
|
||||
delta = chunk.choices[0].delta.content
|
||||
if delta:
|
||||
full_content += delta
|
||||
await emit({"type": "llm_chunk", "content": delta})
|
||||
finally:
|
||||
# Always release the underlying HTTP connection, whether we
|
||||
# finished normally, timed out, were cancelled, or emit()
|
||||
# failed because the client disconnected. This is what
|
||||
# actually tells the backend to stop generating.
|
||||
await stream.close()
|
||||
|
||||
except APIConnectionError as e:
|
||||
print(f"Connection error: {e}")
|
||||
return ""
|
||||
except asyncio.CancelledError:
|
||||
# Real cancellation (e.g. asyncio.wait_for timeout, or task.cancel()
|
||||
# from the router)
|
||||
raise
|
||||
except Exception as e:
|
||||
import traceback
|
||||
print(f"LLM streaming failed: {type(e).__name__}: {e}")
|
||||
|
||||
Reference in New Issue
Block a user