Các công cụ kéo thả rất nhanh cho bản thử nghiệm, nhưng khi cần tích hợp sâu vào hệ thống bán hàng, tùy biến giao diện riêng và kiểm soát từng đồng API, viết AI Agent bằng Python là con đường bền vững nhất. Tin vui là bạn không cần cài framework cồng kềnh: chỉ với khoảng 100 dòng Python sạch sẽ và FastAPI, bạn sẽ tự tay làm ra một ứng dụng web trợ lý đặt hàng chạy thật ngay trên máy.
Tại sao nên tự dựng vòng lặp Agent trước khi dùng Framework?
Thực chất phía sau mọi nền tảng agent nổi tiếng đều chỉ là một vòng lặp for đơn giản: gửi tin nhắn kèm danh sách hàm cho mô hình → nếu mô hình trả về yêu cầu gọi hàm (function_call) thì Python chạy hàm đó rồi nhét kết quả vào lại lịch sử → lặp cho đến khi mô hình trả lời bằng văn bản cuối cùng.
Bước 1. Tạo cấu trúc dự án và cài đặt thư viện
Tạo một thư mục mới tên order-agent gồm đúng 5 tệp sau:
order-agent/
├── .env
├── requirements.txt
├── agent.py
├── app.py
└── static/
└── index.html
Mở Terminal tại thư mục order-agent và chạy các lệnh sau để tạo môi trường ảo và cài 4 thư viện cần thiết:
python3 -m venv .venv source .venv/bin/activate # Trên Windows dùng: .venv\Scripts\activate pip install openai fastapi uvicorn python-dotenv
Tạo tệp .env chứa khóa API của bạn (tuyệt đối không đẩy tệp này lên GitHub):
OPENAI_API_KEY=sk-proj-dien-khoa-cua-ban-vao-day
Bước 2. Viết lõi AI Agent và 3 công cụ thật trong agent.py
Chúng ta sẽ xây dựng Trợ lý Kiểm kho, Tính phí vận chuyển & Lập phiếu đặt hàng nháp. Ba hàm nghiệp vụ nằm ngay trong Python, còn OpenAI SDK dùng Responses API để mô hình tự chọn gọi hàm theo ngữ cảnh. Chép toàn bộ mã nguồn sau vào agent.py:
import json
from datetime import datetime
from pathlib import Path
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv()
client = OpenAI()
MODEL = "gpt-4o-mini"
# Kho mẫu thực tế (trong sản phẩm thật bạn thay bằng truy vấn SQLite/PostgreSQL)
KHO_HANG = {
"TN-02": {"ten": "Tai nghe chống ồn Pro X2", "gia": 1490000, "ton": 8, "kg": 0.4},
"BP-01": {"ten": "Bàn phím cơ không dây K8", "gia": 1850000, "ton": 2, "kg": 1.1},
"CH-05": {"ten": "Chuột công thái học M5", "gia": 790000, "ton": 0, "kg": 0.2},
}
SYSTEM_PROMPT = """Bạn là trợ lý hỗ trợ đặt hàng của cửa hàng thiết bị công nghệ.
Quy tắc bắt buộc:
- Luôn gọi công cụ tra_ton_kho trước khi báo giá hay xác nhận còn hàng.
- Nếu khách hỏi phí giao hàng, gọi tinh_phi_van_chuyen dựa trên khối lượng sản phẩm.
- Chỉ gọi tao_don_nhap khi đã có đủ: tên khách, số điện thoại, mã sản phẩm và số lượng hợp lệ.
- Không tự bịa mã sản phẩm hay giảm giá. Trả lời tiếng Việt ngắn gọn, rõ ràng."""
def tra_ton_kho(ma_sp: str) -> dict:
sp = KHO_HANG.get(ma_sp.strip().upper())
if not sp:
return {"tim_thay": False, "thong_bao": f"Không có mã {ma_sp}. Các mã hiện có: TN-02, BP-01, CH-05."}
return {"tim_thay": True, "ma_sp": ma_sp.upper(), **sp}
def tinh_phi_van_chuyen(tinh_thanh: str, khoi_luong_kg: float) -> dict:
tinh = tinh_thanh.lower()
phi_co_ban = 22000 if ("hồ chí minh" in tinh or "hà nội" in tinh) else 35000
phu_phi = max(0, round((khoi_luong_kg - 0.5) * 10000))
return {"tinh_thanh": tinh_thanh, "phi_ship": phi_co_ban + phu_phi, "du_kien_ngay": "1-3 ngày"}
def tao_don_nhap(ten_khach: str, sdt: str, ma_sp: str, so_luong: int) -> dict:
ma = ma_sp.strip().upper()
sp = KHO_HANG.get(ma)
if not sp:
return {"thanh_cong": False, "ly_do": "Mã sản phẩm không tồn tại."}
if so_luong <= 0 or sp["ton"] < so_luong:
return {"thanh_cong": False, "ly_do": f"Kho chỉ còn {sp['ton']} sản phẩm {ma}."}
don = {
"thoi_gian": datetime.now().isoformat(timespec="seconds"),
"ten_khach": ten_khach.strip(),
"sdt": sdt.strip(),
"ma_sp": ma,
"so_luong": so_luong,
"tam_tinh": sp["gia"] * so_luong,
"trang_thai": "cho_nhan_vien_xac_nhan",
}
with Path("don_nhap.jsonl").open("a", encoding="utf-8") as f:
f.write(json.dumps(don, ensure_ascii=False) + "\n")
return {"thanh_cong": True, "don_nhap": don}
TOOL_MAP = {
"tra_ton_kho": tra_ton_kho,
"tinh_phi_van_chuyen": tinh_phi_van_chuyen,
"tao_don_nhap": tao_don_nhap,
}
TOOLS = [
{
"type": "function",
"name": "tra_ton_kho",
"description": "Tra cứu tên, đơn giá, số lượng tồn kho và khối lượng theo mã sản phẩm.",
"parameters": {
"type": "object",
"properties": {"ma_sp": {"type": "string", "description": "Mã sản phẩm, ví dụ TN-02"}},
"required": ["ma_sp"],
"additionalProperties": False,
},
"strict": True,
},
{
"type": "function",
"name": "tinh_phi_van_chuyen",
"description": "Tính phí vận chuyển theo tỉnh thành và tổng khối lượng đơn hàng (kg).",
"parameters": {
"type": "object",
"properties": {
"tinh_thanh": {"type": "string"},
"khoi_luong_kg": {"type": "number"},
},
"required": ["tinh_thanh", "khoi_luong_kg"],
"additionalProperties": False,
},
"strict": True,
},
{
"type": "function",
"name": "tao_don_nhap",
"description": "Lưu đơn đặt hàng nháp vào hệ thống để nhân viên gọi xác nhận với khách.",
"parameters": {
"type": "object",
"properties": {
"ten_khach": {"type": "string"},
"sdt": {"type": "string"},
"ma_sp": {"type": "string"},
"so_luong": {"type": "integer"},
},
"required": ["ten_khach", "sdt", "ma_sp", "so_luong"],
"additionalProperties": False,
},
"strict": True,
},
]
def run_agent(history: list[dict], max_steps: int = 6) -> dict:
items = list(history)
tool_logs = []
for _ in range(max_steps):
res = client.responses.create(
model=MODEL,
instructions=SYSTEM_PROMPT,
input=items,
tools=TOOLS,
temperature=0.2,
)
items.extend(res.output)
calls = [o for o in res.output if o.type == "function_call"]
if not calls:
return {"reply": res.output_text, "tools_used": tool_logs}
for call in calls:
fn = TOOL_MAP.get(call.name)
args = json.loads(call.arguments)
result = fn(**args) if fn else {"error": f"Không có công cụ {call.name}"}
tool_logs.append({"tool": call.name, "args": args, "result": result})
items.append({
"type": "function_call_output",
"call_id": call.call_id,
"output": json.dumps(result, ensure_ascii=False),
})
return {"reply": "Yêu cầu vượt quá số bước xử lý cho phép, bạn hãy chia nhỏ câu hỏi nhé.", "tools_used": tool_logs}
Bước 3. Đóng gói API FastAPI và Giao diện web dùng ngay
Tạo tệp app.py để mở API chat và phục vụ giao diện web tại cổng 8000:
from fastapi import FastAPI
from fastapi.responses import FileResponse
from pydantic import BaseModel
from agent import run_agent
app = FastAPI(title="Order AI Agent")
SESSIONS: dict[str, list[dict]] = {}
class ChatReq(BaseModel):
session_id: str
message: str
@app.get("/")
def home():
return FileResponse("static/index.html")
@app.post("/api/chat")
def chat(req: ChatReq):
history = SESSIONS.setdefault(req.session_id, [])
history.append({"role": "user", "content": req.message})
out = run_agent(history)
history.append({"role": "assistant", "content": out["reply"]})
# Giữ tối đa 16 lượt gần nhất để tiết kiệm token
SESSIONS[req.session_id] = history[-16:]
return out
Tiếp theo tạo static/index.html — một giao diện chat gọn nhẹ hiển thị cả câu trả lời lẫn danh sách công cụ mà Agent vừa âm thầm gọi:
<!doctype html>
<html lang="vi">
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Trợ lý Đặt hàng AI Agent</title>
<style>
body{font-family:system-ui,sans-serif;max-width:720px;margin:32px auto;padding:0 16px;background:#f6f8fc}
#log{background:#fff;border:1px solid #dbe3ef;border-radius:14px;padding:16px;min-height:340px;overflow:auto}
.msg{margin:10px 0;padding:10px 14px;border-radius:10px;white-space:pre-wrap}
.u{background:#1c3d6e;color:#fff;margin-left:18%}.a{background:#eef3fb;margin-right:10%}
.tools{font-size:12px;color:#2f6bd0;margin-top:6px}
form{display:flex;gap:8px;margin-top:12px}input{flex:1;padding:11px;border-radius:10px;border:1px solid #cbd5e1}
button{padding:11px 18px;border:0;border-radius:10px;background:#1c3d6e;color:#fff;font-weight:700;cursor:pointer}
</style>
<h2>Trợ lý Đặt hàng AI Agent (Python + FastAPI)</h2>
<div id="log"></div>
<form id="f"><input id="q" placeholder="Hỏi tồn kho mã TN-02, phí ship đi Đà Nẵng..." required><button>Gửi</button></form>
<script>
const sid='web-'+Math.random().toString(36).slice(2), log=document.getElementById('log'), q=document.getElementById('q');
function add(cls,text,tools){
const d=document.createElement('div'); d.className='msg '+cls; d.textContent=text;
if(tools&&tools.length){const t=document.createElement('div');t.className='tools';t.textContent='Tool đã gọi: '+tools.map(x=>x.tool).join(' → ');d.appendChild(t);}
log.appendChild(d); log.scrollTop=log.scrollHeight;
}
document.getElementById('f').onsubmit=async(e)=>{
e.preventDefault(); const msg=q.value.trim(); if(!msg)return; q.value=''; add('u',msg);
const r=await fetch('/api/chat',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({session_id:sid,message:msg})});
const data=await r.json(); add('a',data.reply,data.tools_used);
};
</script>
</html>
Bước 4. Khởi chạy và kiểm thử chuỗi nhiều Tool cùng lúc
Chạy máy chủ FastAPI ngay tại Terminal:
uvicorn app:app --reload --port 8000
Mở trình duyệt tại http://localhost:8000 và thử gõ một câu hỏi gộp nhiều yêu cầu cùng lúc:
"Kiểm tra giúp mình tai nghe mã TN-02 còn đủ 3 cái không, tính luôn phí ship đi Đà Nẵng và tạo giúp mình đơn nháp tên Minh, SĐT 0909123456 nhé."
Bạn sẽ thấy ngay dưới câu trả lời dòng nhật ký: Tool đã gọi: tra_ton_kho → tinh_phi_van_chuyen → tao_don_nhap, đồng thời tệp don_nhap.jsonl vừa được ghi thêm một dòng JSON hoàn chỉnh sẵn sàng chuyển cho bộ phận kho xử lý.
Nâng cấp từ bản chạy trên máy lên sản phẩm phục vụ khách thật
| Hạng mục | Trong bài mẫu | Khi chạy thật trên VPS/Cloud |
|---|---|---|
| Lưu phiên hội thoại | Biến từ điển SESSIONS trong RAM | Lưu vào Redis hoặc PostgreSQL để không mất khi khởi động lại server |
| Dữ liệu kho & đơn | Dict tĩnh + tệp .jsonl | Kết nối cơ sở dữ liệu SQLite / PostgreSQL hoặc API phần mềm bán hàng |
| Giới hạn & bảo mật | Mở công khai cổng 8000 | Đặt sau Nginx HTTPS, thêm giới hạn tốc độ (rate limit) theo IP và timeout 20 giây |
| Hiển thị phản hồi | Chờ xong toàn bộ mới trả về | Dùng Server-Sent Events (SSE) truyền từng chữ để người dùng thấy phản hồi tức thì |
Để mở rộng sản phẩm này kết nối với nhiều nguồn dữ liệu nội bộ qua chuẩn chung, xem tiếp hướng dẫn tự viết MCP Server bằng Python và cẩm nang kiểm thử & vận hành AI Agent trên Production.