response
stringlengths 1
33.1k
| instruction
stringlengths 22
582k
|
---|---|
Return the global timeout setting(second) to connect.
|
def getdefaulttimeout():
"""
Return the global timeout setting(second) to connect.
"""
return default_timeout
|
parse url and the result is tuple of
(hostname, port, resource path and the flag of secure mode)
url: url string.
|
def _parse_url(url):
"""
parse url and the result is tuple of
(hostname, port, resource path and the flag of secure mode)
url: url string.
"""
if ":" not in url:
raise ValueError("url is invalid")
scheme, url = url.split(":", 1)
parsed = urlparse(url, scheme="http")
if parsed.hostname:
hostname = parsed.hostname
else:
raise ValueError("hostname is invalid")
port = 0
if parsed.port:
port = parsed.port
is_secure = False
if scheme == "ws":
if not port:
port = 80
elif scheme == "wss":
is_secure = True
if not port:
port = 443
else:
raise ValueError("scheme %s is invalid" % scheme)
if parsed.path:
resource = parsed.path
else:
resource = "/"
if parsed.query:
resource += "?" + parsed.query
return (hostname, port, resource, is_secure)
|
connect to url and return websocket object.
Connect to url and return the WebSocket object.
Passing optional timeout parameter will set the timeout on the socket.
If no timeout is supplied, the global default timeout setting returned by getdefauttimeout() is used.
You can customize using 'options'.
If you set "header" dict object, you can set your own custom header.
>>> conn = create_connection("ws://echo.websocket.org/",
... header=["User-Agent: MyProgram",
... "x-custom: header"])
timeout: socket timeout time. This value is integer.
if you set None for this value, it means "use default_timeout value"
options: current support option is only "header".
if you set header as dict value, the custom HTTP headers are added.
|
def create_connection(url, timeout=None, **options):
"""
connect to url and return websocket object.
Connect to url and return the WebSocket object.
Passing optional timeout parameter will set the timeout on the socket.
If no timeout is supplied, the global default timeout setting returned by getdefauttimeout() is used.
You can customize using 'options'.
If you set "header" dict object, you can set your own custom header.
>>> conn = create_connection("ws://echo.websocket.org/",
... header=["User-Agent: MyProgram",
... "x-custom: header"])
timeout: socket timeout time. This value is integer.
if you set None for this value, it means "use default_timeout value"
options: current support option is only "header".
if you set header as dict value, the custom HTTP headers are added.
"""
sockopt = options.get("sockopt", ())
websock = WebSocket(sockopt=sockopt)
websock.settimeout(timeout != None and timeout or default_timeout)
websock.connect(url, **options)
return websock
|
Line and column are zero based
|
def setBreakpoint(location, condition=None):
""" Line and column are zero based """
params = {}
location.lineNumber = location.lineNumber
params['location'] = location()
if condition:
params['condition'] = condition
command = Command('Debugger.setBreakpoint', params)
return command
|
Line and column are zero based
|
def setBreakpoint_parser(result):
""" Line and column are zero based """
data = {}
data['breakpointId'] = BreakpointId(result['breakpointId'])
data['actualLocation'] = Location(result['actualLocation'])
data['actualLocation'].lineNumber = data['actualLocation'].lineNumber
return data
|
Line and column are zero based
|
def setBreakpointByUrl(lineNumber, url, urlRegex=None, columnNumber=None, condition=None):
""" Line and column are zero based """
params = {}
params['lineNumber'] = lineNumber
params['url'] = restoreQueryString(url)
if urlRegex:
params['urlRegex'] = urlRegex
if columnNumber:
params['columnNumber'] = columnNumber
else:
params['columnNumber'] = 0
if condition:
params['condition'] = condition
else:
params['condition'] = ''
command = Command('Debugger.setBreakpointByUrl', params)
return command
|
Line and column are zero based
|
def setBreakpointByUrl_parser(result):
""" Line and column are zero based """
data = {}
data['breakpointId'] = BreakpointId(result['breakpointId'])
data['locations'] = []
for location in result['locations']:
location_found = Location(location)
location_found.lineNumber = location_found.lineNumber
data['locations'].append(location_found)
return data
|
Login API for email and password based login
|
def login(request: LoginRequest, Authorize: AuthJWT = Depends()):
"""Login API for email and password based login"""
email_to_find = request.email
user: User = db.session.query(User).filter(User.email == email_to_find).first()
if user == None or request.email != user.email or request.password != user.password:
raise HTTPException(status_code=401, detail="Bad username or password")
# subject identifier for who this token is for example id or username from database
access_token = create_access_token(user.email, Authorize)
return {"access_token": access_token}
|
GitHub login
|
def github_login():
"""GitHub login"""
github_client_id = ""
return RedirectResponse(f'https://github.com/login/oauth/authorize?scope=user:email&client_id={github_client_id}')
|
GitHub login callback
|
def github_auth_handler(code: str = Query(...), Authorize: AuthJWT = Depends()):
"""GitHub login callback"""
github_token_url = 'https://github.com/login/oauth/access_token'
github_client_id = superagi.config.config.get_config("GITHUB_CLIENT_ID")
github_client_secret = superagi.config.config.get_config("GITHUB_CLIENT_SECRET")
frontend_url = superagi.config.config.get_config("FRONTEND_URL", "http://localhost:3000")
params = {
'client_id': github_client_id,
'client_secret': github_client_secret,
'code': code
}
headers = {
'Accept': 'application/json'
}
response = requests.post(github_token_url, params=params, headers=headers)
if response.ok:
data = response.json()
access_token = data.get('access_token')
github_api_url = 'https://api.github.com/user'
headers = {
'Authorization': f'Bearer {access_token}'
}
response = requests.get(github_api_url, headers=headers)
if response.ok:
user_data = response.json()
user_email = user_data["email"]
if user_email is None:
user_email = user_data["login"] + "@github.com"
db_user: User = db.session.query(User).filter(User.email == user_email).first()
if db_user is not None:
jwt_token = create_access_token(user_email, Authorize)
redirect_url_success = f"{frontend_url}?access_token={jwt_token}&first_time_login={False}"
return RedirectResponse(url=redirect_url_success)
user = User(name=user_data["name"], email=user_email)
db.session.add(user)
db.session.commit()
jwt_token = create_access_token(user_email, Authorize)
redirect_url_success = f"{frontend_url}?access_token={jwt_token}&first_time_login={True}"
return RedirectResponse(url=redirect_url_success)
else:
redirect_url_failure = "https://superagi.com/"
return RedirectResponse(url=redirect_url_failure)
else:
redirect_url_failure = "https://superagi.com/"
return RedirectResponse(url=redirect_url_failure)
|
API to get current logged in User
|
def user(Authorize: AuthJWT = Depends()):
"""API to get current logged in User"""
Authorize.jwt_required()
current_user = Authorize.get_jwt_subject()
return {"user": current_user}
|
Get GitHub Client ID
|
def github_client_id():
"""Get GitHub Client ID"""
git_hub_client_id = superagi.config.config.get_config("GITHUB_CLIENT_ID")
if git_hub_client_id:
git_hub_client_id = git_hub_client_id.strip()
return {"github_client_id": git_hub_client_id}
|
Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
|
def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
db_url = database_url
if db_url is None:
if db_username is None:
db_url = f'postgresql://{db_host}/{db_name}'
else:
db_url = f'postgresql://{db_username}:{db_password}@{db_host}/{db_name}'
else:
db_url = urlparse(db_url)
db_url = db_url.scheme + "://" + db_url.netloc + db_url.path
config.set_main_option("sqlalchemy.url", db_url)
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
|
Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
|
def run_migrations_online() -> None:
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
db_host = get_config('DB_HOST', 'super__postgres')
db_username = get_config('DB_USERNAME')
db_password = get_config('DB_PASSWORD')
db_name = get_config('DB_NAME')
db_url = get_config('DB_URL', None)
if db_url is None:
if db_username is None:
db_url = f'postgresql://{db_host}/{db_name}'
else:
db_url = f'postgresql://{db_username}:{db_password}@{db_host}/{db_name}'
else:
db_url = urlparse(db_url)
db_url = db_url.scheme + "://" + db_url.netloc + db_url.path
config.set_main_option('sqlalchemy.url', db_url)
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata
)
with context.begin_transaction():
context.run_migrations()
|
Check if wait time of wait workflow step is over and can be resumed.
|
def execute_waiting_workflows():
"""Check if wait time of wait workflow step is over and can be resumed."""
from superagi.jobs.agent_executor import AgentExecutor
logger.info("Executing waiting workflows job")
AgentExecutor().execute_waiting_workflows()
|
Executing agent scheduling in the background.
|
def initialize_schedule_agent_task():
"""Executing agent scheduling in the background."""
schedule_helper = AgentScheduleHelper()
schedule_helper.update_next_scheduled_time()
schedule_helper.run_scheduled_agents()
|
Execute an agent step in background.
|
def execute_agent(agent_execution_id: int, time):
"""Execute an agent step in background."""
from superagi.jobs.agent_executor import AgentExecutor
handle_tools_import()
logger.info("Execute agent:" + str(time) + "," + str(agent_execution_id))
AgentExecutor().execute_next_step(agent_execution_id=agent_execution_id)
|
Summarize a resource in background.
|
def summarize_resource(agent_id: int, resource_id: int):
"""Summarize a resource in background."""
from superagi.resource_manager.resource_summary import ResourceSummarizer
from superagi.types.storage_types import StorageType
from superagi.models.resource import Resource
from superagi.resource_manager.resource_manager import ResourceManager
engine = connect_db()
Session = sessionmaker(bind=engine)
session = Session()
agent_config = Agent.fetch_configuration(session, agent_id)
organisation = Agent.find_org_by_agent_id(session, agent_id)
model_source = Configuration.fetch_configurations(session, organisation.id, "model_source", agent_config["model"]) or "OpenAi"
if ModelSourceType.GooglePalm.value in model_source or ModelSourceType.Replicate.value in model_source:
return
resource = session.query(Resource).filter(Resource.id == resource_id).first()
file_path = resource.path
if resource.storage_type == StorageType.S3.value:
documents = ResourceManager(str(agent_id)).create_llama_document_s3(file_path)
else:
documents = ResourceManager(str(agent_id)).create_llama_document(file_path)
logger.info("Summarize resource:" + str(agent_id) + "," + str(resource_id))
resource_summarizer = ResourceSummarizer(session=session, agent_id=agent_id, model=agent_config["model"])
resource_summarizer.add_to_vector_store_and_create_summary(resource_id=resource_id,
documents=documents)
session.close()
|
Create a new agent with configurations.
Args:
agent_with_config (AgentConfigInput): Data for creating a new agent with configurations.
- name (str): Name of the agent.
- project_id (int): Identifier of the associated project.
- description (str): Description of the agent.
- goal (List[str]): List of goals for the agent.
- constraints (List[str]): List of constraints for the agent.
- tools (List[int]): List of tool identifiers associated with the agent.
- exit (str): Exit condition for the agent.
- iteration_interval (int): Interval between iterations for the agent.
- model (str): Model information for the agent.
- permission_type (str): Permission type for the agent.
- LTM_DB (str): LTM database for the agent.
- max_iterations (int): Maximum number of iterations for the agent.
- user_timezone (string): Timezone of the user
Returns:
dict: Dictionary containing the created agent's ID, execution ID, name, and content type.
Raises:
HTTPException (status_code=404): If the associated project or any of the tools is not found.
|
def create_agent_with_config(agent_with_config: AgentConfigInput,
Authorize: AuthJWT = Depends(check_auth)):
"""
Create a new agent with configurations.
Args:
agent_with_config (AgentConfigInput): Data for creating a new agent with configurations.
- name (str): Name of the agent.
- project_id (int): Identifier of the associated project.
- description (str): Description of the agent.
- goal (List[str]): List of goals for the agent.
- constraints (List[str]): List of constraints for the agent.
- tools (List[int]): List of tool identifiers associated with the agent.
- exit (str): Exit condition for the agent.
- iteration_interval (int): Interval between iterations for the agent.
- model (str): Model information for the agent.
- permission_type (str): Permission type for the agent.
- LTM_DB (str): LTM database for the agent.
- max_iterations (int): Maximum number of iterations for the agent.
- user_timezone (string): Timezone of the user
Returns:
dict: Dictionary containing the created agent's ID, execution ID, name, and content type.
Raises:
HTTPException (status_code=404): If the associated project or any of the tools is not found.
"""
project = db.session.query(Project).get(agent_with_config.project_id)
if not project:
raise HTTPException(status_code=404, detail="Project not found")
invalid_tools = Tool.get_invalid_tools(agent_with_config.tools, db.session)
if len(invalid_tools) > 0: # If the returned value is not True (then it is an invalid tool_id)
raise HTTPException(status_code=404,
detail=f"Tool with IDs {str(invalid_tools)} does not exist. 404 Not Found.")
agent_toolkit_tools = Toolkit.fetch_tool_ids_from_toolkit(session=db.session,
toolkit_ids=agent_with_config.toolkits)
agent_with_config.tools.extend(agent_toolkit_tools)
db_agent = Agent.create_agent_with_config(db, agent_with_config)
start_step = AgentWorkflow.fetch_trigger_step_id(db.session, db_agent.agent_workflow_id)
iteration_step_id = IterationWorkflow.fetch_trigger_step_id(db.session,
start_step.action_reference_id).id if start_step.action_type == "ITERATION_WORKFLOW" else -1
# Creating an execution with RUNNING status
execution = AgentExecution(status='CREATED', last_execution_time=datetime.now(), agent_id=db_agent.id,
name="New Run", current_agent_step_id=start_step.id, iteration_workflow_step_id=iteration_step_id)
agent_execution_configs = {
"goal": agent_with_config.goal,
"instruction": agent_with_config.instruction,
"constraints": agent_with_config.constraints,
"toolkits": agent_with_config.toolkits,
"exit": agent_with_config.exit,
"tools": agent_with_config.tools,
"iteration_interval": agent_with_config.iteration_interval,
"model": agent_with_config.model,
"permission_type": agent_with_config.permission_type,
"LTM_DB": agent_with_config.LTM_DB,
"max_iterations": agent_with_config.max_iterations,
"user_timezone": agent_with_config.user_timezone,
"knowledge": agent_with_config.knowledge
}
db.session.add(execution)
db.session.commit()
db.session.flush()
AgentExecutionConfiguration.add_or_update_agent_execution_config(session=db.session, execution=execution,
agent_execution_configs=agent_execution_configs)
agent = db.session.query(Agent).filter(Agent.id == db_agent.id, ).first()
organisation = agent.get_agent_organisation(db.session)
EventHandler(session=db.session).create_event('run_created',
{'agent_execution_id': execution.id,
'agent_execution_name': execution.name},
db_agent.id,
organisation.id if organisation else 0),
if agent_with_config.knowledge:
knowledge_name = db.session.query(Knowledges.name).filter(Knowledges.id == agent_with_config.knowledge).first()[0]
EventHandler(session=db.session).create_event('knowledge_picked',
{'knowledge_name': knowledge_name,
'agent_execution_id': execution.id},
db_agent.id,
organisation.id if organisation else 0)
EventHandler(session=db.session).create_event('agent_created',
{'agent_name': agent_with_config.name,
'model': agent_with_config.model},
db_agent.id,
organisation.id if organisation else 0)
db.session.commit()
return {
"id": db_agent.id,
"execution_id": execution.id,
"name": db_agent.name,
"contentType": "Agents"
}
|
Create a new agent with configurations and scheduling.
Args:
agent_with_config_schedule (AgentConfigSchedule): Data for creating a new agent with configurations and scheduling.
Returns:
dict: Dictionary containing the created agent's ID, name, content type and schedule ID of the agent.
Raises:
HTTPException (status_code=500): If the associated agent fails to get scheduled.
|
def create_and_schedule_agent(agent_config_schedule: AgentConfigSchedule,
Authorize: AuthJWT = Depends(check_auth)):
"""
Create a new agent with configurations and scheduling.
Args:
agent_with_config_schedule (AgentConfigSchedule): Data for creating a new agent with configurations and scheduling.
Returns:
dict: Dictionary containing the created agent's ID, name, content type and schedule ID of the agent.
Raises:
HTTPException (status_code=500): If the associated agent fails to get scheduled.
"""
project = db.session.query(Project).get(agent_config_schedule.agent_config.project_id)
if not project:
raise HTTPException(status_code=404, detail="Project not found")
agent_config = agent_config_schedule.agent_config
invalid_tools = Tool.get_invalid_tools(agent_config.tools, db.session)
if len(invalid_tools) > 0: # If the returned value is not True (then it is an invalid tool_id)
raise HTTPException(status_code=404,
detail=f"Tool with IDs {str(invalid_tools)} does not exist. 404 Not Found.")
agent_toolkit_tools = Toolkit.fetch_tool_ids_from_toolkit(session=db.session,
toolkit_ids=agent_config.toolkits)
agent_config.tools.extend(agent_toolkit_tools)
db_agent = Agent.create_agent_with_config(db, agent_config)
# Update the agent_id of schedule before scheduling the agent
agent_schedule = agent_config_schedule.schedule
# Create a new agent schedule
agent_schedule = AgentSchedule(
agent_id=db_agent.id,
start_time=agent_schedule.start_time,
next_scheduled_time=agent_schedule.start_time,
recurrence_interval=agent_schedule.recurrence_interval,
expiry_date=agent_schedule.expiry_date,
expiry_runs=agent_schedule.expiry_runs,
current_runs=0,
status="SCHEDULED"
)
agent_schedule.agent_id = db_agent.id
db.session.add(agent_schedule)
db.session.commit()
if agent_schedule.id is None:
raise HTTPException(status_code=500, detail="Failed to schedule agent")
agent = db.session.query(Agent).filter(Agent.id == db_agent.id, ).first()
organisation = agent.get_agent_organisation(db.session)
EventHandler(session=db.session).create_event('agent_created', {'agent_name': agent_config.name,
'model': agent_config.model}, db_agent.id,
organisation.id if organisation else 0)
db.session.commit()
return {
"id": db_agent.id,
"name": db_agent.name,
"contentType": "Agents",
"schedule_id": agent_schedule.id
}
|
Stopping the scheduling for a given agent.
Args:
agent_id (int): Identifier of the Agent
Authorize (AuthJWT, optional): Authorization dependency. Defaults to Depends(check_auth).
Raises:
HTTPException (status_code=404): If the agent schedule is not found.
|
def stop_schedule(agent_id: int, Authorize: AuthJWT = Depends(check_auth)):
"""
Stopping the scheduling for a given agent.
Args:
agent_id (int): Identifier of the Agent
Authorize (AuthJWT, optional): Authorization dependency. Defaults to Depends(check_auth).
Raises:
HTTPException (status_code=404): If the agent schedule is not found.
"""
agent_to_delete = db.session.query(AgentSchedule).filter(AgentSchedule.agent_id == agent_id,
AgentSchedule.status == "SCHEDULED").first()
if not agent_to_delete:
raise HTTPException(status_code=404, detail="Schedule not found")
agent_to_delete.status = "STOPPED"
db.session.commit()
|
Edit the scheduling for a given agent.
Args:
agent_id (int): Identifier of the Agent
schedule (AgentSchedule): New schedule data
Authorize (AuthJWT, optional): Authorization dependency. Defaults to Depends(check_auth).
Raises:
HTTPException (status_code=404): If the agent schedule is not found.
|
def edit_schedule(schedule: AgentScheduleInput,
Authorize: AuthJWT = Depends(check_auth)):
"""
Edit the scheduling for a given agent.
Args:
agent_id (int): Identifier of the Agent
schedule (AgentSchedule): New schedule data
Authorize (AuthJWT, optional): Authorization dependency. Defaults to Depends(check_auth).
Raises:
HTTPException (status_code=404): If the agent schedule is not found.
"""
agent_to_edit = db.session.query(AgentSchedule).filter(AgentSchedule.agent_id == schedule.agent_id, AgentSchedule.status == "SCHEDULED").first()
if not agent_to_edit:
raise HTTPException(status_code=404, detail="Schedule not found")
# Update agent schedule with new data
agent_to_edit.start_time = schedule.start_time
agent_to_edit.next_scheduled_time = schedule.start_time
agent_to_edit.recurrence_interval = schedule.recurrence_interval
agent_to_edit.expiry_date = schedule.expiry_date
agent_to_edit.expiry_runs = schedule.expiry_runs
db.session.commit()
|
Get the scheduling data for a given agent.
Args:
agent_id (int): Identifier of the Agent
Raises:
HTTPException (status_code=404): If the agent schedule is not found.
Returns:
current_datetime (DateTime): Current Date and Time.
recurrence_interval (String): Time interval for recurring schedule run.
expiry_date (DateTime): The date and time when the agent is scheduled to stop runs.
expiry_runs (Integer): The number of runs before the agent expires.
|
def get_schedule_data(agent_id: int, Authorize: AuthJWT = Depends(check_auth)):
"""
Get the scheduling data for a given agent.
Args:
agent_id (int): Identifier of the Agent
Raises:
HTTPException (status_code=404): If the agent schedule is not found.
Returns:
current_datetime (DateTime): Current Date and Time.
recurrence_interval (String): Time interval for recurring schedule run.
expiry_date (DateTime): The date and time when the agent is scheduled to stop runs.
expiry_runs (Integer): The number of runs before the agent expires.
"""
agent = db.session.query(AgentSchedule).filter(AgentSchedule.agent_id == agent_id,
AgentSchedule.status == "SCHEDULED").first()
if not agent:
raise HTTPException(status_code=404, detail="Agent Schedule not found")
user_timezone = db.session.query(AgentConfiguration).filter(AgentConfiguration.key == "user_timezone",
AgentConfiguration.agent_id == agent_id).first()
if user_timezone and user_timezone.value != "None":
tzone = timezone(user_timezone.value)
else:
tzone = timezone('GMT')
current_datetime = datetime.now(tzone).strftime("%d/%m/%Y %I:%M %p")
return {
"current_datetime": current_datetime,
"start_date": agent.start_time.astimezone(tzone).strftime("%d %b %Y"),
"start_time": agent.start_time.astimezone(tzone).strftime("%I:%M %p"),
"recurrence_interval": agent.recurrence_interval if agent.recurrence_interval else None,
"expiry_date": agent.expiry_date.astimezone(tzone).strftime("%d/%m/%Y") if agent.expiry_date else None,
"expiry_runs": agent.expiry_runs if agent.expiry_runs != -1 else None
}
|
Get all agents by project ID.
Args:
project_id (int): Identifier of the project.
Authorize (AuthJWT, optional): Authorization dependency. Defaults to Depends(check_auth).
Returns:
list: List of agents associated with the project, including their status and scheduling information.
Raises:
HTTPException (status_code=404): If the project is not found.
|
def get_agents_by_project_id(project_id: int,
Authorize: AuthJWT = Depends(check_auth)):
"""
Get all agents by project ID.
Args:
project_id (int): Identifier of the project.
Authorize (AuthJWT, optional): Authorization dependency. Defaults to Depends(check_auth).
Returns:
list: List of agents associated with the project, including their status and scheduling information.
Raises:
HTTPException (status_code=404): If the project is not found.
"""
# Checking for project
project = db.session.query(Project).get(project_id)
if not project:
raise HTTPException(status_code=404, detail="Project not found")
agents = db.session.query(Agent).filter(Agent.project_id == project_id, or_(or_(Agent.is_deleted == False, Agent.is_deleted is None), Agent.is_deleted is None)).all()
new_agents, new_agents_sorted = [], []
for agent in agents:
agent_dict = vars(agent)
agent_id = agent.id
# Query the AgentExecution table using the agent ID
executions = db.session.query(AgentExecution).filter_by(agent_id=agent_id).all()
is_running = False
for execution in executions:
if execution.status == "RUNNING":
is_running = True
break
# Check if the agent is scheduled
is_scheduled = db.session.query(AgentSchedule).filter_by(agent_id=agent_id, status="SCHEDULED").first() is not None
new_agent = {
**agent_dict,
'is_running': is_running,
'is_scheduled': is_scheduled
}
new_agents.append(new_agent)
new_agents_sorted = sorted(new_agents, key=lambda agent: agent['is_running'] == True, reverse=True)
return new_agents_sorted
|
Delete an existing Agent
- Updates the is_deleted flag: Executes a soft delete
- AgentExecutions are updated to: "TERMINATED" if agentexecution is created, All the agent executions are updated
- AgentExecutionPermission is set to: "REJECTED" if agentexecutionpersmision is created
Args:
agent_id (int): Identifier of the Agent to delete
Returns:
A dictionary containing a "success" key with the value True to indicate a successful delete.
Raises:
HTTPException (Status Code=404): If the Agent or associated Project is not found or deleted already.
|
def delete_agent(agent_id: int, Authorize: AuthJWT = Depends(check_auth)):
"""
Delete an existing Agent
- Updates the is_deleted flag: Executes a soft delete
- AgentExecutions are updated to: "TERMINATED" if agentexecution is created, All the agent executions are updated
- AgentExecutionPermission is set to: "REJECTED" if agentexecutionpersmision is created
Args:
agent_id (int): Identifier of the Agent to delete
Returns:
A dictionary containing a "success" key with the value True to indicate a successful delete.
Raises:
HTTPException (Status Code=404): If the Agent or associated Project is not found or deleted already.
"""
db_agent = db.session.query(Agent).filter(Agent.id == agent_id).first()
db_agent_executions = db.session.query(AgentExecution).filter(AgentExecution.agent_id == agent_id).all()
db_agent_schedule = db.session.query(AgentSchedule).filter(AgentSchedule.agent_id == agent_id, AgentSchedule.status == "SCHEDULED").first()
if not db_agent or db_agent.is_deleted:
raise HTTPException(status_code=404, detail="agent not found")
# Deletion Procedure
db_agent.is_deleted = True
if db_agent_executions:
# Updating all the RUNNING executions to TERMINATED
for db_agent_execution in db_agent_executions:
db_agent_execution.status = "TERMINATED"
if db_agent_schedule:
# Updating the schedule status to STOPPED
db_agent_schedule.status = "STOPPED"
db.session.commit()
|
Create a new agent execution/run.
Args:
agent_execution (AgentExecution): The agent execution data.
Returns:
AgentExecution: The created agent execution.
Raises:
HTTPException (Status Code=404): If the agent is not found.
|
def create_agent_execution(agent_execution: AgentExecutionIn,
Authorize: AuthJWT = Depends(check_auth)):
"""
Create a new agent execution/run.
Args:
agent_execution (AgentExecution): The agent execution data.
Returns:
AgentExecution: The created agent execution.
Raises:
HTTPException (Status Code=404): If the agent is not found.
"""
agent = db.session.query(Agent).filter(Agent.id == agent_execution.agent_id, Agent.is_deleted == False).first()
if not agent:
raise HTTPException(status_code=404, detail="Agent not found")
start_step = AgentWorkflow.fetch_trigger_step_id(db.session, agent.agent_workflow_id)
iteration_step_id = IterationWorkflow.fetch_trigger_step_id(db.session,
start_step.action_reference_id).id if start_step.action_type == "ITERATION_WORKFLOW" else -1
db_agent_execution = AgentExecution(status="CREATED", last_execution_time=datetime.now(),
agent_id=agent_execution.agent_id, name=agent_execution.name, num_of_calls=0,
num_of_tokens=0,
current_agent_step_id=start_step.id,
iteration_workflow_step_id=iteration_step_id)
agent_execution_configs = {
"goal": agent_execution.goal,
"instruction": agent_execution.instruction
}
agent_configs = db.session.query(AgentConfiguration).filter(AgentConfiguration.agent_id == agent_execution.agent_id).all()
keys_to_exclude = ["goal", "instruction"]
for agent_config in agent_configs:
if agent_config.key not in keys_to_exclude:
if agent_config.key == "toolkits":
if agent_config.value:
toolkits = [int(item) for item in agent_config.value.strip('{}').split(',') if item.strip() and item != '[]']
agent_execution_configs[agent_config.key] = toolkits
else:
agent_execution_configs[agent_config.key] = []
elif agent_config.key == "constraints":
if agent_config.value:
agent_execution_configs[agent_config.key] = agent_config.value
else:
agent_execution_configs[agent_config.key] = []
else:
agent_execution_configs[agent_config.key] = agent_config.value
db.session.add(db_agent_execution)
db.session.commit()
db.session.flush()
#update status from CREATED to RUNNING
db_agent_execution.status = "RUNNING"
db.session.commit()
AgentExecutionConfiguration.add_or_update_agent_execution_config(session=db.session, execution=db_agent_execution,
agent_execution_configs=agent_execution_configs)
organisation = agent.get_agent_organisation(db.session)
agent_execution_knowledge = AgentConfiguration.get_agent_config_by_key_and_agent_id(session= db.session, key= 'knowledge', agent_id= agent_execution.agent_id)
EventHandler(session=db.session).create_event('run_created',
{'agent_execution_id': db_agent_execution.id,
'agent_execution_name':db_agent_execution.name},
agent_execution.agent_id,
organisation.id if organisation else 0)
if agent_execution_knowledge and agent_execution_knowledge.value != 'None':
knowledge_name = Knowledges.get_knowledge_from_id(db.session, int(agent_execution_knowledge.value)).name
if knowledge_name is not None:
EventHandler(session=db.session).create_event('knowledge_picked',
{'knowledge_name': knowledge_name,
'agent_execution_id': db_agent_execution.id},
agent_execution.agent_id,
organisation.id if organisation else 0)
Models.api_key_from_configurations(session=db.session, organisation_id=organisation.id)
if db_agent_execution.status == "RUNNING":
execute_agent.delay(db_agent_execution.id, datetime.now())
return db_agent_execution
|
Create a new agent run with all the information(goals, instructions, model, etc).
Args:
agent_execution (AgentExecution): The agent execution data.
Returns:
AgentExecution: The created agent execution.
Raises:
HTTPException (Status Code=404): If the agent is not found.
|
def create_agent_run(agent_execution: AgentRunIn, Authorize: AuthJWT = Depends(check_auth)):
"""
Create a new agent run with all the information(goals, instructions, model, etc).
Args:
agent_execution (AgentExecution): The agent execution data.
Returns:
AgentExecution: The created agent execution.
Raises:
HTTPException (Status Code=404): If the agent is not found.
"""
agent = db.session.query(Agent).filter(Agent.id == agent_execution.agent_id, Agent.is_deleted == False).first()
if not agent:
raise HTTPException(status_code = 404, detail = "Agent not found")
#Update the agent configurations table with the data of the latest agent execution
AgentConfiguration.update_agent_configurations_table(session=db.session, agent_id=agent_execution.agent_id, updated_details=agent_execution)
start_step = AgentWorkflow.fetch_trigger_step_id(db.session, agent.agent_workflow_id)
iteration_step_id = IterationWorkflow.fetch_trigger_step_id(db.session,
start_step.action_reference_id).id if start_step.action_type == "ITERATION_WORKFLOW" else -1
db_agent_execution = AgentExecution(status="CREATED", last_execution_time=datetime.now(),
agent_id=agent_execution.agent_id, name=agent_execution.name, num_of_calls=0,
num_of_tokens=0,
current_agent_step_id=start_step.id,
iteration_workflow_step_id=iteration_step_id)
agent_execution_configs = {
"goal": agent_execution.goal,
"instruction": agent_execution.instruction,
"constraints": agent_execution.constraints,
"toolkits": agent_execution.toolkits,
"exit": agent_execution.exit,
"tools": agent_execution.tools,
"iteration_interval": agent_execution.iteration_interval,
"model": agent_execution.model,
"permission_type": agent_execution.permission_type,
"LTM_DB": agent_execution.LTM_DB,
"max_iterations": agent_execution.max_iterations,
"user_timezone": agent_execution.user_timezone,
"knowledge": agent_execution.knowledge
}
db.session.add(db_agent_execution)
db.session.commit()
db.session.flush()
#update status from CREATED to RUNNING
db_agent_execution.status = "RUNNING"
db.session.commit()
AgentExecutionConfiguration.add_or_update_agent_execution_config(session = db.session, execution = db_agent_execution,
agent_execution_configs = agent_execution_configs)
organisation = agent.get_agent_organisation(db.session)
EventHandler(session=db.session).create_event('run_created',
{'agent_execution_id': db_agent_execution.id,
'agent_execution_name':db_agent_execution.name},
agent_execution.agent_id,
organisation.id if organisation else 0)
agent_execution_knowledge = AgentConfiguration.get_agent_config_by_key_and_agent_id(session= db.session, key= 'knowledge', agent_id= agent_execution.agent_id)
if agent_execution_knowledge and agent_execution_knowledge.value != 'None':
knowledge_name = Knowledges.get_knowledge_from_id(db.session, int(agent_execution_knowledge.value)).name
if knowledge_name is not None:
EventHandler(session=db.session).create_event('knowledge_picked',
{'knowledge_name': knowledge_name,
'agent_execution_id': db_agent_execution.id},
agent_execution.agent_id,
organisation.id if organisation else 0)
if db_agent_execution.status == "RUNNING":
execute_agent.delay(db_agent_execution.id, datetime.now())
return db_agent_execution
|
Schedules an already existing agent.
Args:
agent_schedule (AgentScheduleInput): Data for creating a scheduling for an existing agent.
agent_id (Integer): The ID of the agent being scheduled.
start_time (DateTime): The date and time from which the agent is scheduled.
recurrence_interval (String): Stores "none" if not recurring,
or a time interval like '2 Weeks', '1 Month', '2 Minutes' based on input.
expiry_date (DateTime): The date and time when the agent is scheduled to stop runs.
expiry_runs (Integer): The number of runs before the agent expires.
Returns:
Schedule ID: Unique Schedule ID of the Agent.
Raises:
HTTPException (Status Code=500): If the agent fails to get scheduled.
|
def schedule_existing_agent(agent_schedule: AgentScheduleInput,
Authorize: AuthJWT = Depends(check_auth)):
"""
Schedules an already existing agent.
Args:
agent_schedule (AgentScheduleInput): Data for creating a scheduling for an existing agent.
agent_id (Integer): The ID of the agent being scheduled.
start_time (DateTime): The date and time from which the agent is scheduled.
recurrence_interval (String): Stores "none" if not recurring,
or a time interval like '2 Weeks', '1 Month', '2 Minutes' based on input.
expiry_date (DateTime): The date and time when the agent is scheduled to stop runs.
expiry_runs (Integer): The number of runs before the agent expires.
Returns:
Schedule ID: Unique Schedule ID of the Agent.
Raises:
HTTPException (Status Code=500): If the agent fails to get scheduled.
"""
# Check if the agent is already scheduled
scheduled_agent = db.session.query(AgentSchedule).filter(AgentSchedule.agent_id == agent_schedule.agent_id,
AgentSchedule.status == "SCHEDULED").first()
if scheduled_agent:
# Update the old record with new data
scheduled_agent.start_time = agent_schedule.start_time
scheduled_agent.next_scheduled_time = agent_schedule.start_time
scheduled_agent.recurrence_interval = agent_schedule.recurrence_interval
scheduled_agent.expiry_date = agent_schedule.expiry_date
scheduled_agent.expiry_runs = agent_schedule.expiry_runs
db.session.commit()
else:
# Schedule the agent
scheduled_agent = AgentSchedule(
agent_id=agent_schedule.agent_id,
start_time=agent_schedule.start_time,
next_scheduled_time=agent_schedule.start_time,
recurrence_interval=agent_schedule.recurrence_interval,
expiry_date=agent_schedule.expiry_date,
expiry_runs=agent_schedule.expiry_runs,
current_runs=0,
status="SCHEDULED"
)
db.session.add(scheduled_agent)
db.session.commit()
schedule_id = scheduled_agent.id
if schedule_id is None:
raise HTTPException(status_code=500, detail="Failed to schedule agent")
return {
"schedule_id": schedule_id
}
|
Get an agent execution by agent_execution_id.
Args:
agent_execution_id (int): The ID of the agent execution.
Returns:
AgentExecution: The requested agent execution.
Raises:
HTTPException (Status Code=404): If the agent execution is not found.
|
def get_agent_execution(agent_execution_id: int,
Authorize: AuthJWT = Depends(check_auth)):
"""
Get an agent execution by agent_execution_id.
Args:
agent_execution_id (int): The ID of the agent execution.
Returns:
AgentExecution: The requested agent execution.
Raises:
HTTPException (Status Code=404): If the agent execution is not found.
"""
if (
db_agent_execution := db.session.query(AgentExecution)
.filter(AgentExecution.id == agent_execution_id)
.first()
):
return db_agent_execution
else:
raise HTTPException(status_code=404, detail="Agent execution not found")
|
Update details of particular agent_execution by agent_execution_id
|
def update_agent_execution(agent_execution_id: int,
agent_execution: AgentExecutionIn,
Authorize: AuthJWT = Depends(check_auth)):
"""Update details of particular agent_execution by agent_execution_id"""
db_agent_execution = db.session.query(AgentExecution).filter(AgentExecution.id == agent_execution_id).first()
if agent_execution.status == "COMPLETED":
raise HTTPException(status_code=400, detail="Invalid Request")
if not db_agent_execution:
raise HTTPException(status_code=404, detail="Agent Execution not found")
if agent_execution.agent_id:
if agent := db.session.query(Agent).get(agent_execution.agent_id):
db_agent_execution.agent_id = agent.id
else:
raise HTTPException(status_code=404, detail="Agent not found")
if agent_execution.status not in [
"CREATED",
"RUNNING",
"PAUSED",
"COMPLETED",
"TERMINATED",
]:
raise HTTPException(status_code=400, detail="Invalid Request")
db_agent_execution.status = agent_execution.status
db_agent_execution.last_execution_time = datetime.now()
db.session.commit()
if db_agent_execution.status == "RUNNING":
execute_agent.delay(db_agent_execution.id, datetime.now())
return db_agent_execution
|
Get list of all agent_ids for a given status
|
def agent_list_by_status(status: str,
Authorize: AuthJWT = Depends(check_auth)):
"""Get list of all agent_ids for a given status"""
running_agent_ids = db.session.query(AgentExecution.agent_id).filter(
AgentExecution.status == status.upper()).distinct().all()
agent_ids = [agent_id for (agent_id) in running_agent_ids]
return agent_ids
|
Get all running state agents
|
def list_running_agents(agent_id: str,
Authorize: AuthJWT = Depends(check_auth)):
"""Get all running state agents"""
executions = db.session.query(AgentExecution).filter(AgentExecution.agent_id == agent_id).order_by(
desc(AgentExecution.status == 'RUNNING'), desc(AgentExecution.last_execution_time)).all()
for execution in executions:
execution.time_difference = get_time_difference(execution.last_execution_time,str(datetime.now()))
return executions
|
Get latest executing agent details
|
def get_agent_by_latest_execution(project_id: int,
Authorize: AuthJWT = Depends(check_auth)):
"""Get latest executing agent details"""
latest_execution = (
db.session.query(AgentExecution)
.join(Agent, AgentExecution.agent_id == Agent.id)
.filter(Agent.project_id == project_id, Agent.is_deleted == False)
.order_by(desc(AgentExecution.last_execution_time))
.first()
)
isRunning = False
if latest_execution.status == "RUNNING":
isRunning = True
agent = db.session.query(Agent).filter(Agent.id == latest_execution.agent_id).first()
return {
"agent_id": latest_execution.agent_id,
"project_id": project_id,
"created_at": agent.created_at,
"description": agent.description,
"updated_at": agent.updated_at,
"name": agent.name,
"id": agent.id,
"status": isRunning,
"contentType": "Agents"
}
|
Get the agent configuration using the agent ID and the agent execution ID.
Args:
agent_id (int): Identifier of the agent.
agent_execution_id (int): Identifier of the agent execution.
Authorize (AuthJWT, optional): Authorization dependency. Defaults to Depends(check_auth).
Returns:
dict: Agent configuration including its details.
Raises:
HTTPException (status_code=404): If the agent is not found or deleted.
HTTPException (status_code=404): If the agent_id or the agent_execution_id is undefined.
|
def get_agent_execution_configuration(agent_id : Union[int, None, str],
agent_execution_id: Union[int, None, str],
Authorize: AuthJWT = Depends(check_auth)):
"""
Get the agent configuration using the agent ID and the agent execution ID.
Args:
agent_id (int): Identifier of the agent.
agent_execution_id (int): Identifier of the agent execution.
Authorize (AuthJWT, optional): Authorization dependency. Defaults to Depends(check_auth).
Returns:
dict: Agent configuration including its details.
Raises:
HTTPException (status_code=404): If the agent is not found or deleted.
HTTPException (status_code=404): If the agent_id or the agent_execution_id is undefined.
"""
# Check
if isinstance(agent_id, str):
raise HTTPException(status_code = 404, detail = "Agent Id undefined")
if isinstance(agent_execution_id, str):
raise HTTPException(status_code = 404, detail = "Agent Execution Id undefined")
# Define the agent_config keys to fetch
agent = db.session.query(Agent).filter(agent_id == Agent.id,or_(Agent.is_deleted == False)).first()
if not agent:
raise HTTPException(status_code = 404, detail = "Agent not found")
#If the agent_execution_id received is -1 then the agent_execution_id is set as the most recent execution
if agent_execution_id == -1:
agent_execution = db.session.query(AgentExecution).filter(AgentExecution.agent_id == agent_id).order_by(desc(AgentExecution.created_at)).first()
if agent_execution: agent_execution_id = agent_execution.id
#Fetch agent id from agent execution id and check whether the agent_id received is correct or not.
if agent_execution_id!=-1:
agent_execution_config = AgentExecution.get_agent_execution_from_id(db.session, agent_execution_id)
if agent_execution_config is None:
raise HTTPException(status_code = 404, detail = "Agent Execution not found")
agent_id_from_execution_id = agent_execution_config.agent_id
if agent_id != agent_id_from_execution_id:
raise HTTPException(status_code = 404, detail = "Wrong agent id")
# Query the AgentConfiguration table and the AgentExecuitonConfiguration table for all the keys
results_agent = db.session.query(AgentConfiguration).filter(AgentConfiguration.agent_id == agent_id).all()
if agent_execution_id!=-1: results_agent_execution = db.session.query(AgentExecutionConfiguration).filter(AgentExecutionConfiguration.agent_execution_id == agent_execution_id).all()
total_calls = db.session.query(func.sum(AgentExecution.num_of_calls)).filter(
AgentExecution.agent_id == agent_id).scalar()
total_tokens = db.session.query(func.sum(AgentExecution.num_of_tokens)).filter(
AgentExecution.agent_id == agent_id).scalar()
response = {}
if agent_execution_id!=-1:
response = AgentExecutionConfiguration.build_agent_execution_config(db.session, agent, results_agent, results_agent_execution, total_calls, total_tokens)
else:
response = AgentExecutionConfiguration.build_scheduled_agent_execution_config(db.session, agent, results_agent, total_calls, total_tokens)
# Close the session
db.session.close()
return response
|
Add a new agent execution feed.
Args:
agent_execution_feed (AgentExecutionFeed): The data for the agent execution feed.
Returns:
AgentExecutionFeed: The newly created agent execution feed.
Raises:
HTTPException (Status Code=404): If the associated agent execution is not found.
|
def create_agent_execution_feed(agent_execution_feed: AgentExecutionFeedIn,
Authorize: AuthJWT = Depends(check_auth)):
"""
Add a new agent execution feed.
Args:
agent_execution_feed (AgentExecutionFeed): The data for the agent execution feed.
Returns:
AgentExecutionFeed: The newly created agent execution feed.
Raises:
HTTPException (Status Code=404): If the associated agent execution is not found.
"""
agent_execution = db.session.query(AgentExecution).get(agent_execution_feed.agent_execution_id)
if not agent_execution:
raise HTTPException(status_code=404, detail="Agent Execution not found")
db_agent_execution_feed = AgentExecutionFeed(agent_execution_id=agent_execution_feed.agent_execution_id,
feed=agent_execution_feed.feed, type=agent_execution_feed.type,
extra_info=agent_execution_feed.extra_info,
feed_group_id=agent_execution.current_feed_group_id)
db.session.add(db_agent_execution_feed)
db.session.commit()
return db_agent_execution_feed
|
Get an agent execution feed by agent_execution_feed_id.
Args:
agent_execution_feed_id (int): The ID of the agent execution feed.
Returns:
AgentExecutionFeed: The agent execution feed with the specified ID.
Raises:
HTTPException (Status Code=404): If the agent execution feed is not found.
|
def get_agent_execution_feed(agent_execution_feed_id: int,
Authorize: AuthJWT = Depends(check_auth)):
"""
Get an agent execution feed by agent_execution_feed_id.
Args:
agent_execution_feed_id (int): The ID of the agent execution feed.
Returns:
AgentExecutionFeed: The agent execution feed with the specified ID.
Raises:
HTTPException (Status Code=404): If the agent execution feed is not found.
"""
db_agent_execution_feed = db.session.query(AgentExecutionFeed).filter(
AgentExecutionFeed.id == agent_execution_feed_id).first()
if not db_agent_execution_feed:
raise HTTPException(status_code=404, detail="agent_execution_feed not found")
return db_agent_execution_feed
|
Update a particular agent execution feed.
Args:
agent_execution_feed_id (int): The ID of the agent execution feed to update.
agent_execution_feed (AgentExecutionFeed): The updated agent execution feed.
Returns:
AgentExecutionFeed: The updated agent execution feed.
Raises:
HTTPException (Status Code=404): If the agent execution feed or agent execution is not found.
|
def update_agent_execution_feed(agent_execution_feed_id: int,
agent_execution_feed: AgentExecutionFeedIn,
Authorize: AuthJWT = Depends(check_auth)):
"""
Update a particular agent execution feed.
Args:
agent_execution_feed_id (int): The ID of the agent execution feed to update.
agent_execution_feed (AgentExecutionFeed): The updated agent execution feed.
Returns:
AgentExecutionFeed: The updated agent execution feed.
Raises:
HTTPException (Status Code=404): If the agent execution feed or agent execution is not found.
"""
db_agent_execution_feed = db.session.query(AgentExecutionFeed).filter(
AgentExecutionFeed.id == agent_execution_feed_id).first()
if not db_agent_execution_feed:
raise HTTPException(status_code=404, detail="Agent Execution Feed not found")
if agent_execution_feed.agent_execution_id:
agent_execution = db.session.query(AgentExecution).get(agent_execution_feed.agent_execution_id)
if not agent_execution:
raise HTTPException(status_code=404, detail="Agent Execution not found")
db_agent_execution_feed.agent_execution_id = agent_execution.id
if agent_execution_feed.type is not None:
db_agent_execution_feed.type = agent_execution_feed.type
if agent_execution_feed.feed is not None:
db_agent_execution_feed.feed = agent_execution_feed.feed
# if agent_execution_feed.extra_info is not None:
# db_agent_execution_feed.extra_info = agent_execution_feed.extra_info
db.session.commit()
return db_agent_execution_feed
|
Get agent execution feed with other execution details.
Args:
agent_execution_id (int): The ID of the agent execution.
Returns:
dict: The agent execution status and feeds.
Raises:
HTTPException (Status Code=400): If the agent run is not found.
|
def get_agent_execution_feed(agent_execution_id: int,
Authorize: AuthJWT = Depends(check_auth)):
"""
Get agent execution feed with other execution details.
Args:
agent_execution_id (int): The ID of the agent execution.
Returns:
dict: The agent execution status and feeds.
Raises:
HTTPException (Status Code=400): If the agent run is not found.
"""
agent_execution = db.session.query(AgentExecution).filter(AgentExecution.id == agent_execution_id).first()
if agent_execution is None:
raise HTTPException(status_code=400, detail="Agent Run not found!")
feeds = db.session.query(AgentExecutionFeed).filter_by(agent_execution_id=agent_execution_id).order_by(
asc(AgentExecutionFeed.created_at)).all()
# # parse json
final_feeds = []
error = ""
for feed in feeds:
if feed.error_message:
if (agent_execution.last_shown_error_id is None) or (feed.id > agent_execution.last_shown_error_id):
#new error occured
error = feed.error_message
agent_execution.last_shown_error_id = feed.id
agent_execution.status = "ERROR_PAUSED"
db.session.commit()
if feed.id == agent_execution.last_shown_error_id and agent_execution.status == "ERROR_PAUSED":
error = feed.error_message
if feed.feed != "" and re.search(r"The current time and date is\s(\w{3}\s\w{3}\s\s?\d{1,2}\s\d{2}:\d{2}:\d{2}\s\d{4})",feed.feed) == None :
final_feeds.append(parse_feed(feed))
# get all permissions
execution_permissions = db.session.query(AgentExecutionPermission).\
filter_by(agent_execution_id=agent_execution_id). \
order_by(asc(AgentExecutionPermission.created_at)).all()
permissions = [
{
"id": permission.id,
"created_at": permission.created_at,
"response": permission.user_feedback,
"status": permission.status,
"tool_name": permission.tool_name,
"question": permission.question,
"user_feedback": permission.user_feedback,
"time_difference": get_time_difference(permission.created_at, str(datetime.now()))
} for permission in execution_permissions
]
waiting_period = None
if agent_execution.status == AgentWorkflowStepAction.WAIT_STEP.value:
workflow_step = AgentWorkflowStep.find_by_id(db.session, agent_execution.current_agent_step_id)
waiting_period = (AgentWorkflowStepWait.find_by_id(db.session, workflow_step.action_reference_id)).delay
return {
"status": agent_execution.status,
"feeds": final_feeds,
"permissions": permissions,
"waiting_period": waiting_period,
"errors": error
}
|
Get agent execution tasks and completed tasks.
Args:
agent_execution_id (int): The ID of the agent execution.
Returns:
dict: The tasks and completed tasks for the agent execution.
|
def get_execution_tasks(agent_execution_id: int,
Authorize: AuthJWT = Depends(check_auth)):
"""
Get agent execution tasks and completed tasks.
Args:
agent_execution_id (int): The ID of the agent execution.
Returns:
dict: The tasks and completed tasks for the agent execution.
"""
task_queue = TaskQueue(str(agent_execution_id))
tasks = []
for task in task_queue.get_tasks():
tasks.append({"name": task})
completed_tasks = []
for task in reversed(task_queue.get_completed_tasks()):
completed_tasks.append({"name": task['task']})
return {
"tasks": tasks,
"completed_tasks": completed_tasks
}
|
Get an agent execution permission by its ID.
Args:
agent_execution_permission_id (int): The ID of the agent execution permission.
Authorize (AuthJWT, optional): Authentication object. Defaults to Depends(check_auth).
Raises:
HTTPException: If the agent execution permission is not found.
Returns:
AgentExecutionPermission: The requested agent execution permission.
|
def get_agent_execution_permission(agent_execution_permission_id: int,
Authorize: AuthJWT = Depends(check_auth)):
"""
Get an agent execution permission by its ID.
Args:
agent_execution_permission_id (int): The ID of the agent execution permission.
Authorize (AuthJWT, optional): Authentication object. Defaults to Depends(check_auth).
Raises:
HTTPException: If the agent execution permission is not found.
Returns:
AgentExecutionPermission: The requested agent execution permission.
"""
db_agent_execution_permission = db.session.query(AgentExecutionPermission).get(agent_execution_permission_id)
if not db_agent_execution_permission:
raise HTTPException(status_code=404, detail="Agent execution permission not found")
return db_agent_execution_permission
|
Create a new agent execution permission.
Args:
agent_execution_permission : An instance of AgentExecutionPermission model as json.
Authorize (AuthJWT, optional): Authorization token, by default depends on the check_auth function.
Returns:
new_agent_execution_permission: A newly created agent execution permission instance.
|
def create_agent_execution_permission(
agent_execution_permission: AgentExecutionPermissionIn
, Authorize: AuthJWT = Depends(check_auth)):
"""
Create a new agent execution permission.
Args:
agent_execution_permission : An instance of AgentExecutionPermission model as json.
Authorize (AuthJWT, optional): Authorization token, by default depends on the check_auth function.
Returns:
new_agent_execution_permission: A newly created agent execution permission instance.
"""
new_agent_execution_permission = AgentExecutionPermission(**agent_execution_permission.dict())
db.session.add(new_agent_execution_permission)
db.session.commit()
return new_agent_execution_permission
|
Update an AgentExecutionPermission in the database.
Given an agent_execution_permission_id and the updated agent_execution_permission, this function updates the
corresponding AgentExecutionPermission in the database. If the AgentExecutionPermission is not found, an HTTPException
is raised.
Args:
agent_execution_permission_id (int): The ID of the AgentExecutionPermission to update.
agent_execution_permission : The updated AgentExecutionPermission object as json.
Authorize (AuthJWT, optional): Dependency to authenticate the user.
Returns:
db_agent_execution_permission (AgentExecutionPermission): The updated AgentExecutionPermission in the database.
Raises:
HTTPException: If the AgentExecutionPermission is not found in the database.
|
def update_agent_execution_permission(agent_execution_permission_id: int,
agent_execution_permission: AgentExecutionPermissionIn,
Authorize: AuthJWT = Depends(check_auth)):
"""
Update an AgentExecutionPermission in the database.
Given an agent_execution_permission_id and the updated agent_execution_permission, this function updates the
corresponding AgentExecutionPermission in the database. If the AgentExecutionPermission is not found, an HTTPException
is raised.
Args:
agent_execution_permission_id (int): The ID of the AgentExecutionPermission to update.
agent_execution_permission : The updated AgentExecutionPermission object as json.
Authorize (AuthJWT, optional): Dependency to authenticate the user.
Returns:
db_agent_execution_permission (AgentExecutionPermission): The updated AgentExecutionPermission in the database.
Raises:
HTTPException: If the AgentExecutionPermission is not found in the database.
"""
db_agent_execution_permission = db.session.query(AgentExecutionPermission).get(agent_execution_permission_id)
if not db_agent_execution_permission:
raise HTTPException(status_code=404, detail="Agent execution permission not found")
for key, value in agent_execution_permission.dict().items():
setattr(db_agent_execution_permission, key, value)
db.session.commit()
return db_agent_execution_permission
|
Update the execution permission status of an agent in the database.
This function updates the execution permission status of an agent in the database. The status can be
either "APPROVED" or "REJECTED". The function also updates the user feedback if provided,
commits the changes to the database, and enqueues the agent for execution.
:params:
- agent_execution_permission_id (int): The ID of the agent execution permission
- status (bool): The status of the agent execution permission, True for "APPROVED", False for "REJECTED"
- user_feedback (str): Optional user feedback on the status update
- Authorize (AuthJWT): Dependency function to check user authorization
:return:
- A dictionary containing a "success" key with the value True to indicate a successful update.
|
def update_agent_execution_permission_status(agent_execution_permission_id: int,
status: Annotated[bool, Body(embed=True)],
user_feedback: Annotated[str, Body(embed=True)] = "",
Authorize: AuthJWT = Depends(check_auth)):
"""
Update the execution permission status of an agent in the database.
This function updates the execution permission status of an agent in the database. The status can be
either "APPROVED" or "REJECTED". The function also updates the user feedback if provided,
commits the changes to the database, and enqueues the agent for execution.
:params:
- agent_execution_permission_id (int): The ID of the agent execution permission
- status (bool): The status of the agent execution permission, True for "APPROVED", False for "REJECTED"
- user_feedback (str): Optional user feedback on the status update
- Authorize (AuthJWT): Dependency function to check user authorization
:return:
- A dictionary containing a "success" key with the value True to indicate a successful update.
"""
agent_execution_permission = db.session.query(AgentExecutionPermission).get(agent_execution_permission_id)
print(agent_execution_permission)
if agent_execution_permission is None:
raise HTTPException(status_code=400, detail="Invalid Request")
if status is None:
raise HTTPException(status_code=400, detail="Invalid Request status is required")
agent_execution_permission.status = "APPROVED" if status else "REJECTED"
agent_execution_permission.user_feedback = user_feedback.strip() if len(user_feedback.strip()) > 0 else None
db.session.commit()
execute_agent.delay(agent_execution_permission.agent_execution_id, datetime.now())
return {"success": True}
|
Get the details of a specific agent template.
Args:
template_source (str): The source of the agent template ("local" or "marketplace").
agent_template_id (int): The ID of the agent template.
organisation (Depends): Dependency to get the user organisation.
Returns:
dict: The details of the agent template.
Raises:
HTTPException (status_code=404): If the agent template is not found.
|
def get_agent_template(template_source, agent_template_id: int, organisation=Depends(get_user_organisation)):
"""
Get the details of a specific agent template.
Args:
template_source (str): The source of the agent template ("local" or "marketplace").
agent_template_id (int): The ID of the agent template.
organisation (Depends): Dependency to get the user organisation.
Returns:
dict: The details of the agent template.
Raises:
HTTPException (status_code=404): If the agent template is not found.
"""
if template_source == "local":
db_agent_template = db.session.query(AgentTemplate).filter(AgentTemplate.organisation_id == organisation.id,
AgentTemplate.id == agent_template_id).first()
if not db_agent_template:
raise HTTPException(status_code=404, detail="Agent execution not found")
template = db_agent_template.to_dict()
configs = {}
agent_template_configs = db.session.query(AgentTemplateConfig).filter(
AgentTemplateConfig.agent_template_id == agent_template_id).all()
agent_workflow = AgentWorkflow.find_by_id(db_agent_template.agent_workflow_id)
for agent_template_config in agent_template_configs:
config_value = AgentTemplate.eval_agent_config(agent_template_config.key, agent_template_config.value)
configs[agent_template_config.key] = {"value": config_value}
template["configs"] = configs
template["agent_workflow_name"] = agent_workflow.name
else:
template = AgentTemplate.fetch_marketplace_detail(agent_template_id)
return template
|
Update the details of an agent template.
Args:
agent_template_id (int): The ID of the agent template to update.
updated_agent_configs (dict): The updated agent configurations.
organisation (Depends): Dependency to get the user organisation.
Returns:
HTTPException (status_code=200): If the agent gets successfully edited.
Raises:
HTTPException (status_code=404): If the agent template is not found.
|
def edit_agent_template(agent_template_id: int,
updated_agent_configs: dict,
organisation=Depends(get_user_organisation)):
"""
Update the details of an agent template.
Args:
agent_template_id (int): The ID of the agent template to update.
updated_agent_configs (dict): The updated agent configurations.
organisation (Depends): Dependency to get the user organisation.
Returns:
HTTPException (status_code=200): If the agent gets successfully edited.
Raises:
HTTPException (status_code=404): If the agent template is not found.
"""
db_agent_template = db.session.query(AgentTemplate).filter(AgentTemplate.organisation_id == organisation.id,
AgentTemplate.id == agent_template_id).first()
if db_agent_template is None:
raise HTTPException(status_code=404, detail="Agent Template not found")
agent_workflow = AgentWorkflow.find_by_name(db.session, updated_agent_configs["agent_configs"]["agent_workflow"])
db_agent_template.name = updated_agent_configs["name"]
db_agent_template.description = updated_agent_configs["description"]
db_agent_template.agent_workflow_id = agent_workflow.id
db.session.commit()
agent_config_values = updated_agent_configs.get('agent_configs', {})
for key, value in agent_config_values.items():
if isinstance(value, (list, dict)):
value = json.dumps(value)
config = db.session.query(AgentTemplateConfig).filter(
AgentTemplateConfig.agent_template_id == agent_template_id,
AgentTemplateConfig.key == key
).first()
if config is not None:
config.value = value
else:
new_config = AgentTemplateConfig(
agent_template_id=agent_template_id,
key=key,
value= value
)
db.session.add(new_config)
db.session.commit()
db.session.flush()
|
Save an agent as a template.
Args:
agent_id (str): The ID of the agent to save as a template.
agent_execution_id (str): The ID of the agent execution to save as a template.
organisation (Depends): Dependency to get the user organisation.
Returns:
dict: The saved agent template.
Raises:
HTTPException (status_code=404): If the agent or agent execution configurations are not found.
|
def save_agent_as_template(agent_execution_id: str,
agent_id: str,
organisation=Depends(get_user_organisation)):
"""
Save an agent as a template.
Args:
agent_id (str): The ID of the agent to save as a template.
agent_execution_id (str): The ID of the agent execution to save as a template.
organisation (Depends): Dependency to get the user organisation.
Returns:
dict: The saved agent template.
Raises:
HTTPException (status_code=404): If the agent or agent execution configurations are not found.
"""
if agent_execution_id == 'undefined':
raise HTTPException(status_code = 404, detail = "Agent Execution Id undefined")
if agent_id == 'undefined':
raise HTTPException(status_code = 404, detail = "Agent Id undefined")
agent = db.session.query(Agent).filter(Agent.id == agent_id).first()
if agent is None:
raise HTTPException(status_code=404, detail="Agent not found")
configs = None
if agent_execution_id == "-1":
configs = db.session.query(AgentConfiguration).filter(AgentConfiguration.agent_id == agent_id).all()
if not configs:
raise HTTPException(status_code=404, detail="Agent configurations not found")
else:
configs = db.session.query(AgentExecutionConfiguration).filter(AgentExecutionConfiguration.agent_execution_id == agent_execution_id).all()
if not configs:
raise HTTPException(status_code=404, detail="Agent execution configurations not found")
if configs is None:
raise HTTPException(status_code=404, detail="Configurations not found")
agent_template = AgentTemplate(name=agent.name, description=agent.description,
agent_workflow_id=agent.agent_workflow_id,
organisation_id=organisation.id)
db.session.add(agent_template)
db.session.commit()
for config in configs:
config_value = config.value
if config.key not in AgentTemplate.main_keys():
continue
if config.key == "tools":
config_value = str(Tool.convert_tool_ids_to_names(db, eval(config.value)))
agent_template_config = AgentTemplateConfig(agent_template_id=agent_template.id, key=config.key,
value=config_value)
db.session.add(agent_template_config)
db.session.commit()
db.session.flush()
return agent_template.to_dict()
|
List agent templates.
Args:
template_source (str, optional): The source of the templates ("local" or "marketplace"). Defaults to "local".
search_str (str, optional): The search string to filter templates. Defaults to "".
page (int, optional): The page number for paginated results. Defaults to 0.
organisation (Depends): Dependency to get the user organisation.
Returns:
list: A list of agent templates.
|
def list_agent_templates(template_source="local", search_str="", page=0, organisation=Depends(get_user_organisation)):
"""
List agent templates.
Args:
template_source (str, optional): The source of the templates ("local" or "marketplace"). Defaults to "local".
search_str (str, optional): The search string to filter templates. Defaults to "".
page (int, optional): The page number for paginated results. Defaults to 0.
organisation (Depends): Dependency to get the user organisation.
Returns:
list: A list of agent templates.
"""
output_json = []
if template_source == "local":
templates = db.session.query(AgentTemplate).filter(AgentTemplate.organisation_id == organisation.id).all()
for template in templates:
template.updated_at = template.updated_at.strftime('%d-%b-%Y').upper()
output_json.append(template)
else:
local_templates = db.session.query(AgentTemplate).filter(AgentTemplate.organisation_id == organisation.id,
AgentTemplate.marketplace_template_id != None).all()
local_templates_hash = {}
for local_template in local_templates:
local_templates_hash[local_template.marketplace_template_id] = True
print(local_templates_hash)
templates = AgentTemplate.fetch_marketplace_list(search_str, page)
print(templates)
for template in templates:
template["is_installed"] = local_templates_hash.get(template["id"], False)
template["organisation_id"] = organisation.id
output_json.append(template)
return output_json
|
Get all marketplace agent templates.
Args:
page (int, optional): The page number for paginated results. Defaults to 0.
Returns:
list: A list of marketplace agent templates.
|
def list_marketplace_templates(page=0):
"""
Get all marketplace agent templates.
Args:
page (int, optional): The page number for paginated results. Defaults to 0.
Returns:
list: A list of marketplace agent templates.
"""
organisation_id = int(get_config("MARKETPLACE_ORGANISATION_ID"))
page_size = 30
templates = db.session.query(AgentTemplate).filter(AgentTemplate.organisation_id == organisation_id).offset(
page * page_size).limit(page_size).all()
output_json = []
for template in templates:
template.updated_at = template.updated_at.strftime('%d-%b-%Y').upper()
output_json.append(template)
return output_json
|
Get marketplace template details.
Args:
agent_template_id (int): The ID of the marketplace agent template.
Returns:
dict: A dictionary containing the marketplace template details.
|
def marketplace_template_detail(agent_template_id):
"""
Get marketplace template details.
Args:
agent_template_id (int): The ID of the marketplace agent template.
Returns:
dict: A dictionary containing the marketplace template details.
"""
organisation_id = int(get_config("MARKETPLACE_ORGANISATION_ID"))
template = db.session.query(AgentTemplate).filter(AgentTemplate.organisation_id == organisation_id,
AgentTemplate.id == agent_template_id).first()
template_configs = db.session.query(AgentTemplateConfig).filter(
AgentTemplateConfig.agent_template_id == template.id).all()
workflow = db.session.query(AgentWorkflow).filter(AgentWorkflow.id == template.agent_workflow_id).first()
tool_configs = {}
for template_config in template_configs:
config_value = AgentTemplate.eval_agent_config(template_config.key, template_config.value)
tool_configs[template_config.key] = {"value": config_value}
output_json = {
"id": template.id,
"name": template.name,
"description": template.description,
"agent_workflow_id": template.agent_workflow_id,
"agent_workflow_name": workflow.name,
"configs": tool_configs
}
return output_json
|
Create a new agent with configurations.
Args:
agent_template_id (int): The ID of the agent template.
organisation: User's organisation.
Returns:
dict: A dictionary containing the details of the downloaded template.
|
def download_template(agent_template_id: int,
organisation=Depends(get_user_organisation)):
"""
Create a new agent with configurations.
Args:
agent_template_id (int): The ID of the agent template.
organisation: User's organisation.
Returns:
dict: A dictionary containing the details of the downloaded template.
"""
template = AgentTemplate.clone_agent_template_from_marketplace(db, organisation.id, agent_template_id)
return template.to_dict()
|
Fetches agent configuration from a template.
Args:
agent_template_id (int): The ID of the agent template.
organisation: User's organisation.
Returns:
dict: A dictionary containing the agent configuration fetched from the template.
Raises:
HTTPException: If the template is not found.
|
def fetch_agent_config_from_template(agent_template_id: int,
organisation=Depends(get_user_organisation)):
"""
Fetches agent configuration from a template.
Args:
agent_template_id (int): The ID of the agent template.
organisation: User's organisation.
Returns:
dict: A dictionary containing the agent configuration fetched from the template.
Raises:
HTTPException: If the template is not found.
"""
agent_template = db.session.query(AgentTemplate).filter(AgentTemplate.id == agent_template_id,
AgentTemplate.organisation_id == organisation.id).first()
if not agent_template:
raise HTTPException(status_code=404, detail="Template not found")
template_config = db.session.query(AgentTemplateConfig).filter(
AgentTemplateConfig.agent_template_id == agent_template_id).all()
template_config_dict = {}
main_keys = AgentTemplate.main_keys()
for config in template_config:
if config.key in main_keys:
template_config_dict[config.key] = AgentTemplate.eval_agent_config(config.key, config.value)
if "instruction" not in template_config_dict:
template_config_dict["instruction"] = []
if "constraints" not in template_config_dict:
template_config_dict["constraints"] = []
for key in main_keys:
if key not in template_config_dict:
template_config_dict[key] = ""
template_config_dict["agent_template_id"] = agent_template.id
agent_workflow = AgentWorkflow.find_by_id(db.session, agent_template.agent_workflow_id)
template_config_dict["agent_workflow"] = agent_workflow.name
return template_config_dict
|
Publish an agent execution as a template.
Args:
agent_execution_id (str): The ID of the agent execution to save as a template.
organisation (Depends): Dependency to get the user organisation.
user (Depends): Dependency to get the user.
Returns:
dict: The saved agent template.
Raises:
HTTPException (status_code=404): If the agent or agent execution configurations are not found.
|
def publish_template(agent_execution_id: str, organisation=Depends(get_user_organisation), user=Depends(get_current_user)):
"""
Publish an agent execution as a template.
Args:
agent_execution_id (str): The ID of the agent execution to save as a template.
organisation (Depends): Dependency to get the user organisation.
user (Depends): Dependency to get the user.
Returns:
dict: The saved agent template.
Raises:
HTTPException (status_code=404): If the agent or agent execution configurations are not found.
"""
if agent_execution_id == 'undefined':
raise HTTPException(status_code = 404, detail = "Agent Execution Id undefined")
agent_executions = AgentExecution.get_agent_execution_from_id(db.session, agent_execution_id)
if agent_executions is None:
raise HTTPException(status_code = 404, detail = "Agent Execution not found")
agent_id = agent_executions.agent_id
agent = db.session.query(Agent).filter(Agent.id == agent_id).first()
if agent is None:
raise HTTPException(status_code=404, detail="Agent not found")
agent_execution_configurations = db.session.query(AgentExecutionConfiguration).filter(AgentExecutionConfiguration.agent_execution_id == agent_execution_id).all()
if not agent_execution_configurations:
raise HTTPException(status_code=404, detail="Agent execution configurations not found")
agent_template = AgentTemplate(name=agent.name, description=agent.description,
agent_workflow_id=agent.agent_workflow_id,
organisation_id=organisation.id)
db.session.add(agent_template)
db.session.commit()
main_keys = AgentTemplate.main_keys()
for agent_execution_configuration in agent_execution_configurations:
config_value = agent_execution_configuration.value
if agent_execution_configuration.key not in main_keys:
continue
if agent_execution_configuration.key == "tools":
config_value = str(Tool.convert_tool_ids_to_names(db, eval(agent_execution_configuration.value)))
agent_template_config = AgentTemplateConfig(agent_template_id=agent_template.id, key=agent_execution_configuration.key,
value=config_value)
db.session.add(agent_template_config)
agent_template_configs = [
AgentTemplateConfig(agent_template_id=agent_template.id, key="status", value="UNDER REVIEW"),
AgentTemplateConfig(agent_template_id=agent_template.id, key="Contributor Name", value=user.name),
AgentTemplateConfig(agent_template_id=agent_template.id, key="Contributor Email", value=user.email)]
db.session.add_all(agent_template_configs)
db.session.commit()
db.session.flush()
return agent_template.to_dict()
|
Publish a template from edit template page.
Args:
organisation (Depends): Dependency to get the user organisation.
user (Depends): Dependency to get the user.
Returns:
dict: The saved agent template.
Raises:
HTTPException (status_code=404): If the agent template or workflow are not found.
|
def handle_publish_template(updated_details: AgentPublish, organisation=Depends(get_user_organisation), user=Depends(get_current_user)):
"""
Publish a template from edit template page.
Args:
organisation (Depends): Dependency to get the user organisation.
user (Depends): Dependency to get the user.
Returns:
dict: The saved agent template.
Raises:
HTTPException (status_code=404): If the agent template or workflow are not found.
"""
old_template_id = updated_details.agent_template_id
old_agent_template = db.session.query(AgentTemplate).filter(AgentTemplate.id==old_template_id, AgentTemplate.organisation_id==organisation.id).first()
if old_agent_template is None:
raise HTTPException(status_code = 404, detail = "Agent Template not found")
agent_workflow_id = old_agent_template.agent_workflow_id
if agent_workflow_id is None:
raise HTTPException(status_code = 404, detail = "Agent Workflow not found")
agent_template = AgentTemplate(name=updated_details.name, description=updated_details.description,
agent_workflow_id=agent_workflow_id,
organisation_id=organisation.id)
db.session.add(agent_template)
db.session.commit()
agent_template_configs = {
"goal": updated_details.goal,
"instruction": updated_details.instruction,
"constraints": updated_details.constraints,
"toolkits": updated_details.toolkits,
"exit": updated_details.exit,
"tools": updated_details.tools,
"iteration_interval": updated_details.iteration_interval,
"model": updated_details.model,
"permission_type": updated_details.permission_type,
"LTM_DB": updated_details.LTM_DB,
"max_iterations": updated_details.max_iterations,
"user_timezone": updated_details.user_timezone,
"knowledge": updated_details.knowledge
}
for key, value in agent_template_configs.items():
if key == "tools":
value = Tool.convert_tool_ids_to_names(db, value)
agent_template_config = AgentTemplateConfig(agent_template_id=agent_template.id, key=key, value=str(value))
db.session.add(agent_template_config)
agent_template_configs = [
AgentTemplateConfig(agent_template_id=agent_template.id, key="status", value="UNDER REVIEW"),
AgentTemplateConfig(agent_template_id=agent_template.id, key="Contributor Name", value=user.name),
AgentTemplateConfig(agent_template_id=agent_template.id, key="Contributor Email", value=user.email)]
db.session.add_all(agent_template_configs)
db.session.commit()
db.session.flush()
return agent_template.to_dict()
|
Lists agent workflows.
Args:
organisation: User's organisation.
Returns:
list: A list of dictionaries representing the agent workflows.
|
def list_workflows(organisation=Depends(get_user_organisation)):
"""
Lists agent workflows.
Args:
organisation: User's organisation.
Returns:
list: A list of dictionaries representing the agent workflows.
"""
workflows = db.session.query(AgentWorkflow).all()
output_json = []
for workflow in workflows:
output_json.append(workflow.to_dict())
return output_json
|
Get the total tokens, total calls, and the number of run completed.
Returns:
metrics: dictionary containing total tokens, total calls, and the number of runs completed.
|
def get_metrics(organisation=Depends(get_user_organisation)):
"""
Get the total tokens, total calls, and the number of run completed.
Returns:
metrics: dictionary containing total tokens, total calls, and the number of runs completed.
"""
try:
return AnalyticsHelper(session=db.session, organisation_id=organisation.id).calculate_run_completed_metrics()
except Exception as e:
logging.error(f"Error while calculating metrics: {str(e)}")
raise HTTPException(status_code=500, detail="Internal Server Error")
|
Create a new budget.
Args:
budget: Budget details.
Returns:
Budget: Created budget.
|
def create_budget(budget: BudgetIn,
Authorize: AuthJWT = Depends(check_auth)):
"""
Create a new budget.
Args:
budget: Budget details.
Returns:
Budget: Created budget.
"""
new_budget = Budget(
budget=budget.budget,
cycle=budget.cycle
)
db.session.add(new_budget)
db.session.commit()
return new_budget
|
Get a budget by budget_id.
Args:
budget_id: Budget ID.
Returns:
Budget: Retrieved budget.
|
def get_budget(budget_id: int,
Authorize: AuthJWT = Depends(check_auth)):
"""
Get a budget by budget_id.
Args:
budget_id: Budget ID.
Returns:
Budget: Retrieved budget.
"""
db_budget = db.session.query(Budget).filter(Budget.id == budget_id).first()
if not db_budget:
raise HTTPException(status_code=404, detail="budget not found")
return db_budget
|
Update budget details by budget_id.
Args:
budget_id: Budget ID.
budget: Updated budget details.
Returns:
Budget: Updated budget.
|
def update_budget(budget_id: int, budget: BudgetIn,
Authorize: AuthJWT = Depends(check_auth)):
"""
Update budget details by budget_id.
Args:
budget_id: Budget ID.
budget: Updated budget details.
Returns:
Budget: Updated budget.
"""
db_budget = db.session.query(Budget).filter(Budget.id == budget_id).first()
if not db_budget:
raise HTTPException(status_code=404, detail="budget not found")
db_budget.budget = budget.budget
db_budget.cycle = budget.cycle
db.session.commit()
return db_budget
|
Creates a new Organisation level config.
Args:
config (Configuration): Configuration details.
organisation_id (int): ID of the organisation.
Returns:
Configuration: Created configuration.
|
def create_config(config: ConfigurationIn, organisation_id: int,
Authorize: AuthJWT = Depends(check_auth)):
"""
Creates a new Organisation level config.
Args:
config (Configuration): Configuration details.
organisation_id (int): ID of the organisation.
Returns:
Configuration: Created configuration.
"""
db_organisation = db.session.query(Organisation).filter(Organisation.id == organisation_id).first()
if not db_organisation:
raise HTTPException(status_code=404, detail="Organisation not found")
existing_config = (
db.session.query(Configuration)
.filter(Configuration.organisation_id == organisation_id, Configuration.key == config.key)
.first()
)
# Encrypt the API key
if config.key == "model_api_key":
encrypted_value = encrypt_data(config.value)
config.value = encrypted_value
if existing_config:
existing_config.value = config.value
db.session.commit()
db.session.flush()
return existing_config
logger.info("NEW CONFIG")
new_config = Configuration(organisation_id=organisation_id, key=config.key, value=config.value)
logger.info(new_config)
logger.info("ORGANISATION ID : ", organisation_id)
db.session.add(new_config)
db.session.commit()
db.session.flush()
return new_config
|
Get a configuration by organisation ID and key.
Args:
organisation_id (int): ID of the organisation.
key (str): Key of the configuration.
Authorize (AuthJWT, optional): Authorization JWT token. Defaults to Depends(check_auth).
Returns:
Configuration: Retrieved configuration.
|
def get_config_by_organisation_id_and_key(organisation_id: int, key: str,
Authorize: AuthJWT = Depends(check_auth)):
"""
Get a configuration by organisation ID and key.
Args:
organisation_id (int): ID of the organisation.
key (str): Key of the configuration.
Authorize (AuthJWT, optional): Authorization JWT token. Defaults to Depends(check_auth).
Returns:
Configuration: Retrieved configuration.
"""
db_organisation = db.session.query(Organisation).filter(Organisation.id == organisation_id).first()
if not db_organisation:
raise HTTPException(status_code=404, detail="Organisation not found")
config = db.session.query(ModelsConfig).filter(ModelsConfig.org_id == organisation_id, ModelsConfig.provider == 'OpenAI').first()
if config is None:
api_key = get_config("OPENAI_API_KEY") or get_config("PALM_API_KEY")
if (api_key is not None and api_key != "YOUR_OPEN_API_KEY") or (
api_key is not None and api_key != "YOUR_PALM_API_KEY"):
encrypted_data = encrypt_data(api_key)
new_config = Configuration(organisation_id=organisation_id, key="model_api_key",value=encrypted_data)
db.session.add(new_config)
db.session.commit()
db.session.flush()
return new_config
return config
|
Get all configurations for a given organisation ID.
Args:
organisation_id (int): ID of the organisation.
Authorize (AuthJWT, optional): Authorization JWT token. Defaults to Depends(check_auth).
Returns:
List[Configuration]: List of configurations for the organisation.
|
def get_config_by_organisation_id(organisation_id: int,
Authorize: AuthJWT = Depends(check_auth)):
"""
Get all configurations for a given organisation ID.
Args:
organisation_id (int): ID of the organisation.
Authorize (AuthJWT, optional): Authorization JWT token. Defaults to Depends(check_auth).
Returns:
List[Configuration]: List of configurations for the organisation.
"""
db_organisation = db.session.query(Organisation).filter(Organisation.id == organisation_id).first()
if not db_organisation:
raise HTTPException(status_code=404, detail="Organisation not found")
configs = db.session.query(Configuration).filter(Configuration.organisation_id == organisation_id).all()
# Decrypt the API key if the key is "model_api_key"
for config in configs:
if config.key == "model_api_key":
decrypted_value = decrypt_data(config.value)
config.value = decrypted_value
return configs
|
Get the current environment.
Returns:
dict: Dictionary containing the current environment.
|
def current_env():
"""
Get the current environment.
Returns:
dict: Dictionary containing the current environment.
"""
env = get_config("ENV", "DEV")
return {
"env": env
}
|
Get Marketplace Knowledge list.
Args:
page (int, optional): The page number for pagination. Defaults to None.
Returns:
dict: The response containing the marketplace list.
|
def get_knowledge_list(
page: int = Query(None, title="Page Number"),
organisation = Depends(get_user_organisation)
):
"""
Get Marketplace Knowledge list.
Args:
page (int, optional): The page number for pagination. Defaults to None.
Returns:
dict: The response containing the marketplace list.
"""
if page < 0:
page = 0
marketplace_knowledges = Knowledges.fetch_marketplace_list(page)
marketplace_knowledges_with_install = Knowledges.get_knowledge_install_details(db.session, marketplace_knowledges, organisation)
for knowledge in marketplace_knowledges_with_install:
knowledge["install_number"] = MarketPlaceStats.get_knowledge_installation_number(knowledge["id"])
return marketplace_knowledges_with_install
|
Get Marketplace Model list.
Args:
page (int, optional): The page number for pagination. Defaults to None.
Returns:
dict: The response containing the marketplace list.
|
def get_models_list(page: int = 0, organisation=Depends(get_user_organisation)):
"""
Get Marketplace Model list.
Args:
page (int, optional): The page number for pagination. Defaults to None.
Returns:
dict: The response containing the marketplace list.
"""
if page < 0:
page = 0
marketplace_models = Models.fetch_marketplace_list(page)
marketplace_models_with_install = Models.get_model_install_details(db.session, marketplace_models, organisation.id)
return marketplace_models_with_install
|
Get Marketplace Model list.
Args:
page (int, optional): The page number for pagination. Defaults to None.
Returns:
dict: The response containing the marketplace list.
|
def get_models_details(page: int = 0):
"""
Get Marketplace Model list.
Args:
page (int, optional): The page number for pagination. Defaults to None.
Returns:
dict: The response containing the marketplace list.
"""
organisation_id = get_config("MARKETPLACE_ORGANISATION_ID")
if organisation_id is not None:
organisation_id = int(organisation_id)
if page < 0:
page = 0
marketplace_models = Models.fetch_marketplace_list(page)
marketplace_models_with_install = Models.get_model_install_details(db.session, marketplace_models, organisation_id,
ModelsTypes.MARKETPLACE.value)
return marketplace_models_with_install
|
Create a new organisation.
Args:
organisation: Organisation data.
Returns:
dict: Dictionary containing the created organisation.
Raises:
HTTPException (status_code=400): If there is an issue creating the organisation.
|
def create_organisation(organisation: OrganisationIn,
Authorize: AuthJWT = Depends(check_auth)):
"""
Create a new organisation.
Args:
organisation: Organisation data.
Returns:
dict: Dictionary containing the created organisation.
Raises:
HTTPException (status_code=400): If there is an issue creating the organisation.
"""
new_organisation = Organisation(
name=organisation.name,
description=organisation.description,
)
db.session.add(new_organisation)
db.session.commit()
db.session.flush()
register_toolkits(session=db.session, organisation=new_organisation)
logger.info(new_organisation)
return new_organisation
|
Get organisation details by organisation_id.
Args:
organisation_id: ID of the organisation.
Returns:
dict: Dictionary containing the organisation details.
Raises:
HTTPException (status_code=404): If the organisation with the specified ID is not found.
|
def get_organisation(organisation_id: int, Authorize: AuthJWT = Depends(check_auth)):
"""
Get organisation details by organisation_id.
Args:
organisation_id: ID of the organisation.
Returns:
dict: Dictionary containing the organisation details.
Raises:
HTTPException (status_code=404): If the organisation with the specified ID is not found.
"""
db_organisation = db.session.query(Organisation).filter(Organisation.id == organisation_id).first()
if not db_organisation:
raise HTTPException(status_code=404, detail="organisation not found")
return db_organisation
|
Update organisation details by organisation_id.
Args:
organisation_id: ID of the organisation.
organisation: Updated organisation data.
Returns:
dict: Dictionary containing the updated organisation details.
Raises:
HTTPException (status_code=404): If the organisation with the specified ID is not found.
|
def update_organisation(organisation_id: int, organisation: OrganisationIn,
Authorize: AuthJWT = Depends(check_auth)):
"""
Update organisation details by organisation_id.
Args:
organisation_id: ID of the organisation.
organisation: Updated organisation data.
Returns:
dict: Dictionary containing the updated organisation details.
Raises:
HTTPException (status_code=404): If the organisation with the specified ID is not found.
"""
db_organisation = db.session.query(Organisation).filter(Organisation.id == organisation_id).first()
if not db_organisation:
raise HTTPException(status_code=404, detail="Organisation not found")
db_organisation.name = organisation.name
db_organisation.description = organisation.description
db.session.commit()
return db_organisation
|
Get organisations associated with a user.If Organisation does not exists a new organisation is created
Args:
user_id: ID of the user.
Returns:
dict: Dictionary containing the organisation details.
Raises:
HTTPException (status_code=400): If the user with the specified ID is not found.
|
def get_organisations_by_user(user_id: int):
"""
Get organisations associated with a user.If Organisation does not exists a new organisation is created
Args:
user_id: ID of the user.
Returns:
dict: Dictionary containing the organisation details.
Raises:
HTTPException (status_code=400): If the user with the specified ID is not found.
"""
user = db.session.query(User).filter(User.id == user_id).first()
if user is None:
raise HTTPException(status_code=400,
detail="User not found")
organisation = Organisation.find_or_create_organisation(db.session, user)
Project.find_or_create_default_project(db.session, organisation.id)
return organisation
|
Get all the llm models associated with an organisation.
Args:
organisation: Organisation data.
|
def get_llm_models(organisation=Depends(get_user_organisation)):
"""
Get all the llm models associated with an organisation.
Args:
organisation: Organisation data.
"""
model_api_key = db.session.query(Configuration).filter(Configuration.organisation_id == organisation.id,
Configuration.key == "model_api_key").first()
model_source = db.session.query(Configuration).filter(Configuration.organisation_id == organisation.id,
Configuration.key == "model_source").first()
if model_api_key is None or model_source is None:
raise HTTPException(status_code=400,
detail="Organisation not found")
decrypted_api_key = decrypt_data(model_api_key.value)
model = build_model_with_api_key(model_source.value, decrypted_api_key)
models = model.get_models() if model is not None else []
return models
|
Get all the agent workflows
Args:
organisation: Organisation data.
|
def agent_workflows(organisation=Depends(get_user_organisation)):
"""
Get all the agent workflows
Args:
organisation: Organisation data.
"""
agent_workflows = db.session.query(AgentWorkflow).all()
workflows = [workflow.name for workflow in agent_workflows]
return workflows
|
Create a new project.
Args:
project (Project): Project data.
Returns:
dict: Dictionary containing the created project.
Raises:
HTTPException (status_code=404): If the organization with the specified ID is not found.
|
def create_project(project: ProjectIn,
Authorize: AuthJWT = Depends(check_auth)):
"""
Create a new project.
Args:
project (Project): Project data.
Returns:
dict: Dictionary containing the created project.
Raises:
HTTPException (status_code=404): If the organization with the specified ID is not found.
"""
logger.info("Organisation_id : ", project.organisation_id)
organisation = db.session.query(Organisation).get(project.organisation_id)
if not organisation:
raise HTTPException(status_code=404, detail="Organisation not found")
project = Project(
name=project.name,
organisation_id=organisation.id,
description=project.description
)
db.session.add(project)
db.session.commit()
return project
|
Get project details by project_id.
Args:
project_id (int): ID of the project.
Returns:
dict: Dictionary containing the project details.
Raises:
HTTPException (status_code=404): If the project with the specified ID is not found.
|
def get_project(project_id: int, Authorize: AuthJWT = Depends(check_auth)):
"""
Get project details by project_id.
Args:
project_id (int): ID of the project.
Returns:
dict: Dictionary containing the project details.
Raises:
HTTPException (status_code=404): If the project with the specified ID is not found.
"""
db_project = db.session.query(Project).filter(Project.id == project_id).first()
if not db_project:
raise HTTPException(status_code=404, detail="project not found")
return db_project
|
Update a project detail by project_id.
Args:
project_id (int): ID of the project.
project (Project): Updated project data.
Returns:
dict: Dictionary containing the updated project details.
Raises:
HTTPException (status_code=404): If the project with the specified ID is not found.
HTTPException (status_code=404): If the organization with the specified ID is not found.
|
def update_project(project_id: int, project: ProjectIn,
Authorize: AuthJWT = Depends(check_auth)):
"""
Update a project detail by project_id.
Args:
project_id (int): ID of the project.
project (Project): Updated project data.
Returns:
dict: Dictionary containing the updated project details.
Raises:
HTTPException (status_code=404): If the project with the specified ID is not found.
HTTPException (status_code=404): If the organization with the specified ID is not found.
"""
db_project = db.session.query(Project).get(project_id)
if not db_project:
raise HTTPException(status_code=404, detail="Project not found")
if project.organisation_id:
organisation = db.session.query(Organisation).get(project.organisation_id)
if not organisation:
raise HTTPException(status_code=404, detail="Organisation not found")
db_project.organisation_id = organisation.id
db_project.name = project.name
db_project.description = project.description
db.session.add(db_project)
db.session.commit()
return db_project
|
Get all projects by organisation_id and create default if no project.
Args:
organisation_id (int): ID of the organisation.
Returns:
List[Project]: List of projects belonging to the organisation.
Raises:
HTTPException (status_code=404): If the organization with the specified ID is not found.
|
def get_projects_organisation(organisation_id: int,
Authorize: AuthJWT = Depends(check_auth)):
"""
Get all projects by organisation_id and create default if no project.
Args:
organisation_id (int): ID of the organisation.
Returns:
List[Project]: List of projects belonging to the organisation.
Raises:
HTTPException (status_code=404): If the organization with the specified ID is not found.
"""
Project.find_or_create_default_project(db.session, organisation_id)
projects = db.session.query(Project).filter(Project.organisation_id == organisation_id).all()
if len(projects) <= 0:
default_project = Project.find_or_create_default_project(db.session, organisation_id)
projects.append(default_project)
return projects
|
Get all resources for an agent.
Args:
agent_id (int): ID of the agent.
Returns:
List[Resource]: List of resources belonging to the agent.
|
def get_all_resources(agent_id: int,
Authorize: AuthJWT = Depends(check_auth)):
"""
Get all resources for an agent.
Args:
agent_id (int): ID of the agent.
Returns:
List[Resource]: List of resources belonging to the agent.
"""
resources = db.session.query(Resource).filter(Resource.agent_id == agent_id).all()
return resources
|
Download a particular resource by resource_id.
Args:
resource_id (int): ID of the resource.
Authorize (AuthJWT, optional): Authorization dependency.
Returns:
StreamingResponse: Streaming response for downloading the resource.
Raises:
HTTPException (status_code=400): If the resource with the specified ID is not found.
HTTPException (status_code=404): If the file is not found.
|
def download_file_by_id(resource_id: int,
Authorize: AuthJWT = Depends(check_auth)):
"""
Download a particular resource by resource_id.
Args:
resource_id (int): ID of the resource.
Authorize (AuthJWT, optional): Authorization dependency.
Returns:
StreamingResponse: Streaming response for downloading the resource.
Raises:
HTTPException (status_code=400): If the resource with the specified ID is not found.
HTTPException (status_code=404): If the file is not found.
"""
resource = db.session.query(Resource).filter(Resource.id == resource_id).first()
download_file_path = resource.path
file_name = resource.name
if not resource:
raise HTTPException(status_code=400, detail="Resource Not found!")
if resource.storage_type == StorageType.S3.value:
bucket_name = get_config("BUCKET_NAME")
file_key = resource.path
response = s3.get_object(Bucket=bucket_name, Key=file_key)
content = response["Body"]
else:
abs_file_path = Path(download_file_path).resolve()
if not abs_file_path.is_file():
raise HTTPException(status_code=404, detail="File not found")
content = open(str(abs_file_path), "rb")
return StreamingResponse(
content,
media_type="application/octet-stream",
headers={
"Content-Disposition": f"attachment; filename={file_name}"
}
)
|
Create a new tool.
Args:
tool (ToolIn): Tool data.
Returns:
Tool: The created tool.
Raises:
HTTPException (status_code=400): If there is an issue creating the tool.
|
def create_tool(
tool: ToolIn,
Authorize: AuthJWT = Depends(check_auth),
):
"""
Create a new tool.
Args:
tool (ToolIn): Tool data.
Returns:
Tool: The created tool.
Raises:
HTTPException (status_code=400): If there is an issue creating the tool.
"""
db_tool = Tool(
name=tool.name,
folder_name=tool.folder_name,
class_name=tool.class_name,
file_name=tool.file_name,
)
db.session.add(db_tool)
db.session.commit()
return db_tool
|
Get a particular tool details.
Args:
tool_id (int): ID of the tool.
Returns:
Tool: The tool details.
Raises:
HTTPException (status_code=404): If the tool with the specified ID is not found.
|
def get_tool(
tool_id: int,
Authorize: AuthJWT = Depends(check_auth),
):
"""
Get a particular tool details.
Args:
tool_id (int): ID of the tool.
Returns:
Tool: The tool details.
Raises:
HTTPException (status_code=404): If the tool with the specified ID is not found.
"""
db_tool = db.session.query(Tool).filter(Tool.id == tool_id).first()
if not db_tool:
raise HTTPException(status_code=404, detail="Tool not found")
return db_tool
|
Get all tools
|
def get_tools(
organisation: Organisation = Depends(get_user_organisation)):
"""Get all tools"""
toolkits = db.session.query(Toolkit).filter(Toolkit.organisation_id == organisation.id).all()
tools = []
for toolkit in toolkits:
db_tools = db.session.query(Tool).filter(Tool.toolkit_id == toolkit.id).all()
tools.extend(db_tools)
return tools
|
Update a particular tool.
Args:
tool_id (int): ID of the tool.
tool (ToolIn): Updated tool data.
Returns:
Tool: The updated tool details.
Raises:
HTTPException (status_code=404): If the tool with the specified ID is not found.
|
def update_tool(
tool_id: int,
tool: ToolIn,
Authorize: AuthJWT = Depends(check_auth),
):
"""
Update a particular tool.
Args:
tool_id (int): ID of the tool.
tool (ToolIn): Updated tool data.
Returns:
Tool: The updated tool details.
Raises:
HTTPException (status_code=404): If the tool with the specified ID is not found.
"""
db_tool = db.session.query(Tool).filter(Tool.id == tool_id).first()
if not db_tool:
raise HTTPException(status_code=404, detail="Tool not found")
db_tool.name = tool.name
db_tool.folder_name = tool.folder_name
db_tool.class_name = tool.class_name
db_tool.file_name = tool.file_name
db.session.add(db_tool)
db.session.commit()
return db_tool
|
Get marketplace tool kits.
Args:
page (int): The page number for pagination.
Returns:
list: A list of tool kits in the marketplace.
|
def get_marketplace_toolkits(
page: int = 0,
):
"""
Get marketplace tool kits.
Args:
page (int): The page number for pagination.
Returns:
list: A list of tool kits in the marketplace.
"""
organisation_id = int(get_config("MARKETPLACE_ORGANISATION_ID"))
page_size = 30
# Apply search filter if provided
query = db.session.query(Toolkit).filter(Toolkit.organisation_id == organisation_id)
# Paginate the results
toolkits = query.offset(page * page_size).limit(page_size).all()
# Fetch tools for each tool kit
for toolkit in toolkits:
toolkit.tools = db.session.query(Tool).filter(Tool.toolkit_id == toolkit.id).all()
toolkit.updated_at = toolkit.updated_at.strftime('%d-%b-%Y').upper()
return toolkits
|
Get tool kit details from the marketplace.
Args:
toolkit_name (str): The name of the tool kit.
Returns:
Toolkit: The tool kit details from the marketplace.
|
def get_marketplace_toolkit_detail(toolkit_name: str):
"""
Get tool kit details from the marketplace.
Args:
toolkit_name (str): The name of the tool kit.
Returns:
Toolkit: The tool kit details from the marketplace.
"""
organisation_id = int(get_config("MARKETPLACE_ORGANISATION_ID"))
toolkit = db.session.query(Toolkit).filter(Toolkit.organisation_id == organisation_id,
Toolkit.name == toolkit_name).first()
toolkit.tools = db.session.query(Tool).filter(Tool.toolkit_id == toolkit.id).all()
toolkit.configs = db.session.query(ToolConfig).filter(ToolConfig.toolkit_id == toolkit.id).all()
for tool_configs in toolkit.configs:
if is_encrypted(tool_configs.value):
tool_configs.value = decrypt_data(tool_configs.value)
return toolkit
|
Get tool kit readme from the marketplace.
Args:
toolkit_name (str): The name of the tool kit.
Returns:
str: The content of the tool kit's readme file.
Raises:
HTTPException (status_code=404): If the specified tool kit is not found.
|
def get_marketplace_toolkit_readme(toolkit_name: str):
"""
Get tool kit readme from the marketplace.
Args:
toolkit_name (str): The name of the tool kit.
Returns:
str: The content of the tool kit's readme file.
Raises:
HTTPException (status_code=404): If the specified tool kit is not found.
"""
organisation_id = int(get_config("MARKETPLACE_ORGANISATION_ID"))
toolkit = db.session.query(Toolkit).filter(Toolkit.name == toolkit_name,
Toolkit.organisation_id == organisation_id).first()
if not toolkit:
raise HTTPException(status_code=404, detail='ToolKit not found')
return get_readme_content_from_code_link(toolkit.tool_code_link)
|
Get tools of a specific tool kit from the marketplace.
Args:
toolkit_name (str): The name of the tool kit.
Returns:
Tool: The tools associated with the tool kit.
Raises:
HTTPException (status_code=404): If the specified tool kit is not found.
|
def get_marketplace_toolkit_tools(toolkit_name: str):
"""
Get tools of a specific tool kit from the marketplace.
Args:
toolkit_name (str): The name of the tool kit.
Returns:
Tool: The tools associated with the tool kit.
Raises:
HTTPException (status_code=404): If the specified tool kit is not found.
"""
organisation_id = int(get_config("MARKETPLACE_ORGANISATION_ID"))
toolkit = db.session.query(Toolkit).filter(Toolkit.name == toolkit_name,
Toolkit.organisation_id == organisation_id).first()
if not toolkit:
raise HTTPException(status_code=404, detail="ToolKit not found")
tools = db.session.query(Tool).filter(Tool.toolkit_id == toolkit.id).first()
return tools
|
Download and install a tool kit from the marketplace.
Args:
toolkit_name (str): The name of the tool kit.
organisation (Organisation): The user's organisation.
Returns:
dict: A message indicating the successful installation of the tool kit.
|
def install_toolkit_from_marketplace(toolkit_name: str,
organisation: Organisation = Depends(get_user_organisation)):
"""
Download and install a tool kit from the marketplace.
Args:
toolkit_name (str): The name of the tool kit.
organisation (Organisation): The user's organisation.
Returns:
dict: A message indicating the successful installation of the tool kit.
"""
# Check if the tool kit exists
toolkit = Toolkit.fetch_marketplace_detail(search_str="details",
toolkit_name=toolkit_name)
db_toolkit = Toolkit.add_or_update(session=db.session, name=toolkit['name'], description=toolkit['description'],
tool_code_link=toolkit['tool_code_link'], organisation_id=organisation.id,
show_toolkit=toolkit['show_toolkit'])
for tool in toolkit['tools']:
Tool.add_or_update(session=db.session, tool_name=tool['name'], description=tool['description'],
folder_name=tool['folder_name'], class_name=tool['class_name'], file_name=tool['file_name'],
toolkit_id=db_toolkit.id)
for config in toolkit['configs']:
ToolConfig.add_or_update(session=db.session, toolkit_id=db_toolkit.id, key=config['key'], value=config['value'], key_type = config['key_type'], is_secret = config['is_secret'], is_required = config['is_required'])
return {"message": "ToolKit installed successfully"}
|
Get details of a locally installed tool kit by its name, including the details of its tools.
Args:
toolkit_name (str): The name of the tool kit.
organisation (Organisation): The user's organisation.
Returns:
Toolkit: The tool kit object with its associated tools.
Raises:
HTTPException (status_code=404): If the specified tool kit is not found.
|
def get_installed_toolkit_details(toolkit_name: str,
organisation: Organisation = Depends(get_user_organisation)):
"""
Get details of a locally installed tool kit by its name, including the details of its tools.
Args:
toolkit_name (str): The name of the tool kit.
organisation (Organisation): The user's organisation.
Returns:
Toolkit: The tool kit object with its associated tools.
Raises:
HTTPException (status_code=404): If the specified tool kit is not found.
"""
# Fetch the tool kit by its ID
toolkit = db.session.query(Toolkit).filter(Toolkit.name == toolkit_name,
Organisation.id == organisation.id).first()
if not toolkit:
# Return an appropriate response if the tool kit doesn't exist
raise HTTPException(status_code=404, detail='ToolKit not found')
# Fetch the tools associated with the tool kit
tools = db.session.query(Tool).filter(Tool.toolkit_id == toolkit.id).all()
# Add the tools to the tool kit object
toolkit.tools = tools
# readme_content = get_readme(toolkit.tool_code_link)
return toolkit
|
Install a tool locally from a GitHub link.
Args:
github_link_request (GitHubLinkRequest): The GitHub link request object.
organisation (Organisation): The user's organisation.
Returns:
None
Raises:
HTTPException (status_code=400): If the GitHub link is invalid.
|
def download_and_install_tool(github_link_request: GitHubLinkRequest = Body(...),
organisation: Organisation = Depends(get_user_organisation)):
"""
Install a tool locally from a GitHub link.
Args:
github_link_request (GitHubLinkRequest): The GitHub link request object.
organisation (Organisation): The user's organisation.
Returns:
None
Raises:
HTTPException (status_code=400): If the GitHub link is invalid.
"""
github_link = github_link_request.github_link
if not GithubHelper.validate_github_link(github_link):
raise HTTPException(status_code=400, detail="Invalid Github link")
# download_folder = get_config("TOOLS_DIR")
# download_tool(github_link, download_folder)
# process_files(download_folder, db.session, organisation, code_link=github_link)
add_tool_to_json(github_link)
|
Get the readme content of a toolkit.
Args:
toolkit_name (str): The name of the toolkit.
organisation (Organisation): The user's organisation.
Returns:
str: The readme content of the toolkit.
Raises:
HTTPException (status_code=404): If the toolkit is not found.
|
def get_installed_toolkit_readme(toolkit_name: str, organisation: Organisation = Depends(get_user_organisation)):
"""
Get the readme content of a toolkit.
Args:
toolkit_name (str): The name of the toolkit.
organisation (Organisation): The user's organisation.
Returns:
str: The readme content of the toolkit.
Raises:
HTTPException (status_code=404): If the toolkit is not found.
"""
toolkit = db.session.query(Toolkit).filter(Toolkit.name == toolkit_name,
Organisation.id == organisation.id).first()
if not toolkit:
raise HTTPException(status_code=404, detail='ToolKit not found')
readme_content = get_readme_content_from_code_link(toolkit.tool_code_link)
return readme_content
|
Handle marketplace operations.
Args:
search_str (str, optional): The search string to filter toolkits. Defaults to None.
toolkit_name (str, optional): The name of the toolkit. Defaults to None.
Returns:
dict: The response containing the marketplace details.
|
def handle_marketplace_operations(
search_str: str = Query(None, title="Search String"),
toolkit_name: str = Query(None, title="Tool Kit Name")
):
"""
Handle marketplace operations.
Args:
search_str (str, optional): The search string to filter toolkits. Defaults to None.
toolkit_name (str, optional): The name of the toolkit. Defaults to None.
Returns:
dict: The response containing the marketplace details.
"""
response = Toolkit.fetch_marketplace_detail(search_str, toolkit_name)
return response
|
Handle marketplace operation list.
Args:
page (int, optional): The page number for pagination. Defaults to None.
Returns:
dict: The response containing the marketplace list.
|
def handle_marketplace_operations_list(
page: int = Query(None, title="Page Number"),
organisation: Organisation = Depends(get_user_organisation)
):
"""
Handle marketplace operation list.
Args:
page (int, optional): The page number for pagination. Defaults to None.
Returns:
dict: The response containing the marketplace list.
"""
marketplace_toolkits = Toolkit.fetch_marketplace_list(page=page)
marketplace_toolkits_with_install = Toolkit.get_toolkit_installed_details(db.session, marketplace_toolkits,
organisation)
return marketplace_toolkits_with_install
|
Get the list of installed tool kits.
Args:
organisation (Organisation): The organisation associated with the tool kits.
Returns:
list: The list of installed tool kits.
|
def get_installed_toolkit_list(organisation: Organisation = Depends(get_user_organisation)):
"""
Get the list of installed tool kits.
Args:
organisation (Organisation): The organisation associated with the tool kits.
Returns:
list: The list of installed tool kits.
"""
toolkits = db.session.query(Toolkit).filter(Toolkit.organisation_id == organisation.id).all()
for toolkit in toolkits:
toolkit_tools = db.session.query(Tool).filter(Tool.toolkit_id == toolkit.id).all()
toolkit.tools = toolkit_tools
return toolkits
|
Check if there is an update available for the installed tool kits.
Returns:
dict: The response containing the update details.
|
def check_toolkit_update(toolkit_name: str, organisation: Organisation = Depends(get_user_organisation)):
"""
Check if there is an update available for the installed tool kits.
Returns:
dict: The response containing the update details.
"""
marketplace_toolkit = Toolkit.fetch_marketplace_detail(search_str="details",
toolkit_name=toolkit_name)
if marketplace_toolkit is None:
raise HTTPException(status_code=404, detail="Toolkit not found in marketplace")
installed_toolkit = Toolkit.get_toolkit_from_name(db.session, toolkit_name, organisation)
if installed_toolkit is None:
return True
installed_toolkit = installed_toolkit.to_dict()
tools = Tool.get_toolkit_tools(db.session, installed_toolkit["id"])
configs = ToolConfig.get_toolkit_tool_config(db.session, installed_toolkit["id"])
installed_toolkit["configs"] = []
installed_toolkit["tools"] = []
for config in configs:
installed_toolkit["configs"].append(config.to_dict())
for tool in tools:
installed_toolkit["tools"].append(tool.to_dict())
return compare_toolkit(marketplace_toolkit, installed_toolkit)
|
Update the toolkit with the latest version from the marketplace.
|
def update_toolkit(toolkit_name: str, organisation: Organisation = Depends(get_user_organisation)):
"""
Update the toolkit with the latest version from the marketplace.
"""
marketplace_toolkit = Toolkit.fetch_marketplace_detail(search_str="details",
toolkit_name=toolkit_name)
update_toolkit = Toolkit.add_or_update(
db.session,
name=marketplace_toolkit["name"],
description=marketplace_toolkit["description"],
show_toolkit=True if len(marketplace_toolkit["tools"]) > 1 else False,
organisation_id=organisation.id,
tool_code_link=marketplace_toolkit["tool_code_link"]
)
for tool in marketplace_toolkit["tools"]:
Tool.add_or_update(db.session, tool_name=tool["name"], folder_name=tool["folder_name"],
class_name=tool["class_name"], file_name=tool["file_name"],
toolkit_id=update_toolkit.id, description=tool["description"])
for tool_config_key in marketplace_toolkit["configs"]:
ToolConfig.add_or_update(db.session, toolkit_id=update_toolkit.id, key=tool_config_key["key"], key_type = tool_config_key['key_type'], is_secret = tool_config_key['is_secret'], is_required = tool_config_key['is_required'])
|
Update tool configurations for a specific tool kit.
Args:
toolkit_name (str): The name of the tool kit.
configs (list): A list of dictionaries containing the tool configurations.
Each dictionary should have the following keys:
- "key" (str): The key of the configuration.
- "value" (str): The new value for the configuration.
Returns:
dict: A dictionary with the message "Tool configs updated successfully".
Raises:
HTTPException (status_code=404): If the specified tool kit is not found.
HTTPException (status_code=500): If an unexpected error occurs during the update process.
|
def update_tool_config(toolkit_name: str, configs: list, organisation: Organisation = Depends(get_user_organisation)):
"""
Update tool configurations for a specific tool kit.
Args:
toolkit_name (str): The name of the tool kit.
configs (list): A list of dictionaries containing the tool configurations.
Each dictionary should have the following keys:
- "key" (str): The key of the configuration.
- "value" (str): The new value for the configuration.
Returns:
dict: A dictionary with the message "Tool configs updated successfully".
Raises:
HTTPException (status_code=404): If the specified tool kit is not found.
HTTPException (status_code=500): If an unexpected error occurs during the update process.
"""
try:
# Check if the tool kit exists
toolkit = Toolkit.get_toolkit_from_name(db.session, toolkit_name,organisation)
if toolkit is None:
raise HTTPException(status_code=404, detail="Tool kit not found")
# Update existing tool configs
for config in configs:
key = config.get("key")
value = config.get("value")
if value is None:
continue
if key is not None:
tool_config = db.session.query(ToolConfig).filter_by(toolkit_id=toolkit.id, key=key).first()
if tool_config:
if tool_config.key_type == ToolConfigKeyType.FILE.value:
value = json.dumps(value)
# Update existing tool config
# added encryption
tool_config.value = encrypt_data(value)
db.session.commit()
return {"message": "Tool configs updated successfully"}
except Exception as e:
# db.session.rollback()
raise HTTPException(status_code=500, detail=str(e))
|
Create or update tool configurations for a specific tool kit.
Args:
toolkit_name (str): The name of the tool kit.
tool_configs (list): A list of tool configuration objects.
Returns:
Toolkit: The updated tool kit object.
Raises:
HTTPException (status_code=404): If the specified tool kit is not found.
|
def create_or_update_tool_config(toolkit_name: str, tool_configs,
Authorize: AuthJWT = Depends(check_auth)):
"""
Create or update tool configurations for a specific tool kit.
Args:
toolkit_name (str): The name of the tool kit.
tool_configs (list): A list of tool configuration objects.
Returns:
Toolkit: The updated tool kit object.
Raises:
HTTPException (status_code=404): If the specified tool kit is not found.
"""
toolkit = db.session.query(Toolkit).filter_by(name=toolkit_name).first()
if not toolkit:
raise HTTPException(status_code=404, detail='ToolKit not found')
# Iterate over the tool_configs list
for tool_config in tool_configs:
existing_tool_config = db.session.query(ToolConfig).filter(
ToolConfig.toolkit_id == toolkit.id,
ToolConfig.key == tool_config.key
).first()
if existing_tool_config.value:
# Update the existing tool config
if existing_tool_config.key_type == ToolConfigKeyType.FILE.value:
existing_tool_config.value = json.dumps(existing_tool_config.value)
existing_tool_config.value = encrypt_data(tool_config.value)
else:
# Create a new tool config
new_tool_config = ToolConfig(key=tool_config.key, value=encrypt_data(tool_config.value), toolkit_id=toolkit.id)
db.session.add(new_tool_config)
db.session.commit()
db.session.refresh(toolkit)
return toolkit
|
Get all tool configurations by Tool Kit Name.
Args:
toolkit_name (str): The name of the tool kit.
organisation (Organisation): The organization associated with the user.
Returns:
list: A list of tool configurations for the specified tool kit.
Raises:
HTTPException (status_code=404): If the specified tool kit is not found.
HTTPException (status_code=403): If the user is not authorized to access the tool kit.
|
def get_all_tool_configs(toolkit_name: str, organisation: Organisation = Depends(get_user_organisation)):
"""
Get all tool configurations by Tool Kit Name.
Args:
toolkit_name (str): The name of the tool kit.
organisation (Organisation): The organization associated with the user.
Returns:
list: A list of tool configurations for the specified tool kit.
Raises:
HTTPException (status_code=404): If the specified tool kit is not found.
HTTPException (status_code=403): If the user is not authorized to access the tool kit.
"""
toolkit = db.session.query(Toolkit).filter(Toolkit.name == toolkit_name,
Toolkit.organisation_id == organisation.id).first()
if not toolkit:
raise HTTPException(status_code=404, detail='ToolKit not found')
tool_configs = db.session.query(ToolConfig).filter(ToolConfig.toolkit_id == toolkit.id).all()
for tool_config in tool_configs:
if tool_config.value:
if(is_encrypted(tool_config.value)):
tool_config.value = decrypt_data(tool_config.value)
if tool_config.key_type == ToolConfigKeyType.FILE.value:
tool_config.value = json.loads(tool_config.value)
return tool_configs
|
Get a specific tool configuration by tool kit name and key.
Args:
toolkit_name (str): The name of the tool kit.
key (str): The key of the tool configuration.
organisation (Organisation): The organization associated with the user.
Returns:
ToolConfig: The tool configuration with the specified key.
Raises:
HTTPException (status_code=403): If the user is not authorized to access the tool kit.
HTTPException (status_code=404): If the specified tool kit or tool configuration is not found.
|
def get_tool_config(toolkit_name: str, key: str, organisation: Organisation = Depends(get_user_organisation)):
"""
Get a specific tool configuration by tool kit name and key.
Args:
toolkit_name (str): The name of the tool kit.
key (str): The key of the tool configuration.
organisation (Organisation): The organization associated with the user.
Returns:
ToolConfig: The tool configuration with the specified key.
Raises:
HTTPException (status_code=403): If the user is not authorized to access the tool kit.
HTTPException (status_code=404): If the specified tool kit or tool configuration is not found.
"""
user_toolkits = db.session.query(Toolkit).filter(Toolkit.organisation_id == organisation.id).all()
toolkit = db.session.query(Toolkit).filter_by(name=toolkit_name)
if toolkit not in user_toolkits:
raise HTTPException(status_code=403, detail='Unauthorized')
tool_config = db.session.query(ToolConfig).filter(
ToolConfig.toolkit_id == toolkit.id,
ToolConfig.key == key
).first()
if not tool_config:
raise HTTPException(status_code=404, detail="Tool configuration not found")
if(is_encrypted(tool_config.value)):
tool_config.value = decrypt_data(tool_config.value)
if tool_config.key_type == ToolConfigKeyType.FILE.value:
tool_config.value = json.loads(tool_config.value)
return tool_config
|
Create a new user.
Args:
user (UserIn): User data.
Returns:
User: The created user.
Raises:
HTTPException (status_code=400): If there is an issue creating the user.
|
def create_user(user: UserIn,
Authorize: AuthJWT = Depends(check_auth)):
"""
Create a new user.
Args:
user (UserIn): User data.
Returns:
User: The created user.
Raises:
HTTPException (status_code=400): If there is an issue creating the user.
"""
db_user = db.session.query(User).filter(User.email == user.email).first()
if db_user:
return db_user
db_user = User(name=user.name, email=user.email, password=user.password, organisation_id=user.organisation_id)
db.session.add(db_user)
db.session.commit()
db.session.flush()
organisation = Organisation.find_or_create_organisation(db.session, db_user)
Project.find_or_create_default_project(db.session, organisation.id)
logger.info("User created", db_user)
#adding local llm configuration
ModelsConfig.add_llm_config(db.session, organisation.id)
return db_user
|
Get a particular user details.
Args:
user_id (int): ID of the user.
Returns:
User: The user details.
Raises:
HTTPException (status_code=404): If the user with the specified ID is not found.
|
def get_user(user_id: int,
Authorize: AuthJWT = Depends(check_auth)):
"""
Get a particular user details.
Args:
user_id (int): ID of the user.
Returns:
User: The user details.
Raises:
HTTPException (status_code=404): If the user with the specified ID is not found.
"""
# Authorize.jwt_required()
db_user = db.session.query(User).filter(User.id == user_id).first()
if not db_user:
raise HTTPException(status_code=404, detail="User not found")
return db_user
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.