华为云Flexus+DeepSeek征文|WordPress 二次开发对接华为云 ModelArts Studio 实现自动化内容生成、AI自动回复、评论(代码披露)

前言

在当今数字化时代,自动化内容生成和智能对话功能已成为提升网站用户体验和运营效率的重要手段。下面将详细介绍如何通过 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 '抱歉,我暂时无法回答这个问题。';
        }
    }
}

五、自动化文章生成功能实现

  1. 文章生成与发布类
<?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 的集成方式,实现更深度的功能融合,为用户带来更智能、更便捷的网站体验。

在这里插入图片描述

### 华为云 ModelArts 的服务器资源配置与分配方法 华为云 ModelArts 是一款面向 AI 开发者的全流程服务平台,支持数据预处理、模型训练、部署等功能。关于 ModelArts 的服务器资源配置与分配方法,可以从以下几个方面展开说明: #### 1. **计算资源的选择** ModelArts 提供多种类型的计算资源以满足不同的应用场景需求。例如,在 Flexus 云服务中提到的 Flexus 云服务器 X 实例和 Flexus 应用服务器 L 实例均可作为底层支撑[^1]。开发者可以根据具体的业务场景选择适合的实例类型,比如 GPU 加速实例用于深度学习训练。 对于 Yolo 模型开发这样的任务,则可能更多依赖于高性能 GPU 资源来加速模型训练过程[^2]。因此,在实际操作前需明确所需硬件规格(如 CPU 核心数、内存大小、GPU 类型及其数量),并通过平台提供的选项完成配置。 #### 2. **账户管理与初次设置** 当获得由管理员分发给每位用户的独立账号之后,首次登录时会被引导至修改默认密码页面[^4]。这一步骤非常重要,不仅保障个人隐私同时也增强了系统的安全性。 接着按照指引进入主界面并确认所选区域是否正确无误——因为不同地理位置可能会对应不一样的数据中心和服务延迟情况等因素影响最终效果表现。另外值得注意的是,“收藏”功能可以帮助快速定位常用工具或模块位置以便日后高效调用。 #### 3. **具体配置流程** - 登录到指定网址后输入用户名及新设定后的密码; - 找到左侧菜单栏里的“三道杠”按钮打开全部可用选项列表; - 定位目标地域节点信息后再切换回原路径继续浏览其他子栏目内容直到找到标注名称为 “ModelArts”的链接入口处单击跳转过去即可开始正式探索之旅啦! 此外还有些额外的小贴士可供参考借鉴:如果希望减少每次重新查找的时间成本的话不妨试试看那个固定图标的功能哟~它能让经常使用的某些特定项目始终保持在显眼的位置方便随时取阅查阅哦~ ```python # 示例代码展示如何连接远程服务器进行自动化脚本编写 import paramiko ssh_client =paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_client.connect(hostname='your_server_ip', username='root', password='password') stdin, stdout, stderr = ssh_client.exec_command('nvidia-smi') print(stdout.read().decode()) ssh_client.close() ``` 以上就是有关华为云 ModelArts 平台下服务器资源配置的一些基本介绍及相关注意事项。合理规划好各项参数指标能够极大地提升工作效率同时降低成本支出比例达到双赢局面的效果呢! ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值