智能体分权
This commit is contained in:
1 parent
e7a455f22e
commit
cf2e4bdd9c
31 files changed
+1237
-436
No files matched your search
@@ -106,6 +106,7 @@ _DEFAULT_ASSISTANT_ID = "lead_agent"
|
||||
# ``configurable`` for consumers like ``setup_agent``.
|
||||
_CONTEXT_CONFIGURABLE_KEYS: frozenset[str] = frozenset(
|
||||
{
|
||||
"agent_id",
|
||||
"model_name",
|
||||
"mode",
|
||||
"thinking_enabled",
|
||||
@@ -139,11 +140,11 @@ def merge_run_context_overrides(config: dict[str, Any], context: Mapping[str, An
|
||||
def resolve_agent_factory(assistant_id: str | None):
|
||||
"""Resolve the agent factory callable from config.
|
||||
|
||||
Custom agents are implemented as ``lead_agent`` + an ``agent_name``
|
||||
Custom agents are implemented as ``lead_agent`` + an ``agent_id``
|
||||
injected into ``configurable`` or ``context`` — see
|
||||
:func:`build_run_config`. All ``assistant_id`` values therefore map to the
|
||||
same factory; the routing happens inside ``make_lead_agent`` when it reads
|
||||
``cfg["agent_name"]``.
|
||||
``cfg["agent_id"]``.
|
||||
"""
|
||||
from deerflow.agents.lead_agent.agent import make_lead_agent
|
||||
|
||||
@@ -160,11 +161,11 @@ def build_run_config(
|
||||
"""Build a RunnableConfig dict for the agent.
|
||||
|
||||
When *assistant_id* refers to a custom agent (anything other than
|
||||
``"lead_agent"`` / ``None``), the name is forwarded as ``agent_name`` in
|
||||
``"lead_agent"`` / ``None``), the id is forwarded as ``agent_id`` in
|
||||
whichever runtime options container is active: ``context`` for
|
||||
LangGraph >= 0.6.0 requests, otherwise ``configurable``.
|
||||
``make_lead_agent`` reads this key to load the matching
|
||||
``agents/<name>/SOUL.md`` and per-agent config — without it the agent
|
||||
``agents/<id>/SOUL.md`` and per-agent config — without it the agent
|
||||
silently runs as the default lead agent.
|
||||
|
||||
This mirrors the channel manager's ``_resolve_run_params`` logic so that
|
||||
@@ -202,25 +203,96 @@ def build_run_config(
|
||||
else:
|
||||
config["configurable"] = {"thread_id": thread_id}
|
||||
|
||||
# Inject custom agent name when the caller specified a non-default assistant.
|
||||
# Honour an explicit agent_name in the active runtime options container.
|
||||
# Inject custom agent id when the caller specified a non-default assistant.
|
||||
# Honour an explicit agent_id in the active runtime options container.
|
||||
if assistant_id and assistant_id != _DEFAULT_ASSISTANT_ID:
|
||||
normalized = assistant_id.strip().lower().replace("_", "-")
|
||||
if not normalized or not re.fullmatch(r"[a-z0-9-]+", normalized):
|
||||
raise ValueError(f"Invalid assistant_id {assistant_id!r}: must contain only letters, digits, and hyphens after normalization.")
|
||||
normalized = assistant_id.strip()
|
||||
if not normalized or not re.fullmatch(r"[A-Za-z0-9_-]+", normalized):
|
||||
raise ValueError(f"Invalid assistant_id {assistant_id!r}: must contain only letters, digits, hyphens, and underscores.")
|
||||
if "configurable" in config:
|
||||
target = config["configurable"]
|
||||
elif "context" in config:
|
||||
target = config["context"]
|
||||
else:
|
||||
target = config.setdefault("configurable", {})
|
||||
if target is not None and "agent_name" not in target:
|
||||
target["agent_name"] = normalized
|
||||
if target is not None and "agent_id" not in target:
|
||||
target["agent_id"] = normalized
|
||||
if metadata:
|
||||
config.setdefault("metadata", {}).update(metadata)
|
||||
return config
|
||||
|
||||
|
||||
def _collect_requested_agent_ids(body: Any) -> set[str]:
|
||||
"""Collect agent ids from assistant_id/config/context for access checks."""
|
||||
agent_ids: set[str] = set()
|
||||
if body.assistant_id and body.assistant_id != _DEFAULT_ASSISTANT_ID:
|
||||
agent_ids.add(str(body.assistant_id))
|
||||
|
||||
def collect(container: Mapping[str, Any] | None) -> None:
|
||||
if not container:
|
||||
return
|
||||
for key in ("agent_id", "agent_name"):
|
||||
value = container.get(key)
|
||||
if value:
|
||||
agent_ids.add(str(value))
|
||||
|
||||
context = getattr(body, "context", None)
|
||||
if isinstance(context, Mapping):
|
||||
collect(context)
|
||||
|
||||
config = body.config or {}
|
||||
if isinstance(config, Mapping):
|
||||
nested_context = config.get("context")
|
||||
nested_configurable = config.get("configurable")
|
||||
if isinstance(nested_context, Mapping):
|
||||
collect(nested_context)
|
||||
if isinstance(nested_configurable, Mapping):
|
||||
collect(nested_configurable)
|
||||
|
||||
return agent_ids
|
||||
|
||||
|
||||
async def _sync_legacy_agent_records(store) -> None:
|
||||
"""Import existing folder-backed agents as built-in records."""
|
||||
from deerflow.config.agents_config import list_custom_agents
|
||||
|
||||
for agent_cfg in list_custom_agents():
|
||||
agent_id = agent_cfg.id or agent_cfg.name
|
||||
if not agent_id:
|
||||
continue
|
||||
await store.ensure_builtin(
|
||||
{
|
||||
"id": agent_id,
|
||||
"name": agent_cfg.name,
|
||||
"description": agent_cfg.description or "",
|
||||
"published": True,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
async def _enforce_agent_access(body: Any, request: Request) -> None:
|
||||
agent_ids = _collect_requested_agent_ids(body)
|
||||
if not agent_ids:
|
||||
return
|
||||
|
||||
from app.gateway.deps import get_agent_store
|
||||
from deerflow.config.agents_config import validate_agent_id
|
||||
from deerflow.runtime.user_context import get_effective_user_id
|
||||
|
||||
store = get_agent_store(request)
|
||||
await _sync_legacy_agent_records(store)
|
||||
user_id = get_effective_user_id()
|
||||
for agent_id in agent_ids:
|
||||
try:
|
||||
normalized = validate_agent_id(agent_id)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
||||
if normalized is None:
|
||||
continue
|
||||
if await store.get_visible(normalized, user_id) is None:
|
||||
raise HTTPException(status_code=404, detail=f"Agent {normalized} not found")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Run lifecycle
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -249,6 +321,8 @@ async def start_run(
|
||||
|
||||
disconnect = DisconnectMode.cancel if body.on_disconnect == "cancel" else DisconnectMode.continue_
|
||||
|
||||
await _enforce_agent_access(body, request)
|
||||
|
||||
try:
|
||||
record = await run_mgr.create_or_reject(
|
||||
thread_id,
|
||||
|
||||
Reference in new issue
Block a user