三分钟把ChatGPT接入Siri,让你的语音助手化身智能AI

5 篇文章 3 订阅

最近,各种各样使用ChatGPT的方式都出现了,但是有很多都需要在电脑操作,或者点击别人的各种各样的链接,而且有些可能还要魔法上网才能实现,这些都是稍微有点繁琐的。

那么,最方便的还是直接使用我们的手机一键打开或者语音唤醒就可以实现链接ChatGPT的,下边我们就来看下怎么实现吧!

1. 效果展示
  • 连续对话

  • 手动输入

2. 云函数实现

我们仍然使用Laf云平台来实现,如何注册Laf和安装依赖,见上篇文章 《使用Laf云平台,两步将ChatGPT接入微信公众号(含代码)》

  • 创建Siri云函数

创建云函数步骤

// siri.js
// 引入必要的库
import cloud from '@lafjs/cloud';
const { v4: uuidv4 } = require('uuid');
const axios = require('axios');

// 创建数据库连接
const db = cloud.database();
const ChatTable = db.collection('siri')


// 设置key和模型
const OPENAI_KEY = process.env.OPENAI_KEY || "YOUR API-KEY";
const OPENAI_MODEL = process.env.MODEL || "gpt-3.5-turbo";
const MAX_MESSAGES_PER_CHAT = 40;


export async function main(params, context) {
  console.log('siri入参:', params);
  const { question, cid } = params.body;

  // 创建一个id
  const chatId = cid ? cid : uuidv4();

  // 保存用户问题
  await ChatTable.add({ chatId, role: 'user', content: question });

  // 获取历史信息
  const chats = await ChatTable
    .where({ chatId })
    .orderBy("createdAt", "desc").limit(MAX_MESSAGES_PER_CHAT).get();

  // 组装问题prompt
  const messages = [
    { role: 'system', content: 'You are a helpful assistant.' },
    ...chats.data.map(one => ({ role: one.role, content: one.content })),
  ];

  const data = JSON.stringify({
    model: OPENAI_MODEL,
    messages: messages
  });

  const config: any = {
    method: 'post',
    maxBodyLength: Infinity,
    url: 'https://api.openai.com/v1/chat/completions',
    headers: {
      Authorization: `Bearer ${OPENAI_KEY}`,
      "Content-Type": "application/json",
    },
    data: data,
    timeout: 50000
  };

  try {
    // 发送请求
    const completion = await axios(config);

    const responseMessage = completion.data.choices[0].message;

    // 保存返回结果
    await ChatTable.add({ chatId, ...responseMessage });

    // 返回结果
    return { reply: responseMessage.content, cid: chatId };

  } catch (error) {
    // 打印错误日志
    console.log('error', error.response || error);


    let errorMessage;

    // 处理返回报错信息
    if (error.response) {
      const { status, statusText, data } = error.response;

      if (status === 401) {
        errorMessage = 'Unauthorized: Invalid OpenAI API key, please check your API key in the AirCode Environments tab.';
      } else if (data.error && data.error.message) {
        errorMessage = data.error.message;
      } else {
        errorMessage = `Request failed with status code ${status}: ${statusText}`;
      }
    } else if (error.request) {
      errorMessage = 'No response received from the server';
    } else if (error.code === 'ENOTFOUND' || error.code === 'ECONNREFUSED') {
      errorMessage = `Network error: ${error.message}`;
    } else {
      errorMessage = `Request setup error: ${error.message}`;
    }
    return { error: errorMessage };
  }
};

最新代码可见:https://github.com/husanr/siri_gpt_laf

3. 添加快捷指令
  • 打开以下链接,添加快捷指令。
    https://www.icloud.com/shortcuts/6f550307e3724769b3e7fc493c07aae6
  • 在打开的页面中点击获取捷径按钮,然后在弹出的窗口中点击添加快捷指令

  • 添加过之后,在快捷指令中找到刚添加打开机器人快捷指令,点击右上角三个点进入编辑页面,然后把上边发布的Siri云函数的地址复制粘贴到文本的位置,然后点击完成。

  • 到此,语音助手设置完成,你可以通过语音嘿 Siri,打开机器人 唤醒带有ChatGPT的语音助手了,快去体验吧!

  • 如果你想要在手机主屏幕通过输入文字与ChatGPT交互,那么你可以把快捷指令添加到主屏幕,如下:


原文地址:https://aircode.cool/828668wg5a

大功告成!

关注我的公众号,更多精彩内容等你来看!

  • 4
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
好的,@Mapper注解是Mybatis框架中用于标识数据访问层接口的注解,用于告诉Spring容器将该接口类实例化并注入到其他Bean中。其使用步骤如下: 1. 在Spring Boot项目中引入Mybatis和Mybatis-Spring的依赖 2. 在配置文件中配置数据源和Mybatis的相关属性 3. 创建一个数据访问层接口,使用@Mapper注解标识该接口 4. 在该数据访问层接口中定义需要操作的数据库方法 5. 在Service或Controller中注入该数据访问层接口的实例,并调用其中的方法 下面是一个示例: 1. 在pom.xml中添加Mybatis和Mybatis-Spring的依赖: ```xml <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.1</version> </dependency> ``` 2. 在application.properties中配置数据源和Mybatis的相关属性: ```properties spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=123456 mybatis.type-aliases-package=com.example.demo.entity mybatis.mapper-locations=classpath:mapper/*.xml ``` 3. 创建一个数据访问层接口UserMapper,使用@Mapper注解标识该接口: ```java @Mapper public interface UserMapper { User selectByPrimaryKey(Integer id); int insert(User record); int updateByPrimaryKey(User record); int deleteByPrimaryKey(Integer id); } ``` 4. 在mapper目录下创建UserMapper.xml,定义需要操作的数据库方法: ```xml <mapper namespace="com.example.demo.mapper.UserMapper"> <resultMap id="BaseResultMap" type="com.example.demo.entity.User"> <id column="id" property="id" jdbcType="INTEGER"/> <result column="username" property="username" jdbcType="VARCHAR"/> <result column="password" property="password" jdbcType="VARCHAR"/> </resultMap> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer"> select * from user where id = #{id,jdbcType=INTEGER} </select> <insert id="insert" parameterType="com.example.demo.entity.User" useGeneratedKeys="true" keyProperty="id"> insert into user (username, password) values (#{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}) </insert> <update id="updateByPrimaryKey" parameterType="com.example.demo.entity.User"> update user set username = #{username,jdbcType=VARCHAR}, password = #{password,jdbcType=VARCHAR} where id = #{id,jdbcType=INTEGER} </update> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> delete from user where id = #{id,jdbcType=INTEGER} </delete> </mapper> ``` 5. 在Service或Controller中注入UserMapper的实例,并调用其中的方法: ```java @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public User selectByPrimaryKey(Integer id) { return userMapper.selectByPrimaryKey(id); } @Override public int insert(User user) { return userMapper.insert(user); } @Override public int updateByPrimaryKey(User user) { return userMapper.updateByPrimaryKey(user); } @Override public int deleteByPrimaryKey(Integer id) { return userMapper.deleteByPrimaryKey(id); } } ``` 这就是使用@Mapper注解的基本步骤,希望对你有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端每日三省

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值