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 ...
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...
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...
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 ra...
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 res...
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 t...
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 t...
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 throug...
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. Yo...
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...
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_man...
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 dictionarie...
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. ...
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 impor...
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 r...
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 impor...
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 confi...
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 ...
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 BlockingSchedul...
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 LogitsProces...
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 LogitsProces...
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:...
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, ...
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, Tup...
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_ar...
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: ...
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,do...
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,do...
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,do...
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,do...
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 ...
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,do...
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,do...
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,do...
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 Too...
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 Too...
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 Too...
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 Too...
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 Too...
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 Too...
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 Too...
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 Too...
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 ...
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 Too...
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 Too...
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 Too...
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 Too...
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 ...
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: "...
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] = No...
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 seq...
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_...
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:...
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 = {...
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 XAgent...
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 p...
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`, `j...
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 f...
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 ...
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,...
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. Ar...
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'): ...
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 depe...
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...
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...
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...
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...
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[XAg...
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, inde...
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. Writ...
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.applicatio...
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.applicatio...
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.applicatio...
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.applicatio...
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.applicatio...
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.applicatio...
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.applicatio...
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.applicatio...
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 f...
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 f...
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 f...
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 f...
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...
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: """ XAgentServe...
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...
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...
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...
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...
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, M...
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_da...
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...
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): de...
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 roo...
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 ...
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 fi...
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 u...
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...
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 u...
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 ...
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='...
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_id...
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...
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, ...
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 ...
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...
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_ra...
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_boostmonodept...
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...
null