Skip to content

armgit / camel

Public Imported from GitHub
0

🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org

chore: Video analysis toolkit arg renaming (#2906)

Wendong-Fane01fb7c9312b
diff --git a/camel/memories/agent_memories.py b/camel/memories/agent_memories.py
index 5c46cddc2..785aa724d 100644
--- a/camel/memories/agent_memories.py
+++ b/camel/memories/agent_memories.py
@@ -101,30 +101,31 @@ class ChatHistoryMemory(AgentMemory):
if not record_dicts:
return
- # Filter out tool-related messages
- cleaned_records = []
- for record in record_dicts:
+ # Track indices to remove (reverse order for efficient deletion)
+ indices_to_remove = []
+
+ # Identify indices of tool-related messages
+ for i, record in enumerate(record_dicts):
role = record.get('role_at_backend')
- # Skip FUNCTION messages
+ # Mark FUNCTION messages for removal
if role == OpenAIBackendRole.FUNCTION.value:
- continue
-
- # Skip TOOL messages
- if role == OpenAIBackendRole.TOOL.value:
- continue
-
- # Skip ASSISTANT messages with tool_calls
- if role == OpenAIBackendRole.ASSISTANT.value:
+ indices_to_remove.append(i)
+ # Mark TOOL messages for removal
+ elif role == OpenAIBackendRole.TOOL.value:
+ indices_to_remove.append(i)
+ # Mark ASSISTANT messages with tool_calls for removal
+ elif role == OpenAIBackendRole.ASSISTANT.value:
meta_dict = record.get('meta_dict', {})
if meta_dict and 'tool_calls' in meta_dict:
- continue
+ indices_to_remove.append(i)
- # Keep all other messages
- cleaned_records.append(record)
+ # Remove records in-place
+ for i in reversed(indices_to_remove):
+ del record_dicts[i]
- # Save the cleaned records back to storage
- self._chat_history_block.storage.save(cleaned_records)
+ # Save the modified records back to storage
+ self._chat_history_block.storage.save(record_dicts)
class VectorDBMemory(AgentMemory):
diff --git a/camel/toolkits/video_analysis_toolkit.py b/camel/toolkits/video_analysis_toolkit.py
index 8fedb8717..9d5bf8222 100644
--- a/camel/toolkits/video_analysis_toolkit.py
+++ b/camel/toolkits/video_analysis_toolkit.py
@@ -97,7 +97,7 @@ class VideoAnalysisToolkit(BaseToolkit):
r"""A class for analysing videos with vision-language model.
Args:
- download_directory (Optional[str], optional): The directory where the
+ working_directory (Optional[str], optional): The directory where the
video will be downloaded to. If not provided, video will be stored
in a temporary directory and will be cleaned up after use.
(default: :obj:`None`)
@@ -123,7 +123,7 @@ class VideoAnalysisToolkit(BaseToolkit):
@dependencies_required("ffmpeg", "scenedetect")
def __init__(
self,
- download_directory: Optional[str] = None,
+ working_directory: Optional[str] = None,
model: Optional[BaseModelBackend] = None,
use_audio_transcription: bool = False,
use_ocr: bool = False,
@@ -133,30 +133,30 @@ class VideoAnalysisToolkit(BaseToolkit):
timeout: Optional[float] = None,
) -> None:
super().__init__(timeout=timeout)
- self._cleanup = download_directory is None
+ self._cleanup = working_directory is None
self._temp_files: list[str] = [] # Track temporary files for cleanup
self._use_audio_transcription = use_audio_transcription
self._use_ocr = use_ocr
self.output_language = output_language
self.frame_interval = frame_interval
- self._download_directory = Path(
- download_directory or tempfile.mkdtemp()
+ self._working_directory = Path(
+ working_directory or tempfile.mkdtemp()
).resolve()
self.video_downloader_toolkit = VideoDownloaderToolkit(
- download_directory=str(self._download_directory),
+ working_directory=str(self._working_directory),
cookies_path=cookies_path,
)
try:
- self._download_directory.mkdir(parents=True, exist_ok=True)
+ self._working_directory.mkdir(parents=True, exist_ok=True)
except OSError as e:
raise ValueError(
- f"Error creating directory {self._download_directory}: {e}"
+ f"Error creating directory {self._working_directory}: {e}"
)
- logger.info(f"Video will be downloaded to {self._download_directory}")
+ logger.info(f"Video will be downloaded to {self._working_directory}")
self.vl_model = model
# Ensure ChatAgent is initialized with a model if provided
@@ -206,16 +206,16 @@ class VideoAnalysisToolkit(BaseToolkit):
)
# Clean up temporary directory if needed
- if self._cleanup and os.path.exists(self._download_directory):
+ if self._cleanup and os.path.exists(self._working_directory):
try:
import sys
if getattr(sys, 'modules', None) is not None:
import shutil
- shutil.rmtree(self._download_directory)
+ shutil.rmtree(self._working_directory)
logger.debug(
- f"Removed temp directory: {self._download_directory}"
+ f"Removed temp directory: {self._working_directory}"
)
except (ImportError, AttributeError):
# Skip cleanup if interpreter is shutting down
@@ -223,7 +223,7 @@ class VideoAnalysisToolkit(BaseToolkit):
except OSError as e:
logger.warning(
f"Failed to remove temporary directory "
- f"{self._download_directory}: {e}"
+ f"{self._working_directory}: {e}"
)
@dependencies_required("pytesseract", "cv2", "numpy")
diff --git a/camel/toolkits/video_download_toolkit.py b/camel/toolkits/video_download_toolkit.py
index 4dac932cd..c23acab1d 100644
--- a/camel/toolkits/video_download_toolkit.py
+++ b/camel/toolkits/video_download_toolkit.py
@@ -62,7 +62,7 @@ class VideoDownloaderToolkit(BaseToolkit):
chunks.
Args:
- download_directory (Optional[str], optional): The directory where the
+ working_directory (Optional[str], optional): The directory where the
video will be downloaded to. If not provided, video will be stored
in a temporary directory and will be cleaned up after use.
(default: :obj:`None`)
@@ -73,30 +73,30 @@ class VideoDownloaderToolkit(BaseToolkit):
@dependencies_required("yt_dlp", "ffmpeg")
def __init__(
self,
- download_directory: Optional[str] = None,
+ working_directory: Optional[str] = None,
cookies_path: Optional[str] = None,
timeout: Optional[float] = None,
) -> None:
super().__init__(timeout=timeout)
- self._cleanup = download_directory is None
+ self._cleanup = working_directory is None
self._cookies_path = cookies_path
- self._download_directory = Path(
- download_directory or tempfile.mkdtemp()
+ self._working_directory = Path(
+ working_directory or tempfile.mkdtemp()
).resolve()
try:
- self._download_directory.mkdir(parents=True, exist_ok=True)
+ self._working_directory.mkdir(parents=True, exist_ok=True)
except FileExistsError:
raise ValueError(
- f"{self._download_directory} is not a valid directory."
+ f"{self._working_directory} is not a valid directory."
)
except OSError as e:
raise ValueError(
- f"Error creating directory {self._download_directory}: {e}"
+ f"Error creating directory {self._working_directory}: {e}"
)
- logger.info(f"Video will be downloaded to {self._download_directory}")
+ logger.info(f"Video will be downloaded to {self._working_directory}")
def __del__(self) -> None:
r"""Deconstructor for the VideoDownloaderToolkit class.
@@ -111,7 +111,7 @@ class VideoDownloaderToolkit(BaseToolkit):
if getattr(sys, 'modules', None) is not None:
import shutil
- shutil.rmtree(self._download_directory, ignore_errors=True)
+ shutil.rmtree(self._working_directory, ignore_errors=True)
except (ImportError, AttributeError):
# Skip cleanup if interpreter is shutting down
pass
@@ -130,7 +130,7 @@ class VideoDownloaderToolkit(BaseToolkit):
"""
import yt_dlp
- video_template = self._download_directory / "%(title)s.%(ext)s"
+ video_template = self._working_directory / "%(title)s.%(ext)s"
ydl_opts = {
'format': 'bestvideo+bestaudio/best',
'outtmpl': str(video_template),
diff --git a/docs/mintlify/reference/camel.toolkits.video_analysis_toolkit.mdx b/docs/mintlify/reference/camel.toolkits.video_analysis_toolkit.mdx
index 9d369e6c5..32d76f744 100644
--- a/docs/mintlify/reference/camel.toolkits.video_analysis_toolkit.mdx
+++ b/docs/mintlify/reference/camel.toolkits.video_analysis_toolkit.mdx
@@ -12,7 +12,7 @@ A class for analysing videos with vision-language model.
**Parameters:**
-- **download_directory** (Optional[str], optional): The directory where the video will be downloaded to. If not provided, video will be stored in a temporary directory and will be cleaned up after use. (default: :obj:`None`)
+- **working_directory** (Optional[str], optional): The directory where the video will be downloaded to. If not provided, video will be stored in a temporary directory and will be cleaned up after use. (default: :obj:`None`)
- **model** (Optional[BaseModelBackend], optional): The model to use for visual analysis. (default: :obj:`None`)
- **use_audio_transcription** (bool, optional): Whether to enable audio transcription using OpenAI's audio models. Requires a valid OpenAI API key. When disabled, video analysis will be based solely on visual content. (default: :obj:`False`)
- **use_ocr** (bool, optional): Whether to enable OCR for extracting text from video frames. (default: :obj:`False`)
@@ -28,7 +28,7 @@ A class for analysing videos with vision-language model.
```python
def __init__(
self,
- download_directory: Optional[str] = None,
+ working_directory: Optional[str] = None,
model: Optional[BaseModelBackend] = None,
use_audio_transcription: bool = False,
use_ocr: bool = False,
diff --git a/docs/mintlify/reference/camel.toolkits.video_download_toolkit.mdx b/docs/mintlify/reference/camel.toolkits.video_download_toolkit.mdx
index 56c10ea15..794c2b85a 100644
--- a/docs/mintlify/reference/camel.toolkits.video_download_toolkit.mdx
+++ b/docs/mintlify/reference/camel.toolkits.video_download_toolkit.mdx
@@ -32,7 +32,7 @@ chunks.
**Parameters:**
-- **download_directory** (Optional[str], optional): The directory where the video will be downloaded to. If not provided, video will be stored in a temporary directory and will be cleaned up after use. (default: :obj:`None`)
+- **working_directory** (Optional[str], optional): The directory where the video will be downloaded to. If not provided, video will be stored in a temporary directory and will be cleaned up after use. (default: :obj:`None`)
- **cookies_path** (Optional[str], optional): The path to the cookies file for the video service in Netscape format. (default: :obj:`None`)
<a id="camel.toolkits.video_download_toolkit.VideoDownloaderToolkit.__init__"></a>
@@ -42,7 +42,7 @@ chunks.
```python
def __init__(
self,
- download_directory: Optional[str] = None,
+ working_directory: Optional[str] = None,
cookies_path: Optional[str] = None,
timeout: Optional[float] = None
):
diff --git a/docs/reference/camel.toolkits.video_analysis_toolkit.md b/docs/reference/camel.toolkits.video_analysis_toolkit.md
index 9d369e6c5..32d76f744 100644
--- a/docs/reference/camel.toolkits.video_analysis_toolkit.md
+++ b/docs/reference/camel.toolkits.video_analysis_toolkit.md
@@ -12,7 +12,7 @@ A class for analysing videos with vision-language model.
**Parameters:**
-- **download_directory** (Optional[str], optional): The directory where the video will be downloaded to. If not provided, video will be stored in a temporary directory and will be cleaned up after use. (default: :obj:`None`)
+- **working_directory** (Optional[str], optional): The directory where the video will be downloaded to. If not provided, video will be stored in a temporary directory and will be cleaned up after use. (default: :obj:`None`)
- **model** (Optional[BaseModelBackend], optional): The model to use for visual analysis. (default: :obj:`None`)
- **use_audio_transcription** (bool, optional): Whether to enable audio transcription using OpenAI's audio models. Requires a valid OpenAI API key. When disabled, video analysis will be based solely on visual content. (default: :obj:`False`)
- **use_ocr** (bool, optional): Whether to enable OCR for extracting text from video frames. (default: :obj:`False`)
@@ -28,7 +28,7 @@ A class for analysing videos with vision-language model.
```python
def __init__(
self,
- download_directory: Optional[str] = None,
+ working_directory: Optional[str] = None,
model: Optional[BaseModelBackend] = None,
use_audio_transcription: bool = False,
use_ocr: bool = False,
diff --git a/docs/reference/camel.toolkits.video_download_toolkit.md b/docs/reference/camel.toolkits.video_download_toolkit.md
index 56c10ea15..794c2b85a 100644
--- a/docs/reference/camel.toolkits.video_download_toolkit.md
+++ b/docs/reference/camel.toolkits.video_download_toolkit.md
@@ -32,7 +32,7 @@ chunks.
**Parameters:**
-- **download_directory** (Optional[str], optional): The directory where the video will be downloaded to. If not provided, video will be stored in a temporary directory and will be cleaned up after use. (default: :obj:`None`)
+- **working_directory** (Optional[str], optional): The directory where the video will be downloaded to. If not provided, video will be stored in a temporary directory and will be cleaned up after use. (default: :obj:`None`)
- **cookies_path** (Optional[str], optional): The path to the cookies file for the video service in Netscape format. (default: :obj:`None`)
<a id="camel.toolkits.video_download_toolkit.VideoDownloaderToolkit.__init__"></a>
@@ -42,7 +42,7 @@ chunks.
```python
def __init__(
self,
- download_directory: Optional[str] = None,
+ working_directory: Optional[str] = None,
cookies_path: Optional[str] = None,
timeout: Optional[float] = None
):
diff --git a/examples/usecases/chat_with_youtube/app.py b/examples/usecases/chat_with_youtube/app.py
index 0332f974d..8b1b8847c 100644
--- a/examples/usecases/chat_with_youtube/app.py
+++ b/examples/usecases/chat_with_youtube/app.py
@@ -23,7 +23,7 @@ from dotenv import load_dotenv
load_dotenv()
# Initialize toolkits
-video_downloader = VideoDownloaderToolkit(download_directory="downloads/")
+video_downloader = VideoDownloaderToolkit(working_directory="downloads/")
audio_toolkit = AudioAnalysisToolkit(cache_dir="downloads/")
summarizer_agent = ChatAgent(system_message="You are a helpful assistant that summarizes transcripts.", model="gpt-4o-mini")
qa_agent = ChatAgent(system_message="Answer the question based on the context provided.", model="gpt-4o-mini")
diff --git a/examples/workforce/eigent.py b/examples/workforce/eigent.py
index 0282de463..c76efaa6a 100644
--- a/examples/workforce/eigent.py
+++ b/examples/workforce/eigent.py
@@ -54,7 +54,9 @@ from camel.utils.commons import api_keys_required
logger = get_logger(__name__)
-WORKING_DIRECTORY = os.environ.get("CAMEL_WORKDIR") or "working_dir/"
+WORKING_DIRECTORY = os.environ.get("CAMEL_WORKDIR") or os.path.abspath(
+ "working_dir/"
+)
def send_message_to_user(
@@ -589,7 +591,9 @@ def multi_modal_agent_factory(model: BaseModelBackend, task_id: str):
r"""Factory for creating a multi modal agent, based on user-provided code
structure."""
tools = [
- *VideoDownloaderToolkit().get_tools(),
+ *VideoDownloaderToolkit(
+ working_directory=WORKING_DIRECTORY
+ ).get_tools(),
*AudioAnalysisToolkit().get_tools(),
*ImageAnalysisToolkit().get_tools(),
*OpenAIImageToolkit(
@@ -602,7 +606,7 @@ def multi_modal_agent_factory(model: BaseModelBackend, task_id: str):
send_message_to_user,
HumanToolkit().ask_human_via_console,
SearchToolkit().search_exa,
- *TerminalToolkit().get_tools(),
+ *TerminalToolkit(safe_mode=True, clone_current_env=False).get_tools(),
*NoteTakingToolkit(working_directory=WORKING_DIRECTORY).get_tools(),
]
@@ -789,6 +793,9 @@ operations.
async def main():
+ # Ensure working directory exists
+ os.makedirs(WORKING_DIRECTORY, exist_ok=True)
+
# google_drive_mcp_toolkit = GoogleDriveMCPToolkit(
# credentials_path="path/to/credentials.json"
# )
diff --git a/test/toolkits/test_video_analysis_toolkit.py b/test/toolkits/test_video_analysis_toolkit.py
index 4813784a1..ac025c906 100644
--- a/test/toolkits/test_video_analysis_toolkit.py
+++ b/test/toolkits/test_video_analysis_toolkit.py
@@ -88,10 +88,10 @@ def test_init_default():
assert toolkit._cleanup is True
assert toolkit._use_audio_transcription is False
# Use startswith instead of exact match to handle /private/tmp on macOS
- assert toolkit._download_directory.as_posix().endswith("/mock_dir")
+ assert toolkit._working_directory.as_posix().endswith("/mock_dir")
-def test_init_with_download_directory():
+def test_init_with_working_directory():
r"""Test initialization with custom download directory"""
with (
patch("pathlib.Path.mkdir"),
@@ -99,9 +99,9 @@ def test_init_with_download_directory():
patch("camel.toolkits.video_analysis_toolkit.VideoDownloaderToolkit"),
patch("os.path.exists", return_value=True),
):
- toolkit = VideoAnalysisToolkit(download_directory="/custom/dir")
+ toolkit = VideoAnalysisToolkit(working_directory="/custom/dir")
assert toolkit._cleanup is False
- assert toolkit._download_directory.as_posix() == "/custom/dir"
+ assert toolkit._working_directory.as_posix() == "/custom/dir"
def test_init_with_audio_transcription():
@@ -137,7 +137,7 @@ def test_init_with_invalid_directory():
patch("camel.agents.ChatAgent"),
):
with pytest.raises(ValueError):
- VideoAnalysisToolkit(download_directory="invalid_dir")
+ VideoAnalysisToolkit(working_directory="invalid_dir")
# Test cleanup