Skip to content

πŸ™Œ OpenHands: AI-Driven Development

[agent, browsing] Support viewing pdf and png/jpg via browser (#7457)

Xingyao Wangac8b5e79342f
diff --git a/openhands/agenthub/codeact_agent/tools/browser.py b/openhands/agenthub/codeact_agent/tools/browser.py
index 6be21b574b..3ac339aeaf 100644
--- a/openhands/agenthub/codeact_agent/tools/browser.py
+++ b/openhands/agenthub/codeact_agent/tools/browser.py
@@ -18,6 +18,11 @@ More than 2-3 actions usually leads to failure or unexpected behavior. Example:
fill('a12', 'example with "quotes"')
click('a51')
click('48', button='middle', modifiers=['Shift'])
+
+You can also use the browser to view pdf, png, jpg files.
+You should first check the content of /tmp/oh-server-url to get the server url, and then use it to view the file by `goto("{server_url}/view?path={absolute_file_path}")`.
+For example: `goto("http://localhost:8000/view?path=/workspace/test_document.pdf")`
+Note: The file should be downloaded to the local machine first before using the browser to view it.
"""
_BROWSER_TOOL_DESCRIPTION = """
diff --git a/openhands/agenthub/codeact_agent/tools/web_read.py b/openhands/agenthub/codeact_agent/tools/web_read.py
index 0c37508e02..db67b7b463 100644
--- a/openhands/agenthub/codeact_agent/tools/web_read.py
+++ b/openhands/agenthub/codeact_agent/tools/web_read.py
@@ -1,8 +1,8 @@
from litellm import ChatCompletionToolParam, ChatCompletionToolParamFunctionChunk
-_WEB_DESCRIPTION = """Read (convert to markdown) content from a webpage. You should prefer using the `web_read` tool over the `browser` tool, but do use the `browser` tool if you need to interact with a webpage (e.g., click a button, fill out a form, etc.).
+_WEB_DESCRIPTION = """Read (convert to markdown) content from a webpage. You should prefer using the `web_read` tool over the `browser` tool, but do use the `browser` tool if you need to interact with a webpage (e.g., click a button, fill out a form, etc.) OR read a webpage that contains images.
-You may use the `web_read` tool to read content from a webpage, and even search the webpage content using a Google search query (e.g., url=`https://www.google.com/search?q=YOUR_QUERY`).
+You may use the `web_read` tool to read text content from a webpage, and even search the webpage content using a Google search query (e.g., url=`https://www.google.com/search?q=YOUR_QUERY`).
"""
WebReadTool = ChatCompletionToolParam(
diff --git a/openhands/core/config/agent_config.py b/openhands/core/config/agent_config.py
index 029973a2ef..fee0b9f0a4 100644
--- a/openhands/core/config/agent_config.py
+++ b/openhands/core/config/agent_config.py
@@ -29,7 +29,7 @@ class AgentConfig(BaseModel):
enable_prompt_extensions: bool = Field(default=True)
disabled_microagents: list[str] = Field(default_factory=list)
enable_history_truncation: bool = Field(default=True)
- enable_som_visual_browsing: bool = Field(default=False)
+ enable_som_visual_browsing: bool = Field(default=True)
condenser: CondenserConfig = Field(
default_factory=lambda: NoOpCondenserConfig(type='noop')
)
diff --git a/openhands/memory/conversation_memory.py b/openhands/memory/conversation_memory.py
index 8440fd6eda..5858639fb0 100644
--- a/openhands/memory/conversation_memory.py
+++ b/openhands/memory/conversation_memory.py
@@ -347,8 +347,6 @@ class ConversationMemory:
text = obs.get_agent_obs_text()
if (
obs.trigger_by_action == ActionType.BROWSE_INTERACTIVE
- and obs.set_of_marks is not None
- and len(obs.set_of_marks) > 0
and enable_som_visual_browsing
and vision_is_active
):
@@ -357,14 +355,27 @@ class ConversationMemory:
role='user',
content=[
TextContent(text=text),
- ImageContent(image_urls=[obs.set_of_marks]),
+ ImageContent(
+ image_urls=[
+ # show set of marks if it exists
+ # otherwise, show raw screenshot when using vision-supported model
+ obs.set_of_marks
+ if obs.set_of_marks is not None
+ and len(obs.set_of_marks) > 0
+ else obs.screenshot
+ ]
+ ),
],
)
+ logger.debug(
+ f'Vision enabled for browsing, showing {"set of marks" if obs.set_of_marks and len(obs.set_of_marks) > 0 else "screenshot"}'
+ )
else:
message = Message(
role='user',
content=[TextContent(text=text)],
)
+ logger.debug('Vision disabled for browsing, showing text')
elif isinstance(obs, AgentDelegateObservation):
text = truncate_content(
obs.outputs['content'] if 'content' in obs.outputs else '',
diff --git a/openhands/runtime/action_execution_server.py b/openhands/runtime/action_execution_server.py
index 84c1e6d0d4..40971801b2 100644
--- a/openhands/runtime/action_execution_server.py
+++ b/openhands/runtime/action_execution_server.py
@@ -20,7 +20,7 @@ from zipfile import ZipFile
from fastapi import Depends, FastAPI, HTTPException, Request, UploadFile
from fastapi.exceptions import RequestValidationError
-from fastapi.responses import FileResponse, JSONResponse
+from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
from fastapi.security import APIKeyHeader
from openhands_aci.editor.editor import OHEditor
from openhands_aci.editor.exceptions import ToolError
@@ -58,6 +58,7 @@ from openhands.runtime.browser import browse
from openhands.runtime.browser.browser_env import BrowserEnv
from openhands.runtime.plugins import ALL_PLUGINS, JupyterPlugin, Plugin, VSCodePlugin
from openhands.runtime.utils.bash import BashSession
+from openhands.runtime.utils.file_viewer import generate_file_viewer_html
from openhands.runtime.utils.files import insert_lines, read_lines
from openhands.runtime.utils.memory_monitor import MemoryMonitor
from openhands.runtime.utils.runtime_init import init_user_and_working_directory
@@ -531,6 +532,11 @@ if __name__ == '__main__':
# example: python client.py 8000 --working-dir /workspace --plugins JupyterRequirement
args = parser.parse_args()
+ port_path = '/tmp/oh-server-url'
+ os.makedirs(os.path.dirname(port_path), exist_ok=True)
+ with open(port_path, 'w') as f:
+ f.write(f'http://127.0.0.1:{args.port}')
+
plugins_to_load: list[Plugin] = []
if args.plugins:
for plugin in args.plugins:
@@ -811,5 +817,53 @@ if __name__ == '__main__':
logger.error(f'Error listing files: {e}')
return []
+ @app.get('/view')
+ async def view_file(path: str, request: Request):
+ """View a file using an embedded viewer.
+
+ Args:
+ path (str): The absolute path of the file to view.
+ request (Request): The FastAPI request object.
+
+ Returns:
+ HTMLResponse: An HTML page with an appropriate viewer for the file.
+ """
+ # Security check: Only allow requests from localhost
+ client_host = request.client.host if request.client else None
+ if client_host not in ['127.0.0.1', 'localhost', '::1']:
+ logger.warning(f'Unauthorized file view attempt from {client_host}')
+ return HTMLResponse(
+ content='<h1>Access Denied</h1><p>This endpoint is only accessible from localhost</p>',
+ status_code=403,
+ )
+
+ if not os.path.isabs(path):
+ return HTMLResponse(
+ content=f'<h1>Error: Path must be absolute</h1><p>{path}</p>',
+ status_code=400,
+ )
+
+ if not os.path.exists(path):
+ return HTMLResponse(
+ content=f'<h1>Error: File not found</h1><p>{path}</p>', status_code=404
+ )
+
+ if os.path.isdir(path):
+ return HTMLResponse(
+ content=f'<h1>Error: Path is a directory</h1><p>{path}</p>',
+ status_code=400,
+ )
+
+ try:
+ html_content = generate_file_viewer_html(path)
+ return HTMLResponse(content=html_content)
+
+ except Exception as e:
+ logger.error(f'Error serving file viewer: {str(e)}')
+ return HTMLResponse(
+ content=f'<h1>Error viewing file</h1><p>{path}</p><p>{str(e)}</p>',
+ status_code=500,
+ )
+
logger.debug(f'Starting action execution API on port {args.port}')
run(app, host='0.0.0.0', port=args.port)
diff --git a/openhands/runtime/utils/file_viewer.py b/openhands/runtime/utils/file_viewer.py
new file mode 100644
index 0000000000..7c765790eb
--- /dev/null
+++ b/openhands/runtime/utils/file_viewer.py
@@ -0,0 +1,146 @@
+"""
+Utility module for generating file viewer HTML content.
+"""
+
+import base64
+import mimetypes
+import os
+
+
+def generate_file_viewer_html(file_path: str) -> str:
+ """
+ Generate HTML content for viewing different file types.
+
+ Args:
+ file_path: The absolute path to the file
+
+ Returns:
+ str: HTML content for viewing the file
+
+ Raises:
+ ValueError: If the file extension is not supported
+ """
+ file_extension = os.path.splitext(file_path)[1].lower()
+ file_name = os.path.basename(file_path)
+
+ # Define supported file extensions
+ supported_extensions = [
+ '.pdf',
+ '.png',
+ '.jpg',
+ '.jpeg',
+ '.gif',
+ ]
+
+ # Check if the file extension is supported
+ if file_extension not in supported_extensions:
+ raise ValueError(
+ f"Unsupported file extension: {file_extension}. "
+ f"Supported extensions are: {', '.join(supported_extensions)}"
+ )
+
+ # Check if the file exists
+ if not os.path.exists(file_path):
+ raise ValueError(
+ f'File not found locally: {file_path}. Please download the file to the local machine and try again.'
+ )
+
+ # Read file content directly
+ file_content = None
+ mime_type = mimetypes.guess_type(file_path)[0] or 'application/octet-stream'
+
+ # For binary files (images, PDFs), encode as base64
+ if file_extension in ['.pdf', '.png', '.jpg', '.jpeg', '.gif', '.bmp']:
+ with open(file_path, 'rb') as file:
+ file_content = base64.b64encode(file.read()).decode('utf-8')
+ # For text files, read as text
+ else:
+ with open(file_path, 'r', encoding='utf-8') as file:
+ file_content = file.read()
+
+ return f"""<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>File Viewer - {file_name}</title>
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script>
+ <style>
+ body, html {{ margin: 0; padding: 0; height: 100%; overflow: hidden; font-family: Arial, sans-serif; }}
+ #viewer-container {{ width: 100%; height: 100vh; overflow: auto; }}
+ .page {{ margin: 10px auto; box-shadow: 0 0 10px rgba(0,0,0,0.3); }}
+ .text-content {{ margin: 20px; white-space: pre-wrap; font-family: monospace; line-height: 1.5; }}
+ .error {{ color: red; margin: 20px; }}
+ img {{ max-width: 100%; margin: 20px auto; display: block; }}
+ </style>
+</head>
+<body>
+ <div id="viewer-container"></div>
+ <script>
+ const filePath = "{file_path}";
+ const fileExtension = "{file_extension}";
+ const fileContent = `{file_content if file_extension not in ['.pdf', '.png', '.jpg', '.jpeg', '.gif', '.bmp'] else ''}`;
+ const fileBase64 = "{file_content if file_extension in ['.pdf', '.png', '.jpg', '.jpeg', '.gif', '.bmp'] else ''}";
+ const mimeType = "{mime_type}";
+ const container = document.getElementById('viewer-container');
+
+ async function loadContent() {{
+ try {{
+ if (fileExtension === '.pdf') {{
+ pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';
+ const binaryString = atob(fileBase64);
+ const bytes = new Uint8Array(binaryString.length);
+ for (let i = 0; i < binaryString.length; i++) {{
+ bytes[i] = binaryString.charCodeAt(i);
+ }}
+
+ const loadingTask = pdfjsLib.getDocument({{data: bytes.buffer}});
+ const pdf = await loadingTask.promise;
+
+ // Get total number of pages
+ const numPages = pdf.numPages;
+
+ // Render each page
+ for (let pageNum = 1; pageNum <= numPages; pageNum++) {{
+ const page = await pdf.getPage(pageNum);
+
+ // Set scale for rendering
+ const viewport = page.getViewport({{ scale: 1.5 }});
+
+ // Create canvas for rendering
+ const canvas = document.createElement('canvas');
+ canvas.className = 'page';
+ canvas.width = viewport.width;
+ canvas.height = viewport.height;
+ container.appendChild(canvas);
+
+ // Render PDF page into canvas context
+ const context = canvas.getContext('2d');
+ const renderContext = {{
+ canvasContext: context,
+ viewport: viewport
+ }};
+
+ await page.render(renderContext).promise;
+ }}
+ }} else if (['.png', '.jpg', '.jpeg', '.gif', '.bmp'].includes(fileExtension)) {{
+ const img = document.createElement('img');
+ img.src = `data:${{mimeType}};base64,${{fileBase64}}`;
+ img.alt = filePath.split('/').pop();
+ container.appendChild(img);
+ }} else {{
+ const pre = document.createElement('pre');
+ pre.className = 'text-content';
+ pre.textContent = fileContent;
+ container.appendChild(pre);
+ }}
+ }} catch (error) {{
+ console.error('Error:', error);
+ container.innerHTML = `<div class="error"><h2>Error loading file</h2><p>${{error.message}}</p></div>`;
+ }}
+ }}
+
+ window.onload = loadContent;
+ </script>
+</body>
+</html>"""
diff --git a/openhands/server/routes/settings.py b/openhands/server/routes/settings.py
index ceee072c87..73442b079a 100644
--- a/openhands/server/routes/settings.py
+++ b/openhands/server/routes/settings.py
@@ -42,9 +42,7 @@ async def load_settings(request: Request) -> GETSettingsModel | JSONResponse:
@app.post('/unset-settings-tokens', response_model=dict[str, str])
-async def unset_settings_tokens(
- request: Request
-) -> JSONResponse:
+async def unset_settings_tokens(request: Request) -> JSONResponse:
try:
settings_store = await SettingsStoreImpl.get_instance(
config, get_user_id(request)
@@ -52,24 +50,26 @@ async def unset_settings_tokens(
existing_settings = await settings_store.load()
if existing_settings:
- settings = existing_settings.model_copy(update={'secrets_store': SecretStore()})
+ settings = existing_settings.model_copy(
+ update={'secrets_store': SecretStore()}
+ )
await settings_store.store(settings)
-
+
return JSONResponse(
status_code=status.HTTP_200_OK,
content={'message': 'Settings stored'},
)
-
+
except Exception as e:
logger.warning(f'Something went wrong unsetting tokens: {e}')
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content={'error': 'Something went wrong unsetting tokens'},
)
+
+
@app.post('/reset-settings', response_model=dict[str, str])
-async def reset_settings(
- request: Request
-) -> JSONResponse:
+async def reset_settings(request: Request) -> JSONResponse:
"""
Resets user settings.
"""
@@ -79,23 +79,28 @@ async def reset_settings(
)
existing_settings = await settings_store.load()
- settings = Settings(language="en",
- agent="CodeActAgent",
- security_analyzer="",
- confirmation_mode=False,
- llm_model="anthropic/claude-3-5-sonnet-20241022",
- llm_api_key="",
- llm_base_url="",
- remote_runtime_resource_factor=1,
- enable_default_condenser=True,
- enable_sound_notifications=False,
- user_consents_to_analytics=existing_settings.user_consents_to_analytics if existing_settings else False
- )
-
+ settings = Settings(
+ language='en',
+ agent='CodeActAgent',
+ security_analyzer='',
+ confirmation_mode=False,
+ llm_model='anthropic/claude-3-5-sonnet-20241022',
+ llm_api_key='',
+ llm_base_url='',
+ remote_runtime_resource_factor=1,
+ enable_default_condenser=True,
+ enable_sound_notifications=False,
+ user_consents_to_analytics=existing_settings.user_consents_to_analytics
+ if existing_settings
+ else False,
+ )
+
server_config_values = server_config.get_config()
- is_hide_llm_settings_enabled = server_config_values.get("FEATURE_FLAGS", {}).get("HIDE_LLM_SETTINGS", False)
+ is_hide_llm_settings_enabled = server_config_values.get(
+ 'FEATURE_FLAGS', {}
+ ).get('HIDE_LLM_SETTINGS', False)
# We don't want the user to be able to modify these settings in SaaS
- if (server_config.app_mode == AppMode.SAAS and is_hide_llm_settings_enabled):
+ if server_config.app_mode == AppMode.SAAS and is_hide_llm_settings_enabled:
if existing_settings:
settings.llm_api_key = existing_settings.llm_api_key
settings.llm_base_url = existing_settings.llm_base_url
@@ -106,7 +111,7 @@ async def reset_settings(
status_code=status.HTTP_200_OK,
content={'message': 'Settings stored'},
)
-
+
except Exception as e:
logger.warning(f'Something went wrong resetting settings: {e}')
return JSONResponse(
@@ -114,6 +119,7 @@ async def reset_settings(
content={'error': 'Something went wrong resetting settings'},
)
+
@app.post('/settings', response_model=dict[str, str])
async def store_settings(
request: Request,
diff --git a/tests/runtime/test_browsing.py b/tests/runtime/test_browsing.py
index 32b7950796..b8937f5c9f 100644
--- a/tests/runtime/test_browsing.py
+++ b/tests/runtime/test_browsing.py
@@ -1,9 +1,12 @@
"""Browsing-related tests for the DockerRuntime, which connects to the ActionExecutor running in the sandbox."""
+import os
+
from conftest import _close_test_runtime, _load_runtime
from openhands.core.logger import openhands_logger as logger
from openhands.events.action import (
+ BrowseInteractiveAction,
BrowseURLAction,
CmdRunAction,
)
@@ -60,3 +63,112 @@ def test_simple_browse(temp_dir, runtime_cls, run_as_openhands):
assert obs.exit_code == 0
_close_test_runtime(runtime)
+
+
+def test_read_pdf_browse(temp_dir, runtime_cls, run_as_openhands):
+ runtime, config = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
+ try:
+ # Create a PDF file using reportlab in the host environment
+ from reportlab.lib.pagesizes import letter
+ from reportlab.pdfgen import canvas
+
+ pdf_path = os.path.join(temp_dir, 'test_document.pdf')
+ pdf_content = 'This is test content for PDF reading test'
+
+ c = canvas.Canvas(pdf_path, pagesize=letter)
+ # Add more content to make the PDF more robust
+ c.drawString(100, 750, pdf_content)
+ c.drawString(100, 700, 'Additional line for PDF structure')
+ c.drawString(100, 650, 'Third line to ensure valid PDF')
+ # Explicitly set PDF version and ensure proper structure
+ c.setPageCompression(0) # Disable compression for simpler structure
+ c.save()
+
+ # Copy the PDF to the sandbox
+ sandbox_dir = config.workspace_mount_path_in_sandbox
+ runtime.copy_to(pdf_path, sandbox_dir)
+
+ # Start HTTP server
+ action_cmd = CmdRunAction(command='ls -alh')
+ logger.info(action_cmd, extra={'msg_type': 'ACTION'})
+ obs = runtime.run_action(action_cmd)
+ logger.info(obs, extra={'msg_type': 'OBSERVATION'})
+ assert isinstance(obs, CmdOutputObservation)
+ assert obs.exit_code == 0
+ assert 'test_document.pdf' in obs.content
+
+ # Get server url
+ action_cmd = CmdRunAction(command='cat /tmp/oh-server-url')
+ logger.info(action_cmd, extra={'msg_type': 'ACTION'})
+ obs = runtime.run_action(action_cmd)
+ logger.info(obs, extra={'msg_type': 'OBSERVATION'})
+ assert obs.exit_code == 0
+ server_url = obs.content.strip()
+
+ # Browse to the PDF file
+ pdf_url = f'{server_url}/view?path=/workspace/test_document.pdf'
+ action_browse = BrowseInteractiveAction(browser_actions=f'goto("{pdf_url}")')
+ logger.info(action_browse, extra={'msg_type': 'ACTION'})
+ obs = runtime.run_action(action_browse)
+ logger.info(obs, extra={'msg_type': 'OBSERVATION'})
+
+ # Verify the browser observation
+ assert isinstance(obs, BrowserOutputObservation)
+ observation_text = str(obs)
+ assert '[Action executed successfully.]' in observation_text
+ assert 'Canvas' in observation_text
+
+ finally:
+ _close_test_runtime(runtime)
+
+
+def test_read_png_browse(temp_dir, runtime_cls, run_as_openhands):
+ runtime, config = _load_runtime(temp_dir, runtime_cls, run_as_openhands)
+ try:
+ # Create a PNG file using PIL in the host environment
+ from PIL import Image, ImageDraw
+
+ png_path = os.path.join(temp_dir, 'test_image.png')
+ # Create a simple image with text
+ img = Image.new('RGB', (400, 200), color=(255, 255, 255))
+ d = ImageDraw.Draw(img)
+ text = 'This is a test PNG image'
+ d.text((20, 80), text, fill=(0, 0, 0))
+ img.save(png_path)
+
+ # Copy the PNG to the sandbox
+ sandbox_dir = config.workspace_mount_path_in_sandbox
+ runtime.copy_to(png_path, sandbox_dir)
+
+ # Verify the file exists in the sandbox
+ action_cmd = CmdRunAction(command='ls -alh')
+ logger.info(action_cmd, extra={'msg_type': 'ACTION'})
+ obs = runtime.run_action(action_cmd)
+ logger.info(obs, extra={'msg_type': 'OBSERVATION'})
+ assert isinstance(obs, CmdOutputObservation)
+ assert obs.exit_code == 0
+ assert 'test_image.png' in obs.content
+
+ # Get server url
+ action_cmd = CmdRunAction(command='cat /tmp/oh-server-url')
+ logger.info(action_cmd, extra={'msg_type': 'ACTION'})
+ obs = runtime.run_action(action_cmd)
+ logger.info(obs, extra={'msg_type': 'OBSERVATION'})
+ assert obs.exit_code == 0
+ server_url = obs.content.strip()
+
+ # Browse to the PNG file
+ png_url = f'{server_url}/view?path=/workspace/test_image.png'
+ action_browse = BrowseInteractiveAction(browser_actions=f'goto("{png_url}")')
+ logger.info(action_browse, extra={'msg_type': 'ACTION'})
+ obs = runtime.run_action(action_browse)
+ logger.info(obs, extra={'msg_type': 'OBSERVATION'})
+
+ # Verify the browser observation
+ assert isinstance(obs, BrowserOutputObservation)
+ observation_text = str(obs)
+ assert '[Action executed successfully.]' in observation_text
+ assert 'File Viewer - test_image.png' in observation_text
+
+ finally:
+ _close_test_runtime(runtime)