Skip to content

Agent Server

Drop-in FastAPI wrapper — POST /invoke, POST /stream, GET/DELETE /threads/{id}, GET /health.

AgentServer

AgentServer(agent: Any, title: str = 'Locus Agent Server', description: str = 'HTTP API for a Locus AI Agent', api_key: str | None = None, allow_unauthenticated: bool = False)

Wrap a Locus Agent as a FastAPI application.

Example

from locus.agent import Agent, AgentConfig from locus.server import AgentServer

agent = Agent(config=AgentConfig(system_prompt="Hello", model=model)) server = AgentServer(agent=agent, api_key="secret") server.run(host="127.0.0.1", port=8000)

Source code in src/locus/server/app.py
def __init__(
    self,
    agent: Any,
    title: str = "Locus Agent Server",
    description: str = "HTTP API for a Locus AI Agent",
    api_key: str | None = None,
    allow_unauthenticated: bool = False,
) -> None:
    self.agent = agent
    self._title = title
    self._description = description
    # Prefer the explicit arg; fall back to the environment so that
    # deployments don't have to thread the secret through code.
    self._api_key = api_key or os.environ.get("LOCUS_SERVER_API_KEY") or None
    self._allow_unauthenticated = allow_unauthenticated
    self._app = None

app property

app: Any

Get or create the FastAPI application.

run

run(host: str = '127.0.0.1', port: int = 8000, **kwargs: Any) -> None

Run the server with uvicorn.

Parameters:

Name Type Description Default
host str

Bind address. Defaults to loopback — using a non-loopback host requires either api_key to be set or allow_unauthenticated=True on this server.

'127.0.0.1'
port int

Bind port.

8000
**kwargs Any

Additional uvicorn.run() arguments.

{}
Source code in src/locus/server/app.py
def run(
    self,
    host: str = "127.0.0.1",
    port: int = 8000,
    **kwargs: Any,
) -> None:
    """Run the server with uvicorn.

    Args:
        host: Bind address. Defaults to loopback — using a
            non-loopback host requires either ``api_key`` to be set
            or ``allow_unauthenticated=True`` on this server.
        port: Bind port.
        **kwargs: Additional uvicorn.run() arguments.
    """
    if self._api_key is None and not self._allow_unauthenticated and not _is_loopback(host):
        msg = (
            f"Refusing to bind AgentServer to {host!r} without an API "
            "key. Set LOCUS_SERVER_API_KEY, pass api_key=... to "
            "AgentServer, or pass allow_unauthenticated=True if an "
            "upstream proxy terminates auth."
        )
        raise RuntimeError(msg)

    try:
        import uvicorn
    except ImportError as e:
        msg = "uvicorn is required for AgentServer.run(). Install with: pip install uvicorn"
        raise ImportError(msg) from e

    uvicorn.run(self.app, host=host, port=port, **kwargs)