Skip to content

Commit 3a99544

Browse files
committed
livekit-api: load the generated Public API client on first use, not on import
1 parent d1fe6e5 commit 3a99544

4 files changed

Lines changed: 55 additions & 21 deletions

File tree

‎livekit-api/livekit/api/database_service.py‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
from google.protobuf.empty_pb2 import Empty
44
from livekit.protocol.agentdb import AgentDB
55

6-
from ._generated.public_api.models import DatabaseServiceCreateDatabaseBody
76
from ._service import PublicApiService
87
from .public_api_client import to_json
98

@@ -33,7 +32,7 @@ async def create_database(self, req: CreateDatabaseRequest) -> CreateDatabaseRes
3332
operation=self._client.databases.database_service_create_database_without_preload_content,
3433
headers=self._auth_header(),
3534
response_class=CreateDatabaseResponse,
36-
database_service_create_database_body=DatabaseServiceCreateDatabaseBody.from_dict(
35+
database_service_create_database_body=self._client.models.DatabaseServiceCreateDatabaseBody.from_dict(
3736
to_json(req)
3837
),
3938
)

‎livekit-api/livekit/api/public_api_client.py‎

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
from __future__ import annotations
1616

17+
import functools
1718
import inspect
1819
import json
1920
from collections.abc import Awaitable
@@ -24,7 +25,6 @@
2425
from google.protobuf import json_format
2526
from google.protobuf.message import Message
2627

27-
from ._generated.public_api import ApiClient, Configuration, DatabaseServiceApi, ThreadServiceApi
2828
from .errors import ServerError, ServerErrorCode
2929
from .version import USER_AGENT
3030

@@ -82,12 +82,37 @@ def __init__(
8282
) -> None:
8383
self.host = public_api_url(host)
8484
self.timeout = timeout.total if timeout and timeout.total else DEFAULT_TIMEOUT
85+
self._session = session
86+
87+
# The generated client (and pydantic) load on the first Public API call, not with
88+
# `import livekit.api`.
89+
@functools.cached_property
90+
def _api(self) -> Any:
91+
from ._generated.public_api import ApiClient, Configuration
92+
8593
api = ApiClient(Configuration(host=self.host))
8694
api.user_agent = USER_AGENT
8795
# Requests go through the caller's session, which this client never closes.
88-
api.rest_client.pool_manager = session
89-
self.threads = ThreadServiceApi(api)
90-
self.databases = DatabaseServiceApi(api)
96+
api.rest_client.pool_manager = self._session
97+
return api
98+
99+
@functools.cached_property
100+
def threads(self) -> Any:
101+
from ._generated.public_api import ThreadServiceApi
102+
103+
return ThreadServiceApi(self._api)
104+
105+
@functools.cached_property
106+
def databases(self) -> Any:
107+
from ._generated.public_api import DatabaseServiceApi
108+
109+
return DatabaseServiceApi(self._api)
110+
111+
@property
112+
def models(self) -> Any:
113+
from ._generated.public_api import models
114+
115+
return models
91116

92117
async def request(
93118
self,

‎livekit-api/livekit/api/thread_service.py‎

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,6 @@
33
from google.protobuf.empty_pb2 import Empty
44
from livekit.protocol.agent_pb.agent_thread import AgentTask, AgentThread
55

6-
from ._generated.public_api.models import (
7-
LivekitAgentAgentTaskStatus,
8-
LivekitPublicapiCommonV1SortOrder,
9-
ThreadServiceCreateThreadBody,
10-
ThreadServiceUpdateThreadBody,
11-
)
126
from ._service import PublicApiService
137
from .public_api_client import to_json
148

@@ -26,11 +20,6 @@
2620
GetThreadTasksRequest = AgentTask.GetTasksRequest
2721
GetThreadTasksResponse = AgentTask.GetTasksResponse
2822

29-
_SORT_ORDERS = {
30-
AgentThread.SORT_ORDER_ASC: LivekitPublicapiCommonV1SortOrder.SORT_ORDER_ASC,
31-
AgentThread.SORT_ORDER_DESC: LivekitPublicapiCommonV1SortOrder.SORT_ORDER_DESC,
32-
}
33-
3423

3524
class ThreadService(PublicApiService):
3625
"""Agent threads: conversations whose chat items, tasks and database outlive any one session.
@@ -51,7 +40,9 @@ async def create_thread(self, req: CreateThreadRequest) -> Thread:
5140
headers=self._auth_header(),
5241
response_class=Thread,
5342
field="thread",
54-
thread_service_create_thread_body=ThreadServiceCreateThreadBody.from_dict(to_json(req)),
43+
thread_service_create_thread_body=self._client.models.ThreadServiceCreateThreadBody.from_dict(
44+
to_json(req)
45+
),
5546
)
5647

5748
async def get_thread(self, *, thread_id: str) -> Thread:
@@ -86,7 +77,9 @@ async def update_thread(self, req: UpdateThreadRequest) -> Thread:
8677
response_class=Thread,
8778
field="thread",
8879
thread_id=req.thread_id,
89-
thread_service_update_thread_body=ThreadServiceUpdateThreadBody.from_dict(body),
80+
thread_service_update_thread_body=self._client.models.ThreadServiceUpdateThreadBody.from_dict(
81+
body
82+
),
9083
)
9184

9285
async def delete_thread(self, *, thread_id: str) -> None:
@@ -109,13 +102,19 @@ async def get_thread_items(self, req: GetThreadItemsRequest) -> GetThreadItemsRe
109102
limit=req.limit,
110103
thread_id=req.thread_id,
111104
agent=req.agent,
112-
sort_order=_SORT_ORDERS.get(req.sort_order),
105+
sort_order=(
106+
self._client.models.LivekitPublicapiCommonV1SortOrder(
107+
ThreadSortOrder.Name(req.sort_order)
108+
)
109+
if req.sort_order
110+
else None
111+
),
113112
)
114113

115114
async def get_thread_tasks(self, req: GetThreadTasksRequest) -> GetThreadTasksResponse:
116115
"""The thread's tasks, oldest first."""
117116
status = (
118-
LivekitAgentAgentTaskStatus(ThreadTaskStatus.Name(req.status))
117+
self._client.models.LivekitAgentAgentTaskStatus(ThreadTaskStatus.Name(req.status))
119118
if req.HasField("status")
120119
else None
121120
)

‎tests/api/test_public_api.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
messages they map the responses onto."""
1818

1919
import asyncio
20+
import subprocess
21+
import sys
2022
import json
2123
from typing import Any, Awaitable, Callable, Dict, List, Optional, Tuple
2224

@@ -354,3 +356,12 @@ async def main() -> Dict[str, Any]:
354356
assert r["pool"] is r["session"]
355357
assert r["host"] == "https://beta-api.livekit.cloud"
356358
assert (r["default"], r["custom"]) == (10.0, 3)
359+
360+
361+
def test_importing_livekit_api_does_not_load_the_generated_client():
362+
code = (
363+
"import sys, livekit.api; "
364+
"assert 'pydantic' not in sys.modules; "
365+
"assert not any(m.startswith('livekit.api._generated') for m in sys.modules)"
366+
)
367+
subprocess.run([sys.executable, "-c", code], check=True)

0 commit comments

Comments
 (0)