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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from agent.planner import Planner
|
| 2 |
+
from agent.solver import Solver
|
| 3 |
+
from agent.reflector import Reflector
|
| 4 |
+
from agent.state import State, print_state
|
| 5 |
+
from agent.utils import colored
|
| 6 |
+
from search.search import es
|
| 7 |
+
from tools.tools import search, search_tool, es_info, search_tool_examples
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pandas as pd
|
| 10 |
+
import sys
|
| 11 |
+
from tqdm import tqdm
|
| 12 |
+
import warnings
|
| 13 |
+
warnings.filterwarnings("ignore")
|
| 14 |
+
|
| 15 |
+
# Planner agent
|
| 16 |
+
planner = Planner()
|
| 17 |
+
|
| 18 |
+
flag = False
|
| 19 |
+
current_results = []
|
| 20 |
+
|
| 21 |
+
# Define tools
|
| 22 |
+
n = int(sys.argv[2]) if len(sys.argv) > 2 else 10
|
| 23 |
+
def search_wrapper(n_candidate=n, *args, **kargs):
|
| 24 |
+
global flag
|
| 25 |
+
global current_results
|
| 26 |
+
kargs['size'] = n_candidate
|
| 27 |
+
current_results.append(search(es, *args, **kargs))
|
| 28 |
+
flag = True
|
| 29 |
+
return current_results
|
| 30 |
+
|
| 31 |
+
tools = [search_tool]
|
| 32 |
+
functions = {search_tool['function']['name']: search_wrapper}
|
| 33 |
+
additional_tools_info = f"""Đây là thông tin về các index và các trường của mỗi index:\n {es_info}
|
| 34 |
+
Khi bạn gọi hàm Search, hãy chỉ định type, các trường trong mỗi type chỉ có thể trong các trường ở bên trên,
|
| 35 |
+
các trường có mô tả với mảng enum thì các giá trị của trường chỉ nằm trong mảng enum, bạn không thể match các giá trị ở
|
| 36 |
+
ngoài mảng enum này. Sau đây là một số ví dụ về tham số khi gọi hàm Search:
|
| 37 |
+
{search_tool_examples}"""
|
| 38 |
+
|
| 39 |
+
# Solver agent
|
| 40 |
+
solver = Solver()
|
| 41 |
+
solver.bind_tools(tools)
|
| 42 |
+
solver.bind_functions(functions)
|
| 43 |
+
solver.additional_tools_info(additional_tools_info)
|
| 44 |
+
|
| 45 |
+
# Reflector agent
|
| 46 |
+
reflector = Reflector()
|
| 47 |
+
|
| 48 |
+
def get_items(user_query:str, max_iter = 3):
|
| 49 |
+
global flag
|
| 50 |
+
|
| 51 |
+
user = f'Hãy tìm cho tôi: {user_query}.\nCâu của tôi có thể bị sai chính tả, hoặc tôi viết sai tên sản phẩm, giúp tôi sửa lại trước khi truy vấn nếu cần.'
|
| 52 |
+
user_message = {'role': 'user', 'content': user}
|
| 53 |
+
|
| 54 |
+
state = State(
|
| 55 |
+
user_info="Người dùng ở chế độ khách",
|
| 56 |
+
long_memory="""Chưa có lịch sử tương tác""",
|
| 57 |
+
messages=[user_message,]
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
items = []
|
| 61 |
+
i = 0
|
| 62 |
+
while i < max_iter:
|
| 63 |
+
global current_results
|
| 64 |
+
current_results = []
|
| 65 |
+
i += 1
|
| 66 |
+
|
| 67 |
+
try:
|
| 68 |
+
planner.step(state)
|
| 69 |
+
solver.step(state)
|
| 70 |
+
# reflector.step(state)
|
| 71 |
+
except Exception as e:
|
| 72 |
+
print_state(state)
|
| 73 |
+
e.with_traceback()
|
| 74 |
+
|
| 75 |
+
if state.finish:
|
| 76 |
+
break
|
| 77 |
+
|
| 78 |
+
if flag:
|
| 79 |
+
items = current_results[0]
|
| 80 |
+
flag = False
|
| 81 |
+
else:
|
| 82 |
+
items = []
|
| 83 |
+
return items, i
|
| 84 |
+
|
| 85 |
+
df2 = pd.read_csv('./data/tv360/raw/eval_search.csv')
|
| 86 |
+
df2.info()
|
| 87 |
+
|
| 88 |
+
# Giả sử đã đọc các DataFrame từ file JSON
|
| 89 |
+
df3 = pd.read_json('./data/tv360/movie.json')
|
| 90 |
+
df4 = pd.read_json('./data/tv360/video.json')
|
| 91 |
+
df5 = pd.read_json('./data/tv360/channel.json')
|
| 92 |
+
|
| 93 |
+
def get_item_by_id(id: int):
|
| 94 |
+
# Kiểm tra trong df3
|
| 95 |
+
result = df3.loc[df3['series_id'] == id, 'series_name'].values
|
| 96 |
+
if result.size > 0:
|
| 97 |
+
return result[0]
|
| 98 |
+
|
| 99 |
+
# Kiểm tra trong df4
|
| 100 |
+
result = df4.loc[df4['series_id'] == id, 'series_name'].values
|
| 101 |
+
if result.size > 0:
|
| 102 |
+
return result[0]
|
| 103 |
+
|
| 104 |
+
# Kiểm tra trong df5
|
| 105 |
+
result = df5.loc[df5['channel_id'] == id, 'channel_name'].values
|
| 106 |
+
if result.size > 0:
|
| 107 |
+
return result[0]
|
| 108 |
+
|
| 109 |
+
# Nếu không tìm thấy trong bất kỳ DataFrame nào, trả về None
|
| 110 |
+
return None
|
| 111 |
+
|
| 112 |
+
n_users = int(sys.argv[1]) if len(sys.argv) > 1 else 1
|
| 113 |
+
|
| 114 |
+
n_users = min(n_users, len(df2))
|
| 115 |
+
n_users_real = 0
|
| 116 |
+
|
| 117 |
+
hit = {i: 0 for i in range(1, n + 1)}
|
| 118 |
+
ndcg = {i: 0 for i in range(1, n + 1)}
|
| 119 |
+
|
| 120 |
+
none_count_type1 = 0
|
| 121 |
+
none_count_type2 = 0
|
| 122 |
+
none_count_type3 = 0
|
| 123 |
+
sum_iter = 0
|
| 124 |
+
|
| 125 |
+
for index, row in tqdm(df2.iterrows(), total=n_users, desc='Process eval search',):
|
| 126 |
+
if index == n_users:
|
| 127 |
+
break
|
| 128 |
+
|
| 129 |
+
query = row['query_search']
|
| 130 |
+
label = int(row['search_click_id'])
|
| 131 |
+
label_title = get_item_by_id(label)
|
| 132 |
+
|
| 133 |
+
print(colored(f"\nUser query:", "yellow"), query)
|
| 134 |
+
print(colored(f"User click:", "yellow"), label_title)
|
| 135 |
+
|
| 136 |
+
if label_title == None:
|
| 137 |
+
none_count_type1 += 1
|
| 138 |
+
continue
|
| 139 |
+
|
| 140 |
+
try:
|
| 141 |
+
items, iter = get_items(user_query=query)
|
| 142 |
+
except Exception as e:
|
| 143 |
+
print(f"Error from eval_search: {e}")
|
| 144 |
+
none_count_type2 += 1
|
| 145 |
+
continue
|
| 146 |
+
|
| 147 |
+
sum_iter += iter
|
| 148 |
+
|
| 149 |
+
if len(items) == 0 or items[0]['id'] == None:
|
| 150 |
+
none_count_type3 += 1
|
| 151 |
+
continue
|
| 152 |
+
|
| 153 |
+
n_users_real += 1
|
| 154 |
+
for i, item in enumerate(items):
|
| 155 |
+
if label == item['id']:
|
| 156 |
+
for j in range(i+1, n + 1):
|
| 157 |
+
hit[j] += 1
|
| 158 |
+
ndcg[j] += np.log(2)/np.log(i + 2)
|
| 159 |
+
break
|
| 160 |
+
|
| 161 |
+
print('Total list count: ', n_users)
|
| 162 |
+
print('Real list count: ', n_users_real)
|
| 163 |
+
print('None list count type 1: ', none_count_type1)
|
| 164 |
+
print('None list count type 2: ', none_count_type2)
|
| 165 |
+
print('None list count type 3: ', none_count_type3)
|
| 166 |
+
print('avg_iter: ', sum_iter/n_users)
|
| 167 |
+
|
| 168 |
+
for i in range(1, n + 1):
|
| 169 |
+
print(f'hit_rate@{i} = ', hit[i] / n_users_real if n_users_real > 0 else 0)
|
| 170 |
+
|
| 171 |
+
for i in range(1, n + 1):
|
| 172 |
+
print(f'ndcg@{i} = ', ndcg[i]/ n_users_real if n_users_real > 0 else 0)
|
ma2crs.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from agent.planner import Planner
|
| 2 |
+
from agent.solver import Solver
|
| 3 |
+
from agent.reflector import Reflector
|
| 4 |
+
from agent.state import State, examples, longer_examples, tests, longer_tests, print_state
|
| 5 |
+
from search.search import es
|
| 6 |
+
from tools.tools import search, search_tool, es_info, search_tool_examples
|
| 7 |
+
from agent.utils import colored
|
| 8 |
+
import json
|
| 9 |
+
|
| 10 |
+
# Planner agent
|
| 11 |
+
planner = Planner()
|
| 12 |
+
# Define tools
|
| 13 |
+
def search_wrapper(*args, **kargs):
|
| 14 |
+
return search(es, *args, **kargs)
|
| 15 |
+
|
| 16 |
+
tools = [search_tool]
|
| 17 |
+
functions = {search_tool['function']['name']: search_wrapper}
|
| 18 |
+
additional_tools_info = f"""Đây là thông tin về các index và các trường của mỗi index:\n {es_info}
|
| 19 |
+
Khi bạn gọi hàm Search, hãy chỉ định type, các trường trong mỗi type chỉ có thể trong các trường ở bên trên,
|
| 20 |
+
các trường có mô tả với mảng enum thì các giá trị của trường chỉ nằm trong mảng enum, bạn không thể match các giá trị ở
|
| 21 |
+
ngoài mảng enum này. Sau đây là một số ví dụ về tham số khi gọi hàm Search:
|
| 22 |
+
{search_tool_examples}"""
|
| 23 |
+
|
| 24 |
+
# Solver agent
|
| 25 |
+
solver = Solver()
|
| 26 |
+
solver.bind_tools(tools)
|
| 27 |
+
solver.bind_functions(functions)
|
| 28 |
+
solver.additional_tools_info(additional_tools_info)
|
| 29 |
+
|
| 30 |
+
# Reflector agent
|
| 31 |
+
reflector = Reflector()
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
MAX_TRY = 3
|
| 35 |
+
|
| 36 |
+
def chat():
|
| 37 |
+
state = State(
|
| 38 |
+
user_info="Name: Nguyễn Minh Quang, Age: 21",
|
| 39 |
+
long_memory="""Người dùng thích xem phim hài, hành động, lãn mạn, phim được đánh giá cao và có nhiều giải thường.
|
| 40 |
+
Người dùng đã từng xem phim: Ba chàng ngốc, Forrest Gump, Titanic"""
|
| 41 |
+
)
|
| 42 |
+
print(colored("========User profile:", "yellow"))
|
| 43 |
+
print(colored("====User info:", "light_blue"))
|
| 44 |
+
print(state.user_info)
|
| 45 |
+
print(colored("====User history:", "light_blue"))
|
| 46 |
+
print(state.long_memory)
|
| 47 |
+
print(colored("================Chat begin================", "yellow"))
|
| 48 |
+
cur_mes = 0
|
| 49 |
+
print(colored("Chào mừng, tối có thể giúp gì cho bạn hôm nay!(type 'quit' to exit)", "yellow"))
|
| 50 |
+
while True:
|
| 51 |
+
user = input(">>>")
|
| 52 |
+
if user == 'quit' or user == 'Quit':
|
| 53 |
+
print(colored("Xin chào, hẹn gặp lại lần sau!", "yellow"))
|
| 54 |
+
break
|
| 55 |
+
|
| 56 |
+
user_message = {'role': 'user', 'content': user}
|
| 57 |
+
state.messages.append(user_message)
|
| 58 |
+
cur_mes += 1
|
| 59 |
+
|
| 60 |
+
trial = 0
|
| 61 |
+
while True:
|
| 62 |
+
trial += 1
|
| 63 |
+
|
| 64 |
+
if trial == MAX_TRY:
|
| 65 |
+
print(colored(f"HIT MAX TRY: {MAX_TRY}", "red"))
|
| 66 |
+
print(colored(f"========Final answer:", "light_blue"))
|
| 67 |
+
print(colored(f"{state.messages[-2]['content']}", "yellow"))
|
| 68 |
+
break
|
| 69 |
+
|
| 70 |
+
# Planning
|
| 71 |
+
print(colored("========Planner step processing ...", "light_blue"))
|
| 72 |
+
planner.step(state)
|
| 73 |
+
|
| 74 |
+
print(colored("====Thought:", "green"))
|
| 75 |
+
for i, thought in enumerate(state.thought):
|
| 76 |
+
print(f"Thought number {i}:", thought)
|
| 77 |
+
|
| 78 |
+
print(colored("====Plan:", "green"))
|
| 79 |
+
for i, plan in enumerate(state.plan):
|
| 80 |
+
print(f"Plan number {i}:", plan)
|
| 81 |
+
|
| 82 |
+
# Solving
|
| 83 |
+
print(colored("========Solver step processing ...", "light_blue"))
|
| 84 |
+
solver.step(state)
|
| 85 |
+
|
| 86 |
+
len_mes = len(state.messages)
|
| 87 |
+
while cur_mes < len_mes:
|
| 88 |
+
mes = state.messages[cur_mes]
|
| 89 |
+
cur_mes += 1
|
| 90 |
+
|
| 91 |
+
if mes['role'] == 'assistant':
|
| 92 |
+
if mes['content']:
|
| 93 |
+
print(colored("====Respond: ", "green"))
|
| 94 |
+
print(mes['content'])
|
| 95 |
+
|
| 96 |
+
elif mes.get('tool_calls'):
|
| 97 |
+
print(colored("====Tool calls:", "green"))
|
| 98 |
+
tool_calls = mes.get('tool_calls')
|
| 99 |
+
for i, tool_call in enumerate(tool_calls):
|
| 100 |
+
print("Tool number: ", i + 1)
|
| 101 |
+
print("Name: ", tool_call['function']['name'])
|
| 102 |
+
print("Kargs: ", tool_call['function']['arguments'])
|
| 103 |
+
elif mes['role'] == 'tool':
|
| 104 |
+
results = json.loads(mes['content'])
|
| 105 |
+
print(colored("====tool_results:", "green"))
|
| 106 |
+
print(json.dumps(results, ensure_ascii=False, indent=2))
|
| 107 |
+
|
| 108 |
+
# Reflecting
|
| 109 |
+
print(colored("========Reflector step processing ...", "light_blue"))
|
| 110 |
+
ref = reflector.step(state)
|
| 111 |
+
print(colored("====Finish:", "green"), state.finish)
|
| 112 |
+
print(colored("====Critical: ", "green"))
|
| 113 |
+
print(ref)
|
| 114 |
+
|
| 115 |
+
if state.finish:
|
| 116 |
+
print(colored(f"========Final answer:\n{state.messages[-1]['content']}", "yellow"))
|
| 117 |
+
break
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
if __name__ == '__main__':
|
| 121 |
+
while True:
|
| 122 |
+
chat()
|
| 123 |
+
key = input("Do you want to exit (y/n):")
|
| 124 |
+
if key == 'y':
|
| 125 |
+
break
|