Skip to main content
Platform Workspace Context enables agents to access workspace-specific settings, instructions, and configurations from the platform database.

Quick Start

1

Basic Workspace Context

Create a workspace context provider that implements the WorkspaceContextProtocol:
from praisonaiagents.auth.protocols import WorkspaceContextProtocol
from sqlalchemy.ext.asyncio import AsyncSession

class PlatformWorkspaceContext:
    def __init__(self, workspace_id: str, session: AsyncSession):
        self.workspace_id = workspace_id
        self.session = session
    
    async def get_workspace_context(self) -> dict:
        # Query workspace from database
        workspace = await self.session.get(Workspace, self.workspace_id)
        if not workspace:
            return None
        
        return {
            "id": workspace.id,
            "name": workspace.name,
            "slug": workspace.slug,
            "description": workspace.description,
            "settings": workspace.settings
        }
2

Agent Configuration

Add agent-specific configuration retrieval:
async def get_agent_config(self, agent_id: str) -> dict:
    # Query agent scoped to workspace
    query = select(Agent).where(
        Agent.id == agent_id,
        Agent.workspace_id == self.workspace_id
    )
    result = await self.session.execute(query)
    agent = result.scalar_one_or_none()
    
    if not agent:
        return None
    
    return {
        "id": agent.id,
        "name": agent.name,
        "runtime_mode": agent.runtime_mode,
        "instructions": agent.instructions,
        "config": agent.config,
        "max_concurrent_tasks": agent.max_concurrent_tasks
    }

How It Works

ComponentPurposeReturns
get_workspace_context()Retrieve workspace settingsWorkspace metadata and configuration
get_agent_config()Get agent configurationAgent-specific runtime settings

Configuration Options

The PlatformWorkspaceContext class supports the following configuration:
OptionTypeDescription
workspace_idstrUnique workspace identifier
sessionAsyncSessionDatabase session for queries

Workspace Context Data

FieldTypeDescription
idstrWorkspace unique identifier
namestrHuman-readable workspace name
slugstrURL-friendly workspace identifier
descriptionstrWorkspace description
settingsdictWorkspace-specific settings

Agent Configuration Data

FieldTypeDescription
idstrAgent unique identifier
namestrAgent display name
runtime_modestrAgent execution mode
instructionsstrAgent system instructions
configdictAgent configuration parameters
max_concurrent_tasksintMaximum parallel task limit

Common Patterns

Workspace-Scoped Agent Query

Query agents that belong to a specific workspace:
async def get_workspace_agents(self) -> list:
    query = select(Agent).where(Agent.workspace_id == self.workspace_id)
    result = await self.session.execute(query)
    return [
        {
            "id": agent.id,
            "name": agent.name,
            "status": agent.status
        }
        for agent in result.scalars().all()
    ]

Conditional Context Loading

Return different context based on workspace type:
async def get_workspace_context(self) -> dict:
    workspace = await self.session.get(Workspace, self.workspace_id)
    if not workspace:
        return None
    
    context = {
        "id": workspace.id,
        "name": workspace.name,
        "settings": workspace.settings
    }
    
    # Add premium features for enterprise workspaces
    if workspace.type == "enterprise":
        context["advanced_features"] = await self._get_premium_features()
    
    return context

Error Handling

Handle database connection and query errors:
from praisonaiagents.errors import PraisonAIError

async def get_agent_config(self, agent_id: str) -> dict:
    try:
        query = select(Agent).where(
            Agent.id == agent_id,
            Agent.workspace_id == self.workspace_id
        )
        result = await self.session.execute(query)
        agent = result.scalar_one_or_none()
        
        if not agent:
            return None
        
        return {
            "id": agent.id,
            "name": agent.name,
            "config": agent.config
        }
    except Exception as e:
        raise PraisonAIError(f"Failed to get agent config: {e}")

Best Practices

Always use dependency injection for database sessions:
# Good: Dependency injection
class PlatformWorkspaceContext:
    def __init__(self, workspace_id: str, session: AsyncSession):
        self.workspace_id = workspace_id
        self.session = session

# Avoid: Creating sessions inside the class
class BadWorkspaceContext:
    async def get_context(self):
        session = create_session()  # Don't do this
Return None for missing resources, raise exceptions for system errors:
async def get_workspace_context(self) -> dict:
    try:
        workspace = await self.session.get(Workspace, self.workspace_id)
        return workspace.to_dict() if workspace else None
    except SQLAlchemyError as e:
        raise PraisonAIError(f"Database error: {e}")
Ensure returned data is JSON-serializable:
async def get_agent_config(self, agent_id: str) -> dict:
    agent = await self._get_agent(agent_id)
    if not agent:
        return None
    
    return {
        "id": str(agent.id),  # Convert UUID to string
        "created_at": agent.created_at.isoformat(),  # Convert datetime
        "config": dict(agent.config)  # Ensure dict serialization
    }
Always scope agent queries to the workspace for security:
# Good: Workspace-scoped query
query = select(Agent).where(
    Agent.id == agent_id,
    Agent.workspace_id == self.workspace_id  # Security check
)

# Bad: Global agent query
query = select(Agent).where(Agent.id == agent_id)  # Security risk

Auth Protocols

Authentication and authorization protocols

Database Integration

Database persistence and session management