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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Importing the libraries
|
2 |
+
import json
|
3 |
+
import time
|
4 |
+
import hnswlib
|
5 |
+
import numpy as np
|
6 |
+
import streamlit as st
|
7 |
+
from openai import OpenAI
|
8 |
+
import streamlit_nested_layout
|
9 |
+
from sentence_transformers import SentenceTransformer, CrossEncoder
|
10 |
+
from utils import *
|
11 |
+
|
12 |
+
# -----------------------------------------------------------defined arguments-----------------------------------------------------------
|
13 |
+
count = 0
|
14 |
+
save = 0
|
15 |
+
|
16 |
+
|
17 |
+
# Defined arguments
|
18 |
+
API_KEY = "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" # api_key
|
19 |
+
model_name = "gpt-3.5-turbo" # model name
|
20 |
+
tool_list_path = "./tools.json" # list of tools path
|
21 |
+
example_path = "./examples.json" # list of examples path
|
22 |
+
user_query = "Summarize my P1 issues in triage"
|
23 |
+
zero_shot = 0
|
24 |
+
no_of_examples = 2
|
25 |
+
|
26 |
+
# ---------------------------------------------------some constants ----------------------------------------------------------------------
|
27 |
+
|
28 |
+
EF = 100 # EF
|
29 |
+
K = 3 # top k number
|
30 |
+
COSINE_THRESHOLD = 0.3 # cosine threshold
|
31 |
+
biencoder = SentenceTransformer("BAAI/bge-large-en-v1.5", device="cpu")
|
32 |
+
cross_encoder = CrossEncoder(
|
33 |
+
"cross-encoder/ms-marco-MiniLM-L-12-v2", max_length=512, device="cpu"
|
34 |
+
)
|
35 |
+
client = OpenAI(api_key=API_KEY, timeout=60, max_retries=2)
|
36 |
+
|
37 |
+
# ------------------------------------------------------------------------------------------------------------------------------
|
38 |
+
|
39 |
+
if "n_args" not in st.session_state:
|
40 |
+
st.session_state["n_args"] = 0
|
41 |
+
|
42 |
+
if "new_tool" not in st.session_state:
|
43 |
+
st.session_state["new_tool"] = {}
|
44 |
+
|
45 |
+
if "tools" not in st.session_state:
|
46 |
+
st.session_state.tools = list(tool_obj.tools.values())
|
47 |
+
|
48 |
+
|
49 |
+
def warn(message):
|
50 |
+
st.toast(message)
|
51 |
+
|
52 |
+
# Save Tool
|
53 |
+
def save_tool(tool_list):
|
54 |
+
if type(tool_list) == list:
|
55 |
+
for t in tool_list:
|
56 |
+
tool_obj.add_tool(t)
|
57 |
+
st.toast("Updated", icon="✅")
|
58 |
+
else:
|
59 |
+
tool_obj.add_tool(tool_list)
|
60 |
+
|
61 |
+
# Function to Add Arguments
|
62 |
+
def add_arguments(i):
|
63 |
+
global count
|
64 |
+
with st.expander(f"Argument {i+1}"):
|
65 |
+
st.session_state["new_tool"]["argument_list"][i][
|
66 |
+
"argument_name"
|
67 |
+
] = st.text_input("Argument Name", "", key=count)
|
68 |
+
count += 1
|
69 |
+
st.session_state["new_tool"]["argument_list"][i][
|
70 |
+
"argument_description"
|
71 |
+
] = st.text_input("Argument Description", "", key=count)
|
72 |
+
count += 1
|
73 |
+
st.session_state["new_tool"]["argument_list"][i][
|
74 |
+
"argument_type"
|
75 |
+
] = st.text_input("Argument Type", "", key=count)
|
76 |
+
count += 1
|
77 |
+
st.session_state["new_tool"]["argument_list"][i]["example"] = st.text_input(
|
78 |
+
"Argument Examples", "", key=count
|
79 |
+
)
|
80 |
+
count += 1
|
81 |
+
if st.button(
|
82 |
+
"Delete Argument", key=count, use_container_width=True, type="primary"
|
83 |
+
):
|
84 |
+
warn(
|
85 |
+
f'Deleted {st.session_state["new_tool"]["argument_list"][i]["argument_name"]}'
|
86 |
+
)
|
87 |
+
st.session_state["n_args"] -= 1
|
88 |
+
del st.session_state["new_tool"]["argument_list"][i]
|
89 |
+
st.rerun()
|
90 |
+
|
91 |
+
count += 1
|
92 |
+
|
93 |
+
# -----------------------------------------------------------User Interface-----------------------------------------------------------
|
94 |
+
with st.sidebar:
|
95 |
+
with st.expander("Add Tool"):
|
96 |
+
st.session_state["new_tool"]["tool_name"] = ""
|
97 |
+
st.session_state["new_tool"]["tool_description"] = ""
|
98 |
+
st.session_state["new_tool"]["return_type"] = ""
|
99 |
+
st.session_state["new_tool"]["tool_name"] = st.text_input("Tool Name", st.session_state["new_tool"]["tool_name"])
|
100 |
+
st.session_state["new_tool"]["tool_description"] = st.text_input(
|
101 |
+
"Tool Description", ""
|
102 |
+
)
|
103 |
+
st.session_state["new_tool"]["return_type"] = st.text_input(
|
104 |
+
"Return Datatype", ""
|
105 |
+
)
|
106 |
+
if "argument_list" not in st.session_state["new_tool"]:
|
107 |
+
st.session_state["new_tool"]["argument_list"] = []
|
108 |
+
|
109 |
+
with st.expander("Arguments"):
|
110 |
+
for i in range(st.session_state["n_args"]):
|
111 |
+
add_arguments(i)
|
112 |
+
cols = st.columns(2)
|
113 |
+
with cols[0]:
|
114 |
+
if st.button("Add", use_container_width=True):
|
115 |
+
st.session_state["n_args"] += 1
|
116 |
+
st.session_state["new_tool"]["argument_list"].append(
|
117 |
+
{
|
118 |
+
"argument_name": "",
|
119 |
+
"argument_description": "",
|
120 |
+
"argument_type": "",
|
121 |
+
"example": "",
|
122 |
+
}
|
123 |
+
)
|
124 |
+
st.rerun()
|
125 |
+
|
126 |
+
with cols[1]:
|
127 |
+
if st.button("Save", use_container_width=True):
|
128 |
+
save = 1
|
129 |
+
try:
|
130 |
+
# Make Sure all fields are filled
|
131 |
+
print(st.session_state.new_tool)
|
132 |
+
if not st.session_state["new_tool"]["tool_name"]:
|
133 |
+
raise Exception("Empty Tool Name")
|
134 |
+
if not st.session_state["new_tool"]["tool_description"]:
|
135 |
+
raise Exception("Empty Tool Description")
|
136 |
+
if not st.session_state["new_tool"]["return_type"]:
|
137 |
+
raise Exception("Empty Return Type")
|
138 |
+
for arg in st.session_state["new_tool"]["argument_list"]:
|
139 |
+
if not arg["argument_name"]:
|
140 |
+
raise Exception("No argument name given")
|
141 |
+
if not arg["argument_description"]:
|
142 |
+
raise Exception("No argument description given")
|
143 |
+
if not arg["argument_type"]:
|
144 |
+
raise Exception("No argument type given")
|
145 |
+
if not arg["example"]:
|
146 |
+
raise Exception("No example of argument given")
|
147 |
+
with st.spinner("Adding..."):
|
148 |
+
|
149 |
+
save_tool(st.session_state["new_tool"])
|
150 |
+
st.session_state.tools = list(tool_obj.tools.values())
|
151 |
+
time.sleep(2)
|
152 |
+
st.session_state["new_tool"] = {}
|
153 |
+
st.session_state["n_args"] = 0
|
154 |
+
except Exception as e:
|
155 |
+
st.toast(e)
|
156 |
+
st.rerun()
|
157 |
+
|
158 |
+
with st.expander("Add Tools Via Json"):
|
159 |
+
uploaded_file = st.file_uploader("Choose a file")
|
160 |
+
if uploaded_file is not None:
|
161 |
+
data = json.load(uploaded_file)
|
162 |
+
# st.write(data)
|
163 |
+
try:
|
164 |
+
try:
|
165 |
+
for d in data:
|
166 |
+
tool_obj.check_json(d)
|
167 |
+
except Exception as e:
|
168 |
+
st.toast(f"Inccorect Format: {e}")
|
169 |
+
with st.spinner("Adding..."):
|
170 |
+
save_tool(data)
|
171 |
+
# st.session_state["tools"] += data
|
172 |
+
st.session_state.tools = list(tool_obj.tools.values())
|
173 |
+
st.toast(":green[Added Tools!]")
|
174 |
+
except:
|
175 |
+
st.toast("Incorrect Format Specified")
|
176 |
+
|
177 |
+
with st.expander("Current Tools"):
|
178 |
+
for i, tool in enumerate(st.session_state.tools):
|
179 |
+
with st.expander(tool["tool_name"]):
|
180 |
+
count += 1
|
181 |
+
st.session_state["tools"][i]["tool_description"] = st.text_input(
|
182 |
+
"Tool Description",
|
183 |
+
st.session_state["tools"][i]["tool_description"],
|
184 |
+
key=count,
|
185 |
+
)
|
186 |
+
count += 1
|
187 |
+
with st.expander("Argument List"):
|
188 |
+
for j, arg in enumerate(tool["argument_list"]):
|
189 |
+
with st.expander(arg["argument_name"]):
|
190 |
+
st.session_state["tools"][i]["argument_list"][j][
|
191 |
+
"argument_name"
|
192 |
+
] = st.text_input(
|
193 |
+
"Argument Name",
|
194 |
+
st.session_state["tools"][i]["argument_list"][j][
|
195 |
+
"argument_name"
|
196 |
+
],
|
197 |
+
key=count,
|
198 |
+
)
|
199 |
+
count += 1
|
200 |
+
st.session_state["tools"][i]["argument_list"][j][
|
201 |
+
"argument_description"
|
202 |
+
] = st.text_input(
|
203 |
+
"Argument Description",
|
204 |
+
st.session_state["tools"][i]["argument_list"][j][
|
205 |
+
"argument_description"
|
206 |
+
],
|
207 |
+
key=count,
|
208 |
+
)
|
209 |
+
count += 1
|
210 |
+
st.session_state["tools"][i]["argument_list"][j][
|
211 |
+
"argument_type"
|
212 |
+
] = st.text_input(
|
213 |
+
"Argument Type",
|
214 |
+
st.session_state["tools"][i]["argument_list"][j][
|
215 |
+
"argument_type"
|
216 |
+
],
|
217 |
+
key=count,
|
218 |
+
)
|
219 |
+
count += 1
|
220 |
+
st.session_state["tools"][i]["argument_list"][j][
|
221 |
+
"example"
|
222 |
+
] = st.text_input(
|
223 |
+
"Argument Example",
|
224 |
+
st.session_state["tools"][i]["argument_list"][j][
|
225 |
+
"example"
|
226 |
+
],
|
227 |
+
key=count,
|
228 |
+
)
|
229 |
+
count += 1
|
230 |
+
columns = st.columns(2)
|
231 |
+
with columns[0]:
|
232 |
+
if st.button(
|
233 |
+
"Delete",
|
234 |
+
key=count,
|
235 |
+
use_container_width=True,
|
236 |
+
type="primary",
|
237 |
+
):
|
238 |
+
with st.spinner("Deleting..."):
|
239 |
+
del st.session_state["tools"][i]["argument_list"][j]
|
240 |
+
save_tool(st.session_state["tools"][i])
|
241 |
+
st.session_state.tools = list(tool_obj.tools.values())
|
242 |
+
st.toast(f":red[Deleted Tool]")
|
243 |
+
st.rerun()
|
244 |
+
count += 1
|
245 |
+
|
246 |
+
with columns[1]:
|
247 |
+
if st.button(
|
248 |
+
"Save", key=count, use_container_width=True
|
249 |
+
):
|
250 |
+
save_tool(st.session_state["tools"][i])
|
251 |
+
st.session_state.tools = list(tool_obj.tools.values())
|
252 |
+
st.rerun()
|
253 |
+
count += 1
|
254 |
+
|
255 |
+
cols = st.columns([2, 2, 1])
|
256 |
+
with cols[0]:
|
257 |
+
if st.button("Add", key=count, use_container_width=True):
|
258 |
+
st.session_state.tools[i]["argument_list"].append(
|
259 |
+
{
|
260 |
+
"argument_name": "",
|
261 |
+
"argument_description": "",
|
262 |
+
"argument_type": "",
|
263 |
+
"example": "",
|
264 |
+
}
|
265 |
+
)
|
266 |
+
st.rerun()
|
267 |
+
count += 1
|
268 |
+
with cols[1]:
|
269 |
+
if st.button("Save", key=count, use_container_width=True):
|
270 |
+
with st.spinner("Wait"):
|
271 |
+
save_tool(st.session_state["tools"][i])
|
272 |
+
st.session_state.tools = list(tool_obj.tools.values())
|
273 |
+
st.toast(f":green[Modified Tool]")
|
274 |
+
st.rerun()
|
275 |
+
count += 1
|
276 |
+
|
277 |
+
with cols[2]:
|
278 |
+
if st.button("❌", key=count):
|
279 |
+
warn(f"Deleted {tool['tool_name']}")
|
280 |
+
tool_obj.delete_tool(tool["tool_name"])
|
281 |
+
st.session_state["tools"] = list(tool_obj.tools.values())
|
282 |
+
st.rerun()
|
283 |
+
count += 1
|
284 |
+
|
285 |
+
from time import sleep
|
286 |
+
st.markdown("# ToolMaster")
|
287 |
+
|
288 |
+
|
289 |
+
prompt = st.chat_input("Say something")
|
290 |
+
if prompt:
|
291 |
+
st.chat_message("user").write(prompt.replace(":", "\:"))
|
292 |
+
with st.spinner('Querying...'):
|
293 |
+
answer = main(prompt)
|
294 |
+
st.chat_message("assistant").write(answer)
|
examples.json
ADDED
@@ -0,0 +1,351 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[
|
2 |
+
{
|
3 |
+
"query": "Summarize work items similar to don:core:dvrv-us-1:devo/0:issue/1",
|
4 |
+
"answer": [
|
5 |
+
{
|
6 |
+
"tool_name": "get_similar_work_items",
|
7 |
+
"arguments": [
|
8 |
+
{
|
9 |
+
"argument_name": "work_id",
|
10 |
+
"argument_value": "don:core:dvrv-us-1:devo/0:issue/1"
|
11 |
+
}
|
12 |
+
]
|
13 |
+
},
|
14 |
+
{
|
15 |
+
"tool_name": "summarize_objects",
|
16 |
+
"arguments": [
|
17 |
+
{
|
18 |
+
"argument_name": "objects",
|
19 |
+
"argument_value": "$$PREV[0]"
|
20 |
+
}
|
21 |
+
]
|
22 |
+
}
|
23 |
+
]
|
24 |
+
},
|
25 |
+
{
|
26 |
+
"query": "What is the meaning of life?",
|
27 |
+
"answer": []
|
28 |
+
},
|
29 |
+
{
|
30 |
+
"query": "Prioritize my P0 issues and add them to the current sprint",
|
31 |
+
"answer": [
|
32 |
+
{
|
33 |
+
"tool_name": "who_am_i",
|
34 |
+
"arguments": []
|
35 |
+
},
|
36 |
+
{
|
37 |
+
"tool_name": "works_list",
|
38 |
+
"arguments": [
|
39 |
+
{
|
40 |
+
"argument_name": "issue.priority",
|
41 |
+
"argument_value": ["p0"]
|
42 |
+
},
|
43 |
+
{
|
44 |
+
"argument_name": "owned_by",
|
45 |
+
"argument_value": ["$$PREV[0]"]
|
46 |
+
},
|
47 |
+
{
|
48 |
+
"argument_name": "type",
|
49 |
+
"argument_value": ["issue"]
|
50 |
+
}
|
51 |
+
]
|
52 |
+
},
|
53 |
+
{
|
54 |
+
"tool_name": "prioritize_objects",
|
55 |
+
"arguments": [
|
56 |
+
{
|
57 |
+
"argument_name": "objects",
|
58 |
+
"argument_value": "$$PREV[1]"
|
59 |
+
}
|
60 |
+
]
|
61 |
+
},
|
62 |
+
{
|
63 |
+
"tool_name": "get_sprint_id",
|
64 |
+
"arguments": []
|
65 |
+
},
|
66 |
+
{
|
67 |
+
"tool_name": "add_work_items_to_sprint",
|
68 |
+
"arguments": [
|
69 |
+
{
|
70 |
+
"argument_name": "work_ids",
|
71 |
+
"argument_value": "$$PREV[2]"
|
72 |
+
},
|
73 |
+
{
|
74 |
+
"argument_name": "sprint_id",
|
75 |
+
"argument_value": "$$PREV[3]"
|
76 |
+
}
|
77 |
+
]
|
78 |
+
}
|
79 |
+
]
|
80 |
+
},
|
81 |
+
{
|
82 |
+
"query": "Summarize high severity tickets from the customer UltimateCustomer",
|
83 |
+
"answer": [
|
84 |
+
{
|
85 |
+
"tool_name": "search_object_by_name",
|
86 |
+
"arguments": [
|
87 |
+
{
|
88 |
+
"argument_name": "query",
|
89 |
+
"argument_value": "UltimateCustomer"
|
90 |
+
}
|
91 |
+
]
|
92 |
+
},
|
93 |
+
{
|
94 |
+
"tool_name": "works_list",
|
95 |
+
"arguments": [
|
96 |
+
{
|
97 |
+
"argument_name": "ticket.rev_org",
|
98 |
+
"argument_value": ["$$PREV[0]"]
|
99 |
+
},
|
100 |
+
{
|
101 |
+
"argument_name": "ticket.severity",
|
102 |
+
"argument_value": ["high"]
|
103 |
+
},
|
104 |
+
{
|
105 |
+
"argument_name": "type",
|
106 |
+
"argument_value": ["ticket"]
|
107 |
+
}
|
108 |
+
]
|
109 |
+
},
|
110 |
+
{
|
111 |
+
"tool_name": "summarize_objects",
|
112 |
+
"arguments": [
|
113 |
+
{
|
114 |
+
"argument_name": "objects",
|
115 |
+
"argument_value": "$$PREV[1]"
|
116 |
+
}
|
117 |
+
]
|
118 |
+
}
|
119 |
+
]
|
120 |
+
},
|
121 |
+
{
|
122 |
+
"query": "What are my all issues in the triage stage under part FEAT-123? Summarize them.",
|
123 |
+
"answer": [
|
124 |
+
{
|
125 |
+
"tool_name": "who_am_i",
|
126 |
+
"arguments": []
|
127 |
+
},
|
128 |
+
{
|
129 |
+
"tool_name": "works_list",
|
130 |
+
"arguments": [
|
131 |
+
{
|
132 |
+
"argument_name": "stage.name",
|
133 |
+
"argument_value": ["triage"]
|
134 |
+
},
|
135 |
+
{
|
136 |
+
"argument_name": "applies_to_part",
|
137 |
+
"argument_value": ["FEAT-123"]
|
138 |
+
},
|
139 |
+
{
|
140 |
+
"argument_name": "owned_by",
|
141 |
+
"argument_value": ["$$PREV[0]"]
|
142 |
+
},
|
143 |
+
{
|
144 |
+
"argument_name": "type",
|
145 |
+
"argument_value": ["issue"]
|
146 |
+
}
|
147 |
+
]
|
148 |
+
},
|
149 |
+
{
|
150 |
+
"tool_name": "summarize_objects",
|
151 |
+
"arguments": [
|
152 |
+
{
|
153 |
+
"argument_name": "objects",
|
154 |
+
"argument_value": "$$PREV[1]"
|
155 |
+
}
|
156 |
+
]
|
157 |
+
}
|
158 |
+
]
|
159 |
+
},
|
160 |
+
{
|
161 |
+
"query": "List all high severity tickets coming in from slack from customer Cust123 and generate a summary of them.",
|
162 |
+
"answer": [
|
163 |
+
{
|
164 |
+
"tool_name": "search_object_by_name",
|
165 |
+
"arguments": [
|
166 |
+
{
|
167 |
+
"argument_name": "query",
|
168 |
+
"argument_value": "Cust123"
|
169 |
+
}
|
170 |
+
]
|
171 |
+
},
|
172 |
+
{
|
173 |
+
"tool_name": "works_list",
|
174 |
+
"arguments": [
|
175 |
+
{
|
176 |
+
"argument_name": "ticket.rev_org",
|
177 |
+
"argument_value": ["$$PREV[0]"]
|
178 |
+
},
|
179 |
+
{
|
180 |
+
"argument_name": "ticket.severity",
|
181 |
+
"argument_value": ["high"]
|
182 |
+
},
|
183 |
+
{
|
184 |
+
"argument_name": "ticket.source_channel",
|
185 |
+
"argument_value": ["slack"]
|
186 |
+
},
|
187 |
+
{
|
188 |
+
"argument_name": "type",
|
189 |
+
"argument_value": ["ticket"]
|
190 |
+
}
|
191 |
+
]
|
192 |
+
},
|
193 |
+
{
|
194 |
+
"tool_name": "summarize_objects",
|
195 |
+
"arguments": [
|
196 |
+
{
|
197 |
+
"argument_name": "objects",
|
198 |
+
"argument_value": "$$PREV[1]"
|
199 |
+
}
|
200 |
+
]
|
201 |
+
}
|
202 |
+
]
|
203 |
+
},
|
204 |
+
{
|
205 |
+
"query": "Given a customer meeting transcript T, create action items and add them to my current sprint",
|
206 |
+
"answer": [
|
207 |
+
{
|
208 |
+
"tool_name": "create_actionable_tasks_from_text",
|
209 |
+
"arguments": [
|
210 |
+
{
|
211 |
+
"argument_name": "text",
|
212 |
+
"argument_value": "T"
|
213 |
+
}
|
214 |
+
]
|
215 |
+
},
|
216 |
+
{
|
217 |
+
"tool_name": "get_sprint_id",
|
218 |
+
"arguments": []
|
219 |
+
},
|
220 |
+
{
|
221 |
+
"tool_name": "add_work_items_to_sprint",
|
222 |
+
"arguments": [
|
223 |
+
{
|
224 |
+
"argument_name": "work_ids",
|
225 |
+
"argument_value": "$$PREV[0]"
|
226 |
+
},
|
227 |
+
{
|
228 |
+
"argument_name": "sprint_id",
|
229 |
+
"argument_value": "$$PREV[1]"
|
230 |
+
}
|
231 |
+
]
|
232 |
+
}
|
233 |
+
]
|
234 |
+
},
|
235 |
+
{
|
236 |
+
"query": "Get all work items similar to TKT-123, summarize them, create issues from that summary, and prioritize them",
|
237 |
+
"answer": [
|
238 |
+
{
|
239 |
+
"tool_name": "get_similar_work_items",
|
240 |
+
"arguments": [
|
241 |
+
{
|
242 |
+
"argument_name": "work_id",
|
243 |
+
"argument_value": "TKT-123"
|
244 |
+
}
|
245 |
+
]
|
246 |
+
},
|
247 |
+
{
|
248 |
+
"tool_name": "summarize_objects",
|
249 |
+
"arguments": [
|
250 |
+
{
|
251 |
+
"argument_name": "objects",
|
252 |
+
"argument_value": "$$PREV[0]"
|
253 |
+
}
|
254 |
+
]
|
255 |
+
},
|
256 |
+
{
|
257 |
+
"tool_name": "create_actionable_tasks_from_text",
|
258 |
+
"arguments": [
|
259 |
+
{
|
260 |
+
"argument_name": "text",
|
261 |
+
"argument_value": "$$PREV[1]"
|
262 |
+
}
|
263 |
+
]
|
264 |
+
},
|
265 |
+
{
|
266 |
+
"tool_name": "prioritize_objects",
|
267 |
+
"arguments": [
|
268 |
+
{
|
269 |
+
"argument_name": "objects",
|
270 |
+
"argument_value": "$$PREV[2]"
|
271 |
+
}
|
272 |
+
]
|
273 |
+
}
|
274 |
+
]
|
275 |
+
},
|
276 |
+
{
|
277 |
+
"query": "Check if any 'blocker' tickets are in the 'triage' stage and if so, return their count",
|
278 |
+
"answer": [
|
279 |
+
{
|
280 |
+
"tool_name": "works_list",
|
281 |
+
"arguments": [
|
282 |
+
{
|
283 |
+
"argument_name": "ticket.severity",
|
284 |
+
"argument_value": [
|
285 |
+
"blocker"
|
286 |
+
]
|
287 |
+
},
|
288 |
+
{
|
289 |
+
"argument_name": "stage.name",
|
290 |
+
"argument_value": [
|
291 |
+
"triage"
|
292 |
+
]
|
293 |
+
},
|
294 |
+
{
|
295 |
+
"argument_name": "type",
|
296 |
+
"argument_value": [
|
297 |
+
"ticket"
|
298 |
+
]
|
299 |
+
}
|
300 |
+
]
|
301 |
+
},
|
302 |
+
{
|
303 |
+
"tool_name": "lambda",
|
304 |
+
"arguments": [
|
305 |
+
{
|
306 |
+
"argument_name": "expression",
|
307 |
+
"argument_value": "lambda $$PREV[0]: len($$PREV[0]) if $$PREV[0] else 0"
|
308 |
+
}
|
309 |
+
]
|
310 |
+
}
|
311 |
+
]
|
312 |
+
},
|
313 |
+
{
|
314 |
+
"query": "Get the total number of issues that need a response and are of priority 'p1' or 'p2'",
|
315 |
+
"answer": [
|
316 |
+
{
|
317 |
+
"tool_name": "works_list",
|
318 |
+
"arguments": [
|
319 |
+
{
|
320 |
+
"argument_name": "issue.priority",
|
321 |
+
"argument_value": [
|
322 |
+
"p1",
|
323 |
+
"p2"
|
324 |
+
]
|
325 |
+
},
|
326 |
+
{
|
327 |
+
"argument_name": "ticket.needs_response",
|
328 |
+
"argument_value": [
|
329 |
+
true
|
330 |
+
]
|
331 |
+
},
|
332 |
+
{
|
333 |
+
"argument_name": "type",
|
334 |
+
"argument_value": [
|
335 |
+
"issue"
|
336 |
+
]
|
337 |
+
}
|
338 |
+
]
|
339 |
+
},
|
340 |
+
{
|
341 |
+
"tool_name": "lambda",
|
342 |
+
"arguments": [
|
343 |
+
{
|
344 |
+
"argument_name": "expression",
|
345 |
+
"argument_value": "lambda $$PREV[0]: len($$PREV[0])"
|
346 |
+
}
|
347 |
+
]
|
348 |
+
}
|
349 |
+
]
|
350 |
+
}
|
351 |
+
]
|
requirements.txt
ADDED
Binary file (194 Bytes). View file
|
|
tools.json
ADDED
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"tools": [
|
3 |
+
{
|
4 |
+
"tool_description": "Returns a list of work items matching the request.",
|
5 |
+
"tool_name": "works_list",
|
6 |
+
"return_type": "array of objects",
|
7 |
+
"argument_list": [
|
8 |
+
{
|
9 |
+
"argument_name": "applies_to_part",
|
10 |
+
"argument_description": "Filters for work belonging to any of the provided parts",
|
11 |
+
"argument_type": "array of strings",
|
12 |
+
"example": [
|
13 |
+
["FEAT-123"],
|
14 |
+
["ENH-123", "PROD-123", "CAPL-123", "CAPL-359"],
|
15 |
+
["HGH-262", "FEAT-007"]
|
16 |
+
]
|
17 |
+
},
|
18 |
+
{
|
19 |
+
"argument_name": "created_by",
|
20 |
+
"argument_description": "Filters for work created by any of these users",
|
21 |
+
"argument_type": "array of strings",
|
22 |
+
"example": [["DEVU-123"], ["PRO-233", "CRE-1233"]]
|
23 |
+
},
|
24 |
+
{
|
25 |
+
"argument_name": "issue.priority",
|
26 |
+
"argument_description": "Filters for issues with any of the provided priorities. Allowed values: p0, p1, p2, p3.",
|
27 |
+
"allowed_values": ["p0", "p1", "p2", "p3"],
|
28 |
+
"argument_type": "array of strings",
|
29 |
+
"example": [["p0"], ["p0", "p3"], ["p0", "p1", "p2", "p3"]]
|
30 |
+
},
|
31 |
+
{
|
32 |
+
"argument_name": "issue.rev_orgs",
|
33 |
+
"argument_description": "Filters for issues with any of the provided Rev organizations",
|
34 |
+
"argument_type": "array of strings",
|
35 |
+
"example": [["REV-123"], ["REV-468", "REV-979"]]
|
36 |
+
},
|
37 |
+
{
|
38 |
+
"argument_name": "limit",
|
39 |
+
"argument_description": "The maximum number of works to return. The default is 50",
|
40 |
+
"argument_type": "integer(int32)",
|
41 |
+
"example": [40, 25, 2, 1, 50]
|
42 |
+
},
|
43 |
+
{
|
44 |
+
"argument_name": "owned_by",
|
45 |
+
"argument_description": "Filters for work owned by any of these users",
|
46 |
+
"argument_type": "array of strings",
|
47 |
+
"example": [["DEVU-123"], ["CAPL-264", "HGH-190"]]
|
48 |
+
},
|
49 |
+
{
|
50 |
+
"argument_name": "stage.name",
|
51 |
+
"argument_description": "Filters for records in the provided stage(s) by name",
|
52 |
+
"argument_type": "array of strings",
|
53 |
+
"example": [["triage"], ["design", "triage"]]
|
54 |
+
},
|
55 |
+
{
|
56 |
+
"argument_name": "ticket.needs_response",
|
57 |
+
"argument_description": "Filters for tickets that need a response",
|
58 |
+
"argument_type": "boolean",
|
59 |
+
"example": ["True", "False"]
|
60 |
+
},
|
61 |
+
{
|
62 |
+
"argument_name": "ticket.rev_org",
|
63 |
+
"argument_description": "Filters for tickets associated with any of the provided Rev organizations",
|
64 |
+
"argument_type": "array of strings",
|
65 |
+
"example": [["REV-123"], ["REV-238", "REV-119"]]
|
66 |
+
},
|
67 |
+
{
|
68 |
+
"argument_name": "ticket.severity",
|
69 |
+
"argument_description": "Filters for tickets with any of the provided severities. Allowed values: blocker, high, low, medium",
|
70 |
+
"argument_type": "array of strings",
|
71 |
+
"allowed_values": ["blocker", "high", "low", "medium"],
|
72 |
+
"example": [
|
73 |
+
["blocker"],
|
74 |
+
["blocker", "high"],
|
75 |
+
["blocker", "high", "low"]
|
76 |
+
]
|
77 |
+
},
|
78 |
+
{
|
79 |
+
"argument_name": "ticket.source_channel",
|
80 |
+
"argument_description": "Filters for tickets with any of the provided source channels",
|
81 |
+
"argument_type": "array of strings",
|
82 |
+
"example": [["slack"], ["github"], ["slack", "scrum"]]
|
83 |
+
},
|
84 |
+
{
|
85 |
+
"argument_name": "type",
|
86 |
+
"argument_description": "Filters for work of the provided types. Allowed values: issue, ticket, task",
|
87 |
+
"allowed_values": ["issue", "ticket", "task"],
|
88 |
+
"argument_type": "array of strings",
|
89 |
+
"example": [["issue"], ["ticket"], ["task"]]
|
90 |
+
}
|
91 |
+
]
|
92 |
+
},
|
93 |
+
{
|
94 |
+
"tool_description": "Summarizes a list of objects. The logic of how to summarize a particular object type is an internal implementation detail.",
|
95 |
+
"tool_name": "summarize_objects",
|
96 |
+
"return_type": "array of objects",
|
97 |
+
"argument_list": [
|
98 |
+
{
|
99 |
+
"argument_name": "objects",
|
100 |
+
"argument_description": "List of objects to summarize",
|
101 |
+
"argument_type": "array of objects",
|
102 |
+
"example": [["issue1"], ["task1", "issue3"]]
|
103 |
+
}
|
104 |
+
]
|
105 |
+
},
|
106 |
+
{
|
107 |
+
"tool_description": "Returns a list of objects sorted by priority.",
|
108 |
+
"tool_name": "prioritize_objects",
|
109 |
+
"return_type": "array of objects",
|
110 |
+
"argument_list": [
|
111 |
+
{
|
112 |
+
"argument_name": "objects",
|
113 |
+
"argument_description": "A list of objects to be prioritized",
|
114 |
+
"argument_type": "array of objects",
|
115 |
+
"example": [["issue4"], ["task2", "issue3"], ["ticket9"]]
|
116 |
+
}
|
117 |
+
]
|
118 |
+
},
|
119 |
+
{
|
120 |
+
"tool_description": "Adds the given work items to the sprint",
|
121 |
+
"tool_name": "add_work_items_to_sprint",
|
122 |
+
"return_type": "none",
|
123 |
+
"argument_list": [
|
124 |
+
{
|
125 |
+
"argument_name": "work_ids",
|
126 |
+
"argument_description": "A list of work item IDs to be added to the sprint.",
|
127 |
+
"argument_type": "array of strings",
|
128 |
+
"example": [["deve/0:issue/6"], ["devdon:core:dvrv-us-1:task/1"]]
|
129 |
+
},
|
130 |
+
{
|
131 |
+
"argument_name": "sprint_id",
|
132 |
+
"argument_description": "The ID of the sprint to which the work items should be added.",
|
133 |
+
"argument_type": "str",
|
134 |
+
"example": ["sprint_4", "sprint_1"]
|
135 |
+
}
|
136 |
+
]
|
137 |
+
},
|
138 |
+
{
|
139 |
+
"tool_description": "Given a search string, returns the ID of a matching object in the system of record. If multiple matches are found, it returns the one where the confidence is highest.",
|
140 |
+
"tool_name": "search_object_by_name",
|
141 |
+
"return_type": "string",
|
142 |
+
"argument_list": [
|
143 |
+
{
|
144 |
+
"argument_name": "query",
|
145 |
+
"argument_description": "The search string, for example, customer's name, part name, user name.",
|
146 |
+
"argument_type": "string",
|
147 |
+
"example": ["DEV-123", "REV-432"]
|
148 |
+
}
|
149 |
+
]
|
150 |
+
},
|
151 |
+
{
|
152 |
+
"tool_description": "Returns the ID of the current sprint.",
|
153 |
+
"tool_name": "get_sprint_id",
|
154 |
+
"return_type": "string",
|
155 |
+
"argument_list": []
|
156 |
+
},
|
157 |
+
{
|
158 |
+
"tool_description": "Given a text, extracts actionable insights, and creates tasks for them, which are kind of a work item.",
|
159 |
+
"tool_name": "create_actionable_tasks_from_text",
|
160 |
+
"return_type": "array of strings",
|
161 |
+
"argument_list": [
|
162 |
+
{
|
163 |
+
"argument_name": "text",
|
164 |
+
"argument_description": "The text from which the actionable insights need to be created.",
|
165 |
+
"argument_type": "string",
|
166 |
+
"example": [
|
167 |
+
"Transcript from slack channels",
|
168 |
+
"Transcripts from a meeting",
|
169 |
+
"workplace report"
|
170 |
+
]
|
171 |
+
}
|
172 |
+
]
|
173 |
+
},
|
174 |
+
{
|
175 |
+
"tool_description": "Returns the ID of the current user.",
|
176 |
+
"tool_name": "who_am_i",
|
177 |
+
"return_type": "string",
|
178 |
+
"argument_list": []
|
179 |
+
},
|
180 |
+
{
|
181 |
+
"tool_description": "Returns a list of work items that are similar to the given work item",
|
182 |
+
"tool_name": "get_similar_work_items",
|
183 |
+
"return_type": "array of objects",
|
184 |
+
"argument_list": [
|
185 |
+
{
|
186 |
+
"argument_name": "work_id",
|
187 |
+
"argument_description": "The ID of the work item for which you want to find similar items",
|
188 |
+
"argument_type": "string",
|
189 |
+
"example": ["der/0:issue/2", "ton:core:dvrv-us-3:sprint/10"]
|
190 |
+
}
|
191 |
+
]
|
192 |
+
},
|
193 |
+
{
|
194 |
+
"tool_description": "Given the outputs from previous tools, process relevant outputs, combining them using mathematical operations, iterations, conditional logic etc and returns output matching the request",
|
195 |
+
"tool_name": "lambda",
|
196 |
+
"return_type": "any",
|
197 |
+
"argument_list": [
|
198 |
+
{
|
199 |
+
"argument_name": "expression",
|
200 |
+
"argument_description": "Operation to be performed",
|
201 |
+
"argument_type": "lambda statements",
|
202 |
+
"example": "['lambda $$PREV[3], $$PREV[5] : $$PREV[3] + $$PREV[5]','lambda $$PREV[0]: len($$PREV[0])']"
|
203 |
+
}
|
204 |
+
]
|
205 |
+
}
|
206 |
+
]
|
207 |
+
}
|
utils.py
ADDED
@@ -0,0 +1,1365 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# important classes
|
2 |
+
import json
|
3 |
+
import hnswlib
|
4 |
+
import numpy as np
|
5 |
+
from openai import OpenAI
|
6 |
+
from sentence_transformers import SentenceTransformer, CrossEncoder
|
7 |
+
|
8 |
+
# It formats the output by printing it in color.
|
9 |
+
|
10 |
+
# Defined arguments
|
11 |
+
API_KEY = "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" # api_key
|
12 |
+
model_name_tr = "gpt-3.5-turbo" # model name
|
13 |
+
model_name_ta = "gpt-4-1106-preview"
|
14 |
+
tool_list_path = './tools.json' # list of tools path[ ]
|
15 |
+
example_path = './examples.json' # list of examples path
|
16 |
+
zero_shot = 0
|
17 |
+
no_of_examples = 2
|
18 |
+
|
19 |
+
# ---------------------------------------------------some constants ----------------------------------------------------------------------
|
20 |
+
|
21 |
+
EF = 100 # EF
|
22 |
+
K = 3 # top k number
|
23 |
+
COSINE_THRESHOLD = 0.3 # cosine threshold
|
24 |
+
biencoder = SentenceTransformer("BAAI/bge-large-en-v1.5", device="cpu")
|
25 |
+
cross_encoder = CrossEncoder(
|
26 |
+
"cross-encoder/ms-marco-MiniLM-L-12-v2", max_length=512, device="cpu"
|
27 |
+
)
|
28 |
+
client = OpenAI(api_key=API_KEY, timeout=60, max_retries=2)
|
29 |
+
|
30 |
+
class color:
|
31 |
+
PURPLE = "\033[1;35;48m"
|
32 |
+
CYAN = "\033[1;36;48m"
|
33 |
+
BOLD = "\033[1;37;48m"
|
34 |
+
BLUE = "\033[1;34;48m"
|
35 |
+
GREEN = "\033[1;32;48m"
|
36 |
+
YELLOW = "\033[1;33;48m"
|
37 |
+
RED = "\033[1;31;48m"
|
38 |
+
BLACK = "\033[1;30;48m"
|
39 |
+
UNDERLINE = "\033[4;37;48m"
|
40 |
+
END = "\033[1;37;0m"
|
41 |
+
|
42 |
+
class Tools:
|
43 |
+
'''
|
44 |
+
A class to represent tools.
|
45 |
+
...
|
46 |
+
Attributes
|
47 |
+
----------
|
48 |
+
- tools: list
|
49 |
+
a list of tools (json format as described above)
|
50 |
+
|
51 |
+
- examples: list
|
52 |
+
a list of examples (json format as described above)
|
53 |
+
|
54 |
+
Methods
|
55 |
+
-------
|
56 |
+
- check_json()
|
57 |
+
checks whether the tool added is in the defined JSON schema
|
58 |
+
|
59 |
+
- build_index()
|
60 |
+
assigns index values to the examples and their respective tool calls to create an index list.
|
61 |
+
|
62 |
+
- add_tool()
|
63 |
+
adds new tool to the index list.
|
64 |
+
|
65 |
+
- add_example()
|
66 |
+
adds the new example in the example pool and modifies the index list.
|
67 |
+
|
68 |
+
- modify_example()
|
69 |
+
modifies an existing example present in the example list.
|
70 |
+
|
71 |
+
- update_tool()
|
72 |
+
updates an exisiting tool in the tool list.
|
73 |
+
|
74 |
+
- replenish_examples()
|
75 |
+
on deletion of tool replenish the examples for the tools where the num_examples < threshold
|
76 |
+
|
77 |
+
- delete_tool()
|
78 |
+
deletes the tool from the index list and example list.
|
79 |
+
|
80 |
+
- similarity_retriever()
|
81 |
+
creates the hsnw index for the example queries
|
82 |
+
|
83 |
+
'''
|
84 |
+
def __init__(self, tools, examples):
|
85 |
+
# assuming the self.tools to be a dict of tools with tool name as the key and tool info as the value.
|
86 |
+
self.tools = tools
|
87 |
+
self.examples = examples
|
88 |
+
self.index = {}
|
89 |
+
self.build_index()
|
90 |
+
self.th = 2
|
91 |
+
self.query_embeddings = []
|
92 |
+
self.queries = []
|
93 |
+
self.search_index = None
|
94 |
+
self.similarity_retriever()
|
95 |
+
|
96 |
+
def check_json(self,tool_json):
|
97 |
+
keys = ['argument_list', 'title', 'tool_description', 'tool_name']
|
98 |
+
argument_keys = ['argument_description', 'argument_name', 'argument_type', 'example']
|
99 |
+
if type(tool_json) != type({}):
|
100 |
+
raise Exception('Given tool json is not a dictionary')
|
101 |
+
if keys != sorted(list(tool_json.keys())):
|
102 |
+
raise Exception(
|
103 |
+
"""Keys don't match
|
104 |
+
Expected Keys: {}
|
105 |
+
Given Keys: {}
|
106 |
+
""".format(keys, sorted(list(tool_json.keys())))
|
107 |
+
)
|
108 |
+
if type(tool_json['argument_list']) != type([]):
|
109 |
+
raise Exception('Given argument list is not a list')
|
110 |
+
for idx, arg in enumerate(tool_json['argument_list']):
|
111 |
+
if type(arg) != type({}):
|
112 |
+
raise Exception(f'Argument at the index: {idx} is not a dictionary')
|
113 |
+
if argument_keys != sorted(list(arg.keys())):
|
114 |
+
raise Exception(
|
115 |
+
"""Keys don't match at {}
|
116 |
+
Expected Keys: {}
|
117 |
+
Given Keys: {}
|
118 |
+
""".format(idx, argument_keys, sorted(list(arg.keys())))
|
119 |
+
)
|
120 |
+
|
121 |
+
def build_index(self):
|
122 |
+
'''
|
123 |
+
Indexes all the examples with their respective tool calls.
|
124 |
+
For example: {'<tool_name>': {'num_examples': <no. of examples containing tool_name>, 'indices': <list of example indices containing respective tool_name>}}
|
125 |
+
Parameters
|
126 |
+
----------
|
127 |
+
None
|
128 |
+
|
129 |
+
Returns
|
130 |
+
----------
|
131 |
+
None
|
132 |
+
|
133 |
+
Modifies
|
134 |
+
----------
|
135 |
+
self.index
|
136 |
+
'''
|
137 |
+
for tool in self.tools:
|
138 |
+
self.index[tool] = {'num_examples': 0, 'indices': []}
|
139 |
+
for i, example in enumerate(self.examples):
|
140 |
+
for tool in example['answer']:
|
141 |
+
self.index[tool['tool_name']]['num_examples'] += 1
|
142 |
+
self.index[tool['tool_name']]['indices'].append(i)
|
143 |
+
|
144 |
+
def add_tool(self, tool):
|
145 |
+
'''
|
146 |
+
On addition of any new tool, this function gets called to add the new tool in self.index.
|
147 |
+
|
148 |
+
Parameters
|
149 |
+
----------
|
150 |
+
- tool : json (format described above)
|
151 |
+
|
152 |
+
Returns
|
153 |
+
----------
|
154 |
+
None
|
155 |
+
|
156 |
+
Modifies
|
157 |
+
----------
|
158 |
+
self.index
|
159 |
+
'''
|
160 |
+
# self.check_json(tool)
|
161 |
+
tool_name = tool['tool_name']
|
162 |
+
if tool_name in self.tools.keys():
|
163 |
+
if tool==self.tools[tool_name]:
|
164 |
+
print(color.YELLOW+'Already Exists!'+color.END)
|
165 |
+
else:
|
166 |
+
self.update_tool(tool)
|
167 |
+
print(color.YELLOW+f"[WARNING] You tried adding a tool that already exists, so updating the tool '{tool_name}'"+color.END)
|
168 |
+
else:
|
169 |
+
self.tools[tool_name] = tool
|
170 |
+
self.index[tool_name] = {'num_examples': 0, 'indices': []}
|
171 |
+
self.add_example(tool, self.th)
|
172 |
+
print(color.GREEN+f"[SUCCESS] Added the tool '{tool_name}'"+color.END)
|
173 |
+
|
174 |
+
def add_example(self, tool, no_of_eg):
|
175 |
+
'''
|
176 |
+
On addition of new tool or replenishing examples on deletion, this function gets called to add the new example in self.examples and modifies index list accordingly.
|
177 |
+
|
178 |
+
Parameters
|
179 |
+
----------
|
180 |
+
- tool : json (format described above)
|
181 |
+
- no_of_eg : int
|
182 |
+
|
183 |
+
Returns
|
184 |
+
----------
|
185 |
+
None
|
186 |
+
|
187 |
+
Modifies
|
188 |
+
----------
|
189 |
+
self.examples
|
190 |
+
self.index
|
191 |
+
'''
|
192 |
+
tool_name = tool['tool_name']
|
193 |
+
try:
|
194 |
+
ex = self.examples[:3]
|
195 |
+
except:
|
196 |
+
ex = self.examples
|
197 |
+
message = create_prompt_for_new_example(list(self.tools.values()), tool, ex, n=no_of_eg)
|
198 |
+
res = client_conn(message, model_name_tr)
|
199 |
+
res = res.choices[0].message.content
|
200 |
+
try:
|
201 |
+
new_examples = json.loads(res)
|
202 |
+
except:
|
203 |
+
new_examples = get_parsed_json(res)
|
204 |
+
for example in new_examples:
|
205 |
+
tool_calls = example['answer']
|
206 |
+
for tool in tool_calls:
|
207 |
+
new_tool_name = tool['tool_name']
|
208 |
+
self.index[new_tool_name]['num_examples'] += 1
|
209 |
+
self.index[new_tool_name]['indices'].append(len(self.examples))
|
210 |
+
self.examples.append(example)
|
211 |
+
self.similarity_retriever()
|
212 |
+
|
213 |
+
def modify_example(self, tool):
|
214 |
+
'''
|
215 |
+
On modification of a tool, this function gets called to modify the examples where the tool is used.
|
216 |
+
|
217 |
+
Parameters
|
218 |
+
----------
|
219 |
+
None
|
220 |
+
|
221 |
+
Returns
|
222 |
+
----------
|
223 |
+
None
|
224 |
+
|
225 |
+
Modifies
|
226 |
+
----------
|
227 |
+
self.examples
|
228 |
+
'''
|
229 |
+
tool_name = tool["tool_name"]
|
230 |
+
indices = self.index[tool_name]["indices"]
|
231 |
+
relevant_examples = []
|
232 |
+
for ind in indices:
|
233 |
+
relevant_examples.append(self.examples[ind])
|
234 |
+
message = create_prompt_for_modified_example(
|
235 |
+
list(self.tools.values()), tool, relevant_examples
|
236 |
+
)
|
237 |
+
res = client_conn(message, model_name_tr)
|
238 |
+
res = res.choices[0].message.content
|
239 |
+
try:
|
240 |
+
examples = json.loads(res)
|
241 |
+
except:
|
242 |
+
examples = get_parsed_json(res)
|
243 |
+
for i in range(len(examples)):
|
244 |
+
self.examples[indices[i]] = examples[i]
|
245 |
+
|
246 |
+
print(color.GREEN + f"[SUCCESS] Modified Examples!" + color.END)
|
247 |
+
self.similarity_retriever()
|
248 |
+
|
249 |
+
def update_tool(self, tool):
|
250 |
+
'''
|
251 |
+
On modification of a tool, this function gets called update the tool.
|
252 |
+
|
253 |
+
Parameters
|
254 |
+
----------
|
255 |
+
tool : json (format described above)
|
256 |
+
|
257 |
+
Returns
|
258 |
+
-------
|
259 |
+
None
|
260 |
+
|
261 |
+
Modifies
|
262 |
+
--------
|
263 |
+
self.tools
|
264 |
+
'''
|
265 |
+
# self.check_json(tool)
|
266 |
+
tool_name = tool['tool_name']
|
267 |
+
if tool_name in self.tools.keys():
|
268 |
+
self.modify_example(tool)
|
269 |
+
self.tools[tool_name] = tool
|
270 |
+
print(color.GREEN+f"[SUCCESS] Updated the tool '{tool_name}'"+color.END)
|
271 |
+
else:
|
272 |
+
print(color.YELLOW+f"[WARNING] You tried updating a tool that does not exist, so added the tool '{tool_name}'"+color.END)
|
273 |
+
self.add_tool(tool)
|
274 |
+
|
275 |
+
def replenish_examples(self):
|
276 |
+
'''
|
277 |
+
On deletion of any new tool if number of examples for other tools goes below threshold, this function gets called to create examples.
|
278 |
+
|
279 |
+
Parameters
|
280 |
+
----------
|
281 |
+
None
|
282 |
+
|
283 |
+
Returns
|
284 |
+
-------
|
285 |
+
None
|
286 |
+
|
287 |
+
Modifies
|
288 |
+
--------
|
289 |
+
None
|
290 |
+
'''
|
291 |
+
for i,tool in enumerate(self.index):
|
292 |
+
if ((self.index[tool]['num_examples']<self.th) and (len(self.tools)>4)):
|
293 |
+
self.add_example(self.tools[tool], self.th-self.index[tool]['num_examples'])
|
294 |
+
|
295 |
+
def delete_tool(self, tool_name):
|
296 |
+
'''
|
297 |
+
On deletion of any new tool, this function gets called to delete the new tool in self.index and remove the respective examples.
|
298 |
+
|
299 |
+
Parameters
|
300 |
+
----------
|
301 |
+
- tool_name : str
|
302 |
+
|
303 |
+
Returns
|
304 |
+
-------
|
305 |
+
None
|
306 |
+
|
307 |
+
Modifies
|
308 |
+
--------
|
309 |
+
self.index
|
310 |
+
self.examples
|
311 |
+
'''
|
312 |
+
if tool_name not in self.tools.keys():
|
313 |
+
print(color.RED+"[ERROR] You tried deleting a tool that does not exist."+color.END)
|
314 |
+
else:
|
315 |
+
indices = self.index[tool_name]['indices']
|
316 |
+
del self.index[tool_name]
|
317 |
+
for idx, tool in enumerate(list(self.tools.values())):
|
318 |
+
if tool['tool_name'] == tool_name:
|
319 |
+
del self.tools[tool_name]
|
320 |
+
break
|
321 |
+
if len(indices) != 0:
|
322 |
+
for idx, index in enumerate(indices):
|
323 |
+
del self.examples[index-idx]
|
324 |
+
self.index = {}
|
325 |
+
self.build_index()
|
326 |
+
print(color.GREEN+f"[SUCCESS] Deleted the tool '{tool_name}'"+color.END)
|
327 |
+
self.replenish_examples()
|
328 |
+
self.similarity_retriever()
|
329 |
+
|
330 |
+
def similarity_retriever(self):
|
331 |
+
'''
|
332 |
+
On addition of any new example, this function gets called to create the new hnsw index for queries.
|
333 |
+
|
334 |
+
Parameters
|
335 |
+
----------
|
336 |
+
None
|
337 |
+
|
338 |
+
Returns
|
339 |
+
-------
|
340 |
+
None
|
341 |
+
|
342 |
+
Modifies
|
343 |
+
--------
|
344 |
+
self.query_embeddings
|
345 |
+
self.queries
|
346 |
+
self.search_index
|
347 |
+
'''
|
348 |
+
self.query_embeddings, self.queries = create_example_query_embeddings(self.examples)
|
349 |
+
self.search_index = create_hnsw_index(np.array(self.query_embeddings))
|
350 |
+
|
351 |
+
# ------------------------------------------important functions------------------------------------------------------------
|
352 |
+
|
353 |
+
|
354 |
+
def read_file(path):
|
355 |
+
"""
|
356 |
+
parameters
|
357 |
+
----------
|
358 |
+
- path: str
|
359 |
+
path of the file to read in json.
|
360 |
+
|
361 |
+
returns
|
362 |
+
---------
|
363 |
+
- file: object
|
364 |
+
the json file object.
|
365 |
+
"""
|
366 |
+
|
367 |
+
with open(path, "r") as f:
|
368 |
+
file = json.load(f)
|
369 |
+
return file
|
370 |
+
|
371 |
+
|
372 |
+
def create_query_embedding(query):
|
373 |
+
"""
|
374 |
+
Encodes the query to get its embedding.
|
375 |
+
|
376 |
+
parameters
|
377 |
+
---------
|
378 |
+
- query: str
|
379 |
+
|
380 |
+
returns
|
381 |
+
---------
|
382 |
+
- embedding: numpy array
|
383 |
+
embedding of the query.
|
384 |
+
|
385 |
+
"""
|
386 |
+
embedding = biencoder.encode([query], normalize_embeddings=True)[0]
|
387 |
+
return embedding
|
388 |
+
|
389 |
+
|
390 |
+
def create_example_query_embeddings(examples):
|
391 |
+
"""
|
392 |
+
creates query embeddings and saves it.
|
393 |
+
|
394 |
+
parameters
|
395 |
+
----------
|
396 |
+
- examples: list
|
397 |
+
List of examples in json format.
|
398 |
+
|
399 |
+
returns
|
400 |
+
---------
|
401 |
+
- query_embeddings: list
|
402 |
+
a list of query embeddings.
|
403 |
+
|
404 |
+
- answers: list
|
405 |
+
a list of answers corresponding to each query.
|
406 |
+
|
407 |
+
- queries: list
|
408 |
+
a list of queries.
|
409 |
+
|
410 |
+
"""
|
411 |
+
query_embeddings = []
|
412 |
+
answers = []
|
413 |
+
queries = []
|
414 |
+
for example in examples:
|
415 |
+
query = example["query"]
|
416 |
+
answer = example["answer"]
|
417 |
+
queries.append(query)
|
418 |
+
query_embedding = create_query_embedding(query)
|
419 |
+
query_embeddings.append(query_embedding)
|
420 |
+
answers.append(answer)
|
421 |
+
np.save("query_embeddings.npy", query_embeddings)
|
422 |
+
return query_embeddings, queries
|
423 |
+
|
424 |
+
|
425 |
+
def create_hnsw_index(embedding, M=16, efC=100):
|
426 |
+
"""
|
427 |
+
creates the HNSW index.
|
428 |
+
|
429 |
+
parameters
|
430 |
+
----------
|
431 |
+
- embedding: list
|
432 |
+
query embedding
|
433 |
+
|
434 |
+
- M: int
|
435 |
+
default = 16
|
436 |
+
|
437 |
+
- efc: int
|
438 |
+
default = 100
|
439 |
+
|
440 |
+
returns
|
441 |
+
----------
|
442 |
+
- index: object
|
443 |
+
"""
|
444 |
+
embeddings = embedding
|
445 |
+
num_dim = embeddings.shape[1]
|
446 |
+
ids = np.arange(embeddings.shape[0])
|
447 |
+
index = hnswlib.Index(space="ip", dim=num_dim)
|
448 |
+
index.init_index(max_elements=embeddings.shape[0], ef_construction=efC, M=M)
|
449 |
+
index.add_items(embeddings, ids)
|
450 |
+
return index
|
451 |
+
|
452 |
+
|
453 |
+
def find_nearest_neighbors(query_embedding, queries, search_index):
|
454 |
+
"""
|
455 |
+
Finds the k nearest neighbors using cosine similarity.
|
456 |
+
parameters
|
457 |
+
----------
|
458 |
+
- query_embedding: list
|
459 |
+
the query embedding whose similarity check has to be made.
|
460 |
+
|
461 |
+
- queries: list
|
462 |
+
a list of queries in the examples.
|
463 |
+
|
464 |
+
- search_index: object
|
465 |
+
|
466 |
+
returns
|
467 |
+
----------
|
468 |
+
- query_list: list
|
469 |
+
a list of similar queries.
|
470 |
+
"""
|
471 |
+
search_index.set_ef(EF)
|
472 |
+
labels, distances = search_index.knn_query(
|
473 |
+
query_embedding, k=K
|
474 |
+
) # Find the k-nearest neighbors for the query embedding
|
475 |
+
labels = [
|
476 |
+
label
|
477 |
+
for label, distance in zip(labels[0], distances[0])
|
478 |
+
if (1 - distance) >= COSINE_THRESHOLD
|
479 |
+
]
|
480 |
+
query_list = [queries[i] for i in labels]
|
481 |
+
return query_list
|
482 |
+
|
483 |
+
|
484 |
+
def rerank_queries_with_cross_encoder(query, chunks):
|
485 |
+
"""
|
486 |
+
Sorts the chunks based on their scores in descending order.
|
487 |
+
parameters
|
488 |
+
---------
|
489 |
+
- query: str
|
490 |
+
- chunks: list
|
491 |
+
the list of similar chunks
|
492 |
+
returns
|
493 |
+
---------
|
494 |
+
- sorted_chunks: list
|
495 |
+
the response after reranking.
|
496 |
+
"""
|
497 |
+
pairs = [(query, chunk) for chunk in chunks]
|
498 |
+
scores = cross_encoder.predict(pairs)
|
499 |
+
sorted_chunks = [chunk for _, chunk in sorted(zip(scores, chunks), reverse=True)]
|
500 |
+
return sorted_chunks
|
501 |
+
|
502 |
+
|
503 |
+
def rerank_queries_with_cross_encoder(query, chunks):
|
504 |
+
"""
|
505 |
+
Sorts the chunks based on their scores in descending order.
|
506 |
+
parameters
|
507 |
+
---------
|
508 |
+
- query: str
|
509 |
+
- chunks: list
|
510 |
+
the list of similar chunks
|
511 |
+
returns
|
512 |
+
---------
|
513 |
+
- sorted_chunks: list
|
514 |
+
the response after reranking.
|
515 |
+
"""
|
516 |
+
pairs = [(query, chunk) for chunk in chunks]
|
517 |
+
scores = cross_encoder.predict(pairs)
|
518 |
+
sorted_chunks = [chunk for _, chunk in sorted(zip(scores, chunks), reverse=True)]
|
519 |
+
return sorted_chunks
|
520 |
+
|
521 |
+
|
522 |
+
# -------------------------------------------fetch topk examples--------------------------------------------------------------
|
523 |
+
|
524 |
+
|
525 |
+
def get_index(queries, topk_queries):
|
526 |
+
"""
|
527 |
+
Fetches the topk_indices given topk queries.
|
528 |
+
|
529 |
+
parameters:
|
530 |
+
- queries: list
|
531 |
+
A list of all queries.
|
532 |
+
- topk_queries: list
|
533 |
+
A list of topk queries.
|
534 |
+
|
535 |
+
returns:
|
536 |
+
- index: list of int
|
537 |
+
"""
|
538 |
+
index = []
|
539 |
+
for i in topk_queries:
|
540 |
+
index.append(queries.index(i))
|
541 |
+
return index
|
542 |
+
|
543 |
+
|
544 |
+
def get_topk_examples(topk_index, examples):
|
545 |
+
"""
|
546 |
+
Fetches topk examples from the examples given indices of topk examples.
|
547 |
+
parameters
|
548 |
+
----------
|
549 |
+
- topk_index: int
|
550 |
+
list of indexes of topk tools.
|
551 |
+
|
552 |
+
- examples: list
|
553 |
+
list of all examples.
|
554 |
+
|
555 |
+
returns
|
556 |
+
----------
|
557 |
+
- res: list
|
558 |
+
list of topk examples.
|
559 |
+
"""
|
560 |
+
|
561 |
+
res = []
|
562 |
+
for index in topk_index:
|
563 |
+
res.append(examples[index])
|
564 |
+
return res
|
565 |
+
|
566 |
+
|
567 |
+
def get_topk_given_query(query, queries, search_index, examples):
|
568 |
+
'''
|
569 |
+
fetches topk examples given the queries.
|
570 |
+
parameters
|
571 |
+
----------
|
572 |
+
- query: str
|
573 |
+
user query
|
574 |
+
|
575 |
+
- queries: list
|
576 |
+
a list of all queries.
|
577 |
+
|
578 |
+
- search_index:
|
579 |
+
index object
|
580 |
+
|
581 |
+
- examples: list
|
582 |
+
a list of all examples.
|
583 |
+
returns
|
584 |
+
-----------
|
585 |
+
- topk_examples: list
|
586 |
+
a list of topk examples.
|
587 |
+
'''
|
588 |
+
query_embedding = create_query_embedding(query)
|
589 |
+
topk_queries = find_nearest_neighbors(query_embedding, queries, search_index)
|
590 |
+
ranked_topk_queries = rerank_queries_with_cross_encoder(query, topk_queries)
|
591 |
+
topk_indices = get_index(queries,ranked_topk_queries)
|
592 |
+
topk_examples = get_topk_examples(topk_indices, examples)
|
593 |
+
return topk_examples
|
594 |
+
|
595 |
+
|
596 |
+
# ---------------------------------------------------prompt generation functions-------------------------------------------------
|
597 |
+
def client_conn(message, model_name):
|
598 |
+
'''
|
599 |
+
Generates an API call instant.
|
600 |
+
parameters
|
601 |
+
----------
|
602 |
+
- message: list
|
603 |
+
A list of conversation between ChatGPT and user.
|
604 |
+
|
605 |
+
returns
|
606 |
+
----------
|
607 |
+
- completion: object
|
608 |
+
An API instant.
|
609 |
+
'''
|
610 |
+
# please don't change the timeout as example generation is time consuming
|
611 |
+
client = OpenAI(api_key=API_KEY, timeout=120, max_retries=2)
|
612 |
+
completion = client.chat.completions.create(
|
613 |
+
model=model_name,
|
614 |
+
messages=message,
|
615 |
+
temperature=0.2
|
616 |
+
)
|
617 |
+
return completion
|
618 |
+
|
619 |
+
def create_prompt_for_query(user_query, examples, tools):
|
620 |
+
message = [
|
621 |
+
{
|
622 |
+
"role": "system",
|
623 |
+
"content": "The following is a friendly conversation between a human and an AI. The AI is professional and parses user input to several tasks. If the AI does not know the answer to a question, it truthfully says it does not know. The AI will be provided with a set of tools their descriptions and the argument in them. Here is the list of tools:"+ json.dumps(tools) + " \n Provide the answer in the exact format as given in the following examples. \nExamples"
|
624 |
+
}
|
625 |
+
]
|
626 |
+
for example in examples:
|
627 |
+
query = example['query']
|
628 |
+
answer = example['answer']
|
629 |
+
user_prompt = "Query: "+ str(query)
|
630 |
+
assistant_prompt = str(answer)
|
631 |
+
message.append(
|
632 |
+
{
|
633 |
+
"role" : "user",
|
634 |
+
"content": user_prompt
|
635 |
+
})
|
636 |
+
message.append(
|
637 |
+
{
|
638 |
+
"role" : "assistant",
|
639 |
+
"content": assistant_prompt
|
640 |
+
})
|
641 |
+
|
642 |
+
message.append(
|
643 |
+
{
|
644 |
+
"role":"user",
|
645 |
+
"content":"Use the above tools to learn how to use the tool on any query. Analyse how to parse the query and extract the correct information and place in the argument name and value. Use all the required tools and arguments in correct order of its calling based on the query and your learning from all the examples. Do not assume any value, you can take the value from query or the previous called tool as shown in the examples. Also focus on the allowed values argument present in tool definition."
|
646 |
+
})
|
647 |
+
message.append({
|
648 |
+
"role" : "user",
|
649 |
+
"content" : "Now its your task to respond to the user queries in the same format as that in the above examples which is json."
|
650 |
+
})
|
651 |
+
message.append({
|
652 |
+
"role" : "user",
|
653 |
+
"content" : "Query: "+ user_query
|
654 |
+
})
|
655 |
+
message.append(
|
656 |
+
{
|
657 |
+
"role":"system",
|
658 |
+
"content": "Generate the answer in a json format only. Enclose the strings in double quotes"
|
659 |
+
})
|
660 |
+
|
661 |
+
return message
|
662 |
+
|
663 |
+
|
664 |
+
def create_prompt_zero_shot(user_query, tools):
|
665 |
+
'''
|
666 |
+
Creates the prompt given user query, single examples and multi examples.
|
667 |
+
parameters
|
668 |
+
----------
|
669 |
+
- user_query: str
|
670 |
+
the user query.
|
671 |
+
|
672 |
+
- single_example: list
|
673 |
+
the list of single tool examples.
|
674 |
+
|
675 |
+
- multi_example: list
|
676 |
+
the list of multi tiik examples.
|
677 |
+
|
678 |
+
returns
|
679 |
+
----------
|
680 |
+
- message: list
|
681 |
+
the list of user prompts.
|
682 |
+
'''
|
683 |
+
message = [
|
684 |
+
{
|
685 |
+
"role": "system",
|
686 |
+
"content": "You are a intelligent AI agent specialized in giving the tool responses given a dictionary of tools. Here is the dictionary of tools: "+ json.dumps(tools)
|
687 |
+
}
|
688 |
+
]
|
689 |
+
message.append({
|
690 |
+
"role" : "user",
|
691 |
+
"content" : '''
|
692 |
+
Now its your task to respond to the user queries in the format given below
|
693 |
+
FORMAT:[{"tool_name": "...", "arguments": [{"argument_name": "...", "argument_value": ... (depending on the argument_type)}, ...]}, ...]
|
694 |
+
To reference the value of the ith tool in the chain, use $$PREV[i] as argument value. i = 0, 1, .. j-1; j = current tool’s index in the array If the query could not be answered with the given set of tools, output an empty list instead.
|
695 |
+
Output in the JSON format
|
696 |
+
'''
|
697 |
+
})
|
698 |
+
message.append({
|
699 |
+
"role" : "user",
|
700 |
+
"content" : "Query: "+ user_query
|
701 |
+
})
|
702 |
+
return message
|
703 |
+
|
704 |
+
|
705 |
+
def create_prompt_for_modified_example(old_tools, modified_tool, relevant_examples):
|
706 |
+
message = [
|
707 |
+
{
|
708 |
+
"role":"system",
|
709 |
+
"content":"You are an intelligent AI Agent specialized in modifying the old data and generating the new relevant data."
|
710 |
+
}
|
711 |
+
]
|
712 |
+
message.append({
|
713 |
+
"role":"user",
|
714 |
+
"content":"Given a list of old tools : " + json.dumps(old_tools) + "Let us say that I modified the tool" + "'" + modified_tool['tool_name'] + "'" + "to be" + json.dumps(modified_tool)+"""
|
715 |
+
Now your task is to modify the following examples where this tool was used according to its new definition keeping in mind the new schema of json mentioned above.
|
716 |
+
""" + json.dumps(relevant_examples)
|
717 |
+
})
|
718 |
+
message.append({
|
719 |
+
"role":"system",
|
720 |
+
"content":"Your response should be in json format only with the strings enclosed in double quotes ready to go in json.loads"
|
721 |
+
})
|
722 |
+
return message
|
723 |
+
# ---------------------------------------------------------------------------------------------------------------------------
|
724 |
+
|
725 |
+
|
726 |
+
def create_prompt_for_new_example(old_tools, new_tool, examples, n=no_of_examples):
|
727 |
+
message = [
|
728 |
+
{
|
729 |
+
"role":"system",
|
730 |
+
"content":"You are an intelligent AI Agent specialized in generating the new relevant data."
|
731 |
+
}
|
732 |
+
]
|
733 |
+
message.append({
|
734 |
+
"role":"user",
|
735 |
+
"content":"Given a list of old tools : " + json.dumps(old_tools) + "and a new tool" + "'" + new_tool['tool_name'] + "'" + " to be " + json.dumps(new_tool)+"""
|
736 |
+
Now your task is to create """+str(n)+""" examples of the usage of the new tool along with any of the tools from the old tool list, similar to the following example:.
|
737 |
+
""" + json.dumps(examples)
|
738 |
+
})
|
739 |
+
message.append({
|
740 |
+
"role":"system",
|
741 |
+
"content":"Your response should be in json format with the strings enclosed in double quotes. Note that To reference the value of the ith tool in the chain, use $$PREV[i] as argument value. i = 0, 1, .. j-1; j = current tool’s index in the array If the query could not be answered with the given set of tools, output an empty list instead."
|
742 |
+
})
|
743 |
+
return message
|
744 |
+
# -------------------------------------------------retriever---------------------------------------------------------------------
|
745 |
+
def create_tool_str(tools):
|
746 |
+
tool_str = ''
|
747 |
+
for tool in tools:
|
748 |
+
tool_str += f"Tool: {tool['tool_name']}, Desc: {tool['tool_description']}\n"
|
749 |
+
return tool_str
|
750 |
+
|
751 |
+
def tool_retriever_prompt(tool_str,user_query):
|
752 |
+
message=[
|
753 |
+
{"role": "system", "content": "You are an intelligent assistant. Please help the user below."},
|
754 |
+
{"role": "user", "content": f'''You are given the following set of tools:\n {tool_str} \n Can you please figure out which tools the query "{user_query}" will require to solve, out of these tools? Please return only the tool names inside []. If it does not need any tool, return an empty list'''}]
|
755 |
+
return message
|
756 |
+
|
757 |
+
|
758 |
+
def tool_retriever(tools, user_query):
|
759 |
+
tool_str = create_tool_str(tools)
|
760 |
+
message = tool_retriever_prompt(tool_str, user_query)
|
761 |
+
output = client_conn(message, model_name_tr)
|
762 |
+
output = output.choices[0].message.content
|
763 |
+
list_delim=output[output.find('[')+1:output.find(']')]
|
764 |
+
tools_retrieved = set()
|
765 |
+
for i in list_delim.split(','):
|
766 |
+
if (i.strip()!=''):
|
767 |
+
tools_retrieved.add(i.strip().replace('\'','').replace('\"',''))
|
768 |
+
return tools_retrieved
|
769 |
+
|
770 |
+
|
771 |
+
def final_tools(tools, tool_names):
|
772 |
+
tool = []
|
773 |
+
for tool_name in tool_names:
|
774 |
+
tool.append(tools[tool_name])
|
775 |
+
for tool_check in list(tools.values()):
|
776 |
+
if not tool_check["argument_list"]:
|
777 |
+
tool.append(tool_check)
|
778 |
+
return tool
|
779 |
+
|
780 |
+
|
781 |
+
# -------------------------------------------------------bonus section prompts---------------------------------------------------------------
|
782 |
+
def create_prompt_for_query_bonus(user_query, examples, tools):
|
783 |
+
message = [
|
784 |
+
{
|
785 |
+
"role": "system",
|
786 |
+
"content": f"""The following is a friendly conversation between a human and an AI.
|
787 |
+
The AI is professional and parses user input to several tasks. If the AI does not
|
788 |
+
know the answer to a question, it truthfully says it does not know. The AI will be
|
789 |
+
provided with a set of tools their descriptions and the argument in them. Here is
|
790 |
+
the list of tools:"+ {json.dumps(tools)} + "\n Provide the answer in the
|
791 |
+
exact format as given in the following examples. \nExamples """
|
792 |
+
}
|
793 |
+
]
|
794 |
+
for example in examples:
|
795 |
+
query = example['query']
|
796 |
+
answer = example['answer']
|
797 |
+
user_prompt = "Query: "+ str(query)
|
798 |
+
assistant_prompt = str(answer)
|
799 |
+
message.append(
|
800 |
+
{
|
801 |
+
"role" : "user",
|
802 |
+
"content": user_prompt
|
803 |
+
})
|
804 |
+
message.append(
|
805 |
+
{
|
806 |
+
"role" : "assistant",
|
807 |
+
"content": assistant_prompt
|
808 |
+
})
|
809 |
+
|
810 |
+
message.append(
|
811 |
+
{
|
812 |
+
"role":"user",
|
813 |
+
"content":"Use the above tools to learn how to use the tool on any query. Analyse how to parse the query and extract the correct information and place in the argument name and value. Use all the required tools and arguments in correct order of its calling based on the query and your learning from all the examples. Do not assume any value, you can take the value from query or the previous called tool as shown in the examples. Also focus on the allowed values argument present in tool definition."
|
814 |
+
})
|
815 |
+
message.append(
|
816 |
+
{
|
817 |
+
"role":"user",
|
818 |
+
"content":f"After producing the list of tools, analyze the query and figure out whether it requires the combination of tool outputs via mathematical operations, iterations, conditional logic etc. or not. In case it does, use the lambda function to produce the required results. Examples of such queries are given below: \n "
|
819 |
+
})
|
820 |
+
|
821 |
+
message.append(
|
822 |
+
{
|
823 |
+
"role":"user",
|
824 |
+
"content":f"Find all tasks created by user 'USER-321' and check if there are more than 10 such tasks"
|
825 |
+
}
|
826 |
+
)
|
827 |
+
message.append(
|
828 |
+
{
|
829 |
+
"role":"assistant",
|
830 |
+
"content":"""
|
831 |
+
"answer": [
|
832 |
+
{
|
833 |
+
"tool_name": "search_object_by_name",
|
834 |
+
"arguments": [
|
835 |
+
{
|
836 |
+
"argument_name": "query",
|
837 |
+
"argument_value": "USER-321"
|
838 |
+
}
|
839 |
+
]
|
840 |
+
},
|
841 |
+
{
|
842 |
+
"tool_name": "works_list",
|
843 |
+
"arguments": [
|
844 |
+
{
|
845 |
+
"argument_name": "created_by",
|
846 |
+
"argument_value": [
|
847 |
+
"$$PREV[0]"
|
848 |
+
]
|
849 |
+
},
|
850 |
+
{
|
851 |
+
"argument_name": "type",
|
852 |
+
"argument_value": [
|
853 |
+
"task"
|
854 |
+
]
|
855 |
+
}
|
856 |
+
]},
|
857 |
+
{
|
858 |
+
"tool_name": "lambda",
|
859 |
+
"arguments": [
|
860 |
+
{
|
861 |
+
"argument_name": "expression",
|
862 |
+
"argument_value": "lambda $$PREV[1]: True if len($$PREV[1]) > 10 else False"
|
863 |
+
}
|
864 |
+
]
|
865 |
+
}
|
866 |
+
]
|
867 |
+
"""
|
868 |
+
}
|
869 |
+
)
|
870 |
+
|
871 |
+
message.append({
|
872 |
+
"role" : "user",
|
873 |
+
"content" : "Now its your task to respond to the user queries in the same format as that in the above examples which is json. Use the lambda function only when necessary."
|
874 |
+
})
|
875 |
+
message.append({
|
876 |
+
"role" : "user",
|
877 |
+
"content" : "Query: "+ user_query
|
878 |
+
})
|
879 |
+
message.append(
|
880 |
+
{
|
881 |
+
"role":"system",
|
882 |
+
"content": "Generate the answer in a json format only. Enclose the strings in double quotes"
|
883 |
+
})
|
884 |
+
|
885 |
+
return message
|
886 |
+
|
887 |
+
|
888 |
+
|
889 |
+
# -------------------------------------------------miscellaneous functions------------------------------------------------------------
|
890 |
+
def create_tool_dict(tools):
|
891 |
+
tool_dict = {}
|
892 |
+
for i in tools:
|
893 |
+
tool_dict[i["tool_name"]] = i
|
894 |
+
return tool_dict
|
895 |
+
|
896 |
+
def get_parsed_json(text_parsed):
|
897 |
+
ans_list = []
|
898 |
+
json_str = text_parsed.split('```json')
|
899 |
+
for i in json_str:
|
900 |
+
if "```" in i:
|
901 |
+
json_data = i.split("```")[0].strip()
|
902 |
+
if json_data: # Check if the JSON data is not empty
|
903 |
+
json_obj = json.loads(json_data)
|
904 |
+
if type(json_obj)==list:
|
905 |
+
ans_list.extend(json_obj)
|
906 |
+
else:
|
907 |
+
ans_list.append(json_obj)
|
908 |
+
return ans_list
|
909 |
+
# -------------------------------------------------postprocessing---------------------------------------------------------------------
|
910 |
+
def get_json(pred):
|
911 |
+
'''
|
912 |
+
parameters
|
913 |
+
-----------------
|
914 |
+
pred: str
|
915 |
+
Answer predicted by the LLM as a string
|
916 |
+
|
917 |
+
returns
|
918 |
+
-----------------
|
919 |
+
json_pred: list
|
920 |
+
List of dictionaries that represents the input string as a json
|
921 |
+
'''
|
922 |
+
|
923 |
+
try:
|
924 |
+
# Tries to find ```json ``` type json format
|
925 |
+
return json.loads(pred[pred.find('```json'):-1*("".join(reversed(pred)).find('```')+1)])
|
926 |
+
except:
|
927 |
+
# Tries to find first instance of '[' from the left and first instance of ']' from the right, and converts all in between ito a json.
|
928 |
+
try:
|
929 |
+
return json.loads(pred[pred.find('['):-1*("".join(reversed(pred)).find(']')+1)] + ']')
|
930 |
+
except:
|
931 |
+
# Tries to fix keys/ strings being wrapped in single quotes, then tries to decode as above
|
932 |
+
pred= pred.replace('\'','\"')
|
933 |
+
try:
|
934 |
+
return json.loads(pred[pred.find('['):-1*("".join(reversed(pred)).find(']')+1)] + ']')
|
935 |
+
# Tries to check for instances of boolean values true and false, that might have been misspelt as True and False
|
936 |
+
except:
|
937 |
+
pred = pred.replace("True", "true").replace("False", "false")
|
938 |
+
return json.loads(pred[pred.find('['):-1*("".join(reversed(pred)).find(']')+1)] + ']')
|
939 |
+
|
940 |
+
def dict_unwrap(json_pred):
|
941 |
+
# Unwraps a dictionary if GPT-4 outputs one instead of a list
|
942 |
+
if type(json_pred)==dict:
|
943 |
+
for key in json_pred.keys():
|
944 |
+
if type(json_pred[key])==list:
|
945 |
+
print(json_pred[key])
|
946 |
+
return json_pred[key]
|
947 |
+
return []
|
948 |
+
return json_pred
|
949 |
+
|
950 |
+
def list_in_str_handler(json_pred):
|
951 |
+
'''
|
952 |
+
parameters
|
953 |
+
-----------------
|
954 |
+
json_pred: list
|
955 |
+
List of dictionaries that represents the tool call sequence
|
956 |
+
|
957 |
+
-----------------
|
958 |
+
json_pred: list
|
959 |
+
Tool call sequence with string arguments like '[arg_val]' turned into 'arg_val'
|
960 |
+
'''
|
961 |
+
# Iterate over tool call sequence and get argument values
|
962 |
+
for i, tool in enumerate(json_pred):
|
963 |
+
|
964 |
+
for j, arg in enumerate(tool["arguments"]):
|
965 |
+
arg_val= arg["argument_value"]
|
966 |
+
# If value is a string and it starts with [ and ends with ], remove them
|
967 |
+
if (type(arg_val)==str):
|
968 |
+
if arg_val.startswith('[') and arg_val.endswith(']'):
|
969 |
+
arg["argument_value"]=arg_val[1:-1]
|
970 |
+
# If value is a list, then iterate over it and perform similar operations as above
|
971 |
+
elif (type(arg_val)==list):
|
972 |
+
for num_item,arg_val_item in enumerate(arg_val):
|
973 |
+
if (type(arg_val_item)==str):
|
974 |
+
if arg_val_item.startswith('[') and arg_val_item.endswith(']'):
|
975 |
+
arg["argument_value"][num_item]=arg_val_item[1:-1]
|
976 |
+
return json_pred
|
977 |
+
|
978 |
+
def func_name_handler(json_pred,tools,no_arg_tool_list):
|
979 |
+
'''
|
980 |
+
parameters
|
981 |
+
-----------------
|
982 |
+
json_pred: list
|
983 |
+
List of dictionaries that represents the tool call sequence
|
984 |
+
|
985 |
+
tools: dict
|
986 |
+
Dict representing tools
|
987 |
+
|
988 |
+
no_arg_tool_list: list
|
989 |
+
List of tool names that do not have arguments
|
990 |
+
returns
|
991 |
+
-----------------
|
992 |
+
json_pred: list
|
993 |
+
Tool call sequence with arguments with $${function_name} errors removed
|
994 |
+
'''
|
995 |
+
# Iteration variable
|
996 |
+
i=0
|
997 |
+
# WHILE loop is required, len(range()) does not work as the loop condition is kept static while items are inserted into the loop.
|
998 |
+
while(i<len(json_pred)):
|
999 |
+
tool=json_pred[i]
|
1000 |
+
for j, arg in enumerate(tool["arguments"]):
|
1001 |
+
if arg["argument_name"] in tools[tool["tool_name"]]["args"] :
|
1002 |
+
# Check argument value
|
1003 |
+
temp = arg["argument_value"]
|
1004 |
+
if type(temp)==str:
|
1005 |
+
# If argument value starts with $$ but is not $$PREV[i]
|
1006 |
+
if (temp.startswith('$$')) and not temp.startswith('$$PREV['):
|
1007 |
+
# Remove the $$
|
1008 |
+
temp_lowercase_call=temp.lower()[2:]
|
1009 |
+
# Iterate over tools with no arguments to figure the appropriate tool to call
|
1010 |
+
for no_arg_tool in no_arg_tool_list:
|
1011 |
+
if temp_lowercase_call.startswith(no_arg_tool):
|
1012 |
+
# Create tool call
|
1013 |
+
tool_ins = {}
|
1014 |
+
tool_ins['arguments']=[]
|
1015 |
+
tool_ins['tool_name']=no_arg_tool
|
1016 |
+
# Insert tool into the list
|
1017 |
+
json_pred.insert(i,tool_ins)
|
1018 |
+
i+=1
|
1019 |
+
# Iterate over the tools, starting from the tool under consideration
|
1020 |
+
for i_n, tool_n in enumerate(json_pred[i:]):
|
1021 |
+
for j_n, arg_n in enumerate(tool_n["arguments"]):
|
1022 |
+
# Check the argument value
|
1023 |
+
prevset = arg_n["argument_value"]
|
1024 |
+
# If the argument value is
|
1025 |
+
if (type(prevset)==str):
|
1026 |
+
# If the argument is of $$PREV[i] type, and it referenced the returned value of the tool that
|
1027 |
+
# came at the same position as, or after the inserted tool, increment i for it,
|
1028 |
+
if prevset.startswith("$$PREV["):
|
1029 |
+
try:
|
1030 |
+
n=int(prevset[7:-1])
|
1031 |
+
except:
|
1032 |
+
indexing_pos=prevset.find('][')
|
1033 |
+
try:
|
1034 |
+
n=int(prevset[7:indexing_pos])
|
1035 |
+
except:
|
1036 |
+
pass
|
1037 |
+
if n>=i-1:
|
1038 |
+
arg_n["argument_value"]=f"$$PREV[{n}]"
|
1039 |
+
# If the argument value is a list, iterate over the values and perform the same process as above.
|
1040 |
+
elif type(prevset)==list:
|
1041 |
+
for list_num,prev_val in enumerate(prevset):
|
1042 |
+
if prev_val.startswith("$$PREV["):
|
1043 |
+
n=0
|
1044 |
+
try:
|
1045 |
+
n=int(prevset[7:-1])
|
1046 |
+
except:
|
1047 |
+
indexing_pos=prevset.find('][')
|
1048 |
+
try:
|
1049 |
+
n=int(prevset[7:indexing_pos])
|
1050 |
+
except:
|
1051 |
+
pass
|
1052 |
+
if n>=i-1:
|
1053 |
+
arg_n["argument_value"][list_num]=f"$$PREV[{n}]"
|
1054 |
+
arg["argument_value"]=f"$$PREV[{i-1}]"
|
1055 |
+
# otherwise the argument value is a list, iterate over this list, and perform the same operations as above.
|
1056 |
+
elif (type(temp)==list):
|
1057 |
+
for num_arg,temp_el in enumerate(temp):
|
1058 |
+
|
1059 |
+
if type(temp_el)==str:
|
1060 |
+
if (temp_el.startswith('$$')) and not temp_el.startswith('$$PREV'):
|
1061 |
+
temp_lowercase_call=temp_el.lower()[2:]
|
1062 |
+
|
1063 |
+
for no_arg_tool in no_arg_tool_list:
|
1064 |
+
if temp_lowercase_call.startswith(no_arg_tool):
|
1065 |
+
tool_ins = {}
|
1066 |
+
tool_ins['arguments']=[]
|
1067 |
+
tool_ins['tool_name']=no_arg_tool
|
1068 |
+
json_pred.insert(i,tool_ins)
|
1069 |
+
i+=1
|
1070 |
+
|
1071 |
+
for i_n, tool_n in enumerate(json_pred[i:]):
|
1072 |
+
for j_n, arg_n in enumerate(tool_n["arguments"]):
|
1073 |
+
|
1074 |
+
prevset = arg_n["argument_value"]
|
1075 |
+
if (type(prevset) not in [list,bool,float]):
|
1076 |
+
if prevset.startswith("$$PREV[") and int(prevset[7:-1])>=i-1:
|
1077 |
+
n=int(prevset[7:-1])+1
|
1078 |
+
arg_n["argument_value"]=f"$$PREV[{n}]"
|
1079 |
+
|
1080 |
+
elif type(prevset) not in [bool,float]:
|
1081 |
+
for list_num,prev_val in enumerate(prevset):
|
1082 |
+
try:
|
1083 |
+
if prev_val.startswith("$$PREV[") and int(prev_val[7:-1])>=i-1:
|
1084 |
+
n=int(prevset[7:-1])+1
|
1085 |
+
arg_n["argument_value"][list_num]=f"$$PREV[{n}]"
|
1086 |
+
|
1087 |
+
except:
|
1088 |
+
pass
|
1089 |
+
arg["argument_value"][num_arg]=f"$$PREV[{i-1}]"
|
1090 |
+
i+=1
|
1091 |
+
return json_pred
|
1092 |
+
|
1093 |
+
|
1094 |
+
|
1095 |
+
def unknown_tool_remover(json_pred,tools):
|
1096 |
+
for i,tool_call in enumerate(json_pred):
|
1097 |
+
if tool_call["tool_name"] not in tools.keys():
|
1098 |
+
return True
|
1099 |
+
|
1100 |
+
|
1101 |
+
def type_handler(json_pred,tools,array_check,string_check,num_check,bool_check,string_to_boolean):
|
1102 |
+
'''
|
1103 |
+
parameters
|
1104 |
+
-----------------
|
1105 |
+
json_pred: list
|
1106 |
+
List of dictionaries that represents the tool call sequence
|
1107 |
+
|
1108 |
+
tools: dict
|
1109 |
+
Dict representing tools
|
1110 |
+
|
1111 |
+
array_check: list
|
1112 |
+
List of keywords to check for array return types
|
1113 |
+
|
1114 |
+
string_check: list
|
1115 |
+
List of keywords to check for string return types
|
1116 |
+
|
1117 |
+
num_check: list
|
1118 |
+
List of keywords to check for numeral return types
|
1119 |
+
|
1120 |
+
bool_check: list
|
1121 |
+
List of keywords to check for boolean return types
|
1122 |
+
|
1123 |
+
string_to_boolean: dict
|
1124 |
+
Dictionary mapping common representations of True/False values to booleans
|
1125 |
+
|
1126 |
+
returns
|
1127 |
+
-----------------
|
1128 |
+
json_pred: list
|
1129 |
+
Tool call sequence with tool inputs respecting tool input type requirements
|
1130 |
+
'''
|
1131 |
+
for i, tool in enumerate(json_pred):
|
1132 |
+
|
1133 |
+
for j, arg in enumerate(tool["arguments"]):
|
1134 |
+
|
1135 |
+
if arg["argument_name"] in tools[tool["tool_name"]]["args"] :
|
1136 |
+
|
1137 |
+
arg_type = tools[tool["tool_name"]]["args"][arg["argument_name"]]["argument_type"]
|
1138 |
+
|
1139 |
+
temp = json_pred[i]["arguments"][j]["argument_value"]
|
1140 |
+
|
1141 |
+
# Split the argument type by spaces for easier checks later
|
1142 |
+
typcheck = set(arg_type.lower().split(' '))
|
1143 |
+
# To check if arg_type is supposed to be a list, but it is not
|
1144 |
+
if typcheck.intersection(array_check) and type(temp)!=list:
|
1145 |
+
# If argument is not $$PREV type and is a string, convert to array of strings
|
1146 |
+
|
1147 |
+
if not temp.startswith("$$") and typcheck.intersection(string_check) :
|
1148 |
+
temp = [str(temp)]
|
1149 |
+
# If argument type has integer, convert to list of integers
|
1150 |
+
elif typcheck.intersection(num_check):
|
1151 |
+
if type(temp) in [int,float]:
|
1152 |
+
temp = [temp]
|
1153 |
+
else:
|
1154 |
+
try:
|
1155 |
+
temp = [int(temp)]
|
1156 |
+
except:
|
1157 |
+
pass
|
1158 |
+
# If argument type has boolean, convert to list of booleans
|
1159 |
+
elif typcheck.intersection(bool_check):
|
1160 |
+
|
1161 |
+
try:
|
1162 |
+
if type(temp)==str:
|
1163 |
+
temp = [string_to_boolean.get(temp,temp)]
|
1164 |
+
else:
|
1165 |
+
temp=[bool(temp)]
|
1166 |
+
except:
|
1167 |
+
pass
|
1168 |
+
# If argument type is string, convert to string
|
1169 |
+
elif typcheck.intersection(string_check) and type(temp) != str:
|
1170 |
+
# If the argument type is currently a list, convert to string. Only the first argument is going to be considered.
|
1171 |
+
if (type(temp)==list and not temp):
|
1172 |
+
try:
|
1173 |
+
if (not temp[0].startswith("$$")):
|
1174 |
+
temp = str(temp[0])
|
1175 |
+
except:
|
1176 |
+
pass
|
1177 |
+
if (type(temp) in [int,float]):
|
1178 |
+
temp=str(temp)
|
1179 |
+
# If argument type is boolean, convert to boolean
|
1180 |
+
elif typcheck.intersection(bool_check) and type(temp)!= bool :
|
1181 |
+
# If the argument type is currently a list, convert to boolean. Only the first argument is going to be considered.
|
1182 |
+
if (type(temp)==list and temp):
|
1183 |
+
if (type(temp[0])==str):
|
1184 |
+
if not temp[0].startswith("$$"):
|
1185 |
+
try:
|
1186 |
+
temp = string_to_boolean.get(temp[0], temp)
|
1187 |
+
except:
|
1188 |
+
pass
|
1189 |
+
elif (type(temp[0])==bool):
|
1190 |
+
temp=temp[0]
|
1191 |
+
elif (type(temp[0]) in [int,float]):
|
1192 |
+
temp=bool(temp[0])
|
1193 |
+
# If the argument type is currently a string, convert to boolean
|
1194 |
+
elif type(temp)==str:
|
1195 |
+
temp=string_to_boolean.get(temp,temp)
|
1196 |
+
json_pred[i]["arguments"][j]["argument_value"] = temp
|
1197 |
+
|
1198 |
+
else:
|
1199 |
+
print("arg name not match for",arg)
|
1200 |
+
return json_pred
|
1201 |
+
|
1202 |
+
|
1203 |
+
def prev_ret_type_handler(json_pred,tools,array_check,string_check,num_check,bool_check):
|
1204 |
+
'''
|
1205 |
+
parameters
|
1206 |
+
-----------------
|
1207 |
+
json_pred: list
|
1208 |
+
List of dictionaries that represents the tool call sequence
|
1209 |
+
|
1210 |
+
tools: dict
|
1211 |
+
Dict representing tools
|
1212 |
+
|
1213 |
+
array_check: list
|
1214 |
+
List of keywords to check for array return types
|
1215 |
+
|
1216 |
+
string_check: list
|
1217 |
+
List of keywords to check for string return types
|
1218 |
+
|
1219 |
+
num_check: list
|
1220 |
+
List of keywords to check for numeral return types
|
1221 |
+
|
1222 |
+
bool_check: list
|
1223 |
+
List of keywords to check for boolean return types
|
1224 |
+
|
1225 |
+
returns
|
1226 |
+
-----------------
|
1227 |
+
json_pred: list
|
1228 |
+
Tool call sequence with $$PREV[i] type arguments respecting tool input type requirements
|
1229 |
+
'''
|
1230 |
+
# Iterate over list of dictionaries
|
1231 |
+
for i, tool in enumerate(json_pred):
|
1232 |
+
for j, arg in enumerate(tool["arguments"]):
|
1233 |
+
|
1234 |
+
if arg["argument_name"] in tools[tool["tool_name"]]["args"] :
|
1235 |
+
# Fetch argument type, and the current argument value
|
1236 |
+
arg_type = set(tools[tool["tool_name"]]["args"][arg["argument_name"]]["argument_type"].split(' '))
|
1237 |
+
temp = json_pred[i]["arguments"][j]["argument_value"]
|
1238 |
+
# If current argument is a string
|
1239 |
+
if type(temp)== str:
|
1240 |
+
# If it is a $$PREV type argument
|
1241 |
+
if temp.startswith('$$PREV'):
|
1242 |
+
# Identify the return type of the tool call referenced by $$PREV[i],
|
1243 |
+
refer=temp[7:-1]
|
1244 |
+
ref_type= set(tools[json_pred[int(refer)]["tool_name"]]["return_type"].split(' '))
|
1245 |
+
# If the referenced tool does not return an array, but the argument expects one
|
1246 |
+
if not ref_type.intersection(array_check) and arg_type.intersection(array_check):
|
1247 |
+
json_pred[i]["arguments"][j]["argument_value"]=[temp]
|
1248 |
+
# Otherwise, if the argument value is a list, iterate over it
|
1249 |
+
elif (type(temp)==list):
|
1250 |
+
for temp_el in temp:
|
1251 |
+
# Perform similar actions as above
|
1252 |
+
if type(temp_el)==str:
|
1253 |
+
if temp_el.startswith('$$PREV'):
|
1254 |
+
refer=temp_el.lower()[7:-1]
|
1255 |
+
ref_type= set(tools[json_pred[int(refer)]["tool_name"]]["return_type"].split(' '))
|
1256 |
+
if (ref_type.intersection(array_check) and arg_type.intersection(array_check)) or (not ref_type.intersection(array_check) and not arg_type.intersection(array_check)):
|
1257 |
+
json_pred[i]["arguments"][j]["argument_value"]=temp_el
|
1258 |
+
|
1259 |
+
return json_pred
|
1260 |
+
|
1261 |
+
def postprocess(json_pred, tool_data):
|
1262 |
+
'''
|
1263 |
+
parameters
|
1264 |
+
-----------------
|
1265 |
+
json_pred: str
|
1266 |
+
Answer predicted by the LLM as a string
|
1267 |
+
|
1268 |
+
tool_data: dict
|
1269 |
+
dictionary representing the given tools
|
1270 |
+
|
1271 |
+
returns
|
1272 |
+
-----------------
|
1273 |
+
json_pred: list
|
1274 |
+
List of dictionaries that represents the final answer
|
1275 |
+
'''
|
1276 |
+
# turn json in string format into list of dicts
|
1277 |
+
# Get dictionary of tools to simplify work
|
1278 |
+
json_pred = dict_unwrap(json_pred)
|
1279 |
+
tools = {}
|
1280 |
+
for i,tool in enumerate(tool_data):
|
1281 |
+
tools[tool["tool_name"]] = tool
|
1282 |
+
tools[tool["tool_name"]]["args"] = {}
|
1283 |
+
tools[tool["tool_name"]]["return_type"] = tool["return_type"]
|
1284 |
+
for arg in tool["argument_list"]:
|
1285 |
+
tools[tool["tool_name"]]["args"][arg["argument_name"]] = arg
|
1286 |
+
for tool in json_pred:
|
1287 |
+
if not tool.get('arguments',None):
|
1288 |
+
tool["arguments"] = []
|
1289 |
+
# Lists holding keywords to search for in the argument types/ return types
|
1290 |
+
array_check = ["array","list","arrays","lists"]
|
1291 |
+
string_check=["string","str","strings"]
|
1292 |
+
num_check=["integer","int32","number","float","double","float32"]
|
1293 |
+
bool_check=["bool","boolean","true","false"]
|
1294 |
+
# Dictionary mapping common strings to boolean values
|
1295 |
+
string_to_boolean = {"True": True, "False": False, "1": True, "0": False, "yes": True, "no": False, "true" : True, "false": False, 'True':True, 'False':False}
|
1296 |
+
|
1297 |
+
# Get tools for which no argument is required, to fix $${function_name} errors encountered
|
1298 |
+
no_arg_tool_list = []
|
1299 |
+
for i,tool in enumerate(tool_data):
|
1300 |
+
if not tool["argument_list"]:
|
1301 |
+
no_arg_tool_list.append(tool["tool_name"])
|
1302 |
+
|
1303 |
+
try:
|
1304 |
+
if unknown_tool_remover(json_pred, tools):
|
1305 |
+
return []
|
1306 |
+
except:
|
1307 |
+
pass
|
1308 |
+
try:
|
1309 |
+
json_pred = list_in_str_handler(json_pred)
|
1310 |
+
except:
|
1311 |
+
pass
|
1312 |
+
|
1313 |
+
try:
|
1314 |
+
# Fix type errors
|
1315 |
+
json_pred = type_handler(json_pred,tools,array_check,string_check,num_check,bool_check,string_to_boolean)
|
1316 |
+
except:
|
1317 |
+
pass
|
1318 |
+
try:
|
1319 |
+
# Fix $${function_name} errors
|
1320 |
+
json_pred = func_name_handler(json_pred,tools,no_arg_tool_list)
|
1321 |
+
except:
|
1322 |
+
pass
|
1323 |
+
try:
|
1324 |
+
# Fix return types for $$PREV[i] type arguments
|
1325 |
+
json_pred = prev_ret_type_handler(json_pred,tools,array_check,string_check,num_check,bool_check)
|
1326 |
+
except:
|
1327 |
+
pass
|
1328 |
+
|
1329 |
+
return json_pred
|
1330 |
+
|
1331 |
+
tools = read_file(tool_list_path)
|
1332 |
+
examples = read_file(example_path)
|
1333 |
+
tool_dict = create_tool_dict(tools["tools"])
|
1334 |
+
tool_obj = Tools(tool_dict, examples)
|
1335 |
+
|
1336 |
+
def main(query):
|
1337 |
+
if len(tool_obj.examples)<5:
|
1338 |
+
message = create_prompt_zero_shot(query,tool_obj.tools)
|
1339 |
+
res = client_conn(message, model_name_tr)
|
1340 |
+
answer = []
|
1341 |
+
try:
|
1342 |
+
answer = json.loads(res.choices[0].message.content)
|
1343 |
+
answer = postprocess(answer, list(tool_obj.tools.values())) # postprocessing
|
1344 |
+
except:
|
1345 |
+
pass
|
1346 |
+
return answer
|
1347 |
+
|
1348 |
+
topk_examples = get_topk_given_query(query, tool_obj.queries, tool_obj.search_index, tool_obj.examples)
|
1349 |
+
reduced_tools = tool_retriever(list(tool_obj.tools.values()), query)
|
1350 |
+
if not reduced_tools:
|
1351 |
+
return []
|
1352 |
+
tool_list = final_tools(tool_obj.tools, list(tool_obj.tools.keys()))
|
1353 |
+
if 'lambda' in reduced_tools:
|
1354 |
+
message = create_prompt_for_query_bonus(query, topk_examples, tool_list)
|
1355 |
+
else:
|
1356 |
+
message = create_prompt_for_query(query, topk_examples, tool_list)
|
1357 |
+
res = client_conn(message, model_name_tr)
|
1358 |
+
print("GPT4 Response: ",res.choices[0].message.content)
|
1359 |
+
answer = []
|
1360 |
+
try:
|
1361 |
+
answer = json.loads(res.choices[0].message.content)
|
1362 |
+
answer = postprocess(answer, list(tool_obj.tools.values())) # postprocessing
|
1363 |
+
except:
|
1364 |
+
pass
|
1365 |
+
return answer
|