Summary
AgentServerHandler.serve() raises UnboundLocalError: cannot access local variable 'os' when port is passed explicitly and agent.base_url is already set (e.g. via callback_url= on the Agent constructor).
Repro
from agentfield import Agent
app = Agent(
node_id="demo",
agentfield_server="https://example.invalid",
callback_url="http://demo.local:8001",
)
if __name__ == "__main__":
app.serve(host="0.0.0.0", port=8001)
Traceback (most recent call last):
File ".../main.py", line 49, in <module>
app.serve(host="0.0.0.0", port=8001)
File ".../agentfield/agent_server.py", line 1140, in serve
env_log_level = os.getenv("UVICORN_LOG_LEVEL", log_level).lower()
^^
UnboundLocalError: cannot access local variable 'os' where it is not associated with a value
Root cause
agent_server.py imports os at module level (line 3), but serve() also contains two import os statements inside conditional branches:
- Line 838 — only runs when
port is None
- Line 902 — only runs when
not self.agent.base_url
Because Python's compiler treats any name assigned anywhere in a function (including via import) as local for the entire function scope, those nested imports shadow the module-level os throughout serve(). When neither branch executes (explicit port + explicit callback_url), the local os is declared but never bound, and line 1140's os.getenv(...) raises UnboundLocalError.
Fix
Drop the two redundant import os lines inside serve() — the module-level import already covers them.
@@ line ~838 @@
if port is None:
# Check for AgentField CLI integration via environment variable
- import os
-
env_port = os.getenv("PORT")
@@ line ~902 @@
if not self.agent.base_url:
# Check AGENT_CALLBACK_URL environment variable before defaulting to localhost
- import os
import urllib.parse
env_callback_url = os.getenv("AGENT_CALLBACK_URL")
Environment
agentfield 0.1.9
- Python 3.14
- macOS (Darwin 25.3.0, arm64)
Summary
AgentServerHandler.serve()raisesUnboundLocalError: cannot access local variable 'os'whenportis passed explicitly andagent.base_urlis already set (e.g. viacallback_url=on theAgentconstructor).Repro
Root cause
agent_server.pyimportsosat module level (line 3), butserve()also contains twoimport osstatements inside conditional branches:port is Nonenot self.agent.base_urlBecause Python's compiler treats any name assigned anywhere in a function (including via
import) as local for the entire function scope, those nested imports shadow the module-levelosthroughoutserve(). When neither branch executes (explicitport+ explicitcallback_url), the localosis declared but never bound, and line 1140'sos.getenv(...)raisesUnboundLocalError.Fix
Drop the two redundant
import oslines insideserve()— the module-level import already covers them.Environment
agentfield0.1.9