2023-10-25 08:30:23 +08:00
|
|
|
|
from langchain.utilities.bing_search import BingSearchAPIWrapper
|
|
|
|
|
|
from langchain.utilities.duckduckgo_search import DuckDuckGoSearchAPIWrapper
|
2023-10-18 23:02:20 +08:00
|
|
|
|
from configs import (BING_SEARCH_URL, BING_SUBSCRIPTION_KEY, METAPHOR_API_KEY,
|
2023-11-09 22:15:52 +08:00
|
|
|
|
LLM_MODELS, SEARCH_ENGINE_TOP_K, TEMPERATURE,
|
2023-10-18 23:02:20 +08:00
|
|
|
|
TEXT_SPLITTER_NAME, OVERLAP_SIZE)
|
2023-08-01 16:39:17 +08:00
|
|
|
|
from fastapi import Body
|
|
|
|
|
|
from fastapi.responses import StreamingResponse
|
2023-09-08 12:25:02 +08:00
|
|
|
|
from fastapi.concurrency import run_in_threadpool
|
2023-09-17 16:19:50 +08:00
|
|
|
|
from server.utils import wrap_done, get_ChatOpenAI
|
2023-09-17 13:27:11 +08:00
|
|
|
|
from server.utils import BaseResponse, get_prompt_template
|
2023-09-27 21:53:47 +08:00
|
|
|
|
from langchain.chains import LLMChain
|
2023-08-01 16:39:17 +08:00
|
|
|
|
from langchain.callbacks import AsyncIteratorCallbackHandler
|
|
|
|
|
|
from typing import AsyncIterable
|
|
|
|
|
|
import asyncio
|
2023-08-08 23:54:51 +08:00
|
|
|
|
from langchain.prompts.chat import ChatPromptTemplate
|
2023-10-25 08:30:23 +08:00
|
|
|
|
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
2023-10-18 23:02:20 +08:00
|
|
|
|
from typing import List, Optional, Dict
|
2023-08-08 23:54:51 +08:00
|
|
|
|
from server.chat.utils import History
|
2023-08-01 16:39:17 +08:00
|
|
|
|
from langchain.docstore.document import Document
|
2023-08-04 12:12:13 +08:00
|
|
|
|
import json
|
2023-10-25 08:30:23 +08:00
|
|
|
|
from strsimpy.normalized_levenshtein import NormalizedLevenshtein
|
|
|
|
|
|
from markdownify import markdownify
|
2023-08-01 16:39:17 +08:00
|
|
|
|
|
2023-08-03 18:22:36 +08:00
|
|
|
|
|
2023-10-25 08:30:23 +08:00
|
|
|
|
def bing_search(text, result_len=SEARCH_ENGINE_TOP_K, **kwargs):
|
2023-08-01 16:39:17 +08:00
|
|
|
|
if not (BING_SEARCH_URL and BING_SUBSCRIPTION_KEY):
|
|
|
|
|
|
return [{"snippet": "please set BING_SUBSCRIPTION_KEY and BING_SEARCH_URL in os ENV",
|
|
|
|
|
|
"title": "env info is not found",
|
|
|
|
|
|
"link": "https://python.langchain.com/en/latest/modules/agents/tools/examples/bing_search.html"}]
|
|
|
|
|
|
search = BingSearchAPIWrapper(bing_subscription_key=BING_SUBSCRIPTION_KEY,
|
|
|
|
|
|
bing_search_url=BING_SEARCH_URL)
|
|
|
|
|
|
return search.results(text, result_len)
|
|
|
|
|
|
|
|
|
|
|
|
|
2023-10-25 08:30:23 +08:00
|
|
|
|
def duckduckgo_search(text, result_len=SEARCH_ENGINE_TOP_K, **kwargs):
|
2023-08-03 18:22:36 +08:00
|
|
|
|
search = DuckDuckGoSearchAPIWrapper()
|
|
|
|
|
|
return search.results(text, result_len)
|
|
|
|
|
|
|
|
|
|
|
|
|
2023-10-18 23:02:20 +08:00
|
|
|
|
def metaphor_search(
|
|
|
|
|
|
text: str,
|
|
|
|
|
|
result_len: int = SEARCH_ENGINE_TOP_K,
|
2023-10-25 08:30:23 +08:00
|
|
|
|
split_result: bool = False,
|
2023-10-18 23:02:20 +08:00
|
|
|
|
chunk_size: int = 500,
|
|
|
|
|
|
chunk_overlap: int = OVERLAP_SIZE,
|
|
|
|
|
|
) -> List[Dict]:
|
|
|
|
|
|
from metaphor_python import Metaphor
|
|
|
|
|
|
|
|
|
|
|
|
if not METAPHOR_API_KEY:
|
|
|
|
|
|
return []
|
2023-10-25 08:30:23 +08:00
|
|
|
|
|
2023-10-18 23:02:20 +08:00
|
|
|
|
client = Metaphor(METAPHOR_API_KEY)
|
|
|
|
|
|
search = client.search(text, num_results=result_len, use_autoprompt=True)
|
|
|
|
|
|
contents = search.get_contents().contents
|
2023-10-25 08:30:23 +08:00
|
|
|
|
for x in contents:
|
|
|
|
|
|
x.extract = markdownify(x.extract)
|
2023-10-18 23:02:20 +08:00
|
|
|
|
|
|
|
|
|
|
# metaphor 返回的内容都是长文本,需要分词再检索
|
2023-10-25 08:30:23 +08:00
|
|
|
|
if split_result:
|
|
|
|
|
|
docs = [Document(page_content=x.extract,
|
|
|
|
|
|
metadata={"link": x.url, "title": x.title})
|
|
|
|
|
|
for x in contents]
|
|
|
|
|
|
text_splitter = RecursiveCharacterTextSplitter(["\n\n", "\n", ".", " "],
|
|
|
|
|
|
chunk_size=chunk_size,
|
|
|
|
|
|
chunk_overlap=chunk_overlap)
|
|
|
|
|
|
splitted_docs = text_splitter.split_documents(docs)
|
|
|
|
|
|
|
|
|
|
|
|
# 将切分好的文档放入临时向量库,重新筛选出TOP_K个文档
|
|
|
|
|
|
if len(splitted_docs) > result_len:
|
|
|
|
|
|
normal = NormalizedLevenshtein()
|
|
|
|
|
|
for x in splitted_docs:
|
|
|
|
|
|
x.metadata["score"] = normal.similarity(text, x.page_content)
|
|
|
|
|
|
splitted_docs.sort(key=lambda x: x.metadata["score"], reverse=True)
|
|
|
|
|
|
splitted_docs = splitted_docs[:result_len]
|
|
|
|
|
|
|
|
|
|
|
|
docs = [{"snippet": x.page_content,
|
|
|
|
|
|
"link": x.metadata["link"],
|
|
|
|
|
|
"title": x.metadata["title"]}
|
|
|
|
|
|
for x in splitted_docs]
|
|
|
|
|
|
else:
|
|
|
|
|
|
docs = [{"snippet": x.extract,
|
|
|
|
|
|
"link": x.url,
|
|
|
|
|
|
"title": x.title}
|
|
|
|
|
|
for x in contents]
|
|
|
|
|
|
|
2023-10-18 23:02:20 +08:00
|
|
|
|
return docs
|
|
|
|
|
|
|
|
|
|
|
|
|
2023-08-03 18:22:36 +08:00
|
|
|
|
SEARCH_ENGINES = {"bing": bing_search,
|
|
|
|
|
|
"duckduckgo": duckduckgo_search,
|
2023-10-18 23:02:20 +08:00
|
|
|
|
"metaphor": metaphor_search,
|
2023-08-03 18:22:36 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
2023-08-01 16:39:17 +08:00
|
|
|
|
def search_result2docs(search_results):
|
|
|
|
|
|
docs = []
|
|
|
|
|
|
for result in search_results:
|
|
|
|
|
|
doc = Document(page_content=result["snippet"] if "snippet" in result.keys() else "",
|
|
|
|
|
|
metadata={"source": result["link"] if "link" in result.keys() else "",
|
|
|
|
|
|
"filename": result["title"] if "title" in result.keys() else ""})
|
|
|
|
|
|
docs.append(doc)
|
|
|
|
|
|
return docs
|
|
|
|
|
|
|
|
|
|
|
|
|
2023-09-08 12:25:02 +08:00
|
|
|
|
async def lookup_search_engine(
|
2023-08-03 18:22:36 +08:00
|
|
|
|
query: str,
|
|
|
|
|
|
search_engine_name: str,
|
|
|
|
|
|
top_k: int = SEARCH_ENGINE_TOP_K,
|
2023-10-25 08:30:23 +08:00
|
|
|
|
split_result: bool = False,
|
2023-08-03 18:22:36 +08:00
|
|
|
|
):
|
2023-09-08 12:25:02 +08:00
|
|
|
|
search_engine = SEARCH_ENGINES[search_engine_name]
|
2023-10-25 08:30:23 +08:00
|
|
|
|
results = await run_in_threadpool(search_engine, query, result_len=top_k, split_result=split_result)
|
2023-08-03 18:22:36 +08:00
|
|
|
|
docs = search_result2docs(results)
|
|
|
|
|
|
return docs
|
|
|
|
|
|
|
|
|
|
|
|
|
2023-09-08 12:25:02 +08:00
|
|
|
|
async def search_engine_chat(query: str = Body(..., description="用户输入", examples=["你好"]),
|
|
|
|
|
|
search_engine_name: str = Body(..., description="搜索引擎名称", examples=["duckduckgo"]),
|
|
|
|
|
|
top_k: int = Body(SEARCH_ENGINE_TOP_K, description="检索结果数量"),
|
|
|
|
|
|
history: List[History] = Body([],
|
|
|
|
|
|
description="历史对话",
|
|
|
|
|
|
examples=[[
|
|
|
|
|
|
{"role": "user",
|
|
|
|
|
|
"content": "我们来玩成语接龙,我先来,生龙活虎"},
|
|
|
|
|
|
{"role": "assistant",
|
|
|
|
|
|
"content": "虎头虎脑"}]]
|
|
|
|
|
|
),
|
|
|
|
|
|
stream: bool = Body(False, description="流式输出"),
|
2023-11-09 22:15:52 +08:00
|
|
|
|
model_name: str = Body(LLM_MODELS[0], description="LLM 模型名称。"),
|
2023-09-27 21:17:50 +08:00
|
|
|
|
temperature: float = Body(TEMPERATURE, description="LLM 采样温度", ge=0.0, le=1.0),
|
2023-10-26 22:44:48 +08:00
|
|
|
|
max_tokens: Optional[int] = Body(None, description="限制LLM生成Token数量,默认None代表模型最大值"),
|
2023-10-18 15:19:02 +08:00
|
|
|
|
prompt_name: str = Body("default",description="使用的prompt模板名称(在configs/prompt_config.py中配置)"),
|
2023-10-25 08:30:23 +08:00
|
|
|
|
split_result: bool = Body(False, description="是否对搜索结果进行拆分(主要用于metaphor搜索引擎)")
|
2023-08-03 18:22:36 +08:00
|
|
|
|
):
|
|
|
|
|
|
if search_engine_name not in SEARCH_ENGINES.keys():
|
|
|
|
|
|
return BaseResponse(code=404, msg=f"未支持搜索引擎 {search_engine_name}")
|
|
|
|
|
|
|
2023-08-25 10:58:40 +08:00
|
|
|
|
if search_engine_name == "bing" and not BING_SUBSCRIPTION_KEY:
|
|
|
|
|
|
return BaseResponse(code=404, msg=f"要使用Bing搜索引擎,需要设置 `BING_SUBSCRIPTION_KEY`")
|
|
|
|
|
|
|
2023-08-23 08:35:26 +08:00
|
|
|
|
history = [History.from_data(h) for h in history]
|
|
|
|
|
|
|
2023-08-03 18:22:36 +08:00
|
|
|
|
async def search_engine_chat_iterator(query: str,
|
|
|
|
|
|
search_engine_name: str,
|
|
|
|
|
|
top_k: int,
|
2023-08-08 23:54:51 +08:00
|
|
|
|
history: Optional[List[History]],
|
2023-11-09 22:15:52 +08:00
|
|
|
|
model_name: str = LLM_MODELS[0],
|
2023-09-17 13:27:11 +08:00
|
|
|
|
prompt_name: str = prompt_name,
|
2023-08-03 18:22:36 +08:00
|
|
|
|
) -> AsyncIterable[str]:
|
2023-08-01 16:39:17 +08:00
|
|
|
|
callback = AsyncIteratorCallbackHandler()
|
2023-11-26 16:47:58 +08:00
|
|
|
|
if isinstance(max_tokens, int) and max_tokens <= 0:
|
|
|
|
|
|
max_tokens = None
|
|
|
|
|
|
|
2023-09-15 17:52:22 +08:00
|
|
|
|
model = get_ChatOpenAI(
|
2023-09-01 23:58:09 +08:00
|
|
|
|
model_name=model_name,
|
2023-09-13 10:00:54 +08:00
|
|
|
|
temperature=temperature,
|
2023-10-12 16:18:56 +08:00
|
|
|
|
max_tokens=max_tokens,
|
2023-09-15 17:52:22 +08:00
|
|
|
|
callbacks=[callback],
|
2023-08-01 16:39:17 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
2023-10-25 08:30:23 +08:00
|
|
|
|
docs = await lookup_search_engine(query, search_engine_name, top_k, split_result=split_result)
|
2023-08-01 16:39:17 +08:00
|
|
|
|
context = "\n".join([doc.page_content for doc in docs])
|
|
|
|
|
|
|
2023-10-18 15:19:02 +08:00
|
|
|
|
prompt_template = get_prompt_template("search_engine_chat", prompt_name)
|
2023-09-17 13:27:11 +08:00
|
|
|
|
input_msg = History(role="user", content=prompt_template).to_msg_template(False)
|
2023-08-08 23:54:51 +08:00
|
|
|
|
chat_prompt = ChatPromptTemplate.from_messages(
|
2023-08-23 08:35:26 +08:00
|
|
|
|
[i.to_msg_template() for i in history] + [input_msg])
|
2023-08-08 23:54:51 +08:00
|
|
|
|
|
|
|
|
|
|
chain = LLMChain(prompt=chat_prompt, llm=model)
|
2023-08-01 16:39:17 +08:00
|
|
|
|
|
|
|
|
|
|
# Begin a task that runs in the background.
|
|
|
|
|
|
task = asyncio.create_task(wrap_done(
|
|
|
|
|
|
chain.acall({"context": context, "question": query}),
|
|
|
|
|
|
callback.done),
|
|
|
|
|
|
)
|
|
|
|
|
|
|
2023-08-03 18:22:36 +08:00
|
|
|
|
source_documents = [
|
|
|
|
|
|
f"""出处 [{inum + 1}] [{doc.metadata["source"]}]({doc.metadata["source"]}) \n\n{doc.page_content}\n\n"""
|
|
|
|
|
|
for inum, doc in enumerate(docs)
|
|
|
|
|
|
]
|
|
|
|
|
|
|
2023-10-27 11:52:44 +08:00
|
|
|
|
if len(source_documents) == 0: # 没有找到相关资料(不太可能)
|
|
|
|
|
|
source_documents.append(f"""<span style='color:red'>未找到相关文档,该回答为大模型自身能力解答!</span>""")
|
|
|
|
|
|
|
2023-08-09 23:35:36 +08:00
|
|
|
|
if stream:
|
|
|
|
|
|
async for token in callback.aiter():
|
|
|
|
|
|
# Use server-sent-events to stream the response
|
2023-09-12 08:31:17 +08:00
|
|
|
|
yield json.dumps({"answer": token}, ensure_ascii=False)
|
|
|
|
|
|
yield json.dumps({"docs": source_documents}, ensure_ascii=False)
|
2023-08-09 23:35:36 +08:00
|
|
|
|
else:
|
|
|
|
|
|
answer = ""
|
|
|
|
|
|
async for token in callback.aiter():
|
|
|
|
|
|
answer += token
|
2023-08-24 17:25:54 +08:00
|
|
|
|
yield json.dumps({"answer": answer,
|
2023-08-09 22:57:36 +08:00
|
|
|
|
"docs": source_documents},
|
|
|
|
|
|
ensure_ascii=False)
|
2023-08-01 16:39:17 +08:00
|
|
|
|
await task
|
|
|
|
|
|
|
2023-09-17 13:27:11 +08:00
|
|
|
|
return StreamingResponse(search_engine_chat_iterator(query=query,
|
|
|
|
|
|
search_engine_name=search_engine_name,
|
|
|
|
|
|
top_k=top_k,
|
|
|
|
|
|
history=history,
|
|
|
|
|
|
model_name=model_name,
|
|
|
|
|
|
prompt_name=prompt_name),
|
2023-08-03 18:22:36 +08:00
|
|
|
|
media_type="text/event-stream")
|