Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 AgentFlow Contributors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
14 changes: 9 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<div align="center">

![AgentFlow](https://img.shields.io/badge/AgentFlow-v2.0.1-6366F1?style=for-the-badge&logo=robot&logoColor=white)
![AgentFlow](https://img.shields.io/badge/AgentFlow-v2.0.2-6366F1?style=for-the-badge&logo=robot&logoColor=white)
[![Python](https://img.shields.io/badge/Python-3.11+-3776AB.svg?style=flat-square&logo=python&logoColor=white)](https://python.org)
[![FastAPI](https://img.shields.io/badge/FastAPI-0.109-009688.svg?style=flat-square&logo=fastapi&logoColor=white)](https://fastapi.tiangolo.com)
[![React](https://img.shields.io/badge/React-18-61DAFB.svg?style=flat-square&logo=react&logoColor=white)](https://react.dev)
Expand Down Expand Up @@ -127,16 +127,20 @@ Skill 运行时支持 OpenAI 兼容网关,可在 `.env` 中配置 `CHATZOC_*`
| Redis | 7+ |
| Docker(推荐) | 20+ |

### Docker 一键部署(推荐)
### Docker 一键部署(推荐,内网演示)

```bash
git clone https://github.com/PHclaw/agentflow.git
cd agentflow
cp .env.example .env # 编辑填入 API Keys
docker-compose up -d
open http://localhost:3000
cp .env.example .env # 必填:JWT_SECRET_KEY、OPENAI_API_KEY(或 CHATZOC_* / DASHSCOPE_*)
docker compose up --build
# 前端 http://localhost:3000 后端 http://localhost:8001
```

**内网可用流程**:注册账号 → 登录(自动进入 `/skills`)→ 选择 Skill → 上传/粘贴内容 → 下载 `/static/generated/*` 生成物。

> **规划中(当前版本未完整实现)**:Stripe 订阅计费、Google OAuth、Browser-Use、Ollama 本地模型。

### 本地开发

```bash
Expand Down
107 changes: 63 additions & 44 deletions backend/app/api/agent_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,19 @@
from app.core.database import get_db
from app.api.auth import get_current_user_id

router = APIRouter()
router = APIRouter(dependencies=[Depends(get_current_user_id)])
logger = get_logger("agent_routes")


async def _require_agent(agent_id: str, user_id: str, db: AsyncSession) -> Agent:
agent = await db.get(Agent, agent_id)
if not agent:
raise HTTPException(status_code=404, detail="Agent 不存在")
if agent.user_id != user_id:
raise HTTPException(status_code=403, detail="无权访问此 Agent")
return agent


# ===== 请求/响应模型 =====

class AgentStatsResponse(BaseModel):
Expand Down Expand Up @@ -50,11 +59,13 @@ class AgentExportResponse(BaseModel):
# ===== Agent 统计 API =====

@router.get("/{agent_id}/stats", response_model=AgentStatsResponse)
async def get_agent_stats(agent_id: str, db: AsyncSession = Depends(get_db)):
async def get_agent_stats(
agent_id: str,
db: AsyncSession = Depends(get_db),
user_id: str = Depends(get_current_user_id),
):
"""获取 Agent 使用统计"""
agent = await db.get(Agent, agent_id)
if not agent:
raise HTTPException(status_code=404, detail="Agent 不存在")
agent = await _require_agent(agent_id, user_id, db)

# 查询会话统计
stats = await db.execute(
Expand Down Expand Up @@ -91,11 +102,13 @@ async def get_agent_stats(agent_id: str, db: AsyncSession = Depends(get_db)):


@router.get("/{agent_id}/versions", response_model=AgentVersionResponse)
async def get_agent_versions(agent_id: str, db: AsyncSession = Depends(get_db)):
async def get_agent_versions(
agent_id: str,
db: AsyncSession = Depends(get_db),
user_id: str = Depends(get_current_user_id),
):
"""获取 Agent 版本历史"""
agent = await db.get(Agent, agent_id)
if not agent:
raise HTTPException(status_code=404, detail="Agent 不存在")
agent = await _require_agent(agent_id, user_id, db)

# 从 settings.versions 读取版本历史
agent_settings = agent.settings or {}
Expand Down Expand Up @@ -124,12 +137,13 @@ async def get_agent_versions(agent_id: str, db: AsyncSession = Depends(get_db)):

@router.post("/{agent_id}/versions/{version}/rollback")
async def rollback_agent_version(
agent_id: str, version: str, db: AsyncSession = Depends(get_db)
agent_id: str,
version: str,
db: AsyncSession = Depends(get_db),
user_id: str = Depends(get_current_user_id),
):
"""回滚到指定版本"""
agent = await db.get(Agent, agent_id)
if not agent:
raise HTTPException(status_code=404, detail="Agent 不存在")
agent = await _require_agent(agent_id, user_id, db)

agent_settings = agent.settings or {}
versions_data = agent_settings.get("versions", [])
Expand Down Expand Up @@ -168,15 +182,16 @@ async def rollback_agent_version(

@router.post("/{agent_id}/duplicate")
async def duplicate_agent(
agent_id: str, request: AgentDuplicateRequest, db: AsyncSession = Depends(get_db)
agent_id: str,
request: AgentDuplicateRequest,
db: AsyncSession = Depends(get_db),
user_id: str = Depends(get_current_user_id),
):
"""复制 Agent"""
original = await db.get(Agent, agent_id)
if not original:
raise HTTPException(status_code=404, detail="Agent 不存在")
original = await _require_agent(agent_id, user_id, db)

new_agent = Agent(
user_id=original.user_id,
user_id=user_id,
name=request.name,
description=request.description or f"{request.name} 的副本",
workflow_definition=original.workflow_definition,
Expand All @@ -203,11 +218,10 @@ async def export_agent(
agent_id: str,
include_knowledge: bool = True,
db: AsyncSession = Depends(get_db),
user_id: str = Depends(get_current_user_id),
):
"""导出 Agent 配置"""
agent = await db.get(Agent, agent_id)
if not agent:
raise HTTPException(status_code=404, detail="Agent 不存在")
agent = await _require_agent(agent_id, user_id, db)

export_data = {
"agent_id": agent.id,
Expand Down Expand Up @@ -241,13 +255,12 @@ async def import_agent(
agent_id: str,
data: dict,
db: AsyncSession = Depends(get_db),
user_id: str = Depends(get_current_user_id),
):
"""导入 Agent 配置"""
logger.info(f"Importing agent data for {agent_id}")

agent = await db.get(Agent, agent_id)
if not agent:
raise HTTPException(status_code=404, detail="Agent 不存在")
agent = await _require_agent(agent_id, user_id, db)

config = data.get("config", {})
agent.name = config.get("name", agent.name)
Expand All @@ -268,11 +281,13 @@ async def import_agent(


@router.get("/{agent_id}/health")
async def check_agent_health(agent_id: str, db: AsyncSession = Depends(get_db)):
async def check_agent_health(
agent_id: str,
db: AsyncSession = Depends(get_db),
user_id: str = Depends(get_current_user_id),
):
"""检查 Agent 健康状态"""
agent = await db.get(Agent, agent_id)
if not agent:
raise HTTPException(status_code=404, detail="Agent 不存在")
agent = await _require_agent(agent_id, user_id, db)

is_valid = bool(agent.workflow_definition and agent.workflow_definition.get("nodes"))

Expand All @@ -290,11 +305,13 @@ async def check_agent_health(agent_id: str, db: AsyncSession = Depends(get_db)):


@router.post("/{agent_id}/validate")
async def validate_agent(agent_id: str, db: AsyncSession = Depends(get_db)):
async def validate_agent(
agent_id: str,
db: AsyncSession = Depends(get_db),
user_id: str = Depends(get_current_user_id),
):
"""验证 Agent 配置"""
agent = await db.get(Agent, agent_id)
if not agent:
raise HTTPException(status_code=404, detail="Agent 不存在")
agent = await _require_agent(agent_id, user_id, db)

issues = []
warnings = []
Expand Down Expand Up @@ -332,13 +349,13 @@ async def validate_agent(agent_id: str, db: AsyncSession = Depends(get_db)):

@router.get("/{agent_id}/performance/tokens")
async def get_token_usage(
agent_id: str, days: int = Query(default=7, ge=1, le=90),
agent_id: str,
days: int = Query(default=7, ge=1, le=90),
db: AsyncSession = Depends(get_db),
user_id: str = Depends(get_current_user_id),
):
"""获取 Token 使用统计"""
agent = await db.get(Agent, agent_id)
if not agent:
raise HTTPException(status_code=404, detail="Agent 不存在")
agent = await _require_agent(agent_id, user_id, db)

total_msgs = agent.message_count or 0
avg_tokens_per_msg = 400
Expand Down Expand Up @@ -366,11 +383,13 @@ async def get_token_usage(


@router.get("/{agent_id}/performance/latency")
async def get_latency_stats(agent_id: str, db: AsyncSession = Depends(get_db)):
async def get_latency_stats(
agent_id: str,
db: AsyncSession = Depends(get_db),
user_id: str = Depends(get_current_user_id),
):
"""获取响应延迟统计"""
agent = await db.get(Agent, agent_id)
if not agent:
raise HTTPException(status_code=404, detail="Agent 不存在")
agent = await _require_agent(agent_id, user_id, db)

# 从 settings 读取真实延迟数据
agent_settings = agent.settings or {}
Expand All @@ -392,13 +411,13 @@ async def get_latency_stats(agent_id: str, db: AsyncSession = Depends(get_db)):

@router.get("/{agent_id}/performance/errors")
async def get_error_stats(
agent_id: str, days: int = Query(default=7, ge=1, le=90),
agent_id: str,
days: int = Query(default=7, ge=1, le=90),
db: AsyncSession = Depends(get_db),
user_id: str = Depends(get_current_user_id),
):
"""获取错误统计"""
agent = await db.get(Agent, agent_id)
if not agent:
raise HTTPException(status_code=404, detail="Agent 不存在")
agent = await _require_agent(agent_id, user_id, db)

agent_settings = agent.settings or {}
error_stats = agent_settings.get("errors", {})
Expand Down
11 changes: 8 additions & 3 deletions backend/app/api/knowledge.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,19 @@

from ..core.config import settings
from ..core.database import get_db
from ..core.paths import uploads_root
from ..models.agent import KnowledgeBase
from ..models.document import Document
from ..services.knowledge import KnowledgeService
from app.api.auth import get_current_user_id

router = APIRouter(prefix="/api/v1/knowledge", tags=["知识库"])
router = APIRouter(
prefix="/api/v1/knowledge",
tags=["知识库"],
dependencies=[Depends(get_current_user_id)],
)

UPLOAD_DIR = Path(settings.UPLOAD_DIR)
UPLOAD_DIR.mkdir(exist_ok=True)
UPLOAD_DIR = uploads_root()


class CreateKBRequest(BaseModel):
Expand Down
3 changes: 2 additions & 1 deletion backend/app/api/workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@

from ..core.database import get_db
from ..services.workflow_runtime import workflow_runtime, NodeStatus
from app.api.auth import get_current_user_id

router = APIRouter()
router = APIRouter(dependencies=[Depends(get_current_user_id)])


class WorkflowExecutionRequest(BaseModel):
Expand Down
27 changes: 11 additions & 16 deletions backend/app/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,22 +37,17 @@ class Settings(BaseSettings):

@lru_cache
def get_settings() -> Settings:
s = Settings()
if not s.dashscope_api_key and core.OPENAI_API_KEY:
s.dashscope_api_key = core.OPENAI_API_KEY
if not s.model_base_url and core.DEEPSEEK_API_KEY:
s.model_base_url = core.DEEPSEEK_BASE_URL
if not s.chatzoc_api_key:
s.chatzoc_api_key = s.dashscope_api_key
if not s.chatzoc_base_url and s.model_base_url:
s.chatzoc_base_url = s.model_base_url
if not s.default_model or s.default_model == "chatzoc_9b_B":
if core.OPENAI_API_KEY:
s.default_model = core.OPENAI_MODEL or "gpt-4o-mini"
if not s.optimize_model or s.optimize_model == "chatzoc_9b_B":
s.optimize_model = s.default_model
s.log_level = core.LOG_LEVEL or s.log_level
return s
return Settings(
dashscope_api_key=core.DASHSCOPE_API_KEY or core.OPENAI_API_KEY,
model_base_url=core.MODEL_BASE_URL or core.DEEPSEEK_BASE_URL,
chatzoc_api_key=core.CHATZOC_API_KEY or core.DASHSCOPE_API_KEY or core.OPENAI_API_KEY,
chatzoc_base_url=core.CHATZOC_BASE_URL or core.MODEL_BASE_URL or core.DEEPSEEK_BASE_URL,
chatzoc_agent_type=core.CHATZOC_AGENT_TYPE,
default_model=core.DEFAULT_MODEL or core.OPENAI_MODEL or "gpt-4o-mini",
optimize_model=core.OPTIMIZE_MODEL or core.DEFAULT_MODEL or core.OPENAI_MODEL or "gpt-4o-mini",
log_level=core.LOG_LEVEL,
semantic_scholar_api_key=core.SEMANTIC_SCHOLAR_API_KEY,
)


def reload_settings() -> Settings:
Expand Down
22 changes: 20 additions & 2 deletions backend/app/core/config.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
"""
核心配置
"""
from pydantic import field_validator
from pydantic_settings import BaseSettings
from typing import List
from typing import Any, List
from functools import lru_cache


Expand All @@ -29,12 +30,29 @@ class Settings(BaseSettings):
ANTHROPIC_MODEL: str = "claude-3-haiku"
DEEPSEEK_API_KEY: str = ""
DEEPSEEK_BASE_URL: str = "https://api.deepseek.com"

# Skill 运行时(Model Lab 兼容)
DASHSCOPE_API_KEY: str = ""
MODEL_BASE_URL: str = ""
CHATZOC_API_KEY: str = ""
CHATZOC_BASE_URL: str = ""
CHATZOC_AGENT_TYPE: str = "chatzoc_9b_B"
DEFAULT_MODEL: str = ""
OPTIMIZE_MODEL: str = ""
SEMANTIC_SCHOLAR_API_KEY: str = ""

# Embedding
EMBEDDING_MODEL: str = "sentence-transformers/all-MiniLM-L6-v2"

# CORS
# CORS(支持逗号分隔字符串,便于 docker-compose 注入)
CORS_ORIGINS: List[str] = ["http://localhost:3000", "http://localhost:5173"]

@field_validator("CORS_ORIGINS", mode="before")
@classmethod
def parse_cors_origins(cls, v: Any) -> list[str]:
if isinstance(v, str):
return [x.strip() for x in v.split(",") if x.strip()]
return v

# 文件存储
UPLOAD_DIR: str = "./uploads"
Expand Down
Loading
Loading