feat: add blackbox websearch and update chat.py

This commit is contained in:
tom
2025-03-14 14:20:28 +08:00
parent 2c450a5ffe
commit 6c0ee5b59a
2 changed files with 112 additions and 3 deletions

View File

@ -16,6 +16,7 @@ import re
from injector import singleton,inject
from datetime import datetime
from .websearch import WebSearch
# 定义保存文件的路径
file_path = "chat_inputs_log.json"
@ -23,8 +24,9 @@ file_path = "chat_inputs_log.json"
class Chat(Blackbox):
@inject
def __init__(self, chroma_query: ChromaQuery):
def __init__(self, chroma_query: ChromaQuery, websearch: WebSearch):
self.chroma_query = chroma_query
self.websearch = websearch
def __call__(self, *args, **kwargs):
return self.processing(*args, **kwargs)
@ -60,6 +62,7 @@ class Chat(Blackbox):
system_prompt = settings.get('system_prompt')
user_prompt_template = settings.get('user_prompt_template')
user_stream = settings.get('stream')
user_websearch = settings.get('websearch')
llm_model = "vllm"
@ -134,7 +137,9 @@ class Chat(Blackbox):
if user_stream in [None, ""]:
user_stream = False
if user_websearch in [None, ""]:
user_websearch = False
# 文心格式和openai的不一样需要单独处理
if re.search(r"ernie", user_model_name):
@ -201,6 +206,32 @@ class Chat(Blackbox):
{"role": "system", "content": system_prompt}
]
if user_websearch:
search_answer_zh_template = \
'''# 以下内容是基于用户发送的消息的搜索结果:
{search_results}
在我给你的搜索结果中,每个结果都是["title"]...["position": X]格式的X代表每篇文章的数字索引。请在适当的情况下在句子末尾引用上下文。请按照引用编号[citation:X]的格式在答案中对应部分引用上下文。如果一句话源自多个上下文,请列出所有相关的引用编号,例如[citation:3][citation:5],切记不要将引用集中在最后返回引用编号,而是在答案对应部分列出。
在回答时,请注意以下几点:
- 今天是{cur_date}
- 并非搜索结果的所有内容都与用户的问题密切相关,你需要结合问题,对搜索结果进行甄别、筛选。
- 对于列举类的问题如列举所有航班信息尽量将答案控制在10个要点以内并告诉用户可以查看搜索来源、获得完整信息。优先提供信息完整、最相关的列举项如非必要不要主动告诉用户搜索结果未提供的内容。
- 对于创作类的问题(如写论文),请务必在正文的段落中引用对应的参考编号,例如[citation:3][citation:5],不能只在文章末尾引用。你需要解读并概括用户的题目要求,选择合适的格式,充分利用搜索结果并抽取重要信息,生成符合用户要求、极具思想深度、富有创造力与专业性的答案。你的创作篇幅需要尽可能延长,对于每一个要点的论述要推测用户的意图,给出尽可能多角度的回答要点,且务必信息量大、论述详尽。
- 如果回答很长请尽量结构化、分段落总结。如果需要分点作答尽量控制在5个点以内并合并相关的内容。
- 对于客观类的问答,如果问题的答案非常简短,可以适当补充一到两句相关信息,以丰富内容。
- 你需要根据用户要求和回答内容选择合适、美观的回答格式,确保可读性强。
- 你的回答应该综合多个相关网页来回答,不能重复引用一个网页。
- 除非用户要求,否则你回答的语言需要和用户提问的语言保持一致。
# 用户消息为:
{question}'''
websearch_response = self.websearch(prompt, settings)
print("2.Websearch_response: \n", websearch_response)
today = datetime.today().strftime("%Y-%m-%d")
user_question = search_answer_zh_template.format(question=user_question, cur_date=today, search_results=websearch_response["organic"])
if llm_model != "vllm":
chat_inputs={
"model": user_model_name,
@ -222,7 +253,12 @@ class Chat(Blackbox):
else:
chat_inputs={
"model": user_model_name,
"prompt": user_question,
"messages": prompt_template + user_context + [
{
"role": "user",
"content": user_question
}
],
"temperature": float(user_temperature),
"top_p": float(user_top_p),
"n": float(user_n),