From f83a4cd2f58def5184767403e61ed5d355f063b2 Mon Sep 17 00:00:00 2001 From: Rounak Bhatia Date: Thu, 3 Aug 2023 15:00:04 +0530 Subject: [PATCH 01/11] Edit agent feature --- superagi/controllers/agent.py | 99 +++++---------- superagi/controllers/agent_execution.py | 74 ++++++++++- .../controllers/agent_execution_config.py | 116 ++++++++++++++---- .../types/agent_execution_config.py | 32 +++++ superagi/models/agent.py | 5 +- superagi/models/agent_config.py | 52 ++++++++ 6 files changed, 283 insertions(+), 95 deletions(-) create mode 100644 superagi/controllers/types/agent_execution_config.py diff --git a/superagi/controllers/agent.py b/superagi/controllers/agent.py index aa4056895..a05d80096 100644 --- a/superagi/controllers/agent.py +++ b/superagi/controllers/agent.py @@ -1,11 +1,13 @@ import json from datetime import datetime - +from typing import Union, List from fastapi import APIRouter from fastapi import HTTPException, Depends from fastapi_jwt_auth import AuthJWT from fastapi_sqlalchemy import db from pydantic import BaseModel +from sqlalchemy import desc +import ast from jsonmerge import merge from pytz import timezone @@ -193,6 +195,7 @@ def create_agent_with_config(agent_with_config: AgentConfigInput, 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, @@ -201,13 +204,26 @@ def create_agent_with_config(agent_with_config: AgentConfigInput, db_agent = Agent.create_agent_with_config(db, agent_with_config) start_step_id = AgentWorkflow.fetch_trigger_step_id(db.session, db_agent.agent_workflow_id) + # Creating an execution with RUNNING status execution = AgentExecution(status='CREATED', last_execution_time=datetime.now(), agent_id=db_agent.id, name="New Run", current_step_id=start_step_id) agent_execution_configs = { "goal": agent_with_config.goal, - "instruction": agent_with_config.instruction + "instruction": agent_with_config.instruction, + "agent_type": agent_with_config.agent_type, + "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() @@ -215,13 +231,17 @@ def create_agent_with_config(agent_with_config: AgentConfigInput, 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() + 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, + + 'agent_execution_name': execution.name}, 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) # execute_agent.delay(execution.id, datetime.now()) @@ -236,6 +256,7 @@ def create_agent_with_config(agent_with_config: AgentConfigInput, } + @router.post("/schedule", status_code=201) def create_and_schedule_agent(agent_config_schedule: AgentConfigSchedule, Authorize: AuthJWT = Depends(check_auth)): @@ -259,6 +280,7 @@ def create_and_schedule_agent(agent_config_schedule: AgentConfigSchedule, 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, @@ -305,6 +327,7 @@ def create_and_schedule_agent(agent_config_schedule: AgentConfigSchedule, } + @router.post("/stop/schedule", status_code=200) def stop_schedule(agent_id: int, Authorize: AuthJWT = Depends(check_auth)): """ @@ -341,8 +364,8 @@ def edit_schedule(schedule: AgentScheduleInput, 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() + 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") @@ -421,7 +444,7 @@ def get_agents_by_project_id(project_id: int, if not project: raise HTTPException(status_code=404, detail="Project not found") - agents = db.session.query(Agent).filter(Agent.project_id == project_id, or_(Agent.is_deleted == False, Agent.is_deleted is None)).all() + 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: @@ -437,8 +460,8 @@ def get_agents_by_project_id(project_id: int, 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 + is_scheduled = db.session.query(AgentSchedule).filter_by(agent_id=agent_id, status="SCHEDULED").first() is not None + new_agent = { **agent_dict, @@ -450,62 +473,6 @@ def get_agents_by_project_id(project_id: int, return new_agents_sorted -@router.get("/get/details/{agent_id}") -def get_agent_configuration(agent_id: int, - Authorize: AuthJWT = Depends(check_auth)): - """ - Get the agent configuration using the agent ID. - - Args: - agent_id (int): Identifier of the agent. - 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. - """ - - # Define the agent_config keys to fetch - keys_to_fetch = AgentTemplate.main_keys() - agent = db.session.query(Agent).filter(agent_id == Agent.id,or_(Agent.is_deleted == False, Agent.is_deleted is None)).first() - - if not agent: - raise HTTPException(status_code=404, detail="Agent not found") - - # Query the AgentConfiguration table for the specified keys - results = db.session.query(AgentConfiguration).filter(AgentConfiguration.key.in_(keys_to_fetch), - AgentConfiguration.agent_id == agent_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() - - name = "" - # Construct the JSON response - response = {result.key: result.value for result in results} - if 'knowledge' in response.keys() and response['knowledge'] != 'None': - knowledge = db.session.query(Knowledges).filter(Knowledges.id == response['knowledge']).first() - name = knowledge.name if knowledge is not None else "" - response = merge(response, {"name": agent.name, "description": agent.description, - # Query the AgentConfiguration table for the speci - "goal": eval(response["goal"]), - "instruction": eval(response.get("instruction", '[]')), - "knowledge_name": name, - "calls": total_calls, - "tokens": total_tokens, - "constraints": eval(response.get("constraints")), - "tools": [int(x) for x in json.loads(response["tools"])]}) - tools = db.session.query(Tool).filter(Tool.id.in_(response["tools"])).all() - response["tools"] = tools - - # Close the session - db.session.close() - - return response - - @router.put("/delete/{agent_id}", status_code=200) def delete_agent(agent_id: int, Authorize: AuthJWT = Depends(check_auth)): """ @@ -542,4 +509,4 @@ def delete_agent(agent_id: int, Authorize: AuthJWT = Depends(check_auth)): # Updating the schedule status to STOPPED db_agent_schedule.status = "STOPPED" - db.session.commit() + db.session.commit() \ No newline at end of file diff --git a/superagi/controllers/agent_execution.py b/superagi/controllers/agent_execution.py index 646f426bf..2754bfbb8 100644 --- a/superagi/controllers/agent_execution.py +++ b/superagi/controllers/agent_execution.py @@ -1,11 +1,12 @@ from datetime import datetime -from typing import Optional +from typing import Optional, Union, List from fastapi_sqlalchemy import db from fastapi import HTTPException, Depends from fastapi_jwt_auth import AuthJWT from pydantic import BaseModel from pydantic.fields import List +from superagi.controllers.types.agent_execution_config import AgentRunIn from superagi.helper.time_helper import get_time_difference from superagi.models.agent_execution_config import AgentExecutionConfiguration @@ -18,8 +19,9 @@ from sqlalchemy import desc from superagi.helper.auth import check_auth from superagi.controllers.types.agent_schedule import AgentScheduleInput -# from superagi.types.db import AgentExecutionOut, AgentExecutionIn from superagi.apm.event_handler import EventHandler +from superagi.controllers.tool import ToolOut +from superagi.models.agent_config import AgentConfiguration router = APIRouter() @@ -40,7 +42,6 @@ class AgentExecutionOut(BaseModel): class Config: orm_mode = True - class AgentExecutionIn(BaseModel): status: Optional[str] name: Optional[str] @@ -53,9 +54,10 @@ class AgentExecutionIn(BaseModel): goal: Optional[List[str]] instruction: Optional[List[str]] - class Config: + class config: orm_mode = True + # CRUD Operations @router.post("/add", response_model=AgentExecutionOut, status_code=201) def create_agent_execution(agent_execution: AgentExecutionIn, @@ -102,6 +104,68 @@ def create_agent_execution(agent_execution: AgentExecutionIn, return db_agent_execution +@router.post("/add_run", status_code = 201) +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. + """ + #Update the agent configurations table with the data of the latest agent execution and returns -1 if agent id not found. + if((AgentConfiguration.update_agent_configurations_table(session=db.session, agent_id=agent_execution.agent_id, updated_details=agent_execution))==-1): + raise HTTPException(status_code=404, detail="Agent ID 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_id = AgentWorkflow.fetch_trigger_step_id(db.session, agent.agent_workflow_id) + + db_agent_execution = AgentExecution(status = "RUNNING", last_execution_time = datetime.now(), + agent_id = agent_execution.agent_id, name = agent_execution.name, num_of_calls = 0, + num_of_tokens = 0, + current_step_id = start_step_id) + agent_execution_configs = { + "goal": agent_execution.goal, + "instruction": agent_execution.instruction, + "agent_type": agent_execution.agent_type, + "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() + + 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) + + if db_agent_execution.status == "RUNNING": + execute_agent.delay(db_agent_execution.id, datetime.now()) + + return db_agent_execution + @router.post("/schedule", status_code=201) def schedule_existing_agent(agent_schedule: AgentScheduleInput, @@ -277,4 +341,4 @@ def get_agent_by_latest_execution(project_id: int, "id": agent.id, "status": isRunning, "contentType": "Agents" - } + } \ No newline at end of file diff --git a/superagi/controllers/agent_execution_config.py b/superagi/controllers/agent_execution_config.py index 985bbb4b3..15e5150f9 100644 --- a/superagi/controllers/agent_execution_config.py +++ b/superagi/controllers/agent_execution_config.py @@ -1,48 +1,120 @@ import ast +import json from fastapi import APIRouter from fastapi import HTTPException, Depends from fastapi_jwt_auth import AuthJWT from fastapi_sqlalchemy import db from typing import Optional, Union +from sqlalchemy import func, or_ +from sqlalchemy import desc from superagi.helper.auth import check_auth +from superagi.models.agent import Agent from superagi.models.agent_config import AgentConfiguration from superagi.models.agent_execution import AgentExecution from superagi.models.agent_execution_config import AgentExecutionConfiguration +from superagi.models.tool import Tool +from superagi.models.knowledges import Knowledges + router = APIRouter() -@router.get("/details/agent/{agent_id}/agent_execution/{agent_execution_id}") -def get_agent_execution_configuration(agent_id : int, - agent_execution_id: Optional[Union[int, None]] = None, +@router.get("/details/agent_id/{agent_id}/agent_execution_id/{agent_execution_id}") +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 execution configuration using the agent execution ID. + Get the agent configuration using the agent ID and the agent execution ID. Args: - agent_execution_id (int): Identifier of the agent. + 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 Execution configuration including its details. + dict: Agent configuration including its details. Raises: - HTTPException (status_code=404): If the agent is not found. + 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. """ - if agent_execution_id > 0: - agent_execution_config = db.session.query(AgentExecutionConfiguration).filter( - AgentExecutionConfiguration.agent_execution_id == agent_execution_id - ).all() - if agent_execution_config: - return {result.key: eval(result.value) for result in agent_execution_config} - - agent_execution = db.session.query(AgentExecution).filter(AgentExecution.id == agent_execution_id).first() - if not agent_execution: - raise HTTPException(status_code=404, detail="Agent Configuration not found") - keys_to_fetch = ["goal", "instruction"] - agent_configuration = db.session.query(AgentConfiguration).filter(AgentConfiguration.key.in_(keys_to_fetch), - AgentConfiguration.agent_id == agent_id).all() - - return {result.key: ast.literal_eval(result.value) for result in agent_configuration} + + # Check + if type(agent_id) == None or type(agent_id) == str: + raise HTTPException(status_code = 404, detail = "Agent Id undefined") + if type(agent_execution_id) == None or type(agent_execution_id) == str: + raise HTTPException(status_code = 404, detail = "Agent Execution Id undefined") + + #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_id = db.session.query(AgentExecution).filter(AgentExecution.agent_id == agent_id).order_by(desc(AgentExecution.created_at)).first().id + + + #Fetch agent id from agent execution id and check whether the agent_id received is correct or not. + 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") + + # 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") + + # 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() + 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() + + + results_agent_dict = {result.key: result.value for result in results_agent} + results_agent_execution_dict = {result.key: result.value for result in results_agent_execution} + + for key, value in results_agent_execution_dict.items(): + if key in results_agent_dict and value is not None: + results_agent_dict[key] = value + + # Construct the response + results_agent_dict['goal'] = json.loads(results_agent_dict['goal'].replace("'", '"')) + + if "toolkits" in results_agent_dict: + results_agent_dict["toolkits"] = list(ast.literal_eval(results_agent_dict["toolkits"])) + + results_agent_dict["tools"] = list(ast.literal_eval(results_agent_dict["tools"])) + tools = db.session.query(Tool).filter(Tool.id.in_(results_agent_dict["tools"])).all() + results_agent_dict["tools"] = tools + + results_agent_dict['instruction'] = json.loads(results_agent_dict['instruction'].replace("'", '"')) + + constraints_str = results_agent_dict["constraints"] + constraints_list = eval(constraints_str) + results_agent_dict["constraints"] = constraints_list + + results_agent_dict["name"] = agent.name + results_agent_dict["description"] = agent.description + results_agent_dict["calls"] = total_calls + results_agent_dict["tokens"] = total_tokens + + knowledge_name = "" + if 'knowledge' in results_agent_dict and results_agent_dict['knowledge'] != 'None': + if type(results_agent_dict['knowledge'])==int: + results_agent_dict['knowledge'] = int(results_agent_dict['knowledge']) + knowledge = db.session.query(Knowledges).filter(Knowledges.id == results_agent_dict['knowledge']).first() + knowledge_name = knowledge.name if knowledge is not None else "" + results_agent_dict['knowledge_name'] = knowledge_name + + response = results_agent_dict + + # Close the session + db.session.close() + + return response \ No newline at end of file diff --git a/superagi/controllers/types/agent_execution_config.py b/superagi/controllers/types/agent_execution_config.py new file mode 100644 index 000000000..a0e8a0f39 --- /dev/null +++ b/superagi/controllers/types/agent_execution_config.py @@ -0,0 +1,32 @@ +import datetime +from typing import List, Optional +from pydantic import BaseModel +from datetime import datetime + + +class AgentRunIn(BaseModel): + status: Optional[str] + name: Optional[str] + agent_id: Optional[int] + last_execution_time: Optional[datetime] + num_of_calls: Optional[int] + num_of_tokens: Optional[int] + current_step_id: Optional[int] + permission_id: Optional[int] + goal: Optional[List[str]] + instruction: Optional[List[str]] + agent_type: str + constraints: List[str] + toolkits: List[int] + tools: List[int] + exit: str + iteration_interval: int + model: str + permission_type: str + LTM_DB: str + max_iterations: int + user_timezone: Optional[str] + knowledge: Optional[int] + + class Config: + orm_mode = True \ No newline at end of file diff --git a/superagi/models/agent.py b/superagi/models/agent.py index f979e2442..0a69ef1c1 100644 --- a/superagi/models/agent.py +++ b/superagi/models/agent.py @@ -1,4 +1,5 @@ from __future__ import annotations +import ast import json @@ -113,7 +114,7 @@ def eval_agent_config(cls, key, value): elif key in ["goal", "constraints", "instruction", "is_deleted"]: return eval(value) elif key == "tools": - return [int(x) for x in json.loads(value)] + return list(ast.literal_eval(value)) @classmethod def create_agent_with_config(cls, db, agent_with_config): @@ -273,4 +274,4 @@ def get_agent_from_id(cls, session, agent_id): Returns: Agent: Agent object is returned. """ - return session.query(Agent).filter(Agent.id == agent_id).first() + return session.query(Agent).filter(Agent.id == agent_id).first() \ No newline at end of file diff --git a/superagi/models/agent_config.py b/superagi/models/agent_config.py index cd7d230e1..51afd6485 100644 --- a/superagi/models/agent_config.py +++ b/superagi/models/agent_config.py @@ -1,8 +1,10 @@ from fastapi import HTTPException from sqlalchemy import Column, Integer, Text, String +from typing import Union from superagi.models.base_model import DBBaseModel from superagi.models.tool import Tool +from superagi.controllers.types.agent_execution_config import AgentRunIn class AgentConfiguration(DBBaseModel): @@ -32,3 +34,53 @@ def __repr__(self): """ return f"AgentConfiguration(id={self.id}, key={self.key}, value={self.value})" + + @classmethod + def update_agent_configurations_table(cls, session, agent_id: Union[int, None], updated_details: AgentRunIn): + + if(type(agent_id)==None): + return -1; + + updated_details_dict = updated_details.dict() + + # Fetch existing 'toolkits' agent configuration for the given agent_id + agent_toolkits_config = session.query(AgentConfiguration).filter( + AgentConfiguration.agent_id == agent_id, + AgentConfiguration.key == 'toolkits' + ).first() + + if agent_toolkits_config: + agent_toolkits_config.value = updated_details_dict['toolkits'] + else: + agent_toolkits_config = AgentConfiguration( + agent_id=agent_id, + key='toolkits', + value=updated_details_dict['toolkits'] + ) + session.add(agent_toolkits_config) + + #Fetch existing knowledge for the given agent id and update it accordingly + knowledge_config = session.query(AgentConfiguration).filter( + AgentConfiguration.agent_id == agent_id, + AgentConfiguration.key == 'knowledge' + ).first() + + if knowledge_config: + knowledge_config.value = updated_details_dict['knowledge'] + else: + knowledge_config = AgentConfiguration( + agent_id=agent_id, + key='knowledge', + value=updated_details_dict['knowledge'] + ) + session.add(knowledge_config) + + # Fetch agent configurations + agent_configs = session.query(AgentConfiguration).filter(AgentConfiguration.agent_id == agent_id).all() + for agent_config in agent_configs: + key = agent_config.key + if key in updated_details_dict: + agent_config.value = updated_details_dict[key] + + # Commit the changes to the database + session.commit() \ No newline at end of file From f812899b1a1208aea47cee56b2b3d50bfec30a64 Mon Sep 17 00:00:00 2001 From: Rounak Bhatia Date: Thu, 3 Aug 2023 16:00:41 +0530 Subject: [PATCH 02/11] Edit agent feature --- superagi/controllers/agent_execution_config.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/superagi/controllers/agent_execution_config.py b/superagi/controllers/agent_execution_config.py index 15e5150f9..473976a9e 100644 --- a/superagi/controllers/agent_execution_config.py +++ b/superagi/controllers/agent_execution_config.py @@ -48,11 +48,15 @@ def get_agent_execution_configuration(agent_id : Union[int, None, str], if type(agent_execution_id) == None or type(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_id = db.session.query(AgentExecution).filter(AgentExecution.agent_id == agent_id).order_by(desc(AgentExecution.created_at)).first().id - #Fetch agent id from agent execution id and check whether the agent_id received is correct or not. agent_execution_config = AgentExecution.get_agent_execution_from_id(db.session, agent_execution_id) if agent_execution_config is None: @@ -61,11 +65,6 @@ def get_agent_execution_configuration(agent_id : Union[int, None, str], if agent_id != agent_id_from_execution_id: raise HTTPException(status_code = 404, detail = "Wrong agent id") - # 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") - # 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() results_agent_execution = db.session.query(AgentExecutionConfiguration).filter(AgentExecutionConfiguration.agent_execution_id == agent_execution_id).all() From 86993b6a8903eaee720f5027f370a04fed1ee8b6 Mon Sep 17 00:00:00 2001 From: Rounak Bhatia Date: Fri, 4 Aug 2023 15:44:20 +0530 Subject: [PATCH 03/11] Edit agent feature --- superagi/controllers/agent_execution.py | 9 ++++----- superagi/controllers/agent_execution_config.py | 4 ++-- superagi/models/agent_config.py | 3 --- 3 files changed, 6 insertions(+), 10 deletions(-) diff --git a/superagi/controllers/agent_execution.py b/superagi/controllers/agent_execution.py index 2754bfbb8..10f1dd7d1 100644 --- a/superagi/controllers/agent_execution.py +++ b/superagi/controllers/agent_execution.py @@ -119,14 +119,13 @@ def create_agent_run(agent_execution: AgentRunIn, Authorize: AuthJWT = Depends(c Raises: HTTPException (Status Code=404): If the agent is not found. """ - #Update the agent configurations table with the data of the latest agent execution and returns -1 if agent id not found. - if((AgentConfiguration.update_agent_configurations_table(session=db.session, agent_id=agent_execution.agent_id, updated_details=agent_execution))==-1): - raise HTTPException(status_code=404, detail="Agent ID 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_id = AgentWorkflow.fetch_trigger_step_id(db.session, agent.agent_workflow_id) db_agent_execution = AgentExecution(status = "RUNNING", last_execution_time = datetime.now(), diff --git a/superagi/controllers/agent_execution_config.py b/superagi/controllers/agent_execution_config.py index 473976a9e..329ae8487 100644 --- a/superagi/controllers/agent_execution_config.py +++ b/superagi/controllers/agent_execution_config.py @@ -43,9 +43,9 @@ def get_agent_execution_configuration(agent_id : Union[int, None, str], """ # Check - if type(agent_id) == None or type(agent_id) == str: + if isinstance(agent_id, str): raise HTTPException(status_code = 404, detail = "Agent Id undefined") - if type(agent_execution_id) == None or type(agent_execution_id) == str: + if isinstance(agent_execution_id, str): raise HTTPException(status_code = 404, detail = "Agent Execution Id undefined") # Define the agent_config keys to fetch diff --git a/superagi/models/agent_config.py b/superagi/models/agent_config.py index 51afd6485..bd84a4d41 100644 --- a/superagi/models/agent_config.py +++ b/superagi/models/agent_config.py @@ -38,9 +38,6 @@ def __repr__(self): @classmethod def update_agent_configurations_table(cls, session, agent_id: Union[int, None], updated_details: AgentRunIn): - if(type(agent_id)==None): - return -1; - updated_details_dict = updated_details.dict() # Fetch existing 'toolkits' agent configuration for the given agent_id From dc8073eb175ea925eb048df9f6a37c957a190f08 Mon Sep 17 00:00:00 2001 From: Rounak Bhatia Date: Sat, 5 Aug 2023 12:18:48 +0530 Subject: [PATCH 04/11] Edit agent feature --- .../controllers/agent_execution_config.py | 23 +++++---- .../test_agent_execution_config.py | 49 ++++++++++--------- 2 files changed, 39 insertions(+), 33 deletions(-) diff --git a/superagi/controllers/agent_execution_config.py b/superagi/controllers/agent_execution_config.py index 329ae8487..5c3c8c5ac 100644 --- a/superagi/controllers/agent_execution_config.py +++ b/superagi/controllers/agent_execution_config.py @@ -83,20 +83,23 @@ def get_agent_execution_configuration(agent_id : Union[int, None, str], results_agent_dict[key] = value # Construct the response - results_agent_dict['goal'] = json.loads(results_agent_dict['goal'].replace("'", '"')) + if 'goal' in results_agent_dict: + results_agent_dict['goal'] = json.loads(results_agent_dict['goal'].replace("'", '"')) if "toolkits" in results_agent_dict: results_agent_dict["toolkits"] = list(ast.literal_eval(results_agent_dict["toolkits"])) - results_agent_dict["tools"] = list(ast.literal_eval(results_agent_dict["tools"])) - tools = db.session.query(Tool).filter(Tool.id.in_(results_agent_dict["tools"])).all() - results_agent_dict["tools"] = tools - - results_agent_dict['instruction'] = json.loads(results_agent_dict['instruction'].replace("'", '"')) - - constraints_str = results_agent_dict["constraints"] - constraints_list = eval(constraints_str) - results_agent_dict["constraints"] = constraints_list + if 'tools' in results_agent_dict: + results_agent_dict["tools"] = list(ast.literal_eval(results_agent_dict["tools"])) + tools = db.session.query(Tool).filter(Tool.id.in_(results_agent_dict["tools"])).all() + results_agent_dict["tools"] = tools + if 'instruction' in results_agent_dict: + results_agent_dict['instruction'] = json.loads(results_agent_dict['instruction'].replace("'", '"')) + + if 'constraints' in results_agent_dict: + constraints_str = results_agent_dict["constraints"] + constraints_list = eval(constraints_str) + results_agent_dict["constraints"] = constraints_list results_agent_dict["name"] = agent.name results_agent_dict["description"] = agent.description diff --git a/tests/unit_tests/controllers/test_agent_execution_config.py b/tests/unit_tests/controllers/test_agent_execution_config.py index f4fe59009..89e1533d5 100644 --- a/tests/unit_tests/controllers/test_agent_execution_config.py +++ b/tests/unit_tests/controllers/test_agent_execution_config.py @@ -4,46 +4,49 @@ from fastapi.testclient import TestClient from main import app +from superagi.models.agent import Agent +from superagi.models.agent_config import AgentConfiguration from superagi.models.agent_execution import AgentExecution from superagi.models.agent_execution_config import AgentExecutionConfiguration client = TestClient(app) - @pytest.fixture def mocks(): # Mock tool kit data for testing - mock_execution_config = [AgentExecutionConfiguration(id=1, key="test_key", value="['test']")] - mock_execution = AgentExecution(id=1,name="test_execution") - return mock_execution,mock_execution_config - - -def test_get_agent_execution_configuration_success(mocks): - with patch('superagi.controllers.agent_execution_config.db') as mock_db: - _,mock_execution_config = mocks - mock_db.session.query.return_value.filter.return_value.all.return_value = mock_execution_config - - response = client.get("/agent_executions_configs/details/agent/1/agent_execution/1") - - assert response.status_code == 200 - assert response.json() == {"test_key": ['test']} + mock_agent = Agent(id=1, name="test_agent", project_id=1, description="testing", agent_workflow_id=1, is_deleted=False) + mock_agent_config = AgentConfiguration(id=1, agent_id=1, key="test_key", value="['test']") + mock_execution = AgentExecution(id=54, agent_id=1, name="test_execution") + mock_execution_config = [AgentExecutionConfiguration(id=64, agent_execution_id=1, key="test_key", value="['test']")] + return mock_agent,mock_agent_config,mock_execution,mock_execution_config def test_get_agent_execution_configuration_not_found_failure(): with patch('superagi.controllers.agent_execution_config.db') as mock_db: mock_db.session.query.return_value.filter.return_value.all.return_value = [] mock_db.session.query.return_value.filter.return_value.first.return_value = None - response = client.get("/agent_executions_configs/details/agent/1/agent_execution/1") + response = client.get("/agent_executions_configs/details/agent_id/1/agent_execution_id/1") assert response.status_code == 404 - assert response.json() == {"detail": "Agent Configuration not found"} + assert response.json() == {"detail": "Agent not found"} -def test_get_agent_execution_configuration_not_found_success(mocks): +def test_get_agent_execution_configuration_success(mocks): with patch('superagi.controllers.agent_execution_config.db') as mock_db: - mock_execution,mock_execution_config = mocks - mock_db.session.query.return_value.filter.return_value.all.side_effect = [[], mock_execution_config] - mock_db.session.query.return_value.filter.return_value.first.return_value = mock_execution - response = client.get("/agent_executions_configs/details/agent/1/agent_execution/1") + mock_agent, mock_agent_config, mock_execution, mock_execution_config = mocks + + # Configure the mock objects to return the mock values + mock_db.session.query.return_value.filter.return_value.first.return_value = mock_agent + mock_db.session.query.return_value.filter.return_value.all.return_value = [mock_agent_config] + mock_db.session.query.return_value.filter.return_value.order_by.return_value.first.return_value = mock_execution + mock_db.session.query.return_value.filter.return_value.all.return_value = mock_execution_config + + # Mock the AgentExecution.get_agent_execution_from_id method to return the mock_execution object + with patch('superagi.controllers.agent_execution_config.AgentExecution.get_agent_execution_from_id') as mock_get_exec: + mock_get_exec.return_value = mock_execution + + response = client.get("/agent_executions_configs/details/agent_id/1/agent_execution_id/1") + + assert response.status_code == 200 + - assert response.status_code == 200 From 5298c5b58ae72053536d2b46be417c873e09c107 Mon Sep 17 00:00:00 2001 From: Rounak Bhatia Date: Sun, 6 Aug 2023 15:46:16 +0530 Subject: [PATCH 05/11] Edit agent feature --- superagi/models/agent_config.py | 5 ++-- .../test_update_agent_config_table.py | 28 +++++++++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) create mode 100644 tests/unit_tests/controllers/test_update_agent_config_table.py diff --git a/superagi/models/agent_config.py b/superagi/models/agent_config.py index bd84a4d41..8440ce3af 100644 --- a/superagi/models/agent_config.py +++ b/superagi/models/agent_config.py @@ -75,9 +75,8 @@ def update_agent_configurations_table(cls, session, agent_id: Union[int, None], # Fetch agent configurations agent_configs = session.query(AgentConfiguration).filter(AgentConfiguration.agent_id == agent_id).all() for agent_config in agent_configs: - key = agent_config.key - if key in updated_details_dict: - agent_config.value = updated_details_dict[key] + if agent_config.key in updated_details_dict: + agent_config.value = updated_details_dict[agent_config.key] # Commit the changes to the database session.commit() \ No newline at end of file diff --git a/tests/unit_tests/controllers/test_update_agent_config_table.py b/tests/unit_tests/controllers/test_update_agent_config_table.py new file mode 100644 index 000000000..5bc6fd35b --- /dev/null +++ b/tests/unit_tests/controllers/test_update_agent_config_table.py @@ -0,0 +1,28 @@ +import unittest +from unittest.mock import MagicMock, call +from superagi.models.agent_config import AgentConfiguration +from superagi.controllers.types.agent_execution_config import AgentRunIn + +class TestAgentConfigurationsUpdate(unittest.TestCase): + + def setUp(self): + self.mock_session = MagicMock() + self.mock_session.query().filter().first.return_value = None + + self.added_configurations = [] + self.mock_session.add.side_effect = lambda config: self.added_configurations.append(config) + + def test_update_toolkits_config(self): + updated_details = AgentRunIn(agent_type="test", constraints=["c1", "c2"], toolkits=[1, 2], tools=[1, 2, 3], exit="exit", iteration_interval=1, model="test", permission_type="p", LTM_DB="LTM", max_iterations=100) + + AgentConfiguration.update_agent_configurations_table(self.mock_session, 1, updated_details) + + added_config = self.added_configurations[0] + + self.assertEqual(added_config.agent_id, 1) + self.assertEqual(added_config.key, 'toolkits') + self.assertEqual(added_config.value, [1, 2]) + self.assertEqual(self.added_configurations[1].agent_id, 1) + self.assertEqual(self.added_configurations[1].key, 'knowledge') + self.assertEqual(self.added_configurations[1].value, None) + self.mock_session.commit.assert_called_once() From 8d5963144a80c30067178cb5d591f1fda365e98c Mon Sep 17 00:00:00 2001 From: Rounak Bhatia Date: Mon, 7 Aug 2023 13:30:55 +0530 Subject: [PATCH 06/11] Edit agent feature --- superagi/models/agent_config.py | 4 +- .../test_update_agent_config_table.py | 41 ++++++++++--------- tests/unit_tests/models/test_agent.py | 15 +++++-- 3 files changed, 36 insertions(+), 24 deletions(-) diff --git a/superagi/models/agent_config.py b/superagi/models/agent_config.py index 8440ce3af..5c5ba4db0 100644 --- a/superagi/models/agent_config.py +++ b/superagi/models/agent_config.py @@ -79,4 +79,6 @@ def update_agent_configurations_table(cls, session, agent_id: Union[int, None], agent_config.value = updated_details_dict[agent_config.key] # Commit the changes to the database - session.commit() \ No newline at end of file + session.commit() + + return "Details updated successfully" \ No newline at end of file diff --git a/tests/unit_tests/controllers/test_update_agent_config_table.py b/tests/unit_tests/controllers/test_update_agent_config_table.py index 5bc6fd35b..7f00b1c91 100644 --- a/tests/unit_tests/controllers/test_update_agent_config_table.py +++ b/tests/unit_tests/controllers/test_update_agent_config_table.py @@ -1,28 +1,31 @@ -import unittest -from unittest.mock import MagicMock, call +import pytest +from unittest.mock import patch, Mock from superagi.models.agent_config import AgentConfiguration from superagi.controllers.types.agent_execution_config import AgentRunIn -class TestAgentConfigurationsUpdate(unittest.TestCase): +def test_update_existing_toolkits(): + agent_id = 1 + updated_details = AgentRunIn( + agent_type="test", constraints=["c1", "c2"], toolkits=[1, 2], + tools=[1, 2, 3], exit="exit", iteration_interval=1, + model="test", permission_type="p", LTM_DB="LTM", max_iterations=100 + ) - def setUp(self): - self.mock_session = MagicMock() - self.mock_session.query().filter().first.return_value = None + # Mock AgentConfiguration instance for the agent_configs list + existing_toolkits_config = Mock(spec=AgentConfiguration) + existing_toolkits_config.key = "toolkits" + existing_toolkits_config.value = [3, 4] - self.added_configurations = [] - self.mock_session.add.side_effect = lambda config: self.added_configurations.append(config) + agent_configs = [existing_toolkits_config] - def test_update_toolkits_config(self): - updated_details = AgentRunIn(agent_type="test", constraints=["c1", "c2"], toolkits=[1, 2], tools=[1, 2, 3], exit="exit", iteration_interval=1, model="test", permission_type="p", LTM_DB="LTM", max_iterations=100) + mock_session = Mock() - AgentConfiguration.update_agent_configurations_table(self.mock_session, 1, updated_details) + # Mock the query filter behavior for existing configurations + mock_session.query().filter().all.return_value = agent_configs - added_config = self.added_configurations[0] + result = AgentConfiguration.update_agent_configurations_table(mock_session, agent_id, updated_details) - self.assertEqual(added_config.agent_id, 1) - self.assertEqual(added_config.key, 'toolkits') - self.assertEqual(added_config.value, [1, 2]) - self.assertEqual(self.added_configurations[1].agent_id, 1) - self.assertEqual(self.added_configurations[1].key, 'knowledge') - self.assertEqual(self.added_configurations[1].value, None) - self.mock_session.commit.assert_called_once() + #Check whether the value gets updated or not + assert existing_toolkits_config.value == [1, 2] + assert mock_session.commit.called_once() + assert result == "Details updated successfully" diff --git a/tests/unit_tests/models/test_agent.py b/tests/unit_tests/models/test_agent.py index 4a6c6b934..da7e6c4c1 100644 --- a/tests/unit_tests/models/test_agent.py +++ b/tests/unit_tests/models/test_agent.py @@ -1,10 +1,8 @@ from unittest.mock import create_autospec - from sqlalchemy.orm import Session - from superagi.models.agent import Agent - - +from unittest.mock import patch + def test_get_agent_from_id(): # Create a mock session session = create_autospec(Session) @@ -23,3 +21,12 @@ def test_get_agent_from_id(): # Assert that the returned agent object matches the mock agent assert agent == mock_agent + +def test_eval_tools_key(): + key = "tools" + value = "[1, 2, 3]" + + result = Agent.eval_agent_config(key, value) + + assert result == [1, 2, 3] + From 5846c7e4788b9c403635513dfb4b8c81439fc9b5 Mon Sep 17 00:00:00 2001 From: Rounak Bhatia Date: Mon, 7 Aug 2023 13:52:23 +0530 Subject: [PATCH 07/11] Edit agent feature --- .../controllers/agent_execution_config.py | 42 +--------------- superagi/models/agent_execution_config.py | 49 +++++++++++++++++++ 2 files changed, 50 insertions(+), 41 deletions(-) diff --git a/superagi/controllers/agent_execution_config.py b/superagi/controllers/agent_execution_config.py index 5c3c8c5ac..31ca022c1 100644 --- a/superagi/controllers/agent_execution_config.py +++ b/superagi/controllers/agent_execution_config.py @@ -74,47 +74,7 @@ def get_agent_execution_configuration(agent_id : Union[int, None, str], total_tokens = db.session.query(func.sum(AgentExecution.num_of_tokens)).filter( AgentExecution.agent_id == agent_id).scalar() - - results_agent_dict = {result.key: result.value for result in results_agent} - results_agent_execution_dict = {result.key: result.value for result in results_agent_execution} - - for key, value in results_agent_execution_dict.items(): - if key in results_agent_dict and value is not None: - results_agent_dict[key] = value - - # Construct the response - if 'goal' in results_agent_dict: - results_agent_dict['goal'] = json.loads(results_agent_dict['goal'].replace("'", '"')) - - if "toolkits" in results_agent_dict: - results_agent_dict["toolkits"] = list(ast.literal_eval(results_agent_dict["toolkits"])) - - if 'tools' in results_agent_dict: - results_agent_dict["tools"] = list(ast.literal_eval(results_agent_dict["tools"])) - tools = db.session.query(Tool).filter(Tool.id.in_(results_agent_dict["tools"])).all() - results_agent_dict["tools"] = tools - if 'instruction' in results_agent_dict: - results_agent_dict['instruction'] = json.loads(results_agent_dict['instruction'].replace("'", '"')) - - if 'constraints' in results_agent_dict: - constraints_str = results_agent_dict["constraints"] - constraints_list = eval(constraints_str) - results_agent_dict["constraints"] = constraints_list - - results_agent_dict["name"] = agent.name - results_agent_dict["description"] = agent.description - results_agent_dict["calls"] = total_calls - results_agent_dict["tokens"] = total_tokens - - knowledge_name = "" - if 'knowledge' in results_agent_dict and results_agent_dict['knowledge'] != 'None': - if type(results_agent_dict['knowledge'])==int: - results_agent_dict['knowledge'] = int(results_agent_dict['knowledge']) - knowledge = db.session.query(Knowledges).filter(Knowledges.id == results_agent_dict['knowledge']).first() - knowledge_name = knowledge.name if knowledge is not None else "" - results_agent_dict['knowledge_name'] = knowledge_name - - response = results_agent_dict + response = AgentExecutionConfiguration.fetch_details_api(db.session, agent, results_agent, results_agent_execution, total_calls, total_tokens) # Close the session db.session.close() diff --git a/superagi/models/agent_execution_config.py b/superagi/models/agent_execution_config.py index 1a451d8c7..8900f9c15 100644 --- a/superagi/models/agent_execution_config.py +++ b/superagi/models/agent_execution_config.py @@ -2,6 +2,12 @@ from superagi.models.base_model import DBBaseModel +import ast +import json +from superagi.models.knowledges import Knowledges + +from superagi.models.tool import Tool + class AgentExecutionConfiguration(DBBaseModel): """ @@ -100,3 +106,46 @@ def eval_agent_config(cls, key, value): if key == "goal" or key == "instruction": return eval(value) + + @classmethod + def fetch_details_api(cls, session, agent, results_agent, results_agent_execution, total_calls, total_tokens): + results_agent_dict = {result.key: result.value for result in results_agent} + results_agent_execution_dict = {result.key: result.value for result in results_agent_execution} + + for key, value in results_agent_execution_dict.items(): + if key in results_agent_dict and value is not None: + results_agent_dict[key] = value + + # Construct the response + if 'goal' in results_agent_dict: + results_agent_dict['goal'] = json.loads(results_agent_dict['goal'].replace("'", '"')) + + if "toolkits" in results_agent_dict: + results_agent_dict["toolkits"] = list(ast.literal_eval(results_agent_dict["toolkits"])) + + if 'tools' in results_agent_dict: + results_agent_dict["tools"] = list(ast.literal_eval(results_agent_dict["tools"])) + tools = session.query(Tool).filter(Tool.id.in_(results_agent_dict["tools"])).all() + results_agent_dict["tools"] = tools + if 'instruction' in results_agent_dict: + results_agent_dict['instruction'] = json.loads(results_agent_dict['instruction'].replace("'", '"')) + + if 'constraints' in results_agent_dict: + constraints_str = results_agent_dict["constraints"] + constraints_list = eval(constraints_str) + results_agent_dict["constraints"] = constraints_list + + results_agent_dict["name"] = agent.name + results_agent_dict["description"] = agent.description + results_agent_dict["calls"] = total_calls + results_agent_dict["tokens"] = total_tokens + + knowledge_name = "" + if 'knowledge' in results_agent_dict and results_agent_dict['knowledge'] != 'None': + if type(results_agent_dict['knowledge'])==int: + results_agent_dict['knowledge'] = int(results_agent_dict['knowledge']) + knowledge = session.query(Knowledges).filter(Knowledges.id == results_agent_dict['knowledge']).first() + knowledge_name = knowledge.name if knowledge is not None else "" + results_agent_dict['knowledge_name'] = knowledge_name + + return results_agent_dict From 9a05125ed4c959cb1e2a7876b264726cc44b96bf Mon Sep 17 00:00:00 2001 From: Rounak Bhatia Date: Mon, 7 Aug 2023 14:37:53 +0530 Subject: [PATCH 08/11] Edit agent feature --- superagi/controllers/agent_execution.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/superagi/controllers/agent_execution.py b/superagi/controllers/agent_execution.py index 10f1dd7d1..f8019e6e9 100644 --- a/superagi/controllers/agent_execution.py +++ b/superagi/controllers/agent_execution.py @@ -85,10 +85,25 @@ def create_agent_execution(agent_execution: AgentExecutionIn, agent_id=agent_execution.agent_id, name=agent_execution.name, num_of_calls=0, num_of_tokens=0, current_step_id=start_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": + toolkits = [int(item) for item in agent_config.value.strip('{}').split(',')] + agent_execution_configs[agent_config.key] = toolkits + elif agent_config.key == "constraints": + constraints = [item.strip('"') for item in agent_config.value.strip('{}').split(',')] + agent_execution_configs[agent_config.key] = constraints + else: + agent_execution_configs[agent_config.key] = agent_config.value + db.session.add(db_agent_execution) db.session.commit() db.session.flush() From 50d2fa834220a52eed11b85fe0a9d85c75ff033d Mon Sep 17 00:00:00 2001 From: Rounak Bhatia Date: Mon, 7 Aug 2023 18:26:40 +0530 Subject: [PATCH 09/11] fix --- superagi/controllers/agent_execution_config.py | 2 +- superagi/models/agent_execution_config.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/superagi/controllers/agent_execution_config.py b/superagi/controllers/agent_execution_config.py index 31ca022c1..d06b99134 100644 --- a/superagi/controllers/agent_execution_config.py +++ b/superagi/controllers/agent_execution_config.py @@ -74,7 +74,7 @@ def get_agent_execution_configuration(agent_id : Union[int, None, str], total_tokens = db.session.query(func.sum(AgentExecution.num_of_tokens)).filter( AgentExecution.agent_id == agent_id).scalar() - response = AgentExecutionConfiguration.fetch_details_api(db.session, agent, results_agent, results_agent_execution, total_calls, total_tokens) + response = AgentExecutionConfiguration.build_agent_execution_config(db.session, agent, results_agent, results_agent_execution, total_calls, total_tokens) # Close the session db.session.close() diff --git a/superagi/models/agent_execution_config.py b/superagi/models/agent_execution_config.py index 8900f9c15..62166514f 100644 --- a/superagi/models/agent_execution_config.py +++ b/superagi/models/agent_execution_config.py @@ -108,7 +108,7 @@ def eval_agent_config(cls, key, value): return eval(value) @classmethod - def fetch_details_api(cls, session, agent, results_agent, results_agent_execution, total_calls, total_tokens): + def build_agent_execution_config(cls, session, agent, results_agent, results_agent_execution, total_calls, total_tokens): results_agent_dict = {result.key: result.value for result in results_agent} results_agent_execution_dict = {result.key: result.value for result in results_agent_execution} From 2031eb34d668371aa044dfbf8e2a017d747b7e56 Mon Sep 17 00:00:00 2001 From: Rounak Bhatia Date: Mon, 7 Aug 2023 18:49:42 +0530 Subject: [PATCH 10/11] fix --- superagi/controllers/agent.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/superagi/controllers/agent.py b/superagi/controllers/agent.py index 429bcd62d..45c169d5b 100644 --- a/superagi/controllers/agent.py +++ b/superagi/controllers/agent.py @@ -197,7 +197,10 @@ def create_agent_with_config(agent_with_config: AgentConfigInput, agent_with_config.tools.extend(agent_toolkit_tools) db_agent = Agent.create_agent_with_config(db, agent_with_config) - start_step_id = AgentWorkflow.fetch_trigger_step_id(db.session, db_agent.agent_workflow_id) + 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) From 989ce4c5ce30dadb0355ba1c5c2f490d078f5251 Mon Sep 17 00:00:00 2001 From: Rounak Bhatia Date: Mon, 7 Aug 2023 18:55:29 +0530 Subject: [PATCH 11/11] fix --- superagi/controllers/agent_execution.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/superagi/controllers/agent_execution.py b/superagi/controllers/agent_execution.py index 76e94e603..0604cca00 100644 --- a/superagi/controllers/agent_execution.py +++ b/superagi/controllers/agent_execution.py @@ -88,7 +88,9 @@ def create_agent_execution(agent_execution: AgentExecutionIn, db_agent_execution = AgentExecution(status="RUNNING", last_execution_time=datetime.now(), agent_id=agent_execution.agent_id, name=agent_execution.name, num_of_calls=0, num_of_tokens=0, - current_step_id=start_step_id) + 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