功能与问题
- 上一篇文章中,我们成果的调用了GPT的网络检索接口,这次我们将这个功能集成到chain中
流程
- 解析
- 封装
# 做成transformerChain (封装)
import os
from langchain_openai import OpenAI
os.environ["OPENAI_API_BASE"] = ''
os.environ["OPENAI_API_KEY"] = 'sk-'
from aiohttp.client import request
from tempfile import template
from langchain.chains import LLMChain
from langchain.chains import LLMRequestsChain
from langchain.prompts import PromptTemplate
# 定义搜索模板
template = '''在>>> 和 <<<直接是来自google的原始搜索结果。
请把对于问题'{query}'的答案从里面提取出来,如果里面没有相关信息的化就说“找不到”
请使用以下格式:
Extracted:<anser or "找不到">
>>> {requests_result} <<<
Extracted:
'''
PROMPT = PromptTemplate(
input_variables=["query","requests_result"],
template=template,
)
request_chain = LLMRequestsChain(llm_chain=LLMChain(llm = OpenAI(temperature = 0),prompt=PROMPT))
question="今天上海市天气"
inputs={
"query":question,
"url":"https://www.google.com/search?q="+question.replace(" ","+")
#"url":"https://www.baidu.com/s?wd="+question.replace(" ","+")
#"url":"https://cn.bing.com/search?q="+question.replace(" ","+")
# https://cn.bing.com/search?q=今天北京市天气
}
import re
def parse_weather_info(weather_info: str) -> dict:
print(weather_info)
# 使用正则表达式提取数据
temperature_match = re.search(r'(\d+)°F', weather_info)
precipitation_match = re.search(r'Precipitation: (\d+)%', weather_info)
humidity_match = re.search(r'Humidity: (\d+)%', weather_info)
wind_match = re.search(r'Wind: (\d+) mph', weather_info)
# 存储提取的数据的字典
weather_data = {}
# 将提取的数据存储在字典中
if temperature_match:
weather_data['Temperature'] = temperature_match.group(1)
if precipitation_match:
weather_data['Precipitation'] = precipitation_match.group(1)
if humidity_match:
weather_data['Humidity'] = humidity_match.group(1)
if wind_match:
weather_data['Wind'] = wind_match.group(1)
print("!!!!!!!!!!!!!")
print(weather_data)
return weather_data
def transform_func(inputs: dict) -> dict:
text = inputs["output"]
return {"weather_info":parse_weather_info(text)}
# {'Temperature': '478', 'Precipitation': '0', 'Humidity': '45', 'Wind': '6'}
from langchain.chains import TransformChain,SequentialChain
transform_chain = TransformChain(input_variables = ["output"],
output_variables=["weather_info"],
transform=transform_func)
final_chain = SequentialChain(chains=[request_chain,transform_chain],
input_variables=["query","url"],output_variables=["weather_info"])
final_rst = final_chain.run(inputs)
print(final_rst)
# {'Temperature': '478', 'Precipitation': '0', 'Humidity': '45', 'Wind': '6'}