iT邦幫忙

2025 iThome 鐵人賽

DAY 25
0

前言

前面我們玩過了 Spotify 和 HackMD 的 MCP Server,今天要來挑戰一個更實用的 —— SearXNG MCP Server
這次讓我們的 Agent 擁有搜尋全網資訊的能力,變成一個真正的資訊搜集專家~
接著我們正文開始(。・∀・)ノ


實踐

事前準備

SearXNG MCP Serverclone 下來並安裝依賴:
git clone <the web URL>
安裝基礎工具
# 安裝 uv (Python 包管理器)
pip install uv

# 安裝必要的 Python 套件到主環境
pip install markdownify beautifulsoup4 httpx fastapi uvicorn requests
設定 SearXNG MCP Server 環境
cd mcp-searxng

# 同步 Python 環境和依賴
uv sync
安裝 Docker Desktop

官網下載
下載完後,並打開它
https://ithelp.ithome.com.tw/upload/images/20251009/20168454g8HOYntHjR.png
https://ithelp.ithome.com.tw/upload/images/20251009/20168454PlaRg2BO7D.png


整合到 Agent

  • searxng_agent

我們只單純使用 web_search 功能

import requests
from dotenv import load_dotenv
from google.adk.agents import Agent
import tools.searxng.searxng_prompt as prompt

load_dotenv()

def web_search(query: str) -> str:
    """
    執行網頁搜尋,查找相關資訊
    
    Args:
        query: 搜尋關鍵字
        
    Returns:
        搜尋結果的摘要資訊
    """
    try:
        # 直接呼叫 SearXNG API
        searxng_url = "http://localhost:8888"
        
        # SearXNG 搜尋參數
        search_params = {
            'q': query,
            'format': 'json',
            'categories': 'general',
            'language': 'zh-TW'
        }
        
        print(f"搜尋:{query}")  # Debug 日誌
        
        response = requests.get(
            f"{searxng_url}/search",
            params=search_params,
            timeout=10
        )
        
        if response.status_code == 200:
            data = response.json()
            results = data.get('results', [])
            
            if results:
                # 格式化前 5 個結果
                formatted_results = f"**搜尋結果:{query}**\n\n"
                
                for i, result in enumerate(results[:5], 1):
                    title = result.get('title', '無標題')
                    content = result.get('content', '')[:150]
                    url = result.get('url', '')
                    
                    formatted_results += f"**{i}. {title}**\n"
                    if content:
                        formatted_results += f"   {content}...\n"
                    formatted_results += f"   {url}\n\n"
                
                return formatted_results
            else:
                return f"搜尋 '{query}' 沒有找到相關結果。請嘗試其他關鍵字。"
                
        else:
            return f"搜尋服務暫時無法使用(狀態碼:{response.status_code})"
            
    except requests.exceptions.RequestException as e:
        return f"搜尋連接錯誤:{str(e)}"
    except Exception as e:
        return f"搜尋處理錯誤:{str(e)}"

searxng_agent = Agent(
    model="gemini-2.0-flash",
    name="searxng_agent", 
    description=prompt.SEARXNG_AGENT_DESCRIPTION,
    instruction=prompt.SEARXNG_AGENT_INSTRUCTION,
    tools=[web_search] 
)
  • searxng_prompt
SEARXNG_AGENT_DESCRIPTION = """
網頁搜尋和資訊擷取專家,負責處理所有與網路搜尋、網頁內容提取相關的功能。
具備多搜尋引擎整合能力,包括 Google、DuckDuckGo、Bing 等,並能提取網頁內容轉換為 Markdown 格式。
"""

SEARXNG_AGENT_INSTRUCTION = """
當用戶需要搜尋時,使用 web_search 工具執行搜尋。
你會直接連接到 SearXNG 搜尋引擎獲取最新資訊。

搜尋完成後,請:
1. 提供搜尋結果的摘要
2. 標明資料來源
3. 如果是價格查詢,重點提供價格資訊
4. 始終使用繁體中文回應

如果搜尋失敗,友善地建議用戶嘗試其他功能。
"""
  • root_agent 只要在 sub_agent 寫入 searxng_agent 就好~(記得匯入喔!)

  • root_agent prompt 依據自己要求撰寫就好,我searxng 部分:

### searxng_agent - 網路搜尋和資訊專家 Search
**服務範圍:**
- 多引擎網頁搜尋(Google、DuckDuckGo、Bing 等)
- 網頁內容提取和 Markdown 轉換
- 即時資訊查詢和事實查證
- 研究資料蒐集和內容摘要

實踐畫面

服務啟動順序

步驟 1:啟動 SearXNG 搜尋引擎 (Port 8888)
# 進入 Docker 目錄
cd ...\searxng-docker

# 檢查 docker-compose.yaml 是否存在
dir docker-compose.yaml

# 啟動 SearXNG 服務(背景運行)
docker compose up -d

# 驗證服務狀態
docker compose ps
# 應該看到 searxng 容器在 port 8888 運行

# 測試搜尋引擎 Web 介面
Start-Process "http://localhost:8888"
步驟 2:啟動 MCP-SearXNG Server (Port 5488) - 可選
# 回到 mcp-searxng 目錄
cd ...\mcp-searxng

# 啟動 MCP Server(如果你想使用 MCP 協議的話)
python server.py --searxng_url="http://localhost:8888"

# 這會在 port 5488 啟動 MCP Server
# 但我們目前使用直接 API 呼叫方式
步驟 3:啟動 Multi-Tool Agent 主服務 (Port 8080)
# 進入主專案目錄
# 確認虛擬環境已啟動
.venv\Scripts\activate

# 啟動 FastAPI 服務
uvicorn main:app --host 0.0.0.0 --port 8080
步驟 4:啟動 Gradio 使用者介面 (Port 7860)
# 開新終端,進入主專案目錄
# 啟動虛擬環境
.venv\Scripts\activate

# 啟動 Gradio 介面
python gradio_app.py

https://ithelp.ithome.com.tw/upload/images/20251009/20168454GhoSCHfj0V.png


結尾廢話

現在我們的 Agent 不只能管理音樂、寫筆記,還能搜尋全網資訊了!
是不是覺得離「萬能 AI 助手」的目標又更近了一步呢?

下一篇我們會繼續探索更多有趣的 MCP Server,讓這個 Agent 生態系變得更加豐富~
我們下一篇見(ノ>ω<)
reference link


上一篇
[Day 24] SearXNG MCP Server(上)
下一篇
[Day 26] 目前進度小結
系列文
AI Agent 開發養成記:做出屬於自己的Agent P26
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言