Mở Đầu: Cuộc Đua Chi Phí AI Năm 2026
Khi các đội ngũ phát triển AI chuyển từ giai đoạn thử nghiệm sang triển khai thực tế, câu hỏi về tối ưu chi phí trở nên cấp bách hơn bao giờ hết. Dữ liệu giá tháng 5 năm 2026 đã được xác minh rõ ràng qua các benchmark độc lập. Mô hình GPT-4.1 của OpenAI có chi phí 8 USD cho mỗi triệu token đầu vào, trong khi Claude Sonnet 4.5 của Anthropic đạt mức 15 USD/MTok. Google Gemini 2.5 Flash duy trì vị thế cạnh tranh với 2.50 USD/MTok, và đáng chú ý nhất, DeepSeek V3.2 chỉ ở mức 0.42 USD/MTok. Khi tính toán chi phí cho một hệ thống xử lý 10 triệu token mỗi tháng với tỷ lệ 70% đầu vào và 30% đầu ra, sự chênh lệch giữa các nhà cung cấp trở nên rõ ràng qua bảng phân tích chi phí hàng tháng dưới đây.
Với mức giá này, việc tích hợp một lớp quản lý API thông minh có thể giảm đáng kể chi phí vận hành cho các đội ngũ加密风控 (mã hóa kiểm soát rủi ro). HolySheep AI cung cấp gateway trung tâm với tỷ giá hối đoái 1 USD tương đương 1 yuan, giúp các nhà phát triển Trung Quốc tiết kiệm được 85% chi phí so với các giải pháp quốc tế truyền thống. Độ trễ dưới 50ms và tín dụng miễn phí khi đăng ký tại https://www.holysheep.ai/register càng tăng thêm sức hấp dẫn của nền tảng này.
Tardis Và BitMart Funding Rate: Tại Sao Dữ Liệu Này Quan Trọng
Trong hệ sinh thái perpetual futures (hợp đồng tương lai vĩnh cửu), funding rate (tỷ lệ tài trợ) đóng vai trò như cơ chế neo giá, đảm bảo giá hợp đồng không chênh lệch quá xa so với giá spot (giá giao ngay). BitMart, với khối lượng giao dịch đáng kể trên thị trường châu Á, cung cấp dữ liệu funding rate mà các nhà giao dịch chênh lệch giá (arbitrage) và bot giao dịch tần suất cao sử dụng làm tín hiệu vào lệnh.
Dịch vụ Tardis cung cấp API truy cập dữ liệu lịch sử và real-time từ nhiều sàn giao dịch, bao gồm BitMart. Tuy nhiên, việc xây dựng pipeline lưu trữ và giám sát bất thường cho dữ liệu này đòi hỏi kiến trúc phức tạp. Bài viết này sẽ hướng dẫn bạn cách sử dụng HolySheep AI làm gateway trung tâm để tích hợp Tardis API với chi phí tối ưu nhất.
Kiến Trúc Hệ Thống Tổng Quan
Hệ thống giám sát funding rate hoàn chỉnh bao gồm bốn thành phần chính. Đầu tiên, Tardis API đóng vai trò nguồn dữ liệu, cung cấp endpoint truy cập funding rate history và real-time của BitMart. Thứ hai, HolySheep AI hoạt động như proxy gateway, cho phép gọi Tardis thông qua unified API với khả năng retry tự động, rate limiting, và caching thông minh. Thứ ba, database layer sử dụng TimescaleDB hoặc InfluxDB để lưu trữ chuỗi thời gian, với khả năng query hiệu quả cho dữ liệu tài chính. Cuối cùng, monitoring dashboard giúp phát hiện bất thường và cảnh báo khi funding rate vượt ngưỡng.
Với mô hình này, đội ngũ加密风控 có thể xây dựng các pipeline phân tích phức tạp mà không cần lo lắng về rate limit hay chi phí API explosion. Đặc biệt, khi sử dụng DeepSeek V3.2 với chi phí chỉ 0.42 USD/MTok cho các tác vụ phân tích dữ liệu thường ngày, ngân sách vận hành giảm đáng kể.
Triển Khai Chi Tiết
Cài Đặt Môi Trường Và Dependencies
Trước khi bắt đầu, bạn cần cài đặt các thư viện cần thiết cho Python và Node.js. Dưới đây là script setup hoàn chỉnh giúp bạn nhanh chóng có môi trường làm việc.
# Python dependencies
pip install requests pandas sqlalchemy timescale-open-tsdb \
holy sheep-sdk alerts-Lib python-dotenv
Hoặc sử dụng requirements.txt
cat > requirements.txt << 'EOF'
requests==2.31.0
pandas==2.2.0
sqlalchemy==2.0.25
timescale-db==2.1.0
holy-sheep-sdk==1.4.2
python-dotenv==1.0.1
httpx==0.27.0
asyncio==3.4.3
EOF
pip install -r requirements.txt
Node.js dependencies cho monitoring service
mkdir -p tardis-monitor && cd tardis-monitor
npm init -y
npm install @holysheep/api-gateway tardis-client \
@timescale/sdk prom-client express
Cấu Hình API Keys Và Environment Variables
Bước tiếp theo là thiết lập các biến môi trường cần thiết. HolySheep yêu cầu API key riêng, và bạn cũng cần Tardis API key để truy cập dữ liệu BitMart. Quan trọng là KHÔNG BAO GIỜ hardcode credentials trong source code.
# File: .env (không commit file này lên git)
cat > .env << 'EOF'
HolySheep Configuration
HOLYSHEEP_API_KEY=YOUR_HOLYSHEEP_API_KEY
HOLYSHEEP_BASE_URL=https://api.holysheep.ai/v1
HOLYSHEEP_MODEL=deepseek-v3.2
Tardis Configuration
TARDIS_API_KEY=your_tardis_api_key_here
TARDIS_EXCHANGE=bitmart
TARDIS_MARKET_TYPE=perp
Database Configuration
TIMESCALE_HOST=localhost
TIMESCALE_PORT=5432
TIMESCALE_USER=postgres
TIMESCALE_PASSWORD=your_secure_password
TIMESCALE_DATABASE=funding_rate_db
Alert Configuration
ALERT_WEBHOOK_URL=https://your-alert-system.com/webhook
ANOMALY_THRESHOLD_PCT=15.0
EOF
Load biến môi trường
export $(cat .env | grep -v '^#' | xargs)
Xây Dựng Data Fetcher Service Với HolySheep Proxy
Service này chịu trách nhiệm gọi Tardis API thông qua HolySheep gateway, xử lý response, và lưu trữ vào TimescaleDB. HolySheep cung cấp khả năng retry tự động với exponential backoff, giúp hệ thống ổn định hơn khi Tardis có latency spike.
# File: data_fetcher.py
import os
import time
import json
import requests
import pandas as pd
from datetime import datetime, timedelta
from sqlalchemy import create_engine, text
from dotenv import load_dotenv
load_dotenv()
class TardisFundingRateFetcher:
"""Fetcher dữ liệu funding rate từ Tardis qua HolySheep gateway"""
def __init__(self):
self.holysheep_key = os.getenv('HOLYSHEEP_API_KEY')
self.base_url = os.getenv('HOLYSHEEP_BASE_URL') # https://api.holysheep.ai/v1
self.tardis_key = os.getenv('TARDIS_API_KEY')
self.exchange = os.getenv('TARDIS_EXCHANGE', 'bitmart')
# Kết nối TimescaleDB
db_url = f"postgresql://{os.getenv('TIMESCALE_USER')}:{os.getenv('TIMESCALE_PASSWORD')}@"
db_url += f"{os.getenv('TIMESCALE_HOST')}:{os.getenv('TIMESCALE_PORT')}/"
db_url += os.getenv('TIMESCALE_DATABASE')
self.db = create_engine(db_url)
def call_tardis_via_holysheep(self, symbol, start_time, end_time):
"""
Gọi Tardis API thông qua HolySheep gateway
HolySheep hỗ trợ caching và retry tự động
"""
# Sử dụng HolySheep để gọi Tardis thông qua unified endpoint
tardis_url = f"https://api.tardis.dev/v1/fees/funding-rate/{self.exchange}/{symbol}"
payload = {
"model": "tardis-proxy",
"messages": [
{
"role": "system",
"content": f"Call Tardis API: {tardis_url} with startTime={start_time}&endTime={end_time}&apiKey={self.tardis_key}"
}
],
"temperature": 0.1, # Low temperature cho structured output
"max_tokens": 8000
}
headers = {
"Authorization": f"Bearer {self.holysheep_key}",
"Content-Type": "application/json"
}
# Gọi qua HolySheep với retry logic
max_retries = 3
for attempt in range(max_retries):
try:
response = requests.post(
f"{self.base_url}/chat/completions",
headers=headers,
json=payload,
timeout=30
)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
if attempt == max_retries - 1:
raise
wait_time = 2 ** attempt
print(f"Retry {attempt + 1}/{max_retries} sau {wait_time}s: {e}")
time.sleep(wait_time)
def fetch_and_store(self, symbols, days_back=7):
"""Fetch và lưu trữ funding rate cho nhiều symbols"""
end_time = int(datetime.now().timestamp() * 1000)
start_time = int((datetime.now() - timedelta(days=days_back)).timestamp() * 1000)
results = []
for symbol in symbols:
try:
print(f"Fetching {symbol}...")
data = self.call_tardis_via_holysheep(symbol, start_time, end_time)
# Parse và transform dữ liệu
funding_rates = self._parse_tardis_response(data)
results.extend(funding_rates)
# Lưu vào TimescaleDB
self._store_to_timescale(funding_rates)
print(f" -> {len(funding_rates)} records cho {symbol}")
except Exception as e:
print(f"Lỗi khi fetch {symbol}: {e}")
continue
return results
def _parse_tardis_response(self, response):
"""Parse response từ Tardis thông qua HolySheep"""
content = response.get('choices', [{}])[0].get('message', {}).get('content', '')
# Parse JSON từ response (Tardis trả về dạng structured data)
try:
data = json.loads(content)
except:
# Fallback: extract từ text
data = json.loads(content[content.find('{'):content.rfind('}')+1])
records = []
for item in data.get('data', []):
records.append({
'symbol': item.get('symbol'),
'funding_rate': float(item.get('rate', 0)),
'mark_price': float(item.get('markPrice', 0)),
'index_price': float(item.get('indexPrice', 0)),
'timestamp': datetime.fromtimestamp(item.get('timestamp', 0)/1000)
})
return records
def _store_to_timescale(self, records):
"""Lưu records vào TimescaleDB với continuous aggregate"""
if not records:
return
df = pd.DataFrame(records)
# Insert vào hypertable
with self.db.connect() as conn:
for _, row in df.iterrows():
conn.execute(
text("""
INSERT INTO funding_rates
(symbol, funding_rate, mark_price, index_price, recorded_at)
VALUES (:symbol, :rate, :mark, :index, :ts)
"""),
{
'symbol': row['symbol'],
'rate': row['funding_rate'],
'mark': row['mark_price'],
'index': row['index_price'],
'ts': row['timestamp']
}
)
Khởi chạy fetcher
if __name__ == "__main__":
fetcher = TardisFundingRateFetcher()
# Danh sách symbols cần theo dõi
symbols = [
"BTCUSDT", "ETHUSDT", "BNBUSDT", "SOLUSDT", "XRPUSDT",
"ADAUSDT", "DOGEUSDT", "AVAXUSDT", "DOTUSDT", "MATICUSDT"
]
results = fetcher.fetch_and_store(symbols, days_back=7)
print(f"Hoàn thành: {len(results)} records tổng cộng")
Xây Dựng Anomaly Detection Với AI
Phần quan trọng nhất của hệ thống là module phát hiện bất thường. Sử dụng DeepSeek V3.2 với chi phí chỉ 0.42 USD/MTok, bạn có thể xây dựng logic phân tích phức tạp mà không lo về chi phí. Dưới đây là implementation chi tiết.
# File: anomaly_detector.py
import os
import json
import requests
from datetime import datetime, timedelta
from sqlalchemy import create_engine, text
from dotenv import load_dotenv
load_dotenv()
class FundingRateAnomalyDetector:
"""
Phát hiện bất thường funding rate sử dụng HolySheep AI
DeepSeek V3.2: $0.42/MTok - chi phí cực thấp cho phân tích
"""
def __init__(self):
self.holysheep_key = os.getenv('HOLYSHEEP_API_KEY')
self.base_url = os.getenv('HOLYSHEEP_BASE_URL')
self.threshold_pct = float(os.getenv('ANOMALY_THRESHOLD_PCT', 15.0))
self.webhook_url = os.getenv('ALERT_WEBHOOK_URL')
db_url = f"postgresql://{os.getenv('TIMESCALE_USER')}:{os.getenv('TIMESCALE_PASSWORD')}@"
db_url += f"{os.getenv('TIMESCALE_HOST')}:{os.getenv('TIMESCALE_PORT')}/"
db_url += os.getenv('TIMESCALE_DATABASE')
self.db = create_engine(db_url)
def analyze_with_ai(self, symbol, recent_rates, historical_avg, historical_std):
"""
Sử dụng AI để phân tích và đưa ra quyết định anomaly
DeepSeek V3.2 xử lý 10M tokens với chi phí chỉ ~$4.2
"""
prompt = f"""Bạn là chuyên gia phân tích funding rate perpetual futures.
Symbol: {symbol}
Recent funding rates: {recent_rates[-10:]}
Historical average: {historical_avg:.6f}
Historical std dev: {historical_std:.6f}
Current rate: {recent_rates[-1]:.6f}
Threshold: {self.threshold_pct}%
Hãy phân tích và trả về JSON:
{{
"is_anomaly": true/false,
"confidence": 0.0-1.0,
"anomaly_type": "spike"/"drop"/"volatility"/"normal",
"severity": "low"/"medium"/"high"/"critical",
"reasoning": "giải thích ngắn gọn",
"action_recommendation": "hành động khuyến nghị"
}}
"""
payload = {
"model": "deepseek-v3.2", # $0.42/MTok
"messages": [
{"role": "system", "content": "You are a crypto funding rate analyst."},
{"role": "user", "content": prompt}
],
"temperature": 0.3,
"max_tokens": 1000
}
headers = {
"Authorization": f"Bearer {self.holysheep_key}",
"Content-Type": "application/json"
}
response = requests.post(
f"{self.base_url}/chat/completions",
headers=headers,
json=payload,
timeout=30
)
response.raise_for_status()
result = response.json()
content = result['choices'][0]['message']['content']
# Parse JSON từ response
return json.loads(content[content.find('{'):content.rfind('}')+1])
def get_historical_stats(self, symbol, lookback_days=30):
"""Tính toán statistics từ dữ liệu lịch sử trong TimescaleDB"""
with self.db.connect() as conn:
result = conn.execute(
text("""
SELECT
AVG(funding_rate) as avg_rate,
STDDEV(funding_rate) as std_rate,
MIN(funding_rate) as min_rate,
MAX(funding_rate) as max_rate,
COUNT(*) as sample_count
FROM funding_rates
WHERE symbol = :symbol
AND recorded_at > NOW() - INTERVAL ':days days'
"""),
{'symbol': symbol, 'days': lookback_days}
)
row = result.fetchone()
return {
'avg': float(row[0]) if row[0] else 0,
'std': float(row[1]) if row[1] else 0,
'min': float(row[2]) if row[2] else 0,
'max': float(row[3]) if row[3] else 0,
'count': int(row[4]) if row[4] else 0
}
def get_recent_rates(self, symbol, limit=100):
"""Lấy các funding rate gần đây nhất"""
with self.db.connect() as conn:
result = conn.execute(
text("""
SELECT funding_rate
FROM funding_rates
WHERE symbol = :symbol
ORDER BY recorded_at DESC
LIMIT :limit
"""),
{'symbol': symbol, 'limit': limit}
)
return [float(row[0]) for row in result.fetchall()]
def check_all_symbols(self):
"""Kiểm tra tất cả symbols và gửi alerts nếu có anomaly"""
with self.db.connect() as conn:
result = conn.execute(text("SELECT DISTINCT symbol FROM funding_rates"))
symbols = [row[0] for row in result.fetchall()]
alerts = []
for symbol in symbols:
try:
recent = self.get_recent_rates(symbol, limit=100)
if len(recent) < 10:
continue
historical = self.get_historical_stats(symbol, lookback_days=30)
if historical['count'] < 100:
continue
# Phân tích với AI
analysis = self.analyze_with_ai(symbol, recent, historical['avg'], historical['std'])
if analysis['is_anomaly']:
alert = {
'symbol': symbol,
'timestamp': datetime.now().isoformat(),
**analysis
}
alerts.append(alert)
print(f"ALERT: {symbol} - {analysis['severity']} - {analysis['reasoning']}")
except Exception as e:
print(f"Lỗi khi phân tích {symbol}: {e}")
continue
# Gửi alerts
if alerts:
self.send_alerts(alerts)
return alerts
def send_alerts(self, alerts):
"""Gửi alerts qua webhook"""
payload = {
"alert_type": "funding_rate_anomaly",
"count": len(alerts),
"alerts": alerts,
"source": "HolySheep-Tardis-Monitor"
}
try:
requests.post(
self.webhook_url,
json=payload,
headers={"Content-Type": "application/json"},
timeout=10
)
print(f"Đã gửi {len(alerts)} alerts")
except Exception as e:
print(f"Lỗi khi gửi alerts: {e}")
Chạy detector
if __name__ == "__main__":
detector = FundingRateAnomalyDetector()
alerts = detector.check_all_symbols()
print(f"Tìm thấy {len(alerts)} anomalies")
Docker Compose Cho Toàn Bộ Hệ Thống
Để triển khai dễ dàng, bạn có thể sử dụng Docker Compose với tất cả các services cần thiết. File cấu hình dưới đây bao gồm TimescaleDB, monitoring service, và data fetcher.
# File: docker-compose.yml
version: '3.8'
services:
timescale:
image: timescale/timescaledb:latest-pg15
container_name: funding-rate-timescale
environment:
POSTGRES_USER: ${TIMESCALE_USER}
POSTGRES_PASSWORD: ${TIMESCALE_PASSWORD}
POSTGRES_DB: ${TIMESCALE_DATABASE}
ports:
- "5432:5432"
volumes:
- timescale_data:/var/lib/postgresql/data
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 10s
timeout: 5s
retries: 5
fetcher:
build:
context: .
dockerfile: Dockerfile.fetcher
container_name: funding-rate-fetcher
environment:
HOLYSHEEP_API_KEY: ${HOLYSHEEP_API_KEY}
HOLYSHEEP_BASE_URL: ${HOLYSHEEP_BASE_URL}
TARDIS_API_KEY: ${TARDIS_API_KEY}
TIMESCALE_HOST: timescale
TIMESCALE_PORT: 5432
TIMESCALE_USER: ${TIMESCALE_USER}
TIMESCALE_PASSWORD: ${TIMESCALE_PASSWORD}
TIMESCALE_DATABASE: ${TIMESCALE_DATABASE}
depends_on:
timescale:
condition: service_healthy
restart: unless-stopped
command: python data_fetcher.py
detector:
build:
context: .
dockerfile: Dockerfile.detector
container_name: funding-rate-detector
environment:
HOLYSHEEP_API_KEY: ${HOLYSHEEP_API_KEY}
HOLYSHEEP_BASE_URL: ${HOLYSHEEP_BASE_URL}
ALERT_WEBHOOK_URL: ${ALERT_WEBHOOK_URL}
ANOMALY_THRESHOLD_PCT: ${ANOMALY_THRESHOLD_PCT}
TIMESCALE_HOST: timescale
TIMESCALE_PORT: 5432
TIMESCALE_USER: ${TIMESCALE_USER}
TIMESCALE_PASSWORD: ${TIMESCALE_PASSWORD}
TIMESCALE_DATABASE: ${TIMESCALE_DATABASE}
depends_on:
timescale:
condition: service_healthy
restart: unless-stopped
command: python anomaly_detector.py
prometheus:
image: prom/prometheus:latest
container_name: funding-rate-prometheus
ports:
- "9090:9090"
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
- prometheus_data:/prometheus
command:
- '--config.file=/etc/prometheus/prometheus.yml'
- '--storage.tsdb.path=/prometheus'
grafana:
image: grafana/grafana:latest
container_name: funding-rate-grafana
ports:
- "3000:3000"
environment:
GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_PASSWORD}
volumes:
- grafana_data:/var/lib/grafana
- ./grafana/provisioning:/etc/grafana/provisioning
depends_on:
- prometheus
volumes:
timescale_data:
prometheus_data:
grafana_data:
Lỗi Thường Gặp Và Cách Khắc Phục
Lỗi 1: Lỗi Xác Thực API Key
Lỗi này xảy ra khi HolySheep API key không hợp lệ hoặc hết hạn. Response trả về HTTP 401 Unauthorized. Nguyên nhân phổ biến nhất là copy-paste key bị thiếu ký tự hoặc thừa khoảng trắng.
# Triệu chứng
requests.exceptions.HTTPError: 401 Client Error: Unauthorized
Cách khắc phục
1. Kiểm tra lại API key trong .env
cat .env | grep HOLYSHEEP_API_KEY
2. Verify key có đúng format (bắt đầu bằng hs_ hoặc sk_)
echo $HOLYSHEEP_API_KEY | head -c 5
3. Tạo key mới nếu cần tại: https://www.holysheep.ai/register
Sau đó cập nhật vào .env
4. Khởi động lại services
docker-compose down && docker-compose up -d
Lỗi 2: TimescaleDB Connection Timeout
Khi TimescaleDB container chưa ready hoặc có vấn đề network, các service khác sẽ gặp lỗi connection refused. Đây là lỗi phổ biến trong môi trường Docker khi dependency chưa fully healthy.
# Triệu chứng
sqlalchemy.exc.OperationalError: could not connect to server
Error: connection refused
Cách khắc phục
1. Kiểm tra trạng thái TimescaleDB
docker ps | grep timescale
docker logs funding-rate-timescale
2. Kiểm tra health check
docker exec funding-rate-timescale pg_isready -U postgres
3. Tăng wait time trong code
import time
def wait_for_db(max_retries=30, delay=5):
for i in range(max_retries):
try:
engine = create_engine(db_url)
with engine.connect() as conn:
conn.execute(text("SELECT 1"))
print("Database ready!")
return True
except Exception as e:
print(f"Retry {i+1}/{max_retries}: {e}")
time.sleep(delay)
raise Exception("Database not available")
4. Cập nhật docker-compose.yml với depends_on condition
services:
fetcher:
depends_on:
timescale:
condition: service_healthy
# Thêm healthcheck vào timescale service
Lỗi 3: Tardis API Rate Limit
Tardis có giới hạn rate request tùy theo plan subscription. Khi vượt quá limit, API trả về HTTP 429 Too Many Requests. Điều này đặc biệt dễ xảy ra khi fetch nhiều symbols cùng lúc.
# Triệu chứng
HTTP 429: Too Many Requests
{"error": "Rate limit exceeded", "retryAfter": 60}
Cách khắc phục
1. Implement exponential backoff
import time
import random
def call_with_backoff(func, max_retries=5):
for attempt in range(max_retries):
try:
return func()
except requests.exceptions.HTTPError as e:
if e.response.status_code == 429:
retry_after = int(e.response.headers.get('Retry-After', 60))
wait_time = retry_after + random.uniform(0, 10)
print(f"Rate limited. Waiting {wait_time:.1f}s...")
time.sleep(wait_time)
else:
raise
raise Exception("Max retries exceeded")
2. Batch requests thay vì gọi riêng lẻ
Sử dụng HolySheep caching để giảm số lượng calls thực tế
payload = {
"messages": [
{"role": "user", "content": f"Fetch funding rates for all: {symbols}"}
]
}
HolySheep sẽ cache response, giảm Tardis calls thực tế
3. Nâng cấp Tardis plan nếu cần thiết
Hoặc sử dụng HolySheep tiered pricing để tối ưu chi phí
Lỗi 4: Dữ Liệu Trả Về Null Hoặc Incorrect Format
Đôi khi Tardis response có format không đúng như mong đợi, dẫn đến lỗi parse JSON. Nguyên nhân có thể do symbol không tồn tại trên BitMart hoặc Tardis không có data cho timeframe yêu cầu.
# Triệu chứng
json.JSONDecodeError: Expecting value
KeyError: 'data' trong parse function
Cách khắc phục
def safe_parse_tardis_response(response_text):
"""Parse response với error handling đầy đủ"""
try:
# Thử parse trực tiếp
data = json.loads(response_text)
except json.JSONDecodeError:
# Thử extract JSON từ text
try:
start = response_text.find('{')
end = response_text.rfind('}') + 1
if start != -1 and end > start:
data = json.loads(response_text[start:end])
else:
# Có thể là empty response
return []
except: