|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2023-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | + |
| 17 | +import asyncio |
| 18 | +import logging |
| 19 | +import time |
| 20 | +from typing import Annotated, Union |
| 21 | + |
| 22 | +from fastapi import Depends, FastAPI, HTTPException, Request |
| 23 | + |
| 24 | +from nemoguardrails.benchmark.mock_llm_server.config import ModelSettings, get_settings |
| 25 | +from nemoguardrails.benchmark.mock_llm_server.models import ( |
| 26 | + ChatCompletionChoice, |
| 27 | + ChatCompletionRequest, |
| 28 | + ChatCompletionResponse, |
| 29 | + CompletionChoice, |
| 30 | + CompletionRequest, |
| 31 | + CompletionResponse, |
| 32 | + Message, |
| 33 | + Model, |
| 34 | + ModelsResponse, |
| 35 | + Usage, |
| 36 | +) |
| 37 | +from nemoguardrails.benchmark.mock_llm_server.response_data import ( |
| 38 | + calculate_tokens, |
| 39 | + generate_id, |
| 40 | + get_latency_seconds, |
| 41 | + get_response, |
| 42 | +) |
| 43 | + |
| 44 | +# Create a console logging handler |
| 45 | +log = logging.getLogger(__name__) |
| 46 | +log.setLevel(logging.INFO) # TODO Control this from the CLi args |
| 47 | + |
| 48 | +# Create a formatter to define the log message format |
| 49 | +formatter = logging.Formatter( |
| 50 | + "%(asctime)s %(levelname)s: %(message)s", datefmt="%Y-%m-%d %H:%M:%S" |
| 51 | +) |
| 52 | + |
| 53 | +# Create a console handler to print logs to the console |
| 54 | +console_handler = logging.StreamHandler() |
| 55 | +console_handler.setLevel(logging.INFO) # DEBUG and higher will go to the console |
| 56 | +console_handler.setFormatter(formatter) |
| 57 | + |
| 58 | +# Add console handler to logs |
| 59 | +log.addHandler(console_handler) |
| 60 | + |
| 61 | + |
| 62 | +ModelSettingsDep = Annotated[ModelSettings, Depends(get_settings)] |
| 63 | + |
| 64 | + |
| 65 | +def _validate_request_model( |
| 66 | + config: ModelSettingsDep, |
| 67 | + request: Union[CompletionRequest, ChatCompletionRequest], |
| 68 | +) -> None: |
| 69 | + """Check the Completion or Chat Completion `model` field is in our supported model list""" |
| 70 | + if request.model != config.model: |
| 71 | + raise HTTPException( |
| 72 | + status_code=400, |
| 73 | + detail=f"Model '{request.model}' not found. Available models: {config.model}", |
| 74 | + ) |
| 75 | + |
| 76 | + |
| 77 | +app = FastAPI( |
| 78 | + title="Mock LLM Server", |
| 79 | + description="OpenAI-compatible mock LLM server for testing and benchmarking", |
| 80 | + version="0.0.1", |
| 81 | +) |
| 82 | + |
| 83 | + |
| 84 | +@app.middleware("http") |
| 85 | +async def log_http_duration(request: Request, call_next): |
| 86 | + """ |
| 87 | + Middleware to log incoming requests and their responses. |
| 88 | + """ |
| 89 | + request_time = time.time() |
| 90 | + response = await call_next(request) |
| 91 | + response_time = time.time() |
| 92 | + |
| 93 | + duration_seconds = response_time - request_time |
| 94 | + log.info( |
| 95 | + "Request finished: %s, took %.3f seconds", |
| 96 | + response.status_code, |
| 97 | + duration_seconds, |
| 98 | + ) |
| 99 | + return response |
| 100 | + |
| 101 | + |
| 102 | +@app.get("/") |
| 103 | +async def root(config: ModelSettingsDep): |
| 104 | + """Root endpoint with basic server information.""" |
| 105 | + return { |
| 106 | + "message": "Mock LLM Server", |
| 107 | + "version": "0.0.1", |
| 108 | + "description": f"OpenAI-compatible mock LLM server for model: {config.model}", |
| 109 | + "endpoints": ["/v1/models", "/v1/chat/completions", "/v1/completions"], |
| 110 | + "model_configuration": config, |
| 111 | + } |
| 112 | + |
| 113 | + |
| 114 | +@app.get("/v1/models", response_model=ModelsResponse) |
| 115 | +async def list_models(config: ModelSettingsDep): |
| 116 | + """List available models.""" |
| 117 | + log.debug("/v1/models request") |
| 118 | + |
| 119 | + model = Model( |
| 120 | + id=config.model, object="model", created=int(time.time()), owned_by="system" |
| 121 | + ) |
| 122 | + response = ModelsResponse(object="list", data=[model]) |
| 123 | + log.debug("/v1/models response: %s", response) |
| 124 | + return response |
| 125 | + |
| 126 | + |
| 127 | +@app.post("/v1/chat/completions", response_model=ChatCompletionResponse) |
| 128 | +async def chat_completions( |
| 129 | + request: ChatCompletionRequest, config: ModelSettingsDep |
| 130 | +) -> ChatCompletionResponse: |
| 131 | + """Create a chat completion.""" |
| 132 | + |
| 133 | + log.debug("/v1/chat/completions request: %s", request) |
| 134 | + |
| 135 | + # Validate model exists |
| 136 | + _validate_request_model(config, request) |
| 137 | + |
| 138 | + # Generate dummy response |
| 139 | + response_content = get_response(config) |
| 140 | + response_latency_seconds = get_latency_seconds(config) |
| 141 | + |
| 142 | + # Calculate token usage |
| 143 | + prompt_text = " ".join([msg.content for msg in request.messages]) |
| 144 | + prompt_tokens = calculate_tokens(prompt_text) |
| 145 | + completion_tokens = calculate_tokens(response_content) |
| 146 | + |
| 147 | + # Create response |
| 148 | + completion_id = generate_id("chatcmpl") |
| 149 | + created_timestamp = int(time.time()) |
| 150 | + |
| 151 | + choices = [] |
| 152 | + for i in range(request.n or 1): |
| 153 | + choice = ChatCompletionChoice( |
| 154 | + index=i, |
| 155 | + message=Message(role="assistant", content=response_content), |
| 156 | + finish_reason="stop", |
| 157 | + ) |
| 158 | + choices.append(choice) |
| 159 | + |
| 160 | + response = ChatCompletionResponse( |
| 161 | + id=completion_id, |
| 162 | + object="chat.completion", |
| 163 | + created=created_timestamp, |
| 164 | + model=request.model, |
| 165 | + choices=choices, |
| 166 | + usage=Usage( |
| 167 | + prompt_tokens=prompt_tokens, |
| 168 | + completion_tokens=completion_tokens, |
| 169 | + total_tokens=prompt_tokens + completion_tokens, |
| 170 | + ), |
| 171 | + ) |
| 172 | + await asyncio.sleep(response_latency_seconds) |
| 173 | + log.debug("/v1/chat/completions response: %s", response) |
| 174 | + return response |
| 175 | + |
| 176 | + |
| 177 | +@app.post("/v1/completions", response_model=CompletionResponse) |
| 178 | +async def completions( |
| 179 | + request: CompletionRequest, config: ModelSettingsDep |
| 180 | +) -> CompletionResponse: |
| 181 | + """Create a text completion.""" |
| 182 | + |
| 183 | + log.debug("/v1/completions request: %s", request) |
| 184 | + |
| 185 | + # Validate model exists |
| 186 | + _validate_request_model(config, request) |
| 187 | + |
| 188 | + # Handle prompt (can be string or list) |
| 189 | + if isinstance(request.prompt, list): |
| 190 | + prompt_text = " ".join(request.prompt) |
| 191 | + else: |
| 192 | + prompt_text = request.prompt |
| 193 | + |
| 194 | + # Generate dummy response |
| 195 | + response_text = get_response(config) |
| 196 | + response_latency_seconds = get_latency_seconds(config) |
| 197 | + |
| 198 | + # Calculate token usage |
| 199 | + prompt_tokens = calculate_tokens(prompt_text) |
| 200 | + completion_tokens = calculate_tokens(response_text) |
| 201 | + |
| 202 | + # Create response |
| 203 | + completion_id = generate_id("cmpl") |
| 204 | + created_timestamp = int(time.time()) |
| 205 | + |
| 206 | + choices = [] |
| 207 | + for i in range(request.n or 1): |
| 208 | + choice = CompletionChoice( |
| 209 | + text=response_text, index=i, logprobs=None, finish_reason="stop" |
| 210 | + ) |
| 211 | + choices.append(choice) |
| 212 | + |
| 213 | + response = CompletionResponse( |
| 214 | + id=completion_id, |
| 215 | + object="text_completion", |
| 216 | + created=created_timestamp, |
| 217 | + model=request.model, |
| 218 | + choices=choices, |
| 219 | + usage=Usage( |
| 220 | + prompt_tokens=prompt_tokens, |
| 221 | + completion_tokens=completion_tokens, |
| 222 | + total_tokens=prompt_tokens + completion_tokens, |
| 223 | + ), |
| 224 | + ) |
| 225 | + |
| 226 | + await asyncio.sleep(response_latency_seconds) |
| 227 | + log.debug("/v1/completions response: %s", response) |
| 228 | + return response |
| 229 | + |
| 230 | + |
| 231 | +@app.get("/health") |
| 232 | +async def health_check(): |
| 233 | + """Health check endpoint.""" |
| 234 | + log.debug("/health request") |
| 235 | + response = {"status": "healthy", "timestamp": int(time.time())} |
| 236 | + log.debug("/health response: %s", response) |
| 237 | + return response |
0 commit comments