aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGravatar Krzysztof Czerwinski <34861343+kcze@users.noreply.github.com> 2024-03-16 12:10:43 +0100
committerGravatar GitHub <noreply@github.com> 2024-03-16 12:10:43 +0100
commitfea62a77bc3072c3570ab16e050a1b032e0154da (patch)
tree91ff61fb97b6843ea60f9b6a737e898c7aa69a8f
parentfix(docs): Replace `polyfill.io` by Cloudflare mirror (#6952) (diff)
downloadAuto-GPT-fea62a77bc3072c3570ab16e050a1b032e0154da.tar.gz
Auto-GPT-fea62a77bc3072c3570ab16e050a1b032e0154da.tar.bz2
Auto-GPT-fea62a77bc3072c3570ab16e050a1b032e0154da.zip
feat(autogpt/cli): Check if port is available before running server (#6996)
-rw-r--r--autogpts/autogpt/autogpt/app/agent_protocol_server.py9
-rw-r--r--autogpts/autogpt/autogpt/app/utils.py10
2 files changed, 19 insertions, 0 deletions
diff --git a/autogpts/autogpt/autogpt/app/agent_protocol_server.py b/autogpts/autogpt/autogpt/app/agent_protocol_server.py
index 0df2bd13b..dd40545b6 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_state
from autogpt.agent_factory.generators import generate_agent_for_task
from autogpt.agent_manager import AgentManager
from autogpt.agents.utils.exceptions import AgentFinished
+from autogpt.app.utils import is_port_free
from autogpt.commands.system import finish
from autogpt.commands.user_interaction import ask_user
from 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.py
index 7b815e2c7..3e986852b 100644
--- a/autogpts/autogpt/autogpt/app/utils.py
+++ b/autogpts/autogpt/autogpt/app/utils.py
@@ -2,6 +2,7 @@ import contextlib
import logging
import os
import re
+import socket
import sys
from pathlib import Path
from 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