简介:本文详述如何通过Dify框架与SearXNG搜索引擎集成,为Deepseek模型赋予实时联网知识查询能力,涵盖技术原理、部署流程、代码示例及优化策略。
在AI大模型应用场景中,Deepseek等模型虽具备强大的文本生成能力,但其知识库受限于训练数据的时间节点(如2023年前的公开数据)。当用户询问”2024年巴黎奥运会金牌榜”等实时性问题时,传统模型无法给出准确回答。此时,联网知识查询成为刚需。
Dify作为开源的LLM应用开发框架,提供模型调用、工作流编排等核心能力。而SearXNG作为去中心化元搜索引擎,可聚合Google、Bing等搜索结果,且支持自定义搜索引擎规则。两者的结合能实现:
sequenceDiagramUser->>Dify API: 发送查询请求Dify API->>SearXNG: 调用搜索接口SearXNG->>Google/Bing: 发起搜索Google/Bing-->>SearXNG: 返回搜索结果SearXNG-->>Dify API: 聚合结果Dify API->>Deepseek: 生成最终回答Deepseek-->>Dify API: 返回回答Dify API-->>User: 展示结果
# 基础环境(以Ubuntu为例)sudo apt updatesudo apt install -y docker docker-compose python3-pip# 安装Dify(假设已fork到本地)git clone https://github.com/your-repo/dify.gitcd difypip install -r requirements.txt
Docker部署方式:
version: '3'services:searxng:image: searxng/searxng:latestports:- "8080:8080"environment:- INSTANCE_NAME=my_searxng- BASE_URL=http://localhost:8080volumes:- ./searxng-settings.yml:/etc/searxng/settings.yml
关键配置(searxng-settings.yml):
server:bind_address: "0.0.0.0"port: 8080search:engines:- name: googleengine: googleshortcut: g- name: bingengine: bingshortcut: bdefault_engines:- bing
class WebSearchTool(Tool):
def init(self, searxng_url=”http://localhost:8080“):
self.searxng_url = searxng_url
def run(self, query: str, num_results: int = 3):params = {"q": query,"format": "json","pageno": 1,"results": num_results}response = requests.get(f"{self.searxng_url}/search", params=params)results = response.json().get("results", [])return [{"title": r["title"], "url": r["url"], "content": r["content"]} for r in results]
2. **工作流编排**(Dify YAML配置):```yamlname: web_search_workflowsteps:- name: check_intenttype: pythoncode: |def run(input):if "最新" in input or "现在" in input or "当前" in input:return {"need_search": True}return {"need_search": False}- name: perform_searchtype: tooltool: WebSearchToolcondition: ${steps.check_intent.output.need_search}input_mapping:query: ${input.question}- name: generate_answertype: llmmodel: deepseekprompt: |用户问题:${input.question}<% if steps.perform_search.output: %>搜索结果:<% for result in steps.perform_search.output: %>- ${result.title}(${result.url}):${result.content}<% end %><% end %>请结合上述信息生成回答,若信息不足请说明。
def cached_search(query):
cache_key = f”search:{query}”
cached = r.get(cache_key)
if cached:
return json.loads(cached)
results = web_search_tool.run(query)
r.setex(cache_key, 3600, json.dumps(results)) # 1小时缓存
return results
- **异步处理**:对耗时搜索请求采用异步任务队列(如Celery)### 4.2 安全控制- **搜索结果过滤**:```pythonimport refrom bs4 import BeautifulSoupdef sanitize_content(html):soup = BeautifulSoup(html, 'html.parser')# 移除脚本、样式等非文本内容for script in soup(["script", "style"]):script.decompose()# 提取纯文本并限制长度text = soup.get_text(separator="\n", strip=True)return text[:500] # 限制500字符
limits:global:max_requests_per_second: 10ip_based:max_requests_per_minute: 60
建议建立以下评估指标:
通过Dify与SearXNG的深度集成,开发者可快速构建具备实时知识查询能力的AI应用,在保持模型原有优势的同时,突破静态知识库的限制。实际部署时需根据业务场景调整搜索策略、缓存策略和安全控制措施,以达到最佳效果。