def build_factory_websocket_endpoint(
    path: str, endpoint: Callable[..., Any]
) -> Callable[..., Awaitable[Any]]:
    """Build a factory endpoint for WebSocket routes.

    Args:
        path: The path for the route.
        endpoint: openai resource factory function.
    """
    resource = compile_openai_resource_factory(endpoint)

    # index 1 of `compile_path` contains path_format output
    model_prefix = compile_model_prefix(compile_path(path)[1], resource)
    request_model = create_request_model(resource, model_prefix)

    async def factory_endpoint(
        websocket: WebSocket, resource: OpenAIResource = Depends(endpoint)
    ):
        async with WebsocketSession().connect(websocket) as session:
            async for data in session:
                try:
                    async for chunk in resource.stream_response(
                        **model_dump(request_model(**data))
                    ):
                        await websocket.send_json(
                            dict(
                                data=chunk,
                                event=Events.COMPLETION,
                            )
                        )
                except Exception as e:
                    logger.error(f"openai error: {e}")
                    await websocket.send_json(
                        dict(
                            data=dict(
                                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                                detail=HTTPStatusDetail.INTERNAL_SERVER_ERROR,
                            ),
                            event=Events.ERROR,
                        )
                    )
                await websocket.send_json(dict(data="", event=Events.END))

    return factory_endpoint
Build a factory endpoint for WebSocket routes.

    Args:
        path: The path for the route.
        endpoint: openai resource factory function.
    
lanarky/adapters/openai/utils.py