基于本地大语言模型与 LangChain 构建免费 AI 搜索问答助手
本文介绍了如何利用本地部署的大语言模型结合检索增强生成(RAG)技术构建免费 AI 搜索问答助手。方案使用 Ollama 运行本地模型,通过搜索引擎获取最新网络信息,经解析、切片、向量化后存入 Chroma 数据库,最终由 LangChain 框架实现上下文问答。该方法无需付费 API,解决了大模型知识滞后问题,并提供环境搭建、核心代码实现及性能优化建议。

本文介绍了如何利用本地部署的大语言模型结合检索增强生成(RAG)技术构建免费 AI 搜索问答助手。方案使用 Ollama 运行本地模型,通过搜索引擎获取最新网络信息,经解析、切片、向量化后存入 Chroma 数据库,最终由 LangChain 框架实现上下文问答。该方法无需付费 API,解决了大模型知识滞后问题,并提供环境搭建、核心代码实现及性能优化建议。

大语言模型虽然拥有海量的训练数据,但对于训练截止后产生的新内容或特定领域的专业知识,往往无法给出准确回应。一个常用的解决方案是检索增强生成(RAG),通过将相关上下文提供给大模型,利用其强大的理解和生成能力来缓解知识滞后问题。
本文介绍如何借助搜索引擎获取较新的网络内容,并结合本地部署的大语言模型构建 AI 搜索问答助手。该方法无需使用付费 API,整个流程可在单台笔记本电脑上运行,完全免费。
本方案的核心依然是 RAG 架构。AI 搜索并非实时爬取全互联网数据,而是借助搜索引擎接口获取相关文档。从搜索引擎获取结果后,后续处理流程与标准 RAG 一致:解析文本、切片、向量化存储、检索匹配,最后结合 Prompt 生成回答。
处理流程如下:
本文涉及的组件支持 Windows、Linux 和 macOS。以下以 macOS 14.4 Sonoma (ARM 芯片) 为例进行说明。
推荐使用 Conda 管理虚拟环境。确保 Python 版本为 3.10 或以上。 创建并激活环境:
conda create -n rag_env python=3.11
conda activate rag_env
安装依赖包:
pip install langchain langchain-community chromadb beautifulsoup4 requests chainlit
Ollama 用于本地运行大语言模型及 Embedding 模型。
在命令行执行以下命令下载模型:
ollama pull qwen:7b
ollama pull znbang/bge:large-zh-v1.5-q8_0
qwen:7b 为通义千问大语言模型,znbang/bge 为中文向量模型。若机器配置较高,可选择参数量更大的模型;若配置较低,可尝试 qwen:1.8b 等轻量级模型。
验证模型是否就绪:
ollama list
ollama run qwen:7b
输入 /exit 退出交互模式。
在 Python 中测试 LLM 连接:
from langchain_community.llms import Ollama
model = Ollama(
base_url="http://localhost:11434",
model="qwen:7b"
)
print(model("你是谁"))
测试 Embedding 模型:
from langchain_community.embeddings import OllamaEmbeddings
embeddings = OllamaEmbeddings(
base_url="http://localhost:11434",
model="znbang/bge:large-zh-v1.5-q8_0"
)
print(embeddings.embed_query("你好"))
由于部分搜索引擎 API 申请复杂或有限制,本文采用模拟浏览器请求 Bing 中文版的方式获取搜索结果。
import requests
from bs4 import BeautifulSoup
from urllib.parse import quote
def search_with_bing(query):
url = f'https://cn.bing.com/search?q={quote(query)}'
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36'
}
resp = requests.get(url, headers=headers, timeout=10)
soup = BeautifulSoup(resp.text, 'html.parser')
results = []
for item in soup.select('#b_results > li'):
title_tag = item.select_one('h2 a')
if not title_tag:
continue
abstract_tag = item.select_one('div.b_caption p')
results.append({
'title': title_tag.text,
'link': title_tag['href'],
'abstract': abstract_tag.text.replace('\u2002', ' ') if abstract_tag else ''
})
return results
调用上述搜索函数获取链接列表,随后遍历链接获取网页正文。
search_results = search_with_bing('大语言模型')
for item in search_results:
try:
resp = requests.get(item['link'], timeout=5)
html = resp.text
# 此处需根据实际编码调整,通常 utf-8
soup = BeautifulSoup(html, 'html.parser')
# 移除脚本样式
for script in soup(["script", "style"]):
script.decompose()
item['body'] = soup.get_text(separator='\n', strip=True)
except Exception as e:
print(f"Failed to fetch {item['link']}: {e}")
使用 LangChain 的文本分割器对长文本进行切片,避免超出模型上下文窗口。
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.docstore.document import Document
from langchain.vectorstores import Chroma
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=400,
chunk_overlap=50,
separators=["\n\n", "\n", " ", ""]
)
docs = [
Document(page_content=item['body'], metadata={'source': item['link'], 'title': item['title']})
for item in search_results
]
split_docs = text_splitter.split_documents(docs)
vectorstore = Chroma.from_documents(documents=split_docs, embedding=embeddings)
retriever = vectorstore.as_retriever(search_kwargs={'k': 6})
设计清晰的 Prompt 模板,要求模型仅基于提供的上下文回答。
prompt_template = """请使用下方的上下文回答问题。如果上下文中没有相关信息,请回答'我无法回答这个问题'。
<<<context>>>
{context}
<</context>>>
用户提问:{query}
请回答:
"""
def generate_answer(query):
context_docs = retriever.invoke(query)
context = '\n\n'.join([doc.page_content for doc in context_docs])
prompt = prompt_template.format(context=context, query=query)
response = model(prompt)
return response
使用 Chainlit 快速构建聊天界面。
import chainlit as cl
@cl.on_message
async def main(message: cl.Message):
answer = generate_answer(message.content)
await cl.Message(content=answer).send()
启动服务:
chainlit run app.py
本文详细介绍了如何利用本地大语言模型结合 RAG 技术构建免费的 AI 搜索助手。通过 Ollama 实现模型本地化,避免了 API 费用;通过搜索引擎解决知识时效性问题;通过 LangChain 简化了开发流程。该方案适合个人开发者学习 RAG 原理及本地部署实践。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online