coze智能体后端接入问题:

是否一定要按照coze官方API文档格式调用?

不一定:以下面代码为例(给了注释)

python 复制代码
@app.route('/compare_models', methods=['POST'])
def compare_models():

    print("收到 compare_models 请求!")
#begin-这一部分代码作用:从前端接收参数  也就是前端输入的数据通过按钮发送
    data = request.json
    model1 = data.get('model1', '')
    model2 = data.get('model2', '')
    scene = data.get('scene', '')
    budget = data.get('budget', '')
    requirement = data.get('requirement', '')
#end-
    user_message = (
        f"请帮我综合对比两个大模型,并结合参数给出推荐和详细分析:\n"
        f"模型一:{model1}\n"
        f"模型二:{model2}\n"
        f"应用场景:{scene}\n"
        f"预算:{budget}元\n"
        f"性能要求:{requirement}\n"
        "请说明理由,逐条对比优劣,最后推荐一个更合适的模型,并说明推荐理由。请用自然语言详细分点方式直接文本回复,不要以插件或JSON结构返回,不要只给出总结。"
    )
    #begin- 构造Coze官方API所需的请求体(官方API调用文档:https://www.coze.cn/open/docs/developer_guides/chat)
    headers = {
        'Authorization': f'Bearer {COZE_API_KEY}',
        'Content-Type': 'application/json'
    }
    payload = {
        'bot_id': COZE_BOT_ID,
        'user': 'user_001',
        'query': user_message
    }
    #end-

    #begin- 用 requests转发到 Coze官方API
    response = requests.post(COZE_API_URL, headers=headers, json=payload)
    data = response.json()
    #end-

    #begin- 解析官方API的返回结果
    messages = data.get("messages", [])
    #end-

    print("COZE messages:", messages)

    collected_chunks = []
    final_reply = ""
    for msg in messages:
        raw_content = msg.get("content", "")
        try:
            parsed_outer = json.loads(raw_content)
            msg_type = parsed_outer.get("msg_type", "")
            inner_data_str = parsed_outer.get("data", "")
            if msg_type != "knowledge_recall":
                final_reply = parsed_outer.get("content", raw_content)
                break
            else:
                if inner_data_str:
                    parsed_inner = json.loads(inner_data_str)
                    chunks = parsed_inner.get("chunks", [])
                    if isinstance(chunks, list) and len(chunks) > 0:
                        for chunk in chunks:
                            collected_chunks.append(chunk.get("content", ""))
        except (ValueError, json.JSONDecodeError):
            final_reply = raw_content
            break

    if not final_reply and collected_chunks:
        final_reply = "".join(collected_chunks)
    if not final_reply:
        final_reply = "对不起,暂时无法获取有效回复。"

    # 结构化内容处理
    try:
        parsed = json.loads(final_reply)
        if isinstance(parsed, dict):
            if 'arguments' in parsed and 'keyword' in parsed['arguments']:
                final_reply = parsed['arguments']['keyword']
            elif 'content' in parsed:
                final_reply = parsed['content']
            else:
                final_reply = json.dumps(parsed, ensure_ascii=False, indent=2)
    except Exception:
        pass

    # 统一做文本清理
    final_reply = re.sub(r'(\^*来源[::]?.*?\^*)', '', final_reply, flags=re.IGNORECASE)
    final_reply = final_reply.strip()
    return jsonify({'reply': final_reply})
相关推荐
小园子的小菜1 天前
FastAPI 全方位入门实战:高性能 Python Web 框架开发指南
python·pycharm·fastapi
vx_Biye_Design1 天前
flask学生课程笔记共享系统29026-计算机课程设计、毕业设计
java·javascript·spring boot·后端·elasticsearch·flask·课程设计
小羊没烦恼!1 天前
Windows Azure Platform体验(1):Windows Azure
java·大数据·后端·python·flask·word·.net
天蓝蓝的本我4 天前
conda日常用到的命令积累1-登录linux,安装pycharm
linux·pycharm·conda
郝学胜-神的一滴4 天前
AI 编程智能体 05:拆解智能体分级体系、类型与全行业落地场景
开发语言·人工智能·python·程序人生·pycharm
昔我往昔5 天前
Blueprint和route的区别
flask
专业程序开发源5 天前
flask动漫推荐系统32319-计算机课程设计、毕业设计
java·spring boot·后端·django·flask·php·课程设计
VIP_CQCRE6 天前
Coze 接入大模型太麻烦?用 Ace Data Cloud 统一 OpenAI Responses API
ai·大模型·agent·coze·acedatacloud
qq_2518364577 天前
理发管理系统 —— 会员模块
开发语言·前端·python·flask
昔我往昔7 天前
init文件介绍
python·flask