Update app.py
Browse files
app.py
CHANGED
@@ -368,9 +368,10 @@ def handsome_chat_completions():
|
|
368 |
)
|
369 |
total_time = end_time - start_time
|
370 |
|
|
|
371 |
prompt_tokens = 0
|
372 |
completion_tokens = 0
|
373 |
-
|
374 |
for line in full_response_content.splitlines():
|
375 |
if line.startswith("data:"):
|
376 |
line = line[5:].strip()
|
@@ -378,45 +379,35 @@ def handsome_chat_completions():
|
|
378 |
continue
|
379 |
try:
|
380 |
response_json = json.loads(line)
|
381 |
-
|
382 |
-
if
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
|
396 |
-
|
397 |
-
|
398 |
-
|
399 |
-
|
400 |
-
|
401 |
-
|
402 |
-
|
403 |
-
|
404 |
-
|
405 |
-
)
|
406 |
-
|
407 |
-
|
408 |
-
|
409 |
-
|
410 |
-
except (
|
411 |
-
KeyError,
|
412 |
-
ValueError,
|
413 |
-
IndexError
|
414 |
-
) as e:
|
415 |
-
logging.error(
|
416 |
-
f"解析流式响应单行 JSON 失败: {e}, "
|
417 |
-
f"行内容: {line}"
|
418 |
-
)
|
419 |
-
|
420 |
user_content = extract_user_content(data.get("messages", []))
|
421 |
|
422 |
user_content_replaced = user_content.replace(
|
|
|
368 |
)
|
369 |
total_time = end_time - start_time
|
370 |
|
371 |
+
response_content = ""
|
372 |
prompt_tokens = 0
|
373 |
completion_tokens = 0
|
374 |
+
|
375 |
for line in full_response_content.splitlines():
|
376 |
if line.startswith("data:"):
|
377 |
line = line[5:].strip()
|
|
|
379 |
continue
|
380 |
try:
|
381 |
response_json = json.loads(line)
|
382 |
+
|
383 |
+
if "usage" in response_json:
|
384 |
+
if "completion_tokens" in response_json["usage"]:
|
385 |
+
completion_tokens += response_json["usage"]["completion_tokens"]
|
386 |
+
if "prompt_tokens" in response_json["usage"]:
|
387 |
+
prompt_tokens += response_json["usage"]["prompt_tokens"]
|
388 |
+
|
389 |
+
|
390 |
+
if "choices" in response_json:
|
391 |
+
for choice in response_json["choices"]:
|
392 |
+
if "delta" in choice and "content" in choice["delta"]:
|
393 |
+
response_content += choice["delta"]["content"]
|
394 |
+
elif "message" in choice and "content" in choice["message"]:
|
395 |
+
response_content += choice["message"]["content"]
|
396 |
+
|
397 |
+
if "finish_reason" in choice:
|
398 |
+
finish_reason = choice["finish_reason"]
|
399 |
+
# Handle finish_reason as needed (e.g., log it)
|
400 |
+
logging.debug(f"Finish reason: {finish_reason}")
|
401 |
+
except json.JSONDecodeError as e:
|
402 |
+
logging.error(f"JSON 解析失败: {e}, 行内容: {line}")
|
403 |
+
except KeyError as e:
|
404 |
+
logging.error(f"键错误: {e}, 行内容: {line}")
|
405 |
+
except IndexError as e:
|
406 |
+
logging.error(f"索引错误: {e}, 行内容: {line}")
|
407 |
+
|
408 |
+
print(f'{response_content=}')
|
409 |
+
print(f'{prompt_tokens=}')
|
410 |
+
print(f'{completion_tokens=}')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
411 |
user_content = extract_user_content(data.get("messages", []))
|
412 |
|
413 |
user_content_replaced = user_content.replace(
|