Thực chiến Phi-4-mini-reasoning: Xây dựng client gọi API ổn định bằng Python requests

1. Giới thiệu mô hình và yêu cầu

Phi-4-mini-reasoning là mô hình ngôn ngữ nhỏ gọn 3.8 tỷ tham số do Microsoft phát triển, chuyên xử lý các tác vụ logic phức tạp như giải toán, lập luận và phân tích đa bước. Mô hình sở hữu các đặc điểm nổi bật:

  • Hiệu năng cao: Vượt trội trong giải toán và phân tích mã nguồn
  • Tiết kiệm tài nguyên: Kích thước chỉ 7.2GB
  • Hỗ trợ ngữ cảnh dài: 128,000 tokens
  • Độ trễ thấp: Tối ưu tốc độ phản hồi

2. Cài đặt môi trường

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

pip install requests

2.2 Ví dụ gọi API cơ bản


import requests

def truy_van(prompt):
url = "http://localhost:7860/api/v1/generate"
du_lieu = {
"prompt": prompt,
"max_new_tokens": 512,
"temperature": 0.3
}

try:
phản_hồi = requests.post(url, json=du_lieu)
phản_hồi.raise_for_status()
return phản_hồi.json()["results"][0]["text"]
except requests.exceptions.RequestException as e:
print(f"Yêu cầu thất bại: {e}")
return None

# Sử dụng
ket_qua = truy_van("Giải phương trình: 2x + 5 = 15")
print(ket_qua)

3. Thiết kế client chuyên nghiệp

3.1 Quản lý kết nối


import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

class Phi4MiniClient:
def __init__(self, base_url="http://localhost:7860"):
self.base_url = base_url
self.phiên = requests.Session()

# Cấu hình thử lại
chien_luoc_thu_lai = Retry(
total=3,
backoff_factor=1,
status_forcelist=[500, 502, 503, 504]
)

# Cấu hình pool kết nối
adapter = HTTPAdapter(
max_retries=chien_luoc_thu_lai,
pool_connections=10,
pool_maxsize=20
)

self.phiên.mount("http://", adapter)
self.phiên.mount("https://", adapter)

3.2 Quản lý tham số


class Phi4MiniClient:
# ... phần khởi tạo ...

THAM_SO_MAC_DINH = {
"max_new_tokens": 512,
"temperature": 0.3,
"top_p": 0.85,
"repetition_penalty": 1.2
}

def sinh_van_ban(self, prompt, **kwargs):
tham_so = {**self.THAM_SO_MAC_DINH, **kwargs}
du_lieu = {
"prompt": prompt,
**tham_so
}

try:
phản_hồi = self.phiên.post(
f"{self.base_url}/api/v1/generate",
json=du_lieu,
timeout=30
)
phản_hồi.raise_for_status()
return phản_hồi.json()["results"][0]["text"]
except requests.exceptions.RequestException as e:
print(f"Lỗi yêu cầu: {e}")
return None

4. Tính năng nâng cao

4.1 Xử lý luồng dữ liệu


def sinh_theo_dong(self, prompt, hàm_phản_hồi, **kwargs):
tham_so = {**self.THAM_SO_MAC_DINH, **kwargs}
du_lieu = {
"prompt": prompt,
"stream": True,
**tham_so
}

try:
with self.phiên.post(
f"{self.base_url}/api/v1/generate",
json=du_lieu,
stream=True,
timeout=60
) as phản_hồi:
phản_hồi.raise_for_status()

for đoạn in phản_hồi.iter_lines():
if đoạn:
đã_giải = đoạn.decode('utf-8')
if đã_giải.startswith("data:"):
dữ_liệu = json.loads(đã_giải[5:])
hàm_phản_hồi(dữ_liệu["results"][0]["text"])
except requests.exceptions.RequestException as e:
print(f"Lỗi luồng dữ liệu: {e}")

4.2 Xử lý hàng loạt


from concurrent.futures import ThreadPoolExecutor

def tao_hang_loat(self, danh_sach_prompt, luong_toi_da=4):
ket_qua = []

def worker(prompt):
return self.sinh_van_ban(prompt)

with ThreadPoolExecutor(max_workers=luong_toi_da) as executor:
cac_tuong_lai = [executor.submit(worker, prompt) for prompt in danh_sach_prompt]
for tuong_lai in cac_tuong_lai:
try:
ket_qua.append(tuong_lai.result())
except Exception as e:
print(f"Lỗi xử lý hàng loạt: {e}")
ket_qua.append(None)

return ket_qua

Thẻ: python requests phi-4 api-client production-code

Đăng vào ngày 19 tháng 6 lúc 22:09