Spaces:
Running
Running
Commit ·
fde43e7
1
Parent(s): 0e58feb
Fixing tool deletion
Browse filesFiles changed (7)
11 unmodified lines12131415161787 unmodified lines10510610710810911011151 unmodified lines16316416516616716816917020 unmodified lines19119219319419519619719819920020120213 unmodified lines21621721821922022122222322422522612 unmodified lines23924024124224324424513 unmodified lines25926026126226326426526626726811 unmodified linesfrom dotenv import load_dotenvfrom src.manager.budget_manager import BudgetManagerclass Agent(ABC):def __init__(self, agent_name: str, base_model: str, system_prompt: str, creation_cost: str, invoke_cost: str):87 unmodified linesself._load_agents()def create_agent(self, agent_name: str, base_model: str, system_prompt: str, description: str = "", create_cost: float = 0, invoke_cost: float = 0,**additional_params) -> Tuple[Agent, int]:if agent_name in self._agents:51 unmodified linesdef list_agents(self) -> dict:"""Return agent information (name, description, costs)"""try:if os.path.exists("./models/models.json"):with open("./models/models.json", "r", encoding="utf8") as f:full_models = json.loads(f.read())# Create a simplified version with only the description and costs20 unmodified linesdel self._agents[agent_name]try:if os.path.exists("./models/models.json"):with open("./models/models.json", "r", encoding="utf8") as f:models = json.loads(f.read())del models[agent_name]with open("./models/models.json", "w", encoding="utf8") as f:f.write(json.dumps(models, indent=4))except Exception as e:output_assistant_response(f"Error deleting agent: {e}")13 unmodified lines"""Save a single agent to the models.json file"""try:# Ensure the directory existsos.makedirs("./models", exist_ok=True)# Read existing models file or create empty dict if it doesn't existtry:with open("./models/models.json", "r", encoding="utf8") as f:models = json.loads(f.read())except (FileNotFoundError, json.JSONDecodeError):models = {}12 unmodified linesmodels[agent_name][key] = value# Write the updated models back to the filewith open("./models/models.json", "w", encoding="utf8") as f:f.write(json.dumps(models, indent=4))except Exception as e:13 unmodified linesdef _load_agents(self) -> None:"""Load agent configurations from disk"""try:if not os.path.exists("./models/models.json"):returnwith open("./models/models.json", "r", encoding="utf8") as f:models = json.loads(f.read())for name, data in models.items():11 unmodified lines12131415161718192087 unmodified lines10810911011111211311411511611751 unmodified lines16917017117217317417517620 unmodified lines19719819920020120220320420520620720813 unmodified lines22222322422522622722822923023123212 unmodified lines24524624724824925025113 unmodified lines26526626726826927027127227327411 unmodified linesfrom dotenv import load_dotenvfrom src.manager.budget_manager import BudgetManagerMODEL_PATH = "./src/models/"MODEL_FILE_PATH = "./src/models/models.json"class Agent(ABC):def __init__(self, agent_name: str, base_model: str, system_prompt: str, creation_cost: str, invoke_cost: str):87 unmodified linesself._load_agents()def create_agent(self, agent_name: str,base_model: str, system_prompt: str,description: str = "", create_cost: float = 0,invoke_cost: float = 0,**additional_params) -> Tuple[Agent, int]:if agent_name in self._agents:51 unmodified linesdef list_agents(self) -> dict:"""Return agent information (name, description, costs)"""try:if os.path.exists(MODEL_FILE_PATH):with open(MODEL_FILE_PATH, "r", encoding="utf8") as f:full_models = json.loads(f.read())# Create a simplified version with only the description and costs20 unmodified linesdel self._agents[agent_name]try:if os.path.exists(MODEL_FILE_PATH):with open(MODEL_FILE_PATH, "r", encoding="utf8") as f:models = json.loads(f.read())del models[agent_name]with open(MODEL_FILE_PATH, "w", encoding="utf8") as f:f.write(json.dumps(models, indent=4))except Exception as e:output_assistant_response(f"Error deleting agent: {e}")13 unmodified lines"""Save a single agent to the models.json file"""try:# Ensure the directory existsos.makedirs(MODEL_PATH, exist_ok=True)# Read existing models file or create empty dict if it doesn't existtry:with open(MODEL_FILE_PATH, "r", encoding="utf8") as f:models = json.loads(f.read())except (FileNotFoundError, json.JSONDecodeError):models = {}12 unmodified linesmodels[agent_name][key] = value# Write the updated models back to the filewith open(MODEL_FILE_PATH, "w", encoding="utf8") as f:f.write(json.dumps(models, indent=4))except Exception as e:13 unmodified linesdef _load_agents(self) -> None:"""Load agent configurations from disk"""try:if not os.path.exists(MODEL_FILE_PATH):returnwith open(MODEL_FILE_PATH, "r", encoding="utf8") as f:models = json.loads(f.read())for name, data in models.items():
97 unmodified lines989910010110210310410510610710810911011197 unmodified linesself.toolsLoader.load_tools()except Exception as e:logger.info(f"Error loading tools: {e}. Deleting the tool.")thinking += f"Error loading tools: {e}. Deleting the tool.\n"yield {"role": "assistant","content": thinking,"metadata": {"title": title,"id": i,"status": "done",}}# delete the created tool97 unmodified lines989910010110210310410510610710897 unmodified linesself.toolsLoader.load_tools()except Exception as e:logger.info(f"Error loading tools: {e}. Deleting the tool.")yield {"role": "assistant","content": f"Error loading tools: {e}. Deleting the tool.\n","metadata": {"title": "Trying to load the newly created tool",}}# delete the created tool
1{}12345678910111213141516{"RecipeAgent": {"base_model": "gemini-2.5-flash-preview-04-17","description": "Agent that extracts recipe from a website","system_prompt": "You are a recipe extraction agent. Given a URL, you extract the title, ingredients, and instructions from the website. If you cannot find the recipe, you return an error message.","create_cost": 20,"invoke_cost": 50},"TimeAgent": {"base_model": "gemini-2.0-flash","description": "An agent that provides the current time.","system_prompt": "You are a helpful agent that provides the current time in the format YYYY-MM-DD HH:MM:SS. Use the current date and time to respond to the user. Do not use any external tools or APIs.","create_cost": 20,"invoke_cost": 50}}
33 unmodified lines3435363738394082 unmodified lines12312412512612733 unmodified lines</Info><Info>Once the you're finished with a conversation, you can use the DigestConversation to clear the conversation history and create a summary of the interaction. This summary can be used to improve the system's performance and user experience in future interactions.</Info>Here's a set of rules you must follow:82 unmodified lines</Rule><Rule>When using the DigestConversation tool, ensure that the summary is clear and concise, capturing the main points of the conversation without unnecessary details. Include any important information such as how errors were solved, user's preferences, and any other relevant context that could help in future interactions.</Rule>33 unmodified lines3435363738394082 unmodified lines12312412512612712812913013133 unmodified lines</Info><Info>If user shares something important or sensitive, you should usee the UpdateMemory tool to store this information. Include details such as the user's preferences, how you solved errors, and any other relevant context that could help in future interactions. This will help you provide better assistance in the future.</Info>Here's a set of rules you must follow:82 unmodified lines</Rule><Rule>Every time you encounter an error and fix it, you should use the UpdateMemory tool to store the FIX.</Rule><Rule>Every time user corrects you or provides feedback, you should use the UpdateMemory tool to store this information.</Rule>
22 unmodified lines2324252627282 unmodified lines3132333435363722 unmodified lines"required": ["name", "tool_code"],}}def run(self, **kwargs):print("Running Tool Creator")2 unmodified linesprint(f"Tool Name: {name}")print(f"Tool Content: {content}")# Create the tool filetool_file_path = f"tools/{name}.py"with open(tool_file_path, "w") as tool_file:tool_file.write(content)print(f"Tool file created at {tool_file_path}")22 unmodified lines2324252627282930313233343536372 unmodified lines4041424344454622 unmodified lines"required": ["name", "tool_code"],}}def validate_tool_code(self, tool_code):# Basic validation to check if the code is a valid Python functiontry:compile(tool_code, '<string>', 'exec')return True, Noneexcept SyntaxError as e:print(f"Syntax error in tool code: {e}")return False, edef run(self, **kwargs):print("Running Tool Creator")2 unmodified linesprint(f"Tool Name: {name}")print(f"Tool Content: {content}")# Create the tool filetool_file_path = f"src/tools/user_tools/{name}.py"with open(tool_file_path, "w") as tool_file:tool_file.write(content)print(f"Tool file created at {tool_file_path}")
29 unmodified lines3031323334353629 unmodified linesname = kwargs.get("name")file_path = kwargs.get("file_path")# make sure the file path is in tools/if not file_path.startswith("tools/"):return {"status": "error","message": "File path must start with tools/",29 unmodified lines3031323334353629 unmodified linesname = kwargs.get("name")file_path = kwargs.get("file_path")# make sure the file path is in tools/if not file_path.startswith("src/tools/user_tools/"):return {"status": "error","message": "File path must start with tools/",
123456716 unmodified lines242526272829303132__all__ = ['UpdateMemory']from src.manager.budget_manager import BudgetManagerclass UpdateMemory():16 unmodified linesdef run(self, **kwargs):return {"status": "fail","message": "This tool is not implemented yet","output": None}123456716 unmodified lines2425262728293031323334353637383940414243444546474849505152535455__all__ = ['UpdateMemory']import jsonclass UpdateMemory():16 unmodified linesdef run(self, **kwargs):# save it to src/data/memory.jsonmemory = kwargs.get("memory")if not memory:return {"status": "error","message": "Memory is required","output": None}# add the memory to the memory.json file which is list of strings# create the file if it does not existtry:with open("src/data/memory.json", "r") as f:memory_list = json.load(f)except FileNotFoundError:memory_list = []except json.JSONDecodeError:memory_list = []# add the new memory to the listmemory_list.append(memory)# save the list to the filewith open("src/data/memory.json", "w") as f:json.dump(memory_list, f)# return the list of memoriesreturn {"status": "success","message": "Memory updated successfully","output": memory_list}
src/manager/agent_manager.py+17-11
src/manager/manager.py+2-5
src/models/models.json+16-1
src/models/system3.prompt+6-2
src/tools/default_tools/tool_creator.py+10-1
src/tools/default_tools/tool_deletor.py+1-1
src/tools/default_tools/update_memory.py+29-6