Skip to content

Control Plane

BaseControlPlane #

Bases: MessageQueuePublisherMixin, ABC

The control plane for the system.

The control plane is responsible for managing the state of the system, including: - Registering services. - Managing sessions and tasks. - Handling service completion. - Launching the control plane server.

Source code in llama-agents/llama_deploy/control_plane/base.py
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
class BaseControlPlane(MessageQueuePublisherMixin, ABC):
    """The control plane for the system.

    The control plane is responsible for managing the state of the system, including:
    - Registering services.
    - Managing sessions and tasks.
    - Handling service completion.
    - Launching the control plane server.
    """

    @property
    @abstractmethod
    def message_queue(self) -> BaseMessageQueue:
        """Return associated message queue."""

    @abstractmethod
    def as_consumer(self, remote: bool = False) -> BaseMessageQueueConsumer:
        """
        Get the consumer for the message queue.

        Args:
            remote (bool):
                Whether the consumer is remote.
                If True, the consumer will be a RemoteMessageConsumer.

        Returns:
            BaseMessageQueueConsumer: Message queue consumer.
        """
        ...

    @abstractmethod
    async def register_service(self, service_def: ServiceDefinition) -> None:
        """
        Register a service with the control plane.

        Args:
            service_def (ServiceDefinition): Definition of the service.
        """
        ...

    @abstractmethod
    async def deregister_service(self, service_name: str) -> None:
        """
        Deregister a service from the control plane.

        Args:
            service_name (str): Name of the service.
        """
        ...

    @abstractmethod
    async def get_service(self, service_name: str) -> ServiceDefinition:
        """
        Get the definition of a service by name.

        Args:
            service_name (str): Name of the service.

        Returns:
            ServiceDefinition: Definition of the service.
        """
        ...

    @abstractmethod
    async def get_all_services(self) -> Dict[str, ServiceDefinition]:
        """
        Get all services registered with the control plane.

        Returns:
            dict: All services, mapped from service name to service definition.
        """
        ...

    @abstractmethod
    async def create_session(self) -> str:
        """
        Create a new session.

        Returns:
            str: Session ID.
        """
        ...

    @abstractmethod
    async def add_task_to_session(
        self, session_id: str, task_def: TaskDefinition
    ) -> str:
        """
        Add a task to an existing session.

        Args:
            session_id (str): ID of the session.
            task_def (TaskDefinition): Definition of the task.

        Returns:
            str: Task ID.
        """
        ...

    @abstractmethod
    async def send_task_to_service(self, task_def: TaskDefinition) -> TaskDefinition:
        """
        Send a task to a service.

        Args:
            task_def (TaskDefinition): Definition of the task.

        Returns:
            TaskDefinition: Task definition with updated state.
        """
        ...

    @abstractmethod
    async def handle_service_completion(
        self,
        task_result: TaskResult,
    ) -> None:
        """
        Handle the completion of a task by a service.

        Args:
            task_result (TaskResult): Result of the task.
        """
        ...

    @abstractmethod
    async def get_session(self, session_id: str) -> SessionDefinition:
        """
        Get the specified session session.

        Args:
            session_id (str): Unique identifier of the session.

        Returns:
            SessionDefinition: The session definition.
        """
        ...

    @abstractmethod
    async def delete_session(self, session_id: str) -> None:
        """
        Delete the specified session.

        Args:
            session_id (str): Unique identifier of the session.
        """
        ...

    @abstractmethod
    async def get_all_sessions(self) -> Dict[str, SessionDefinition]:
        """
        Get all sessions.

        Returns:
            dict: All sessions, mapped from session ID to session definition.
        """
        ...

    @abstractmethod
    async def get_session_tasks(self, session_id: str) -> List[TaskDefinition]:
        """
        Get all tasks for a session.

        Args:
            session_id (str): Unique identifier of the session.

        Returns:
            List[TaskDefinition]: All tasks in the session.
        """
        ...

    @abstractmethod
    async def get_current_task(self, session_id: str) -> Optional[TaskDefinition]:
        """
        Get the current task for a session.

        Args:
            session_id (str): Unique identifier of the session.

        Returns:
            Optional[TaskDefinition]: The current task, if any.
        """
        ...

    @abstractmethod
    async def get_task(self, task_id: str) -> TaskDefinition:
        """
        Get the specified task.

        Args:
            task_id (str): Unique identifier of the task.

        Returns:
            TaskDefinition: The task definition.
        """
        ...

    @abstractmethod
    async def get_message_queue_config(self) -> Dict[str, dict]:
        """
        Gets the config dict for the message queue being used.

        Returns:
            Dict[str, dict]: A dict of message queue name -> config dict
        """
        ...

    @abstractmethod
    async def launch_server(self) -> None:
        """
        Launch the control plane server.
        """
        ...

    @abstractmethod
    async def register_to_message_queue(self) -> StartConsumingCallable:
        """Register the service to the message queue."""

message_queue abstractmethod property #

message_queue: BaseMessageQueue

Return associated message queue.

as_consumer abstractmethod #

as_consumer(remote: bool = False) -> BaseMessageQueueConsumer

Get the consumer for the message queue.

Parameters:

Name Type Description Default
remote bool

Whether the consumer is remote. If True, the consumer will be a RemoteMessageConsumer.

False

Returns:

Name Type Description
BaseMessageQueueConsumer BaseMessageQueueConsumer

Message queue consumer.

Source code in llama-agents/llama_deploy/control_plane/base.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
@abstractmethod
def as_consumer(self, remote: bool = False) -> BaseMessageQueueConsumer:
    """
    Get the consumer for the message queue.

    Args:
        remote (bool):
            Whether the consumer is remote.
            If True, the consumer will be a RemoteMessageConsumer.

    Returns:
        BaseMessageQueueConsumer: Message queue consumer.
    """
    ...

register_service abstractmethod async #

register_service(service_def: ServiceDefinition) -> None

Register a service with the control plane.

Parameters:

Name Type Description Default
service_def ServiceDefinition

Definition of the service.

required
Source code in llama-agents/llama_deploy/control_plane/base.py
48
49
50
51
52
53
54
55
56
@abstractmethod
async def register_service(self, service_def: ServiceDefinition) -> None:
    """
    Register a service with the control plane.

    Args:
        service_def (ServiceDefinition): Definition of the service.
    """
    ...

deregister_service abstractmethod async #

deregister_service(service_name: str) -> None

Deregister a service from the control plane.

Parameters:

Name Type Description Default
service_name str

Name of the service.

required
Source code in llama-agents/llama_deploy/control_plane/base.py
58
59
60
61
62
63
64
65
66
@abstractmethod
async def deregister_service(self, service_name: str) -> None:
    """
    Deregister a service from the control plane.

    Args:
        service_name (str): Name of the service.
    """
    ...

get_service abstractmethod async #

get_service(service_name: str) -> ServiceDefinition

Get the definition of a service by name.

Parameters:

Name Type Description Default
service_name str

Name of the service.

required

Returns:

Name Type Description
ServiceDefinition ServiceDefinition

Definition of the service.

Source code in llama-agents/llama_deploy/control_plane/base.py
68
69
70
71
72
73
74
75
76
77
78
79
@abstractmethod
async def get_service(self, service_name: str) -> ServiceDefinition:
    """
    Get the definition of a service by name.

    Args:
        service_name (str): Name of the service.

    Returns:
        ServiceDefinition: Definition of the service.
    """
    ...

get_all_services abstractmethod async #

get_all_services() -> Dict[str, ServiceDefinition]

Get all services registered with the control plane.

Returns:

Name Type Description
dict Dict[str, ServiceDefinition]

All services, mapped from service name to service definition.

Source code in llama-agents/llama_deploy/control_plane/base.py
81
82
83
84
85
86
87
88
89
@abstractmethod
async def get_all_services(self) -> Dict[str, ServiceDefinition]:
    """
    Get all services registered with the control plane.

    Returns:
        dict: All services, mapped from service name to service definition.
    """
    ...

create_session abstractmethod async #

create_session() -> str

Create a new session.

Returns:

Name Type Description
str str

Session ID.

Source code in llama-agents/llama_deploy/control_plane/base.py
91
92
93
94
95
96
97
98
99
@abstractmethod
async def create_session(self) -> str:
    """
    Create a new session.

    Returns:
        str: Session ID.
    """
    ...

add_task_to_session abstractmethod async #

add_task_to_session(session_id: str, task_def: TaskDefinition) -> str

Add a task to an existing session.

Parameters:

Name Type Description Default
session_id str

ID of the session.

required
task_def TaskDefinition

Definition of the task.

required

Returns:

Name Type Description
str str

Task ID.

Source code in llama-agents/llama_deploy/control_plane/base.py
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
@abstractmethod
async def add_task_to_session(
    self, session_id: str, task_def: TaskDefinition
) -> str:
    """
    Add a task to an existing session.

    Args:
        session_id (str): ID of the session.
        task_def (TaskDefinition): Definition of the task.

    Returns:
        str: Task ID.
    """
    ...

send_task_to_service abstractmethod async #

send_task_to_service(task_def: TaskDefinition) -> TaskDefinition

Send a task to a service.

Parameters:

Name Type Description Default
task_def TaskDefinition

Definition of the task.

required

Returns:

Name Type Description
TaskDefinition TaskDefinition

Task definition with updated state.

Source code in llama-agents/llama_deploy/control_plane/base.py
117
118
119
120
121
122
123
124
125
126
127
128
@abstractmethod
async def send_task_to_service(self, task_def: TaskDefinition) -> TaskDefinition:
    """
    Send a task to a service.

    Args:
        task_def (TaskDefinition): Definition of the task.

    Returns:
        TaskDefinition: Task definition with updated state.
    """
    ...

handle_service_completion abstractmethod async #

handle_service_completion(task_result: TaskResult) -> None

Handle the completion of a task by a service.

Parameters:

Name Type Description Default
task_result TaskResult

Result of the task.

required
Source code in llama-agents/llama_deploy/control_plane/base.py
130
131
132
133
134
135
136
137
138
139
140
141
@abstractmethod
async def handle_service_completion(
    self,
    task_result: TaskResult,
) -> None:
    """
    Handle the completion of a task by a service.

    Args:
        task_result (TaskResult): Result of the task.
    """
    ...

get_session abstractmethod async #

get_session(session_id: str) -> SessionDefinition

Get the specified session session.

Parameters:

Name Type Description Default
session_id str

Unique identifier of the session.

required

Returns:

Name Type Description
SessionDefinition SessionDefinition

The session definition.

Source code in llama-agents/llama_deploy/control_plane/base.py
143
144
145
146
147
148
149
150
151
152
153
154
@abstractmethod
async def get_session(self, session_id: str) -> SessionDefinition:
    """
    Get the specified session session.

    Args:
        session_id (str): Unique identifier of the session.

    Returns:
        SessionDefinition: The session definition.
    """
    ...

delete_session abstractmethod async #

delete_session(session_id: str) -> None

Delete the specified session.

Parameters:

Name Type Description Default
session_id str

Unique identifier of the session.

required
Source code in llama-agents/llama_deploy/control_plane/base.py
156
157
158
159
160
161
162
163
164
@abstractmethod
async def delete_session(self, session_id: str) -> None:
    """
    Delete the specified session.

    Args:
        session_id (str): Unique identifier of the session.
    """
    ...

get_all_sessions abstractmethod async #

get_all_sessions() -> Dict[str, SessionDefinition]

Get all sessions.

Returns:

Name Type Description
dict Dict[str, SessionDefinition]

All sessions, mapped from session ID to session definition.

Source code in llama-agents/llama_deploy/control_plane/base.py
166
167
168
169
170
171
172
173
174
@abstractmethod
async def get_all_sessions(self) -> Dict[str, SessionDefinition]:
    """
    Get all sessions.

    Returns:
        dict: All sessions, mapped from session ID to session definition.
    """
    ...

get_session_tasks abstractmethod async #

get_session_tasks(session_id: str) -> List[TaskDefinition]

Get all tasks for a session.

Parameters:

Name Type Description Default
session_id str

Unique identifier of the session.

required

Returns:

Type Description
List[TaskDefinition]

List[TaskDefinition]: All tasks in the session.

Source code in llama-agents/llama_deploy/control_plane/base.py
176
177
178
179
180
181
182
183
184
185
186
187
@abstractmethod
async def get_session_tasks(self, session_id: str) -> List[TaskDefinition]:
    """
    Get all tasks for a session.

    Args:
        session_id (str): Unique identifier of the session.

    Returns:
        List[TaskDefinition]: All tasks in the session.
    """
    ...

get_current_task abstractmethod async #

get_current_task(session_id: str) -> Optional[TaskDefinition]

Get the current task for a session.

Parameters:

Name Type Description Default
session_id str

Unique identifier of the session.

required

Returns:

Type Description
Optional[TaskDefinition]

Optional[TaskDefinition]: The current task, if any.

Source code in llama-agents/llama_deploy/control_plane/base.py
189
190
191
192
193
194
195
196
197
198
199
200
@abstractmethod
async def get_current_task(self, session_id: str) -> Optional[TaskDefinition]:
    """
    Get the current task for a session.

    Args:
        session_id (str): Unique identifier of the session.

    Returns:
        Optional[TaskDefinition]: The current task, if any.
    """
    ...

get_task abstractmethod async #

get_task(task_id: str) -> TaskDefinition

Get the specified task.

Parameters:

Name Type Description Default
task_id str

Unique identifier of the task.

required

Returns:

Name Type Description
TaskDefinition TaskDefinition

The task definition.

Source code in llama-agents/llama_deploy/control_plane/base.py
202
203
204
205
206
207
208
209
210
211
212
213
@abstractmethod
async def get_task(self, task_id: str) -> TaskDefinition:
    """
    Get the specified task.

    Args:
        task_id (str): Unique identifier of the task.

    Returns:
        TaskDefinition: The task definition.
    """
    ...

get_message_queue_config abstractmethod async #

get_message_queue_config() -> Dict[str, dict]

Gets the config dict for the message queue being used.

Returns:

Type Description
Dict[str, dict]

Dict[str, dict]: A dict of message queue name -> config dict

Source code in llama-agents/llama_deploy/control_plane/base.py
215
216
217
218
219
220
221
222
223
@abstractmethod
async def get_message_queue_config(self) -> Dict[str, dict]:
    """
    Gets the config dict for the message queue being used.

    Returns:
        Dict[str, dict]: A dict of message queue name -> config dict
    """
    ...

launch_server abstractmethod async #

launch_server() -> None

Launch the control plane server.

Source code in llama-agents/llama_deploy/control_plane/base.py
225
226
227
228
229
230
@abstractmethod
async def launch_server(self) -> None:
    """
    Launch the control plane server.
    """
    ...

register_to_message_queue abstractmethod async #

register_to_message_queue() -> StartConsumingCallable

Register the service to the message queue.

Source code in llama-agents/llama_deploy/control_plane/base.py
232
233
234
@abstractmethod
async def register_to_message_queue(self) -> StartConsumingCallable:
    """Register the service to the message queue."""

ControlPlaneServer #

Bases: BaseControlPlane

Control plane server.

The control plane is responsible for managing the state of the system, including: - Registering services. - Submitting tasks. - Managing task state. - Handling service completion. - Launching the control plane server.

Parameters:

Name Type Description Default
message_queue BaseMessageQueue

Message queue for the system.

required
orchestrator BaseOrchestrator

Orchestrator for the system.

required
publish_callback Optional[PublishCallback]

Callback for publishing messages. Defaults to None.

None
state_store Optional[BaseKVStore]

State store for the system. Defaults to None.

None
services_store_key str

Key for the services store. Defaults to "services".

'services'
tasks_store_key str

Key for the tasks store. Defaults to "tasks".

'tasks'
step_interval float

The interval in seconds to poll for tool call results. Defaults to 0.1s.

0.1
host str

The host of the service. Defaults to "127.0.0.1".

'127.0.0.1'
port Optional[int]

The port of the service. Defaults to 8000.

8000
internal_host Optional[str]

The host for external networking as in Docker-Compose or K8s.

None
internal_port Optional[int]

The port for external networking as in Docker-Compose or K8s.

None
running bool

Whether the service is running. Defaults to True.

True

Examples:

from llama_deploy import ControlPlaneServer
from llama_deploy import SimpleMessageQueue, SimpleOrchestrator
from llama_index.llms.openai import OpenAI

control_plane = ControlPlaneServer(
    SimpleMessageQueue(),
    SimpleOrchestrator(),
)
Source code in llama-agents/llama_deploy/control_plane/server.py
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
class ControlPlaneServer(BaseControlPlane):
    """Control plane server.

    The control plane is responsible for managing the state of the system, including:
    - Registering services.
    - Submitting tasks.
    - Managing task state.
    - Handling service completion.
    - Launching the control plane server.

    Args:
        message_queue (BaseMessageQueue): Message queue for the system.
        orchestrator (BaseOrchestrator): Orchestrator for the system.
        publish_callback (Optional[PublishCallback], optional): Callback for publishing messages. Defaults to None.
        state_store (Optional[BaseKVStore], optional): State store for the system. Defaults to None.
        services_store_key (str, optional): Key for the services store. Defaults to "services".
        tasks_store_key (str, optional): Key for the tasks store. Defaults to "tasks".
        step_interval (float, optional): The interval in seconds to poll for tool call results. Defaults to 0.1s.
        host (str, optional): The host of the service. Defaults to "127.0.0.1".
        port (Optional[int], optional): The port of the service. Defaults to 8000.
        internal_host (Optional[str], optional): The host for external networking as in Docker-Compose or K8s.
        internal_port (Optional[int], optional): The port for external networking as in Docker-Compose or K8s.
        running (bool, optional): Whether the service is running. Defaults to True.

    Examples:
        ```python
        from llama_deploy import ControlPlaneServer
        from llama_deploy import SimpleMessageQueue, SimpleOrchestrator
        from llama_index.llms.openai import OpenAI

        control_plane = ControlPlaneServer(
            SimpleMessageQueue(),
            SimpleOrchestrator(),
        )
        ```
    """

    def __init__(
        self,
        message_queue: BaseMessageQueue,
        orchestrator: BaseOrchestrator,
        publish_callback: Optional[PublishCallback] = None,
        state_store: Optional[BaseKVStore] = None,
        services_store_key: str = "services",
        tasks_store_key: str = "tasks",
        session_store_key: str = "sessions",
        step_interval: float = 0.1,
        host: str = "127.0.0.1",
        port: Optional[int] = 8000,
        internal_host: Optional[str] = None,
        internal_port: Optional[int] = None,
        running: bool = True,
    ) -> None:
        self.orchestrator = orchestrator

        self.step_interval = step_interval
        self.running = running
        self.host = host
        self.port = port
        self.internal_host = internal_host
        self.internal_port = internal_port

        self.state_store = state_store or SimpleKVStore()

        self.services_store_key = services_store_key
        self.tasks_store_key = tasks_store_key
        self.session_store_key = session_store_key

        self._message_queue = message_queue
        self._publisher_id = f"{self.__class__.__qualname__}-{uuid.uuid4()}"
        self._publish_callback = publish_callback

        self.app = FastAPI()
        self.app.add_api_route("/", self.home, methods=["GET"], tags=["Control Plane"])
        self.app.add_api_route(
            "/process_message",
            self.process_message,
            methods=["POST"],
            tags=["Control Plane"],
        )
        self.app.add_api_route(
            "/queue_config",
            self.get_message_queue_config,
            methods=["GET"],
            tags=["Message Queue"],
        )

        self.app.add_api_route(
            "/services/register",
            self.register_service,
            methods=["POST"],
            tags=["Services"],
        )
        self.app.add_api_route(
            "/services/deregister",
            self.deregister_service,
            methods=["POST"],
            tags=["Services"],
        )
        self.app.add_api_route(
            "/services/{service_name}",
            self.get_service,
            methods=["GET"],
            tags=["Services"],
        )
        self.app.add_api_route(
            "/services",
            self.get_all_services,
            methods=["GET"],
            tags=["Services"],
        )

        self.app.add_api_route(
            "/sessions/{session_id}",
            self.get_session,
            methods=["GET"],
            tags=["Sessions"],
        )
        self.app.add_api_route(
            "/sessions/create",
            self.create_session,
            methods=["POST"],
            tags=["Sessions"],
        )
        self.app.add_api_route(
            "/sessions/{session_id}/delete",
            self.delete_session,
            methods=["POST"],
            tags=["Sessions"],
        )
        self.app.add_api_route(
            "/sessions/{session_id}/tasks",
            self.add_task_to_session,
            methods=["POST"],
            tags=["Sessions"],
        )
        self.app.add_api_route(
            "/sessions",
            self.get_all_sessions,
            methods=["GET"],
            tags=["Sessions"],
        )
        self.app.add_api_route(
            "/sessions/{session_id}/tasks",
            self.get_session_tasks,
            methods=["GET"],
            tags=["Sessions"],
        )
        self.app.add_api_route(
            "/sessions/{session_id}/current_task",
            self.get_current_task,
            methods=["GET"],
            tags=["Sessions"],
        )
        self.app.add_api_route(
            "/sessions/{session_id}/tasks/{task_id}/result",
            self.get_task_result,
            methods=["GET"],
            tags=["Sessions"],
        )

    @property
    def message_queue(self) -> BaseMessageQueue:
        return self._message_queue

    @property
    def publisher_id(self) -> str:
        return self._publisher_id

    @property
    def publish_callback(self) -> Optional[PublishCallback]:
        return self._publish_callback

    async def process_message(self, message: QueueMessage) -> None:
        action = message.action

        if action == ActionTypes.NEW_TASK and message.data is not None:
            task_def = TaskDefinition(**message.data)
            if task_def.session_id is None:
                task_def.session_id = await self.create_session()

            await self.add_task_to_session(task_def.session_id, task_def)
        elif action == ActionTypes.COMPLETED_TASK and message.data is not None:
            await self.handle_service_completion(TaskResult(**message.data))
        else:
            raise ValueError(f"Action {action} not supported by control plane")

    def as_consumer(self, remote: bool = False) -> BaseMessageQueueConsumer:
        if remote:
            return RemoteMessageConsumer(
                id_=self.publisher_id,
                url=(
                    f"http://{self.host}:{self.port}/process_message"
                    if self.port
                    else f"http://{self.host}/process_message"
                ),
                message_type="control_plane",
            )

        return CallableMessageConsumer(
            id_=self.publisher_id,
            message_type="control_plane",
            handler=self.process_message,
        )

    async def launch_server(self) -> None:
        # give precedence to external settings
        host = self.internal_host or self.host
        port = self.internal_port or self.port
        logger.info(f"Launching control plane server at {host}:{port}")
        # uvicorn.run(self.app, host=self.host, port=self.port)

        class CustomServer(uvicorn.Server):
            def install_signal_handlers(self) -> None:
                pass

        cfg = uvicorn.Config(self.app, host=host, port=port)
        server = CustomServer(cfg)
        await server.serve()

    async def home(self) -> Dict[str, str]:
        return {
            "running": str(self.running),
            "step_interval": str(self.step_interval),
            "services_store_key": self.services_store_key,
            "tasks_store_key": self.tasks_store_key,
            "session_store_key": self.session_store_key,
        }

    async def register_service(self, service_def: ServiceDefinition) -> None:
        await self.state_store.aput(
            service_def.service_name,
            service_def.model_dump(),
            collection=self.services_store_key,
        )

    async def deregister_service(self, service_name: str) -> None:
        await self.state_store.adelete(service_name, collection=self.services_store_key)

    async def get_service(self, service_name: str) -> ServiceDefinition:
        service_dict = await self.state_store.aget(
            service_name, collection=self.services_store_key
        )
        if service_dict is None:
            raise HTTPException(status_code=404, detail="Service not found")

        return ServiceDefinition.model_validate(service_dict)

    async def get_all_services(self) -> Dict[str, ServiceDefinition]:
        service_dicts = await self.state_store.aget_all(
            collection=self.services_store_key
        )

        return {
            service_name: ServiceDefinition.model_validate(service_dict)
            for service_name, service_dict in service_dicts.items()
        }

    async def create_session(self) -> str:
        session = SessionDefinition()
        await self.state_store.aput(
            session.session_id,
            session.model_dump(),
            collection=self.session_store_key,
        )

        return session.session_id

    async def get_session(self, session_id: str) -> SessionDefinition:
        session_dict = await self.state_store.aget(
            session_id, collection=self.session_store_key
        )
        if session_dict is None:
            raise HTTPException(status_code=404, detail="Session not found")

        return SessionDefinition(**session_dict)

    async def delete_session(self, session_id: str) -> None:
        await self.state_store.adelete(session_id, collection=self.session_store_key)

    async def get_all_sessions(self) -> Dict[str, SessionDefinition]:
        session_dicts = await self.state_store.aget_all(
            collection=self.session_store_key
        )

        return {
            session_id: SessionDefinition(**session_dict)
            for session_id, session_dict in session_dicts.items()
        }

    async def get_session_tasks(self, session_id: str) -> List[TaskDefinition]:
        session = await self.get_session(session_id)
        task_defs = []
        for task_id in session.task_ids:
            task_defs.append(await self.get_task(task_id))
        return task_defs

    async def get_current_task(self, session_id: str) -> Optional[TaskDefinition]:
        session = await self.get_session(session_id)
        if len(session.task_ids) == 0:
            return None
        return await self.get_task(session.task_ids[-1])

    async def add_task_to_session(
        self, session_id: str, task_def: TaskDefinition
    ) -> str:
        session_dict = await self.state_store.aget(
            session_id, collection=self.session_store_key
        )
        if session_dict is None:
            raise HTTPException(status_code=404, detail="Session not found")

        session = SessionDefinition(**session_dict)
        session.task_ids.append(task_def.task_id)
        await self.state_store.aput(
            session_id, session.model_dump(), collection=self.session_store_key
        )

        await self.state_store.aput(
            task_def.task_id, task_def.model_dump(), collection=self.tasks_store_key
        )

        task_def = await self.send_task_to_service(task_def)

        return task_def.task_id

    async def send_task_to_service(self, task_def: TaskDefinition) -> TaskDefinition:
        if task_def.session_id is None:
            raise ValueError(f"Task with id {task_def.task_id} has no session")

        session = await self.get_session(task_def.session_id)

        next_messages, session_state = await self.orchestrator.get_next_messages(
            task_def, session.state
        )

        logger.debug(f"Sending task {task_def.task_id} to services: {next_messages}")

        for message in next_messages:
            await self.publish(message)

        session.state.update(session_state)

        await self.state_store.aput(
            task_def.session_id, session.model_dump(), collection=self.session_store_key
        )

        return task_def

    async def handle_service_completion(
        self,
        task_result: TaskResult,
    ) -> None:
        # add result to task state
        task_def = await self.get_task(task_result.task_id)
        if task_def.session_id is None:
            raise ValueError(f"Task with id {task_result.task_id} has no session")

        session = await self.get_session(task_def.session_id)
        state = await self.orchestrator.add_result_to_state(task_result, session.state)

        # update session state
        session.state.update(state)
        await self.state_store.aput(
            session.session_id,
            session.model_dump(),
            collection=self.session_store_key,
        )

        # generate and send new tasks (if any)
        task_def = await self.send_task_to_service(task_def)

        await self.state_store.aput(
            task_def.task_id, task_def.model_dump(), collection=self.tasks_store_key
        )

    async def get_task(self, task_id: str) -> TaskDefinition:
        state_dict = await self.state_store.aget(
            task_id, collection=self.tasks_store_key
        )
        if state_dict is None:
            raise HTTPException(status_code=404, detail="Task not found")

        return TaskDefinition(**state_dict)

    async def get_task_result(
        self, task_id: str, session_id: str
    ) -> Optional[TaskResult]:
        """Get the result of a task if it has one.

        Args:
            task_id (str): The ID of the task to get the result for.
            session_id (str): The ID of the session the task belongs to.

        Returns:
            Optional[TaskResult]: The result of the task if it has one, otherwise None.
        """
        session = await self.get_session(session_id)

        result_key = get_result_key(task_id)
        if result_key not in session.state:
            return None

        result = session.state[result_key]
        if not isinstance(result, TaskResult):
            if isinstance(result, dict):
                result = TaskResult(**result)
            elif isinstance(result, str):
                result = TaskResult(**json.loads(result))
            else:
                raise HTTPException(status_code=500, detail="Unexpected result type")

        # sanity check
        if result.task_id != task_id:
            logger.debug(
                f"Retrieved result did not match requested task_id: {str(result)}"
            )
            return None

        return result

    async def get_message_queue_config(self) -> Dict[str, dict]:
        """
        Gets the config dict for the message queue being used.

        Returns:
            Dict[str, dict]: A dict of message queue name -> config dict
        """
        queue_config = self._message_queue.as_config()
        return {queue_config.__class__.__name__: queue_config.model_dump()}

    async def register_to_message_queue(self) -> StartConsumingCallable:
        return await self.message_queue.register_consumer(self.as_consumer(remote=True))

get_task_result async #

get_task_result(task_id: str, session_id: str) -> Optional[TaskResult]

Get the result of a task if it has one.

Parameters:

Name Type Description Default
task_id str

The ID of the task to get the result for.

required
session_id str

The ID of the session the task belongs to.

required

Returns:

Type Description
Optional[TaskResult]

Optional[TaskResult]: The result of the task if it has one, otherwise None.

Source code in llama-agents/llama_deploy/control_plane/server.py
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
async def get_task_result(
    self, task_id: str, session_id: str
) -> Optional[TaskResult]:
    """Get the result of a task if it has one.

    Args:
        task_id (str): The ID of the task to get the result for.
        session_id (str): The ID of the session the task belongs to.

    Returns:
        Optional[TaskResult]: The result of the task if it has one, otherwise None.
    """
    session = await self.get_session(session_id)

    result_key = get_result_key(task_id)
    if result_key not in session.state:
        return None

    result = session.state[result_key]
    if not isinstance(result, TaskResult):
        if isinstance(result, dict):
            result = TaskResult(**result)
        elif isinstance(result, str):
            result = TaskResult(**json.loads(result))
        else:
            raise HTTPException(status_code=500, detail="Unexpected result type")

    # sanity check
    if result.task_id != task_id:
        logger.debug(
            f"Retrieved result did not match requested task_id: {str(result)}"
        )
        return None

    return result

get_message_queue_config async #

get_message_queue_config() -> Dict[str, dict]

Gets the config dict for the message queue being used.

Returns:

Type Description
Dict[str, dict]

Dict[str, dict]: A dict of message queue name -> config dict

Source code in llama-agents/llama_deploy/control_plane/server.py
481
482
483
484
485
486
487
488
489
async def get_message_queue_config(self) -> Dict[str, dict]:
    """
    Gets the config dict for the message queue being used.

    Returns:
        Dict[str, dict]: A dict of message queue name -> config dict
    """
    queue_config = self._message_queue.as_config()
    return {queue_config.__class__.__name__: queue_config.model_dump()}

ControlPlaneConfig #

Bases: BaseSettings

Control plane configuration.

Source code in llama-agents/llama_deploy/control_plane/server.py
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class ControlPlaneConfig(BaseSettings):
    """Control plane configuration."""

    model_config = SettingsConfigDict(
        env_prefix="CONTROL_PLANE_", arbitrary_types_allowed=True
    )

    state_store: Optional[BaseKVStore] = None
    services_store_key: str = "services"
    tasks_store_key: str = "tasks"
    session_store_key: str = "sessions"
    step_interval: float = 0.1
    host: str = "127.0.0.1"
    port: Optional[int] = 8000
    internal_host: Optional[str] = None
    internal_port: Optional[int] = None
    running: bool = True

    @property
    def url(self) -> str:
        if self.port:
            return f"http://{self.host}:{self.port}"
        else:
            return f"http://{self.host}"

options: members: - ControlPlaneConfig - ControlPlaneServer - BaseControlPlane