200 lines
6.8 KiB
Python
200 lines
6.8 KiB
Python
"""Assistants compatibility endpoints.
|
|
|
|
Provides LangGraph Platform-compatible assistants API backed by the
|
|
``langgraph.json`` graph registry and ``config.yaml`` agent definitions.
|
|
|
|
This is a minimal stub that satisfies the ``useStream`` React hook's
|
|
initialization requirements (``assistants.search()`` and ``assistants.get()``).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
from datetime import UTC, datetime
|
|
from typing import Any
|
|
|
|
from fastapi import APIRouter, HTTPException, Request
|
|
from pydantic import BaseModel, Field
|
|
|
|
logger = logging.getLogger(__name__)
|
|
router = APIRouter(prefix="/api/assistants", tags=["assistants-compat"])
|
|
|
|
|
|
class AssistantResponse(BaseModel):
|
|
assistant_id: str
|
|
graph_id: str
|
|
name: str
|
|
config: dict[str, Any] = Field(default_factory=dict)
|
|
metadata: dict[str, Any] = Field(default_factory=dict)
|
|
description: str | None = None
|
|
created_at: str = ""
|
|
updated_at: str = ""
|
|
version: int = 1
|
|
|
|
|
|
class AssistantSearchRequest(BaseModel):
|
|
graph_id: str | None = None
|
|
name: str | None = None
|
|
metadata: dict[str, Any] | None = None
|
|
limit: int = 10
|
|
offset: int = 0
|
|
|
|
|
|
def _get_default_assistant() -> AssistantResponse:
|
|
"""Return the default lead_agent assistant."""
|
|
now = datetime.now(UTC).isoformat()
|
|
return AssistantResponse(
|
|
assistant_id="lead_agent",
|
|
graph_id="lead_agent",
|
|
name="lead_agent",
|
|
config={},
|
|
metadata={"created_by": "system"},
|
|
description="DeerFlow lead agent",
|
|
created_at=now,
|
|
updated_at=now,
|
|
version=1,
|
|
)
|
|
|
|
|
|
async def _sync_legacy_agents(store) -> None:
|
|
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 agent_id:
|
|
await store.ensure_builtin(
|
|
{
|
|
"id": agent_id,
|
|
"name": agent_cfg.name,
|
|
"description": agent_cfg.description or "",
|
|
"published": True,
|
|
}
|
|
)
|
|
|
|
|
|
def _legacy_assistants() -> list[AssistantResponse]:
|
|
assistants: list[AssistantResponse] = []
|
|
try:
|
|
from deerflow.config.agents_config import list_custom_agents
|
|
|
|
for agent_cfg in list_custom_agents():
|
|
now = datetime.now(UTC).isoformat()
|
|
assistant_id = agent_cfg.id or agent_cfg.name
|
|
assistants.append(
|
|
AssistantResponse(
|
|
assistant_id=assistant_id,
|
|
graph_id="lead_agent",
|
|
name=agent_cfg.name,
|
|
config={},
|
|
metadata={"created_by": "system", "agent_id": assistant_id},
|
|
description=agent_cfg.description or "",
|
|
created_at=now,
|
|
updated_at=now,
|
|
version=1,
|
|
)
|
|
)
|
|
except Exception:
|
|
logger.debug("Could not load legacy custom agents for assistants list")
|
|
return assistants
|
|
|
|
|
|
async def _list_assistants(request: Request) -> list[AssistantResponse]:
|
|
"""List all available assistants from config."""
|
|
assistants = [_get_default_assistant()]
|
|
|
|
try:
|
|
from app.gateway.deps import get_agent_store
|
|
from deerflow.runtime.user_context import get_effective_user_id
|
|
|
|
store = get_agent_store(request)
|
|
await _sync_legacy_agents(store)
|
|
for record in await store.list_visible(get_effective_user_id()):
|
|
created_at = str(record.get("created_at") or datetime.now(UTC).isoformat())
|
|
updated_at = str(record.get("updated_at") or created_at)
|
|
assistants.append(
|
|
AssistantResponse(
|
|
assistant_id=record["id"],
|
|
graph_id="lead_agent", # All agents use the same graph
|
|
name=record["name"],
|
|
config={},
|
|
metadata={
|
|
"created_by": "system" if record.get("user_id") is None else "user",
|
|
"agent_id": record["id"],
|
|
"published": bool(record.get("published", False)),
|
|
},
|
|
description=record.get("description") or "",
|
|
created_at=created_at,
|
|
updated_at=updated_at,
|
|
version=1,
|
|
)
|
|
)
|
|
except Exception:
|
|
logger.debug("Could not load DB-backed custom agents for assistants list")
|
|
assistants.extend(_legacy_assistants())
|
|
|
|
return assistants
|
|
|
|
|
|
@router.post("/search", response_model=list[AssistantResponse])
|
|
async def search_assistants(request: Request, body: AssistantSearchRequest | None = None) -> list[AssistantResponse]:
|
|
"""Search assistants.
|
|
|
|
Returns all registered assistants (lead_agent + custom agents from config).
|
|
"""
|
|
assistants = await _list_assistants(request)
|
|
|
|
if body and body.graph_id:
|
|
assistants = [a for a in assistants if a.graph_id == body.graph_id]
|
|
if body and body.name:
|
|
assistants = [a for a in assistants if body.name.lower() in a.name.lower()]
|
|
|
|
offset = body.offset if body else 0
|
|
limit = body.limit if body else 10
|
|
return assistants[offset : offset + limit]
|
|
|
|
|
|
@router.get("/{assistant_id}", response_model=AssistantResponse)
|
|
async def get_assistant_compat(assistant_id: str, request: Request) -> AssistantResponse:
|
|
"""Get an assistant by ID."""
|
|
for a in await _list_assistants(request):
|
|
if a.assistant_id == assistant_id:
|
|
return a
|
|
raise HTTPException(status_code=404, detail=f"Assistant {assistant_id} not found")
|
|
|
|
|
|
@router.get("/{assistant_id}/graph")
|
|
async def get_assistant_graph(assistant_id: str, request: Request) -> dict:
|
|
"""Get the graph structure for an assistant.
|
|
|
|
Returns a minimal graph description. Full graph introspection is
|
|
not supported in the Gateway — this stub satisfies SDK validation.
|
|
"""
|
|
found = any(a.assistant_id == assistant_id for a in await _list_assistants(request))
|
|
if not found:
|
|
raise HTTPException(status_code=404, detail=f"Assistant {assistant_id} not found")
|
|
|
|
return {
|
|
"graph_id": "lead_agent",
|
|
"nodes": [],
|
|
"edges": [],
|
|
}
|
|
|
|
|
|
@router.get("/{assistant_id}/schemas")
|
|
async def get_assistant_schemas(assistant_id: str, request: Request) -> dict:
|
|
"""Get JSON schemas for an assistant's input/output/state.
|
|
|
|
Returns empty schemas — full introspection not supported in Gateway.
|
|
"""
|
|
found = any(a.assistant_id == assistant_id for a in await _list_assistants(request))
|
|
if not found:
|
|
raise HTTPException(status_code=404, detail=f"Assistant {assistant_id} not found")
|
|
|
|
return {
|
|
"graph_id": "lead_agent",
|
|
"input_schema": {},
|
|
"output_schema": {},
|
|
"state_schema": {},
|
|
"config_schema": {},
|
|
}
|