Skip to content

UnboundLocalError: cannot access 'next_node' when running with PYTHONOPTIMIZE=1 #1261

@jmortiz-syc

Description

@jmortiz-syc

Initial Checks

Description

I'm building a conversational tool based on AI agents using Pydantic AI. When deploying to AWS Lambda I found the following error:

... File ".../.venv/lib/python3.11/site-packages/pydantic_ai/_agent_graph.py", line 379, in run return next_node UnboundLocalError: cannot access local variable 'next_node' where it is not associated with a value

I was trying to replicate the error in my local environment and found that the issue was due to the Dockerfile used for deployment defining the environment variable PYTHONOPTIMIZE=1, as is usually done for this type of deployment.

Indeed, when the example code below is run with python script.py, no issues occur, but when it is run with python -O script.py (equivalent to PYTHONOPTIMIZE=1), the reported error appears.

Example Code

from pydantic_ai import Agent
import asyncio

agent = Agent('openai:gpt-4o-mini-2024-07-18')

async def main():
    result = await agent.run('What is the capital of France?')
    print(result.data)

if __name__ == '__main__':
    asyncio.run(main())

Python, Pydantic AI & LLM client version

Python version: 3.11
pydantic-ai version: 0.0.46
LLM: 'openai:gpt-4o-mini-2024-07-18'

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions