MCPcopy Index your code
hub / github.com/microsoft/JARVIS / get_response

Function get_response

taskbench/inference.py:216–293  ·  view source on GitHub ↗
(url, header, payload, id, reformat, reformat_by, dependency_type, log_detail=False)

Source from the content-addressed store, hash-verified

214 wf.flush()
215
216async def get_response(url, header, payload, id, reformat, reformat_by, dependency_type, log_detail=False):
217 async with aiohttp.ClientSession() as session:
218 async with session.post(url, headers=header, data=payload, timeout=300) as response:
219 resp = await response.json()
220
221 if response.status == 429:
222 raise RateLimitError(f"{resp}")
223 if response.status != 200:
224 raise Exception(f"{resp}")
225
226 if log_detail:
227 logger.info(json.loads(payload)["messages"][0]["content"])
228 logger.info(resp["choices"][0]["message"]["content"])
229
230 oring_content = resp["choices"][0]["message"]["content"]
231 oring_content = oring_content.replace("\n", "")
232 oring_content = oring_content.replace("\_", "_")
233 content = oring_content.replace("\\", "")
234
235 start_pos = content.find("RESULT #:")
236 if start_pos!=-1:
237 content = content[start_pos+len("RESULT #:"):]
238
239 content = content[content.find("{"):content.rfind("}")+1]
240 try:
241 content = json.loads(content)
242 if isinstance(content, list) and len(content):
243 merge_content = {}
244 for c in content:
245 for k, v in c.items():
246 merge_content[k].extend(v) if k in merge_content else merge_content.update({k: v})
247 return content
248 except json.JSONDecodeError as e:
249 if reformat:
250 if dependency_type == "resource":
251 prompt = """Please format the result # RESULT # to a strict JSON format # STRICT JSON FORMAT #. \nRequirements:\n1. Do not change the meaning of task steps and task nodes;\n2. Don't tolerate any possible irregular formatting to ensure that the generated content can be converted by json.loads();\n3. You must output the result in this schema: {"task_steps": [ step description of one or more steps ], "task_nodes": [{"task": "tool name must be from # TOOL LIST #", "arguments": [ a concise list of arguments for the tool. Either original text, or user-mentioned filename, or tag '<node-j>' (start from 0) to refer to the output of the j-th node. ]}]}\n# RESULT #:{{illegal_result}}\n# STRICT JSON FORMAT #:"""
252 else:
253 prompt = """Please format the result # RESULT # to a strict JSON format # STRICT JSON FORMAT #. \nRequirements:\n1. Do not change the meaning of task steps, task nodes and task links;\n2. Don't tolerate any possible irregular formatting to ensure that the generated content can be converted by json.loads();\n3. Pay attention to the matching of brackets. Write in a compact format and avoid using too many space formatting controls;\n4. You must output the result in this schema: {"task_steps": [ "concrete steps, format as Step x: Call xxx tool with xxx: 'xxx' and xxx: 'xxx'" ], "task_nodes": [{"task": "task name must be from # TASK LIST #", "arguments": [ {"name": "parameter name", "value": "parameter value, either user-specified text or the specific name of the tool whose result is required by this node"} ]}], "task_links": [{"source": "task name i", "target": "task name j"}]}\n# RESULT #:{{illegal_result}}\n# STRICT JSON FORMAT #:"""
254 prompt = prompt.replace("{{illegal_result}}", oring_content)
255 payload = json.loads(payload)
256 if reformat_by != "self":
257 payload["model"] = reformat_by
258
259 if log_detail:
260 logger.info(f"{emoji.emojize(':warning:')} #id {id} Illegal JSON format: {content}")
261 logger.info(f"{emoji.emojize(':sparkles:')} #id {id} Detected illegal JSON format, try to reformat by {payload['model']}...")
262
263 payload["messages"][0]["content"] = prompt
264 payload = json.dumps(payload)
265
266 async with aiohttp.ClientSession() as session:
267 async with session.post(url, headers=header, data=payload, timeout=120) as response:
268 resp = await response.json()
269
270 if response.status == 429:
271 raise RateLimitError(f"{resp}")
272 if response.status != 200:
273 raise Exception(f"{resp}")

Callers 1

inferenceFunction · 0.85

Calls 2

RateLimitErrorClass · 0.70
ContentFormatErrorClass · 0.70

Tested by

no test coverage detected