Open ai 开发指南:gpt接口的第一个问答机器人demo

目录

内容

Python代码

C++ 代码

workspace 文件

BUILD文件

Java 代码

maven文件

执行效果


 

 

 

 (PS:CSDN上相关的内容无法发布,有需要的朋友私信我直接全套发送给你)

 

内容

基于openai接口实现循环gpt问答,并使用一个文件将问答内容进行记录。

Python代码

# -*- coding: utf-8 -*-
import openai
import time
from pathlib import Path# Set the OpenAI API key
openai.api_key = ""class ChatBot:def __init__(self, model):self.user = "\nYou: "self.bot = "GPT-3.5-turbo: "self.model = modelself.question_list = []self.answer_list = []self.text = ''self.turns = []self.last_result = ''def save_dialogue(self):# Generate a timestamp and create a filename for saving the dialoguetimestamp = time.strftime("%Y%m%d-%H%M-%S", time.localtime())  # Timestampfile_name = 'output/Chat_' + timestamp + '.md'  # Filenamef = Path(file_name)f.parent.mkdir(parents=True, exist_ok=True)# Save the dialogue to the filewith open(file_name, "w", encoding="utf-8") as f:for q, a in zip(self.question_list, self.answer_list):f.write(f"You: {q}\nGPT-3.5-turbo: {a}\n\n")print("Dialogue content saved to file: " + file_name)def generate(self):print('\nStart your conversation, type "exit" to end.')while True:question = input(self.user)self.question_list.append(question)prompt = self.bot + self.text + self.user + questionif question == 'exit':breakelse:try:response = openai.ChatCompletion.create(model=self.model,messages=[{"role": "user", "content": prompt},],)result = response["choices"][0]["message"]["content"].strip()print(result)self.answer_list.append(result)self.last_result = resultself.turns += [question] + [result]if len(self.turns) <= 10:self.text = " ".join(self.turns)else:self.text = " ".join(self.turns[-10:])except Exception as exc:print(exc)self.save_dialogue()if __name__ == '__main__':bot = ChatBot('gpt-3.5-turbo')bot.generate()

在这个代码中,我们实现了一个与 GPT-3.5-turbo 模型进行对话的聊天机器人。以下是代码的执行流程:

  1. 首先,我们导入需要用到的库,包括 openai、time 和 pathlib。
  2. 我们设置 OpenAI API 密钥,以便能够调用 GPT-3.5-turbo 模型。
  3. 定义一个名为 ChatBot 的类,该类用于与 GPT-3.5-turbo 模型进行交互。
  4. 类的 __init__ 方法初始化聊天机器人,包括设定用户和机器人的提示符(self.user 和 self.bot),以及其他一些变量,如问题列表、回答列表等。
  5. save_dialogue 方法用于将聊天记录保存到文件中。这个方法首先创建一个带有时间戳的文件名,然后将问题和回答列表中的内容写入该文件。
  6. generate 方法用于与 GPT-3.5-turbo 模型进行交互。在这个方法中,我们使用一个循环来获取用户输入的问题,并将其添加到问题列表中。然后,我们构建提示并使用 OpenAI API 调用 GPT-3.5-turbo 模型。我们获取模型的回答,并将其添加到回答列表中。循环会一直进行,直到用户输入 "exit",此时循环结束,调用 save_dialogue 方法将对话内容保存到文件中。
  7. 在主函数(if __name__ == '__main__')中,我们创建一个 ChatBot 类的实例,并调用 generate 方法开始与 GPT-3.5-turbo 模型的交互。

C++ 代码

// main.cpp
#include <cpprest/http_client.h>
#include <cpprest/filestream.h>
#include <cpprest/json.h>
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <iomanip>using namespace utility;
using namespace web;
using namespace web::http;
using namespace web::http::client;
using namespace concurrency::streams;
namespace {const std::string api_key = "";
}
class ChatBot {
public:
/**
* @brief Construct a new ChatBot object
*
* @param model The OpenAI GPT model to use (e.g., "gpt-3.5-turbo")
*/
explicit ChatBot(std::string model) : model_(model) {}/**
* @brief Save the dialogue content to a Markdown file
*
* @note This function saves the generated dialogue to a Markdown file named
* "Chat_timestamp.md" in the "output" directory.
*/
void SaveDialogue() {auto timestamp = std::time(nullptr);std::stringstream ss;ss << "output/Chat_" << std::put_time(std::localtime(&timestamp), "%Y%m%d-%H%M-%S") << ".md";std::string file_name = ss.str();std::ofstream out(file_name);if (!out) {std::cerr << "Could not create the output file.\n";return;}for (size_t i = 0; i < question_list_.size(); ++i) {out << "You: " << question_list_[i] << "\nGPT-3.5-turbo: " << answer_list_[i] << "\n\n";}out.close();std::cout << "Dialogue content saved to file: " << file_name << std::endl;
}/**
* @brief Generate answers to the user's questions using the GPT model
*
* @note This function prompts the user for their questions, generates answers
* using the GPT model, and saves the dialogue to a file when the user exits.
*/
void Generate() {std::string question;std::cout << "\nStart your conversation, type \"exit\" to end." << std::endl;while (true) {std::cout << "\nYou: ";std::getline(std::cin, question);if (question == "exit") {break;}question_list_.push_back(question);auto answer = GetAnswer(question);if (!answer.empty()) {std::cout << "GPT-3.5-turbo: " << answer << std::endl;answer_list_.push_back(answer);}}SaveDialogue();
}private:
/**
* @brief Get the GPT model's answer to the given question
*
* @param question The user's question
* @return The GPT model's answer as a string
*
* @note This function sends the user's question to the GPT model and
* retrieves the model's answer as a string. If an error occurs, it
* returns an empty string.
*/
std::string GetAnswer(const std::string& question) {
http_client client(U("https://api.openai.com/v1/engines/gpt-3.5-turbo/completions"));
http_request request(methods::POST);
request.headers().add("Authorization", "Bearer "+api_key);
request.headers().add("Content-Type", "application/json");json::value body;
body[U("prompt")] = json::value::string(U("GPT-3.5-turbo: " + question));
body[U("max_tokens")] = 50;
body[U("n")] = 1;
body[U("stop")] = json::value::array({json::value::string(U("\n"))});
request.set_body(body);try {
auto response = client.request(request).get();
auto response_body = response.extract_json().get();
auto result = response_body.at(U("choices")).as_array()[0].at(U("text")).as_string();
return utility::conversions::to_utf8string(result);
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
return "";
}
}std::string model_;
std::vector<std::string> question_list_;
std::vector<std::string> answer_list_;
};int main(){
ChatBot bot("gpt-3.5-turbo");
bot.Generate();
return 0;
}

因为我的最近经常在使用bazel,所以给出一个基于bazel 的C++编译方法

workspace 文件

load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")# Add cpprestsdk as a dependency
http_archive(name = "cpprestsdk",build_file = "@//:cpprestsdk.BUILD",sha256 = "106e8a5a4f9667f329b8f277f8f25e1f2d31f1a7c7f9e1f366c5b1e3af2f8c4c",strip_prefix = "cpprestsdk-2.10.18",urls = ["https://github.com/microsoft/cpprestsdk/archive/v2.10.18.zip"],
)

BUILD文件

cc_binary(name = "chatbot",srcs = ["main.cpp"],deps = ["@cpprestsdk//:cpprest",],linkopts = [# Required for cpprestsdk"-lboost_system","-lssl","-lcrypto",],
)# cpprestsdk.BUILD file content (create this file in the same directory as WORKSPACE)
'''
load("@rules_cc//cc:defs.bzl", "cc_library")cc_library(name = "cpprest",hdrs = glob(["cpprestsdk/cpprestsdk/Release/include/**/*.h"]),srcs = glob(["cpprestsdk/cpprestsdk/Release/src/http/client/*.cpp","cpprestsdk/cpprestsdk/Release/src/http/common/*.cpp","cpprestsdk/cpprestsdk/Release/src/http/listener/*.cpp","cpprestsdk/cpprestsdk/Release/src/json/*.cpp","cpprestsdk/cpprestsdk/Release/src/pplx/*.cpp","cpprestsdk/cpprestsdk/Release/src/uri/*.cpp","cpprestsdk/cpprestsdk/Release/src/utilities/*.cpp","cpprestsdk/cpprestsdk/Release/src/websockets/client/*.cpp",]),includes = ["cpprestsdk/cpprestsdk/Release/include"],copts = ["-std=c++11"],linkopts = ["-lboost_system","-lssl","-lcrypto",],visibility = ["//visibility:public"],
)
'''

Java 代码

// ChatBot.java
import okhttp3.*;
import com.google.gson.*;
import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;public class ChatBot {private static final String API_KEY = "your_openai_api_key_here";private String model;private ArrayList<String> questionList;private ArrayList<String> answerList;public ChatBot(String model) {this.model = model;this.questionList = new ArrayList<>();this.answerList = new ArrayList<>();}public void saveDialogue() {LocalDateTime timestamp = LocalDateTime.now();DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd-HHmm-ss");String fileName = "output/Chat_" + timestamp.format(formatter) + ".md";try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {for (int i = 0; i < questionList.size(); ++i) {writer.write("You: " + questionList.get(i) + "\nGPT-3.5-turbo: " + answerList.get(i) + "\n\n");}System.out.println("Dialogue content saved to file: " + fileName);} catch (IOException e) {System.err.println("Could not create the output file.");e.printStackTrace();}}public void generate() {System.out.println("\nStart your conversation, type \"exit\" to end.");BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));String question;while (true) {System.out.print("\nYou: ");try {question = reader.readLine();} catch (IOException e) {System.err.println("Error reading input.");e.printStackTrace();break;}if ("exit".equalsIgnoreCase(question)) {break;}questionList.add(question);String answer = getAnswer(question);if (!answer.isEmpty()) {System.out.println("GPT-3.5-turbo: " + answer);answerList.add(answer);}}saveDialogue();}private String getAnswer(String question) {OkHttpClient client = new OkHttpClient();Gson gson = new Gson();String requestBodyJson = gson.toJson(new RequestBody("GPT-3.5-turbo: " + question, 50, 1, "\n"));RequestBody requestBody = RequestBody.create(requestBodyJson, MediaType.parse("application/json"));Request request = new Request.Builder().url("https://api.openai.com/v1/engines/gpt-3.5-turbo/completions").addHeader("Authorization", "Bearer " + API_KEY).addHeader("Content-Type", "application/json").post(requestBody).build();try (Response response = client.newCall(request).execute()) {if (!response.isSuccessful()) {throw new IOException("Unexpected code " + response);}String responseBodyJson = response.body().string();ResponseBody responseBody = gson.fromJson(responseBodyJson, ResponseBody.class);return responseBody.choices.get(0).text.trim();} catch (IOException e) {System.err.println("Error: " + e.getMessage());e.printStackTrace();return "";}}public static void main(String[] args) {ChatBot bot = new ChatBot("gpt-3.5-turbo");bot.generate();}private static class RequestBody {String prompt;int max_tokens;int n;String stop;RequestBody(String prompt, int max_tokens, int n, String stop) {this.prompt = prompt;this.max_tokens = max_tokens;this.n = n;this.stop = stop;}}private static class ResponseBody {ArrayList<Choice> choices;private static class Choice {String text;}}
}

maven文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.example</groupId><artifactId>gpt-chatbot</artifactId><version>1.0-SNAPSHOT</version><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.compiler.source>1.8</maven.compiler.source><maven.compiler.target>1.8</maven.compiler.target></properties><dependencies><dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>4.9.3</version></dependency><dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId><version>2.8.9</version></dependency></dependencies><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.8.0</version></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-jar-plugin</artifactId><version>3.1.0</version><configuration><archive><manifest><addClasspath>true</addClasspath><classpathPrefix>lib/</classpathPrefix><mainClass>com.example.ChatBot</mainClass></manifest></archive></configuration></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-dependency-plugin</artifactId><version>3.1.1</version><executions><execution><id>copy-dependencies</id><phase>package</phase><goals><goal>copy-dependencies</goal></goals><configuration><outputDirectory>${project.build.directory}/lib</outputDirectory></configuration></execution></executions></plugin></plugins></build>
</project>

执行效果

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

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Unity VR开发教程 OpenXR+XR Interaction Toolkit(八)手指触控 Poke Interaction

文章目录 &#x1f4d5;教程说明&#x1f4d5;XR Poke Interactor&#x1f4d5;与 UI 进行触控交互⭐添加 Tracked Device Graphic Raycaster 和 XR UI Input Module 让 UI 可被交互 &#x1f4d5;与物体进行交互⭐XR Simple Interactable⭐XR Poke Filter 往期回顾&#xff1a…

微信小程序web-view嵌入uni-app H5页面,通过H5页面跳转其他小程序如何操作?

1、H5页面代码 wx.miniProgram.reLaunch({ url: /pages/index/index?appId${您的微信小程序appId} });//触发小程序刷新页面获取appId 微信小程序appId查看方法&#xff1a; 1&#xff09;有后台登录权限的情况下&#xff1a;登录微信公众平台后&#xff0c; 微信公众平台微信…

Diffusion扩散模型学习2——Stable Diffusion结构解析-以文本生成图像为例

Diffusion扩散模型学习2——Stable Diffusion结构解析 学习前言源码下载地址网络构建一、什么是Stable Diffusion&#xff08;SD&#xff09;二、Stable Diffusion的组成三、生成流程1、文本编码2、采样流程a、生成初始噪声b、对噪声进行N次采样c、单次采样解析I、预测噪声II、…

nuxt 设置i18n后多语言文件不会动态更新

nuxt 设置i18n后多语言文件不会动态更新 昨天遇到的一个问题&#xff0c;然后研究了一整天&#xff0c;今天才得到解决 nuxt 设置i18n多语言时多语言文件不会动态更新 我的原始代码如下&#xff1a; {modules: [nuxtjs/i18n,],i18n: {locales: [{code: en,iso: en-US,name:…

【GitLab私有仓库】在Linux上用Gitlab搭建自己的私有库并配置cpolar内网穿透

文章目录 前言1. 下载Gitlab2. 安装Gitlab3. 启动Gitlab4. 安装cpolar5. 创建隧道配置访问地址6. 固定GitLab访问地址6.1 保留二级子域名6.2 配置二级子域名 7. 测试访问二级子域名 转载自远控源码文章&#xff1a;Linux搭建GitLab私有仓库&#xff0c;并内网穿透实现公网访问 …

go mod tidy 提示错误 go mod tidy -go=1.16 go mod tidy -go=1.17

错误概览 执行 go mod tidy 时&#xff0c;提示如下错误 > go mod tidy github.com/myrepo/myproj importsgo.k6.io/k6 importsgo.k6.io/k6/cmd importsgithub.com/fatih/color loaded from github.com/fatih/colorv1.12.0,but go 1.16 would select v1.13.0To upgrade to t…

人工智能(pytorch)搭建模型11-pytorch搭建DCGAN模型,一种生成对抗网络GAN的变体实际应用

大家好&#xff0c;我是微学AI&#xff0c;今天给大家介绍一下人工智能(pytorch)搭建模型11-pytorch搭建DCGAN模型&#xff0c;一种生成对抗网络GAN的变体实际应用&#xff0c;本文将具体介绍DCGAN模型的原理&#xff0c;并使用PyTorch搭建一个简单的DCGAN模型。我们将提供模型…

荔枝集团战队斩获 2023 Amazon DeepRacer自动驾驶赛车企业总决赛冠军

6月27日&#xff0c;2023 Amazon DeepRacer自动驾驶赛车企业总决赛在上海决出了最终结果&#xff0c;荔枝集团“状元红”战队与Cisco、德勤管理咨询、北京辛诺创新、神州泰岳、敦煌网等12支队伍的竞逐中&#xff0c;在两轮比赛中成绩遥遥领先&#xff0c;最终斩获桂冠。而今年年…

人工智能数据集处理——数据清理2

目录 异常值的检测与处理 一、异常值的检测 1、使用3σ准则检测异常值 定义一个基于3σ准则检测的函数&#xff0c;使用该函数检测文件中的数据&#xff0c;并返回异常值 2、使用箱形图检测异常值 根据data.xlsx文件中的数据&#xff0c;使用boxplot()方法绘制一个箱型图 …

数字孪生百科之海康威视安防系统

智能安防是指利用先进的技术手段和系统&#xff0c;以提升安全防护能力和监控效果的安全领域。数字化则是指将信息以数字形式进行处理和存储的过程。智能安防与数字化密切相关&#xff0c;通过数字化的手段和技术&#xff0c;可以实现对安全领域的全面监控、数据分析和智能决策…

人工智能:揭示未来科技所带来的革命性变革

目录 引言&#xff1a; 一、人工智能的定义与发展历程&#xff1a; 二、人工智能的应用领域&#xff1a; 三、人工智能对未来的影响&#xff1a; 结论&#xff1a; 引言&#xff1a; 在当今科技快速发展的时代&#xff0c;人工智能&#xff08;Artificial Intelligence&am…

1-Eureka服务注册与发现以及Eureka集群搭建(实操型)

1-Eureka服务注册与发现以及Eureka集群搭建&#xff08;实操型&#xff09; 1. 简单搭建微服务框架1.1 idea创建maven多模块项目1.2 项目结构1.3 项目依赖与配置1.3.1 父工程&#xff1a;dog-cloud-parent1.3.2 管理实体项目&#xff1a;dog-po1.3.3 服务提供者&#xff1a;dog…