id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
6,228
import logging import os import random import re import time import json import abc from logging import LogRecord from typing import Any import uuid from threading import Lock from colorama import Fore, Style from XAgent.utils import Singleton, TaskSaveItem logger = Logger() class TaskSaveItem: """ This class represents the structure of saved tasks. Attributes: name (str): The name of the task. goal (str): The objective of the task. milestones (List[str]): The steps involved to achieve the task. prior_plan_criticism (str): Any criticism on the initial plan of the task. status (TaskStatusCode): The current status of the task. action_list_summary (str): A summary of all the actions done to achieve the task. posterior_plan_reflection (List[str]): A list containing reflection of the finally decided plan. tool_reflection (List[Dict[str,str]]): A list of dictionaries where each dictionary holds reflection of a tool. """ name: str = "" goal: str = "" milestones: List[str] = field(default_factory=lambda: []) prior_plan_criticism: str = "" status: TaskStatusCode = TaskStatusCode.TODO action_list_summary: str = "" posterior_plan_reflection: List[str] = field(default_factory=lambda: []) tool_reflection: List[Dict[str,str]] = field(default_factory=lambda: []) def load_from_json(self, function_output_item): """Load data from the json representation""" if "subtask name" in function_output_item.keys(): self.name = function_output_item["subtask name"] else: print(f"field subtask name not exist") if "goal" in function_output_item.keys() and "goal" in function_output_item["goal"].keys(): self.goal=function_output_item["goal"]["goal"] else: print(f"field goal.goal not exist") if "goal" in function_output_item.keys() and "criticism" in function_output_item["goal"].keys(): self.prior_plan_criticism=function_output_item["goal"]["criticism"] else: print(f"field goal.criticism not exist") # if "handler" in function_output_item.keys(): # self.handler=function_output_item["handler"] # else: # print(f"field handler not exist") # if "tool_budget" in function_output_item.keys(): # self.tool_budget=function_output_item["tool_budget"] # else: # print(f"field tool_budget not exist") if "milestones" in function_output_item.keys(): self.milestones = function_output_item["milestones"] # if "expected_tools" in function_output_item.keys(): # self.expected_tools = function_output_item["expected_tools"] def to_json(self, posterior=False): """Convert the object to json representation.""" json_data = { "name": self.name, "goal": self.goal, # "handler": self.handler, # "tool_budget": self.tool_budget, "prior_plan_criticsim": self.prior_plan_criticism, "milestones": self.milestones, # "expected_tools": self.expected_tools, "exceute_status": self.status.name, } if posterior: if self.action_list_summary != "": json_data["action_list_summary"] = self.action_list_summary # if self.posterior_plan_reflection != []: # json_data["posterior_plan_reflection"] = self.posterior_plan_reflection # if self.tool_reflection != []: # json_data["tool_reflection"] = self.tool_reflection return json_data def raw(self) -> str: """Convert the object to a raw json string""" return json.dumps(self.to_json(posterior=True), indent=2, ensure_ascii=False) def print_task_save_items( item: TaskSaveItem, ) -> None: logger.typewriter_log( f"Task Name:", Fore.YELLOW, f"{item.name}" ) logger.typewriter_log( f"Task Goal:", Fore.YELLOW, f"{item.goal}" ) logger.typewriter_log( f"Task Prior-Criticism:", Fore.YELLOW, f"{item.prior_plan_criticism}" ) if len(item.posterior_plan_reflection) > 0: logger.typewriter_log( f"Task Posterior-Criticism:", Fore.YELLOW ) for line in item.posterior_plan_reflection: line = line.lstrip("- ") logger.typewriter_log("- ", Fore.GREEN, line.strip()) if len(item.milestones) > 0: logger.typewriter_log( f"Task Milestones:", Fore.YELLOW, ) for line in item.milestones: line = line.lstrip("- ") logger.typewriter_log("- ", Fore.GREEN, line.strip()) # if len(item.expected_tools) > 0: # logger.typewriter_log( # f"Expected Tools:", Fore.YELLOW, # ) # for line in item.expected_tools: # line = f"{line['tool_name']}: {line['reason']}".lstrip("- ") # logger.typewriter_log("- ", Fore.GREEN, line.strip()) if len(item.tool_reflection) > 0: logger.typewriter_log( f"Posterior Tool Reflections:", Fore.YELLOW, ) for line in item.tool_reflection: line = f"{line['target_tool_name']}: {line['reflection']}".lstrip("- ") logger.typewriter_log("- ", Fore.GREEN, line.strip()) logger.typewriter_log( f"Task Status:", Fore.YELLOW, f"{item.status.name}" ) if item.action_list_summary != "": logger.typewriter_log( f"Action Summary:", Fore.YELLOW, f"{item.action_list_summary}" )
null
6,229
import logging import os import random import re import time import json import abc from logging import LogRecord from typing import Any import uuid from threading import Lock from colorama import Fore, Style from XAgent.utils import Singleton, TaskSaveItem logger = Logger() def print_assistant_thoughts( # ai_name: object, assistant_reply_json_valid: object, speak_mode: bool = False, ) -> None: assistant_thoughts_reasoning = None assistant_thoughts_plan = None assistant_thoughts_speak = None assistant_thoughts_criticism = None assistant_thoughts = assistant_reply_json_valid.get("thoughts", {}) assistant_thoughts = assistant_thoughts.get("properties", {}) assistant_thoughts_text = assistant_thoughts.get("thought") if assistant_thoughts: assistant_thoughts_reasoning = assistant_thoughts.get("reasoning") assistant_thoughts_plan = assistant_thoughts.get("plan") assistant_thoughts_criticism = assistant_thoughts.get("criticism") if assistant_thoughts_text is not None and assistant_thoughts_text != "": logger.typewriter_log( f"THOUGHTS:", Fore.YELLOW, f"{assistant_thoughts_text}" ) if assistant_thoughts_reasoning is not None and assistant_thoughts_reasoning != "": logger.typewriter_log("REASONING:", Fore.YELLOW, f"{assistant_thoughts_reasoning}") if assistant_thoughts_plan is not None and len(assistant_thoughts_plan) > 0: logger.typewriter_log("PLAN:", Fore.YELLOW, "") # If it's a list, join it into a string if isinstance(assistant_thoughts_plan, list): assistant_thoughts_plan = "\n".join(assistant_thoughts_plan) elif isinstance(assistant_thoughts_plan, dict): assistant_thoughts_plan = str(assistant_thoughts_plan) # Split the input_string using the newline character and dashes lines = assistant_thoughts_plan.split("\n") for line in lines: line = line.lstrip("- ") logger.typewriter_log("- ", Fore.GREEN, line.strip()) if assistant_thoughts_criticism is not None and assistant_thoughts_criticism != "": logger.typewriter_log("CRITICISM:", Fore.YELLOW, f"{assistant_thoughts_criticism}") return { "thoughts": assistant_thoughts_text, "reasoning": assistant_thoughts_reasoning, "plan": assistant_thoughts_plan, "criticism": assistant_thoughts_criticism, "node_id": uuid.uuid4().hex }
null
6,230
import json from colorama import Fore from XAgent.config import CONFIG from XAgent.agent.base_agent import BaseAgent from XAgent.agent.summarize import summarize_action, summarize_plan, clip_text from XAgent.core import XAgentCoreComponents from XAgent.data_structure.node import ToolNode from XAgent.data_structure.tree import TaskSearchTree from XAgent.inner_loop_search_algorithms.base_search import BaseSearchMethod from XAgent.message_history import Message from XAgent.utils import SearchMethodStatusCode, ToolCallStatusCode CONFIG = XAgentConfig.get_default_config() def summarize_action(action_process:list[dict], task:str,)->(list[str],str): """ Generate a summarized series of actions. Args: action_process (list[dict]): The list of actions to process. task (str): The task name. Returns: str: The string contains a summary of the actions. """ if len(action_process) < 1: return "No steps found" def generate_func_args(args:dict,black_list=[])->str: """ Generate function arguments in the form of strings. Args: args (dict): A dictionary of arguments. black_list (list): A list of forbidden or restricted words or keys in the args dictionary. Returns: str: A string that summarizes the function arguments. """ ret = '' args_len = 0 for k,v in args.items(): if k in black_list: v = '`wrapped`' v_str,v_len = clip_text(str(v),SINGLE_ACTION_MAX_LENGTH-args_len,clip_end=True) if v_len < SINGLE_ACTION_MAX_LENGTH-args_len: ret += f'{k}="{v_str}",' if isinstance(v,str) else f'{k}={v_str},' args_len += v_len else: ret += f'{k}="{v_str}...",' if isinstance(v,str) else f'{k}={v_str}...,' args_len += SINGLE_ACTION_MAX_LENGTH-args_len return ret[:-1] # remove last comma # wrap old content raw_actions = {} accessed_files = [] last_successful_action_index = None last_failed_action_index = None for index,action in zip(range(len(action_process)-1,-1,-1),action_process[::-1]): if last_successful_action_index is None and action['tool_status_code'] == ToolCallStatusCode.TOOL_CALL_SUCCESS: last_successful_action_index = index if last_failed_action_index is None and action['tool_status_code'] == ToolCallStatusCode.TOOL_CALL_FAILED: last_failed_action_index = index command = action["command"]["properties"] if command['name'] == '' or not isinstance(command['args'],dict): continue raw_action = ['`placeholder`','`placeholder`'] if "FileSystem" in command["name"] and "filepath" in command["args"] and action["tool_status_code"] == ToolCallStatusCode.TOOL_CALL_SUCCESS: raw_action[0] = command['name']+f"({generate_func_args(command['args'],black_list=['content','new_content'])})" if command['args']['filepath'] in accessed_files: raw_action[1] = "`Old Content has been wrapped, check latest filesystem calling`" else: raw_action[1] = str(action['tool_output']) accessed_files.append(command["args"]["filepath"]) else: raw_action[0] = command['name']+f"({generate_func_args(command['args'])})" raw_action[1] = str(action['tool_output']) raw_actions[index] = raw_action valid_index = list(raw_actions.keys()) valid_index.sort() ret = {} for index in valid_index: action = action_process[index] if 'summary' not in action: raw_actions_des = '\n'.join([ f'[{k}] {v}' for k,v in action['thoughts']['properties'].items() ] + [ f"[tool_status_code] {action['tool_status_code']}", f"[tool calling] {raw_actions[index][0]}", f"[return] " ]) raw_actions_des += clip_text(raw_actions[index][1],MAX_RETURN_LENGTH-get_token_nums(raw_actions_des))[0] summary,tokens = function_manager('summarize_action', action=raw_actions_des,current_task=task, return_generation_usage=True,) action['summary'] = summary logger.typewriter_log(f"Action summarized in {tokens['completion_tokens']} tokens",Fore.YELLOW) else: summary = action['summary'] act_str = '\n'.join([ f'[{index}] {raw_actions[index][0]}', f"[{index}][summary] {summary['summary']}", f"[{index}][description] {summary['description']}", f"[{index}][status code] {action['tool_status_code']}" ]) if 'failed_reason_and_reflection' in summary and summary['failed_reason_and_reflection'] != '': act_str += f'\n[{index}][failed reason] {summary["failed_reason_and_reflection"]}' # directly adding short returns if len(raw_actions[index][1]) < 1000 and get_token_nums(raw_actions[index][1]) < 150: act_str += f'\n[{index}][return] {raw_actions[index][1]}' ret[index] = act_str reflection = function_manager('actions_reflection', actions=clip_text('\n'.join([ret[i] for i in valid_index]),MAX_RETURN_LENGTH)[0], current_task=task) ret_lenght = {k:get_token_nums(v) for k,v in ret.items()} total_length = sum(ret_lenght.values()) # adding more return to last successful action for i in [last_successful_action_index,last_failed_action_index]: if i is not None and '[return]' not in ret[i]: s = f'\n[{i}][return] {clip_text(raw_actions[i][1],(MAX_RETURN_LENGTH-total_length)//2)[0]}' return_length = get_token_nums(s) ret_lenght[i] += return_length total_length += return_length ret[i] += s key_actions:list = reflection['key_actions'] key_actions.sort(reverse=True) for i in key_actions: if total_length >= MAX_RETURN_LENGTH: break if i in ret and action_process[i]["tool_status_code"] == ToolCallStatusCode.TOOL_CALL_SUCCESS and '[return]' not in ret[i]: s = f'\n[{i}][return] {clip_text(raw_actions[i][1],SINGLE_ACTION_MAX_LENGTH-ret_lenght[i])[0]}' if (tokens := get_token_nums(s))> MAX_RETURN_LENGTH-total_length: continue total_length += tokens ret[i] += s while len(valid_index) > 0: i = valid_index.pop() if total_length >= MAX_RETURN_LENGTH: break if action_process[i]["tool_status_code"] == ToolCallStatusCode.TOOL_CALL_SUCCESS and '[return]' not in ret[i]: s = f'\n[{i}][return] {clip_text(raw_actions[i][1],SINGLE_ACTION_MAX_LENGTH-ret_lenght[i])[0]}' if (tokens := get_token_nums(s))> MAX_RETURN_LENGTH-total_length: continue total_length += tokens ret[i] += s valid_index = list(ret.keys()) valid_index.sort() ordered_rets = [ret[i] for i in valid_index] + [f'[suggestion] {sugg}'for sugg in reflection["suggestions"]] return '\n'.join(ordered_rets) def summarize_plan(plans:dict)->str: """ Generate a summarized plan based on provided plans. Args: plans (dict): The plans to provide. Returns: str: The string contains a summary of the plan. """ summary:list[list] = [] task_ids = [] detailed_info:dict[str,list] = {} current_task_id = None def recursive_summary(plan:dict,): """ Generate a summarized plan in a recursive process. Args: plan (dict): A dictionary of plans. Returns: None """ nonlocal summary nonlocal current_task_id plan_des = [ f'[Task ID] {plan["task_id"]}', f'[Name] {plan["name"]}', f'[Goal] {plan["goal"]}', f'[Status] {plan["exceute_status"]}', ] if current_task_id is None and plan['exceute_status'] == 'DOING': current_task_id = plan['task_id'] if 'milestones' in plan and len(plan['milestones']) > 0: plan_des.extend(['[Milestones]']+['- '+milestone for milestone in plan["milestones"]]) if 'action_list_summary' not in plan and 'prior_plan_criticism' in plan: plan_des.append(f'[Prior Plan Criticism] {plan["prior_plan_criticism"]}') if 'submit_result' in plan and 'args' in plan['submit_result']: submission = plan['submit_result']['args'] plan_des.append(f'[Action Status] {"Success" if submission["result"]["success"] else "Fail"}') # possible too long part action_des = [ '[Action Info]', f"- [Conclusion] {submission['result']['conclusion']}" ] if 'action_list_summary' in plan: action_des.append(f'- [Summary] {plan["action_list_summary"]}') if submission['suggestions_for_latter_subtasks_plan']['need_for_plan_refine']: if submission['suggestions_for_latter_subtasks_plan']['reason'] != '': action_des.append(f"- [Proposal] {submission['suggestions_for_latter_subtasks_plan']['reason']}") detailed_info[plan['task_id']] = action_des task_ids.append(plan['task_id']) summary.append(plan_des) if "subtask" in plan: for subtask in plan["subtask"]: recursive_summary(subtask) recursive_summary(plans) total_tokens = sum([get_token_nums('\n'.join(plan)) for plan in summary]) if current_task_id is None: current_task_id = task_ids[-1] for task_id,plan in zip(task_ids[::-1],summary[::-1]): if task_id <= current_task_id and task_id in detailed_info: if (tokens:=get_token_nums('\n'.join(detailed_info[task_id]))) > MAX_PLAN_LENGTH-total_tokens: continue else: total_tokens += tokens plan.extend(detailed_info[task_id]) # logger.typewriter_log(f'Plan summarized {total_tokens}',Fore.YELLOW) ret = [] for plan in summary: ret.append('\n'.join(plan)) return '\n'.join(ret) class ToolNode(Node): """ Class representing a tool node in the XAgent's data structure. A tool node has a “father” that represents its parent node, "children" that represents its child nodes, and “data” containing metadata about node's status, command, tool's output, and thoughts properties. It also carries a message history and a workspace hash id. """ def __init__(self): """ Initialize a new tool node. Setup father, children, expand_num, data, history, workspace_hash_id attributes for the instance. """ self.father: ToolNode = None self.children: list[ToolNode] = [] self.expand_num = 0 self.data = { "content": "", "thoughts": { "properties": { "thought": "", "reasoning": "", "plan": "", "criticism": "", }, }, "command": { "properties": { "name": "", "args": "", }, }, "tool_output": "", "tool_status_code": ToolCallStatusCode.TOOL_CALL_SUCCESS, } self.history: MessageHistory = MessageHistory() self.workspace_hash_id = "" def process(self): """ Generate a list of data from current node up to root node. Returns: data (List): A list of data from current node up to root node. """ data = [] now_node = self while now_node.father != None: data = [now_node.data] + data now_node = now_node.father return data def to_json(self): """ Convert the data attribute of the instance to a JSON-compatible format. Returns: data (Dict): The data attribute of the instance in a JSON-compatible format. """ data = deepcopy(self.data) data["tool_status_code"] = data["tool_status_code"].name return data def get_depth(self): """ Calculate the depth of current node in the tree. Returns: depth (int): The depth of the node. Return 0 if the node is a root node. """ if self.father == None: return 0 return self.father.get_depth() + 1 def get_subtree_size(self): """ Calculate the size of the subtree rooted at current node. Returns: size (int): The size of the subtree rooted at current node. """ if self.children == []: return 1 now_size = 1 for child in self.children: now_size += child.get_subtree_size() return now_size class Message: """OpenAI Message class. A class representing a message from an agent, a user, or a system function. Attributes: role (MessageRole): Source of the message, can be either 'system', 'user', 'assistant', or 'function'. content (str): The actual content of the message. type (MessageType): The type of message, either 'ai_response' for AI dialogue messages or 'action_result' for results of API calls. function_call (dict): A dictionary representing the method invocation in programmable API calls. """ role: MessageRole content: str type: MessageType | None = None function_call: dict | None = None def raw(self) -> MessageDict: """Extracts raw content of the message, stripping away other metadata. Returns: MessageDict: Dictionary containing 'role' and 'content'. """ data = {"role": self.role, "content": self.content} if self.function_call != None: data["function_call"] = self.function_call return data def to_json(self): """Convert the message into JSON format. Returns: MessageDict: JSON representation of the message. """ return self.raw() def equal(cls, a: Message, b: Message): """Checks if two messages are equal by comparing all their attributes. Args: a (Message): first message to be compared. b (Message): second message to be compared. Returns: bool: Returns True if both messages are equal in all their attributes; False otherwise. """ if a.role != b.role: return False if a.content != b.content: return False if a.type != b.type: return False if a.function_call != b.function_call: return False return True The provided code snippet includes necessary dependencies for implementing the `make_message` function. Write a Python function `def make_message(now_node: ToolNode, max_length, config, now_dealing_task)` to solve the following problem: Function to generate messages for each node. Args: now_node: The current ToolNode instance. task_handler: Handler of the tasks. max_length: Maximum length of the subtask chain. config: The configuration settings. Returns: The sequence of messages for the current node. Here is the function: def make_message(now_node: ToolNode, max_length, config, now_dealing_task): """ Function to generate messages for each node. Args: now_node: The current ToolNode instance. task_handler: Handler of the tasks. max_length: Maximum length of the subtask chain. config: The configuration settings. Returns: The sequence of messages for the current node. """ if CONFIG.enable_summary: terminal_task_info = summarize_plan( now_dealing_task.to_json()) else: terminal_task_info = json.dumps( now_dealing_task.to_json(), indent=2, ensure_ascii=False) message_sequence = [] now_subtask_prompt = f'''Now you will perform the following subtask:\n"""\n{terminal_task_info}\n"""\n''' message_sequence.append(Message("user", now_subtask_prompt)) action_process = now_node.process if config.enable_summary: action_process = summarize_action( action_process, terminal_task_info) user_prompt = f"""The following steps have been performed (you have already done the following and the current file contents are shown below):\n {action_process} """ message_sequence.append(Message("user", user_prompt)) return message_sequence
Function to generate messages for each node. Args: now_node: The current ToolNode instance. task_handler: Handler of the tasks. max_length: Maximum length of the subtask chain. config: The configuration settings. Returns: The sequence of messages for the current node.
6,231
import json from typing import Dict The provided code snippet includes necessary dependencies for implementing the `get_command` function. Write a Python function `def get_command(response_json: Dict)` to solve the following problem: Parses the response and returns the command name and arguments. This function will raise the exception `json.decoder.JSONDecodeError` if the response is not valid JSON. Any other error that occurs is also caught and the function returns an "Error:" message with the exception message. Args: response_json (Dict): The response from the AI in dictionary format. Returns: tuple: The command name and arguments, or some error indication. If the response json dictionary does not contain the 'command' key, or the value of 'command' is not a dictionary, or the 'command' dictionary does not contain the 'name' key, returns a tuple where the first element is 'Error:' and the second element is a string explaining the problem. If some error occurs, returns a tuple where the first element is 'Error:' and the second element is the str of the exception. Raises: json.decoder.JSONDecodeError: If the response is not valid JSON. Exception: If any other error occurs. Here is the function: def get_command(response_json: Dict): """ Parses the response and returns the command name and arguments. This function will raise the exception `json.decoder.JSONDecodeError` if the response is not valid JSON. Any other error that occurs is also caught and the function returns an "Error:" message with the exception message. Args: response_json (Dict): The response from the AI in dictionary format. Returns: tuple: The command name and arguments, or some error indication. If the response json dictionary does not contain the 'command' key, or the value of 'command' is not a dictionary, or the 'command' dictionary does not contain the 'name' key, returns a tuple where the first element is 'Error:' and the second element is a string explaining the problem. If some error occurs, returns a tuple where the first element is 'Error:' and the second element is the str of the exception. Raises: json.decoder.JSONDecodeError: If the response is not valid JSON. Exception: If any other error occurs. """ try: if "command" not in response_json: return "Error:", "Missing 'command' object in JSON" if not isinstance(response_json, dict): return "Error:", f"'response_json' object is not dictionary {response_json}" command = response_json["command"] if not isinstance(command, dict): return "Error:", "'command' object is not a dictionary" if "name" not in command: return "Error:", "Missing 'name' field in 'command' object" command_name = command["name"] # Use an empty dictionary if 'args' field is not present in 'command' object arguments = command.get("args", {}) return command_name, arguments except json.decoder.JSONDecodeError: return "Error:", "Invalid JSON" # All other errors, return "Error: + error message" except Exception as e: return "Error:", str(e)
Parses the response and returns the command name and arguments. This function will raise the exception `json.decoder.JSONDecodeError` if the response is not valid JSON. Any other error that occurs is also caught and the function returns an "Error:" message with the exception message. Args: response_json (Dict): The response from the AI in dictionary format. Returns: tuple: The command name and arguments, or some error indication. If the response json dictionary does not contain the 'command' key, or the value of 'command' is not a dictionary, or the 'command' dictionary does not contain the 'name' key, returns a tuple where the first element is 'Error:' and the second element is a string explaining the problem. If some error occurs, returns a tuple where the first element is 'Error:' and the second element is the str of the exception. Raises: json.decoder.JSONDecodeError: If the response is not valid JSON. Exception: If any other error occurs.
6,232
SYSTEM_PROMPT = '''You are plan-rectify agent, your task is to iteratively rectify a plan of a query. --- Background Information --- PLAN AND SUBTASK: A plan has a tree manner of subtasks: task 1 contains subtasks task 1.1, task 1.2, task 1.3, and task 1.2 contains subtasks 1.2.1, 1.2.2... Please remember: 1.The plan tree has a max width of {{max_plan_tree_width}}, meaning the max subtask count of a task. If max_width=4, the task like 1.4 is valid, but task 1.5 is not valid. 2.The plan tree has a max depth of {{max_plan_tree_depth}}. If max_depth=3, the task like 1.3.2 is valid, but task 1.4.4.5 is not valid. A subtask-structure has the following json component: { "subtask name": string "goal.goal": string, the main purpose of the sub-task should handle, and what will you do to reach this goal? "goal.criticism": string, What problems may the current subtask and goal have? "milestones": list[string]. How to automatically check the sub-task is done? } SUBTASK HANDLE: A task-handling agent will handle all the subtasks as the inorder-traversal. For example: 1. it will handle subtask 1 first. 2. if solved, handle subtask 2. If failed, split subtask 1 as subtask 1.1 1.2 1.3... Then handle subtask 1.1. 3. Handle subtasks recursively, until all subtasks are solved. 4. It is powered by a state-of-the-art LLM, so it can handle many subtasks without using external tools or execute codes. RESOURCES: 1. Internet access for searches and information gathering, search engine and web browsing. 2. A FileSystemEnv to read and write files (txt, code, markdown, latex...) 3. A python interpretor to execute python files together with a pdb debugger to test and refine the code. 4. A ShellEnv to execute bash or zsh command to further achieve complex goals. --- Task Description --- Your task is iteratively rectify a given plan and based on the goals, suggestions and now handling postions. PLAN_REFINE_MODE: At this mode, you will use the given operations to rectify the plan. At each time, use one operation. SUBTASK OPERATION: - split: Split a already handled but failed subtask into subtasks because it is still so hard. The `target_subtask_id` for this operation must be a leaf task node that have no children subtasks, and should provide new splitted `subtasks` of length 2-4. You must ensure the `target_subtask_id` exist, and the depth of new splitted subtasks < {{max_plan_tree_depth}}. - split 1.2 with 2 subtasks will result in create new 1.2.1, 1.2.2 subtasks. - add: Add new subtasks as brother nodes of the `target_subtask_id`. This operation will expand the width of the plan tree. The `target_subtask_id` should point to a now handling subtask or future subtask. - add 1.1 with 2 subtasks will result in create new 1.2, 1.3 subtasks. - add 1.2.1 with 3 subtasks wil result in create new 1.2.2, 1.2.3, 1.2.4 subtasks. - delete: Delete a subtask. The `target_subtask_id` should point to a future/TODO subtask. Don't delete the now handling or done subtask. - delete 1.2.1 will result in delete 1.2.1 subtask. - exit: Exit PLAN_REFINE_MODE and let task-handle agent to perform subtasks. --- Note --- The user is busy, so make efficient plans that can lead to successful task solving. Do not waste time on making irrelevant or unnecessary plans. Don't use search engine if you have the knowledge for planning. Don't divide trivial task into multiple steps. If task is un-solvable, give up and submit the task. *** Important Notice *** - Never change the subtasks before the handling positions, you can compare them in lexicographical order. - Never create (with add or split action) new subtasks that similar or same as the existing subtasks. - For subtasks with similar goals, try to do them together in one subtask with a list of subgoals, rather than split them into multiple subtasks. - Every time you use a operation, make sure the hierarchy structure of the subtasks remians, e.g. if a subtask 1.2 is to "find A,B,C" , then newly added plan directly related to this plan (like "find A", "find B", "find C") should always be added as 1.2.1, 1.2.2, 1.2.3... - You are restricted to give operations in at most 4 times, so the plan refine is not so much. - The task handler is powered by sota LLM, which can directly answer many questions. So make sure your plan can fully utilize its ability and reduce the complexity of the subtasks tree. ''' USER_PROMPT = '''Your task is to choose one of the operators of SUBTASK OPERATION, note that 1.You can only modify the subtask with subtask_id>{{subtask_id}}(not included). 2.If you think the existing plan is good enough, use REFINE_SUBMIT. 3.You can at most perform {{max_step}} operations before REFINE_SUBMIT operation, you have already made {{modify_steps}} steps, watch out the budget. 4.All the plan has a max depth of {{max_plan_tree_depth}}. Be carefull when using SUBTASK_SPLIT. 5. Please use function call to respond to me (remember this!!!). --- Status --- File System Structure: {{workspace_files}} Refine Node Message: {{refine_node_message}} ''' The provided code snippet includes necessary dependencies for implementing the `get_examples_for_dispatcher` function. Write a Python function `def get_examples_for_dispatcher()` to solve the following problem: The example that will be given to the dispatcher to generate the prompt Returns: example_input: the user query or the task example_system_prompt: the system prompt example_user_prompt: the user prompt Here is the function: def get_examples_for_dispatcher(): """The example that will be given to the dispatcher to generate the prompt Returns: example_input: the user query or the task example_system_prompt: the system prompt example_user_prompt: the user prompt """ example_input = "Refine a plan for writing a Python-based calculator." example_system_prompt = SYSTEM_PROMPT example_user_prompt = USER_PROMPT return example_input, example_system_prompt, example_user_prompt
The example that will be given to the dispatcher to generate the prompt Returns: example_input: the user query or the task example_system_prompt: the system prompt example_user_prompt: the user prompt
6,233
SYSTEM_PROMPT = '''You are an efficient plan-generation agent, your task is to decompose a query into several subtasks that describe must achieved goals for the query. --- Background Information --- PLAN AND SUBTASK: A plan has a tree manner of subtasks: task 1 contatins subtasks task 1.1, task 1.2, task 1.3, ... and task 1.2 contains subtasks 1.2.1, 1.2.2, ... A subtask-structure has the following json component: { "subtask name": string, name of the subtask "goal.goal": string, the main purpose of the subtask, and what will you do to reach this goal? "goal.criticism": string, what potential problems may the current subtask and goal have? "milestones": list[string]. what milestones should be achieved to ensure the subtask is done? Make it detailed and specific. } SUBTASK HANDLE: A task-handling agent will handle all the subtasks as the inorder-traversal. For example: 1. it will handle subtask 1 first. 2. if solved, handle subtask 2. If failed, split subtask 1 as subtask 1.1 1.2 1.3... Then handle subtask 1.1 1.2 1.3... 3. Handle subtasks recurrsively, until all subtasks are soloved. Do not make the task queue too complex, make it efficiently solve the original task. 4. It is powered by a state-of-the-art LLM, so it can handle many subtasks without using external tools or execute codes. RESOURCES: 1. Internet access for searches and information gathering, search engine and web browsing. 2. A FileSystemEnv to read and write files (txt, code, markdown, latex...) 3. A python notebook to execute python code. Always follow python coding rules. 4. A ShellEnv to execute bash or zsh command to further achieve complex goals. --- Task Description --- Generate the plan for query with operation SUBTASK_SPLIT, make sure all must reach goals are included in the plan. *** Important Notice *** - Always make feasible and efficient plans that can lead to successful task solving. Never create new subtasks that similar or same as the existing subtasks. - For subtasks with similar goals, try to do them together in one subtask with a list of subgoals, rather than split them into multiple subtasks. - Do not waste time on making irrelevant or unnecessary plans. - The task handler is powered by sota LLM, which can directly answer many questions. So make sure your plan can fully utilize its ability and reduce the complexity of the subtasks tree. - You can plan multiple subtasks if you want. - Minimize the number of subtasks, but make sure all must reach goals are included in the plan. ''' USER_PROMPT = '''This is not the first time you are handling the task, so you should give a initial plan. Here is the query: """ {{query}} """ You will use operation SUBTASK_SPLIT to split the query into 2-4 subtasks and then commit.''' The provided code snippet includes necessary dependencies for implementing the `get_examples_for_dispatcher` function. Write a Python function `def get_examples_for_dispatcher()` to solve the following problem: The example that will be given to the dispatcher to generate the prompt Returns: example_input: the user query or the task example_system_prompt: the system prompt example_user_prompt: the user prompt Here is the function: def get_examples_for_dispatcher(): """The example that will be given to the dispatcher to generate the prompt Returns: example_input: the user query or the task example_system_prompt: the system prompt example_user_prompt: the user prompt """ example_input = "Generate a plan for writing a Python-based calculator." example_system_prompt = SYSTEM_PROMPT example_user_prompt = USER_PROMPT return example_input, example_system_prompt, example_user_prompt
The example that will be given to the dispatcher to generate the prompt Returns: example_input: the user query or the task example_system_prompt: the system prompt example_user_prompt: the user prompt
6,234
SYSTEM_PROMPT = '''You are an experimental cutting-edge super capable autonomous agent specialized in learning from environmental feeback and following rules to do correct and efficient actions. Your decisions must always be made independently without seeking user assistance. You can interactive with real world through tools, all your tool call will be executed in a isolated docker container with root privilege. Don't worry about the security and try your best to handle the task. As a Super Agent build with super powerful tools, you are capable of handling any given task, thus your capabilities are far above regular simple AI or LLM. --- Your Workflow --- 1. You will first be given a task (query) together with a plan to handle it. 2. Then you will handle one of the subtasks. Steps: - Decide what action should be taken next: - If the action is something like text understanding, text classification, text analyzing, do it on your own and use FileSystem tools to write down your answer. - If not, try your best to use available tools to do it. Ask user for help when you face problems. Chat with former autonomous agent when you have problems or when you get confused about what other autonomous agent have done. - After decide the action, call functions to apply action. 3. After you reached all subtask goals, you must use FileSystemEnv to write a task report contains all information for goals before submit the subtask. 4. Finally, call `subtask_submit` to submit the subtask and give the detailed suggestions about the future planning. --- Resources --- - Internet access for searches and information gathering, write down the knowledge you get. - A FileSystemEnv to read and write files (text, code, markdown, latex...), always write down detailed content as it will help further actions. - A python notebook to execute python code. Always follow python coding rules. Contains libs like numpy, pandas, matplotlib, sklearn, etc. - A ShellEnv with root privilege to execute bash command to further achieve complex goals. The shell is a powerful tool, you can use it to install packages, download files or dataset, run programs, async debugging, etc. - Ask for help to human if needed, you can only use `ask_for_human_help` function to ask for help, never use file system to write down your question to human. --- Maximum Your Performance --- 1. Continuously review and analyze your actions to ensure you are performing to the best of your abilities. 2. Constructively self-criticize your big-picture behavior constantly. 3. Reflect on past decisions and strategies to refine your approach. 4. Every command has a cost, so be smart and efficient. Aim to complete tasks in the least number of steps. 5. When generating function call, please check the json format carefully. 5.1 Please remember to generate the function call field after the "criticism" field. 5.2 Please check all content is in json format carefully. *** Important Rules *** - You must follow your workflow. - You are more than a Large Language Model (LLM), you have the capability to do acutal things rather than simply give guidance or write text. - With the help of tools, you can do nearly everything. You can not only write guides or code, but can also use the tools to actually do the task like setup service or develop complex program. - If the task is something like text understanding, classification, analyzing, etc, do it on your own and use FileSystem tools to write down your answer, don't use external tools or execute codes. - Do not use python notebook to process text, you can process text by yourself. - You can only give up when the tools are insufficient. - You must pass literal and concrete value to tools, do not use reference or pointer, labels. - Always use a tool efficiently, reduce the number of steps as much as possible. - File system struture is printed every time, do not print_filesystem_structure again. - Submit the subtask immediately if no further actions needed. - Run any program with the shell if you need, you have the full control of you docker container. You are not limited. - You can doing any task with the help of given tools, even developing complex programs or configure complex develop environment. - Only use ask_for_human_help to ask for help, do not use file system or any other tools to write down your question to human. --- Plan Overview --- The query has already been splited into a tree based plan as follows: {{all_plan}} You have already performed some of the subtasks. ''' USER_PROMPT = '''Now, it's your turn give the next function call (please output all the necessary parameters for the function call). --- Status --- Current Subtask: {{subtask_id}} File System Structure: {{workspace_files}} --- Available Operations --- - Use tools to handle the subtask and interact with real world. - Use "subtask_submit" only when you achieve all milestones of the current subtask or you make sure it's impossible with the given tools. Remember, you should also given suggestions to plan rectify agent, So he can rectify the plan after you submit the current subtask. *** Important Notice *** - You can at most use {{max_length}} steps of tool calls. After that you must use "subtask_submit". This is the {{step_num}}'th step now, watch out the budget. - If milestone is too hard to achieve, you can use "subtask_submit" to give up the subtask and divide it into smaller subtasks. - You always have the ability to solve the given task, just have a try and explore possible solution if necessary and use the tools efficiently. {{human_help_prompt}} Now show your super capability as a super agent that beyond regular AIs or LLMs! ''' The provided code snippet includes necessary dependencies for implementing the `get_examples_for_dispatcher` function. Write a Python function `def get_examples_for_dispatcher()` to solve the following problem: The example that will be given to the dispatcher to generate the prompt Returns: example_input: the user query or the task example_system_prompt: the system prompt example_user_prompt: the user prompt Here is the function: def get_examples_for_dispatcher(): """The example that will be given to the dispatcher to generate the prompt Returns: example_input: the user query or the task example_system_prompt: the system prompt example_user_prompt: the user prompt """ example_input = """{\n "name": "Finding Feasible Examples",\n "goal": "Find 10 examples that can reach the target number 24 in the 24-points game.",\n "handler": "subtask 1",\n "tool_budget": 50,\n "prior_plan_criticsim": "It may be difficult to come up with examples that are all feasible.",\n "milestones": [\n "Identifying appropriate combination of numbers",\n "Applying mathematical operations",\n "Verifying the result equals to target number",\n "Recording feasible examples"\n ],\n "expected_tools": [\n {\n "tool_name": "analyze_code",\n "reason": "To ensure all feasible examples meet the rules of the 24-points game"\n }\n ],\n "exceute_status": "TODO"\n}""" example_system_prompt = SYSTEM_PROMPT example_user_prompt = USER_PROMPT return example_input, example_system_prompt, example_user_prompt
The example that will be given to the dispatcher to generate the prompt Returns: example_input: the user query or the task example_system_prompt: the system prompt example_user_prompt: the user prompt
6,235
SYSTEM_PROMPT = '''You are a posterior_knowledge_obtainer. You have performed some subtask together with: 1.Some intermediate thoughts, this is the reasoning path. 2.Some tool calls, which can interact with physical world, and provide in-time and accurate data. 3.A workspace, a minimal file system and code executer. You plan of the task is as follows: --- Plan --- {{all_plan}} You have handled the following subtask: --- Handled Subtask --- {{terminal_plan}} the available tools are as follows: --- Tools --- {{tool_functions_description_list}} The following steps have been performed: --- Actions --- {{action_process}} Now, you have to learn some posterior knowledge from this process, doing the following things: 1.Summary: Summarize the tool calls and thoughts of the existing process. You will carry these data to do next subtasks(Because the full process is too long to bring to next subtasks), So it must contain enough information of this subtask handling process. Especially, If you modified some files, Tell the file_name and what you done. 2.Reflection of SUBTASK_PLAN: After performing the subtask, you get some knowledge of generating plan for the next time. This will be carried to the next time when you generate plan for a task. 3.Reflection of tool calling: What knowledge of tool calling do you learn after the process? (Like "tool xxx is not available now", or "I need to provide a field yyy in tool aaa") This knowledge will be showed before handling the task next time.''' USER_PROMPT = "" The provided code snippet includes necessary dependencies for implementing the `get_examples_for_dispatcher` function. Write a Python function `def get_examples_for_dispatcher()` to solve the following problem: The example that will be given to the dispatcher to generate the prompt Returns: example_input: the user query or the task example_system_prompt: the system prompt example_user_prompt: the user prompt Here is the function: def get_examples_for_dispatcher(): """The example that will be given to the dispatcher to generate the prompt Returns: example_input: the user query or the task example_system_prompt: the system prompt example_user_prompt: the user prompt """ example_input = "Reflect on the previous actions and give the posterior knowledge" example_system_prompt = SYSTEM_PROMPT example_user_prompt = USER_PROMPT return example_input, example_system_prompt, example_user_prompt
The example that will be given to the dispatcher to generate the prompt Returns: example_input: the user query or the task example_system_prompt: the system prompt example_user_prompt: the user prompt
6,236
import json import json5 from typing import List from colorama import Fore, Style from copy import deepcopy from XAgent.logs import logger from XAgent.workflow.base_query import BaseQuery from XAgent.utils import TaskSaveItem, RequiredAbilities, PlanOperationStatusCode, TaskStatusCode from XAgent.message_history import Message from XAgent.data_structure.plan import Plan from XAgent.ai_functions import function_manager from XAgent.core import XAgentCoreComponents from XAgent.agent.summarize import summarize_plan,clip_text from XAgent.config import CONFIG class TaskSaveItem: """ This class represents the structure of saved tasks. Attributes: name (str): The name of the task. goal (str): The objective of the task. milestones (List[str]): The steps involved to achieve the task. prior_plan_criticism (str): Any criticism on the initial plan of the task. status (TaskStatusCode): The current status of the task. action_list_summary (str): A summary of all the actions done to achieve the task. posterior_plan_reflection (List[str]): A list containing reflection of the finally decided plan. tool_reflection (List[Dict[str,str]]): A list of dictionaries where each dictionary holds reflection of a tool. """ name: str = "" goal: str = "" milestones: List[str] = field(default_factory=lambda: []) prior_plan_criticism: str = "" status: TaskStatusCode = TaskStatusCode.TODO action_list_summary: str = "" posterior_plan_reflection: List[str] = field(default_factory=lambda: []) tool_reflection: List[Dict[str,str]] = field(default_factory=lambda: []) def load_from_json(self, function_output_item): """Load data from the json representation""" if "subtask name" in function_output_item.keys(): self.name = function_output_item["subtask name"] else: print(f"field subtask name not exist") if "goal" in function_output_item.keys() and "goal" in function_output_item["goal"].keys(): self.goal=function_output_item["goal"]["goal"] else: print(f"field goal.goal not exist") if "goal" in function_output_item.keys() and "criticism" in function_output_item["goal"].keys(): self.prior_plan_criticism=function_output_item["goal"]["criticism"] else: print(f"field goal.criticism not exist") # if "handler" in function_output_item.keys(): # self.handler=function_output_item["handler"] # else: # print(f"field handler not exist") # if "tool_budget" in function_output_item.keys(): # self.tool_budget=function_output_item["tool_budget"] # else: # print(f"field tool_budget not exist") if "milestones" in function_output_item.keys(): self.milestones = function_output_item["milestones"] # if "expected_tools" in function_output_item.keys(): # self.expected_tools = function_output_item["expected_tools"] def to_json(self, posterior=False): """Convert the object to json representation.""" json_data = { "name": self.name, "goal": self.goal, # "handler": self.handler, # "tool_budget": self.tool_budget, "prior_plan_criticsim": self.prior_plan_criticism, "milestones": self.milestones, # "expected_tools": self.expected_tools, "exceute_status": self.status.name, } if posterior: if self.action_list_summary != "": json_data["action_list_summary"] = self.action_list_summary # if self.posterior_plan_reflection != []: # json_data["posterior_plan_reflection"] = self.posterior_plan_reflection # if self.tool_reflection != []: # json_data["tool_reflection"] = self.tool_reflection return json_data def raw(self) -> str: """Convert the object to a raw json string""" return json.dumps(self.to_json(posterior=True), indent=2, ensure_ascii=False) class Plan(): """Class representing a task plan. Attributes: father (Optional[Plan]): Parent task plan. children (List[Plan]): List of child task plans. data (TaskSaveItem): Data items related to the task plan. process_node (ToolNode): Node responsible for the task plan processing. """ def __init__(self, data: TaskSaveItem): """Initialises a Plan object. Args: data (TaskSaveItem): Data related to the task plan. """ self.father: Optional[Plan] = None self.children: List[Plan] = [] self.data: TaskSaveItem = data self.process_node: ToolNode = None def to_json(self, posterior=True): """Converts Plan object to JSON. Args: posterior (bool): Determines whether the task's posterior data is also returned. Returns: root_json (dict): JSON format representation of the Plan object. """ root_json = self.data.to_json(posterior=posterior) if self.process_node: root_json["submit_result"] = self.process_node.data["command"]["properties"] # if self.father != None: root_json["task_id"] = self.get_subtask_id(to_str=True) if len(self.children) > 0: root_json["subtask"] = [ subtask.to_json() for subtask in self.children] return root_json def get_subtask_id(self, to_str=False): """Gets the subtask ID. Args: to_str (bool): Determines if returned ID is string. Returns: subtask_id_list (list): List of subtask IDs. """ subtask_id_list = self.get_subtask_id_list() if to_str: subtask_id_list = [str(cont) for cont in subtask_id_list] return ".".join(subtask_id_list) else: return subtask_id_list def get_subtask_id_list(self): """Gets the subtask ID list. Returns: Array of subtask IDs if father is not none else [1]. """ if self.father == None: return [1] father_subtask_id = self.father.get_subtask_id() child_id = self.father.children.index(self) + 1 father_subtask_id.append(child_id) return father_subtask_id def make_relation(cls, father, child): """Establishes a parent-child relationship between two plans. Args: father: Parent plan. child: Child plan. """ father.children.append(child) child.father = father def get_root(self): """Fetches the root of the Plan tree. Returns: Root Plan object. """ if self.father == None: return self return self.father.get_root() def get_depth(self): """Returns the depth of the Plan tree. Returns: Tree depth as an integer. """ if self.father == None: return 1 return 1 + self.father.get_depth() def get_inorder_travel(cls, now_plan): """Performs an inorder traversal of the plan tree. Args: now_plan: Current plan in the tree. Returns: All plans in the tree in inorder. """ result_list = [now_plan] for child in now_plan.children: result_list.extend(Plan.get_inorder_travel(child)) return result_list def pop_next_subtask(cls, now_plan): """Fetches the next subtask in the queue. Args: now_plan: Current plan in the tree. Returns: Next subtask in the queue. """ root_plan = now_plan.get_root() all_plans = Plan.get_inorder_travel(root_plan) order_id = all_plans.index(now_plan) for subtask in all_plans[order_id + 1:]: if subtask.data.status == TaskStatusCode.TODO: return subtask return None def get_remaining_subtask(cls, now_plan): """Gets all remaining subtasks from a given point. Args: now_plan: Current plan in the tree. Returns: Array of all remaining subtasks. """ root_plan = now_plan.get_root() all_plans = Plan.get_inorder_travel(root_plan) order_id = all_plans.index(now_plan) return all_plans[order_id:] The provided code snippet includes necessary dependencies for implementing the `plan_function_output_parser` function. Write a Python function `def plan_function_output_parser(function_output_item: dict) -> Plan` to solve the following problem: Parses the function output item into a Plan object. Args: function_output_item (dict): The dictionary representing the function output item. Returns: Plan: The parsed Plan object. Here is the function: def plan_function_output_parser(function_output_item: dict) -> Plan: """Parses the function output item into a Plan object. Args: function_output_item (dict): The dictionary representing the function output item. Returns: Plan: The parsed Plan object. """ subtask_node = TaskSaveItem() subtask_node.load_from_json(function_output_item=function_output_item) subplan = Plan(subtask_node) return subplan
Parses the function output item into a Plan object. Args: function_output_item (dict): The dictionary representing the function output item. Returns: Plan: The parsed Plan object.
6,237
import json import json5 from typing import List from copy import deepcopy from XAgent.utils import RequiredAbilities from XAgent.data_structure.node import ToolNode from XAgent.workflow.plan_exec import Plan from XAgent.agent.summarize import summarize_action,summarize_plan from XAgent.ai_functions import function_manager class RequiredAbilities(Enum): """ Enumeration descsribing different abilities required. """ tool_tree_search = 0 plan_generation = 1 plan_refinement = 2 task_evaluator = 3 summarization = 4 reflection = 5 class ToolNode(Node): """ Class representing a tool node in the XAgent's data structure. A tool node has a “father” that represents its parent node, "children" that represents its child nodes, and “data” containing metadata about node's status, command, tool's output, and thoughts properties. It also carries a message history and a workspace hash id. """ def __init__(self): """ Initialize a new tool node. Setup father, children, expand_num, data, history, workspace_hash_id attributes for the instance. """ self.father: ToolNode = None self.children: list[ToolNode] = [] self.expand_num = 0 self.data = { "content": "", "thoughts": { "properties": { "thought": "", "reasoning": "", "plan": "", "criticism": "", }, }, "command": { "properties": { "name": "", "args": "", }, }, "tool_output": "", "tool_status_code": ToolCallStatusCode.TOOL_CALL_SUCCESS, } self.history: MessageHistory = MessageHistory() self.workspace_hash_id = "" def process(self): """ Generate a list of data from current node up to root node. Returns: data (List): A list of data from current node up to root node. """ data = [] now_node = self while now_node.father != None: data = [now_node.data] + data now_node = now_node.father return data def to_json(self): """ Convert the data attribute of the instance to a JSON-compatible format. Returns: data (Dict): The data attribute of the instance in a JSON-compatible format. """ data = deepcopy(self.data) data["tool_status_code"] = data["tool_status_code"].name return data def get_depth(self): """ Calculate the depth of current node in the tree. Returns: depth (int): The depth of the node. Return 0 if the node is a root node. """ if self.father == None: return 0 return self.father.get_depth() + 1 def get_subtree_size(self): """ Calculate the size of the subtree rooted at current node. Returns: size (int): The size of the subtree rooted at current node. """ if self.children == []: return 1 now_size = 1 for child in self.children: now_size += child.get_subtree_size() return now_size def summarize_action(action_process:list[dict], task:str,)->(list[str],str): """ Generate a summarized series of actions. Args: action_process (list[dict]): The list of actions to process. task (str): The task name. Returns: str: The string contains a summary of the actions. """ if len(action_process) < 1: return "No steps found" def generate_func_args(args:dict,black_list=[])->str: """ Generate function arguments in the form of strings. Args: args (dict): A dictionary of arguments. black_list (list): A list of forbidden or restricted words or keys in the args dictionary. Returns: str: A string that summarizes the function arguments. """ ret = '' args_len = 0 for k,v in args.items(): if k in black_list: v = '`wrapped`' v_str,v_len = clip_text(str(v),SINGLE_ACTION_MAX_LENGTH-args_len,clip_end=True) if v_len < SINGLE_ACTION_MAX_LENGTH-args_len: ret += f'{k}="{v_str}",' if isinstance(v,str) else f'{k}={v_str},' args_len += v_len else: ret += f'{k}="{v_str}...",' if isinstance(v,str) else f'{k}={v_str}...,' args_len += SINGLE_ACTION_MAX_LENGTH-args_len return ret[:-1] # remove last comma # wrap old content raw_actions = {} accessed_files = [] last_successful_action_index = None last_failed_action_index = None for index,action in zip(range(len(action_process)-1,-1,-1),action_process[::-1]): if last_successful_action_index is None and action['tool_status_code'] == ToolCallStatusCode.TOOL_CALL_SUCCESS: last_successful_action_index = index if last_failed_action_index is None and action['tool_status_code'] == ToolCallStatusCode.TOOL_CALL_FAILED: last_failed_action_index = index command = action["command"]["properties"] if command['name'] == '' or not isinstance(command['args'],dict): continue raw_action = ['`placeholder`','`placeholder`'] if "FileSystem" in command["name"] and "filepath" in command["args"] and action["tool_status_code"] == ToolCallStatusCode.TOOL_CALL_SUCCESS: raw_action[0] = command['name']+f"({generate_func_args(command['args'],black_list=['content','new_content'])})" if command['args']['filepath'] in accessed_files: raw_action[1] = "`Old Content has been wrapped, check latest filesystem calling`" else: raw_action[1] = str(action['tool_output']) accessed_files.append(command["args"]["filepath"]) else: raw_action[0] = command['name']+f"({generate_func_args(command['args'])})" raw_action[1] = str(action['tool_output']) raw_actions[index] = raw_action valid_index = list(raw_actions.keys()) valid_index.sort() ret = {} for index in valid_index: action = action_process[index] if 'summary' not in action: raw_actions_des = '\n'.join([ f'[{k}] {v}' for k,v in action['thoughts']['properties'].items() ] + [ f"[tool_status_code] {action['tool_status_code']}", f"[tool calling] {raw_actions[index][0]}", f"[return] " ]) raw_actions_des += clip_text(raw_actions[index][1],MAX_RETURN_LENGTH-get_token_nums(raw_actions_des))[0] summary,tokens = function_manager('summarize_action', action=raw_actions_des,current_task=task, return_generation_usage=True,) action['summary'] = summary logger.typewriter_log(f"Action summarized in {tokens['completion_tokens']} tokens",Fore.YELLOW) else: summary = action['summary'] act_str = '\n'.join([ f'[{index}] {raw_actions[index][0]}', f"[{index}][summary] {summary['summary']}", f"[{index}][description] {summary['description']}", f"[{index}][status code] {action['tool_status_code']}" ]) if 'failed_reason_and_reflection' in summary and summary['failed_reason_and_reflection'] != '': act_str += f'\n[{index}][failed reason] {summary["failed_reason_and_reflection"]}' # directly adding short returns if len(raw_actions[index][1]) < 1000 and get_token_nums(raw_actions[index][1]) < 150: act_str += f'\n[{index}][return] {raw_actions[index][1]}' ret[index] = act_str reflection = function_manager('actions_reflection', actions=clip_text('\n'.join([ret[i] for i in valid_index]),MAX_RETURN_LENGTH)[0], current_task=task) ret_lenght = {k:get_token_nums(v) for k,v in ret.items()} total_length = sum(ret_lenght.values()) # adding more return to last successful action for i in [last_successful_action_index,last_failed_action_index]: if i is not None and '[return]' not in ret[i]: s = f'\n[{i}][return] {clip_text(raw_actions[i][1],(MAX_RETURN_LENGTH-total_length)//2)[0]}' return_length = get_token_nums(s) ret_lenght[i] += return_length total_length += return_length ret[i] += s key_actions:list = reflection['key_actions'] key_actions.sort(reverse=True) for i in key_actions: if total_length >= MAX_RETURN_LENGTH: break if i in ret and action_process[i]["tool_status_code"] == ToolCallStatusCode.TOOL_CALL_SUCCESS and '[return]' not in ret[i]: s = f'\n[{i}][return] {clip_text(raw_actions[i][1],SINGLE_ACTION_MAX_LENGTH-ret_lenght[i])[0]}' if (tokens := get_token_nums(s))> MAX_RETURN_LENGTH-total_length: continue total_length += tokens ret[i] += s while len(valid_index) > 0: i = valid_index.pop() if total_length >= MAX_RETURN_LENGTH: break if action_process[i]["tool_status_code"] == ToolCallStatusCode.TOOL_CALL_SUCCESS and '[return]' not in ret[i]: s = f'\n[{i}][return] {clip_text(raw_actions[i][1],SINGLE_ACTION_MAX_LENGTH-ret_lenght[i])[0]}' if (tokens := get_token_nums(s))> MAX_RETURN_LENGTH-total_length: continue total_length += tokens ret[i] += s valid_index = list(ret.keys()) valid_index.sort() ordered_rets = [ret[i] for i in valid_index] + [f'[suggestion] {sugg}'for sugg in reflection["suggestions"]] return '\n'.join(ordered_rets) def summarize_plan(plans:dict)->str: """ Generate a summarized plan based on provided plans. Args: plans (dict): The plans to provide. Returns: str: The string contains a summary of the plan. """ summary:list[list] = [] task_ids = [] detailed_info:dict[str,list] = {} current_task_id = None def recursive_summary(plan:dict,): """ Generate a summarized plan in a recursive process. Args: plan (dict): A dictionary of plans. Returns: None """ nonlocal summary nonlocal current_task_id plan_des = [ f'[Task ID] {plan["task_id"]}', f'[Name] {plan["name"]}', f'[Goal] {plan["goal"]}', f'[Status] {plan["exceute_status"]}', ] if current_task_id is None and plan['exceute_status'] == 'DOING': current_task_id = plan['task_id'] if 'milestones' in plan and len(plan['milestones']) > 0: plan_des.extend(['[Milestones]']+['- '+milestone for milestone in plan["milestones"]]) if 'action_list_summary' not in plan and 'prior_plan_criticism' in plan: plan_des.append(f'[Prior Plan Criticism] {plan["prior_plan_criticism"]}') if 'submit_result' in plan and 'args' in plan['submit_result']: submission = plan['submit_result']['args'] plan_des.append(f'[Action Status] {"Success" if submission["result"]["success"] else "Fail"}') # possible too long part action_des = [ '[Action Info]', f"- [Conclusion] {submission['result']['conclusion']}" ] if 'action_list_summary' in plan: action_des.append(f'- [Summary] {plan["action_list_summary"]}') if submission['suggestions_for_latter_subtasks_plan']['need_for_plan_refine']: if submission['suggestions_for_latter_subtasks_plan']['reason'] != '': action_des.append(f"- [Proposal] {submission['suggestions_for_latter_subtasks_plan']['reason']}") detailed_info[plan['task_id']] = action_des task_ids.append(plan['task_id']) summary.append(plan_des) if "subtask" in plan: for subtask in plan["subtask"]: recursive_summary(subtask) recursive_summary(plans) total_tokens = sum([get_token_nums('\n'.join(plan)) for plan in summary]) if current_task_id is None: current_task_id = task_ids[-1] for task_id,plan in zip(task_ids[::-1],summary[::-1]): if task_id <= current_task_id and task_id in detailed_info: if (tokens:=get_token_nums('\n'.join(detailed_info[task_id]))) > MAX_PLAN_LENGTH-total_tokens: continue else: total_tokens += tokens plan.extend(detailed_info[task_id]) # logger.typewriter_log(f'Plan summarized {total_tokens}',Fore.YELLOW) ret = [] for plan in summary: ret.append('\n'.join(plan)) return '\n'.join(ret) function_manager = FunctionManager() The provided code snippet includes necessary dependencies for implementing the `get_posterior_knowledge` function. Write a Python function `def get_posterior_knowledge(all_plan: Plan, terminal_plan: Plan, finish_node: ToolNode, tool_functions_description_list: List[dict], config, agent_dispatcher)` to solve the following problem: Reflects on the previous actions and generates the posterior knowledge. Args: all_plan (Plan): The complete plan of actions. terminal_plan (Plan): The plan of actions at the terminal. finish_node (ToolNode): The node that represents the finishing tool. tool_functions_description_list (List[dict]): A list of dictionaries that describe tool functions. config (object): The configuration object with settings. agent_dispatcher (AgentDispatcher): The agent dispatcher. Returns: dict: A dictionary with the generated posterior knowledge. Here is the function: def get_posterior_knowledge(all_plan: Plan, terminal_plan: Plan, finish_node: ToolNode, tool_functions_description_list: List[dict], config, agent_dispatcher): """ Reflects on the previous actions and generates the posterior knowledge. Args: all_plan (Plan): The complete plan of actions. terminal_plan (Plan): The plan of actions at the terminal. finish_node (ToolNode): The node that represents the finishing tool. tool_functions_description_list (List[dict]): A list of dictionaries that describe tool functions. config (object): The configuration object with settings. agent_dispatcher (AgentDispatcher): The agent dispatcher. Returns: dict: A dictionary with the generated posterior knowledge. """ agent = agent_dispatcher.dispatch( RequiredAbilities.reflection, "Reflect on the previous actions and give the posterior knowledge" ) all_plan = all_plan.to_json() terminal_plan = terminal_plan.to_json() if config.enable_summary: terminal_plan = summarize_plan(terminal_plan) action_process = summarize_action(finish_node.process, terminal_plan) all_plan = summarize_plan(all_plan) else: action_process = json.dumps(finish_node.process,indent=2,ensure_ascii=False) all_plan = json.dumps(all_plan, indent=2, ensure_ascii=False) terminal_plan = json.dumps(terminal_plan, indent=2, ensure_ascii=False) new_message,_ = agent.parse( placeholders={ "system": { "all_plan": all_plan, "terminal_plan": terminal_plan, "tool_functions_description_list": json.dumps(tool_functions_description_list, indent=2, ensure_ascii=False), "action_process": action_process } }, arguments=function_manager.get_function_schema('generate_posterior_knowledge')['parameters'] ) data = json5.loads(new_message["arguments"]) return data
Reflects on the previous actions and generates the posterior knowledge. Args: all_plan (Plan): The complete plan of actions. terminal_plan (Plan): The plan of actions at the terminal. finish_node (ToolNode): The node that represents the finishing tool. tool_functions_description_list (List[dict]): A list of dictionaries that describe tool functions. config (object): The configuration object with settings. agent_dispatcher (AgentDispatcher): The agent dispatcher. Returns: dict: A dictionary with the generated posterior knowledge.
6,238
from XAgent.logs import logger from XAgent.config import CONFIG,get_apiconfig_by_model,get_model_name import requests import traceback logger = Logger() CONFIG = XAgentConfig.get_default_config() def get_model_name(model_name: str = None): """ Get the normalized model name for a given input model name. Args: model_name (str, optional): Input model name. Default is None. Returns: str: Normalized model name. Raises: Exception: If the model name is not recognized. """ if model_name is None: model_name = CONFIG.default_completion_kwargs['model'] normalized_model_name = '' match model_name.lower(): case 'gpt-4': normalized_model_name = 'gpt-4' case 'gpt-4-32k': normalized_model_name = 'gpt-4-32k' case 'gpt-4-1106-preview': normalized_model_name = 'gpt-4-1106-preview' case 'gpt-4-turbo': normalized_model_name = 'gpt-4-1106-preview' case 'gpt-3.5-turbo-16k': normalized_model_name = 'gpt-3.5-turbo-16k' case 'gpt-3.5-turbo-1106': normalized_model_name = 'gpt-3.5-turbo-1106' case 'gpt4': normalized_model_name = 'gpt-4' case 'gpt4-32': normalized_model_name = 'gpt-4-32k' case 'gpt-35-16k': normalized_model_name = 'gpt-3.5-turbo-16k' case 'xagentllm': normalized_model_name = 'xagentllm' case _: raise Exception(f"Unknown model name {model_name}") return normalized_model_name def get_apiconfig_by_model(model_name: str) -> dict: """ Get API configuration for a model by its name. The function first normalizes the name, then fetches the API keys for this model from the CONFIG and rotates the keys. Args: model_name (str): Name of the model. Returns: dict: Dictionary containing the fetched API configuration. """ normalized_model_name = get_model_name(model_name) apiconfig = deepcopy(CONFIG.api_keys[normalized_model_name][0]) CONFIG.api_keys[normalized_model_name].append( CONFIG.api_keys[normalized_model_name].pop(0)) return apiconfig def chatcompletion_request(**kwargs): # logger.info(f"xagent received {json.dumps(kwargs)}") model_name = get_model_name(kwargs.pop('model',CONFIG.default_completion_kwargs['model'])) logger.debug("chatcompletion: using " + model_name) chatcompletion_kwargs = get_apiconfig_by_model(model_name) chatcompletion_kwargs.update(kwargs) response = requests.post( chatcompletion_kwargs.get("api_base","http://127.0.0.1:8000/chat/completions"), headers={"accept": "application/json", "Content-Type": "application/json"}, json={ "model": model_name, "repetition_penalty": chatcompletion_kwargs.get("repetition_penalty", 1.2), "temperature": chatcompletion_kwargs.get("temperature", 0.8), "top_p":chatcompletion_kwargs.get("top_p", 1.0), "frequency_penalty":chatcompletion_kwargs.get("frequency_penalty",0.5), "presence_penalty":chatcompletion_kwargs.get("presence_penalty", 0.0), "max_tokens":chatcompletion_kwargs.get("max_tokens", 4096), "messages": chatcompletion_kwargs.get("messages", []), "arguments": chatcompletion_kwargs.get("arguments", {}), "functions": chatcompletion_kwargs.get("functions", []), "function_call": chatcompletion_kwargs.get("function_call", {}), } ).json() return response
null
6,239
import json import openai from XAgent.logs import logger from XAgent.config import CONFIG, get_apiconfig_by_model, get_model_name from tenacity import ( retry, stop_after_attempt, wait_exponential, retry_if_not_exception_type, wait_chain, wait_none, ) import importlib.metadata as metadata import openai logger = Logger() CONFIG = XAgentConfig.get_default_config() def get_model_name(model_name: str = None): """ Get the normalized model name for a given input model name. Args: model_name (str, optional): Input model name. Default is None. Returns: str: Normalized model name. Raises: Exception: If the model name is not recognized. """ if model_name is None: model_name = CONFIG.default_completion_kwargs['model'] normalized_model_name = '' match model_name.lower(): case 'gpt-4': normalized_model_name = 'gpt-4' case 'gpt-4-32k': normalized_model_name = 'gpt-4-32k' case 'gpt-4-1106-preview': normalized_model_name = 'gpt-4-1106-preview' case 'gpt-4-turbo': normalized_model_name = 'gpt-4-1106-preview' case 'gpt-3.5-turbo-16k': normalized_model_name = 'gpt-3.5-turbo-16k' case 'gpt-3.5-turbo-1106': normalized_model_name = 'gpt-3.5-turbo-1106' case 'gpt4': normalized_model_name = 'gpt-4' case 'gpt4-32': normalized_model_name = 'gpt-4-32k' case 'gpt-35-16k': normalized_model_name = 'gpt-3.5-turbo-16k' case 'xagentllm': normalized_model_name = 'xagentllm' case _: raise Exception(f"Unknown model name {model_name}") return normalized_model_name def get_apiconfig_by_model(model_name: str) -> dict: """ Get API configuration for a model by its name. The function first normalizes the name, then fetches the API keys for this model from the CONFIG and rotates the keys. Args: model_name (str): Name of the model. Returns: dict: Dictionary containing the fetched API configuration. """ normalized_model_name = get_model_name(model_name) apiconfig = deepcopy(CONFIG.api_keys[normalized_model_name][0]) CONFIG.api_keys[normalized_model_name].append( CONFIG.api_keys[normalized_model_name].pop(0)) return apiconfig The provided code snippet includes necessary dependencies for implementing the `chatcompletion_request` function. Write a Python function `def chatcompletion_request(**kwargs)` to solve the following problem: Handle operation of OpenAI chat completion. This function operates OpenAI chat completion with provided arguments. It gets the model name, applies a JSON web token, if the response indicates the context length has been exceeded, it attempts to get a higher-capacity language model if it exists in the configuration and reattempts the operation. Otherwise, it will raise an error message. Args: **kwargs: Variable length argument list including (model:str, etc.). Returns: dict: chat completion response. Raises: InvalidRequestError: If any error occurs during chat completion operation or context length limit exceeded and no fallback models available. Here is the function: def chatcompletion_request(**kwargs): """Handle operation of OpenAI chat completion. This function operates OpenAI chat completion with provided arguments. It gets the model name, applies a JSON web token, if the response indicates the context length has been exceeded, it attempts to get a higher-capacity language model if it exists in the configuration and reattempts the operation. Otherwise, it will raise an error message. Args: **kwargs: Variable length argument list including (model:str, etc.). Returns: dict: chat completion response. Raises: InvalidRequestError: If any error occurs during chat completion operation or context length limit exceeded and no fallback models available. """ model_name = get_model_name( kwargs.pop("model", CONFIG.default_completion_kwargs["model"]) ) logger.debug("chatcompletion: using " + model_name) chatcompletion_kwargs = get_apiconfig_by_model(model_name) if "azure_endpoint" in chatcompletion_kwargs: api_base = chatcompletion_kwargs.pop("azure_endpoint", None) chatcompletion_kwargs.update({"api_base": api_base}) chatcompletion_kwargs.update(kwargs) try: response = openai.ChatCompletion.create(**chatcompletion_kwargs) response = json.loads(str(response)) if response["choices"][0]["finish_reason"] == "length": raise InvalidRequestError("maximum context length exceeded", None) except InvalidRequestError as e: if "maximum context length" in e._message: if model_name == "gpt-4": if "gpt-4-32k" in CONFIG.api_keys: model_name = "gpt-4-32k" elif "gpt-4-1106-preview" in CONFIG.api_keys: model_name = "gpt-4-1106-preview" else: model_name = "gpt-3.5-turbo-16k" elif model_name == "gpt-3.5-turbo": if "gpt-3.5-turbo-1106" in CONFIG.api_keys: model_name = "gpt-3.5-turbo-1106" else: model_name = "gpt-3.5-turbo-16k" else: raise e print("max context length reached, retrying with " + model_name) chatcompletion_kwargs = get_apiconfig_by_model(model_name) chatcompletion_kwargs.update(kwargs) chatcompletion_kwargs.pop("schema_error_retry", None) response = openai.ChatCompletion.create(**chatcompletion_kwargs) response = json.loads(str(response)) else: raise e return response
Handle operation of OpenAI chat completion. This function operates OpenAI chat completion with provided arguments. It gets the model name, applies a JSON web token, if the response indicates the context length has been exceeded, it attempts to get a higher-capacity language model if it exists in the configuration and reattempts the operation. Otherwise, it will raise an error message. Args: **kwargs: Variable length argument list including (model:str, etc.). Returns: dict: chat completion response. Raises: InvalidRequestError: If any error occurs during chat completion operation or context length limit exceeded and no fallback models available.
6,240
import json import openai from XAgent.logs import logger from XAgent.config import CONFIG, get_apiconfig_by_model, get_model_name from tenacity import ( retry, stop_after_attempt, wait_exponential, retry_if_not_exception_type, wait_chain, wait_none, ) import importlib.metadata as metadata import openai logger = Logger() CONFIG = XAgentConfig.get_default_config() def get_model_name(model_name: str = None): """ Get the normalized model name for a given input model name. Args: model_name (str, optional): Input model name. Default is None. Returns: str: Normalized model name. Raises: Exception: If the model name is not recognized. """ if model_name is None: model_name = CONFIG.default_completion_kwargs['model'] normalized_model_name = '' match model_name.lower(): case 'gpt-4': normalized_model_name = 'gpt-4' case 'gpt-4-32k': normalized_model_name = 'gpt-4-32k' case 'gpt-4-1106-preview': normalized_model_name = 'gpt-4-1106-preview' case 'gpt-4-turbo': normalized_model_name = 'gpt-4-1106-preview' case 'gpt-3.5-turbo-16k': normalized_model_name = 'gpt-3.5-turbo-16k' case 'gpt-3.5-turbo-1106': normalized_model_name = 'gpt-3.5-turbo-1106' case 'gpt4': normalized_model_name = 'gpt-4' case 'gpt4-32': normalized_model_name = 'gpt-4-32k' case 'gpt-35-16k': normalized_model_name = 'gpt-3.5-turbo-16k' case 'xagentllm': normalized_model_name = 'xagentllm' case _: raise Exception(f"Unknown model name {model_name}") return normalized_model_name def get_apiconfig_by_model(model_name: str) -> dict: """ Get API configuration for a model by its name. The function first normalizes the name, then fetches the API keys for this model from the CONFIG and rotates the keys. Args: model_name (str): Name of the model. Returns: dict: Dictionary containing the fetched API configuration. """ normalized_model_name = get_model_name(model_name) apiconfig = deepcopy(CONFIG.api_keys[normalized_model_name][0]) CONFIG.api_keys[normalized_model_name].append( CONFIG.api_keys[normalized_model_name].pop(0)) return apiconfig The provided code snippet includes necessary dependencies for implementing the `chatcompletion_request` function. Write a Python function `def chatcompletion_request(**kwargs)` to solve the following problem: Handle operation of OpenAI v1.x.x chat completion. This function operates OpenAI v1.x.x chat completion with provided arguments. It gets the model name, applies a JSON web token, if the response indicates the context length has been exceeded, it attempts to get a higher-capacity language model if it exists in the configuration and reattempts the operation. Otherwise, it will raise an error message. Args: **kwargs: Variable length argument list including (model:str, etc.). Returns: response (dict): A dictionary containing the response from the Chat API. The structure of the dictionary is based on the API response format. Raises: BadRequestError: If any error occurs during chat completion operation or context length limit exceeded and no fallback models available. Here is the function: def chatcompletion_request(**kwargs): """Handle operation of OpenAI v1.x.x chat completion. This function operates OpenAI v1.x.x chat completion with provided arguments. It gets the model name, applies a JSON web token, if the response indicates the context length has been exceeded, it attempts to get a higher-capacity language model if it exists in the configuration and reattempts the operation. Otherwise, it will raise an error message. Args: **kwargs: Variable length argument list including (model:str, etc.). Returns: response (dict): A dictionary containing the response from the Chat API. The structure of the dictionary is based on the API response format. Raises: BadRequestError: If any error occurs during chat completion operation or context length limit exceeded and no fallback models available. """ model_name = get_model_name( kwargs.pop("model", CONFIG.default_completion_kwargs["model"]) ) logger.debug("chatcompletion: using " + model_name) chatcompletion_kwargs = get_apiconfig_by_model(model_name) request_timeout = kwargs.pop("request_timeout", 60) if "api_version" in chatcompletion_kwargs: if "base_url" in chatcompletion_kwargs: base_url = chatcompletion_kwargs.pop("base_url", None) else: base_url = chatcompletion_kwargs.pop("api_base", None) azure_endpoint = chatcompletion_kwargs.pop("azure_endpoint", base_url) api_version = chatcompletion_kwargs.pop("api_version", None) api_key = chatcompletion_kwargs.pop("api_key", None) chatcompletion_kwargs.pop("api_type", None) if "engine" in chatcompletion_kwargs: model = chatcompletion_kwargs.pop("engine", None) else: model = chatcompletion_kwargs.pop("model", None) chatcompletion_kwargs.update({"model": model}) chatcompletion_kwargs.update(kwargs) client = openai.AzureOpenAI( api_key=api_key, azure_endpoint=azure_endpoint, api_version=api_version, timeout=request_timeout, ) else: if "base_url" in chatcompletion_kwargs: base_url = chatcompletion_kwargs.pop("base_url", None) else: base_url = chatcompletion_kwargs.pop("api_base", None) api_key = chatcompletion_kwargs.pop("api_key", None) organization = chatcompletion_kwargs.pop("organization", None) chatcompletion_kwargs.update(kwargs) client = openai.OpenAI( api_key=api_key, organization=organization, base_url=base_url, timeout=request_timeout ) try: completions = client.chat.completions.create(**chatcompletion_kwargs) response = completions.model_dump() if response["choices"][0]["finish_reason"] == "length": raise BadRequestError( message="maximum context length exceeded", response=None, body=None ) except BadRequestError as e: if "maximum context length" in e.message: if model_name == "gpt-4" and "gpt-4-32k" in CONFIG.api_keys: model_name = "gpt-4-32k" elif model_name == "gpt-4" and "gpt-4-1106-preview" in CONFIG.api_keys: model_name = "gpt-4-1106-preview" else: if "gpt-3.5-turbo-1106" in CONFIG.api_keys: model_name = "gpt-3.5-turbo-1106" else: model_name = "gpt-3.5-turbo-16k" print(f"max context length reached, retrying with {model_name}") chatcompletion_kwargs = get_apiconfig_by_model(model_name) request_timeout = kwargs.pop("request_timeout", 60) if "base_url" in chatcompletion_kwargs: base_url = chatcompletion_kwargs.pop("base_url", None) else: base_url = chatcompletion_kwargs.pop("api_base", None) api_key = chatcompletion_kwargs.pop("api_key", None) chatcompletion_kwargs.update(kwargs) chatcompletion_kwargs.pop("schema_error_retry", None) completions = client.chat.completions.create(**chatcompletion_kwargs) response = completions.model_dump() else: raise e return response
Handle operation of OpenAI v1.x.x chat completion. This function operates OpenAI v1.x.x chat completion with provided arguments. It gets the model name, applies a JSON web token, if the response indicates the context length has been exceeded, it attempts to get a higher-capacity language model if it exists in the configuration and reattempts the operation. Otherwise, it will raise an error message. Args: **kwargs: Variable length argument list including (model:str, etc.). Returns: response (dict): A dictionary containing the response from the Chat API. The structure of the dictionary is based on the API response format. Raises: BadRequestError: If any error occurs during chat completion operation or context length limit exceeded and no fallback models available.
6,241
import os import base64 import uuid import json5 as json import requests from colorama import Fore from XAgent.utils import ToolCallStatusCode from XAgent.ai_functions import function_manager from XAgent.recorder import RunningRecoder def is_wrapped_response(obj: dict) -> bool: """ Check if the response object is wrapped. Args: obj (dict): The response object. Returns: bool: True if the response object is wrapped, False otherwise. """ if 'type' in obj and obj['type'] in ['simple', 'composite', 'binary'] and 'data' in obj: return True return False The provided code snippet includes necessary dependencies for implementing the `unwrap_tool_response` function. Write a Python function `def unwrap_tool_response(obj, logger=None)` to solve the following problem: Unwrap the tool response object. Args: obj: The tool response object. logger: The logger. Returns: The unwrapped tool response object. Here is the function: def unwrap_tool_response(obj, logger=None): """ Unwrap the tool response object. Args: obj: The tool response object. logger: The logger. Returns: The unwrapped tool response object. """ if isinstance(obj, dict): if is_wrapped_response(obj): match obj['type']: case 'simple': return obj['data'] case 'binary': name = obj.get('name', uuid.uuid4().hex) if obj['media_type'] == 'image/png' and not str(name).endswith('.png'): name += '.png' with open(os.path.join('local_workspace', name), 'wb') as f: f.write(base64.b64decode(obj['data'])) return { 'media_type': obj['media_type'], 'file_name': name } case 'composite': return [unwrap_tool_response(o, logger) for o in obj['data']] else: return obj elif isinstance(obj, (str, int, float, bool, list)): return obj elif obj is None: return None else: logger.typewriter_log( f'Unknown type {type(obj)} in unwrap_tool_response', Fore.YELLOW) return None
Unwrap the tool response object. Args: obj: The tool response object. logger: The logger. Returns: The unwrapped tool response object.
6,242
import asyncio from contextlib import contextmanager import json import os import threading import traceback import uuid from datetime import datetime from typing import List from colorama import Fore from apscheduler.schedulers.asyncio import AsyncIOScheduler from apscheduler.schedulers.blocking import BlockingScheduler from XAgentServer.application.core.envs import XAgentServerEnv from XAgentServer.database.connect import SessionLocal from XAgentServer.enums.status import StatusEnum from XAgentServer.exts.exception_ext import XAgentError from XAgentServer.interaction import XAgentInteraction from XAgentServer.loggers.logs import Logger from XAgentServer.models.interaction import InteractionBase from XAgentServer.models.parameter import InteractionParameter from XAgentServer.models.raw import XAgentRaw from XAgentServer.server import XAgentServer from XAgentServer.application.cruds.interaction import InteractionCRUD from XAgentServer.application.global_val import redis from command_input import CommandLineInput SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) The provided code snippet includes necessary dependencies for implementing the `get_db` function. Write a Python function `def get_db()` to solve the following problem: Provide a transactional scope around a series of operations. Here is the function: def get_db(): """ Provide a transactional scope around a series of operations. """ session = SessionLocal() try: yield session session.commit() except: session.rollback() raise finally: session.close()
Provide a transactional scope around a series of operations.
6,243
from xgen.parser import FunctionParser from xgen.server.datamodel import * from xgen.server.message_formater import format import xgen.text.generate as generate from xgen.models.transformers import XTransformers from outlines.models.transformers import TransformersTokenizer from vllm.sampling_params import LogitsProcessor from vllm.engine.arg_utils import AsyncEngineArgs from vllm.engine.async_llm_engine import AsyncLLMEngine from vllm.utils import random_uuid from vllm import SamplingParams from typing import List import torch from addict import Dict import json from fastapi import FastAPI, Response, status, Request from fastapi.middleware.cors import CORSMiddleware import argparse import uvicorn from transformers import AutoTokenizer async def health(): return "ok"
null
6,244
from xgen.parser import FunctionParser from xgen.server.datamodel import * from xgen.server.message_formater import format import xgen.text.generate as generate from xgen.models.transformers import XTransformers from outlines.models.transformers import TransformersTokenizer from vllm.sampling_params import LogitsProcessor from vllm.engine.arg_utils import AsyncEngineArgs from vllm.engine.async_llm_engine import AsyncLLMEngine from vllm.utils import random_uuid from vllm import SamplingParams from typing import List import torch from addict import Dict import json from fastapi import FastAPI, Response, status, Request from fastapi.middleware.cors import CORSMiddleware import argparse import uvicorn from transformers import AutoTokenizer model_path = args.model_path engine = AsyncLLMEngine.from_engine_args(engine_configs) tokenizer = AutoTokenizer.from_pretrained( model_path, trust_remote_code='auto', tokenizer_revision=None) class ConstrainedLogitsProcessor(LogitsProcessor): def __init__(self, extra_arguments, functions, function_call, tokenizer_path, device=None): if function_call is not None and len(function_call) == 0: function_call = None self.dp = FunctionParser() outline_tokenizer = TransformersTokenizer(tokenizer_path) fake_model = Dict() fake_model.device = device model = XTransformers(fake_model, outline_tokenizer) self.dp.create_all_functions_model(extra_arguments, functions, function_call) regex_list = self.dp.models_to_regex() self.generator = generate.multi_regex(model, regex_list) def __call__(self, generated_token_ids: List[int], logits: torch.Tensor) -> torch.Tensor: generated_token_ids = torch.LongTensor(generated_token_ids).view(1, -1).to(logits.device) masked_logits = self.generator.create_proposal(generated_token_ids, logits.view(1, -1)) return masked_logits def format(item, dump_method='yaml'): """ reformat the request item item: {"messages": ..., "arguments": ..., "functions": ..., "function_call": ...} """ if "arguments" in item and item['arguments'] is not None and len(item['arguments']) > 0: arguments_string = "# Global Arguments\n" + my_dump(item["arguments"], "yaml") else: arguments_string = "" if "functions" in item and item['functions'] is not None and len(item['functions']) > 0: functions_string = "# Functions\n" + my_dump(item["functions"], "yaml") else: functions_string = "" if "function_call" in item and item['function_call'] is not None and 'name' in item['function_call']: function_call_string = f"You need to use {item['function_call']['name']} function." else: function_call_string = "" system_prefix = ( "Response with following json schemas:\n" + f"{arguments_string}\n{functions_string}\n{function_call_string}" ) system_prefix = system_prefix.strip() dialog = item["messages"] sys_msg_idx = find_system_msg(dialog) if sys_msg_idx == -1: dialog.insert(0, {"role": "system", "content": system_prefix}) else: dialog[sys_msg_idx]["content"] += "\n" + system_prefix dialog = merge_messages(dialog) input_string = "".join([message_format(msg) for msg in dialog]) return input_string async def chat_function(response:Response,request: Request): global engine call_msg = await request.json() model_name = call_msg.get("model","") if model_name != "agentllama" and model_name != "xagentllm": return {"model": "", "choices": [{'message': {'content': f'bad model {model_name}'}, 'finish_reason': 'error', 'index': -1}]} messages = call_msg.get("messages",None) arguments = call_msg.get("arguments",None) functions = call_msg.get("functions",None) function_call = call_msg.get("function_call",None) task_prompt = format({ "messages": messages, "arguments": arguments, "functions": functions, "function_call": function_call }, dump_method='json') processor = ConstrainedLogitsProcessor(arguments, functions, function_call, model_path, device='cuda') sampling_params = SamplingParams( temperature=call_msg.get("temperature", 0.8), top_p=call_msg.get("top_p", 1.0), frequency_penalty=call_msg.get("frequency_penalty",0.5), presence_penalty=call_msg.get("presence_penalty", 0.0), repetition_penalty=call_msg.get("repetition_penalty",1.2), max_tokens=call_msg.get("max_tokens", 4000), logits_processors=[processor] ) # make request request_id = random_uuid() # tokenize prompt input_ids = tokenizer.encode(task_prompt, return_tensors="pt") prompt_tokens = input_ids.shape[1] results_generator = engine.generate(task_prompt, sampling_params, request_id) final_output = None async for request_output in results_generator: if await request.is_disconnected(): # Abort the request if the client disconnects. await engine.abort(request_id) return Response(status_code=499) final_output = request_output sequence = final_output.outputs[0].text # tokenizer output output_ids = tokenizer.encode(sequence, return_tensors="pt") completion_tokens = output_ids.shape[1] try: sequence = json.loads(sequence) if "extra_parameters" in sequence: sequence["arguments"] = sequence["extra_parameters"] sequence.pop("extra_parameters") except Exception as e: res = {"status": "fail","broken_json":sequence,"error_message":str(e)} else: res = { "status": "success", "function_res": sequence, "usage":{ "prompt_tokens": prompt_tokens, "completion_tokens": completion_tokens, "total_tokens": prompt_tokens + completion_tokens } } if res["status"] == "fail": response.status_code = 400 return {"model": "", "choices": [{'message': {'content': json.dumps(res,ensure_ascii=False)}, 'finish_reason': 'error', 'index': -1}]} response_model = { 'model': model_name, 'usage': res["usage"], 'choices':[ { "message":{ "content": json.dumps(res["function_res"], ensure_ascii=False) }, "finish_reason":"stop", "index":0, } ] } return response_model
null
6,245
from typing import TYPE_CHECKING, Dict, List, Optional, Set, Union import interegular from cachetools import TTLCache from outlines.text.generate.regex import Regex from outlines.text.fsm import create_fsm_index_tokenizer, make_deterministic_fsm def to_hash(vocabulary, regex_str, eos_token): string = f"vocabulary:{''.join(vocabulary)}, regex: {regex_str}, eos_token: {eos_token}" return hash(string)
null
6,246
from typing import TYPE_CHECKING, Dict, List, Optional, Set, Union import interegular from cachetools import TTLCache from outlines.text.generate.regex import Regex from outlines.text.fsm import create_fsm_index_tokenizer, make_deterministic_fsm class XRegex(Regex): def __init__( self, model, regex_string: str, max_tokens: Optional[int] = None, *, sampler: Optional["Sampler"] = None, stop: Union[str, List[str]] = [], allow_empty_tokens: bool = True, initial_state: Optional[int] = None, final_states: Optional[Set[int]] = None, states_to_token_maps: Optional[Dict[int, Dict[int, int]]] = None, empty_token_ids: Optional[Set[int]] = None, ): vocab = model.tokenizer.vocabulary sorted_vocabulary = [ model.tokenizer.convert_token_to_string(k) for k, v in sorted(vocab.items(), key=lambda kv: kv[1]) ] hash_key = to_hash(list(sorted_vocabulary), regex_string, model.tokenizer.eos_token) if hash_key in pstate_to_vocab_path_cache: regex_fsm,states_to_token_maps,empty_token_ids = pstate_to_vocab_path_cache[hash_key] initial_state = regex_fsm.initial final_states = regex_fsm.finals else: regex_pattern = interegular.parse_pattern(regex_string) regex_fsm, _ = make_deterministic_fsm(regex_pattern.to_fsm().reduce()) ( states_to_token_maps, empty_token_ids, ) = create_fsm_index_tokenizer(regex_fsm, model.tokenizer) initial_state = regex_fsm.initial final_states = regex_fsm.finals pstate_to_vocab_path_cache[hash_key] = (regex_fsm,states_to_token_maps,empty_token_ids) super().__init__( model, regex_string, max_tokens, sampler=sampler,stop=stop, allow_empty_tokens=allow_empty_tokens,initial_state=initial_state,final_states=final_states, states_to_token_maps=states_to_token_maps,empty_token_ids=empty_token_ids) def multi_regex( model, choices: List[str], max_tokens: Optional[int] = None, *, sampler: Optional["Sampler"] = None, allow_empty_tokens: bool = True, ): regex_str = r"(" + r"|".join(choices) + r")" return XRegex( model, regex_str, max_tokens, sampler=sampler, allow_empty_tokens=allow_empty_tokens, )
null
6,247
from transformers.generation.logits_process import ( LogitsProcessorList, RepetitionPenaltyLogitsProcessor, TemperatureLogitsWarper, TopKLogitsWarper, TopPLogitsWarper, ) from outlines.models.transformers import Transformers,TransformersTokenizer from typing import TYPE_CHECKING, List, Optional, Tuple, Union import torch The provided code snippet includes necessary dependencies for implementing the `prepare_logits_processor` function. Write a Python function `def prepare_logits_processor( temperature: float, repetition_penalty: float, top_p: float, top_k: int ) -> LogitsProcessorList` to solve the following problem: generate the logits processor with params Here is the function: def prepare_logits_processor( temperature: float, repetition_penalty: float, top_p: float, top_k: int ) -> LogitsProcessorList: """generate the logits processor with params""" processor_list = LogitsProcessorList() # TemperatureLogitsWarper doesn't accept 0.0, 1.0 makes it a no-op so we skip two cases. if temperature >= 1e-5 and temperature != 1.0: processor_list.append(TemperatureLogitsWarper(temperature)) if repetition_penalty > 1.0: processor_list.append(RepetitionPenaltyLogitsProcessor(repetition_penalty)) if 1e-8 <= top_p < 1.0: processor_list.append(TopPLogitsWarper(top_p)) if top_k > 0: processor_list.append(TopKLogitsWarper(top_k)) return processor_list
generate the logits processor with params
6,248
import json import os import orjson from io import StringIO from ruamel import yaml def yaml_load(string): def my_load(string, dump_method): if dump_method == 'yaml': return yaml_load(string) elif dump_method == 'json': return json.loads(string) else: raise NotImplementedError
null
6,249
import os from contextlib import redirect_stdout import argparse from copy import deepcopy from XAgent.config import CONFIG, ARGS from command import CommandLine, CommandLineParam The provided code snippet includes necessary dependencies for implementing the `parse_args` function. Write a Python function `def parse_args() -> argparse.Namespace` to solve the following problem: Parse the command line arguments and return them as an argparse.Namespace object. Returns: argparse.Namespace: An object containing command line arguments and their values. Here is the function: def parse_args() -> argparse.Namespace: """ Parse the command line arguments and return them as an argparse.Namespace object. Returns: argparse.Namespace: An object containing command line arguments and their values. """ parser = argparse.ArgumentParser() parser.add_argument("--task", type=str, required=True, help="The task description.") parser.add_argument("--upload-files", nargs='+', dest="upload_files", help="List of files to upload.") parser.add_argument("--model", type=str, help="Model identifier for the task.") parser.add_argument("--record-dir", type=str, dest="record_dir", help="Directory to record task execution logs.") parser.add_argument("--mode", type=str, default="auto", help="Operational mode: 'auto' or 'manual'.") parser.add_argument("--quiet", action="store_true", default=False, help="Run in quiet mode; minimal output.") parser.add_argument("--max-subtask-chain-length", type=int, dest="max_subtask_chain_length", help="Maximum length of subtask chain.") parser.add_argument("--enable-ask-human-for-help", action="store_true", dest="enable_ask_human_for_help", help="Flag to enable asking for human assistance.") parser.add_argument("--max-plan-refine-chain-length", type=int, dest="max_plan_refine_chain_length", help="Maximum length of plan refinement chain.") parser.add_argument("--max-plan-tree-depth", type=int, dest="max_plan_tree_depth", help="Maximum depth of the plan tree.") parser.add_argument("--max-plan-tree-width", type=int, dest="max_plan_tree_width", help="Maximum width of the plan tree.") parser.add_argument("--max-retry-times", type=int, dest="max_retry_times", help="Maximum number of retry attempts.") parser.add_argument("--config-file", type=str, default=os.getenv('CONFIG_FILE', 'assets/config.yml'), dest="config_file", help="Path to the configuration file.") return parser.parse_args()
Parse the command line arguments and return them as an argparse.Namespace object. Returns: argparse.Namespace: An object containing command line arguments and their values.
6,250
import os from contextlib import redirect_stdout import argparse from copy import deepcopy from XAgent.config import CONFIG, ARGS from command import CommandLine, CommandLineParam def start_command_line(args_dict: dict) -> None: """ Start the command line interface with the provided arguments. Args: args_dict (dict): A dictionary of command line arguments. """ param = CommandLineParam( task=args_dict['task'], upload_files=args_dict.get('upload_files'), role="Assistant", mode=args_dict["mode"], ) cmd = CommandLine(param) cmd.start() CONFIG = XAgentConfig.get_default_config() ARGS = {} recorder = RunningRecoder() The provided code snippet includes necessary dependencies for implementing the `execute_command_line_process` function. Write a Python function `def execute_command_line_process(args: argparse.Namespace, quiet_mode: bool = False) -> None` to solve the following problem: Execute the command line process based on the parsed arguments. If quiet mode is enabled, redirect stdout to a file specified by the recorder's record_root_dir. Args: args (argparse.Namespace): Parsed command line arguments. quiet_mode (bool): Whether to run in quiet mode, outputting to a file instead of the terminal. Here is the function: def execute_command_line_process(args: argparse.Namespace, quiet_mode: bool = False) -> None: """ Execute the command line process based on the parsed arguments. If quiet mode is enabled, redirect stdout to a file specified by the recorder's record_root_dir. Args: args (argparse.Namespace): Parsed command line arguments. quiet_mode (bool): Whether to run in quiet mode, outputting to a file instead of the terminal. """ args_dict = vars(args) for key, value in args_dict.items(): if value is not None: if key == 'model': ARGS['default_completion_kwargs'] = deepcopy(CONFIG['default_completion_kwargs']) ARGS['default_completion_kwargs']['model'] = value else: ARGS[key] = value # Redirect stdout to a file if quiet mode is true if quiet_mode: from XAgent.running_recorder import recorder record_file_path = os.path.join(recorder.record_root_dir, "command_line.ansi") with open(record_file_path, "w", encoding="utf-8") as file, redirect_stdout(file): start_command_line(args_dict) else: start_command_line(args_dict)
Execute the command line process based on the parsed arguments. If quiet mode is enabled, redirect stdout to a file specified by the recorder's record_root_dir. Args: args (argparse.Namespace): Parsed command line arguments. quiet_mode (bool): Whether to run in quiet mode, outputting to a file instead of the terminal.
6,251
import os import psutil import uvicorn import httpx import asyncio import traceback import datetime import docker.types from fastapi import FastAPI, Cookie,Request,HTTPException,Response from fastapi.responses import JSONResponse,RedirectResponse from config import CONFIG,logger,MANAGER_ID from connections import db,docker_client from models import ToolServerNode, NodeChecker app = FastAPI() async def route_to_node(requset:Request,*,node_id:str = Cookie(None)): """ Routes a request to a specific node. Fetches the node info, checks if it is valid and running. Updates latest request time in the database and then sends a post request to the node. Args: request (Request): The request object containing all request information. Returns: Response: The response object containing all response information received from the node. Raises: HTTPException: If node_id is not valid or if the node is not running or not responding. """ # logger.info("accept node_id:",node_id) node = await ToolServerNode.find_one(ToolServerNode.id == node_id) if node is None: raise HTTPException(status_code=403,detail="invalid node_id: " + str(node_id)) if node.status != "running": raise HTTPException(status_code=503,detail="node is not running: " + str(node_id)) # update latest_req_time in db node.last_req_time = datetime.datetime.utcnow() await node.replace() #post request to node method = requset.method headers = dict(requset.headers) body = await requset.body() url = "http://" + node.ip +":"+str(node.port) + requset.url.path logger.info("Request to node: " + url) async with httpx.AsyncClient(timeout=None) as client: try: response = await client.request(method,url,headers=headers,data=body) except httpx.RequestError: traceback.print_exc() raise HTTPException(status_code=503, detail="node is not responding") logger.info('Response from node: ' + str(response.status_code)) res = Response(content=response.content, status_code=response.status_code, headers=response.headers) return res CONFIG = XAgentConfig.get_default_config() MANAGER_ID = uuid.uuid4().hex db: AgnosticDatabase = mongo_client[os.getenv('DB_COLLECTION', 'TSM')] class ToolServerNode(Document): """ A class that represents a node in the database. """ id: str short_id: str status: str health: str last_req_time: datetime ip: str port: int class NodeChecker(Document): manager_id: str interval: float pid: int async def check_nodes_status_loop(): """ An infinite loop that checks the status of the nodes and waits 1 second before each iteration. """ logger.info("Nodes status checker started.") while True: try: await check_nodes_status() except: import traceback traceback.print_exc() await asyncio.sleep(CONFIG['node'].get('health_check_interval',1)) The provided code snippet includes necessary dependencies for implementing the `startup` function. Write a Python function `async def startup()` to solve the following problem: Event handler triggered on startup of the app. Sets up necessary configurations like checking and creating table nodes if not exists in databse, creating subprocess to update node status, and registering path to node. Here is the function: async def startup(): """ Event handler triggered on startup of the app. Sets up necessary configurations like checking and creating table nodes if not exists in databse, creating subprocess to update node status, and registering path to node. """ from beanie import init_beanie await init_beanie(database=db, document_models=[ToolServerNode,NodeChecker],) # create subprocess to update node status if CONFIG['builtin_monitor']: from node_checker import check_nodes_status_loop async for checker in NodeChecker.find_all(): if not psutil.pid_exists(checker.pid): checker.delete() checker = NodeChecker( manager_id=MANAGER_ID, interval=float(CONFIG['node'].get('health_check_interval',1)), pid=os.getpid() ) await checker.save() asyncio.create_task(check_nodes_status_loop()) # register path to node for path in CONFIG['redirect_to_node_path']['post']: app.add_api_route(path, route_to_node, methods=["POST"]) for path in CONFIG['redirect_to_node_path']['get']: app.add_api_route(path, route_to_node, methods=["GET"])
Event handler triggered on startup of the app. Sets up necessary configurations like checking and creating table nodes if not exists in databse, creating subprocess to update node status, and registering path to node.
6,252
import os import psutil import uvicorn import httpx import asyncio import traceback import datetime import docker.types from fastapi import FastAPI, Cookie,Request,HTTPException,Response from fastapi.responses import JSONResponse,RedirectResponse from config import CONFIG,logger,MANAGER_ID from connections import db,docker_client from models import ToolServerNode, NodeChecker MANAGER_ID = uuid.uuid4().hex db: AgnosticDatabase = mongo_client[os.getenv('DB_COLLECTION', 'TSM')] class NodeChecker(Document): manager_id: str interval: float pid: int The provided code snippet includes necessary dependencies for implementing the `shutdown` function. Write a Python function `async def shutdown()` to solve the following problem: Event handler on shutdown of the app. Specifically closes the database cursor if the database type os sqlite3. Here is the function: async def shutdown(): """ Event handler on shutdown of the app. Specifically closes the database cursor if the database type os sqlite3. """ async for checker in NodeChecker.find(NodeChecker.manager_id == MANAGER_ID): await checker.delete() db.client.close()
Event handler on shutdown of the app. Specifically closes the database cursor if the database type os sqlite3.
6,253
import os import psutil import uvicorn import httpx import asyncio import traceback import datetime import docker.types from fastapi import FastAPI, Cookie,Request,HTTPException,Response from fastapi.responses import JSONResponse,RedirectResponse from config import CONFIG,logger,MANAGER_ID from connections import db,docker_client from models import ToolServerNode, NodeChecker The provided code snippet includes necessary dependencies for implementing the `alive` function. Write a Python function `async def alive()` to solve the following problem: Endpoint to check if the service is running. Returns: str: "alive" Here is the function: async def alive(): """ Endpoint to check if the service is running. Returns: str: "alive" """ return "alive"
Endpoint to check if the service is running. Returns: str: "alive"
6,254
import os import psutil import uvicorn import httpx import asyncio import traceback import datetime import docker.types from fastapi import FastAPI, Cookie,Request,HTTPException,Response from fastapi.responses import JSONResponse,RedirectResponse from config import CONFIG,logger,MANAGER_ID from connections import db,docker_client from models import ToolServerNode, NodeChecker async def wait_for_node_startup(node_id:str): """ Wait for the startup of node with id node_id. It probes the node status every seconds until creation_wait_seconds reached. Args: node_id (str): The unique identifier of the node whose startup is to be waited for. Returns: bool: True if node has started successfully, False if time out occured before node startup. Raises: HTTPException: If node is not found in the databse. """ MAX_PROBE_TIMES = CONFIG['node']['creation_wait_seconds'] probe_times = 0 while probe_times < MAX_PROBE_TIMES: node = await ToolServerNode.find_one(ToolServerNode.id == node_id) if node is None: raise HTTPException(status_code=503, detail="Failed to detect node status! Node not found in db!") if CONFIG['node']['health_check']: if node.health == 'healthy': return True else: if node.status == "running": return True probe_times += 1 await asyncio.sleep(1) return False CONFIG = XAgentConfig.get_default_config() logger = logging.getLogger(CONFIG['logger']) logger.setLevel(CONFIG['logger_level']) docker_client = docker.from_env() class ToolServerNode(Document): """ A class that represents a node in the database. """ id: str short_id: str status: str health: str last_req_time: datetime ip: str port: int The provided code snippet includes necessary dependencies for implementing the `read_cookie_info` function. Write a Python function `async def read_cookie_info()` to solve the following problem: Fetch server version and node info, create docker container and set the response cookies with the key "node_id" and value as the id of the created container. Also, adds the created node's details to the databse and waits for the node to startup. Returns: JSONResponse: A response object with status, headers and cookies set accordingly. Raises: HTTPException: If node creation timeout occurs. Here is the function: async def read_cookie_info(): """ Fetch server version and node info, create docker container and set the response cookies with the key "node_id" and value as the id of the created container. Also, adds the created node's details to the databse and waits for the node to startup. Returns: JSONResponse: A response object with status, headers and cookies set accordingly. Raises: HTTPException: If node creation timeout occurs. """ # append server version info content = {"message": "add cookie","version":CONFIG['version']} response = JSONResponse(content=content) response.headers["Server"] = "ToolServerManager/" + CONFIG['version'] # create a docker container container = docker_client.containers.run( device_requests=[docker.types.DeviceRequest(**req) for req in CONFIG['node']['device_requests']] if CONFIG['node']['device_requests'] else None, **(CONFIG['node']['creation_kwargs']),) logger.info("Node created: " + container.id) response.set_cookie(key="node_id", value=container.id) container.reload() node = ToolServerNode( id=container.id, short_id=container.short_id, status=container.attrs["State"]["Status"], ip=container.attrs["NetworkSettings"]["Networks"][CONFIG['node']['creation_kwargs']['network']]["IPAddress"], port=CONFIG['node'].get('port',31942), last_req_time=datetime.datetime.utcnow(), health=container.attrs['State']['Health']['Status'] if CONFIG['node']['health_check'] else None ) await node.insert() # probe node status every seconds until creation_wait_seconds reached if await wait_for_node_startup(container.id): return response else: logger.warning("Node status detection timeout: " + container.id) raise HTTPException(status_code=503, detail="Node creation timeout!")
Fetch server version and node info, create docker container and set the response cookies with the key "node_id" and value as the id of the created container. Also, adds the created node's details to the databse and waits for the node to startup. Returns: JSONResponse: A response object with status, headers and cookies set accordingly. Raises: HTTPException: If node creation timeout occurs.
6,255
import os import psutil import uvicorn import httpx import asyncio import traceback import datetime import docker.types from fastapi import FastAPI, Cookie,Request,HTTPException,Response from fastapi.responses import JSONResponse,RedirectResponse from config import CONFIG,logger,MANAGER_ID from connections import db,docker_client from models import ToolServerNode, NodeChecker async def wait_for_node_startup(node_id:str): """ Wait for the startup of node with id node_id. It probes the node status every seconds until creation_wait_seconds reached. Args: node_id (str): The unique identifier of the node whose startup is to be waited for. Returns: bool: True if node has started successfully, False if time out occured before node startup. Raises: HTTPException: If node is not found in the databse. """ MAX_PROBE_TIMES = CONFIG['node']['creation_wait_seconds'] probe_times = 0 while probe_times < MAX_PROBE_TIMES: node = await ToolServerNode.find_one(ToolServerNode.id == node_id) if node is None: raise HTTPException(status_code=503, detail="Failed to detect node status! Node not found in db!") if CONFIG['node']['health_check']: if node.health == 'healthy': return True else: if node.status == "running": return True probe_times += 1 await asyncio.sleep(1) return False logger = logging.getLogger(CONFIG['logger']) logger.setLevel(CONFIG['logger_level']) docker_client = docker.from_env() class ToolServerNode(Document): """ A class that represents a node in the database. """ id: str short_id: str status: str health: str last_req_time: datetime ip: str port: int The provided code snippet includes necessary dependencies for implementing the `reconnect_session` function. Write a Python function `async def reconnect_session(node_id:str = Cookie(None))` to solve the following problem: Reconnect session of a node. Fetches node info and restarts the node if it exists. Args: node_id (str, optional): The unique identifier of the node. Defaults to Cookie(None). Returns: str: Success message if node restarts successfully. Raises: HTTPException: If node restart timeout occurs. Here is the function: async def reconnect_session(node_id:str = Cookie(None)): """ Reconnect session of a node. Fetches node info and restarts the node if it exists. Args: node_id (str, optional): The unique identifier of the node. Defaults to Cookie(None). Returns: str: Success message if node restarts successfully. Raises: HTTPException: If node restart timeout occurs. """ node = await ToolServerNode.find_one(ToolServerNode.id == node_id) if node is None: return "invalid node_id: " + str(node_id) # restart node container = docker_client.containers.get(node_id) if container is not None: container.restart() logger.info("Node restarted: " + node_id) if await wait_for_node_startup(node_id): return "Reconnect session: " + str(node_id) else: logger.warning("Node restart timeout: " + node_id) raise HTTPException(status_code=503, detail="Node restart timeout!")
Reconnect session of a node. Fetches node info and restarts the node if it exists. Args: node_id (str, optional): The unique identifier of the node. Defaults to Cookie(None). Returns: str: Success message if node restarts successfully. Raises: HTTPException: If node restart timeout occurs.
6,256
import os import psutil import uvicorn import httpx import asyncio import traceback import datetime import docker.types from fastapi import FastAPI, Cookie,Request,HTTPException,Response from fastapi.responses import JSONResponse,RedirectResponse from config import CONFIG,logger,MANAGER_ID from connections import db,docker_client from models import ToolServerNode, NodeChecker logger = logging.getLogger(CONFIG['logger']) logger.setLevel(CONFIG['logger_level']) docker_client = docker.from_env() class ToolServerNode(Document): """ A class that represents a node in the database. """ id: str short_id: str status: str health: str last_req_time: datetime ip: str port: int The provided code snippet includes necessary dependencies for implementing the `close_session` function. Write a Python function `async def close_session(node_id:str = Cookie(None))` to solve the following problem: Close session of a node. Fetches node info and stops the node if it exists and is not already exited. Args: node_id (str, optional): The unique identifier of the node. Defaults to Cookie(None). Returns: str: Success message if node stops successfully. Here is the function: async def close_session(node_id:str = Cookie(None)): """ Close session of a node. Fetches node info and stops the node if it exists and is not already exited. Args: node_id (str, optional): The unique identifier of the node. Defaults to Cookie(None). Returns: str: Success message if node stops successfully. """ node = await ToolServerNode.find_one(ToolServerNode.id == node_id) if node is None: return "invalid node_id: " + str(node_id) # stop node container = docker_client.containers.get(node_id) if container is not None and container.attrs["State"]["Status"] != "exit": container.stop() logger.info("Node stopped: " + node_id) return "Close session: " + str(node_id)
Close session of a node. Fetches node info and stops the node if it exists and is not already exited. Args: node_id (str, optional): The unique identifier of the node. Defaults to Cookie(None). Returns: str: Success message if node stops successfully.
6,257
import os import psutil import uvicorn import httpx import asyncio import traceback import datetime import docker.types from fastapi import FastAPI, Cookie,Request,HTTPException,Response from fastapi.responses import JSONResponse,RedirectResponse from config import CONFIG,logger,MANAGER_ID from connections import db,docker_client from models import ToolServerNode, NodeChecker logger = logging.getLogger(CONFIG['logger']) logger.setLevel(CONFIG['logger_level']) docker_client = docker.from_env() class ToolServerNode(Document): """ A class that represents a node in the database. """ id: str short_id: str status: str health: str last_req_time: datetime ip: str port: int The provided code snippet includes necessary dependencies for implementing the `release_session` function. Write a Python function `async def release_session(node_id:str = Cookie(None))` to solve the following problem: Release session of a node. Fetches node info and kills the node if it exists and is not already exited. Also, removes the node. Args: node_id (str, optional): The unique identifier of the node. Defaults to Cookie(None). Returns: str: Success message if node is successfully killed and removed. Here is the function: async def release_session(node_id:str = Cookie(None)): """ Release session of a node. Fetches node info and kills the node if it exists and is not already exited. Also, removes the node. Args: node_id (str, optional): The unique identifier of the node. Defaults to Cookie(None). Returns: str: Success message if node is successfully killed and removed. """ node = await ToolServerNode.find_one(ToolServerNode.id == node_id) if node is None: return "invalid node_id: " + str(node_id) # delete node in docker container = docker_client.containers.get(node_id) if container is not None: if container.attrs["State"]["Status"] != "exited": container.kill() logger.info("Node killed: " + node_id) container.remove() logger.info("Node deleted: " + node_id) return "Release session: " + str(node_id)
Release session of a node. Fetches node info and kills the node if it exists and is not already exited. Also, removes the node. Args: node_id (str, optional): The unique identifier of the node. Defaults to Cookie(None). Returns: str: Success message if node is successfully killed and removed.
6,258
import os import sys import zipfile import traceback from typing import Coroutine,List from fastapi import FastAPI,Body,UploadFile from fastapi.requests import Request from fastapi.exceptions import HTTPException from starlette.responses import FileResponse from config import CONFIG,logger from core.register import ToolRegister from core.exceptions import ToolNotFound,OutputNotReady from utils.retriever import ada_retriever,build_tool_embeddings from utils.response import wrap_tool_response app = FastAPI() def build_tool_embeddings(tools_json: list[dict]) -> tuple: """ Build tool embeddings. Args: tools_json: The list of dictionaries containing tool data. Returns: A tuple containing a list of document embeddings and a dictionary mapping tool id to tool name. """ cfg = CONFIG['retriver'] if os.path.exists(cfg['id2tool_file']) and os.path.exists(cfg['embedding_file']): id2tool = json.load(open(cfg['id2tool_file'], "r")) doc_embedings = np.load(cfg['embedding_file']) if len(id2tool) != len(doc_embedings): logger.error('Embedding file and id2tool file do not match! Rebuild embeddings!') id2tool = {} doc_embedings = [] else: id2tool = {} doc_embedings = [] # check embedding file whether need to be updated # get all current tool names # tool_names = set(map(lambda tool_json: tool_json['name'], tools_json)) # cached_tool_names = set(id2tool.values()) # if tool_names == cached_tool_names: # logger.info('No tools change, use cached embeddings!') # return doc_embedings, id2tool return doc_embedings, id2tool # update embeddings logger.info('Tools change detected, updating embeddings...') url = cfg['endpoint'] headers = cfg['headers'] new_id2tool = { str(i):tool_json['name'] for i,tool_json in enumerate(tools_json) } json.dump(new_id2tool, open(cfg['id2tool_file'], "w"), indent=4) def get_embedding(tool_json:dict) -> list: """ Get embedding for a certain tool. Args: tool_json: The dictionary containing tool data. Returns: A list of tool embeddings. """ payload = {'input':json.dumps(tool_json)} payload.update(cfg['payload']) try: response = requests.post(url, json=payload, headers=headers) response.raise_for_status() except Exception as e: logger.error(f'Failed to get embedding for tool {tool_json["name"]}! Error: {e}') return [-1.000001] * cfg['embedding_dim'] return response.json()['data'][0]['embedding'] uncached_tools = list(filter(lambda tool_json: tool_json['name'] not in cached_tool_names, tools_json)) uncached_tools_name = list(map(lambda tool_json: tool_json['name'],uncached_tools)) uncached_doc_embedings = [] with ThreadPoolExecutor(16) as pool: futures = [pool.submit(get_embedding, tool_json) for tool_json in uncached_tools] for future in tqdm.tqdm(futures,ncols=100): uncached_doc_embedings.append(future.result()) new_doc_embedings = [] for tool_json in tools_json: if tool_json['name'] not in cached_tool_names: new_doc_embedings.append( uncached_doc_embedings[ uncached_tools_name.index(tool_json['name']) ]) else: for doc_id in id2tool.keys(): if id2tool[doc_id] == tool_json['name']: new_doc_embedings.append(doc_embedings[int(doc_id)]) break new_doc_embedings = np.array(new_doc_embedings) np.save(cfg['embedding_file'], new_doc_embedings) logger.info('Embeddings updated! New embeddings saved!') return doc_embedings, new_id2tool The provided code snippet includes necessary dependencies for implementing the `startup` function. Write a Python function `def startup()` to solve the following problem: Startup function to initialize the required services and variables for the application. Here is the function: def startup(): """ Startup function to initialize the required services and variables for the application. """ try: # start docker service os.system('service docker start') except: pass app.tool_register = ToolRegister() app.doc_embeddings, app.id2tool = build_tool_embeddings(app.tool_register.get_all_tools_dict(include_invisible=True))
Startup function to initialize the required services and variables for the application.
6,259
import os import sys import zipfile import traceback from typing import Coroutine,List from fastapi import FastAPI,Body,UploadFile from fastapi.requests import Request from fastapi.exceptions import HTTPException from starlette.responses import FileResponse from config import CONFIG,logger from core.register import ToolRegister from core.exceptions import ToolNotFound,OutputNotReady from utils.retriever import ada_retriever,build_tool_embeddings from utils.response import wrap_tool_response The provided code snippet includes necessary dependencies for implementing the `root` function. Write a Python function `async def root()` to solve the following problem: Root function that returns a message Hello World. Returns: dict: A dictionary containing a welcoming message. Here is the function: async def root(): """ Root function that returns a message Hello World. Returns: dict: A dictionary containing a welcoming message. """ return {"message": "Hello World"}
Root function that returns a message Hello World. Returns: dict: A dictionary containing a welcoming message.
6,260
import os import sys import zipfile import traceback from typing import Coroutine,List from fastapi import FastAPI,Body,UploadFile from fastapi.requests import Request from fastapi.exceptions import HTTPException from starlette.responses import FileResponse from config import CONFIG,logger from core.register import ToolRegister from core.exceptions import ToolNotFound,OutputNotReady from utils.retriever import ada_retriever,build_tool_embeddings from utils.response import wrap_tool_response CONFIG = XAgentConfig.get_default_config() The provided code snippet includes necessary dependencies for implementing the `upload_file` function. Write a Python function `async def upload_file(file:UploadFile)` to solve the following problem: This function allows the user to upload a file to the work directory defined in configuration file. Args: file (fastapi.UploadFile): The file to be uploaded. Returns: dict: A message denoting successful upload of the file. Here is the function: async def upload_file(file:UploadFile): """ This function allows the user to upload a file to the work directory defined in configuration file. Args: file (fastapi.UploadFile): The file to be uploaded. Returns: dict: A message denoting successful upload of the file. """ upload_file = file.file.read() file_name = file.filename work_directory = CONFIG['filesystem']['work_directory'] with open(os.path.join(work_directory,file_name),'wb') as f: f.write(upload_file) return {"message": "Upload Success!"}
This function allows the user to upload a file to the work directory defined in configuration file. Args: file (fastapi.UploadFile): The file to be uploaded. Returns: dict: A message denoting successful upload of the file.
6,261
import os import sys import zipfile import traceback from typing import Coroutine,List from fastapi import FastAPI,Body,UploadFile from fastapi.requests import Request from fastapi.exceptions import HTTPException from starlette.responses import FileResponse from config import CONFIG,logger from core.register import ToolRegister from core.exceptions import ToolNotFound,OutputNotReady from utils.retriever import ada_retriever,build_tool_embeddings from utils.response import wrap_tool_response CONFIG = XAgentConfig.get_default_config() The provided code snippet includes necessary dependencies for implementing the `download_file` function. Write a Python function `async def download_file(file_path:str=Body(...),file_type:str=Body(default='text/plain'))` to solve the following problem: This function downloads a file from the work directory. Args: file_path (str): The path of the file to be downloaded. file_type (str, optional): Type of the file. Defaults to 'text/plain'. Returns: starlette.responses.FileResponse: File response containing the requested file for user to download. Here is the function: async def download_file(file_path:str=Body(...),file_type:str=Body(default='text/plain')): """ This function downloads a file from the work directory. Args: file_path (str): The path of the file to be downloaded. file_type (str, optional): Type of the file. Defaults to 'text/plain'. Returns: starlette.responses.FileResponse: File response containing the requested file for user to download. """ work_directory = CONFIG['filesystem']['work_directory'] if file_path.startswith(os.path.basename(work_directory)): file_path = file_path[len(os.path.basename(work_directory))+1:] response = FileResponse( path=os.path.join(work_directory,file_path), filename=os.path.basename(file_path), ) return response
This function downloads a file from the work directory. Args: file_path (str): The path of the file to be downloaded. file_type (str, optional): Type of the file. Defaults to 'text/plain'. Returns: starlette.responses.FileResponse: File response containing the requested file for user to download.
6,262
import os import sys import zipfile import traceback from typing import Coroutine,List from fastapi import FastAPI,Body,UploadFile from fastapi.requests import Request from fastapi.exceptions import HTTPException from starlette.responses import FileResponse from config import CONFIG,logger from core.register import ToolRegister from core.exceptions import ToolNotFound,OutputNotReady from utils.retriever import ada_retriever,build_tool_embeddings from utils.response import wrap_tool_response CONFIG = XAgentConfig.get_default_config() The provided code snippet includes necessary dependencies for implementing the `download_workspace` function. Write a Python function `async def download_workspace()` to solve the following problem: This function downloads the workspace which is a directory consisting of all the uploaded files. Returns: starlette.responses.FileResponse: File response containing the workspace for the user to download. Here is the function: async def download_workspace(): """ This function downloads the workspace which is a directory consisting of all the uploaded files. Returns: starlette.responses.FileResponse: File response containing the workspace for the user to download. """ work_directory = CONFIG['filesystem']['work_directory'] zip = zipfile.ZipFile('/tmp/workspace.zip','w',zipfile.ZIP_DEFLATED) for path,dirs,files in os.walk(work_directory): fpath= path.replace(work_directory,'') for file in files: zip.write(os.path.join(path,file),os.path.join(fpath,file)) zip.close() response = FileResponse( path=os.path.join(work_directory,'/tmp/workspace.zip'), filename='workspace.zip', ) return response
This function downloads the workspace which is a directory consisting of all the uploaded files. Returns: starlette.responses.FileResponse: File response containing the workspace for the user to download.
6,263
import os import sys import zipfile import traceback from typing import Coroutine,List from fastapi import FastAPI,Body,UploadFile from fastapi.requests import Request from fastapi.exceptions import HTTPException from starlette.responses import FileResponse from config import CONFIG,logger from core.register import ToolRegister from core.exceptions import ToolNotFound,OutputNotReady from utils.retriever import ada_retriever,build_tool_embeddings from utils.response import wrap_tool_response CONFIG = XAgentConfig.get_default_config() The provided code snippet includes necessary dependencies for implementing the `get_workspace_structure` function. Write a Python function `async def get_workspace_structure()` to solve the following problem: This function generates the structure of the workspace directory. Returns: dict: A dictionary depicting the structure of the workspace directory. Here is the function: async def get_workspace_structure(): """ This function generates the structure of the workspace directory. Returns: dict: A dictionary depicting the structure of the workspace directory. """ work_directory = CONFIG['filesystem']['work_directory'] def generate_directory_structure(path): result = {'name':os.path.basename(path)} if os.path.isdir(path): result['type'] = 'directory' result['children'] = [generate_directory_structure(os.path.join(path,child)) for child in os.listdir(path)] else: result['type'] = 'file' return result return generate_directory_structure(work_directory)
This function generates the structure of the workspace directory. Returns: dict: A dictionary depicting the structure of the workspace directory.
6,264
import os import sys import zipfile import traceback from typing import Coroutine,List from fastapi import FastAPI,Body,UploadFile from fastapi.requests import Request from fastapi.exceptions import HTTPException from starlette.responses import FileResponse from config import CONFIG,logger from core.register import ToolRegister from core.exceptions import ToolNotFound,OutputNotReady from utils.retriever import ada_retriever,build_tool_embeddings from utils.response import wrap_tool_response app = FastAPI() The provided code snippet includes necessary dependencies for implementing the `get_available_tools` function. Write a Python function `async def get_available_tools()` to solve the following problem: This function returns the available tools and environments registered in the ToolRegister. Returns: dict: A dictionary of available tools, environments and the JSON representation of the tools. Here is the function: async def get_available_tools(): """ This function returns the available tools and environments registered in the ToolRegister. Returns: dict: A dictionary of available tools, environments and the JSON representation of the tools. """ tool_register:ToolRegister = app.tool_register return { "available_envs": tool_register.get_all_envs(), "available_tools": tool_register.get_all_tools(), "tools_json": tool_register.get_all_tools_dict(), }
This function returns the available tools and environments registered in the ToolRegister. Returns: dict: A dictionary of available tools, environments and the JSON representation of the tools.
6,265
import os import sys import zipfile import traceback from typing import Coroutine,List from fastapi import FastAPI,Body,UploadFile from fastapi.requests import Request from fastapi.exceptions import HTTPException from starlette.responses import FileResponse from config import CONFIG,logger from core.register import ToolRegister from core.exceptions import ToolNotFound,OutputNotReady from utils.retriever import ada_retriever,build_tool_embeddings from utils.response import wrap_tool_response app = FastAPI() logger = logging.getLogger(CONFIG['logger']) logger.setLevel(CONFIG['logger_level']) def ada_retriever(doc_embeddings: list, id2tool:dict, question: str, top_k: int=5) -> list: """ Retrieve tools related to the provided question. Args: doc_embeddings: The list of document embeddings. id2tool: A dictionary mapping tool id to tool name. question: The question for the ADA retriever. top_k: The number of top tools to return (default is 5). Returns: A list of retrieved tools. """ cfg = CONFIG['retriver'] url = cfg['endpoint'] headers = cfg['headers'] payload = {'input':question} payload.update(cfg['payload']) response = requests.post(url, json=payload, headers=headers) query_embedding = np.array(response.json()['data'][0]['embedding']) similarities = cosine_similarity([query_embedding], doc_embeddings) sorted_doc_indices = sorted(range(len(similarities[0])), key=lambda i: similarities[0][i], reverse=True) retrieved_tools = list(map(lambda doc_id: id2tool[str(doc_id)],sorted_doc_indices[:top_k])) return retrieved_tools The provided code snippet includes necessary dependencies for implementing the `retrieving_tools` function. Write a Python function `async def retrieving_tools(question:str=Body(...), top_k:int=Body(default=5))` to solve the following problem: This function retrieves the tool names based on a query question using the ADA retriever. Args: question (str): The query question for which tools are to be retrieved. top_k (int, optional): The number of top similar tools to be retrieved. Defaults to 5. Returns: dict: A dictionary with the list of retrieved tools and JSON representations of the tools. Raises: HTTPException: If an error occurs during retrieving the tools. Here is the function: async def retrieving_tools(question:str=Body(...), top_k:int=Body(default=5)): """ This function retrieves the tool names based on a query question using the ADA retriever. Args: question (str): The query question for which tools are to be retrieved. top_k (int, optional): The number of top similar tools to be retrieved. Defaults to 5. Returns: dict: A dictionary with the list of retrieved tools and JSON representations of the tools. Raises: HTTPException: If an error occurs during retrieving the tools. """ try: retrieved_tools = ada_retriever(app.doc_embeddings, app.id2tool, question, top_k) except Exception as e: error_report = traceback.format_exc() logger.error(error_report) raise HTTPException(status_code=500, detail=f"Errorhappens when retrieving tools:\n{e}\n\n" + error_report) tool_register:ToolRegister = app.tool_register tools_json = [] for tool_name in retrieved_tools: if tool_name in tool_register.tools: tools_json.append(tool_register.get_tool_dict(tool_name)) return { "retrieved_tools":retrieved_tools, "tools_json":tools_json, }
This function retrieves the tool names based on a query question using the ADA retriever. Args: question (str): The query question for which tools are to be retrieved. top_k (int, optional): The number of top similar tools to be retrieved. Defaults to 5. Returns: dict: A dictionary with the list of retrieved tools and JSON representations of the tools. Raises: HTTPException: If an error occurs during retrieving the tools.
6,266
import os import sys import zipfile import traceback from typing import Coroutine,List from fastapi import FastAPI,Body,UploadFile from fastapi.requests import Request from fastapi.exceptions import HTTPException from starlette.responses import FileResponse from config import CONFIG,logger from core.register import ToolRegister from core.exceptions import ToolNotFound,OutputNotReady from utils.retriever import ada_retriever,build_tool_embeddings from utils.response import wrap_tool_response app = FastAPI() The provided code snippet includes necessary dependencies for implementing the `get_json_schema_for_tool` function. Write a Python function `async def get_json_schema_for_tool(tool_names:List[str]=Body(...))` to solve the following problem: This function returns the JSON schema for the given list of tools. Args: tool_names (List[str]): List of tool names for which JSON schema is required. Returns: dict: JSON schema dictionary for all the available tools and list of error names for missing tools. Here is the function: async def get_json_schema_for_tool(tool_names:List[str]=Body(...)): """ This function returns the JSON schema for the given list of tools. Args: tool_names (List[str]): List of tool names for which JSON schema is required. Returns: dict: JSON schema dictionary for all the available tools and list of error names for missing tools. """ tool_register:ToolRegister = app.tool_register error_names = [] tools_json = [] for tool_name in tool_names: if tool_name not in tool_register.tools: error_names.append(tool_name) else: tools_json.append(tool_register.get_tool_dict(tool_name)) return { "tools_json": tools_json, "missing_tools": error_names, }
This function returns the JSON schema for the given list of tools. Args: tool_names (List[str]): List of tool names for which JSON schema is required. Returns: dict: JSON schema dictionary for all the available tools and list of error names for missing tools.
6,267
import os import sys import zipfile import traceback from typing import Coroutine,List from fastapi import FastAPI,Body,UploadFile from fastapi.requests import Request from fastapi.exceptions import HTTPException from starlette.responses import FileResponse from config import CONFIG,logger from core.register import ToolRegister from core.exceptions import ToolNotFound,OutputNotReady from utils.retriever import ada_retriever,build_tool_embeddings from utils.response import wrap_tool_response app = FastAPI() The provided code snippet includes necessary dependencies for implementing the `get_json_schema_for_env` function. Write a Python function `async def get_json_schema_for_env(env_names:List[str]=Body(...))` to solve the following problem: This function returns the JSON schema for the given list of tool environments. Args: env_names (List[str]): List of environment names for which JSON schema is required. Returns: dict: JSON schema dictionary for all the available environments and list of error names for missing environments. Here is the function: async def get_json_schema_for_env(env_names:List[str]=Body(...)): """ This function returns the JSON schema for the given list of tool environments. Args: env_names (List[str]): List of environment names for which JSON schema is required. Returns: dict: JSON schema dictionary for all the available environments and list of error names for missing environments. """ tool_register:ToolRegister = app.tool_register error_names = [] envs_json = [] for env_name in env_names: if env_name not in tool_register.envs: error_names.append(env_name) else: envs_json.append(tool_register.get_env_dict(env_name)) return { "envs_json": envs_json, "missing_envs": error_names, }
This function returns the JSON schema for the given list of tool environments. Args: env_names (List[str]): List of environment names for which JSON schema is required. Returns: dict: JSON schema dictionary for all the available environments and list of error names for missing environments.
6,268
import os import sys import zipfile import traceback from typing import Coroutine,List from fastapi import FastAPI,Body,UploadFile from fastapi.requests import Request from fastapi.exceptions import HTTPException from starlette.responses import FileResponse from config import CONFIG,logger from core.register import ToolRegister from core.exceptions import ToolNotFound,OutputNotReady from utils.retriever import ada_retriever,build_tool_embeddings from utils.response import wrap_tool_response app = FastAPI() logger = logging.getLogger(CONFIG['logger']) logger.setLevel(CONFIG['logger_level']) The provided code snippet includes necessary dependencies for implementing the `register_new_tool` function. Write a Python function `async def register_new_tool(tool_name:str=Body(...), code:str=Body(...))` to solve the following problem: This function allows the user to register a new tool by providing the tool name and code. Args: tool_name (str): The name of the new tool. code (str): The code for the new tool. Returns: dict: A dictionary representing the registered tool. Raises: HTTPException: If an error occurs during registering the new tool. Here is the function: async def register_new_tool(tool_name:str=Body(...), code:str=Body(...)): """ This function allows the user to register a new tool by providing the tool name and code. Args: tool_name (str): The name of the new tool. code (str): The code for the new tool. Returns: dict: A dictionary representing the registered tool. Raises: HTTPException: If an error occurs during registering the new tool. """ tool_register:ToolRegister = app.tool_register try: tool_dict = tool_register.register_tool(tool_name,code) except Exception as e: error_report = traceback.format_exc() logger.error(error_report) raise HTTPException(status_code=406, detail=f"Error happens when registering new tool:\n{e}\n\n" + error_report) return tool_dict
This function allows the user to register a new tool by providing the tool name and code. Args: tool_name (str): The name of the new tool. code (str): The code for the new tool. Returns: dict: A dictionary representing the registered tool. Raises: HTTPException: If an error occurs during registering the new tool.
6,269
import os import sys import zipfile import traceback from typing import Coroutine,List from fastapi import FastAPI,Body,UploadFile from fastapi.requests import Request from fastapi.exceptions import HTTPException from starlette.responses import FileResponse from config import CONFIG,logger from core.register import ToolRegister from core.exceptions import ToolNotFound,OutputNotReady from utils.retriever import ada_retriever,build_tool_embeddings from utils.response import wrap_tool_response app = FastAPI() logger = logging.getLogger(CONFIG['logger']) logger.setLevel(CONFIG['logger_level']) class OutputNotReady(Exception): """The output is not ready. """ def __init__(self, *args: object,type:str='retry',next_calling:str=None,arguments:dict={}) -> None: super().__init__(*args) self.type = type self.next_calling = next_calling self.arguments = arguments def next_try(self): """Prepare the next try by returning a dictionary containing type, next calling event and arguments.""" return { "type":self.type, "next_calling":self.next_calling, "arguments":self.arguments } class ToolNotFound(Exception): """Custom exception class that is raised when the tool is not found. Args: *args (object): Variable length argument list. tool_name (str): The name of the tool. Attributes: tool_name (str): The name of the tool. """ def __init__(self, *args: object,tool_name:str=None) -> None: super().__init__(*args) self.tool_name = tool_name def __str__(self) -> str: """Returns the formatted exception error message with the name of the tool""" s = super().__str__() if s != '': s += f'\nThe tool {self.tool_name} is not found!' else: s = f'The tool {self.tool_name} is not found!' return s def wrap_tool_response(obj:Any) -> dict|list|str|int|float|bool: """ Wrap the tool response in a standardized object structure (depending on its type) to allow decoding. Format ====== ``` { 'type': 'simple', # for single return value like python basic types 'data': obj }, { 'type': 'binary', # for single return value like python basic types 'media_type':'image/png', # or other media types 'name': 'xxx', # file name of the binary data 'data': obj # base64 encoded binary data }, str,int,float,bool,list is directly returned or { 'type': 'composite', # for multiple return values 'data': [ { 'type': 'simple', 'data': obj1 }, { 'type': 'simple', 'data': obj2 } ] } ``` Standardized Structures: - For simple data types (str, int, float, bool), the object is directly returned. - For composite types (tuples), data is wrapped in an object with a composite type. - For binary data, data is base64 encoded and wrapped in an object with a binary type. Args: obj (Any): any Python object that needs to be wrapped. Returns: Union[dict, list, str, int, float, bool]: the wrapped response. Raises: logger.warning: raises warning if the type of 'obj' is unknown. """ if isinstance(obj,tuple): if len(obj) == 0: ret = { 'type': 'simple', 'data': None } elif len(obj) == 1: ret = { 'type': 'simple', 'data': obj[0] } else: ret = { 'type': 'composite', 'data': [] } for o in obj: ret['data'].append(wrap_tool_response(o)) elif isinstance(obj,bytes): ret = { 'type': 'binary', 'media_type': 'bytes', 'name': None, 'data': base64.b64encode(obj).decode() } elif isinstance(obj,(str,int,float,bool,list)) or obj is None: ret = obj elif isinstance(obj,dict): # check if already wrapped if is_wrapped_response(obj): ret = obj else: ret = { 'type': 'simple', 'data': obj } else: logger.warning(f'Unknown type {type(obj)} in wrap_tool_response') ret = { 'type': 'simple', 'data': obj } return ret The provided code snippet includes necessary dependencies for implementing the `execute_tool` function. Write a Python function `async def execute_tool(tool_name:str=Body(...), arguments:dict=Body(...), env_name:str=Body(default=None))` to solve the following problem: This function executes a tool with the provided arguments and environment. Args: tool_name (str): The name of the tool to be executed. arguments (dict): The arguments for executing the tool. env_name (str, optional): The name of the tool environment in which tool is to be executed. Defaults to None. Returns: dict: The result of executing the tool is wrapped in a dictionary. Raises: HTTPException: If an error occurs during tool execution. Here is the function: async def execute_tool(tool_name:str=Body(...), arguments:dict=Body(...), env_name:str=Body(default=None)): """ This function executes a tool with the provided arguments and environment. Args: tool_name (str): The name of the tool to be executed. arguments (dict): The arguments for executing the tool. env_name (str, optional): The name of the tool environment in which tool is to be executed. Defaults to None. Returns: dict: The result of executing the tool is wrapped in a dictionary. Raises: HTTPException: If an error occurs during tool execution. """ tool_register:ToolRegister = app.tool_register try: if env_name is not None: tool = tool_register[env_name,tool_name] else: tool = tool_register[tool_name] result = tool(**arguments) if isinstance(result,Coroutine): result = await result result = wrap_tool_response(result) except ToolNotFound as e: raise HTTPException(status_code=404, detail=str(e)) except OutputNotReady as e: raise HTTPException(status_code=450, detail=e.next_try()) except HTTPException as e: raise e except Exception as e: trace_info = traceback.format_exc() logger.error(f'Error happens when executing tool {tool_name}! Exception: {e}\n{trace_info}') raise HTTPException(status_code=500, detail=trace_info) return result
This function executes a tool with the provided arguments and environment. Args: tool_name (str): The name of the tool to be executed. arguments (dict): The arguments for executing the tool. env_name (str, optional): The name of the tool environment in which tool is to be executed. Defaults to None. Returns: dict: The result of executing the tool is wrapped in a dictionary. Raises: HTTPException: If an error occurs during tool execution.
6,270
import logging import importlib import traceback from copy import deepcopy from typing import Optional,Callable,Any,Type,Union from core.base import BaseEnv from core.labels import ToolLabels,EnvLabels from core.exceptions import ToolNotFound,EnvNotFound,ToolRegisterError from config import CONFIG class BaseEnv: """ BaseEnv class. It helps to handle functions and function names of the classes and subclasses. This class provides methods to get all functions, defined functions and their names. It also ensures the configuration updates if necessary. Attributes: config(Dict[str, Any], optional): A dictionary containing the configuration. Defaults to an empty dictionary. """ def __init__(self, config: Dict[str, Any] = {}): """Initialize BaseEnv class with specified or default configuration. Args: config (Dict[str, Any], optional): A dictionary containing the configuration. Defaults to an empty dictionary. Notes: The configuration is deep copied to avoid modifications to the original object. """ self.config = deepcopy(CONFIG) if isinstance(config, dict): self.config.update(config) def __get_all_func_name__(cls) -> list[str]: """Get all the function names of the class, excluding methods starting with '_' character. Returns: list[str]: A list that contains function names. """ return [name for name in dir(cls) if not str(name).startswith('_') and callable(getattr(cls, name))] def __get_all_func__(cls) -> list[Callable]: """Get all functions of the class, excluding methods starting with '__' characters. Returns: list[Callable]: A list that contains functions. """ func_names = cls.__get_all_func_name__() return list(map(getattr, [cls]*len(func_names), func_names)) def __get_defined_func__(cls) -> list[Callable]: """Get all the functions of the subclass, excluding methods starting with '_' character. Returns: list[Callable]: A list that contains defined functions of the subclass. Notes: This method removes the parent class's methods from the functions list to provide only the functions that are newly defined in the subclass. """ functions = cls.__get_all_func__() for parent_cls in cls.__bases__: if not issubclass(parent_cls, BaseEnv): continue parent_functions = parent_cls.__get_all_func__() functions = list(filter(lambda x: x not in parent_functions, functions)) return functions def __get_defined_func_name__(cls) -> list[str]: """Get all the function names of the subclass, excluding methods starting with '_' character. Returns: list[str]: A list that contains function names of the subclass. """ functions = cls.__get_defined_func__() return list(map(lambda x: x.__name__, functions)) def get_func_name(func:Callable,env:BaseEnv=None)->str: if env is None or not hasattr(env,'env_labels'): if hasattr(func,'tool_labels'): return func.tool_labels.name else: return func.__name__ else: if hasattr(func,'tool_labels'): return env.env_labels.name + '_' + func.tool_labels.name else: return env.env_labels.name + '_' + func.__name__
null
6,271
import logging import inspect import docstring_parser from typing import Optional,Callable,Any,Type,Union from core.base import BaseEnv from core.labels import ToolLabels,EnvLabels from config import CONFIG def generate_tool_labels( name: str = None, enabled: bool = True, disabled_reason: Optional[str] = None, func: Callable[..., Any] = None, visible:bool = True, )->Union[ToolLabels,None]: """ Generate and return tool labels for the provided function. If the tool is not enabled, then a debug log message is printed and None is returned. Args: name (str, optional): The name of the tool. If it's not specified, the function's name is used. enabled (bool, optional): Determines if the tool is enabled or not. Defaults to True. disabled_reason (Optional[str], optional): The reason why the tool is disabled. Defaults to None. func (Callable[..., Any], optional): The function for which the tool labels are generated. Defaults to None. visible(bool, optional): The visibility status of the tool. Defaults to True. Returns: Union[ToolLabels,None]: A ToolLabels object containing tool information or None if tool is not enabled. """ if not enabled: if disabled_reason is not None: logger.debug(f"tool '{func.__name__}' is disabled: {disabled_reason}") return None # check if the method have full annotations auto_signature = {} func_desc = docstring_parser.parse(func.__doc__) required = [] for arg in func_desc.params: auto_signature[arg.arg_name] = { 'type':arg.type_name, # TODO support self defined type 'description':arg.description, } if arg.default is not None: auto_signature[arg.arg_name]['default'] = arg.default if not arg.is_optional: required.append(arg.arg_name) # for arg in inspect.getargs(func.__code__).args: # if arg in auto_signature: # continue # if arg in ['self','cls','config','return']: # continue # # if arg not in func.__annotations__: # # raise SyntaxError(f'Signature is None and the annotation of varable {arg} in func {func.__name__} is not found!') # auto_signature[arg] = { # 'type':'string', # 'description':'' # TODO try to generate description # } tool_name = func.__name__ if name is None else name description = '' if func_desc.short_description is not None: description = func_desc.short_description if func_desc.long_description is not None: description += '\n' + func_desc.long_description return ToolLabels( name=tool_name, description=description, method=func, signature=auto_signature, required=required, enabled=enabled, disabled_reason=disabled_reason, visible=visible, ) class BaseEnv: """ BaseEnv class. It helps to handle functions and function names of the classes and subclasses. This class provides methods to get all functions, defined functions and their names. It also ensures the configuration updates if necessary. Attributes: config(Dict[str, Any], optional): A dictionary containing the configuration. Defaults to an empty dictionary. """ def __init__(self, config: Dict[str, Any] = {}): """Initialize BaseEnv class with specified or default configuration. Args: config (Dict[str, Any], optional): A dictionary containing the configuration. Defaults to an empty dictionary. Notes: The configuration is deep copied to avoid modifications to the original object. """ self.config = deepcopy(CONFIG) if isinstance(config, dict): self.config.update(config) def __get_all_func_name__(cls) -> list[str]: """Get all the function names of the class, excluding methods starting with '_' character. Returns: list[str]: A list that contains function names. """ return [name for name in dir(cls) if not str(name).startswith('_') and callable(getattr(cls, name))] def __get_all_func__(cls) -> list[Callable]: """Get all functions of the class, excluding methods starting with '__' characters. Returns: list[Callable]: A list that contains functions. """ func_names = cls.__get_all_func_name__() return list(map(getattr, [cls]*len(func_names), func_names)) def __get_defined_func__(cls) -> list[Callable]: """Get all the functions of the subclass, excluding methods starting with '_' character. Returns: list[Callable]: A list that contains defined functions of the subclass. Notes: This method removes the parent class's methods from the functions list to provide only the functions that are newly defined in the subclass. """ functions = cls.__get_all_func__() for parent_cls in cls.__bases__: if not issubclass(parent_cls, BaseEnv): continue parent_functions = parent_cls.__get_all_func__() functions = list(filter(lambda x: x not in parent_functions, functions)) return functions def __get_defined_func_name__(cls) -> list[str]: """Get all the function names of the subclass, excluding methods starting with '_' character. Returns: list[str]: A list that contains function names of the subclass. """ functions = cls.__get_defined_func__() return list(map(lambda x: x.__name__, functions)) class EnvLabels: """A class representing an environment. Each environment has a set of subtools associated with it. This object manages the collection of tools. Attributes: name (str): Name of the environment. description (str): Description of the environment. subtools_labels (dict): Collection of tools associated to the environment. defined_tools (list): List of tool names defined in the environment. cls (Type): Class that the environment pertains to. enabled (bool): Flag indicating whether the environment is enabled or not. disabled_reason (str): Reason for disabling the environment, if applicable. visible (bool): Flag indicating whether the environment is visible or not. """ def __init__( self, name: str, description: str, subtools_labels: dict[ToolLabels] = {}, defined_tools:list[str] = [], cls: Type = None, enabled: bool = True, disabled_reason: Optional[str] = None, visible: bool = True, ): self.name = name self.description = description self.subtools_labels = subtools_labels self.defined_tools = defined_tools self.cls = cls self.enabled = enabled self.disabled_reason = disabled_reason self.visible = visible def dict(self, include_invisible=False, max_show_tools: int = CONFIG['toolregister']['env_max_tools_display']) -> dict: """ Returns the environment's tools as a dictionary. Args: include_invisible (bool): If true, includes tools even if they're set as invisible. max_show_tools (int): Maximum number of tools to display in the output. Returns: dict: Dictionary of environment attributes and associated tools. """ if include_invisible: tools_name = list(self.subtools_labels.keys()) else: if CONFIG['toolregister']['parent_tools_visible']: tools_name = [tool_name for tool_name in self.subtools_labels.keys() if self.subtools_labels[tool_name].visible] else: tools_name = self.defined_tools if max_show_tools != -1 and len(tools_name) > max_show_tools: # only show first max_show_tools tools tools_name = tools_name[:max_show_tools] tools_name.append('...') return { "name": self.name, "description": self.description, "total_tools": len(self.subtools_labels), "tools": tools_name, } def __str__(self) -> str: """Returns the environment information as a formatted string. Returns: str: Formatted string containing environment attributes. """ return f"{self.name}: {self.description}" CONFIG = XAgentConfig.get_default_config() The provided code snippet includes necessary dependencies for implementing the `toolwrapper` function. Write a Python function `def toolwrapper( name: str = None, enabled: bool = True, disabled_reason: Optional[str] = None, parent_tools_visible: bool = CONFIG['toolregister']['parent_tools_visible'], visible:bool = True, )->Union[Type,Callable[..., Any]]` to solve the following problem: The tool decorator for class, used to create tool objects from ordinary class. Here is the function: def toolwrapper( name: str = None, enabled: bool = True, disabled_reason: Optional[str] = None, parent_tools_visible: bool = CONFIG['toolregister']['parent_tools_visible'], visible:bool = True, )->Union[Type,Callable[..., Any]]: """The tool decorator for class, used to create tool objects from ordinary class.""" def decorator(obj:object)->Union[Type,Callable[..., Any]]: if inspect.isclass(obj): cls = obj cls_name = name if name is not None else cls.__name__ if not issubclass(cls,BaseEnv): raise Exception(f'The class {cls} is not a subclass of BaseEnv!') description = cls.__doc__ if cls.__doc__ is not None else '' if not visible: description = 'Note: All tools of this env are invisible during all tools display, please check this env\'s defination to show all tools.\n' + description subtools_labels = {} if BaseEnv not in cls.__bases__: direct_parents = [parent.__name__ for parent in cls.__bases__] if not parent_tools_visible: description = f'Note: This env is subclass of {direct_parents}, and all tools of parent envs are inherited and not visible. You can try call parent tools or check this env\'s defination to show them.\n' + description else: description = f'Note: This env is subclass of {direct_parents}, and all tools of parent envs are inherited.\n' + description for parent in cls.__bases__: if hasattr(parent,'env_labels') and isinstance(parent.env_labels,EnvLabels): subtools_labels.update(parent.env_labels.subtools_labels) cls_func_names = cls.__get_defined_func_name__() for func_name in cls_func_names: origin_func = getattr(cls,func_name) tool_labels = generate_tool_labels( name=func_name, enabled=enabled, disabled_reason=disabled_reason, func=origin_func, visible=visible) if tool_labels is None: continue # label classmethod, staticmethod and instance method #check if the function is a classmethod if inspect.ismethod(origin_func) and not inspect.isfunction(origin_func): tool_labels.func_type = 'classmethod' # check if the function is a staticmethod if 'self' in inspect.getargs(origin_func.__code__).args: tool_labels.func_type = 'instancemethod' else: tool_labels.func_type = 'staticmethod' # tool_labels.dependent_cls = cls origin_func.tool_labels = tool_labels subtools_labels[tool_labels.name] = tool_labels cls.env_labels = EnvLabels( name=cls_name, description=description, subtools_labels=subtools_labels, defined_tools=cls_func_names, cls=cls, enabled=enabled, disabled_reason=disabled_reason, visible=visible ) return cls elif inspect.isfunction(obj): func = obj tool_labels = generate_tool_labels( name=name, enabled=enabled, disabled_reason=disabled_reason, func=func, visible=visible) func.tool_labels = tool_labels return func else: raise NotImplementedError(f'Object with type {type(obj)} not recognized!') return decorator
The tool decorator for class, used to create tool objects from ordinary class.
6,272
import re from fastapi import HTTPException ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])') The provided code snippet includes necessary dependencies for implementing the `remove_color` function. Write a Python function `def remove_color(text)` to solve the following problem: Removes ANSI escape sequences i.e. colors, from the text. Args: text (str): The text from which color needs to be removed. Returns: str: The filtered text with no color. Here is the function: def remove_color(text): """Removes ANSI escape sequences i.e. colors, from the text. Args: text (str): The text from which color needs to be removed. Returns: str: The filtered text with no color. """ return ansi_escape.sub('', text)
Removes ANSI escape sequences i.e. colors, from the text. Args: text (str): The text from which color needs to be removed. Returns: str: The filtered text with no color.
6,273
import asyncio from config import CONFIG from core.register import toolwrapper from core.exceptions import ToolExecutionError ALL_SHELLS: dict[int, asyncio.subprocess.Process] = {} async def read_exec_proc_display(exec_proc: asyncio.subprocess.Process): display = "" for pipe, name in zip([exec_proc.stderr,exec_proc.stdout], ['stderr','stdout']): ret = await async_read_pipe(pipe) if ret != b'': display += f'\n{name}:\n'+ ret.decode() return display CONFIG = XAgentConfig.get_default_config() class ToolExecutionError(HTTPException): """Custom exception class that is raised when the tool execution encounters an error. Args: error_msg (str): The error message during tool execution. """ def __init__(self,error_msg:str): if isinstance(error_msg,str): error_msg = remove_color(error_msg) super().__init__(500,error_msg) The provided code snippet includes necessary dependencies for implementing the `shell_command_executor` function. Write a Python function `async def shell_command_executor(command: str = '', run_async: bool = False, shell_id: int = None, kill:bool = False)` to solve the following problem: The shell tool that execute shell command in root privilege, return the output and error. You can use this tool to install packages, download files, run programs, etc. Set run_async=True to run the command in a new thread and return instantly if your command is time costly like install packages, host services. Example: ``` In: shell_command_executor(command='echo "hello world"') Out: "hello world" In: shell_command_executor(command='sleep 10', run_async=True) Out: {'shell_id': 0} # You can use this id to read the output and error later. In: shell_command_executor(shell_id=0, kill=True) Out: "" # The shell 0 will be killed. ``` :param string? command: The shell command to be executed, must avoid command requiring additional user input. Default is empty string. :param boolean? run_async: Whether to run the command asynchronously, default is False. If True, call this tool again with shell_id to get the final output and error. :param integer? shell_id: The id of shell to execute command, default is None, which means running in a new shell. Change this to execute command in the same shell. :param boolean? kill: If True, kill the shell which runs the command after execution. Default is False. Don't use any other kill command! Here is the function: async def shell_command_executor(command: str = '', run_async: bool = False, shell_id: int = None, kill:bool = False): """The shell tool that execute shell command in root privilege, return the output and error. You can use this tool to install packages, download files, run programs, etc. Set run_async=True to run the command in a new thread and return instantly if your command is time costly like install packages, host services. Example: ``` In: shell_command_executor(command='echo "hello world"') Out: "hello world" In: shell_command_executor(command='sleep 10', run_async=True) Out: {'shell_id': 0} # You can use this id to read the output and error later. In: shell_command_executor(shell_id=0, kill=True) Out: "" # The shell 0 will be killed. ``` :param string? command: The shell command to be executed, must avoid command requiring additional user input. Default is empty string. :param boolean? run_async: Whether to run the command asynchronously, default is False. If True, call this tool again with shell_id to get the final output and error. :param integer? shell_id: The id of shell to execute command, default is None, which means running in a new shell. Change this to execute command in the same shell. :param boolean? kill: If True, kill the shell which runs the command after execution. Default is False. Don't use any other kill command! """ if shell_id is not None: exec_proc = ALL_SHELLS.get(shell_id, None) if exec_proc is None: raise ToolExecutionError( {'Error': 'Shell not found or has been closed.'}) if exec_proc.returncode is not None: print(exec_proc.returncode) ALL_SHELLS.pop(shell_id) raise ToolExecutionError({'Error': 'Shell has been closed.'}) else: exec_proc = await asyncio.create_subprocess_shell( 'bash', stderr=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stdin=asyncio.subprocess.PIPE, cwd=CONFIG['filesystem']['work_directory']) shell_id = max(ALL_SHELLS.keys(), default=-1) + 1 ALL_SHELLS[shell_id] = exec_proc if not run_async: try: ret = await asyncio.wait_for(exec_proc.communicate(command.encode()), timeout=CONFIG['shell']['timeout']) except asyncio.TimeoutError: des = "Timeout while executing command." if kill: des += " Shell has been killed." exec_proc.kill() display = await read_exec_proc_display(exec_proc) if display != "": des += " But get some response:" + display raise ToolExecutionError(des) ALL_SHELLS.pop(shell_id) result = { 'ReturnCode': exec_proc.returncode, 'display': '' } if ret[1] != b'': result['display'] += f'\nstderr:\n'+ret[1].decode() if ret[0] != b'': result['display'] = f'\nstdout:\n'+ret[0].decode() if result['ReturnCode'] != 0 and not kill: raise ToolExecutionError(result) return result else: if command[-1] != '\n': command += '\n' exec_proc.stdin.write(command.encode()) await exec_proc.stdin.drain() await asyncio.sleep(5) result = {'shell_id': shell_id , 'display':await read_exec_proc_display(exec_proc)} if result['display'] == "": await asyncio.sleep(30) result['display'] = await read_exec_proc_display(exec_proc) if kill: exec_proc.kill() ALL_SHELLS.pop(shell_id) result['status'] = 'shell thread has been killed' else: result['status'] = 'shell still running, no return code' return result
The shell tool that execute shell command in root privilege, return the output and error. You can use this tool to install packages, download files, run programs, etc. Set run_async=True to run the command in a new thread and return instantly if your command is time costly like install packages, host services. Example: ``` In: shell_command_executor(command='echo "hello world"') Out: "hello world" In: shell_command_executor(command='sleep 10', run_async=True) Out: {'shell_id': 0} # You can use this id to read the output and error later. In: shell_command_executor(shell_id=0, kill=True) Out: "" # The shell 0 will be killed. ``` :param string? command: The shell command to be executed, must avoid command requiring additional user input. Default is empty string. :param boolean? run_async: Whether to run the command asynchronously, default is False. If True, call this tool again with shell_id to get the final output and error. :param integer? shell_id: The id of shell to execute command, default is None, which means running in a new shell. Change this to execute command in the same shell. :param boolean? kill: If True, kill the shell which runs the command after execution. Default is False. Don't use any other kill command!
6,274
import os import json import httpx from typing import Type from copy import deepcopy from config import CONFIG from core.base import BaseEnv from core.register import toolwrapper from utils.retriever import standardizing API_INFOS = {} def convert_rapidapi_desc_to_code(rapidapi_desc:dict)->list[dict]: tool_desc = { 'category':rapidapi_desc['category'], 'tool_name':standardizing(rapidapi_desc['tool_name']), } api_infos = {} for api_desc in rapidapi_desc['api_list']: api_name = standardizing(api_desc['name']) if api_name in ['from','class','return','false','true','id','and']: api_name = 'is_'+ api_name api_info = {'api_name':api_name} api_info.update(tool_desc) api_uri = '_'.join(['rapi',tool_desc['tool_name'],api_name]) args_doc = [] for param in api_desc['required_parameters']: args_doc.append(generate_arg_doc( param['name'], param['type'], param['description'], param['default'] if 'default' in param else None, )) for param in api_desc['optional_parameters']: args_doc.append(generate_arg_doc( param['name'], param['type'], param['description'], param['default'] if 'default' in param else None, True)) args_doc = '\n '.join(args_doc) code = f"""async def {api_uri}(self,*args,**kwargs): '''{rapidapi_desc['tool_description']} {api_info['description'] if 'description' in api_info else ''} {args_doc} ''' return await self._request_rapid_api('{api_uri}',kwargs) """ api_info['code'] = code api_infos[api_uri] = api_info return api_infos import os if os.path.exists("XAgentServer/application/core/prod_server_envs.py") and XAgentServerEnv.prod: from XAgentServer.application.core.prod_server_envs import XAgentServerEnv CONFIG = XAgentConfig.get_default_config() The provided code snippet includes necessary dependencies for implementing the `rapid_api_mapper` function. Write a Python function `def rapid_api_mapper(cls:Type)` to solve the following problem: Dynamic adding api functions to RapidAPIENnv. Here is the function: def rapid_api_mapper(cls:Type): """Dynamic adding api functions to RapidAPIENnv.""" #reading api list if not os.path.exists(CONFIG['rapidapi']['api_infos_json']): try: api_list = json.load(open(CONFIG['rapidapi']['api_raw_json'])) except: raise FileNotFoundError(f'Both api_infos_json and api_raw_json are not found! Failed to setup RapidAPIEnv!') for rapidapi_desc in api_list: API_INFOS.update(convert_rapidapi_desc_to_code(rapidapi_desc)) json.dump(API_INFOS,open(CONFIG['rapidapi']['api_infos_json'],'w'),indent=4) else: API_INFOS.update(json.load(open(CONFIG['rapidapi']['api_infos_json']))) for api_uri,api_info in API_INFOS.items(): exec(api_info['code']) setattr(cls,api_uri,eval(api_uri)) return cls
Dynamic adding api functions to RapidAPIENnv.
6,275
import subprocess import sys import select import os import io from typing import Union,Dict,Any from core.base import BaseEnv from core.register import toolwrapper,get_func_name from core.exceptions import OutputNotReady import os if os.path.exists("XAgentServer/application/core/prod_server_envs.py") and XAgentServerEnv.prod: from XAgentServer.application.core.prod_server_envs import XAgentServerEnv The provided code snippet includes necessary dependencies for implementing the `read_pipe` function. Write a Python function `def read_pipe(pipe:Union[io.StringIO,io.BytesIO],text=True)->Union[str,bytes]` to solve the following problem: Reading the `subprocess.PIPE` when readable. If `text` is `True`, return str, else return bytes. Here is the function: def read_pipe(pipe:Union[io.StringIO,io.BytesIO],text=True)->Union[str,bytes]: """Reading the `subprocess.PIPE` when readable. If `text` is `True`, return str, else return bytes. """ output = '' if text else b'' while True: ready_fds,_,_ = select.select( [pipe.fileno()],[],[],0.01) if len(ready_fds) == 0: break output += os.read(ready_fds[0],16384).decode() if text else os.read(ready_fds[0],16384) return output
Reading the `subprocess.PIPE` when readable. If `text` is `True`, return str, else return bytes.
6,276
import requests from config import CONFIG from core.register import toolwrapper bing_cfg = CONFIG['bing'] The provided code snippet includes necessary dependencies for implementing the `bing_search` function. Write a Python function `def bing_search(query:str,region:str = None)->str|list[str]` to solve the following problem: Return 3 most relevant results of a Bing search using the official Bing API. This tool does not provide website details, use other tools to browse website if you need. :param string query: The search query. :param string? region: The region code of the search, default to `en-US`. Available regions: `en-US`, `zh-CN`, `ja-JP`, `en-AU`, `en-CA`, `en-GB`, `de-DE`, `en-IN`, `en-ID`, `es-ES`, `fr-FR`, `it-IT`, `en-MY`, `nl-NL`, `en-NZ`, `en-PH`, `en-SG`, `en-ZA`, `sv-SE`, `tr-TR`. :return string: The results of the search. Here is the function: def bing_search(query:str,region:str = None)->str|list[str]: """Return 3 most relevant results of a Bing search using the official Bing API. This tool does not provide website details, use other tools to browse website if you need. :param string query: The search query. :param string? region: The region code of the search, default to `en-US`. Available regions: `en-US`, `zh-CN`, `ja-JP`, `en-AU`, `en-CA`, `en-GB`, `de-DE`, `en-IN`, `en-ID`, `es-ES`, `fr-FR`, `it-IT`, `en-MY`, `nl-NL`, `en-NZ`, `en-PH`, `en-SG`, `en-ZA`, `sv-SE`, `tr-TR`. :return string: The results of the search. """ # :param int num_results: The number of results to return. num_results = 3 endpoint = bing_cfg["endpoint"] api_key = bing_cfg["api_key"] if region is None: region = 'en-US' result = requests.get(endpoint, headers={'Ocp-Apim-Subscription-Key': api_key}, params={'q': query, 'mkt': region }, timeout=10) result.raise_for_status() result = result.json() pages = result["webPages"]["value"] search_results = [] for idx in range(min(len(pages),num_results)): message = { 'url':pages[idx]['url'], 'name':pages[idx]['name'], 'snippet':pages[idx]['snippet'] } search_results.append(message) # Return the list of search result return search_results
Return 3 most relevant results of a Bing search using the official Bing API. This tool does not provide website details, use other tools to browse website if you need. :param string query: The search query. :param string? region: The region code of the search, default to `en-US`. Available regions: `en-US`, `zh-CN`, `ja-JP`, `en-AU`, `en-CA`, `en-GB`, `de-DE`, `en-IN`, `en-ID`, `es-ES`, `fr-FR`, `it-IT`, `en-MY`, `nl-NL`, `en-NZ`, `en-PH`, `en-SG`, `en-ZA`, `sv-SE`, `tr-TR`. :return string: The results of the search.
6,277
import asyncio from config import CONFIG from core.register import toolwrapper from core.envs.filesystem import FileSystemEnv CODE_FS = FileSystemEnv() CONFIG = XAgentConfig.get_default_config() The provided code snippet includes necessary dependencies for implementing the `run_interpreter` function. Write a Python function `async def run_interpreter(code:str=None,command:str=None,filename:str='code.py')` to solve the following problem: The code interpreter tool that runs code and return the output. The `code` will be written to file `filename` and the `command` will be executed in a shell. Example: ``` run_interpreter(code='print("hello world")',command='python code.py') ``` :param string? code: The code to be written, default to `None`, which means no code will be written to file. :param string? command: The shell command to be executed should avoid requiring additional user input, default to `python {filename}`. :param string? filename: The filename to be written in mode `w`, default to `code.py`. Here is the function: async def run_interpreter(code:str=None,command:str=None,filename:str='code.py'): """The code interpreter tool that runs code and return the output. The `code` will be written to file `filename` and the `command` will be executed in a shell. Example: ``` run_interpreter(code='print("hello world")',command='python code.py') ``` :param string? code: The code to be written, default to `None`, which means no code will be written to file. :param string? command: The shell command to be executed should avoid requiring additional user input, default to `python {filename}`. :param string? filename: The filename to be written in mode `w`, default to `code.py`. """ if code is not None and code != "" and filename != "": CODE_FS.write_to_file(filename,code) if command is None: command = f'python {filename}' exec_proc = await asyncio.create_subprocess_shell( 'bash', stderr=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stdin=asyncio.subprocess.PIPE, cwd=CODE_FS.work_directory) ret = await asyncio.wait_for(exec_proc.communicate(command.encode()),timeout=CONFIG['shell']['timeout']) result = { 'ReturnCode':exec_proc.returncode, } if ret[1]!=b'': result['Error'] = ret[1].decode() if ret[0]!=b'': result['Output'] = ret[0].decode() return result
The code interpreter tool that runs code and return the output. The `code` will be written to file `filename` and the `command` will be executed in a shell. Example: ``` run_interpreter(code='print("hello world")',command='python code.py') ``` :param string? code: The code to be written, default to `None`, which means no code will be written to file. :param string? command: The shell command to be executed should avoid requiring additional user input, default to `python {filename}`. :param string? filename: The filename to be written in mode `w`, default to `code.py`.
6,278
import requests import xmltodict from config import CONFIG from core.register import toolwrapper The provided code snippet includes necessary dependencies for implementing the `calculator` function. Write a Python function `def calculator(expression:str)->str` to solve the following problem: It is a simple calculator, which can execute Python expressions: e.g., "(123 + 234) / 23 * 1.5 - 8". :param string expression: The python expression you requested. :return string: The execution results of the expression. Here is the function: def calculator(expression:str)->str: """It is a simple calculator, which can execute Python expressions: e.g., "(123 + 234) / 23 * 1.5 - 8". :param string expression: The python expression you requested. :return string: The execution results of the expression. """ globals={} locals={} try: # Wrap the code in an eval() call to return the result wrapped_code = f"__result__ = eval({repr(expression)}, globals(), locals())" exec(wrapped_code, globals, locals) return locals.get('__result__', None) except Exception as e: try: # If eval fails, attempt to exec the code without returning a result exec(expression, globals, locals) return "Code executed successfully." except Exception as e: return f"Error: {str(e)}"
It is a simple calculator, which can execute Python expressions: e.g., "(123 + 234) / 23 * 1.5 - 8". :param string expression: The python expression you requested. :return string: The execution results of the expression.
6,279
import base64 from typing import Callable,Dict,Any from config import logger The provided code snippet includes necessary dependencies for implementing the `is_base64` function. Write a Python function `def is_base64(s:str) -> bool` to solve the following problem: Check if the given string is a base64 sting or not. Args: s (str): the string to be checked. Returns: bool: Returns True if the given string is a base64 string, False otherwise. Here is the function: def is_base64(s:str) -> bool: """ Check if the given string is a base64 sting or not. Args: s (str): the string to be checked. Returns: bool: Returns True if the given string is a base64 string, False otherwise. """ try: base64.b64decode(s) return True except: return False
Check if the given string is a base64 sting or not. Args: s (str): the string to be checked. Returns: bool: Returns True if the given string is a base64 string, False otherwise.
6,280
import os import importlib def import_all_modules_in_folder(file,name): current_dir = os.path.dirname(file) all_modules = [] for item in os.listdir(current_dir): item_path = os.path.join(current_dir, item) if os.path.isfile(item_path) and item != '__init__.py' and item.endswith('.py'): module_name = item[:-3] elif os.path.isdir(item_path) and item != '__pycache__' and os.path.exists(os.path.join(item_path, '__init__.py')) and os.path.isfile(os.path.join(item_path, '__init__.py')): module_name = item else: continue full_module_path = f"{name}.{module_name}" # print(module_name,full_module_path) imported_module = importlib.import_module(full_module_path) globals()[module_name] = imported_module all_modules.append(imported_module) return all_modules
null
6,281
import asyncio import functools import time from colorama import Fore from XAgentServer.exts.exception_ext import XAgentTimeoutError, XAgentCloseError from inputimeout import inputimeout, TimeoutOccurred from XAgentServer.application.global_val import redis import math The provided code snippet includes necessary dependencies for implementing the `timer` function. Write a Python function `def timer(func)` to solve the following problem: Decorator function to time the execution of a function. Args: func (Function): The function to be timed. Returns: wrapper (Function): The wrapped function with added timing functionality. Here is the function: def timer(func): """ Decorator function to time the execution of a function. Args: func (Function): The function to be timed. Returns: wrapper (Function): The wrapped function with added timing functionality. """ @functools.wraps(func) def wrapper(*args, **kwargs): try: start_time = time.time() result = func(*args, **kwargs) end_time = time.time() except: pass return wrapper
Decorator function to time the execution of a function. Args: func (Function): The function to be timed. Returns: wrapper (Function): The wrapped function with added timing functionality.
6,282
import traceback import uvicorn from colorama import Fore from fastapi import FastAPI, Request, Response from fastapi.exceptions import RequestValidationError from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse from XAgentServer.application.core.envs import XAgentServerEnv from XAgentServer.application.dependence import (enable_dependence, enable_logger) from XAgentServer.exts.exception_ext import XAgentAuthError, XAgentDBError, XAgentError, XAgentFileError from XAgentServer.application.routers import conv, user, workspace from XAgentServer.application.websockets import base, recorder, replayer, share class XAgentServerEnv: """ XAgentServer environment variables if you change value of the environment variable, you need to restart the XAgentServer by running the following command: `python start_server.py` or start a unicorn server by yourself """ app = "app:app" prod: bool = config.get("PROD", "False").lower() == "true" base_dir = "XAgentServer" use_redis: bool = False recorder_root_dir = "running_records" # you can set default_login with True, # use the default user "admin" with token "xagent-admin" to login, default_login: bool = True # only one XAgentServer can be set to check whether the interaction is running. check_running: bool = False host = "0.0.0.0" port = 8090 debug = True reload = True workers = 1 share_url = "https://x-agent.net/api/conv/community" class DB: """ database config """ use_db = True db_url = "mysql+pymysql://root:xagent@localhost:3306/xagent" class Redis: """ redis config """ use_redis = False redis_url = "redis://localhost" redis_host = "localhost" redis_port = 6379 redis_db = 0 redis_password = "xagent" # if you want to use email to send message, # you can set send_email to True and set # email_host, # email_port, # email_user, # email_password, # auth_server class Email: """ email config """ send_email = False email_host = "" email_port = 465 email_user = "" email_password = "" auth_server = "" # if you want to use upload function, # you can set upload_dir to the path of the upload directory # and set upload_allowed_types of the allowed types class Upload: """ upload config """ upload_dir = "XAgentServer/localstorage/upload" if not os.path.exists(upload_dir): os.makedirs(upload_dir) upload_allowed_types = ["image/png", "image/jpeg", "image/gif", "text/plain", "application/msword", "pdf", "txt", "pptx", "xlsx", "doc", "ppt", "xls", "zip", "rar", "tar", "gz", "7z", "bz2", "tgz", "tbz2", "tar.gz", "tar.bz2"] class XAgentError(Exception): """Base class for exceptions in this module.""" def __init__(self, message="XAgent Error!"): self.message = message super().__init__(self.message) class XAgentFileError(XAgentError): """Exception raised for errors in the input. Attributes: message -- explanation of the error """ def __init__(self, message="XAgent File Error!"): self.message = message super().__init__(self.message) class XAgentDBError(XAgentError): """Exception raised because of DB error Attributes: message -- explanation of the error """ def __init__(self, message="XAgent DB Error!"): self.message = message super().__init__(self.message) class XAgentAuthError(XAgentError): """Exception raised because of auth error Attributes: message -- explanation of the error """ def __init__(self, message="XAgent Auth Error!"): self.message = message super().__init__(self.message) The provided code snippet includes necessary dependencies for implementing the `db_session_middleware` function. Write a Python function `async def db_session_middleware(request: Request, call_next)` to solve the following problem: Exception middleware Here is the function: async def db_session_middleware(request: Request, call_next): """ Exception middleware """ # 默认响应 message = "Internal server error" response = Response(message, status_code=500) try: response = await call_next(request) except XAgentDBError as error: traceback.print_exc() message = "XAgent DB Error." if XAgentServerEnv.prod else error.message response = JSONResponse( status_code=500, content={"status": "failed", "message": message} ) except XAgentFileError as error: traceback.print_exc() message = "XAgent File Error." if XAgentServerEnv.prod else error.message response = JSONResponse( status_code=500, content={"status": "failed", "message": message} ) except XAgentAuthError as error: traceback.print_exc() response = JSONResponse( status_code=401, content={"status": "failed", "message": error.message} ) except XAgentError as error: traceback.print_exc() message = "XAgent Error." if XAgentServerEnv.prod else error.message response = JSONResponse( status_code=500, content={"status": "failed", "message": message} ) return response
Exception middleware
6,283
import traceback import uvicorn from colorama import Fore from fastapi import FastAPI, Request, Response from fastapi.exceptions import RequestValidationError from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse from XAgentServer.application.core.envs import XAgentServerEnv from XAgentServer.application.dependence import (enable_dependence, enable_logger) from XAgentServer.exts.exception_ext import XAgentAuthError, XAgentDBError, XAgentError, XAgentFileError logger = enable_logger() async def print_start_message(): """ print start message """ logger.typewriter_log( title="XAgent Server Dependences:", title_color=Fore.RED, content=""" Python: 3.10+ FastAPI: Http server Websocket: long connect with client MySQL: save xagent data SqlAlchemy: ORM with MySQL Redis: save status of interaction Threading: run interaction APScheduler: send data to client and keep alive FastAPI APIRouter: manage websocket route XAgentError: XAgentServer.exts.exception_ext""", ) logger.typewriter_log( title="XAgent Server Version:", title_color=Fore.RED, content=""" V 1.1.0""", ) logger.typewriter_log( title="Notes:", title_color=Fore.RED, content=""" Since V 1.1.0, Local storage will no longer be supported, replaced by Mysql. The service depends on Redis and Mysql, so you need to install Redis and Mysql before using it. Before you use this service, please ensure that the following services are available: 1. Redis on docker, port: 6379, you can start it by docker, default password: xagent 2. Mysql on docker, port: 3306, you can start it by docker 3. XAgent Tool Server is runnning on port 8080 4. Port 8090 is not occupied """, ) async def startup_event(): """start up event """ logger.info("XAgent Service Startup Param:") for key, item in XAgentServerEnv.__dict__.items(): if not key.startswith("__"): logger.info(f"{' '*10}{key}: {item}") enable_dependence(logger) from XAgentServer.application.routers import conv, user, workspace from XAgentServer.application.websockets import base, recorder, replayer, share class XAgentServerEnv: """ XAgentServer environment variables if you change value of the environment variable, you need to restart the XAgentServer by running the following command: `python start_server.py` or start a unicorn server by yourself """ app = "app:app" prod: bool = config.get("PROD", "False").lower() == "true" base_dir = "XAgentServer" use_redis: bool = False recorder_root_dir = "running_records" # you can set default_login with True, # use the default user "admin" with token "xagent-admin" to login, default_login: bool = True # only one XAgentServer can be set to check whether the interaction is running. check_running: bool = False host = "0.0.0.0" port = 8090 debug = True reload = True workers = 1 share_url = "https://x-agent.net/api/conv/community" class DB: """ database config """ use_db = True db_url = "mysql+pymysql://root:xagent@localhost:3306/xagent" class Redis: """ redis config """ use_redis = False redis_url = "redis://localhost" redis_host = "localhost" redis_port = 6379 redis_db = 0 redis_password = "xagent" # if you want to use email to send message, # you can set send_email to True and set # email_host, # email_port, # email_user, # email_password, # auth_server class Email: """ email config """ send_email = False email_host = "" email_port = 465 email_user = "" email_password = "" auth_server = "" # if you want to use upload function, # you can set upload_dir to the path of the upload directory # and set upload_allowed_types of the allowed types class Upload: """ upload config """ upload_dir = "XAgentServer/localstorage/upload" if not os.path.exists(upload_dir): os.makedirs(upload_dir) upload_allowed_types = ["image/png", "image/jpeg", "image/gif", "text/plain", "application/msword", "pdf", "txt", "pptx", "xlsx", "doc", "ppt", "xls", "zip", "rar", "tar", "gz", "7z", "bz2", "tgz", "tbz2", "tar.gz", "tar.bz2"] The provided code snippet includes necessary dependencies for implementing the `startup` function. Write a Python function `async def startup()` to solve the following problem: start up event Here is the function: async def startup(): """ start up event """ await startup_event() if XAgentServerEnv.default_login: logger.typewriter_log( title="Default user: Guest, token: xagent, you can use it to login", title_color=Fore.RED) await print_start_message()
start up event
6,284
import traceback import uvicorn from colorama import Fore from fastapi import FastAPI, Request, Response from fastapi.exceptions import RequestValidationError from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse from XAgentServer.application.core.envs import XAgentServerEnv from XAgentServer.application.dependence import (enable_dependence, enable_logger) from XAgentServer.exts.exception_ext import XAgentAuthError, XAgentDBError, XAgentError, XAgentFileError from XAgentServer.application.routers import conv, user, workspace from XAgentServer.application.websockets import base, recorder, replayer, share The provided code snippet includes necessary dependencies for implementing the `shutdown` function. Write a Python function `async def shutdown()` to solve the following problem: shut down event Here is the function: async def shutdown(): """ shut down event """ print("XAgent Service Shutdown!")
shut down event
6,285
import traceback import uvicorn from colorama import Fore from fastapi import FastAPI, Request, Response from fastapi.exceptions import RequestValidationError from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse from XAgentServer.application.core.envs import XAgentServerEnv from XAgentServer.application.dependence import (enable_dependence, enable_logger) from XAgentServer.exts.exception_ext import XAgentAuthError, XAgentDBError, XAgentError, XAgentFileError from XAgentServer.application.routers import conv, user, workspace from XAgentServer.application.websockets import base, recorder, replayer, share The provided code snippet includes necessary dependencies for implementing the `validation_exception_handler` function. Write a Python function `async def validation_exception_handler(request: Request, exc: RequestValidationError)` to solve the following problem: handle validation exception Args: request (Request): _description_ exc (RequestValidationError): _description_ Returns: _type_: _description_ Here is the function: async def validation_exception_handler(request: Request, exc: RequestValidationError): """handle validation exception Args: request (Request): _description_ exc (RequestValidationError): _description_ Returns: _type_: _description_ """ return JSONResponse( status_code=400, content={"status": "failed", "message": exc.errors()} )
handle validation exception Args: request (Request): _description_ exc (RequestValidationError): _description_ Returns: _type_: _description_
6,286
import base64 import os from XAgentServer.application.cruds.user import UserCRUD from XAgentServer.database.models import Raw from XAgentServer.exts.exception_ext import XAgentWebSocketConnectError class UserCRUD(metaclass=abc.ABCMeta): """ User CRUD """ def get_user_list(cls, db: Session) -> list[XAgentUser]: """ get all users Args: db: database session """ try: return UserDBInterface.get_user_list(db=db) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def get_user(cls, db: Session, user_id: str | None = None, email: str | None = None) -> XAgentUser | None: """ get user by user_id or email Args: db: database session user_id: user_id email: email Returns: user """ try: return UserDBInterface.get_user(db=db, user_id=user_id, email=email) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def is_exist(cls, db: Session, user_id: str | None = None, email: str | None = None): """ check user is exist Args: db: database session user_id: user_id email: email Returns: bool """ try: return UserDBInterface.is_exist(db=db, user_id=user_id, email=email) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def token_is_exist(cls, db: Session, user_id: str, token: str | None = None): """ check token is exist Args: db: database session user_id: user_id token: token Returns: bool """ try: return UserDBInterface.token_is_exist(db=db, user_id=user_id, token=token) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def user_is_valid(cls, db: Session, user_id: str | None = None, email: str | None = None, token: str | None = None): """ check user is valid Args: db: database session user_id: user_id email: email token: token Returns: bool """ try: return UserDBInterface.user_is_valid(db=db, user_id=user_id, email=email, token=token) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def add_user(cls, db: Session, user_dict: dict): """ add user Args: db: database session user_dict: user dict Returns: None """ try: UserDBInterface.add_user(db=db, user_dict=user_dict) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def update_user(cls, db: Session, user: XAgentUser): """ update user Args: db: database session user: user Returns: None """ try: UserDBInterface.update_user(db=db, user=user) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e class XAgentWebSocketConnectError(XAgentWebSocketError): """Exception raised for errors in the input. Attributes: message -- explanation of the error """ def __init__(self, message="XAgentWebSocket Connect Error!"): self.message = message super().__init__(self.message) The provided code snippet includes necessary dependencies for implementing the `check_user` function. Write a Python function `async def check_user(db, user_id, token)` to solve the following problem: check user for websocket connection Here is the function: async def check_user(db, user_id, token): """ check user for websocket connection """ if not UserCRUD.is_exist(db=db, user_id=user_id): raise XAgentWebSocketConnectError("user is not exist!") # auth if not UserCRUD.user_is_valid(db=db, user_id=user_id, token=token): raise XAgentWebSocketConnectError("user is not available!") user = UserCRUD.get_user(db=db, user_id=user_id) if not user or user.token != token or user.available is False or user.is_beta is False: raise XAgentWebSocketConnectError( "XAgentServer is running in production mode, if you want to use it, please contact the administrator.")
check user for websocket connection
6,287
import base64 import os from XAgentServer.application.cruds.user import UserCRUD from XAgentServer.database.models import Raw from XAgentServer.exts.exception_ext import XAgentWebSocketConnectError class Raw(Base): """Raw Data""" __tablename__ = "raw" # id/id id = Column(Integer, primary_key=True, index=True) # node_id node_id = Column(String(255)) # 交互id/interaction_id interaction_id = Column(String(255)) # 当前节点/current current = Column(String(128)) # step/step step = Column(Integer, default=0) # 数据/agent data data = Column(JSON) # workspace文件列表/workspace file list file_list = Column(JSON) # 状态/status status = Column(String(20)) # 是否中断/interrupt or not do_interrupt = Column(Boolean, default=False) # 已等待时间/wait seconds wait_seconds = Column(Integer, default=0) # 是否需要人工干预/ask for human help or not ask_for_human_help = Column(Boolean, default=False) # 创建时间/create time create_time = Column(String(255)) # 更新时间/update time update_time = Column(String(255)) # 是否删除/is deleted or not is_deleted = Column(Boolean, default=False) # 是否人工已经输入/has human input or not is_human = Column(Boolean, default=False) # 人工输入数据/human data human_data = Column(JSON) # 人工文件列表/agent file list human_file_list = Column(JSON) # 是否推送前端/has send to frontend or not is_send = Column(Boolean, default=False) # 是否接收前端消息/has receive message from frontend or not is_receive = Column(Boolean, default=False) # 是否包含png/has png or not include_pictures = Column(Boolean, default=False) The provided code snippet includes necessary dependencies for implementing the `handle_data` function. Write a Python function `def handle_data(row: Raw, root_dir: str)` to solve the following problem: handle data for websocket response Here is the function: def handle_data(row: Raw, root_dir: str): """ handle data for websocket response """ data = row.data try: using_tools = data.get("using_tools", "") if not using_tools: return data tool_name = using_tools.get("tool_name", "") if isinstance( using_tools, dict) else "" tool_output = using_tools.get( "tool_output", {}) if isinstance(using_tools, dict) else "" tool_input = using_tools.get( "tool_input", {}) if isinstance(using_tools, dict) else "" if row.include_pictures: if tool_name == "PythonNotebook_execute_cell": for output in tool_output: if isinstance(output, dict) and 'file_name' in output: file_name = output['file_name'] png_base64 = None if file_name: file_path = os.path.join( root_dir, "workspace", file_name) if os.path.exists(file_path): try: with open(file_path, "rb") as f: png_base64 = base64.b64encode( f.read()).decode("utf-8") except Exception: pass output["file_data"] = png_base64 using_tools["is_include_pictures"] = True if tool_input: data["using_tools"]["tool_input"] = tool_input.encode("utf-8").decode("unicode_escape") if tool_output and isinstance(tool_output, str): data["using_tools"]["tool_output"] = tool_output.encode("utf-8").decode("unicode_escape") except Exception: pass return data
handle data for websocket response
6,288
import base64 import os from XAgentServer.application.cruds.user import UserCRUD from XAgentServer.database.models import Raw from XAgentServer.exts.exception_ext import XAgentWebSocketConnectError The provided code snippet includes necessary dependencies for implementing the `handle_workspace_filelist` function. Write a Python function `def handle_workspace_filelist(file_list)` to solve the following problem: handle workspace file list Args: file_list (_type_): file_list is a list of file name Returns: List[Dict]: element list, each element is a dict with name and suffix Here is the function: def handle_workspace_filelist(file_list): """handle workspace file list Args: file_list (_type_): file_list is a list of file name Returns: List[Dict]: element list, each element is a dict with name and suffix """ if not isinstance(file_list, list) or not file_list: return [] return [{"name": file, "suffix": file.split(".")[-1]} for file in file_list]
handle workspace file list Args: file_list (_type_): file_list is a list of file name Returns: List[Dict]: element list, each element is a dict with name and suffix
6,289
from datetime import datetime import time import json import os from typing import List import uuid import zipfile from fastapi import APIRouter, Depends, File, Form, UploadFile import requests from sqlalchemy.orm import Session from XAgentServer.application.core.envs import XAgentServerEnv from XAgentServer.application.cruds.interaction import InteractionCRUD from XAgentServer.application.cruds.user import UserCRUD from XAgentServer.application.dependence import get_db from XAgentServer.application.schemas.response_body import ResponseBody from XAgentServer.enums.status import StatusEnum from XAgentServer.exts.exception_ext import XAgentAuthError, XAgentWebError from XAgentServer.models.interaction import InteractionBase from XAgentServer.models.raw import XAgentRaw from XAgentServer.models.shared_interaction import SharedInteractionBase def user_is_available( user_id: str = Form(...), token: str = Form(...), db: Session = Depends(get_db)): """ check user is available """ if user_id == "": raise XAgentAuthError("user_id is empty!") if not UserCRUD.is_exist(db=db, user_id=user_id): raise XAgentAuthError("user is not exist!") if not UserCRUD.user_is_valid(db=db, user_id=user_id, token=token): raise XAgentAuthError("user is not available!") return user_id class InteractionCRUD(metaclass=abc.ABCMeta): """ interaction crud """ def search_many_interaction(cls, db: Session) -> list: """ search many interaction """ try: return InteractionDBInterface.search_many_interaction(db=db) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_interaction(cls, db: Session, interaction_id: str) -> InteractionBase | None: """ get interaction Args: db: db interaction_id: interaction id Returns: interaction InteractionBase Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_interaction(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def create_interaction(cls, db: Session, base: InteractionBase): """ create interaction Args: db: db base: base Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.create_interaction(db=db, base=base) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_ready_interaction(cls, db: Session, user_id: str): """ create interaction Args: db: db user_id: user_id Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_ready_interaction(db=db, user_id=user_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def add_parameter(cls, db: Session, parameter: InteractionParameter = None): """ add parameter Args: db: db parameter: parameter Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.add_parameter(db=db, parameter=parameter) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_parameter(cls, db: Session, interaction_id: str) -> list: """ get parameter Args: db: db interaction_id: interaction id Returns: parameter list [InteractionParameter] Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_parameter(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_init_parameter(cls, db: Session, interaction_id: str) -> InteractionParameter: """ get init parameter Args: db: db interaction_id: interaction id Returns: parameter InteractionParameter Raises: XAgentDBError: XAgent DB Error """ try: parameters = InteractionDBInterface.get_parameter(db=db, interaction_id=interaction_id) init_parameter = parameters[0] parameter = InteractionParameter.from_json({"args": init_parameter, "interaction_id": interaction_id, "parameter_id": None}) return parameter except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def search_interaction_by_user_id(cls, db: Session, user_id: str, page_size: int = 10, page_num: int = 1) -> list[dict]: """ get interaction by user id Args: db: db user_id: user id page_size: page size page_num: page num Returns: interaction list [dict] Raises: XAgentDBError: XAgent DB Error """ return InteractionDBInterface.search_interaction_by_user_id(db=db, user_id=user_id, page_size=page_size, page_num=page_num) def is_exist(cls, db: Session, interaction_id: str) -> bool: """ interaction is exist Args: db: db interaction_id: interaction id Returns: True if interaction is exist, else False Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.is_exist(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_interaction(cls, db: Session, base_data: dict): """ update interaction Args: db: db base_data: base data Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_interaction(db=db, base_data=base_data) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_interaction_status(cls, db: Session, interaction_id: str, status: str, message: str, current_step: int): """ update interaction status Args: db: db interaction_id: interaction id status: status message: message current_step: current step Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_interaction_status( db=db, interaction_id=interaction_id, status=status, message=message, current_step=current_step) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_interaction_parameter(cls, db: Session, interaction_id: str, parameter: InteractionParameter): """ update interaction parameter Args: db: db interaction_id: interaction id parameter: parameter Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_interaction_parameter( db=db, interaction_id=interaction_id, parameter=parameter) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def is_running(cls, db: Session, user_id: str): """ is running Args: db: db user_id: user id Returns: True if running, else False Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.is_running(db=db, user_id=user_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def delete_interaction(cls, db: Session, interaction_id: str): """ delete interaction Args: db: db interaction_id: interaction id Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.delete_interaction( db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_shared_interaction(cls, db: Session, interaction_id: str) -> InteractionBase | None: """ get shared interaction Args: db: db interaction_id: interaction id Returns: interaction InteractionBase, if not found, return None Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_shared_interaction( db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def search_many_shared(cls, db: Session, page_size: int = 20, page_index: int = 1) -> list[dict]: """ search many shared Args: db: db page_size: page size page_index: page index Returns: interaction list [dict] Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.search_many_shared(db=db, page_size=page_size, page_index=page_index) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def insert_raw(cls, db: Session, process: XAgentRaw): """ insert raw Args: db: db process: process Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.insert_raw(db=db, process=process) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def search_many_raws(cls, db: Session, interaction_id: str) -> List[XAgentRaw] | None: """ search many raws Args: db: db interaction_id: interaction id Returns: raw list [XAgentRaw] Raises: XAgentDBError: XAgent DB Error """ try: return [XAgentRaw.from_db(raw) for raw in InteractionDBInterface.search_many_raws(db=db, interaction_id=interaction_id)] except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_raw(cls, db: Session, interaction_id: str, node_id: str) -> XAgentRaw | None: """ get raw Args: db: db interaction_id: interaction id node_id: node id Returns: raw XAgentRaw, if not found, return None Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_raw(db=db, interaction_id=interaction_id, node_id=node_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_next_send(cls, db: Session, interaction_id: str) -> List[Raw] | None: """ get next send Args: db: db interaction_id: interaction id Returns: raw list [Raw] Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_next_send(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_send_flag(cls, db: Session, interaction_id: str, node_id: str): """ update send flag Args: db: db interaction_id: interaction id node_id: node id Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_send_flag( db=db, interaction_id=interaction_id, node_id=node_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_receive_flag(cls, db: Session, interaction_id: str, node_id: str): """ update receive flag Args: db: db interaction_id: interaction id node_id: node id Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_receive_flag( db=db, interaction_id=interaction_id, node_id=node_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_human_data(cls, db: Session, interaction_id: str, node_id: str, human_data: dict): """ update human data Args: db: db interaction_id: interaction id node_id: node id human_data: human data Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_human_data(db=db, interaction_id=interaction_id, node_id=node_id, human_data=human_data) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def insert_error(cls, db: Session, interaction_id: str, message: str, status: str = "failed"): """ insert error Args: db: db interaction_id: interaction id message: message status: status, default is failed Returns: raw XAgentRaw Raises: XAgentDBError: XAgent DB Error """ try: process = XAgentRaw( node_id=uuid.uuid4().hex, interaction_id=interaction_id, current="", step=0, data=message, file_list=[], status=status, do_interrupt=False, wait_seconds=0, ask_for_human_help=False, create_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"), update_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"), is_deleted=False, is_human=False, human_data={}, human_file_list=[], is_send=False, is_receive=False, include_pictures=False, ) InteractionDBInterface.insert_raw(db=db, process=process) return process except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def add_share(cls, db: Session, share): """ add share Args: db: db share: share Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.add_share(db=db, shared=share) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_finish_status(cls, db: Session, interaction_id: str) -> bool: """ get finish status Args: db: db interaction_id: interaction id Returns: True if finish, else False """ try: return InteractionDBInterface.get_finish_status(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_db(): """db""" session = SessionLocal() try: yield session session.commit() except Exception as e: session.rollback() raise e finally: session.close() class ResponseBody(BaseModel): """Response body """ data: Union[str, dict, list, Json, None] = None success: bool = True message: Union[str, None] = None def to_dict(self): """to dict """ return self.dict() def to_json(self): """to json """ return self.json() The provided code snippet includes necessary dependencies for implementing the `get_all_interactions` function. Write a Python function `async def get_all_interactions(user_id: str = Depends(user_is_available), page_size: int = Form(...), page_num: int = Form(...), db: Session = Depends(get_db)) -> ResponseBody` to solve the following problem: get all interactions by user_id Here is the function: async def get_all_interactions(user_id: str = Depends(user_is_available), page_size: int = Form(...), page_num: int = Form(...), db: Session = Depends(get_db)) -> ResponseBody: """ get all interactions by user_id """ data = InteractionCRUD.search_interaction_by_user_id(db=db, user_id=user_id, page_size=page_size, page_num=page_num) return ResponseBody(data=data, success=True, message="success")
get all interactions by user_id
6,290
from datetime import datetime import time import json import os from typing import List import uuid import zipfile from fastapi import APIRouter, Depends, File, Form, UploadFile import requests from sqlalchemy.orm import Session from XAgentServer.application.core.envs import XAgentServerEnv from XAgentServer.application.cruds.interaction import InteractionCRUD from XAgentServer.application.cruds.user import UserCRUD from XAgentServer.application.dependence import get_db from XAgentServer.application.schemas.response_body import ResponseBody from XAgentServer.enums.status import StatusEnum from XAgentServer.exts.exception_ext import XAgentAuthError, XAgentWebError from XAgentServer.models.interaction import InteractionBase from XAgentServer.models.raw import XAgentRaw from XAgentServer.models.shared_interaction import SharedInteractionBase def user_is_available( user_id: str = Form(...), token: str = Form(...), db: Session = Depends(get_db)): """ check user is available """ if user_id == "": raise XAgentAuthError("user_id is empty!") if not UserCRUD.is_exist(db=db, user_id=user_id): raise XAgentAuthError("user is not exist!") if not UserCRUD.user_is_valid(db=db, user_id=user_id, token=token): raise XAgentAuthError("user is not available!") return user_id class InteractionCRUD(metaclass=abc.ABCMeta): """ interaction crud """ def search_many_interaction(cls, db: Session) -> list: """ search many interaction """ try: return InteractionDBInterface.search_many_interaction(db=db) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_interaction(cls, db: Session, interaction_id: str) -> InteractionBase | None: """ get interaction Args: db: db interaction_id: interaction id Returns: interaction InteractionBase Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_interaction(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def create_interaction(cls, db: Session, base: InteractionBase): """ create interaction Args: db: db base: base Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.create_interaction(db=db, base=base) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_ready_interaction(cls, db: Session, user_id: str): """ create interaction Args: db: db user_id: user_id Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_ready_interaction(db=db, user_id=user_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def add_parameter(cls, db: Session, parameter: InteractionParameter = None): """ add parameter Args: db: db parameter: parameter Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.add_parameter(db=db, parameter=parameter) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_parameter(cls, db: Session, interaction_id: str) -> list: """ get parameter Args: db: db interaction_id: interaction id Returns: parameter list [InteractionParameter] Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_parameter(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_init_parameter(cls, db: Session, interaction_id: str) -> InteractionParameter: """ get init parameter Args: db: db interaction_id: interaction id Returns: parameter InteractionParameter Raises: XAgentDBError: XAgent DB Error """ try: parameters = InteractionDBInterface.get_parameter(db=db, interaction_id=interaction_id) init_parameter = parameters[0] parameter = InteractionParameter.from_json({"args": init_parameter, "interaction_id": interaction_id, "parameter_id": None}) return parameter except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def search_interaction_by_user_id(cls, db: Session, user_id: str, page_size: int = 10, page_num: int = 1) -> list[dict]: """ get interaction by user id Args: db: db user_id: user id page_size: page size page_num: page num Returns: interaction list [dict] Raises: XAgentDBError: XAgent DB Error """ return InteractionDBInterface.search_interaction_by_user_id(db=db, user_id=user_id, page_size=page_size, page_num=page_num) def is_exist(cls, db: Session, interaction_id: str) -> bool: """ interaction is exist Args: db: db interaction_id: interaction id Returns: True if interaction is exist, else False Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.is_exist(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_interaction(cls, db: Session, base_data: dict): """ update interaction Args: db: db base_data: base data Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_interaction(db=db, base_data=base_data) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_interaction_status(cls, db: Session, interaction_id: str, status: str, message: str, current_step: int): """ update interaction status Args: db: db interaction_id: interaction id status: status message: message current_step: current step Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_interaction_status( db=db, interaction_id=interaction_id, status=status, message=message, current_step=current_step) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_interaction_parameter(cls, db: Session, interaction_id: str, parameter: InteractionParameter): """ update interaction parameter Args: db: db interaction_id: interaction id parameter: parameter Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_interaction_parameter( db=db, interaction_id=interaction_id, parameter=parameter) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def is_running(cls, db: Session, user_id: str): """ is running Args: db: db user_id: user id Returns: True if running, else False Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.is_running(db=db, user_id=user_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def delete_interaction(cls, db: Session, interaction_id: str): """ delete interaction Args: db: db interaction_id: interaction id Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.delete_interaction( db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_shared_interaction(cls, db: Session, interaction_id: str) -> InteractionBase | None: """ get shared interaction Args: db: db interaction_id: interaction id Returns: interaction InteractionBase, if not found, return None Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_shared_interaction( db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def search_many_shared(cls, db: Session, page_size: int = 20, page_index: int = 1) -> list[dict]: """ search many shared Args: db: db page_size: page size page_index: page index Returns: interaction list [dict] Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.search_many_shared(db=db, page_size=page_size, page_index=page_index) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def insert_raw(cls, db: Session, process: XAgentRaw): """ insert raw Args: db: db process: process Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.insert_raw(db=db, process=process) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def search_many_raws(cls, db: Session, interaction_id: str) -> List[XAgentRaw] | None: """ search many raws Args: db: db interaction_id: interaction id Returns: raw list [XAgentRaw] Raises: XAgentDBError: XAgent DB Error """ try: return [XAgentRaw.from_db(raw) for raw in InteractionDBInterface.search_many_raws(db=db, interaction_id=interaction_id)] except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_raw(cls, db: Session, interaction_id: str, node_id: str) -> XAgentRaw | None: """ get raw Args: db: db interaction_id: interaction id node_id: node id Returns: raw XAgentRaw, if not found, return None Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_raw(db=db, interaction_id=interaction_id, node_id=node_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_next_send(cls, db: Session, interaction_id: str) -> List[Raw] | None: """ get next send Args: db: db interaction_id: interaction id Returns: raw list [Raw] Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_next_send(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_send_flag(cls, db: Session, interaction_id: str, node_id: str): """ update send flag Args: db: db interaction_id: interaction id node_id: node id Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_send_flag( db=db, interaction_id=interaction_id, node_id=node_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_receive_flag(cls, db: Session, interaction_id: str, node_id: str): """ update receive flag Args: db: db interaction_id: interaction id node_id: node id Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_receive_flag( db=db, interaction_id=interaction_id, node_id=node_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_human_data(cls, db: Session, interaction_id: str, node_id: str, human_data: dict): """ update human data Args: db: db interaction_id: interaction id node_id: node id human_data: human data Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_human_data(db=db, interaction_id=interaction_id, node_id=node_id, human_data=human_data) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def insert_error(cls, db: Session, interaction_id: str, message: str, status: str = "failed"): """ insert error Args: db: db interaction_id: interaction id message: message status: status, default is failed Returns: raw XAgentRaw Raises: XAgentDBError: XAgent DB Error """ try: process = XAgentRaw( node_id=uuid.uuid4().hex, interaction_id=interaction_id, current="", step=0, data=message, file_list=[], status=status, do_interrupt=False, wait_seconds=0, ask_for_human_help=False, create_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"), update_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"), is_deleted=False, is_human=False, human_data={}, human_file_list=[], is_send=False, is_receive=False, include_pictures=False, ) InteractionDBInterface.insert_raw(db=db, process=process) return process except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def add_share(cls, db: Session, share): """ add share Args: db: db share: share Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.add_share(db=db, shared=share) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_finish_status(cls, db: Session, interaction_id: str) -> bool: """ get finish status Args: db: db interaction_id: interaction id Returns: True if finish, else False """ try: return InteractionDBInterface.get_finish_status(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_db(): """db""" session = SessionLocal() try: yield session session.commit() except Exception as e: session.rollback() raise e finally: session.close() class ResponseBody(BaseModel): """Response body """ data: Union[str, dict, list, Json, None] = None success: bool = True message: Union[str, None] = None def to_dict(self): """to dict """ return self.dict() def to_json(self): """to json """ return self.json() class InteractionBase(metaclass=abc.ABCMeta): def __init__(self, interaction_id: str, user_id: str, create_time: str, description: str, agent: str = "", mode: str = "", file_list: list = [], recorder_root_dir: str = "", status: str = "", message: str = "", current_step: str = "", update_time: str = "", is_deleted: bool = False, call_method: str = "web", ): self.interaction_id = interaction_id self.user_id = user_id self.create_time = create_time self.description = description self.agent = agent self.mode = mode self.file_list = file_list self.recorder_root_dir = recorder_root_dir self.status = status self.message = message self.current_step = current_step self.update_time = update_time self.is_deleted = is_deleted self.call_method = call_method def to_dict(self, include=None, exclude=None): data = { "interaction_id": self.interaction_id, "user_id": self.user_id, "create_time": self.create_time, "description": self.description, "agent": self.agent, "mode": self.mode, "file_list": self.file_list, "recorder_root_dir": self.recorder_root_dir, "status": self.status, "message": self.message, "current_step": self.current_step, "update_time": self.update_time, "is_deleted": self.is_deleted, "call_method": self.call_method, } if include: data = {k: v for k, v in data.items() if k in include} if exclude: data = {k: v for k, v in data.items() if k not in exclude} return data def to_json(self): return json.dumps(self.to_dict(), indent=2, ensure_ascii=False) def from_json(cls, json_data): return cls(**json_data) def from_db(cls, interaction): return cls(interaction.interaction_id, interaction.user_id, interaction.create_time, interaction.description, interaction.agent, interaction.mode, interaction.file_list, interaction.recorder_root_dir, interaction.status, interaction.message, interaction.current_step, interaction.update_time, interaction.is_deleted, interaction.call_method, ) The provided code snippet includes necessary dependencies for implementing the `init_conv_env` function. Write a Python function `def init_conv_env(user_id: str = Depends(user_is_available), db: Session = Depends(get_db))` to solve the following problem: initialize conv env Here is the function: def init_conv_env(user_id: str = Depends(user_is_available), db: Session = Depends(get_db)): """ initialize conv env """ interaction = InteractionCRUD.get_ready_interaction(db=db, user_id=user_id) if interaction is None: interaction_id = uuid.uuid4().hex base = InteractionBase(interaction_id=interaction_id, user_id=user_id, create_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"), description="XAgent", agent="", mode="", file_list=[], recorder_root_dir="", status="ready", message="ready...", current_step="-1", update_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S") ) InteractionCRUD.create_interaction(db=db, base=base) else: interaction_id = interaction.interaction_id return ResponseBody(data={"id": interaction_id, "t": str(int(datetime.now().timestamp() * 1000))}, success=True, message="success")
initialize conv env
6,291
from datetime import datetime import time import json import os from typing import List import uuid import zipfile from fastapi import APIRouter, Depends, File, Form, UploadFile import requests from sqlalchemy.orm import Session from XAgentServer.application.core.envs import XAgentServerEnv from XAgentServer.application.cruds.interaction import InteractionCRUD from XAgentServer.application.cruds.user import UserCRUD from XAgentServer.application.dependence import get_db from XAgentServer.application.schemas.response_body import ResponseBody from XAgentServer.enums.status import StatusEnum from XAgentServer.exts.exception_ext import XAgentAuthError, XAgentWebError from XAgentServer.models.interaction import InteractionBase from XAgentServer.models.raw import XAgentRaw from XAgentServer.models.shared_interaction import SharedInteractionBase def user_is_available( user_id: str = Form(...), token: str = Form(...), db: Session = Depends(get_db)): """ check user is available """ if user_id == "": raise XAgentAuthError("user_id is empty!") if not UserCRUD.is_exist(db=db, user_id=user_id): raise XAgentAuthError("user is not exist!") if not UserCRUD.user_is_valid(db=db, user_id=user_id, token=token): raise XAgentAuthError("user is not available!") return user_id class InteractionCRUD(metaclass=abc.ABCMeta): """ interaction crud """ def search_many_interaction(cls, db: Session) -> list: """ search many interaction """ try: return InteractionDBInterface.search_many_interaction(db=db) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_interaction(cls, db: Session, interaction_id: str) -> InteractionBase | None: """ get interaction Args: db: db interaction_id: interaction id Returns: interaction InteractionBase Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_interaction(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def create_interaction(cls, db: Session, base: InteractionBase): """ create interaction Args: db: db base: base Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.create_interaction(db=db, base=base) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_ready_interaction(cls, db: Session, user_id: str): """ create interaction Args: db: db user_id: user_id Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_ready_interaction(db=db, user_id=user_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def add_parameter(cls, db: Session, parameter: InteractionParameter = None): """ add parameter Args: db: db parameter: parameter Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.add_parameter(db=db, parameter=parameter) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_parameter(cls, db: Session, interaction_id: str) -> list: """ get parameter Args: db: db interaction_id: interaction id Returns: parameter list [InteractionParameter] Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_parameter(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_init_parameter(cls, db: Session, interaction_id: str) -> InteractionParameter: """ get init parameter Args: db: db interaction_id: interaction id Returns: parameter InteractionParameter Raises: XAgentDBError: XAgent DB Error """ try: parameters = InteractionDBInterface.get_parameter(db=db, interaction_id=interaction_id) init_parameter = parameters[0] parameter = InteractionParameter.from_json({"args": init_parameter, "interaction_id": interaction_id, "parameter_id": None}) return parameter except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def search_interaction_by_user_id(cls, db: Session, user_id: str, page_size: int = 10, page_num: int = 1) -> list[dict]: """ get interaction by user id Args: db: db user_id: user id page_size: page size page_num: page num Returns: interaction list [dict] Raises: XAgentDBError: XAgent DB Error """ return InteractionDBInterface.search_interaction_by_user_id(db=db, user_id=user_id, page_size=page_size, page_num=page_num) def is_exist(cls, db: Session, interaction_id: str) -> bool: """ interaction is exist Args: db: db interaction_id: interaction id Returns: True if interaction is exist, else False Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.is_exist(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_interaction(cls, db: Session, base_data: dict): """ update interaction Args: db: db base_data: base data Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_interaction(db=db, base_data=base_data) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_interaction_status(cls, db: Session, interaction_id: str, status: str, message: str, current_step: int): """ update interaction status Args: db: db interaction_id: interaction id status: status message: message current_step: current step Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_interaction_status( db=db, interaction_id=interaction_id, status=status, message=message, current_step=current_step) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_interaction_parameter(cls, db: Session, interaction_id: str, parameter: InteractionParameter): """ update interaction parameter Args: db: db interaction_id: interaction id parameter: parameter Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_interaction_parameter( db=db, interaction_id=interaction_id, parameter=parameter) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def is_running(cls, db: Session, user_id: str): """ is running Args: db: db user_id: user id Returns: True if running, else False Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.is_running(db=db, user_id=user_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def delete_interaction(cls, db: Session, interaction_id: str): """ delete interaction Args: db: db interaction_id: interaction id Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.delete_interaction( db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_shared_interaction(cls, db: Session, interaction_id: str) -> InteractionBase | None: """ get shared interaction Args: db: db interaction_id: interaction id Returns: interaction InteractionBase, if not found, return None Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_shared_interaction( db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def search_many_shared(cls, db: Session, page_size: int = 20, page_index: int = 1) -> list[dict]: """ search many shared Args: db: db page_size: page size page_index: page index Returns: interaction list [dict] Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.search_many_shared(db=db, page_size=page_size, page_index=page_index) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def insert_raw(cls, db: Session, process: XAgentRaw): """ insert raw Args: db: db process: process Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.insert_raw(db=db, process=process) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def search_many_raws(cls, db: Session, interaction_id: str) -> List[XAgentRaw] | None: """ search many raws Args: db: db interaction_id: interaction id Returns: raw list [XAgentRaw] Raises: XAgentDBError: XAgent DB Error """ try: return [XAgentRaw.from_db(raw) for raw in InteractionDBInterface.search_many_raws(db=db, interaction_id=interaction_id)] except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_raw(cls, db: Session, interaction_id: str, node_id: str) -> XAgentRaw | None: """ get raw Args: db: db interaction_id: interaction id node_id: node id Returns: raw XAgentRaw, if not found, return None Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_raw(db=db, interaction_id=interaction_id, node_id=node_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_next_send(cls, db: Session, interaction_id: str) -> List[Raw] | None: """ get next send Args: db: db interaction_id: interaction id Returns: raw list [Raw] Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_next_send(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_send_flag(cls, db: Session, interaction_id: str, node_id: str): """ update send flag Args: db: db interaction_id: interaction id node_id: node id Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_send_flag( db=db, interaction_id=interaction_id, node_id=node_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_receive_flag(cls, db: Session, interaction_id: str, node_id: str): """ update receive flag Args: db: db interaction_id: interaction id node_id: node id Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_receive_flag( db=db, interaction_id=interaction_id, node_id=node_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_human_data(cls, db: Session, interaction_id: str, node_id: str, human_data: dict): """ update human data Args: db: db interaction_id: interaction id node_id: node id human_data: human data Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_human_data(db=db, interaction_id=interaction_id, node_id=node_id, human_data=human_data) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def insert_error(cls, db: Session, interaction_id: str, message: str, status: str = "failed"): """ insert error Args: db: db interaction_id: interaction id message: message status: status, default is failed Returns: raw XAgentRaw Raises: XAgentDBError: XAgent DB Error """ try: process = XAgentRaw( node_id=uuid.uuid4().hex, interaction_id=interaction_id, current="", step=0, data=message, file_list=[], status=status, do_interrupt=False, wait_seconds=0, ask_for_human_help=False, create_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"), update_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"), is_deleted=False, is_human=False, human_data={}, human_file_list=[], is_send=False, is_receive=False, include_pictures=False, ) InteractionDBInterface.insert_raw(db=db, process=process) return process except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def add_share(cls, db: Session, share): """ add share Args: db: db share: share Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.add_share(db=db, shared=share) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_finish_status(cls, db: Session, interaction_id: str) -> bool: """ get finish status Args: db: db interaction_id: interaction id Returns: True if finish, else False """ try: return InteractionDBInterface.get_finish_status(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_db(): """db""" session = SessionLocal() try: yield session session.commit() except Exception as e: session.rollback() raise e finally: session.close() class ResponseBody(BaseModel): """Response body """ data: Union[str, dict, list, Json, None] = None success: bool = True message: Union[str, None] = None def to_dict(self): """to dict """ return self.dict() def to_json(self): """to json """ return self.json() The provided code snippet includes necessary dependencies for implementing the `get_share_interactions` function. Write a Python function `async def get_share_interactions(user_id: str = Depends(user_is_available), page_size: int = Form(...), page_num: int = Form(...), db: Session = Depends(get_db)) -> ResponseBody` to solve the following problem: get all interactions by user id Here is the function: async def get_share_interactions(user_id: str = Depends(user_is_available), page_size: int = Form(...), page_num: int = Form(...), db: Session = Depends(get_db)) -> ResponseBody: """ get all interactions by user id """ data = InteractionCRUD.search_many_shared( db=db, page_size=page_size, page_index=page_num) return ResponseBody(data=data, success=True, message="success")
get all interactions by user id
6,292
from datetime import datetime import time import json import os from typing import List import uuid import zipfile from fastapi import APIRouter, Depends, File, Form, UploadFile import requests from sqlalchemy.orm import Session from XAgentServer.application.core.envs import XAgentServerEnv from XAgentServer.application.cruds.interaction import InteractionCRUD from XAgentServer.application.cruds.user import UserCRUD from XAgentServer.application.dependence import get_db from XAgentServer.application.schemas.response_body import ResponseBody from XAgentServer.enums.status import StatusEnum from XAgentServer.exts.exception_ext import XAgentAuthError, XAgentWebError from XAgentServer.models.interaction import InteractionBase from XAgentServer.models.raw import XAgentRaw from XAgentServer.models.shared_interaction import SharedInteractionBase def user_is_available( user_id: str = Form(...), token: str = Form(...), db: Session = Depends(get_db)): """ check user is available """ if user_id == "": raise XAgentAuthError("user_id is empty!") if not UserCRUD.is_exist(db=db, user_id=user_id): raise XAgentAuthError("user is not exist!") if not UserCRUD.user_is_valid(db=db, user_id=user_id, token=token): raise XAgentAuthError("user is not available!") return user_id class XAgentServerEnv: """ XAgentServer environment variables if you change value of the environment variable, you need to restart the XAgentServer by running the following command: `python start_server.py` or start a unicorn server by yourself """ app = "app:app" prod: bool = config.get("PROD", "False").lower() == "true" base_dir = "XAgentServer" use_redis: bool = False recorder_root_dir = "running_records" # you can set default_login with True, # use the default user "admin" with token "xagent-admin" to login, default_login: bool = True # only one XAgentServer can be set to check whether the interaction is running. check_running: bool = False host = "0.0.0.0" port = 8090 debug = True reload = True workers = 1 share_url = "https://x-agent.net/api/conv/community" class DB: """ database config """ use_db = True db_url = "mysql+pymysql://root:xagent@localhost:3306/xagent" class Redis: """ redis config """ use_redis = False redis_url = "redis://localhost" redis_host = "localhost" redis_port = 6379 redis_db = 0 redis_password = "xagent" # if you want to use email to send message, # you can set send_email to True and set # email_host, # email_port, # email_user, # email_password, # auth_server class Email: """ email config """ send_email = False email_host = "" email_port = 465 email_user = "" email_password = "" auth_server = "" # if you want to use upload function, # you can set upload_dir to the path of the upload directory # and set upload_allowed_types of the allowed types class Upload: """ upload config """ upload_dir = "XAgentServer/localstorage/upload" if not os.path.exists(upload_dir): os.makedirs(upload_dir) upload_allowed_types = ["image/png", "image/jpeg", "image/gif", "text/plain", "application/msword", "pdf", "txt", "pptx", "xlsx", "doc", "ppt", "xls", "zip", "rar", "tar", "gz", "7z", "bz2", "tgz", "tbz2", "tar.gz", "tar.bz2"] class InteractionCRUD(metaclass=abc.ABCMeta): """ interaction crud """ def search_many_interaction(cls, db: Session) -> list: """ search many interaction """ try: return InteractionDBInterface.search_many_interaction(db=db) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_interaction(cls, db: Session, interaction_id: str) -> InteractionBase | None: """ get interaction Args: db: db interaction_id: interaction id Returns: interaction InteractionBase Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_interaction(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def create_interaction(cls, db: Session, base: InteractionBase): """ create interaction Args: db: db base: base Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.create_interaction(db=db, base=base) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_ready_interaction(cls, db: Session, user_id: str): """ create interaction Args: db: db user_id: user_id Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_ready_interaction(db=db, user_id=user_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def add_parameter(cls, db: Session, parameter: InteractionParameter = None): """ add parameter Args: db: db parameter: parameter Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.add_parameter(db=db, parameter=parameter) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_parameter(cls, db: Session, interaction_id: str) -> list: """ get parameter Args: db: db interaction_id: interaction id Returns: parameter list [InteractionParameter] Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_parameter(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_init_parameter(cls, db: Session, interaction_id: str) -> InteractionParameter: """ get init parameter Args: db: db interaction_id: interaction id Returns: parameter InteractionParameter Raises: XAgentDBError: XAgent DB Error """ try: parameters = InteractionDBInterface.get_parameter(db=db, interaction_id=interaction_id) init_parameter = parameters[0] parameter = InteractionParameter.from_json({"args": init_parameter, "interaction_id": interaction_id, "parameter_id": None}) return parameter except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def search_interaction_by_user_id(cls, db: Session, user_id: str, page_size: int = 10, page_num: int = 1) -> list[dict]: """ get interaction by user id Args: db: db user_id: user id page_size: page size page_num: page num Returns: interaction list [dict] Raises: XAgentDBError: XAgent DB Error """ return InteractionDBInterface.search_interaction_by_user_id(db=db, user_id=user_id, page_size=page_size, page_num=page_num) def is_exist(cls, db: Session, interaction_id: str) -> bool: """ interaction is exist Args: db: db interaction_id: interaction id Returns: True if interaction is exist, else False Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.is_exist(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_interaction(cls, db: Session, base_data: dict): """ update interaction Args: db: db base_data: base data Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_interaction(db=db, base_data=base_data) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_interaction_status(cls, db: Session, interaction_id: str, status: str, message: str, current_step: int): """ update interaction status Args: db: db interaction_id: interaction id status: status message: message current_step: current step Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_interaction_status( db=db, interaction_id=interaction_id, status=status, message=message, current_step=current_step) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_interaction_parameter(cls, db: Session, interaction_id: str, parameter: InteractionParameter): """ update interaction parameter Args: db: db interaction_id: interaction id parameter: parameter Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_interaction_parameter( db=db, interaction_id=interaction_id, parameter=parameter) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def is_running(cls, db: Session, user_id: str): """ is running Args: db: db user_id: user id Returns: True if running, else False Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.is_running(db=db, user_id=user_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def delete_interaction(cls, db: Session, interaction_id: str): """ delete interaction Args: db: db interaction_id: interaction id Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.delete_interaction( db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_shared_interaction(cls, db: Session, interaction_id: str) -> InteractionBase | None: """ get shared interaction Args: db: db interaction_id: interaction id Returns: interaction InteractionBase, if not found, return None Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_shared_interaction( db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def search_many_shared(cls, db: Session, page_size: int = 20, page_index: int = 1) -> list[dict]: """ search many shared Args: db: db page_size: page size page_index: page index Returns: interaction list [dict] Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.search_many_shared(db=db, page_size=page_size, page_index=page_index) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def insert_raw(cls, db: Session, process: XAgentRaw): """ insert raw Args: db: db process: process Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.insert_raw(db=db, process=process) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def search_many_raws(cls, db: Session, interaction_id: str) -> List[XAgentRaw] | None: """ search many raws Args: db: db interaction_id: interaction id Returns: raw list [XAgentRaw] Raises: XAgentDBError: XAgent DB Error """ try: return [XAgentRaw.from_db(raw) for raw in InteractionDBInterface.search_many_raws(db=db, interaction_id=interaction_id)] except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_raw(cls, db: Session, interaction_id: str, node_id: str) -> XAgentRaw | None: """ get raw Args: db: db interaction_id: interaction id node_id: node id Returns: raw XAgentRaw, if not found, return None Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_raw(db=db, interaction_id=interaction_id, node_id=node_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_next_send(cls, db: Session, interaction_id: str) -> List[Raw] | None: """ get next send Args: db: db interaction_id: interaction id Returns: raw list [Raw] Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_next_send(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_send_flag(cls, db: Session, interaction_id: str, node_id: str): """ update send flag Args: db: db interaction_id: interaction id node_id: node id Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_send_flag( db=db, interaction_id=interaction_id, node_id=node_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_receive_flag(cls, db: Session, interaction_id: str, node_id: str): """ update receive flag Args: db: db interaction_id: interaction id node_id: node id Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_receive_flag( db=db, interaction_id=interaction_id, node_id=node_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_human_data(cls, db: Session, interaction_id: str, node_id: str, human_data: dict): """ update human data Args: db: db interaction_id: interaction id node_id: node id human_data: human data Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_human_data(db=db, interaction_id=interaction_id, node_id=node_id, human_data=human_data) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def insert_error(cls, db: Session, interaction_id: str, message: str, status: str = "failed"): """ insert error Args: db: db interaction_id: interaction id message: message status: status, default is failed Returns: raw XAgentRaw Raises: XAgentDBError: XAgent DB Error """ try: process = XAgentRaw( node_id=uuid.uuid4().hex, interaction_id=interaction_id, current="", step=0, data=message, file_list=[], status=status, do_interrupt=False, wait_seconds=0, ask_for_human_help=False, create_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"), update_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"), is_deleted=False, is_human=False, human_data={}, human_file_list=[], is_send=False, is_receive=False, include_pictures=False, ) InteractionDBInterface.insert_raw(db=db, process=process) return process except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def add_share(cls, db: Session, share): """ add share Args: db: db share: share Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.add_share(db=db, shared=share) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_finish_status(cls, db: Session, interaction_id: str) -> bool: """ get finish status Args: db: db interaction_id: interaction id Returns: True if finish, else False """ try: return InteractionDBInterface.get_finish_status(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e class UserCRUD(metaclass=abc.ABCMeta): """ User CRUD """ def get_user_list(cls, db: Session) -> list[XAgentUser]: """ get all users Args: db: database session """ try: return UserDBInterface.get_user_list(db=db) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def get_user(cls, db: Session, user_id: str | None = None, email: str | None = None) -> XAgentUser | None: """ get user by user_id or email Args: db: database session user_id: user_id email: email Returns: user """ try: return UserDBInterface.get_user(db=db, user_id=user_id, email=email) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def is_exist(cls, db: Session, user_id: str | None = None, email: str | None = None): """ check user is exist Args: db: database session user_id: user_id email: email Returns: bool """ try: return UserDBInterface.is_exist(db=db, user_id=user_id, email=email) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def token_is_exist(cls, db: Session, user_id: str, token: str | None = None): """ check token is exist Args: db: database session user_id: user_id token: token Returns: bool """ try: return UserDBInterface.token_is_exist(db=db, user_id=user_id, token=token) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def user_is_valid(cls, db: Session, user_id: str | None = None, email: str | None = None, token: str | None = None): """ check user is valid Args: db: database session user_id: user_id email: email token: token Returns: bool """ try: return UserDBInterface.user_is_valid(db=db, user_id=user_id, email=email, token=token) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def add_user(cls, db: Session, user_dict: dict): """ add user Args: db: database session user_dict: user dict Returns: None """ try: UserDBInterface.add_user(db=db, user_dict=user_dict) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def update_user(cls, db: Session, user: XAgentUser): """ update user Args: db: database session user: user Returns: None """ try: UserDBInterface.update_user(db=db, user=user) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def get_db(): """db""" session = SessionLocal() try: yield session session.commit() except Exception as e: session.rollback() raise e finally: session.close() class ResponseBody(BaseModel): """Response body """ data: Union[str, dict, list, Json, None] = None success: bool = True message: Union[str, None] = None def to_dict(self): """to dict """ return self.dict() def to_json(self): """to json """ return self.json() The provided code snippet includes necessary dependencies for implementing the `share_interaction` function. Write a Python function `async def share_interaction(user_id: str = Depends(user_is_available), interaction_id: str = Form(...), db: Session = Depends(get_db)) -> ResponseBody` to solve the following problem: update_interaction_description Here is the function: async def share_interaction(user_id: str = Depends(user_is_available), interaction_id: str = Form(...), db: Session = Depends(get_db)) -> ResponseBody: """ update_interaction_description """ interaction = InteractionCRUD.get_interaction(db=db, interaction_id=interaction_id) if interaction is None: return ResponseBody(success=False, message=f"Don't find any interaction by interaction_id: \ {interaction_id}, Please check your interaction_id!") finish_status = InteractionCRUD.get_finish_status( db=db, interaction_id=interaction_id) if not finish_status: return ResponseBody(success=False, message="interaction is not finish!") user = UserCRUD.get_user(db=db, user_id=user_id) user_name = user.name interaction_dir = os.path.join(XAgentServerEnv.base_dir, "localstorage", "interact_records", interaction.create_time[:10], interaction_id) workspace_dir = os.path.join(interaction_dir, "workspace") zip_file = os.path.join(interaction_dir, "workspace.zip") if not os.path.exists(zip_file): if os.path.exists(workspace_dir): files = os.listdir(workspace_dir) # zip workspace with zipfile.ZipFile(zip_file, 'w', zipfile.ZIP_DEFLATED) as z: for f in files: file = os.path.join(workspace_dir, f) z.write(file, arcname=f) raws = InteractionCRUD.search_many_raws( db=db, interaction_id=interaction_id) share_data = { "user_id": user_id, "user_name": user_name, "token": user.token, "interaction": json.dumps(interaction.to_dict(), ensure_ascii=False), "raws": json.dumps([raw.to_dict() for raw in raws], ensure_ascii=False), } with open(zip_file, 'rb') as f: files = {"files": f.read()} try: res = requests.post(url=XAgentServerEnv.share_url, data=share_data, files=files, timeout=60) data = res.json() return ResponseBody(**data) except Exception as e: return ResponseBody(success=False, message=str(e), data=None)
update_interaction_description
6,293
from datetime import datetime import time import json import os from typing import List import uuid import zipfile from fastapi import APIRouter, Depends, File, Form, UploadFile import requests from sqlalchemy.orm import Session from XAgentServer.application.core.envs import XAgentServerEnv from XAgentServer.application.cruds.interaction import InteractionCRUD from XAgentServer.application.cruds.user import UserCRUD from XAgentServer.application.dependence import get_db from XAgentServer.application.schemas.response_body import ResponseBody from XAgentServer.enums.status import StatusEnum from XAgentServer.exts.exception_ext import XAgentAuthError, XAgentWebError from XAgentServer.models.interaction import InteractionBase from XAgentServer.models.raw import XAgentRaw from XAgentServer.models.shared_interaction import SharedInteractionBase def user_is_available( user_id: str = Form(...), token: str = Form(...), db: Session = Depends(get_db)): """ check user is available """ if user_id == "": raise XAgentAuthError("user_id is empty!") if not UserCRUD.is_exist(db=db, user_id=user_id): raise XAgentAuthError("user is not exist!") if not UserCRUD.user_is_valid(db=db, user_id=user_id, token=token): raise XAgentAuthError("user is not available!") return user_id class XAgentServerEnv: """ XAgentServer environment variables if you change value of the environment variable, you need to restart the XAgentServer by running the following command: `python start_server.py` or start a unicorn server by yourself """ app = "app:app" prod: bool = config.get("PROD", "False").lower() == "true" base_dir = "XAgentServer" use_redis: bool = False recorder_root_dir = "running_records" # you can set default_login with True, # use the default user "admin" with token "xagent-admin" to login, default_login: bool = True # only one XAgentServer can be set to check whether the interaction is running. check_running: bool = False host = "0.0.0.0" port = 8090 debug = True reload = True workers = 1 share_url = "https://x-agent.net/api/conv/community" class DB: """ database config """ use_db = True db_url = "mysql+pymysql://root:xagent@localhost:3306/xagent" class Redis: """ redis config """ use_redis = False redis_url = "redis://localhost" redis_host = "localhost" redis_port = 6379 redis_db = 0 redis_password = "xagent" # if you want to use email to send message, # you can set send_email to True and set # email_host, # email_port, # email_user, # email_password, # auth_server class Email: """ email config """ send_email = False email_host = "" email_port = 465 email_user = "" email_password = "" auth_server = "" # if you want to use upload function, # you can set upload_dir to the path of the upload directory # and set upload_allowed_types of the allowed types class Upload: """ upload config """ upload_dir = "XAgentServer/localstorage/upload" if not os.path.exists(upload_dir): os.makedirs(upload_dir) upload_allowed_types = ["image/png", "image/jpeg", "image/gif", "text/plain", "application/msword", "pdf", "txt", "pptx", "xlsx", "doc", "ppt", "xls", "zip", "rar", "tar", "gz", "7z", "bz2", "tgz", "tbz2", "tar.gz", "tar.bz2"] class InteractionCRUD(metaclass=abc.ABCMeta): """ interaction crud """ def search_many_interaction(cls, db: Session) -> list: """ search many interaction """ try: return InteractionDBInterface.search_many_interaction(db=db) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_interaction(cls, db: Session, interaction_id: str) -> InteractionBase | None: """ get interaction Args: db: db interaction_id: interaction id Returns: interaction InteractionBase Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_interaction(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def create_interaction(cls, db: Session, base: InteractionBase): """ create interaction Args: db: db base: base Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.create_interaction(db=db, base=base) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_ready_interaction(cls, db: Session, user_id: str): """ create interaction Args: db: db user_id: user_id Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_ready_interaction(db=db, user_id=user_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def add_parameter(cls, db: Session, parameter: InteractionParameter = None): """ add parameter Args: db: db parameter: parameter Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.add_parameter(db=db, parameter=parameter) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_parameter(cls, db: Session, interaction_id: str) -> list: """ get parameter Args: db: db interaction_id: interaction id Returns: parameter list [InteractionParameter] Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_parameter(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_init_parameter(cls, db: Session, interaction_id: str) -> InteractionParameter: """ get init parameter Args: db: db interaction_id: interaction id Returns: parameter InteractionParameter Raises: XAgentDBError: XAgent DB Error """ try: parameters = InteractionDBInterface.get_parameter(db=db, interaction_id=interaction_id) init_parameter = parameters[0] parameter = InteractionParameter.from_json({"args": init_parameter, "interaction_id": interaction_id, "parameter_id": None}) return parameter except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def search_interaction_by_user_id(cls, db: Session, user_id: str, page_size: int = 10, page_num: int = 1) -> list[dict]: """ get interaction by user id Args: db: db user_id: user id page_size: page size page_num: page num Returns: interaction list [dict] Raises: XAgentDBError: XAgent DB Error """ return InteractionDBInterface.search_interaction_by_user_id(db=db, user_id=user_id, page_size=page_size, page_num=page_num) def is_exist(cls, db: Session, interaction_id: str) -> bool: """ interaction is exist Args: db: db interaction_id: interaction id Returns: True if interaction is exist, else False Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.is_exist(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_interaction(cls, db: Session, base_data: dict): """ update interaction Args: db: db base_data: base data Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_interaction(db=db, base_data=base_data) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_interaction_status(cls, db: Session, interaction_id: str, status: str, message: str, current_step: int): """ update interaction status Args: db: db interaction_id: interaction id status: status message: message current_step: current step Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_interaction_status( db=db, interaction_id=interaction_id, status=status, message=message, current_step=current_step) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_interaction_parameter(cls, db: Session, interaction_id: str, parameter: InteractionParameter): """ update interaction parameter Args: db: db interaction_id: interaction id parameter: parameter Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_interaction_parameter( db=db, interaction_id=interaction_id, parameter=parameter) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def is_running(cls, db: Session, user_id: str): """ is running Args: db: db user_id: user id Returns: True if running, else False Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.is_running(db=db, user_id=user_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def delete_interaction(cls, db: Session, interaction_id: str): """ delete interaction Args: db: db interaction_id: interaction id Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.delete_interaction( db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_shared_interaction(cls, db: Session, interaction_id: str) -> InteractionBase | None: """ get shared interaction Args: db: db interaction_id: interaction id Returns: interaction InteractionBase, if not found, return None Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_shared_interaction( db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def search_many_shared(cls, db: Session, page_size: int = 20, page_index: int = 1) -> list[dict]: """ search many shared Args: db: db page_size: page size page_index: page index Returns: interaction list [dict] Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.search_many_shared(db=db, page_size=page_size, page_index=page_index) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def insert_raw(cls, db: Session, process: XAgentRaw): """ insert raw Args: db: db process: process Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.insert_raw(db=db, process=process) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def search_many_raws(cls, db: Session, interaction_id: str) -> List[XAgentRaw] | None: """ search many raws Args: db: db interaction_id: interaction id Returns: raw list [XAgentRaw] Raises: XAgentDBError: XAgent DB Error """ try: return [XAgentRaw.from_db(raw) for raw in InteractionDBInterface.search_many_raws(db=db, interaction_id=interaction_id)] except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_raw(cls, db: Session, interaction_id: str, node_id: str) -> XAgentRaw | None: """ get raw Args: db: db interaction_id: interaction id node_id: node id Returns: raw XAgentRaw, if not found, return None Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_raw(db=db, interaction_id=interaction_id, node_id=node_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_next_send(cls, db: Session, interaction_id: str) -> List[Raw] | None: """ get next send Args: db: db interaction_id: interaction id Returns: raw list [Raw] Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_next_send(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_send_flag(cls, db: Session, interaction_id: str, node_id: str): """ update send flag Args: db: db interaction_id: interaction id node_id: node id Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_send_flag( db=db, interaction_id=interaction_id, node_id=node_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_receive_flag(cls, db: Session, interaction_id: str, node_id: str): """ update receive flag Args: db: db interaction_id: interaction id node_id: node id Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_receive_flag( db=db, interaction_id=interaction_id, node_id=node_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_human_data(cls, db: Session, interaction_id: str, node_id: str, human_data: dict): """ update human data Args: db: db interaction_id: interaction id node_id: node id human_data: human data Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_human_data(db=db, interaction_id=interaction_id, node_id=node_id, human_data=human_data) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def insert_error(cls, db: Session, interaction_id: str, message: str, status: str = "failed"): """ insert error Args: db: db interaction_id: interaction id message: message status: status, default is failed Returns: raw XAgentRaw Raises: XAgentDBError: XAgent DB Error """ try: process = XAgentRaw( node_id=uuid.uuid4().hex, interaction_id=interaction_id, current="", step=0, data=message, file_list=[], status=status, do_interrupt=False, wait_seconds=0, ask_for_human_help=False, create_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"), update_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"), is_deleted=False, is_human=False, human_data={}, human_file_list=[], is_send=False, is_receive=False, include_pictures=False, ) InteractionDBInterface.insert_raw(db=db, process=process) return process except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def add_share(cls, db: Session, share): """ add share Args: db: db share: share Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.add_share(db=db, shared=share) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_finish_status(cls, db: Session, interaction_id: str) -> bool: """ get finish status Args: db: db interaction_id: interaction id Returns: True if finish, else False """ try: return InteractionDBInterface.get_finish_status(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_db(): """db""" session = SessionLocal() try: yield session session.commit() except Exception as e: session.rollback() raise e finally: session.close() class ResponseBody(BaseModel): """Response body """ data: Union[str, dict, list, Json, None] = None success: bool = True message: Union[str, None] = None def to_dict(self): """to dict """ return self.dict() def to_json(self): """to json """ return self.json() class StatusEnum: """XAgent Status Enum """ START = "start" SUBTASK = "subtask" REFINEMENT = "refinement" INNER = "inner" FINISHED = "finished" FAILED = "failed" SUBMIT = "subtask_submit" RUNNING = "running" ASK_FOR_HUMAN_HELP = "ask_for_human_help" CLOSED = "closed" class XAgentWebError(XAgentError): """Exception raised because of Running error Attributes: message -- explanation of the error """ def __init__(self, message="XAgent WEB Error!"): self.message = message super().__init__(self.message) class InteractionBase(metaclass=abc.ABCMeta): def __init__(self, interaction_id: str, user_id: str, create_time: str, description: str, agent: str = "", mode: str = "", file_list: list = [], recorder_root_dir: str = "", status: str = "", message: str = "", current_step: str = "", update_time: str = "", is_deleted: bool = False, call_method: str = "web", ): self.interaction_id = interaction_id self.user_id = user_id self.create_time = create_time self.description = description self.agent = agent self.mode = mode self.file_list = file_list self.recorder_root_dir = recorder_root_dir self.status = status self.message = message self.current_step = current_step self.update_time = update_time self.is_deleted = is_deleted self.call_method = call_method def to_dict(self, include=None, exclude=None): data = { "interaction_id": self.interaction_id, "user_id": self.user_id, "create_time": self.create_time, "description": self.description, "agent": self.agent, "mode": self.mode, "file_list": self.file_list, "recorder_root_dir": self.recorder_root_dir, "status": self.status, "message": self.message, "current_step": self.current_step, "update_time": self.update_time, "is_deleted": self.is_deleted, "call_method": self.call_method, } if include: data = {k: v for k, v in data.items() if k in include} if exclude: data = {k: v for k, v in data.items() if k not in exclude} return data def to_json(self): return json.dumps(self.to_dict(), indent=2, ensure_ascii=False) def from_json(cls, json_data): return cls(**json_data) def from_db(cls, interaction): return cls(interaction.interaction_id, interaction.user_id, interaction.create_time, interaction.description, interaction.agent, interaction.mode, interaction.file_list, interaction.recorder_root_dir, interaction.status, interaction.message, interaction.current_step, interaction.update_time, interaction.is_deleted, interaction.call_method, ) class XAgentRaw(metaclass=abc.ABCMeta): """XAgent Raw Object""" def __init__(self, node_id: str, interaction_id: str, current: str, step: int, data: dict, file_list: list, status: str, do_interrupt: bool, wait_seconds: int, ask_for_human_help: bool, create_time: str, update_time: str, is_deleted: bool, is_human: bool, human_data: dict, human_file_list: list, is_send: bool, is_receive: bool, include_pictures: bool = False,): self.node_id = node_id self.interaction_id = interaction_id self.current = current self.step = step self.data = data self.file_list = file_list self.status = status self.do_interrupt = do_interrupt self.wait_seconds = wait_seconds self.ask_for_human_help = ask_for_human_help self.create_time = create_time self.update_time = update_time self.is_deleted = is_deleted self.is_human = is_human self.human_data = human_data self.human_file_list = human_file_list self.is_send = is_send self.is_receive = is_receive self.include_pictures = include_pictures def to_dict(self): """XAgent Raw Object to dict""" return { "node_id": self.node_id, "interaction_id": self.interaction_id, "current": self.current, "step": self.step, "data": self.data, "file_list": self.file_list, "status": self.status, "do_interrupt": self.do_interrupt, "wait_seconds": self.wait_seconds, "ask_for_human_help": self.ask_for_human_help, "create_time": self.create_time, "update_time": self.update_time, "is_deleted": self.is_deleted, "is_human": self.is_human, "human_data": self.human_data, "human_file_list": self.human_file_list, "is_send": self.is_send, "is_receive": self.is_receive, "include_pictures": self.include_pictures } def to_json(self): """XAgent Raw Object to json""" return json.dumps(self.to_dict(), indent=2, ensure_ascii=False) def from_json(cls, json_data): """XAgent Raw Object from json""" return cls(**json_data) def update(self, update_data: dict): """XAgent Raw Object update""" for k, v in update_data.items(): setattr(self, k, v) return self def from_db(cls, db_data): """XAgent Raw Object from db""" return cls( node_id=db_data.node_id, interaction_id=db_data.interaction_id, current=db_data.current, step=db_data.step, data=db_data.data, file_list=db_data.file_list, status=db_data.status, do_interrupt=db_data.do_interrupt, wait_seconds=db_data.wait_seconds, ask_for_human_help=db_data.ask_for_human_help, create_time=db_data.create_time, update_time=db_data.update_time, is_deleted=db_data.is_deleted, is_human=db_data.is_human, human_data=db_data.human_data, human_file_list=db_data.human_file_list, is_send=db_data.is_send, is_receive=db_data.is_receive, include_pictures=db_data.include_pictures ) class SharedInteractionBase(metaclass=abc.ABCMeta): def __init__(self, interaction_id: str, user_name: str, create_time: str, update_time: str, description: str, agent: str = "", mode: str = "", is_deleted: bool = False, star: int = 0, is_audit: bool = False ): self.interaction_id = interaction_id self.user_name = user_name self.create_time = create_time self.update_time = update_time self.description = description self.agent = agent self.mode = mode self.is_deleted = is_deleted self.star = star self.is_audit = is_audit def to_dict(self, include=None, exclude=None): data = { "interaction_id": self.interaction_id, "user_name": self.user_name, "create_time": self.create_time, "update_time": self.update_time, "description": self.description, "agent": self.agent, "mode": self.mode, "is_deleted": self.is_deleted, "star": self.star, "is_audit": self.is_audit } if include: data = {k: v for k, v in data.items() if k in include} if exclude: data = {k: v for k, v in data.items() if k not in exclude} return data def to_json(self): return json.dumps(self.to_dict(), indent=2, ensure_ascii=False) def from_db(cls, interaction): return cls(interaction.interaction_id, interaction.user_name, interaction.create_time, interaction.update_time, interaction.description, interaction.agent, interaction.mode, interaction.is_deleted, interaction.star, interaction.is_audit ) The provided code snippet includes necessary dependencies for implementing the `community` function. Write a Python function `def community(user_id: str = Depends(user_is_available), user_name: str = Form(...), interaction: str = Form(...), raws: str = Form(...), files: UploadFile = File(...), db: Session = Depends(get_db))` to solve the following problem: community, this api is runing on x-agent.net Here is the function: def community(user_id: str = Depends(user_is_available), user_name: str = Form(...), interaction: str = Form(...), raws: str = Form(...), files: UploadFile = File(...), db: Session = Depends(get_db)): """ community, this api is runing on x-agent.net """ interaction = json.loads(interaction) raws = json.loads(raws) interaction_id = interaction["interaction_id"] old_share = InteractionCRUD.get_shared_interaction( db=db, interaction_id=interaction_id) # 如果已经分享过了,就不再分享了 if old_share: raise XAgentWebError("interaction is exist!") contain_finish = False for raw in raws: if raw["status"] == StatusEnum.FINISHED: contain_finish = True break # 如果没有finish的节点,就不分享了 if not contain_finish: raise XAgentWebError("interaction is not finish!") interaction_dir = os.path.join(XAgentServerEnv.base_dir, "localstorage", "interact_records", interaction["create_time"][:10], interaction_id, "workspace") if not os.path.exists(interaction_dir): os.makedirs(interaction_dir) # 先暂存文件 with open(os.path.join(interaction_dir, "workspace.zip"), "wb") as f: f.write(files.file.read()) # 解压文件 with zipfile.ZipFile(file=os.path.join(interaction_dir, "workspace.zip"), mode="r") as zip_file: zip_list = zip_file.namelist() # 得到压缩包里所有文件 for f in zip_list: zip_file.extract(f, interaction_dir) # 循环解压文件到指定目录 # 删除压缩包 os.remove(os.path.join(interaction_dir, "workspace.zip")) base = InteractionBase(**interaction) share = SharedInteractionBase( interaction_id=interaction_id, user_name=user_name, create_time=interaction["create_time"], update_time=interaction["update_time"], description=interaction["description"], agent=interaction["agent"], mode=interaction["mode"], is_deleted=False, star=0, is_audit=False ) InteractionCRUD.create_interaction(db=db, base=base) InteractionCRUD.add_share(db=db, share=share) for raw in raws: old_raw = InteractionCRUD.get_raw(db=db, interaction_id=interaction_id, node_id=raw["node_id"]) if old_raw is None: xraw = XAgentRaw(**raw) InteractionCRUD.insert_raw(db=db, process=xraw) return ResponseBody(data=None, success=True, message="success")
community, this api is runing on x-agent.net
6,294
from datetime import datetime import time import json import os from typing import List import uuid import zipfile from fastapi import APIRouter, Depends, File, Form, UploadFile import requests from sqlalchemy.orm import Session from XAgentServer.application.core.envs import XAgentServerEnv from XAgentServer.application.cruds.interaction import InteractionCRUD from XAgentServer.application.cruds.user import UserCRUD from XAgentServer.application.dependence import get_db from XAgentServer.application.schemas.response_body import ResponseBody from XAgentServer.enums.status import StatusEnum from XAgentServer.exts.exception_ext import XAgentAuthError, XAgentWebError from XAgentServer.models.interaction import InteractionBase from XAgentServer.models.raw import XAgentRaw from XAgentServer.models.shared_interaction import SharedInteractionBase def user_is_available( user_id: str = Form(...), token: str = Form(...), db: Session = Depends(get_db)): """ check user is available """ if user_id == "": raise XAgentAuthError("user_id is empty!") if not UserCRUD.is_exist(db=db, user_id=user_id): raise XAgentAuthError("user is not exist!") if not UserCRUD.user_is_valid(db=db, user_id=user_id, token=token): raise XAgentAuthError("user is not available!") return user_id class InteractionCRUD(metaclass=abc.ABCMeta): """ interaction crud """ def search_many_interaction(cls, db: Session) -> list: """ search many interaction """ try: return InteractionDBInterface.search_many_interaction(db=db) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_interaction(cls, db: Session, interaction_id: str) -> InteractionBase | None: """ get interaction Args: db: db interaction_id: interaction id Returns: interaction InteractionBase Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_interaction(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def create_interaction(cls, db: Session, base: InteractionBase): """ create interaction Args: db: db base: base Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.create_interaction(db=db, base=base) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_ready_interaction(cls, db: Session, user_id: str): """ create interaction Args: db: db user_id: user_id Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_ready_interaction(db=db, user_id=user_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def add_parameter(cls, db: Session, parameter: InteractionParameter = None): """ add parameter Args: db: db parameter: parameter Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.add_parameter(db=db, parameter=parameter) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_parameter(cls, db: Session, interaction_id: str) -> list: """ get parameter Args: db: db interaction_id: interaction id Returns: parameter list [InteractionParameter] Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_parameter(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_init_parameter(cls, db: Session, interaction_id: str) -> InteractionParameter: """ get init parameter Args: db: db interaction_id: interaction id Returns: parameter InteractionParameter Raises: XAgentDBError: XAgent DB Error """ try: parameters = InteractionDBInterface.get_parameter(db=db, interaction_id=interaction_id) init_parameter = parameters[0] parameter = InteractionParameter.from_json({"args": init_parameter, "interaction_id": interaction_id, "parameter_id": None}) return parameter except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def search_interaction_by_user_id(cls, db: Session, user_id: str, page_size: int = 10, page_num: int = 1) -> list[dict]: """ get interaction by user id Args: db: db user_id: user id page_size: page size page_num: page num Returns: interaction list [dict] Raises: XAgentDBError: XAgent DB Error """ return InteractionDBInterface.search_interaction_by_user_id(db=db, user_id=user_id, page_size=page_size, page_num=page_num) def is_exist(cls, db: Session, interaction_id: str) -> bool: """ interaction is exist Args: db: db interaction_id: interaction id Returns: True if interaction is exist, else False Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.is_exist(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_interaction(cls, db: Session, base_data: dict): """ update interaction Args: db: db base_data: base data Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_interaction(db=db, base_data=base_data) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_interaction_status(cls, db: Session, interaction_id: str, status: str, message: str, current_step: int): """ update interaction status Args: db: db interaction_id: interaction id status: status message: message current_step: current step Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_interaction_status( db=db, interaction_id=interaction_id, status=status, message=message, current_step=current_step) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_interaction_parameter(cls, db: Session, interaction_id: str, parameter: InteractionParameter): """ update interaction parameter Args: db: db interaction_id: interaction id parameter: parameter Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_interaction_parameter( db=db, interaction_id=interaction_id, parameter=parameter) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def is_running(cls, db: Session, user_id: str): """ is running Args: db: db user_id: user id Returns: True if running, else False Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.is_running(db=db, user_id=user_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def delete_interaction(cls, db: Session, interaction_id: str): """ delete interaction Args: db: db interaction_id: interaction id Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.delete_interaction( db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_shared_interaction(cls, db: Session, interaction_id: str) -> InteractionBase | None: """ get shared interaction Args: db: db interaction_id: interaction id Returns: interaction InteractionBase, if not found, return None Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_shared_interaction( db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def search_many_shared(cls, db: Session, page_size: int = 20, page_index: int = 1) -> list[dict]: """ search many shared Args: db: db page_size: page size page_index: page index Returns: interaction list [dict] Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.search_many_shared(db=db, page_size=page_size, page_index=page_index) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def insert_raw(cls, db: Session, process: XAgentRaw): """ insert raw Args: db: db process: process Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.insert_raw(db=db, process=process) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def search_many_raws(cls, db: Session, interaction_id: str) -> List[XAgentRaw] | None: """ search many raws Args: db: db interaction_id: interaction id Returns: raw list [XAgentRaw] Raises: XAgentDBError: XAgent DB Error """ try: return [XAgentRaw.from_db(raw) for raw in InteractionDBInterface.search_many_raws(db=db, interaction_id=interaction_id)] except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_raw(cls, db: Session, interaction_id: str, node_id: str) -> XAgentRaw | None: """ get raw Args: db: db interaction_id: interaction id node_id: node id Returns: raw XAgentRaw, if not found, return None Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_raw(db=db, interaction_id=interaction_id, node_id=node_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_next_send(cls, db: Session, interaction_id: str) -> List[Raw] | None: """ get next send Args: db: db interaction_id: interaction id Returns: raw list [Raw] Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_next_send(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_send_flag(cls, db: Session, interaction_id: str, node_id: str): """ update send flag Args: db: db interaction_id: interaction id node_id: node id Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_send_flag( db=db, interaction_id=interaction_id, node_id=node_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_receive_flag(cls, db: Session, interaction_id: str, node_id: str): """ update receive flag Args: db: db interaction_id: interaction id node_id: node id Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_receive_flag( db=db, interaction_id=interaction_id, node_id=node_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_human_data(cls, db: Session, interaction_id: str, node_id: str, human_data: dict): """ update human data Args: db: db interaction_id: interaction id node_id: node id human_data: human data Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_human_data(db=db, interaction_id=interaction_id, node_id=node_id, human_data=human_data) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def insert_error(cls, db: Session, interaction_id: str, message: str, status: str = "failed"): """ insert error Args: db: db interaction_id: interaction id message: message status: status, default is failed Returns: raw XAgentRaw Raises: XAgentDBError: XAgent DB Error """ try: process = XAgentRaw( node_id=uuid.uuid4().hex, interaction_id=interaction_id, current="", step=0, data=message, file_list=[], status=status, do_interrupt=False, wait_seconds=0, ask_for_human_help=False, create_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"), update_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"), is_deleted=False, is_human=False, human_data={}, human_file_list=[], is_send=False, is_receive=False, include_pictures=False, ) InteractionDBInterface.insert_raw(db=db, process=process) return process except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def add_share(cls, db: Session, share): """ add share Args: db: db share: share Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.add_share(db=db, shared=share) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_finish_status(cls, db: Session, interaction_id: str) -> bool: """ get finish status Args: db: db interaction_id: interaction id Returns: True if finish, else False """ try: return InteractionDBInterface.get_finish_status(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_db(): """db""" session = SessionLocal() try: yield session session.commit() except Exception as e: session.rollback() raise e finally: session.close() class ResponseBody(BaseModel): """Response body """ data: Union[str, dict, list, Json, None] = None success: bool = True message: Union[str, None] = None def to_dict(self): """to dict """ return self.dict() def to_json(self): """to json """ return self.json() The provided code snippet includes necessary dependencies for implementing the `delete_interaction` function. Write a Python function `async def delete_interaction(user_id: str = Depends(user_is_available), interaction_id: str = Form(...), db: Session = Depends(get_db)) -> ResponseBody` to solve the following problem: delete Here is the function: async def delete_interaction(user_id: str = Depends(user_is_available), interaction_id: str = Form(...), db: Session = Depends(get_db)) -> ResponseBody: """ delete """ data = InteractionCRUD.delete_interaction(db=db, interaction_id=interaction_id) return ResponseBody(data=data, success=True, message="success")
delete
6,295
from datetime import datetime import time import json import os from typing import List import uuid import zipfile from fastapi import APIRouter, Depends, File, Form, UploadFile import requests from sqlalchemy.orm import Session from XAgentServer.application.core.envs import XAgentServerEnv from XAgentServer.application.cruds.interaction import InteractionCRUD from XAgentServer.application.cruds.user import UserCRUD from XAgentServer.application.dependence import get_db from XAgentServer.application.schemas.response_body import ResponseBody from XAgentServer.enums.status import StatusEnum from XAgentServer.exts.exception_ext import XAgentAuthError, XAgentWebError from XAgentServer.models.interaction import InteractionBase from XAgentServer.models.raw import XAgentRaw from XAgentServer.models.shared_interaction import SharedInteractionBase def user_is_available( user_id: str = Form(...), token: str = Form(...), db: Session = Depends(get_db)): """ check user is available """ if user_id == "": raise XAgentAuthError("user_id is empty!") if not UserCRUD.is_exist(db=db, user_id=user_id): raise XAgentAuthError("user is not exist!") if not UserCRUD.user_is_valid(db=db, user_id=user_id, token=token): raise XAgentAuthError("user is not available!") return user_id class InteractionCRUD(metaclass=abc.ABCMeta): """ interaction crud """ def search_many_interaction(cls, db: Session) -> list: """ search many interaction """ try: return InteractionDBInterface.search_many_interaction(db=db) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_interaction(cls, db: Session, interaction_id: str) -> InteractionBase | None: """ get interaction Args: db: db interaction_id: interaction id Returns: interaction InteractionBase Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_interaction(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def create_interaction(cls, db: Session, base: InteractionBase): """ create interaction Args: db: db base: base Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.create_interaction(db=db, base=base) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_ready_interaction(cls, db: Session, user_id: str): """ create interaction Args: db: db user_id: user_id Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_ready_interaction(db=db, user_id=user_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def add_parameter(cls, db: Session, parameter: InteractionParameter = None): """ add parameter Args: db: db parameter: parameter Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.add_parameter(db=db, parameter=parameter) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_parameter(cls, db: Session, interaction_id: str) -> list: """ get parameter Args: db: db interaction_id: interaction id Returns: parameter list [InteractionParameter] Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_parameter(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_init_parameter(cls, db: Session, interaction_id: str) -> InteractionParameter: """ get init parameter Args: db: db interaction_id: interaction id Returns: parameter InteractionParameter Raises: XAgentDBError: XAgent DB Error """ try: parameters = InteractionDBInterface.get_parameter(db=db, interaction_id=interaction_id) init_parameter = parameters[0] parameter = InteractionParameter.from_json({"args": init_parameter, "interaction_id": interaction_id, "parameter_id": None}) return parameter except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def search_interaction_by_user_id(cls, db: Session, user_id: str, page_size: int = 10, page_num: int = 1) -> list[dict]: """ get interaction by user id Args: db: db user_id: user id page_size: page size page_num: page num Returns: interaction list [dict] Raises: XAgentDBError: XAgent DB Error """ return InteractionDBInterface.search_interaction_by_user_id(db=db, user_id=user_id, page_size=page_size, page_num=page_num) def is_exist(cls, db: Session, interaction_id: str) -> bool: """ interaction is exist Args: db: db interaction_id: interaction id Returns: True if interaction is exist, else False Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.is_exist(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_interaction(cls, db: Session, base_data: dict): """ update interaction Args: db: db base_data: base data Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_interaction(db=db, base_data=base_data) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_interaction_status(cls, db: Session, interaction_id: str, status: str, message: str, current_step: int): """ update interaction status Args: db: db interaction_id: interaction id status: status message: message current_step: current step Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_interaction_status( db=db, interaction_id=interaction_id, status=status, message=message, current_step=current_step) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_interaction_parameter(cls, db: Session, interaction_id: str, parameter: InteractionParameter): """ update interaction parameter Args: db: db interaction_id: interaction id parameter: parameter Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_interaction_parameter( db=db, interaction_id=interaction_id, parameter=parameter) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def is_running(cls, db: Session, user_id: str): """ is running Args: db: db user_id: user id Returns: True if running, else False Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.is_running(db=db, user_id=user_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def delete_interaction(cls, db: Session, interaction_id: str): """ delete interaction Args: db: db interaction_id: interaction id Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.delete_interaction( db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_shared_interaction(cls, db: Session, interaction_id: str) -> InteractionBase | None: """ get shared interaction Args: db: db interaction_id: interaction id Returns: interaction InteractionBase, if not found, return None Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_shared_interaction( db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def search_many_shared(cls, db: Session, page_size: int = 20, page_index: int = 1) -> list[dict]: """ search many shared Args: db: db page_size: page size page_index: page index Returns: interaction list [dict] Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.search_many_shared(db=db, page_size=page_size, page_index=page_index) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def insert_raw(cls, db: Session, process: XAgentRaw): """ insert raw Args: db: db process: process Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.insert_raw(db=db, process=process) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def search_many_raws(cls, db: Session, interaction_id: str) -> List[XAgentRaw] | None: """ search many raws Args: db: db interaction_id: interaction id Returns: raw list [XAgentRaw] Raises: XAgentDBError: XAgent DB Error """ try: return [XAgentRaw.from_db(raw) for raw in InteractionDBInterface.search_many_raws(db=db, interaction_id=interaction_id)] except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_raw(cls, db: Session, interaction_id: str, node_id: str) -> XAgentRaw | None: """ get raw Args: db: db interaction_id: interaction id node_id: node id Returns: raw XAgentRaw, if not found, return None Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_raw(db=db, interaction_id=interaction_id, node_id=node_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_next_send(cls, db: Session, interaction_id: str) -> List[Raw] | None: """ get next send Args: db: db interaction_id: interaction id Returns: raw list [Raw] Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_next_send(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_send_flag(cls, db: Session, interaction_id: str, node_id: str): """ update send flag Args: db: db interaction_id: interaction id node_id: node id Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_send_flag( db=db, interaction_id=interaction_id, node_id=node_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_receive_flag(cls, db: Session, interaction_id: str, node_id: str): """ update receive flag Args: db: db interaction_id: interaction id node_id: node id Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_receive_flag( db=db, interaction_id=interaction_id, node_id=node_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_human_data(cls, db: Session, interaction_id: str, node_id: str, human_data: dict): """ update human data Args: db: db interaction_id: interaction id node_id: node id human_data: human data Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_human_data(db=db, interaction_id=interaction_id, node_id=node_id, human_data=human_data) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def insert_error(cls, db: Session, interaction_id: str, message: str, status: str = "failed"): """ insert error Args: db: db interaction_id: interaction id message: message status: status, default is failed Returns: raw XAgentRaw Raises: XAgentDBError: XAgent DB Error """ try: process = XAgentRaw( node_id=uuid.uuid4().hex, interaction_id=interaction_id, current="", step=0, data=message, file_list=[], status=status, do_interrupt=False, wait_seconds=0, ask_for_human_help=False, create_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"), update_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"), is_deleted=False, is_human=False, human_data={}, human_file_list=[], is_send=False, is_receive=False, include_pictures=False, ) InteractionDBInterface.insert_raw(db=db, process=process) return process except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def add_share(cls, db: Session, share): """ add share Args: db: db share: share Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.add_share(db=db, shared=share) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_finish_status(cls, db: Session, interaction_id: str) -> bool: """ get finish status Args: db: db interaction_id: interaction id Returns: True if finish, else False """ try: return InteractionDBInterface.get_finish_status(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_db(): """db""" session = SessionLocal() try: yield session session.commit() except Exception as e: session.rollback() raise e finally: session.close() class ResponseBody(BaseModel): """Response body """ data: Union[str, dict, list, Json, None] = None success: bool = True message: Union[str, None] = None def to_dict(self): """to dict """ return self.dict() def to_json(self): """to json """ return self.json() The provided code snippet includes necessary dependencies for implementing the `update_interaction_parameter` function. Write a Python function `async def update_interaction_parameter(user_id: str = Depends(user_is_available), mode: str = Form(...), agent: str = Form(...), file_list: List[str] = Form(...), interaction_id: str = Form(...), db: Session = Depends(get_db) ) -> ResponseBody` to solve the following problem: update parameter Here is the function: async def update_interaction_parameter(user_id: str = Depends(user_is_available), mode: str = Form(...), agent: str = Form(...), file_list: List[str] = Form(...), interaction_id: str = Form(...), db: Session = Depends(get_db) ) -> ResponseBody: """ update parameter """ if interaction_id == "": return ResponseBody(success=False, message="interaction_id is empty!") interaction = InteractionCRUD.get_interaction(db=db, interaction_id=interaction_id) if interaction is None: return ResponseBody(success=False, message=f"Don't find any interaction by interaction_id:\ {interaction_id}, Please check your interaction_id!") update_data = { "interaction_id": interaction_id, "agent": agent, "mode": mode, "file_list": [json.loads(l) for l in file_list], } InteractionCRUD.update_interaction(db=db, base_data=update_data) return ResponseBody(data=update_data, success=True, message="success!")
update parameter
6,296
from datetime import datetime import time import json import os from typing import List import uuid import zipfile from fastapi import APIRouter, Depends, File, Form, UploadFile import requests from sqlalchemy.orm import Session from XAgentServer.application.core.envs import XAgentServerEnv from XAgentServer.application.cruds.interaction import InteractionCRUD from XAgentServer.application.cruds.user import UserCRUD from XAgentServer.application.dependence import get_db from XAgentServer.application.schemas.response_body import ResponseBody from XAgentServer.enums.status import StatusEnum from XAgentServer.exts.exception_ext import XAgentAuthError, XAgentWebError from XAgentServer.models.interaction import InteractionBase from XAgentServer.models.raw import XAgentRaw from XAgentServer.models.shared_interaction import SharedInteractionBase def user_is_available( user_id: str = Form(...), token: str = Form(...), db: Session = Depends(get_db)): """ check user is available """ if user_id == "": raise XAgentAuthError("user_id is empty!") if not UserCRUD.is_exist(db=db, user_id=user_id): raise XAgentAuthError("user is not exist!") if not UserCRUD.user_is_valid(db=db, user_id=user_id, token=token): raise XAgentAuthError("user is not available!") return user_id class InteractionCRUD(metaclass=abc.ABCMeta): """ interaction crud """ def search_many_interaction(cls, db: Session) -> list: """ search many interaction """ try: return InteractionDBInterface.search_many_interaction(db=db) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_interaction(cls, db: Session, interaction_id: str) -> InteractionBase | None: """ get interaction Args: db: db interaction_id: interaction id Returns: interaction InteractionBase Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_interaction(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def create_interaction(cls, db: Session, base: InteractionBase): """ create interaction Args: db: db base: base Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.create_interaction(db=db, base=base) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_ready_interaction(cls, db: Session, user_id: str): """ create interaction Args: db: db user_id: user_id Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_ready_interaction(db=db, user_id=user_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def add_parameter(cls, db: Session, parameter: InteractionParameter = None): """ add parameter Args: db: db parameter: parameter Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.add_parameter(db=db, parameter=parameter) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_parameter(cls, db: Session, interaction_id: str) -> list: """ get parameter Args: db: db interaction_id: interaction id Returns: parameter list [InteractionParameter] Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_parameter(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_init_parameter(cls, db: Session, interaction_id: str) -> InteractionParameter: """ get init parameter Args: db: db interaction_id: interaction id Returns: parameter InteractionParameter Raises: XAgentDBError: XAgent DB Error """ try: parameters = InteractionDBInterface.get_parameter(db=db, interaction_id=interaction_id) init_parameter = parameters[0] parameter = InteractionParameter.from_json({"args": init_parameter, "interaction_id": interaction_id, "parameter_id": None}) return parameter except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def search_interaction_by_user_id(cls, db: Session, user_id: str, page_size: int = 10, page_num: int = 1) -> list[dict]: """ get interaction by user id Args: db: db user_id: user id page_size: page size page_num: page num Returns: interaction list [dict] Raises: XAgentDBError: XAgent DB Error """ return InteractionDBInterface.search_interaction_by_user_id(db=db, user_id=user_id, page_size=page_size, page_num=page_num) def is_exist(cls, db: Session, interaction_id: str) -> bool: """ interaction is exist Args: db: db interaction_id: interaction id Returns: True if interaction is exist, else False Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.is_exist(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_interaction(cls, db: Session, base_data: dict): """ update interaction Args: db: db base_data: base data Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_interaction(db=db, base_data=base_data) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_interaction_status(cls, db: Session, interaction_id: str, status: str, message: str, current_step: int): """ update interaction status Args: db: db interaction_id: interaction id status: status message: message current_step: current step Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_interaction_status( db=db, interaction_id=interaction_id, status=status, message=message, current_step=current_step) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_interaction_parameter(cls, db: Session, interaction_id: str, parameter: InteractionParameter): """ update interaction parameter Args: db: db interaction_id: interaction id parameter: parameter Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_interaction_parameter( db=db, interaction_id=interaction_id, parameter=parameter) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def is_running(cls, db: Session, user_id: str): """ is running Args: db: db user_id: user id Returns: True if running, else False Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.is_running(db=db, user_id=user_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def delete_interaction(cls, db: Session, interaction_id: str): """ delete interaction Args: db: db interaction_id: interaction id Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.delete_interaction( db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_shared_interaction(cls, db: Session, interaction_id: str) -> InteractionBase | None: """ get shared interaction Args: db: db interaction_id: interaction id Returns: interaction InteractionBase, if not found, return None Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_shared_interaction( db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def search_many_shared(cls, db: Session, page_size: int = 20, page_index: int = 1) -> list[dict]: """ search many shared Args: db: db page_size: page size page_index: page index Returns: interaction list [dict] Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.search_many_shared(db=db, page_size=page_size, page_index=page_index) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def insert_raw(cls, db: Session, process: XAgentRaw): """ insert raw Args: db: db process: process Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.insert_raw(db=db, process=process) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def search_many_raws(cls, db: Session, interaction_id: str) -> List[XAgentRaw] | None: """ search many raws Args: db: db interaction_id: interaction id Returns: raw list [XAgentRaw] Raises: XAgentDBError: XAgent DB Error """ try: return [XAgentRaw.from_db(raw) for raw in InteractionDBInterface.search_many_raws(db=db, interaction_id=interaction_id)] except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_raw(cls, db: Session, interaction_id: str, node_id: str) -> XAgentRaw | None: """ get raw Args: db: db interaction_id: interaction id node_id: node id Returns: raw XAgentRaw, if not found, return None Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_raw(db=db, interaction_id=interaction_id, node_id=node_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_next_send(cls, db: Session, interaction_id: str) -> List[Raw] | None: """ get next send Args: db: db interaction_id: interaction id Returns: raw list [Raw] Raises: XAgentDBError: XAgent DB Error """ try: return InteractionDBInterface.get_next_send(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_send_flag(cls, db: Session, interaction_id: str, node_id: str): """ update send flag Args: db: db interaction_id: interaction id node_id: node id Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_send_flag( db=db, interaction_id=interaction_id, node_id=node_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_receive_flag(cls, db: Session, interaction_id: str, node_id: str): """ update receive flag Args: db: db interaction_id: interaction id node_id: node id Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_receive_flag( db=db, interaction_id=interaction_id, node_id=node_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def update_human_data(cls, db: Session, interaction_id: str, node_id: str, human_data: dict): """ update human data Args: db: db interaction_id: interaction id node_id: node id human_data: human data Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.update_human_data(db=db, interaction_id=interaction_id, node_id=node_id, human_data=human_data) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def insert_error(cls, db: Session, interaction_id: str, message: str, status: str = "failed"): """ insert error Args: db: db interaction_id: interaction id message: message status: status, default is failed Returns: raw XAgentRaw Raises: XAgentDBError: XAgent DB Error """ try: process = XAgentRaw( node_id=uuid.uuid4().hex, interaction_id=interaction_id, current="", step=0, data=message, file_list=[], status=status, do_interrupt=False, wait_seconds=0, ask_for_human_help=False, create_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"), update_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"), is_deleted=False, is_human=False, human_data={}, human_file_list=[], is_send=False, is_receive=False, include_pictures=False, ) InteractionDBInterface.insert_raw(db=db, process=process) return process except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def add_share(cls, db: Session, share): """ add share Args: db: db share: share Raises: XAgentDBError: XAgent DB Error """ try: InteractionDBInterface.add_share(db=db, shared=share) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_finish_status(cls, db: Session, interaction_id: str) -> bool: """ get finish status Args: db: db interaction_id: interaction id Returns: True if finish, else False """ try: return InteractionDBInterface.get_finish_status(db=db, interaction_id=interaction_id) except Exception as e: raise XAgentDBError(f"XAgent DB Error [Interact Module]: {str(e)}") from e def get_db(): """db""" session = SessionLocal() try: yield session session.commit() except Exception as e: session.rollback() raise e finally: session.close() class ResponseBody(BaseModel): """Response body """ data: Union[str, dict, list, Json, None] = None success: bool = True message: Union[str, None] = None def to_dict(self): """to dict """ return self.dict() def to_json(self): """to json """ return self.json() The provided code snippet includes necessary dependencies for implementing the `update_interaction_description` function. Write a Python function `async def update_interaction_description(user_id: str = Depends(user_is_available), description: str = Form(...), interaction_id: str = Form(...), db: Session = Depends(get_db) ) -> ResponseBody` to solve the following problem: update description Here is the function: async def update_interaction_description(user_id: str = Depends(user_is_available), description: str = Form(...), interaction_id: str = Form(...), db: Session = Depends(get_db) ) -> ResponseBody: """ update description """ if interaction_id == "": return ResponseBody(success=False, message="interaction_id is empty!") interaction = InteractionCRUD.get_interaction(db=db, interaction_id=interaction_id) if interaction is None: return ResponseBody(success=False, message=f"Don't find any interaction by interaction_id:\ {interaction_id}, Please check your interaction_id!") update_data = { "interaction_id": interaction_id, "description": description if description else "XAgent", } InteractionCRUD.update_interaction(db=db, base_data=update_data) return ResponseBody(data=update_data, success=True, message="success!")
update description
6,297
import smtplib import uuid from datetime import datetime from fastapi import APIRouter, Depends, Form, Query from sqlalchemy.orm import Session from XAgentServer.application.core.envs import XAgentServerEnv from XAgentServer.application.cruds.user import UserCRUD from XAgentServer.application.dependence import get_db from XAgentServer.application.schemas.response_body import ResponseBody from XAgentServer.exts.mail_ext import email_content class XAgentServerEnv: """ XAgentServer environment variables if you change value of the environment variable, you need to restart the XAgentServer by running the following command: `python start_server.py` or start a unicorn server by yourself """ app = "app:app" prod: bool = config.get("PROD", "False").lower() == "true" base_dir = "XAgentServer" use_redis: bool = False recorder_root_dir = "running_records" # you can set default_login with True, # use the default user "admin" with token "xagent-admin" to login, default_login: bool = True # only one XAgentServer can be set to check whether the interaction is running. check_running: bool = False host = "0.0.0.0" port = 8090 debug = True reload = True workers = 1 share_url = "https://x-agent.net/api/conv/community" class DB: """ database config """ use_db = True db_url = "mysql+pymysql://root:xagent@localhost:3306/xagent" class Redis: """ redis config """ use_redis = False redis_url = "redis://localhost" redis_host = "localhost" redis_port = 6379 redis_db = 0 redis_password = "xagent" # if you want to use email to send message, # you can set send_email to True and set # email_host, # email_port, # email_user, # email_password, # auth_server class Email: """ email config """ send_email = False email_host = "" email_port = 465 email_user = "" email_password = "" auth_server = "" # if you want to use upload function, # you can set upload_dir to the path of the upload directory # and set upload_allowed_types of the allowed types class Upload: """ upload config """ upload_dir = "XAgentServer/localstorage/upload" if not os.path.exists(upload_dir): os.makedirs(upload_dir) upload_allowed_types = ["image/png", "image/jpeg", "image/gif", "text/plain", "application/msword", "pdf", "txt", "pptx", "xlsx", "doc", "ppt", "xls", "zip", "rar", "tar", "gz", "7z", "bz2", "tgz", "tbz2", "tar.gz", "tar.bz2"] class UserCRUD(metaclass=abc.ABCMeta): """ User CRUD """ def get_user_list(cls, db: Session) -> list[XAgentUser]: """ get all users Args: db: database session """ try: return UserDBInterface.get_user_list(db=db) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def get_user(cls, db: Session, user_id: str | None = None, email: str | None = None) -> XAgentUser | None: """ get user by user_id or email Args: db: database session user_id: user_id email: email Returns: user """ try: return UserDBInterface.get_user(db=db, user_id=user_id, email=email) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def is_exist(cls, db: Session, user_id: str | None = None, email: str | None = None): """ check user is exist Args: db: database session user_id: user_id email: email Returns: bool """ try: return UserDBInterface.is_exist(db=db, user_id=user_id, email=email) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def token_is_exist(cls, db: Session, user_id: str, token: str | None = None): """ check token is exist Args: db: database session user_id: user_id token: token Returns: bool """ try: return UserDBInterface.token_is_exist(db=db, user_id=user_id, token=token) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def user_is_valid(cls, db: Session, user_id: str | None = None, email: str | None = None, token: str | None = None): """ check user is valid Args: db: database session user_id: user_id email: email token: token Returns: bool """ try: return UserDBInterface.user_is_valid(db=db, user_id=user_id, email=email, token=token) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def add_user(cls, db: Session, user_dict: dict): """ add user Args: db: database session user_dict: user dict Returns: None """ try: UserDBInterface.add_user(db=db, user_dict=user_dict) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def update_user(cls, db: Session, user: XAgentUser): """ update user Args: db: database session user: user Returns: None """ try: UserDBInterface.update_user(db=db, user=user) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def get_db(): """db""" session = SessionLocal() try: yield session session.commit() except Exception as e: session.rollback() raise e finally: session.close() class ResponseBody(BaseModel): """Response body """ data: Union[str, dict, list, Json, None] = None success: bool = True message: Union[str, None] = None def to_dict(self): """to dict """ return self.dict() def to_json(self): """to json """ return self.json() def email_content(user): html_body = f""" <body style="font-family: Arial, sans-serif;background-color: #f5f5f5;margin: 0; padding: 0;"> <div style="background-color: #ffffff;margin: 0 auto;padding: 20px;border-radius: 10px;box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);"> <h1 style="font-size: 28px;margin-bottom: 20px;">Hello {user['name']},</h1> <p style="font-size: 16px;line-height: 1.5;color: #333333;text-indent:2em;">Welcome to XAgent, your personal assistant! Thanks for signing up for XAgent. There are some information about your account:</p> <p style="font-size: 16px;line-height: 1.5;color: #333333;text-indent:2em;">Your XAgent Account: <b>{user["email"]}</b></p> <p style="font-size: 16px;line-height: 1.5;color: #333333;text-indent:2em;">You need to use this token for authentication on subsequent logins: </p> <p style="font-size: 16px;line-height: 1.5;color: #333333;text-indent:2em;">You need to use this token for authentication on subsequent logins: </p> <p style="font-size: 16px;line-height: 1.5;color: #333333;text-indent:2em;">Token: <b>{user["token"]}</b></p> <p style="font-size: 16px;line-height: 1.5;color: #333333;text-indent:2em;">Next is an activation link. You need to click on this link to activate your account. After that, you will be able to use XAgent happily:<a href="{XAgentServerEnv.Email.auth_server}/auth?user_id={user["user_id"]}&token={user["token"]}">{XAgentServerEnv.Email.auth_server}/auth?user_id={user["user_id"]}&token={user["token"]}</a>! This Verification link will expire in 7 days.</p> <p>If you have any questions, please contact us at yourxagent@gmail.com .</p> <p style="margin-top: 20px;font-size: 14px;color: #999999;text-indent:2em;">Best wishes!</p> <p style="margin-top: 20px;font-size: 14px;color: #999999;">XAgent Team</p> </div> </body>""" return html_body yag: yagmail.SMTP = None The provided code snippet includes necessary dependencies for implementing the `register` function. Write a Python function `async def register(email: str = Form(...), name: str = Form(...), corporation: str = Form(...), position: str = Form(...), industry: str = Form(...), db: Session = Depends(get_db)) -> ResponseBody` to solve the following problem: register user Here is the function: async def register(email: str = Form(...), name: str = Form(...), corporation: str = Form(...), position: str = Form(...), industry: str = Form(...), db: Session = Depends(get_db)) -> ResponseBody: """ register user """ if UserCRUD.is_exist(db=db, email=email): return ResponseBody(success=False, message="user is already exist") token = uuid.uuid4().hex user = {"user_id": uuid.uuid4().hex, "email": email, "name": name, "token": token, "available": False, "corporation": corporation, "position": position, "industry": industry, "create_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "update_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "is_beta": False} try: contents = email_content(user) if XAgentServerEnv.Email.send_email: from XAgentServer.application.global_val import yag yag.send(user["email"], 'XAgent Token Verification', contents) else: user["available"] = True UserCRUD.add_user(db=db, user_dict=user) except smtplib.SMTPAuthenticationError: return ResponseBody(success=False, message="email send failed!", data=None) except Exception: return ResponseBody(success=False, message="register failed", data=None) return ResponseBody(data=user, success=True, message="Register success, we will send a email to you!")
register user
6,298
import smtplib import uuid from datetime import datetime from fastapi import APIRouter, Depends, Form, Query from sqlalchemy.orm import Session from XAgentServer.application.core.envs import XAgentServerEnv from XAgentServer.application.cruds.user import UserCRUD from XAgentServer.application.dependence import get_db from XAgentServer.application.schemas.response_body import ResponseBody from XAgentServer.exts.mail_ext import email_content class UserCRUD(metaclass=abc.ABCMeta): """ User CRUD """ def get_user_list(cls, db: Session) -> list[XAgentUser]: """ get all users Args: db: database session """ try: return UserDBInterface.get_user_list(db=db) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def get_user(cls, db: Session, user_id: str | None = None, email: str | None = None) -> XAgentUser | None: """ get user by user_id or email Args: db: database session user_id: user_id email: email Returns: user """ try: return UserDBInterface.get_user(db=db, user_id=user_id, email=email) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def is_exist(cls, db: Session, user_id: str | None = None, email: str | None = None): """ check user is exist Args: db: database session user_id: user_id email: email Returns: bool """ try: return UserDBInterface.is_exist(db=db, user_id=user_id, email=email) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def token_is_exist(cls, db: Session, user_id: str, token: str | None = None): """ check token is exist Args: db: database session user_id: user_id token: token Returns: bool """ try: return UserDBInterface.token_is_exist(db=db, user_id=user_id, token=token) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def user_is_valid(cls, db: Session, user_id: str | None = None, email: str | None = None, token: str | None = None): """ check user is valid Args: db: database session user_id: user_id email: email token: token Returns: bool """ try: return UserDBInterface.user_is_valid(db=db, user_id=user_id, email=email, token=token) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def add_user(cls, db: Session, user_dict: dict): """ add user Args: db: database session user_dict: user dict Returns: None """ try: UserDBInterface.add_user(db=db, user_dict=user_dict) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def update_user(cls, db: Session, user: XAgentUser): """ update user Args: db: database session user: user Returns: None """ try: UserDBInterface.update_user(db=db, user=user) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def get_db(): """db""" session = SessionLocal() try: yield session session.commit() except Exception as e: session.rollback() raise e finally: session.close() class ResponseBody(BaseModel): """Response body """ data: Union[str, dict, list, Json, None] = None success: bool = True message: Union[str, None] = None def to_dict(self): """to dict """ return self.dict() def to_json(self): """to json """ return self.json() The provided code snippet includes necessary dependencies for implementing the `auth` function. Write a Python function `async def auth(user_id: str = Query(...), token: str = Query(...), db: Session = Depends(get_db) ) -> ResponseBody` to solve the following problem: user auth Here is the function: async def auth(user_id: str = Query(...), token: str = Query(...), db: Session = Depends(get_db) ) -> ResponseBody: """ user auth """ user = UserCRUD.get_user(db=db, user_id=user_id) if user is None: return ResponseBody(success=False, message="user is not exist") if user.token != token: return ResponseBody(success=False, message="token is not correct") expired_time = datetime.now() - datetime.strptime( user.update_time, "%Y-%m-%d %H:%M:%S") if expired_time.seconds > 60 * 60 * 24 * 7: return ResponseBody(success=False, message="token is expired") if not user.available: user.available = True user.update_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") UserCRUD.update_user(db=db, user=user) else: return ResponseBody(success=False, message="user is already available!") return ResponseBody(data=user.to_dict(), success=True, message="auth success")
user auth
6,299
import smtplib import uuid from datetime import datetime from fastapi import APIRouter, Depends, Form, Query from sqlalchemy.orm import Session from XAgentServer.application.core.envs import XAgentServerEnv from XAgentServer.application.cruds.user import UserCRUD from XAgentServer.application.dependence import get_db from XAgentServer.application.schemas.response_body import ResponseBody from XAgentServer.exts.mail_ext import email_content class UserCRUD(metaclass=abc.ABCMeta): """ User CRUD """ def get_user_list(cls, db: Session) -> list[XAgentUser]: """ get all users Args: db: database session """ try: return UserDBInterface.get_user_list(db=db) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def get_user(cls, db: Session, user_id: str | None = None, email: str | None = None) -> XAgentUser | None: """ get user by user_id or email Args: db: database session user_id: user_id email: email Returns: user """ try: return UserDBInterface.get_user(db=db, user_id=user_id, email=email) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def is_exist(cls, db: Session, user_id: str | None = None, email: str | None = None): """ check user is exist Args: db: database session user_id: user_id email: email Returns: bool """ try: return UserDBInterface.is_exist(db=db, user_id=user_id, email=email) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def token_is_exist(cls, db: Session, user_id: str, token: str | None = None): """ check token is exist Args: db: database session user_id: user_id token: token Returns: bool """ try: return UserDBInterface.token_is_exist(db=db, user_id=user_id, token=token) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def user_is_valid(cls, db: Session, user_id: str | None = None, email: str | None = None, token: str | None = None): """ check user is valid Args: db: database session user_id: user_id email: email token: token Returns: bool """ try: return UserDBInterface.user_is_valid(db=db, user_id=user_id, email=email, token=token) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def add_user(cls, db: Session, user_dict: dict): """ add user Args: db: database session user_dict: user dict Returns: None """ try: UserDBInterface.add_user(db=db, user_dict=user_dict) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def update_user(cls, db: Session, user: XAgentUser): """ update user Args: db: database session user: user Returns: None """ try: UserDBInterface.update_user(db=db, user=user) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def get_db(): """db""" session = SessionLocal() try: yield session session.commit() except Exception as e: session.rollback() raise e finally: session.close() class ResponseBody(BaseModel): """Response body """ data: Union[str, dict, list, Json, None] = None success: bool = True message: Union[str, None] = None def to_dict(self): """to dict """ return self.dict() def to_json(self): """to json """ return self.json() The provided code snippet includes necessary dependencies for implementing the `login` function. Write a Python function `async def login(email: str = Form(...), token: str = Form(...), db: Session = Depends(get_db)) -> ResponseBody` to solve the following problem: login Here is the function: async def login(email: str = Form(...), token: str = Form(...), db: Session = Depends(get_db)) -> ResponseBody: """ login """ user = UserCRUD.get_user(db=db, email=email) if user is None: return ResponseBody(success=False, message="user is not exist") if user.token != token: return ResponseBody(success=False, message="token is not correct") if not user.available: return ResponseBody(success=False, message="user is not available") return ResponseBody(data=user.to_dict(), success=True, message="login success")
login
6,300
import smtplib import uuid from datetime import datetime from fastapi import APIRouter, Depends, Form, Query from sqlalchemy.orm import Session from XAgentServer.application.core.envs import XAgentServerEnv from XAgentServer.application.cruds.user import UserCRUD from XAgentServer.application.dependence import get_db from XAgentServer.application.schemas.response_body import ResponseBody from XAgentServer.exts.mail_ext import email_content class UserCRUD(metaclass=abc.ABCMeta): """ User CRUD """ def get_user_list(cls, db: Session) -> list[XAgentUser]: """ get all users Args: db: database session """ try: return UserDBInterface.get_user_list(db=db) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def get_user(cls, db: Session, user_id: str | None = None, email: str | None = None) -> XAgentUser | None: """ get user by user_id or email Args: db: database session user_id: user_id email: email Returns: user """ try: return UserDBInterface.get_user(db=db, user_id=user_id, email=email) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def is_exist(cls, db: Session, user_id: str | None = None, email: str | None = None): """ check user is exist Args: db: database session user_id: user_id email: email Returns: bool """ try: return UserDBInterface.is_exist(db=db, user_id=user_id, email=email) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def token_is_exist(cls, db: Session, user_id: str, token: str | None = None): """ check token is exist Args: db: database session user_id: user_id token: token Returns: bool """ try: return UserDBInterface.token_is_exist(db=db, user_id=user_id, token=token) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def user_is_valid(cls, db: Session, user_id: str | None = None, email: str | None = None, token: str | None = None): """ check user is valid Args: db: database session user_id: user_id email: email token: token Returns: bool """ try: return UserDBInterface.user_is_valid(db=db, user_id=user_id, email=email, token=token) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def add_user(cls, db: Session, user_dict: dict): """ add user Args: db: database session user_dict: user dict Returns: None """ try: UserDBInterface.add_user(db=db, user_dict=user_dict) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def update_user(cls, db: Session, user: XAgentUser): """ update user Args: db: database session user: user Returns: None """ try: UserDBInterface.update_user(db=db, user=user) except Exception as e: raise XAgentDBError(f"XAgent DB Error [User Module]: {str(e)}") from e def get_db(): """db""" session = SessionLocal() try: yield session session.commit() except Exception as e: session.rollback() raise e finally: session.close() class ResponseBody(BaseModel): """Response body """ data: Union[str, dict, list, Json, None] = None success: bool = True message: Union[str, None] = None def to_dict(self): """to dict """ return self.dict() def to_json(self): """to json """ return self.json() The provided code snippet includes necessary dependencies for implementing the `check` function. Write a Python function `async def check(token: str = Form(...), db: Session = Depends(get_db)) -> ResponseBody` to solve the following problem: check token is effective Here is the function: async def check(token: str = Form(...), db: Session = Depends(get_db)) -> ResponseBody: """ check token is effective """ if token is None: return ResponseBody(success=False, message="token is none") result = UserCRUD.token_is_exist(db=db, token=token, user_id=None) if result: return ResponseBody(data=result, success=True, message="token is effective") return ResponseBody(data=result, success=True, message="token is invalid")
check token is effective
6,301
import base64 import json import os from typing import List import uuid from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile from fastapi.responses import FileResponse from sqlalchemy.orm import Session from XAgentServer.application.core.envs import XAgentServerEnv from XAgentServer.application.cruds.interaction import InteractionCRUD from XAgentServer.application.cruds.user import UserCRUD from XAgentServer.application.dependence import get_db from XAgentServer.application.schemas.response_body import ResponseBody def user_is_available( user_id: str = Form(...), token: str = Form(...), db: Session = Depends(get_db)): """ check user is available """ if user_id == "": raise HTTPException(status_code=401, detail="user_id is empty!") if not UserCRUD.is_exist(db=db, user_id=user_id): raise HTTPException(status_code=401, detail="user is not exist!") if not UserCRUD.user_is_valid(db=db, user_id=user_id, token=token): raise HTTPException( status_code=401, detail="user is not available!") return user_id async def file(user_id: str = Depends(user_is_available), interaction_id: str = Form(...), db: Session = Depends(get_db), file_name: str = Form(...)): """ get download file """ interaction = InteractionCRUD.get_interaction(db=db, interaction_id=interaction_id) if interaction is None: return ResponseBody(success=False, message="interaction is not exist!") time_str = interaction.create_time[:10] file_path = os.path.join( XAgentServerEnv.base_dir, "localstorage/interact_records", time_str, interaction_id, "workspace") if not os.path.exists(file_path): return ResponseBody(success=False, message="file is not exist!") file_suffix = file_name.split(".")[-1] if file_suffix in ["jpg", "png", "jpeg", "gif", "bmp"]: with open(os.path.join(file_path, file_name), "rb") as f: data = base64.b64encode(f.read()).decode("utf-8") return ResponseBody( data=f"data:image/{file_suffix};base64,{data}", success=True, message="get file success!" ) if file_suffix in ["mp4", "avi", "mkv", "rmvb", "rm", "flv", "3gp", "wmv"]: return FileResponse(os.path.join(file_path, file_name), media_type="video/" + file_suffix) if file_suffix in ["mp3", "wav", "wma", "ogg", "aac", "flac", "ape"]: return FileResponse(os.path.join(file_path, file_name), media_type="audio/" + file_suffix) if file_suffix in ["pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx"]: return FileResponse(os.path.join(file_path, file_name), media_type="application/" + file_suffix) if file_suffix in ["json"]: with open(os.path.join(file_path, file_name), 'r', encoding="utf-8") as f: data = json.load(f) return ResponseBody(data=json.dumps(data, ensure_ascii=False, indent=4), success=True, message="get file success!") if file_suffix in ["ipynb"]: return FileResponse(os.path.join(file_path, file_name), media_type="application/" + file_suffix) with open(os.path.join(file_path, file_name), 'r', encoding="utf-8") as f: data = f.read() return ResponseBody(data=data, success=True, message="get file success!") class XAgentServerEnv: """ XAgentServer environment variables if you change value of the environment variable, you need to restart the XAgentServer by running the following command: `python start_server.py` or start a unicorn server by yourself """ app = "app:app" prod: bool = config.get("PROD", "False").lower() == "true" base_dir = "XAgentServer" use_redis: bool = False recorder_root_dir = "running_records" # you can set default_login with True, # use the default user "admin" with token "xagent-admin" to login, default_login: bool = True # only one XAgentServer can be set to check whether the interaction is running. check_running: bool = False host = "0.0.0.0" port = 8090 debug = True reload = True workers = 1 share_url = "https://x-agent.net/api/conv/community" class DB: """ database config """ use_db = True db_url = "mysql+pymysql://root:xagent@localhost:3306/xagent" class Redis: """ redis config """ use_redis = False redis_url = "redis://localhost" redis_host = "localhost" redis_port = 6379 redis_db = 0 redis_password = "xagent" # if you want to use email to send message, # you can set send_email to True and set # email_host, # email_port, # email_user, # email_password, # auth_server class Email: """ email config """ send_email = False email_host = "" email_port = 465 email_user = "" email_password = "" auth_server = "" # if you want to use upload function, # you can set upload_dir to the path of the upload directory # and set upload_allowed_types of the allowed types class Upload: """ upload config """ upload_dir = "XAgentServer/localstorage/upload" if not os.path.exists(upload_dir): os.makedirs(upload_dir) upload_allowed_types = ["image/png", "image/jpeg", "image/gif", "text/plain", "application/msword", "pdf", "txt", "pptx", "xlsx", "doc", "ppt", "xls", "zip", "rar", "tar", "gz", "7z", "bz2", "tgz", "tbz2", "tar.gz", "tar.bz2"] class ResponseBody(BaseModel): """Response body """ data: Union[str, dict, list, Json, None] = None success: bool = True message: Union[str, None] = None def to_dict(self): """to dict """ return self.dict() def to_json(self): """to json """ return self.json() The provided code snippet includes necessary dependencies for implementing the `create_upload_files` function. Write a Python function `async def create_upload_files(files: List[UploadFile] = File(...), user_id: str = Depends(user_is_available)) -> ResponseBody` to solve the following problem: Upload Files Here is the function: async def create_upload_files(files: List[UploadFile] = File(...), user_id: str = Depends(user_is_available)) -> ResponseBody: """Upload Files""" if len(files) == 0: return ResponseBody(success=False, message="files is empty!") if len(files) > 5: files = files[:5] if not os.path.exists(os.path.join(XAgentServerEnv.Upload.upload_dir, user_id)): os.makedirs(os.path.join(XAgentServerEnv.Upload.upload_dir, user_id)) for f in files: if f.size > 1024 * 1024 * 1: return ResponseBody(success=False, message="file size is too large, limit is 1MB for each file!") file_list = [] for file in files: file_name = uuid.uuid4().hex + os.path.splitext(file.filename)[-1] with open(os.path.join(XAgentServerEnv.Upload.upload_dir, user_id, file_name), "wb") as f: f.write(await file.read()) file_list.append({"uuid": file_name, "name": file.filename}) return ResponseBody(data={"user_id": user_id, "file_list": file_list}, success=True, message="upload success")
Upload Files
6,302
import os from colorama import Fore from XAgentServer.application.core.envs import XAgentServerEnv from XAgentServer.application.global_val import (init_executor, init_yag) from XAgentServer.loggers.logs import Logger from XAgentServer.database.connect import SessionLocal class XAgentServerEnv: """ XAgentServer environment variables if you change value of the environment variable, you need to restart the XAgentServer by running the following command: `python start_server.py` or start a unicorn server by yourself """ app = "app:app" prod: bool = config.get("PROD", "False").lower() == "true" base_dir = "XAgentServer" use_redis: bool = False recorder_root_dir = "running_records" # you can set default_login with True, # use the default user "admin" with token "xagent-admin" to login, default_login: bool = True # only one XAgentServer can be set to check whether the interaction is running. check_running: bool = False host = "0.0.0.0" port = 8090 debug = True reload = True workers = 1 share_url = "https://x-agent.net/api/conv/community" class DB: """ database config """ use_db = True db_url = "mysql+pymysql://root:xagent@localhost:3306/xagent" class Redis: """ redis config """ use_redis = False redis_url = "redis://localhost" redis_host = "localhost" redis_port = 6379 redis_db = 0 redis_password = "xagent" # if you want to use email to send message, # you can set send_email to True and set # email_host, # email_port, # email_user, # email_password, # auth_server class Email: """ email config """ send_email = False email_host = "" email_port = 465 email_user = "" email_password = "" auth_server = "" # if you want to use upload function, # you can set upload_dir to the path of the upload directory # and set upload_allowed_types of the allowed types class Upload: """ upload config """ upload_dir = "XAgentServer/localstorage/upload" if not os.path.exists(upload_dir): os.makedirs(upload_dir) upload_allowed_types = ["image/png", "image/jpeg", "image/gif", "text/plain", "application/msword", "pdf", "txt", "pptx", "xlsx", "doc", "ppt", "xls", "zip", "rar", "tar", "gz", "7z", "bz2", "tgz", "tbz2", "tar.gz", "tar.bz2"] class Logger(metaclass=abc.ABCMeta): """ Logger that handle titles in different colors. Outputs logs in console, activity.log, and errors.log For console handler: simulates typing """ def __init__(self, log_dir: str = None, log_name: str= "", log_file: str = "activity.log", error_file: str = "errors.log"): """init""" if not os.path.exists(log_dir): os.makedirs(log_dir) # create log directory if it doesn't exist self.log_name = time.strftime("%Y-%m-%d", time.localtime()) if not log_name else log_name self.logger = logging.getLogger(self.log_name) console_formatter = RecordFormatter("%(title_color)s %(message)s") # Create a handler for console which simulate typing self.typing_console_handler = TypingConsoleHandler() self.typing_console_handler.setLevel(logging.INFO) self.typing_console_handler.setFormatter(console_formatter) # Create a handler for console without typing simulation self.console_handler = ConsoleHandler() self.console_handler.setLevel(logging.DEBUG) self.console_handler.setFormatter(console_formatter) self.speak_mode = False self.chat_plugins = [] # Info handler in activity.log self.file_handler = logging.FileHandler( os.path.join(log_dir, log_file), "a", "utf-8" ) self.file_handler.setLevel(logging.DEBUG) info_formatter = RecordFormatter( "%(asctime)s [%(threadName)s] %(levelname)s: %(title_color)s %(title)s %(message)s" ) self.file_handler.setFormatter(info_formatter) # Error handler error.log error_handler = logging.FileHandler( os.path.join(log_dir, error_file), "a", "utf-8" ) error_handler.setLevel(logging.ERROR) error_formatter = RecordFormatter( "%(asctime)s [%(threadName)s] %(levelname)s %(module)s:%(funcName)s:%(lineno)d %(title_color)s %(title)s" " %(message_no_color)s" ) error_handler.setFormatter(error_formatter) # self.typing_logger = logging.getLogger(self.log_name) # if not self.typing_logger.handlers: # self.typing_logger.addHandler(self.typing_console_handler) # self.typing_logger.addHandler(self.file_handler) # self.typing_logger.addHandler(error_handler) # self.typing_logger.setLevel(logging.DEBUG) if self.log_name.endswith("_INTERACT") or not self.logger.handlers: # self.logger.addHandler(self.typing_console_handler) self.logger.addHandler(self.console_handler) self.logger.addHandler(error_handler) self.logger.addHandler(self.file_handler) self.logger.setLevel(logging.DEBUG) def typewriter_log( self, title="", title_color="", content="", speak_text=False, level=logging.INFO ): # if speak_text and self.speak_mode: # say_text(f"{title}. {content}") for plugin in self.chat_plugins: plugin.report(f"{title}. {content}") if content: if isinstance(content, list): content = " ".join(content) else: content = "" self.logger.log( level, content, extra={"title": title, "color": title_color} ) def debug( self, message, title="", title_color="", ): self._log(title, title_color, message, logging.DEBUG) def info( self, message, title="", title_color="", ): self._log(title, title_color, message, logging.INFO) def warn( self, message, title="", title_color="", ): self._log(title, title_color, message, logging.WARN) def error(self, title, message=""): self._log(title, Fore.RED, message, logging.ERROR) def _log( self, title: str = "", title_color: str = "", message: str = "", level=logging.INFO, ): if message: if isinstance(message, list): message = " ".join(message) self.logger.log( level, message, extra={"title": str(title), "color": str(title_color)} ) def set_level(self, level): self.logger.setLevel(level) self.typing_logger.setLevel(level) def double_check(self, additionalText=None): if not additionalText: additionalText = ( "Please ensure you've setup and configured everything" " correctly. Read https://github.com/Torantulino/Auto-GPT#readme to " "double check. You can also create a github issue or join the discord" " and ask there!" ) self.typewriter_log("DOUBLE CHECK CONFIGURATION", Fore.YELLOW, additionalText) def log_json(self, data: Any, file_name: str) -> None: # Define log directory this_files_dir_path = os.path.dirname(__file__) log_dir = os.path.join(this_files_dir_path, "../logs") # Create a handler for JSON files json_file_path = os.path.join(log_dir, file_name) json_data_handler = JsonFileHandler(json_file_path) json_data_handler.setFormatter(JsonFormatter()) # Log the JSON data using the custom file handler self.json_logger.addHandler(json_data_handler) self.json_logger.debug(data) self.json_logger.removeHandler(json_data_handler) def get_log_directory(self): this_files_dir_path = os.path.dirname(__file__) log_dir = os.path.join(this_files_dir_path, "../logs") return os.path.abspath(log_dir) The provided code snippet includes necessary dependencies for implementing the `enable_logger` function. Write a Python function `def enable_logger()` to solve the following problem: logger Here is the function: def enable_logger(): """logger""" if not os.path.exists(os.path.join(XAgentServerEnv.base_dir, "logs")): os.makedirs(os.path.join( XAgentServerEnv.base_dir, "logs")) logger = Logger(log_dir=os.path.join( XAgentServerEnv.base_dir, "logs"), log_file="app.log", log_name="XAgentServerApp") return logger
logger
6,303
import abc import json import logging import os import random import re import time from logging import LogRecord from typing import Any from colorama import Fore, Style def remove_color_codes(s: str) -> str: ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])") return ansi_escape.sub("", s)
null
6,304
global_map = {} def add_to_map(key, value): global_map[key] = value
null
6,305
global_map = {} def lookup_in_map(key): return global_map.get(key)
null
6,306
import math import copy import os import warnings import torch import torch.utils.checkpoint import torch.nn.functional as F from torch import nn from torch.nn import CrossEntropyLoss, LayerNorm from torch.nn.utils import skip_init from typing import Optional, Tuple, Union, List, Callable from transformers.utils import ( add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, ) from transformers.modeling_outputs import ( BaseModelOutputWithPast, CausalLMOutputWithPast, BaseModelOutputWithPastAndCrossAttentions, ) from transformers.modeling_utils import PreTrainedModel from transformers.utils import logging from transformers.generation.logits_process import LogitsProcessor from transformers.generation.utils import LogitsProcessorList, StoppingCriteriaList, GenerationConfig from configuration_chatglm import ChatGLMConfig torch._C._jit_set_profiling_mode(False) torch._C._jit_set_profiling_executor(False) torch._C._jit_override_can_fuse_on_cpu(True) torch._C._jit_override_can_fuse_on_gpu(True) logger = logging.get_logger(__name__) The provided code snippet includes necessary dependencies for implementing the `load_tf_weights_in_chatglm_6b` function. Write a Python function `def load_tf_weights_in_chatglm_6b(model, config, tf_checkpoint_path)` to solve the following problem: Load tf checkpoints in a pytorch model. Here is the function: def load_tf_weights_in_chatglm_6b(model, config, tf_checkpoint_path): """Load tf checkpoints in a pytorch model.""" try: import re import numpy as np import tensorflow as tf except ImportError: logger.error( "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see " "https://www.tensorflow.org/install/ for installation instructions." ) raise tf_path = os.path.abspath(tf_checkpoint_path) logger.info(f"Converting TensorFlow checkpoint from {tf_path}") # Load weights from TF model init_vars = tf.train.list_variables(tf_path) names = [] arrays = [] for name, shape in init_vars: logger.info(f"Loading TF weight {name} with shape {shape}") array = tf.train.load_variable(tf_path, name) names.append(name) arrays.append(array) for name, array in zip(names, arrays): name = name.split("/") # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v # which are not required for using pretrained model if any( n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"] for n in name ): logger.info(f"Skipping {'/'.join(name)}") continue pointer = model for m_name in name: if re.fullmatch(r"[A-Za-z]+_\d+", m_name): scope_names = re.split(r"_(\d+)", m_name) else: scope_names = [m_name] if scope_names[0] == "kernel" or scope_names[0] == "gamma": pointer = getattr(pointer, "weight") elif scope_names[0] == "output_bias" or scope_names[0] == "beta": pointer = getattr(pointer, "bias") elif scope_names[0] == "output_weights": pointer = getattr(pointer, "weight") elif scope_names[0] == "squad": pointer = getattr(pointer, "classifier") else: try: pointer = getattr(pointer, scope_names[0]) except AttributeError: logger.info(f"Skipping {'/'.join(name)}") continue if len(scope_names) >= 2: num = int(scope_names[1]) pointer = pointer[num] if m_name[-11:] == "_embeddings": pointer = getattr(pointer, "weight") elif m_name == "kernel": array = np.transpose(array) try: assert ( pointer.shape == array.shape ), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched" except AssertionError as e: e.args += (pointer.shape, array.shape) raise logger.info(f"Initialize PyTorch weight {name}") pointer.data = torch.from_numpy(array) return model
Load tf checkpoints in a pytorch model.
6,307
import math import copy import os import warnings import torch import torch.utils.checkpoint import torch.nn.functional as F from torch import nn from torch.nn import CrossEntropyLoss, LayerNorm from torch.nn.utils import skip_init from typing import Optional, Tuple, Union, List, Callable from transformers.utils import ( add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, ) from transformers.modeling_outputs import ( BaseModelOutputWithPast, CausalLMOutputWithPast, BaseModelOutputWithPastAndCrossAttentions, ) from transformers.modeling_utils import PreTrainedModel from transformers.utils import logging from transformers.generation.logits_process import LogitsProcessor from transformers.generation.utils import LogitsProcessorList, StoppingCriteriaList, GenerationConfig from configuration_chatglm import ChatGLMConfig def gelu_impl(x): """OpenAI's gelu implementation.""" return 0.5 * x * (1.0 + torch.tanh(0.7978845608028654 * x * (1.0 + 0.044715 * x * x))) def gelu(x): return gelu_impl(x)
null
6,308
import math import copy import os import warnings import torch import torch.utils.checkpoint import torch.nn.functional as F from torch import nn from torch.nn import CrossEntropyLoss, LayerNorm from torch.nn.utils import skip_init from typing import Optional, Tuple, Union, List, Callable from transformers.utils import ( add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, ) from transformers.modeling_outputs import ( BaseModelOutputWithPast, CausalLMOutputWithPast, BaseModelOutputWithPastAndCrossAttentions, ) from transformers.modeling_utils import PreTrainedModel from transformers.utils import logging from transformers.generation.logits_process import LogitsProcessor from transformers.generation.utils import LogitsProcessorList, StoppingCriteriaList, GenerationConfig from configuration_chatglm import ChatGLMConfig def rotate_half(x): x1, x2 = x[..., :x.shape[-1] // 2], x[..., x.shape[-1] // 2:] return torch.cat((-x2, x1), dim=x1.ndim - 1) # dim=-1 triggers a bug in earlier torch versions def apply_rotary_pos_emb_index(q, k, cos, sin, position_id): # position_id: [sq, b], q, k: [sq, b, np, hn], cos: [sq, 1, hn] -> [sq, b, 1, hn] cos, sin = F.embedding(position_id, cos.squeeze(1)).unsqueeze(2), \ F.embedding(position_id, sin.squeeze(1)).unsqueeze(2) q, k = (q * cos) + (rotate_half(q) * sin), (k * cos) + (rotate_half(k) * sin) return q, k
null
6,309
import math import copy import os import warnings import torch import torch.utils.checkpoint import torch.nn.functional as F from torch import nn from torch.nn import CrossEntropyLoss, LayerNorm from torch.nn.utils import skip_init from typing import Optional, Tuple, Union, List, Callable from transformers.utils import ( add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, ) from transformers.modeling_outputs import ( BaseModelOutputWithPast, CausalLMOutputWithPast, BaseModelOutputWithPastAndCrossAttentions, ) from transformers.modeling_utils import PreTrainedModel from transformers.utils import logging from transformers.generation.logits_process import LogitsProcessor from transformers.generation.utils import LogitsProcessorList, StoppingCriteriaList, GenerationConfig from configuration_chatglm import ChatGLMConfig torch._C._jit_set_profiling_mode(False) torch._C._jit_set_profiling_executor(False) torch._C._jit_override_can_fuse_on_cpu(True) torch._C._jit_override_can_fuse_on_gpu(True) def attention_fn( self, query_layer, key_layer, value_layer, attention_mask, hidden_size_per_partition, layer_id, layer_past=None, scaling_attention_score=True, use_cache=False, ): if layer_past is not None: past_key, past_value = layer_past key_layer = torch.cat((past_key, key_layer), dim=0) value_layer = torch.cat((past_value, value_layer), dim=0) # seqlen, batch, num_attention_heads, hidden_size_per_attention_head seq_len, b, nh, hidden_size = key_layer.shape if use_cache: present = (key_layer, value_layer) else: present = None query_key_layer_scaling_coeff = float(layer_id + 1) if scaling_attention_score: query_layer = query_layer / (math.sqrt(hidden_size) * query_key_layer_scaling_coeff) # =================================== # Raw attention scores. [b, np, s, s] # =================================== # [b, np, sq, sk] output_size = (query_layer.size(1), query_layer.size(2), query_layer.size(0), key_layer.size(0)) # [sq, b, np, hn] -> [sq, b * np, hn] query_layer = query_layer.view(output_size[2], output_size[0] * output_size[1], -1) # [sk, b, np, hn] -> [sk, b * np, hn] key_layer = key_layer.view(output_size[3], output_size[0] * output_size[1], -1) matmul_result = torch.empty( output_size[0] * output_size[1], output_size[2], output_size[3], dtype=query_layer.dtype, device=query_layer.device, ) matmul_result = torch.baddbmm( matmul_result, query_layer.transpose(0, 1), # [b * np, sq, hn] key_layer.transpose(0, 1).transpose(1, 2), # [b * np, hn, sk] beta=0.0, alpha=1.0, ) # change view to [b, np, sq, sk] attention_scores = matmul_result.view(*output_size) if self.scale_mask_softmax: self.scale_mask_softmax.scale = query_key_layer_scaling_coeff attention_probs = self.scale_mask_softmax(attention_scores, attention_mask.contiguous()) else: if not (attention_mask == 0).all(): # if auto-regressive, skip attention_scores.masked_fill_(attention_mask, -10000.0) dtype = attention_scores.type() attention_scores = attention_scores.float() attention_scores = attention_scores * query_key_layer_scaling_coeff attention_probs = F.softmax(attention_scores, dim=-1) attention_probs = attention_probs.type(dtype) # ========================= # Context layer. [sq, b, hp] # ========================= # value_layer -> context layer. # [sk, b, np, hn] --> [b, np, sq, hn] # context layer shape: [b, np, sq, hn] output_size = (value_layer.size(1), value_layer.size(2), query_layer.size(0), value_layer.size(3)) # change view [sk, b * np, hn] value_layer = value_layer.view(value_layer.size(0), output_size[0] * output_size[1], -1) # change view [b * np, sq, sk] attention_probs = attention_probs.view(output_size[0] * output_size[1], output_size[2], -1) # matmul: [b * np, sq, hn] context_layer = torch.bmm(attention_probs, value_layer.transpose(0, 1)) # change view [b, np, sq, hn] context_layer = context_layer.view(*output_size) # [b, np, sq, hn] --> [sq, b, np, hn] context_layer = context_layer.permute(2, 0, 1, 3).contiguous() # [sq, b, np, hn] --> [sq, b, hp] new_context_layer_shape = context_layer.size()[:-2] + (hidden_size_per_partition,) context_layer = context_layer.view(*new_context_layer_shape) outputs = (context_layer, present, attention_probs) return outputs
null
6,310
import logging import math import os import sys from dataclasses import dataclass, field from itertools import chain from typing import Optional import datasets import evaluate import torch from datasets import load_dataset from typing import Dict import transformers from transformers import ( CONFIG_MAPPING, MODEL_FOR_CAUSAL_LM_MAPPING, AutoConfig, AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, is_torch_tpu_available, set_seed, ) from transformers.testing_utils import CaptureLogger from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version from transformers import TrainerCallback, TrainerControl, TrainingArguments, TrainerState from modeling_chatglm import ChatGLMForConditionalGeneration from chat_dataset import chat_data_collator, Chat_Dataset def main(): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: model_args, data_args, training_args = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("run_clm", model_args, data_args) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", handlers=[logging.StreamHandler(sys.stdout)], ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() log_level = training_args.get_process_log_level() logger.setLevel(log_level) datasets.utils.logging.set_verbosity(log_level) transformers.utils.logging.set_verbosity(log_level) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}" + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}" ) logger.info(f"Training/evaluation parameters {training_args}") # Detecting last checkpoint. last_checkpoint = None if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir: last_checkpoint = get_last_checkpoint(training_args.output_dir) if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0: raise ValueError( f"Output directory ({training_args.output_dir}) already exists and is not empty. " "Use --overwrite_output_dir to overcome." ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Set seed before initializing model. set_seed(training_args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. raw_datasets = load_dataset( data_args.dataset_name, data_args.dataset_config_name, cache_dir=model_args.cache_dir, use_auth_token=True if model_args.use_auth_token else None, streaming=data_args.streaming, ) if "validation" not in raw_datasets.keys(): raw_datasets["validation"] = load_dataset( data_args.dataset_name, data_args.dataset_config_name, split=f"train[:{data_args.validation_split_percentage}%]", cache_dir=model_args.cache_dir, use_auth_token=True if model_args.use_auth_token else None, streaming=data_args.streaming, ) raw_datasets["train"] = load_dataset( data_args.dataset_name, data_args.dataset_config_name, split=f"train[{data_args.validation_split_percentage}%:]", cache_dir=model_args.cache_dir, use_auth_token=True if model_args.use_auth_token else None, streaming=data_args.streaming, ) lm_datasets = raw_datasets else: data_files = {} dataset_args = {} lm_datasets = {} if data_args.train_file is not None: data_files["train"] = data_args.train_file train_dataset = Chat_Dataset(data_files["train"],data_args.max_seq_length) lm_datasets["train"] = train_dataset if data_args.validation_file is not None: data_files["validation"] = data_args.validation_file valid_dataset = Chat_Dataset(data_files["validation"],data_args.max_seq_length) lm_datasets["validation"] = valid_dataset # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. config_kwargs = { "cache_dir": model_args.cache_dir, "revision": model_args.model_revision, "use_auth_token": True if model_args.use_auth_token else None, } if model_args.config_name: config = AutoConfig.from_pretrained(model_args.config_name, trust_remote_code=True, **config_kwargs) elif model_args.model_name_or_path: config = AutoConfig.from_pretrained(model_args.model_name_or_path,trust_remote_code=True, **config_kwargs) else: config = CONFIG_MAPPING[model_args.model_type]() logger.warning("You are instantiating a new config instance from scratch.") if model_args.config_overrides is not None: logger.info(f"Overriding config: {model_args.config_overrides}") config.update_from_string(model_args.config_overrides) logger.info(f"New config: {config}") tokenizer_kwargs = { "cache_dir": model_args.cache_dir, "use_fast": model_args.use_fast_tokenizer, "revision": model_args.model_revision, "use_auth_token": True if model_args.use_auth_token else None, } if model_args.tokenizer_name: tokenizer = AutoTokenizer.from_pretrained(model_args.tokenizer_name,trust_remote_code=True,**tokenizer_kwargs) elif model_args.model_name_or_path: tokenizer = AutoTokenizer.from_pretrained(model_args.model_name_or_path, trust_remote_code=True,**tokenizer_kwargs) else: raise ValueError( "You are instantiating a new tokenizer from scratch. This is not supported by this script." "You can do it from another script, save it, and load it from here, using --tokenizer_name." ) if model_args.model_name_or_path: torch_dtype = ( model_args.torch_dtype if model_args.torch_dtype in ["auto", None] else getattr(torch, model_args.torch_dtype) ) model = ChatGLMForConditionalGeneration.from_pretrained( model_args.model_name_or_path, from_tf=bool(".ckpt" in model_args.model_name_or_path), config=config, cache_dir=model_args.cache_dir, revision=model_args.model_revision, use_auth_token=True if model_args.use_auth_token else None, torch_dtype=torch_dtype, low_cpu_mem_usage=model_args.low_cpu_mem_usage, trust_remote_code=True, ) # model = ChatGLMForConditionalGeneration.from_pretrained( # "THUDM/chatglm-6b", load_in_8bit=True, trust_remote_code=True, device_map="auto" # ) else: model = ChatGLMForConditionalGeneration.from_config(config) n_params = sum({p.data_ptr(): p.numel() for p in model.parameters()}.values()) logger.info(f"Training new model from scratch - Total size={n_params/2**20:.2f}M params") model.gradient_checkpointing_enable() model.enable_input_require_grads() model.is_parallelizable = False model.model_parallel = False # model.lm_head = CastOutputToFloat(model.lm_head) model.config.use_cache = ( False # silence the warnings. Please re-enable for inference! ) # We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch # on a small vocab and want a smaller embedding size, remove this test. embedding_size = model.get_input_embeddings().weight.shape[0] if len(tokenizer) > embedding_size: model.resize_token_embeddings(len(tokenizer)) # since this will be pickled to avoid _LazyModule error in Hasher force logger loading before tokenize_function tok_logger = transformers.utils.logging.get_logger("transformers.tokenization_utils_base") if data_args.max_seq_length is None: max_seq_length = tokenizer.model_max_length/2 else: if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( f"The block_size passed ({data_args.block_size}) is larger than the maximum length for the model" f"({tokenizer.model_max_length}). Using block_size={tokenizer.model_max_length}." ) block_size = min(data_args.max_seq_length, tokenizer.model_max_length/2) if training_args.do_train: if "train" not in lm_datasets: raise ValueError("--do_train requires a train dataset") train_dataset = lm_datasets["train"] if data_args.max_train_samples is not None: max_train_samples = min(len(train_dataset), data_args.max_train_samples) train_dataset = train_dataset.select(range(max_train_samples)) if training_args.do_eval: if "validation" not in lm_datasets: raise ValueError("--do_eval requires a validation dataset") eval_dataset = lm_datasets["validation"] if data_args.max_eval_samples is not None: max_eval_samples = min(len(eval_dataset), data_args.max_eval_samples) eval_dataset = eval_dataset.select(range(max_eval_samples)) def preprocess_logits_for_metrics(logits, labels): if isinstance(logits, tuple): # Depending on the model and config, logits may contain extra tensors, # like past_key_values, but logits always come first logits = logits[0] return logits.argmax(dim=-1) metric = evaluate.load("accuracy") def compute_metrics(eval_preds): preds, labels = eval_preds # preds have the same shape as the labels, after the argmax(-1) has been calculated # by preprocess_logits_for_metrics but we need to shift the labels labels = labels[:, 1:].reshape(-1) preds = preds[:, :-1].reshape(-1) return metric.compute(predictions=preds, references=labels) # Initialize our Trainer trainer = Trainer( model=model, args=training_args, train_dataset=train_dataset if training_args.do_train else None, eval_dataset=eval_dataset if training_args.do_eval else None, tokenizer=tokenizer, # Data collator will default to DataCollatorWithPadding, so we change it. data_collator=chat_data_collator, compute_metrics=compute_metrics if training_args.do_eval and not is_torch_tpu_available() else None, preprocess_logits_for_metrics=preprocess_logits_for_metrics if training_args.do_eval and not is_torch_tpu_available() else None, callbacks=[LoggingLossCallback(log_interval=10, log_file=data_args.log_file)], ) # Training if training_args.do_train: checkpoint = None if training_args.resume_from_checkpoint is not None: checkpoint = training_args.resume_from_checkpoint elif last_checkpoint is not None: checkpoint = last_checkpoint train_result = trainer.train(resume_from_checkpoint=checkpoint) trainer.save_model() # Saves the tokenizer too for easy upload metrics = train_result.metrics max_train_samples = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset) ) metrics["train_samples"] = min(max_train_samples, len(train_dataset)) trainer.log_metrics("train", metrics) trainer.save_metrics("train", metrics) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("*** Evaluate ***") metrics = trainer.evaluate() max_eval_samples = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(eval_dataset) metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset)) try: perplexity = math.exp(metrics["eval_loss"]) except OverflowError: perplexity = float("inf") metrics["perplexity"] = perplexity trainer.log_metrics("eval", metrics) trainer.save_metrics("eval", metrics) kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "text-generation"} if data_args.dataset_name is not None: kwargs["dataset_tags"] = data_args.dataset_name if data_args.dataset_config_name is not None: kwargs["dataset_args"] = data_args.dataset_config_name kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}" else: kwargs["dataset"] = data_args.dataset_name if training_args.push_to_hub: trainer.push_to_hub(**kwargs) else: trainer.create_model_card(**kwargs) def _mp_fn(index): # For xla_spawn (TPUs) main()
null
6,311
import json import torch from torch.utils.data import Dataset from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained( "THUDM/chatglm-6b", trust_remote_code=True) def get_masks_and_position_ids( seq, seq_len, context_length, device, gmask=False, position_encoding_2d=True ): def chat_data_collator(features: list) -> dict: # 只对target的部分计算loss len_ids = [len(feature["input_ids"]) for feature in features] longest = max(len_ids) + 1 input_ids = [] attention_mask_list = [] position_ids_list = [] labels_list = [] for ids_l, feature in sorted(zip(len_ids, features), key=lambda x: -x[0]): ids = feature["input_ids"] seq_len = feature["seq_len"] labels = ( [-100] * (seq_len - 1) + ids[(seq_len - 1):] + [tokenizer.eos_token_id] + [-100] * (longest - ids_l - 1) ) ids = ids + [tokenizer.eos_token_id] * (longest - ids_l) _ids = torch.LongTensor(ids) attention_mask, position_ids = get_masks_and_position_ids( ids, seq_len, longest, _ids.device, gmask=False ) labels_list.append(torch.LongTensor(labels)) input_ids.append(_ids) attention_mask_list.append(attention_mask) position_ids_list.append(position_ids) input_ids = torch.stack(input_ids) labels = torch.stack(labels_list) attention_mask = torch.stack(attention_mask_list) position_ids = torch.stack(position_ids_list) return { "input_ids": input_ids, "labels": labels, "attention_mask": attention_mask, "position_ids": position_ids, }
null
6,312
import random import numpy as np import torch.utils.data as data from PIL import Image import torchvision.transforms as transforms from abc import ABC, abstractmethod def get_params(opt, size): w, h = size new_h = h new_w = w if opt.preprocess == 'resize_and_crop': new_h = new_w = opt.load_size elif opt.preprocess == 'scale_width_and_crop': new_w = opt.load_size new_h = opt.load_size * h // w x = random.randint(0, np.maximum(0, new_w - opt.crop_size)) y = random.randint(0, np.maximum(0, new_h - opt.crop_size)) flip = random.random() > 0.5 return {'crop_pos': (x, y), 'flip': flip}
null
6,313
import random import numpy as np import torch.utils.data as data from PIL import Image import torchvision.transforms as transforms from abc import ABC, abstractmethod def __make_power_2(img, base, method=Image.BICUBIC): def __scale_width(img, target_size, crop_size, method=Image.BICUBIC): def __crop(img, pos, size): def __flip(img, flip): def get_transform(opt, params=None, grayscale=False, method=Image.BICUBIC, convert=True): transform_list = [] if grayscale: transform_list.append(transforms.Grayscale(1)) if 'resize' in opt.preprocess: osize = [opt.load_size, opt.load_size] transform_list.append(transforms.Resize(osize, method)) elif 'scale_width' in opt.preprocess: transform_list.append(transforms.Lambda(lambda img: __scale_width(img, opt.load_size, opt.crop_size, method))) if 'crop' in opt.preprocess: if params is None: transform_list.append(transforms.RandomCrop(opt.crop_size)) else: transform_list.append(transforms.Lambda(lambda img: __crop(img, params['crop_pos'], opt.crop_size))) if opt.preprocess == 'none': transform_list.append(transforms.Lambda(lambda img: __make_power_2(img, base=4, method=method))) if not opt.no_flip: if params is None: transform_list.append(transforms.RandomHorizontalFlip()) elif params['flip']: transform_list.append(transforms.Lambda(lambda img: __flip(img, params['flip']))) if convert: transform_list += [transforms.ToTensor()] if grayscale: transform_list += [transforms.Normalize((0.5,), (0.5,))] else: transform_list += [transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))] return transforms.Compose(transform_list)
null
6,314
import torch.utils.data as data from PIL import Image import os def is_image_file(filename): return any(filename.endswith(extension) for extension in IMG_EXTENSIONS) def make_dataset(dir, max_dataset_size=float("inf")): images = [] assert os.path.isdir(dir), '%s is not a valid directory' % dir for root, _, fnames in sorted(os.walk(dir)): for fname in fnames: if is_image_file(fname): path = os.path.join(root, fname) images.append(path) return images[:min(max_dataset_size, len(images))]
null
6,315
import torch.utils.data as data from PIL import Image import os def default_loader(path): return Image.open(path).convert('RGB')
null
6,316
from pix2pix.data.base_dataset import BaseDataset from pix2pix.data.image_folder import make_dataset from pix2pix.util.guidedfilter import GuidedFilter import numpy as np import os import torch from PIL import Image def normalize(img): img = img * 2 img = img - 1 return img
null
6,317
from pix2pix.data.base_dataset import BaseDataset from pix2pix.data.image_folder import make_dataset from pix2pix.util.guidedfilter import GuidedFilter import numpy as np import os import torch from PIL import Image def normalize01(img): return (img - torch.min(img)) / (torch.max(img)-torch.min(img))
null
6,318
import torch import torch.nn as nn from torch.nn import init import functools from torch.optim import lr_scheduler The provided code snippet includes necessary dependencies for implementing the `get_scheduler` function. Write a Python function `def get_scheduler(optimizer, opt)` to solve the following problem: Return a learning rate scheduler Parameters: optimizer -- the optimizer of the network opt (option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions. opt.lr_policy is the name of learning rate policy: linear | step | plateau | cosine For 'linear', we keep the same learning rate for the first <opt.n_epochs> epochs and linearly decay the rate to zero over the next <opt.n_epochs_decay> epochs. For other schedulers (step, plateau, and cosine), we use the default PyTorch schedulers. See https://pytorch.org/docs/stable/optim.html for more details. Here is the function: def get_scheduler(optimizer, opt): """Return a learning rate scheduler Parameters: optimizer -- the optimizer of the network opt (option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions.  opt.lr_policy is the name of learning rate policy: linear | step | plateau | cosine For 'linear', we keep the same learning rate for the first <opt.n_epochs> epochs and linearly decay the rate to zero over the next <opt.n_epochs_decay> epochs. For other schedulers (step, plateau, and cosine), we use the default PyTorch schedulers. See https://pytorch.org/docs/stable/optim.html for more details. """ if opt.lr_policy == 'linear': def lambda_rule(epoch): lr_l = 1.0 - max(0, epoch + opt.epoch_count - opt.n_epochs) / float(opt.n_epochs_decay + 1) return lr_l scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule) elif opt.lr_policy == 'step': scheduler = lr_scheduler.StepLR(optimizer, step_size=opt.lr_decay_iters, gamma=0.1) elif opt.lr_policy == 'plateau': scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.2, threshold=0.01, patience=5) elif opt.lr_policy == 'cosine': scheduler = lr_scheduler.CosineAnnealingLR(optimizer, T_max=opt.n_epochs, eta_min=0) else: return NotImplementedError('learning rate policy [%s] is not implemented', opt.lr_policy) return scheduler
Return a learning rate scheduler Parameters: optimizer -- the optimizer of the network opt (option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions. opt.lr_policy is the name of learning rate policy: linear | step | plateau | cosine For 'linear', we keep the same learning rate for the first <opt.n_epochs> epochs and linearly decay the rate to zero over the next <opt.n_epochs_decay> epochs. For other schedulers (step, plateau, and cosine), we use the default PyTorch schedulers. See https://pytorch.org/docs/stable/optim.html for more details.
6,319
import torch import torch.nn as nn from torch.nn import init import functools from torch.optim import lr_scheduler def get_norm_layer(norm_type='instance'): """Return a normalization layer Parameters: norm_type (str) -- the name of the normalization layer: batch | instance | none For BatchNorm, we use learnable affine parameters and track running statistics (mean/stddev). For InstanceNorm, we do not use learnable affine parameters. We do not track running statistics. """ if norm_type == 'batch': norm_layer = functools.partial(nn.BatchNorm2d, affine=True, track_running_stats=True) elif norm_type == 'instance': norm_layer = functools.partial(nn.InstanceNorm2d, affine=False, track_running_stats=False) elif norm_type == 'none': def norm_layer(x): return Identity() else: raise NotImplementedError('normalization layer [%s] is not found' % norm_type) return norm_layer def init_net(net, init_type='normal', init_gain=0.02, gpu_ids=[]): """Initialize a network: 1. register CPU/GPU device (with multi-GPU support); 2. initialize the network weights Parameters: net (network) -- the network to be initialized init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal gain (float) -- scaling factor for normal, xavier and orthogonal. gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2 Return an initialized network. """ if len(gpu_ids) > 0: assert(torch.cuda.is_available()) net.to(gpu_ids[0]) net = torch.nn.DataParallel(net, gpu_ids) # multi-GPUs init_weights(net, init_type, init_gain=init_gain) return net class ResnetGenerator(nn.Module): """Resnet-based generator that consists of Resnet blocks between a few downsampling/upsampling operations. We adapt Torch code and idea from Justin Johnson's neural style transfer project(https://github.com/jcjohnson/fast-neural-style) """ def __init__(self, input_nc, output_nc, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False, n_blocks=6, padding_type='reflect'): """Construct a Resnet-based generator Parameters: input_nc (int) -- the number of channels in input images output_nc (int) -- the number of channels in output images ngf (int) -- the number of filters in the last conv layer norm_layer -- normalization layer use_dropout (bool) -- if use dropout layers n_blocks (int) -- the number of ResNet blocks padding_type (str) -- the name of padding layer in conv layers: reflect | replicate | zero """ assert(n_blocks >= 0) super(ResnetGenerator, self).__init__() if type(norm_layer) == functools.partial: use_bias = norm_layer.func == nn.InstanceNorm2d else: use_bias = norm_layer == nn.InstanceNorm2d model = [nn.ReflectionPad2d(3), nn.Conv2d(input_nc, ngf, kernel_size=7, padding=0, bias=use_bias), norm_layer(ngf), nn.ReLU(True)] n_downsampling = 2 for i in range(n_downsampling): # add downsampling layers mult = 2 ** i model += [nn.Conv2d(ngf * mult, ngf * mult * 2, kernel_size=3, stride=2, padding=1, bias=use_bias), norm_layer(ngf * mult * 2), nn.ReLU(True)] mult = 2 ** n_downsampling for i in range(n_blocks): # add ResNet blocks model += [ResnetBlock(ngf * mult, padding_type=padding_type, norm_layer=norm_layer, use_dropout=use_dropout, use_bias=use_bias)] for i in range(n_downsampling): # add upsampling layers mult = 2 ** (n_downsampling - i) model += [nn.ConvTranspose2d(ngf * mult, int(ngf * mult / 2), kernel_size=3, stride=2, padding=1, output_padding=1, bias=use_bias), norm_layer(int(ngf * mult / 2)), nn.ReLU(True)] model += [nn.ReflectionPad2d(3)] model += [nn.Conv2d(ngf, output_nc, kernel_size=7, padding=0)] model += [nn.Tanh()] self.model = nn.Sequential(*model) def forward(self, input): """Standard forward""" return self.model(input) class UnetGenerator(nn.Module): """Create a Unet-based generator""" def __init__(self, input_nc, output_nc, num_downs, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False): """Construct a Unet generator Parameters: input_nc (int) -- the number of channels in input images output_nc (int) -- the number of channels in output images num_downs (int) -- the number of downsamplings in UNet. For example, # if |num_downs| == 7, image of size 128x128 will become of size 1x1 # at the bottleneck ngf (int) -- the number of filters in the last conv layer norm_layer -- normalization layer We construct the U-Net from the innermost layer to the outermost layer. It is a recursive process. """ super(UnetGenerator, self).__init__() # construct unet structure unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer, innermost=True) # add the innermost layer for i in range(num_downs - 5): # add intermediate layers with ngf * 8 filters unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer, use_dropout=use_dropout) # gradually reduce the number of filters from ngf * 8 to ngf unet_block = UnetSkipConnectionBlock(ngf * 4, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer) unet_block = UnetSkipConnectionBlock(ngf * 2, ngf * 4, input_nc=None, submodule=unet_block, norm_layer=norm_layer) unet_block = UnetSkipConnectionBlock(ngf, ngf * 2, input_nc=None, submodule=unet_block, norm_layer=norm_layer) self.model = UnetSkipConnectionBlock(output_nc, ngf, input_nc=input_nc, submodule=unet_block, outermost=True, norm_layer=norm_layer) # add the outermost layer def forward(self, input): """Standard forward""" return self.model(input) The provided code snippet includes necessary dependencies for implementing the `define_G` function. Write a Python function `def define_G(input_nc, output_nc, ngf, netG, norm='batch', use_dropout=False, init_type='normal', init_gain=0.02, gpu_ids=[])` to solve the following problem: Create a generator Parameters: input_nc (int) -- the number of channels in input images output_nc (int) -- the number of channels in output images ngf (int) -- the number of filters in the last conv layer netG (str) -- the architecture's name: resnet_9blocks | resnet_6blocks | unet_256 | unet_128 norm (str) -- the name of normalization layers used in the network: batch | instance | none use_dropout (bool) -- if use dropout layers. init_type (str) -- the name of our initialization method. init_gain (float) -- scaling factor for normal, xavier and orthogonal. gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2 Returns a generator Our current implementation provides two types of generators: U-Net: [unet_128] (for 128x128 input images) and [unet_256] (for 256x256 input images) The original U-Net paper: https://arxiv.org/abs/1505.04597 Resnet-based generator: [resnet_6blocks] (with 6 Resnet blocks) and [resnet_9blocks] (with 9 Resnet blocks) Resnet-based generator consists of several Resnet blocks between a few downsampling/upsampling operations. We adapt Torch code from Justin Johnson's neural style transfer project (https://github.com/jcjohnson/fast-neural-style). The generator has been initialized by <init_net>. It uses RELU for non-linearity. Here is the function: def define_G(input_nc, output_nc, ngf, netG, norm='batch', use_dropout=False, init_type='normal', init_gain=0.02, gpu_ids=[]): """Create a generator Parameters: input_nc (int) -- the number of channels in input images output_nc (int) -- the number of channels in output images ngf (int) -- the number of filters in the last conv layer netG (str) -- the architecture's name: resnet_9blocks | resnet_6blocks | unet_256 | unet_128 norm (str) -- the name of normalization layers used in the network: batch | instance | none use_dropout (bool) -- if use dropout layers. init_type (str) -- the name of our initialization method. init_gain (float) -- scaling factor for normal, xavier and orthogonal. gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2 Returns a generator Our current implementation provides two types of generators: U-Net: [unet_128] (for 128x128 input images) and [unet_256] (for 256x256 input images) The original U-Net paper: https://arxiv.org/abs/1505.04597 Resnet-based generator: [resnet_6blocks] (with 6 Resnet blocks) and [resnet_9blocks] (with 9 Resnet blocks) Resnet-based generator consists of several Resnet blocks between a few downsampling/upsampling operations. We adapt Torch code from Justin Johnson's neural style transfer project (https://github.com/jcjohnson/fast-neural-style). The generator has been initialized by <init_net>. It uses RELU for non-linearity. """ net = None norm_layer = get_norm_layer(norm_type=norm) if netG == 'resnet_9blocks': net = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=9) elif netG == 'resnet_6blocks': net = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=6) elif netG == 'resnet_12blocks': net = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=12) elif netG == 'unet_128': net = UnetGenerator(input_nc, output_nc, 7, ngf, norm_layer=norm_layer, use_dropout=use_dropout) elif netG == 'unet_256': net = UnetGenerator(input_nc, output_nc, 8, ngf, norm_layer=norm_layer, use_dropout=use_dropout) elif netG == 'unet_672': net = UnetGenerator(input_nc, output_nc, 5, ngf, norm_layer=norm_layer, use_dropout=use_dropout) elif netG == 'unet_960': net = UnetGenerator(input_nc, output_nc, 6, ngf, norm_layer=norm_layer, use_dropout=use_dropout) elif netG == 'unet_1024': net = UnetGenerator(input_nc, output_nc, 10, ngf, norm_layer=norm_layer, use_dropout=use_dropout) else: raise NotImplementedError('Generator model name [%s] is not recognized' % netG) return init_net(net, init_type, init_gain, gpu_ids)
Create a generator Parameters: input_nc (int) -- the number of channels in input images output_nc (int) -- the number of channels in output images ngf (int) -- the number of filters in the last conv layer netG (str) -- the architecture's name: resnet_9blocks | resnet_6blocks | unet_256 | unet_128 norm (str) -- the name of normalization layers used in the network: batch | instance | none use_dropout (bool) -- if use dropout layers. init_type (str) -- the name of our initialization method. init_gain (float) -- scaling factor for normal, xavier and orthogonal. gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2 Returns a generator Our current implementation provides two types of generators: U-Net: [unet_128] (for 128x128 input images) and [unet_256] (for 256x256 input images) The original U-Net paper: https://arxiv.org/abs/1505.04597 Resnet-based generator: [resnet_6blocks] (with 6 Resnet blocks) and [resnet_9blocks] (with 9 Resnet blocks) Resnet-based generator consists of several Resnet blocks between a few downsampling/upsampling operations. We adapt Torch code from Justin Johnson's neural style transfer project (https://github.com/jcjohnson/fast-neural-style). The generator has been initialized by <init_net>. It uses RELU for non-linearity.
6,320
import torch import torch.nn as nn from torch.nn import init import functools from torch.optim import lr_scheduler def get_norm_layer(norm_type='instance'): """Return a normalization layer Parameters: norm_type (str) -- the name of the normalization layer: batch | instance | none For BatchNorm, we use learnable affine parameters and track running statistics (mean/stddev). For InstanceNorm, we do not use learnable affine parameters. We do not track running statistics. """ if norm_type == 'batch': norm_layer = functools.partial(nn.BatchNorm2d, affine=True, track_running_stats=True) elif norm_type == 'instance': norm_layer = functools.partial(nn.InstanceNorm2d, affine=False, track_running_stats=False) elif norm_type == 'none': def norm_layer(x): return Identity() else: raise NotImplementedError('normalization layer [%s] is not found' % norm_type) return norm_layer def init_net(net, init_type='normal', init_gain=0.02, gpu_ids=[]): """Initialize a network: 1. register CPU/GPU device (with multi-GPU support); 2. initialize the network weights Parameters: net (network) -- the network to be initialized init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal gain (float) -- scaling factor for normal, xavier and orthogonal. gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2 Return an initialized network. """ if len(gpu_ids) > 0: assert(torch.cuda.is_available()) net.to(gpu_ids[0]) net = torch.nn.DataParallel(net, gpu_ids) # multi-GPUs init_weights(net, init_type, init_gain=init_gain) return net class NLayerDiscriminator(nn.Module): """Defines a PatchGAN discriminator""" def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d): """Construct a PatchGAN discriminator Parameters: input_nc (int) -- the number of channels in input images ndf (int) -- the number of filters in the last conv layer n_layers (int) -- the number of conv layers in the discriminator norm_layer -- normalization layer """ super(NLayerDiscriminator, self).__init__() if type(norm_layer) == functools.partial: # no need to use bias as BatchNorm2d has affine parameters use_bias = norm_layer.func == nn.InstanceNorm2d else: use_bias = norm_layer == nn.InstanceNorm2d kw = 4 padw = 1 sequence = [nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), nn.LeakyReLU(0.2, True)] nf_mult = 1 nf_mult_prev = 1 for n in range(1, n_layers): # gradually increase the number of filters nf_mult_prev = nf_mult nf_mult = min(2 ** n, 8) sequence += [ nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=2, padding=padw, bias=use_bias), norm_layer(ndf * nf_mult), nn.LeakyReLU(0.2, True) ] nf_mult_prev = nf_mult nf_mult = min(2 ** n_layers, 8) sequence += [ nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=1, padding=padw, bias=use_bias), norm_layer(ndf * nf_mult), nn.LeakyReLU(0.2, True) ] sequence += [nn.Conv2d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw)] # output 1 channel prediction map self.model = nn.Sequential(*sequence) def forward(self, input): """Standard forward.""" return self.model(input) class PixelDiscriminator(nn.Module): """Defines a 1x1 PatchGAN discriminator (pixelGAN)""" def __init__(self, input_nc, ndf=64, norm_layer=nn.BatchNorm2d): """Construct a 1x1 PatchGAN discriminator Parameters: input_nc (int) -- the number of channels in input images ndf (int) -- the number of filters in the last conv layer norm_layer -- normalization layer """ super(PixelDiscriminator, self).__init__() if type(norm_layer) == functools.partial: # no need to use bias as BatchNorm2d has affine parameters use_bias = norm_layer.func == nn.InstanceNorm2d else: use_bias = norm_layer == nn.InstanceNorm2d self.net = [ nn.Conv2d(input_nc, ndf, kernel_size=1, stride=1, padding=0), nn.LeakyReLU(0.2, True), nn.Conv2d(ndf, ndf * 2, kernel_size=1, stride=1, padding=0, bias=use_bias), norm_layer(ndf * 2), nn.LeakyReLU(0.2, True), nn.Conv2d(ndf * 2, 1, kernel_size=1, stride=1, padding=0, bias=use_bias)] self.net = nn.Sequential(*self.net) def forward(self, input): """Standard forward.""" return self.net(input) The provided code snippet includes necessary dependencies for implementing the `define_D` function. Write a Python function `def define_D(input_nc, ndf, netD, n_layers_D=3, norm='batch', init_type='normal', init_gain=0.02, gpu_ids=[])` to solve the following problem: Create a discriminator Parameters: input_nc (int) -- the number of channels in input images ndf (int) -- the number of filters in the first conv layer netD (str) -- the architecture's name: basic | n_layers | pixel n_layers_D (int) -- the number of conv layers in the discriminator; effective when netD=='n_layers' norm (str) -- the type of normalization layers used in the network. init_type (str) -- the name of the initialization method. init_gain (float) -- scaling factor for normal, xavier and orthogonal. gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2 Returns a discriminator Our current implementation provides three types of discriminators: [basic]: 'PatchGAN' classifier described in the original pix2pix paper. It can classify whether 70×70 overlapping patches are real or fake. Such a patch-level discriminator architecture has fewer parameters than a full-image discriminator and can work on arbitrarily-sized images in a fully convolutional fashion. [n_layers]: With this mode, you can specify the number of conv layers in the discriminator with the parameter <n_layers_D> (default=3 as used in [basic] (PatchGAN).) [pixel]: 1x1 PixelGAN discriminator can classify whether a pixel is real or not. It encourages greater color diversity but has no effect on spatial statistics. The discriminator has been initialized by <init_net>. It uses Leakly RELU for non-linearity. Here is the function: def define_D(input_nc, ndf, netD, n_layers_D=3, norm='batch', init_type='normal', init_gain=0.02, gpu_ids=[]): """Create a discriminator Parameters: input_nc (int) -- the number of channels in input images ndf (int) -- the number of filters in the first conv layer netD (str) -- the architecture's name: basic | n_layers | pixel n_layers_D (int) -- the number of conv layers in the discriminator; effective when netD=='n_layers' norm (str) -- the type of normalization layers used in the network. init_type (str) -- the name of the initialization method. init_gain (float) -- scaling factor for normal, xavier and orthogonal. gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2 Returns a discriminator Our current implementation provides three types of discriminators: [basic]: 'PatchGAN' classifier described in the original pix2pix paper. It can classify whether 70×70 overlapping patches are real or fake. Such a patch-level discriminator architecture has fewer parameters than a full-image discriminator and can work on arbitrarily-sized images in a fully convolutional fashion. [n_layers]: With this mode, you can specify the number of conv layers in the discriminator with the parameter <n_layers_D> (default=3 as used in [basic] (PatchGAN).) [pixel]: 1x1 PixelGAN discriminator can classify whether a pixel is real or not. It encourages greater color diversity but has no effect on spatial statistics. The discriminator has been initialized by <init_net>. It uses Leakly RELU for non-linearity. """ net = None norm_layer = get_norm_layer(norm_type=norm) if netD == 'basic': # default PatchGAN classifier net = NLayerDiscriminator(input_nc, ndf, n_layers=3, norm_layer=norm_layer) elif netD == 'n_layers': # more options net = NLayerDiscriminator(input_nc, ndf, n_layers_D, norm_layer=norm_layer) elif netD == 'pixel': # classify if each pixel is real or fake net = PixelDiscriminator(input_nc, ndf, norm_layer=norm_layer) else: raise NotImplementedError('Discriminator model name [%s] is not recognized' % netD) return init_net(net, init_type, init_gain, gpu_ids)
Create a discriminator Parameters: input_nc (int) -- the number of channels in input images ndf (int) -- the number of filters in the first conv layer netD (str) -- the architecture's name: basic | n_layers | pixel n_layers_D (int) -- the number of conv layers in the discriminator; effective when netD=='n_layers' norm (str) -- the type of normalization layers used in the network. init_type (str) -- the name of the initialization method. init_gain (float) -- scaling factor for normal, xavier and orthogonal. gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2 Returns a discriminator Our current implementation provides three types of discriminators: [basic]: 'PatchGAN' classifier described in the original pix2pix paper. It can classify whether 70×70 overlapping patches are real or fake. Such a patch-level discriminator architecture has fewer parameters than a full-image discriminator and can work on arbitrarily-sized images in a fully convolutional fashion. [n_layers]: With this mode, you can specify the number of conv layers in the discriminator with the parameter <n_layers_D> (default=3 as used in [basic] (PatchGAN).) [pixel]: 1x1 PixelGAN discriminator can classify whether a pixel is real or not. It encourages greater color diversity but has no effect on spatial statistics. The discriminator has been initialized by <init_net>. It uses Leakly RELU for non-linearity.
6,321
import torch import torch.nn as nn from torch.nn import init import functools from torch.optim import lr_scheduler The provided code snippet includes necessary dependencies for implementing the `cal_gradient_penalty` function. Write a Python function `def cal_gradient_penalty(netD, real_data, fake_data, device, type='mixed', constant=1.0, lambda_gp=10.0)` to solve the following problem: Calculate the gradient penalty loss, used in WGAN-GP paper https://arxiv.org/abs/1704.00028 Arguments: netD (network) -- discriminator network real_data (tensor array) -- real images fake_data (tensor array) -- generated images from the generator device (str) -- GPU / CPU: from torch.device('cuda:{}'.format(self.gpu_ids[0])) if self.gpu_ids else torch.device('cpu') type (str) -- if we mix real and fake data or not [real | fake | mixed]. constant (float) -- the constant used in formula ( ||gradient||_2 - constant)^2 lambda_gp (float) -- weight for this loss Returns the gradient penalty loss Here is the function: def cal_gradient_penalty(netD, real_data, fake_data, device, type='mixed', constant=1.0, lambda_gp=10.0): """Calculate the gradient penalty loss, used in WGAN-GP paper https://arxiv.org/abs/1704.00028 Arguments: netD (network) -- discriminator network real_data (tensor array) -- real images fake_data (tensor array) -- generated images from the generator device (str) -- GPU / CPU: from torch.device('cuda:{}'.format(self.gpu_ids[0])) if self.gpu_ids else torch.device('cpu') type (str) -- if we mix real and fake data or not [real | fake | mixed]. constant (float) -- the constant used in formula ( ||gradient||_2 - constant)^2 lambda_gp (float) -- weight for this loss Returns the gradient penalty loss """ if lambda_gp > 0.0: if type == 'real': # either use real images, fake images, or a linear interpolation of two. interpolatesv = real_data elif type == 'fake': interpolatesv = fake_data elif type == 'mixed': alpha = torch.rand(real_data.shape[0], 1, device=device) alpha = alpha.expand(real_data.shape[0], real_data.nelement() // real_data.shape[0]).contiguous().view(*real_data.shape) interpolatesv = alpha * real_data + ((1 - alpha) * fake_data) else: raise NotImplementedError('{} not implemented'.format(type)) interpolatesv.requires_grad_(True) disc_interpolates = netD(interpolatesv) gradients = torch.autograd.grad(outputs=disc_interpolates, inputs=interpolatesv, grad_outputs=torch.ones(disc_interpolates.size()).to(device), create_graph=True, retain_graph=True, only_inputs=True) gradients = gradients[0].view(real_data.size(0), -1) # flat the data gradient_penalty = (((gradients + 1e-16).norm(2, dim=1) - constant) ** 2).mean() * lambda_gp # added eps return gradient_penalty, gradients else: return 0.0, None
Calculate the gradient penalty loss, used in WGAN-GP paper https://arxiv.org/abs/1704.00028 Arguments: netD (network) -- discriminator network real_data (tensor array) -- real images fake_data (tensor array) -- generated images from the generator device (str) -- GPU / CPU: from torch.device('cuda:{}'.format(self.gpu_ids[0])) if self.gpu_ids else torch.device('cpu') type (str) -- if we mix real and fake data or not [real | fake | mixed]. constant (float) -- the constant used in formula ( ||gradient||_2 - constant)^2 lambda_gp (float) -- weight for this loss Returns the gradient penalty loss
6,322
from __future__ import print_function import torch import numpy as np from PIL import Image import os The provided code snippet includes necessary dependencies for implementing the `diagnose_network` function. Write a Python function `def diagnose_network(net, name='network')` to solve the following problem: Calculate and print the mean of average absolute(gradients) Parameters: net (torch network) -- Torch network name (str) -- the name of the network Here is the function: def diagnose_network(net, name='network'): """Calculate and print the mean of average absolute(gradients) Parameters: net (torch network) -- Torch network name (str) -- the name of the network """ mean = 0.0 count = 0 for param in net.parameters(): if param.grad is not None: mean += torch.mean(torch.abs(param.grad.data)) count += 1 if count > 0: mean = mean / count print(name) print(mean)
Calculate and print the mean of average absolute(gradients) Parameters: net (torch network) -- Torch network name (str) -- the name of the network
6,323
from __future__ import print_function import torch import numpy as np from PIL import Image import os The provided code snippet includes necessary dependencies for implementing the `print_numpy` function. Write a Python function `def print_numpy(x, val=True, shp=False)` to solve the following problem: Print the mean, min, max, median, std, and size of a numpy array Parameters: val (bool) -- if print the values of the numpy array shp (bool) -- if print the shape of the numpy array Here is the function: def print_numpy(x, val=True, shp=False): """Print the mean, min, max, median, std, and size of a numpy array Parameters: val (bool) -- if print the values of the numpy array shp (bool) -- if print the shape of the numpy array """ x = x.astype(np.float64) if shp: print('shape,', x.shape) if val: x = x.flatten() print('mean = %3.3f, min = %3.3f, max = %3.3f, median = %3.3f, std=%3.3f' % ( np.mean(x), np.min(x), np.max(x), np.median(x), np.std(x)))
Print the mean, min, max, median, std, and size of a numpy array Parameters: val (bool) -- if print the values of the numpy array shp (bool) -- if print the shape of the numpy array
6,324
from __future__ import print_function import torch import numpy as np from PIL import Image import os def mkdir(path): """create a single empty directory if it didn't exist Parameters: path (str) -- a single directory path """ if not os.path.exists(path): os.makedirs(path) The provided code snippet includes necessary dependencies for implementing the `mkdirs` function. Write a Python function `def mkdirs(paths)` to solve the following problem: create empty directories if they don't exist Parameters: paths (str list) -- a list of directory paths Here is the function: def mkdirs(paths): """create empty directories if they don't exist Parameters: paths (str list) -- a list of directory paths """ if isinstance(paths, list) and not isinstance(paths, str): for path in paths: mkdir(path) else: mkdir(paths)
create empty directories if they don't exist Parameters: paths (str list) -- a list of directory paths
6,325
import numpy as np import os import sys import ntpath import time from . import util, html from subprocess import Popen, PIPE import torch The provided code snippet includes necessary dependencies for implementing the `save_images` function. Write a Python function `def save_images(webpage, visuals, image_path, aspect_ratio=1.0, width=256)` to solve the following problem: Save images to the disk. Parameters: webpage (the HTML class) -- the HTML webpage class that stores these imaegs (see html.py for more details) visuals (OrderedDict) -- an ordered dictionary that stores (name, images (either tensor or numpy) ) pairs image_path (str) -- the string is used to create image paths aspect_ratio (float) -- the aspect ratio of saved images width (int) -- the images will be resized to width x width This function will save images stored in 'visuals' to the HTML file specified by 'webpage'. Here is the function: def save_images(webpage, visuals, image_path, aspect_ratio=1.0, width=256): """Save images to the disk. Parameters: webpage (the HTML class) -- the HTML webpage class that stores these imaegs (see html.py for more details) visuals (OrderedDict) -- an ordered dictionary that stores (name, images (either tensor or numpy) ) pairs image_path (str) -- the string is used to create image paths aspect_ratio (float) -- the aspect ratio of saved images width (int) -- the images will be resized to width x width This function will save images stored in 'visuals' to the HTML file specified by 'webpage'. """ image_dir = webpage.get_image_dir() short_path = ntpath.basename(image_path[0]) name = os.path.splitext(short_path)[0] webpage.add_header(name) ims, txts, links = [], [], [] for label, im_data in visuals.items(): im = util.tensor2im(im_data) image_name = '%s_%s.png' % (name, label) save_path = os.path.join(image_dir, image_name) util.save_image(im, save_path, aspect_ratio=aspect_ratio) ims.append(image_name) txts.append(label) links.append(image_name) webpage.add_images(ims, txts, links, width=width)
Save images to the disk. Parameters: webpage (the HTML class) -- the HTML webpage class that stores these imaegs (see html.py for more details) visuals (OrderedDict) -- an ordered dictionary that stores (name, images (either tensor or numpy) ) pairs image_path (str) -- the string is used to create image paths aspect_ratio (float) -- the aspect ratio of saved images width (int) -- the images will be resized to width x width This function will save images stored in 'visuals' to the HTML file specified by 'webpage'.
6,326
import os import cv2 import glob import numpy as np import imageio from MiDaS.MiDaS_utils import write_depth BOOST_BASE = 'BoostingMonocularDepth' BOOST_INPUTS = 'inputs' BOOST_OUTPUTS = 'outputs' def clean_folder(folder, img_exts=['.png', '.jpg', '.npy']): def resize_depth(depth, width, height): def run_boostmonodepth(img_names, src_folder, depth_folder): if not isinstance(img_names, list): img_names = [img_names] # remove irrelevant files first clean_folder(os.path.join(BOOST_BASE, BOOST_INPUTS)) clean_folder(os.path.join(BOOST_BASE, BOOST_OUTPUTS)) tgt_names = [] for img_name in img_names: base_name = os.path.basename(img_name) tgt_name = os.path.join(BOOST_BASE, BOOST_INPUTS, base_name) os.system(f'cp {img_name} {tgt_name}') # keep only the file name here. # they save all depth as .png file tgt_names.append(os.path.basename(tgt_name).replace('.jpg', '.png')) os.system(f'cd {BOOST_BASE} && python run.py --Final --data_dir {BOOST_INPUTS}/ --output_dir {BOOST_OUTPUTS} --depthNet 0') for i, (img_name, tgt_name) in enumerate(zip(img_names, tgt_names)): img = imageio.imread(img_name) H, W = img.shape[:2] scale = 640. / max(H, W) # resize and save depth target_height, target_width = int(round(H * scale)), int(round(W * scale)) depth = imageio.imread(os.path.join(BOOST_BASE, BOOST_OUTPUTS, tgt_name)) depth = np.array(depth).astype(np.float32) depth = resize_depth(depth, target_width, target_height) np.save(os.path.join(depth_folder, tgt_name.replace('.png', '.npy')), depth / 32768. - 1.) write_depth(os.path.join(depth_folder, tgt_name.replace('.png', '')), depth)
null
6,327
import os import glob import cv2 import scipy.misc as misc from skimage.transform import resize import numpy as np from functools import reduce from operator import mul import torch from torch import nn import matplotlib.pyplot as plt import re from scipy.ndimage import gaussian_filter from skimage.feature import canny import collections import shutil import imageio import copy from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D import time from scipy.interpolate import interp1d from collections import namedtuple def clean_far_edge(mask_edge, mask_edge_with_id, context_edge, mask, info_on_pix, global_mesh, anchor): if isinstance(mask_edge, torch.Tensor): if mask_edge.is_cuda: mask_edge = mask_edge.cpu() mask_edge = mask_edge.data mask_edge = mask_edge.numpy() if isinstance(context_edge, torch.Tensor): if context_edge.is_cuda: context_edge = context_edge.cpu() context_edge = context_edge.data context_edge = context_edge.numpy() if isinstance(mask, torch.Tensor): if mask.is_cuda: mask = mask.cpu() mask = mask.data mask = mask.numpy() mask = mask.squeeze() mask_edge = mask_edge.squeeze() context_edge = context_edge.squeeze() valid_near_edge = np.zeros_like(mask_edge) far_edge = np.zeros_like(mask_edge) far_edge_with_id = np.ones_like(mask_edge) * -1 near_edge_with_id = np.ones_like(mask_edge) * -1 uncleaned_far_edge = np.zeros_like(mask_edge) # Detect if there is any valid pixel mask_edge, if not ==> return default value if mask_edge.sum() == 0: return far_edge, uncleaned_far_edge, far_edge_with_id, near_edge_with_id mask_edge_ids = dict(collections.Counter(mask_edge_with_id.flatten())).keys() for edge_id in mask_edge_ids: if edge_id < 0: continue specific_edge_map = (mask_edge_with_id == edge_id).astype(np.uint8) _, sub_specific_edge_maps = cv2.connectedComponents(specific_edge_map.astype(np.uint8), connectivity=8) for sub_edge_id in range(1, sub_specific_edge_maps.max() + 1): specific_edge_map = (sub_specific_edge_maps == sub_edge_id).astype(np.uint8) edge_pxs, edge_pys = np.where(specific_edge_map > 0) edge_mesh = netx.Graph() for edge_px, edge_py in zip(edge_pxs, edge_pys): edge_mesh.add_node((edge_px, edge_py)) for ex in [edge_px-1, edge_px, edge_px+1]: for ey in [edge_py-1, edge_py, edge_py+1]: if edge_px == ex and edge_py == ey: continue if ex < 0 or ex >= specific_edge_map.shape[0] or ey < 0 or ey >= specific_edge_map.shape[1]: continue if specific_edge_map[ex, ey] == 1: if edge_mesh.has_node((ex, ey)): edge_mesh.add_edge((ex, ey), (edge_px, edge_py)) periphery_nodes = netx.periphery(edge_mesh) path_diameter = netx.diameter(edge_mesh) start_near_node = None for node_s in periphery_nodes: for node_e in periphery_nodes: if node_s != node_e: if netx.shortest_path_length(edge_mesh, node_s, node_e) == path_diameter: if np.any(context_edge[node_s[0]-1:node_s[0]+2, node_s[1]-1:node_s[1]+2].flatten()): start_near_node = (node_s[0], node_s[1]) end_near_node = (node_e[0], node_e[1]) break if np.any(context_edge[node_e[0]-1:node_e[0]+2, node_e[1]-1:node_e[1]+2].flatten()): start_near_node = (node_e[0], node_e[1]) end_near_node = (node_s[0], node_s[1]) break if start_near_node is not None: break if start_near_node is None: continue new_specific_edge_map = np.zeros_like(mask) for path_node in netx.shortest_path(edge_mesh, start_near_node, end_near_node): new_specific_edge_map[path_node[0], path_node[1]] = 1 context_near_pxs, context_near_pys = np.where(context_edge[start_near_node[0]-1:start_near_node[0]+2, start_near_node[1]-1:start_near_node[1]+2] > 0) distance = np.abs((context_near_pxs - 1)) + np.abs((context_near_pys - 1)) if (np.where(distance == distance.min())[0].shape[0]) > 1: closest_pxs = context_near_pxs[np.where(distance == distance.min())[0]] closest_pys = context_near_pys[np.where(distance == distance.min())[0]] closest_depths = [] for closest_px, closest_py in zip(closest_pxs, closest_pys): if info_on_pix.get((closest_px + start_near_node[0] - 1 + anchor[0], closest_py + start_near_node[1] - 1 + anchor[2])) is not None: for info in info_on_pix.get((closest_px + start_near_node[0] - 1 + anchor[0], closest_py + start_near_node[1] - 1 + anchor[2])): if info['synthesis'] is False: closest_depths.append(abs(info['depth'])) context_near_px, context_near_py = closest_pxs[np.array(closest_depths).argmax()], closest_pys[np.array(closest_depths).argmax()] else: context_near_px, context_near_py = context_near_pxs[distance.argmin()], context_near_pys[distance.argmin()] context_near_node = (start_near_node[0]-1 + context_near_px, start_near_node[1]-1 + context_near_py) far_node_list = [] global_context_near_node = (context_near_node[0] + anchor[0], context_near_node[1] + anchor[2]) if info_on_pix.get(global_context_near_node) is not None: for info in info_on_pix[global_context_near_node]: if info['synthesis'] is False: context_near_node_3d = (global_context_near_node[0], global_context_near_node[1], info['depth']) if global_mesh.nodes[context_near_node_3d].get('far') is not None: for far_node in global_mesh.nodes[context_near_node_3d].get('far'): far_node = (far_node[0] - anchor[0], far_node[1] - anchor[2], far_node[2]) if mask[far_node[0], far_node[1]] == 0: far_node_list.append([far_node[0], far_node[1]]) if len(far_node_list) > 0: far_nodes_dist = np.sum(np.abs(np.array(far_node_list) - np.array([[edge_px, edge_py]])), axis=1) context_far_node = tuple(far_node_list[far_nodes_dist.argmin()]) corresponding_far_edge = np.zeros_like(mask_edge) corresponding_far_edge[context_far_node[0], context_far_node[1]] = 1 surround_map = cv2.dilate(new_specific_edge_map.astype(np.uint8), np.array([[1,1,1],[1,1,1],[1,1,1]]).astype(np.uint8), iterations=1) specific_edge_map_wo_end_pt = new_specific_edge_map.copy() specific_edge_map_wo_end_pt[end_near_node[0], end_near_node[1]] = 0 surround_map_wo_end_pt = cv2.dilate(specific_edge_map_wo_end_pt.astype(np.uint8), np.array([[1,1,1],[1,1,1],[1,1,1]]).astype(np.uint8), iterations=1) surround_map_wo_end_pt[new_specific_edge_map > 0] = 0 surround_map_wo_end_pt[context_near_node[0], context_near_node[1]] = 0 surround_map = surround_map_wo_end_pt.copy() _, far_edge_cc = cv2.connectedComponents(surround_map.astype(np.uint8), connectivity=4) start_far_node = None accompany_far_node = None if surround_map[context_far_node[0], context_far_node[1]] == 1: start_far_node = context_far_node else: four_nes = [(context_far_node[0] - 1, context_far_node[1]), (context_far_node[0] + 1, context_far_node[1]), (context_far_node[0], context_far_node[1] - 1), (context_far_node[0], context_far_node[1] + 1)] candidate_bevel = [] for ne in four_nes: if surround_map[ne[0], ne[1]] == 1: start_far_node = (ne[0], ne[1]) break elif (ne[0] != context_near_node[0] or ne[1] != context_near_node[1]) and \ (ne[0] != start_near_node[0] or ne[1] != start_near_node[1]): candidate_bevel.append((ne[0], ne[1])) if start_far_node is None: for ne in candidate_bevel: if ne[0] == context_far_node[0]: bevel_xys = [[ne[0] + 1, ne[1]], [ne[0] - 1, ne[1]]] if ne[1] == context_far_node[1]: bevel_xys = [[ne[0], ne[1] + 1], [ne[0], ne[1] - 1]] for bevel_x, bevel_y in bevel_xys: if surround_map[bevel_x, bevel_y] == 1: start_far_node = (bevel_x, bevel_y) accompany_far_node = (ne[0], ne[1]) break if start_far_node is not None: break if start_far_node is not None: for far_edge_id in range(1, far_edge_cc.max() + 1): specific_far_edge = (far_edge_cc == far_edge_id).astype(np.uint8) if specific_far_edge[start_far_node[0], start_far_node[1]] == 1: if accompany_far_node is not None: specific_far_edge[accompany_far_node] = 1 far_edge[specific_far_edge > 0] = 1 far_edge_with_id[specific_far_edge > 0] = edge_id end_far_candidates = np.zeros_like(far_edge) end_far_candidates[end_near_node[0], end_near_node[1]] = 1 end_far_candidates = cv2.dilate(end_far_candidates.astype(np.uint8), np.array([[0,1,0],[1,1,1],[0,1,0]]).astype(np.uint8), iterations=1) end_far_candidates[end_near_node[0], end_near_node[1]] = 0 invalid_nodes = (((far_edge_cc != far_edge_id).astype(np.uint8) * \ (far_edge_cc != 0).astype(np.uint8)).astype(np.uint8) + \ (new_specific_edge_map).astype(np.uint8) + \ (mask == 0).astype(np.uint8)).clip(0, 1) end_far_candidates[invalid_nodes > 0] = 0 far_edge[end_far_candidates > 0] = 1 far_edge_with_id[end_far_candidates > 0] = edge_id far_edge[context_far_node[0], context_far_node[1]] = 1 far_edge_with_id[context_far_node[0], context_far_node[1]] = edge_id near_edge_with_id[(mask_edge_with_id == edge_id) > 0] = edge_id uncleaned_far_edge = far_edge.copy() far_edge[mask == 0] = 0 return far_edge, uncleaned_far_edge, far_edge_with_id, near_edge_with_id
null