1

python实现公众号版chatgpt开发教程:私人AI助理

 1 year ago
source link: https://foofish.net/wechat-chatGPT.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

python实现公众号版chatgpt开发教程:私人AI助理

By 刘志军, 2023-02-10, 分类: 思考



chatgpt 网页版不稳定,必须配合梯子使用,用起来体验很不好。我在想能不能做个微信版chatgpt来打造一个私人AI助理,考虑到有封号的风险这个方案放弃了。最终使用公众号来实现。

因为公众号本身就提供了开放接口,即便是个人号也支持一些简单的对话功能,用来做基于聊天的场景非常适合。

开发前的准备

  1. openai账号
  2. 微信公众号

申请 OpenAI KEY

首先你要有个chatgpt(OpenAI)的账号,才能接入chatgpt,还不知道怎么注册的请参考文章ChatGPT保姆级注册教程。注册成功后,申请一个API KEY,地址:https://platform.openai.com/account/api-keys。

image-20230216160339632

注册微信公众号

打开网址 https://mp.weixin.qq.com/cgi-bin/registermidpage?action=index&lang=zh_CN&token=, 直接选订阅号,如果你是企业,可以考虑注册服务号,服务号开放的接口更丰富。

image-20230216124145610

成为开发者

在公众号后台的【设置与开发】基本配置,申请成为开发者,申请成功后,会分配一个AppID和AppSecret。这两个配置项在项目中会用到,所以要记下来。 IP白名单就是你的服务器IP。

image-20230216160758300

填写服务器配置

在公众号后台的【设置与开发】基本配置中填上接口配置信息。URL必须是一个域名地址,所以你需要先把项目部署后这一步才能提交成功,所以这一步也可以放在后面

image-20230216124925584

微信服务器配置校验

项目是基于Flask开发的,我只贴核心代码,下面接口是提供给微信平台调用的,用来给微信校验消息的真实性

@wechat_bp.get('/wechat')
@siwa.doc(query=SignatureDto, resp=ResponseSuccessDto, group="wechat")
def signature_validate(query: SignatureDto):
    """
    微信服务器校验
    """
    try:
        token = current_app.config.get("WECHAT_TOKEN") # 这里的TOKEN就是在微信后台自己配置的Token
        return check_signature(token, query.signature, query.timestamp, query.nonce)
    except InvalidSignatureException:
        raise WechatError(msg="invalid signature")

处理用户的问题的核心代码

@wechat_bp.post("/wechat")
def handler_wx_msg():
    """
    处理微信事件
    """
    msg = parse_message(request.data)
    openid = request.args.get("openid")
    current_app.logger.info("openid:%s", openid)
    if isinstance(msg, (SubscribeScanEvent, ScanEvent)):
        # 关注或扫二维码
        result = TextReply(content="欢迎使用志军的私人AI助理,请直接输入问题,技术支持:lzjun567", message=msg).render()
    elif isinstance(msg, TextMessage):
        question = msg.content
        if question != "继续":
            current_app.logger.info(f"问题:{question}")
            s = threading.Thread(target=set_answer, args=(openid, question))
            s.start()
            time.sleep(2)
            answer = cache.pop(openid)
            if not answer:
                answer = "我正在思考中,请稍后回复【继续】获取回答"
        else:
            answer = cache.pop(openid)
            if not answer:
                answer = "请稍后,还没准备好参考答案"
        result = TextReply(content=answer, message=msg).render()
    else:
        result = TextReply(content="欢迎使用志军的私人AI助理", message=msg).render()
    return result

核心代码非常简单,注意我这里使用了一个线程去异步处理用户的消息,因为openai处理问题有时候需要3秒甚至更长时间,而公众号的会话必须在3秒内进行响应,所以我这里会把没有及时返回的答案放到redis中,等用户回复【继续】的时候给它返回结果。

因为项目是一个基于Flask的web项目,我直接部署在centos服务器上。用supervisor来管理进程,web server 使用gunicorn。都是Web开发中常规的技术。

部署之后,可以来体验一下了。

image-20230216152404777

完整代码可在公众号【Python之禅】回复 “chatgpt" 获取。任何技术问题可添加我的微信 lzjun567 咨询。

有问题可以扫描二维码和我交流

关注公众号「Python之禅」,回复「1024」免费获取Python资源

python之禅

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK