Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /stateset_stateset-agents /stateset_agents /api /routers /agents.py
| """ | |
| Agents Router Module | |
| API endpoints for agent management and conversations. | |
| """ | |
| import os | |
| from dataclasses import asdict, is_dataclass | |
| from datetime import datetime | |
| from typing import Any | |
| from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query | |
| from pydantic import BaseModel, ConfigDict, Field | |
| from stateset_agents.utils.security import SecurityMonitor | |
| from ..constants import MAX_MESSAGE_LENGTH | |
| from ..dependencies import ( | |
| AuthenticatedUser, | |
| get_agent_service, | |
| get_current_user, | |
| get_security_monitor, | |
| ) | |
| from ..errors import ( | |
| AgentNotFoundError, | |
| ConversationNotFoundError, | |
| InternalError, | |
| InvalidAgentConfigError, | |
| PromptInjectionError, | |
| ) | |
| from ..models import PaginatedResponse | |
| from ..schemas import ( | |
| AgentConfigRequest, | |
| ConversationRequest, | |
| ConversationResponse, | |
| ErrorResponse, | |
| ) | |
| from ..security import InputValidator, get_api_security_monitor | |
| from ..services.agent_service import AgentService | |
| router = APIRouter(prefix="/agents", tags=["agents"]) | |
| conversation_router = APIRouter(prefix="/conversations", tags=["conversations"]) | |
| AGENT_API_EXCEPTIONS = (AttributeError, KeyError, RuntimeError, TypeError, ValueError) | |
| def _can_access_conversation( | |
| conversation: dict[str, Any], user: AuthenticatedUser | |
| ) -> bool: | |
| if "admin" in user.roles: | |
| return True | |
| metadata = conversation.get("metadata") | |
| if not isinstance(metadata, dict): | |
| return True | |
| owner = metadata.get("user_id") | |
| return owner is None or owner == user.user_id | |
| def _agent_config_to_dict(config: Any) -> dict[str, Any]: | |
| if isinstance(config, dict): | |
| return config | |
| if is_dataclass(config) and not isinstance(config, type): | |
| return asdict(config) | |
| return {} | |
| # ============================================================================ | |
| # Response Models | |
| # ============================================================================ | |
| class AgentCreatedResponse(BaseModel): | |
| """Response for agent creation.""" | |
| agent_id: str = Field(..., description="Unique identifier for the created agent") | |
| created_at: datetime = Field( | |
| default_factory=datetime.utcnow, description="Creation timestamp" | |
| ) | |
| config: AgentConfigRequest = Field(..., description="Agent configuration") | |
| message: str = Field("Agent created successfully", description="Status message") | |
| class AgentDetailResponse(BaseModel): | |
| """Detailed agent information.""" | |
| model_config = ConfigDict(protected_namespaces=()) | |
| agent_id: str = Field(..., description="Agent identifier") | |
| model_name: str = Field(..., description="Model name") | |
| created_at: datetime = Field(..., description="Creation timestamp") | |
| conversation_count: int = Field(0, description="Number of conversations") | |
| total_tokens_used: int = Field(0, description="Total tokens used") | |
| config: dict[str, Any] = Field( | |
| default_factory=dict, description="Agent configuration" | |
| ) | |
| status: str = Field("active", description="Agent status") | |
| class AgentListResponse(PaginatedResponse): | |
| """Paginated list of agents.""" | |
| items: list[AgentDetailResponse] = Field( | |
| default_factory=list, description="List of agents" | |
| ) | |
| class ConversationSummary(BaseModel): | |
| """Summary of a conversation.""" | |
| conversation_id: str = Field(..., description="Conversation identifier") | |
| agent_id: str = Field(..., description="Associated agent ID") | |
| message_count: int = Field(0, description="Number of messages") | |
| created_at: datetime = Field(..., description="Creation timestamp") | |
| last_message_at: datetime | None = Field(None, description="Last message timestamp") | |
| total_tokens: int = Field(0, description="Total tokens used") | |
| class ConversationListResponse(PaginatedResponse): | |
| """Paginated list of conversations.""" | |
| items: list[ConversationSummary] = Field( | |
| default_factory=list, description="List of conversations" | |
| ) | |
| # ============================================================================ | |
| # Agent Endpoints | |
| # ============================================================================ | |
| async def create_agent( | |
| config: AgentConfigRequest, | |
| user: AuthenticatedUser = Depends(get_current_user), | |
| svc: AgentService = Depends(get_agent_service), | |
| ) -> AgentCreatedResponse: | |
| """ | |
| Create a new agent with the specified configuration. | |
| Args: | |
| config: Agent configuration including model name, temperature, etc. | |
| user: Authenticated user making the request. | |
| Returns: | |
| AgentCreatedResponse with the created agent's ID and details. | |
| Raises: | |
| InvalidAgentConfigError: If the configuration is invalid. | |
| InternalError: If agent creation fails unexpectedly. | |
| """ | |
| try: | |
| # Validate system prompt for injection if provided | |
| if config.system_prompt: | |
| try: | |
| InputValidator.validate_string( | |
| config.system_prompt, | |
| max_length=10000, | |
| field_name="system_prompt", | |
| check_injection=True, | |
| ) | |
| except ValueError as e: | |
| if "potentially harmful content" in str(e).lower(): | |
| raise PromptInjectionError("system_prompt") from e | |
| raise InvalidAgentConfigError(str(e)) from e | |
| agent_id = await svc.create_agent(config) | |
| return AgentCreatedResponse( | |
| agent_id=agent_id, | |
| created_at=datetime.utcnow(), | |
| config=config, | |
| message="Agent created successfully", | |
| ) | |
| except PromptInjectionError: | |
| raise | |
| except ValueError as e: | |
| raise InvalidAgentConfigError(str(e)) from e | |
| except AGENT_API_EXCEPTIONS as e: | |
| raise InternalError("Failed to create agent", internal_error=e) from e | |
| async def list_agents( | |
| page: int = Query(1, ge=1, description="Page number"), | |
| page_size: int = Query(20, ge=1, le=100, description="Items per page"), | |
| status: str | None = Query(None, description="Filter by status"), | |
| user: AuthenticatedUser = Depends(get_current_user), | |
| svc: AgentService = Depends(get_agent_service), | |
| ) -> AgentListResponse: | |
| """ | |
| Get a paginated list of all agents. | |
| Args: | |
| page: Page number (1-indexed). | |
| page_size: Number of items per page (max 100). | |
| status: Optional filter by agent status. | |
| user: Authenticated user. | |
| Returns: | |
| Paginated list of agent details. | |
| """ | |
| # Get all agents from service | |
| all_agents = list(svc.agents.items()) | |
| # Apply status filter if provided | |
| if status: | |
| all_agents = [ | |
| (aid, a) | |
| for aid, a in all_agents | |
| if getattr(a, "status", "active") == status | |
| ] | |
| total = len(all_agents) | |
| # Calculate pagination | |
| start_idx = (page - 1) * page_size | |
| end_idx = start_idx + page_size | |
| page_agents = all_agents[start_idx:end_idx] | |
| items = [ | |
| AgentDetailResponse( | |
| agent_id=agent_id, | |
| model_name=getattr(agent, "model_name", "unknown"), | |
| created_at=getattr(agent, "created_at", datetime.utcnow()), | |
| conversation_count=len(svc.conversations.get(agent_id, [])), | |
| total_tokens_used=getattr(agent, "total_tokens", 0), | |
| config=_agent_config_to_dict(getattr(agent, "config", {})), | |
| status=getattr(agent, "status", "active"), | |
| ) | |
| for agent_id, agent in page_agents | |
| ] | |
| return AgentListResponse( | |
| items=items, | |
| total=total, | |
| page=page, | |
| page_size=page_size, | |
| has_next=end_idx < total, | |
| has_prev=page > 1, | |
| ) | |
| async def get_agent( | |
| agent_id: str, | |
| user: AuthenticatedUser = Depends(get_current_user), | |
| svc: AgentService = Depends(get_agent_service), | |
| ) -> AgentDetailResponse: | |
| """ | |
| Get detailed information about a specific agent. | |
| Args: | |
| agent_id: The agent's unique identifier. | |
| user: Authenticated user. | |
| Returns: | |
| Detailed agent information. | |
| Raises: | |
| AgentNotFoundError: If the agent doesn't exist. | |
| """ | |
| if agent_id not in svc.agents: | |
| raise AgentNotFoundError(agent_id) | |
| agent = svc.agents[agent_id] | |
| return AgentDetailResponse( | |
| agent_id=agent_id, | |
| model_name=getattr(agent, "model_name", "unknown"), | |
| created_at=getattr(agent, "created_at", datetime.utcnow()), | |
| conversation_count=len(svc.conversations.get(agent_id, [])), | |
| total_tokens_used=getattr(agent, "total_tokens", 0), | |
| config=_agent_config_to_dict(getattr(agent, "config", {})), | |
| status=getattr(agent, "status", "active"), | |
| ) | |
| async def delete_agent( | |
| agent_id: str, | |
| user: AuthenticatedUser = Depends(get_current_user), | |
| svc: AgentService = Depends(get_agent_service), | |
| ) -> None: | |
| """ | |
| Delete an agent and all associated conversations. | |
| Args: | |
| agent_id: The agent's unique identifier. | |
| user: Authenticated user. | |
| Raises: | |
| AgentNotFoundError: If the agent doesn't exist. | |
| """ | |
| if agent_id not in svc.agents: | |
| raise AgentNotFoundError(agent_id) | |
| deleted = svc.delete_agent(agent_id) | |
| if not deleted: | |
| raise AgentNotFoundError(agent_id) | |
| # ============================================================================ | |
| # Conversation Endpoints | |
| # ============================================================================ | |
| async def converse_with_agent( | |
| request: ConversationRequest, | |
| background_tasks: BackgroundTasks, | |
| user: AuthenticatedUser = Depends(get_current_user), | |
| monitor: SecurityMonitor = Depends(get_security_monitor), | |
| svc: AgentService = Depends(get_agent_service), | |
| ) -> ConversationResponse: | |
| """ | |
| Have a conversation with an agent. | |
| Sends user messages to the agent and returns the generated response. | |
| Supports both single-turn and multi-turn conversations. | |
| Args: | |
| request: Conversation request with messages. | |
| background_tasks: FastAPI background tasks for async logging. | |
| user: Authenticated user. | |
| monitor: Security monitor for event logging. | |
| Returns: | |
| ConversationResponse with the agent's reply. | |
| Raises: | |
| AgentNotFoundError: If the specified agent doesn't exist. | |
| PromptInjectionError: If prompt injection is detected. | |
| InternalError: If response generation fails. | |
| """ | |
| try: | |
| # Never trust caller-provided user identifiers in payload. | |
| request.user_id = user.user_id | |
| # Validate messages for prompt injection | |
| api_security = get_api_security_monitor() | |
| for i, msg in enumerate(request.messages): | |
| content = msg.get("content", "") | |
| try: | |
| _, security_event = InputValidator.validate_string( | |
| content, | |
| max_length=MAX_MESSAGE_LENGTH, | |
| field_name=f"messages[{i}].content", | |
| check_injection=True, | |
| ) | |
| except ValueError as e: | |
| if "potentially harmful content" in str(e).lower(): | |
| _, _, patterns = InputValidator.detect_prompt_injection(content) | |
| api_security.log_prompt_injection_attempt( | |
| client_ip="unknown", | |
| path="/conversations", | |
| content_preview=content[:100], | |
| patterns=patterns, | |
| user_id=user.user_id if user else None, | |
| ) | |
| raise PromptInjectionError(f"messages[{i}].content") from e | |
| raise HTTPException(status_code=400, detail=str(e)) from e | |
| if security_event: | |
| api_security.log_event(security_event) | |
| # Use a default agent for demo purposes | |
| agent_id = getattr(request, "agent_id", "default") | |
| # Create a temporary agent if none exists. | |
| if agent_id not in svc.agents: | |
| # If STATESET_DEFAULT_CHECKPOINT was set, the startup hook should | |
| # have registered an agent under id "default". Falling through | |
| # to the gpt2 demo agent silently would hide a real failure. | |
| if agent_id == "default" and os.environ.get("STATESET_DEFAULT_CHECKPOINT"): | |
| import logging | |
| logging.getLogger(__name__).warning( | |
| "Request asked for the default agent, but no agent named 'default' " | |
| "is registered, yet STATESET_DEFAULT_CHECKPOINT=%s was set. " | |
| "The startup hook likely failed — check the API logs. " | |
| "Falling back to a demo gpt2 agent.", | |
| os.environ.get("STATESET_DEFAULT_CHECKPOINT"), | |
| ) | |
| config = AgentConfigRequest(model_name="gpt2") | |
| agent_id = await svc.create_agent(config) | |
| response = await svc.get_conversation_response(agent_id, request) | |
| # Log the conversation for analytics | |
| async def _log_conversation_event( | |
| event_type: str, details: dict[str, Any] | |
| ) -> None: | |
| monitor.log_security_event(event_type, details) | |
| background_tasks.add_task( | |
| _log_conversation_event, | |
| "conversation", | |
| { | |
| "agent_id": agent_id, | |
| "conversation_id": response.conversation_id, | |
| "tokens_used": response.tokens_used, | |
| "processing_time": response.processing_time, | |
| "user_id": user.user_id if user else None, | |
| }, | |
| ) | |
| return response | |
| except (PromptInjectionError, AgentNotFoundError): | |
| raise | |
| except HTTPException: | |
| raise | |
| except AGENT_API_EXCEPTIONS as e: | |
| raise InternalError("Conversation failed", internal_error=e) from e | |
| async def list_conversations( | |
| page: int = Query(1, ge=1, description="Page number"), | |
| page_size: int = Query(20, ge=1, le=100, description="Items per page"), | |
| agent_id: str | None = Query(None, description="Filter by agent ID"), | |
| user: AuthenticatedUser = Depends(get_current_user), | |
| svc: AgentService = Depends(get_agent_service), | |
| ) -> ConversationListResponse: | |
| """ | |
| Get a paginated list of conversations. | |
| Args: | |
| page: Page number (1-indexed). | |
| page_size: Number of items per page (max 100). | |
| agent_id: Optional filter by agent ID. | |
| user: Authenticated user. | |
| Returns: | |
| Paginated list of conversation summaries. | |
| """ | |
| # Gather all conversations | |
| all_convs: list[ConversationSummary] = [] | |
| for aid, conv_list in svc.conversations.items(): | |
| if agent_id and aid != agent_id: | |
| continue | |
| for conv in conv_list: | |
| if not _can_access_conversation(conv, user): | |
| continue | |
| all_convs.append( | |
| ConversationSummary( | |
| conversation_id=conv.get("id", "unknown"), | |
| agent_id=aid, | |
| message_count=len(conv.get("messages", [])), | |
| created_at=conv.get("created_at", datetime.utcnow()), | |
| last_message_at=conv.get("last_message_at"), | |
| total_tokens=conv.get("total_tokens", 0), | |
| ) | |
| ) | |
| total = len(all_convs) | |
| # Sort by creation time (newest first) | |
| all_convs.sort(key=lambda c: c.created_at, reverse=True) | |
| # Paginate | |
| start_idx = (page - 1) * page_size | |
| end_idx = start_idx + page_size | |
| page_convs = all_convs[start_idx:end_idx] | |
| return ConversationListResponse( | |
| items=page_convs, | |
| total=total, | |
| page=page, | |
| page_size=page_size, | |
| has_next=end_idx < total, | |
| has_prev=page > 1, | |
| ) | |
| async def get_conversation( | |
| conversation_id: str, | |
| user: AuthenticatedUser = Depends(get_current_user), | |
| svc: AgentService = Depends(get_agent_service), | |
| ) -> dict[str, Any]: | |
| """ | |
| Get details of a specific conversation. | |
| Args: | |
| conversation_id: The conversation's unique identifier. | |
| user: Authenticated user. | |
| Returns: | |
| Full conversation details including message history. | |
| Raises: | |
| ConversationNotFoundError: If the conversation doesn't exist. | |
| """ | |
| # Search for conversation across all agents | |
| for aid, conv_list in svc.conversations.items(): | |
| for conv in conv_list: | |
| if conv.get("id") == conversation_id: | |
| if not _can_access_conversation(conv, user): | |
| raise ConversationNotFoundError(conversation_id) | |
| return { | |
| "conversation_id": conversation_id, | |
| "agent_id": aid, | |
| "messages": conv.get("messages", []), | |
| "created_at": conv.get("created_at"), | |
| "last_message_at": conv.get("last_message_at"), | |
| "total_tokens": conv.get("total_tokens", 0), | |
| "metadata": conv.get("metadata", {}), | |
| } | |
| raise ConversationNotFoundError(conversation_id) | |
| async def delete_conversation( | |
| conversation_id: str, | |
| user: AuthenticatedUser = Depends(get_current_user), | |
| svc: AgentService = Depends(get_agent_service), | |
| ) -> None: | |
| """ | |
| Delete a specific conversation. | |
| Args: | |
| conversation_id: The conversation's unique identifier. | |
| user: Authenticated user. | |
| Raises: | |
| ConversationNotFoundError: If the conversation doesn't exist. | |
| """ | |
| deleted = svc.delete_conversation(conversation_id, user_id=user.user_id) | |
| if not deleted: | |
| raise ConversationNotFoundError(conversation_id) | |
Xet Storage Details
- Size:
- 21.2 kB
- Xet hash:
- 43f6633ca0dcf4654cfa5636b21dd6ded44fed0f78652543dea54771993d6e99
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.