Harness 与 Agent 工程 · Agent架构与协作 · 2025-11-20

一个销售数据分析机器人的诞生:看 Dify 如何在 DMS 助力下实现自动化闭环

Dify 与 DMS 的强强联合,打造企业级 AI 应用开发新范式,实现从开发到调度的全链路闭环。

核心内容:

  1. Dify 原生能力的局限与挑战
  2. DMS Notebook 和 DMS Airflow 如何增强 Dify 功能
  3. 销售数据分析机器人的完整开发案例

背景与挑战

dify 作为一款低代码 AI 应用开发平台,凭借其直观的可视化工作流编排能力,极大降低了大模型应用的开发门槛。然而,在实际企业级落地过程中,我们发现其原生能力仍存在两个关键瓶颈:

这两个问题严重制约了 Dify 在生产环境中的深度应用——尤其当我们希望构建一个具备“感知-决策-执行-反馈”闭环能力的智能 Agent 时,仅靠 Dify 自身往往力不从心。为突破这些限制,我们在实践中探索出一套 “Dify + DMS Notebook + DMS Airflow”三位一体的一站式增强开发架构,有效补齐了 Dify 在执行能力与调度能力上的短板:

本文将以一个销售数据分析机器人的完整开发案例,详细介绍如何基于 DMS 平台,构建一个可调度、可扩展、可运维的 Agent 系统。使用 DMS Notebook 扩展 Dify 的代码执行能力

为什么需要 Notebook?

在 Dify 中,若需调用 Pandas 进行数据清洗、使用 Prophet 做时间序列预测,或集成企业内部 SDK,Sandbox 节点往往无能为力。而 DMS Notebook 提供了完整的 Python 环境,支持:

这使其成为 Dify 外部能力扩展的理想“执行单元”。步骤详解:构建一个销售数据分析 API 服务

1.创建 DMS Notebook 会话

💡 踩坑提示:若未设置 DMS_KERNEL_IDLE_TIMEOUT=0,长时间运行的 API 服务可能在空闲数分钟后被系统回收,导致后续调用失败。

2.编写并启动 FastAPI 服务

点击文件夹图标,右键点击default(默认库),再点击新建Notebook文件。

import osfrom fastapi import FastAPI, HTTPException, Request, File, UploadFile, Path, Query, Form, Headerfrom fastapi.staticfiles import StaticFilesfrom typing import Optionalimport nest_asyncioimport asyncioimport httpximport io'''注意,Jupyter本身就在一个asyncio事件循环中运行。我们不能在已有循环中直接运行另一个循环,但nest_asyncio这个库可以“打补丁”,允许我们这样做。'''nest_asyncio.apply()app = FastAPI(title="Your Service Name", description="Description of Your Service")# 创建static目录(如果不存在)static_dir = "static"ifnot os.path.exists(static_dir): os.makedirs(static_dir)# 挂载静态文件服务app.mount("/static", StaticFiles(directory=static_dir), name="static")@app.get("/")async def root(): """ 根节点,返回服务基本信息 # --- 如何使用 curl 调用 --- curl -X GET "http://127.0.0.1:8000/" """ return { "message": "Service is running", "documentation": "/docs", "note": "..." }@app.post("/process-data/{item_id}")async def process_data( request: Request, # 使用 Request 对象来接收原始请求 # 路径参数 item_id: int = Path(..., title="物品ID", ge=1), # 查询参数 is_premium: bool = Query(False, description="是否为高级物品"), # 请求头参数 x_token: Optional[str] = Header(None, description="自定义的认证Token")): """ 接收 JSON 请求体、路径参数、查询参数和请求头。 # --- 如何使用 curl 调用 --- # -X POST: 指定请求方法 # URL: 包含路径参数 {item_id} 和查询参数 ?is_premium=true # -H: 添加请求头 (Header) # -d: 发送请求体 (Body),这里是 JSON 字符串 curl -X POST "http://127.0.0.1:8000/process-data/101?is_premium=true" \ -H "Content-Type: application/json" \ -H "X-Token: my-secret-token" \ -d '{"name": "笔记本电脑", "price": 7999.9, "tags": ["electronics", "office"]}' """ if x_token != "my-secret-token": raise HTTPException(status_code=401, detail="X-Token 无效") try: # 手动解析 JSON 请求体 json_body = await request.json() name = json_body.get("name") price = json_body.get("price") # 你的业务逻辑代码 if not name or not price: raise HTTPException(status_code=400, detail="请求体中缺少 'name' 或 'price'") return { "message": "数据处理成功", "received_data": { "item_id": item_id, "is_premium": is_premium, "x_token": x_token, "body": json_body } } except Exception as e: raise HTTPException(status_code=500, detail=f"服务执行错误: {str(e)}")@app.post("/upload-file")async def upload_file( # 表单数据 token: str = Form(...), # 上传文件 file: UploadFile = File(...)): """ 通过表单(form-data)上传文件和附带的文本信息。 # --- 如何使用 curl 调用 --- # -F: 用于发送 multipart/form-data # -F "file=@/path/to/your/file.txt": @符号表示后面是文件路径,curl会读取该文件内容作为上传数据 # -F "token=user123": 发送一个名为 token 的表单字段 # 注意: 请将 /path/to/your/file.txt 替换为你的本地文件真实路径 curl -X POST "http://127.0.0.1:8000/upload-file" \ -F "file=@./test_upload.txt" \ -F "token=my-form-token" """ # 为了让curl示例能工作,我们先创建一个示例文件 if not os.path.exists("test_upload.txt"): with open("test_upload.txt", "w") as f: f.write("This is a test file for curl upload.") try: contents = await file.read() file_location = os.path.join(static_dir, file.filename) with open(file_location, "wb") as f: f.write(contents) return { "message": "文件上传成功!", "token": token, "filename": file.filename, "file_size": len(contents), "file_url": f"/static/{file.filename}" } except Exception as e: raise HTTPException(status_code=500, detail=f"文件处理错误: {str(e)}")@app.get("/status")async def get_server_status(): """ 获取服务器状态。 # --- 如何使用 curl 调用 --- curl -X GET "http://127.0.0.1:8000/status" """ return {"status": "running"}async def run_server(host="127.0.0.1", port=8000): """在后台运行uvicorn服务器""" import uvicorn config = uvicorn.Config(app, host=host, port=port, log_level="info") server = uvicorn.Server(config) # uvicorn.run() 是一个阻塞调用,所以我们用更底层的Server.serve() await server.serve()task = asyncio.create_task(run_server(host="0.0.0.0", port=8000))# 等待服务启动await asyncio.sleep(2)# 创建一个异步HTTP客户端async with httpx.AsyncClient() as client: print("正在向 http://127.0.0.1:8000/status/ 发送请求...") # 发送POST请求 response = await client.get("http://127.0.0.1:8000/status") # 打印结果 if response.status_code == 200: print("服务启动成功") else: print("服务启动失败,请检查报错信息")
import osimport pandas as pdfrom fastapi import FastAPI, HTTPException, Request, File, UploadFilefrom fastapi.staticfiles import StaticFilesimport nest_asyncioimport asyncioimport httpximport io'''注意,Jupyter本身就在一个asyncio事件循环中运行。我们不能在已有循环中直接运行另一个循环,但nest_asyncio这个库可以“打补丁”,允许我们这样做。'''nest_asyncio.apply()app = FastAPI(title="Sales Data Analysis Service", description="Provides data analysis and chart generation capabilities for Dify")# 创建static目录(如果不存在)static_dir = "static"ifnot os.path.exists(static_dir): os.makedirs(static_dir)# 挂载静态文件服务app.mount("/static", StaticFiles(directory=static_dir), name="static")def load_sales_data_from_file(file_content: bytes): """从上传的文件内容加载销售数据""" try: # 将字节内容转换为StringIO对象 csv_string = file_content.decode('utf-8') df = pd.read_csv(io.String…
— 以上为试看内容(约 40%),开通会员后阅读全文 —

原文出处:https://www.53ai.com/news/zhinengyingxiao/2025112057631.html