OpenAI官方吴达恩《ChatGPT Prompt Engineering 提示词工程师》(7)聊天机器人 / ChatBot

聊天机器人 / ChatBot

使用大型语言模型来构建你的自定义聊天机器人
在本视频中,你将学习使用OpenAI ChatCompletions格式的组件构建一个机器人。

环境准备

首先,我们将像往常一样设置OpenAI Python包。

import os
import openai
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv()) # read local .env fileopenai.api_key  = os.getenv('OPENAI_API_KEY')

定义函数

def get_completion(prompt, model="gpt-3.5-turbo"):messages = [{"role": "user", "content": prompt}]response = openai.ChatCompletion.create(model=model,messages=messages,temperature=0, # this is the degree of randomness of the model's output)return response.choices[0].message["content"]def get_completion_from_messages(messages, model="gpt-3.5-turbo", temperature=0):response = openai.ChatCompletion.create(model=model,messages=messages,temperature=temperature, # this is the degree of randomness of the model's output)
#     print(str(response.choices[0].message))return response.choices[0].message["content"]


你的消息就是用户消息
ChatGPT的消息就是助手消息
系统消息有助于设置助手的行为和角色,它在某种程度上是对话的高级指令。所以你可以把它想象成在助手耳边窃窃私语,引导助手的反应,而用户却没有意识到系统消息。
下面是一个例子,系统消息提示你是一个说话像莎士比亚的助手,用户说你讲一个笑话,助手说为什么鸡要过马路?用户信息是,我不知道。调用函数后回答是“到达另一边,公平地说,夫人,这是一个古老的经典,永远不会失败。”

messages =  [  
{'role':'system', 'content':'You are an assistant that speaks like Shakespeare.'},    
{'role':'user', 'content':'tell me a joke'},   
{'role':'assistant', 'content':'Why did the chicken cross the road'},   
{'role':'user', 'content':'I don't know'}  ]response = get_completion_from_messages(messages, temperature=1)
print(response)
"""
To get to the other side, sire! 'Tis a classic jest, known by many a bard.
"""

下面的例子,助手消息是,你是一个友好的聊天机器人,第一条用户消息是,嗨,我的名字是Isa。我们想,嗯,获取第一条用户消息。所以,让我们执行这个。第一条助手消息。所以,第一条消息是,你好Isa,很高兴见到你。我今天可以如何帮助你?

messages =  [  
{'role':'system', 'content':'You are friendly chatbot.'},    
{'role':'user', 'content':'Yes,  can you remind me, What is my name?'}  ]
response = get_completion_from_messages(messages, temperature=1)
print(response)
"""
I'm sorry, but as a chatbot, I do not have access to information about your personal details such as your name. However, you can tell me your name and we can continue our conversation.
"""

对话必须要有上下文,不然模型不知道。比如模型不知道你叫什么名字。

messages =  [  
{'role':'system', 'content':'You are friendly chatbot.'},    
{'role':'user', 'content':'Yes,  can you remind me, What is my name?'}  ]
response = get_completion_from_messages(messages, temperature=1)
print(response)
"""
I'm sorry, but as a chatbot, I do not have access to information about your personal details such as your name. However, you can tell me your name and we can continue our conversation.
"""

如果有上下文就可以提取

messages =  [  
{'role':'system', 'content':'You are friendly chatbot.'},
{'role':'user', 'content':'Hi, my name is Isa'},
{'role':'assistant', 'content': "Hi Isa! It's nice to meet you. \
Is there anything I can help you with today?"},
{'role':'user', 'content':'Yes, you can remind me, What is my name?'}  ]
response = get_completion_from_messages(messages, temperature=1)
print(response)
"""
Of course, your name is Isa.
"""

订单机器人

你要构建你自己的聊天机器人orderbot,自动化收集用户提示和助手响应,就是把用户回应自动的添加进去形成上下文。

def collect_messages(_):prompt = inp.value_inputinp.value = ''context.append({'role':'user', 'content':f"{prompt}"})response = get_completion_from_messages(context) context.append({'role':'assistant', 'content':f"{response}"})panels.append(pn.Row('User:', pn.pane.Markdown(prompt, width=600)))panels.append(pn.Row('Assistant:', pn.pane.Markdown(response, width=600, style={'background-color': '#F6F6F6'})))return pn.Column(*panels)

具体的询问顺序:
你是订单机器人,一个为比萨饼餐厅收集订单的自动化服务。
你首先问候顾客,然后收集订单,然后询问是提货还是送货。
你等待收集整个订单,然后总结一下,最后一次检查客户是否想要添加任何其他东西。
如果是送货,你可以要求一个地址。
最后,你收取付款。确保澄清所有选项、额外费用和尺寸,以唯一地识别菜单中的项目。
你以简短、非常对话、友好的方式回应。菜单包括,然后我们有菜单。

import panel as pn  # GUI
pn.extension()panels = [] # collect display context = [ {'role':'system', 'content':"""
You are OrderBot, an automated service to collect orders for a pizza restaurant. \
You first greet the customer, then collects the order, \
and then asks if it's a pickup or delivery. \
You wait to collect the entire order, then summarize it and check for a final \
time if the customer wants to add anything else. \
If it's a delivery, you ask for an address. \
Finally you collect the payment.\
Make sure to clarify all options, extras and sizes to uniquely \
identify the item from the menu.\
You respond in a short, very conversational friendly style. \
The menu includes \
pepperoni pizza  12.95, 10.00, 7.00 \
cheese pizza   10.95, 9.25, 6.50 \
eggplant pizza   11.95, 9.75, 6.75 \
fries 4.50, 3.50 \
greek salad 7.25 \
Toppings: \
extra cheese 2.00, \
mushrooms 1.50 \
sausage 3.00 \
canadian bacon 3.50 \
AI sauce 1.50 \
peppers 1.00 \
Drinks: \
coke 3.00, 2.00, 1.00 \
sprite 3.00, 2.00, 1.00 \
bottled water 5.00 \
"""} ]  # accumulate messagesinp = pn.widgets.TextInput(value="Hi", placeholder='Enter text here…')
button_conversation = pn.widgets.Button(name="Chat!")interactive_conversation = pn.bind(collect_messages, button_conversation)dashboard = pn.Column(inp,pn.Row(button_conversation),pn.panel(interactive_conversation, loading_indicator=True, height=300),
)dashboard
"""
[出现一个人机交互界面]
"""

 

要求模型创建一个JSON摘要,我们可以根据对话发送到订单系统。

messages =  context.copy()
messages.append(
{'role':'system', 'content':'create a json summary of the previous food order. Itemize the price for each item\The fields should be 1) pizza, include size 2) list of toppings 3) list of drinks, include size   4) list of sides include size  5)total price '},    
)#The fields should be 1) pizza, price 2) list of toppings 3) list of drinks, include size include price  4) list of sides include size include price, 5)total price '},    response = get_completion_from_messages(messages, temperature=0)
print(response)"""
Sure, here's a JSON summary of your order:···
{"pizza": {"type": "意大利辣香肠披萨","size": "中号","price": 12.95},"toppings": [{"type": "加拿大培根","price": 3.50},{"type": "蘑菇","price": 1.50},{"type": "彩椒","price": 1.00}],"drinks": [{"type": "可乐","size": "中杯","price": 3.00}],"sides": [],"total_price": 18.95
}
···
"""

温度值这里是0

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

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

相关文章

ruoyi框架修改左侧菜单样式

菜单效果 ruoyi前端框架左侧的菜单很丑,我们需要修改一下样式,下面直接看效果。 修改代码 1、sidebar.scss .el-menu-item, .el-submenu__title {overflow: hidden !important;text-overflow: ellipsis !important;white-space: nowrap !important;//…

vue3——pixi初学,编写一个简单的小游戏,复制粘贴可用学习

pixi官网 小游戏效果 两个文件夹 一个index.html 一个data.js //data.js import { reactive } from "vue"; import { Sprite, utils, Rectangle, Application, Text, Graphics } from "pixi.js";//首先 先创建一个舞台 export const app new Applicat…

QT配置MySQL数据库 ninja: build stopped: subcommand failed

QT配置MySQL数据库 我当前的软件版本:QT Creator 10.0.2 (community),MingW 6.4.3 (QT6),MySQL 8.0。 MySQL不配置支持的数据库有QList("QSQLITE", "QODBC", "QPSQL"),这个时候是不支持MYSQL数据…

[极客大挑战 2019]RCE ME 取反绕过正则匹配 绕过disable_function设置

目录 取反 1.蚁剑插件绕过 2.baypass disable_function open_dir/disable_function putenv()/LD_PRELOAD 来绕过限制 利用条件 利用思路 有意思。。。。 <?php error_reporting(0); if(isset($_GET[code])){$code$_GET[code];if(strlen($code)>40){die("Th…

windbg -I之后如何恢复原有的

直接运行了一下windbg -I&#xff0c;抓取了注册表行为&#xff0c;然后这里记录一下&#xff0c;方便翻阅。 抓取到的windbg的注册表 计算机\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug\Debugger 将值改为 "C:\WINDOWS\system32\vsji…

git 本地工作区和仓库区基本使用

(1)git 本地有三个区 工作区和暂存区和 git管理的仓库. &#xff08;自行动手实践理解,然后就入门了&#xff09;(2)本地初次使用git做的事情,需要做如下工作 git config --global user.name "xx" git config --global user.email xxxqq.com git config --globa…

java 工程管理系统源码+项目说明+功能描述+前后端分离 + 二次开发

Java版工程项目管理系统 Spring CloudSpring BootMybatisVueElementUI前后端分离 功能清单如下&#xff1a; 首页 工作台&#xff1a;待办工作、消息通知、预警信息&#xff0c;点击可进入相应的列表 项目进度图表&#xff1a;选择&#xff08;总体或单个&#xff09;项目显示…

编写第一个Go程序

编写第一个Go程序 1. 开发环境构建 在Go语言中&#xff0c;开发环境的构建需要设置GOPATH环境变量。在1.8版本之前&#xff0c;必须显式设置GOPATH环境变量。而在1.8版本及之后&#xff0c;如果没有设置GOPATH&#xff0c;Go将使用默认值。 在Unix系统上&#xff0c;默认值为…

基于YOLOv8模型的条形码二维码检测系统(PyTorch+Pyside6+YOLOv8模型)

摘要&#xff1a;基于YOLOv8模型的条形码二维码检测系统可用于日常生活中检测与定位条形码与二维码目标&#xff0c;利用深度学习算法可实现图片、视频、摄像头等方式的目标检测&#xff0c;另外本系统还支持图片、视频等格式的结果可视化与结果导出。本系统采用YOLOv8目标检测…

Android12之仿Codec2.0实现传递编解码器组件本质(四十六)

简介: CSDN博客专家,专注Android/Linux系统,分享多mic语音方案、音视频、编解码等技术,与大家一起成长! 优质专栏:Audio工程师进阶系列【原创干货持续更新中……】🚀 人生格言: 人生从来没有捷径,只有行动才是治疗恐惧和懒惰的唯一良药. 更多原创,欢迎关注:Android…

多策略改进蜣螂优化--螺旋搜索+最优值引导+反向学习策略

声明&#xff1a;对于作者的原创代码&#xff0c;禁止转售倒卖&#xff0c;违者必究&#xff01; 关于蜣螂算法的原理网上有很多&#xff0c;本文就不再详细介绍&#xff0c;本期算法是作者在参考了网上一些文献后自行改进的&#xff0c;接下来直接上改进策略&#xff1a; ①螺…

十六)Stable Diffusion教程:出图流程化

今天说一个流程化出图的案例&#xff0c;适用很多方面。 1、得到线稿&#xff0c;自己画或者图生图加线稿lora出线稿&#xff1b;如果想sd出图调整参数不那么频繁细致&#xff0c;则线稿的素描关系、层次、精深要表现出来&#xff0c;表现清楚。 2、文生图&#xff0c;seed随机…

前后端分离毕设项目之springboot同城上门喂遛宠物系统(内含文档+源码+教程)

博主介绍&#xff1a;✌全网粉丝10W,前互联网大厂软件研发、集结硕博英豪成立工作室。专注于计算机相关专业毕业设计项目实战6年之久&#xff0c;选择我们就是选择放心、选择安心毕业✌ &#x1f345;由于篇幅限制&#xff0c;想要获取完整文章或者源码&#xff0c;或者代做&am…

Quartz 建表语句SQL文件

SQL文件在jar里面&#xff0c;github下载 https://github.com/quartz-scheduler/quartz/releases/tag/v2.3.2 解压&#xff0c;sql文件路径&#xff1a;quartz-core\src\main\resources\org\quartz\impl\jdbcjobstore tables_mysql_innodb.sql # # In your Quartz propertie…

七天学会C语言-第七天(结构体)

1.定义结构体 例 1&#xff1a;把一个学生的信息(包括学号、姓名、性别、住址等 4 项信息) 放在一个结构体变量中&#xff0c;然后输出这个学生的信息。 #include <stdio.h>struct Student {int student_id;char name[30];char gender;char address[60]; };int main() …

Flink的部署模式:Local模式、Standalone模式、Flink On Yarn模式

Flink常见的部署模式 Flink部署、执行模式Flink的部署模式Flink的执行模式 Local本地模式下载安装启动、停止Flink提交测试任务停止作业 Standalone独立模式会话模式单作业模式应用模式 YARN运行模式会话模式启动Hadoop集群申请一个YARN会话查看Yarn、Flink提交作业查看、测试作…

SQL模板-用户留存率计算

在这段实习中&#xff0c;我遇到了用户留存率计算的需求&#xff0c;这里做个总结。 首先来讲下&#xff0c;什么是用户留存&#xff1f; 在互联网行业中&#xff0c;用户在某段时间内开始使用应用&#xff0c;经过一段时间后&#xff0c;仍然继续使用该应用的用户。用户留存一…

5.docker可视化工具(Portainer)

本文操作&#xff0c;在 192.168.204.102 机器执行 安装最新版 portainer&#xff0c;请使用 portainer/portainer-ce 镜像。图片来源&#xff1a;https://hub.docker.com/r/portainer/portainer。   来这里可查看最新版本&#xff1a;https://github.com/portainer/p…

内网穿透,轻松实现PostgreSQL数据库公网远程连接!

文章目录 前言1. 安装postgreSQL2. 本地连接postgreSQL3. Windows 安装 cpolar4. 配置postgreSQL公网地址5. 公网postgreSQL访问6. 固定连接公网地址7. postgreSQL固定地址连接测试 前言 PostgreSQL是一个功能非常强大的关系型数据库管理系统&#xff08;RDBMS&#xff09;,下…

MongoDB的搭建 和crud操作

MongoDB docker 下载 docker run --restartalways -d --name mongo -v /docker/mongodb/data:/data/db -p 27017:27017 mongo:4.0.6使用navcat工具使用MongoDB Crud操作 jar包 <dependency><groupId>org.projectlombok</groupId><artifactId>lom…