with or async with on AgentTeam to automatically close connections, memory stores, and per-agent resources when your workflow finishes.
Quick Start
How It Works
| Entry Point | Method | Description |
|---|---|---|
with team: | __enter__ / __exit__ | Sync context manager - calls close() on exit |
async with team: | __aenter__ / __aexit__ | Async context manager - prefers aclose() when available |
| Manual cleanup | team.close() | Explicit cleanup call |
Choosing the right approach
Common Patterns
Using with shared memory
Using inside FastAPI endpoint
Explicit cleanup in long-running worker
User interaction flow
A user sends a research request to your FastAPI application. The endpoint creates an AgentTeam with a research agent inside anasync with block. The agent uses ChromaDB for memory storage and external APIs for research. When the request completes successfully or fails with an exception, the async with block automatically calls close(), ensuring ChromaDB connections, agent resources, and any open file handles are properly released without manual intervention.
Best Practices
Always prefer context managers over manual close()
Always prefer context managers over manual close()
Use
with or async with instead of calling close() manually. Context managers guarantee cleanup even when exceptions occur.Cleanup is best-effort - failures are logged, never raised
Cleanup is best-effort - failures are logged, never raised
Resource cleanup failures are logged as warnings but don’t raise exceptions. This prevents cleanup failures from masking the original issue.
Don't reuse a team after exiting its with block
Don't reuse a team after exiting its with block
Once you exit a
with block, consider the AgentTeam closed. Create a new one for additional work.For multi-request servers, create one team per request
For multi-request servers, create one team per request
Instead of sharing an AgentTeam across requests, create one team per request inside the
with block. This isolates resources and prevents connection leaks.Configuration Options
| Method | Async | Description |
|---|---|---|
close() | No | Closes all agents, shared memory, and context manager resources. Best-effort; logs warnings on failure. |
__enter__ / __exit__ | No | Enables with team: … — calls close() on exit. |
__aenter__ / __aexit__ | Yes | Enables async with team: … — prefers aclose() on agents/memory when available, falls back to sync close(). |
Auto-generated SDK reference
Related
Agent Management
Core agent concepts and configuration
Memory Systems
Shared memory stores that benefit from automatic cleanup

