import json

def main(arg1: str):
    """
    解析 SSE 流式输出,兼容转义的双引号和换行。
    拼接 sql-result、chart-result 内容,并提取其他类型数据。
    """
    chat_id = None
    question = None
    sql_result_parts = []
    chart_result_parts = []
    errors = []
    other = []

    for line in arg1.splitlines():
        line = line.strip()
        if not line.startswith("data:"):
            continue
        json_str = line[len("data:"):]

        # 修正转义
        json_str = json_str.replace('\\"', '"').replace('\\\\n', '\n')

        # 跳过空内容
        if not json_str.strip():
            continue

        try:
            item = json.loads(json_str)
        except json.JSONDecodeError:
            print("JSON解析失败:", json_str)
            continue

        t = item.get("type")
        if t == "id":
            chat_id = item.get("id")
        elif t == "question":
            question = item.get("question")
        elif t == "sql-result":
            sql_result_parts.append(item.get("content", ""))
        elif t == "chart-result":
            chart_result_parts.append(item.get("content", ""))
        elif t == "error":
            errors.append(item.get("content", ""))
        else:
            other.append(item)

    sql_result = "".join(sql_result_parts)
    chart_result = "".join(chart_result_parts)

    res = {
        "chat_id": chat_id,
        "question": question,
        "sql_result": sql_result,
        "chart_result": chart_result,
        "errors": errors,
        "other": other
    }

    return {
        "result": json.dumps(res, ensure_ascii=False)
    }
Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐