vue对接openai_实现ChatGPT

一、openai密钥

使用API 密钥才能连接到OpenAI API,去 OpenAI 网站注册一个账户(目前国内访问openai受限制,需要其他方式进行访问),单击个人资料图片和“查看 API 密钥”,创建一个新的密钥。

openai官网icon-default.png?t=N7T8https://openai.com/

二、使用openai包发送请求获得数据

1.下载openai包

 npm i openai --save

2.使用openai包发送请求
 import OpenAI from 'openai';
 const openai = new OpenAI({
    apiKey: '你的openai密钥', 
    dangerouslyAllowBrowser: true,
 });

    //发送请求
  const req = async () => {

        //实现打字机效果
        const response = await openai.chat.completions.create({
            model: "gpt-3.5-turbo",
            messages: [{ "role": "user", "content": state.textarea }],
            stream: true,
        });

        for await (const part of response) {
            console.log(part.choices[0].delta);
        }

       //响应数据整体返回效果
        const response = await openai.chat.completions.create({
          model: "gpt-3.5-turbo",
          messages: [{"role": "user", "content": "Hello!"}],
        });
        console.log(chatCompletion.choices[0].message);
   }

这个是npm的 openai包的"^4.0.0"  ,  v3和v4使用方法不同

eg:引入方式不同

// v3
import { Configuration, OpenAIApi } from "openai";

const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);

// v4
import OpenAI from 'openai';

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY // This is also the default, can be omitted
});

其他不同之处具体见下面的github

npm 的openai 包v3-v4迁移icon-default.png?t=N7T8https://github.com/openai/openai-node/discussions/217

三、直接发送请求获得数据

第二方式使用openai包发送请求获得数据,是直接在前端向openai接口发送的请求,只能在本电脑使用特殊方法发送请求才会成功。如果是公司线上项目是不可以的。公司线上项目需要向后端发送请求,后端向openai发送请求,解决跨域问题。

  • 17
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值