```
feat: 添加飞书用户模块和订阅功能支持 - 新增feishu_users模块用于处理飞书用户身份验证和权限管理 - 新增subscriptions模块用于处理订阅相关功能 - 新增personalization模块用于个性化服务 - 在alembic迁移配置中注册新的模型模块 - 在API路由器中添加feishu_users和subscriptions路由 - 实现事件调度服务的改进,包括错误处理和状态更新优化 - 添加飞书命令处理的权限检查机制 - 实现飞书应用票据事件处理 - 改进审计日志记录功能 ```
This commit is contained in:
@@ -1,12 +1,13 @@
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
from app.modules.ai_agent.constants import (
|
||||
CHAT_USER_CONTENT_TEMPLATE,
|
||||
COMPANY_MANAGEMENT_SYSTEM_INSTRUCTIONS,
|
||||
UNEXPECTED_HERMES_RESPONSE,
|
||||
AIChatRole,
|
||||
AIContextKey,
|
||||
AIErrorKey,
|
||||
AIHttpPayloadKey,
|
||||
AIResponseKey,
|
||||
@@ -41,6 +42,7 @@ def _chat_completion_payload(response: Any, error_key: AIErrorKey) -> dict[str,
|
||||
|
||||
|
||||
def _chat_messages(prompt: str, context: dict[str, Any] | None = None) -> list[dict[str, str]]:
|
||||
request_context = context or {}
|
||||
return [
|
||||
{
|
||||
AIHttpPayloadKey.ROLE: AIChatRole.SYSTEM,
|
||||
@@ -48,14 +50,57 @@ def _chat_messages(prompt: str, context: dict[str, Any] | None = None) -> list[d
|
||||
},
|
||||
{
|
||||
AIHttpPayloadKey.ROLE: AIChatRole.USER,
|
||||
AIHttpPayloadKey.CONTENT: CHAT_USER_CONTENT_TEMPLATE.format(
|
||||
context=context or {},
|
||||
task=prompt,
|
||||
),
|
||||
AIHttpPayloadKey.CONTENT: _ordered_context(prompt, request_context),
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def _ordered_context(prompt: str, context: dict[str, Any]) -> str:
|
||||
"""Serialize trusted personalization layers in their required precedence."""
|
||||
|
||||
company_rules = context.get(AIContextKey.COMPANY_RULES)
|
||||
if company_rules is None:
|
||||
company_rules = context.get(AIContextKey.USER_RULES) or []
|
||||
controlled_keys = {
|
||||
AIContextKey.USER_RULES,
|
||||
AIContextKey.COMPANY_RULES,
|
||||
AIContextKey.PERSONAL_RULES,
|
||||
AIContextKey.PREFERENCES,
|
||||
AIContextKey.INTERESTS,
|
||||
AIContextKey.LOCAL_MEMORY,
|
||||
AIContextKey.CONVERSATION_HISTORY,
|
||||
AIContextKey.PROVIDER_SESSION_ID,
|
||||
AIContextKey.ALLOW_PROVIDER_MEMORY,
|
||||
}
|
||||
current_context = {
|
||||
str(key): value for key, value in context.items() if key not in controlled_keys
|
||||
}
|
||||
sections = [
|
||||
("公司规则", company_rules),
|
||||
("个人规则", context.get(AIContextKey.PERSONAL_RULES) or []),
|
||||
(
|
||||
"当前请求",
|
||||
{
|
||||
"prompt": prompt,
|
||||
"context": current_context,
|
||||
},
|
||||
),
|
||||
(
|
||||
"个人偏好与兴趣",
|
||||
{
|
||||
"preferences": context.get(AIContextKey.PREFERENCES) or [],
|
||||
"interests": context.get(AIContextKey.INTERESTS) or [],
|
||||
},
|
||||
),
|
||||
("个人相关记忆", context.get(AIContextKey.LOCAL_MEMORY) or []),
|
||||
("当前会话历史", context.get(AIContextKey.CONVERSATION_HISTORY) or []),
|
||||
]
|
||||
return "\n\n".join(
|
||||
f"{title}:\n{json.dumps(value, ensure_ascii=False, default=str)}"
|
||||
for title, value in sections
|
||||
)
|
||||
|
||||
|
||||
def _service_root(base_url: str, suffix: str) -> str:
|
||||
root = base_url.rstrip("/")
|
||||
normalized_suffix = suffix.rstrip("/")
|
||||
|
||||
@@ -15,6 +15,7 @@ from app.modules.ai_agent.constants import (
|
||||
AUTHORIZATION_BEARER_TEMPLATE,
|
||||
UNEXPECTED_HERMES_RESPONSE,
|
||||
AIErrorKey,
|
||||
AIContextKey,
|
||||
AIHttpHeader,
|
||||
AIHttpPath,
|
||||
AIHttpPayloadKey,
|
||||
@@ -38,11 +39,16 @@ class HermesAdapter(AIAdapter):
|
||||
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
|
||||
request_context = context or {}
|
||||
session_id = (
|
||||
request_context.get(AIContextKey.PROVIDER_SESSION_ID)
|
||||
or self.settings.hermes_session_id
|
||||
)
|
||||
if session_id:
|
||||
headers[AIHttpHeader.HERMES_SESSION_ID] = str(session_id)
|
||||
payload = {
|
||||
AIHttpPayloadKey.MODEL: self.settings.hermes_model,
|
||||
AIHttpPayloadKey.MESSAGES: _chat_messages(prompt, context),
|
||||
AIHttpPayloadKey.MESSAGES: _chat_messages(prompt, request_context),
|
||||
AIHttpPayloadKey.STREAM: False,
|
||||
}
|
||||
with httpx.Client(timeout=300, trust_env=False) as client:
|
||||
|
||||
@@ -32,7 +32,14 @@ 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)
|
||||
allow_provider_memory = bool(
|
||||
base_context.get(AIContextKey.ALLOW_PROVIDER_MEMORY, True)
|
||||
)
|
||||
recall = (
|
||||
self._recall_memory(prompt, base_context)
|
||||
if allow_provider_memory
|
||||
else {AIResponseKey.ANSWER: "", AIResponseKey.RAW: {}}
|
||||
)
|
||||
openclaw = self._openclaw_context(base_context)
|
||||
hermes_context = {
|
||||
**base_context,
|
||||
@@ -41,10 +48,14 @@ class OpenClawHermesAdapter(AIAdapter):
|
||||
AIContextKey.OPENCLAW: openclaw,
|
||||
}
|
||||
hermes_result = self.hermes.ask(prompt, hermes_context)
|
||||
remember = self._remember_interaction(
|
||||
prompt,
|
||||
base_context,
|
||||
hermes_result[AIResponseKey.ANSWER],
|
||||
remember = (
|
||||
self._remember_interaction(
|
||||
prompt,
|
||||
base_context,
|
||||
hermes_result[AIResponseKey.ANSWER],
|
||||
)
|
||||
if allow_provider_memory
|
||||
else {AIResponseKey.OK: False, AIResponseKey.RAW: {}}
|
||||
)
|
||||
return {
|
||||
AIResponseKey.ANSWER: hermes_result[AIResponseKey.ANSWER],
|
||||
|
||||
@@ -60,6 +60,14 @@ class AIContextKey(StrEnum):
|
||||
REQUEST_CONTEXT = "request_context"
|
||||
ASSISTANT_ANSWER = "assistant_answer"
|
||||
USER_RULES = "user_rules"
|
||||
COMPANY_RULES = "company_rules"
|
||||
PERSONAL_RULES = "personal_rules"
|
||||
PREFERENCES = "preferences"
|
||||
INTERESTS = "interests"
|
||||
CONVERSATION_HISTORY = "conversation_history"
|
||||
PROVIDER_SESSION_ID = "provider_session_id"
|
||||
ALLOW_PROVIDER_MEMORY = "allow_provider_memory"
|
||||
EXECUTION_MODE = "execution_mode"
|
||||
|
||||
|
||||
class AIMemoryMode(StrEnum):
|
||||
@@ -67,6 +75,14 @@ class AIMemoryMode(StrEnum):
|
||||
WRITE = "memory_write"
|
||||
|
||||
|
||||
class AIExecutionMode(StrEnum):
|
||||
INTERNAL = "internal"
|
||||
PERSONALIZED = "personalized"
|
||||
PREFERENCE_EXTRACTION = "preference_extraction"
|
||||
SCHEDULED_PRIVATE = "scheduled_private"
|
||||
SCHEDULED_GROUP = "scheduled_group"
|
||||
|
||||
|
||||
class AIHttpPath(StrEnum):
|
||||
CHAT_COMPLETIONS = "/chat/completions"
|
||||
HEALTH = "/health"
|
||||
@@ -95,13 +111,6 @@ class AIHttpPayloadKey(StrEnum):
|
||||
MESSAGE = "message"
|
||||
|
||||
|
||||
class AIToolAuditKey(StrEnum):
|
||||
TOOL = "tool"
|
||||
ACTION = "action"
|
||||
ARGS = "args"
|
||||
SESSION_KEY = "session_key"
|
||||
|
||||
|
||||
class AIChatRole(StrEnum):
|
||||
SYSTEM = "system"
|
||||
USER = "user"
|
||||
@@ -133,16 +142,25 @@ 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."
|
||||
"Set MODEL_PROVIDER to openclaw_hermes, hermes, or direct_llm after "
|
||||
"credentials are ready."
|
||||
)
|
||||
AI_UNAVAILABLE_ANSWER = "AI 当前不可用,请稍后重试。"
|
||||
PREFERENCE_EXTRACTION_INSTRUCTIONS = (
|
||||
"Extract only durable user communication preferences from the supplied user text. "
|
||||
"Allowed categories are language, tone, detail, topic, and interest. "
|
||||
"Return strict JSON only in this shape: "
|
||||
'{"preferences":[{"category":"language","value":"中文"}]}. '
|
||||
"Return an empty preferences list when there is no durable preference. "
|
||||
"Never return secrets, credentials, health, religion, politics, sexual orientation, "
|
||||
"performance, compensation, or confidential financial information."
|
||||
)
|
||||
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"
|
||||
OPENCLAW_CHAT_PROVIDER_REQUIRED = (
|
||||
"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."
|
||||
"OpenClaw Gateway is not exposed as a tool-execution provider. "
|
||||
"Use MODEL_PROVIDER=hermes, openclaw_hermes, or direct_llm for AI answers."
|
||||
)
|
||||
OPENCLAW_TOOL_NOT_ALLOWED = "OpenClaw tool is not allowed"
|
||||
OPENCLAW_ACTION_NOT_ALLOWED = "OpenClaw action is not allowed"
|
||||
|
||||
@@ -2,14 +2,13 @@ from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.security import ApiPrincipal, require_api_key, require_operations_enabled
|
||||
from app.core.security import ApiPrincipal, require_api_key
|
||||
from app.modules.audit.constants import AuditSource
|
||||
from app.modules.ai_agent.schemas import (
|
||||
AIAskRequest,
|
||||
AIAskResponse,
|
||||
DraftPolicyRequest,
|
||||
InvestmentResearchRequest,
|
||||
OpenClawToolInvokeRequest,
|
||||
)
|
||||
from app.modules.ai_agent.service import AIService
|
||||
|
||||
@@ -38,22 +37,6 @@ def provider_health(
|
||||
return AIService(db).provider_health(actor=principal.actor)
|
||||
|
||||
|
||||
@router.post("/openclaw/tools/invoke")
|
||||
def invoke_openclaw_tool(
|
||||
payload: OpenClawToolInvokeRequest,
|
||||
db: Session = Depends(get_db),
|
||||
principal: ApiPrincipal = Depends(require_api_key),
|
||||
) -> dict:
|
||||
require_operations_enabled()
|
||||
return AIService(db).invoke_openclaw_tool(
|
||||
tool=payload.tool,
|
||||
action=payload.action,
|
||||
args=payload.args,
|
||||
session_key=payload.session_key,
|
||||
actor=principal.actor,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/draft-policy", response_model=AIAskResponse)
|
||||
def draft_policy(
|
||||
payload: DraftPolicyRequest,
|
||||
|
||||
@@ -3,7 +3,7 @@ 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.ai_agent.constants import AIRiskPreference
|
||||
from app.modules.audit.constants import AuditSource
|
||||
|
||||
|
||||
@@ -15,17 +15,11 @@ class AIAskRequest(BaseModel):
|
||||
|
||||
|
||||
class AIAskResponse(BaseModel):
|
||||
ok: bool = True
|
||||
provider: str
|
||||
answer: str
|
||||
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
|
||||
error: str | None = None
|
||||
|
||||
|
||||
class DraftPolicyRequest(BaseModel):
|
||||
|
||||
@@ -1,20 +1,23 @@
|
||||
from typing import Any
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
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,
|
||||
AI_UNAVAILABLE_ANSWER,
|
||||
AI_AUDIT_MAX_DEPTH,
|
||||
AI_AUDIT_MAX_SEQUENCE_ITEMS,
|
||||
AI_AUDIT_MAX_TEXT_LENGTH,
|
||||
AI_AUDIT_REDACTED_VALUE,
|
||||
AI_AUDIT_SENSITIVE_KEYS,
|
||||
AI_AUDIT_TRUNCATED_VALUE,
|
||||
AIToolAuditKey,
|
||||
COMPANY_MANAGEMENT_SYSTEM_INSTRUCTIONS,
|
||||
PREFERENCE_EXTRACTION_INSTRUCTIONS,
|
||||
AIContextKey,
|
||||
AIExecutionMode,
|
||||
AIProviderName,
|
||||
AIRequestKey,
|
||||
AIResponseKey,
|
||||
@@ -30,6 +33,13 @@ from app.modules.audit.constants import (
|
||||
)
|
||||
from app.modules.audit.schemas import AuditLogCreate
|
||||
from app.modules.audit.service import AuditService
|
||||
from app.modules.personalization.services import (
|
||||
ConversationService,
|
||||
PersonalizationContext,
|
||||
PersonalizationContextService,
|
||||
PreferenceService,
|
||||
)
|
||||
from app.modules.personalization.services.preferences import contains_preference_signal
|
||||
|
||||
|
||||
class AIService:
|
||||
@@ -46,15 +56,30 @@ class AIService:
|
||||
actor: str = ActorValue.API,
|
||||
source: str = AuditSource.API,
|
||||
) -> dict[str, Any]:
|
||||
request_context = dict(context or {})
|
||||
_validate_external_context(request_context)
|
||||
adapter = get_adapter()
|
||||
original_context = context or {}
|
||||
adapter_context = dict(original_context)
|
||||
if _is_unavailable_adapter(adapter):
|
||||
response = _unavailable_response(adapter.provider_name)
|
||||
self._audit_ai_response(
|
||||
actor=actor,
|
||||
source=source,
|
||||
request_payload={
|
||||
AIRequestKey.PROMPT: prompt,
|
||||
AIRequestKey.CONTEXT: request_context,
|
||||
},
|
||||
response=response,
|
||||
)
|
||||
return response
|
||||
|
||||
adapter_context = dict(request_context)
|
||||
memory_service = AIMemoryService(self.db)
|
||||
memory_scope = _memory_scope(original_context)
|
||||
memory_subject = _memory_subject(original_context)
|
||||
memory_scope = _memory_scope(request_context)
|
||||
memory_subject = _memory_subject(request_context)
|
||||
user_rules = memory_service.active_rules(
|
||||
scope=memory_scope,
|
||||
subject=memory_subject,
|
||||
owner_id=None,
|
||||
)
|
||||
if user_rules:
|
||||
adapter_context[AIContextKey.USER_RULES] = user_rules
|
||||
@@ -63,6 +88,7 @@ class AIService:
|
||||
scope=memory_scope,
|
||||
subject=memory_subject,
|
||||
actor=actor,
|
||||
owner_id=None,
|
||||
)
|
||||
if local_memory:
|
||||
adapter_context[AIContextKey.LOCAL_MEMORY] = local_memory
|
||||
@@ -73,9 +99,10 @@ class AIService:
|
||||
raw[AIResponseKey.LOCAL_MEMORY] = local_memory
|
||||
memory_record = memory_service.auto_write(
|
||||
prompt=prompt,
|
||||
context=original_context,
|
||||
context=request_context,
|
||||
answer=answer,
|
||||
actor=actor,
|
||||
owner_id=None,
|
||||
)
|
||||
if memory_record is not None:
|
||||
raw[AIResponseKey.MEMORY_WRITE] = {
|
||||
@@ -83,10 +110,253 @@ class AIService:
|
||||
AIMemoryPayloadKey.STATUS: memory_record.status,
|
||||
}
|
||||
response = {
|
||||
AIResponseKey.OK: True,
|
||||
AIResponseKey.PROVIDER: adapter.provider_name,
|
||||
AIResponseKey.ANSWER: answer,
|
||||
AIResponseKey.RAW: raw,
|
||||
}
|
||||
self._audit_ai_response(
|
||||
actor=actor,
|
||||
source=source,
|
||||
request_payload={
|
||||
AIRequestKey.PROMPT: prompt,
|
||||
AIRequestKey.CONTEXT: request_context,
|
||||
},
|
||||
response=response,
|
||||
)
|
||||
return response
|
||||
|
||||
def ask_personalized(
|
||||
self,
|
||||
owner_id: int,
|
||||
chat_type: str,
|
||||
chat_key: str,
|
||||
prompt: str,
|
||||
actor: str = ActorValue.FEISHU,
|
||||
source: str = AuditSource.FEISHU,
|
||||
scope: str = AIMemoryScope.USER,
|
||||
subject: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Answer with one verified owner's isolated personalization context."""
|
||||
|
||||
_validate_owner_id(owner_id)
|
||||
_validate_prompt(prompt)
|
||||
session_id = ConversationService.provider_session_id(
|
||||
owner_id,
|
||||
chat_type,
|
||||
chat_key,
|
||||
)
|
||||
adapter = get_adapter()
|
||||
if _is_unavailable_adapter(adapter):
|
||||
response = _unavailable_response(adapter.provider_name)
|
||||
self._audit_ai_response(
|
||||
actor=actor,
|
||||
source=source,
|
||||
request_payload={
|
||||
"owner_id": owner_id,
|
||||
"chat_type": chat_type,
|
||||
AIContextKey.EXECUTION_MODE: AIExecutionMode.PERSONALIZED,
|
||||
},
|
||||
response=response,
|
||||
)
|
||||
return response
|
||||
|
||||
memory_subject = subject or f"owner:{owner_id}"
|
||||
personalization = PersonalizationContextService(self.db).build(
|
||||
owner_id=owner_id,
|
||||
request=prompt,
|
||||
system_constraints=COMPANY_MANAGEMENT_SYSTEM_INSTRUCTIONS,
|
||||
chat_type=chat_type,
|
||||
chat_key=chat_key,
|
||||
scope=scope,
|
||||
subject=memory_subject,
|
||||
actor=actor,
|
||||
include_company_rules=True,
|
||||
include_personal_context=True,
|
||||
include_history=True,
|
||||
)
|
||||
adapter_context = _adapter_context(
|
||||
personalization,
|
||||
execution_mode=AIExecutionMode.PERSONALIZED,
|
||||
allow_provider_memory=False,
|
||||
provider_session_id=session_id,
|
||||
)
|
||||
result = adapter.ask(prompt, adapter_context)
|
||||
answer = _required_answer(result)
|
||||
raw = dict(result.get(AIResponseKey.RAW, {}))
|
||||
|
||||
ConversationService(self.db).record_turn(
|
||||
owner_id,
|
||||
chat_type,
|
||||
chat_key,
|
||||
user_content=prompt,
|
||||
assistant_content=answer,
|
||||
provider_name=str(adapter.provider_name),
|
||||
)
|
||||
memory_record = AIMemoryService(self.db).auto_write(
|
||||
prompt=prompt,
|
||||
context={
|
||||
AIMemoryPayloadKey.SCOPE: scope,
|
||||
AIMemoryPayloadKey.SUBJECT: memory_subject,
|
||||
},
|
||||
answer=answer,
|
||||
actor=actor,
|
||||
owner_id=owner_id,
|
||||
)
|
||||
if memory_record is not None:
|
||||
raw[AIResponseKey.MEMORY_WRITE] = {
|
||||
AIMemoryPayloadKey.CODE: memory_record.code,
|
||||
AIMemoryPayloadKey.STATUS: memory_record.status,
|
||||
}
|
||||
saved_preferences = self._extract_preferences(
|
||||
adapter=adapter,
|
||||
owner_id=owner_id,
|
||||
user_text=prompt,
|
||||
provider_session_id=session_id,
|
||||
)
|
||||
if saved_preferences:
|
||||
raw["preferences_saved"] = [
|
||||
{
|
||||
"code": item["code"],
|
||||
"category": item["category"],
|
||||
}
|
||||
for item in saved_preferences
|
||||
]
|
||||
|
||||
response = {
|
||||
AIResponseKey.OK: True,
|
||||
AIResponseKey.PROVIDER: adapter.provider_name,
|
||||
AIResponseKey.ANSWER: answer,
|
||||
AIResponseKey.RAW: raw,
|
||||
}
|
||||
self._audit_ai_response(
|
||||
actor=actor,
|
||||
source=source,
|
||||
request_payload={
|
||||
"owner_id": owner_id,
|
||||
"chat_type": chat_type,
|
||||
AIContextKey.EXECUTION_MODE: AIExecutionMode.PERSONALIZED,
|
||||
},
|
||||
response={
|
||||
AIResponseKey.OK: True,
|
||||
AIResponseKey.PROVIDER: adapter.provider_name,
|
||||
},
|
||||
)
|
||||
return response
|
||||
|
||||
def generate_scheduled(
|
||||
self,
|
||||
prompt: str,
|
||||
owner_id: int | None,
|
||||
group: bool,
|
||||
actor: str = "subscription-system",
|
||||
) -> dict[str, Any]:
|
||||
"""Generate side-effect-free scheduled content within its target boundary."""
|
||||
|
||||
_validate_prompt(prompt)
|
||||
if not group:
|
||||
if owner_id is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Private scheduled generation requires an owner",
|
||||
)
|
||||
_validate_owner_id(owner_id)
|
||||
|
||||
adapter = get_adapter()
|
||||
execution_mode = (
|
||||
AIExecutionMode.SCHEDULED_GROUP
|
||||
if group
|
||||
else AIExecutionMode.SCHEDULED_PRIVATE
|
||||
)
|
||||
if _is_unavailable_adapter(adapter):
|
||||
response = _unavailable_response(adapter.provider_name)
|
||||
self._audit_ai_response(
|
||||
actor=actor,
|
||||
source=AuditSource.FEISHU,
|
||||
request_payload={AIContextKey.EXECUTION_MODE: execution_mode},
|
||||
response=response,
|
||||
)
|
||||
return response
|
||||
|
||||
context_service = PersonalizationContextService(self.db)
|
||||
if group:
|
||||
personalization = context_service.build_group_scheduled(
|
||||
request=prompt,
|
||||
system_constraints=COMPANY_MANAGEMENT_SYSTEM_INSTRUCTIONS,
|
||||
)
|
||||
else:
|
||||
personalization = context_service.build_private_scheduled(
|
||||
owner_id=owner_id,
|
||||
request=prompt,
|
||||
system_constraints=COMPANY_MANAGEMENT_SYSTEM_INSTRUCTIONS,
|
||||
actor=actor,
|
||||
scope=AIMemoryScope.USER,
|
||||
subject=f"owner:{owner_id}",
|
||||
)
|
||||
adapter_context = _adapter_context(
|
||||
personalization,
|
||||
execution_mode=execution_mode,
|
||||
allow_provider_memory=False,
|
||||
provider_session_id=None,
|
||||
)
|
||||
result = adapter.ask(prompt, adapter_context)
|
||||
response = {
|
||||
AIResponseKey.OK: True,
|
||||
AIResponseKey.PROVIDER: adapter.provider_name,
|
||||
AIResponseKey.ANSWER: _required_answer(result),
|
||||
AIResponseKey.RAW: dict(result.get(AIResponseKey.RAW, {})),
|
||||
}
|
||||
self._audit_ai_response(
|
||||
actor=actor,
|
||||
source=AuditSource.FEISHU,
|
||||
request_payload={AIContextKey.EXECUTION_MODE: execution_mode},
|
||||
response={
|
||||
AIResponseKey.OK: True,
|
||||
AIResponseKey.PROVIDER: adapter.provider_name,
|
||||
},
|
||||
)
|
||||
return response
|
||||
|
||||
def _extract_preferences(
|
||||
self,
|
||||
*,
|
||||
adapter: Any,
|
||||
owner_id: int,
|
||||
user_text: str,
|
||||
provider_session_id: str,
|
||||
) -> list[dict[str, Any]]:
|
||||
if not contains_preference_signal(user_text):
|
||||
return []
|
||||
extraction_context = {
|
||||
"preference_source_text": user_text,
|
||||
AIContextKey.PROVIDER_SESSION_ID: f"{provider_session_id}-preferences",
|
||||
AIContextKey.ALLOW_PROVIDER_MEMORY: False,
|
||||
AIContextKey.EXECUTION_MODE: AIExecutionMode.PREFERENCE_EXTRACTION,
|
||||
}
|
||||
try:
|
||||
extraction = adapter.ask(
|
||||
PREFERENCE_EXTRACTION_INSTRUCTIONS,
|
||||
extraction_context,
|
||||
)
|
||||
structured_payload = extraction.get(AIResponseKey.ANSWER, "")
|
||||
return PreferenceService(self.db).save_auto_extraction(
|
||||
owner_id,
|
||||
provider_name=str(adapter.provider_name),
|
||||
user_text=user_text,
|
||||
structured_payload=structured_payload,
|
||||
)
|
||||
except Exception:
|
||||
# Preference inference must never block or change the primary answer.
|
||||
return []
|
||||
|
||||
def _audit_ai_response(
|
||||
self,
|
||||
*,
|
||||
actor: str,
|
||||
source: str,
|
||||
request_payload: dict[str, Any],
|
||||
response: dict[str, Any],
|
||||
) -> None:
|
||||
self.audit.log(
|
||||
AuditLogCreate(
|
||||
actor=actor,
|
||||
@@ -94,14 +364,10 @@ class AIService:
|
||||
action=AuditAction.AI_ASK,
|
||||
target_type=AuditTargetType.AI,
|
||||
risk_level=AuditRiskLevel.MEDIUM,
|
||||
request_payload=_audit_safe_payload({
|
||||
AIRequestKey.PROMPT: prompt,
|
||||
AIRequestKey.CONTEXT: context or {},
|
||||
}),
|
||||
request_payload=_audit_safe_payload(request_payload),
|
||||
response_payload=_audit_safe_payload(response),
|
||||
)
|
||||
)
|
||||
return response
|
||||
|
||||
def run_skill(
|
||||
self,
|
||||
@@ -139,35 +405,6 @@ class AIService:
|
||||
)
|
||||
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=_audit_safe_payload({
|
||||
AIToolAuditKey.TOOL: tool,
|
||||
AIToolAuditKey.ACTION: action,
|
||||
AIToolAuditKey.ARGS: args or {},
|
||||
AIToolAuditKey.SESSION_KEY: session_key,
|
||||
}),
|
||||
response_payload=_audit_safe_payload(result),
|
||||
)
|
||||
)
|
||||
return response
|
||||
|
||||
@staticmethod
|
||||
def _health_result(check: Any) -> dict[str, Any]:
|
||||
try:
|
||||
@@ -247,3 +484,103 @@ def _memory_scope(context: dict[str, Any]) -> str:
|
||||
def _memory_subject(context: dict[str, Any]) -> str | None:
|
||||
value = context.get(AIContextKey.MEMORY_SUBJECT) or context.get(AIMemoryPayloadKey.SUBJECT)
|
||||
return str(value) if value else None
|
||||
|
||||
|
||||
def _validate_external_context(context: dict[str, Any]) -> None:
|
||||
controlled_keys = {
|
||||
AIContextKey.OPENCLAW_TOOL,
|
||||
AIContextKey.OPENCLAW_ACTION,
|
||||
AIContextKey.OPENCLAW_ARGS,
|
||||
AIContextKey.OPENCLAW_SESSION_KEY,
|
||||
AIContextKey.AGENT_PIPELINE,
|
||||
AIContextKey.HERMES_MEMORY,
|
||||
AIContextKey.LOCAL_MEMORY,
|
||||
AIContextKey.OPENCLAW,
|
||||
AIContextKey.MODE,
|
||||
AIContextKey.USER_PROMPT,
|
||||
AIContextKey.REQUEST_CONTEXT,
|
||||
AIContextKey.ASSISTANT_ANSWER,
|
||||
AIContextKey.USER_RULES,
|
||||
AIContextKey.COMPANY_RULES,
|
||||
AIContextKey.PERSONAL_RULES,
|
||||
AIContextKey.PREFERENCES,
|
||||
AIContextKey.INTERESTS,
|
||||
AIContextKey.CONVERSATION_HISTORY,
|
||||
AIContextKey.PROVIDER_SESSION_ID,
|
||||
AIContextKey.ALLOW_PROVIDER_MEMORY,
|
||||
AIContextKey.EXECUTION_MODE,
|
||||
"system_constraints",
|
||||
"current_request",
|
||||
"personal_memory",
|
||||
"owner_id",
|
||||
"tenant_key",
|
||||
"open_id",
|
||||
}
|
||||
supplied = {str(key) for key in context}
|
||||
if supplied.intersection(str(key) for key in controlled_keys):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Controlled AI context fields are not allowed",
|
||||
)
|
||||
|
||||
|
||||
def _adapter_context(
|
||||
personalization: PersonalizationContext,
|
||||
*,
|
||||
execution_mode: AIExecutionMode,
|
||||
allow_provider_memory: bool,
|
||||
provider_session_id: str | None,
|
||||
) -> dict[str, Any]:
|
||||
context: dict[str, Any] = {
|
||||
AIContextKey.COMPANY_RULES: personalization.company_rules,
|
||||
AIContextKey.PERSONAL_RULES: personalization.personal_rules,
|
||||
AIContextKey.PREFERENCES: personalization.preferences,
|
||||
AIContextKey.INTERESTS: personalization.interests,
|
||||
AIContextKey.LOCAL_MEMORY: personalization.personal_memory,
|
||||
AIContextKey.CONVERSATION_HISTORY: personalization.conversation_history,
|
||||
}
|
||||
if provider_session_id:
|
||||
context[AIContextKey.PROVIDER_SESSION_ID] = provider_session_id
|
||||
context[AIContextKey.ALLOW_PROVIDER_MEMORY] = allow_provider_memory
|
||||
context[AIContextKey.EXECUTION_MODE] = execution_mode
|
||||
return context
|
||||
|
||||
|
||||
def _is_unavailable_adapter(adapter: Any) -> bool:
|
||||
return str(getattr(adapter, "provider_name", "")).strip().lower() == AIProviderName.NOOP
|
||||
|
||||
|
||||
def _unavailable_response(provider_name: Any) -> dict[str, Any]:
|
||||
return {
|
||||
AIResponseKey.OK: False,
|
||||
AIResponseKey.PROVIDER: str(provider_name or AIProviderName.NOOP),
|
||||
AIResponseKey.ANSWER: AI_UNAVAILABLE_ANSWER,
|
||||
AIResponseKey.RAW: {"reason": "provider_unavailable"},
|
||||
AIResponseKey.ERROR: "AI provider unavailable",
|
||||
}
|
||||
|
||||
|
||||
def _required_answer(result: dict[str, Any]) -> str:
|
||||
answer = str(result.get(AIResponseKey.ANSWER) or "").strip()
|
||||
if not answer:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail="AI provider returned an empty answer",
|
||||
)
|
||||
return answer
|
||||
|
||||
|
||||
def _validate_owner_id(owner_id: int) -> None:
|
||||
if owner_id <= 0:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Valid AI owner is required",
|
||||
)
|
||||
|
||||
|
||||
def _validate_prompt(prompt: str) -> None:
|
||||
if not str(prompt).strip():
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="AI prompt is required",
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user