Skip to content

UnboundLocalError: 'os' in serve() when both port and callback_url are explicit #561

@code-tmpl

Description

@code-tmpl

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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions