yym68686 commited on
Commit
e6c24d4
·
1 Parent(s): cf121cf
Files changed (1) hide show
  1. utils.py +64 -64
utils.py CHANGED
@@ -73,63 +73,20 @@ def ensure_string(item):
73
  else:
74
  return str(item)
75
 
76
- import asyncio
77
- async def error_handling_wrapper(generator, status_code=200):
78
- async def new_generator():
79
- try:
80
- yield ensure_string(first_item)
81
- async for item in generator:
82
- yield ensure_string(item)
83
- except (httpx.ReadError, asyncio.CancelledError) as e:
84
- logger.error(f"Network error in new_generator: {e}")
85
- raise HTTPException(status_code=503, detail=f"Stream interrupted: {str(e)}")
86
- except Exception as e:
87
- logger.exception(f"Error in new_generator: {e}")
88
- raise HTTPException(status_code=status_code, detail=f"Stream error: {str(e)}")
89
-
90
- try:
91
- first_item = await generator.__anext__()
92
- first_item_str = first_item
93
- if isinstance(first_item_str, (bytes, bytearray)):
94
- first_item_str = first_item_str.decode("utf-8")
95
- if isinstance(first_item_str, str):
96
- if first_item_str.startswith("data: "):
97
- first_item_str = first_item_str[6:]
98
- elif first_item_str.startswith("data:"):
99
- first_item_str = first_item_str[5:]
100
- if first_item_str.startswith("[DONE]"):
101
- logger.error("error_handling_wrapper [DONE]!")
102
- raise StopAsyncIteration
103
- try:
104
- first_item_str = json.loads(first_item_str)
105
- except json.JSONDecodeError:
106
- logger.error("error_handling_wrapper JSONDecodeError!" + repr(first_item_str))
107
- raise StopAsyncIteration
108
- if isinstance(first_item_str, dict) and 'error' in first_item_str:
109
- raise HTTPException(status_code=status_code, detail=f"{first_item_str}"[:300])
110
-
111
- wrapped_generator = new_generator()
112
- try:
113
- async for item in wrapped_generator:
114
- yield item
115
- except HTTPException as http_exc:
116
- raise HTTPException(status_code=status_code, detail=f"Wrapper error: {str(http_exc)}")
117
- except (httpx.ReadError, asyncio.CancelledError) as e:
118
- logger.error(f"Network error during streaming: {e}")
119
- raise HTTPException(status_code=503, detail=f"Stream interrupted: {str(e)}")
120
- except Exception as e:
121
- logger.exception(f"Unexpected error in error_handling_wrapper: {e}")
122
- raise HTTPException(status_code=status_code, detail=f"Unexpected error: {str(e)}")
123
-
124
- except StopAsyncIteration:
125
- raise HTTPException(status_code=status_code, detail="data: {'error': 'No data returned'}")
126
- except HTTPException as http_exc:
127
- raise HTTPException(status_code=status_code, detail=f"Wrapper error: {str(http_exc)}")
128
- except Exception as e:
129
- logger.exception(f"Error in error_handling_wrapper: {e}")
130
- raise HTTPException(status_code=status_code, detail=f"Wrapper error: {str(e)}")
131
-
132
  # async def error_handling_wrapper(generator, status_code=200):
 
 
 
 
 
 
 
 
 
 
 
 
133
  # try:
134
  # first_item = await generator.__anext__()
135
  # first_item_str = first_item
@@ -149,19 +106,62 @@ async def error_handling_wrapper(generator, status_code=200):
149
  # logger.error("error_handling_wrapper JSONDecodeError!" + repr(first_item_str))
150
  # raise StopAsyncIteration
151
  # if isinstance(first_item_str, dict) and 'error' in first_item_str:
152
- # # 如果第一个 yield 的项是错误信息,抛出 HTTPException
153
  # raise HTTPException(status_code=status_code, detail=f"{first_item_str}"[:300])
154
 
155
- # # 如果不是错误,创建一个新的生成器,首先yield第一个项,然后yield剩余的项
156
- # async def new_generator():
157
- # yield ensure_string(first_item)
158
- # async for item in generator:
159
- # yield ensure_string(item)
160
-
161
- # return new_generator()
 
 
 
 
 
162
 
163
  # except StopAsyncIteration:
164
  # raise HTTPException(status_code=status_code, detail="data: {'error': 'No data returned'}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
 
166
  def post_all_models(token, config, api_list):
167
  all_models = []
 
73
  else:
74
  return str(item)
75
 
76
+ # import asyncio
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  # async def error_handling_wrapper(generator, status_code=200):
78
+ # async def new_generator():
79
+ # try:
80
+ # yield ensure_string(first_item)
81
+ # async for item in generator:
82
+ # yield ensure_string(item)
83
+ # except (httpx.ReadError, asyncio.CancelledError) as e:
84
+ # logger.error(f"Network error in new_generator: {e}")
85
+ # raise HTTPException(status_code=503, detail=f"Stream interrupted: {str(e)}")
86
+ # except Exception as e:
87
+ # logger.exception(f"Error in new_generator: {e}")
88
+ # raise HTTPException(status_code=status_code, detail=f"Stream error: {str(e)}")
89
+
90
  # try:
91
  # first_item = await generator.__anext__()
92
  # first_item_str = first_item
 
106
  # logger.error("error_handling_wrapper JSONDecodeError!" + repr(first_item_str))
107
  # raise StopAsyncIteration
108
  # if isinstance(first_item_str, dict) and 'error' in first_item_str:
 
109
  # raise HTTPException(status_code=status_code, detail=f"{first_item_str}"[:300])
110
 
111
+ # wrapped_generator = new_generator()
112
+ # try:
113
+ # async for item in wrapped_generator:
114
+ # yield item
115
+ # except HTTPException as http_exc:
116
+ # raise HTTPException(status_code=status_code, detail=f"Wrapper error: {str(http_exc)}")
117
+ # except (httpx.ReadError, asyncio.CancelledError) as e:
118
+ # logger.error(f"Network error during streaming: {e}")
119
+ # raise HTTPException(status_code=503, detail=f"Stream interrupted: {str(e)}")
120
+ # except Exception as e:
121
+ # logger.exception(f"Unexpected error in error_handling_wrapper: {e}")
122
+ # raise HTTPException(status_code=status_code, detail=f"Unexpected error: {str(e)}")
123
 
124
  # except StopAsyncIteration:
125
  # raise HTTPException(status_code=status_code, detail="data: {'error': 'No data returned'}")
126
+ # except HTTPException as http_exc:
127
+ # raise HTTPException(status_code=status_code, detail=f"Wrapper error: {str(http_exc)}")
128
+ # except Exception as e:
129
+ # logger.exception(f"Error in error_handling_wrapper: {e}")
130
+ # raise HTTPException(status_code=status_code, detail=f"Wrapper error: {str(e)}")
131
+
132
+ async def error_handling_wrapper(generator, status_code=200):
133
+ try:
134
+ first_item = await generator.__anext__()
135
+ first_item_str = first_item
136
+ if isinstance(first_item_str, (bytes, bytearray)):
137
+ first_item_str = first_item_str.decode("utf-8")
138
+ if isinstance(first_item_str, str):
139
+ if first_item_str.startswith("data: "):
140
+ first_item_str = first_item_str[6:]
141
+ elif first_item_str.startswith("data:"):
142
+ first_item_str = first_item_str[5:]
143
+ if first_item_str.startswith("[DONE]"):
144
+ logger.error("error_handling_wrapper [DONE]!")
145
+ raise StopAsyncIteration
146
+ try:
147
+ first_item_str = json.loads(first_item_str)
148
+ except json.JSONDecodeError:
149
+ logger.error("error_handling_wrapper JSONDecodeError!" + repr(first_item_str))
150
+ raise StopAsyncIteration
151
+ if isinstance(first_item_str, dict) and 'error' in first_item_str:
152
+ # 如果第一个 yield 的项是错误信息,抛出 HTTPException
153
+ raise HTTPException(status_code=status_code, detail=f"{first_item_str}"[:300])
154
+
155
+ # 如果不是错误,创建一个新的生成器,首先yield第一个项,然后yield剩余的项
156
+ async def new_generator():
157
+ yield ensure_string(first_item)
158
+ async for item in generator:
159
+ yield ensure_string(item)
160
+
161
+ return new_generator()
162
+
163
+ except StopAsyncIteration:
164
+ raise HTTPException(status_code=status_code, detail="data: {'error': 'No data returned'}")
165
 
166
  def post_all_models(token, config, api_list):
167
  all_models = []