mirror of
https://github.com/BoardWare-Genius/jarvis-models.git
synced 2025-12-13 16:53:24 +00:00
feat: add blackbox websearch and update chat.py
This commit is contained in:
@ -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),
|
||||
|
||||
73
src/blackbox/websearch.py
Normal file
73
src/blackbox/websearch.py
Normal file
@ -0,0 +1,73 @@
|
||||
import datetime
|
||||
from typing import Any, Coroutine
|
||||
|
||||
from fastapi import Request, Response, status
|
||||
from fastapi.responses import JSONResponse
|
||||
from openai import OpenAI
|
||||
from .blackbox import Blackbox
|
||||
|
||||
import logging
|
||||
from ..log.logging_time import logging_time
|
||||
import requests
|
||||
import json
|
||||
|
||||
logger = logging.getLogger
|
||||
DEFAULT_COLLECTION_ID = "123"
|
||||
|
||||
from injector import singleton
|
||||
@singleton
|
||||
class WebSearch(Blackbox):
|
||||
|
||||
def __call__(self, *args, **kwargs):
|
||||
return self.processing(*args, **kwargs)
|
||||
|
||||
def valid(self, *args, **kwargs) -> bool:
|
||||
data = args[0]
|
||||
return isinstance(data, list)
|
||||
|
||||
# @logging_time(logger=logger)
|
||||
def processing(self, question: str, settings: dict) -> str:
|
||||
|
||||
if settings is None:
|
||||
settings = {}
|
||||
|
||||
# from googlesearch import search
|
||||
|
||||
# question = "要搜索的关键词"
|
||||
# for url in search(question, num_results=10):
|
||||
# print(url)
|
||||
|
||||
url = "https://google.serper.dev/search"
|
||||
|
||||
payload = json.dumps({
|
||||
"q": question,
|
||||
"location": "China", # 限制所在位置为中国
|
||||
"gl": "cn", # 限制国家为中国
|
||||
"hl": "zh-cn", # 限制搜索结果为中文
|
||||
"tbs": "qdr:y" # 限制搜索结果为一年内的
|
||||
})
|
||||
|
||||
headers = {
|
||||
'X-API-KEY': '00c0f5144e44721bd0cfed219e2b3256bb3dd5fc',
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
|
||||
response = requests.request("POST", url, headers=headers, data=payload)
|
||||
|
||||
print("web search results:", response.json())
|
||||
|
||||
return response.json()
|
||||
|
||||
|
||||
async def fast_api_handler(self, request: Request) -> Response:
|
||||
try:
|
||||
data = await request.json()
|
||||
except:
|
||||
return JSONResponse(content={"error": "json parse error"}, status_code=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
user_question = data.get("question")
|
||||
setting = data.get("settings")
|
||||
|
||||
return JSONResponse(
|
||||
content={"response": self.processing(user_question, setting)},
|
||||
status_code=status.HTTP_200_OK)
|
||||
Reference in New Issue
Block a user