初探chatgpt

发布时间 2023-07-19 18:01:30作者: yeweiliang95

chatgpt-api

生成chatgpt accessToken

1.创建node项目

项目需要使用的node >= 18保证fetch可用的

# 创建项目文件夹
mkdir chatGPT-demo

cd chatGPT-demo

# 初始化项目
npm init

# 创建运行文件
touch  index.js

# 安装chetgpt-api
npm install chatgpt

# 安装node服务,我用的express,也可用koa、hapi,也可以直接用node原生http模块,选择很多
npm install express

# post接口入参解析
npm install body-parser -D

 // package.json中配置启动脚本
 "scripts": {
    "start": "node index.js",
    "dev": "nodemon index.js",
    "start:hot": "nodemon index.js",
  },

# 安装依赖
npm install

创建post接口

import { ChatGPTAPI,ChatGPTUnofficialProxyAPI } from "chatgpt";
import express from 'express';
import bodyParser from 'body-parser';


// https://chat.openai.com/api/auth/session 获取accesstoken
const accessToken = "ChatGPT Web 应用程序的 OpenAI 访问令牌";

const app = express()
const port = 3000
app.use(bodyParser.json());// 添加json解析
app.use(bodyParser.urlencoded({extended: false}));
//设置跨域访问
// app.all('*', function(req, res, next) {
//   res.header("Access-Control-Allow-Origin", "*");
//   res.header("Content-Type", "application/json;charset=utf-8");
//   next();
// });

app.all('*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  res.header("Access-Control-Allow-Credentials", "true");
  res.header("Access-Control-Allow-Headers", "*");
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By",' 3.2.1');
  if(req.method=="OPTIONS") res.send(200);/*让options请求快速返回*/
  else next();
});

// const chatGPTApi = new ChatGPTAPI({
//   apiKey,
// });

const chatGPTApi = new ChatGPTUnofficialProxyAPI({
    accessToken: accessToken,
    apiReverseProxyUrl: 'https://ai.fakeopen.com/api/conversation'
  })

app.post('/sendMsg', async (req, res) => {
    console.log(req.body.msg)
  let result = await chatGPTApi.sendMessage(req.body.msg)
  console.log('res==>', result)
  res.send(`${result.text}`)
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

遇到的问题

  • ChatGPTAPI无法访问
    • 使用ChatGPTUnofficialProxyAPI,反向代理进行访问
  • 获取accessToken

运行项目

npm run dev

postman访问localhost:3000/senMsg

image-20230719174413779