# Chapter5. 突破時空限制 - 整合搜尋功能 :+1: 完整程式碼在 https://github.com/iamalex33329/chatgpt-develop-guide-zhtw ## 其他章節 [Chapter1. OpenAI API 入門](https://hackmd.io/@U3f2IzHERbymAst2-lDdjA/S1cNMYi6T) [Chapter2. 使用 Python 呼叫 API](https://hackmd.io/@U3f2IzHERbymAst2-lDdjA/HyZBg5ia6) [Chapter3. API 參數解析與錯誤處理](https://hackmd.io/@U3f2IzHERbymAst2-lDdjA/BJWNtsh6p) [Chapter4. 打造自己的 ChatGPT](https://hackmd.io/@112356044/Hk81U96Tp) [Chapter6. 讓 AI 幫 AI - 自動串接流程](https://hackmd.io/@112356044/r1Ke-GR6T) [Chapter7. 網頁版聊天程式與文字生圖 Image API](https://hackmd.io/@112356044/Hyf-AvgAT) [Chapter8. 設計 LINE AI 聊天機器人](https://hackmd.io/@112356044/r1d6HsgAa) [Chapter9. 自媒體業者必看!使用 AI 自動生成高品質字幕](https://hackmd.io/@112356044/rJ2T37V0T) [Chapter10. 把 AI 帶到 Discord](https://hackmd.io/@112356044/Sy_L-B40T) [Chapter11. AI 客製化投資理財應用實戰](https://hackmd.io/@112356044/HkUE0rER6) [Chapter12. 用 LangChain 實作新書宣傳自動小編](https://hackmd.io/@112356044/SybvbdN0p) ## 目錄結構 [TOC] ## 用搜尋網頁幫 AI 補充知識 由於模型訓練資料僅到 2021 年 9 月,而作為語言模型,openai 有關鍵的兩個角色: 1. **理解文意**:模型能夠根據輸入的文字,理解文字內含的意義。 2. **能言善道**:模型也能夠編出語意通順的回覆,甚至可以把錯的事情說得頭頭是道,間單來說就是:睜眼說瞎話。 ### 使用 Google 搜尋 我們能夠在與模型對話時,導入 Google 搜尋的功能,這邊使用 `googlesearch-python` 的套件,擷取 Google 搜尋結果,再整理成簡單的格式。 ``` python= !pip install googlesearch-python ``` 従 `googlesearch` 中匯入 `search()` ``` python= from googlesearch import search ``` 只要傳入搜尋關鍵字,就能夠取得數個搜尋結果的**連結** ``` python=+ for link in search('台灣2024總統'): print(link) # https://www.bbc.com/zhongwen/trad/chinese-news-67971619 # https://zh.wikipedia.org/zh-cn/2024%E5%B9%B4%E4%B8%AD%E8%8F%AF%E6%B0%91%E5%9C%8B%E7%B8%BD%E7%B5%B1%E9%81%B8%E8%88%89 # https://www.president.gov.tw/NEWS/28140 # https://www.president.gov.tw/NEWS/28140 # https://topic.ctee.com.tw/2024vote # https://www.president.gov.tw/NEWS/28140 # https://www.president.gov.tw/NEWS/28140 # https://www.president.gov.tw/NEWS/28140 # https://2024.cec.gov.tw/ # https://www.president.gov.tw/NEWS/28140 # https://topic.ctee.com.tw/2024vote ``` 若要取得搜尋結果的**標題**以及**摘要內容**,可以加入以下參數: ``` python= for item in search('台灣2024總統', advanced=True, num_results=5): print(item.title) print(item.description) print(item.url) # 台灣大選2024:賴清德當選總統民進黨未能控制立法院 # Jan 13, 2024 — 1月13日,台灣舉行2024年總統選舉與立法委員選舉,執政黨民進黨候選人賴清德以超過558萬票勝選。 # https://www.bbc.com/zhongwen/trad/chinese-news-67971619 # ---------- # 2024總統大選》破連任魔咒!賴清德、蕭美琴當選第16任正副 ... # 2024總統大選登場,藍綠白三組候選人讓選情幾度膠著,最終由民進黨賴清德、蕭美琴打敗民眾黨柯文哲、吳欣盈,及國民黨侯友宜、趙少康,成為第16任總統、副總統。 # https://www.cw.com.tw/article/5127925 # ---------- # 台灣大選2024:賴清德當選總統民進黨未能控制立法院 # Jan 13, 2024 — 1月13日,台灣舉行2024年總統選舉與立法委員選舉,執政黨民進黨候選人賴清德以超過558萬票勝選。 # https://www.bbc.com/zhongwen/trad/chinese-news-67971619 ``` 啟用進階模式(advanced=True)就不只回傳連結,而是傳回**物件** > 即使設定傳回筆數,也不一定會精準控制在設定的該數字 ## 整合搜尋結果讓 AI 跟上時代 這裡直接改寫與 openai 互動的程式碼,我們以 `/w:` 作為上網搜尋資料的暗號,並嘗試比較經過網路搜尋結果所得出的答案異同: ``` python= def chat_web(sys_msg, user_msg): web_res = [] if user_msg[:3].lower() == '/w ': user_msg = user_msg[3:] content = "The following news is fact:\n" for res in search(user_msg, advanced=True, num_results=5, lang='zh-TW'): content += f"Title:{res.title}\n" \ f"Description:{res.description}\n\n" content += "Please answer the following question based on the information provided above.\n" web_res = [{"role": "user", "content": content}] web_res.append({"role": "user", "content": user_msg}) while len(hist) >= 2 * backtrace: hist.pop(0) reply_full = "" for reply in get_reply_stream(hist + web_res + [{"role": "system", "content": sys_msg}]): reply_full += reply yield reply hist.append({"role": "user", "content": user_msg}) while len(hist) >= 2 * backtrace: hist.pop(0) hist.append({"role": "assistant", "content": reply_full}) # => Who is the 2024 president in Taiwan? # As of my last update, the president of Taiwan in 2024 is Tsai Ing-wen. # => /w Who is the 2024 president in Taiwan? # Lai Ching-te is the president of Taiwan in 2024. ``` 雖然實際在執行時,會花一點時間來等待 google 返回搜尋結果,但仍能發現得出的結果是準確的 > 這部分尚未使用其他例子比較,僅供參考! ## 使用 Google Search JSON API 上一節的套件 `googlesearch-python` 是採用網頁爬蟲的方式,當程式在短時間內頻繁送出請求時,可能會遭 Google 封鎖 IP 一小段時間。 而 Google 有提供 API 可以進行搜尋,免費版本會有一天 100 次的請求限制。 [:link: Custom Search JSON API](https://developers.google.com/custom-search/v1/overview?hl=zh-tw) ### 建立搜尋引擎 ID ::: 使用 Custom Search JSON API 之前,請先建立並設定程式化搜尋引擎。如果您尚未建立程式化搜尋引擎,可以先造訪[程式化搜尋引擎控制台](https://programmablesearchengine.google.com/controlpanel/all?hl=zh-tw)。 ![Screenshot 2024-03-13 at 1.02.22 AM](https://hackmd.io/_uploads/BJHCcZCpp.png) ### 取得 API KEY ::: Custom Search JSON API 需要使用 API 金鑰。 ![Screenshot 2024-03-13 at 12.58.26 AM](https://hackmd.io/_uploads/Syu1q-RpT.png) ### 使用 HTTP API 取得搜尋結果 > Google Search JSON API 採用 HTTP GET 方式 必要查詢參數: 1. `key`:$CUSTOM_SEARCH_JSON_API 2. `ctx`:$SEARCH_ENGINE_ID 3. `q`:keyword 可選常用查詢參數: 1. `num`:傳回的筆數,至多 10 筆 2. `start`:從搜尋結果第幾筆開始傳回,最多 100 筆,因此 start + num 不能超過 100 3. `siteSearch`:指定搜尋的網站 4. `lr`:限定搜尋語言,如 "lang_zh-TW" 是繁體中文 ``` python= import requests import apikey r = requests.get( 'https://www.googleapis.com/customsearch/v1?' \ 'key={}&' \ 'cx={}&' \ 'num={}&' \ 'q={}'.format( apikey.CUSTOM_SEARCH_JSON_API, apikey.SEARCH_ENGINE_ID, 3, '2024 President in Taiwan' ) ) print(r.json()) ``` 傳回的 JSON 資料非常複雜,可以直接進行操作 ``` python=+ for item in r.json()['items']: print(item['title']) print(item['snippet']) print(item['link']) print() # Taiwan's 2024 Elections: Results and Implications # Jan 19, 2024 ... On January 13, 2024, Taiwan held elections for its presidency and 113-seat legislature, the Legislative Yuan. The run-up to the election ... # https://www.csis.org/analysis/taiwans-2024-elections-results-and-implications # 2024 Taiwanese presidential election - Wikipedia # Results edit. All election results were released at 22:00 on 13 January, and showed that Lai Ching-te had won with 40.05% of the vote. # https://en.wikipedia.org/wiki/2024_Taiwanese_presidential_election # Lai Ching-te will be the next president of Taiwan | The Economist # Jan 13, 2024 ... On January 13th 2024, voters elected Lai Ching-te of the Democratic Progressive Party as Taiwan's next president. Mr Lai won 40% of the vote ... # https://www.economist.com/interactive/2024-taiwan-election ``` > 可以看到回傳的筆數非常精準!