解析流式返回,生成 chunk List[dict]
(response)
| 57 | |
| 58 | |
| 59 | def get_stream_chunks(response): |
| 60 | """解析流式返回,生成 chunk List[dict]""" |
| 61 | chunks = [] |
| 62 | |
| 63 | if response.status_code == 200: |
| 64 | for line in response.iter_lines(decode_unicode=True): |
| 65 | if line: |
| 66 | if line.startswith("data: "): |
| 67 | line = line[len("data: ") :] |
| 68 | |
| 69 | if line.strip() == "[DONE]": |
| 70 | break |
| 71 | |
| 72 | try: |
| 73 | chunk = json.loads(line) |
| 74 | chunks.append(chunk) |
| 75 | except Exception as e: |
| 76 | base_logger.error(f"解析失败: {e}, 行内容: {line}") |
| 77 | else: |
| 78 | base_logger.error(f"请求失败,状态码: {response.status_code}") |
| 79 | base_logger.error("返回内容:", response.text) |
| 80 | |
| 81 | return chunks |
| 82 | |
| 83 | |
| 84 | def get_token_list(response): |