前言
满足了新技术跟机器人,后续追加尝试了。看了很多文章不如亲自动手试试。今日前端早读课文章由 @尼奥投稿分享。
正文从这开始~~
Siri ChatGPT 使用教程
将 Siri 接入 ChatGPT,直接语音唤醒,并且支持连续对话。
第一步:拷贝项目
点击右上角「Get a copy」,这会打开 AirCode,并基于此模板创建一个你自己的项目。如果没登录的话,可能会先跳转到登录页面,推荐使用 GitHub 登录,会快一些。
在弹出的创建对话框中,输入你的项目名称,并点击「Create」完成创建。
第二步:将 OpenAI Key 填入到环境变量中
登录到你的 OpenAI 账号中(如果还没有,需要注册一个),进入「API Keys」页面,点击「Create new secret key」创建一个密钥。
在弹出的对话框中,点击复制图标,将这个 API Key 复制并保存下来。注意:正确的 API Key 都是以 sk- 开头的字符串。
进入刚才创建好的 AirCode 应用中,在「Environments」标签页,将复制的 API Key 的值填入「OPENAI_KEY」这一项的 value 中。
第三步:部署 AirCode 应用
填完环境变量后,点击页面最上方的「Deploy」按钮,在弹出对话框中点击「Deploy」,开始部署。
部署成功后,在左侧文件列表中选中「chat.js」,可以看到中间编辑器部分,文件下方有一个 URL,点击复制这个 URL。
我们可以测试一下系统是否运行正常。将这个 URL 在新标签页打开,并在后面加上?question = 你好,如果返回的结果包含正常的 reply 信息,则代表一切正常。注意:因为 ChatGPT 响应需要一定的时间,视网络状况大概 15 到 45 秒不等,所以请耐心等待,不要频繁刷新页面。
第四步:添加 iPhone 快捷指令
在 iPhone 的浏览器中,打开以下链接。
https://www.icloud.com/shortcuts/96820bde426948918c25ed0d7a4c548f
在打开的页面中点击「获取捷径」按钮,然后在弹出的窗口中点击「添加快捷指令」。
点击刚刚添加成功的快捷指令右上角的三个点,打开快捷指令的编辑页面。将上面「第三步」中获取到的 AirCode 云函数的 URL 填入「文本」区域,点击右上角「完成」。注意:云函数 URL 是类似 https://xxxx.hk.aircode.run/chat 这样的格式。
使用
至此,你完成了所有配置过程,直接在手机中通过「嘿 Siri,打开机器人」就可以唤醒 ChatGPT,然后问问题了。
另外,你也可以在快捷指令的编辑页面中,点击下方的「分享」按钮,在弹出的菜单中选择「添加到主屏幕」,这样就可以在桌面通过点击打开对话框。
Enjoy your life with ChatGPT!
chat.js
// @see https://docs.aircode.io/guide/functions/
const aircode = require('aircode');
const { Configuration, OpenAIApi } = require('openai');
const { v4: uuidv4 } = require('uuid');
const { db } = aircode;
const ChatTable = db.table('chat');
// Setup OpenAI configurations
const OPENAI_KEY = process.env.OPENAI_KEY || "";
const OPENAI_MODEL = process.env.MODEL || "gpt-3.5-turbo";
const MAX_MESSAGES_PER_CHAT = 40;
const systemContent = 'You are a helpful assistant.';
module.exports = async function(params, context) {
console.log('Received params:', params);
const { question, cid } = params;
// Create a chat ID if not provided
const chatId = cid ? cid : uuidv4();
// Save user's question to the ChatTable
await ChatTable.save({ chatId, role: 'user', content: question });
// Retrieve chat history
const chats = await ChatTable
.where({ chatId })
.sort({ createdAt: -1 })
.limit(MAX_MESSAGES_PER_CHAT)
.find();
// Construct message array for GPT-3.5 Turbo
const messages = [
{ role: 'system', content: 'You are a helpful assistant.' },
...chats.reverse().map(one => ({ role: one.role, content: one.content })),
];
const openai = new OpenAIApi(new Configuration({ apiKey: OPENAI_KEY }));
try {
// Request completion from GPT-3.5 Turbo
const completion = await openai.createChatCompletion({
model: OPENAI_MODEL,
messages,
temperature: 1,
n: 1,
stream: false,
});
const responseMessage = completion.data.choices[0].message;
// Save generated response to ChatTable
await ChatTable.save({ chatId, ...responseMessage });
// Return response message and chat ID
return { reply: responseMessage.content, cid: chatId };
} catch (error) {
// Set the response status to 500 (Internal Server Error)
context.status(500);
// Log the error
console.log('error', error.response || error);
// Initialize an error message variable
let errorMessage;
// If there is a response object in the error,
// it means the request was made and the server responded with an error status
if (error.response) {
const { status, statusText, data } = error.response;
if (status === 401) {
// If the status code is 401, set a specific error message related to the OpenAI API key
errorMessage = 'Unauthorized: Invalid OpenAI API key, please check your API key in the AirCode Environments tab.';
} else if (data.error && data.error.message) {
// If there is an error message in the data, use it as the error message
errorMessage = data.error.message;
} else {
// Otherwise, use the status code and status text as the error message
errorMessage = `Request failed with status code ${status}: ${statusText}`;
}
} else if (error.request) {
// If there is a request object in the error,
// it means the request was made but no response was received
errorMessage = 'No response received from the server';
} else if (error.code === 'ENOTFOUND' || error.code === 'ECONNREFUSED') {
// If there is a network error, such as DNS resolution or connection refused
errorMessage = `Network error: ${error.message}`;
} else {
// If none of the above conditions are met,
// it means there was an error setting up the request
errorMessage = `Request setup error: ${error.message}`;
}
// Return an object containing the error message
return { error: errorMessage };
}
};
最后,在 github 上也有不少开源的在 Siri 上跑的 Demo,有兴趣的可以去尝试看看。
关于本文
作者:@尼奥
原文:https://aircode.cool/828668wg5a
这期前端早读课
对你有帮助,帮” 赞 “一下,
期待下一期,帮” 在看” 一下 。