logo
/
SiriGPT
Get a copy
146
Connect Siri to ChatGPT in 5 minutes with JavaScript.
  • README.md
    arrow

    SiriGPT Tutorial

    Connect Siri to ChatGPT for direct voice activation and support for continuous conversation.

    Step 1: Get a Copy

    Deploy to AirCode

    1. Click the Deploy to AirCode button. This will open AirCode and create an application based on this template. If you're not logged in, you may be redirected to the login page. It is recommended to log in with GitHub for a faster experience.

    1. In the create dialog that pops up, enter your application name and click Create to finish.

    Step 2: Fill in Environment Variables with OpenAI Key

    1. Log in to your OpenAI account (if you don't have one, you'll need to register). Go to the API Keys page and click Create new secret key to create a new key.

    2. In the pop-up dialog, click the copy icon to copy and save the API Key. Note: Correct API Keys always start with sk-.

    3. Go to the AirCode app you just created, and on the Environments tab, paste the copied API Key value into the OPENAI_KEY field.

    Step 3: Deploy the AirCode App

    1. After filling in the environment variables, click the Deploy button at the top of the page. In the pop-up dialog, click Deploy to start the deployment process.

    2. Once the deployment is successful, select the chat.js file in the left file list. In the middle editor section, you'll see a URL at the bottom of the file. Click to copy this URL.

    3. We can test if the system is running correctly. Open the copied URL in a new browser tab, and add ?question=Hello at the end. If the returned result contains a normal reply message, then everything is working as expected.

      Note: Since ChatGPT responses take some time, depending on your network conditions, it may take around 15 to 45 seconds. Please be patient and avoid refreshing the page frequently.

    Step 4: Add iPhone Shortcut

    1. On your iPhone's browser, open the following link:

      https://www.icloud.com/shortcuts/6b58235ee5c34c3eabb1742c95b2d0d2

    2. On the opened page, tap Get Shortcut button, and then tap Add Shortcut in the pop-up window.

    3. Tap the three dots in the upper-right corner of the successfully added shortcut to open the shortcut's edit page. Fill in the Text area with the AirCode cloud function URL obtained in Step 3 above, and tap Done in the upper-right corner.

      Note: The cloud function URL should be in a format similar to https://xxxx.hk.aircode.run/chat.

    Usage

    At this point, you have completed all the setup steps. Simply use the voice command "Hey Siri, open ChatGPT" on your phone to invoke ChatGPT and start asking questions.

    Additionally, you can also add a shortcut to your home screen. In the shortcut's edit page, tap the Share button at the bottom, and select Add to Home Screen from the pop-up menu. This way, you can open the dialog box by tapping the icon on your home screen.

    Enjoy your life with ChatGPT!

    Community and Support

    Need help or want to connect with other AirCode users? Check out these community and support resources:

    • Community Forum: Request features, discussion about best practices or ask questions about AirCode.
    • GitHub Issues: Report bugs and errors you encounter while using AirCode.
    • Discord: Join our Discord community to chat with other users, get help, and share your experiences with AirCode.
    • Email Support: Reach out to our team directly for assistance through email.
  • 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 (data.error && data.error.message) {
    78        // If there is an error message in the data, use it as the error message
    79        errorMessage = data.error.message;
    80      } else {
    81        // Otherwise, use the status code and status text as the error message
    82        errorMessage = `Request failed with status code ${status}: ${statusText}`;
    83      }
    84    } else if (error.request) {
    85      // If there is a request object in the error,
    86      // it means the request was made but no response was received
    87      errorMessage = 'No response received from the server';
    88    } else if (error.code === 'ENOTFOUND' || error.code === 'ECONNREFUSED') {
    89      // If there is a network error, such as DNS resolution or connection refused
    90      errorMessage = `Network error: ${error.message}`;
    91    } else {
    92      // If none of the above conditions are met,
    93      // it means there was an error setting up the request
    94      errorMessage = `Request setup error: ${error.message}`;
    95    }
    96
    97    // Return an object containing the error message
    98    return { error: errorMessage };
    99  }
    100};
    101
  • 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