Mở Đầu: Khi Chatbot Thương Mại Điện Tử Cần "Nói Chuyện" Với Hệ Thống Kho Hàng

Tưởng tượng bạn điều hành một cửa hàng trực tuyến với 50,000 sản phẩm. Mỗi ngày, đội ngũ chăm sóc khách hàng phải trả lời hàng trăm câu hỏi như: "Còn hàng không?", "Giá bao nhiêu?", "Giao trong bao lâu?". Đó là lúc Function Calling phát huy sức mạnh.

Bài viết này sẽ hướng dẫn bạn xây dựng một chatbot thông minh có thể tự động truy vấn database, kiểm tra tồn kho, và đặt hàng — tất cả thông qua Function Calling của OpenAI API.

Function Calling Là Gì?

Function Calling là tính năng cho phép mô hình AI nhận diện khi nào cần gọi một hàm (function) bên ngoài để lấy dữ liệu hoặc thực hiện hành động. Thay vì AI tự "bịa" thông tin, nó sẽ:

Kiến Trúc Hệ Thống

+------------------+     +------------------+     +------------------+
|   Người Dùng     | --> |   Chatbot AI     | --> |  OpenAI API      |
|   (Frontend)     |     |   (Backend)      |     |  (Function Call) |
+------------------+     +------------------+     +------------------+
                                |
                                v
                         +------------------+
                         |  Functions xử lý |
                         |  - check_stock   |
                         |  - get_price     |
                         |  - create_order  |
                         +------------------+
                                |
                                v
                         +------------------+
                         |  Database/System |
                         |  (Kho hàng CRM)  |
                         +------------------+

Triển Khai Chi Tiết Với HolySheep AI

Chúng ta sẽ sử dụng HolySheep AI — nền tảng API tương thích 100% với OpenAI, với chi phí tiết kiệm đến 85% so với API gốc (chỉ từ $0.42/MTok cho DeepSeek V3.2).

Bước 1: Cài Đặt Môi Trường

# Tạo virtual environment
python -m venv venv
source venv/bin/activate  # Windows: venv\Scripts\activate

Cài đặt thư viện cần thiết

pip install openai python-dotenv fastapi uvicorn

Bước 2: Định Nghĩa Functions

import openai
from typing import Optional
import json

Cấu hình HolySheep AI

client = openai.OpenAI( api_key="YOUR_HOLYSHEEP_API_KEY", base_url="https://api.holysheep.ai/v1" )

Định nghĩa các functions cho hệ thống thương mại điện tử

functions = [ { "type": "function", "function": { "name": "check_product_stock", "description": "Kiểm tra số lượng tồn kho của sản phẩm", "parameters": { "type": "object", "properties": { "product_id": { "type": "string", "description": "Mã sản phẩm cần kiểm tra" } }, "required": ["product_id"] } } }, { "type": "function", "function": { "name": "get_product_price", "description": "Lấy giá hiện tại của sản phẩm", "parameters": { "type": "object", "properties": { "product_id": { "type": "string", "description": "Mã sản phẩm" }, "quantity": { "type": "integer", "description": "Số lượng mua (để tính giá sỉ)" } }, "required": ["product_id"] } } }, { "type": "function", "function": { "name": "create_order", "description": "Tạo đơn hàng mới", "parameters": { "type": "object", "properties": { "product_id": {"type": "string"}, "quantity": {"type": "integer"}, "customer_name": {"type": "string"}, "shipping_address": {"type": "string"} }, "required": ["product_id", "quantity", "customer_name"] } } } ]

Database giả lập

product_database = { "SP001": {"name": "Laptop Dell XPS 15", "stock": 25, "price": 28990000}, "SP002": {"name": "iPhone 15 Pro Max", "stock": 0, "price": 34990000}, "SP003": {"name": "Tai nghe Sony WH-1000XM5", "stock": 150, "price": 8990000} }

Bước 3: Triển Khai Logic Xử Lý Functions

def execute_function(function_name: str, arguments: dict) -> dict:
    """Xử lý các function calls"""
    
    if function_name == "check_product_stock":
        product_id = arguments.get("product_id")
        product = product_database.get(product_id)
        
        if not product:
            return {"error": "Sản phẩm không tồn tại"}
        
        return {
            "product_id": product_id,
            "name": product["name"],
            "stock": product["stock"],
            "available": product["stock"] > 0
        }
    
    elif function_name == "get_product_price":
        product_id = arguments.get("product_id")
        quantity = arguments.get("quantity", 1)
        product = product_database.get(product_id)
        
        if not product:
            return {"error": "Sản phẩm không tồn tại"}
        
        base_price = product["price"]
        # Giảm giá 10% nếu mua >= 5 sản phẩm
        discount = 0.1 if quantity >= 5 else 0
        final_price = base_price * (1 - discount) * quantity
        
        return {
            "product_id": product_id,
            "unit_price": base_price,
            "quantity": quantity,
            "discount_percent": discount * 100,
            "total_price": int(final_price)
        }
    
    elif function_name == "create_order":
        product_id = arguments.get("product_id")
        quantity = arguments.get("quantity")
        customer_name = arguments.get("customer_name")
        
        product = product_database.get(product_id)
        if not product:
            return {"error": "Sản phẩm không tồn tại"}
        
        if product["stock"] < quantity:
            return {
                "success": False,
                "message": f"Không đủ hàng. Chỉ còn {product['stock']} sản phẩm"
            }
        
        # Tạo đơn hàng (trong thực tế sẽ ghi vào database)
        order_id = f"ORD{int(time.time())}"
        
        return {
            "success": True,
            "order_id": order_id,
            "product": product["name"],
            "quantity": quantity,
            "customer": customer_name,
            "total": product["price"] * quantity
        }
    
    return {"error": "Function không được hỗ trợ"}

Bước 4: Xây Dựng Chatbot Hoàn Chỉnh

import time

def chatbot_response(user_message: str) -> str:
    """Xử lý tin nhắn người dùng với Function Calling"""
    
    messages = [
        {"role": "system", "content": """Bạn là trợ lý bán hàng thân thiện của cửa hàng công nghệ.
Khi khách hỏi về sản phẩm, bạn phải:
- Kiểm tra tồn kho trước khi xác nhận đặt hàng
- Trả lời bằng tiếng Việt, thân thiện
- Nếu hết hàng, gợi ý sản phẩm thay thế"""},
        {"role": "user", "content": user_message}
    ]
    
    # Gọi API lần đầu - AI quyết định có cần gọi function không
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=messages,
        tools=functions,
        tool_choice="auto"
    )
    
    assistant_message = response.choices[0].message
    
    # Kiểm tra xem có function call không
    if assistant_message.tool_calls:
        messages.append(assistant_message)
        
        # Xử lý từng function call
        for tool_call in assistant_message.tool_calls:
            function_name = tool_call.function.name
            arguments = json.loads(tool_call.function.arguments)
            
            # Thực thi function
            result = execute_function(function_name, arguments)
            
            # Thêm kết quả vào conversation
            messages.append({
                "role": "tool",
                "tool_call_id": tool_call.id,
                "content": json.dumps(result, ensure_ascii=False)
            })
        
        # Gọi API lần 2 với kết quả từ function
        final_response = client.chat.completions.create(
            model="gpt-4o-mini",
            messages=messages,
            tools=functions
        )
        
        return final_response.choices[0].message.content
    
    # Không có function call - trả lời trực tiếp
    return assistant_message.content

Demo

if __name__ == "__main__": print("=== Chatbot Thương Mại Điện Tử ===\n") test_messages = [ "Còn hàng laptop Dell không?", "Cho tôi hỏi giá iPhone 15 Pro Max", "Tôi muốn đặt 2 cái tai nghe Sony" ] for msg in test_messages: print(f"👤 Khách hàng: {msg}") print(f"🤖 Chatbot: {chatbot_response(msg)}\n")

Tối Ưu Chi Phí Với HolySheep AI

Khi sử dụng HolySheep AI, bạn được hưởng các ưu đãi đặc biệt:

ModelGiá/MTok (2026)Phù hợp cho
GPT-4.1$8Tác vụ phức tạp
Claude Sonnet 4.5$15Phân tích chuyên sâu
Gemini 2.5 Flash$2.50Ứng dụng production
DeepSeek V3.2$0.42Chi phí tối ưu

Ứng Dụng Nâng Cao: RAG System Với Function Calling

Bạn có thể mở rộng Function Calling để xây dựng hệ thống RAG (Retrieval Augmented Generation) cho doanh nghiệp:

functions_rag = [
    {
        "type": "function",
        "function": {
            "name": "search_knowledge_base",
            "description": "Tìm kiếm thông tin trong cơ sở kiến thức công ty",
            "parameters": {
                "type": "object",
                "properties": {
                    "query": {"type": "string", "description": "Câu hỏi tìm kiếm"},
                    "department": {"type": "string", "enum": ["HR", "IT", "Sales", "Legal"]}
                }
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "get_employee_info",
            "description": "Lấy thông tin nhân viên",
            "parameters": {
                "type": "object",
                "properties": {
                    "employee_id": {"type": "string"},
                    "info_type": {"type": "string", "enum": ["contact", "team", "leave"]}
                }
            }
        }
    }
]

Lỗi Thường Gặp Và Cách Khắc Phục

1. Lỗi "Invalid API Key"

Nguyên nhân: API key không đúng hoặc chưa được cấu hình đúng.

Cách khắc phục:

# Sai - sử dụng endpoint OpenAI gốc
client = openai.OpenAI(api_key="sk-xxx", base_url="https://api.openai.com/v1")

Đúng - sử dụng HolySheep AI

client = openai.OpenAI( api_key="YOUR_HOLYSHEEP_API_KEY", base_url="https://api.holysheep.ai/v1" # Quan trọng! )

2. Function Không Được Gọi

Nguyên nhân: Model không nhận diện được intent hoặc prompt system chưa rõ ràng.

Cách khắc phục:

3. JSON Parse Error Khi Đọc Arguments

Nguyên nhân: Arguments từ model có thể không đúng format JSON hoặc thiếu trường.

Cách khắc phục:

# Xử lý an toàn khi parse arguments
try:
    arguments = json.loads