利用LangChain实现网页内容爬取并总结

本文介绍了如何使用LangChain库中的load_summarize_chain函数处理长网页内容,通过Map-reduce策略将长文本切分并总结,以解决超出LLMtoken限制的问题,以查找产品生产厂商为例,展示了具体的应用过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

背景

利用LangChain中load_summarize_chain实现网页内容爬取并总结。

亮点:

网页内容过长,导致超过LLM的token限制,使用LangChain中load_summarize_chain实现。

Map-reduce思想:

  • 先对长文本进行切分
  • map阶段-对每段进行summary
  • reduce-对每个map再进行总结
  • 实现长文本内容总结

案例实现:

背景:想查找某个产品的生产厂商,需要先去网页查找相关连接,然后分别总结每个连接内容,最后对内容进行汇总。以下为代码:

​
# 使用google针对产品进行搜索,返回产品列表

import os
from autogen import config_list_from_json
import autogen
import requests
from bs4 import BeautifulSoup
import json

# from langchain.chat_models import ChatOpenAI
from langchain_community.chat_models import ChatOpenAI
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.chains.summarize import load_summarize_chain
from langchain import PromptTemplate
import openai
from dotenv import load_dotenv
# Get API key
load_dotenv()
config_list3 = {"model": "gpt-3.5-turbo","api_key": "sk-xxxxx", "cache_seed": 42}

os.environ["OPENAI_API_KEY"] = "sk-xxxxx"

# summary chain:对每个url输出进行总结
def summary(product,content):
    llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo-16k-0613")
    text_splitter = RecursiveCharacterTextSplitter(
        separators=["\n\n", "\n"], chunk_size=10000, chunk_overlap=500)
    docs = text_splitter.create_documents([content])
    map_prompt = """
        content is :{text}
        Please summarize the Chinese manufacturers of """+ product +""" ,based on the above content and return them in list format.
        The returned results should be in the following format(Return strictly in list format.): ["manu1","manu2","manu3"...]
        The manufacturers should be from the Chinese market, and it's preferred to use the full name of the manufacturers rather than abbreviations.
        """
    combine_prompt = """
        content is :{text}
        Please summarize the Chinese manufacturers of """+ product +""" ,based on the above content and return them in list format.
        The returned results should be in the following format(Return strictly in list format.): ["manu1","manu2","manu3"...]
        The manufacturers should be from the Chinese market, and it's preferred to use the full name of the manufacturers rather than abbreviations.
        """
    map_prompt_template = PromptTemplate(
        template=map_prompt, input_variables=["text"])
    combine_prompt_template = PromptTemplate(
        template=combine_prompt, input_variables=["text"])

    summary_chain = load_summarize_chain(
        llm=llm,
        chain_type='map_reduce',
        map_prompt=map_prompt_template,
        combine_prompt=combine_prompt_template,
        verbose=False
    )

    output = summary_chain.run(input_documents=docs, )
    # print(output)
    return output
# print(summary("GPU","GPU的生产厂家有:七彩虹厂商,技嘉厂商."))
# print(type(summary("GPU","GPU的生产厂家有:七彩虹厂商,技嘉厂商.")))

# 抓取内容:
def scrape(product:str,url: str):
    # scrape and summary
    print("Scraping website...")
    # Define the headers for the request
    headers = {
        'Cache-Control': 'no-cache',
        'Content-Type': 'application/json',
    }
    # Define the data to be sent in the request
    data = {
        "url": url
    }
    # 转json
    data_json = json.dumps(data)

    # Send the POST request
    response = requests.post(
        "https://chrome.browserless.io/content?token=2db344e9-a08a-4179-8f48-195a2f7ea6ee", headers=headers, data=data_json)

    # Check the response status code
    if response.status_code == 200:
        soup = BeautifulSoup(response.content, "html.parser")
        text = soup.get_text()
        # print("CONTENTTTTTT:", text)
        # 不论长短都做总结  -> 生成厂商list
        # text超长问题
        if len(text) > 8000:
            text = text[:8000]
        output = summary(product,text)
        try:
            result_list = eval(output)
        except Exception as e:
            print("生成结果格式转化为list失败,返回为[]")
            result_list = []
        return result_list
    else:
        print(f"HTTP request failed with status code {response.status_code}")

# 查找
def search(query):
    url = "https://google.serper.dev/search"

    payload = json.dumps({
        "q": query
    })
    headers = {
        'X-API-KEY': 'do not use mine',
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    results = response.json()['organic']
    # print(results)
    product_manu=[]
    for res in results[:10]:
        if res["link"]:
            res_manu = scrape(query, res["link"])
            # 增加判断,如果返回是列表再去扩展
            if isinstance(res_manu, list):
                product_manu.extend(res_manu)
            else:
                print("the result of scrape is not list ,pass ")
        else:
            continue

    print("******  product_manu is: \n",product_manu)
    return response.json()

search("RTX3050显卡生产厂商")

​

<think>好的,用户现在想用langchain4j库来实现WPS自动生成大纲,需要示例代码或教程。首先,我需要确认langchain4j是否支持直接与WPS集成。根据我的了解,langchain4j主要是一个用于集成大语言模型(LLM)到Java应用中的库,它本身可能不直接处理WPS文档的操作,但可以通过生成结构化内容,然后利用其他库(如Apache POI)来操作文档。 接下来,用户可能需要的是如何结合LLM生成大纲的结构,然后将这个结构转化为WPS文档的格式。因此,步骤应该是:1.使用langchain4j调用LLM生成大纲内容;2.使用文档处理库将大纲内容写入WPS文件。我需要检查是否有相关的示例代码或者文档。目前,langchain4j的文档可能没有直接涉及WPS的部分,但可以借鉴处理Office文件的一般方法。例如,生成Markdown格式的大纲,再转换为DOCX文件,或者直接使用ApachePOI创建文档。另外,用户可能不熟悉如何将生成的内容插入到WPS中,所以需要分步说明。首先,确保依赖项正确,包括langchain4j-core和可能的文档处理库。然后,编写代码调用模型生成大纲,接着处理输出写入文档。 可能遇到的问题包括模型选择、输出格式的解析以及文档生成的兼容性。需要提醒用户替换API密钥,选择合适的模型,处理可能的异常。此外,如果用户需要更复杂的格式,可能需要结合其他工具或库。 最后,生成相关问题,帮助用户深入理解,比如如何优化提示词、处理长文档或集成到WPS插件中。确保回答清晰,步骤明确,提供示例代码作为参考。</think>根据现有技术栈分析,实现WPS自动生成大纲需要结合语言模型和文档处理技术。以下是基于langchain4j的实现思路与示例代码: ### 实现步骤 1. **搭建语言模型接口** 使用langchain4j连接大语言模型(如GPT-3.5/4、DeepSeek等)生成结构化大纲内容 2. **文档格式转换** 将生成的Markdown/文本格式大纲转换为WPS支持的.docx格式 3. **自动化流程整合** 通过Java文件操作API完成内容写入 ### 基础示例代码 ```java // 添加依赖 // implementation "dev.langchain4j:langchain4j-open-ai:0.27.0" // implementation "org.apache.poi:poi-ooxml:5.2.3" import dev.langchain4j.model.openai.OpenAiChatModel; import org.apache.poi.xwpf.usermodel.*; public class WpsOutlineGenerator { public static void main(String[] args) { // 1. 通过LLM生成大纲内容 String outline = generateOutline("人工智能在教育领域的应用"); // 2. 创建WPS文档 XWPFDocument doc = new XWPFDocument(); createOutlineDocument(doc, outline); // 保存文件 try (FileOutputStream out = new FileOutputStream("AI教育大纲.docx")) { doc.write(out); } } static String generateOutline(String topic) { OpenAiChatModel model = OpenAiChatModel.builder() .apiKey("your-api-key") .modelName("gpt-3.5-turbo") .temperature(0.3) .build(); String prompt = "请为'" + topic + "'生成包含三级标题的文档大纲,使用Markdown格式,最多5个主章节"; return model.generate(prompt); } static void createOutlineDocument(XWPFDocument doc, String markdown) { // 解析Markdown生成文档结构 String[] lines = markdown.split("\n"); for (String line : lines) { if (line.startsWith("# ")) { addHeading(doc, line.substring(2), 1); } else if (line.startsWith("## ")) { addHeading(doc, line.substring(3), 2); } else if (line.startsWith("### ")) { addHeading(doc, line.substring(4), 3); } } } static void addHeading(XWPFDocument doc, String text, int level) { XWPFParagraph para = doc.createParagraph(); para.setStyle("Heading" + level); XWPFRun run = para.createRun(); run.setText(text); } } ``` ### 关键实现点说明 1. **提示词工程** 通过明确格式要求(Markdown三级标题)确保输出结构化,示例提示词包含: - 明确的格式指令 - 内容范围限制 - 结构化层级要求 2. **文档格式转换** 使用Apache POI库实现: - 创建`XWPFDocument`对象 - 根据`#`数量匹配WPS标题样式(Heading1-Heading3) - 保持格式与WPS原生样式兼容 3. **模型参数优化** 通过设置`temperature=0.3`平衡创造性与结构稳定性[^1] ### 扩展优化建议 1. **增加交互功能** ```java // 可添加大纲修订功能 public String reviseOutline(String original, String feedback) { String prompt = "根据以下反馈修改大纲:" + feedback + "\n原大纲:" + original; return model.generate(prompt); } ``` 2. **样式深度定制** 通过修改`doc.getStyles().getStyle("Heading1")`自定义标题字体、缩进等样式参数
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值