Coze代码节点调试思路

众所周知,代码调试是程序员必备技能之一。

Coze平台代码节点的缺陷

  • 调试能力有限:缺少如VS Code等IDE的断点、单步、变量监视功能;print输出不可见。
  • 异常不友好:节点异常时可能不弹窗、不中断,甚至 try...except捕获不到预期错误。
  • 类型不一致:上游节点输出看似 string,实为字典/JSON 字符串,导致本地可解析而平台解析失败。
  • 执行环境差异:代码节点运行方式与本地脚本不同,尤其是对复杂对象、隐式类型转换的处理。

因此,一些常用的调试方法都在这里折戟沉沙。

提供一种调试思路

将错误信息,通过返回值传输出来。

调试案例

问题:coze显示变量的内容是string,但实际上是字典。(这不符合平常的程序员常识)

失败思路
  • 试图通过在本地使用传入上游的参数输入,然后使用print这种朴素调试手段尝试
  • 该代码本地通过,但是该段代码在Coze上失效,且无法打印,没有异常
def extract_urls_from_json():
    """
    从 JSON 文件中提取所有 URL 链接
    
    Args:
        file_path (str): JSON 文件路径
        
    Returns:
        list: 包含所有 URL 链接的列表
    """
    links = []
    inputs = []
    inputs.append(
        "{\"fields\":\"{\\\"clent\\\":[{\\\"text\\\":\\\"公众号\\\",\\\"type\\\":\\\"text\\\"}],\\\"url\\\":[{\\\"link\\\":\\\"https://mp.weixin.qq.com/s/7PKnof0acHcasb3ca_nMKQ\\\",\\\"text\\\":\\\"https://mp.weixin.qq.com/s/7PKnof0acHcasb3ca_nMKQ\\\",\\\"type\\\":\\\"url\\\"}]}\",\"record_id\":\"reclgXDdIk\"}"
    )
    inputs.append(
        "{\"fields\":\"{\\\"clent\\\":[{\\\"text\\\":\\\"公众号\\\",\\\"type\\\":\\\"text\\\"}],\\\"url\\\":[{\\\"link\\\":\\\"https://mp.weixin.qq.com/s/7PKnof0acHcasb3ca_nMKQ\\\",\\\"text\\\":\\\"https://mp.weixin.qq.com/s/7PKnof0acHcasb3ca_nMKQ\\\",\\\"type\\\":\\\"url\\\"}]}\",\"record_id\":\"reclgXDdIk\"}"
    )
    try:
        # 读取 JSON 文件
        for item in inputs:
            item_json = json.loads(item)
            fields_str = item_json.get('fields', '{}')
            try:
                fields_data = json.loads(fields_str)

                # 提取 url 数组中的链接
                url_list = fields_data.get('url', [])
                for url_item in url_list:
                    link = url_item.get('link')
                    if link:
                        links.append(link)

            except json.JSONDecodeError:
                print(
                    f"警告: 无法解析 record_id {item_json.get('record_id')} 的 fields 字段")
                continue
    except json.JSONDecodeError:
        print(f"错误: input 不是有效的 JSON 格式")
    except Exception as e:
        print(f"错误: 处理文件时发生异常 - {e}")

    return links
调试思路
  • 将错误信息通过返回值传输
def extract_urls_with_regex(inputs=None):
    """
    使用正则表达式从字符串中提取所有 URL 链接
    
    Args:
        inputs (list): 输入字符串列表,如果为None则使用默认数据
    
    Returns:
        dict: 包含返回码、消息和链接列表的字典
    """
    if inputs is None:
        inputs = []
        inputs.append(
            "{\"fields\":\"{\\\"clent\\\":[{\\\"text\\\":\\\"公众号\\\",\\\"type\\\":\\\"text\\\"}],\\\"url\\\":[{\\\"link\\\":\\\"https://mp.weixin.qq.com/s/7PKnof0acHcasb3ca_nMKQ\\\",\\\"text\\\":\\\"https://mp.weixin.qq.com/s/7PKnof0acHcasb3ca_nMKQ\\\",\\\"type\\\":\\\"url\\\"}]}\",\"record_id\":\"reclgXDdIk\"}"
        )
        inputs.append(
            "{\"fields\":\"{\\\"clent\\\":[{\\\"text\\\":\\\"公众号\\\",\\\"type\\\":\\\"text\\\"}],\\\"url\\\":[{\\\"link\\\":\\\"https://mp.weixin.qq.com/s/7PKnof0acHcasb3ca_nMKQ\\\",\\\"text\\\":\\\"https://mp.weixin.qq.com/s/7PKnof0acHcasb3ca_nMKQ\\\",\\\"type\\\":\\\"url\\\"}]}\",\"record_id\":\"reclgXDdIk\"}"
        )
    
    links = []
    
    # 检查输入是否为空
    if not inputs:
        return {
            'ret_code': 400,
            'ret_message': '输入数据为空',
            'links': links
        }
    
    # 定义 URL 正则表达式模式
    # 匹配 https:// 开头的 URL
    url_pattern = r'https://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,}(?:/[a-zA-Z0-9\-\._~:/\?#\[\]@!$&\'()*+,;=%]*)?'
    
    try:
        for item in inputs:
            # 使用正则表达式查找所有匹配的 URL
            found_urls = re.findall(url_pattern, item)
            
            # 过滤掉重复的 URL
            for url in found_urls:
                if url not in links:
                    links.append(url)
                    
    except Exception as e:
        return {
            'ret_code': 500,
            'ret_message': f'使用正则表达式提取 URL 时发生异常: {str(e)}',
            'links': links
        }
    
    # 检查是否匹配到URL
    if not links:
        return {
            'ret_code': 404,
            'ret_message': '未找到匹配的URL链接',
            'links': links
        }
    
    return {
        'ret_code': 200,
        'ret_message': f'成功提取到 {len(links)} 个URL链接',
        'links': links
    }
调试结果:
  • 最终通过返回值反馈,可以看出错误的原因:即coze显示变量的内容是string,但实际上是字典
  • 在这里插入图片描述
Logo

中国智能体开发者社区,聚焦智能体与大模型开发,提供前沿资讯、实用工具链、开源项目及行业案例。通过技术沙龙、开发者大赛等活动,促进经验交流与协作,助力开发者快速构建创新智能应用。

更多推荐