AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(autogpt/cli): Check if port is available before running server (#6996)
Krzysztof Czerwinskifea62a77bc30
diff --git a/autogpts/autogpt/autogpt/app/agent_protocol_server.py b/autogpts/autogpt/autogpt/app/agent_protocol_server.pyindex 0df2bd13b9..dd40545b60 100644--- a/autogpts/autogpt/autogpt/app/agent_protocol_server.py+++ b/autogpts/autogpt/autogpt/app/agent_protocol_server.py@@ -31,6 +31,7 @@ from autogpt.agent_factory.configurators import configure_agent_with_statefrom autogpt.agent_factory.generators import generate_agent_for_taskfrom autogpt.agent_manager import AgentManagerfrom autogpt.agents.utils.exceptions import AgentFinished+from autogpt.app.utils import is_port_freefrom autogpt.commands.system import finishfrom autogpt.commands.user_interaction import ask_userfrom autogpt.config import Config@@ -64,6 +65,14 @@ class AgentProtocolServer:async def start(self, port: int = 8000, router: APIRouter = base_router):"""Start the agent server."""logger.debug("Starting the agent server...")+ if not is_port_free(port):+ logger.error(f"Port {port} is already in use.")+ logger.info(+ "You can specify a port by either setting the AP_SERVER_PORT "+ "environment variable or defining AP_SERVER_PORT in the .env file."+ )+ return+config = HypercornConfig()config.bind = [f"localhost:{port}"]app = FastAPI(diff --git a/autogpts/autogpt/autogpt/app/utils.py b/autogpts/autogpt/autogpt/app/utils.pyindex 7b815e2c73..3e986852b4 100644--- a/autogpts/autogpt/autogpt/app/utils.py+++ b/autogpts/autogpt/autogpt/app/utils.py@@ -2,6 +2,7 @@ import contextlibimport loggingimport osimport re+import socketimport sysfrom pathlib import Pathfrom typing import TYPE_CHECKING@@ -272,3 +273,12 @@ def set_env_config_value(key: str, value: str) -> None:file.write(f"{key}={value}\n")file.truncate()+++def is_port_free(port: int, host: str = "127.0.0.1"):+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:+ try:+ s.bind((host, port)) # Try to bind to the port+ return True # If successful, the port is free+ except OSError:+ return False # If failed, the port is likely in use