LangChain 实战:构建微博大 V 推荐智能体
前言
在深入理解 LangChain 各个模块后,通过实际业务场景进行实战是掌握其用法的关键。本文将以一个电商推广场景为例,利用 LangChain 和 LLM(大语言模型)开发一款效率工具,帮助网销团队在微博上自动寻找适合合作的大 V。
项目需求
某电商品牌计划结合节日和食补概念提升品牌形象,需要联系微博上的相关领域大 V 进行推广。AIGC 开发部门需开发一个社交网络工具,实现以下功能:
- 利用搜索能力找到对特定主题感兴趣的大 V 并获取 UID。
- 爬取大 V 的公开信息以 JSON 格式输出。
- 基于爬虫内容,让 LLM 生成个性化的合作邀请文案。
- 基于 Flask 将功能封装为服务交付给业务部门使用。
技术分析
- Agent 搜索:利用 LangChain 的 Agent 和 Search Chain,定位微博中对特定关键词有兴趣的大 V,返回 UID。
- 数据爬取:编写爬虫抓取大 V 公开信息,解析为结构化数据。
- Prompt 模板:结合爬虫内容,使用 PromptTemplate 让 LLM 生成热情的合作邀请。
- 服务封装:基于 Flask 提供 API 接口。
查找大 V
首先编写代码,通过 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)
定义 Agent
我们如何在微博中找到合适的 UID?通过 find_V 方法实现。
# tools_search_tool 后续会编写
from tools_search_tool import get_UID
langchain.prompts PromptTemplate
langchain.chat_models ChatOpenAI
langchain.agents initialize_agent, Tool
langchain.agents AgentType
():
llm = ChatOpenAI(temperature=, model_name=)
template =
prompt_template = PromptTemplate(
input_variables=[],
template=template
)
tools = [
Tool(
name=,
func=get_UID,
description=
)
]
agent = initialize_agent(
tools,
llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=
)
ID = agent.run(prompt_template.format_prompt(food=food_type))
ID


