chatgptapi是OpenAIChatGPT的非官方的Node。js包装器。包括TS类型定义。chatgptapi不再需要任何浏览器破解它使用泄露出来的OpenAI官方ChatGPT在后台使用的模型。 推荐:使用NSDT场景设计器快速搭建3D场景。 你可以使用它开始构建由ChatGPT支持的项目,例如聊天机器人、网站等。。。import{ChatGPTAPI}fromchatgptconstapinewChatGPTAPI({apiKey:process。env。OPENAIAPIKEY})constresawaitapi。sendMessage(HelloWorld!)console。log(res。text) 请升级到chatgptlatest(至少v4。0。0)。与以前的版本相比,更新后的版本明显更加轻巧和健壮,你也不必担心IP问题或速率限制。 1、安装chatgptapi 确保你使用的是node18以便fetch可用(node14也可以,但你需要安装fetchpolyfill)。 使用如下命令安装chatgptapi:npminstallchatgpt2、chatgptapi使用方法 首先注册获取OpenAIAPI密钥并将其存储在你的环境中。 下面是简单的一次性对话:import{ChatGPTAPI}fromchatgptasyncfunctionexample(){constapinewChatGPTAPI({apiKey:process。env。OPENAIAPIKEY})constresawaitapi。sendMessage(HelloWorld!)console。log(res。text)} 如果你想进行持续多轮的对话,需要传递parentMessageid和conversationid:constapinewChatGPTAPI({apiKey:process。env。OPENAIAPIKEY})sendamessageandwaitfortheresponseletresawaitapi。sendMessage(WhatisOpenAI?)console。log(res。text)sendafollowupresawaitapi。sendMessage(Canyouexpandonthat?,{conversationId:res。conversationId,parentMessageId:res。id})console。log(res。text)sendanotherfollowupresawaitapi。sendMessage(Whatwerewetalkingabout?,{conversationId:res。conversationId,parentMessageId:res。id})console。log(res。text) 可以通过onProgress处理程序添加流式响应:constresawaitapi。sendMessage(Writea500wordessayonfrogs。,{printthepartialresponseastheAIistypingonProgress:(partialResponse)console。log(partialResponse。text)})printthefulltextattheendconsole。log(res。text) 也可以使用timeoutMs选项添加超时设置:timeoutafter2minutes(whichwillalsoaborttheunderlyingHTTPrequest)constresponseawaitapi。sendMessage(writemeareallyreallylongessayonfrogs,{timeoutMs:2601000}) 如果想查看有关实际发送到OpenAI完成API的内容的更多信息,请在ChatGPTAPI构造函数中设置debug:true选项:constapinewChatGPTAPI({apiKey:process。env。OPENAIAPIKEY,debug:true}) 你会注意到我们正在使用反向工程得到的promptPrefix和promptSuffix。你可以通过sendMessage的选项自定义这些:constresawaitapi。sendMessage(whatistheanswertotheuniverse?,{promptPrefix:YouareChatGPT,alargelanguagemodeltrainedbyOpenAI。Youanswerasconciselyaspossibleforeachresponse(e。g。don’tbeverbose)。Itisveryimportantthatyouanswerasconciselyaspossible,sopleaserememberthis。Ifyouaregeneratingalist,donothavetoomanyitems。Keepthenumberofitemsshort。Currentdate:{newDate()。toISOString()}}) 请注意,我们会自动处理将先前的消息附加到提示并尝试优化可用token(默认为4096)。 在CommonJS中可以使用动态导入:asyncfunctionexample(){TouseESMinCommonJS,youcanuseadynamicimportconst{ChatGPTAPI}awaitimport(chatgpt)constapinewChatGPTAPI({apiKey:process。env。OPENAIAPIKEY})constresawaitapi。sendMessage(HelloWorld!)console。log(res。text)} 完整的使用文档可以在这里查看。3、使用演示程序 要运行包含的演示:克隆这个仓库安装node。js依赖在。env中设置OPENAIAPIKEY 运行仓库中包含的基本演示程序:npxtsxdemosdemo。ts 运行仓库中包含的显示进度处理的演示程序:npxtsxdemosdemoonprogress。ts 上面这个演示使用sendMessage可选的onProgress参数以接收中间结果,看起来就像ChatGPT正在输入。 运行仓库中包含的多轮对话演示程序:npxtsxdemosdemoconversation。ts 仓库中的持久性演示展示了如何在Redis中存储消息以实现持久化:npxtsxdemosdemoconversation。ts 任何keyv适配器都支持消息的持久化,如果你想使用不同的方式存储检索消息,则可以进行覆盖。 请注意,需要持久化消息来记住当前Node。js进程范围之外的先前对话的上下文,因为默认情况下,我们仅将消息存储在内存中。 原文链接:http:www。bimant。comblogchatgptapinpm