Running LLMs locally used to be a serious pain, requiring complex setups and a hefty GPU investment. Ollama changes that dramatically. It provides a remarkably straightforward way to download, manage, and run LLMs – think Docker for LLMs – on your own machine. This post walks you through building a Python-based AI chatbot leveraging Ollama, accessible both via a command-line interface (CLI) and a simple web interface. We'll cover the essentials, discuss practical considerations, and provide working code examples. This isn't a tutorial for beginners—you should have a basic understanding of Python and its ecosystem.
Why bother with local LLMs? Data privacy is a big one. Keeping data on-premise eliminates the need to send user queries to third-party APIs, a crucial requirement for many applications. Cost is another factor – API usage can quickly become expensive. And finally, offline operation offers unmatched reliability. With Ollama and a downloaded model, your chatbot keeps functioning even without an internet connection.
Setting up the Foundation
Before we dive into the code, ensure you have the prerequisites in place. First, install Ollama: follow the instructions on the Ollama website. Once installed, pull down a model. I'll use qwen3:1.7b for this example – it’s relatively lightweight and performs well:
$ ollama pull qwen3:1.7bNext, create a Python virtual environment and install the dependencies:
$ python -m venv venv
$ source venv/bin/activate
$ pip install ollama flaskThe CLI Chatbot: Core Logic
Let's start with the CLI implementation. The core of the chatbot lies in managing conversation history and interacting with the Ollama API.
import ollama
def chat_with_ollama(ai_model="qwen3:1.7b"):
history = []
while True:
user_input = input("You: ")
if user_input.lower() in ["exit", "quit"]:
break
history.append({"role": "user", "content": user_input})
response = ollama.chat(
model=ai_model,
messages=history,
stream=True,
think=False # Disable thinking steps for cleaner output
)
bot_message_content = ""
for chunk in response:
text = chunk.message.content or ""
print(text, end="", flush=True)
bot_message_content += text
history.append({"role": "assistant", "content": bot_message_content})
print()
return history
if __name__ == "__main__":
chat_history = chat_with_ollama()
print("Chat history:", chat_history)This script initializes an empty history list. It then enters a loop, prompting the user for input. User input is added to the history. The ollama.chat() function, critically, uses stream=True to get the response in chunks, which allows us to display the bot’s progress in real-time. think=False prevents the model from showing intermediate thinking steps, resulting in a cleaner user experience. Finally, the bot’s response is added to the history, and the loop repeats.
Here’s what it looks like in action — notice how responses stream in character by character:
Adding a Web Interface with Flask
To make the chatbot accessible via a web interface, we’ll use Flask. Here’s a Flask application that integrates the chat_with_ollama function:
from flask import Flask, render_template, request
import ollama
app = Flask(__name__)
@app.route("/", methods=["GET", "POST"])
def index():
chat_history = []
error = None
if request.method == "POST":
user_input = request.form.get("user_input", "").strip()
if not user_input:
error = "Enter a message first."
elif len(user_input) > 4000:
error = "Keep your message under 4,000 characters."
else:
chat_history.append({"role": "user", "content": user_input})
try:
response = ollama.chat(
model="qwen3:1.7b", messages=chat_history, think=False
)
chat_history.append({
"role": "assistant", "content": response.message.content
})
except (ollama.ResponseError, ConnectionError):
error = "Ollama is unavailable. Check the server and model."
return render_template("index.html", chat_history=chat_history, error=error)
if __name__ == "__main__":
app.run(host="127.0.0.1", port=5000)This Flask app exposes a single route /. When a GET request is received, it renders the index.html template (which we'll create next). When a POST request is received (triggered by submitting the form), it retrieves the user’s input from the form, calls chat_with_ollama to get the bot's response, stores the updated chat history and renders the index.html template again.
Save this as app.py and run python app.py. Each form submission makes one request to Ollama and renders one question and answer; it does not retain conversation history between requests. The request handler never reads from terminal input.
Create a template file named templates/index.html:
<!DOCTYPE html>
<html>
<head>
<title>Ollama Chatbot</title>
</head>
<body>
<h1>Ollama Chatbot</h1>
<div id="chat-container">
{% for message in chat_history %}
<div class="message {% if message.role == 'user' %}user{% else %}bot{% endif %}">
{{ message.content }}
</div>
{% endfor %}
</div>
{% if error %}<p role="alert">{{ error }}</p>{% endif %}
<form method="post">
<input type="text" name="user_input" placeholder="Type your message...">
<button type="submit">Send</button>
</form>
</body>
</html>This basic HTML template displays the chat_history and provides a simple form for user input. CSS styling can be added for a more polished look.
Gotchas and Tips
- Hardware Requirements: Running LLMs locally is resource-intensive. Even smaller models like
qwen3:1.7bbenefit from at least 8GB of RAM. Larger models require significantly more. Monitor your system's resource usage to avoid performance bottlenecks. - Model Selection: Different models offer varying trade-offs between speed and quality. Experiment with different models available through Ollama to find the best fit for your needs.
llama2:7b-chatandmistral:7b-instructare other popular choices. - Context Window: LLMs have a limited context window – the amount of text they can consider when generating a response. Long conversations can exceed this window, leading to the bot "forgetting" earlier parts of the conversation. Consider implementing strategies to manage the context window (e.g., summarizing earlier parts of the conversation).
- Error Handling: The code examples provided are simplified. In a production environment, you’d want to add robust error handling to catch exceptions and provide informative error messages to the user. This includes handling cases where the Ollama API is unavailable or the model fails to respond.
- Security: If you’re deploying the web application publicly, be mindful of security considerations. Sanitize user input to prevent cross-site scripting (XSS) attacks and implement appropriate authentication and authorization mechanisms.
Running the Web App
After running the Flask application, you can interact with it in your browser at http://127.0.0.1:5000/. Here's the app starting up and responding to a curl request:
Project Structure
Here's what the final project layout looks like:
What to do next? Expand the web interface with styling (CSS), add user authentication, experiment with different LLMs, and explore more advanced features like prompt engineering and response filtering. A particularly useful next step would be implementing a mechanism to save the chat history to a file or database for later review or analysis. Explore Ollama's Modelfile to configure prompts and model parameters; creating a Modelfile does not train or fine-tune model weights.