怎样在PHP项目中实现生成式对话?

wen java案例 4

本文目录导读:

怎样在PHP项目中实现生成式对话?

  1. 调用第三方AI API(推荐首选)
  2. 使用PHP本地AI库
  3. 结合微服务架构
  4. 完整的对话系统架构
  5. 性能优化建议
  6. 选择建议

在PHP项目中实现生成式对话,通常有以下几种可行方案,从简单到复杂排列:

调用第三方AI API(推荐首选)

这是最直接、效果最好的方式,PHP端只需做HTTP请求即可。

使用OpenAI API示例

<?php
class AIChat {
    private $apiKey;
    public function __construct($apiKey) {
        $this->apiKey = $apiKey;
    }
    public function chat($messages, $model = 'gpt-3.5-turbo') {
        $url = 'https://api.openai.com/v1/chat/completions';
        $data = [
            'model' => $model,
            'messages' => $messages,
            'temperature' => 0.7,
            'max_tokens' => 1000
        ];
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $this->apiKey,
                'Content-Type: application/json'
            ],
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 60
        ]);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($httpCode !== 200) {
            throw new Exception('API请求失败: ' . $response);
        }
        $result = json_decode($response, true);
        return $result['choices'][0]['message']['content'];
    }
}
// 使用示例
$chat = new AIChat('your-api-key-here');
$messages = [
    ['role' => 'system', 'content' => '你是一个友好的AI助手'],
    ['role' => 'user', 'content' => '帮我写一段PHP代码']
];
try {
    $reply = $chat->chat($messages);
    echo $reply;
} catch (Exception $e) {
    echo '错误: ' . $e->getMessage();
}

常用AI API提供商

  • OpenAI - ChatGPT系列
  • 百度文心一言 - 国内速度快
  • 阿里通义千问 - 国内免费额度较多
  • DeepSeek - 性价比高

使用PHP本地AI库

适合需要离线部署或数据安全的场景。

使用llama-cpp-php

<?php
// 需要先安装PHP扩展:php-llama-cpp
$model = new LlamaCPP\Model('/path/to/model.gguf');
$response = $model->prompt(
    '介绍PHP语言的特点',
    [
        'temperature' => 0.7,
        'max_tokens' => 500
    ]
);
echo $response;

使用Rubix ML(机器学习库)

<?php
require_once 'vendor/autoload.php';
use Rubix\ML\Persisters\Persister;
use Rubix\ML\Transformers\TextNormalizer;
use Rubix\ML\Datasets\Labeled;
// 实现简单的对话 - 基于预训练词向量
class SimpleChatBot {
    private $responses = [];
    private $tokenizer;
    public function __construct() {
        // 加载训练数据
        $this->responses = [
            '你好' => '你好!有什么可以帮助你的?',
            'PHP' => 'PHP是一种流行的服务器端脚本语言',
            '默认' => '我还在学习,请换个问题试试'
        ];
    }
    public function respond($input) {
        // 简单的关键词匹配
        foreach ($this->responses as $key => $response) {
            if (strpos($input, $key) !== false) {
                return $response;
            }
        }
        return $this->responses['默认'];
    }
}

结合微服务架构

将AI对话逻辑分离为独立服务:

<?php
// PHP微服务客户端
class ChatServiceClient {
    private $serviceUrl;
    public function __construct($serviceUrl) {
        $this->serviceUrl = $serviceUrl;
    }
    public function sendMessage($message, $sessionId = null) {
        $payload = [
            'message' => $message,
            'session_id' => $sessionId ?? uniqid(),
            'context' => [
                'user' => [
                    'id' => $_SESSION['user_id'] ?? null,
                    'preferences' => $this->getUserPreferences()
                ]
            ]
        ];
        // 使用Guzzle发送请求
        $client = new \GuzzleHttp\Client();
        $response = $client->post($this->serviceUrl . '/chat', [
            'json' => $payload,
            'timeout' => 30
        ]);
        return json_decode($response->getBody(), true);
    }
    private function getUserPreferences() {
        // 从数据库获取用户偏好
        return ['language' => 'zh-CN', 'style' => 'friendly'];
    }
}

完整的对话系统架构

数据库表设计

CREATE TABLE conversation_history (
    id INT AUTO_INCREMENT PRIMARY KEY,
    session_id VARCHAR(64) NOT NULL,
    role ENUM('user', 'assistant', 'system') NOT NULL,
    content TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_session (session_id),
    INDEX idx_created (created_at)
);

完整的PHP对话控制器

<?php
class ChatController {
    private $aiClient;
    private $db;
    public function __construct($aiClient, $db) {
        $this->aiClient = $aiClient;
        $this->db = $db;
    }
    public function handleChat($userMessage) {
        $sessionId = $this->getOrCreateSession();
        // 保存用户消息
        $this->saveMessage($sessionId, 'user', $userMessage);
        // 获取对话上下文(最近10条)
        $context = $this->getContext($sessionId, 10);
        // 构建API请求格式
        $messages = [];
        foreach ($context as $msg) {
            $messages[] = [
                'role' => $msg['role'],
                'content' => $msg['content']
            ];
        }
        // 调用AI接口
        $aiResponse = $this->aiClient->chat($messages);
        // 保存AI回复
        $this->saveMessage($sessionId, 'assistant', $aiResponse);
        return [
            'response' => $aiResponse,
            'session_id' => $sessionId
        ];
    }
    private function getOrCreateSession() {
        // 从Cookie或Session获取/创建会话ID
    }
    private function saveMessage($sessionId, $role, $content) {
        $stmt = $this->db->prepare(
            "INSERT INTO conversation_history (session_id, role, content) VALUES (?, ?, ?)"
        );
        $stmt->execute([$sessionId, $role, $content]);
    }
    private function getContext($sessionId, $limit = 10) {
        $stmt = $this->db->prepare(
            "SELECT role, content FROM conversation_history 
             WHERE session_id = ? 
             ORDER BY created_at DESC LIMIT ?"
        );
        $stmt->execute([$sessionId, $limit]);
        return array_reverse($stmt->fetchAll());
    }
}

性能优化建议

<?php
// 1. 缓存常用回复
$cache = new \Redis();
$cache->connect('127.0.0.1', 6379);
function getCachedResponse($query) {
    global $cache;
    $key = 'chat_response:' . md5($query);
    if ($cached = $cache->get($key)) {
        return json_decode($cached, true);
    }
    $response = callAI($query);
    $cache->setex($key, 3600, json_encode($response)); // 缓存1小时
    return $response;
}
// 2. 流式响应(SSE)
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
function streamResponse($messages) {
    $url = 'https://api.openai.com/v1/chat/completions';
    $data = [
        'model' => 'gpt-3.5-turbo',
        'messages' => $messages,
        'stream' => true
    ];
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . API_KEY,
            'Content-Type: application/json'
        ],
        CURLOPT_POSTFIELDS => json_encode($data),
        CURLOPT_WRITEFUNCTION => function($ch, $data) {
            echo "data: $data\n\n";
            ob_flush();
            flush();
            return strlen($data);
        }
    ]);
    curl_exec($ch);
    curl_close($ch);
}

选择建议

场景 推荐方案 成本 难度
生产级应用 OpenAI/国产大模型API
数据安全要求高 本地部署LLaMA等
简单问答 PHP本地简单模型 免费
高性能要求 微服务架构+异步处理

最佳实践:对于大多数PHP项目,直接调用成熟的AI API(如OpenAI、DeepSeek、文心一言)是最实际的选择,成本可控且效果最好,如果对数据隐私有要求,可以选择国内大模型API或私有化部署。

抱歉,评论功能暂时关闭!