```
feat: 添加公司AI管理平台基础架构 添加了完整的FastAPI后端项目结构,包括: - 环境配置文件(.env.example)和项目说明文档(README.md、AGENTS.md) - Dockerfile用于容器化部署 - 核心基础设施:配置管理、数据库连接、调度器、安全认证 - 模块化设计:AI代理、审批流程、审计日志、业务台账等功能模块 - 支持多数据库连接(主库和遗留系统只读库) - AI适配器支持OpenClaw、Hermes、OpenAI兼容接口 - 飞书集成、报表生成、风险监控等企业级功能 - 完整的依赖管理和测试指南 ```
This commit is contained in:
1
app/modules/ai_agent/__init__.py
Normal file
1
app/modules/ai_agent/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
"""AI agent integration."""
|
||||
123
app/modules/ai_agent/adapters.py
Normal file
123
app/modules/ai_agent/adapters.py
Normal file
@@ -0,0 +1,123 @@
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
|
||||
from app.core.config import Settings, get_settings
|
||||
|
||||
|
||||
class AIAdapter(ABC):
|
||||
"""Interface for model provider adapters."""
|
||||
|
||||
provider_name: str
|
||||
|
||||
@abstractmethod
|
||||
def ask(self, prompt: str, context: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class NoopAdapter(AIAdapter):
|
||||
"""Deterministic adapter used when no model provider is configured."""
|
||||
|
||||
provider_name = "noop"
|
||||
|
||||
def ask(self, prompt: str, context: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
return {
|
||||
"answer": (
|
||||
"AI provider is not configured yet. This is a deterministic placeholder. "
|
||||
"Set MODEL_PROVIDER to openclaw, hermes, or direct_llm after credentials are ready."
|
||||
),
|
||||
"raw": {"prompt": prompt, "context": context or {}},
|
||||
}
|
||||
|
||||
|
||||
class OpenClawAdapter(AIAdapter):
|
||||
"""Adapter for an OpenClaw-compatible agent endpoint."""
|
||||
|
||||
provider_name = "openclaw"
|
||||
|
||||
def __init__(self, settings: Settings):
|
||||
self.settings = settings
|
||||
|
||||
def ask(self, prompt: str, context: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
url = f"{self.settings.openclaw_base_url.rstrip('/')}/api/v1/agent/ask"
|
||||
headers = {}
|
||||
if self.settings.openclaw_api_key:
|
||||
headers["Authorization"] = f"Bearer {self.settings.openclaw_api_key}"
|
||||
payload = {"prompt": prompt, "context": context or {}}
|
||||
with httpx.Client(timeout=60) as client:
|
||||
response = client.post(url, json=payload, headers=headers)
|
||||
if response.status_code >= 400:
|
||||
raise HTTPException(status_code=502, detail={"openclaw_error": response.text})
|
||||
data = response.json()
|
||||
return {"answer": data.get("answer") or data.get("content") or str(data), "raw": data}
|
||||
|
||||
|
||||
class HermesAdapter(AIAdapter):
|
||||
"""Adapter for a Hermes-compatible memory or agent endpoint."""
|
||||
|
||||
provider_name = "hermes"
|
||||
|
||||
def __init__(self, settings: Settings):
|
||||
self.settings = settings
|
||||
|
||||
def ask(self, prompt: str, context: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
url = f"{self.settings.hermes_base_url.rstrip('/')}/api/v1/ask"
|
||||
headers = {}
|
||||
if self.settings.hermes_api_key:
|
||||
headers["Authorization"] = f"Bearer {self.settings.hermes_api_key}"
|
||||
payload = {"prompt": prompt, "context": context or {}}
|
||||
with httpx.Client(timeout=60) as client:
|
||||
response = client.post(url, json=payload, headers=headers)
|
||||
if response.status_code >= 400:
|
||||
raise HTTPException(status_code=502, detail={"hermes_error": response.text})
|
||||
data = response.json()
|
||||
return {"answer": data.get("answer") or data.get("content") or str(data), "raw": data}
|
||||
|
||||
|
||||
class DirectLLMAdapter(AIAdapter):
|
||||
"""Adapter for OpenAI-compatible chat completions APIs."""
|
||||
|
||||
provider_name = "direct_llm"
|
||||
|
||||
def __init__(self, settings: Settings):
|
||||
self.settings = settings
|
||||
|
||||
def ask(self, prompt: str, context: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
if not self.settings.direct_llm_api_key:
|
||||
raise HTTPException(status_code=503, detail="DIRECT_LLM_API_KEY is not configured")
|
||||
url = f"{self.settings.direct_llm_base_url.rstrip('/')}/chat/completions"
|
||||
headers = {"Authorization": f"Bearer {self.settings.direct_llm_api_key}"}
|
||||
messages = [
|
||||
{
|
||||
"role": "system",
|
||||
"content": (
|
||||
"You are a company management AI. Be concise, cite data from context, "
|
||||
"and never approve payments, performance changes, or trades automatically."
|
||||
),
|
||||
},
|
||||
{"role": "user", "content": f"Context:\n{context or {}}\n\nTask:\n{prompt}"},
|
||||
]
|
||||
payload = {"model": self.settings.direct_llm_model, "messages": messages}
|
||||
with httpx.Client(timeout=60) as client:
|
||||
response = client.post(url, json=payload, headers=headers)
|
||||
if response.status_code >= 400:
|
||||
raise HTTPException(status_code=502, detail={"llm_error": response.text})
|
||||
data = response.json()
|
||||
answer = data["choices"][0]["message"]["content"]
|
||||
return {"answer": answer, "raw": data}
|
||||
|
||||
|
||||
def get_adapter() -> AIAdapter:
|
||||
"""Return the configured AI provider adapter."""
|
||||
|
||||
settings = get_settings()
|
||||
provider = settings.model_provider.lower()
|
||||
if provider == "openclaw":
|
||||
return OpenClawAdapter(settings)
|
||||
if provider == "hermes":
|
||||
return HermesAdapter(settings)
|
||||
if provider == "direct_llm":
|
||||
return DirectLLMAdapter(settings)
|
||||
return NoopAdapter()
|
||||
38
app/modules/ai_agent/routes.py
Normal file
38
app/modules/ai_agent/routes.py
Normal file
@@ -0,0 +1,38 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.security import require_api_key
|
||||
from app.modules.ai_agent.schemas import (
|
||||
AIAskRequest,
|
||||
AIAskResponse,
|
||||
DraftPolicyRequest,
|
||||
InvestmentResearchRequest,
|
||||
)
|
||||
from app.modules.ai_agent.service import AIService
|
||||
|
||||
router = APIRouter(dependencies=[Depends(require_api_key)])
|
||||
|
||||
|
||||
@router.post("/ask", response_model=AIAskResponse)
|
||||
def ask(payload: AIAskRequest, db: Session = Depends(get_db)) -> dict:
|
||||
return AIService(db).ask(payload.prompt, payload.context, payload.actor, payload.source)
|
||||
|
||||
|
||||
@router.post("/draft-policy", response_model=AIAskResponse)
|
||||
def draft_policy(payload: DraftPolicyRequest, db: Session = Depends(get_db)) -> dict:
|
||||
return AIService(db).draft_policy(
|
||||
title=payload.title,
|
||||
policy_type=payload.policy_type,
|
||||
requirements=payload.requirements,
|
||||
actor=payload.actor,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/investment-research", response_model=AIAskResponse)
|
||||
def investment_research(payload: InvestmentResearchRequest, db: Session = Depends(get_db)) -> dict:
|
||||
return AIService(db).draft_investment_research(
|
||||
symbol_or_topic=payload.symbol_or_topic,
|
||||
risk_preference=payload.risk_preference,
|
||||
actor=payload.actor,
|
||||
)
|
||||
29
app/modules/ai_agent/schemas.py
Normal file
29
app/modules/ai_agent/schemas.py
Normal file
@@ -0,0 +1,29 @@
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class AIAskRequest(BaseModel):
|
||||
prompt: str
|
||||
context: dict[str, Any] = Field(default_factory=dict)
|
||||
actor: str = "api"
|
||||
source: str = "api"
|
||||
|
||||
|
||||
class AIAskResponse(BaseModel):
|
||||
provider: str
|
||||
answer: str
|
||||
raw: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class DraftPolicyRequest(BaseModel):
|
||||
title: str
|
||||
policy_type: str
|
||||
requirements: list[str]
|
||||
actor: str = "api"
|
||||
|
||||
|
||||
class InvestmentResearchRequest(BaseModel):
|
||||
symbol_or_topic: str
|
||||
risk_preference: str = "balanced"
|
||||
actor: str = "api"
|
||||
70
app/modules/ai_agent/service.py
Normal file
70
app/modules/ai_agent/service.py
Normal file
@@ -0,0 +1,70 @@
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.modules.ai_agent.adapters import get_adapter
|
||||
from app.modules.audit.schemas import AuditLogCreate
|
||||
from app.modules.audit.service import AuditService
|
||||
|
||||
|
||||
class AIService:
|
||||
"""Coordinate AI provider calls and audit logging."""
|
||||
|
||||
def __init__(self, db: Session):
|
||||
self.db = db
|
||||
self.audit = AuditService(db)
|
||||
|
||||
def ask(
|
||||
self,
|
||||
prompt: str,
|
||||
context: dict[str, Any] | None = None,
|
||||
actor: str = "api",
|
||||
source: str = "api",
|
||||
) -> dict[str, Any]:
|
||||
adapter = get_adapter()
|
||||
result = adapter.ask(prompt, context or {})
|
||||
response = {
|
||||
"provider": adapter.provider_name,
|
||||
"answer": result["answer"],
|
||||
"raw": result.get("raw", {}),
|
||||
}
|
||||
self.audit.log(
|
||||
AuditLogCreate(
|
||||
actor=actor,
|
||||
source=source,
|
||||
action="ai.ask",
|
||||
target_type="ai",
|
||||
risk_level="medium",
|
||||
request_payload={"prompt": prompt, "context": context or {}},
|
||||
response_payload=response,
|
||||
)
|
||||
)
|
||||
return response
|
||||
|
||||
def draft_policy(
|
||||
self,
|
||||
title: str,
|
||||
policy_type: str,
|
||||
requirements: list[str],
|
||||
actor: str,
|
||||
) -> dict[str, Any]:
|
||||
prompt = (
|
||||
f"Draft a company policy in Chinese. Title: {title}. Type: {policy_type}. "
|
||||
"Include purpose, scope, roles, process, approval rules, audit rules, and KPI linkage. "
|
||||
f"Requirements: {requirements}"
|
||||
)
|
||||
return self.ask(prompt, actor=actor, source="policy")
|
||||
|
||||
def draft_investment_research(
|
||||
self,
|
||||
symbol_or_topic: str,
|
||||
risk_preference: str,
|
||||
actor: str,
|
||||
) -> dict[str, Any]:
|
||||
prompt = (
|
||||
"Create an investment research memo in Chinese. Do not give direct trading "
|
||||
"instructions. Include thesis, risks, data needed, position sizing constraints, "
|
||||
"and human approval checklist. "
|
||||
f"Topic: {symbol_or_topic}. Risk preference: {risk_preference}."
|
||||
)
|
||||
return self.ask(prompt, actor=actor, source="investment")
|
||||
Reference in New Issue
Block a user