Skip to main content

AI Agent Python SDK

让任何后台系统快速接入 AI 对话能力,用自然语言完成数据库增删改查。

安装

pip install mcp-ai-agent-sdk

快速开始

from mcp_ai_agent_sdk import AIAgentClient

# 1. 初始化客户端
client = AIAgentClient(
    api_key="your-deepseek-api-key",
    db_config={
        "host": "localhost",
        "port": 3306,
        "user": "root",
        "password": "xxx",
        "database": "mydb"
    }
)

# 2. 自动生成 Schema(或手动注册)
# ⚠️ 重要:使用AI对话前,必须确保Schema配置是最新的!
client.generate_schema_from_db()

# 3. 一行代码完成 AI 对话 + 数据库操作
result = client.ask_and_execute("查询所有学生")
print(result["message"])  # AI 总结的回复
print(result["data"])     # 查询结果

# 或启动 HTTP 服务供其他语言调用
client.run_server(port=8000)

功能特性

  • ✅ 自然语言操作 - 用中文描述需求,AI 自动生成 SQL 并执行
  • ✅ 智能名称匹配 - 自动处理中文数字(一→1)、大小写、模糊匹配
  • ✅ 成绩数据透视 - 自动将长格式转为宽格式,方便查看和导出
  • ✅ 流式对话 - 支持 SSE 流式输出,实时显示处理进度
  • ✅ 多语言支持 - Python 原生 + HTTP API 供 Java/PHP/Go/Node.js 调用
  • ✅ 安全可靠 - 增删改操作需确认后才执行

Docker 部署

Java/JavaScript 等其他语言可以通过 Docker 部署 Python SDK 服务:

# 1. 复制环境变量配置
cp .env.example .env
# 编辑 .env 填入你的配置

# 2. 启动服务
docker-compose up -d

# 服务启动后,其他语言通过 HTTP 调用
# POST http://localhost:8000/api/chat/stream - 流式对话
# POST http://localhost:8000/api/chat - 普通对话

环境变量

变量 说明 默认值
API_KEY DeepSeek API Key -
DB_HOST 数据库地址 localhost
DB_PORT 数据库端口 3306
DB_USER 数据库用户 root
DB_PASSWORD 数据库密码 -
DB_NAME 数据库名 -

核心 API

初始化

from mcp_ai_agent_sdk import AIAgentClient

client = AIAgentClient(
    api_key="your_api_key",           # 必填,DeepSeek API Key
    db_config={                        # 数据库配置
        "host": "localhost",
        "port": 3306,
        "user": "root",
        "password": "xxx",
        "database": "mydb"
    }
)

# 设置 Schema 文件路径(自动加载和保存)
client.set_schema_file("./schema.json")

ask_and_execute(message)

核心方法:一行代码完成 AI 对话 + 数据库操作。

result = client.ask_and_execute("查询高三1班数学成绩低于60分的学生")

print(result["message"])  # AI 总结的回复
print(result["data"])     # 查询结果列表
print(result["steps"])    # 执行的 SQL 步骤

process_chat_stream(message)

流式对话,返回 SSE 事件流,适用于 Web 聊天界面。

for event in client.process_chat_stream("查询学生"):
    yield event  # 用于 StreamingResponse

事件类型:

  • thinking - 处理进度(icon, text)
  • confirm - 需要用户确认(增删改操作)
  • done - 完成(message, data, step_results)

generate_schema_from_db()

从数据库自动生成 Schema。

⚠️ 重要提示:使用AI对话前,必须确保Schema配置是最新的!如果数据库结构发生变化(新增表、修改字段等),请重新生成Schema。

client.generate_schema_from_db()           # 快速生成
client.generate_schema_from_db(use_ai=True) # AI 分析(更准确但较慢)

register_schema(system_name, entities)

手动注册 Schema 配置。

client.register_schema(
    system_name="学生管理系统",
    entities=[
        {
            "name": "student",
            "description": "学生信息",
            "fields": {
                "id": {"type": "number", "label": "学生ID", "primaryKey": True},
                "name": {"type": "string", "label": "姓名", "required": True},
                "classId": {"type": "number", "label": "班级ID"}
            }
        }
    ]
)

run_server(port)

启动内置 HTTP 服务器。

client.run_server(port=8000)

# 自动提供以下 API:
# POST /api/chat/stream - 流式对话
# POST /api/chat - 普通对话
# GET  /api/schema - 获取 Schema
# POST /api/schema/register - 注册 Schema
# POST /api/schema/generate - 生成 Schema

智能特性

智能名称匹配

SDK 内置本地相似度匹配算法,自动处理用户输入的各种变体:

  • 中文数字转换:高一一班 → 高11班
  • 大小写统一:Stop → stop
  • 模糊匹配:相似度 ≥0.85 自动确认,0.7-0.85 标记不确定,<0.7 跳过

成绩数据透视

自动将成绩数据从长格式转换为宽格式:

# 原始数据(长格式)
张三, 语文, 90
张三, 数学, 85

# 透视后(宽格式)
张三, 语文:90, 数学:85

表格行数限制

前端表格默认显示 20 行,超出部分可下载 Excel 查看完整数据。

使用场景

1. 后台管理系统

from fastapi import FastAPI
from fastapi.responses import StreamingResponse

app = FastAPI()

@app.post("/api/ai/chat")
async def ai_chat(message: str):
    return StreamingResponse(
        client.process_chat_stream(message),
        media_type="text/event-stream"
    )

2. 命令行工具

while True:
    query = input("请输入指令: ")
    if query == 'exit':
        break
    result = client.ask_and_execute(query)
    print(result['message'])

3. 定制服务

SDK 支持定制服务模式,如教务助手:

# 在 education_ai_agent.py 中定义定制逻辑
def get_custom_analysis():
    return """
    ## 教务助手专属分析
    - 成绩数据智能分析
    - 优秀学生表彰
    - 需关注学生提醒
    - 教学建议
    """

安全说明

  1. API Key 保密 - 不要在前端代码中暴露
  2. 操作确认 - 增删改操作需用户确认后才执行
  3. SQL 安全 - 禁止 DROP、TRUNCATE 等危险操作

获取帮助

License

MIT License

Metadata

Release files for mcp-ai-agent-sdk 1.0.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for mcp-ai-agent-sdk 1.0.4
File Size Uploaded Provenance
mcp_ai_agent_sdk-1.0.4.tar.gz 31.9 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for mcp-ai-agent-sdk 1.0.4
File Interpreter ABI Platform
mcp_ai_agent_sdk-1.0.4-py3-none-any.whl Python 3 none any Details

Total release size: 61.5 kB

Release files / mcp_ai_agent_sdk-1.0.4.tar.gz

Download URL mcp_ai_agent_sdk-1.0.4.tar.gz
Size 31.9 kB
Tags Source
SHA-256 checksum
How to use checksums
3d4522ee73c00b4898c1349bfa21ec9b85815c2c9f806bc380c2a9d1b4f35754
BLAKE2b-256 checksum
How to use checksums
830a1383611f15aa41bba75fa16389cdc30e88b6c813cbf480d5fe83833f3669
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.6

Release files / mcp_ai_agent_sdk-1.0.4-py3-none-any.whl

Download URL mcp_ai_agent_sdk-1.0.4-py3-none-any.whl
Size 29.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
09f788f13d44f5d644731e79bfabf8fdb7558da9a3a5aeb9f9e9e6d4c9ee6080
BLAKE2b-256 checksum
How to use checksums
969686c907fd6c4180cf9d0025e07a9ec8b11dfdacbb32c17400187215f1d4bc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.6

Security for mcp-ai-agent-sdk 1.0.4

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page