Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Chat Bot Code

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

Step 1: install ollama

Step 2: ollama run llama3.2:3b

Step 3: .\chatbot\Scripts\activate.bat – terminal

pip install langchain langchain-ollama ollama

pip install flask

app.py file

from flask import Flask, render_template, request, jsonify


from langchain_ollama import OllamaLLM
from langchain_core.prompts import ChatPromptTemplate

app = Flask(__name__)

template = """
Answer the question below.

Here is the conversation history: {context}

Question: {question}

Answer:
"""

model = OllamaLLM(model="llama3.2:3b")
prompt = ChatPromptTemplate.from_template(template)
chain = prompt | model

@app.route('/')
def home():
return render_template('index.html')

@app.route('/chat', methods=['POST'])
def chat():
user_input = request.form['message']
context = request.form['context']

# Generate a response using the chain


result = chain.invoke({"context": context.strip(), "question":
user_input.strip()})

# Format the result to make it more readable


formatted_result = format_response(result)
# Update context
new_context = f"{context}\nUser: {user_input}\nBot:
{formatted_result}"

return jsonify({'response': formatted_result, 'context':


new_context})

def format_response(response):
# Format the response (example: replace newlines with <br> for
HTML)
return response.replace('\n', '<br>').strip() # Add any additional
formatting as needed

if __name__ == '__main__':
app.run(debug=True)

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0"> <!-- Viewport meta tag -->
<title>Chatbot</title>
<link rel="stylesheet" href="{{ url_for('static',
filename='styles.css') }}">
</head>
<body>
<div class="chat-container">
<div id="chat-box"></div>
<div class="input-container">
<input type="text" id="user-input" placeholder="Type a
message..." />
<button id="send-button">Send</button>
</div>
</div>

<script>
let context = ""; // To keep track of conversation history

function sendMessage() {
var userInput = document.getElementById('user-
input').value;
if (userInput.trim() === "") return; // Ignore empty input
document.getElementById('chat-box').innerHTML +=
"<div>User: " + userInput + "</div>";
document.getElementById('user-input').value = "";

fetch('/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-
urlencoded',
},
body: 'message=' + encodeURIComponent(userInput) +
'&context=' + encodeURIComponent(context)
})
.then(response => response.json())
.then(data => {
document.getElementById('chat-box').innerHTML +=
"<div>Bot: " + data.response + "</div>";
context = data.context; // Update context with the new
conversation history
});
}

document.getElementById('send-button').onclick = sendMessage;

// Allow sending message with Enter key


document.getElementById('user-
input').addEventListener('keypress', function(event) {
if (event.key === 'Enter') {
sendMessage();
event.preventDefault(); // Prevent form submission if
it's within a form element
}
});
</script>
</body>
</html>

Styles.css

body {
font-family: Arial, sans-serif;
background-color: #f4f4f4; /* Light background */
padding: 20px;
margin: 0; /* Remove default margin */
}

.chat-container {
max-width: 800px; /* Increased width for larger screens */
width: 100%; /* Make it responsive */
margin: 0 auto;
background: white; /* White background */
border-radius: 8px;
padding: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); /* Light shadow */
}

#chat-box {
height: 600px; /* Increased height */
overflow-y: auto; /* Scrollable chat box */
border: 1px solid #ddd; /* Light gray border */
padding: 10px;
margin-bottom: 10px;
background-color: #f9f9f9; /* Light background for better
visibility */
}

/* Scrollbar styling */
#chat-box::-webkit-scrollbar {
width: 8px; /* Width of the scrollbar */
}

#chat-box::-webkit-scrollbar-thumb {
background-color: #28a745; /* Color of the scrollbar thumb */
border-radius: 10px; /* Round edges */
}

#chat-box::-webkit-scrollbar-thumb:hover {
background-color: #218838; /* Darker color on hover */
}

.input-container {
display: flex; /* Use flexbox for input and button alignment */
gap: 10px; /* Space between input and button */
}

input[type="text"] {
flex: 1; /* Allow input to grow */
padding: 10px;
border: 1px solid #ddd; /* Light gray border */
border-radius: 20px; /* Curvy input */
}

button {
padding: 10px 15px; /* Button padding */
background-color: #28a745; /* Green button */
color: white; /* White text */
border: none; /* No border */
border-radius: 20px; /* Curvy button */
cursor: pointer; /* Pointer on hover */
}

button:hover {
background-color: #218838; /* Darker green on hover */
}

button:active {
background-color: #1e7e34; /* Even darker green when pressed */
}

input[type="text"]:focus {
border-color: #28a745; /* Change border color on focus */
outline: none; /* Remove default outline */
}

/* Responsive styles */
@media (max-width: 600px) {
#chat-box {
height: 400px; /* Reduced height for smaller screens */
}

.input-container {
flex-direction: column; /* Stack input and button */
gap: 5px; /* Space between input and button */
}

button {
width: 100%; /* Full width for button on mobile */
}
}

You might also like