Skip to content

server

Class info

Classes

Name Children Inherits
OpenAIServer
llmling_models.openai_server.server
OpenAI-compatible API server backed by Pydantic-AI models.

    🛈 DocStrings

    OpenAI-compatible API server for Pydantic-AI models.

    OpenAIServer

    OpenAI-compatible API server backed by Pydantic-AI models.

    Source code in src/llmling_models/openai_server/server.py
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    class OpenAIServer:
        """OpenAI-compatible API server backed by Pydantic-AI models."""
    
        def __init__(
            self,
            registry: ModelRegistry,
            api_key: str | None = None,
            title: str = "LLMling OpenAI-Compatible API",
            description: str | None = None,
        ) -> None:
            """Initialize the server.
    
            Args:
                registry: Model registry
                api_key: API key for authentication (None to disable auth)
                title: API title
                description: API description
            """
            self.registry = registry
            self.api_key = api_key
            self.app = FastAPI(title=title, description=description or "")
    
            # Add CORS middleware
            self.app.add_middleware(
                CORSMiddleware,
                allow_origins=["*"],
                allow_credentials=True,
                allow_methods=["*"],
                allow_headers=["*"],
            )
    
            self.setup_routes()
    
        def verify_api_key(
            self, authorization: Annotated[str | None, Header(alias="Authorization")] = None
        ) -> None:
            """Verify API key if configured."""
            if not self.api_key:
                return
    
            if not authorization:
                raise HTTPException(401, "Missing API key")
            if not authorization.startswith("Bearer "):
                raise HTTPException(401, "Invalid authorization format")
    
            token = authorization.removeprefix("Bearer ")
            if token != self.api_key:
                raise HTTPException(401, "Invalid API key")
    
        def setup_routes(self) -> None:
            """Configure API routes."""
            # List models endpoint
            self.app.get(
                "/v1/models",
                dependencies=[Depends(self.verify_api_key)] if self.api_key else None,
            )(self.list_models)
            deps = [Depends(self.verify_api_key)] if self.api_key else None
            self.app.post("/v1/chat/completions", dependencies=deps)(self.create_chat_completion)
    
            # WebSocket endpoint for chat completions
            if self.api_key:
                self.app.websocket("/v1/chat/completions/ws")(self.websocket_chat_completion)
    
            # Add common OpenAI endpoints (stubs)
            self.app.get("/v1/dashboard/billing/subscription")(self.stub_billing)
            self.app.get("/v1/dashboard/billing/usage")(self.stub_usage)
    
            # Health check endpoint
            self.app.get("/health")(self.health_check)
    
        async def list_models(self) -> dict[str, Any]:
            """List available models."""
            models = self.registry.list_models()
            return {"object": "list", "data": models}
    
        async def create_chat_completion(self, request: ChatCompletionRequest) -> Response:
            """Handle chat completion requests."""
            try:
                # Get model
                try:
                    model = self.registry.get_model(request.model)
                except ValueError:
                    raise HTTPException(404, f"Model {request.model} not found") from None
    
                # Convert messages
                messages = openai_to_pydantic_messages(request.messages)
    
                # Create settings
                settings_data: dict[str, Any] = {}
                if request.temperature is not None:
                    settings_data["temperature"] = request.temperature
                if request.max_tokens is not None:
                    settings_data["max_tokens"] = request.max_tokens
    
                settings = ModelSettings(**settings_data) if settings_data else None
    
                # Handle function/tool calls
                function_tools = []
                if request.tools:
                    function_tools = convert_tools(request.tools)
    
                # Determine if we should force tool usage
                allow_text_output = True
                if request.tool_choice and request.tool_choice != "auto":
                    allow_text_output = False
    
                # Prepare request parameters
                request_params = ModelRequestParameters(
                    function_tools=function_tools,
                    allow_text_output=allow_text_output,
                    output_tools=[],  # Not used in OpenAI API
                )
    
                # Check if streaming is requested
                if request.stream:
                    return StreamingResponse(
                        self._stream_response(
                            model,
                            messages,
                            settings,
                            request_params,
                            request.model,
                            allow_tools=bool(request.tools),
                        ),
                        media_type="text/event-stream",
                    )
    
                # Non-streaming response
                response = await model.request(
                    messages,
                    model_settings=cast(ModelSettings, settings),
                    model_request_parameters=request_params,
                )
    
                # Convert to OpenAI format
                openai_response = pydantic_response_to_openai(
                    response, request.model, allow_tools=bool(request.tools)
                )
    
                # Add usage information
                usage = response.usage
                if openai_response.usage and usage:
                    openai_response.usage.update({
                        "prompt_tokens": usage.input_tokens or 0,
                        "completion_tokens": usage.output_tokens or 0,
                        "total_tokens": usage.total_tokens or 0,
                    })
    
                return Response(
                    content=openai_response.model_dump_json(),
                    media_type="application/json",
                )
    
            except Exception as e:
                logger.exception("Error processing chat completion")
                error_response = {
                    "error": {
                        "message": str(e),
                        "type": "server_error",
                        "param": None,
                        "code": "internal_error",
                    }
                }
                return Response(
                    content=anyenv.dump_json(error_response),
                    status_code=500,
                    media_type="application/json",
                )
    
        async def _stream_response(
            self,
            model: Model,
            messages: list[ModelMessage],
            settings: Any,
            request_params: ModelRequestParameters,
            model_name: str,
            allow_tools: bool = True,
        ) -> AsyncGenerator[str]:
            """Stream response in OpenAI format."""
            response_id = f"chatcmpl-{int(time.time() * 1000)}"
    
            try:
                async with model.request_stream(
                    messages,
                    model_settings=cast(ModelSettings, settings),
                    model_request_parameters=request_params,
                ) as stream:
                    # First chunk with role
                    choice = {
                        "index": 0,
                        "delta": {"role": "assistant"},
                        "finish_reason": None,
                    }
                    first_chunk = {
                        "id": response_id,
                        "object": "chat.completion.chunk",
                        "created": int(time.time()),
                        "model": model_name,
                        "choices": [choice],
                    }
                    yield f"data: {anyenv.dump_json(first_chunk)}\n\n"
    
                    # Process stream events
                    converter = StreamDeltaConverter(allow_tools=allow_tools)
                    async for event in stream:
                        if (delta := converter.convert(event)) is None:
                            continue
                        choice = {"index": 0, "delta": delta, "finish_reason": None}
                        chunk_data = {
                            "id": response_id,
                            "object": "chat.completion.chunk",
                            "created": int(time.time()),
                            "model": model_name,
                            "choices": [choice],
                        }
                        yield f"data: {anyenv.dump_json(chunk_data)}\n\n"
    
                    # Final chunk
                    final_chunk = {
                        "id": response_id,
                        "object": "chat.completion.chunk",
                        "created": int(time.time()),
                        "model": model_name,
                        "choices": [
                            {"index": 0, "delta": {}, "finish_reason": converter.finish_reason}
                        ],
                    }
                    yield f"data: {anyenv.dump_json(final_chunk)}\n\n"
                    yield "data: [DONE]\n\n"
    
            except Exception as e:
                logger.exception("Error during streaming response")
                choice = {
                    "index": 0,
                    "delta": {"content": f"Error: {e!s}"},
                    "finish_reason": "error",
                }
                error_chunk = {
                    "id": response_id,
                    "object": "chat.completion.chunk",
                    "created": int(time.time()),
                    "model": model_name,
                    "choices": [choice],
                }
                yield f"data: {anyenv.dump_json(error_chunk)}\n\n"
                yield "data: [DONE]\n\n"
    
        async def websocket_chat_completion(self, websocket: WebSocket) -> None:
            """Handle WebSocket chat completions."""
            await websocket.accept()
    
            try:
                # Verify authentication
                auth = websocket.headers.get("Authorization")
                try:
                    self.verify_api_key(auth)
                except HTTPException as e:
                    await websocket.send_json({"error": e.detail})
                    await websocket.close(code=e.status_code)
                    return
    
                while True:
                    # Receive request
                    data = await websocket.receive_text()
                    request = ChatCompletionRequest.model_validate_json(data)
    
                    # Get model
                    try:
                        model = self.registry.get_model(request.model)
                    except ValueError:
                        await websocket.send_json({"error": f"Model {request.model} not found"})
                        continue
    
                    # Convert messages
                    messages = openai_to_pydantic_messages(request.messages)
    
                    # Create settings
                    settings_data: dict[str, Any] = {}
                    if request.temperature is not None:
                        settings_data["temperature"] = request.temperature
                    if request.max_tokens is not None:
                        settings_data["max_tokens"] = request.max_tokens
    
                    settings = ModelSettings(**settings_data) if settings_data else None
    
                    # Handle function/tool calls
                    function_tools = []
                    if request.tools:
                        function_tools = convert_tools(request.tools)
    
                    # Determine if we should force tool usage
                    allow_text_output = True
                    if request.tool_choice and request.tool_choice != "auto":
                        allow_text_output = False
    
                    # Prepare request parameters
                    request_params = ModelRequestParameters(
                        function_tools=function_tools,
                        allow_text_output=allow_text_output,
                        output_tools=[],  # Not used in OpenAI API
                    )
    
                    # Process request with streaming
                    response_id = f"chatcmpl-{int(time.time() * 1000)}"
    
                    try:
                        # Stream response
                        if request.stream:
                            async with model.request_stream(
                                messages,
                                model_settings=cast(ModelSettings, settings),
                                model_request_parameters=request_params,
                            ) as stream:
                                choice = {
                                    "index": 0,
                                    "delta": {"role": "assistant"},
                                    "finish_reason": None,
                                }
                                first_chunk = {
                                    "id": response_id,
                                    "object": "chat.completion.chunk",
                                    "created": int(time.time()),
                                    "model": request.model,
                                    "choices": [choice],
                                }
                                await websocket.send_json(first_chunk)
    
                                # Process stream events
                                converter = StreamDeltaConverter(allow_tools=bool(request.tools))
                                async for event in stream:
                                    if (delta := converter.convert(event)) is None:
                                        continue
                                    choice = {"index": 0, "delta": delta, "finish_reason": None}
                                    chunk_data = {
                                        "id": response_id,
                                        "object": "chat.completion.chunk",
                                        "created": int(time.time()),
                                        "model": request.model,
                                        "choices": [choice],
                                    }
                                    await websocket.send_json(chunk_data)
    
                                # Final chunk
                                final_chunk = {
                                    "id": response_id,
                                    "object": "chat.completion.chunk",
                                    "created": int(time.time()),
                                    "model": request.model,
                                    "choices": [
                                        {
                                            "index": 0,
                                            "delta": {},
                                            "finish_reason": converter.finish_reason,
                                        }
                                    ],
                                }
                                await websocket.send_json(final_chunk)
                                await websocket.send_json({"done": True})
    
                        # Non-streaming response
                        else:
                            response = await model.request(
                                messages,
                                model_settings=cast(ModelSettings, settings),
                                model_request_parameters=request_params,
                            )
    
                            # Convert to OpenAI format
                            openai_response = pydantic_response_to_openai(
                                response, request.model, allow_tools=bool(request.tools)
                            )
    
                            # Add usage information
                            usage = response.usage
                            if openai_response.usage and usage:
                                openai_response.usage.update({
                                    "prompt_tokens": usage.input_tokens or 0,
                                    "completion_tokens": usage.output_tokens or 0,
                                    "total_tokens": usage.total_tokens or 0,
                                })
    
                            # Send response
                            await websocket.send_json(openai_response.model_dump())
    
                    except Exception as e:
                        logger.exception("Error processing WebSocket request")
                        error_response = {
                            "error": {
                                "message": str(e),
                                "type": "server_error",
                                "param": None,
                                "code": "internal_error",
                            }
                        }
                        await websocket.send_json(error_response)
    
            except Exception as e:
                logger.exception("WebSocket error")
                with contextlib.suppress(RuntimeError):
                    await websocket.send_json({"error": str(e)})
            finally:
                with contextlib.suppress(RuntimeError):
                    await websocket.close()
    
        async def stub_billing(self) -> dict[str, Any]:
            """Stub billing endpoint."""
            return {
                "object": "billing_subscription",
                "has_payment_method": True,
                "canceled": False,
                "canceled_at": None,
                "delinquent": None,
                "access_until": int(time.time() + 31536000),  # 1 year from now
                "soft_limit": 10000,
                "hard_limit": 100000,
                "system_hard_limit": 100000,
            }
    
        async def stub_usage(self) -> dict[str, Any]:
            """Stub usage endpoint."""
            return {"object": "list", "data": [], "total_usage": 0}
    
        async def health_check(self) -> dict[str, bool]:
            """Health check endpoint."""
            return {"status": True}
    

    __init__

    __init__(
        registry: ModelRegistry,
        api_key: str | None = None,
        title: str = "LLMling OpenAI-Compatible API",
        description: str | None = None,
    ) -> None
    

    Initialize the server.

    Parameters:

    Name Type Description Default
    registry ModelRegistry

    Model registry

    required
    api_key str | None

    API key for authentication (None to disable auth)

    None
    title str

    API title

    'LLMling OpenAI-Compatible API'
    description str | None

    API description

    None
    Source code in src/llmling_models/openai_server/server.py
    def __init__(
        self,
        registry: ModelRegistry,
        api_key: str | None = None,
        title: str = "LLMling OpenAI-Compatible API",
        description: str | None = None,
    ) -> None:
        """Initialize the server.
    
        Args:
            registry: Model registry
            api_key: API key for authentication (None to disable auth)
            title: API title
            description: API description
        """
        self.registry = registry
        self.api_key = api_key
        self.app = FastAPI(title=title, description=description or "")
    
        # Add CORS middleware
        self.app.add_middleware(
            CORSMiddleware,
            allow_origins=["*"],
            allow_credentials=True,
            allow_methods=["*"],
            allow_headers=["*"],
        )
    
        self.setup_routes()
    

    create_chat_completion async

    create_chat_completion(request: ChatCompletionRequest) -> Response
    

    Handle chat completion requests.

    Source code in src/llmling_models/openai_server/server.py
    async def create_chat_completion(self, request: ChatCompletionRequest) -> Response:
        """Handle chat completion requests."""
        try:
            # Get model
            try:
                model = self.registry.get_model(request.model)
            except ValueError:
                raise HTTPException(404, f"Model {request.model} not found") from None
    
            # Convert messages
            messages = openai_to_pydantic_messages(request.messages)
    
            # Create settings
            settings_data: dict[str, Any] = {}
            if request.temperature is not None:
                settings_data["temperature"] = request.temperature
            if request.max_tokens is not None:
                settings_data["max_tokens"] = request.max_tokens
    
            settings = ModelSettings(**settings_data) if settings_data else None
    
            # Handle function/tool calls
            function_tools = []
            if request.tools:
                function_tools = convert_tools(request.tools)
    
            # Determine if we should force tool usage
            allow_text_output = True
            if request.tool_choice and request.tool_choice != "auto":
                allow_text_output = False
    
            # Prepare request parameters
            request_params = ModelRequestParameters(
                function_tools=function_tools,
                allow_text_output=allow_text_output,
                output_tools=[],  # Not used in OpenAI API
            )
    
            # Check if streaming is requested
            if request.stream:
                return StreamingResponse(
                    self._stream_response(
                        model,
                        messages,
                        settings,
                        request_params,
                        request.model,
                        allow_tools=bool(request.tools),
                    ),
                    media_type="text/event-stream",
                )
    
            # Non-streaming response
            response = await model.request(
                messages,
                model_settings=cast(ModelSettings, settings),
                model_request_parameters=request_params,
            )
    
            # Convert to OpenAI format
            openai_response = pydantic_response_to_openai(
                response, request.model, allow_tools=bool(request.tools)
            )
    
            # Add usage information
            usage = response.usage
            if openai_response.usage and usage:
                openai_response.usage.update({
                    "prompt_tokens": usage.input_tokens or 0,
                    "completion_tokens": usage.output_tokens or 0,
                    "total_tokens": usage.total_tokens or 0,
                })
    
            return Response(
                content=openai_response.model_dump_json(),
                media_type="application/json",
            )
    
        except Exception as e:
            logger.exception("Error processing chat completion")
            error_response = {
                "error": {
                    "message": str(e),
                    "type": "server_error",
                    "param": None,
                    "code": "internal_error",
                }
            }
            return Response(
                content=anyenv.dump_json(error_response),
                status_code=500,
                media_type="application/json",
            )
    

    health_check async

    health_check() -> dict[str, bool]
    

    Health check endpoint.

    Source code in src/llmling_models/openai_server/server.py
    async def health_check(self) -> dict[str, bool]:
        """Health check endpoint."""
        return {"status": True}
    

    list_models async

    list_models() -> dict[str, Any]
    

    List available models.

    Source code in src/llmling_models/openai_server/server.py
    async def list_models(self) -> dict[str, Any]:
        """List available models."""
        models = self.registry.list_models()
        return {"object": "list", "data": models}
    

    setup_routes

    setup_routes() -> None
    

    Configure API routes.

    Source code in src/llmling_models/openai_server/server.py
    def setup_routes(self) -> None:
        """Configure API routes."""
        # List models endpoint
        self.app.get(
            "/v1/models",
            dependencies=[Depends(self.verify_api_key)] if self.api_key else None,
        )(self.list_models)
        deps = [Depends(self.verify_api_key)] if self.api_key else None
        self.app.post("/v1/chat/completions", dependencies=deps)(self.create_chat_completion)
    
        # WebSocket endpoint for chat completions
        if self.api_key:
            self.app.websocket("/v1/chat/completions/ws")(self.websocket_chat_completion)
    
        # Add common OpenAI endpoints (stubs)
        self.app.get("/v1/dashboard/billing/subscription")(self.stub_billing)
        self.app.get("/v1/dashboard/billing/usage")(self.stub_usage)
    
        # Health check endpoint
        self.app.get("/health")(self.health_check)
    

    stub_billing async

    stub_billing() -> dict[str, Any]
    

    Stub billing endpoint.

    Source code in src/llmling_models/openai_server/server.py
    async def stub_billing(self) -> dict[str, Any]:
        """Stub billing endpoint."""
        return {
            "object": "billing_subscription",
            "has_payment_method": True,
            "canceled": False,
            "canceled_at": None,
            "delinquent": None,
            "access_until": int(time.time() + 31536000),  # 1 year from now
            "soft_limit": 10000,
            "hard_limit": 100000,
            "system_hard_limit": 100000,
        }
    

    stub_usage async

    stub_usage() -> dict[str, Any]
    

    Stub usage endpoint.

    Source code in src/llmling_models/openai_server/server.py
    async def stub_usage(self) -> dict[str, Any]:
        """Stub usage endpoint."""
        return {"object": "list", "data": [], "total_usage": 0}
    

    verify_api_key

    verify_api_key(authorization: Annotated[str | None, Header(alias=Authorization)] = None) -> None
    

    Verify API key if configured.

    Source code in src/llmling_models/openai_server/server.py
    def verify_api_key(
        self, authorization: Annotated[str | None, Header(alias="Authorization")] = None
    ) -> None:
        """Verify API key if configured."""
        if not self.api_key:
            return
    
        if not authorization:
            raise HTTPException(401, "Missing API key")
        if not authorization.startswith("Bearer "):
            raise HTTPException(401, "Invalid authorization format")
    
        token = authorization.removeprefix("Bearer ")
        if token != self.api_key:
            raise HTTPException(401, "Invalid API key")
    

    websocket_chat_completion async

    websocket_chat_completion(websocket: WebSocket) -> None
    

    Handle WebSocket chat completions.

    Source code in src/llmling_models/openai_server/server.py
    async def websocket_chat_completion(self, websocket: WebSocket) -> None:
        """Handle WebSocket chat completions."""
        await websocket.accept()
    
        try:
            # Verify authentication
            auth = websocket.headers.get("Authorization")
            try:
                self.verify_api_key(auth)
            except HTTPException as e:
                await websocket.send_json({"error": e.detail})
                await websocket.close(code=e.status_code)
                return
    
            while True:
                # Receive request
                data = await websocket.receive_text()
                request = ChatCompletionRequest.model_validate_json(data)
    
                # Get model
                try:
                    model = self.registry.get_model(request.model)
                except ValueError:
                    await websocket.send_json({"error": f"Model {request.model} not found"})
                    continue
    
                # Convert messages
                messages = openai_to_pydantic_messages(request.messages)
    
                # Create settings
                settings_data: dict[str, Any] = {}
                if request.temperature is not None:
                    settings_data["temperature"] = request.temperature
                if request.max_tokens is not None:
                    settings_data["max_tokens"] = request.max_tokens
    
                settings = ModelSettings(**settings_data) if settings_data else None
    
                # Handle function/tool calls
                function_tools = []
                if request.tools:
                    function_tools = convert_tools(request.tools)
    
                # Determine if we should force tool usage
                allow_text_output = True
                if request.tool_choice and request.tool_choice != "auto":
                    allow_text_output = False
    
                # Prepare request parameters
                request_params = ModelRequestParameters(
                    function_tools=function_tools,
                    allow_text_output=allow_text_output,
                    output_tools=[],  # Not used in OpenAI API
                )
    
                # Process request with streaming
                response_id = f"chatcmpl-{int(time.time() * 1000)}"
    
                try:
                    # Stream response
                    if request.stream:
                        async with model.request_stream(
                            messages,
                            model_settings=cast(ModelSettings, settings),
                            model_request_parameters=request_params,
                        ) as stream:
                            choice = {
                                "index": 0,
                                "delta": {"role": "assistant"},
                                "finish_reason": None,
                            }
                            first_chunk = {
                                "id": response_id,
                                "object": "chat.completion.chunk",
                                "created": int(time.time()),
                                "model": request.model,
                                "choices": [choice],
                            }
                            await websocket.send_json(first_chunk)
    
                            # Process stream events
                            converter = StreamDeltaConverter(allow_tools=bool(request.tools))
                            async for event in stream:
                                if (delta := converter.convert(event)) is None:
                                    continue
                                choice = {"index": 0, "delta": delta, "finish_reason": None}
                                chunk_data = {
                                    "id": response_id,
                                    "object": "chat.completion.chunk",
                                    "created": int(time.time()),
                                    "model": request.model,
                                    "choices": [choice],
                                }
                                await websocket.send_json(chunk_data)
    
                            # Final chunk
                            final_chunk = {
                                "id": response_id,
                                "object": "chat.completion.chunk",
                                "created": int(time.time()),
                                "model": request.model,
                                "choices": [
                                    {
                                        "index": 0,
                                        "delta": {},
                                        "finish_reason": converter.finish_reason,
                                    }
                                ],
                            }
                            await websocket.send_json(final_chunk)
                            await websocket.send_json({"done": True})
    
                    # Non-streaming response
                    else:
                        response = await model.request(
                            messages,
                            model_settings=cast(ModelSettings, settings),
                            model_request_parameters=request_params,
                        )
    
                        # Convert to OpenAI format
                        openai_response = pydantic_response_to_openai(
                            response, request.model, allow_tools=bool(request.tools)
                        )
    
                        # Add usage information
                        usage = response.usage
                        if openai_response.usage and usage:
                            openai_response.usage.update({
                                "prompt_tokens": usage.input_tokens or 0,
                                "completion_tokens": usage.output_tokens or 0,
                                "total_tokens": usage.total_tokens or 0,
                            })
    
                        # Send response
                        await websocket.send_json(openai_response.model_dump())
    
                except Exception as e:
                    logger.exception("Error processing WebSocket request")
                    error_response = {
                        "error": {
                            "message": str(e),
                            "type": "server_error",
                            "param": None,
                            "code": "internal_error",
                        }
                    }
                    await websocket.send_json(error_response)
    
        except Exception as e:
            logger.exception("WebSocket error")
            with contextlib.suppress(RuntimeError):
                await websocket.send_json({"error": str(e)})
        finally:
            with contextlib.suppress(RuntimeError):
                await websocket.close()
    

    run_server async

    run_server(
        models: dict[str, str | Model],
        host: str = "0.0.0.0",
        port: int = 8000,
        api_key: str | None = None,
    ) -> None
    

    Run the OpenAI-compatible API server.

    Source code in src/llmling_models/openai_server/server.py
    async def run_server(
        models: dict[str, str | Model],
        host: str = "0.0.0.0",
        port: int = 8000,
        api_key: str | None = None,
    ) -> None:
        """Run the OpenAI-compatible API server."""
        import uvicorn
    
        logger.info("Starting OpenAI-compatible API server...")
        logger.info("Available models: %s", list(models.keys()))
    
        registry = ModelRegistry(models)
        server = OpenAIServer(
            registry=registry,
            api_key=api_key,
            title="LLMling OpenAI-Compatible API",
            description="OpenAI-compatible API server powered by LLMling models",
        )
    
        config = uvicorn.Config(app=server.app, host=host, port=port, log_level="info")
        server_instance = uvicorn.Server(config)
        await server_instance.serve()
    

    run_with_auto_discovery async

    run_with_auto_discovery() -> None
    

    Run the server with auto-discovered models from tokonomics.

    Source code in src/llmling_models/openai_server/server.py
    async def run_with_auto_discovery() -> None:
        """Run the server with auto-discovered models from tokonomics."""
        registry = await ModelRegistry.create()
        server = OpenAIServer(
            registry=registry,
            api_key="test-key",
            title="LLMling OpenAI-Compatible API",
            description="OpenAI-compatible API server powered by LLMling models",
        )
        config = uvicorn.Config(app=server.app, host="0.0.0.0", port=8000, log_level="info")
        server_instance = uvicorn.Server(config)
        await server_instance.serve()