2025年2月12日 星期三

Python 學習筆記 : 使用 DuckDuckGo API 搜尋網路資料 (一)

最近在讀旗標的 "LangChain 開發手冊" 這本書時看到 DuckDuckGo 搜尋引擎的訊息 (LangChain 工具集有內建 DuckDuckGoSearchAPIWrapper 類別), 以前在安裝不知哪款瀏覽器時似乎預設搜尋引擎是 DuckDuckGo, 但是在 Google 主宰搜尋市場時代, 誰還會去用甚麼鴨子搜尋引擎呢? 但今天深入了解後才發現它的好, 優點摘要如下 :
  • 使用方便 : 提供免費且不需要金鑰的 API, 可整合到應用程式中
  • 保護隱私 : DuckDuckGo 瀏覽器不追蹤使用者, 不收集個人資料, 不紀錄瀏覽歷史 
  • 立場中立 : 不過濾搜尋結果 (谷歌根據使用者資料提供個人化搜尋結果) 
  • 廣告簡單 : 僅依據搜尋關鍵字提供直接相關之簡單廣告 (谷歌提供個人化廣告)
  • 輕量快速 : 網站無過多的廣告與追蹤腳本程式碼, 執行效能高
於是立馬來測試一下 DuckDuckGo API 的用法, 其 API 網址如下 :


可以直接用瀏覽器連線此網站手動輸入關鍵字進行搜尋 : 




也可以透過第三方套件於自己的應用程式中呼叫其 API 取得搜尋結果. 


1. 安裝 duckduckgo-search 套件 : 

如果要在應用程式中使用 DuckDuckGo API 取得搜尋結果, 要先用 pip install 安裝 duckduckgo-search 套件 :

pip install duckduckgo-search   

D:\python\test>pip install duckduckgo-search   
Collecting duckduckgo-search
  Downloading duckduckgo_search-7.3.2-py3-none-any.whl.metadata (17 kB)
Collecting click>=8.1.8 (from duckduckgo-search)
  Downloading click-8.1.8-py3-none-any.whl.metadata (2.3 kB)
Collecting primp>=0.11.0 (from duckduckgo-search)
  Downloading primp-0.12.0-cp38-abi3-win_amd64.whl.metadata (13 kB)
Collecting lxml>=5.3.0 (from duckduckgo-search)
  Downloading lxml-5.3.1-cp310-cp310-win_amd64.whl.metadata (3.8 kB)
Requirement already satisfied: colorama in c:\users\tony1\appdata\local\programs\thonny\lib\site-packages (from click>=8.1.8->duckduckgo-search) (0.4.6)
Downloading duckduckgo_search-7.3.2-py3-none-any.whl (19 kB)
Downloading click-8.1.8-py3-none-any.whl (98 kB)
Downloading lxml-5.3.1-cp310-cp310-win_amd64.whl (3.8 MB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 3.8/3.8 MB 4.1 MB/s eta 0:00:00
Downloading primp-0.12.0-cp38-abi3-win_amd64.whl (3.1 MB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 3.1/3.1 MB 7.0 MB/s eta 0:00:00
Installing collected packages: primp, lxml, click, duckduckgo-search
  Attempting uninstall: lxml
    Found existing installation: lxml 4.9.3
    Uninstalling lxml-4.9.3:
      Successfully uninstalled lxml-4.9.3
  Attempting uninstall: click
    Found existing installation: click 8.1.7
    Uninstalling click-8.1.7:
      Successfully uninstalled click-8.1.7
Successfully installed click-8.1.8 duckduckgo-search-7.3.2 lxml-5.3.1 primp-0.12.0

安裝後的套件名稱是 duckduckgo_search, 先匯入整個套件 :

>>> import duckduckgo_search    
>>> duckduckgo_search.__version__   
'7.3.2'

用 dir() 檢視套件內容 :

>>> dir(duckduckgo_search)   
['DDGS', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', 'duckduckgo_search', 'exceptions', 'logging', 'utils', 'version'] 

這些成員中的核心是 DDGS 類別, 其他都是子模組, 除 exceptions 開發者可用來處理例外, 其餘均為內部使用. 


2. 建立 DDGS 物件 : 

使用 DuckDuckGo API 搜尋必須先建立 DDGS 物件, 首先匯入 DDGS 類別, 然後呼叫其建構式 DDGS() 來建立物件 : 

>>> from duckduckgo_search import DDGS   
>>> ddgs=DDGS()     
>>> type(ddgs)   
<class 'duckduckgo_search.duckduckgo_search.DDGS'>  

用 dir() 檢視 DDGS 物件內容 : 

>>> dir(ddgs)   
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_chat_messages', '_chat_models', '_chat_tokens_count', '_chat_vqd', '_get_url', '_get_vqd', '_impersonates', '_impersonates_os', '_sleep', '_text_html', '_text_lite', 'chat', 'client', 'headers', 'images', 'news', 'parser', 'proxy', 'sleep_timestamp', 'text', 'videos']

其中 client, headers, proxy, parser, sllep_timestamp 五個為屬性, 大部分為 DDGS 內部使用或很少用到, 其餘為物件方法, 也是 DDGS 主要的功能所在, 提供文字, 圖片, 視訊, 新聞等搜尋功能, 以及聊天機器人, 用法說明摘要如下表 : 


DDGS 物件方法 說明
chat(query, model='gpt-3.5-turbo') AI 聊天機器人 (可指定 gpt-4o-mini 模型).
text(query, max_results=10, region='us', safesearch='moderate', timelimit=None) 一般文字搜尋, 回傳標題, 網址與摘要.
images(query, max_results=10, safesearch='moderate') 圖片搜尋, 回傳圖片 URL 及縮圖.
videos(query, max_results=10, region='us', safesearch='moderate') 影片搜尋, 回傳影片標題與連結.
news(query, max_results=10, region='us', safesearch='moderate') 新聞搜尋, 回傳新聞標題, 網址與摘要.


3. 文字搜尋 :  

呼叫 DDGS 物件的 text() 方法並傳入關鍵字 (也可指定搜尋區域 region 與傳回筆數 max_results 等參數) 進行搜尋會傳回一個包含標題, 網址, 摘要等搜尋結果的字典串列, 例如 : 

>>> query='Langchain'  
>>> results=ddgs.text(query)   
>>> type(results)   
<class 'list'> 
>>> len(results)   
10

可見傳回值是一個串列, 如果沒有指定 max_results 參數預設是最多傳回 10 筆搜尋結果. 檢視串列元素為字典, 包含 title (網頁標題), href (網址), 與 body (內容) 三個鍵 : 

>>> type(results[0])  
<class 'dict'>  
>>> results[0]   
{'title': 'LangChain', 'href': 'https://www.langchain.com/', 'body': '"Working with LangChain and LangSmith on the Elastic AI Assistant had a significant positive impact on the overall pace and quality of the development and shipping experience. We couldn\'t have achieved the product experience delivered to our customers without LangChain, and we couldn\'t have done it at the same pace without LangSmith."'}
>>> results[0].keys()   
dict_keys(['title', 'href', 'body'])

傳入 max_results 參數可以指定最多傳回幾筆搜尋結果, 例如 :

>>> results=ddgs.text(query, max_results=5)   
>>> len(results)      
5

下面利用迴圈輸出這 5 筆搜尋結果的標題 (title) 與超連結 (href) :

>>> i=1   
>>> for result in results:   
    print(f'{i}. {result["title"]}\n{result["href"]}')   
    i += 1   
    
1. LangChain
https://www.langchain.com/
2. Introduction | ️ LangChain
https://python.langchain.com/docs/introduction/
3. GitHub - langchain-ai/langchain: Build context-aware reasoning ...
https://github.com/langchain-ai/langchain
4. LangChain - Wikipedia
https://en.wikipedia.org/wiki/LangChain
5. LangChain
https://www.langchain.com/langchain

也可以傳入 region 參數限制搜尋結果網頁的地區與語言, 例如台灣繁體中文的 region 代號為 'zh-tw' : 

>>> results=ddgs.text(query, region='zh-tw', max_results=5)   
>>> i=1    
>>> for result in results:   
    print(f'{i}. {result["title"]}\n{result["href"]}')   
    i += 1   

1. LangChain
https://www.langchain.com/
2. LangChain是什麼?AI開發者必須了解的LLM開源框架 - ALPHA Camp
https://tw.alphacamp.co/blog/langchain-intro
3. LangChain 框架介绍 | ️ Langchain
https://docs.langchain.com.cn/docs/introduction/
4. 快速入門 | ️ LangChain 框架
https://langchain-python.dev.org.tw/docs/get_started/quickstart/
5. 一文搞懂LangChain是什么(非常详细),零基础入门到精通,看这一篇就够了-CSDN博客
https://blog.csdn.net/weixin_49895216/article/details/142848013

不過看起來似乎不分簡體繁體, 只要是中文都包含在內. 


4. 圖片搜尋 :  

呼叫 DDGS 物件的 images() 方法並傳入關鍵字 (也可指定搜尋區域 region 與傳回筆數 max_results 等參數) 會傳回一個包含網頁標題與網址, 圖片與其縮圖網址, 圖片尺寸等搜尋結果的字典串列, 例如 : 

>>> query='可愛的貓'  
>>> results=ddgs.images(query, max_results=5)  
>>> type(results)  
<class 'list'>  

檢視第一個元素內容為紀錄網頁網址, 圖片網址, 與圖片尺寸等訊息的字典 : 

>>> results[0]   
{'title': '真想養貓!6種適合新手認養的可愛貓咪 | 布偶貓 | 網紅貓 | 大紀元', 'image': 'https://i.epochtimes.com/assets/uploads/2020/10/shutterstock_1665879682.jpg', 'thumbnail': 'https://tse2.mm.bing.net/th?id=OIP.siVhfvYFrZi77bBl4fAJBgHaE7&pid=Api', 'url': 'https://www.epochtimes.com/b5/20/10/13/n12472751.htm', 'height': 3016, 'width': 4525, 'source': 'Bing'}
>>> results[0].keys()  
dict_keys(['title', 'image', 'thumbnail', 'url', 'height', 'width', 'source'])

其中 title 為網頁標題, images 為圖片網址, url 為包含此圖片之網頁的網址, height 與 width 分別為圖片之高度與寬度 (px), source 為網頁來源, thumbnail 為縮圖網址. 按圖片網址即可看到此圖片 : 





用迴圈列出這五筆圖片 : 

>>> i=1    
>>> for result in results:
    print(f'{i}. {result["title"]}:\n{result["image"]}')
    i += 1   
    
1. 真想養貓!6種適合新手認養的可愛貓咪 | 布偶貓 | 網紅貓 | 大紀元:
https://i.epochtimes.com/assets/uploads/2020/10/shutterstock_1665879682.jpg
2. 【貓桌布】可愛喵合集!13款治癒系喵星人桌布,快讓你的桌面被喵星人佔領~ | CatCity 貓奴日常:
https://image.presslogic.com/cats.presslogic.com/wp-content/uploads/2021/03/c3671215.jpeg
3. 【手機壁紙】第二五期 可愛貓咪壁紙 - 每日頭條:
https://i2.kknews.cc/SIG=bbhro/61690001p648srn7rnqp.jpg
4. 可爱猫|快乐版 - 全部作品 - 素材集市:
http://img.sucaijishi.com/uploadfile/2023/0210/20230210100626916.png?imageMogr2/format/jpg/blur/1x0/quality/60
5. 可爱的猫 向量, 可愛的, 画, 卡通貓向量圖案素材免費下載,PNG,EPS和AI素材下載 - Pngtree:
https://png.pngtree.com/png-clipart/20230430/original/pngtree-cute-cat-png-image_9126653.png


5. 新聞搜尋 :  

呼叫 DDGS 物件的 news() 方法並傳入關鍵字 (也可指定搜尋區域 region 與傳回筆數 max_results 等參數) 會傳回一個包含標題, 網址, 摘要等搜尋結果的字典串列, 例如 : 

>>> query='Taiwan'  
>>> results=ddgs.news(query, max_results=5)  
>>> type(results)  
<class 'list'>  

檢視第一個元素內容, 可見此字典包含新聞日期, 標題, 內容, 網頁網址, 圖片網址, 以及新聞來源等 : 

>>> results[0]   
{'date': '2025-02-12T01:22:00+00:00', 'title': 'Taiwan environment minister eyes insurance funds to help with green transition', 'body': "Taiwan aims to get more than $1.5 billion in investment from insurance funds to help finance the island's green energy transition as part of its climate change and carbon reduction goals, Environment Minister Peng Chi-ming has said.", 'url': 'https://www.reuters.com/sustainability/sustainable-finance-reporting/taiwan-environment-minister-eyes-insurance-funds-help-with-green-transition-2025-02-12/', 'image': 'https://www.reuters.com/resizer/v2/HAZKYEC4ONNSFIRMNE3YL3X5FE.jpg?auth=63a2bee4ac149ad73c2938a9370ebc61fbe9142fc0b572a4d3fac552c7f9ad93&height=1005&width=1920&quality=80&smart=true', 'source': 'Reuters'} 
>>> results[0].keys()   
dict_keys(['date', 'title', 'body', 'url', 'image', 'source'])   

用迴圈列出這五筆新聞 : 

>>> i=1   
>>> for result in results:   
    print(f'{i}. {result["title"]}:\n{result["title"]}\n{result["body"]}\n')   
    i += 1    
    
1. Taiwan environment minister eyes insurance funds to help with green transition:
Taiwan environment minister eyes insurance funds to help with green transition
Taiwan aims to get more than $1.5 billion in investment from insurance funds to help finance the island's green energy transition as part of its climate change and carbon reduction goals, Environment Minister Peng Chi-ming has said.

2. Taiwan looks to buy Alaskan natural gas as it seeks to head off US tariffs:
Taiwan looks to buy Alaskan natural gas as it seeks to head off US tariffs
TAIPEI (Reuters) -Taiwan is interested in natural gas from Alaska and will continue to assess the feasibility of purchases, the economy ministry said on Monday, as the government looks to narrow the trade surplus with the United States and head off tariffs.

3. Taiwan detects 62 Chinese aircraft as US ships transit waters:
Taiwan detects 62 Chinese aircraft as US ships transit waters
Taiwan said Wednesday it detected 62 Chinese military aircraft near the self-ruled island this week, as two US ships sailed through the sensitive Taiwan Strait.

4. Chinese Military Monitored US Ship Crossing Taiwan Strait, State Media Reports:
Chinese Military Monitored US Ship Crossing Taiwan Strait, State Media Reports
(Reuters) - China's military said it organised naval and air forces to monitor the navigation operations of a U.S. destroyer and oceanographic survey ship crossing the Taiwan Strait from February 10-12, according to state broadcaster CCTV on Tuesday.

5. Hope film 'Ne Zha 2' to be screened in Taiwan island as soon as possible: spokesperson:
Hope film 'Ne Zha 2' to be screened in Taiwan island as soon as possible: spokesperson
In response to heated discussions about "Ne Zha 2" on the island of Taiwan, Zhu Fenglian, spokesperson for the State Council Taiwan Affairs Office, expressed the wish on Wednesday's press conference that the film will be screened in the island as soon as possible,


6. 影片搜尋 :  

呼叫 DDGS 物件的 videos() 方法並傳入關鍵字 (也可指定搜尋區域 region 與傳回筆數 max_results 等參數) 會傳回一個影片搜尋結果的字典串列, 例如 : 

>>> query='APT'    
>>> results=ddgs.videos(query, max_results=5)    
>>> type(results)  
<class 'list'>  
>>> len(results)     
5

檢視第一個元素內容 : 

>>> results[0]   
{'content': 'https://www.youtube.com/watch?v=ekr2nIex040', 'description': "ROSÉ & Bruno Mars - APT. Download/stream: https://rosesarerosie.lnk.to/APTID Order APT. single CD: https://rosesarerosie.lnk.to/APT-CDID 'rosie' - the first studio album by ROSÉ - out now download/stream: http://rosesarerosie.lnk.to/rosieID ROSÉ store exclusive 'rosie' vinyl, cd's, and more available now: http://rosesarerosie.lnk.to/storeID ...", 'duration': '2:54', 'embed_html': '<iframe width="1280" height="720" src="https://www.youtube.com/embed/ekr2nIex040?autoplay=1" frameborder="0" allowfullscreen></iframe>', 'embed_url': 'https://www.youtube.com/embed/ekr2nIex040?autoplay=1', 'image_token': '0be8410e804bf8c9e7c153c4f1747a34f92023b265a805e271710c9b129f9e62', 'images': {'large': 'https://tse1.mm.bing.net/th?id=OVP.u9EjUh1N1E2_3aDLeeiQNAHgFo&pid=Api', 'medium': 'https://tse1.mm.bing.net/th?id=OVP.u9EjUh1N1E2_3aDLeeiQNAHgFo&pid=Api', 'motion': 'https://tse2.mm.bing.net/th?id=OM.cEYhVc1Do-7hdA_1731902268&pid=Api', 'small': 'https://tse1.mm.bing.net/th?id=OVP.u9EjUh1N1E2_3aDLeeiQNAHgFo&pid=Api'}, 'provider': 'Bing', 'published': '2024-10-18T04:00:07.0000000', 'publisher': 'YouTube', 'statistics': {'viewCount': 1082191568}, 'title': 'ROSÉ & Bruno Mars - APT. (Official Music Video)', 'uploader': 'ROSÉ'}

檢視字典的鍵 : 

>>> results[0].keys()    
dict_keys(['content', 'description', 'duration', 'embed_html', 'embed_url', 'image_token', 'images', 'provider', 'published', 'publisher', 'statistics', 'title', 'uploader'])

其中 content 為影片網址, title 是影片標題, embed_html 是影片嵌入網頁碼, embed_url 是影片嵌入網址, duration 是影片長度, images 是影片不同解析度的縮圖 (有 small, medium, 與 large 等尺寸) 網址, published 是發佈時間等等. 





用迴圈列出這五筆影片搜尋結果 :

>>> i=1   
>>> for result in results:  
    print(f'{i}. {result["title"]}:\n{result["content"]}')   
    i += 1   
    
1. ROSÉ & Bruno Mars - APT. (Official Music Video):
https://www.youtube.com/watch?v=ekr2nIex040
2. ROSÉ & Bruno Mars - APT. (live from 2024 MAMA AWARDS):
https://www.youtube.com/watch?v=Jn8KvdWagfo
3. ROSÉ - APT. in the Radio 1 Live Lounge:
https://www.youtube.com/watch?v=Lwv254J8Ozk
4. APT Bruno Mars and Rosé | Learn the Viral Dance | Step-by-Step Beginner Tutorial:
https://www.youtube.com/watch?v=XxOAEpW8rPs
5. APT Bruno Mars and Rosé | Learn the Viral Dance | Practice it with Music:
https://www.youtube.com/watch?v=Cysgn9xOt-Q


7. 聊天機器人 :  

呼叫 DDGS 物件的 chat() 方法並傳入提示詞會傳回一個回應字串, 例如 : 

>>> prompt='Who are you?'   
>>> reply=ddgs.chat(prompt)   
>>> type(reply)   
<class 'str'>   
>>> reply  
'I am an AI language model created by OpenAI, designed to assist with a wide range of questions and tasks by providing information and generating text based on the input I receive. How can I help you today?'

問它使用甚麼模型只回答 GPT-3 :

>>> prompt='Please tell me your specific model name'    
>>> ddgs.chat(prompt)   
"I am based on OpenAI's GPT-3 model. If you have any specific questions or need assistance, feel free to ask!"

追問它版本代號是否為 gpt-3.5-turbo, 回答 Yes :

>>> prompt='Are you using gpt-3.5-turbo?'   
>>> ddgs.chat(prompt)   
'Yes, I am based on the GPT-3.5-turbo model. If you have any questions or need assistance, feel free to ask!'

用中文也可以 : 

>>> prompt='高雄有哪些代表性美食(請用繁體中文 zh-hant 回答)?'   
>>> ddgs.chat(prompt)   
'高雄是台灣的美食天堂,擁有許多代表性的美食。以下是一些高雄的特色美食:\n\n1. **六合夜市小吃**:六合夜市是高雄最著名的夜市之一,這裡有各式各樣的小吃,如鹽酥雞、蚵仔煎、魷魚羹等。\n\n2. **海鮮**:高雄靠近海邊,新鮮的海鮮是當地的特色。可以品嚐到生魚片、蒸螃蟹、烤魚等美味。\n\n3. **牛肉麵**:高雄的牛肉麵也相當有名,湯頭濃郁,牛肉軟嫩,搭配手工麵條,讓人回味無窮。\n\n4. **鳳梨酥**:這是一種受歡迎的台灣伴手禮,高雄的鳳梨酥以餡料豐富、外皮酥脆著稱。\n\n5. **草莓冰**:在夏天,草莓冰是高雄的消暑佳品,清爽的草莓搭配冰品,讓人感到清涼。\n\n6. **珍珠奶茶**:雖然珍珠奶茶在台灣各地都很流行,但高雄有許多獨特的店家,提供不同口味的珍珠奶茶。\n\n7. **豆花**:高雄的豆花口感滑嫩,常搭配花生、紅豆等配料,是一道受歡迎的甜品。\n\n這些只是高雄美食的一部分,還有許多其他美味的選擇,值得一試!'

可能需要條列的就會回應 Markdown 字串, 要用 print() 輸出才會排列整齊 : 

>>> reply=ddgs.chat(prompt)    
>>> print(reply)     
高雄是台灣的美食重鎮,擁有許多代表性的美食。以下是一些高雄的特色美食:

1. **鹽酥雞**:這道小吃在高雄的夜市非常受歡迎,外酥內嫩,搭配各種香料和調味料,口感極佳。

2. **蚵仔煎**:高雄靠近海邊,新鮮的蚵仔是這道料理的主角,搭配蛋和地瓜粉,口感滑嫩,常淋上特製醬汁。

3. **魷魚羹**:這是一道以魷魚為主料的湯品,湯頭鮮美,魷魚鮮嫩,常搭配米飯或麵條。

4. **牛肉麵**:高雄的牛肉麵以濃郁的湯頭和軟嫩的牛肉著稱,配上手工麵條,讓人一試成主顧。

5. **海鮮**:高雄的海鮮新鮮且多樣,生魚片、蒸螃蟹、烤魚等都是當地的美味選擇。

6. **草莓冰**:在炎熱的夏天,草莓冰是高雄的消暑佳品,清爽的草莓搭配冰品,讓人感到清涼。

7. **珍珠奶茶**:雖然珍珠奶茶在台灣各地都很流行,但高雄有許多獨特的店家,提供不同口味的珍珠奶茶。

8. **豆花**:高雄的豆花口感滑嫩,常搭配花生、紅豆等配料,是一道受歡迎的甜品。

這些美食只是高雄的一部分,還有許多其他美味的選擇,值得你親自去品嚐!

問它物理學的東西 :

>>> prompt='請簡單說明何謂量子糾纏?'   
>>> ddgs.chat(prompt)    
'量子糾纏是一種量子力學現象,當兩個或多個粒子以某種方式相互作用後,它們的量子狀態會變得相互依賴,即使這些粒子相隔很遠。這意味著對其中一個粒子的測量會立即影響到另一個粒子的狀態,無論它們之間的距離有多遠。\n\n簡單來說,量子糾纏使得粒子之間存在一種超越經典物理學的聯繫,這種現象挑戰了我們對於空間和時間的傳統理解。量子糾纏在量子計算和量子通信等領域具有重要的應用潛力。'

可以傳入 model 參數指定 gpt-4o-mini 模型 : 

>>> ddgs.chat(prompt, model='gpt-4o-mini')    
'量子糾纏是一種量子力學現象,當兩個或多個粒子相互作用後,它們的量子狀態會變得相互依賴。這意味著對其中一個粒子的測量會立即影響到另一個粒子的狀態,無論它們之間的距離有多遠。這種現象顯示了粒子之間存在一種超越經典物理學的聯繫,並在量子計算和量子通信等領域具有重要的應用。'

如果指定 gpt-4o 會出現錯誤, 但自動改用 gpt-4o-mini :

>>> ddgs.chat(prompt, model='gpt-4o')    
C:\Users\tony1\AppData\Local\Programs\Thonny\lib\site-packages\duckduckgo_search\duckduckgo_search.py:167: UserWarning: model='gpt-4o' is unavailable. Using 'gpt-4o-mini'
  warnings.warn(f"{model=} is unavailable. Using 'gpt-4o-mini'", stacklevel=1)
'量子糾纏是一種量子力學現象,當兩個或多個粒子相互作用後,它們的量子狀態會變得緊密相關。這意味著對其中一個粒子的測量會立即影響到另一個粒子的狀態,即使這些粒子相隔很遠。量子糾纏挑戰了我們對於空間和時間的傳統理解,並在量子計算和量子通信等領域具有重要的應用潛力。'

傳入 context 參數可以讓模型記得前後脈絡, 但下面測試卻顯示它居然記得耶 :

>>> prompt='我有養兩隻貓, 名叫小咪與萬萬'  
>>> ddgs.chat(prompt)    
'聽起來你有兩隻可愛的貓咪!小咪和萬萬的名字都很有趣。牠們的性格如何呢?有沒有什麼特別的故事或趣事可以分享?'   
>>> prompt='我那兩隻貓名字是甚麼?'   
>>> ddgs.chat(prompt)   
'你提到的兩隻貓的名字是小咪和萬萬。牠們聽起來都很可愛!如果你有任何關於牠們的問題或想分享的故事,隨時告訴我!' 
>>> prompt='你還記得我養了幾隻貓嗎? 名字是甚麼?'   
>>> ddgs.chat(prompt)   
'你養了兩隻貓,名字分別是小咪和萬萬。如果你有更多想分享的關於牠們的故事或問題,隨時告訴我!'

哇塞! 真不錯啊! 我猜 chat() 可能內建了記憶機制. 

沒有留言 :