当前位置:

首页 > 编程开发 > Python基于Google Bard怎么实现交互式聊天机器人

Python基于Google Bard怎么实现交互式聊天机器人

用Python基于GoogleBard做一个交互式的聊天机器人之前已经通过浏览器试过了GoogleBard,更多细节请看:TryoutGoogleBard,WillGoogleBardbeattheChatGPT?.现在我们想实现自动化,所以我用Python做一个交互式的聊天机器人。获取SessionID通过浏览器先拿到SessionID,它是一个cookie,名为__Secure-1PSID,然后复制一下对应的值:Python代码先做一些初始化,主要是一些请求头和请求参数:def__init__(sel

用Python基于Google Bard做一个交互式的聊天机器人

之前已经通过浏览器试过了 Google Bard ,更多细节请看: Try out Google Bard, Will Google Bard beat the ChatGPT?.

现在我们想实现自动化,所以我用Python做一个交互式的聊天机器人。

获取Session ID

通过浏览器先拿到SessionID,它是一个cookie,名为 __Secure-1PSID,然后复制一下对应的值:

Python基于Google Bard怎么实现交互式聊天机器人

Python代码

先做一些初始化,主要是一些请求头和请求参数:

def __init__(self, session_id):
  headers = {
    "Host": "bard.google.com",
    "X-Same-Domain": "1",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36",
    "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
    "Origin": "https://bard.google.com",
    "Referer": "https://bard.google.com/",
  }
  self._reqid = int("".join(random.choices(string.digits, k=4)))
  self.conversation_id = ""
  self.response_id = ""
  self.choice_id = ""
  self.session = requests.Session()
  self.session.headers = headers
  self.session.cookies.set("__Secure-1PSID", session_id)
  self.SNlM0e = self.__get_snlm0e()

发送请求的时候,把之前准备的参数和数据发一个POST请求到 bard.google.com

resp = self.session.post(
  "https://bard.google.com/_/BardChatUi/data/assistant.lamda.BardFrontendService/StreamGenerate",
  params=params,
  data=data,
  timeout=120,
)

返回了之后,需要解析消息体,获取我们所需要的信息:

chat_data = json.loads(resp.content.splitlines()[3])[0][2]
if not chat_data:
  return {"content": f"Google Bard encountered an error: {resp.content}."}
json_chat_data = json.loads(chat_data)
results = {
  "content": json_chat_data[0][0],
  "conversation_id": json_chat_data[1][0],
  "response_id": json_chat_data[1][1],
  "factualityQueries": json_chat_data[3],
  "textQuery": json_chat_data[2][0] if json_chat_data[2] is not None else "",
  "choices": [{"id": i[0], "content": i[1]} for i in json_chat_data[4]],
}

运行与尝试

python Bard.py --session 'UgiXYPjpaIYuE9K_3BSxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

它一个交互式的终端,我随便问了几个问题:

ChatGPT - A command-line interface to Google's Bard (https://bard.google.com/)
You:
What is terrible-two?
Google Bard:
Terrible-two is a term used to describe the behavior of a child around the age of 2. It is a normal developmental phase that all children go through. During this time, children  
are learning to assert their independence and explore the world around them. This can lead to tantrums, defiance, and other challenging behavior.                                 
There are a few things that parents can do to help manage the terrible twos:                                                                                                      
 • Be patient and understanding. Remember that this is a normal phase and that your child is not trying to be difficult.                                                          
 • Set clear boundaries and expectations. Children need to know what is expected of them.                                                                                         
 • Be consistent with your discipline. If you are not consistent, your child will not learn what is right and wrong.                                                              
 • Offer positive reinforcement. Praise your child for good behavior and help them feel good about themselves.                                                                    
 • Talk to your child's doctor if you are concerned about their behavior. Your doctor can offer advice and support.                                                               
The terrible twos can be a challenging time for parents, but it is important to remember that this is a normal phase and that your child will eventually grow out of it.          
You:
how far is the moon?
Google Bard:
The Moon is an average of 238,855 miles (384,400 km) away from Earth. This distance varies slightly because the Moon's orbit is not a perfect circle. The Moon is closest to Earth
at perigee, which is when it is about 225,623 miles (363,104 km) away. It is farthest from Earth at apogee, which is when it is about 252,088 miles (405,696 km) away.            
You:
how far is the sun?
Google Bard:
The Sun is about 93 million miles (150 million kilometers) away from Earth. That's about 1 Astronomical Unit (AU).                                                                
The Sun is the center of our solar system. All of the planets and other objects in our solar system orbit around the Sun. The Sun is a very large star. It is about 109 times the 
diameter of Earth and about 330,000 times more massive than Earth. The Sun is made up of mostly hydrogen and helium. It is so hot that the hydrogen and helium are constantly     
fusing together to create heavier elements. This process is called nuclear fusion. Nuclear fusion releases a lot of energy, which is what powers the Sun.                         
You:
how to cure a flu?
Google Bard:
There is no cure for the flu, but there are treatments that can help relieve symptoms and prevent complications. The most effective way to prevent the flu is to get a flu vaccine
every year.                                                                                                                                                                       
If you get the flu, there are a few things you can do to feel better:                                                                                                             
 • Rest. Get plenty of sleep and avoid strenuous activity.                                                                                                                        
 • Drink plenty of fluids. Water, juice, and soup are all good choices.                                                                                                           
 • Take over-the-counter pain relievers like acetaminophen or ibuprofen.                                                                                                          
 • Use a humidifier. The moisture can help soothe your throat and make it easier to breathe.                                                                                      
 • See a doctor if you have severe symptoms or are at high risk of complications.                                                                                                 
Here are some tips to help you prevent the flu:                                                                                                                                   
 • Get a flu vaccine every year. The flu vaccine is the best way to prevent the flu.                                                                                              
 • Wash your hands often with soap and water. This helps to prevent the spread of germs.                                                                                          
 • Avoid close contact with people who are sick. If you must be around someone who is sick, wear a mask.                                                                          
 • Clean and disinfect surfaces that may be contaminated with germs.                                                                                                              
 • Stay home from work or school if you are sick. This will help to prevent the spread of the flu.                                                                                
 • Eat a healthy diet and exercise regularly. A healthy immune system is better able to fight off infection.                                                                      
You:
Exiting...
本文内容来源于互联网,如有侵权请联系删除。
作者最新文章
编程开发 Python
相关文章 更多
Python安装后怎么打开:使用IDLE或命令行启动解释器
Python安装后怎么打开:使用IDLE或命令行启动解释器

刚在Windows安装好Python却不知道如何启动?本文详细演示如何通过开始菜单找到并打开IDLE集成开发环境,以及如何在PowerShell或命令提示符中使用python和py命令启动交互式解释器、运行.py脚本文件。包含退出解释器的方法及常见启动问题排查,帮助初学者快速验证安装成功并开始编写代码。

Windows系统Python安装教程:下载、勾选PATH及环境变量配置
Windows系统Python安装教程:下载、勾选PATH及环境变量配置

针对Windows初学者的Python安装实战指南。详细讲解如何从Python官网下载匹配架构的安装包,重点演示安装首屏勾选“Add python.exe to PATH”的关键操作,并提供使用python --version和py命令验证环境变量的具体步骤,帮助新手快速搭建开发环境并排查路径问题。

麒麟OS如何查看Python进程的运行状态
麒麟OS如何查看Python进程的运行状态

要想确认麒麟OS中Python程序的运行状态以及资源占用情况,我们可以这样做:用ps -ef | grep python来筛选进程;通过top命令,按P键排序查看实时负载;使用pgrep -f "script.py"精准获取PID;借助lsof -p PID验证文件打开状态。另外,还可以结合syst

Python在Debian上如何配置SSL证书
Python在Debian上如何配置SSL证书

在Debian系统上配置SSL证书通常涉及以下几个步骤:安装Web服务器:首先,你需要一个Web服务器,比如Apache或Nginx。这里以Apache为例。sudo apt updatesudo apt install apache2获取SSL证书:你可以从Let’s Encrypt免费获取SSL

统信UOS怎么安装Python开发环境
统信UOS怎么安装Python开发环境

要想让Python项目在统信UOS上正常运行,得先安装python3、python3-pip、python3-venv、python3-dev以及build-essential等组件。具体操作就是执行sudo apt install命令来一步到位完成安装,同时别忘了配置清华镜像源来给pip加速哦。在

纯Python方案实现中英文全文搜索
纯Python方案实现中英文全文搜索

在互联网上的各类网站中,无论大小,基本上都会有一个搜索框,用来给用户对内容进行搜索,小到站点搜索,大到搜索引擎搜索。从简单的来说,搜索功能确实很简单,一个简单的select语句就可以实现数据的搜索。而从复杂的来看,无论是搜索的精度还是搜索的效率,都是有很深的研究范围的。对于简单的搜索功能来说,一个s

Mac如何取消通过Python脚本运行的关机程序
Mac如何取消通过Python脚本运行的关机程序

立即在终端输入sudo shutdown -c取消倒计时关机,成功后显示“Shutdown cancelled”;若存在pmset重复任务,需再执行sudo pmset repeat cancel清除。Mac因Python脚本执行了os.system("sudo shutdown -h +10")或

Pythonasyncio异步并发与多固定出口IP调度实战
Pythonasyncio异步并发与多固定出口IP调度实战

之前写过一篇同步场景下用 Python 管理多个固定出口 IP 的实践(ExitPool + requests/httpx),覆盖了健康检查、故障转移和连接池复用。但在实际业务中,越来越多的场景用 asyncio 做高并发采集或批量接口调用——异步事件循环下多出口的管理方式和同步场景完全不同:单线程

Python在静态出口IP产品中的实战:从地址漂移巡检到多IP故障切换
Python在静态出口IP产品中的实战:从地址漂移巡检到多IP故障切换

写在前面:为什么静态出口 IP 不是"买了就行"不少团队在引入静态出口 IP 产品时,第一反应往往是:“地址配上去,这事就算完了。”可真到了真实业务里,静态出口 IP 真正能体现价值的地方,往往不在分配这一步,而在分配之后怎么管:地址有没有漂移,质量是否达标,某一条线路突然不可用时怎么切换,连接层又

using namespace 使用中遇到的问题怎么解决
using namespace 使用中遇到的问题怎么解决

命名空间的基本概念与常见引入问题在C++等编程语言中,命名空间(namespace)是一种将代码标识符(如变量、函数、类名)封装在特定名称下的机制,其主要目的是避免命名冲突,尤其是在大型项目或使用多个第三方库时。使用“using namespace”指令可以将指定命名空间中的所有名称引入当前作用域,

查看更多
精品专题 更多
装机必备
装机必备

正软商城装机必备专区,精选办公、浏览器、安全防护、影音播放、压缩解压、设计创作和系统工具等电脑常用正版软件,帮助用户快速完成新电脑软件配置。

Windows
Windows

正软商城Windows软件专区,汇集适用于Windows电脑的办公、设计、安全防护、影音播放、开发工具和系统优化软件,提供软件介绍、系统要求、正版授权及购买下载服务。

macOS软件
macOS软件

正软商城macOS软件专区,精选适用于Mac电脑的办公、设计、影音、效率、开发和系统工具,提供软件功能介绍、macOS兼容版本、正版授权及购买下载服务。

Mac软件 更多
灵活计算器
灵活计算器
macOS/iOS/Android

灵活计算器是一款笔记式算数应用,支持实时计算、动态关联和云端同步功能。记录、整理和输出之间的过渡会更自然,适合长期写作、做笔记或持续沉淀个人内容。

赤友清理大师
赤友清理大师
macOS

赤友清理大师是一款为 Mac 设计的智能清理优化工具,可精准扫描垃圾、大文件、重复文件等,释放磁盘空间。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。

极度公式
极度公式
Windows/macOS/Linux

极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。

WINDOWS 更多
Windows 10
Windows 10
Windows

Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。

极度公式
极度公式
Windows/macOS/Linux

极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。

密码键盘
密码键盘
Windows/macOS/iOS/Android

密码键盘是一款兼具安全性与便捷性的高效密码管理器。日常使用里的持续防护和信息管理会更突出,适合把安全控制放进长期使用流程中的场景。