用Python基於Google Bard做一個互動式的聊天機器人

来源:https://www.cnblogs.com/larrydpk/archive/2023/03/24/17250015.html
-Advertisement-
Play Games

用Python基於Google Bard做一個互動式的聊天機器人 之前已經通過瀏覽器試過了 Google Bard ,更多細節請看: Try out Google Bard, Will Google Bard beat the ChatGPT?. 現在我們想實現自動化,所以我用Python做一個交互 ...


用Python基於Google Bard做一個互動式的聊天機器人

之前已經通過瀏覽器試過了 Google Bard ,更多細節請看: Try out Google Bard, Will Google Bard beat the ChatGPT?.

現在我們想實現自動化,所以我用Python做一個互動式的聊天機器人。

獲取Session ID

通過瀏覽器先拿到SessionID,它是一個cookie,名為 __Secure-1PSID,然後複製一下對應的值:

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...

代碼

相關代碼請查看: GitHUb LarryDpk/pkslow-samples


References:

Bard


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • const: 這個最簡單,只需記住是聲明的常量,定義的時候必須聲明const的具體值,且之後不允許改變const的值 var和let區別 1、由於js引擎存在預解析,會把var變數名進行提升 對於var來說是這樣執行的 var m; console.log(m); m=10; let不存在變數提升, ...
  • ### canvas特性 標簽中的文本只有在瀏覽器下支持canvas標簽時才顯示 行內塊元素 高度設置在標簽屬性上 ### 填充色設置 ctx.fillStyle="#ff0000" ### 線條顏色設置 ctx.strokeStyle="ff0000" ### 線條粗細 ctx.lineWidth ...
  • 備忘錄模式(Memento Pattern):是一種行為型設計模式,在不破壞封裝性的前提下,捕獲一個對象的內部狀態,併在該對象之外保存這個狀態。在JavaScript中,可以使用閉包來實現備忘錄模式。 備忘錄模式通常用於處理用戶界面的狀態。當用戶與應用程式交互時,應用程式會根據用戶的輸入更改其狀態。 ...
  • 在基於vue-next-admin 的 Vue3+TypeScript 前端項目中,可以整合自己的 .NET 後端,前端操作一些功能的時候,為了使用方便全局掛載的對象介面,以便能夠快速處理一些特殊的操作,如消息提示、輔助函數、正則測試等等。本篇隨筆介紹在Vue3+TypeScript 前端項目中全局... ...
  • 眾所周知,網頁的暗黑模式可以減少屏幕反射和藍光輻射,減少眼睛的疲勞感,特別是在夜間使用時更為明顯。其實暗黑模式也給霓虹燈效應(Neon Effect)提供了發揮的環境。 霓虹燈效應是一種視覺效果,其特點是在深色背景上使用鮮艷的顏色來產生強烈的視覺衝擊。這種效應通常用於設計海報、廣告、標誌和網頁等。霓 ...
  • 領域驅動設計(Domain Driven Design,簡稱:DDD)設計思想和方法論早在2005年時候就被提出來,但是一直沒有被重視和推薦使用,直到2015年之後微服務流行之後,再次被人重視和推薦使用。 下麵我來介紹一下DDD設計思想和方法論,同時結合我們在實際項目中應用總結和思考。 目錄 1、為 ...
  • 一、案例背景 電腦包含記憶體(RAM),CPU 等硬體設備,根據如圖所示的“產品等級結構-產品族示意圖”,使用抽象工廠模式實現電腦設備創建過程並繪製類圖 二、實現步驟 根據題意,使用抽象工廠模式並畫出類圖,類圖中應包含一個抽象工廠類 AbstractFactory,PcFactory 和 MacF ...
  • 1. 理解可變性 1.1. 理解測試結果如何隨時間變化 1.2. 可以通過多次運行測試後取平均值來解決 1.3. 因代碼改進而進行的測試叫作回歸測試(regression testing) 1.3.1. 原本的代碼叫作基線(baseline) 1.3.2. 新的代碼叫作樣本(specimen) 1. ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...