Skip to content

Memory leak of Agent #2008

@8lank

Description

@8lank

Describe the bug

Agent is leaking after a run completion.

Debug information

  • Agents SDK version: (e.g. v0.3.3)
  • Python version (e.g. Python 3.13)

Repro steps

async def probe():
    agent = Agent(
        name="Leaker",
        instructions="You are an agent who answers questions",
    )
    wr = weakref.ref(agent)

    result = await Runner.run(agent, "What is the capital of France?")
    print(
        result.context_wrapper.usage.input_tokens,
        result.context_wrapper.usage.output_tokens,
    )

    agent = None
    result = None
    gc.collect()

    return wr


async def prove_leak():
    wr = await probe()
    print("You are indeed a leaker:", wr() is not None)


async def main() -> None:
    await prove_leak()


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

This is likely due to MessageOutputItem keeping a strong ref to Agent.

Expected behavior

No leak should happen.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions