AI Scaffold:面向 AI 应用开发的 Python 脚手架

AI2周前发布 beixibaobao
14 0 0

AI Scaffold

AI 应用开发脚手架 / AI application development scaffold
让开发者用 10 分钟启动一个可运行的 AI 应用项目,而不是从零搭建模型调用、工作流、配置、日志、数据库和工具集成。
Start a runnable AI application in 10 minutes, without rebuilding model integration, workflows, configuration, logging, databases, and tool orchestration from scratch.


目录 / Table of Contents

  • 一、这是什么? / What Is It?
  • 二、快速体验 / Quick Start
  • 三、架构总览 / Architecture Overview
  • 四、核心模块 / Core Modules
  • 五、快速上手 / Getting Started
  • 六、与传统脚手架对比 / Compared with Traditional Scaffolds
  • 七、配置文件参考 / Configuration Reference
  • 八、设计模式总结 / Design Patterns
  • 九、项目模板 / Project Template
  • 十、适用场景 / Use Cases
  • 十一、风险与待补充项 / Risks and Future Work
  • 十二、总结 / Summary

一、这是什么? / What Is It?

AI Scaffold 是一个面向 AI 应用开发的 Python 脚手架,提供一套完整的基础设施抽象层、工作流引擎和 CLI 工具链。

AI Scaffold is a Python scaffold for AI application development. It provides a practical foundation layer, a workflow engine, and a CLI toolchain for building AI applications faster.

它重点解决的问题是:AI 应用从原型到工程化落地时,开发者经常要重复处理 LLM 接入、工作流编排、数据持久化、工具调用、配置管理和项目模板等基础问题。

The core problem it solves is repeated engineering work. When an AI prototype grows into a real application, developers usually need to rebuild LLM adapters, workflow orchestration, data persistence, tool calling, configuration management, logging, and project templates again and again.

问题 / Problem 传统做法 / Traditional Approach AI Scaffold 的做法 / AI Scaffold Approach
LLM 集成 / LLM integration 每个模型写一套调用代码 / Write separate integration code for each model 统一 BaseReasoningEngine 抽象,一行配置切换模型 / Use a unified BaseReasoningEngine abstraction and switch models by configuration
AI 工作流 / AI workflow 手写多线程、回调和状态机 / Manually write threads, callbacks, and state machines 声明式 DAG 编排,自动处理并行和状态 / Declarative DAG orchestration with built-in parallelism and state handling
数据持久化 / Data persistence 每个项目重新搭数据库层 / Rebuild a database layer for every project 内置 Repository 层,支持 MySQL、PostgreSQL、SQLite / Built-in Repository layer with MySQL, PostgreSQL, and SQLite support
第三方服务 / External services 调用逻辑散落在各处 / Service calls scattered across the codebase 统一 Tool 封装,Agent 可发现和使用 / Unified Tool abstraction that Agents can discover and use
项目启动 / Project bootstrap 从零搭目录结构、依赖和配置 / Set up structure, dependencies, and config from scratch ric create 一键生成可运行项目 / Generate a runnable project with ric create

设计理念 / Design Philosophy

零配置启动 -> 渐进式增强 -> 模块即插即用 -> 声明式工作流
Zero-config startup -> Progressive enhancement -> Plug-and-play modules -> Declarative workflows

AI Scaffold 的目标不是替代 LangChain、LangGraph 或 Vercel AI SDK,而是在这些能力之上提供更靠近业务开发者的工程脚手架层。

AI Scaffold is not designed to replace LangChain, LangGraph, or the Vercel AI SDK. Instead, it provides a business-oriented scaffolding layer on top of these capabilities.


二、快速体验 / Quick Start

# 安装 / Install
pip install ric-scaffold
# 创建项目 / Create a project
ric create my-ai-app
# 启动。默认使用 SQLite,并可在无 API Key 的情况下运行基础示例。
# Run. By default, it uses SQLite and can run a basic example without an API key.
cd my-ai-app
ric run

浏览器打开 / Open in your browser:

http://localhost:8000

如果项目创建成功,AI 应用服务应已经启动。

If the project is created successfully, the AI application service should now be running.


三、架构总览 / Architecture Overview

+--------------------------------------------------------------+
|                    用户界面 / User Interface                  |
|              REST API / WebSocket / CLI / Stream             |
+--------------------------------------------------------------+
|                                                              |
|  +------------------+      +-------------------------------+ |
|  | 编排层            |      | 工作流引擎                     | |
|  | Orchestration    |      | Workflow Engine               | |
|  | Agent 调度        |      | DAG / Parallel / Branching     | |
|  | Pipeline 管理     |      | Auto Loading / State Mgmt      | |
|  +------------------+      +-------------------------------+ |
|                                 /                            |
|                                /                             |
|          +----------------------------------+                 |
|          | LLM 推理层 / LLM Reasoning Layer |                 |
|          | BaseReasoningEngine              |                 |
|          | Qwen / DeepSeek / OpenAI / Local |                 |
|          +----------------------------------+                 |
|                     |                                        |
|  +----------+  +------------+  +----------+  +-------------+  |
|  | Tool 层  |  | Memory 层  |  | Cache 层 |  | Storage 层  |  |
|  | Tools    |  | Memory     |  | Cache    |  | Storage     |  |
|  | Mail/API |  | Chat/Vec   |  | Redis    |  | MySQL/MinIO |  |
|  +----------+  +------------+  +----------+  +-------------+  |
|                                                              |
|  +----------------------------------------------------------+ |
|  | 配置管理 / 日志 / 监控                                   | |
|  | Configuration / Logging / Monitoring                     | |
|  +----------------------------------------------------------+ |
+--------------------------------------------------------------+

三层架构 / Three-Layer Architecture

层级 / Layer 关注点 / Responsibility 核心模块 / Core Modules
编排层 / Orchestration layer 负责“做什么” / Defines what to do Agent 调度器、Workflow 引擎、Pipeline 管理器 / Agent scheduler, Workflow engine, Pipeline manager
推理层 / Reasoning layer 负责“怎么想” / Defines how to reason LLM 抽象层、Prompt 管理、Guardrails / LLM abstraction, Prompt management, Guardrails
基础设施层 / Infrastructure layer 负责“如何稳定运行” / Keeps the system running reliably 数据库、缓存、存储、工具、配置、日志、监控 / Database, cache, storage, tools, config, logging, monitoring

四、核心模块 / Core Modules

4.1 Core:基础设施 / Infrastructure

配置管理 / Configuration Management

配置系统基于 Pydantic Settings,支持从 .env 文件自动加载,并按环境分层合并。

The configuration system is based on Pydantic Settings. It can load values from .env files and merge environment-specific overrides.

from ric_scaffold.config import settings
db_host = settings.db.host
llm_api_key = settings.llm.api_key

推荐的配置文件层级 / Recommended configuration layers:

.env             -> 基础配置,所有环境共享 / Shared base configuration
.env.local       -> 本地覆盖,不提交到 Git / Local overrides, not committed to Git
.env.production  -> 生产配置,不提交到 Git / Production overrides, not committed to Git
日志系统 / Logging

内置开箱即用的日志配置 / Built-in logging features:

  • 彩色控制台输出,方便本地开发。 / Colored console output for local development.
  • 按天轮转文件日志,适合生产环境。 / Daily rotating file logs for production.
  • ERROR 级别日志单独落盘,便于监控和排障。 / Dedicated ERROR logs for monitoring and troubleshooting.
from ric_scaffold.config import logger
logger.info("推理请求开始")
logger.error("LLM 调用超时", exc_info=True)
工具函数库 / Utility Library
模块 / Module 功能 / Capability
utils.file 文件操作、临时文件管理 / File operations and temporary file management
utils.path 项目根目录自动发现 / Project root discovery
utils.date 日期时间格式化 / Date and time formatting
utils.data 数据处理、差异计算、哈希、安全序列访问 / Data processing, diff calculation, hashing, safe sequence access
utils.http HTTP 响应封装,支持链式调用 / HTTP response helpers with chainable APIs
utils.decorator 重试、超时、前置条件检查等通用装饰器 / Decorators for retry, timeout, and precondition checks
utils.pdf PDF 文本提取 / PDF text extraction
utils.audio FFmpeg 封装、音频切片、时长获取 / FFmpeg wrappers, audio slicing, duration reading
utils.doc Word 文档生成,支持 Jinja2 模板渲染 / Word document generation with Jinja2 templates
utils.reflection 基于标记的函数自动发现和加载 / Marker-based function discovery and loading

4.2 LLM:推理抽象层 / Reasoning Abstraction

LLM 模块是脚手架的核心。它将不同模型供应商的 API 差异封装在统一接口之下。

The LLM module is the core of the scaffold. It hides provider-specific API differences behind a unified interface.

核心接口 / Core Interface
from abc import ABC
from typing import Generator
class BaseReasoningEngine(ABC):
    """推理引擎:AI 应用的“大脑”抽象。"""
    def reason(self, prompt: str, **kwargs) -> str:
        """同步推理。"""
    async def areason(self, prompt: str, **kwargs) -> str:
        """异步推理。"""
    def stream(self, prompt: str, **kwargs) -> Generator[str, None, None]:
        """流式推理。"""
    def chat(self, messages: list, **kwargs) -> str:
        """多轮对话。"""
支持的推理引擎 / Supported Engines
BaseReasoningEngine
├── QwenEngine       # 通义千问 / Qwen via DashScope
├── DeepSeekEngine   # DeepSeek
├── OpenAIEngine     # OpenAI GPT 系列 / OpenAI GPT models
├── LocalEngine      # 本地模型 / Local models, Ollama or llama.cpp
└── RuleEngine       # 规则引擎 / Rule-based engine for simple non-LLM scenarios
一行配置切换模型 / Switch Models by Configuration
from ric_scaffold.llm import get_engine
engine = get_engine()
result = engine.reason("讲一个适合程序员的笑话")

.env 中只需要切换 LLM_ENGINE / Switch LLM_ENGINE in .env:

LLM_ENGINE=qwen
# LLM_ENGINE=deepseek
# LLM_ENGINE=openai
# LLM_ENGINE=local
消息类型 / Message Types
from ric_scaffold.llm import SystemMsg, UserMsg, AssistantMsg
messages = [
    SystemMsg("你是一个专业的翻译助手"),
    UserMsg("翻译成中文:Hello, world!"),
]
response = engine.chat(messages)

4.3 Workflow:工作流引擎 / Workflow Engine

Workflow 模块基于 LangGraph 构建声明式工作流引擎,支持 DAG 编排、并行节点、条件分支和自动加载。

The Workflow module builds a declarative workflow engine on top of LangGraph. It supports DAG orchestration, parallel nodes, conditional branches, and automatic loading.

声明式工作流定义 / Declarative Workflow Definition
from ric_scaffold.workflow import BaseWorkFlow
node_list = [
    ["extract_info", "process_audio"],      # 第一层并行 / First parallel layer
    ["analyze", "evaluate", "summarize"],   # 第二层并行 / Second parallel layer
    "generate_output",                      # 最终串行 / Final sequential step
]
wf = BaseWorkFlow(node_list=node_list, state_schema=MyState)
result = wf.invoke(input_data)
节点实现 / Node Implementation
from ric_scaffold.workflow import graph_node
@graph_node(description="从输入中提取关键信息")
def extract_info(state: MyState):
    info = extract_from_text(state.raw_input)
    return {"extracted": info}
@graph_node(description="分析提取的信息")
def analyze(state: MyState):
    result = llm.reason(f"分析以下内容:{state.extracted}")
    return {"analysis": result}
节点类型 / Node Types
类型 / Type 语法 / Syntax 行为 / Behavior
普通节点 / Normal node "node_name" 单个函数顺序执行 / Run a single function sequentially
并行节点 / Parallel node ["a", "b", "c"] 组内所有节点同时执行 / Run all nodes in the group concurrently
条件节点 / Conditional node ("node", "condition", {...}) 根据条件结果决定下一条路径 / Route to the next path based on condition output
自动加载机制 / Auto Loading
@graph_node
def my_node(state):
    """该函数会被自动注册到工作流引擎。"""
    ...
@edge_condition
def my_condition(state):
    """该函数会被自动注册为边条件。"""
    return "next_node" if state.flag else "fallback"
YAML 工作流配置 / YAML Workflow Configuration
workflow:
  name: data_pipeline
  state: MyState
  nodes:
    - id: extract
      function: my_module.extract
    - id: transform
      function: my_module.transform
    - id: load
      function: my_module.load
  edges:
    - from: extract
      to: transform
    - from: transform
      to: load
from ric_scaffold.workflow import WorkflowLoader
wf = WorkflowLoader.load("workflow.yaml")
wf.invoke(state)

4.4 Repository:数据访问层 / Data Access Layer

Repository 模块提供统一的数据访问接口,支持多种数据库。

The Repository module provides a unified data access interface with support for multiple databases.

架构 / Structure
BaseConnection
├── MySQLConnection        # MySQL,连接池可基于 DBUtils / MySQL, connection pool via DBUtils
├── PostgreSQLConnection   # PostgreSQL
└── SQLiteConnection       # SQLite,支持 :memory: 模式 / SQLite with :memory: support
BaseDBModel
└── save / get_by_id / update / delete / find_by / count
ConnectionManager
└── register / get / get_default / close_all
ORM 风格操作 / ORM-Style Operations
from typing import Optional
from ric_scaffold.repository import BaseDBModel
class User(BaseDBModel):
    table_alias = "users"
    id: Optional[int] = None
    name: str
    email: str
user = User(name="Alice", email="alice@example.com")
user.save()
found = User.get_by_id(1)
users = User.find_by(name="Alice")
自动数据库适配 / Automatic Database Selection

当未配置数据库连接信息时,默认使用 SQLite 内存模式,保证零配置可运行。配置 MySQL 或 PostgreSQL 环境变量后,连接管理器可自动切换到对应数据库。

If no database connection is configured, AI Scaffold uses in-memory SQLite by default so the project can run with zero configuration. When MySQL or PostgreSQL environment variables are provided, the connection manager can switch to the corresponding database automatically.

4.5 Tools:工具层 / Tool Layer

Tool 是 Agent 与外部世界交互的统一方式。

Tools provide a unified way for Agents to interact with external systems.

from ric_scaffold.tools import tool
@tool(
    name="send_email",
    description="发送邮件",
    params={
        "to": "收件人邮箱",
        "subject": "邮件主题",
        "body": "邮件内容",
    },
)
def send_email(to: str, subject: str, body: str) -> dict:
    ...

内置工具 / Built-in tools:

工具 / Tool 功能 / Capability
tools.email 邮件发送,基于 SMTP,支持附件 / SMTP email sending with attachment support
tools.redis Redis 缓存操作 / Redis cache operations
tools.storage 文件存储,支持 MinIO 和本地文件 / File storage with MinIO and local file support
tools.db_query 受限数据库查询 / Restricted database query tool

五、快速上手 / Getting Started

第一步:安装 / Step 1: Install

pip install ric-scaffold

第二步:创建项目 / Step 2: Create a Project

ric create my-first-ai-app
cd my-first-ai-app

第三步:编写工作流 / Step 3: Write a Workflow

from ric_scaffold.workflow import BaseWorkFlow, graph_node
from ric_scaffold.workflow.state import BaseState
class MyState(BaseState):
    input_text: str = ""
    output: str = ""
@graph_node
def process_input(state: MyState):
    return {"output": f"处理结果:{state.input_text}"}
wf = BaseWorkFlow(
    node_list=["process_input"],
    state_schema=MyState,
)
state = MyState(input_text="你好,世界!")
wf.invoke(state)
print(state.output)

第四步:启动服务 / Step 4: Run the Service

ric run

六、与传统脚手架对比 / Compared with Traditional Scaffolds

架构范式变化 / Architecture Shift

传统 Web 应用 / Traditional web application:
Model -> View -> Controller
AI 应用 / AI application:
Reasoning -> Agent -> Execution -> Context
维度 / Dimension 传统脚手架 / Traditional Scaffolds, Django or Spring AI Scaffold
核心抽象 / Core abstraction 数据库 ORM / Database ORM 推理引擎 / Reasoning Engine
业务流程 / Business flow Controller -> Service -> DAO Agent -> Tool -> LLM
状态管理 / State management Session / JWT 记忆管理层,短期 / 长期 / 向量 / Memory layer: short-term, long-term, vector
扩展方式 / Extension model 中间件 / 插件 / Middleware or plugins Tool 注册 / Agent 编排 / Tool registration and Agent orchestration
配置重心 / Configuration focus 数据库连接、缓存、消息队列 / Database, cache, message queue 模型选择、API Key、Prompt 模板 / Model selection, API keys, prompt templates
部署关注 / Deployment concerns WSGI / ASGI 服务 / WSGI or ASGI server 流式输出、Token 用量、缓存策略 / Streaming, token usage, cache strategy

七、配置文件参考 / Configuration Reference

# ============================
# 数据库配置。留空则使用 SQLite。
# Database configuration. Leave empty to use SQLite.
# ============================
DB_HOST=
DB_PORT=3306
DB_USER=
DB_PASSWORD=
DB_NAME=
# ============================
# LLM 配置 / LLM configuration
# ============================
LLM_ENGINE=qwen
LLM_TIMEOUT=30
# 通义千问 / Qwen
QWEN_BASE_URL=https://dashscope.aliyuncs.com/compatible-mode/v1
QWEN_DEFAULT_MODEL=qwen-plus
DASHSCOPE_API_KEY=sk-xxx
# DeepSeek
DEEPSEEK_BASE_URL=https://api.deepseek.com
DEEPSEEK_DEFAULT_MODEL=deepseek-chat
DEEPSEEK_API_KEY=sk-xxx
# OpenAI
OPENAI_BASE_URL=https://api.openai.com/v1
OPENAI_DEFAULT_MODEL=gpt-4.1-mini
OPENAI_API_KEY=sk-xxx
# ============================
# 缓存,Redis / Cache, Redis
# ============================
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_DB=0
# ============================
# 存储,MinIO / Storage, MinIO
# ============================
MINIO_ENDPOINT=127.0.0.1:9000
MINIO_ACCESS_KEY=minioadmin
MINIO_SECRET_KEY=minioadmin
# ============================
# 日志 / Logging
# ============================
LOG_LEVEL=INFO

八、设计模式总结 / Design Patterns

设计模式 / Pattern 应用位置 / Where It Is Used 说明 / Description
抽象工厂 / Abstract Factory LLM 引擎层 / LLM engine layer BaseReasoningEngineQwenEngineDeepSeekEngine 等实现 / Maps BaseReasoningEngine to concrete engines
工厂方法 / Factory Method 节点工厂 / Node factory NodeFactory.create_node() 根据类型创建节点实例 / Creates node instances by type
单例模式 / Singleton 配置管理、连接管理器 / Configuration and connection managers 全局唯一 settingsConnectionManager / Global settings and ConnectionManager
装饰器模式 / Decorator @graph_node@edge_condition 对函数进行标记、增强和注册 / Marks, enhances, and registers functions
策略模式 / Strategy 工作流条件节点 / Conditional workflow nodes 条件分支决定执行路径 / Branching logic chooses execution paths
仓储模式 / Repository Repository 层 / Repository layer 统一数据访问接口 / Unified data access interface
自动加载 / Auto Loading _loader.py 和反射工具 / _loader.py and reflection utilities 通过装饰器标记自动发现并注册函数 / Discovers and registers decorated functions automatically

九、项目模板 / Project Template

ric create 默认生成以下项目结构 / ric create generates the following project structure by default:

my-ai-app/
├── app/
│   ├── __init__.py
│   ├── nodes.py              # 工作流节点定义 / Workflow node definitions
│   ├── conditions.py         # 条件定义 / Condition definitions
│   └── config.py             # 应用配置 / Application configuration
├── .env                      # 环境变量 / Environment variables
├── .env.template             # 环境变量模板 / Environment variable template
├── Dockerfile                # Docker 构建 / Docker build
├── docker-compose.yml        # Docker 编排 / Docker Compose
├── requirements.txt          # 依赖 / Dependencies
├── pyproject.toml            # 项目元信息 / Project metadata
└── README.md                 # 项目说明 / Project documentation

十、适用场景 / Use Cases

  • 智能客服系统 / Intelligent customer service: Agent 编排、RAG、工具调用和多轮对话。 / Agent orchestration, RAG, tool calling, and multi-turn conversation.
  • 文档分析工具 / Document analysis tools: 多步骤文档解析、摘要、评估和报告生成。 / Multi-step document parsing, summarization, evaluation, and report generation.
  • AI 工作流引擎 / AI workflow engines: 用声明式节点编排复杂任务链。 / Orchestrate complex task chains with declarative nodes.
  • 多模型聚合 API / Multi-model aggregation API: 以统一接口接入多个 LLM 供应商。 / Connect multiple LLM providers through a unified interface.
  • 快速原型验证 / Rapid prototyping: 零配置启动,快速验证产品想法。 / Start with zero configuration and validate product ideas quickly.

十一、风险与待补充项 / Risks and Future Work

为了让 AI Scaffold 更适合生产级 AI 应用,建议后续补充以下能力说明。

To make AI Scaffold more suitable for production-grade AI applications, the following areas should be clarified or expanded.

方向 / Area 建议补充 / Suggested Improvement
Agent 机制 / Agent mechanism 说明 Agent 如何选择工具、规划步骤、处理失败和避免无限循环 / Explain how Agents select tools, plan steps, handle failures, and avoid infinite loops
Memory 层 / Memory layer 明确短期记忆、长期记忆、向量记忆的存储接口和生命周期 / Define storage interfaces and lifecycles for short-term, long-term, and vector memory
Workflow 稳定性 / Workflow reliability 补充节点超时、重试、失败回滚、状态合并和幂等策略 / Add timeout, retry, rollback, state merge, and idempotency strategies
安全治理 / Security and governance 增加 API Key 管理、Tool 权限、Prompt 注入防护、审计日志 / Add API key management, tool permissions, prompt-injection protection, and audit logs
数据访问 / Data access 明确自研 Repository 与 SQLAlchemy、Alembic 等成熟工具的边界 / Clarify the boundary between the custom Repository layer and mature tools such as SQLAlchemy and Alembic
测试示例 / Testing examples 提供最小可运行示例、单元测试和集成测试模板 / Provide a minimal runnable example, unit tests, and integration test templates
部署方案 / Deployment 补充 Docker Compose、生产环境配置和可观测性说明 / Add Docker Compose, production configuration, and observability guidance

十二、总结 / Summary

AI Scaffold 的价值在于把 AI 应用开发中高度重复的底座能力抽象出来,让业务开发者更快进入“业务逻辑 + 工作流 + 模型能力组合”的核心开发阶段。

AI Scaffold extracts the repetitive foundation work in AI application development, so developers can focus sooner on business logic, workflow design, and model capability composition.

如果后续能补齐 Agent、Memory、安全、测试和部署方面的细节,它可以从“快速原型脚手架”进一步演进为更完整的 AI 应用工程化框架。

With stronger Agent, Memory, security, testing, and deployment guidance, AI Scaffold can grow from a rapid prototyping scaffold into a more complete engineering framework for AI applications.

© 版权声明

相关文章