logo
/
iOS Siri 接入 ChatGPT
Get a copy
3.8k
将 Siri 接入 ChatGPT,直接语音唤醒,并且支持连续对话
  • README.md
    arrow

    Siri ChatGPT 使用教程

    将 Siri 接入 ChatGPT,直接语音唤醒,并且支持连续对话。

    第一步:拷贝项目

    1. 通过 AirCode 源码链接中右上角的「Get a copy」按钮快速生成一个自己的 AirCode Node.js 应用。 注意不要直接复制代码,如果是直接复制纯代码粘贴过去,需要再手工安装 NPM 依赖包。 如果没有登录,需先登录 AirCode。推荐使用 GitHub 登录,会快一些。

    1. 在弹出的创建对话框中,输入你的项目名称,并点击「Create」完成创建。

    第二步:将 OpenAI Key 填入到环境变量中

    1. 登录到你的 OpenAI 账号中(如果还没有,需要注册一个),进入「API Keys」页面,点击「Create new secret key」创建一个密钥。

    2. 在弹出的对话框中,点击复制图标,将这个 API Key 复制并保存下来。注意:正确的 API Key 都是以 sk- 开头的字符串。

    3. 进入刚才创建好的 AirCode 应用中,在「Environments」标签页,将复制的 API Key 的值填入「OPENAI_KEY」这一项的 value 中。

    第三步:部署 AirCode 应用

    1. 填完环境变量后,点击页面最上方的「Deploy」按钮,在弹出对话框中点击「Deploy」,开始部署。

    2. 部署成功后,在左侧文件列表中选中「chat.js」,可以看到中间编辑器部分,文件下方有一个 URL,点击复制这个 URL。

    3. 我们可以测试一下系统是否运行正常。将这个 URL 在新标签页打开,并在后面加上 ?question=你好,如果返回的结果包含正常的 reply 信息,则代表一切正常。注意:因为 ChatGPT 响应需要一定的时间,视网络状况大概 15 到 45 秒不等,所以请耐心等待,不要频繁刷新页面。

    第四步:添加 iPhone 快捷指令

    1. 在 iPhone 的浏览器中,打开以下链接。

      https://www.icloud.com/shortcuts/96820bde426948918c25ed0d7a4c548f

    2. 在打开的页面中点击「获取捷径」按钮,然后在弹出的窗口中点击「添加快捷指令」。

    3. 点击刚刚添加成功的快捷指令右上角的三个点,打开快捷指令的编辑页面。将上面「第三步」中获取到的 AirCode 云函数的 URL 填入「文本」区域,点击右上角「完成」。注意:云函数 URL 是类似 https://xxxx.hk.aircode.run/chat 这样的格式。

    使用

    至此,你完成了所有配置过程,直接在手机中通过「嘿 Siri,打开机器人」就可以唤醒 ChatGPT,然后问问题了。

    另外,你也可以在快捷指令的编辑页面中,点击下方的「分享」按钮,在弹出的菜单中选择「添加到主屏幕」,这样就可以在桌面通过点击打开对话框。

    Enjoy your life with ChatGPT!

    问题反馈

    更多阅读

  • chat.js
    arrow
    1// @see https://docs.aircode.io/guide/functions/
    2const aircode = require('aircode');
    3const { Configuration, OpenAIApi } = require('openai');
    4const { v4: uuidv4 } = require('uuid');
    5
    6const { db } = aircode;
    7const ChatTable = db.table('chat');
    8
    9// Setup OpenAI configurations
    10const OPENAI_KEY = process.env.OPENAI_KEY || '';
    11// Use the latest OpenAI GPT-3.5 model, if the next 4 is released, modify this parameter
    12// OpenAI models parameter list https://platform.openai.com/docs/models
    13const OPENAI_MODEL = process.env.MODEL || 'gpt-3.5-turbo';
    14const MAX_MESSAGES_PER_CHAT = 40;
    15
    16const systemContent = 'You are a helpful assistant.';
    17
    18module.exports = async function (params, context) {
    19  console.log('Received params:', params);
    20  const { question, cid } = params;
    21
    22  // Create a chat ID if not provided
    23  const chatId = cid ? cid : uuidv4();
    24
    25  // Save user's question to the ChatTable
    26  await ChatTable.save({ chatId, role: 'user', content: question });
    27
    28  // Retrieve chat history
    29  const chats = await ChatTable.where({ chatId })
    30    .sort({ createdAt: -1 })
    31    .limit(MAX_MESSAGES_PER_CHAT)
    32    .find();
    33
    34  // Construct message array for ChatGPT
    35  const messages = [
    36    { role: 'system', content: 'You are a helpful assistant.' },
    37    ...chats.reverse().map((one) => ({ role: one.role, content: one.content })),
    38  ];
    39
    40  const openai = new OpenAIApi(new Configuration({ apiKey: OPENAI_KEY }));
    41
    42  try {
    43    // Request completion from ChatGPT
    44    const completion = await openai.createChatCompletion({
    45      model: OPENAI_MODEL,
    46      messages,
    47      temperature: 1,
    48      n: 1,
    49      stream: false,
    50    });
    51
    52    const responseMessage = completion.data.choices[0].message;
    53
    54    // Save generated response to ChatTable
    55    await ChatTable.save({ chatId, ...responseMessage });
    56
    57    // Return response message and chat ID
    58    return { reply: responseMessage.content, cid: chatId };
    59  } catch (error) {
    60    // Set the response status to 500 (Internal Server Error)
    61    context.status(500);
    62    // Log the error
    63    console.log('error', error.response || error);
    64
    65    // Initialize an error message variable
    66    let errorMessage;
    67
    68    // If there is a response object in the error,
    69    // it means the request was made and the server responded with an error status
    70    if (error.response) {
    71      const { status, statusText, data } = error.response;
    72
    73      if (status === 401) {
    74        // If the status code is 401, set a specific error message related to the OpenAI API key
    75        errorMessage =
    76          'Unauthorized: Invalid OpenAI API key, please check your API key in the AirCode Environments tab.';
    77      } else if (status === 429) {
    78				errorMessage = 'You encounter a OpenAI ChatGPT 429 situation, need to go to OpenAI and pay for more quotas. ChatGPT Plus is only for web-based payments, the API is another channel that requires payment per token.';
    79			} else if (data.error && data.error.message) {
    80        // If there is an error message in the data, use it as the error message
    81        errorMessage = data.error.message;
    82      } else {
    83        // Otherwise, use the status code and status text as the error message
    84        errorMessage = `Request failed with status code ${status}: ${statusText}`;
    85      }
    86    } else if (error.request) {
    87      // If there is a request object in the error,
    88      // it means the request was made but no response was received
    89      errorMessage = 'No response received from the server';
    90    } else if (error.code === 'ENOTFOUND' || error.code === 'ECONNREFUSED') {
    91      // If there is a network error, such as DNS resolution or connection refused
    92      errorMessage = `Network error: ${error.message}`;
    93    } else {
    94      // If none of the above conditions are met,
    95      // it means there was an error setting up the request
    96      errorMessage = `Request setup error: ${error.message}`;
    97    }
    98
    99    // Return an object containing the error message
    100    return { error: errorMessage };
    101  }
    102};
    103
  • Runtime
    arrow
    • Node.js versionnode/v16
    • Function execution timeout60 s
  • Dependencies
    arrow
    • aircode0.2.12
    • openai3.2.1
    • uuid9.0.0
  • Environments
    arrow
    arrow
    • OPENAI_KEY