AI Agent 接受自然语言提问,自动写 SQL、执行查询、生成图表和报告。

适用场景

Data teams that get ad-hoc analysis requests from non-technical stakeholders and want to automate 60-80% of routine queries.

前提条件

Dify with code execution enabled, read-only database access, OpenAI/Claude API key

工作流图

用 Dify 搭建自主数据分析 Agent

Database Connection
Agent Configuration
Query Safety Layer
Visualization Generation
Report Output

分步指南

  1. 1

    Database Connection

    In Dify, add a database tool connection. Provide your PostgreSQL/MySQL connection string. Configure read-only access to prevent accidental writes. Set a row limit of 10,000 to prevent memory issues.

  2. 2

    Agent Configuration

    Create a new Agent app with ReAct (Reasoning + Acting) mode. Add the database tool and a code execution tool. Set the system prompt: 'You are a data analyst. When given a question, write SQL, execute it, analyze the results, and provide insights. Always explain your SQL logic before running it.'

  3. 3

    Query Safety Layer

    Add a pre-processing Code node that validates the SQL query before execution. Block DROP, DELETE, UPDATE, INSERT statements. Add a timeout of 30 seconds per query. Log all queries for audit.

  4. 4

    Visualization Generation

    After the agent gets query results, use a Code node to generate a chart using a JavaScript charting library (e.g., Chart.js). Convert the chart to a base64 image and embed it in the response.

  5. 5

    Report Output

    Format the final output as a structured report: 1) Executive summary, 2) SQL query used, 3) Data table (top 20 rows), 4) Chart visualization, 5) Key insights (3-5 bullet points), 6) Recommended actions. Save to your knowledge base for future reference.

标签

#data-analysis#agent#sql#dify#automation