add ensure active, fix utils logger impot in sb tool base

This commit is contained in:
marko-kraemer 2025-05-11 18:36:33 +02:00
parent 5617f5e06d
commit 52fceeb39a
3 changed files with 45 additions and 54 deletions

View File

@ -6,7 +6,6 @@ from typing import Optional
from agentpress.tool import ToolResult, openapi_schema, xml_schema
from sandbox.tool_base import SandboxToolsBase
from agentpress.thread_manager import ThreadManager
from utils.logger import logger
import json
# Add common image MIME types if mimetypes module is limited
@ -64,7 +63,6 @@ class SandboxVisionTool(SandboxToolsBase):
# Clean and construct full path
cleaned_path = self.clean_path(file_path)
full_path = f"{self.workspace_path}/{cleaned_path}"
logger.info(f"Attempting to see image: {full_path} (original: {file_path})")
# Check if file exists and get info
try:
@ -72,7 +70,6 @@ class SandboxVisionTool(SandboxToolsBase):
if file_info.is_dir:
return self.fail_response(f"Path '{cleaned_path}' is a directory, not an image file.")
except Exception as e:
logger.warning(f"File not found at {full_path}: {e}")
return self.fail_response(f"Image file not found at path: '{cleaned_path}'")
# Check file size
@ -83,7 +80,6 @@ class SandboxVisionTool(SandboxToolsBase):
try:
image_bytes = self.sandbox.fs.download_file(full_path)
except Exception as e:
logger.error(f"Error reading image file {full_path}: {e}")
return self.fail_response(f"Could not read image file: {cleaned_path}")
# Convert to base64
@ -101,8 +97,6 @@ class SandboxVisionTool(SandboxToolsBase):
else:
return self.fail_response(f"Unsupported or unknown image format for file: '{cleaned_path}'. Supported: JPG, PNG, GIF, WEBP.")
logger.info(f"Successfully read and encoded image '{cleaned_path}' as {mime_type}")
# Prepare the temporary message content
image_context_data = {
"mime_type": mime_type,
@ -118,11 +112,9 @@ class SandboxVisionTool(SandboxToolsBase):
content=image_context_data, # Store the dict directly
is_llm_message=False # This is context generated by a tool
)
logger.info(f"Added image context message for '{cleaned_path}' to thread {self.thread_id}")
# Inform the agent the image will be available next turn
return self.success_response(f"Successfully loaded the image '{cleaned_path}'.")
except Exception as e:
logger.error(f"Error processing see_image for {file_path}: {e}", exc_info=True)
return self.fail_response(f"An unexpected error occurred while trying to see the image: {str(e)}")

View File

@ -212,56 +212,56 @@ async def read_file(
raise HTTPException(status_code=500, detail=str(e))
# Should happen on server-side fully
# @router.post("/project/{project_id}/sandbox/ensure-active")
# async def ensure_project_sandbox_active(
# project_id: str,
# request: Request = None,
# user_id: Optional[str] = Depends(get_optional_user_id)
# ):
# """
# Ensure that a project's sandbox is active and running.
# Checks the sandbox status and starts it if it's not running.
# """
# logger.info(f"Received ensure sandbox active request for project {project_id}, user_id: {user_id}")
# client = await db.client
@router.post("/project/{project_id}/sandbox/ensure-active")
async def ensure_project_sandbox_active(
project_id: str,
request: Request = None,
user_id: Optional[str] = Depends(get_optional_user_id)
):
"""
Ensure that a project's sandbox is active and running.
Checks the sandbox status and starts it if it's not running.
"""
logger.info(f"Received ensure sandbox active request for project {project_id}, user_id: {user_id}")
client = await db.client
# # Find the project and sandbox information
# project_result = await client.table('projects').select('*').eq('project_id', project_id).execute()
# Find the project and sandbox information
project_result = await client.table('projects').select('*').eq('project_id', project_id).execute()
# if not project_result.data or len(project_result.data) == 0:
# logger.error(f"Project not found: {project_id}")
# raise HTTPException(status_code=404, detail="Project not found")
if not project_result.data or len(project_result.data) == 0:
logger.error(f"Project not found: {project_id}")
raise HTTPException(status_code=404, detail="Project not found")
# project_data = project_result.data[0]
project_data = project_result.data[0]
# # For public projects, no authentication is needed
# if not project_data.get('is_public'):
# # For private projects, we must have a user_id
# if not user_id:
# logger.error(f"Authentication required for private project {project_id}")
# raise HTTPException(status_code=401, detail="Authentication required for this resource")
# For public projects, no authentication is needed
if not project_data.get('is_public'):
# For private projects, we must have a user_id
if not user_id:
logger.error(f"Authentication required for private project {project_id}")
raise HTTPException(status_code=401, detail="Authentication required for this resource")
# account_id = project_data.get('account_id')
account_id = project_data.get('account_id')
# # Verify account membership
# if account_id:
# account_user_result = await client.schema('basejump').from_('account_user').select('account_role').eq('user_id', user_id).eq('account_id', account_id).execute()
# if not (account_user_result.data and len(account_user_result.data) > 0):
# logger.error(f"User {user_id} not authorized to access project {project_id}")
# raise HTTPException(status_code=403, detail="Not authorized to access this project")
# Verify account membership
if account_id:
account_user_result = await client.schema('basejump').from_('account_user').select('account_role').eq('user_id', user_id).eq('account_id', account_id).execute()
if not (account_user_result.data and len(account_user_result.data) > 0):
logger.error(f"User {user_id} not authorized to access project {project_id}")
raise HTTPException(status_code=403, detail="Not authorized to access this project")
# try:
# # Get or create the sandbox
# logger.info(f"Ensuring sandbox is active for project {project_id}")
# sandbox, sandbox_id, sandbox_pass = await get_or_create_project_sandbox(client, project_id)
try:
# Get or create the sandbox
logger.info(f"Ensuring sandbox is active for project {project_id}")
sandbox, sandbox_id, sandbox_pass = await get_or_create_project_sandbox(client, project_id)
# logger.info(f"Successfully ensured sandbox {sandbox_id} is active for project {project_id}")
logger.info(f"Successfully ensured sandbox {sandbox_id} is active for project {project_id}")
# return {
# "status": "success",
# "sandbox_id": sandbox_id,
# "message": "Sandbox is active"
# }
# except Exception as e:
# logger.error(f"Error ensuring sandbox is active for project {project_id}: {str(e)}")
# raise HTTPException(status_code=500, detail=str(e))
return {
"status": "success",
"sandbox_id": sandbox_id,
"message": "Sandbox is active"
}
except Exception as e:
logger.error(f"Error ensuring sandbox is active for project {project_id}: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))

View File

@ -5,10 +5,9 @@ from agentpress.thread_manager import ThreadManager
from agentpress.tool import Tool
from daytona_sdk import Sandbox
from sandbox.sandbox import get_or_start_sandbox
from utils import logger
from utils.logger import logger
from utils.files_utils import clean_path
class SandboxToolsBase(Tool):
"""Base class for all sandbox tools that provides project-based sandbox access."""