refactor: 移除 Redis/Rabbit 依赖,Agent Mongo 切至 ai_crm_angent_dev

This commit is contained in:
2026-10-22 00:02:46 +08:00
parent 8307ff95e4
commit 7685f280c6
25 changed files with 80 additions and 486 deletions
+2 -4
View File
@@ -2,10 +2,8 @@
# 可另建 gitignore 的 .env 覆盖本文件中的密钥
JWT_SECRET=your-secret-key-here-must-be-at-least-64-bytes-long-for-hs512-algorithm-security
MONGO_URI=mongodb://ecom_dmb_agent_dev:ecom_dmb_agent_dev@192.168.3.100:27017/?authSource=ecom_dmb_agent_dev
MONGO_DB=ecom_dmb_agent_dev
# 与 Server application-dev 同 Redis DB=2
REDIS_URL=redis://:redis_qinghua@192.168.3.100:6379/2
MONGO_URI=mongodb://ai_crm_angent_dev:ai_crm_angent_dev@192.168.3.100:27017/?authSource=ai_crm_angent_dev
MONGO_DB=ai_crm_angent_dev
SERVER_BASE_URL=http://localhost:8080
LLM_FALLBACK_ENABLED=true
LLM_FALLBACK_BASE_URL=https://api.deepseek.com/v1
+2 -4
View File
@@ -9,12 +9,10 @@
# 本地也可再建 gitignore 的 .env,会覆盖同名变量(便于放真实 Key)。
# 部署时 compose 注入 AGENT_ENV=test|pre|prod,并挂载对应 .env.{env}。
#
# Redis:与同环境 Server 共用同一 Redis DB,读缓存键 agent:llm:rt:*
JWT_SECRET=your-secret-key-here-must-be-at-least-64-bytes-long-for-hs512-algorithm-security
MONGO_URI=mongodb://ecom_dmb_agent_dev:ecom_dmb_agent_dev@192.168.3.100:27017/?authSource=ecom_dmb_agent_dev
MONGO_DB=ecom_dmb_agent_dev
REDIS_URL=redis://:redis_qinghua@192.168.3.100:6379/2
MONGO_URI=mongodb://ai_crm_angent_dev:ai_crm_angent_dev@192.168.3.100:27017/?authSource=ai_crm_angent_dev
MONGO_DB=ai_crm_angent_dev
SERVER_BASE_URL=http://localhost:8080
LLM_FALLBACK_ENABLED=true
LLM_FALLBACK_BASE_URL=https://api.deepseek.com/v1
-2
View File
@@ -1,10 +1,8 @@
# 预发环境(AGENT_ENV=pre,端口 8202)
# 与 Server application-pre 对齐:Redis DB=0、后端 8102
JWT_SECRET=your-secret-key-here-must-be-at-least-64-bytes-long-for-hs512-algorithm-security
MONGO_URI=mongodb://qinghua:mongo_qinghua@192.168.3.100:27017/?authSource=ecom_dmb_agent_pre
MONGO_DB=ecom_dmb_agent_pre
REDIS_URL=redis://:redis_qinghua@192.168.3.100:6379/0
SERVER_BASE_URL=http://192.168.3.101:8102
LLM_FALLBACK_ENABLED=false
LLM_FALLBACK_BASE_URL=
-2
View File
@@ -1,10 +1,8 @@
# 生产环境(AGENT_ENV=prod,端口 8203)
# 与 Server application-prod 对齐:Redis DB=0、后端 8103
JWT_SECRET=your-secret-key-here-must-be-at-least-64-bytes-long-for-hs512-algorithm-security
MONGO_URI=mongodb://qinghua:mongo_qinghua@192.168.3.100:27017/?authSource=ecom_dmb_agent
MONGO_DB=ecom_dmb_agent
REDIS_URL=redis://:redis_qinghua@192.168.3.100:6379/0
SERVER_BASE_URL=http://192.168.3.101:8103
LLM_FALLBACK_ENABLED=false
LLM_FALLBACK_BASE_URL=
-2
View File
@@ -1,10 +1,8 @@
# 测试环境(AGENT_ENV=test,端口 8201)
# 与 Server application-test 对齐:Redis DB=3、后端 8101
JWT_SECRET=your-secret-key-here-must-be-at-least-64-bytes-long-for-hs512-algorithm-security
MONGO_URI=mongodb://ecom_dmb_agent_test:ecom_dmb_agent_test@192.168.3.100:27017/?authSource=ecom_dmb_agent_test
MONGO_DB=ecom_dmb_agent_test
REDIS_URL=redis://:redis_qinghua@192.168.3.100:6379/3
SERVER_BASE_URL=http://192.168.3.101:8101
LLM_FALLBACK_ENABLED=false
LLM_FALLBACK_BASE_URL=
+2 -3
View File
@@ -37,9 +37,8 @@ API 前缀:`/api/agent/...`(会话/聊天/记忆;与前端代理 `/api/age
|------|------|
| `AGENT_ENV` | 选择 `.env.{env}` |
| `JWT_SECRET` | 与 Java `jwt.secret` 一致 |
| `MONGO_URI` / `MONGO_DB` | Agent 独立库(sessions / messages / memory) |
| `REDIS_URL` | **与同环境 Server 同 DB**,读 LLM 运行时缓存 `agent:llm:rt:*` |
| `SERVER_BASE_URL` | Java 根地址,内部拉 `/api/internal/agent/llm-runtime` |
| `MONGO_URI` / `MONGO_DB` | Agent 独立库(sessions / messages / memory);dev 默认 `ai_crm_angent_dev` |
| `SERVER_BASE_URL` | Java 根地址,内部拉 `/api/internal/agent/llm-runtime`(暂无 Redis 缓存) |
| `MCP_BASE_URL` / `MCP_BEARER_TOKEN` | 调 Server `/mcp`;Bearer 须与 Java `AGENT_MCP_TOKEN` / `ecom.agent.mcp.bearer-token` 一致,空则不加载 MCP 工具 |
| `LLM_FALLBACK_*` | 仅本地:公司未配置时的 OpenAI Compatible fallback |
| `CHAT_HISTORY_FETCH_LIMIT` | 从 Mongo 最多拉多少条再按 token 裁剪(默认 200) |
+8 -8
View File
@@ -13,17 +13,16 @@ from domain.models import Actor
from infrastructure.auth.jwt import parse_actor
from infrastructure.llm.factory import OpenAICompatibleStreamer
from infrastructure.llm.gateway import ServerLlmRuntimeGateway
from infrastructure.persistence.memory.cache import (
NoopLlmProtocolCapabilityCache,
NoopLlmRuntimeCache,
)
from infrastructure.persistence.mongo.client import get_db
from infrastructure.persistence.mongo.repositories import (
MongoMemoryRepository,
MongoMessageRepository,
MongoSessionRepository,
)
from infrastructure.persistence.redis.cache import (
RedisLlmProtocolCapabilityCache,
RedisLlmRuntimeCache,
get_redis,
)
async def current_actor(
@@ -41,8 +40,9 @@ async def current_actor(
async def llm_runtime_service(
settings: Settings = Depends(get_settings),
) -> LlmRuntimeService:
cache = RedisLlmRuntimeCache(get_redis(settings))
return LlmRuntimeService(settings, cache, ServerLlmRuntimeGateway(settings))
return LlmRuntimeService(
settings, NoopLlmRuntimeCache(), ServerLlmRuntimeGateway(settings)
)
async def session_service(
@@ -77,7 +77,7 @@ async def chat_service(
llm_runtime=llm_svc,
memory=mem_svc,
streamer=OpenAICompatibleStreamer(
RedisLlmProtocolCapabilityCache(get_redis(settings)),
NoopLlmProtocolCapabilityCache(),
capability_ttl_seconds=settings.llm_capability_ttl_seconds,
),
)
-2
View File
@@ -12,7 +12,6 @@ from api.response import fail
from api.routers import chat, memories, sessions
from config.settings import get_settings
from infrastructure.persistence.mongo.client import close_mongo, ensure_indexes, get_db
from infrastructure.persistence.redis.cache import close_redis
@asynccontextmanager
@@ -22,7 +21,6 @@ async def lifespan(_app: FastAPI):
await ensure_indexes(db)
yield
await close_mongo()
await close_redis()
def create_app() -> FastAPI:
@@ -1,4 +1,4 @@
"""租户 LLM 运行时解析:Redis → Server 内部 API → 本地 fallback。"""
"""租户 LLM 运行时解析:缓存(可 Noop)→ Server 内部 API → 本地 fallback。"""
from __future__ import annotations
+4 -6
View File
@@ -38,7 +38,7 @@ class Settings(BaseSettings):
extra="ignore",
)
app_name: str = "ecom-dmb-agent"
app_name: str = "ai-crm-agent"
# 当前环境名(只读展示;实际由 AGENT_ENV 决定加载哪个文件)
agent_env: str = _AGENT_ENV
host: str = "0.0.0.0"
@@ -49,11 +49,9 @@ class Settings(BaseSettings):
jwt_secret: str = "your-secret-key-here-must-be-at-least-64-bytes-long-for-hs512-algorithm-security"
jwt_algorithms: str = "HS512"
mongo_uri: str = "mongodb://ecom_dmb_agent_dev:ecom_dmb_agent_dev@192.168.3.100:27017/?authSource=ecom_dmb_agent_dev"
mongo_db: str = "ecom_dmb_agent_dev"
# 须与同环境 Server Redis 同库,才能命中 agent:llm:rt:* 缓存
redis_url: str = "redis://:redis_qinghua@192.168.3.100:6379/2"
mongo_uri: str = "mongodb://ai_crm_angent_dev:ai_crm_angent_dev@192.168.3.100:27017/?authSource=ai_crm_angent_dev"
mongo_db: str = "ai_crm_angent_dev"
# 本地缓存 TTL(当前为 Noop,直连 Server;预留)
llm_cache_ttl_seconds: int = 600
# Java Server 根地址(内部拉 LLM 运行时)
@@ -0,0 +1,44 @@
"""内存空实现:暂不接 Redis,LLM 运行时每次走 Server 内部 API。"""
from __future__ import annotations
from domain.models import LlmProtocolCapability, LlmRuntimeConfig
from domain.ports import LlmProtocolCapabilityCache, LlmRuntimeCache
class NoopLlmRuntimeCache(LlmRuntimeCache):
async def get(
self,
company_id: int,
provider_id: int | None = None,
model: str | None = None,
) -> LlmRuntimeConfig | None:
return None
async def set(
self,
company_id: int,
config: LlmRuntimeConfig,
ttl_seconds: int,
) -> None:
return None
async def delete(self, company_id: int) -> None:
return None
class NoopLlmProtocolCapabilityCache(LlmProtocolCapabilityCache):
async def get(
self, *, provider_id: int | None, base_url: str
) -> LlmProtocolCapability | None:
return None
async def set(
self,
*,
provider_id: int | None,
base_url: str,
capability: LlmProtocolCapability,
ttl_seconds: int,
) -> None:
return None
@@ -1,153 +0,0 @@
"""Redis 缓存租户 LLM 运行时配置(按公司+提供商+模型)。"""
from __future__ import annotations
import json
import redis.asyncio as redis
from config.settings import Settings
from domain.models import LlmProtocolCapability, LlmRuntimeConfig
from domain.ports import LlmProtocolCapabilityCache, LlmRuntimeCache
from infrastructure.llm.api_style import normalize_api_style
class RedisLlmRuntimeCache(LlmRuntimeCache):
def __init__(self, client: redis.Redis) -> None:
self._r = client
@staticmethod
def _key(company_id: int, provider_id: int | None, model: str | None) -> str:
if provider_id is not None and model:
return f"agent:llm:rt:{company_id}:{provider_id}:{model}"
if model:
return f"agent:llm:rt:{company_id}:{model}"
return f"agent:llm:rt:{company_id}"
async def get(
self,
company_id: int,
provider_id: int | None = None,
model: str | None = None,
) -> LlmRuntimeConfig | None:
raw = await self._r.get(self._key(company_id, provider_id, model))
if not raw and provider_id is not None and model:
# 兼容旧键 companyId:model
raw = await self._r.get(self._key(company_id, None, model))
if not raw:
return None
data = json.loads(raw)
cfg = LlmRuntimeConfig(
base_url=data["base_url"],
api_key=data["api_key"],
model=data["model"],
provider_id=_optional_int(data.get("provider_id")) or provider_id,
extra_headers=data.get("extra_headers") or {},
context_window=_optional_int(data.get("context_window")),
api_style=normalize_api_style(data.get("api_style")),
)
if model and cfg.model and cfg.model != model:
return None
if provider_id is not None and cfg.provider_id is not None and cfg.provider_id != provider_id:
return None
return cfg
async def set(
self,
company_id: int,
config: LlmRuntimeConfig,
ttl_seconds: int,
) -> None:
payload = {
"provider_id": config.provider_id,
"base_url": config.base_url,
"api_key": config.api_key,
"model": config.model,
"extra_headers": config.extra_headers,
"context_window": config.context_window,
"api_style": normalize_api_style(config.api_style),
}
await self._r.set(
self._key(company_id, config.provider_id, config.model),
json.dumps(payload),
ex=ttl_seconds,
)
async def delete(self, company_id: int) -> None:
keys = await self._r.keys(f"agent:llm:rt:{company_id}*")
if keys:
await self._r.delete(*keys)
_redis: redis.Redis | None = None
def _optional_int(v) -> int | None:
if v is None:
return None
try:
n = int(v)
except (TypeError, ValueError):
return None
return n if n > 0 else None
def get_redis(settings: Settings) -> redis.Redis:
global _redis
if _redis is None:
_redis = redis.from_url(settings.redis_url, decode_responses=True)
return _redis
class RedisLlmProtocolCapabilityCache(LlmProtocolCapabilityCache):
"""按 provider_id(优先)或 base_url 缓存 Responses/store 能力。"""
def __init__(self, client: redis.Redis) -> None:
self._r = client
@staticmethod
def _key(*, provider_id: int | None, base_url: str) -> str:
if provider_id is not None and int(provider_id) > 0:
return f"agent:llm:cap:p:{int(provider_id)}"
url = (base_url or "").rstrip("/").lower()
return f"agent:llm:cap:u:{url}"
async def get(
self, *, provider_id: int | None, base_url: str
) -> LlmProtocolCapability | None:
raw = await self._r.get(self._key(provider_id=provider_id, base_url=base_url))
if not raw:
return None
try:
data = json.loads(raw)
except json.JSONDecodeError:
return None
return LlmProtocolCapability(
responses=data.get("responses"),
store=data.get("store"),
)
async def set(
self,
*,
provider_id: int | None,
base_url: str,
capability: LlmProtocolCapability,
ttl_seconds: int,
) -> None:
payload = {
"responses": capability.responses,
"store": capability.store,
}
await self._r.set(
self._key(provider_id=provider_id, base_url=base_url),
json.dumps(payload),
ex=max(60, ttl_seconds),
)
async def close_redis() -> None:
global _redis
if _redis is not None:
await _redis.aclose()
_redis = None
-1
View File
@@ -5,7 +5,6 @@ pydantic>=2.9.0
pydantic-settings>=2.6.0
PyJWT>=2.9.0
motor>=3.6.0
redis>=5.2.0
httpx>=0.27.0
langchain-core>=0.3.0
langchain-openai>=0.3.26