Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Build a Chatbot with Streamlit and Llama

· 6 min read · Home Tech

In this article
  1. Background: Why Streamlit and Llama?
  2. What You Need Before Starting
  3. How It Works: The Basic Architecture
  4. Step-by-Step: Building the Streamlit App
  5. Choosing the Right Llama Model
  6. Common Problems and How to Fix Them
  7. Comparing Local vs. Hosted Llama
  8. Costs and Safety Considerations
  9. Frequently Asked Questions

Yes, you can build a chatbot with Streamlit and Llama, and it’s a practical way to create a web interface for a local or API‑based large language model. This guide walks you through the core components, the code, and the common pitfalls so you can go from idea to working prototype in an afternoon.

Background: Why Streamlit and Llama?

Streamlit is a Python library that turns scripts into interactive web apps with minimal boilerplate. Instead of writing HTML, CSS, and JavaScript, you describe the UI with Python calls, and Streamlit handles the rendering. It’s especially popular for data science and machine learning demos because it natively supports chat widgets, dataframes, and live updates.

Llama (Meta’s open‑source large language model family) is a strong choice for self‑hosted chatbots because it runs on consumer hardware when quantized, and it doesn’t require sending data to a third party. You can load a model via the transformers library or use a quantized version with llama-cpp-python. Alternatively, you can call a hosted Llama endpoint (like Replicate or Together) if you prefer not to manage GPU resources.

What You Need Before Starting

  • Python 3.9+ and a virtual environment (venv or conda).
  • Streamlit – install with pip install streamlit.
  • A Llama model – either a local file (e.g., llama-2-7b-chat.Q4_K_M.gguf) or access to a hosted API.
  • GPU (optional) – for local models, a GPU with at least 8 GB VRAM is recommended for 7B models; CPU‑only works but is slower.
  • An API key – if using a hosted service like Replicate or Together.

How It Works: The Basic Architecture

The chatbot has three parts: the Streamlit UI, a backend that calls the model, and a way to maintain conversation history. Streamlit provides a st.chat_message and st.chat_input to build the chat interface. When the user sends a message, you append it to a list of messages, pass the whole list to the Llama model, and then display the response.

For local models, you can use llama-cpp-python with a GGUF file, or transformers with a Hugging Face model. The latter is more flexible but uses more memory. Here’s a minimal example using llama-cpp-python:

from llama_cpp import Llama
llm = Llama(model_path="llama-2-7b-chat.Q4_K_M.gguf")
response = llm("Hello, how are you?", max_tokens=100)
print(response["choices"][0]["text"])

For hosted APIs, you’d use the provider’s SDK (e.g., replicate or together) and pass the conversation history in the request.

Step-by-Step: Building the Streamlit App

  1. Create a new Python file (e.g., app.py).
  2. Import Streamlit and your model library.
  3. Initialize the model – load it once at the top of the script, using @st.cache_resource to avoid reloading on every rerun.
  4. Set up the chat UI – use st.title and a container for messages.
  5. Maintain session state – store the conversation in st.session_state.messages as a list of dicts with “role” and “content”.
  6. Handle user input – when st.chat_input returns a string, append it to the messages, then call the model, and append the response.
  7. Display messages – loop through the session state and render each with st.chat_message.

Here’s a skeleton you can adapt:

import streamlit as st
from llama_cpp import Llama

@st.cache_resource
def load_model():
    return Llama(model_path="llama-2-7b-chat.Q4_K_M.gguf")

llm = load_model()

if "messages" not in st.session_state:
    st.session_state.messages = []

for msg in st.session_state.messages:
    with st.chat_message(msg["role"]):
        st.write(msg["content"])

prompt = st.chat_input("Ask me anything")
if prompt:
    st.session_state.messages.append({"role": "user", "content": prompt})
    with st.chat_message("user"):
        st.write(prompt)
    with st.chat_message("assistant"):
        response = llm(prompt, max_tokens=256)
        answer = response["choices"][0]["text"]
        st.write(answer)
        st.session_state.messages.append({"role": "assistant", "content": answer})

Run it with streamlit run app.py and you’ll have a working chatbot.

Choosing the Right Llama Model

Not all Llama models are the same. The original Llama 2 has sizes 7B, 13B, and 70B. Llama 3 (8B, 70B) and Llama 3.2 (1B, 3B) are newer and generally better. For a chatbot, you want a “chat” or “instruct” variant, which is fine‑tuned for dialogue. Quantized versions (GGUF) reduce memory usage, but may lose a bit of quality. For a quick demo, a 7B or 8B model with Q4 quantization is a good balance.

If you have no GPU, consider using a hosted API. Many providers offer free tiers or low‑cost usage. The trade‑off is that your data goes to a third party, so for sensitive information, local is safer.

Common Problems and How to Fix Them

  • Model loads slowly – Use @st.cache_resource to load once. For large models, consider using a smaller quantized version.
  • Out‑of‑memory errors – Reduce the model size, lower the context window, or use CPU offloading (e.g., n_gpu_layers=-1 in llama-cpp).
  • Responses are too long or cut off – Set max_tokens appropriately, and handle the case where the model doesn’t end with a stop token.
  • Chat history not preserved – Make sure you store messages in st.session_state and pass the full history to the model.
  • Streamlit reruns the whole script – That’s normal; use caching and avoid heavy operations outside of cached functions.

Comparing Local vs. Hosted Llama

Local models give you privacy, no per‑token costs, and offline capability. The downsides are hardware requirements and setup complexity. Hosted APIs are easier to use, scale automatically, and often have lower latency if you don’t have a GPU. But they cost money per token and require sending your data to the provider. For a hobby project, local is fine; for production, you might start with hosted and later move to your own infrastructure.

Costs and Safety Considerations

Running a local model has no direct cost beyond electricity and hardware. A hosted API charges per token – for example, Llama 3 8B on Replicate is about $0.0002 per token (as of early 2025, but prices change). For a typical conversation of 500 tokens, that’s a fraction of a cent. However, if you deploy a public app, you should add rate limiting and authentication to avoid abuse.

Safety is important: LLMs can generate biased or harmful content. For a public bot, you should add a moderation layer (e.g., filtering prompts and responses) and clearly state that the bot is AI‑generated. For local use, you’re responsible for what you generate. Also, be cautious about prompt injection – if your bot processes user input that includes instructions, it might be manipulated. Keep that in mind if you connect it to other tools.

Frequently Asked Questions

Can I use a free GPU for this?

Yes, Google Colab offers a free Tesla T4 with 16 GB VRAM, which can run a 7B model with quantization. You’ll need to install Streamlit in the notebook and use st.experimental_rerun or a public tunnel like ngrok to access the app. Be aware that Colab sessions are limited and may disconnect.

What’s the difference between Llama 2 and Llama 3?

Llama 3 is the successor, with better performance on benchmarks, a larger vocabulary, and support for longer context windows (up to 8K tokens by default). It also comes in smaller sizes (1B and 3B) that run on CPU. For a new project, Llama 3 is generally recommended.

How do I add memory to the chatbot?

Memory is just conversation history. Store all messages in st.session_state and pass them to the model as a single prompt (e.g., with special tokens like <|begin_of_text|> for Llama 3). For long conversations, you may need to truncate old messages to fit the context window.

Can I deploy this to the cloud?

Yes, you can deploy a Streamlit app to Streamlit Community Cloud for free, or to a platform like Hugging Face Spaces, Heroku, or a VM. For local models, you’ll need a VM with a GPU. For hosted APIs, you can deploy on a free tier as long as you keep the API key secure.

Why does my bot repeat the user’s input?

That usually happens because the model isn’t receiving the correct chat format. Llama models expect a specific structure (e.g., <|start_header_id|>user<|end_header_id|>...<|eot_id|>). If you pass plain text, the model may just echo it. Use the model’s tokenizer or a chat template to format the input correctly.