This commit is contained in:
“yangqiao”
2024-12-31 11:03:01 +08:00
4 changed files with 162 additions and 62 deletions

View File

@@ -1,61 +1,116 @@
import requests
import pandas
import glob
import os
def retrieval_from_knowledge_base(
query: str,
topk: int
) -> str:
"""
Retrieval for knowledge from the knowledge base based on the specified query and returns the topk results.
Parameters:
query (str): The query for knowledge retrieval.
topk (int): The number of top results to return, default is 3.
Returns:
str: The result of the knowledge retrieval in JSON format.
"""
url = 'http://127.0.0.1:7080/v1/chat-messages'
headers = {
'Authorization': f'Bearer app-uJgo3TQKcS1O9PMCDHko71Fp',
'Content-Type': 'application/json'
}
data = {
"inputs": {"topK": topk},
"query": query,
"response_mode": "blocking",
"user": "tangger",
"files": []
}
def get_max_uv_wavelength_from_txt(latest_file_path: str):
import pandas as pd
import os
# 文件检查
if not os.path.isfile(latest_file_path):
res = "ERROR: 指定的文件不存在"
return res
response = requests.post(url, headers=headers, json=data)
# 打开并读取最新文件
with open(latest_file_path, 'r') as file:
lines = file.readlines()
if response.status_code == 524:
print("Server is not responding. Please try again later. Maybe GPU was down in the container.")
return None
# 找到数据开始的行号
data_start_index = -1
for i, line in enumerate(lines):
if "Wavelength Scan Data Record" in line:
data_start_index = i + 2 # 数据从该行的下两行开始
break
try:
result = response.json()
except ValueError:
return [{"error": "Response is not in JSON format"}]
if data_start_index == -1:
res = "ERROR: 无法找到数据记录部分"
return res
useful_results = []
try:
answer = eval(result.get("answer", "[]"))
for item in answer:
metadata = item.get("metadata", {})
useful_info = {
"id": metadata.get("document_id"),
"title": item.get("title"),
"content": item.get("content"),
"metadata": None,
"embedding": None,
"score": metadata.get("score")
}
useful_results.append(useful_info)
except Exception as e:
return [{"error": f"Error processing result: {e}", "status": "TERMINATE"}]
if useful_results == []:
useful_results = "NULL"
return str(useful_results)
# 解析数据并构建表格
data = []
for line in lines[data_start_index:]:
parts = line.split()
if len(parts) == 7: # 保证每行有7列数据
no, wavelength, abs_value, trans, energy, energy_100, energy_0 = parts
try:
data.append({
'No': int(no),
'Wavelength(nm)': float(wavelength),
'Abs': float(abs_value),
'Trans(%T)': float(trans),
'Energy': float(energy),
'Energy(100%T)': float(energy_100),
'Energy(0%T)': float(energy_0)
})
except ValueError:
print(f"跳过无法解析的行: {line}")
if not data:
res = "ERROR: 未解析到任何有效数据"
return res
# 构建DataFrame
df = pd.DataFrame(data)
# 找到Abs值最大的行
max_abs_row = df.loc[df['Abs'].idxmax()]
# 获取最大Abs值对应的波长
max_abs_wavelength = max_abs_row['Wavelength(nm)']
res = f"本次实验的UV波长为: {max_abs_wavelength} nm"
print(res)
return res
def get_max_pl_peak_from_txt(latest_file_path: str):
import pandas as pd
import os
# 文件检查
if not os.path.isfile(latest_file_path):
res = "ERROR: 指定的文件不存在"
return res
# 打开并读取最新文件
with open(latest_file_path, 'r') as file:
lines = file.readlines()
# 找到 'Data Points' 开始的行号
data_start_index = -1
for i, line in enumerate(lines):
if "Data Points" in line:
data_start_index = i + 1 # 数据从该行的下一行开始
break
if data_start_index == -1:
res = "ERROR: 无法找到数据记录部分"
return res
# 解析nm和Data数据
data = []
for line in lines[data_start_index:]:
parts = line.split()
if len(parts) == 2: # 每行应该有2列数据nm 和 Data
try:
nm = float(parts[0])
data_value = float(parts[1])
data.append({'nm': nm, 'Data': data_value})
except ValueError:
print(f"跳过无法解析的行: {line}")
if not data:
res = "ERROR: 未解析到任何有效数据"
return res
# 构建DataFrame
df = pd.DataFrame(data)
# 找到Data值最大的行
max_data_row = df.loc[df['Data'].idxmax()]
# 获取最大Data值对应的nm
max_data_nm = max_data_row['nm']
res = f"本次实验的PL峰位为: {max_data_nm} nm"
print(res)
return res

View File

@@ -14,7 +14,7 @@ MODEL = "gpt-4o"
# config_list = [{"model": MODEL, "api_key": OPENAI_API_KEY, "base_url": OPENAI_BASE_URL, "temperature": 0}]
config_list = [{"model": MODEL, "api_key": OPENAI_API_KEY, "base_url": OPENAI_BASE_URL}]
SILENT = False # 关闭嵌套智能体的输出
SILENT = True # 关闭嵌套智能体的输出
STREAM = True # stream on console
CACHE = None # None 就是关闭 41是默认值开启

View File

@@ -68,18 +68,57 @@ class ChatConsumer(AsyncWebsocketConsumer):
print(" - Sending message to server.", flush=True)
websocket.send(text_data)
# with open("websocket_messages.txt", "w", encoding="utf-8") as file:
import re
current_agent = "User"
while True:
message = websocket.recv()
message = message.decode("utf-8") if isinstance(message, bytes) else message
print(message, end="", flush=True)
import re
cleaned_string = re.sub(r'\x1b\[[0-?]*[ -/]*[@-~]', '', message)
# file.write(cleaned_string)
# 通过 WebSocket 消费者发送消息
asyncio.run(self.send(text_data=cleaned_string))
cleaned_string = re.sub(r'\x1b\[[0-?]*[ -/]*[@-~]', '', message)
# match = re.findall(r"(\w+)\s*\(to\s+(\w+)\)", cleaned_string)
# print(match)
# if len(match)==1:
# current_agent = match[0][0] if current_agent != match[0][0] else current_agent
# print(f"A: {match[0][0]}, B: {match[0][1]}")
if "Next speaker" in cleaned_string:
match = re.search(r"Next\s+speaker:\s+(\w+)", cleaned_string)
current_agent = match.group(1)
else:
if cleaned_string == "\n--------------------------------------------------------------------------------\n":
continue
if cleaned_string == "\n********************************************************************************\n":
continue
if cleaned_string == "Starting a new chat....\n":
continue
if cleaned_string == "\n>>>>>>>> USING AUTO REPLY...\n":
continue
match = re.findall(r"(\w+)\s*\(to\s+(\w+)\)", cleaned_string)
if len(match)==1:
continue
if current_agent in ['Outer_Retrieval_Admin', 'Outer_Generate_Admin', 'Outer_Converter_Admin']:
current_agent = current_agent.replace('Outer_', '')
if current_agent in ['vector_code_executor']:
continue
if current_agent == 'User':
group_name = 'Planner'
if current_agent in ['vector_searcher','vector_code_executor', 'graphrag_searcher', 'graphrag_code_executor', 'web_searcher', 'web_summary', 'Outer_Retrieval_Admin']:
group_name = 'Retrieval'
if current_agent in ['structure_scientist','property_scientist', 'application_scientist', 'synthesis_scientist', 'scheme_critic', 'Outer_Generate_Admin']:
group_name = 'Generator'
if current_agent in ['scheme_converter','converter_critic', 'mergrid_ploter', 'scheme_code_writer', 'scheme_code_critic', 'Outer_Converter_Admin']:
group_name = 'Converter'
if current_agent in ['experiment_executor','expriment_code_writer', 'data_collector', 'collector_code_writer', 'Outer_Executor_Admin']:
group_name = 'Executor'
if current_agent in ['analysis_executor','analysis_pl_uv', 'analysis_picturer', 'Experiment_Optimizer', 'optimizer_critic', 'Outer_Analysis_Admin']:
group_name = 'Optimizer'
content = {"group_name": group_name, "agent_name": current_agent.replace("_", " ").title(), "content": cleaned_string}
# 通过 WebSocket 消费者发送消息
asyncio.run(self.send(text_data=json.dumps(content)))
# if "TERMINATE" in message:
# print(" - Received TERMINATE message. Exiting.", flush=True)

6
frontend/.env Normal file
View File

@@ -0,0 +1,6 @@
# 打包路径
VITE_BASE_URL = /
VITE_IS_REQUEST_PROXY = true
VITE_API_URL = http://47.121.220.134
VITE_API_URL_PREFIX = /matagent
VITE_WB_BASE_URL = ws://47.121.220.134:8000/matagent/chat