π OpenHands: AI-Driven Development
Runtime build fixes for OpenHands as a python library (#3989)
Boxuan Li568c8ce9936f
diff --git a/.github/workflows/pypi-release.yml b/.github/workflows/pypi-release.ymlindex 79a4d8a0de..f7228697b8 100644--- a/.github/workflows/pypi-release.yml+++ b/.github/workflows/pypi-release.yml@@ -26,6 +26,6 @@ jobs:- name: Install Poetry Dependenciesrun: poetry install --no-interaction --no-root- name: Build poetry project- run: poetry build -v+ run: ./build.sh- name: publishrun: poetry publish -u __token__ -p ${{ secrets.PYPI_TOKEN }}diff --git a/build.sh b/build.shnew file mode 100755index 0000000000..5bbad4bdfc--- /dev/null+++ b/build.sh@@ -0,0 +1,5 @@+#!/bin/bash+set -e++cp pyproject.toml poetry.lock openhands+poetry build -vdiff --git a/openhands/__init__.py b/openhands/__init__.pyindex 885a4267f9..dfd64a7440 100644--- a/openhands/__init__.py+++ b/openhands/__init__.py@@ -1,12 +1,14 @@import os+__package_name__ = 'openhands_ai'+def get_version():try:from importlib.metadata import PackageNotFoundError, versiontry:- return version('openhands-ai')+ return version(__package_name__)except PackageNotFoundError:passexcept ImportError:@@ -16,7 +18,7 @@ def get_version():from pkg_resources import DistributionNotFound, get_distributiontry:- return get_distribution('openhands-ai').version+ return get_distribution(__package_name__).versionexcept DistributionNotFound:passexcept ImportError:diff --git a/openhands/runtime/utils/runtime_build.py b/openhands/runtime/utils/runtime_build.pyindex 2316e23c02..92d4805330 100644--- a/openhands/runtime/utils/runtime_build.py+++ b/openhands/runtime/utils/runtime_build.py@@ -1,8 +1,8 @@import argparseimport hashlib+import importlib.metadataimport osimport shutil-import subprocessimport tempfileimport docker@@ -10,6 +10,7 @@ from dirhash import dirhashfrom jinja2 import Environment, FileSystemLoaderimport openhands+from openhands import __package_name__from openhands import __version__ as oh_versionfrom openhands.core.logger import openhands_logger as loggerfrom openhands.runtime.builder import DockerRuntimeBuilder, RuntimeBuilder@@ -22,55 +23,50 @@ def get_runtime_image_repo():def _put_source_code_to_dir(temp_dir: str):"""Builds the project source tarball directly in temp_dir and unpacks it.The OpenHands source code ends up in the temp_dir/code directory.-Parameters:- temp_dir (str): The directory to put the source code in"""if not os.path.isdir(temp_dir):raise RuntimeError(f'Temp directory {temp_dir} does not exist')- project_root = os.path.dirname(os.path.dirname(os.path.abspath(openhands.__file__)))- logger.info(f'Building source distribution using project root: {project_root}')-- # Fetch the correct version from pyproject.toml- package_version = oh_version- tarball_filename = f'openhands_ai-{package_version}.tar.gz'- tarball_path = os.path.join(temp_dir, tarball_filename)-- # Run "python -m build -s" on project_root to create project tarball directly in temp_dir- _cleaned_project_root = project_root.replace(- ' ', r'\ '- ) # escape spaces in the project root- result = subprocess.run(- f'python -m build -s -o "{temp_dir}" {_cleaned_project_root}',- shell=True,- stdout=subprocess.PIPE,- stderr=subprocess.PIPE,- )- logger.info(result.stdout.decode())- err_logs = result.stderr.decode()- if err_logs:- logger.error(err_logs)-- if result.returncode != 0:- logger.error(f'Image build failed:\n{result}')- raise RuntimeError(f'Image build failed:\n{result}')-- if not os.path.exists(tarball_path):- logger.error(f'Source distribution not found at {tarball_path}. (Do you need to run `make build`?)')- raise RuntimeError(f'Source distribution not found at {tarball_path}')- logger.info(f'Source distribution created at {tarball_path}')-- # Unzip the tarball- shutil.unpack_archive(tarball_path, temp_dir)- # Remove the tarball- os.remove(tarball_path)- # Rename the directory containing the code to 'code'- os.rename(- os.path.join(temp_dir, f'openhands_ai-{package_version}'),- os.path.join(temp_dir, 'code'),- )- logger.info(f'Unpacked source code directory: {os.path.join(temp_dir, "code")}')+ dest_dir = os.path.join(temp_dir, 'code')+ openhands_dir = None++ try:+ # Try to get the source directory from the installed package+ distribution = importlib.metadata.distribution(__package_name__)+ source_dir = os.path.dirname(distribution.locate_file(__package_name__))+ openhands_dir = os.path.join(source_dir, 'openhands')+ except importlib.metadata.PackageNotFoundError:+ pass++ if openhands_dir is not None and os.path.isdir(openhands_dir):+ logger.info(f'Package {__package_name__} found')+ shutil.copytree(openhands_dir, os.path.join(dest_dir, 'openhands'))+ # note: "pyproject.toml" and "poetry.lock" are included in the openhands+ # package, so we need to move them out to the top-level directory+ for filename in ['pyproject.toml', 'poetry.lock']:+ shutil.move(os.path.join(dest_dir, 'openhands', filename), dest_dir)+ else:+ # If package is not found, build from source code+ project_root = os.path.dirname(+ os.path.dirname(os.path.abspath(openhands.__file__))+ )+ logger.info(f'Building source distribution using project root: {project_root}')++ # Copy the 'openhands' directory+ openhands_dir = os.path.join(project_root, 'openhands')+ if not os.path.isdir(openhands_dir):+ raise RuntimeError(f"'openhands' directory not found in {project_root}")+ shutil.copytree(openhands_dir, os.path.join(dest_dir, 'openhands'))++ # Copy pyproject.toml and poetry.lock files+ for file in ['pyproject.toml', 'poetry.lock']:+ src_file = os.path.join(project_root, file)+ dest_file = os.path.join(dest_dir, file)+ shutil.copy2(src_file, dest_file)++ logger.info(f'Unpacked source code directory: {dest_dir}')def _generate_dockerfile(diff --git a/pyproject.toml b/pyproject.tomlindex a965a634d6..9704680ac8 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -6,7 +6,6 @@ authors = ["OpenHands"]license = "MIT"readme = "README.md"repository = "https://github.com/All-Hands-AI/OpenHands"-include = ["poetry.lock"]packages = [{ include = "openhands/**/*" }]diff --git a/tests/unit/test_runtime_build.py b/tests/unit/test_runtime_build.pyindex 867305fd59..75d9fbdeec 100644--- a/tests/unit/test_runtime_build.py+++ b/tests/unit/test_runtime_build.py@@ -54,14 +54,12 @@ def _check_source_code_in_dir(temp_dir):# check the source file is the same as the current code baseassert os.path.exists(os.path.join(code_dir, 'pyproject.toml'))- # The source code should only include the `openhands` folder, but not the other folders+ # The source code should only include the `openhands` folder,+ # and pyproject.toml & poetry.lock that are needed to build the runtime imageassert set(os.listdir(code_dir)) == {'openhands','pyproject.toml','poetry.lock',- 'LICENSE',- 'README.md',- 'PKG-INFO',}assert os.path.exists(os.path.join(code_dir, 'openhands'))assert os.path.isdir(os.path.join(code_dir, 'openhands'))