发一个用本地AI(openclaw)写的调用本地llama.cpp服务对话,并按指定要求识别图片的PHP类
一、PHP类
utils/LlamaClient.php
php
<?php
/**
* 本地 llama.cpp server 调用客户端 (PHP 7.4)
*
* 支持: chat / 流式 / 图片分析 / completion
* 假设 llama-server 运行在: http://127.0.0.1:8080
*/
namespace app\utils;
use Generator;
use InvalidArgumentException;
use RuntimeException;
class LlamaClient
{
/** @var string API 基础地址 */
protected $baseUrl;
/** @var string 使用的模型名 */
protected $model;
/** @var string API Key (用于认证) */
protected $apiKey;
/** @var int 请求超时(秒) */
protected $timeout;
/** @var float 连接超时(秒) */
protected $connectTimeout;
/** @var array 默认参数 */
protected $defaultParams;
/**
* @param string $baseUrl 服务地址
* @param string $model 模型名
* @param string $apiKey API Key (可选)
* @param int $timeout 请求超时秒数
* @param float $connectTimeout 连接超时秒数
*/
public function __construct(
string $baseUrl = 'http://127.0.0.1:8080',
string $model = 'default',
string $apiKey = '',
int $timeout = 300,
float $connectTimeout = 10.0
) {
$this->baseUrl = rtrim($baseUrl, '/');
$this->model = $model;
$this->apiKey = $apiKey;
$this->timeout = $timeout;
$this->connectTimeout = $connectTimeout;
$this->defaultParams = [
'temperature' => 0.7,
'top_k' => 40,
'top_p' => 0.9,
'max_tokens' => 2048,
'repeat_penalty' => 1.1,
'stop' => [],
];
}
// ==================================================================
// 对话(非流式)
// ==================================================================
/**
* 对话请求
*
* @param array $messages 消息列表 [['role' => 'user', 'content' => '你好'], ...]
* @param array $options 可选参数覆盖
* @return string 模型回复文本
*/
public function chat(array $messages, array $options = []): string
{
$params = array_merge($this->defaultParams, $options);
$payload = $this->buildPayload($messages, $params);
$response = $this->request('/v1/chat/completions', $payload);
$result = json_decode($response, true);
if (!isset($result['choices'][0]['message']['content'])) {
throw new RuntimeException('LLM 响应格式异常: ' . $response);
}
return $result['choices'][0]['message']['content'];
}
// ==================================================================
// 对话(流式)
// ==================================================================
/**
* 对话请求(流式输出)
*
* @param array $messages 消息列表
* @param array $options 可选参数
* @return Generator 每次 yield 一个增量文本
*/
public function chatStream(array $messages, array $options = []): Generator
{
$params = array_merge($this->defaultParams, $options);
$payload = $this->buildPayload($messages, $params, true);
$json = json_encode($payload, JSON_UNESCAPED_UNICODE);
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => $this->buildHeaders($json, 'text/event-stream'),
'content' => $json,
'timeout' => $this->timeout,
'ignore_errors' => true,
],
]);
$handle = @fopen($this->baseUrl . '/v1/chat/completions', 'r', false, $context);
if ($handle === false) {
throw new RuntimeException('无法连接 LLM 服务');
}
$buffer = '';
while (!feof($handle)) {
$line = fgets($handle, 2048);
if ($line === false) {
continue;
}
$line = trim($line);
if (strpos($line, 'data: ') === 0) {
$content = substr($line, 6);
if (trim($content) === '[DONE]') {
break;
}
$data = json_decode($content, true);
if (isset($data['choices'][0]['delta']['content'])) {
$chunk = $data['choices'][0]['delta']['content'];
$buffer .= $chunk;
yield $chunk;
}
}
}
fclose($handle);
if ($buffer === '') {
throw new RuntimeException('流式响应为空');
}
}
// ==================================================================
// 图片分析(多模态)
// ==================================================================
/**
* 上传图片并按用户要求解读
*
* @param string $imageUrl 图片文件路径 或 base64 数据 URL
* @param string $prompt 对图片的要求,如 "描述这张图片的内容"
* @param array $options 可选参数
* @return string 模型对图片的分析结果
*/
public function analyzeImage(string $imageUrl, string $prompt = '描述这张图片的内容', array $options = []): string
{
$params = array_merge($this->defaultParams, $options);
// 读取图片并转为 base64
$base64Data = $this->loadImageToBase64($imageUrl);
// 构建多模态消息
$messages = [
[
'role' => 'user',
'content' => [
[
'type' => 'text',
'text' => $prompt,
],
[
'type' => 'image_url',
'image_url' => [
'url' => $base64Data,
],
],
],
],
];
$payload = $this->buildPayload($messages, $params);
$response = $this->request('/v1/chat/completions', $payload);
$result = json_decode($response, true);
if (!isset($result['choices'][0]['message']['content'])) {
throw new RuntimeException('LLM 响应格式异常: ' . $response);
}
return $result['choices'][0]['message']['content'];
}
/**
* 图片流式分析(返回 Generator)
*
* @param string $imageUrl 图片文件路径
* @param string $prompt 对图片的要求
* @param array $options 可选参数
* @return Generator
*/
public function analyzeImageStream(string $imageUrl, string $prompt = '描述这张图片的内容', array $options = []): Generator
{
$params = array_merge($this->defaultParams, $options);
$base64Data = $this->loadImageToBase64($imageUrl);
$messages = [
[
'role' => 'user',
'content' => [
[
'type' => 'text',
'text' => $prompt,
],
[
'type' => 'image_url',
'image_url' => [
'url' => $base64Data,
],
],
],
],
];
$payload = $this->buildPayload($messages, $params, true);
$json = json_encode($payload, JSON_UNESCAPED_UNICODE);
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => $this->buildHeaders($json, 'text/event-stream'),
'content' => $json,
'timeout' => $this->timeout,
'ignore_errors' => true,
],
]);
$handle = @fopen($this->baseUrl . '/v1/chat/completions', 'r', false, $context);
if ($handle === false) {
throw new RuntimeException('无法连接 LLM 服务');
}
$buffer = '';
while (!feof($handle)) {
$line = fgets($handle, 2048);
if ($line === false) {
continue;
}
$line = trim($line);
if (strpos($line, 'data: ') === 0) {
$content = substr($line, 6);
if (trim($content) === '[DONE]') {
break;
}
$data = json_decode($content, true);
if (isset($data['choices'][0]['delta']['content'])) {
$chunk = $data['choices'][0]['delta']['content'];
$buffer .= $chunk;
yield $chunk;
}
}
}
fclose($handle);
if ($buffer === '') {
throw new RuntimeException('流式响应为空');
}
}
// ==================================================================
// 文本补全
// ==================================================================
/**
* 文本补全
*
* @param string $prompt 提示文本
* @param array $options 可选参数
* @return string 生成的文本
*/
public function complete(string $prompt, array $options = []): string
{
$params = array_merge($this->defaultParams, $options);
$payload = [
'model' => $this->model,
'prompt' => $prompt,
'stream' => false,
'n' => 1,
];
foreach (['temperature', 'top_k', 'top_p', 'max_tokens', 'repeat_penalty', 'stop'] as $key) {
if (isset($params[$key])) {
$payload[$key] = $params[$key];
}
}
$response = $this->request('/v1/completions', $payload);
$result = json_decode($response, true);
if (!isset($result['choices'][0]['text'])) {
throw new RuntimeException('LLM 响应格式异常: ' . $response);
}
return $result['choices'][0]['text'];
}
// ==================================================================
// 工具方法
// ==================================================================
/**
* 获取模型列表
*/
public function listModels(): array
{
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $this->baseUrl . '/v1/models',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => $this->connectTimeout,
] + $this->getAuthHeaders());
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response, true);
return $result['data'] ?? [];
}
/**
* 健康检查
*/
public function healthCheck(): bool
{
try {
$this->listModels();
return true;
} catch (Throwable $e) {
return false;
}
}
// ==================================================================
// 内部方法
// ==================================================================
/**
* 构建消息 payload(兼容 chat/completions 格式)
*/
protected function buildPayload(array $messages, array $params, bool $stream = false): array
{
$payload = [
'model' => $this->model,
'messages' => $messages,
'stream' => $stream,
'n' => 1,
];
foreach (['temperature', 'top_k', 'top_p', 'max_tokens', 'repeat_penalty', 'stop'] as $key) {
if (isset($params[$key])) {
$payload[$key] = $params[$key];
}
}
return $payload;
}
/**
* 读取图片并转为 base64 data URL
*/
protected function loadImageToBase64(string $path): string
{
// 如果是 data URL 直接返回
if (strpos($path, 'data:') === 0) {
return $path;
}
if (!is_file($path) || !is_readable($path)) {
throw new InvalidArgumentException('图片文件不存在或不可读: ' . $path);
}
$content = file_get_contents($path);
$ext = pathinfo($path, PATHINFO_EXTENSION);
// 自动检测 MIME 类型
$mime = mime_content_type($path) ?: 'image/jpeg';
return 'data:' . $mime . ';base64,' . base64_encode($content);
}
/**
* 构建 HTTP Headers
*/
protected function buildHeaders(string $body, string $accept = 'application/json'): array
{
$headers = [
'Content-Type: application/json',
'Accept: ' . $accept,
'Content-Length: ' . (string) strlen($body),
];
if ($this->apiKey) {
$headers[] = 'Authorization: Bearer ' . $this->apiKey;
}
return $headers;
}
/**
* 构建 cURL 认证头(用于 listModels 等 GET 请求)
*/
protected function getAuthHeaders(): array
{
if (!$this->apiKey) {
return [];
}
return [
CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $this->apiKey],
];
}
/**
* 发起 HTTP 请求
*/
protected function request(string $endpoint, array $payload): string
{
$json = json_encode($payload, JSON_UNESCAPED_UNICODE);
$ch = curl_init();
$headers = $this->buildHeaders($json, 'application/json');
curl_setopt_array($ch, [
CURLOPT_URL => $this->baseUrl . $endpoint,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => $this->timeout,
CURLOPT_CONNECTTIMEOUT => $this->connectTimeout,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $json,
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
throw new RuntimeException('LLM 请求错误: ' . $error);
}
if ($httpCode !== 200) {
throw new RuntimeException("LLM 请求失败 HTTP {$httpCode}: {$response}");
}
return $response;
}
}
二、使用示例
环境是yii2,通过命令控制器调用
commands\LlamaTestController.php
php
<?php
/*
* @Author: john.tang 64500165@qq.com
* @Date: 2026-11-27 10:57:57
* @LastEditors: john.tang 64500165@qq.com
* @LastEditTime: 2026-12-01 14:38:08
* @FilePath: \commands\LlamaTestController.php
* @Description:
* Copyright (c) 2026 by ${git_name} email: ${git_email}, All Rights Reserved.
*/
namespace app\commands;
use Yii;
use app\utils\LlamaClient;
use yii\console\Controller;
class LlamaTestController extends Controller
{
/**
* 调用本地模型测试
*/
public function actionIndex()
{
Yii::beginProfile('WwcTestController');
// ======================================================================
// 使用示例
// ======================================================================
// 1. 创建客户端(带 API Key)
$client = new LlamaClient(
'http://127.0.0.1:11444', // 地址
'Qwen3VL-30B-A3B-Instruct-Q4_K_M', // 模型
'your-api-key-here', // API Key(可选)
300, // 超时 300 秒
10.0 // 连接超时
);
foreach ($client->listModels() as $listModel) {
// echo $listModel['id'] . PHP_EOL;
}
// 2. 简单对话
$response = $client->chat([
['role' => 'system', 'content' => '你是一个 helpful assistant。'],
['role' => 'user', 'content' => '你好,介绍一下自己'],
]);
echo $response . PHP_EOL;
// 3. 流式对话
echo "<pre>" . PHP_EOL;
foreach (
$client->chatStream([
['role' => 'user', 'content' => '写一段关于春天的短文'],
]) as $chunk
) {
echo $chunk;
if (ob_get_level() > 0) {
ob_flush();
}
flush();
}
echo "</pre>" . PHP_EOL;
// 4. 图片分析
$text = $client->analyzeImage('llama-test-pic.png', '描述这张图片的内容,包括物体、颜色、场景');
echo $text;
// 5. 图片流式分析
echo "<pre>" . PHP_EOL;
foreach ($client->analyzeImageStream('llama-test-pic2.jpg', '描述这张图片') as $chunk) {
echo $chunk;
if (ob_get_level() > 0) {
ob_flush();
}
flush();
}
echo "</pre>" . PHP_EOL;
// 6. 文本补全
$response = $client->complete('今天天气真好,');
// 7. 健康检查
echo $client->healthCheck() ? '服务正常。' : '服务异常。' . PHP_EOL;
Yii::endProfile('WwcTestController');
return 0;
}
}
注意:llama-test-pic2.jpg文件放在yii项目根文件夹下。
三、运行
bash
yii llama-test/index
四、在网页面端输出stream
stream-test.php
php
<?php
// 1. 禁用 PHP 输出缓冲和压缩
// 必须在任何输出之前执行
if (function_exists('apache_setenv')) {
apache_setenv('no-gzip', 1);
}
@ini_set('zlib.output_compression', 0);
@ini_set('implicit_flush', 1);
@ob_end_clean(); // 清除并关闭当前激活的输出缓冲区
// 2. 设置必要的 HTTP 头
header('Content-Type: text/html; charset=utf-8');
header('Cache-Control: no-cache');
// 针对 Nginx 的关键头,告诉代理不要缓冲
header('X-Accel-Buffering: no');
// 3. 填充缓冲区以触发浏览器立即渲染
// 大多数浏览器(如 Chrome)需要接收至少 1KB - 4KB 的数据才会开始渲染页面
echo str_repeat(' ', 1024 * 4);
flush(); // 强制将数据推送到 Web 服务器
// 4. 模拟长时间处理并逐块输出
for ($i = 1; $i <= 10; $i++) {
echo "<div>正在处理第 {$i} 项数据...</div>\n";
// 每次输出后强制刷新
if (function_exists('flush')) {
flush();
}
// 模拟耗时操作
usleep(500000); // 0.5秒
// 检测客户端是否断开连接,避免无效计算
if (connection_aborted()) {
break;
}
}
echo "<div>处理完成!</div>";
flush();