让Chat-GPT成为你的微信小助理

news2024/10/5 13:15:10

前言

最近公司裁员风波,很不幸成为了裁员名单中的一员;此时又恰逢一波AIGC浪潮,首当其冲的就是GPT这样的大语言模型的诞生,是整个AI领域的一个质的飞跃。正好在这样一个空挡期,我就基于Chat-GPT 做了一些深入的实践,并将整个过程记录下来。

准备工作

  • 需要在OpenAI官方平台注册一个账号
    首先访问官网需要梯子,不然无法访问;
    账号注册时,最好使用谷歌邮箱,用国内的邮箱注册会返回一些异常的错误;
    注册第二步,需要接受一个短信验证,这里我使用的是sms-activate平台(可以百度一下使用方式),主要就是获取一个临时的国际号码,来获取验证码,我买的印尼🇮🇩的号码,比较便宜,充值1$能用好几次;

  • 获取API-Key
    注册成功后,点击头像,选择Views API Keys,然后+ Create New Secret Key

接入

OpenAI 提供了多种接入方式,包括Python,Node,云API等等

1.Python方式

//安装OpenAI模块
pip install openai
import os
import openai
//组织信息(如果存在多组织)
openai.organization = "org-CfErNk1yqg8HSj5mzWA6AUwA"
//OpenAI-Key
openai.api_key = os.getenv("OPENAI_API_KEY")
//获取训练模型列表
openai.Model.list()
//Completion方式互动
response = openai.Completion.create(
      model="text-davinci-003", 
      prompt="Say this is a test", 
      temperature=0, 
      max_tokens=7
)

2.Node.js 方式

npm install openai
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
//Completion方式互动
const response = await openai.createCompletion({
  model: "text-davinci-003",
  prompt: "Say this is a test",
  temperature: 0,
  max_tokens: 7,
});
//ChatCompletion方式互动
const response1 = await openai.ChatCompletion.create(
  model="gpt-3.5-turbo",
  messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Who won the world series in 2020?"},
        {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},
        {"role": "user", "content": "Where was it played?"}
    ]
)

//ChatCompletion Respones
/*
{
 'id': 'chatcmpl-6p9XYPYSTTRi0xEviKjjilqrWU2Ve',
 'object': 'chat.completion',
 'created': 1677649420,
 'model': 'gpt-3.5-turbo',
 'usage': {'prompt_tokens': 56, 'completion_tokens': 31, 'total_tokens': 87},
 'choices': [
   {
    'message': {
      'role': 'assistant',
      'content': 'The 2020 World Series was played in Arlington, Texas at the Globe Life Field, which was the new home stadium for the Texas Rangers.'},
    'finish_reason': 'stop',
    'index': 0
   }
  ]
}
*/

3.云API

  • Completions 方式
    POST https://api.openai.com/v1/completions
header:
{
  "Content-Type: application/json",
  "Authorization: Bearer $OPENAI_API_KEY"
}
body:
{
  "model": "text-davinci-003",    //使用的模型id
  "prompt": "Say this is a test",  //用户输入的内容(提示词)
  "max_tokens": 7,    //最大token数(消费token 来计费)
  "temperature": 0,  //采样精度(0~2) 值越小,精度越高
  "top_p": 1, //概率质量系数, 默认为1
  "n": 1,  //为prompt生成的Completions个数
  "stream": false,  //是否采用流式响应
  "stop": "\n" //生成结果 停止标识符
}
respones:
{
  "id": "cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7",
  "object": "text_completion",
  "created": 1589478378,
  "model": "text-davinci-003",
  "choices": [
    {
      "text": "\n\nThis is indeed a test", //互动返回的结果
      "index": 0,
      "logprobs": null,
      "finish_reason": "length"
    }
  ],
  "usage": {                          // token 消费信息
    "prompt_tokens": 5,
    "completion_tokens": 7,
    "total_tokens": 12
  }
}
  • Chat 方式
    POST https://api.openai.com/v1/chat/completions
header:
{
  "Content-Type: application/json",
  "Authorization: Bearer $OPENAI_API_KEY"
}
body:
{
  "model": "gpt-3.5-turbo",
  "messages": [      //消息对象列表,每个对象都包含一个角色(user,system,assistant)和内容字段,支持填充默认/预设的上下文内容
      {"role": "system", "content": "你是一个得力助手,无所不能"},
      {"role": "assistant", "content": "我是得力小助手"},
      {"role": "user", "content": "说你好"}
  ]
}
response:
{
  "id": "chatcmpl-123",
  "object": "chat.completion",
  "created": 1677652288,
  "choices": [{
    "index": 0,
    "message": {
      "role": "assistant",
      "content": "\n\nHello there, how may I assist you today?",
    },
    "finish_reason": "stop"
  }],
  "usage": {
    "prompt_tokens": 9,
    "completion_tokens": 12,
    "total_tokens": 21
  }
}

上面是关于Chat-GPT相关的内容铺垫,接下看微信相关

WeChaty

GitHub地址:https://github.com/wechaty/wechaty
官方介绍:Wechaty is a RPA (Robotic Process Automation) SDK for Chatbot Makers which can help you create a bot in 6 lines of JavaScript, Python, Go, and Java, with cross-platform support including Linux, Windows, MacOS, and Docker.
更多

参考:什么是无头浏览器,它的用途是什么?
总之,使用WeChaty,可以模拟一个微信客户端,用户通过扫码登陆后,它会捕获登陆用户的所以会话,并可以通过提供的API 完成一些自动回复的功能(思考:微信同意这样搞吗?难道没有安全隐患吗?),当前在WeChaty社区也看到了很多被封号的情况,说明在微信的生态下还是不能随便玩的。

在这个基础上,小助理的实现逻辑思路就很清晰了,也非常简单

开始模块组装

核心依赖的3个模块:
"chatgpt": "^4.8.3",    //对openai 的云api 做了上层的封装和管理
"wechaty": "^1.20.2",  //微信机器人模块
"wechaty-puppet-wechat": "^1.18.4" 

初始化Wechaty

async function initProject() {
  try {
    await initChatGPT();
    bot = WechatyBuilder.build({
      name: 'zezefamily',
      puppet: 'wechaty-puppet-wechat',
      puppetOptions: {
        uos: true,
      },
    });

    bot
      .on('scan', onScan)
      .on('login', onLogin)
      .on('logout', onLogout)
      .on('message', onMessage);
    if (config.friendShipRule) {
      bot.on('friendship', onFriendShip);
    }

    bot
      .start()
      .then(() => console.log('Start to log in WeChat...'))
      .catch((e) => console.error(e));
  } catch (error) {
    console.log('init error: ', error);
  }
}

处理bot 的回调

//扫码登陆
function onScan(qrcode) {
  qrcodeTerminal.generate(qrcode); // 在console端显示二维码
  const qrcodeImageUrl = [
    'https://api.qrserver.com/v1/create-qr-code/?data=',
    encodeURIComponent(qrcode),
  ].join('');

  console.log(qrcodeImageUrl);
}
//登陆
async function onLogin(user) {
  console.log(`${user} has logged in`);
  const date = new Date();
  console.log(`Current time:${date}`);
  if (config.autoReply) {
    console.log(`Automatic robot chat mode has been activated`);
  }
}
//登出
function onLogout(user) {
  console.log(`${user} has logged out`);
}
//添加好友
async function onFriendShip(friendship) {
  if (friendship.type() === 2) {
    if (config.friendShipRule.test(friendship.hello())) {
      await friendship.accept();
    }
  }
}

// 收到消息
async function onMessage(msg) {
  // 避免重复发送
  if (msg.date() < startTime) {
    return;
  }
  const contact = msg.talker();    //消息发送者
  const receiver = msg.to();         //消息接收者
  const content = msg.text().trim();  //消息体
  const room = msg.room();        //是否为群消息
  const alias = (await contact.alias()) || (await contact.name());
  const isText = msg.type() === bot.Message.Type.Text;   //判断是否为文本消息
  if (msg.self()) {     //如果是自己给自己发送
    return;
  }

  if (room && isText) {    //只处理文本类消息
    const topic = await room.topic();
    console.log(
      `Group name: ${topic} talker: ${await contact.name()} content: ${content}`
    );
    // console.log("receiver.name() ==>",receiver.name())
    if (await msg.mentionSelf()) {    //群消息,是否@的是自己
      // console.log("是自我提及:",content);
      if (content.startsWith("@小泽玛利亚")){
        const groupContent = content.replace("@小泽玛利亚", '');
        console.log("groupContent ==>",groupContent)
        replyMessage(room, groupContent);  //提取内容发送给Chat-gpt
        return;
      }else {
        console.log(
          'Content is not within the scope of the customizition format'
        );
      }
    }
  } else if (isText) {   //单聊消息
    console.log(`talker: ${alias} content: ${content}`);
    if (config.autoReply) {
      if (content.startsWith(config.privateKey) || config.privateKey === '') {
        let privateContent = content;
        if (config.privateKey === '') {
          privateContent = content.substring(config.privateKey.length).trim();
        }
        replyMessage(contact, privateContent);   //提取内容给Chat-gpt
      } else {
        console.log(
          'Content is not within the scope of the customizition format'
        );
      }
    }
  }
}

Chat-GPT 内部,对外导出了几个function

//chat-gpt 模块初始化
export function initChatGPT() {
  chatGPT = new ChatGPTAPI({
    apiKey: config.OPENAI_API_KEY,
    completionParams: {
      model: 'gpt-3.5-turbo',
    },
  });
}
//contact : talker实例  content:发送的内容
export async function replyMessage(contact, content) {
  const { id: contactId } = contact;
  try {
    if (
      content.trim().toLocaleLowerCase() === config.resetKey.toLocaleLowerCase()
    ) {
      chatOption = {
        ...chatOption,
        [contactId]: {},
      };
      await contact.say('Previous conversation has been reset.');
      return;
    }
    const message = await retryRequest(
      () => getChatGPTReply(content, contactId),
      config.retryTimes,
      500
    );

    if (
      (contact.topic && contact?.topic() && config.groupReplyMode) ||
      (!contact.topic && config.privateReplyMode)
    ) {
      const result = content + '\n-----------\n' + message;
      await contact.say(result);
      return;
    } else {
      await contact.say(message);
    }
  } catch (e: any) {
    console.error(e);
    if (e.message.includes('timed out')) {
      await contact.say(
        content +
          '\n-----------\nERROR: Please try again, ChatGPT timed out for waiting response.'
      );
    }
  }
}
//请求OpenAI接口
async function getChatGPTReply(content, contactId) {
  //调用封装的chatGPT模块发起请求
  const { conversationId, text, id } = await chatGPT.sendMessage(
    content,
    chatOption[contactId]
  );
  chatOption = {
    [contactId]: {
      conversationId,
      parentMessageId: id,
    },
  };
  console.log('response: ', conversationId, text);
  // response is a markdown-formatted string
  return text;
}

核心的内容基本完成,演示一下结果吧
单聊:

群聊:

至此,一个简单Chat-GPT 助理就搞定了。

注意:以上案例仅供学习,不能商业运作;

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/526921.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

ChatGPT是什么?

ChatGPT是什么&#xff1f; ChatGPT是一个基于人工智能技术的聊天机器人平台&#xff0c;旨在为用户提供智能化、高效率的交互体验。ChatGPT能够理解用户输入的自然语言&#xff0c;根据语义分析和机器学习算法生成相应的回答。它可以回答用户的问题、提供建议、进行闲聊等&am…

前端技术搭建井字游戏(内含源码)

The sand accumulates to form a pagoda ✨ 写在前面✨ 功能介绍✨ 页面搭建✨ 样式设置✨ 逻辑部分 ✨ 写在前面 上周我们实通过前端基础实现了飞机大战游戏&#xff0c;今天还是继续按照我们原定的节奏来带领大家完成一个井字游戏游戏&#xff0c;功能也比较简单简单&#x…

路径规划 | 图解快速随机扩展树RRT算法(附ROS C++/Python/Matlab仿真)

目录 0 专栏介绍1 什么是RRT算法&#xff1f;2 图解RRT算法原理3 算法仿真与实现3.1 ROS C实现3.2 Python实现3.3 Matlab实现 0 专栏介绍 &#x1f525;附C/Python/Matlab全套代码&#x1f525;课程设计、毕业设计、创新竞赛必备&#xff01;详细介绍全局规划(图搜索、采样法、…

〖Python网络爬虫实战㉕〗- Ajax数据爬取之Ajax 案例实战

订阅&#xff1a;新手可以订阅我的其他专栏。免费阶段订阅量1000 python项目实战 Python编程基础教程系列&#xff08;零基础小白搬砖逆袭) 说明&#xff1a;本专栏持续更新中&#xff0c;目前专栏免费订阅&#xff0c;在转为付费专栏前订阅本专栏的&#xff0c;可以免费订阅付…

Gradle下载、安装、配置

1. Gradle下载 1.1 Gradle下载地址&#xff1a;https://docs.gradle.org/current/userguide/installation.html#installing_manually 1.2 点击Download 1.3 选择想要下载的版本&#xff0c;点击binary-only即可下载 2. Gradle安装&#xff08;注意&#xff1a;安装gradle之前…

【C语言】三子棋小游戏的思路及实现(内附代码)

简单不先于复杂&#xff0c;而是在复杂之后。 目录 1. 分文件实现 2.分步骤实现 2.1 游戏菜单 2.2 创建棋盘 2.3 初始化棋盘 2.4 打印棋盘 2.5 玩家下棋 2.6 电脑下棋 2.7 判断输赢 3. 附完整代码 3.1 test.c 3.2 game.h 3.2 game.c 1. 分文件实现 当我…

对称加密、非对称加密、数字签名、消息摘要的简单学习

对称加密、非对称加密、数字签名、消息摘要的简单学习 前言对称加密算法DES特点&#xff1a;为什么不使用&#xff1a; 3DES&#xff08;Triple DES 或者 DESede&#xff09;特点&#xff1a;使用场景&#xff1a;为什么不用&#xff1a; AES&#xff08;Advanced Encryption S…

聊一聊模板方法模式

统一抽取&#xff0c;制定规范&#xff1b; 一、概述 模板方法模式&#xff0c;又叫模板模式&#xff0c;属于23种设计模式中的行为型模式。在抽象类中公开定义了执行的方法&#xff0c;子类可以按需重写其方法&#xff0c;但是要以抽象类中定义的方式调用方法。总结起来就是&…

c语言实现栈(顺序栈,链栈)

&#x1f388;个人主页:&#x1f388; :✨✨✨初阶牛✨✨✨ &#x1f43b;推荐专栏: &#x1f354;&#x1f35f;&#x1f32f;C语言进阶 &#x1f511;个人信条: &#x1f335;知行合一 &#x1f349;本篇简介:>:讲解用c语言实现:“数据结构之"栈”,分别从"顺序栈…

区间预测 | MATLAB实现QRCNN-BiGRU卷积双向门控循环单元分位数回归时间序列区间预测

区间预测 | MATLAB实现QRCNN-BiGRU卷积双向门控循环单元分位数回归时间序列区间预测 目录 区间预测 | MATLAB实现QRCNN-BiGRU卷积双向门控循环单元分位数回归时间序列区间预测效果一览基本介绍模型描述程序设计参考资料 效果一览 基本介绍 1.Matlab实现基于QRCNN-BiGRU分位数回…

MySQL视图与联集

一、VIEW&#xff08;视图&#xff09; 1、 概念 可以被当作是虚拟表或存储查询 视图跟表格的不同是&#xff0c;表格中有实际储存资料&#xff0c;而视图是建立在表格之上的一个架构&#xff0c;它本身并不实际储存资料。 临时表在用户退出或同数据库的连接断开后就自动消…

DIY技巧:微星B760主板13600K降压教程 CPU温度暴降25℃

前段时间微星B600/700系主板更新了最新的BIOS&#xff0c;最新的BIOS更新&#xff1b;额105微码&#xff0c;让用户能直接在BIOS中对13代带K处理器进行降压&#xff0c;十分方便&#xff0c;今就带大家体验一下微星B760迫击炮主板的降压流程&#xff0c;其他微星B600/700系主板…

43岁,年薪200万的高管,被裁了!这4条职场潜规则,你越早知道越好

作者| Mr.K 编辑| Emma 来源| 技术领导力(ID&#xff1a;jishulingdaoli) 我的一位老朋友S总&#xff0c;是某世界500强外企中国区运营总监&#xff0c;光年薪就200万&#xff0c;还不包括福利、股票的部分&#xff0c;他比我略长一两岁&#xff0c;我们人生经历相似&#xf…

一文搞懂Go错误链

0. Go错误处理简要回顾 Go是一种非常强调错误处理的编程语言。在Go中&#xff0c;错误被表示为实现了error接口的类型的值&#xff0c;error接口只有一个方法&#xff1a; type error interface {Error() string } 这个接口的引入使得Go程序可以以一致和符合惯用法的方式进行错…

Python实现哈里斯鹰优化算法(HHO)优化LightGBM回归模型(LGBMRegressor算法)项目实战

说明&#xff1a;这是一个机器学习实战项目&#xff08;附带数据代码文档视频讲解&#xff09;&#xff0c;如需数据代码文档视频讲解可以直接到文章最后获取。 1.项目背景 2019年Heidari等人提出哈里斯鹰优化算法(Harris Hawk Optimization, HHO)&#xff0c;该算法有较强的全…

有主题的图文内容创作 | AIGC实践

话说&#xff0c;昨天我发布了第一篇&#xff0c;内容由ChatGPT和Midjourney协助完成的文章&#xff1a;胡同与侏罗纪公园的时空交错 | 胡同幻想 在这篇文章中&#xff0c;大约70%图文内容由ChatGPT和Midjourney输出。我个人参与的部分&#xff0c;主要是提出指令&#xff08;P…

Monaco Editor编辑器教程(三一):在编辑器中实现模拟调试的交互

前言 最近有小伙伴咨询如何在编辑中实现 像vscode调试代码那样,可以打断点,可以高亮当前运行的一行。这样的需求并不多见,如果要做,那肯定是对编辑器做一个深层次的定制。一般很少很少会实现这种在浏览器中调试。 目前我还没见过,如果有遇到过的朋友可以指点一下。我去学…

Cesium AI GPT 文档 源码 ChatGPT问答

我用Cesium104.0的 源码 | 文档 | 3DTiles标准 作为上下文语料定制了一个智能Cesium专家问答助手 语料: 3D Tiles Specificationhttps://cesium.com/downloads/cesiumjs/releases/1.104/Build/CesiumUnminified/Cesium.jshttps://github1s.com/CesiumGS/cesium/blob/HEAD/Doc…

redis中的管道

Redis 管道 文章目录 1. 前言2. Redis 管道3. 小总结 1. 前言 通过一个问题引出 我们接下来要学习的 Redis 管道 : 提问 : 如何优化频繁命令往返造成的性能瓶颈 ? 另外 &#xff1a; 关于上面这个问题的由来 也可以简单的说一说 上面所说的思路 其实就是管道的概念 &#xff0…

读俞敏洪的书

没有认真写过一篇关于书籍的读后感文章&#xff0c;但在读完俞敏洪老师这本书后&#xff0c;想推荐给大家&#xff0c;也想分享下我的想法。 几周前&#xff0c;我在微信读书首页看到了俞敏洪老师的读书推荐 《在绝望中寻找希望》——俞敏洪写给迷茫不安的年轻人 有好几个晚上&…