PHP 项目与 BERT/Transformers 结合方案
在 PHP 项目中使用 BERT 或 Transformers 模型,主要有以下几种方案:

外部服务调用方式(推荐)
Python API + PHP 调用
// Python API (Flask/FastAPI 服务)
// app.py
from transformers import pipeline
from flask import Flask, request, jsonify
app = Flask(__name__)
classifier = pipeline("text-classification", model="bert-base-chinese")
@app.route('/predict', methods=['POST'])
def predict():
text = request.json['text']
result = classifier(text)
return jsonify(result)
if __name__ == '__main__':
app.run(port=5000)
// PHP 客户端调用
$client = new \GuzzleHttp\Client();
$response = $client->post('http://localhost:5000/predict', [
'json' => ['text' => '今天天气真好']
]);
$result = json_decode($response->getBody(), true);
PHP 内直接集成方案
使用 llama.cpp 的 PHP 绑定
// 使用 llama-cpp-php 扩展
$model = new \LlamaCpp\BertModel('/path/to/model.bin');
$result = $model->predict('这是一个测试句子');
通过 ONNX Runtime 的 PHP 扩展
// 安装 php-onnx 扩展
$session = new \ONNX\Runtime\InferenceSession('/path/to/model.onnx');
$input = ['input_ids' => $tokenized_input];
$output = $session->run($input);
实用工具和库
PHP BERT 工具包
// 使用 php-bert 库
use BERT\BERT;
$bert = new BERT('/path/to/bert_model');
$embeddings = $bert->embed('要处理的文本');
$classification = $bert->classify('文本分类任务');
快速部署方案
Docker 容器部署
# docker-compose.yml
version: '3'
services:
php-app:
build: .
ports:
- "8080:80"
depends_on:
- bert-api
bert-api:
image: python:3.9
command: python app.py
volumes:
- ./models:/models
性能优化建议
- 批量处理:合并多个请求一次性处理
- 缓存机制:使用 Redis 缓存重复查询
- 异步处理:使用 PHP 的异步 HTTP 客户端
// 批量处理示例
$batch = ['文本1', '文本2', '文本3'];
$promises = [];
foreach ($batch as $text) {
$promises[] = $client->postAsync('/predict', [
'json' => ['text' => $text]
]);
}
$results = \GuzzleHttp\Promise\settle($promises)->wait();
本地部署开源模型
推荐使用以下易于部署的模型:
- DistilBERT:轻量级,适合生产环境
- ALBERT:参数更少,性能接近
- MiniLM:微软出品,速度较快
实用代码示例
<?php
class BertProcessor {
private $apiUrl;
public function __construct($apiUrl) {
$this->apiUrl = $apiUrl;
}
public function analyze($text) {
$client = new \GuzzleHttp\Client([
'timeout' => 30.0,
'headers' => ['Content-Type' => 'application/json']
]);
try {
$response = $client->post($this->apiUrl . '/predict', [
'json' => [
'text' => $text,
'task' => 'sentiment' // 或 'ner', 'qa' 等
]
]);
return json_decode($response->getBody(), true);
} catch (\Exception $e) {
return ['error' => $e->getMessage()];
}
}
}
// 使用示例
$processor = new BertProcessor('http://localhost:5000');
$result = $processor->analyze('这个产品非常好用');
echo json_encode($result);
选择建议
| 场景 | 推荐方案 | 优点 | 缺点 |
|---|---|---|---|
| 生产环境 | Python API + 微服务 | 稳定、可扩展 | 增加网络延迟 |
| 小型项目 | Docker 部署 | 简单、隔离性好 | 资源占用稍高 |
| 测试环境 | 直接调用 Python | 开发速度快 | 耦合度高 |
| 高性能需求 | C++ ONNX 部署 | 延迟最低 | 开发复杂度高 |
建议从 Python API 方案开始,等业务稳定后再考虑优化到其他方案。