★★★ 本文源自AlStudio社区精品项目,【点击此处】查看更多精品内容 >>>

之前有看到LLM嵌入搜索引擎根据搜索结果进行精确回答的推文,这里浅浅复现一下~

整个流程如下:

  1. 输入问题
  2. 获取Bing搜索结果的文字信息(搜索结果通常包括标题、网址、快照文字信息)
  3. 将问题和搜索结果嵌入预先准备好的Prompt模板中
  4. 将嵌入信息的模板输入ChatGLM-6B获取回复

本项目的应用示例如下:

  1. 通过GLM无法给出"五月天的演唱会门票价格"
  2. 通过Bing获取搜索结果
  3. 结合Bing搜索结果,GLM可以给出门票价格!

参考项目

特别鸣谢以下项目,部分代码摘抄自对应项目。

代码流程

环境准备

# 获取PaddleNLP
# import os
# if not os.path.exists('PaddleNLP'):
#     ! git clone https://github.com/PaddlePaddle/PaddleNLP.git
# 为了避免git失败,可以直接从压缩包获取
!unzip -oq paddlenlp.zip
# 更新环境
!cp -Rf paddlenlp /home/aistudio/.data/webide/pip/lib/python3.7/site-packages/paddlenlp
# !pip install --pre --upgrade paddlenlp -f https://www.paddlepaddle.org.cn/whl/paddlenlp.html # 安装nlp分支最新包,和上一条命令选用即可
!python -m pip install paddlepaddle-gpu==0.0.0.post112 -f https://www.paddlepaddle.org.cn/whl/linux/gpu/develop.html --user
#  注意安装后重启内核

获取Bing搜索结果

此部分代码摘抄自python3.5 爬取bing搜索结果页面标题、链接,有时候搜索内容是空的,这是因为搜索失败导致的,多试几下就好了

import re,urllib.parse,urllib.request,urllib.error
from bs4 import BeautifulSoup as BS

# 搜索框中的搜索内容
word = '五月天2023年演唱会门票多少钱'

# 获取bing搜索的结果
def get_bing_results(word):
    baseUrl = 'http://cn.bing.com/search?'
    word = word.encode(encoding='utf-8', errors='strict')

    data = {'q':word}
    data = urllib.parse.urlencode(data)
    url = baseUrl+data
    print(url)

    try:
        html = urllib.request.urlopen(url)
    except urllib.error.HTTPError as e:
        print(e.code)
    except urllib.error.URLError as e:
        print(e.reason)

    # 解析html
    soup = BS(html,"html.parser")
    context = soup.findAll(class_="b_lineclamp4 b_algoSlug")
    # print(context)
    results = ""
    for i in range(len(context)):
        if '\u2002·\u2002' not in str(context[i]): continue
        results += (str(i)+')')
        results += (str(context[i]).split('\u2002·\u2002')[1].replace('</p>',''))

    # 返回soup, context用于debug,有时候results是空的,这是因为搜索失败导致的
    return results, soup, context

results, soup, context = get_bing_results(word)
# print(soup)
print(results)
http://cn.bing.com/search?q=%E4%BA%94%E6%9C%88%E5%A4%A92023%E5%B9%B4%E6%BC%94%E5%94%B1%E4%BC%9A%E9%97%A8%E7%A5%A8%E5%A4%9A%E5%B0%91%E9%92%B1
2)<strong>五月天</strong>北京<strong>演唱会</strong>现场舞台完成搭建后经重新评估,尚有少量座位确认无遮挡可用于观演,该部分<strong>门票</strong>将于5/25上午11点开放售票,每个用户限购2张。 如有意购买请前往大麦APP官方购票渠道。 <strong>五月天</strong>开场嘉宾公布 ☞点击查看: <strong>2023五月天</strong>北京<strong>演唱会</strong>开场嘉宾公布 》》 <strong>2023五月天</strong>北京<strong>演唱会</strong>观演指南(时间+入场+出行) 大麦新发布购票问 …3)【导语】:2023年五月天北京演唱会终于官宣了,五月天演唱会门票价格、开票时间、购票平台已官宣。 五月天演唱会北京看台票价是多少? 答:看台票有三个票档:355元、555元、855元、855元套票区4)2023年五月天演唱会鸟巢票价是多少? 1、看台票:355元、555元、855元、855元套票区 2、场地票:1655元、1855元 3、双人票:1555元(855元套票区*2) 2023年五月天演唱会鸟巢在哪里买票? 1、五月天2023好好好想见到你北京5)<strong>五月天</strong>北京<strong>演唱会门票价格</strong>:355,555,855,1655,1855 在线订票: https://www.dahepiao.com/yanchupiaowu1/ych/2017050226028.html 欢迎关注公众号:大河票务网ID:dahepw,获取<strong>五月天</strong>北京<strong>演唱会</strong>最新<strong>门票</strong>订票及演出信息。6)27日晚,<strong>五月天</strong>北京<strong>演唱会</strong>第二场结束,有黄牛在群里放出了6张6月1日的内场<strong>票</strong>,仅隔12分钟就卖出3张;余<strong>票价格</strong>表更新后,立刻有人在群内询价。7)<strong>五月天</strong>北京<strong>演唱会</strong>时间:<strong>2023</strong>-05-26至<strong>2023<

创建GLM模型和对话推理

# 创建模型
import paddle
from paddlenlp.transformers import (
    ChatGLMConfig,
    ChatGLMForConditionalGeneration,
    ChatGLMTokenizer,
)

# 读取原始的chatglm-6b模型
model_name_or_path = 'THUDM/chatglm-6b' # 使用该路径会自动下载和加载模型
tokenizer = ChatGLMTokenizer.from_pretrained(model_name_or_path)

config = ChatGLMConfig.from_pretrained(model_name_or_path)
paddle.set_default_dtype(config.paddle_dtype)

model = ChatGLMForConditionalGeneration.from_pretrained(
    model_name_or_path,
    tensor_parallel_degree=paddle.distributed.get_world_size(),
    tensor_parallel_rank=0,
    load_state_as_np=True,
    dtype=config.paddle_dtype,
)

model.eval()
# 函数定义,用于一问一答
# 输入参数:初始prompt, 最长输入长度,最长输出长度
def glm_single_QA(model,tokenizer,next_inputs,input_length,output_length):
    # 输入格式转换
    inputs = tokenizer(
        next_inputs,
        return_tensors="np",
        padding=True,
        max_length=input_length,
        truncation=True,
        truncation_side="left",
    )
    input_map = {}
    for key in inputs:
        input_map[key] = paddle.to_tensor(inputs[key])

    # 获取结果
    infer_result = model.generate(
        **input_map,
        decode_strategy="sampling",
        top_k=1,
        # top_p =5,
        max_length=output_length,
        use_cache=True,
        use_fast=True,
        use_fp16_decoding=True,
        repetition_penalty=1,
        temperature = 0.95,
        length_penalty=1,
    )[0]

    # 结果转换
    output = ''
    result = []
    for x in infer_result.tolist():
        res = tokenizer.decode(x, skip_special_tokens=True)
        res = res.strip("\n")
        result.append(res)
        output = output + res
    return output
# 调用函数示例

# 要求
Q = "五月天2023年演唱会门票多少钱"
# 获取结果
glm_result=glm_single_QA(model,tokenizer,Q,2048,2048)
print(glm_result)
很抱歉,作为一个人工智能语言模型,我没有实时更新的价格信息或演唱会门票销售信息。建议您前往五月天官方网站或第三方票务平台查看最新的票价和购票信息。祝您购票愉快!

结合搜索结果进行预测

# 要求
Q = "五月天2023年演唱会门票多少钱"
# Prompt
Q_motif = f"请回答{Q},根据以下信息回答{results}"
# 获取结果
glm_result=glm_single_QA(model,tokenizer,Q_motif,2048,2048)
print(glm_result)
2023 年五月天演唱会门票价格如下:

1 看台票:355 元、555 元、855 元、855 元套票区
2 场地票:1655 元、1855 元
3 双人票:1555 元(855 元套票区*2)

需要注意的是,由于演唱会门票价格波动较大,具体价格可能会根据时间和供求关系有所变化,建议在购买前仔细查询官方售票渠道或咨询五月天演唱会官方售票点以确保购买到最优惠的价格。

此文章为搬运
原项目链接

Logo

学大模型,用大模型上飞桨星河社区!每天8点V100G算力免费领!免费领取ERNIE 4.0 100w Token >>>

更多推荐