前言
在当今数字化时代,自动化内容生成和智能对话功能已成为提升网站用户体验和运营效率的重要手段。下面将详细介绍如何通过 WordPress 与华为云 ModelArts Studio 大模型对接,实现每日自动生成文章和网站 AI 对话功能。
一、方案整体架构设计
1.1 整个系统架构主要包含以下几个核心部分:
WordPress 网站平台:作为内容展示和用户交互的前端平台
华为云 ModelArts Studio:提供大模型算力和 API 服务支持
中间接口服务:负责数据传输和指令调度
自动化调度系统:控制文章生成和发布的时间逻辑
1.2 系统工作流程如下:
定时任务触发 WordPress 文章生成流程
1.3 开通华为云ModelArts Studio大模型
1.4 中间服务调用 华为云ModelArts API 生成内容
1.5 创建一个华为云API Key
当用户使用MaaS部署的模型服务进行数据请求、模型推理等操作时,系统通过验证API Key来确认用户的身份与访问权限,只有具备有效API Key的用户才能成功调用模型服务,防止未经授权的访问。
1.6 文章内容经处理后发布到 WordPress
二、华为云 ModelArts Studio 准备工作
2.1 创建 ModelArts 开发环境
登录华为云控制台,进入 ModelArts 服务
创建 开发环境,选择合适的算力规格(建议 GPU 类型)
2.2 开发模型推理 API
编写模型推理代码并部署为 API:
import json
import requests
from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
# 加载大模型
model_name = "huawei-cloud/nlp-large-model"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)
generator = pipeline("text-generation", model=model, tokenizer=tokenizer)
# 定义文章生成函数
def generate_article(topic, length=1000):
prompt = f"请围绕'{topic}'生成一篇{length}字左右的高质量文章,要求结构清晰、内容详实。"
output = generator(prompt, max_length=length+len(prompt), num_return_sequences=1)
return output[0]['generated_text']
# 定义对话处理函数
def process_chat(history, new_message):
full_prompt = ""
for turn in history:
full_prompt += f"用户: {turn['user']}\nAI: {turn['ai']}\n"
full_prompt += f"用户: {new_message}\nAI: "
output = generator(full_prompt, max_length=500, num_return_sequences=1)
ai_response = output[0]['generated_text'].replace(full_prompt, "").strip()
return ai_response
# 部署为Flask API
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/generate/article', methods=['POST'])
def api_generate_article():
data = request.json
topic = data.get('topic', '科技资讯')
length = data.get('length', 1000)
article = generate_article(topic, length)
return jsonify({"status": "success", "content": article})
@app.route('/chat/process', methods=['POST'])
def api_process_chat():
data = request.json
history = data.get('history', [])
new_message = data.get('message', '')
response = process_chat(history, new_message)
return jsonify({"status": "success", "response": response})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080)
三、WordPress 系统集成开发
3.1 创建 WordPress 插件
首先创建插件基础目录结构:
huawei-ai-integration/
├── huawei-ai-integration.php
├── includes/
│ ├── article-generator.php
│ ├── chat-handler.php
│ └── api-client.php
├── assets/
│ ├── css/
│ └── js/
│ └── chat-ui.js
└── README.md
3.2 定时任务回调 - 每日生成文章
add_action('huawei_ai_daily_article', 'huawei_ai_generate_daily_article');
function huawei_ai_generate_daily_article() {
$generator = new Huawei_AI_Article_Generator();
$generator->generate_and_publish_article();
}
3.3 添加AI对话前端脚本
add_action('wp_enqueue_scripts', 'huawei_ai_enqueue_scripts');
function huawei_ai_enqueue_scripts() {
wp_enqueue_script('huawei-ai-chat', plugin_dir_url(__FILE__) . 'assets/js/chat-ui.js', array('jquery'), '1.0.0', true);
wp_localize_script('huawei-ai-chat', 'huaweiAIConfig', array(
'apiUrl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('huawei_ai_chat_nonce')
));
}
3.4 处理AI对话AJAX请求
add_action('wp_ajax_huawei_ai_process_chat', 'huawei_ai_ajax_process_chat');
add_action('wp_ajax_nopriv_huawei_ai_process_chat', 'huawei_ai_ajax_process_chat');
function huawei_ai_ajax_process_chat() {
check_ajax_referer('huawei_ai_chat_nonce', 'nonce');
$history = json_decode(stripslashes($_POST['history']), true);
$message = sanitize_text_field($_POST['message']);
$chat_handler = new Huawei_AI_Chat_Handler();
$response = $chat_handler->process_chat($history, $message);
wp_send_json($response);
}
3.5 二次开发好之后,还需要在后台进行配置华为云 ModelArts Studio的API接口参数进去,才能正常使用哦!
3.6 在你自己的网站后台设置采集定时任务
四、API 客户端实现
<?php
// 华为云API客户端类
class Huawei_AI_API_Client {
private $api_key;
private $api_secret;
private $article_api_url;
private $chat_api_url;
public function __construct() {
// 从WordPress设置中获取API配置
$this->api_key = get_option('huawei_ai_api_key', '');
$this->api_secret = get_option('huawei_ai_api_secret', '');
$this->article_api_url = get_option('huawei_ai_article_api', '');
$this->chat_api_url = get_option('huawei_ai_chat_api', '');
}
// 生成文章
public function generate_article($topic, $length = 1000) {
$headers = array(
'Content-Type: application/json',
'X-Api-Key: ' . $this->api_key,
'X-Api-Secret: ' . $this->api_secret
);
$data = array(
'topic' => $topic,
'length' => $length
);
$response = wp_remote_post($this->article_api_url, array(
'headers' => $headers,
'body' => json_encode($data),
'timeout' => 60
));
if (is_wp_error($response)) {
error_log('华为云API请求错误: ' . $response->get_error_message());
return false;
}
$body = wp_remote_retrieve_body($response);
$result = json_decode($body, true);
if ($result && $result['status'] == 'success') {
return $result['content'];
} else {
error_log('华为云API返回错误: ' . print_r($result, true));
return false;
}
}
// 处理对话
public function process_chat($history, $message) {
$headers = array(
'Content-Type: application/json',
'X-Api-Key: ' . $this->api_key,
'X-Api-Secret: ' . $this->api_secret
);
$data = array(
'history' => $history,
'message' => $message
);
$response = wp_remote_post($this->chat_api_url, array(
'headers' => $headers,
'body' => json_encode($data),
'timeout' => 30
));
if (is_wp_error($response)) {
error_log('华为云对话API请求错误: ' . $response->get_error_message());
return '抱歉,我暂时无法回答这个问题。';
}
$body = wp_remote_retrieve_body($response);
$result = json_decode($body, true);
if ($result && $result['status'] == 'success') {
return $result['response'];
} else {
error_log('华为云对话API返回错误: ' . print_r($result, true));
return '抱歉,我暂时无法回答这个问题。';
}
}
}
五、自动化文章生成功能实现
- 文章生成与发布类
<?php
// 文章生成与发布类
class Huawei_AI_Article_Generator {
private $api_client;
private $default_categories = array('资讯'); // 默认文章分类
public function __construct() {
$this->api_client = new Huawei_AI_API_Client();
}
// 生成并发布文章
public function generate_and_publish_article() {
// 确定今日文章主题
$today = date('Y-m-d');
$topic = $this->get_today_article_topic();
// 调用华为云API生成文章内容
$content = $this->api_client->generate_article($topic);
if (!$content) {
error_log('文章生成失败');
return false;
}
// 处理生成的内容(添加格式、图片等)
$formatted_content = $this->format_article_content($content);
// 创建文章数据
$post_data = array(
'post_title' => $topic,
'post_content' => $formatted_content,
'post_status' => 'publish',
'post_date' => $today,
'post_author' => 1, // 默认为管理员
'post_category' => $this->default_categories
);
// 插入文章到WordPress
$post_id = wp_insert_post($post_data);
if ($post_id && !is_wp_error($post_id)) {
// 文章发布成功,可添加额外处理逻辑
update_post_meta($post_id, '_huawei_ai_generated', 1);
return $post_id;
} else {
error_log('文章发布失败: ' . print_r($post_data, true));
return false;
}
}
// 获取今日文章主题
private function get_today_article_topic() {
// 可以根据日期、热门话题、网站主题等生成不同的主题
$topics = array(
'今日行业动态:' . date('Y年m月d日') . '最新资讯',
date('Y年m月d日') . '科技前沿:' . $this->get_random_tech_topic(),
'每日知识分享:' . $this->get_random_knowledge_topic()
);
return $topics[array_rand($topics)];
}
// 获取随机科技主题
private function get_random_tech_topic() {
$tech_topics = array(
'人工智能发展趋势',
'云计算技术应用',
'大数据分析实践',
'区块链技术创新',
'5G通信技术进展',
'物联网应用案例'
);
return $tech_topics[array_rand($tech_topics)];
}
// 获取随机知识主题
private function get_random_knowledge_topic() {
$knowledge_topics = array(
'历史上的今天',
'科学小常识',
'生活技巧分享',
'文化知识科普',
'健康养生指南'
);
return $knowledge_topics[array_rand($knowledge_topics)];
}
// 格式化文章内容
private function format_article_content($content) {
// 添加段落分隔
$content = preg_replace('/\n+/', '</p><p>', '<p>' . $content . '</p>');
// 随机插入相关图片(可调用图床API或本地图片)
$images = $this->get_related_images();
if ($images && rand(1, 3) == 1) { // 30%概率插入图片
$image_html = '<div class="article-image"><img src="' . $images[array_rand($images)] . '" alt=""></div>';
$content = $image_html . $content;
}
// 添加版权声明
$content .= '<p style="font-size: 14px; color: #999; text-align: right;">本文由AI自动生成于 ' . date('Y年m月d日 H:i:s') . '</p>';
return $content;
}
// 获取相关图片URL
private function get_related_images() {
// 实际应用中可调用图片API(如Unsplash、Pexels等)
return array(
'https://images.unsplash.com/photo-1501785888041-af3ef285b470',
'https://images.unsplash.com/photo-1493976040374-85c8e12f0c0e',
'https://images.unsplash.com/photo-1506794778202-cad84cf45f17'
);
}
}
六、网站 AI 对话功能实现
对话处理类
<?php
// AI对话处理类
class Huawei_AI_Chat_Handler {
private $api_client;
private $chat_history;
private $max_history_length = 5; // 最大对话历史长度
public function __construct() {
$this->api_client = new Huawei_AI_API_Client();
$this->chat_history = $this->get_chat_history();
}
// 处理用户对话
public function process_chat($history, $message) {
// 合并历史对话
if (!empty($history)) {
$this->chat_history = array_merge($this->chat_history, $history);
}
// 添加当前用户消息
$this->chat_history[] = array('user' => $message);
// 调用华为云API获取AI回复
$response = $this->api_client->process_chat($this->chat_history, $message);
// 添加AI回复到历史
$this->chat_history[] = array('ai' => $response);
// 限制历史长度
if (count($this->chat_history) > $this->max_history_length) {
array_shift($this->chat_history);
}
// 保存对话历史
$this->save_chat_history($this->chat_history);
return $response;
}
// 获取对话历史
private function get_chat_history() {
// 实际应用中可使用会话或缓存存储对话历史
$history = get_transient('huawei_ai_chat_history');
return $history ? $history : array();
}
// 保存对话历史
private function save_chat_history($history) {
// 使用WordPress transient存储对话历史(实际应用中建议使用会话或用户元数据)
set_transient('huawei_ai_chat_history', $history, 86400); // 保存24小时
}
}
七、AI机器人给网站进行自动评论功能截图
四、总结与展望
总体而言,WordPress 对接华为云 ModelArts Studio 大模型为网站运营带来了巨大价值,自动化内容生成和 AI 对话功能显著提升了网站竞争力。尽管存在成本、内容审核和性能优化等方面的问题,但这些都是可以通过技术优化和合理配置逐步解决的。未来,期待华为云在大模型技术上不断创新,降低使用成本,提高模型精准度;同时,也希望能进一步优化与 WordPress 的集成方式,实现更深度的功能融合,为用户带来更智能、更便捷的网站体验。