hi again! :wave: i'm wondering what best practices...
# server-api
w
hi again! đź‘‹ i'm wondering what best practices are for passing around an
api.LiveKitAPI
object in a large application in Python. would placing it in a container class with static accessors and mutex locks suffice? how can i ensure it gets properly closed when the process exits? i'm troubleshooting some memory leaks and this is a potential suspect
r
Wow, good to hear from you Aoife. I think this is a representative example that may help you: https://github.com/livekit-examples/python-agents-examples/blob/main/mcp/server.py#L49 I would avoid an static accessor or mutex if possible.
w
hi Chris :) thanks for the pointer! for some reason i was under the impression that i should only have one
LiveKitAPI
object open at any given point, but from this example it seems to not be relevant, so long as they're properly cleaned up?
r
@jolly-air-155 can correct me but that is how I understand it.
👍 1
j
w
@jolly-air-155 not using Agents in this context… just the API. my question is whether creating the API object for one-off actions and then immediately closing it is faster/safer/generally more recommended than creating it once and passing it around?
j
I think both
async with LiveKitAPI() as api
or cache it for later use should be fine, like in job ctx it’s defined as
Copy code
@functools.cached_property
    def api(self) -> api.LiveKitAPI:
        """Returns an LiveKitAPI for making API calls to LiveKit.

        Credentials are sourced from environment variables if not provided explicitly.
        When starting via the worker, values passed in `WorkerOptions` are exported to
        LIVEKIT_URL, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET so this API is always
        usable inside job entrypoints.
        """
        return api.LiveKitAPI(session=http_context.http_session())
if you use your own
aiohttp.ClientSession instance
as session and will close it properly,
api.aclose()
is not needed
w
ah, so the acloser just handles closing the aiohttp object, nothing else?
j
yes
w
wonderful. thank you very much!
good work on agents btw :D