From 504daef0d47f24a30f3240e0a43ec14b45b00de6 Mon Sep 17 00:00:00 2001 From: Tianqi Xu Date: Wed, 24 Jul 2024 16:28:44 +0300 Subject: [PATCH] Delete outdated code --- crab/agents/single_agent/__init__.py | 13 -- crab/agents/single_agent/base_agent.py | 97 -------------- crab/agents/single_agent/openai_agent.py | 155 ----------------------- 3 files changed, 265 deletions(-) delete mode 100644 crab/agents/single_agent/__init__.py delete mode 100644 crab/agents/single_agent/base_agent.py delete mode 100644 crab/agents/single_agent/openai_agent.py diff --git a/crab/agents/single_agent/__init__.py b/crab/agents/single_agent/__init__.py deleted file mode 100644 index 66e0731..0000000 --- a/crab/agents/single_agent/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# =========== Copyright 2024 @ CAMEL-AI.org. All Rights Reserved. =========== -# Licensed under the Apache License, Version 2.0 (the “License”); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an “AS IS” BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# =========== Copyright 2024 @ CAMEL-AI.org. All Rights Reserved. =========== diff --git a/crab/agents/single_agent/base_agent.py b/crab/agents/single_agent/base_agent.py deleted file mode 100644 index 88dbc13..0000000 --- a/crab/agents/single_agent/base_agent.py +++ /dev/null @@ -1,97 +0,0 @@ -# =========== Copyright 2024 @ CAMEL-AI.org. All Rights Reserved. =========== -# Licensed under the Apache License, Version 2.0 (the “License”); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an “AS IS” BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# =========== Copyright 2024 @ CAMEL-AI.org. All Rights Reserved. =========== -from abc import ABC, abstractmethod -from typing import Any, List, Tuple - -from crab import Action - -signle_env_system_prompt = """You are a helpful assistant. Now you have to do a task as -described below: - -**"{description}."** - -You should never forget this task and always perform actions to achieve this task. A -unit operation you can perform is called Action. You have a limited action space as -function calls: -{action_descriptions} -You may receive a screenshot of the current system. You may receive a screenshot of a -smartphone app. The interactive UI elements on the screenshot are labeled with numeric -tags starting from 1. - -In each step, You MUST explain what do you see from the current observation and -the plan of the next action, then use a provided action in each step to -achieve the task. You should state what action to take and what the parameters should -be. Your answer MUST be a least one function call. You SHOULD NEVER ask me to do -anything for you. Always do them by yourself using function call. -""" - -multi_env_system_prompt = """You are a helpful assistant. Now you have to do a task as -described below: {description} A unit operation you can perform is called action in a -given environment. For each environment, you are given a limited action space as -function calls: -{action_descriptions} -You may receive a screenshot of the current system. The interactive UI elements on the -screenshot are labeled with numeric tags starting from 1. For each step, You must state -what actions to take, what the parameters are, and you MUST provide in which environment -to perform these actions. Your answer must be a least one function call. please do not -output any other infomation. You must make sure all function calls get their required -parameters.""" - - -class BaseAgent(ABC): - @abstractmethod - def __init__( - self, - description: str, - model: str, - action_space: dict[list[Action]], - multienv: bool = False, - max_tokens: int = 300, - history_messages_len: int = 0, - ) -> None: - # action_descriptions = ".\n".join([json.dumps(action) for action in actions]) - - self.action_space = action_space - self.multienv = multienv - self.model = model - self.max_tokens = max_tokens - self.history_messages_len = history_messages_len - assert self.history_messages_len >= 0 - - self.signle_env_system_prompt = signle_env_system_prompt - self.multi_env_system_prompt = multi_env_system_prompt - - self.chat_history = [] - self.token_usage = 0 - - @abstractmethod - def chat(self, contents: List[Tuple[str, int]]) -> dict[str, Any]: - pass - - @abstractmethod - def _to_message(self, content: str, modality: int): - pass - - @abstractmethod - def _convert_action_to_schema(self, action_space): - pass - - def _generate_action_prompt(self, actions: list[dict]): - result = "" - for action in actions: - result += f"[{action['name']}: {action['description']}]\n" - return result - - def get_token_usage(self): - return self.token_usage diff --git a/crab/agents/single_agent/openai_agent.py b/crab/agents/single_agent/openai_agent.py deleted file mode 100644 index d98ecd5..0000000 --- a/crab/agents/single_agent/openai_agent.py +++ /dev/null @@ -1,155 +0,0 @@ -# =========== Copyright 2024 @ CAMEL-AI.org. All Rights Reserved. =========== -# Licensed under the Apache License, Version 2.0 (the “License”); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an “AS IS” BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# =========== Copyright 2024 @ CAMEL-AI.org. All Rights Reserved. =========== -import json -from typing import Any - -import openai - -from crab import Action - -from .base_agent import BaseAgent - - -class OpenAIAgent(BaseAgent): - def __init__( - self, - description: str, - action_space: dict[str, list[Action]], - multienv=False, - model: str = "gpt-4-turbo", - max_tokens: int = 3000, - history_messages_len: int = 0, - ): - super().__init__( - description, model, action_space, multienv, max_tokens, history_messages_len - ) - - self._convert_action_to_schema(self.action_space) - - if self.multienv: - self.system_message = { - "role": "system", - "content": self.multi_env_system_prompt.format( - description=description, - action_descriptions=self._generate_action_prompt(self.actions), - ), - } - else: - self.system_message = { - "role": "system", - "content": self.signle_env_system_prompt.format( - description=description, - action_descriptions=self._generate_action_prompt(self.actions), - ), - } - - self.client = openai.OpenAI() - - def chat(self, contents: list[tuple[str, int]]) -> dict[str, Any]: - new_message = { - "role": "user", - "content": [ - self._to_message(content, modality) for content, modality in contents - ], - } - - request = [self.system_message] - # Add chat_history - if self.history_messages_len > 0 and len(self.chat_history) > 0: - for message in self.chat_history[-self.history_messages_len :]: - request = request + message - - request.append(new_message) - self.chat_history.append([new_message]) - - response = self.client.chat.completions.create( - messages=request, # type: ignore - model=self.model, - max_tokens=self.max_tokens, - tools=[{"type": "function", "function": action} for action in self.actions], - ) - - if response.usage is not None: - self.token_usage += response.usage.total_tokens - response_message = response.choices[0].message - - tool_calls = response_message.tool_calls - if tool_calls is None: - print("\nRequest: ", request) - print("\033[94m" f"Agent Reponse: {response_message}" "\033[0m") - raise ValueError("For each step agent should take at least one action. ") - - self.chat_history[-1].append(response_message) - for tool_call in tool_calls: - self.chat_history[-1].append( - { - "tool_call_id": tool_call.id, - "role": "tool", - "name": tool_call.function.name, - "content": "", - } - ) # extend conversation with function response - - if self.multienv: - return { - "content": response_message, - "action_list": [ - ( - ( - call.function.name.split("__in__")[0], - json.loads(call.function.arguments), - ), - call.function.name.split("__in__")[1], - ) - for call in tool_calls - ], - } - else: - return { - "content": response_message.content, - "action_list": [ - ( - call.function.name.split("__in__")[0], - json.loads(call.function.arguments), - ) - for call in tool_calls - ], - } - - def _to_message(self, content: str, modality: int): - match modality: - case 0: - return { - "type": "text", - "text": content, - } - case 1: - return { - "type": "image_url", - "image_url": { - "url": f"data:image/jpeg;base64,{content}", - "detail": "high", - }, - } - - def _convert_action_to_schema(self, action_space): - self.actions = [] - for env in action_space: - for action in action_space[env]: - new_action = action.to_openai_json_schema() - new_action["name"] = new_action["name"] + "__in__" + env - new_action["description"] = "In {} environment, {}".format( - env, new_action["description"] - ) - self.actions.append(new_action)