Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
Agent bridge: log a refused request as a warning, a server failure as an error
Petr Bauchca806d2017d4
diff --git a/core/switch_core/bridges/agent/app.py b/core/switch_core/bridges/agent/app.pyindex 8e4ebea0f..fc80d1211 100644--- a/core/switch_core/bridges/agent/app.py+++ b/core/switch_core/bridges/agent/app.py@@ -51,6 +51,45 @@ from switch_core.trust.client import TrustClientlogger = logging.getLogger(__name__)+def http_error_level(status_code: int) -> int:+ """How loudly to log a refused request.++ A 4xx is the caller's mistake (an argument the tool does not take, a room+ it is not in): the server worked, so it is a warning. A 5xx is the+ server's own failure and an error.+ """+ return logging.ERROR if status_code >= 500 else logging.WARNING+++async def log_http_exceptions(request: Request, exc: HTTPException) -> JSONResponse:+ if exc.status_code >= 400:+ logger.log(+ http_error_level(exc.status_code),+ "%s %s → %d: %s",+ request.method,+ request.url.path,+ exc.status_code,+ exc.detail,+ )+ return JSONResponse(+ status_code=exc.status_code,+ content={"detail": exc.detail},+ )+++async def log_validation_errors(+ request: Request, exc: RequestValidationError+) -> JSONResponse:+ logger.warning(+ "%s %s → 422 validation: errors=%s body=%r",+ request.method,+ request.url.path,+ exc.errors(),+ exc.body,+ )+ return JSONResponse(status_code=422, content={"detail": exc.errors()})++def create_agent_bridge_app(*,agent_store: AgentStore,@@ -119,34 +158,8 @@ def create_agent_bridge_app(app = FastAPI(title="Switch Agent Bridge API")- @app.exception_handler(HTTPException)- async def log_http_exceptions(request: Request, exc: HTTPException) -> JSONResponse:- if exc.status_code >= 400:- logger.error(- "%s %s → %d: %s",- request.method,- request.url.path,- exc.status_code,- exc.detail,- )- return JSONResponse(- status_code=exc.status_code,- content={"detail": exc.detail},- )-- @app.exception_handler(RequestValidationError)- async def log_validation_errors(- request: Request, exc: RequestValidationError- ) -> JSONResponse:- logger.error(- "%s %s → 422 validation: errors=%s body=%r",- request.method,- request.url.path,- exc.errors(),- exc.body,- )- return JSONResponse(status_code=422, content={"detail": exc.errors()})-+ app.add_exception_handler(HTTPException, log_http_exceptions) # type: ignore[arg-type]+ app.add_exception_handler(RequestValidationError, log_validation_errors) # type: ignore[arg-type]app.add_exception_handler(SessionError, session_error_response)app.include_router(activity_router, tags=["session activity"])app.include_router(api_router, prefix="/agents", tags=["api"])diff --git a/core/tests/switch_core/bridges/agent/test_http_error_logging.py b/core/tests/switch_core/bridges/agent/test_http_error_logging.pynew file mode 100644index 000000000..4c5ad1449--- /dev/null+++ b/core/tests/switch_core/bridges/agent/test_http_error_logging.py@@ -0,0 +1,72 @@+import logging++import pytest+from fastapi import FastAPI, HTTPException+from fastapi.exceptions import RequestValidationError+from httpx import ASGITransport, AsyncClient+from pydantic import BaseModel++from switch_core.bridges.agent.app import log_http_exceptions, log_validation_errors+++class _Body(BaseModel):+ text: str+++def _app() -> FastAPI:+ app = FastAPI()+ app.add_exception_handler(HTTPException, log_http_exceptions) # type: ignore[arg-type]+ app.add_exception_handler(RequestValidationError, log_validation_errors) # type: ignore[arg-type]++ @app.get("/refused/{status}")+ async def refused(status: int) -> None:+ raise HTTPException(+ status_code=status, detail="post_message does not accept: room_id"+ )++ @app.post("/typed")+ async def typed(body: _Body) -> None:+ return None++ return app+++async def _records(+ caplog: pytest.LogCaptureFixture, method: str, path: str+) -> list[logging.LogRecord]:+ caplog.clear()+ with caplog.at_level(logging.DEBUG, logger="switch_core.bridges.agent.app"):+ async with AsyncClient(+ transport=ASGITransport(app=_app()), base_url="http://test"+ ) as client:+ await client.request(method, path, json={})+ return [r for r in caplog.records if r.name == "switch_core.bridges.agent.app"]+++ ("status", "level"),+ [+ (400, logging.WARNING),+ (404, logging.WARNING),+ (500, logging.ERROR),+ (503, logging.ERROR),+ ],+)+async def test_a_refused_request_logs_a_warning_and_a_server_failure_an_error(+ caplog: pytest.LogCaptureFixture, status: int, level: int+) -> None:+ records = await _records(caplog, "GET", f"/refused/{status}")+ assert [r.levelno for r in records] == [level]+ assert (+ f"→ {status}: post_message does not accept: room_id" in records[0].getMessage()+ )+++async def test_a_request_that_fails_validation_logs_a_warning(+ caplog: pytest.LogCaptureFixture,+) -> None:+ records = await _records(caplog, "POST", "/typed")+ assert [r.levelno for r in records] == [logging.WARNING]+ assert "→ 422 validation" in records[0].getMessage()