Dari Nol Hingga Deployment: Chatbot dengan FastAPI dan React
Dalam artikel ini, kita akan membuat chatbot menggunakan FastAPI (backend), React (frontend), dan Ollama sebagai LLM.
Teknologi yang Digunakan
- FastAPI → Backend API untuk menangani request dari frontend.
- React (Vite/Next.js) → Frontend untuk UI chatbot.
- Ollama → Model LLM yang menangani respons.
- Railway/Vercel → Hosting backend dan frontend.
- Ngrok → Untuk mengekspos Ollama secara publik.
Langkah 1: Instalasi & Persiapan Environment
Pertama, kita perlu menyiapkan environment pengembangan dengan menginstal semua dependensi yang dibutuhkan.
1.1. Install FastAPI dan Dependensi
Buat virtual environment dan install FastAPI:
python -m venv env
source env/bin/activate
pip install fastapi uvicorn langchain_ollama pydantic
1.2. Install Ollama
Ollama adalah LLM yang berjalan lokal. Install Ollama di sistem:
curl -fsSL https://ollama.ai/install.sh | sh
Pull model Llama 3.3
ollama pull llama3.3:70b-instruct-q4_K_M
Kemudian, jalankan Ollama:
ollama serve
1.3. Install React untuk Frontend
Jalankan perintah berikut untuk membuat aplikasi React:
npx create-react-app frontend
cd frontend
npm install axios
Langkah 2: Instal Ngrok
Ngrok adalah tools untuk mengekspos lokal komputer ke internet, yang memungkinkan kita untuk membuat Ollama dapat diakses oleh Railway.
2.1. Download & Install Ngrok
Silahkan ikut langkah instalasi disini.
https://dashboard.ngrok.com/get-started/setup/linux
2.2. Verifikasi Versi Ngrok
ngrok --version
Jika sudah benar, akan muncul seperti ini.
2.3. Start Ngrok
Setelah Ngrok terinstal, ekspos server Ollama lokal Anda:
ngrok http 11434
Setelah dijalankan, akan muncul public URL yang berekstensi .ngrok-free.app seperti gambar berikut. Simpan URL tersebut, karena akan digunakan pada backend FastAPI.
Langkah 3: Implementasi FastAPI (Backend)
3.1. Buat Direktori Backend
mkdir backend && cd backend
3.2. Buat File app.py
Ganti parameter ‘base_url’ dengan public URL dari ngrok.
from fastapi import FastAPI
from langchain_ollama import ChatOllama
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
import logging
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Load the model
local_llm = "llama3.3:70b-instruct-q4_K_M"
llm = ChatOllama(
model=local_llm,
temperature=0,
base_url="https://1234-567-89-011-123.ngrok-free.app" # ganti dengan Public URL dari ngrok Anda
)
# Define a request model
class QueryRequest(BaseModel):
question: str
logging.basicConfig(level=logging.INFO)
@app.post("/query/")
def query(request: QueryRequest):
try:
logging.info(f"Received query: {request.question}")
response = llm.invoke(request.question)
logging.info(f"Generated response: {response}")
if isinstance(response, dict) and "content" in response:
return {"response": response["content"]}
elif hasattr(response, "content"):
return {"response": response.content}
else:
return {"response": str(response)}
except Exception as e:
logging.error(f"Error processing query: {e}")
return {"response": f"Error in processing query: {str(e)}"}
Langkah 4: Deployment Backend di Railway
4.1. Deploy dengan Docker
Tambahkan file bernama Dockerfile in backend
(backend/Dockerfile):
# Use a lightweight Python image
FROM python:3.9
# Set the working directory
WORKDIR /app
# Copy only the requirements file first (to optimize caching)
COPY requirements.txt ./
# Install dependencies
RUN pip install - no-cache-dir -r requirements.txt
# Copy the rest of the application code
COPY . .
# Expose FastAPI port
EXPOSE 8000
# Run FastAPI app
CMD ["uvicorn", "app:app", " - host", "0.0.0.0", " - port", "8000"]
Kemudian, build dan run backend dalam sebuah kontainer:
docker build -t backend .
docker run -p 8000:8000 backend
4.2. Tambahkan requirements.txt
Di dalam backend/requirements.txt
:
fastapi
uvicorn
langchain_ollama
4.3. Pengaturan Railway
- Pastikan Anda sudah masukkan proyek anda di Github.
- Buka https://railway.com/ → Klik “New Project” → Pilih “Deploy from GitHub”.
- Pilih repositori GitHub Anda.
- Di “Settings”, tetapkan Direktori Root ke backend/.
5. Klik “Deploy”.
Setelah deployment, akan mendapatkan public FastAPI URL seperti ini:
https://my-fastapi-chatbot.up.railway.app
Langkah 5: Implementasi React (Frontend)
Edit file App.js
di frontend/src/
seperti pada kode berikut. Ganti API_URL
dengan public FastAPI URL dari Railway.
import React, { useState } from "react";
import axios from "axios";
import { Container, TextField, Button, Typography, Paper, CircularProgress } from "@mui/material";
function App() {
const [question, setQuestion] = useState("");
const [response, setResponse] = useState("");
const [loading, setLoading] = useState(false);
const API_URL = "https://my-fastapi-chatbot.up.railway.app/query/"; // Pakai backend URL Anda
const handleSubmit = async () => {
setLoading(true);
try {
const res = await axios.post(API_URL, { question });
// Extract response content
if (res.data.response && typeof res.data.response === "object") {
setResponse(res.data.response.content || "No response content.");
} else {
setResponse(res.data.response || "No response available.");
}
} catch (error) {
console.error("Error fetching response:", error);
setResponse("Error fetching response. Please try again.");
}
setLoading(false);
};
return (
<Container maxWidth="md" style={{ textAlign: "center", marginTop: "50px" }}>
<Paper elevation={3} style={{ padding: "20px", borderRadius: "10px" }}>
<Typography variant="h4" gutterBottom>
Chatbot
</Typography>
<TextField
label="Ask a question..."
variant="outlined"
fullWidth
value={question}
onChange={(e) => setQuestion(e.target.value)}
style={{ marginBottom: "20px" }}
/>
<Button
variant="contained"
color="primary"
onClick={handleSubmit}
disabled={loading}
>
{loading ? <CircularProgress size={24} color="inherit" /> : "Submit"}
</Button>
{response && (
<Paper
elevation={2}
style={{
marginTop: "20px",
padding: "15px",
backgroundColor: "#f5f5f5",
borderRadius: "5px",
}}
>
<Typography>{response}</Typography>
</Paper>
)}
</Paper>
</Container>
);
}
export default App;
Jalankan frontend:
npm start
Langkah 6: Deployment Frontend di Vercel
6.1. Login ke Vercel
- Buka https://vercel.com/ → Klik “New Project”.
- Pilih GitHub repository.
- Pada “Settings”, pilih Root Directory ke
frontend/
.
4. Instal Vercel CLI
npm install -g vercel
5. Deploy Frontend
vercel deploy --prod
6. Klik URL pada Production dan hasilnya akan muncul di web.
Informasi Tambahan
Railway berubah otomatis ketika update
Jika kode github terdapat perubahan (setelah di push), Railway akan secara otomatis mengupdate deployment-nya.
Pastikan semua servis selalu berjalan
Karena Ngrok, Ollama, dan npm harus selalu berjalan, gunakan tmux
agar layanan tidak mati ketika terminal ditutup. Lebih detil silahkan lihat tutorial berikut.
GitHub repository private dapat digunakan
GitHub repository private bisa digunakan untuk Railway dan Vercel, tetapi tetap memerlukan akses OAuth ke GitHub agar deployment tetap berjalan.
Penutup
Semoga artikel ini membantu Anda dalam membuat dan mengembangkan chatbot sendiri! Jika ada pertanyaan atau kendala, jangan ragu untuk berdiskusi di kolom komentar. 🚀🔥
Jangan lupa bagikan artikel ini jika bermanfaat! 🙌