Sunday, December 06, 2026

BUILDING A CHATGPT-LIKE INTERFACE WITH LOCAL LLMS



INTRODUCTION

The rise of large language models has transformed how we interact with artificial intelligence. While services like ChatGPT offer powerful capabilities through cloud-based APIs, there are compelling reasons to run language models locally. Privacy concerns, cost considerations, offline availability, and full control over the model's behavior drive many developers and organizations toward local deployments. This tutorial guides you through building a complete ChatGPT-like chat interface that runs entirely on your own hardware, automatically detecting and utilizing whatever computational resources you have available, whether that's an NVIDIA GPU, AMD graphics card, Apple Silicon, Intel integrated graphics, or just your CPU.


The challenge in creating such a system lies not merely in loading a model and generating text, but in orchestrating multiple components into a cohesive, production-ready application. You need a robust backend that handles model loading, inference optimization, conversation management, and hardware detection. You need a frontend that provides the familiar chat interface users expect, complete with streaming responses, conversation history, and a responsive design. You need the glue that connects these pieces together efficiently and reliably.


Throughout this tutorial, we will build a complete system from the ground up. We will explore the architecture decisions that make the system flexible and maintainable. 


We will implement automatic hardware detection that seamlessly works across different GPU vendors and falls back gracefully to CPU when necessary. We will create a streaming response system that provides the real-time feel of ChatGPT. We will handle the complexities of conversation context management, ensuring the model remembers previous exchanges. By the end, you will have a fully functional, production-ready chat application running entirely on your local machine.


UNDERSTANDING THE ARCHITECTURE

Before diving into code, we must understand the architectural components that comprise our system. A ChatGPT-like application consists of several distinct layers, each with specific responsibilities. The separation of concerns between these layers ensures maintainability, testability, and the ability to swap components as technology evolves.


At the foundation sits the model inference layer. This layer is responsible for loading the language model into memory, managing the computational resources, and generating text based on input prompts. The inference layer must handle the complexities of different hardware backends, optimize memory usage, and provide a consistent interface regardless of the underlying acceleration technology. Modern language models can range from a few gigabytes to hundreds of gigabytes in size, so efficient memory management becomes critical.


Above the inference layer, we have the conversation management layer. Language models are fundamentally stateless; they process input and produce output without inherent memory of previous interactions. To create a chat experience, we must maintain conversation history, format it appropriately for the model, and manage context windows. The context window represents the maximum amount of text the model can process at once, typically measured in tokens. As conversations grow longer, we must implement strategies to summarize or truncate older messages while preserving the essential context.


The API layer provides the interface between the backend logic and the frontend application. This layer handles HTTP requests, manages concurrent connections, implements streaming responses, and ensures proper error handling. For a chat application, streaming is particularly important because it allows the user to see the response being generated in real-time rather than waiting for the entire response to complete.


Finally, the presentation layer delivers the user interface. This includes the HTML structure, CSS styling, and JavaScript logic that creates the interactive chat experience. The frontend must handle user input, display messages in a conversation format, show typing indicators, and smoothly render streaming responses as they arrive from the backend.


HARDWARE DETECTION AND ACCELERATION

One of the most critical aspects of running local language models is efficiently utilizing available hardware. Different systems have vastly different capabilities, and our application must adapt automatically. A developer might have an NVIDIA RTX 4090 with 24GB of VRAM, while another user runs on a MacBook with Apple Silicon, and yet another operates on a server with AMD GPUs. Our system must detect these configurations and select the appropriate acceleration backend.


The Python ecosystem provides several libraries for running language models with hardware acceleration. The most prominent is the transformers library from Hugging Face, combined with PyTorch as the underlying tensor computation framework. PyTorch supports multiple backends through its device abstraction. However, detecting which backend to use requires careful probing of the system.


Let's examine how we implement comprehensive hardware detection:


import torch

import platform

import subprocess


class HardwareDetector:

    """

    Detects available hardware acceleration and selects the optimal device

    for running language models. Supports NVIDIA CUDA, AMD ROCm, Apple MPS,

    Intel GPUs, and CPU fallback.

    """

    

    def __init__(self):

        self.device = None

        self.device_name = None

        self.compute_dtype = None

        self.detected_backend = None

        

    def detect_optimal_device(self):

        """

        Probes the system for available acceleration hardware in order

        of preference: CUDA > ROCm > MPS > Intel > CPU

        """

        # Check for NVIDIA CUDA support

        if torch.cuda.is_available():

            self.device = torch.device("cuda")

            self.device_name = torch.cuda.get_device_name(0)

            self.detected_backend = "NVIDIA CUDA"

            # Use float16 for better performance on modern NVIDIA GPUs

            self.compute_dtype = torch.float16

            return self.device

        

        # Check for AMD ROCm support

        # ROCm uses the same CUDA API in PyTorch but with different backend

        if hasattr(torch.version, 'hip') and torch.version.hip is not None:

            self.device = torch.device("cuda")  # ROCm uses cuda device string

            self.device_name = "AMD GPU (ROCm)"

            self.detected_backend = "AMD ROCm"

            self.compute_dtype = torch.float16

            return self.device

        

        # Check for Apple Metal Performance Shaders (MPS)

        if hasattr(torch.backends, 'mps') and torch.backends.mps.is_available():

            self.device = torch.device("mps")

            self.device_name = "Apple Silicon GPU"

            self.detected_backend = "Apple MPS"

            # MPS works best with float32 currently

            self.compute_dtype = torch.float32

            return self.device

        

        # Check for Intel GPU support (requires intel-extension-for-pytorch)

        try:

            import intel_extension_for_pytorch as ipex

            if ipex.xpu.is_available():

                self.device = torch.device("xpu")

                self.device_name = "Intel GPU"

                self.detected_backend = "Intel XPU"

                self.compute_dtype = torch.float16

                return self.device

        except ImportError:

            pass

        

        # Fallback to CPU

        self.device = torch.device("cpu")

        self.device_name = platform.processor() or "CPU"

        self.detected_backend = "CPU"

        self.compute_dtype = torch.float32

        return self.device


This hardware detection class systematically probes for available acceleration backends. The order of detection matters because we want to use the most powerful available hardware. NVIDIA CUDA GPUs typically offer the best performance for language model inference, so we check for them first. The torch.cuda.is_available() function returns True if PyTorch was compiled with CUDA support and a compatible NVIDIA GPU is present.


AMD GPUs using ROCm present an interesting case. PyTorch's ROCm support uses the same CUDA API surface, which means we use the "cuda" device string even though the underlying implementation uses AMD hardware. We detect ROCm by checking if the torch.version.hip attribute exists and is not None. The HIP (Heterogeneous-compute Interface for Portability) runtime is AMD's equivalent to NVIDIA's CUDA runtime.


Apple's Metal Performance Shaders framework provides GPU acceleration on macOS systems with Apple Silicon or recent Intel Macs. PyTorch added MPS backend support relatively recently, and it continues to improve. We check for MPS availability through the torch.backends.mps.is_available() function. Note that we use float32 precision for MPS because, at the time of this writing, float16 support on MPS can be unstable for some operations.


Intel GPU support requires the intel-extension-for-pytorch package, which provides the XPU device backend. We wrap this check in a try-except block because the extension might not be installed. If available, we can leverage Intel integrated or discrete GPUs for acceleration.


Finally, if no GPU acceleration is available, we fall back to CPU. While CPU inference is significantly slower than GPU acceleration, modern CPUs can still run smaller language models at acceptable speeds, especially with optimizations like quantization.


The compute_dtype attribute is crucial for performance and memory efficiency. Modern GPUs can perform half-precision (float16) arithmetic much faster than full-precision (float32), and using float16 reduces memory consumption by half. However, not all hardware handles float16 equally well, so we select the appropriate precision based on the detected backend.


MODEL LOADING AND INFERENCE

With hardware detection in place, we can now focus on loading and running the language model. The Hugging Face transformers library provides a unified interface for loading thousands of pre-trained models. For our chat application, we'll use models specifically fine-tuned for conversational AI, such as Microsoft's Phi series, Meta's Llama models, or Mistral AI's models.


Loading a large language model involves several steps. First, we must download the model weights and configuration files if they're not already cached locally. Then we load the model into memory and move it to the appropriate device. We also need to load the tokenizer, which converts text into the numerical tokens the model processes.


Here's how we implement the model loading logic:


from transformers import AutoModelForCausalLM, AutoTokenizer

import torch


class LocalLLM:

    """

    Manages loading and inference for local language models with automatic

    hardware acceleration and memory optimization.

    """

    

    def __init__(self, model_name="microsoft/phi-2", max_memory_gb=None):

        """

        Initialize the local LLM with specified model and memory constraints.

        

        Args:

            model_name: HuggingFace model identifier or local path

            max_memory_gb: Maximum GPU memory to use in gigabytes

        """

        self.model_name = model_name

        self.max_memory_gb = max_memory_gb

        self.hardware = HardwareDetector()

        self.device = self.hardware.detect_optimal_device()

        self.model = None

        self.tokenizer = None

        

        print(f"Detected hardware: {self.hardware.detected_backend}")

        print(f"Device: {self.hardware.device_name}")

        print(f"Using dtype: {self.hardware.compute_dtype}")

        

    def load_model(self):

        """

        Load the model and tokenizer with appropriate optimizations

        for the detected hardware.

        """

        print(f"Loading model: {self.model_name}")

        

        # Load tokenizer first as it's lightweight

        self.tokenizer = AutoTokenizer.from_pretrained(

            self.model_name,

            trust_remote_code=True

        )

        

        # Set padding token if not defined

        if self.tokenizer.pad_token is None:

            self.tokenizer.pad_token = self.tokenizer.eos_token

        

        # Prepare model loading arguments based on hardware

        model_kwargs = {

            "trust_remote_code": True,

            "torch_dtype": self.hardware.compute_dtype,

        }

        

        # Add device mapping for multi-GPU or memory-constrained scenarios

        if self.hardware.detected_backend in ["NVIDIA CUDA", "AMD ROCm"]:

            if self.max_memory_gb:

                max_memory = {0: f"{self.max_memory_gb}GB"}

                model_kwargs["device_map"] = "auto"

                model_kwargs["max_memory"] = max_memory

            else:

                model_kwargs["device_map"] = "auto"

        

        # Load the model

        self.model = AutoModelForCausalLM.from_pretrained(

            self.model_name,

            **model_kwargs

        )

        

        # Move to device if not using device_map

        if "device_map" not in model_kwargs:

            self.model = self.model.to(self.device)

        

        # Set model to evaluation mode

        self.model.eval()

        

        print("Model loaded successfully")


The LocalLLM class encapsulates all model-related functionality. In the initialization, we create a HardwareDetector instance and immediately detect the optimal device. This ensures that all subsequent operations use the correct hardware backend.


The load_model method handles the actual loading process. We load the tokenizer first because it's lightweight and fast. The tokenizer is essential for converting text into tokens and vice versa. Some models don't define a padding token, which is needed for batch processing, so we set it to the end-of-sequence token if it's missing.


For the model itself, we use AutoModelForCausalLM, which automatically selects the appropriate model architecture based on the configuration files. The trust_remote_code parameter allows loading models that include custom code, which is necessary for some newer architectures. We specify the torch_dtype to match our hardware's optimal precision.


The device_map parameter is particularly important for large models. When set to "auto", the transformers library automatically distributes the model across available GPUs and can even offload some layers to CPU or disk if GPU memory is insufficient. This enables running models that wouldn't fit entirely in GPU memory. We only use device_map for CUDA and ROCm backends because MPS and XPU have different memory management characteristics.


Setting the model to evaluation mode with model.eval() disables dropout and other training-specific behaviors, ensuring consistent inference results.


IMPLEMENTING TEXT GENERATION

With the model loaded, we can now implement the text generation logic. Language models generate text autoregressively, meaning they predict one token at a time based on all previous tokens. For a chat application, we want to generate responses that are coherent, relevant, and appropriately constrained in length.


The generation process involves several hyperparameters that control the randomness and quality of the output. Temperature controls the randomness of predictions, with lower values making the model more deterministic and higher values more creative. Top-k and top-p sampling limit the set of tokens considered at each step, preventing the model from selecting unlikely tokens. Repetition penalty discourages the model from repeating the same phrases.


Let's implement a generation method with streaming support:


def generate_response(self, prompt, max_new_tokens=512, temperature=0.7,

                     top_p=0.9, top_k=50, repetition_penalty=1.1,

                     stream=False):

    """

    Generate a response to the given prompt with support for streaming output.

    

    Args:

        prompt: Input text to generate from

        max_new_tokens: Maximum number of tokens to generate

        temperature: Sampling temperature (higher = more random)

        top_p: Nucleus sampling threshold

        top_k: Top-k sampling parameter

        repetition_penalty: Penalty for repeating tokens

        stream: If True, yields tokens as they're generated

        

    Returns:

        Generated text string, or yields tokens if stream=True

    """

    # Tokenize the input prompt

    inputs = self.tokenizer(prompt, return_tensors="pt", padding=True)

    input_ids = inputs["input_ids"].to(self.device)

    attention_mask = inputs["attention_mask"].to(self.device)

    

    # Store the length of the input for later extraction

    input_length = input_ids.shape[1]

    

    if stream:

        # Streaming generation yields tokens as they're produced

        generated_tokens = []

        

        with torch.no_grad():

            for _ in range(max_new_tokens):

                # Get model outputs for current sequence

                outputs = self.model(

                    input_ids=input_ids,

                    attention_mask=attention_mask,

                    use_cache=True

                )

                

                # Get logits for the last token

                next_token_logits = outputs.logits[:, -1, :]

                

                # Apply temperature scaling

                next_token_logits = next_token_logits / temperature

                

                # Apply repetition penalty

                if repetition_penalty != 1.0:

                    for token_id in set(input_ids[0].tolist()):

                        next_token_logits[0, token_id] /= repetition_penalty

                

                # Apply top-k filtering

                if top_k > 0:

                    indices_to_remove = next_token_logits < torch.topk(

                        next_token_logits, top_k

                    )[0][..., -1, None]

                    next_token_logits[indices_to_remove] = float('-inf')

                

                # Apply top-p (nucleus) filtering

                if top_p < 1.0:

                    sorted_logits, sorted_indices = torch.sort(

                        next_token_logits, descending=True

                    )

                    cumulative_probs = torch.cumsum(

                        torch.softmax(sorted_logits, dim=-1), dim=-1

                    )

                    sorted_indices_to_remove = cumulative_probs > top_p

                    sorted_indices_to_remove[..., 1:] = \

                        sorted_indices_to_remove[..., :-1].clone()

                    sorted_indices_to_remove[..., 0] = 0

                    indices_to_remove = sorted_indices_to_remove.scatter(

                        1, sorted_indices, sorted_indices_to_remove

                    )

                    next_token_logits[indices_to_remove] = float('-inf')

                

                # Sample from the filtered distribution

                probs = torch.softmax(next_token_logits, dim=-1)

                next_token = torch.multinomial(probs, num_samples=1)

                

                # Check for end of sequence

                if next_token.item() == self.tokenizer.eos_token_id:

                    break

                

                # Decode and yield the new token

                token_text = self.tokenizer.decode(

                    next_token[0], skip_special_tokens=True

                )

                yield token_text

                

                # Append token to sequence for next iteration

                input_ids = torch.cat([input_ids, next_token], dim=-1)

                attention_mask = torch.cat([

                    attention_mask,

                    torch.ones((1, 1), device=self.device)

                ], dim=-1)

                generated_tokens.append(next_token.item())

    else:

        # Non-streaming generation uses the built-in generate method

        with torch.no_grad():

            outputs = self.model.generate(

                input_ids=input_ids,

                attention_mask=attention_mask,

                max_new_tokens=max_new_tokens,

                temperature=temperature,

                top_p=top_p,

                top_k=top_k,

                repetition_penalty=repetition_penalty,

                do_sample=True,

                pad_token_id=self.tokenizer.pad_token_id,

                eos_token_id=self.tokenizer.eos_token_id

            )

        

        # Extract only the newly generated tokens

        generated_ids = outputs[0][input_length:]

        response = self.tokenizer.decode(

            generated_ids, skip_special_tokens=True

        )

        return response


This generation method supports both streaming and non-streaming modes. The streaming mode is essential for creating a responsive chat interface where users see the response being typed out in real-time, just like ChatGPT. The non-streaming mode uses the model's built-in generate method, which is optimized but returns the complete response only after generation finishes.


In streaming mode, we implement the generation loop manually. At each step, we pass the current sequence through the model to get logits for the next token. Logits are the raw, unnormalized scores for each token in the vocabulary. We then apply several transformations to these logits to control the generation process.


Temperature scaling divides the logits by the temperature value. Lower temperatures make the probability distribution more peaked around the highest-scoring tokens, leading to more deterministic output. Higher temperatures flatten the distribution, increasing randomness and creativity.


Repetition penalty discourages the model from repeating tokens that have already appeared in the sequence. We divide the logits of previously seen tokens by the repetition penalty, making them less likely to be selected again.


Top-k filtering keeps only the k highest-probability tokens and sets all others to negative infinity, effectively removing them from consideration. This prevents the model from selecting very unlikely tokens that might derail the generation.


Top-p sampling, also called nucleus sampling, keeps the smallest set of tokens whose cumulative probability exceeds p. This is more dynamic than top-k because the number of tokens considered varies based on the probability distribution. We implement this by sorting the logits, computing cumulative probabilities, and masking tokens beyond the threshold.


After applying all these filters, we convert the logits to probabilities using softmax and sample a token from the resulting distribution. We check if the sampled token is the end-of-sequence token, which signals that the model has finished its response. If not, we decode the token to text and yield it, then append it to the sequence for the next iteration.


The attention_mask keeps track of which positions in the sequence are actual tokens versus padding. We extend it with each new token to maintain proper attention patterns.


CONVERSATION MANAGEMENT

A chat application must maintain conversation history to provide context for the model. Unlike APIs that handle this server-side, our local implementation must manage the conversation state explicitly. We need to format the conversation in a way the model understands, typically using special tokens or formatting conventions that the model was trained with.


Different models use different conversation formats. Some use special tokens like <|user|> and <|assistant|>, while others use specific prompt templates. We'll implement a flexible conversation manager that can adapt to different formats:


class ConversationManager:

    """

    Manages conversation history and formats messages appropriately

    for the language model.

    """

    

    def __init__(self, system_prompt=None, max_context_tokens=2048):

        """

        Initialize the conversation manager.

        

        Args:

            system_prompt: Optional system message to set behavior

            max_context_tokens: Maximum tokens to keep in context

        """

        self.messages = []

        self.system_prompt = system_prompt

        self.max_context_tokens = max_context_tokens

        

        if system_prompt:

            self.messages.append({

                "role": "system",

                "content": system_prompt

            })

    

    def add_user_message(self, content):

        """Add a user message to the conversation history."""

        self.messages.append({

            "role": "user",

            "content": content

        })

    

    def add_assistant_message(self, content):

        """Add an assistant message to the conversation history."""

        self.messages.append({

            "role": "assistant",

            "content": content

        })

    

    def format_conversation(self, tokenizer):

        """

        Format the conversation history into a prompt string.

        Handles context window limitations by truncating old messages.

        

        Args:

            tokenizer: The model's tokenizer for counting tokens

            

        Returns:

            Formatted prompt string

        """

        # Try to use the tokenizer's chat template if available

        if hasattr(tokenizer, 'apply_chat_template'):

            try:

                prompt = tokenizer.apply_chat_template(

                    self.messages,

                    tokenize=False,

                    add_generation_prompt=True

                )

                return prompt

            except Exception:

                pass

        

        # Fallback to manual formatting

        prompt_parts = []

        

        for message in self.messages:

            role = message["role"]

            content = message["content"]

            

            if role == "system":

                prompt_parts.append(f"System: {content}\n")

            elif role == "user":

                prompt_parts.append(f"User: {content}\n")

            elif role == "assistant":

                prompt_parts.append(f"Assistant: {content}\n")

        

        # Add the prompt for the assistant's next response

        prompt_parts.append("Assistant:")

        

        prompt = "\n".join(prompt_parts)

        

        # Check token count and truncate if necessary

        tokens = tokenizer.encode(prompt)

        if len(tokens) > self.max_context_tokens:

            # Keep system message and truncate from the beginning of conversation

            system_messages = [m for m in self.messages if m["role"] == "system"]

            other_messages = [m for m in self.messages if m["role"] != "system"]

            

            # Binary search to find how many messages fit

            left, right = 0, len(other_messages)

            while left < right:

                mid = (left + right + 1) // 2

                test_messages = system_messages + other_messages[-mid:]

                

                if hasattr(tokenizer, 'apply_chat_template'):

                    try:

                        test_prompt = tokenizer.apply_chat_template(

                            test_messages,

                            tokenize=False,

                            add_generation_prompt=True

                        )

                    except Exception:

                        test_prompt = self._manual_format(test_messages)

                else:

                    test_prompt = self._manual_format(test_messages)

                

                test_tokens = tokenizer.encode(test_prompt)

                if len(test_tokens) <= self.max_context_tokens:

                    left = mid

                else:

                    right = mid - 1

            

            # Reconstruct with fitting messages

            self.messages = system_messages + other_messages[-left:]

            return self.format_conversation(tokenizer)

        

        return prompt

    

    def _manual_format(self, messages):

        """Helper method for manual message formatting."""

        prompt_parts = []

        for message in messages:

            role = message["role"]

            content = message["content"]

            if role == "system":

                prompt_parts.append(f"System: {content}\n")

            elif role == "user":

                prompt_parts.append(f"User: {content}\n")

            elif role == "assistant":

                prompt_parts.append(f"Assistant: {content}\n")

        prompt_parts.append("Assistant:")

        return "\n".join(prompt_parts)

    

    def clear_history(self):

        """Clear conversation history, keeping only system prompt if set."""

        if self.system_prompt:

            self.messages = [{

                "role": "system",

                "content": self.system_prompt

            }]

        else:

            self.messages = []

    

    def get_history(self):

        """Return the conversation history."""

        return self.messages.copy()


The ConversationManager class maintains a list of messages, each with a role (system, user, or assistant) and content. The system role allows setting instructions that guide the model's behavior throughout the conversation. For example, you might set a system prompt like "You are a helpful assistant that provides concise answers" to influence the model's response style.


The format_conversation method is crucial because it transforms the structured message history into a prompt string the model can process. Modern models often include a chat template in their tokenizer configuration, which we can use via the apply_chat_template method. This ensures we format the conversation exactly as the model expects based on its training.


If the chat template is unavailable or fails, we fall back to a simple manual format using role prefixes. This works reasonably well with most instruction-tuned models, though it may not be optimal for every model.


Context window management is one of the trickiest aspects of conversation handling. Language models have a maximum context length they can process, typically between 2048 and 8192 tokens for smaller models. As conversations grow longer, we must truncate older messages to stay within this limit. Our implementation uses a binary search algorithm to find the maximum number of recent messages that fit within the token budget, always preserving the system message if present.


The binary search approach is efficient because it avoids repeatedly tokenizing the entire conversation. We test different message counts, tokenize the resulting prompt, and adjust our search range based on whether the result fits within the limit. This ensures we include as much context as possible while respecting the model's constraints.


BUILDING THE WEB API

To create a web-based chat interface, we need an API that the frontend can communicate with. We'll use FastAPI, a modern Python web framework that provides excellent performance, automatic API documentation, and built-in support for asynchronous operations and streaming responses.


The API needs several endpoints: one for sending messages and receiving responses, one for clearing conversation history, and one for checking the system status. The message endpoint must support streaming to enable real-time response display.


Here's the implementation of our API layer:


from fastapi import FastAPI, HTTPException

from fastapi.responses import StreamingResponse, JSONResponse

from fastapi.middleware.cors import CORSMiddleware

from pydantic import BaseModel

from typing import Optional, List, Dict

import asyncio

import json

import uvicorn


app = FastAPI(title="Local LLM Chat API")


# Enable CORS for frontend access

app.add_middleware(

    CORSMiddleware,

    allow_origins=["*"],

    allow_credentials=True,

    allow_methods=["*"],

    allow_headers=["*"],

)


# Global instances

llm_instance = None

conversation_manager = None


class ChatMessage(BaseModel):

    """Schema for incoming chat messages."""

    message: str

    stream: bool = True

    temperature: Optional[float] = 0.7

    max_tokens: Optional[int] = 512


class SystemConfig(BaseModel):

    """Schema for system configuration."""

    system_prompt: Optional[str] = None

    model_name: Optional[str] = "microsoft/phi-2"

    max_context_tokens: Optional[int] = 2048


@app.on_event("startup")

async def startup_event():

    """Initialize the model and conversation manager on startup."""

    global llm_instance, conversation_manager

    

    print("Initializing Local LLM Chat System...")

    

    # Initialize with default model

    llm_instance = LocalLLM(model_name="microsoft/phi-2")

    llm_instance.load_model()

    

    # Initialize conversation manager

    conversation_manager = ConversationManager(

        system_prompt="You are a helpful AI assistant.",

        max_context_tokens=2048

    )

    

    print("System ready!")


@app.post("/chat")

async def chat(message: ChatMessage):

    """

    Process a chat message and return the assistant's response.

    Supports both streaming and non-streaming modes.

    """

    if llm_instance is None or conversation_manager is None:

        raise HTTPException(status_code=503, detail="Model not loaded")

    

    # Add user message to conversation history

    conversation_manager.add_user_message(message.message)

    

    # Format the conversation into a prompt

    prompt = conversation_manager.format_conversation(llm_instance.tokenizer)

    

    if message.stream:

        # Return streaming response

        async def generate_stream():

            """Async generator for streaming responses."""

            full_response = ""

            

            try:

                # Run the synchronous generator in a thread pool

                for token in llm_instance.generate_response(

                    prompt=prompt,

                    max_new_tokens=message.max_tokens,

                    temperature=message.temperature,

                    stream=True

                ):

                    full_response += token

                    # Format as Server-Sent Events

                    yield f"data: {json.dumps({'token': token})}\n\n"

                    # Small delay to prevent overwhelming the client

                    await asyncio.sleep(0.01)

                

                # Add complete response to conversation history

                conversation_manager.add_assistant_message(full_response)

                

                # Send completion signal

                yield f"data: {json.dumps({'done': True})}\n\n"

                

            except Exception as e:

                error_msg = f"Error during generation: {str(e)}"

                yield f"data: {json.dumps({'error': error_msg})}\n\n"

        

        return StreamingResponse(

            generate_stream(),

            media_type="text/event-stream"

        )

    else:

        # Return complete response

        try:

            response = llm_instance.generate_response(

                prompt=prompt,

                max_new_tokens=message.max_tokens,

                temperature=message.temperature,

                stream=False

            )

            

            # Add assistant response to conversation history

            conversation_manager.add_assistant_message(response)

            

            return JSONResponse({

                "response": response,

                "done": True

            })

        except Exception as e:

            raise HTTPException(

                status_code=500,

                detail=f"Error during generation: {str(e)}"

            )


@app.post("/clear")

async def clear_conversation():

    """Clear the conversation history."""

    if conversation_manager is None:

        raise HTTPException(status_code=503, detail="System not initialized")

    

    conversation_manager.clear_history()

    return JSONResponse({"status": "success", "message": "Conversation cleared"})


@app.get("/history")

async def get_history():

    """Retrieve the conversation history."""

    if conversation_manager is None:

        raise HTTPException(status_code=503, detail="System not initialized")

    

    return JSONResponse({"history": conversation_manager.get_history()})


@app.get("/status")

async def get_status():

    """Get system status and hardware information."""

    if llm_instance is None:

        return JSONResponse({

            "status": "not_ready",

            "model_loaded": False

        })

    

    return JSONResponse({

        "status": "ready",

        "model_loaded": True,

        "model_name": llm_instance.model_name,

        "device": llm_instance.hardware.detected_backend,

        "device_name": llm_instance.hardware.device_name

    })


@app.post("/configure")

async def configure_system(config: SystemConfig):

    """

    Reconfigure the system with new settings.

    This will reload the model if model_name changes.

    """

    global llm_instance, conversation_manager

    

    try:

        # Check if we need to reload the model

        if config.model_name and config.model_name != llm_instance.model_name:

            print(f"Reloading model: {config.model_name}")

            llm_instance = LocalLLM(model_name=config.model_name)

            llm_instance.load_model()

        

        # Reconfigure conversation manager

        conversation_manager = ConversationManager(

            system_prompt=config.system_prompt,

            max_context_tokens=config.max_context_tokens or 2048

        )

        

        return JSONResponse({

            "status": "success",

            "message": "System reconfigured"

        })

    except Exception as e:

        raise HTTPException(

            status_code=500,

            detail=f"Configuration error: {str(e)}"

        )


The FastAPI application defines several endpoints that together provide complete chat functionality. The startup_event function runs when the server starts, initializing the language model and conversation manager. This ensures the model is loaded and ready before any requests arrive.


The chat endpoint is the core of the API. It accepts a ChatMessage object containing the user's message and optional parameters like streaming mode, temperature, and maximum token count. We add the user's message to the conversation history, format the entire conversation into a prompt, and generate a response.


For streaming responses, we use FastAPI's StreamingResponse with an async generator. The generator yields tokens as they're produced by the model, formatted as Server-Sent Events (SSE). SSE is a standard protocol for server-to-client streaming over HTTP, perfect for our real-time chat application. Each token is sent as a JSON object wrapped in the SSE format, and we include a small delay to prevent overwhelming the client with data.


The non-streaming path is simpler, generating the complete response and returning it as a JSON object. Both paths add the assistant's response to the conversation history, ensuring subsequent messages have the full context.


The clear endpoint allows users to start a new conversation by clearing the history. The history endpoint returns the current conversation, which could be useful for debugging or implementing a conversation export feature. The status endpoint provides information about the system's state and the loaded model, useful for displaying system information in the UI.


The configure endpoint allows dynamic reconfiguration of the system. Users can change the system prompt, adjust the context window size, or even switch to a different model without restarting the server. This flexibility is particularly valuable during development and testing.


CORS middleware is enabled to allow the frontend to make requests from a different origin. In production, you would restrict this to specific domains, but for development, allowing all origins simplifies testing.


CREATING THE FRONTEND INTERFACE

The frontend must provide an intuitive, responsive chat interface that feels natural and familiar to users. We'll create a single-page application using HTML, CSS, and vanilla JavaScript. While frameworks like React or Vue could be used, vanilla JavaScript keeps our dependencies minimal and the code easier to understand.


The interface needs several components: a message display area that shows the conversation history, an input field for typing messages, a send button, and visual indicators for loading states. We'll implement smooth scrolling, typing animations, and proper error handling.


Let's start with the HTML structure:


<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Local LLM Chat</title>

    <style>

        * {

            margin: 0;

            padding: 0;

            box-sizing: border-box;

        }

        

        body {

            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 

                         'Helvetica Neue', Arial, sans-serif;

            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

            height: 100vh;

            display: flex;

            justify-content: center;

            align-items: center;

            padding: 20px;

        }

        

        .chat-container {

            width: 100%;

            max-width: 800px;

            height: 90vh;

            background: white;

            border-radius: 16px;

            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);

            display: flex;

            flex-direction: column;

            overflow: hidden;

        }

        

        .chat-header {

            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

            color: white;

            padding: 20px;

            display: flex;

            justify-content: space-between;

            align-items: center;

        }

        

        .chat-header h1 {

            font-size: 24px;

            font-weight: 600;

        }

        

        .status-indicator {

            display: flex;

            align-items: center;

            gap: 8px;

            font-size: 14px;

        }

        

        .status-dot {

            width: 10px;

            height: 10px;

            border-radius: 50%;

            background: #4ade80;

            animation: pulse 2s infinite;

        }

        

        @keyframes pulse {

            0%, 100% { opacity: 1; }

            50% { opacity: 0.5; }

        }

        

        .messages-container {

            flex: 1;

            overflow-y: auto;

            padding: 20px;

            display: flex;

            flex-direction: column;

            gap: 16px;

        }

        

        .message {

            display: flex;

            gap: 12px;

            animation: slideIn 0.3s ease-out;

        }

        

        @keyframes slideIn {

            from {

                opacity: 0;

                transform: translateY(10px);

            }

            to {

                opacity: 1;

                transform: translateY(0);

            }

        }

        

        .message.user {

            flex-direction: row-reverse;

        }

        

        .message-avatar {

            width: 40px;

            height: 40px;

            border-radius: 50%;

            display: flex;

            align-items: center;

            justify-content: center;

            font-weight: 600;

            flex-shrink: 0;

        }

        

        .message.user .message-avatar {

            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

            color: white;

        }

        

        .message.assistant .message-avatar {

            background: #f3f4f6;

            color: #6b7280;

        }

        

        .message-content {

            max-width: 70%;

            padding: 12px 16px;

            border-radius: 12px;

            line-height: 1.5;

            word-wrap: break-word;

        }

        

        .message.user .message-content {

            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

            color: white;

        }

        

        .message.assistant .message-content {

            background: #f3f4f6;

            color: #1f2937;

        }

        

        .typing-indicator {

            display: flex;

            gap: 4px;

            padding: 12px 16px;

        }

        

        .typing-dot {

            width: 8px;

            height: 8px;

            border-radius: 50%;

            background: #9ca3af;

            animation: typing 1.4s infinite;

        }

        

        .typing-dot:nth-child(2) {

            animation-delay: 0.2s;

        }

        

        .typing-dot:nth-child(3) {

            animation-delay: 0.4s;

        }

        

        @keyframes typing {

            0%, 60%, 100% {

                transform: translateY(0);

            }

            30% {

                transform: translateY(-10px);

            }

        }

        

        .input-container {

            padding: 20px;

            background: #f9fafb;

            border-top: 1px solid #e5e7eb;

            display: flex;

            gap: 12px;

        }

        

        .message-input {

            flex: 1;

            padding: 12px 16px;

            border: 2px solid #e5e7eb;

            border-radius: 24px;

            font-size: 15px;

            outline: none;

            transition: border-color 0.2s;

            font-family: inherit;

        }

        

        .message-input:focus {

            border-color: #667eea;

        }

        

        .send-button {

            padding: 12px 24px;

            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

            color: white;

            border: none;

            border-radius: 24px;

            font-size: 15px;

            font-weight: 600;

            cursor: pointer;

            transition: transform 0.2s, box-shadow 0.2s;

        }

        

        .send-button:hover:not(:disabled) {

            transform: translateY(-2px);

            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);

        }

        

        .send-button:disabled {

            opacity: 0.5;

            cursor: not-allowed;

        }

        

        .clear-button {

            padding: 8px 16px;

            background: rgba(255, 255, 255, 0.2);

            color: white;

            border: 1px solid rgba(255, 255, 255, 0.3);

            border-radius: 16px;

            font-size: 14px;

            cursor: pointer;

            transition: background 0.2s;

        }

        

        .clear-button:hover {

            background: rgba(255, 255, 255, 0.3);

        }

        

        .error-message {

            background: #fee2e2;

            color: #991b1b;

            padding: 12px 16px;

            border-radius: 8px;

            margin: 8px 0;

            border-left: 4px solid #dc2626;

        }

    </style>

</head>

<body>

    <div class="chat-container">

        <div class="chat-header">

            <h1>Local LLM Chat</h1>

            <div class="status-indicator">

                <div class="status-dot"></div>

                <span id="status-text">Ready</span>

                <button class="clear-button" onclick="clearConversation()">

                    Clear Chat

                </button>

            </div>

        </div>

        

        <div class="messages-container" id="messages">

            <!-- Messages will be inserted here -->

        </div>

        

        <div class="input-container">

            <input 

                type="text" 

                class="message-input" 

                id="messageInput"

                placeholder="Type your message..."

                onkeypress="handleKeyPress(event)"

            >

            <button 

                class="send-button" 

                id="sendButton"

                onclick="sendMessage()"

            >

                Send

            </button>

        </div>

    </div>

    

    <script>

        // API configuration

        const API_BASE_URL = 'http://localhost:8000';

        

        // State management

        let isGenerating = false;

        let currentAssistantMessage = null;

        

        /**

         * Initialize the application and check system status

         */

        async function initialize() {

            try {

                const response = await fetch(`${API_BASE_URL}/status`);

                const data = await response.json();

                

                if (data.status === 'ready') {

                    updateStatus(`Ready - ${data.device}`, true);

                } else {

                    updateStatus('Initializing...', false);

                }

            } catch (error) {

                updateStatus('Connection Error', false);

                showError('Could not connect to the backend server. Please ensure it is running.');

            }

        }

        

        /**

         * Update the status indicator in the header

         */

        function updateStatus(text, isReady) {

            const statusText = document.getElementById('status-text');

            const statusDot = document.querySelector('.status-dot');

            

            statusText.textContent = text;

            statusDot.style.background = isReady ? '#4ade80' : '#fbbf24';

        }

        

        /**

         * Add a message to the chat display

         */

        function addMessage(content, role) {

            const messagesContainer = document.getElementById('messages');

            const messageDiv = document.createElement('div');

            messageDiv.className = `message ${role}`;

            

            const avatar = document.createElement('div');

            avatar.className = 'message-avatar';

            avatar.textContent = role === 'user' ? 'U' : 'AI';

            

            const contentDiv = document.createElement('div');

            contentDiv.className = 'message-content';

            contentDiv.textContent = content;

            

            messageDiv.appendChild(avatar);

            messageDiv.appendChild(contentDiv);

            messagesContainer.appendChild(messageDiv);

            

            // Scroll to bottom

            messagesContainer.scrollTop = messagesContainer.scrollHeight;

            

            return contentDiv;

        }

        

        /**

         * Show typing indicator while assistant is generating response

         */

        function showTypingIndicator() {

            const messagesContainer = document.getElementById('messages');

            const messageDiv = document.createElement('div');

            messageDiv.className = 'message assistant';

            messageDiv.id = 'typing-indicator';

            

            const avatar = document.createElement('div');

            avatar.className = 'message-avatar';

            avatar.textContent = 'AI';

            

            const typingDiv = document.createElement('div');

            typingDiv.className = 'message-content';

            typingDiv.innerHTML = `

                <div class="typing-indicator">

                    <div class="typing-dot"></div>

                    <div class="typing-dot"></div>

                    <div class="typing-dot"></div>

                </div>

            `;

            

            messageDiv.appendChild(avatar);

            messageDiv.appendChild(typingDiv);

            messagesContainer.appendChild(messageDiv);

            messagesContainer.scrollTop = messagesContainer.scrollHeight;

        }

        

        /**

         * Remove typing indicator

         */

        function removeTypingIndicator() {

            const indicator = document.getElementById('typing-indicator');

            if (indicator) {

                indicator.remove();

            }

        }

        

        /**

         * Show error message in the chat

         */

        function showError(message) {

            const messagesContainer = document.getElementById('messages');

            const errorDiv = document.createElement('div');

            errorDiv.className = 'error-message';

            errorDiv.textContent = message;

            messagesContainer.appendChild(errorDiv);

            messagesContainer.scrollTop = messagesContainer.scrollHeight;

        }

        

        /**

         * Send a message to the backend and handle the streaming response

         */

        async function sendMessage() {

            const input = document.getElementById('messageInput');

            const message = input.value.trim();

            

            if (!message || isGenerating) {

                return;

            }

            

            // Clear input and disable controls

            input.value = '';

            isGenerating = true;

            updateControls();

            

            // Add user message to display

            addMessage(message, 'user');

            

            // Show typing indicator

            showTypingIndicator();

            

            try {

                const response = await fetch(`${API_BASE_URL}/chat`, {

                    method: 'POST',

                    headers: {

                        'Content-Type': 'application/json',

                    },

                    body: JSON.stringify({

                        message: message,

                        stream: true,

                        temperature: 0.7,

                        max_tokens: 512

                    })

                });

                

                if (!response.ok) {

                    throw new Error(`HTTP error! status: ${response.status}`);

                }

                

                // Remove typing indicator and create assistant message

                removeTypingIndicator();

                currentAssistantMessage = addMessage('', 'assistant');

                

                // Process the streaming response

                const reader = response.body.getReader();

                const decoder = new TextDecoder();

                let buffer = '';

                

                while (true) {

                    const { done, value } = await reader.read();

                    

                    if (done) {

                        break;

                    }

                    

                    // Decode the chunk and add to buffer

                    buffer += decoder.decode(value, { stream: true });

                    

                    // Process complete SSE messages

                    const lines = buffer.split('\n');

                    buffer = lines.pop(); // Keep incomplete line in buffer

                    

                    for (const line of lines) {

                        if (line.startsWith('data: ')) {

                            const data = JSON.parse(line.slice(6));

                            

                            if (data.error) {

                                showError(data.error);

                                break;

                            }

                            

                            if (data.token) {

                                // Append token to assistant message

                                currentAssistantMessage.textContent += data.token;

                                

                                // Auto-scroll

                                const messagesContainer = document.getElementById('messages');

                                messagesContainer.scrollTop = messagesContainer.scrollHeight;

                            }

                            

                            if (data.done) {

                                break;

                            }

                        }

                    }

                }

                

            } catch (error) {

                removeTypingIndicator();

                showError(`Error: ${error.message}`);

            } finally {

                isGenerating = false;

                currentAssistantMessage = null;

                updateControls();

            }

        }

        

        /**

         * Update control states based on generation status

         */

        function updateControls() {

            const sendButton = document.getElementById('sendButton');

            const messageInput = document.getElementById('messageInput');

            

            sendButton.disabled = isGenerating;

            messageInput.disabled = isGenerating;

            

            if (!isGenerating) {

                messageInput.focus();

            }

        }

        

        /**

         * Handle Enter key press in input field

         */

        function handleKeyPress(event) {

            if (event.key === 'Enter' && !event.shiftKey) {

                event.preventDefault();

                sendMessage();

            }

        }

        

        /**

         * Clear the conversation history

         */

        async function clearConversation() {

            if (!confirm('Are you sure you want to clear the conversation?')) {

                return;

            }

            

            try {

                const response = await fetch(`${API_BASE_URL}/clear`, {

                    method: 'POST'

                });

                

                if (response.ok) {

                    // Clear the messages display

                    const messagesContainer = document.getElementById('messages');

                    messagesContainer.innerHTML = '';

                }

            } catch (error) {

                showError(`Error clearing conversation: ${error.message}`);

            }

        }

        

        // Initialize on page load

        window.addEventListener('load', initialize);

    </script>

</body>

</html>


This HTML file contains everything needed for the frontend: structure, styling, and JavaScript logic. The CSS creates a modern, polished interface with smooth animations and a gradient color scheme. The layout uses flexbox to create a responsive design that adapts to different screen sizes.


The JavaScript code manages the entire client-side application state and communication with the backend. The initialize function runs when the page loads, checking the backend status and updating the UI accordingly. This provides immediate feedback to users about whether the system is ready.


The sendMessage function handles the core chat interaction. When the user sends a message, we add it to the display, show a typing indicator, and make a POST request to the backend's chat endpoint. The streaming response requires special handling because it arrives as Server-Sent Events rather than a simple JSON response.


We use the Fetch API's streaming capabilities to process the response incrementally. The response.body.getReader() method returns a reader that lets us consume the response chunk by chunk. We decode each chunk using TextDecoder and parse the SSE format, which consists of lines starting with "data: " followed by JSON.“


As tokens arrive, we append them to the assistant's message element, creating the typing effect users expect from ChatGPT. The auto-scroll ensures the latest content remains visible as the message grows. When the stream completes or an error occurs, we update the UI state and re-enable the input controls.


The clearConversation function provides a way to start fresh, calling the backend's clear endpoint and removing all messages from the display. We include a confirmation dialog to prevent accidental clearing.


Error handling is comprehensive throughout the code. Network errors, backend errors, and parsing errors all result in user-friendly error messages displayed in the chat interface. This ensures users understand what went wrong rather than seeing cryptic console errors.


RUNNING THE COMPLETE SYSTEM

Now that we have implemented all components, let's discuss how to run the complete system. The process involves installing dependencies, starting the backend server, and opening the frontend in a web browser.


First, you need to install the required Python packages. Create a requirements.txt file with the following contents:


torch>=2.0.0

transformers>=4.35.0

fastapi>=0.104.0

uvicorn>=0.24.0

pydantic>=2.0.0

accelerate>=0.24.0


Install these packages using pip:

pip install -r requirements.txt


For GPU support, you need to install the appropriate PyTorch version for your hardware. 


For NVIDIA CUDA:

pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118


For AMD ROCm:

pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/rocm5.6


For Apple Silicon, the default PyTorch installation includes MPS support. 


For Intel GPUs, install the Intel extension:

pip install intel-extension-for-pytorch


With dependencies installed, you can start the backend server. Save all the Python code we've written into a file called main.py, then run:

uvicorn main:app --host 0.0.0.0 --port 8000 --reload


The server will start and automatically load the language model. You'll see output indicating the detected hardware and model loading progress. The first time you run it, the model will be downloaded from Hugging Face, which may take several minutes depending on your internet connection and the model size.


Once the server is running, save the HTML frontend code to a file called index.html and open it in a web browser. You can simply double-click the file or use a local web server. If you have Python installed, you can start a simple HTTP server:

python -m http.server 8080


Then navigate to http://localhost:8080/index.html in your browser. You should see the chat interface with a "Ready" status indicator. Type a message and press Enter or click Send. The assistant will respond, with the text appearing token by token just like ChatGPT.


OPTIMIZATION AND PRODUCTION CONSIDERATIONS

While our implementation is fully functional, there are several optimizations and considerations for production deployment. Performance, memory usage, and reliability all benefit from additional refinements.


Model quantization significantly reduces memory usage and can improve inference speed. Quantization converts model weights from 32-bit or 16-bit floating-point to 8-bit or even 4-bit integers. The transformers library supports several quantization methods through the bitsandbytes library:


from transformers import BitsAndBytesConfig


quantization_config = BitsAndBytesConfig(

    load_in_4bit=True,

    bnb_4bit_compute_dtype=torch.float16,

    bnb_4bit_use_double_quant=True,

    bnb_4bit_quant_type="nf4"

)


model = AutoModelForCausalLM.from_pretrained(

    model_name,

    quantization_config=quantization_config,

    device_map="auto"

)


This configuration loads the model in 4-bit precision using the NF4 quantization type, which provides excellent quality while reducing memory usage by approximately 75 percent compared to float16. The double quantization further compresses the quantization constants themselves.


Caching is another important optimization. The model's generate method supports key-value caching, which stores intermediate computations and reuses them for subsequent tokens. This is already enabled in our implementation through the use_cache parameter. For conversation management, you might implement a cache for formatted prompts to avoid repeatedly tokenizing the same conversation history.


For production deployments, consider implementing request queuing and rate limiting. Multiple concurrent users can overwhelm the system, especially on limited hardware. A queue ensures requests are processed sequentially or with controlled parallelism:


from asyncio import Queue, create_task

import asyncio


request_queue = Queue(maxsize=10)


async def process_queue():

    """Background task that processes queued requests."""

    while True:

        request = await request_queue.get()

        try:

            await request['handler']()

        finally:

            request_queue.task_done()


@app.on_event("startup")

async def start_queue_processor():

    """Start the queue processor on application startup."""

    create_task(process_queue())


This queue-based approach prevents the system from attempting to run multiple inferences simultaneously, which could cause out-of-memory errors or severe performance degradation.


Monitoring and logging are essential for production systems. Implement comprehensive logging of requests, response times, errors, and resource usage. This data helps identify performance bottlenecks and system issues:


import logging

import time


logging.basicConfig(

    level=logging.INFO,

    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'

)

logger = logging.getLogger(__name__)


@app.middleware("http")

async def log_requests(request, call_next):

    """Middleware to log all requests and their processing time."""

    start_time = time.time()

    response = await call_next(request)

    process_time = time.time() - start_time

    logger.info(

        f"{request.method} {request.url.path} "

        f"completed in {process_time:.2f}s"

    )

    return response


Security considerations include input validation, rate limiting per user, and sanitization of generated content. While language models generally don't execute code or access systems directly, they can be prompted to generate harmful or inappropriate content. Implementing content filters and monitoring for abuse patterns helps maintain a safe environment.


For deployment, containerization with Docker simplifies distribution and ensures consistent environments across different systems. A Dockerfile for our application might look like:


FROM python:3.10-slim


WORKDIR /app


COPY requirements.txt .

RUN pip install --no-cache-dir -r requirements.txt


COPY main.py .

COPY index.html .


EXPOSE 8000


CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]


This creates a containerized version of the application that can run anywhere Docker is available, with all dependencies included.


ADVANCED FEATURES AND EXTENSIONS

Beyond the basic chat functionality, several advanced features can enhance the user experience and expand the system's capabilities. These extensions demonstrate the flexibility of our architecture and provide starting points for customization.


Multi-model support allows users to switch between different language models without restarting the application. We've already implemented the configure endpoint for this purpose. You could extend the frontend to include a model selector dropdown that calls this endpoint when changed.


Document upload and context injection enable the model to answer questions about specific documents. This requires implementing document parsing, chunking, and retrieval mechanisms:


from typing import List

import PyPDF2

import io


class DocumentProcessor:

    """Process and manage documents for context injection."""

    

    def __init__(self, max_chunk_size=1000):

        self.max_chunk_size = max_chunk_size

        self.documents = {}

    

    def process_pdf(self, file_bytes: bytes, doc_id: str):

        """Extract text from PDF and store in chunks."""

        pdf_reader = PyPDF2.PdfReader(io.BytesIO(file_bytes))

        text = ""

        for page in pdf_reader.pages:

            text += page.extract_text()

        

        # Split into chunks

        chunks = self._chunk_text(text)

        self.documents[doc_id] = chunks

        return len(chunks)

    

    def _chunk_text(self, text: str) -> List[str]:

        """Split text into manageable chunks."""

        words = text.split()

        chunks = []

        current_chunk = []

        current_size = 0

        

        for word in words:

            current_chunk.append(word)

            current_size += len(word) + 1

            

            if current_size >= self.max_chunk_size:

                chunks.append(' '.join(current_chunk))

                current_chunk = []

                current_size = 0

        

        if current_chunk:

            chunks.append(' '.join(current_chunk))

        

        return chunks

    

    def get_relevant_context(self, query: str, doc_id: str, 

                           num_chunks: int = 3) -> str:

        """Retrieve relevant document chunks for a query."""

        if doc_id not in self.documents:

            return ""

        

        # Simple relevance: chunks containing query words

        # In production, use embeddings and semantic search

        query_words = set(query.lower().split())

        chunks = self.documents[doc_id]

        

        scored_chunks = []

        for chunk in chunks:

            chunk_words = set(chunk.lower().split())

            score = len(query_words & chunk_words)

            scored_chunks.append((score, chunk))

        

        scored_chunks.sort(reverse=True)

        relevant = [chunk for _, chunk in scored_chunks[:num_chunks]]

        

        return "\n\n".join(relevant)


This document processor extracts text from PDFs, splits it into chunks, and retrieves relevant sections based on the user's query. For production use, you would implement semantic search using embeddings to find truly relevant content rather than simple keyword matching.


Conversation export and import allow users to save and restore chat sessions. This is straightforward to implement by serializing the conversation manager's message history:


import json

from datetime import datetime


@app.get("/export")

async def export_conversation():

    """Export the current conversation as JSON."""

    if conversation_manager is None:

        raise HTTPException(status_code=503, detail="System not initialized")

    

    export_data = {

        "timestamp": datetime.now().isoformat(),

        "model": llm_instance.model_name,

        "messages": conversation_manager.get_history()

    }

    

    return JSONResponse(export_data)


@app.post("/import")

async def import_conversation(data: dict):

    """Import a previously exported conversation."""

    global conversation_manager

    

    if "messages" not in data:

        raise HTTPException(status_code=400, detail="Invalid import data")

    

    conversation_manager.messages = data["messages"]

    return JSONResponse({"status": "success", "message_count": len(data["messages"])})


These endpoints enable users to download their conversation history and restore it later, useful for long-running discussions or collaborative scenarios.


Multi-turn conversation improvements can include better context management strategies. Instead of simple truncation, implement summarization of older messages to preserve key information while staying within token limits:


async def summarize_old_messages(self, messages: List[dict], 

                                tokenizer) -> str:

    """Summarize old messages to compress context."""

    # Format messages for summarization

    text_to_summarize = "\n".join([

        f"{msg['role']}: {msg['content']}" 

        for msg in messages

    ])

    

    summary_prompt = f"""Summarize the following conversation, 

    preserving key points and context:

    

    {text_to_summarize}

    

    Summary:"""

    

    # Generate summary using the model

    summary = llm_instance.generate_response(

        prompt=summary_prompt,

        max_new_tokens=200,

        temperature=0.3,

        stream=False

    )

    

    return summary


This summarization approach maintains conversation continuity even as the chat grows very long, though it does require additional inference time.


FULL RUNNING EXAMPLE VERSION 1: WITHOUT MODEL LOADING


# main.py - Complete Local LLM Chat System - FINAL PRODUCTION VERSION


import torch

import platform

import logging

from typing import Optional, List, Dict, Generator, Union

from datetime import datetime

import asyncio

import json

import sys


from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig

from fastapi import FastAPI, HTTPException

from fastapi.responses import StreamingResponse, JSONResponse, HTMLResponse

from fastapi.middleware.cors import CORSMiddleware

from pydantic import BaseModel, Field

import uvicorn


# Configure logging

logging.basicConfig(

    level=logging.INFO,

    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',

    handlers=[logging.StreamHandler(sys.stdout)]

)

logger = logging.getLogger(__name__)



class HardwareDetector:

    """Comprehensive hardware detection for optimal LLM inference."""

    

    def __init__(self):

        self.device = None

        self.device_name = None

        self.compute_dtype = None

        self.detected_backend = None

        self.memory_available = 0

        

    def detect_optimal_device(self) -> torch.device:

        """Detect and select the most appropriate hardware backend."""

        logger.info("Starting hardware detection...")

        

        # NVIDIA CUDA detection

        if torch.cuda.is_available():

            try:

                self.device = torch.device("cuda:0")

                self.device_name = torch.cuda.get_device_name(0)

                self.detected_backend = "NVIDIA CUDA"

                self.compute_dtype = torch.float16

                self.memory_available = torch.cuda.get_device_properties(0).total_memory / (1024**3)

                logger.info(f"Detected NVIDIA GPU: {self.device_name}")

                logger.info(f"Available VRAM: {self.memory_available:.2f} GB")

                return self.device

            except Exception as e:

                logger.warning(f"CUDA detection failed: {e}")

        

        # AMD ROCm detection

        if hasattr(torch.version, 'hip') and torch.version.hip is not None:

            try:

                self.device = torch.device("cuda:0")

                self.device_name = "AMD GPU (ROCm)"

                self.detected_backend = "AMD ROCm"

                self.compute_dtype = torch.float16

                logger.info("Detected AMD GPU with ROCm support")

                return self.device

            except Exception as e:

                logger.warning(f"ROCm detection failed: {e}")

        

        # Apple MPS detection

        if hasattr(torch.backends, 'mps'):

            try:

                if torch.backends.mps.is_available() and torch.backends.mps.is_built():

                    self.device = torch.device("mps")

                    self.device_name = "Apple Silicon GPU"

                    self.detected_backend = "Apple MPS"

                    self.compute_dtype = torch.float32

                    logger.info("Detected Apple Silicon with MPS support")

                    return self.device

            except Exception as e:

                logger.warning(f"MPS detection failed: {e}")

        

        # Intel XPU detection

        try:

            import intel_extension_for_pytorch as ipex

            if ipex.xpu.is_available():

                self.device = torch.device("xpu:0")

                self.device_name = "Intel GPU"

                self.detected_backend = "Intel XPU"

                self.compute_dtype = torch.float16

                logger.info("Detected Intel GPU with XPU support")

                return self.device

        except (ImportError, Exception) as e:

            if not isinstance(e, ImportError):

                logger.warning(f"Intel XPU detection failed: {e}")

        

        # CPU fallback

        self.device = torch.device("cpu")

        self.device_name = platform.processor() or "CPU"

        self.detected_backend = "CPU"

        self.compute_dtype = torch.float32

        logger.info(f"Using CPU: {self.device_name}")

        logger.warning("No GPU acceleration available. Performance will be limited.")

        

        return self.device

    

    def supports_quantization(self) -> bool:

        """Check if hardware supports model quantization."""

        return self.detected_backend in ["NVIDIA CUDA", "AMD ROCm"]



class ConversationManager:

    """Manages conversation history with intelligent context window handling."""

    

    def __init__(self, system_prompt: Optional[str] = None, max_context_tokens: int = 2048):

        self.messages: List[Dict[str, str]] = []

        self.system_prompt = system_prompt

        self.max_context_tokens = max_context_tokens

        self.conversation_id = datetime.now().strftime("%Y%m%d_%H%M%S")

        

        if system_prompt:

            self.messages.append({

                "role": "system",

                "content": system_prompt,

                "timestamp": datetime.now().isoformat()

            })

        

        logger.info(f"Initialized conversation {self.conversation_id}")

    

    def add_user_message(self, content: str) -> None:

        """Add a user message with timestamp."""

        self.messages.append({

            "role": "user",

            "content": content,

            "timestamp": datetime.now().isoformat()

        })

        logger.debug(f"Added user message: {content[:50]}...")

    

    def add_assistant_message(self, content: str) -> None:

        """Add an assistant message with timestamp."""

        self.messages.append({

            "role": "assistant",

            "content": content,

            "timestamp": datetime.now().isoformat()

        })

        logger.debug(f"Added assistant message: {content[:50]}...")

    

    def format_conversation(self, tokenizer) -> str:

        """Format conversation for model input with intelligent truncation."""

        # Try model's native chat template

        if hasattr(tokenizer, 'apply_chat_template') and tokenizer.chat_template is not None:

            try:

                messages_for_template = [

                    {"role": m["role"], "content": m["content"]}

                    for m in self.messages

                ]

                

                prompt = tokenizer.apply_chat_template(

                    messages_for_template,

                    tokenize=False,

                    add_generation_prompt=True

                )

                

                tokens = tokenizer.encode(prompt, add_special_tokens=False)

                if len(tokens) <= self.max_context_tokens:

                    return prompt

                

                logger.info(f"Context too long ({len(tokens)} tokens), truncating...")

                return self._truncate_conversation(tokenizer)

                

            except Exception as e:

                logger.warning(f"Chat template failed: {e}, using fallback")

        

        return self._manual_format(tokenizer)

    

    def _manual_format(self, tokenizer) -> str:

        """Manual conversation formatting with role prefixes."""

        prompt_parts = []

        

        for message in self.messages:

            role = message["role"]

            content = message["content"]

            

            if role == "system":

                prompt_parts.append(f"System: {content}")

            elif role == "user":

                prompt_parts.append(f"User: {content}")

            elif role == "assistant":

                prompt_parts.append(f"Assistant: {content}")

        

        prompt_parts.append("Assistant:")

        prompt = "\n\n".join(prompt_parts)

        

        tokens = tokenizer.encode(prompt, add_special_tokens=False)

        if len(tokens) > self.max_context_tokens:

            return self._truncate_conversation(tokenizer)

        

        return prompt

    

    def _truncate_conversation(self, tokenizer) -> str:

        """Intelligently truncate conversation to fit context window."""

        system_messages = [m for m in self.messages if m["role"] == "system"]

        other_messages = [m for m in self.messages if m["role"] != "system"]

        

        if len(other_messages) == 0:

            return self._manual_format(tokenizer)

        

        # Binary search for optimal message count

        left, right = 1, len(other_messages)

        best_count = 1

        

        while left <= right:

            mid = (left + right) // 2

            test_messages = system_messages + other_messages[-mid:]

            

            if hasattr(tokenizer, 'apply_chat_template') and tokenizer.chat_template is not None:

                try:

                    messages_for_template = [

                        {"role": m["role"], "content": m["content"]}

                        for m in test_messages

                    ]

                    test_prompt = tokenizer.apply_chat_template(

                        messages_for_template,

                        tokenize=False,

                        add_generation_prompt=True

                    )

                except Exception:

                    test_prompt = self._format_messages_simple(test_messages)

            else:

                test_prompt = self._format_messages_simple(test_messages)

            

            test_tokens = tokenizer.encode(test_prompt, add_special_tokens=False)

            

            if len(test_tokens) <= self.max_context_tokens:

                best_count = mid

                left = mid + 1

            else:

                right = mid - 1

        

        self.messages = system_messages + other_messages[-best_count:]

        logger.info(f"Truncated to {len(self.messages)} messages")

        

        if hasattr(tokenizer, 'apply_chat_template') and tokenizer.chat_template is not None:

            try:

                messages_for_template = [

                    {"role": m["role"], "content": m["content"]}

                    for m in self.messages

                ]

                return tokenizer.apply_chat_template(

                    messages_for_template,

                    tokenize=False,

                    add_generation_prompt=True

                )

            except Exception:

                pass

        

        return self._format_messages_simple(self.messages)

    

    def _format_messages_simple(self, messages: List[Dict]) -> str:

        """Simple message formatting helper."""

        parts = []

        for msg in messages:

            role = msg["role"].capitalize()

            parts.append(f"{role}: {msg['content']}")

        parts.append("Assistant:")

        return "\n\n".join(parts)

    

    def clear_history(self) -> None:

        """Clear conversation while preserving system prompt."""

        if self.system_prompt:

            self.messages = [{

                "role": "system",

                "content": self.system_prompt,

                "timestamp": datetime.now().isoformat()

            }]

        else:

            self.messages = []

        logger.info("Conversation history cleared")

    

    def get_history(self) -> List[Dict[str, str]]:

        """Return copy of conversation history."""

        return self.messages.copy()

    

    def export_conversation(self) -> Dict:

        """Export conversation with metadata."""

        return {

            "conversation_id": self.conversation_id,

            "created": self.messages[0]["timestamp"] if self.messages else None,

            "message_count": len(self.messages),

            "messages": self.messages

        }



class LocalLLM:

    """Manages local language model with automatic hardware optimization."""

    

    def __init__(self, model_name: str = "microsoft/phi-2",

                 max_memory_gb: Optional[float] = None,

                 use_quantization: bool = True):

        self.model_name = model_name

        self.max_memory_gb = max_memory_gb

        self.use_quantization = use_quantization

        

        self.hardware = HardwareDetector()

        self.device = self.hardware.detect_optimal_device()

        

        self.model = None

        self.tokenizer = None

        

        logger.info(f"Initialized LocalLLM with model: {model_name}")

    

    def load_model(self) -> None:

        """Load model and tokenizer with optimal configuration."""

        logger.info(f"Loading model: {self.model_name}")

        start_time = datetime.now()

        

        # Load tokenizer

        try:

            self.tokenizer = AutoTokenizer.from_pretrained(

                self.model_name,

                trust_remote_code=True

            )

            

            if self.tokenizer.pad_token is None:

                self.tokenizer.pad_token = self.tokenizer.eos_token

            

            if not hasattr(self.tokenizer, 'padding_side') or self.tokenizer.padding_side is None:

                self.tokenizer.padding_side = "left"

            

            logger.info("Tokenizer loaded successfully")

        except Exception as e:

            logger.error(f"Failed to load tokenizer: {e}")

            raise

        

        # Prepare model loading configuration

        model_kwargs = {

            "trust_remote_code": True,

            "torch_dtype": self.hardware.compute_dtype,

            "low_cpu_mem_usage": True

        }

        

        # Add quantization if supported

        if self.use_quantization and self.hardware.supports_quantization():

            try:

                logger.info("Enabling 4-bit quantization")

                quantization_config = BitsAndBytesConfig(

                    load_in_4bit=True,

                    bnb_4bit_compute_dtype=self.hardware.compute_dtype,

                    bnb_4bit_use_double_quant=True,

                    bnb_4bit_quant_type="nf4"

                )

                model_kwargs["quantization_config"] = quantization_config

            except Exception as e:

                logger.warning(f"Quantization setup failed: {e}, loading without quantization")

        

        # Configure device mapping

        if self.hardware.detected_backend in ["NVIDIA CUDA", "AMD ROCm"]:

            if self.max_memory_gb:

                max_memory = {0: f"{self.max_memory_gb}GiB"}

                model_kwargs["device_map"] = "auto"

                model_kwargs["max_memory"] = max_memory

            else:

                model_kwargs["device_map"] = "auto"

        

        # Load model

        try:

            self.model = AutoModelForCausalLM.from_pretrained(

                self.model_name,

                **model_kwargs

            )

            

            if "device_map" not in model_kwargs:

                self.model = self.model.to(self.device)

            

            self.model.eval()

            

            load_time = (datetime.now() - start_time).total_seconds()

            logger.info(f"Model loaded successfully in {load_time:.2f} seconds")

            

        except Exception as e:

            logger.error(f"Failed to load model: {e}")

            raise

    

    def generate_response(self, prompt: str, 

                         max_new_tokens: int = 512,

                         temperature: float = 0.7,

                         top_p: float = 0.9,

                         top_k: int = 50,

                         repetition_penalty: float = 1.1,

                         stream: bool = False) -> Union[Generator[str, None, None], str]:

        """Generate response with support for streaming output."""

        if self.model is None or self.tokenizer is None:

            raise RuntimeError("Model not loaded. Call load_model() first.")

        

        # Tokenize input

        try:

            max_length = getattr(self.tokenizer, 'model_max_length', 2048)

            if max_length is None or max_length > 100000:

                max_length = 2048

            

            inputs = self.tokenizer(

                prompt, 

                return_tensors="pt", 

                padding=True, 

                truncation=True, 

                max_length=max_length

            )

            input_ids = inputs["input_ids"].to(self.device)

            attention_mask = inputs["attention_mask"].to(self.device)

            input_length = input_ids.shape[1]

        except Exception as e:

            logger.error(f"Tokenization failed: {e}")

            raise

        

        logger.debug(f"Generating response for prompt of {input_length} tokens")

        

        if stream:

            return self._generate_streaming(

                input_ids, attention_mask, input_length,

                max_new_tokens, temperature, top_p, top_k, repetition_penalty

            )

        else:

            return self._generate_complete(

                input_ids, attention_mask, input_length,

                max_new_tokens, temperature, top_p, top_k, repetition_penalty

            )

    

    def _generate_streaming(self, input_ids, attention_mask, input_length,

                           max_new_tokens, temperature, top_p, top_k, repetition_penalty):

        """Internal method for streaming generation."""

        past_key_values = None

        generated_tokens = []

        

        with torch.no_grad():

            for step in range(max_new_tokens):

                try:

                    if past_key_values is None:

                        outputs = self.model(

                            input_ids=input_ids,

                            attention_mask=attention_mask,

                            use_cache=True

                        )

                    else:

                        outputs = self.model(

                            input_ids=input_ids[:, -1:],

                            attention_mask=attention_mask,

                            past_key_values=past_key_values,

                            use_cache=True

                        )

                    

                    past_key_values = outputs.past_key_values

                    next_token_logits = outputs.logits[:, -1, :].clone()

                    

                    # Temperature scaling

                    if temperature > 0 and temperature != 1.0:

                        next_token_logits = next_token_logits / temperature

                    

                    # Repetition penalty

                    if repetition_penalty != 1.0:

                        for token_id in set(input_ids[0].tolist()):

                            if next_token_logits[0, token_id] < 0:

                                next_token_logits[0, token_id] = next_token_logits[0, token_id] * repetition_penalty

                            else:

                                next_token_logits[0, token_id] = next_token_logits[0, token_id] / repetition_penalty

                    

                    # Top-k filtering

                    if top_k > 0:

                        vocab_size = next_token_logits.size(-1)

                        top_k_actual = min(top_k, vocab_size)

                        indices_to_remove = next_token_logits < torch.topk(next_token_logits, top_k_actual)[0][..., -1, None]

                        next_token_logits = next_token_logits.masked_fill(indices_to_remove, float('-inf'))

                    

                    # Top-p filtering

                    if top_p < 1.0:

                        sorted_logits, sorted_indices = torch.sort(next_token_logits, descending=True)

                        cumulative_probs = torch.cumsum(torch.softmax(sorted_logits, dim=-1), dim=-1)

                        

                        sorted_indices_to_remove = cumulative_probs > top_p

                        sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()

                        sorted_indices_to_remove[..., 0] = False

                        

                        indices_to_remove = torch.zeros_like(next_token_logits, dtype=torch.bool)

                        indices_to_remove.scatter_(1, sorted_indices, sorted_indices_to_remove)

                        next_token_logits = next_token_logits.masked_fill(indices_to_remove, float('-inf'))

                    

                    # Sample next token

                    probs = torch.softmax(next_token_logits, dim=-1)

                    next_token = torch.multinomial(probs, num_samples=1)

                    

                    # Check for EOS

                    if next_token.item() == self.tokenizer.eos_token_id:

                        break

                    

                    generated_tokens.append(next_token.item())

                    

                    # Decode and yield token

                    token_text = self.tokenizer.decode(next_token[0], skip_special_tokens=True)

                    

                    if token_text:

                        yield token_text

                    

                    # Update sequence

                    input_ids = torch.cat([input_ids, next_token], dim=-1)

                    attention_mask = torch.cat([

                        attention_mask,

                        torch.ones((1, 1), device=self.device, dtype=attention_mask.dtype)

                    ], dim=-1)

                    

                except Exception as e:

                    logger.error(f"Error during streaming generation at step {step}: {e}")

                    break

    

    def _generate_complete(self, input_ids, attention_mask, input_length,

                          max_new_tokens, temperature, top_p, top_k, repetition_penalty):

        """Internal method for complete generation."""

        with torch.no_grad():

            try:

                actual_temperature = max(temperature, 0.01) if temperature > 0 else 1.0

                

                outputs = self.model.generate(

                    input_ids=input_ids,

                    attention_mask=attention_mask,

                    max_new_tokens=max_new_tokens,

                    temperature=actual_temperature,

                    top_p=top_p,

                    top_k=top_k,

                    repetition_penalty=repetition_penalty,

                    do_sample=temperature > 0,

                    pad_token_id=self.tokenizer.pad_token_id,

                    eos_token_id=self.tokenizer.eos_token_id,

                    use_cache=True

                )

                

                generated_ids = outputs[0][input_length:]

                response = self.tokenizer.decode(generated_ids, skip_special_tokens=True)

                return response

            except Exception as e:

                logger.error(f"Error during complete generation: {e}")

                raise



# Pydantic models for API

class ChatMessage(BaseModel):

    message: str = Field(..., min_length=1, max_length=10000)

    stream: bool = True

    temperature: float = Field(0.7, ge=0.0, le=2.0)

    max_tokens: int = Field(512, ge=1, le=2048)

    top_p: float = Field(0.9, ge=0.0, le=1.0)

    top_k: int = Field(50, ge=0, le=100)

    repetition_penalty: float = Field(1.1, ge=1.0, le=2.0)



class SystemConfig(BaseModel):

    system_prompt: Optional[str] = None

    model_name: Optional[str] = None

    max_context_tokens: Optional[int] = Field(None, ge=512, le=8192)



# FastAPI application

app = FastAPI(

    title="Local LLM Chat API",

    description="Production-ready local language model chat system",

    version="1.0.0"

)


# CORS middleware

app.add_middleware(

    CORSMiddleware,

    allow_origins=["*"],

    allow_credentials=True,

    allow_methods=["*"],

    allow_headers=["*"],

)


# Global state

llm_instance: Optional[LocalLLM] = None

conversation_manager: Optional[ConversationManager] = None



@app.on_event("startup")

async def startup_event():

    """Initialize system on startup."""

    global llm_instance, conversation_manager

    

    logger.info("=" * 60)

    logger.info("Starting Local LLM Chat System")

    logger.info("=" * 60)

    

    try:

        llm_instance = LocalLLM(

            model_name="microsoft/phi-2",

            use_quantization=True

        )

        llm_instance.load_model()

        

        conversation_manager = ConversationManager(

            system_prompt="You are a helpful, knowledgeable AI assistant.",

            max_context_tokens=2048

        )

        

        logger.info("System initialization complete")

        logger.info("=" * 60)

        

    except Exception as e:

        logger.error(f"Startup failed: {e}", exc_info=True)

        raise



@app.get("/", response_class=HTMLResponse)

async def serve_frontend():

    """Serve the frontend HTML."""

    return """<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Local LLM Chat</title>

    <style>

        * { margin: 0; padding: 0; box-sizing: border-box; }

        body {

            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif;

            background-color: #343541; color: #ececf1; height: 100vh; overflow: hidden;

        }

        .app-container { display: flex; height: 100vh; width: 100%; }

        .sidebar {

            width: 260px; background-color: #202123; display: flex; flex-direction: column;

            padding: 8px; border-right: 1px solid #4d4d4f;

        }

        .new-chat-button {

            display: flex; align-items: center; gap: 12px; padding: 12px; border: 1px solid #4d4d4f;

            border-radius: 6px; background: transparent; color: #ececf1; cursor: pointer;

            font-size: 14px; transition: background-color 0.2s; margin-bottom: 8px;

        }

        .new-chat-button:hover { background-color: #2a2b32; }

        .sidebar-content { flex: 1; overflow-y: auto; }

        .sidebar-footer {

            padding: 12px; border-top: 1px solid #4d4d4f; font-size: 12px; color: #8e8ea0;

        }

        .status-info { display: flex; align-items: center; gap: 8px; margin-bottom: 4px; }

        .status-dot { width: 8px; height: 8px; border-radius: 50%; background: #10a37f; }

        .main-content { flex: 1; display: flex; flex-direction: column; }

        .chat-header {

            padding: 12px 16px; border-bottom: 1px solid #4d4d4f; display: flex;

            justify-content: space-between; align-items: center; background-color: #343541;

        }

        .model-selector {

            background: #40414f; border: 1px solid #4d4d4f; border-radius: 6px;

            padding: 8px 12px; color: #ececf1; font-size: 14px;

        }

        .messages-container { flex: 1; overflow-y: auto; display: flex; flex-direction: column; }

        .messages-wrapper { max-width: 768px; width: 100%; margin: 0 auto; padding: 24px; }

        .message-group {

            display: flex; gap: 16px; padding: 24px 0; border-bottom: 1px solid #4d4d4f;

        }

        .message-group.user { background-color: #343541; }

        .message-group.assistant { background-color: #444654; }

        .avatar {

            width: 30px; height: 30px; border-radius: 2px; display: flex;

            align-items: center; justify-content: center; font-weight: 600; font-size: 12px;

            flex-shrink: 0;

        }

        .avatar.user { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }

        .avatar.assistant { background: #10a37f; color: white; }

        .message-content {

            flex: 1; line-height: 1.7; font-size: 16px; word-wrap: break-word; white-space: pre-wrap;

        }

        .typing-indicator { display: flex; gap: 4px; padding: 8px 0; }

        .typing-dot {

            width: 8px; height: 8px; border-radius: 50%; background: #8e8ea0;

            animation: typing 1.4s infinite;

        }

        .typing-dot:nth-child(2) { animation-delay: 0.2s; }

        .typing-dot:nth-child(3) { animation-delay: 0.4s; }

        @keyframes typing {

            0%, 60%, 100% { transform: translateY(0); opacity: 0.7; }

            30% { transform: translateY(-10px); opacity: 1; }

        }

        .input-area { padding: 24px; background-color: #343541; }

        .input-wrapper { max-width: 768px; margin: 0 auto; }

        .input-container {

            display: flex; align-items: flex-end; background: #40414f; border: 1px solid #4d4d4f;

            border-radius: 12px; padding: 12px; box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);

        }

        .message-input {

            flex: 1; background: transparent; border: none; color: #ececf1; font-size: 16px;

            outline: none; resize: none; max-height: 200px; overflow-y: auto; font-family: inherit;

            line-height: 24px; padding: 0 8px;

        }

        .message-input::placeholder { color: #8e8ea0; }

        .send-button {

            width: 32px; height: 32px; border-radius: 6px; border: none; background: #19c37d;

            color: white; cursor: pointer; display: flex; align-items: center; justify-content: center;

            transition: background-color 0.2s; flex-shrink: 0; margin-left: 8px;

        }

        .send-button:hover:not(:disabled) { background: #1a7f5a; }

        .send-button:disabled { background: #4d4d4f; cursor: not-allowed; }

        .error-message {

            background: #f44336; color: white; padding: 16px; border-radius: 8px; margin: 16px 0;

            display: flex; align-items: center; gap: 12px;

        }

        .welcome-screen {

            display: flex; flex-direction: column; align-items: center; justify-content: center;

            height: 100%; padding: 24px; text-align: center;

        }

        .welcome-title { font-size: 32px; font-weight: 600; margin-bottom: 16px; }

        .welcome-subtitle { font-size: 16px; color: #8e8ea0; margin-bottom: 32px; }

        .example-prompts {

            display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));

            gap: 12px; max-width: 800px; width: 100%;

        }

        .example-prompt {

            background: #40414f; border: 1px solid #4d4d4f; border-radius: 8px; padding: 16px;

            cursor: pointer; transition: background-color 0.2s; text-align: left;

        }

        .example-prompt:hover { background: #4d4d4f; }

        .example-prompt-title { font-weight: 600; margin-bottom: 4px; }

        .example-prompt-text { font-size: 14px; color: #8e8ea0; }

        .scrollbar-custom::-webkit-scrollbar { width: 8px; }

        .scrollbar-custom::-webkit-scrollbar-track { background: transparent; }

        .scrollbar-custom::-webkit-scrollbar-thumb { background: #4d4d4f; border-radius: 4px; }

        .scrollbar-custom::-webkit-scrollbar-thumb:hover { background: #5e5e60; }

        @media (max-width: 768px) {

            .sidebar { display: none; }

            .messages-wrapper { padding: 16px; }

            .input-area { padding: 16px; }

        }

    </style>

</head>

<body>

    <div class="app-container">

        <div class="sidebar">

            <button class="new-chat-button" onclick="newChat()">

                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">

                    <line x1="12" y1="5" x2="12" y2="19"></line>

                    <line x1="5" y1="12" x2="19" y2="12"></line>

                </svg>

                New chat

            </button>

            <div class="sidebar-content scrollbar-custom"></div>

            <div class="sidebar-footer">

                <div class="status-info">

                    <div class="status-dot" id="statusDot"></div>

                    <span id="statusText">Connecting...</span>

                </div>

                <div id="deviceInfo" style="margin-top: 4px;"></div>

            </div>

        </div>

        <div class="main-content">

            <div class="chat-header">

                <div class="model-selector" id="modelName">Local LLM</div>

            </div>

            <div class="messages-container scrollbar-custom" id="messagesContainer">

                <div class="messages-wrapper" id="messages">

                    <div class="welcome-screen" id="welcomeScreen">

                        <div class="welcome-title">Local LLM Chat</div>

                        <div class="welcome-subtitle">Chat with a powerful language model running entirely on your device</div>

                        <div class="example-prompts">

                            <div class="example-prompt" onclick="useExample('Explain quantum computing in simple terms')">

                                <div class="example-prompt-title">Explain a concept</div>

                                <div class="example-prompt-text">Quantum computing in simple terms</div>

                            </div>

                            <div class="example-prompt" onclick="useExample('Write a Python function to calculate fibonacci numbers')">

                                <div class="example-prompt-title">Code assistance</div>

                                <div class="example-prompt-text">Python fibonacci function</div>

                            </div>

                            <div class="example-prompt" onclick="useExample('What are the benefits of exercise?')">

                                <div class="example-prompt-title">Get information</div>

                                <div class="example-prompt-text">Benefits of exercise</div>

                            </div>

                        </div>

                    </div>

                </div>

            </div>

            <div class="input-area">

                <div class="input-wrapper">

                    <div class="input-container">

                        <textarea class="message-input" id="messageInput" placeholder="Send a message..." rows="1" onkeydown="handleKeyDown(event)" oninput="autoResize(this)"></textarea>

                        <button class="send-button" id="sendButton" onclick="sendMessage()">

                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none">

                                <path d="M7 11L12 6L17 11M12 18V7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                            </svg>

                        </button>

                    </div>

                </div>

            </div>

        </div>

    </div>

    <script>

        const API_BASE_URL = window.location.origin;

        let isGenerating = false;

        let currentAssistantMessage = null;

        let messageCount = 0;

        

        async function initialize() {

            try {

                const response = await fetch(API_BASE_URL + '/status');

                const data = await response.json();

                if (data.status === 'ready') {

                    updateStatus('Ready', true);

                    document.getElementById('modelName').textContent = data.model_name || 'Local LLM';

                    document.getElementById('deviceInfo').textContent = data.device || '';

                } else {

                    updateStatus('Initializing...', false);

                    setTimeout(initialize, 2000);

                }

            } catch (error) {

                updateStatus('Connection Error', false);

                console.error('Connection error:', error);

                setTimeout(initialize, 5000);

            }

        }

        

        function updateStatus(text, isReady) {

            document.getElementById('statusText').textContent = text;

            document.getElementById('statusDot').style.background = isReady ? '#10a37f' : '#ef4444';

        }

        

        function hideWelcomeScreen() {

            const welcomeScreen = document.getElementById('welcomeScreen');

            if (welcomeScreen) welcomeScreen.style.display = 'none';

        }

        

        function addMessage(content, role) {

            hideWelcomeScreen();

            const messagesDiv = document.getElementById('messages');

            const messageGroup = document.createElement('div');

            messageGroup.className = 'message-group ' + role;

            const avatar = document.createElement('div');

            avatar.className = 'avatar ' + role;

            avatar.textContent = role === 'user' ? 'U' : 'AI';

            const contentDiv = document.createElement('div');

            contentDiv.className = 'message-content';

            contentDiv.textContent = content;

            messageGroup.appendChild(avatar);

            messageGroup.appendChild(contentDiv);

            messagesDiv.appendChild(messageGroup);

            scrollToBottom();

            messageCount++;

            return contentDiv;

        }

        

        function showTypingIndicator() {

            hideWelcomeScreen();

            const messagesDiv = document.getElementById('messages');

            const messageGroup = document.createElement('div');

            messageGroup.className = 'message-group assistant';

            messageGroup.id = 'typing-indicator';

            const avatar = document.createElement('div');

            avatar.className = 'avatar assistant';

            avatar.textContent = 'AI';

            const typingDiv = document.createElement('div');

            typingDiv.className = 'message-content';

            typingDiv.innerHTML = '<div class="typing-indicator"><div class="typing-dot"></div><div class="typing-dot"></div><div class="typing-dot"></div></div>';

            messageGroup.appendChild(avatar);

            messageGroup.appendChild(typingDiv);

            messagesDiv.appendChild(messageGroup);

            scrollToBottom();

        }

        

        function removeTypingIndicator() {

            const indicator = document.getElementById('typing-indicator');

            if (indicator) indicator.remove();

        }

        

        function showError(message) {

            const messagesDiv = document.getElementById('messages');

            const errorDiv = document.createElement('div');

            errorDiv.className = 'error-message';

            errorDiv.innerHTML = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line></svg><span>' + message + '</span>';

            messagesDiv.appendChild(errorDiv);

            scrollToBottom();

        }

        

        function scrollToBottom() {

            const container = document.getElementById('messagesContainer');

            container.scrollTop = container.scrollHeight;

        }

        

        async function sendMessage() {

            const input = document.getElementById('messageInput');

            const message = input.value.trim();

            if (!message || isGenerating) return;

            input.value = '';

            input.style.height = 'auto';

            isGenerating = true;

            updateControls();

            addMessage(message, 'user');

            showTypingIndicator();

            try {

                const response = await fetch(API_BASE_URL + '/chat', {

                    method: 'POST',

                    headers: { 'Content-Type': 'application/json' },

                    body: JSON.stringify({ message: message, stream: true, temperature: 0.7, max_tokens: 512 })

                });

                if (!response.ok) throw new Error('HTTP error! status: ' + response.status);

                removeTypingIndicator();

                currentAssistantMessage = addMessage('', 'assistant');

                const reader = response.body.getReader();

                const decoder = new TextDecoder();

                let buffer = '';

                while (true) {

                    const result = await reader.read();

                    if (result.done) break;

                    buffer += decoder.decode(result.value, { stream: true });

                    const lines = buffer.split('\\n');

                    buffer = lines.pop() || '';

                    for (let i = 0; i < lines.length; i++) {

                        const line = lines[i];

                        if (line.startsWith('data: ')) {

                            try {

                                const data = JSON.parse(line.slice(6));

                                if (data.error) { showError(data.error); break; }

                                if (data.token) { currentAssistantMessage.textContent += data.token; scrollToBottom(); }

                                if (data.done) break;

                            } catch (e) { console.error('Parse error:', e); }

                        }

                    }

                }

            } catch (error) {

                removeTypingIndicator();

                showError('Error: ' + error.message);

                console.error('Error:', error);

            } finally {

                isGenerating = false;

                currentAssistantMessage = null;

                updateControls();

            }

        }

        

        function updateControls() {

            document.getElementById('sendButton').disabled = isGenerating;

            document.getElementById('messageInput').disabled = isGenerating;

            if (!isGenerating) document.getElementById('messageInput').focus();

        }

        

        function handleKeyDown(event) {

            if (event.key === 'Enter' && !event.shiftKey) {

                event.preventDefault();

                sendMessage();

            }

        }

        

        function autoResize(textarea) {

            textarea.style.height = 'auto';

            textarea.style.height = Math.min(textarea.scrollHeight, 200) + 'px';

        }

        

        async function newChat() {

            if (messageCount === 0) return;

            if (!confirm('Start a new conversation? Current chat will be cleared.')) return;

            try {

                const response = await fetch(API_BASE_URL + '/clear', { method: 'POST' });

                if (response.ok) {

                    document.getElementById('messages').innerHTML = '<div class="welcome-screen" id="welcomeScreen"><div class="welcome-title">Local LLM Chat</div><div class="welcome-subtitle">Chat with a powerful language model running entirely on your device</div><div class="example-prompts"><div class="example-prompt" onclick="useExample(\\'Explain quantum computing in simple terms\\')"><div class="example-prompt-title">Explain a concept</div><div class="example-prompt-text">Quantum computing in simple terms</div></div><div class="example-prompt" onclick="useExample(\\'Write a Python function to calculate fibonacci numbers\\')"><div class="example-prompt-title">Code assistance</div><div class="example-prompt-text">Python fibonacci function</div></div><div class="example-prompt" onclick="useExample(\\'What are the benefits of exercise?\\')"><div class="example-prompt-title">Get information</div><div class="example-prompt-text">Benefits of exercise</div></div></div></div>';

                    messageCount = 0;

                }

            } catch (error) {

                showError('Error clearing conversation: ' + error.message);

            }

        }

        

        function useExample(text) {

            const input = document.getElementById('messageInput');

            input.value = text;

            input.focus();

            autoResize(input);

        }

        

        window.addEventListener('load', function() {

            initialize();

            document.getElementById('messageInput').focus();

        });

    </script>

</body>

</html>"""



@app.post("/chat")

async def chat(message: ChatMessage):

    """Process chat message and return response."""

    if llm_instance is None or conversation_manager is None:

        raise HTTPException(status_code=503, detail="System not initialized")

    

    try:

        conversation_manager.add_user_message(message.message)

        prompt = conversation_manager.format_conversation(llm_instance.tokenizer)

        

        if message.stream:

            async def generate_stream():

                full_response = ""

                try:

                    for token in llm_instance.generate_response(

                        prompt=prompt,

                        max_new_tokens=message.max_tokens,

                        temperature=message.temperature,

                        top_p=message.top_p,

                        top_k=message.top_k,

                        repetition_penalty=message.repetition_penalty,

                        stream=True

                    ):

                        full_response += token

                        yield f"data: {json.dumps({'token': token})}\n\n"

                        await asyncio.sleep(0.001)

                    

                    conversation_manager.add_assistant_message(full_response)

                    yield f"data: {json.dumps({'done': True})}\n\n"

                    

                except Exception as e:

                    logger.error(f"Generation error: {e}", exc_info=True)

                    yield f"data: {json.dumps({'error': str(e)})}\n\n"

            

            return StreamingResponse(generate_stream(), media_type="text/event-stream")

        else:

            response = llm_instance.generate_response(

                prompt=prompt,

                max_new_tokens=message.max_tokens,

                temperature=message.temperature,

                top_p=message.top_p,

                top_k=message.top_k,

                repetition_penalty=message.repetition_penalty,

                stream=False

            )

            

            conversation_manager.add_assistant_message(response)

            return JSONResponse({"response": response, "done": True})

            

    except Exception as e:

        logger.error(f"Chat error: {e}", exc_info=True)

        raise HTTPException(status_code=500, detail=str(e))



@app.post("/clear")

async def clear_conversation():

    """Clear conversation history."""

    if conversation_manager is None:

        raise HTTPException(status_code=503, detail="System not initialized")

    conversation_manager.clear_history()

    return JSONResponse({"status": "success", "message": "Conversation cleared"})



@app.get("/history")

async def get_history():

    """Get conversation history."""

    if conversation_manager is None:

        raise HTTPException(status_code=503, detail="System not initialized")

    return JSONResponse({"history": conversation_manager.get_history()})



@app.get("/status")

async def get_status():

    """Get system status."""

    if llm_instance is None:

        return JSONResponse({"status": "not_ready", "model_loaded": False})

    

    return JSONResponse({

        "status": "ready",

        "model_loaded": True,

        "model_name": llm_instance.model_name,

        "device": llm_instance.hardware.detected_backend,

        "device_name": llm_instance.hardware.device_name,

        "compute_dtype": str(llm_instance.hardware.compute_dtype),

        "memory_available": llm_instance.hardware.memory_available

    })



@app.post("/configure")

async def configure_system(config: SystemConfig):

    """Reconfigure system settings."""

    global llm_instance, conversation_manager

    

    try:

        if config.model_name and llm_instance and config.model_name != llm_instance.model_name:

            logger.info(f"Reloading model: {config.model_name}")

            llm_instance = LocalLLM(model_name=config.model_name, use_quantization=True)

            llm_instance.load_model()

        

        conversation_manager = ConversationManager(

            system_prompt=config.system_prompt,

            max_context_tokens=config.max_context_tokens or 2048

        )

        

        return JSONResponse({"status": "success", "message": "System reconfigured"})

        

    except Exception as e:

        logger.error(f"Configuration error: {e}", exc_info=True)

        raise HTTPException(status_code=500, detail=str(e))



@app.get("/export")

async def export_conversation():

    """Export current conversation."""

    if conversation_manager is None:

        raise HTTPException(status_code=503, detail="System not initialized")

    return JSONResponse(conversation_manager.export_conversation())



if __name__ == "__main__":

    uvicorn.run(app, host="0.0.0.0", port=8000, log_level="info")

INSTALLATION:

pip install torch transformers fastapi uvicorn pydantic accelerate bitsandbytes


TO RUN:

python main.py


Then open http://localhost:8000 in your browser.


This complete implementation provides a production-ready local LLM chat system with comprehensive error handling, logging, hardware optimization, and all the features discussed throughout this tutorial. The code is well-structured, documented, and ready for deployment.


To use this system, save the code to main.py, install the required dependencies, and run it with uvicorn. The system will automatically detect your hardware, load the model with optimal settings, and provide a full-featured chat API that can be accessed through the HTML frontend we created earlier.


The implementation demonstrates clean architecture principles with clear separation of concerns between hardware detection, model management, conversation handling, and API endpoints. Each component is independently testable and can be extended or replaced without affecting others. This modularity makes the system maintainable and adaptable to future requirements.


Configuring LLM Models

Overview


The system supports multiple ways to configure which LLM model to use. You can set the model at startup, change it dynamically via API, or modify the code directly.


Method 1: Modify Startup Configuration (Recommended)

Edit the startup_event() function in main.py:


@app.on_event("startup")

async def startup_event():

    global llm_instance, conversation_manager

    

    llm_instance = LocalLLM(

        model_name="microsoft/phi-2",  # Change this line

        use_quantization=True

    )

    llm_instance.load_model()

    

    conversation_manager = ConversationManager(

        system_prompt="You are a helpful AI assistant.",

        max_context_tokens=2048

    )


Popular Model Options:


# Small models (2-3GB VRAM)

model_name="microsoft/phi-2"                    # 2.7B parameters

model_name="TinyLlama/TinyLlama-1.1B-Chat-v1.0" # 1.1B parameters

model_name="stabilityai/stablelm-2-zephyr-1_6b" # 1.6B parameters


# Medium models (6-8GB VRAM)

model_name="mistralai/Mistral-7B-Instruct-v0.2" # 7B parameters

model_name="meta-llama/Llama-2-7b-chat-hf"      # 7B parameters (requires approval)

model_name="NousResearch/Nous-Hermes-2-Mistral-7B-DPO" # 7B parameters


# Large models (12-16GB VRAM)

model_name="mistralai/Mixtral-8x7B-Instruct-v0.1" # 47B parameters (MoE)

model_name="meta-llama/Llama-2-13b-chat-hf"       # 13B parameters


# Code-specialized models

model_name="Salesforce/codegen-2B-mono"         # 2B parameters

model_name="WizardLM/WizardCoder-Python-7B-V1.0" # 7B parameters


Method 2: Dynamic Configuration via API

Use the /configure endpoint to change models without restarting:


import requests


# Change model

response = requests.post('http://localhost:8000/configure', json={

    "model_name": "mistralai/Mistral-7B-Instruct-v0.2",

    "system_prompt": "You are a helpful coding assistant.",

    "max_context_tokens": 4096

})


print(response.json())

# Output: {"status": "success", "message": "System reconfigured"}


JavaScript Example:


async function changeModel(modelName) {

    const response = await fetch('http://localhost:8000/configure', {

        method: 'POST',

        headers: { 'Content-Type': 'application/json' },

        body: JSON.stringify({

            model_name: modelName,

            system_prompt: "You are a helpful AI assistant.",

            max_context_tokens: 2048

        })

    });

    

    const result = await response.json();

    console.log(result);

}


// Usage

changeModel("microsoft/phi-2");


Method 3: Environment Variables

Create a .env file for configuration:


# .env

MODEL_NAME=mistralai/Mistral-7B-Instruct-v0.2

USE_QUANTIZATION=true

MAX_CONTEXT_TOKENS=2048

SYSTEM_PROMPT=You are a helpful AI assistant.

MAX_MEMORY_GB=8


Load environment variables in your code:


import os

from dotenv import load_dotenv


load_dotenv()


@app.on_event("startup")

async def startup_event():

    global llm_instance, conversation_manager

    

    model_name = os.getenv("MODEL_NAME", "microsoft/phi-2")

    use_quantization = os.getenv("USE_QUANTIZATION", "true").lower() == "true"

    max_memory_gb = float(os.getenv("MAX_MEMORY_GB", "0")) if os.getenv("MAX_MEMORY_GB") else None

    

    llm_instance = LocalLLM(

        model_name=model_name,

        use_quantization=use_quantization,

        max_memory_gb=max_memory_gb

    )

    llm_instance.load_model()

    

    conversation_manager = ConversationManager(

        system_prompt=os.getenv("SYSTEM_PROMPT", "You are a helpful AI assistant."),

        max_context_tokens=int(os.getenv("MAX_CONTEXT_TOKENS", "2048"))

    )


Install python-dotenv:


pip install python-dotenv


Method 4: Command Line Arguments

Add argument parsing to your script:


import argparse


def parse_args():

    parser = argparse.ArgumentParser(description='Local LLM Chat System')

    parser.add_argument('--model', type=str, default='microsoft/phi-2',

                       help='HuggingFace model name')

    parser.add_argument('--quantize', action='store_true', default=True,

                       help='Use 4-bit quantization')

    parser.add_argument('--no-quantize', action='store_false', dest='quantize',

                       help='Disable quantization')

    parser.add_argument('--max-memory', type=float, default=None,

                       help='Max GPU memory in GB')

    parser.add_argument('--context-tokens', type=int, default=2048,

                       help='Maximum context window size')

    parser.add_argument('--port', type=int, default=8000,

                       help='Server port')

    return parser.parse_args()


if __name__ == "__main__":

    args = parse_args()

    

    # Store args globally for startup event

    app.state.args = args

    

    uvicorn.run(app, host="0.0.0.0", port=args.port, log_level="info")


Update startup event:


@app.on_event("startup")

async def startup_event():

    global llm_instance, conversation_manager

    

    args = app.state.args

    

    llm_instance = LocalLLM(

        model_name=args.model,

        use_quantization=args.quantize,

        max_memory_gb=args.max_memory

    )

    llm_instance.load_model()

    

    conversation_manager = ConversationManager(

        system_prompt="You are a helpful AI assistant.",

        max_context_tokens=args.context_tokens

    )


Run with arguments:


# Use Mistral 7B with quantization

python main.py --model mistralai/Mistral-7B-Instruct-v0.2


# Use Phi-2 without quantization

python main.py --model microsoft/phi-2 --no-quantize


# Limit GPU memory to 8GB

python main.py --model mistralai/Mistral-7B-Instruct-v0.2 --max-memory 8


# Use different port

python main.py --port 8080


# Combine options

python main.py --model meta-llama/Llama-2-7b-chat-hf --max-memory 10 --context-tokens 4096


Method 5: Configuration File

Create a config.json file:


{

    "model_name": "mistralai/Mistral-7B-Instruct-v0.2",

    "use_quantization": true,

    "max_memory_gb": 8,

    "max_context_tokens": 2048,

    "system_prompt": "You are a helpful AI assistant.",

    "temperature": 0.7,

    "top_p": 0.9,

    "top_k": 50,

    "repetition_penalty": 1.1

}


Load configuration:


import json


def load_config(config_path="config.json"):

    with open(config_path, 'r') as f:

        return json.load(f)


@app.on_event("startup")

async def startup_event():

    global llm_instance, conversation_manager

    

    config = load_config()

    

    llm_instance = LocalLLM(

        model_name=config["model_name"],

        use_quantization=config["use_quantization"],

        max_memory_gb=config.get("max_memory_gb")

    )

    llm_instance.load_model()

    

    conversation_manager = ConversationManager(

        system_prompt=config["system_prompt"],

        max_context_tokens=config["max_context_tokens"]

    )


Model Selection Guide

By Use Case

General Chat:


model_name="mistralai/Mistral-7B-Instruct-v0.2"  # Best overall

model_name="microsoft/phi-2"                      # Fastest


Coding:


model_name="WizardLM/WizardCoder-Python-7B-V1.0"

model_name="Salesforce/codegen-2B-mono"

model_name="deepseek-ai/deepseek-coder-6.7b-instruct"


Creative Writing:


model_name="NousResearch/Nous-Hermes-2-Mistral-7B-DPO"

model_name="meta-llama/Llama-2-7b-chat-hf"


Multilingual:


model_name="mistralai/Mistral-7B-Instruct-v0.2"

model_name="bigscience/bloomz-7b1"


By Hardware

Low VRAM (4GB):


model_name="TinyLlama/TinyLlama-1.1B-Chat-v1.0"

use_quantization=True


Medium VRAM (8GB):

model_name="microsoft/phi-2"

model_name="mistralai/Mistral-7B-Instruct-v0.2"

use_quantization=True


High VRAM (16GB+):

model_name="mistralai/Mixtral-8x7B-Instruct-v0.1"

model_name="meta-llama/Llama-2-13b-chat-hf"

use_quantization=True  # Optional


CPU Only:

model_name="microsoft/phi-2"

use_quantization=False

max_memory_gb=None


Advanced Configuration

Custom Model Parameters


llm_instance = LocalLLM(

    model_name="mistralai/Mistral-7B-Instruct-v0.2",

    use_quantization=True,

    max_memory_gb=8  # Limit GPU memory usage

)


Custom Generation Settings


response = llm_instance.generate_response(

    prompt=prompt,

    max_new_tokens=1024,      # Longer responses

    temperature=0.8,          # More creative

    top_p=0.95,               # Nucleus sampling

    top_k=50,                 # Top-k sampling

    repetition_penalty=1.2,   # Reduce repetition

    stream=True

)


Model-Specific Optimizations

For Llama models:


conversation_manager = ConversationManager(

    system_prompt="You are a helpful assistant.",

    max_context_tokens=4096  # Llama supports longer context

)


For Mistral models:


conversation_manager = ConversationManager(

    system_prompt="<s>[INST] You are a helpful assistant. [/INST]",

    max_context_tokens=8192  # Mistral supports 8k context

)


Checking Available Models

List models from HuggingFace:


from huggingface_hub import list_models


# Search for chat models

for model in list_models(filter="text-generation", sort="downloads", direction=-1, limit=20):

    if "chat" in model.modelId.lower() or "instruct" in model.modelId.lower():

        print(f"{model.modelId} - {model.downloads} downloads")


Check current model:


@app.get("/model-info")

async def get_model_info():

    if llm_instance is None:

        raise HTTPException(status_code=503, detail="Model not loaded")

    

    return JSONResponse({

        "model_name": llm_instance.model_name,

        "device": llm_instance.hardware.detected_backend,

        "quantization_enabled": llm_instance.use_quantization,

        "memory_available": llm_instance.hardware.memory_available,

        "context_window": conversation_manager.max_context_tokens

    })


Troubleshooting Model Loading


Model not found:


# Verify model exists

from huggingface_hub import model_info


try:

    info = model_info("mistralai/Mistral-7B-Instruct-v0.2")

    print(f"Model found: {info.modelId}")

except Exception as e:

    print(f"Model not found: {e}")


Authentication required:


# Login to HuggingFace (for gated models like Llama)

huggingface-cli login


Out of memory:


# Enable quantization and limit memory

llm_instance = LocalLLM(

    model_name="mistralai/Mistral-7B-Instruct-v0.2",

    use_quantization=True,

    max_memory_gb=6  # Adjust based on your GPU

)


This chapter covers all methods to configure LLM models in your system. Choose the method that best fits your deployment scenario!


FULL RUNNING EXAMPLE VERSION 2: WITH MODEL LOADING


# main.py - Complete Local LLM Chat System with Model Management


import torch

import platform

import logging

from typing import Optional, List, Dict, Generator, Union

from datetime import datetime

import asyncio

import json

import sys

import os

from pathlib import Path


from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig

from huggingface_hub import scan_cache_dir, list_models, snapshot_download

from fastapi import FastAPI, HTTPException, BackgroundTasks

from fastapi.responses import StreamingResponse, JSONResponse, HTMLResponse

from fastapi.middleware.cors import CORSMiddleware

from pydantic import BaseModel, Field

import uvicorn


# Configure logging

logging.basicConfig(

    level=logging.INFO,

    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',

    handlers=[logging.StreamHandler(sys.stdout)]

)

logger = logging.getLogger(__name__)



class HardwareDetector:

    """Comprehensive hardware detection for optimal LLM inference."""

    

    def __init__(self):

        self.device = None

        self.device_name = None

        self.compute_dtype = None

        self.detected_backend = None

        self.memory_available = 0

        

    def detect_optimal_device(self) -> torch.device:

        """Detect and select the most appropriate hardware backend."""

        logger.info("Starting hardware detection...")

        

        # NVIDIA CUDA detection

        if torch.cuda.is_available():

            try:

                self.device = torch.device("cuda:0")

                self.device_name = torch.cuda.get_device_name(0)

                self.detected_backend = "NVIDIA CUDA"

                self.compute_dtype = torch.float16

                self.memory_available = torch.cuda.get_device_properties(0).total_memory / (1024**3)

                logger.info(f"Detected NVIDIA GPU: {self.device_name}")

                logger.info(f"Available VRAM: {self.memory_available:.2f} GB")

                return self.device

            except Exception as e:

                logger.warning(f"CUDA detection failed: {e}")

        

        # AMD ROCm detection

        if hasattr(torch.version, 'hip') and torch.version.hip is not None:

            try:

                self.device = torch.device("cuda:0")

                self.device_name = "AMD GPU (ROCm)"

                self.detected_backend = "AMD ROCm"

                self.compute_dtype = torch.float16

                logger.info("Detected AMD GPU with ROCm support")

                return self.device

            except Exception as e:

                logger.warning(f"ROCm detection failed: {e}")

        

        # Apple MPS detection

        if hasattr(torch.backends, 'mps'):

            try:

                if torch.backends.mps.is_available() and torch.backends.mps.is_built():

                    self.device = torch.device("mps")

                    self.device_name = "Apple Silicon GPU"

                    self.detected_backend = "Apple MPS"

                    self.compute_dtype = torch.float32

                    logger.info("Detected Apple Silicon with MPS support")

                    return self.device

            except Exception as e:

                logger.warning(f"MPS detection failed: {e}")

        

        # Intel XPU detection

        try:

            import intel_extension_for_pytorch as ipex

            if ipex.xpu.is_available():

                self.device = torch.device("xpu:0")

                self.device_name = "Intel GPU"

                self.detected_backend = "Intel XPU"

                self.compute_dtype = torch.float16

                logger.info("Detected Intel GPU with XPU support")

                return self.device

        except (ImportError, Exception) as e:

            if not isinstance(e, ImportError):

                logger.warning(f"Intel XPU detection failed: {e}")

        

        # CPU fallback

        self.device = torch.device("cpu")

        self.device_name = platform.processor() or "CPU"

        self.detected_backend = "CPU"

        self.compute_dtype = torch.float32

        logger.info(f"Using CPU: {self.device_name}")

        logger.warning("No GPU acceleration available. Performance will be limited.")

        

        return self.device

    

    def supports_quantization(self) -> bool:

        """Check if hardware supports model quantization."""

        return self.detected_backend in ["NVIDIA CUDA", "AMD ROCm"]



class ModelManager:

    """Manages model downloads, caching, and metadata."""

    

    def __init__(self, cache_dir: Optional[str] = None):

        self.cache_dir = cache_dir or os.path.join(str(Path.home()), ".cache", "huggingface", "hub")

        self.download_progress = {}

        

    def get_cached_models(self) -> List[Dict]:

        """Get list of locally cached models."""

        try:

            cache_info = scan_cache_dir(self.cache_dir)

            models = []

            

            for repo in cache_info.repos:

                model_info = {

                    "repo_id": repo.repo_id,

                    "repo_type": repo.repo_type,

                    "size_on_disk": repo.size_on_disk / (1024**3),  # Convert to GB

                    "last_accessed": repo.last_accessed.isoformat() if repo.last_accessed else None,

                    "last_modified": repo.last_modified.isoformat() if repo.last_modified else None,

                    "refs": [ref.name for ref in repo.refs],

                }

                models.append(model_info)

            

            return models

        except Exception as e:

            logger.error(f"Error scanning cache: {e}")

            return []

    

    def search_models(self, query: str = "", limit: int = 20, task: str = "text-generation") -> List[Dict]:

        """Search for models on HuggingFace Hub."""

        try:

            models = []

            for model in list_models(

                filter=task,

                search=query,

                sort="downloads",

                direction=-1,

                limit=limit

            ):

                model_info = {

                    "id": model.id,

                    "downloads": model.downloads or 0,

                    "likes": model.likes or 0,

                    "tags": model.tags or [],

                    "pipeline_tag": model.pipeline_tag,

                    "library_name": model.library_name,

                }

                models.append(model_info)

            

            return models

        except Exception as e:

            logger.error(f"Error searching models: {e}")

            return []

    

    async def download_model(self, model_id: str, progress_callback=None) -> bool:

        """Download a model from HuggingFace Hub."""

        try:

            self.download_progress[model_id] = {

                "status": "downloading",

                "progress": 0,

                "message": "Starting download..."

            }

            

            # Download in background

            def download():

                try:

                    snapshot_download(

                        repo_id=model_id,

                        cache_dir=self.cache_dir,

                        resume_download=True

                    )

                    self.download_progress[model_id] = {

                        "status": "completed",

                        "progress": 100,

                        "message": "Download completed"

                    }

                    return True

                except Exception as e:

                    self.download_progress[model_id] = {

                        "status": "failed",

                        "progress": 0,

                        "message": str(e)

                    }

                    logger.error(f"Download failed for {model_id}: {e}")

                    return False

            

            # Run download in thread pool

            import concurrent.futures

            with concurrent.futures.ThreadPoolExecutor() as executor:

                future = executor.submit(download)

                return future.result()

                

        except Exception as e:

            logger.error(f"Error downloading model {model_id}: {e}")

            self.download_progress[model_id] = {

                "status": "failed",

                "progress": 0,

                "message": str(e)

            }

            return False

    

    def delete_model(self, model_id: str) -> bool:

        """Delete a cached model."""

        try:

            cache_info = scan_cache_dir(self.cache_dir)

            for repo in cache_info.repos:

                if repo.repo_id == model_id:

                    # Delete all revisions

                    delete_strategy = cache_info.delete_revisions(*[rev.commit_hash for rev in repo.revisions])

                    delete_strategy.execute()

                    logger.info(f"Deleted model: {model_id}")

                    return True

            return False

        except Exception as e:

            logger.error(f"Error deleting model {model_id}: {e}")

            return False

    

    def get_download_progress(self, model_id: str) -> Dict:

        """Get download progress for a model."""

        return self.download_progress.get(model_id, {

            "status": "not_started",

            "progress": 0,

            "message": ""

        })



class ConversationManager:

    """Manages conversation history with intelligent context window handling."""

    

    def __init__(self, system_prompt: Optional[str] = None, max_context_tokens: int = 2048):

        self.messages: List[Dict[str, str]] = []

        self.system_prompt = system_prompt

        self.max_context_tokens = max_context_tokens

        self.conversation_id = datetime.now().strftime("%Y%m%d_%H%M%S")

        

        if system_prompt:

            self.messages.append({

                "role": "system",

                "content": system_prompt,

                "timestamp": datetime.now().isoformat()

            })

        

        logger.info(f"Initialized conversation {self.conversation_id}")

    

    def add_user_message(self, content: str) -> None:

        """Add a user message with timestamp."""

        self.messages.append({

            "role": "user",

            "content": content,

            "timestamp": datetime.now().isoformat()

        })

        logger.debug(f"Added user message: {content[:50]}...")

    

    def add_assistant_message(self, content: str) -> None:

        """Add an assistant message with timestamp."""

        self.messages.append({

            "role": "assistant",

            "content": content,

            "timestamp": datetime.now().isoformat()

        })

        logger.debug(f"Added assistant message: {content[:50]}...")

    

    def format_conversation(self, tokenizer) -> str:

        """Format conversation for model input with intelligent truncation."""

        # Try model's native chat template

        if hasattr(tokenizer, 'apply_chat_template') and tokenizer.chat_template is not None:

            try:

                messages_for_template = [

                    {"role": m["role"], "content": m["content"]}

                    for m in self.messages

                ]

                

                prompt = tokenizer.apply_chat_template(

                    messages_for_template,

                    tokenize=False,

                    add_generation_prompt=True

                )

                

                tokens = tokenizer.encode(prompt, add_special_tokens=False)

                if len(tokens) <= self.max_context_tokens:

                    return prompt

                

                logger.info(f"Context too long ({len(tokens)} tokens), truncating...")

                return self._truncate_conversation(tokenizer)

                

            except Exception as e:

                logger.warning(f"Chat template failed: {e}, using fallback")

        

        return self._manual_format(tokenizer)

    

    def _manual_format(self, tokenizer) -> str:

        """Manual conversation formatting with role prefixes."""

        prompt_parts = []

        

        for message in self.messages:

            role = message["role"]

            content = message["content"]

            

            if role == "system":

                prompt_parts.append(f"System: {content}")

            elif role == "user":

                prompt_parts.append(f"User: {content}")

            elif role == "assistant":

                prompt_parts.append(f"Assistant: {content}")

        

        prompt_parts.append("Assistant:")

        prompt = "\n\n".join(prompt_parts)

        

        tokens = tokenizer.encode(prompt, add_special_tokens=False)

        if len(tokens) > self.max_context_tokens:

            return self._truncate_conversation(tokenizer)

        

        return prompt

    

    def _truncate_conversation(self, tokenizer) -> str:

        """Intelligently truncate conversation to fit context window."""

        system_messages = [m for m in self.messages if m["role"] == "system"]

        other_messages = [m for m in self.messages if m["role"] != "system"]

        

        if len(other_messages) == 0:

            return self._manual_format(tokenizer)

        

        # Binary search for optimal message count

        left, right = 1, len(other_messages)

        best_count = 1

        

        while left <= right:

            mid = (left + right) // 2

            test_messages = system_messages + other_messages[-mid:]

            

            if hasattr(tokenizer, 'apply_chat_template') and tokenizer.chat_template is not None:

                try:

                    messages_for_template = [

                        {"role": m["role"], "content": m["content"]}

                        for m in test_messages

                    ]

                    test_prompt = tokenizer.apply_chat_template(

                        messages_for_template,

                        tokenize=False,

                        add_generation_prompt=True

                    )

                except Exception:

                    test_prompt = self._format_messages_simple(test_messages)

            else:

                test_prompt = self._format_messages_simple(test_messages)

            

            test_tokens = tokenizer.encode(test_prompt, add_special_tokens=False)

            

            if len(test_tokens) <= self.max_context_tokens:

                best_count = mid

                left = mid + 1

            else:

                right = mid - 1

        

        self.messages = system_messages + other_messages[-best_count:]

        logger.info(f"Truncated to {len(self.messages)} messages")

        

        if hasattr(tokenizer, 'apply_chat_template') and tokenizer.chat_template is not None:

            try:

                messages_for_template = [

                    {"role": m["role"], "content": m["content"]}

                    for m in self.messages

                ]

                return tokenizer.apply_chat_template(

                    messages_for_template,

                    tokenize=False,

                    add_generation_prompt=True

                )

            except Exception:

                pass

        

        return self._format_messages_simple(self.messages)

    

    def _format_messages_simple(self, messages: List[Dict]) -> str:

        """Simple message formatting helper."""

        parts = []

        for msg in messages:

            role = msg["role"].capitalize()

            parts.append(f"{role}: {msg['content']}")

        parts.append("Assistant:")

        return "\n\n".join(parts)

    

    def clear_history(self) -> None:

        """Clear conversation while preserving system prompt."""

        if self.system_prompt:

            self.messages = [{

                "role": "system",

                "content": self.system_prompt,

                "timestamp": datetime.now().isoformat()

            }]

        else:

            self.messages = []

        logger.info("Conversation history cleared")

    

    def get_history(self) -> List[Dict[str, str]]:

        """Return copy of conversation history."""

        return self.messages.copy()

    

    def export_conversation(self) -> Dict:

        """Export conversation with metadata."""

        return {

            "conversation_id": self.conversation_id,

            "created": self.messages[0]["timestamp"] if self.messages else None,

            "message_count": len(self.messages),

            "messages": self.messages

        }



class LocalLLM:

    """Manages local language model with automatic hardware optimization."""

    

    def __init__(self, model_name: str = "microsoft/phi-2",

                 max_memory_gb: Optional[float] = None,

                 use_quantization: bool = True):

        self.model_name = model_name

        self.max_memory_gb = max_memory_gb

        self.use_quantization = use_quantization

        

        self.hardware = HardwareDetector()

        self.device = self.hardware.detect_optimal_device()

        

        self.model = None

        self.tokenizer = None

        

        logger.info(f"Initialized LocalLLM with model: {model_name}")

    

    def load_model(self) -> None:

        """Load model and tokenizer with optimal configuration."""

        logger.info(f"Loading model: {self.model_name}")

        start_time = datetime.now()

        

        # Load tokenizer

        try:

            self.tokenizer = AutoTokenizer.from_pretrained(

                self.model_name,

                trust_remote_code=True

            )

            

            if self.tokenizer.pad_token is None:

                self.tokenizer.pad_token = self.tokenizer.eos_token

            

            if not hasattr(self.tokenizer, 'padding_side') or self.tokenizer.padding_side is None:

                self.tokenizer.padding_side = "left"

            

            logger.info("Tokenizer loaded successfully")

        except Exception as e:

            logger.error(f"Failed to load tokenizer: {e}")

            raise

        

        # Prepare model loading configuration

        model_kwargs = {

            "trust_remote_code": True,

            "torch_dtype": self.hardware.compute_dtype,

            "low_cpu_mem_usage": True

        }

        

        # Add quantization if supported

        if self.use_quantization and self.hardware.supports_quantization():

            try:

                logger.info("Enabling 4-bit quantization")

                quantization_config = BitsAndBytesConfig(

                    load_in_4bit=True,

                    bnb_4bit_compute_dtype=self.hardware.compute_dtype,

                    bnb_4bit_use_double_quant=True,

                    bnb_4bit_quant_type="nf4"

                )

                model_kwargs["quantization_config"] = quantization_config

            except Exception as e:

                logger.warning(f"Quantization setup failed: {e}, loading without quantization")

        

        # Configure device mapping

        if self.hardware.detected_backend in ["NVIDIA CUDA", "AMD ROCm"]:

            if self.max_memory_gb:

                max_memory = {0: f"{self.max_memory_gb}GiB"}

                model_kwargs["device_map"] = "auto"

                model_kwargs["max_memory"] = max_memory

            else:

                model_kwargs["device_map"] = "auto"

        

        # Load model

        try:

            self.model = AutoModelForCausalLM.from_pretrained(

                self.model_name,

                **model_kwargs

            )

            

            if "device_map" not in model_kwargs:

                self.model = self.model.to(self.device)

            

            self.model.eval()

            

            load_time = (datetime.now() - start_time).total_seconds()

            logger.info(f"Model loaded successfully in {load_time:.2f} seconds")

            

        except Exception as e:

            logger.error(f"Failed to load model: {e}")

            raise

    

    def unload_model(self) -> None:

        """Unload model from memory."""

        if self.model is not None:

            del self.model

            self.model = None

        if self.tokenizer is not None:

            del self.tokenizer

            self.tokenizer = None

        

        # Clear CUDA cache if available

        if torch.cuda.is_available():

            torch.cuda.empty_cache()

        

        logger.info("Model unloaded from memory")

    

    def generate_response(self, prompt: str, 

                         max_new_tokens: int = 512,

                         temperature: float = 0.7,

                         top_p: float = 0.9,

                         top_k: int = 50,

                         repetition_penalty: float = 1.1,

                         stream: bool = False) -> Union[Generator[str, None, None], str]:

        """Generate response with support for streaming output."""

        if self.model is None or self.tokenizer is None:

            raise RuntimeError("Model not loaded. Call load_model() first.")

        

        # Tokenize input

        try:

            max_length = getattr(self.tokenizer, 'model_max_length', 2048)

            if max_length is None or max_length > 100000:

                max_length = 2048

            

            inputs = self.tokenizer(

                prompt, 

                return_tensors="pt", 

                padding=True, 

                truncation=True, 

                max_length=max_length

            )

            input_ids = inputs["input_ids"].to(self.device)

            attention_mask = inputs["attention_mask"].to(self.device)

            input_length = input_ids.shape[1]

        except Exception as e:

            logger.error(f"Tokenization failed: {e}")

            raise

        

        logger.debug(f"Generating response for prompt of {input_length} tokens")

        

        if stream:

            return self._generate_streaming(

                input_ids, attention_mask, input_length,

                max_new_tokens, temperature, top_p, top_k, repetition_penalty

            )

        else:

            return self._generate_complete(

                input_ids, attention_mask, input_length,

                max_new_tokens, temperature, top_p, top_k, repetition_penalty

            )

    

    def _generate_streaming(self, input_ids, attention_mask, input_length,

                           max_new_tokens, temperature, top_p, top_k, repetition_penalty):

        """Internal method for streaming generation."""

        past_key_values = None

        

        with torch.no_grad():

            for step in range(max_new_tokens):

                try:

                    if past_key_values is None:

                        outputs = self.model(

                            input_ids=input_ids,

                            attention_mask=attention_mask,

                            use_cache=True

                        )

                    else:

                        outputs = self.model(

                            input_ids=input_ids[:, -1:],

                            attention_mask=attention_mask,

                            past_key_values=past_key_values,

                            use_cache=True

                        )

                    

                    past_key_values = outputs.past_key_values

                    next_token_logits = outputs.logits[:, -1, :].clone()

                    

                    # Temperature scaling

                    if temperature > 0 and temperature != 1.0:

                        next_token_logits = next_token_logits / temperature

                    

                    # Repetition penalty

                    if repetition_penalty != 1.0:

                        for token_id in set(input_ids[0].tolist()):

                            if next_token_logits[0, token_id] < 0:

                                next_token_logits[0, token_id] = next_token_logits[0, token_id] * repetition_penalty

                            else:

                                next_token_logits[0, token_id] = next_token_logits[0, token_id] / repetition_penalty

                    

                    # Top-k filtering

                    if top_k > 0:

                        vocab_size = next_token_logits.size(-1)

                        top_k_actual = min(top_k, vocab_size)

                        indices_to_remove = next_token_logits < torch.topk(next_token_logits, top_k_actual)[0][..., -1, None]

                        next_token_logits = next_token_logits.masked_fill(indices_to_remove, float('-inf'))

                    

                    # Top-p filtering

                    if top_p < 1.0:

                        sorted_logits, sorted_indices = torch.sort(next_token_logits, descending=True)

                        cumulative_probs = torch.cumsum(torch.softmax(sorted_logits, dim=-1), dim=-1)

                        

                        sorted_indices_to_remove = cumulative_probs > top_p

                        sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()

                        sorted_indices_to_remove[..., 0] = False

                        

                        indices_to_remove = torch.zeros_like(next_token_logits, dtype=torch.bool)

                        indices_to_remove.scatter_(1, sorted_indices, sorted_indices_to_remove)

                        next_token_logits = next_token_logits.masked_fill(indices_to_remove, float('-inf'))

                    

                    # Sample next token

                    probs = torch.softmax(next_token_logits, dim=-1)

                    next_token = torch.multinomial(probs, num_samples=1)

                    

                    # Check for EOS

                    if next_token.item() == self.tokenizer.eos_token_id:

                        break

                    

                    # Decode and yield token

                    token_text = self.tokenizer.decode(next_token[0], skip_special_tokens=True)

                    

                    if token_text:

                        yield token_text

                    

                    # Update sequence

                    input_ids = torch.cat([input_ids, next_token], dim=-1)

                    attention_mask = torch.cat([

                        attention_mask,

                        torch.ones((1, 1), device=self.device, dtype=attention_mask.dtype)

                    ], dim=-1)

                    

                except Exception as e:

                    logger.error(f"Error during streaming generation at step {step}: {e}")

                    break

    

    def _generate_complete(self, input_ids, attention_mask, input_length,

                          max_new_tokens, temperature, top_p, top_k, repetition_penalty):

        """Internal method for complete generation."""

        with torch.no_grad():

            try:

                actual_temperature = max(temperature, 0.01) if temperature > 0 else 1.0

                

                outputs = self.model.generate(

                    input_ids=input_ids,

                    attention_mask=attention_mask,

                    max_new_tokens=max_new_tokens,

                    temperature=actual_temperature,

                    top_p=top_p,

                    top_k=top_k,

                    repetition_penalty=repetition_penalty,

                    do_sample=temperature > 0,

                    pad_token_id=self.tokenizer.pad_token_id,

                    eos_token_id=self.tokenizer.eos_token_id,

                    use_cache=True

                )

                

                generated_ids = outputs[0][input_length:]

                response = self.tokenizer.decode(generated_ids, skip_special_tokens=True)

                return response

            except Exception as e:

                logger.error(f"Error during complete generation: {e}")

                raise



# Pydantic models for API

class ChatMessage(BaseModel):

    message: str = Field(..., min_length=1, max_length=10000)

    stream: bool = True

    temperature: float = Field(0.7, ge=0.0, le=2.0)

    max_tokens: int = Field(512, ge=1, le=2048)

    top_p: float = Field(0.9, ge=0.0, le=1.0)

    top_k: int = Field(50, ge=0, le=100)

    repetition_penalty: float = Field(1.1, ge=1.0, le=2.0)



class SystemConfig(BaseModel):

    system_prompt: Optional[str] = None

    model_name: Optional[str] = None

    max_context_tokens: Optional[int] = Field(None, ge=512, le=8192)



class ModelDownloadRequest(BaseModel):

    model_id: str = Field(..., min_length=1)



class ModelSearchRequest(BaseModel):

    query: str = ""

    limit: int = Field(20, ge=1, le=100)



# FastAPI application

app = FastAPI(

    title="Local LLM Chat API",

    description="Production-ready local language model chat system with model management",

    version="2.0.0"

)


# CORS middleware

app.add_middleware(

    CORSMiddleware,

    allow_origins=["*"],

    allow_credentials=True,

    allow_methods=["*"],

    allow_headers=["*"],

)


# Global state

llm_instance: Optional[LocalLLM] = None

conversation_manager: Optional[ConversationManager] = None

model_manager: ModelManager = ModelManager()



@app.on_event("startup")

async def startup_event():

    """Initialize system on startup."""

    global conversation_manager

    

    logger.info("=" * 60)

    logger.info("Starting Local LLM Chat System")

    logger.info("=" * 60)

    

    try:

        conversation_manager = ConversationManager(

            system_prompt="You are a helpful, knowledgeable AI assistant.",

            max_context_tokens=2048

        )

        

        logger.info("System initialization complete (no model loaded)")

        logger.info("=" * 60)

        

    except Exception as e:

        logger.error(f"Startup failed: {e}", exc_info=True)

        raise



@app.get("/", response_class=HTMLResponse)

async def serve_frontend():

    """Serve the frontend HTML with model management UI."""

    return """<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Local LLM Chat - Model Manager</title>

    <style>

        * { margin: 0; padding: 0; box-sizing: border-box; }

        body {

            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif;

            background-color: #343541; color: #ececf1; height: 100vh; overflow: hidden;

        }

        .app-container { display: flex; height: 100vh; width: 100%; }

        .sidebar {

            width: 260px; background-color: #202123; display: flex; flex-direction: column;

            padding: 8px; border-right: 1px solid #4d4d4f;

        }

        .new-chat-button, .model-manager-button {

            display: flex; align-items: center; gap: 12px; padding: 12px; border: 1px solid #4d4d4f;

            border-radius: 6px; background: transparent; color: #ececf1; cursor: pointer;

            font-size: 14px; transition: background-color 0.2s; margin-bottom: 8px;

        }

        .new-chat-button:hover, .model-manager-button:hover { background-color: #2a2b32; }

        .model-manager-button { background: #10a37f; border-color: #10a37f; }

        .model-manager-button:hover { background: #0d8c6d; }

        .sidebar-content { flex: 1; overflow-y: auto; }

        .sidebar-footer {

            padding: 12px; border-top: 1px solid #4d4d4f; font-size: 12px; color: #8e8ea0;

        }

        .status-info { display: flex; align-items: center; gap: 8px; margin-bottom: 4px; }

        .status-dot { width: 8px; height: 8px; border-radius: 50%; background: #10a37f; }

        .main-content { flex: 1; display: flex; flex-direction: column; }

        .chat-header {

            padding: 12px 16px; border-bottom: 1px solid #4d4d4f; display: flex;

            justify-content: space-between; align-items: center; background-color: #343541;

        }

        .model-selector {

            background: #40414f; border: 1px solid #4d4d4f; border-radius: 6px;

            padding: 8px 12px; color: #ececf1; font-size: 14px;

        }

        .messages-container { flex: 1; overflow-y: auto; display: flex; flex-direction: column; }

        .messages-wrapper { max-width: 768px; width: 100%; margin: 0 auto; padding: 24px; }

        .message-group {

            display: flex; gap: 16px; padding: 24px 0; border-bottom: 1px solid #4d4d4f;

        }

        .message-group.user { background-color: #343541; }

        .message-group.assistant { background-color: #444654; }

        .avatar {

            width: 30px; height: 30px; border-radius: 2px; display: flex;

            align-items: center; justify-content: center; font-weight: 600; font-size: 12px;

            flex-shrink: 0;

        }

        .avatar.user { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }

        .avatar.assistant { background: #10a37f; color: white; }

        .message-content {

            flex: 1; line-height: 1.7; font-size: 16px; word-wrap: break-word; white-space: pre-wrap;

        }

        .typing-indicator { display: flex; gap: 4px; padding: 8px 0; }

        .typing-dot {

            width: 8px; height: 8px; border-radius: 50%; background: #8e8ea0;

            animation: typing 1.4s infinite;

        }

        .typing-dot:nth-child(2) { animation-delay: 0.2s; }

        .typing-dot:nth-child(3) { animation-delay: 0.4s; }

        @keyframes typing {

            0%, 60%, 100% { transform: translateY(0); opacity: 0.7; }

            30% { transform: translateY(-10px); opacity: 1; }

        }

        .input-area { padding: 24px; background-color: #343541; }

        .input-wrapper { max-width: 768px; margin: 0 auto; }

        .input-container {

            display: flex; align-items: flex-end; background: #40414f; border: 1px solid #4d4d4f;

            border-radius: 12px; padding: 12px; box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);

        }

        .message-input {

            flex: 1; background: transparent; border: none; color: #ececf1; font-size: 16px;

            outline: none; resize: none; max-height: 200px; overflow-y: auto; font-family: inherit;

            line-height: 24px; padding: 0 8px;

        }

        .message-input::placeholder { color: #8e8ea0; }

        .send-button {

            width: 32px; height: 32px; border-radius: 6px; border: none; background: #19c37d;

            color: white; cursor: pointer; display: flex; align-items: center; justify-content: center;

            transition: background-color 0.2s; flex-shrink: 0; margin-left: 8px;

        }

        .send-button:hover:not(:disabled) { background: #1a7f5a; }

        .send-button:disabled { background: #4d4d4f; cursor: not-allowed; }

        .error-message {

            background: #f44336; color: white; padding: 16px; border-radius: 8px; margin: 16px 0;

            display: flex; align-items: center; gap: 12px;

        }

        .welcome-screen {

            display: flex; flex-direction: column; align-items: center; justify-content: center;

            height: 100%; padding: 24px; text-align: center;

        }

        .welcome-title { font-size: 32px; font-weight: 600; margin-bottom: 16px; }

        .welcome-subtitle { font-size: 16px; color: #8e8ea0; margin-bottom: 32px; }

        .example-prompts {

            display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));

            gap: 12px; max-width: 800px; width: 100%;

        }

        .example-prompt {

            background: #40414f; border: 1px solid #4d4d4f; border-radius: 8px; padding: 16px;

            cursor: pointer; transition: background-color 0.2s; text-align: left;

        }

        .example-prompt:hover { background: #4d4d4f; }

        .example-prompt-title { font-weight: 600; margin-bottom: 4px; }

        .example-prompt-text { font-size: 14px; color: #8e8ea0; }

        

        /* Modal Styles */

        .modal {

            display: none; position: fixed; z-index: 1000; left: 0; top: 0;

            width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.7);

        }

        .modal.active { display: flex; align-items: center; justify-content: center; }

        .modal-content {

            background-color: #343541; margin: auto; padding: 0; border: 1px solid #4d4d4f;

            width: 90%; max-width: 900px; border-radius: 12px; max-height: 90vh; overflow: hidden;

            display: flex; flex-direction: column;

        }

        .modal-header {

            padding: 20px; border-bottom: 1px solid #4d4d4f; display: flex;

            justify-content: space-between; align-items: center;

        }

        .modal-title { font-size: 24px; font-weight: 600; }

        .close-button {

            background: none; border: none; color: #8e8ea0; font-size: 28px;

            cursor: pointer; padding: 0; width: 32px; height: 32px;

        }

        .close-button:hover { color: #ececf1; }

        .modal-body { padding: 20px; overflow-y: auto; flex: 1; }

        .tabs {

            display: flex; gap: 8px; margin-bottom: 20px; border-bottom: 1px solid #4d4d4f;

        }

        .tab {

            padding: 12px 24px; background: transparent; border: none; color: #8e8ea0;

            cursor: pointer; font-size: 14px; border-bottom: 2px solid transparent;

            transition: all 0.2s;

        }

        .tab.active { color: #ececf1; border-bottom-color: #10a37f; }

        .tab:hover { color: #ececf1; }

        .tab-content { display: none; }

        .tab-content.active { display: block; }

        

        /* Search Bar */

        .search-bar {

            display: flex; gap: 8px; margin-bottom: 20px;

        }

        .search-input {

            flex: 1; background: #40414f; border: 1px solid #4d4d4f; border-radius: 6px;

            padding: 12px; color: #ececf1; font-size: 14px;

        }

        .search-button {

            background: #10a37f; border: none; border-radius: 6px; padding: 12px 24px;

            color: white; cursor: pointer; font-size: 14px; transition: background-color 0.2s;

        }

        .search-button:hover { background: #0d8c6d; }

        

        /* Model Cards */

        .model-grid {

            display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));

            gap: 16px;

        }

        .model-card {

            background: #40414f; border: 1px solid #4d4d4f; border-radius: 8px;

            padding: 16px; transition: all 0.2s;

        }

        .model-card:hover { border-color: #10a37f; }

        .model-name { font-weight: 600; margin-bottom: 8px; font-size: 16px; }

        .model-info { font-size: 12px; color: #8e8ea0; margin-bottom: 12px; }

        .model-actions {

            display: flex; gap: 8px; margin-top: 12px;

        }

        .btn {

            padding: 8px 16px; border: none; border-radius: 6px; cursor: pointer;

            font-size: 13px; transition: all 0.2s; flex: 1;

        }

        .btn-primary { background: #10a37f; color: white; }

        .btn-primary:hover { background: #0d8c6d; }

        .btn-danger { background: #f44336; color: white; }

        .btn-danger:hover { background: #d32f2f; }

        .btn-secondary { background: #4d4d4f; color: #ececf1; }

        .btn-secondary:hover { background: #5e5e60; }

        .btn:disabled { opacity: 0.5; cursor: not-allowed; }

        

        /* Progress Bar */

        .progress-bar {

            width: 100%; height: 4px; background: #4d4d4f; border-radius: 2px;

            overflow: hidden; margin-top: 8px;

        }

        .progress-fill {

            height: 100%; background: #10a37f; transition: width 0.3s;

        }

        .progress-text {

            font-size: 11px; color: #8e8ea0; margin-top: 4px;

        }

        

        .scrollbar-custom::-webkit-scrollbar { width: 8px; }

        .scrollbar-custom::-webkit-scrollbar-track { background: transparent; }

        .scrollbar-custom::-webkit-scrollbar-thumb { background: #4d4d4f; border-radius: 4px; }

        .scrollbar-custom::-webkit-scrollbar-thumb:hover { background: #5e5e60; }

        

        .loading-spinner {

            border: 3px solid #4d4d4f;

            border-top: 3px solid #10a37f;

            border-radius: 50%;

            width: 20px;

            height: 20px;

            animation: spin 1s linear infinite;

            display: inline-block;

        }

        @keyframes spin {

            0% { transform: rotate(0deg); }

            100% { transform: rotate(360deg); }

        }

        

        @media (max-width: 768px) {

            .sidebar { display: none; }

            .messages-wrapper { padding: 16px; }

            .input-area { padding: 16px; }

            .modal-content { width: 95%; }

            .model-grid { grid-template-columns: 1fr; }

        }

    </style>

</head>

<body>

    <div class="app-container">

        <div class="sidebar">

            <button class="new-chat-button" onclick="newChat()">

                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">

                    <line x1="12" y1="5" x2="12" y2="19"></line>

                    <line x1="5" y1="12" x2="19" y2="12"></line>

                </svg>

                New chat

            </button>

            <button class="model-manager-button" onclick="openModelManager()">

                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">

                    <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"></path>

                </svg>

                Model Manager

            </button>

            <div class="sidebar-content scrollbar-custom"></div>

            <div class="sidebar-footer">

                <div class="status-info">

                    <div class="status-dot" id="statusDot"></div>

                    <span id="statusText">No Model Loaded</span>

                </div>

                <div id="deviceInfo" style="margin-top: 4px;"></div>

                <div id="currentModel" style="margin-top: 4px; font-weight: 600;"></div>

            </div>

        </div>

        <div class="main-content">

            <div class="chat-header">

                <div class="model-selector" id="modelName">Local LLM Chat</div>

            </div>

            <div class="messages-container scrollbar-custom" id="messagesContainer">

                <div class="messages-wrapper" id="messages">

                    <div class="welcome-screen" id="welcomeScreen">

                        <div class="welcome-title">Local LLM Chat</div>

                        <div class="welcome-subtitle">Load a model to start chatting</div>

                        <button class="model-manager-button" onclick="openModelManager()" style="margin-top: 20px; padding: 16px 32px; font-size: 16px;">

                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">

                                <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"></path>

                            </svg>

                            Open Model Manager

                        </button>

                    </div>

                </div>

            </div>

            <div class="input-area">

                <div class="input-wrapper">

                    <div class="input-container">

                        <textarea class="message-input" id="messageInput" placeholder="Send a message..." rows="1" onkeydown="handleKeyDown(event)" oninput="autoResize(this)"></textarea>

                        <button class="send-button" id="sendButton" onclick="sendMessage()">

                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none">

                                <path d="M7 11L12 6L17 11M12 18V7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>

                            </svg>

                        </button>

                    </div>

                </div>

            </div>

        </div>

    </div>

    

    <!-- Model Manager Modal -->

    <div id="modelManagerModal" class="modal">

        <div class="modal-content">

            <div class="modal-header">

                <h2 class="modal-title">Model Manager</h2>

                <button class="close-button" onclick="closeModelManager()">&times;</button>

            </div>

            <div class="modal-body scrollbar-custom">

                <div class="tabs">

                    <button class="tab active" onclick="switchTab('cached')">Cached Models</button>

                    <button class="tab" onclick="switchTab('search')">Search & Download</button>

                </div>

                

                <div id="cachedTab" class="tab-content active">

                    <div id="cachedModels" class="model-grid">

                        <div style="text-align: center; padding: 40px; color: #8e8ea0;">

                            <div class="loading-spinner" style="margin: 0 auto 16px;"></div>

                            <p>Loading cached models...</p>

                        </div>

                    </div>

                </div>

                

                <div id="searchTab" class="tab-content">

                    <div class="search-bar">

                        <input type="text" class="search-input" id="searchInput" placeholder="Search models (e.g., mistral, llama, phi)...">

                        <button class="search-button" onclick="searchModels()">Search</button>

                    </div>

                    <div id="searchResults" class="model-grid">

                        <div style="text-align: center; padding: 40px; color: #8e8ea0;">

                            <p>Enter a search term to find models</p>

                        </div>

                    </div>

                </div>

            </div>

        </div>

    </div>

    

    <script>

        const API_BASE_URL = window.location.origin;

        let isGenerating = false;

        let currentAssistantMessage = null;

        let messageCount = 0;

        let currentModelLoaded = null;

        

        async function initialize() {

            try {

                const response = await fetch(API_BASE_URL + '/status');

                const data = await response.json();

                if (data.status === 'ready') {

                    updateStatus('Ready', true);

                    currentModelLoaded = data.model_name;

                    document.getElementById('modelName').textContent = data.model_name || 'Local LLM';

                    document.getElementById('deviceInfo').textContent = data.device || '';

                    document.getElementById('currentModel').textContent = 'Model: ' + (data.model_name || 'None');

                    hideWelcomeScreen();

                } else {

                    updateStatus('No Model Loaded', false);

                    document.getElementById('currentModel').textContent = 'Model: None';

                }

            } catch (error) {

                updateStatus('Connection Error', false);

                console.error('Connection error:', error);

                setTimeout(initialize, 5000);

            }

        }

        

        function updateStatus(text, isReady) {

            document.getElementById('statusText').textContent = text;

            document.getElementById('statusDot').style.background = isReady ? '#10a37f' : '#ef4444';

        }

        

        function hideWelcomeScreen() {

            const welcomeScreen = document.getElementById('welcomeScreen');

            if (welcomeScreen) welcomeScreen.style.display = 'none';

        }

        

        function addMessage(content, role) {

            hideWelcomeScreen();

            const messagesDiv = document.getElementById('messages');

            const messageGroup = document.createElement('div');

            messageGroup.className = 'message-group ' + role;

            const avatar = document.createElement('div');

            avatar.className = 'avatar ' + role;

            avatar.textContent = role === 'user' ? 'U' : 'AI';

            const contentDiv = document.createElement('div');

            contentDiv.className = 'message-content';

            contentDiv.textContent = content;

            messageGroup.appendChild(avatar);

            messageGroup.appendChild(contentDiv);

            messagesDiv.appendChild(messageGroup);

            scrollToBottom();

            messageCount++;

            return contentDiv;

        }

        

        function showTypingIndicator() {

            hideWelcomeScreen();

            const messagesDiv = document.getElementById('messages');

            const messageGroup = document.createElement('div');

            messageGroup.className = 'message-group assistant';

            messageGroup.id = 'typing-indicator';

            const avatar = document.createElement('div');

            avatar.className = 'avatar assistant';

            avatar.textContent = 'AI';

            const typingDiv = document.createElement('div');

            typingDiv.className = 'message-content';

            typingDiv.innerHTML = '<div class="typing-indicator"><div class="typing-dot"></div><div class="typing-dot"></div><div class="typing-dot"></div></div>';

            messageGroup.appendChild(avatar);

            messageGroup.appendChild(typingDiv);

            messagesDiv.appendChild(messageGroup);

            scrollToBottom();

        }

        

        function removeTypingIndicator() {

            const indicator = document.getElementById('typing-indicator');

            if (indicator) indicator.remove();

        }

        

        function showError(message) {

            const messagesDiv = document.getElementById('messages');

            const errorDiv = document.createElement('div');

            errorDiv.className = 'error-message';

            errorDiv.innerHTML = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line></svg><span>' + message + '</span>';

            messagesDiv.appendChild(errorDiv);

            scrollToBottom();

        }

        

        function scrollToBottom() {

            const container = document.getElementById('messagesContainer');

            container.scrollTop = container.scrollHeight;

        }

        

        async function sendMessage() {

            if (!currentModelLoaded) {

                showError('Please load a model first using the Model Manager');

                return;

            }

            

            const input = document.getElementById('messageInput');

            const message = input.value.trim();

            if (!message || isGenerating) return;

            input.value = '';

            input.style.height = 'auto';

            isGenerating = true;

            updateControls();

            addMessage(message, 'user');

            showTypingIndicator();

            try {

                const response = await fetch(API_BASE_URL + '/chat', {

                    method: 'POST',

                    headers: { 'Content-Type': 'application/json' },

                    body: JSON.stringify({ message: message, stream: true, temperature: 0.7, max_tokens: 512 })

                });

                if (!response.ok) throw new Error('HTTP error! status: ' + response.status);

                removeTypingIndicator();

                currentAssistantMessage = addMessage('', 'assistant');

                const reader = response.body.getReader();

                const decoder = new TextDecoder();

                let buffer = '';

                while (true) {

                    const result = await reader.read();

                    if (result.done) break;

                    buffer += decoder.decode(result.value, { stream: true });

                    const lines = buffer.split('\\n');

                    buffer = lines.pop() || '';

                    for (let i = 0; i < lines.length; i++) {

                        const line = lines[i];

                        if (line.startsWith('data: ')) {

                            try {

                                const data = JSON.parse(line.slice(6));

                                if (data.error) { showError(data.error); break; }

                                if (data.token) { currentAssistantMessage.textContent += data.token; scrollToBottom(); }

                                if (data.done) break;

                            } catch (e) { console.error('Parse error:', e); }

                        }

                    }

                }

            } catch (error) {

                removeTypingIndicator();

                showError('Error: ' + error.message);

                console.error('Error:', error);

            } finally {

                isGenerating = false;

                currentAssistantMessage = null;

                updateControls();

            }

        }

        

        function updateControls() {

            document.getElementById('sendButton').disabled = isGenerating || !currentModelLoaded;

            document.getElementById('messageInput').disabled = isGenerating || !currentModelLoaded;

            if (!isGenerating && currentModelLoaded) document.getElementById('messageInput').focus();

        }

        

        function handleKeyDown(event) {

            if (event.key === 'Enter' && !event.shiftKey) {

                event.preventDefault();

                sendMessage();

            }

        }

        

        function autoResize(textarea) {

            textarea.style.height = 'auto';

            textarea.style.height = Math.min(textarea.scrollHeight, 200) + 'px';

        }

        

        async function newChat() {

            if (messageCount === 0) return;

            if (!confirm('Start a new conversation? Current chat will be cleared.')) return;

            try {

                const response = await fetch(API_BASE_URL + '/clear', { method: 'POST' });

                if (response.ok) {

                    document.getElementById('messages').innerHTML = '';

                    messageCount = 0;

                    if (!currentModelLoaded) {

                        document.getElementById('messages').innerHTML = '<div class="welcome-screen" id="welcomeScreen"><div class="welcome-title">Local LLM Chat</div><div class="welcome-subtitle">Load a model to start chatting</div><button class="model-manager-button" onclick="openModelManager()" style="margin-top: 20px; padding: 16px 32px; font-size: 16px;"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"></path></svg>Open Model Manager</button></div>';

                    }

                }

            } catch (error) {

                showError('Error clearing conversation: ' + error.message);

            }

        }

        

        // Model Manager Functions

        function openModelManager() {

            document.getElementById('modelManagerModal').classList.add('active');

            loadCachedModels();

        }

        

        function closeModelManager() {

            document.getElementById('modelManagerModal').classList.remove('active');

        }

        

        function switchTab(tab) {

            document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));

            document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));

            

            if (tab === 'cached') {

                document.querySelector('.tab:nth-child(1)').classList.add('active');

                document.getElementById('cachedTab').classList.add('active');

                loadCachedModels();

            } else {

                document.querySelector('.tab:nth-child(2)').classList.add('active');

                document.getElementById('searchTab').classList.add('active');

            }

        }

        

        async function loadCachedModels() {

            const container = document.getElementById('cachedModels');

            container.innerHTML = '<div style="text-align: center; padding: 40px; color: #8e8ea0;"><div class="loading-spinner" style="margin: 0 auto 16px;"></div><p>Loading cached models...</p></div>';

            

            try {

                const response = await fetch(API_BASE_URL + '/models/cached');

                const models = await response.json();

                

                if (models.length === 0) {

                    container.innerHTML = '<div style="text-align: center; padding: 40px; color: #8e8ea0;"><p>No cached models found. Search and download models from the Search tab.</p></div>';

                    return;

                }

                

                container.innerHTML = '';

                models.forEach(model => {

                    const card = createModelCard(model, true);

                    container.appendChild(card);

                });

            } catch (error) {

                container.innerHTML = '<div style="text-align: center; padding: 40px; color: #f44336;"><p>Error loading models: ' + error.message + '</p></div>';

            }

        }

        

        async function searchModels() {

            const query = document.getElementById('searchInput').value.trim();

            const container = document.getElementById('searchResults');

            

            container.innerHTML = '<div style="text-align: center; padding: 40px; color: #8e8ea0;"><div class="loading-spinner" style="margin: 0 auto 16px;"></div><p>Searching models...</p></div>';

            

            try {

                const response = await fetch(API_BASE_URL + '/models/search', {

                    method: 'POST',

                    headers: { 'Content-Type': 'application/json' },

                    body: JSON.stringify({ query: query, limit: 20 })

                });

                const models = await response.json();

                

                if (models.length === 0) {

                    container.innerHTML = '<div style="text-align: center; padding: 40px; color: #8e8ea0;"><p>No models found. Try a different search term.</p></div>';

                    return;

                }

                

                container.innerHTML = '';

                models.forEach(model => {

                    const card = createModelCard(model, false);

                    container.appendChild(card);

                });

            } catch (error) {

                container.innerHTML = '<div style="text-align: center; padding: 40px; color: #f44336;"><p>Error searching models: ' + error.message + '</p></div>';

            }

        }

        

        function createModelCard(model, isCached) {

            const card = document.createElement('div');

            card.className = 'model-card';

            

            const modelId = isCached ? model.repo_id : model.id;

            const isCurrentModel = modelId === currentModelLoaded;

            

            let html = '<div class="model-name">' + modelId + '</div>';

            

            if (isCached) {

                html += '<div class="model-info">';

                html += 'Size: ' + model.size_on_disk.toFixed(2) + ' GB<br>';

                if (model.last_accessed) {

                    html += 'Last used: ' + new Date(model.last_accessed).toLocaleDateString();

                }

                html += '</div>';

            } else {

                html += '<div class="model-info">';

                html += 'Downloads: ' + (model.downloads || 0).toLocaleString() + '<br>';

                html += 'Likes: ' + (model.likes || 0).toLocaleString();

                html += '</div>';

            }

            

            html += '<div class="model-actions">';

            

            if (isCached) {

                if (isCurrentModel) {

                    html += '<button class="btn btn-secondary" disabled>Currently Loaded</button>';

                } else {

                    html += '<button class="btn btn-primary" onclick="loadModel(\'' + modelId + '\')">Load Model</button>';

                }

                html += '<button class="btn btn-danger" onclick="deleteModel(\'' + modelId + '\')">Delete</button>';

            } else {

                html += '<button class="btn btn-primary" onclick="downloadModel(\'' + modelId + '\')">Download</button>';

            }

            

            html += '</div>';

            html += '<div id="progress-' + modelId.replace(/\//g, '-') + '"></div>';

            

            card.innerHTML = html;

            return card;

        }

        

        async function loadModel(modelId) {

            try {

                updateStatus('Loading model...', false);

                const response = await fetch(API_BASE_URL + '/models/load', {

                    method: 'POST',

                    headers: { 'Content-Type': 'application/json' },

                    body: JSON.stringify({ model_id: modelId })

                });

                

                const result = await response.json();

                

                if (response.ok) {

                    currentModelLoaded = modelId;

                    updateStatus('Ready', true);

                    document.getElementById('modelName').textContent = modelId;

                    document.getElementById('currentModel').textContent = 'Model: ' + modelId;

                    closeModelManager();

                    hideWelcomeScreen();

                    updateControls();

                    alert('Model loaded successfully!');

                } else {

                    updateStatus('Load failed', false);

                    alert('Error loading model: ' + result.detail);

                }

            } catch (error) {

                updateStatus('Load failed', false);

                alert('Error loading model: ' + error.message);

            }

        }

        

        async function downloadModel(modelId) {

            const progressId = 'progress-' + modelId.replace(/\//g, '-');

            const progressDiv = document.getElementById(progressId);

            

            progressDiv.innerHTML = '<div class="progress-bar"><div class="progress-fill" style="width: 0%"></div></div><div class="progress-text">Starting download...</div>';

            

            try {

                const response = await fetch(API_BASE_URL + '/models/download', {

                    method: 'POST',

                    headers: { 'Content-Type': 'application/json' },

                    body: JSON.stringify({ model_id: modelId })

                });

                

                if (response.ok) {

                    // Poll for progress

                    const pollProgress = setInterval(async () => {

                        const progressResponse = await fetch(API_BASE_URL + '/models/download/progress/' + encodeURIComponent(modelId));

                        const progress = await progressResponse.json();

                        

                        const progressBar = progressDiv.querySelector('.progress-fill');

                        const progressText = progressDiv.querySelector('.progress-text');

                        

                        if (progressBar && progressText) {

                            progressBar.style.width = progress.progress + '%';

                            progressText.textContent = progress.message;

                        }

                        

                        if (progress.status === 'completed') {

                            clearInterval(pollProgress);

                            setTimeout(() => {

                                loadCachedModels();

                            }, 1000);

                        } else if (progress.status === 'failed') {

                            clearInterval(pollProgress);

                            progressText.textContent = 'Download failed: ' + progress.message;

                            progressText.style.color = '#f44336';

                        }

                    }, 1000);

                } else {

                    const error = await response.json();

                    progressDiv.querySelector('.progress-text').textContent = 'Download failed: ' + error.detail;

                    progressDiv.querySelector('.progress-text').style.color = '#f44336';

                }

            } catch (error) {

                progressDiv.querySelector('.progress-text').textContent = 'Download failed: ' + error.message;

                progressDiv.querySelector('.progress-text').style.color = '#f44336';

            }

        }

        

        async function deleteModel(modelId) {

            if (!confirm('Are you sure you want to delete ' + modelId + '?')) return;

            

            try {

                const response = await fetch(API_BASE_URL + '/models/delete/' + encodeURIComponent(modelId), {

                    method: 'DELETE'

                });

                

                if (response.ok) {

                    if (modelId === currentModelLoaded) {

                        currentModelLoaded = null;

                        updateStatus('No Model Loaded', false);

                        document.getElementById('modelName').textContent = 'Local LLM Chat';

                        document.getElementById('currentModel').textContent = 'Model: None';

                        updateControls();

                    }

                    loadCachedModels();

                } else {

                    const error = await response.json();

                    alert('Error deleting model: ' + error.detail);

                }

            } catch (error) {

                alert('Error deleting model: ' + error.message);

            }

        }

        

        // Close modal when clicking outside

        window.onclick = function(event) {

            const modal = document.getElementById('modelManagerModal');

            if (event.target === modal) {

                closeModelManager();

            }

        }

        

        // Search on Enter key

        document.addEventListener('DOMContentLoaded', function() {

            const searchInput = document.getElementById('searchInput');

            if (searchInput) {

                searchInput.addEventListener('keypress', function(e) {

                    if (e.key === 'Enter') {

                        searchModels();

                    }

                });

            }

        });

        

        window.addEventListener('load', function() {

            initialize();

            updateControls();

        });

    </script>

</body>

</html>"""



@app.post("/chat")

async def chat(message: ChatMessage):

    """Process chat message and return response."""

    if llm_instance is None or conversation_manager is None:

        raise HTTPException(status_code=503, detail="No model loaded. Please load a model first.")

    

    try:

        conversation_manager.add_user_message(message.message)

        prompt = conversation_manager.format_conversation(llm_instance.tokenizer)

        

        if message.stream:

            async def generate_stream():

                full_response = ""

                try:

                    for token in llm_instance.generate_response(

                        prompt=prompt,

                        max_new_tokens=message.max_tokens,

                        temperature=message.temperature,

                        top_p=message.top_p,

                        top_k=message.top_k,

                        repetition_penalty=message.repetition_penalty,

                        stream=True

                    ):

                        full_response += token

                        yield f"data: {json.dumps({'token': token})}\n\n"

                        await asyncio.sleep(0.001)

                    

                    conversation_manager.add_assistant_message(full_response)

                    yield f"data: {json.dumps({'done': True})}\n\n"

                    

                except Exception as e:

                    logger.error(f"Generation error: {e}", exc_info=True)

                    yield f"data: {json.dumps({'error': str(e)})}\n\n"

            

            return StreamingResponse(generate_stream(), media_type="text/event-stream")

        else:

            response = llm_instance.generate_response(

                prompt=prompt,

                max_new_tokens=message.max_tokens,

                temperature=message.temperature,

                top_p=message.top_p,

                top_k=message.top_k,

                repetition_penalty=message.repetition_penalty,

                stream=False

            )

            

            conversation_manager.add_assistant_message(response)

            return JSONResponse({"response": response, "done": True})

            

    except Exception as e:

        logger.error(f"Chat error: {e}", exc_info=True)

        raise HTTPException(status_code=500, detail=str(e))



@app.post("/clear")

async def clear_conversation():

    """Clear conversation history."""

    if conversation_manager is None:

        raise HTTPException(status_code=503, detail="System not initialized")

    conversation_manager.clear_history()

    return JSONResponse({"status": "success", "message": "Conversation cleared"})



@app.get("/history")

async def get_history():

    """Get conversation history."""

    if conversation_manager is None:

        raise HTTPException(status_code=503, detail="System not initialized")

    return JSONResponse({"history": conversation_manager.get_history()})



@app.get("/status")

async def get_status():

    """Get system status."""

    if llm_instance is None or llm_instance.model is None:

        return JSONResponse({

            "status": "not_ready",

            "model_loaded": False,

            "model_name": None,

            "device": None,

            "device_name": None

        })

    

    return JSONResponse({

        "status": "ready",

        "model_loaded": True,

        "model_name": llm_instance.model_name,

        "device": llm_instance.hardware.detected_backend,

        "device_name": llm_instance.hardware.device_name,

        "compute_dtype": str(llm_instance.hardware.compute_dtype),

        "memory_available": llm_instance.hardware.memory_available

    })



@app.get("/models/cached")

async def get_cached_models():

    """Get list of cached models."""

    try:

        models = model_manager.get_cached_models()

        return JSONResponse(models)

    except Exception as e:

        logger.error(f"Error getting cached models: {e}")

        raise HTTPException(status_code=500, detail=str(e))



@app.post("/models/search")

async def search_models(request: ModelSearchRequest):

    """Search for models on HuggingFace Hub."""

    try:

        models = model_manager.search_models(query=request.query, limit=request.limit)

        return JSONResponse(models)

    except Exception as e:

        logger.error(f"Error searching models: {e}")

        raise HTTPException(status_code=500, detail=str(e))



@app.post("/models/download")

async def download_model(request: ModelDownloadRequest, background_tasks: BackgroundTasks):

    """Download a model from HuggingFace Hub."""

    try:

        # Start download in background

        background_tasks.add_task(model_manager.download_model, request.model_id)

        return JSONResponse({

            "status": "started",

            "message": f"Download started for {request.model_id}"

        })

    except Exception as e:

        logger.error(f"Error starting download: {e}")

        raise HTTPException(status_code=500, detail=str(e))



@app.get("/models/download/progress/{model_id:path}")

async def get_download_progress(model_id: str):

    """Get download progress for a model."""

    try:

        progress = model_manager.get_download_progress(model_id)

        return JSONResponse(progress)

    except Exception as e:

        logger.error(f"Error getting download progress: {e}")

        raise HTTPException(status_code=500, detail=str(e))



@app.post("/models/load")

async def load_model(request: ModelDownloadRequest):

    """Load a model into memory."""

    global llm_instance

    

    try:

        # Unload current model if any

        if llm_instance is not None:

            llm_instance.unload_model()

            llm_instance = None

        

        # Load new model

        llm_instance = LocalLLM(

            model_name=request.model_id,

            use_quantization=True

        )

        llm_instance.load_model()

        

        return JSONResponse({

            "status": "success",

            "message": f"Model {request.model_id} loaded successfully",

            "model_name": llm_instance.model_name,

            "device": llm_instance.hardware.detected_backend

        })

    except Exception as e:

        logger.error(f"Error loading model: {e}", exc_info=True)

        llm_instance = None

        raise HTTPException(status_code=500, detail=str(e))



@app.delete("/models/delete/{model_id:path}")

async def delete_model(model_id: str):

    """Delete a cached model."""

    global llm_instance

    

    try:

        # Unload if currently loaded

        if llm_instance is not None and llm_instance.model_name == model_id:

            llm_instance.unload_model()

            llm_instance = None

        

        # Delete from cache

        success = model_manager.delete_model(model_id)

        

        if success:

            return JSONResponse({

                "status": "success",

                "message": f"Model {model_id} deleted successfully"

            })

        else:

            raise HTTPException(status_code=404, detail="Model not found in cache")

    except HTTPException:

        raise

    except Exception as e:

        logger.error(f"Error deleting model: {e}")

        raise HTTPException(status_code=500, detail=str(e))



@app.post("/configure")

async def configure_system(config: SystemConfig):

    """Reconfigure system settings."""

    global llm_instance, conversation_manager

    

    try:

        if config.model_name and (llm_instance is None or config.model_name != llm_instance.model_name):

            logger.info(f"Loading model: {config.model_name}")

            if llm_instance is not None:

                llm_instance.unload_model()

            

            llm_instance = LocalLLM(model_name=config.model_name, use_quantization=True)

            llm_instance.load_model()

        

        if config.system_prompt is not None or config.max_context_tokens is not None:

            conversation_manager = ConversationManager(

                system_prompt=config.system_prompt or "You are a helpful AI assistant.",

                max_context_tokens=config.max_context_tokens or 2048

            )

        

        return JSONResponse({"status": "success", "message": "System reconfigured"})

        

    except Exception as e:

        logger.error(f"Configuration error: {e}", exc_info=True)

        raise HTTPException(status_code=500, detail=str(e))



@app.get("/export")

async def export_conversation():

    """Export current conversation."""

    if conversation_manager is None:

        raise HTTPException(status_code=503, detail="System not initialized")

    return JSONResponse(conversation_manager.export_conversation())



if __name__ == "__main__":

    uvicorn.run(app, host="0.0.0.0", port=8000, log_level="info")


Key Improvements and Fixes:

1. Error Corrections:

  • Fixed model loading to allow starting without a pre-loaded model
  • Added proper model unloading to free memory
  • Fixed status endpoint to handle no-model-loaded state
  • Added proper error handling for all model operations


2. New Model Management Features:


ModelManager Class:

  • get_cached_models() - Lists all locally cached models
  • search_models() - Searches HuggingFace Hub
  • download_model() - Downloads models with progress tracking
  • delete_model() - Removes cached models
  • get_download_progress() - Tracks download status


New API Endpoints:

  • GET /models/cached - Get cached models
  • POST /models/search - Search HuggingFace
  • POST /models/download - Download a model
  • GET /models/download/progress/{model_id} - Get download progress
  • POST /models/load - Load a model into memory
  • DELETE /models/delete/{model_id} - Delete a cached model


3. Enhanced UI:


Model Manager Modal:

  • Two tabs: "Cached Models" and "Search & Download"
  • Search bar for finding models
  • Model cards showing:
    • Model name and metadata
    • Download count and likes
    • Size on disk (for cached models)
    • Load/Download/Delete buttons
  • Real-time download progress bars
  • Visual feedback for current loaded model

Improved Chat Interface:

  • Shows current loaded model in sidebar
  • Prevents chatting without a loaded model
  • Better status indicators
  • Welcome screen with direct access to Model Manager


4. Usage Instructions:


# Install dependencies

pip install torch transformers fastapi uvicorn pydantic accelerate bitsandbytes huggingface-hub


# Run the application

python main.py


Open browser to: http://localhost:8000


To use:

  1. Click "Model Manager" button
  2. Search for models (e.g., "mistral", "phi-2", "llama")
  3. Click "Download" on desired model
  4. Wait for download to complete
  5. Click "Load Model" to load it into memory
  6. Start chatting!


This complete solution provides a professional model management system with download, caching, loading, and deletion capabilities.