LangChain 实战:构建微博大 V 推荐智能体
本文介绍了如何使用 LangChain 框架结合 LLM 和爬虫技术,构建一个自动识别微博大 V 并获取其信息的智能体。通过 SerpAPI 搜索关键词定位 UID,利用爬虫抓取公开资料,最后通过 Flask 封装服务供业务部门调用。重点展示了 Agent 初始化、Prompt 模板设计及数据清洗流程,实现了从需求分析到服务交付的完整闭环。

本文介绍了如何使用 LangChain 框架结合 LLM 和爬虫技术,构建一个自动识别微博大 V 并获取其信息的智能体。通过 SerpAPI 搜索关键词定位 UID,利用爬虫抓取公开资料,最后通过 Flask 封装服务供业务部门调用。重点展示了 Agent 初始化、Prompt 模板设计及数据清洗流程,实现了从需求分析到服务交付的完整闭环。

在深入理解 LangChain 各个模块后,通过实际业务场景进行实战是掌握其用法的关键。本文将以一个电商推广场景为例,利用 LangChain 和 LLM(大语言模型)开发一款效率工具,帮助网销团队在微博上自动寻找适合合作的大 V。
某电商品牌计划结合节日和食补概念提升品牌形象,需要联系微博上的相关领域大 V 进行推广。AIGC 开发部门需开发一个社交网络工具,实现以下功能:
首先编写代码,通过 Agent 找到目标大 V 的微博 UID。
# 环境变量设置
import os
os.environ['OPENAI_API_KEY'] = 'your_api_key_here'
os.environ['SERPAPI_API_KEY'] = 'your_api_key_here'
# 正则模块
import re
# 核心开发一个 weibo_agent find_v 方法
from agents.weibo_agent import find_V
if __name__ == "__main__":
response_UID = find_V(food_type="助眠")
print(response_UID)
# 从返回结果中正则提取所有的 UID 数字
UID = re.findall(r'\d+', response_UID)[0]
print("这位大 V 的微博 ID 是", UID)
我们如何在微博中找到合适的 UID?通过 find_V 方法实现。
# tools_search_tool 后续会编写
from tools_search_tool import get_UID
# 模板
from langchain.prompts import PromptTemplate
from langchain.chat_models import ChatOpenAI
# 准备定制 Agent
from langchain.agents import initialize_agent, Tool
from langchain.agents import AgentType
def find_V(food_type: str):
llm = ChatOpenAI(temperature=0, model_name="gpt-3.5-turbo")
template = """given the {food} I want you to get a related 微博 UID.
Your answer should contain only a UID.
The URL always starts with https://weibo.com/u/
for example, if https://weibo.com/u/3659536733 is her 微博,then 3659536733 is his UID This is only the example don't give me this, but the actual UID
"""
prompt_template = PromptTemplate(
input_variables=["food"],
template=template
)
tools = [
Tool(
name="Crawl Google for 微博 page",
func=get_UID,
description="useful for when you need get the 微博 UID"
)
]
agent = initialize_agent(
tools,
llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=True
)
ID = agent.run(prompt_template.format_prompt(food=food_type))
return ID
在上述代码中定义了一个 Agent,只需提供食补类型,即可获取 Agent 返回的 UID。langchain.agents 提供了 initialize_agent 和 Tool,第一个参数 tools 内部会使用 SerpAPI 搜索相关内容;第二个参数是 LLM。
编写 get_UID 方法,SerpAPI 是一个很好的搜索集成工具。
# langchain 集成了 SerpAIWrapper
from langchain.utilities import SerpAPIWrapper
def get_UID(food: str):
"""Searches for Weibo Page."""
search = SerpAPIWrapper()
res = search.run(f"{food} site:weibo.com")
return res
为了生成更贴合该博主的邀请信,我们需要爬取博主的更多消息并交给 LLM 处理。
import json # json 解析
import requests #发送请求
import time #时间
def scrape_weibo(url: str):
'''爬取相关博主的资料'''
# 请求头 User-Agent 模拟浏览器,referer 模拟来源
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36",
"Referer": "https://weibo.com"
}
# 注意:生产环境中请妥善保管 Cookie,避免硬编码
cookies = {
"cookie": "XSRF-TOKEN=...; _s_tentry=weibo.com; ..."
}
try:
response = requests.get(url, headers=headers, cookies=cookies, timeout=10)
time.sleep(2) # 加上 2 秒延时防止被反爬
return response.text
except Exception as e:
print(f"Request failed: {e}")
return None
def get_data(id):
url = f"https://weibo.com/ajax/profile/detail?uid={id}"
html = scrape_weibo(url)
if not html:
return {}
response = json.loads(html)
return response
我们可以通过 https://weibo.com/ajax/profile/detail?uid=xxx 页面查找博主的信息,返回格式为 JSON。
获取了博主信息后,我们需要移除不重要的内容,确保 AIGC 输入的是中文有效信息。
import re
def contains_chinese(s):
return bool(re.search('[\u4e00-\u9fa5]', s))
def remove_non_chinese_fields(d):
if isinstance(d, dict):
to_remove = [key for key, value in d.items() if isinstance(value, (str, int, float, bool)) and (not contains_chinese(str(value)))]
for key in to_remove:
del d[key]
for key, value in d.items():
if isinstance(value, (dict, list)):
remove_non_chinese_fields(value)
elif isinstance(d, list):
to_remove_indices = []
for i, item in enumerate(d):
if isinstance(item, (str, int, float, bool)) and (not contains_chinese(str(item))):
to_remove_indices.append(i)
else:
remove_non_chinese_fields(item)
for index in reversed(to_remove_indices):
d.pop(index)
为了满足网销部门的使用需求,我们将上述功能封装为 Flask API。
from flask import Flask, request, jsonify
from agents.weibo_agent import find_V
from tools.scraping_tool import get_data
app = Flask(__name__)
@app.route('/api/find_kol', methods=['POST'])
def find_kol():
data = request.json
food_type = data.get('food_type', '养生')
uid = find_V(food_type)
if not uid:
return jsonify({"status": "error", "message": "未找到合适的大 V"})
# 获取详细信息
info = get_data(uid)
return jsonify({"status": "success", "uid": uid, "info": info})
if __name__ == '__main__':
app.run(debug=True, port=5000)
本文完成了查找适合推广食疗干货的大 V 微博 UID,并爬取了大 V 的详细资料。主要使用了以下 LangChain 组件:
通过 Flask 封装,该工具可方便地集成到现有的营销工作流中,显著提高人工筛选大 V 的效率。在实际部署时,建议增加错误重试机制、频率限制以及敏感信息脱敏处理,以确保系统的稳定性和合规性。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 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