Spaces:
Runtime error

File size: 1,519 Bytes
8d34fa1
4852346
8d34fa1
 
5ee38aa
 
55d7625
9400b51
816d153
 
5ee38aa
9400b51
 
 
 
 
ab0f5a8
 
 
 
9400b51
ab0f5a8
 
 
 
 
 
 
5ee38aa
ab0f5a8
9400b51
 
 
 
 
ab0f5a8
9400b51
 
5ee38aa
8d34fa1
 
 
5ee38aa
ab0f5a8
473dfc1
ab0f5a8
 
473dfc1
 
 
 
250465b
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
import gradio as gr
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

# Load the TinyLlama model
model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float32)

# Define chatbot function
def chat_with_tinyllama(user_input):
    # Add context to the prompt to guide the model
    prompt = f"Question: {user_input}\nAnswer:"

    # Tokenize input
    inputs = tokenizer(prompt, return_tensors="pt").to("cpu")

    # Generate a response
    outputs = model.generate(
        **inputs,
        max_new_tokens=150,  # Limit response length
        do_sample=True,
        temperature=0.7,
        top_p=0.9,
        repetition_penalty=1.2
    )

    # Decode the output
    response = tokenizer.decode(outputs[0], skip_special_tokens=True)

    # Extract the answer part (removing repeated prompt)
    if "Answer:" in response:
        response = response.split("Answer:")[1].strip()

    # Ensure the model gives an actual answer
    if response.strip().lower() == user_input.strip().lower():
        return "I don't have an answer for that yet. Can you ask another way?"

    return response

# Create Gradio UI
chatbot = gr.Interface(
    fn=chat_with_tinyllama,
    inputs=gr.Textbox(lines=2, placeholder="Ask me a question..."),
    outputs="text",
    title="💬 TinyLlama Chatbot",
    description="A chatbot powered by TinyLlama."
)

# Launch app
chatbot.launch()