```
feat(ai_agent): 完善AI适配器和服务功能 - 添加OpenClaw和Hermes健康检查接口 - 实现OpenClaw工具调用功能 - 重构AI适配器使用常量定义 - 增加AI技能系统支持 - 更新配置文件中的默认模型提供者设置 refactor(scheduler): 使用常量替换硬编码值 - 将硬编码的actor值替换为ActorValue常量 - 将receive_id_type替换为FeishuReceiveIdType枚举 refactor(audit): 统一审计日志常量使用 - 将硬编码的actor、source、risk_level等值替换为对应常量 - 更新审核服务中的状态和操作常量引用 refactor(approvals): 标准化审批模块常量使用 - 将applicant默认值替换为ActorValue.API常量 - 使用ApprovalStatus常量替代硬编码状态值 - 更新审核操作常量引用 ```
This commit is contained in:
@@ -5,6 +5,28 @@ import httpx
|
||||
from fastapi import HTTPException
|
||||
|
||||
from app.core.config import Settings, get_settings
|
||||
from app.modules.ai_agent.constants import (
|
||||
AUTHORIZATION_BEARER_TEMPLATE,
|
||||
CHAT_USER_CONTENT_TEMPLATE,
|
||||
COMPANY_MANAGEMENT_SYSTEM_INSTRUCTIONS,
|
||||
DIRECT_LLM_API_KEY_MISSING,
|
||||
NOOP_PROVIDER_ANSWER,
|
||||
OPENCLAW_HERMES_PIPELINE,
|
||||
OPENCLAW_TOOL_COMPLETED_ANSWER,
|
||||
UNEXPECTED_HERMES_RESPONSE,
|
||||
AIDefault,
|
||||
AIChatRole,
|
||||
AIContextKey,
|
||||
AIErrorKey,
|
||||
AIHttpHeader,
|
||||
AIHttpPath,
|
||||
AIHttpPayloadKey,
|
||||
AIMemoryMode,
|
||||
AIProviderName,
|
||||
AIRequestKey,
|
||||
AIResponseKey,
|
||||
)
|
||||
from app.modules.ai_agent.skills import AISkillId, get_ai_skill
|
||||
|
||||
|
||||
class AIAdapter(ABC):
|
||||
@@ -20,67 +42,163 @@ class AIAdapter(ABC):
|
||||
class NoopAdapter(AIAdapter):
|
||||
"""Deterministic adapter used when no model provider is configured."""
|
||||
|
||||
provider_name = "noop"
|
||||
provider_name = AIProviderName.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, openclaw, hermes, or direct_llm "
|
||||
"after credentials are ready."
|
||||
),
|
||||
"raw": {"prompt": prompt, "context": context or {}},
|
||||
AIResponseKey.ANSWER: NOOP_PROVIDER_ANSWER,
|
||||
AIResponseKey.RAW: {
|
||||
AIRequestKey.PROMPT: prompt,
|
||||
AIRequestKey.CONTEXT: context or {},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
class OpenClawAdapter(AIAdapter):
|
||||
"""Adapter for an OpenClaw-compatible agent endpoint."""
|
||||
"""Adapter for the OpenClaw Gateway control-plane API."""
|
||||
|
||||
provider_name = "openclaw"
|
||||
provider_name = AIProviderName.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)
|
||||
context = context or {}
|
||||
tool = context.get(AIContextKey.OPENCLAW_TOOL)
|
||||
if not tool:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=(
|
||||
"OpenClaw Gateway is not configured as a chat provider. "
|
||||
"Provide context.openclaw_tool for /tools/invoke, or use "
|
||||
"MODEL_PROVIDER=hermes/openclaw_hermes for AI answers."
|
||||
),
|
||||
)
|
||||
result = self.invoke_tool(
|
||||
tool=str(tool),
|
||||
action=str(context.get(AIContextKey.OPENCLAW_ACTION) or AIDefault.ACTION_JSON),
|
||||
args=context.get(AIContextKey.OPENCLAW_ARGS) or {},
|
||||
session_key=str(
|
||||
context.get(AIContextKey.OPENCLAW_SESSION_KEY) or AIDefault.SESSION_KEY_MAIN
|
||||
),
|
||||
)
|
||||
return {
|
||||
AIResponseKey.ANSWER: OPENCLAW_TOOL_COMPLETED_ANSWER,
|
||||
AIResponseKey.RAW: result,
|
||||
}
|
||||
|
||||
def health(self) -> dict[str, Any]:
|
||||
"""Check OpenClaw Gateway health endpoints."""
|
||||
|
||||
headers = self._headers()
|
||||
base_url = self._base_url()
|
||||
with httpx.Client(timeout=5, trust_env=False) as client:
|
||||
healthz = client.get(f"{base_url}{AIHttpPath.HEALTHZ}", headers=headers)
|
||||
readyz = client.get(f"{base_url}{AIHttpPath.READYZ}", headers=headers)
|
||||
return {
|
||||
AIResponseKey.OK: healthz.status_code < 400 and readyz.status_code < 400,
|
||||
AIResponseKey.BASE_URL: base_url,
|
||||
AIResponseKey.HEALTHZ: _response_payload(healthz),
|
||||
AIResponseKey.READYZ: _response_payload(readyz),
|
||||
}
|
||||
|
||||
def invoke_tool(
|
||||
self,
|
||||
tool: str,
|
||||
action: str = AIDefault.ACTION_JSON,
|
||||
args: dict[str, Any] | None = None,
|
||||
session_key: str = AIDefault.SESSION_KEY_MAIN,
|
||||
) -> dict[str, Any]:
|
||||
"""Invoke one OpenClaw Gateway tool through `/tools/invoke`."""
|
||||
|
||||
payload = {
|
||||
AIHttpPayloadKey.TOOL: tool,
|
||||
AIHttpPayloadKey.ACTION: action,
|
||||
AIHttpPayloadKey.ARGS: args or {},
|
||||
AIHttpPayloadKey.SESSION_KEY: session_key,
|
||||
}
|
||||
url = f"{self._base_url()}{AIHttpPath.TOOLS_INVOKE}"
|
||||
with httpx.Client(timeout=120, trust_env=False) as client:
|
||||
response = client.post(url, json=payload, headers=self._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}
|
||||
raise HTTPException(status_code=502, detail={AIErrorKey.OPENCLAW: response.text})
|
||||
return _response_payload(response)
|
||||
|
||||
def _base_url(self) -> str:
|
||||
return (self.settings.openclaw_http_url or self.settings.openclaw_base_url).rstrip("/")
|
||||
|
||||
def _headers(self) -> dict[str, str]:
|
||||
token = self.settings.openclaw_gateway_token or self.settings.openclaw_api_key
|
||||
if not token:
|
||||
return {}
|
||||
return {
|
||||
AIHttpHeader.AUTHORIZATION: AUTHORIZATION_BEARER_TEMPLATE.format(token=token)
|
||||
}
|
||||
|
||||
|
||||
class HermesAdapter(AIAdapter):
|
||||
"""Adapter for a Hermes-compatible memory or agent endpoint."""
|
||||
"""Adapter for the Hermes OpenAI-compatible agent endpoint."""
|
||||
|
||||
provider_name = "hermes"
|
||||
provider_name = AIProviderName.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"
|
||||
url = f"{self.settings.hermes_base_url.rstrip('/')}{AIHttpPath.CHAT_COMPLETIONS}"
|
||||
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:
|
||||
headers[AIHttpHeader.AUTHORIZATION] = AUTHORIZATION_BEARER_TEMPLATE.format(
|
||||
token=self.settings.hermes_api_key
|
||||
)
|
||||
if self.settings.hermes_session_id:
|
||||
headers[AIHttpHeader.HERMES_SESSION_ID] = self.settings.hermes_session_id
|
||||
payload = {
|
||||
AIHttpPayloadKey.MODEL: self.settings.hermes_model,
|
||||
AIHttpPayloadKey.MESSAGES: _chat_messages(prompt, context),
|
||||
AIHttpPayloadKey.STREAM: False,
|
||||
}
|
||||
with httpx.Client(timeout=300, trust_env=False) 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})
|
||||
raise HTTPException(status_code=502, detail={AIErrorKey.HERMES: response.text})
|
||||
data = response.json()
|
||||
return {"answer": data.get("answer") or data.get("content") or str(data), "raw": data}
|
||||
try:
|
||||
answer = data[AIHttpPayloadKey.CHOICES][0][AIHttpPayloadKey.MESSAGE][
|
||||
AIHttpPayloadKey.CONTENT
|
||||
]
|
||||
except (KeyError, IndexError, TypeError) as exc:
|
||||
raise HTTPException(
|
||||
status_code=502,
|
||||
detail={
|
||||
AIErrorKey.HERMES: UNEXPECTED_HERMES_RESPONSE,
|
||||
AIResponseKey.RAW: data,
|
||||
},
|
||||
) from exc
|
||||
return {AIResponseKey.ANSWER: answer, AIResponseKey.RAW: data}
|
||||
|
||||
def health(self) -> dict[str, Any]:
|
||||
"""Check Hermes Agent health without triggering a chat completion."""
|
||||
|
||||
url = f"{_service_root(self.settings.hermes_base_url, AIHttpPath.V1)}{AIHttpPath.HEALTH}"
|
||||
headers = {}
|
||||
if self.settings.hermes_api_key:
|
||||
headers[AIHttpHeader.AUTHORIZATION] = AUTHORIZATION_BEARER_TEMPLATE.format(
|
||||
token=self.settings.hermes_api_key
|
||||
)
|
||||
with httpx.Client(timeout=5, trust_env=False) as client:
|
||||
response = client.get(url, headers=headers)
|
||||
return {
|
||||
AIResponseKey.OK: response.status_code < 400,
|
||||
AIResponseKey.BASE_URL: self.settings.hermes_base_url.rstrip("/"),
|
||||
AIResponseKey.HEALTH: _response_payload(response),
|
||||
}
|
||||
|
||||
|
||||
class OpenClawHermesAdapter(AIAdapter):
|
||||
"""Compose Hermes memory with OpenClaw execution."""
|
||||
"""Compose OpenClaw Gateway context with Hermes Agent answers."""
|
||||
|
||||
provider_name = "openclaw_hermes"
|
||||
provider_name = AIProviderName.OPENCLAW_HERMES
|
||||
|
||||
def __init__(self, settings: Settings):
|
||||
self.openclaw = OpenClawAdapter(settings)
|
||||
@@ -89,40 +207,80 @@ class OpenClawHermesAdapter(AIAdapter):
|
||||
def ask(self, prompt: str, context: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
base_context = context or {}
|
||||
recall = self._recall_memory(prompt, base_context)
|
||||
openclaw_context = {
|
||||
openclaw = self._openclaw_context(base_context)
|
||||
hermes_context = {
|
||||
**base_context,
|
||||
"agent_pipeline": self.provider_name,
|
||||
"hermes_memory": recall["answer"],
|
||||
AIContextKey.AGENT_PIPELINE: self.provider_name,
|
||||
AIContextKey.HERMES_MEMORY: recall[AIResponseKey.ANSWER],
|
||||
AIContextKey.OPENCLAW: openclaw,
|
||||
}
|
||||
openclaw_result = self.openclaw.ask(prompt, openclaw_context)
|
||||
remember = self._remember_interaction(prompt, base_context, openclaw_result["answer"])
|
||||
hermes_result = self.hermes.ask(prompt, hermes_context)
|
||||
remember = self._remember_interaction(
|
||||
prompt,
|
||||
base_context,
|
||||
hermes_result[AIResponseKey.ANSWER],
|
||||
)
|
||||
return {
|
||||
"answer": openclaw_result["answer"],
|
||||
"raw": {
|
||||
"pipeline": "hermes_recall -> openclaw_answer -> hermes_remember",
|
||||
"hermes_recall": recall,
|
||||
"openclaw": openclaw_result.get("raw", {}),
|
||||
"hermes_remember": remember,
|
||||
AIResponseKey.ANSWER: hermes_result[AIResponseKey.ANSWER],
|
||||
AIResponseKey.RAW: {
|
||||
AIResponseKey.PIPELINE: OPENCLAW_HERMES_PIPELINE,
|
||||
AIResponseKey.HERMES_RECALL: recall,
|
||||
AIResponseKey.OPENCLAW: openclaw,
|
||||
AIResponseKey.HERMES_ANSWER: hermes_result.get(AIResponseKey.RAW, {}),
|
||||
AIResponseKey.HERMES_REMEMBER: remember,
|
||||
},
|
||||
}
|
||||
|
||||
def _openclaw_context(self, context: dict[str, Any]) -> dict[str, Any]:
|
||||
result: dict[str, Any] = {AIResponseKey.TOOL_INVOKED: False}
|
||||
try:
|
||||
result[AIResponseKey.HEALTH] = self.openclaw.health()
|
||||
except Exception as exc:
|
||||
result[AIResponseKey.HEALTH] = {
|
||||
AIResponseKey.OK: False,
|
||||
AIResponseKey.ERROR: _error_detail(exc),
|
||||
}
|
||||
|
||||
tool = context.get(AIContextKey.OPENCLAW_TOOL)
|
||||
if not tool:
|
||||
return result
|
||||
|
||||
try:
|
||||
result[AIResponseKey.TOOL_INVOKED] = True
|
||||
result[AIResponseKey.TOOL] = self.openclaw.invoke_tool(
|
||||
tool=str(tool),
|
||||
action=str(context.get(AIContextKey.OPENCLAW_ACTION) or AIDefault.ACTION_JSON),
|
||||
args=context.get(AIContextKey.OPENCLAW_ARGS) or {},
|
||||
session_key=str(
|
||||
context.get(AIContextKey.OPENCLAW_SESSION_KEY)
|
||||
or AIDefault.SESSION_KEY_MAIN
|
||||
),
|
||||
)
|
||||
except Exception as exc:
|
||||
result[AIResponseKey.TOOL_ERROR] = _error_detail(exc)
|
||||
return result
|
||||
|
||||
def _recall_memory(self, prompt: str, context: dict[str, Any]) -> dict[str, Any]:
|
||||
recall_prompt = (
|
||||
"Retrieve concise long-term memory, preferences, prior decisions, and relevant "
|
||||
"business context for this request. Return only information useful to answer it."
|
||||
)
|
||||
recall_skill = get_ai_skill(AISkillId.HERMES_MEMORY_RECALL)
|
||||
try:
|
||||
result = self.hermes.ask(
|
||||
recall_prompt,
|
||||
recall_skill.render(),
|
||||
{
|
||||
"mode": "memory_recall",
|
||||
"user_prompt": prompt,
|
||||
"request_context": context,
|
||||
AIContextKey.MODE: AIMemoryMode.RECALL,
|
||||
AIContextKey.USER_PROMPT: prompt,
|
||||
AIContextKey.REQUEST_CONTEXT: context,
|
||||
},
|
||||
)
|
||||
except Exception as exc: # Hermes memory should not block OpenClaw execution.
|
||||
return {"answer": "", "raw": {}, "error": _error_detail(exc)}
|
||||
return {"answer": result["answer"], "raw": result.get("raw", {})}
|
||||
return {
|
||||
AIResponseKey.ANSWER: "",
|
||||
AIResponseKey.RAW: {},
|
||||
AIResponseKey.ERROR: _error_detail(exc),
|
||||
}
|
||||
return {
|
||||
AIResponseKey.ANSWER: result[AIResponseKey.ANSWER],
|
||||
AIResponseKey.RAW: result.get(AIResponseKey.RAW, {}),
|
||||
}
|
||||
|
||||
def _remember_interaction(
|
||||
self,
|
||||
@@ -130,56 +288,60 @@ class OpenClawHermesAdapter(AIAdapter):
|
||||
context: dict[str, Any],
|
||||
answer: str,
|
||||
) -> dict[str, Any]:
|
||||
remember_prompt = (
|
||||
"Store durable lessons from this interaction for future company management "
|
||||
"assistance. Ignore transient details and do not store secrets."
|
||||
)
|
||||
remember_skill = get_ai_skill(AISkillId.HERMES_MEMORY_WRITE)
|
||||
try:
|
||||
result = self.hermes.ask(
|
||||
remember_prompt,
|
||||
remember_skill.render(),
|
||||
{
|
||||
"mode": "memory_write",
|
||||
"user_prompt": prompt,
|
||||
"request_context": context,
|
||||
"assistant_answer": answer,
|
||||
AIContextKey.MODE: AIMemoryMode.WRITE,
|
||||
AIContextKey.USER_PROMPT: prompt,
|
||||
AIContextKey.REQUEST_CONTEXT: context,
|
||||
AIContextKey.ASSISTANT_ANSWER: answer,
|
||||
},
|
||||
)
|
||||
except Exception as exc:
|
||||
return {"ok": False, "raw": {}, "error": _error_detail(exc)}
|
||||
return {"ok": True, "raw": result.get("raw", {}), "answer": result["answer"]}
|
||||
return {
|
||||
AIResponseKey.OK: False,
|
||||
AIResponseKey.RAW: {},
|
||||
AIResponseKey.ERROR: _error_detail(exc),
|
||||
}
|
||||
return {
|
||||
AIResponseKey.OK: True,
|
||||
AIResponseKey.RAW: result.get(AIResponseKey.RAW, {}),
|
||||
AIResponseKey.ANSWER: result[AIResponseKey.ANSWER],
|
||||
}
|
||||
|
||||
|
||||
class DirectLLMAdapter(AIAdapter):
|
||||
"""Adapter for OpenAI-compatible chat completions APIs."""
|
||||
|
||||
provider_name = "direct_llm"
|
||||
provider_name = AIProviderName.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:
|
||||
raise HTTPException(status_code=503, detail=DIRECT_LLM_API_KEY_MISSING)
|
||||
url = f"{self.settings.direct_llm_base_url.rstrip('/')}{AIHttpPath.CHAT_COMPLETIONS}"
|
||||
headers = {
|
||||
AIHttpHeader.AUTHORIZATION: AUTHORIZATION_BEARER_TEMPLATE.format(
|
||||
token=self.settings.direct_llm_api_key
|
||||
)
|
||||
}
|
||||
payload = {
|
||||
AIHttpPayloadKey.MODEL: self.settings.direct_llm_model,
|
||||
AIHttpPayloadKey.MESSAGES: _chat_messages(prompt, context),
|
||||
}
|
||||
with httpx.Client(timeout=60, trust_env=False) 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})
|
||||
raise HTTPException(status_code=502, detail={AIErrorKey.DIRECT_LLM: response.text})
|
||||
data = response.json()
|
||||
answer = data["choices"][0]["message"]["content"]
|
||||
return {"answer": answer, "raw": data}
|
||||
answer = data[AIHttpPayloadKey.CHOICES][0][AIHttpPayloadKey.MESSAGE][
|
||||
AIHttpPayloadKey.CONTENT
|
||||
]
|
||||
return {AIResponseKey.ANSWER: answer, AIResponseKey.RAW: data}
|
||||
|
||||
|
||||
def get_adapter() -> AIAdapter:
|
||||
@@ -187,13 +349,17 @@ def get_adapter() -> AIAdapter:
|
||||
|
||||
settings = get_settings()
|
||||
provider = settings.model_provider.lower()
|
||||
if provider == "openclaw":
|
||||
if provider == AIProviderName.OPENCLAW:
|
||||
return OpenClawAdapter(settings)
|
||||
if provider == "hermes":
|
||||
if provider == AIProviderName.HERMES:
|
||||
return HermesAdapter(settings)
|
||||
if provider in {"openclaw_hermes", "openclaw-hermes", "hybrid"}:
|
||||
if provider in {
|
||||
AIProviderName.OPENCLAW_HERMES,
|
||||
AIProviderName.OPENCLAW_HERMES_DASH,
|
||||
AIProviderName.HYBRID,
|
||||
}:
|
||||
return OpenClawHermesAdapter(settings)
|
||||
if provider == "direct_llm":
|
||||
if provider == AIProviderName.DIRECT_LLM:
|
||||
return DirectLLMAdapter(settings)
|
||||
return NoopAdapter()
|
||||
|
||||
@@ -201,4 +367,36 @@ def get_adapter() -> AIAdapter:
|
||||
def _error_detail(exc: Exception) -> Any:
|
||||
if isinstance(exc, HTTPException):
|
||||
return exc.detail
|
||||
return {"type": type(exc).__name__, "message": str(exc)}
|
||||
return {AIResponseKey.TYPE: type(exc).__name__, AIResponseKey.MESSAGE: str(exc)}
|
||||
|
||||
|
||||
def _response_payload(response: httpx.Response) -> dict[str, Any]:
|
||||
try:
|
||||
data = response.json()
|
||||
except ValueError:
|
||||
data = {AIResponseKey.TEXT: response.text}
|
||||
return {AIResponseKey.STATUS_CODE: response.status_code, AIResponseKey.DATA: data}
|
||||
|
||||
|
||||
def _chat_messages(prompt: str, context: dict[str, Any] | None = None) -> list[dict[str, str]]:
|
||||
return [
|
||||
{
|
||||
AIHttpPayloadKey.ROLE: AIChatRole.SYSTEM,
|
||||
AIHttpPayloadKey.CONTENT: COMPANY_MANAGEMENT_SYSTEM_INSTRUCTIONS,
|
||||
},
|
||||
{
|
||||
AIHttpPayloadKey.ROLE: AIChatRole.USER,
|
||||
AIHttpPayloadKey.CONTENT: CHAT_USER_CONTENT_TEMPLATE.format(
|
||||
context=context or {},
|
||||
task=prompt,
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def _service_root(base_url: str, suffix: str) -> str:
|
||||
root = base_url.rstrip("/")
|
||||
normalized_suffix = suffix.rstrip("/")
|
||||
if root.endswith(normalized_suffix):
|
||||
root = root[: -len(normalized_suffix)]
|
||||
return root.rstrip("/")
|
||||
|
||||
128
app/modules/ai_agent/constants.py
Normal file
128
app/modules/ai_agent/constants.py
Normal file
@@ -0,0 +1,128 @@
|
||||
from enum import StrEnum
|
||||
|
||||
|
||||
class AIProviderName(StrEnum):
|
||||
NOOP = "noop"
|
||||
OPENCLAW = "openclaw"
|
||||
HERMES = "hermes"
|
||||
OPENCLAW_HERMES = "openclaw_hermes"
|
||||
OPENCLAW_HERMES_DASH = "openclaw-hermes"
|
||||
HYBRID = "hybrid"
|
||||
DIRECT_LLM = "direct_llm"
|
||||
|
||||
|
||||
class AIResponseKey(StrEnum):
|
||||
PROVIDER = "provider"
|
||||
ANSWER = "answer"
|
||||
RAW = "raw"
|
||||
RESULT = "result"
|
||||
OK = "ok"
|
||||
ERROR = "error"
|
||||
MESSAGE = "message"
|
||||
TYPE = "type"
|
||||
BASE_URL = "base_url"
|
||||
HEALTH = "health"
|
||||
HEALTHZ = "healthz"
|
||||
READYZ = "readyz"
|
||||
DATA = "data"
|
||||
STATUS_CODE = "status_code"
|
||||
TEXT = "text"
|
||||
PIPELINE = "pipeline"
|
||||
HERMES_RECALL = "hermes_recall"
|
||||
HERMES_ANSWER = "hermes_answer"
|
||||
HERMES_REMEMBER = "hermes_remember"
|
||||
OPENCLAW = "openclaw"
|
||||
TOOL = "tool"
|
||||
TOOL_INVOKED = "tool_invoked"
|
||||
TOOL_ERROR = "tool_error"
|
||||
|
||||
|
||||
class AIRequestKey(StrEnum):
|
||||
PROMPT = "prompt"
|
||||
CONTEXT = "context"
|
||||
|
||||
|
||||
class AIContextKey(StrEnum):
|
||||
OPENCLAW_TOOL = "openclaw_tool"
|
||||
OPENCLAW_ACTION = "openclaw_action"
|
||||
OPENCLAW_ARGS = "openclaw_args"
|
||||
OPENCLAW_SESSION_KEY = "openclaw_session_key"
|
||||
AGENT_PIPELINE = "agent_pipeline"
|
||||
HERMES_MEMORY = "hermes_memory"
|
||||
OPENCLAW = "openclaw"
|
||||
MODE = "mode"
|
||||
USER_PROMPT = "user_prompt"
|
||||
REQUEST_CONTEXT = "request_context"
|
||||
ASSISTANT_ANSWER = "assistant_answer"
|
||||
|
||||
|
||||
class AIMemoryMode(StrEnum):
|
||||
RECALL = "memory_recall"
|
||||
WRITE = "memory_write"
|
||||
|
||||
|
||||
class AIHttpPath(StrEnum):
|
||||
CHAT_COMPLETIONS = "/chat/completions"
|
||||
HEALTH = "/health"
|
||||
HEALTHZ = "/healthz"
|
||||
READYZ = "/readyz"
|
||||
TOOLS_INVOKE = "/tools/invoke"
|
||||
V1 = "/v1"
|
||||
|
||||
|
||||
class AIHttpHeader(StrEnum):
|
||||
AUTHORIZATION = "Authorization"
|
||||
HERMES_SESSION_ID = "X-Hermes-Session-Id"
|
||||
|
||||
|
||||
class AIHttpPayloadKey(StrEnum):
|
||||
MODEL = "model"
|
||||
MESSAGES = "messages"
|
||||
ROLE = "role"
|
||||
CONTENT = "content"
|
||||
STREAM = "stream"
|
||||
TOOL = "tool"
|
||||
ACTION = "action"
|
||||
ARGS = "args"
|
||||
SESSION_KEY = "sessionKey"
|
||||
CHOICES = "choices"
|
||||
MESSAGE = "message"
|
||||
|
||||
|
||||
class AIChatRole(StrEnum):
|
||||
SYSTEM = "system"
|
||||
USER = "user"
|
||||
|
||||
|
||||
class AIDefault(StrEnum):
|
||||
ACTION_JSON = "json"
|
||||
SESSION_KEY_MAIN = "main"
|
||||
|
||||
|
||||
class AIRiskPreference(StrEnum):
|
||||
BALANCED = "balanced"
|
||||
|
||||
|
||||
class AIErrorKey(StrEnum):
|
||||
OPENCLAW = "openclaw_error"
|
||||
HERMES = "hermes_error"
|
||||
DIRECT_LLM = "llm_error"
|
||||
|
||||
|
||||
OPENCLAW_HERMES_PIPELINE = (
|
||||
"hermes_recall -> openclaw_gateway -> hermes_answer -> hermes_remember"
|
||||
)
|
||||
COMPANY_MANAGEMENT_SYSTEM_INSTRUCTIONS = (
|
||||
"You are a company management AI. Be concise, cite data from context, "
|
||||
"and never approve payments, performance changes, or trades automatically."
|
||||
)
|
||||
CHAT_USER_CONTENT_TEMPLATE = "Context:\n{context}\n\nTask:\n{task}"
|
||||
AUTHORIZATION_BEARER_TEMPLATE = "Bearer {token}"
|
||||
NOOP_PROVIDER_ANSWER = (
|
||||
"AI provider is not configured yet. This is a deterministic placeholder. "
|
||||
"Set MODEL_PROVIDER to openclaw_hermes, openclaw, hermes, or direct_llm "
|
||||
"after credentials are ready."
|
||||
)
|
||||
OPENCLAW_TOOL_COMPLETED_ANSWER = "OpenClaw tool invocation completed."
|
||||
DIRECT_LLM_API_KEY_MISSING = "DIRECT_LLM_API_KEY is not configured"
|
||||
UNEXPECTED_HERMES_RESPONSE = "Unexpected chat completion response"
|
||||
@@ -1,6 +1,7 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.constants import ActorValue
|
||||
from app.core.database import get_db
|
||||
from app.core.security import require_api_key
|
||||
from app.modules.ai_agent.schemas import (
|
||||
@@ -8,6 +9,7 @@ from app.modules.ai_agent.schemas import (
|
||||
AIAskResponse,
|
||||
DraftPolicyRequest,
|
||||
InvestmentResearchRequest,
|
||||
OpenClawToolInvokeRequest,
|
||||
)
|
||||
from app.modules.ai_agent.service import AIService
|
||||
|
||||
@@ -19,6 +21,25 @@ def ask(payload: AIAskRequest, db: Session = Depends(get_db)) -> dict:
|
||||
return AIService(db).ask(payload.prompt, payload.context, payload.actor, payload.source)
|
||||
|
||||
|
||||
@router.get("/provider-health")
|
||||
def provider_health(actor: str = ActorValue.API, db: Session = Depends(get_db)) -> dict:
|
||||
return AIService(db).provider_health(actor=actor)
|
||||
|
||||
|
||||
@router.post("/openclaw/tools/invoke")
|
||||
def invoke_openclaw_tool(
|
||||
payload: OpenClawToolInvokeRequest,
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
return AIService(db).invoke_openclaw_tool(
|
||||
tool=payload.tool,
|
||||
action=payload.action,
|
||||
args=payload.args,
|
||||
session_key=payload.session_key,
|
||||
actor=payload.actor,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/draft-policy", response_model=AIAskResponse)
|
||||
def draft_policy(payload: DraftPolicyRequest, db: Session = Depends(get_db)) -> dict:
|
||||
return AIService(db).draft_policy(
|
||||
|
||||
@@ -2,12 +2,16 @@ from typing import Any
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.core.constants import ActorValue
|
||||
from app.modules.ai_agent.constants import AIDefault, AIRiskPreference
|
||||
from app.modules.audit.constants import AuditSource
|
||||
|
||||
|
||||
class AIAskRequest(BaseModel):
|
||||
prompt: str
|
||||
context: dict[str, Any] = Field(default_factory=dict)
|
||||
actor: str = "api"
|
||||
source: str = "api"
|
||||
actor: str = ActorValue.API
|
||||
source: str = AuditSource.API
|
||||
|
||||
|
||||
class AIAskResponse(BaseModel):
|
||||
@@ -16,14 +20,22 @@ class AIAskResponse(BaseModel):
|
||||
raw: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class OpenClawToolInvokeRequest(BaseModel):
|
||||
tool: str
|
||||
action: str = AIDefault.ACTION_JSON
|
||||
args: dict[str, Any] = Field(default_factory=dict)
|
||||
session_key: str = AIDefault.SESSION_KEY_MAIN
|
||||
actor: str = ActorValue.API
|
||||
|
||||
|
||||
class DraftPolicyRequest(BaseModel):
|
||||
title: str
|
||||
policy_type: str
|
||||
requirements: list[str]
|
||||
actor: str = "api"
|
||||
actor: str = ActorValue.API
|
||||
|
||||
|
||||
class InvestmentResearchRequest(BaseModel):
|
||||
symbol_or_topic: str
|
||||
risk_preference: str = "balanced"
|
||||
actor: str = "api"
|
||||
risk_preference: str = AIRiskPreference.BALANCED
|
||||
actor: str = ActorValue.API
|
||||
|
||||
@@ -2,7 +2,22 @@ from typing import Any
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.modules.ai_agent.adapters import get_adapter
|
||||
from app.core.constants import ActorValue
|
||||
from app.core.config import get_settings
|
||||
from app.modules.ai_agent.adapters import HermesAdapter, OpenClawAdapter, get_adapter
|
||||
from app.modules.ai_agent.constants import (
|
||||
AIDefault,
|
||||
AIProviderName,
|
||||
AIRequestKey,
|
||||
AIResponseKey,
|
||||
)
|
||||
from app.modules.ai_agent.skills import AISkillId, get_ai_skill
|
||||
from app.modules.audit.constants import (
|
||||
AuditAction,
|
||||
AuditRiskLevel,
|
||||
AuditSource,
|
||||
AuditTargetType,
|
||||
)
|
||||
from app.modules.audit.schemas import AuditLogCreate
|
||||
from app.modules.audit.service import AuditService
|
||||
|
||||
@@ -18,29 +33,109 @@ class AIService:
|
||||
self,
|
||||
prompt: str,
|
||||
context: dict[str, Any] | None = None,
|
||||
actor: str = "api",
|
||||
source: str = "api",
|
||||
actor: str = ActorValue.API,
|
||||
source: str = AuditSource.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", {}),
|
||||
AIResponseKey.PROVIDER: adapter.provider_name,
|
||||
AIResponseKey.ANSWER: result[AIResponseKey.ANSWER],
|
||||
AIResponseKey.RAW: result.get(AIResponseKey.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 {}},
|
||||
action=AuditAction.AI_ASK,
|
||||
target_type=AuditTargetType.AI,
|
||||
risk_level=AuditRiskLevel.MEDIUM,
|
||||
request_payload={
|
||||
AIRequestKey.PROMPT: prompt,
|
||||
AIRequestKey.CONTEXT: context or {},
|
||||
},
|
||||
response_payload=response,
|
||||
)
|
||||
)
|
||||
return response
|
||||
|
||||
def run_skill(
|
||||
self,
|
||||
skill_id: AISkillId | str,
|
||||
context: dict[str, Any] | None = None,
|
||||
variables: dict[str, Any] | None = None,
|
||||
actor: str = ActorValue.API,
|
||||
) -> dict[str, Any]:
|
||||
skill = get_ai_skill(skill_id)
|
||||
return self.ask(
|
||||
skill.render(variables),
|
||||
context=context or {},
|
||||
actor=actor,
|
||||
source=skill.source,
|
||||
)
|
||||
|
||||
def provider_health(self, actor: str = ActorValue.API) -> dict[str, Any]:
|
||||
settings = get_settings()
|
||||
openclaw = self._health_result(OpenClawAdapter(settings).health)
|
||||
hermes = self._health_result(HermesAdapter(settings).health)
|
||||
response = {
|
||||
"model_provider": settings.model_provider,
|
||||
AIProviderName.OPENCLAW: openclaw,
|
||||
AIProviderName.HERMES: hermes,
|
||||
}
|
||||
self.audit.log(
|
||||
AuditLogCreate(
|
||||
actor=actor,
|
||||
source=AuditSource.API,
|
||||
action=AuditAction.AI_PROVIDER_HEALTH,
|
||||
target_type=AuditTargetType.AI,
|
||||
risk_level=AuditRiskLevel.LOW,
|
||||
response_payload=response,
|
||||
)
|
||||
)
|
||||
return response
|
||||
|
||||
def invoke_openclaw_tool(
|
||||
self,
|
||||
tool: str,
|
||||
action: str = AIDefault.ACTION_JSON,
|
||||
args: dict[str, Any] | None = None,
|
||||
session_key: str = AIDefault.SESSION_KEY_MAIN,
|
||||
actor: str = ActorValue.API,
|
||||
) -> dict[str, Any]:
|
||||
result = OpenClawAdapter(get_settings()).invoke_tool(tool, action, args or {}, session_key)
|
||||
response = {AIResponseKey.PROVIDER: AIProviderName.OPENCLAW, AIResponseKey.RESULT: result}
|
||||
self.audit.log(
|
||||
AuditLogCreate(
|
||||
actor=actor,
|
||||
source=AuditSource.OPENCLAW,
|
||||
action=AuditAction.OPENCLAW_TOOLS_INVOKE,
|
||||
target_type=AuditTargetType.OPENCLAW_TOOL,
|
||||
target_id=tool,
|
||||
risk_level=AuditRiskLevel.HIGH,
|
||||
request_payload={
|
||||
"tool": tool,
|
||||
"action": action,
|
||||
"args": args or {},
|
||||
"session_key": session_key,
|
||||
},
|
||||
response_payload=result,
|
||||
)
|
||||
)
|
||||
return response
|
||||
|
||||
@staticmethod
|
||||
def _health_result(check: Any) -> dict[str, Any]:
|
||||
try:
|
||||
return check()
|
||||
except Exception as exc:
|
||||
# Health checks should report failures, not mask the other provider.
|
||||
return {
|
||||
AIResponseKey.OK: False,
|
||||
AIResponseKey.ERROR: str(exc),
|
||||
AIResponseKey.TYPE: type(exc).__name__,
|
||||
}
|
||||
|
||||
def draft_policy(
|
||||
self,
|
||||
title: str,
|
||||
@@ -48,12 +143,15 @@ class AIService:
|
||||
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.run_skill(
|
||||
AISkillId.DRAFT_POLICY,
|
||||
variables={
|
||||
"title": title,
|
||||
"policy_type": policy_type,
|
||||
"requirements": requirements,
|
||||
},
|
||||
actor=actor,
|
||||
)
|
||||
return self.ask(prompt, actor=actor, source="policy")
|
||||
|
||||
def draft_investment_research(
|
||||
self,
|
||||
@@ -61,10 +159,11 @@ class AIService:
|
||||
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.run_skill(
|
||||
AISkillId.INVESTMENT_RESEARCH,
|
||||
variables={
|
||||
"symbol_or_topic": symbol_or_topic,
|
||||
"risk_preference": risk_preference,
|
||||
},
|
||||
actor=actor,
|
||||
)
|
||||
return self.ask(prompt, actor=actor, source="investment")
|
||||
|
||||
101
app/modules/ai_agent/skills.py
Normal file
101
app/modules/ai_agent/skills.py
Normal file
@@ -0,0 +1,101 @@
|
||||
from dataclasses import dataclass
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
|
||||
class AISkillId(StrEnum):
|
||||
"""Stable identifiers for AI capabilities exposed to business modules."""
|
||||
|
||||
DRAFT_POLICY = "draft_policy"
|
||||
INVESTMENT_RESEARCH = "investment_research"
|
||||
PROJECT_LIFECYCLE_ANALYSIS = "project_lifecycle_analysis"
|
||||
HERMES_MEMORY_RECALL = "hermes_memory_recall"
|
||||
HERMES_MEMORY_WRITE = "hermes_memory_write"
|
||||
|
||||
|
||||
class AISkillSource(StrEnum):
|
||||
"""Audit source names for AI skill invocations."""
|
||||
|
||||
POLICY = "policy"
|
||||
INVESTMENT = "investment"
|
||||
REPORTS_LIFECYCLE = "reports.lifecycle"
|
||||
AI_MEMORY = "ai.memory"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AISkill:
|
||||
"""Business-facing AI skill definition."""
|
||||
|
||||
skill_id: AISkillId
|
||||
source: AISkillSource
|
||||
instruction_template: str
|
||||
|
||||
def render(self, variables: dict[str, Any] | None = None) -> str:
|
||||
return self.instruction_template.format(**(variables or {}))
|
||||
|
||||
|
||||
POLICY_DRAFT_INSTRUCTIONS = (
|
||||
"Draft a company policy in Chinese. Title: {title}. Type: {policy_type}. "
|
||||
"Include purpose, scope, roles, process, approval rules, audit rules, and KPI linkage. "
|
||||
"Requirements: {requirements}"
|
||||
)
|
||||
INVESTMENT_RESEARCH_INSTRUCTIONS = (
|
||||
"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. Topic: {symbol_or_topic}. "
|
||||
"Risk preference: {risk_preference}."
|
||||
)
|
||||
PROJECT_LIFECYCLE_ANALYSIS_INSTRUCTIONS = (
|
||||
"请基于项目全生命周期统计,输出中文管理层分析。"
|
||||
"包括总体判断、前三个风险、接下来一周优先动作。"
|
||||
"不要审批付款、不要最终定绩效、不要下投资交易指令。"
|
||||
)
|
||||
HERMES_MEMORY_RECALL_INSTRUCTIONS = (
|
||||
"Retrieve concise long-term memory, preferences, prior decisions, and relevant "
|
||||
"business context for this request. Return only information useful to answer it."
|
||||
)
|
||||
HERMES_MEMORY_WRITE_INSTRUCTIONS = (
|
||||
"Store durable lessons from this interaction for future company management "
|
||||
"assistance. Ignore transient details and do not store secrets."
|
||||
)
|
||||
|
||||
AI_SKILLS: dict[AISkillId, AISkill] = {
|
||||
AISkillId.DRAFT_POLICY: AISkill(
|
||||
skill_id=AISkillId.DRAFT_POLICY,
|
||||
source=AISkillSource.POLICY,
|
||||
instruction_template=POLICY_DRAFT_INSTRUCTIONS,
|
||||
),
|
||||
AISkillId.INVESTMENT_RESEARCH: AISkill(
|
||||
skill_id=AISkillId.INVESTMENT_RESEARCH,
|
||||
source=AISkillSource.INVESTMENT,
|
||||
instruction_template=INVESTMENT_RESEARCH_INSTRUCTIONS,
|
||||
),
|
||||
AISkillId.PROJECT_LIFECYCLE_ANALYSIS: AISkill(
|
||||
skill_id=AISkillId.PROJECT_LIFECYCLE_ANALYSIS,
|
||||
source=AISkillSource.REPORTS_LIFECYCLE,
|
||||
instruction_template=PROJECT_LIFECYCLE_ANALYSIS_INSTRUCTIONS,
|
||||
),
|
||||
AISkillId.HERMES_MEMORY_RECALL: AISkill(
|
||||
skill_id=AISkillId.HERMES_MEMORY_RECALL,
|
||||
source=AISkillSource.AI_MEMORY,
|
||||
instruction_template=HERMES_MEMORY_RECALL_INSTRUCTIONS,
|
||||
),
|
||||
AISkillId.HERMES_MEMORY_WRITE: AISkill(
|
||||
skill_id=AISkillId.HERMES_MEMORY_WRITE,
|
||||
source=AISkillSource.AI_MEMORY,
|
||||
instruction_template=HERMES_MEMORY_WRITE_INSTRUCTIONS,
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def get_ai_skill(skill_id: AISkillId | str) -> AISkill:
|
||||
try:
|
||||
normalized_id = AISkillId(skill_id)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"Unsupported AI skill: {skill_id}",
|
||||
) from exc
|
||||
return AI_SKILLS[normalized_id]
|
||||
Reference in New Issue
Block a user