取得 API_TOKEN
官方网站
Hugging Face
登入后,只要去管理页面找到 Access Tokens ,创立一个属于你的 Token 就好了
Python 程式码
我简单先用 Python 玩一下
# 我记得 json 函式库不用特别下载,预设就有了import json# 没有 requests 函式库的人要记得用 `pip install requests` 下载喔~import requestsAPI_TOKEN = "hf_l...." # 请换上你的 API_TOKENModel_ID = "facebook/blenderbot-3B" # 可以换成你想要使用的 Modeldef query(payload): headers = {"Authorization": f"Bearer {API_TOKEN}"} API_URL = "https://api-inference.huggingface.co/models/" + Model_ID data = json.dumps(payload) response = requests.request("POST", API_URL, headers=headers, data=data) return json.loads(response.content.decode("utf-8"))data = query({"inputs": "HI"})print(data) # 可以自行看他回传什么print(data["generated_text"]) # Hello, how are you today??? or Hi! How are you doing?
Google Apps Script 内部档案分布
再来用 Google Apps Script 玩一下
主程式原始码(doPost)
var CHANNEL_ACCESS_TOKEN="" // 请放上自己的CHANNEL_ACCESS_TOKENvar API_token = "hf_l...." // 请换上你的 API_TOKENvar Model_ID = "facebook/blenderbot-3B" // 可以换成你想要使用的 Modelfunction doPost(e) { //从接收到的讯息中取出 replyToken 和发送的讯息文字资讯 var msg = JSON.parse(e.postData.contents); var replyToken = msg.events[0].replyToken; var type = msg.events[0].type; var userid = msg.events[0].source.userId; var groupid = msg.events[0].source.groupId; // 只接收纯文字的讯息 if (type == 'message' && msg.events[0].message.text != null) { var userMessage = msg.events[0].message.text; } else { return 0 } reply_msg = JSON.parse(hf_chat_api(userMessage))["generated_text"] reply_message(replyToken, [{ 'type': 'text', 'text': reply_msg }])}
hf_chat_api()
function hf_chat_api(message) { return UrlFetchApp.fetch('https://api-inference.huggingface.co/models/'+Model_ID, { 'method': 'post', 'headers': { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + API_token, }, "payload": JSON.stringify(message) })}
程式码(网址)
去吧~ 我都放在连结里面了~
https://script.google.com/d/1DsfQ8u-mp7oP_qOxwA9rjXlG8gAvM16lUwOLd7roFXEzd_DmU3dtOENF/edit?usp=sharing
参考资料
https://huggingface.co/docs/api-inference/detailed_parameters
若以上有任何的错误都欢迎留言跟我说我会非常感谢你的(ノ>ω<)ノ
【GPT-3 LINE BOT】 系列
(1) 介绍 ChatGPT & GPT-3
(2) 玩坏 ChatGPT LINE BOT
(3) 创建属于自己的 ChatGPT LINE BOT
(4) 来人啊~ 上程式码 啦~~
(5) 同场加映:介绍 Hugging Face 及 Meta AI BlenderBot
(6) 同场加映:Hugging Face 串接 LINE BOT
(7) 同场加映:用 Python & Google Apps Script 玩 Hugging Face
接案 (☛´∀`*)☛ LINE ID:albert20699