feat: 添加公司AI管理平台基础架构 添加了完整的FastAPI后端项目结构,包括: - 环境配置文件(.env.example)和项目说明文档(README.md、AGENTS.md) - Dockerfile用于容器化部署 - 核心基础设施:配置管理、数据库连接、调度器、安全认证 - 模块化设计:AI代理、审批流程、审计日志、业务台账等功能模块 - 支持多数据库连接(主库和遗留系统只读库) - AI适配器支持OpenClaw、Hermes、OpenAI兼容接口 - 飞书集成、报表生成、风险监控等企业级功能 - 完整的依赖管理和测试指南 ```
124 lines
4.7 KiB
Python
124 lines
4.7 KiB
Python
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()
|