import os import gradio as gr import torch from unsloth import FastLanguageModel # Check for GPU availability device = "cuda" if torch.cuda.is_available() else "cpu" print(f"Using device: {device}") # Initialize variables model = None tokenizer = None model_loaded = False # Load model with proper error handling try: print("Loading model...") model, tokenizer = FastLanguageModel.from_pretrained( model_name="BARKEM/qwen3-8b-eko-lora-conversation-3", max_seq_length=2048, dtype=None, load_in_4bit=True, ) FastLanguageModel.for_inference(model) model_loaded = True print("Model loaded successfully!") except Exception as e: print(f"Error loading model: {e}") model_loaded = False def respond( message, history: list[dict[str, str]], system_message="You are a helpful assistant.", max_tokens=150, temperature=0.8, top_p=0.95, hf_token="", ): if not model_loaded or model is None or tokenizer is None: return "Error: Model failed to load. Please check the logs." try: # Build conversation history with proper context messages = [{"role": "system", "content": system_message}] # Add conversation history (Gradio ChatInterface provides history as list of dicts) for chat in history: if "role" in chat and "content" in chat: messages.append({ "role": chat["role"], "content": chat["content"] }) # Add the current message messages.append({"role": "user", "content": message}) # Limit context length to prevent token overflow max_history_pairs = 8 # Keep last 8 exchanges + system message if len(messages) > (max_history_pairs * 2 + 2): # Keep system message and recent history messages = [messages[0]] + messages[-(max_history_pairs * 2 + 1):] print(f"Processing {len(messages)} messages in conversation context") # Apply chat template with full conversation context inputs = tokenizer.apply_chat_template( messages, tokenize=True, add_generation_prompt=True, return_tensors="pt" ) # Check input length and truncate if necessary max_input_length = 1800 # Leave room for generation if inputs.shape[1] > max_input_length: print(f"Input too long ({inputs.shape[1]} tokens), truncating to {max_input_length}") inputs = inputs[:, -max_input_length:] # Move to appropriate device if device == "cuda" and torch.cuda.is_available(): inputs = inputs.to("cuda") print("Moved inputs to CUDA") # Generate response with specified parameters print(f"Generating with max_tokens={max_tokens}, temp={temperature}, top_p={top_p}") with torch.no_grad(): # Save memory outputs = model.generate( input_ids=inputs, max_new_tokens=min(max_tokens, 400), # Cap at 400 for safety use_cache=True, do_sample=True, temperature=temperature, top_p=top_p, pad_token_id=tokenizer.eos_token_id, eos_token_id=tokenizer.eos_token_id, ) # Decode the full response full_response = tokenizer.batch_decode(outputs, skip_special_tokens=False)[0] input_text = tokenizer.batch_decode(inputs, skip_special_tokens=False)[0] # Extract only the new generated text if input_text in full_response: response = full_response.replace(input_text, "").strip() else: response = full_response # Clean up response by removing special tokens and extracting assistant content special_tokens = ["<|im_start|>", "<|im_end|>", "<|endoftext|>"] for token in special_tokens: response = response.replace(token, "") # Handle assistant tag specifically if "assistant" in response: parts = response.split("assistant", 1) if len(parts) > 1: response = parts[1].strip() response = response.strip() # Fallback if response is empty if not response or len(response.strip()) < 2: response = "I apologize, but I couldn't generate a proper response. Please try again." print(f"Generated response: {response[:100]}...") return response except Exception as e: error_msg = f"Error generating response: {str(e)}" print(error_msg) return error_msg # Create the chat interface with comprehensive controls demo = gr.ChatInterface( respond, type="messages", title="Eko, aspiring human", description="Chat with Eko, the beginning of what will be the next gen human like AI using only a small language model (Qwen3-8B), final version wont just sound like one, you will be convinced it is one.", theme=gr.themes.Soft(), additional_inputs=[ gr.Textbox( value="", label="System Message", placeholder="Experiment with the AI's personality and behavior... (Human like interaction is hardwired)", lines=2 ), gr.Slider( minimum=1, maximum=400, value=150, step=1, label="Max New Tokens", info="Maximum number of new tokens to generate" ), gr.Slider( minimum=0.1, maximum=2.0, value=0.7, step=0.1, label="Temperature", info="Higher = more creative, Lower = more focused" ), gr.Slider( minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (Nucleus Sampling)", info="Diversity of token selection" ), gr.Textbox( value="", label="HuggingFace Token (Optional)", type="password", placeholder="Optional: for private model access" ), ], ) # Add custom CSS for better appearance demo.css = """ .gradio-container { max-width: 1200px !important; margin: auto; } """ if __name__ == "__main__": demo.launch( share=False, # Set to True if you want a public link server_name="0.0.0.0", server_port=7860, show_error=True )