马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
一、引言
在前次小弟发布了一款基于openai大模子的Chrome网页插件后,有很多朋友向我提意见,表示这个插件需要翻墙,对于真正的小白还是有些不友好。因此这次我花了两个通宵,完成了一款基于百度文心一言大模子的网页插件的创作。本文将以作为一款商品品评的智能回复工具为例,具体介绍插件的功能及利用方法,大家可以根据本身的需求魔改插件,实现不同的目标,例如文稿助手、谈天助手等。本插件完全开源,也欢迎大家一起学习,或作为课设毕设利用。
二、功能展示
本文以作为商品品评智能回复工具的目标为例,具体展示插件各功能。
在普通模式下,用户可以将消耗者的品评输入进插件,插件将会调用百度api进行智能回复。
而在高级模式下,用户可以选择四种情绪模式、三种回复策略来让插件作答,如图所示,每种模式将会有不同的表达,如许能让商家对于不同范例的买家品评做出最得当且快速的回复。
三、插件部署
对于插件本身来说,包罗这几个文件:
1.manifest.json
- {
- "manifest_version": 3,
- "name": "Wenxin Chat reply",
- "version": "1.0",
- "description": "A Chrome extension to chat with Baidu Wenxin",
- "permissions": [
- "activeTab",
- "storage"
- ],
- "background": {
- "service_worker": "background.js"
- },
- "action": {
- "default_popup": "popup.html",
- "default_icon": {
- "16": "icons/icon16.png",
- "48": "icons/icon48.png",
- "128": "icons/icon128.png"
- }
- },
- "icons": {
- "16": "icons/icon16.png",
- "48": "icons/icon48.png",
- "128": "icons/icon128.png"
- }
- }
复制代码
2.popup.html(插件前端页面)
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>文心一言商家智能回复</title>
- <style>
- html, body {
- width: 500px; /* 调整宽度 */
- height: 100%;
- margin: 0;
- padding: 0;
- box-sizing: border-box;
- }
- </style>
- <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">
- <link rel="stylesheet" href="./style.css">
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-icons/1.7.2/font/bootstrap-icons.min.css">
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
- </head>
- <body>
- <div class="container mt-4">
- <h1 class="text-center mb-4">文心一言商品评价回复</h1>
- <div class="form-check form-switch mb-3">
- <span id="mode-text">智能回复(高级模式)</span>
- <input class="form-check-input" type="checkbox" role="switch" id="model-selector">
- <label class="form-check-label" for="model-selector"></label>
- </div>
- <p style="font-size: 17px;">消费者的评论</p>
- <div class="form mb-3">
- <textarea class="form-control" id="user-input" placeholder="请输入......" rows="4"></textarea>
- </div>
- <div id="review-section" class="d-none">
- <div class="mb-3">
- <p>选择情绪模式:</p>
- <div class="btn-group-vertical w-100" role="group">
- <input type="radio" class="btn-check" name="emotionStrategy" id="acknowledgement" autocomplete="off" checked>
- <label class="btn btn-outline-primary" for="acknowledgement">认可</label>
- <input type="radio" class="btn-check" name="emotionStrategy" id="informal" autocomplete="off">
- <label class="btn btn-outline-primary" for="informal">随和</label>
- <input type="radio" class="btn-check" name="emotionStrategy" id="attentiveness" autocomplete="off">
- <label class="btn btn-outline-primary" for="attentiveness">关注</label>
- <input type="radio" class="btn-check" name="emotionStrategy" id="encouragement" autocomplete="off">
- <label class="btn btn-outline-primary" for="encouragement">鼓励</label>
- </div>
- </div>
- <div class="mb-3">
- <p>选择回复策略:</p>
- <div class="btn-group-vertical w-100" role="group">
- <input type="radio" class="btn-check" name="rationalStrategy" id="explanation" autocomplete="off" checked>
- <label class="btn btn-outline-success" for="explanation">解释</label>
- <input type="radio" class="btn-check" name="rationalStrategy" id="redress" autocomplete="off">
- <label class="btn btn-outline-success" for="redress">补偿</label>
- <input type="radio" class="btn-check" name="rationalStrategy" id="facilitation" autocomplete="off">
- <label class="btn btn-outline-success" for="facilitation">改进</label>
- </div>
- </div>
- </div>
- <div class="d-grid gap-2 mb-4">
- <button id="send-button" class="btn btn-primary">提交</button>
- </div>
- <div id="response" class="p-3 bg-light border rounded" style="min-height: 100px;"></div>
- </div>
- <script src="./popup.js"></script>
- </body>
- </html>
复制代码
3.popup.js
- document.getElementById('model-selector').addEventListener('change', function() {
- const reviewSection = document.getElementById('review-section');
- if (this.checked) {
- reviewSection.classList.remove('d-none');
- } else {
- reviewSection.classList.add('d-none');
- }
- });
- document.getElementById('send-button').addEventListener('click', function () {
- const userInput = document.getElementById('user-input').value;
- const responseElement = document.getElementById('response');
- const isBasicMode = document.getElementById('model-selector').checked;
- const emotionStrategy = isBasicMode ? document.querySelector('input[name="emotionStrategy"]:checked').id : null;
- const rationalStrategy = isBasicMode ? document.querySelector('input[name="rationalStrategy"]:checked').id : null;
- responseElement.innerText = 'Loading...';
- chrome.runtime.sendMessage({ action: 'getWenxinResponse', content: userInput, emotionStrategy, rationalStrategy, isBasicMode }, function (response) {
- if (chrome.runtime.lastError) {
- responseElement.innerText = 'Error: ' + chrome.runtime.lastError.message;
- } else {
- responseElement.innerText = response;
- }
- });
- });
复制代码
4. background.js
- const serverUrl = 'http://127.0.0.1:3000'; // 代理服务器的URL
- function getAccessToken() {
- return new Promise((resolve, reject) => {
- fetch(`${serverUrl}/getAccessToken`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({})
- })
- .then(response => {
- if (!response.ok) {
- throw new Error(`HTTP error! Status: ${response.status}`);
- }
- return response.json();
- })
- .then(data => {
- if (data.access_token) {
- resolve(data.access_token);
- } else {
- throw new Error('Failed to retrieve access token');
- }
- })
- .catch(error => {
- console.error('Error fetching access token:', error);
- reject(error);
- });
- });
- }
- function getPrompt(userMessage, emotionStrategy, rationalStrategy, isBasicMode) {
- if (!isBasicMode) {
- return `我是一名商家,需要回复消费者对自己商品的评价:${userMessage}`;
- }
- let emotionPrompt = '';
- let rationalPrompt = '';
- switch (emotionStrategy) {
- case 'acknowledgement':
- emotionPrompt = '请用一种理解客户情绪的方式进行回答';
- break;
- case 'informal':
- emotionPrompt = '请用一种轻松、友好的语气与客户沟通';
- break;
- case 'attentiveness':
- emotionPrompt = '请表示你会关注客户的问题,并尽力解决';
- break;
- case 'encouragement':
- emotionPrompt = '请表达出你会改善的强烈意愿';
- break;
- }
- switch (rationalStrategy) {
- case 'explanation':
- rationalPrompt = '请解释客户投诉的原因';
- break;
- case 'redress':
- rationalPrompt = '请提供合适的补救措施来弥补';
- break;
- case 'facilitation':
- rationalPrompt = '请提出改进措施';
- break;
- }
- return `我是一名商家,需要回复消费者对自己商品的评价。${emotionPrompt}。${rationalPrompt}:${userMessage}`;
- }
- function getWenxinResponse(accessToken, userMessage, emotionStrategy, rationalStrategy, isBasicMode) {
- const prompt = getPrompt(userMessage, emotionStrategy, rationalStrategy, isBasicMode);
- return new Promise((resolve, reject) => {
- fetch(`${serverUrl}/getWenxinResponse`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({ accessToken, prompt })
- })
- .then(response => {
- if (!response.ok) {
- throw new Error(`HTTP error! Status: ${response.status}`);
- }
- return response.json();
- })
- .then(data => {
- if (data.result) {
- resolve(data.result);
- } else {
- throw new Error('Failed to retrieve Wenxin response');
- }
- })
- .catch(error => {
- console.error('Error fetching Wenxin response:', error);
- reject(error);
- });
- });
- }
- chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
- if (message.action === 'getWenxinResponse') {
- getAccessToken()
- .then(accessToken => getWenxinResponse(accessToken, message.content, message.emotionStrategy, message.rationalStrategy, message.isBasicMode))
- .then(response => sendResponse(response))
- .catch(error => sendResponse('Error: ' + error.message));
- return true; // Will respond asynchronously.
- }
- });
复制代码
5.style.css
- body {
- font-family: Arial, sans-serif;
- background-color: #f7f7f7;
- margin: 0;
- padding: 0;
- box-sizing: border-box;
- }
- .container {
- padding: 20px;
- max-width: 480px; /* 调整宽度 */
- margin: auto;
- background-color: #fff;
- border-radius: 8px;
- box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
- }
- .text-center {
- font-size: 24px;
- margin-bottom: 20px;
- color: #333;
- }
- .form-control {
- font-size: 16px;
- padding: 10px;
- border-radius: 4px;
- border: 1px solid #ddd;
- resize: none;
- }
- .btn-primary {
- background-color: #4CAF50;
- border-color: #4CAF50;
- border-radius: 4px;
- font-size: 16px;
- transition: background-color 0.3s ease;
- }
- .btn-primary:hover {
- background-color: #45a049;
- }
- .bg-light {
- background-color: #f1f1f1;
- border: 1px solid #ddd;
- border-radius: 4px;
- font-size: 14px;
- white-space: pre-wrap;
- }
- .btn-outline-primary {
- color: #007bff;
- border-color: #007bff;
- }
- .btn-outline-primary:hover {
- background-color: #007bff;
- color: #ffffff;
- }
- .btn-check:checked + .btn-outline-primary {
- background-color: #007bff;
- border-color: #007bff;
- color: #ffffff;
- }
- .btn-outline-success {
- color: #28a745;
- border-color: #28a745;
- }
- .btn-outline-success:hover {
- background-color: #28a745;
- color: #ffffff;
- }
- .btn-check:checked + .btn-outline-success {
- background-color: #28a745;
- border-color: #28a745;
- color: #ffffff;
- }
复制代码 末了,大家需要在文件内里创建一个icons文件夹,如果不会调代码,请往内里存放命名为icon16、icon48、icon128的图片。
四、服务器部署
CORS(跨域资源共享)策略限制题目足足硬控了笔者一天,欣赏器会制止从插件的背景脚本直接发送跨域请求到第三方API。为相识决这个题目,笔者先通过修改background.js权限、利用CORS署理服务等方法进行实验,但都以失败告终。无奈之下,只好通过部署了一个本地服务器,在服务器上创建一个署理,将请求转发到百度API,从而解决CORS题目。
创建一个新python项目,命名为wenxin_proxy_pythonreply(举例)
创建一个名为server.py的文件
- from flask import Flask, request, jsonify
- from flask_cors import CORS
- import requests
- app = Flask(__name__)
- CORS(app) # 启用CORS
- CLIENT_ID = '*****' # 替换为你的API Key
- CLIENT_SECRET = '****' # 替换为你的Secret Key
- @app.route('/getAccessToken', methods=['POST'])
- def get_access_token():
- url = f"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={CLIENT_ID}&client_secret={CLIENT_SECRET}"
- headers = {
- 'Content-Type': 'application/json'
- }
- response = requests.post(url, headers=headers, json={})
- if response.status_code == 200:
- return jsonify(response.json())
- else:
- return jsonify({'error': 'Failed to retrieve access token'}), response.status_code
- @app.route('/getWenxinResponse', methods=['POST'])
- def get_wenxin_response():
- data = request.get_json()
- access_token = data['accessToken']
- prompt = data['prompt']
- url = f"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-4.0-8k-0329?access_token={access_token}"
- payload = {
- "messages": [
- {
- "role": "user",
- "content": prompt
- }
- ]
- }
- headers = {
- 'Content-Type': 'application/json'
- }
- response = requests.post(url, headers=headers, json=payload)
- if response.status_code == 200:
- return jsonify(response.json())
- else:
- return jsonify({'error': 'Failed to retrieve Wenxin response'}), response.status_code
- if __name__ == '__main__':
- app.run(host='0.0.0.0', port=3000)
复制代码 复制后,在对应位置填入API Key和Secret Key,并在终端分别运行这两段代码
- pip install flask requests
复制代码 然后运行server.py
如果没有报错,就将之前插件的文件夹在chrome://extensions/里打开,选择开辟者模式并点击“加载已解压的拓展步伐”。
末了,点击插件,输入内容,如果能够乐成运行,那么恭喜你大功告成。
五、总结
一款即插即用的多功能网页插件,能根据个人需求魔改成各种工具,欢迎大家交流学习!如有不解之处,请仔细阅读API调用文档https://cloud.baidu.com/doc/WENXINWORKSHOP/s/xlvlzz84k,或与我接洽,我将尽我所能。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |