Building a ChatGPT-like Web App with Ollama
In this chapter we will build a ChatGPT-like application: multi-session switching, history persistence to a database, a complete front-end interface, and three deployment methods.
Feature planning and data model
A usable chat product needs at least four capabilities: multi-session isolation, history persistence, streaming replies, and session management (create and delete).
The database model supporting these capabilities needs only two tables:
chats stores the session list, and messages stores each message grouped by foreign key. When switching sessions, assemble the corresponding messages into Ollama's messages array to restore the full context.
The tech stack follows the minimal-dependency principle: Flask + sqlite3 (Python standard library) + native JavaScript front end, with zero front-end frameworks.
Install the flask and ollama extensions:
pip install flask ollama
Load the model:
ollama pull qwen3.5:4b
Back end: the complete API for sessions and messages
The back end has clear responsibilities: manage the two tables and write each streaming reply from /api/chat to the database.
Example
File path: server.py
import
json
import
sqlite3
from
flask
import
Flask
,
request
,
Response
,
jsonify
,
stream_with_context
from
ollama
import
chat
app
=
Flask
(
name
)
DB
=
'chats.db'
def
db
(
)
:
"""Open a database connection, return rows as dictionaries"""
conn
=
sqlite3.
connect
(
DB
)
conn.
row_factory
=
sqlite3.
Row
return
conn
def
init_db
(
)
:
with
db
(
)
as
conn:
conn.
executescript
(
'''
CREATE TABLE IF NOT EXISTS chats(
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS messages(
id INTEGER PRIMARY KEY AUTOINCREMENT,
chat_id INTEGER NOT NULL,
role TEXT NOT NULL,
content TEXT NOT NULL
);
'''
)
init_db
(
)
Session list
@
app.
get
(
'/api/chats'
)
def
list_chats
(
)
:
with
db
(
)
as
conn:
rows
=
conn.
execute
(
'SELECT id, title, created_at FROM chats ORDER BY id DESC'
)
.
fetchall
(
)
return
jsonify
(
[
dict
(
r
)
for
r
in
rows
]
)
New session
@
app.
post
(
'/api/chats'
)
def
create_chat
(
)
:
title
=
(
request.
json
or
{
}
)
.
get
(
'title'
,
'New session'
)
with
db
(
)
as
conn:
cur
=
conn.
execute
(
'INSERT INTO chats(title) VALUES (?)'
,
(
title
,
)
)
return
jsonify
(
{
'id'
: cur.
lastrowid
,
'title'
: title
}
)
Delete a session (along with its messages)
@
app.
delete
(
'/api/chats/int:cid'
)
def
delete_chat
(
cid
)
:
with
db
(
)
as
conn:
conn.
execute
(
'DELETE FROM messages WHERE chat_id=?'
,
(
cid
,
)
)
conn.
execute
(
'DELETE FROM chats WHERE id=?'
,
(
cid
,
)
)
return
jsonify
(
{
'ok'
:
True
}
)
Read the history of a session
@
app.
get
(
'/api/chats/int:cid/messages'
)
def
get_messages
(
cid
)
:
with
db
(
)
as
conn:
rows
=
conn.
execute
(
'SELECT role, content FROM messages WHERE chat_id=? ORDER BY id'
,
(
cid
,
)
)
.
fetchall
(
)
return
jsonify
(
[
dict
(
r
)
for
r
in
rows
]
)
Back-end core: streaming chat and history write-back
The chat endpoint does three things: fetch history to build context, generate in streaming mode, and write the complete reply back to the database.
Example
Append to server.py
@
app.
post
(
'/api/chat'
)
def
do_chat
(
)
:
data
=
request.
get_json
(
)
cid
,
user_input
=
data
[
'chat_id'
]
,
data
[
'message'
]
Fetch history (including the just-inserted user message) as the model context
with
db
(
)
as
conn:
conn.
execute
(
'INSERT INTO messages(chat_id, role, content) VALUES (?,?,?)'
,
(
cid
,
'user'
,
user_input
)
)
history
=
[
dict
(
r
)
for
r
in
conn.
execute
(
'SELECT role, content FROM messages WHERE chat_id=? ORDER BY id'
,
(
cid
,
)
)
]
messages
=
[
{
'role'
:
'system'
,
'content'
:
'You are the RUNOOB programming assistant; answer accurately and concisely.'
}
]
messages +
=
history
def
generate
(
)
:
reply
=
''
stream
=
chat
(
model
=
'qwen3.5:4b'
,
messages
=
messages
,
stream
=
True
)
for
chunk
in
stream:
reply +
=
chunk
.
message
.
content
Push to the front end chunk by chunk as NDJSON
yield
json.
dumps
(
{
'delta'
:
chunk
.
message
.
content
}
,
ensure_ascii
=
False
)
'\n'
Key point: write the complete reply back to the database to form persistent memory
with
db
(
)
as
conn:
conn.
execute
(
'INSERT INTO messages(chat_id, role, content) VALUES (?,?,?)'
,
(
cid
,
'assistant'
,
reply
)
)
yield
json.
dumps
(
{
'done'
:
True
}
,
ensure_ascii
=
False
)
'\n'
return
Response
(
stream_with_context
(
generate
(
)
)
,
mimetype
=
'application/x-ndjson'
)
Home page: return the front-end page
@
app.
get
(
'/'
)
def
index
(
)
:
return
open
(
'index.html'
,
encoding
=
'utf-8'
)
.
read
(
)
if
name
==
'main'
:
app.
run
(
port
=
5000
)
Front end: a native JS chat interface
The front end is fully functional yet simple enough: session list on the left, message area plus input box on the right, with fetch streaming rendering.
Example
Local ChatGPT
Start and access:
python server.py
Open http://localhost:5000 in a browser to see the generated page.
Verify three core functions: switching sessions on the left fully restores history; different new sessions do not interfere with each other; after restarting server.py the history still exists (persisted to chats.db).
Deployment: three levels
| Level | Approach | Notes |
|---|---|---|
| Local personal use | Run python server.py directly | Listens on 127.0.0.1 by default, secure |
| Intranet sharing | app.run(host='0.0.0.0'), members access http://server-IP:5000 | No authentication; be sure to add Nginx Basic Auth (see the private deployment chapter) |
| Long-term operation on a cloud server | Register a systemd service + Nginx reverse proxy + domain name | First ollama pull the model on the server |
Use systemd on the cloud server to keep the app running:
Example
File path: /etc/systemd/system/runoob-chat.service
[Unit]
Description
=
Runoob Chat Web App
After
=
network.target ollama.service
[Service]
WorkingDirectory
=
/opt/runoob-chat
ExecStart
=
/usr/bin/python3 server.py
Restart
=
always
RestartSec
=
3
[Install]
WantedBy
=
multi-user.target
Configure long-term operation:
sudo systemctl daemon-reload
sudo systemctl enable --now runoob-chat
The complete security checklist for external deployment (loopback ports, reverse-proxy authentication, exposure self-check) is in the security and compliance chapter; be sure to go through it before going live.