Skip to content

Commit

Permalink
feat(autogpt/cli): Check if port is available before running server (S…
Browse files Browse the repository at this point in the history
  • Loading branch information
kcze authored Mar 16, 2024
1 parent dfad535 commit fea62a7
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
9 changes: 9 additions & 0 deletions autogpts/autogpt/autogpt/app/agent_protocol_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
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
Expand Down Expand Up @@ -64,6 +65,14 @@ def __init__(
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(
Expand Down
10 changes: 10 additions & 0 deletions autogpts/autogpt/autogpt/app/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import logging
import os
import re
import socket
import sys
from pathlib import Path
from typing import TYPE_CHECKING
Expand Down Expand Up @@ -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

0 comments on commit fea62a7

Please sign in to comment.