学习笔记20《部署一个鲜花网络电商的人脉工具(上)》

63 阅读3分钟

项目背景与目标

易速鲜花电商网络希望通过微博大V推广品牌,需要一个工具帮助市场营销部门找到合适的大V并提供联络方案。

技术实现细节

  1. 找到大V:通过LangChain搜索工具找到可能对鲜花推广感兴趣的大V的UID。
  2. 爬取大V资料:根据UID爬取大V的公开信息。
  3. 生成合作文案:利用LLM生成介绍型文章,谋求合作。
  4. 格式化数据结构:使用LangChain输出解析功能,生成可嵌入提示模板的数据结构。
  5. 创建App:使用HTML、CSS和Flask创建并部署人脉工具App。

第一步:找到大V

主程序 findbigV.py

# 设置OpenAI API密钥
import os
os.environ["OPENAI_API_KEY"] = ''
os.environ["SERPAPI_API_KEY"] = ''

# 导入所取的库
import re
from agents.weibo_agent import lookup_V

if __name__ == "__main__":
    # 拿到UID
    response_UID = lookup_V(flower_type="牡丹")
    print(response_UID)

    # 抽取UID里面的数字
    UID = re.findall(r'\d+', response_UID)[0]
    print("这位鲜花大V的微博ID是", UID)

微博Agent weibo_agent.py

# 导入一个搜索UID的工具
from tools.search_tool import get_UID

# 导入所需的库
from langchain.prompts import PromptTemplate
from langchain.chat_models import ChatOpenAI
from langchain.agents import initialize_agent, Tool
from langchain.agents import AgentType

# 通过LangChain代理找到UID的函数
def lookup_V(flower_type: str):
    # 初始化大模型
    llm = ChatOpenAI(temperature=0, model_name="gpt-3.5-turbo")

    # 寻找UID的模板
    template = """given the {flower} 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/1669879400  is her 微博, then 1669879400 is her UID
                  This is only the example don't give me this, but the actual UID"""
    # 完整的提示模板
    prompt_template = PromptTemplate(
        input_variables=["flower"], 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
    )

    # 返回找到的UID
    ID = agent.run(prompt_template.format_prompt(flower=flower_type))

    return ID

定制的SerpAPI search_tool.py

# 导入SerpAPIWrapper
from langchain.utilities import SerpAPIWrapper

# 重新定制SerpAPIWrapper,重构_process_response,返回URL
class CustomSerpAPIWrapper(SerpAPIWrapper):
    def __init__(self):
        super(CustomSerpAPIWrapper, self).__init__()

    @staticmethod
    def _process_response(res: dict) -> str:
        """Process response from SerpAPI."""
        if "error" in res.keys():
            raise ValueError(f"Got error from SerpAPI: {res['error']}")
        # ... 省略无关代码 ...
        if "organic_results" in res.keys():
            first_organic_result = res["organic_results"][0]
            if "snippet" in first_organic_result.keys():
                snippets.append(first_organic_result["link"])  # 返回URL
        # ... 省略无关代码 ...

# 获取与某种鲜花相关的微博UID的函数
def get_UID(flower: str):
    search = CustomSerpAPIWrapper()
    res = search.run(f"{flower}")
    return res

第二步:爬取大V资料

主程序 findbigV.py

# 导入所取的库
from tools.general_tool import remove_non_chinese_fields
from tools.scraping_tool import get_data

if __name__ == "__main__":
    # 拿到UID
    response_UID = lookup_V(flower_type="牡丹")
    # 抽取UID里面的数字
    UID = re.findall(r'\d+', response_UID)[0]
    print("这位鲜花大V的微博ID是", UID)

    # 根据UID爬取大V信息
    person_info = get_data(UID)
    print(person_info)

    # 移除无用的信息
    remove_non_chinese_fields(person_info)
    print(person_info)

爬虫工具 scraping_tool.py

# 导入所需的库
import json
import requests
import time

# 定义爬取微博用户信息的函数
def scrape_weibo(url: str):
    headers = {
        "User-Agent": "Mozilla/5.0 ...",
        "Referer": "https://weibo.com" 
    }
    cookies = {
        "cookie": "你的Cookie"
    }
    response = requests.get(url, headers=headers, cookies=cookies)
    time.sleep(3)   # 加上3s 的延时防止被反爬
    return response.text

# 根据UID构建URL爬取信息
def get_data(id):
    url = "https://weibo.com/ajax/profile/detail?uid={}".format(id)
    html = scrape_weibo(url)
    response = json.loads(html)

    return response

总结

通过LangChain组件,我们完成了找到大V UID和爬取大V资料的步骤,为后续生成合作文案和部署App打下了基础。

思考题

  1. 如果Agent不返回UID而是返回URL,是否也能完成任务?尝试重构提示模板和后续逻辑,返回URL并解析UID。
  2. 研究SerpAPIWrapper类的_process_response中的代码,了解其设计和功能。