File size: 2,067 Bytes
4716fd7
 
12a3a98
 
4716fd7
 
284b0c2
4716fd7
 
 
12a3a98
8d5e154
12a3a98
4716fd7
 
 
 
 
 
 
12a3a98
4716fd7
 
 
 
 
 
 
 
 
 
 
12a3a98
4716fd7
 
 
12a3a98
4716fd7
 
 
 
 
 
 
ac63131
 
4716fd7
 
 
 
 
 
 
 
 
 
12a3a98
4716fd7
12a3a98
 
4716fd7
 
 
 
 
12a3a98
 
 
4716fd7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
import gradio as gr

# Initialize model and tokenizer
model = AutoModelForCausalLM.from_pretrained(
    "microsoft/Phi-3.5-mini-instruct",
    trust_remote_code=True,
    torch_dtype=torch.float32,  # Force float32 for CPU compatibility
)

tokenizer = AutoTokenizer.from_pretrained("microsoft/Phi-3.5-mini-instruct")

# Create pipeline
pipe = pipeline(
    "text-generation",
    model=model,
    tokenizer=tokenizer,
    device=-1,  # Force CPU usage (-1 = CPU)
)

def respond(message, chat_history):
    # Format the chat history with system prompt
    system_prompt = "You are a helpful AI assistant."
    messages = [{"role": "system", "content": system_prompt}]
    
    # Add previous chat history
    for user_msg, bot_msg in chat_history:
        messages.append({"role": "user", "content": user_msg})
        messages.append({"role": "assistant", "content": bot_msg})
    
    # Add new user message
    messages.append({"role": "user", "content": message})
    
    # Format for the model
    formatted_input = tokenizer.apply_chat_template(
        messages,
        tokenize=False,
        add_generation_prompt=True
    )
    
    # Generate response
    generation_args = {
        "max_new_tokens": 200,  # Reduced for CPU performance
        "temperature": 0.7,
        "do_sample": True,
    }
    
    output = pipe(formatted_input, **generation_args)
    response = output[0]['generated_text']
    
    # Remove the input text from the response
    if response.startswith(formatted_input):
        response = response[len(formatted_input):]
    
    return response

# Create Gradio interface
demo = gr.ChatInterface(
    respond,
    chatbot=gr.Chatbot(height=400),
    textbox=gr.Textbox(placeholder="Ask me anything...", container=False, scale=7),
    title="Phi-3 Mini Chat (CPU)",
    examples=["What's 2x + 3 = 7?", "How to make banana smoothie?", "Explain quantum computing simply"],
    cache_examples=False,
)

if __name__ == "__main__":
    demo.launch()