-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
base.py
862 lines (740 loc) · 28.6 KB
/
base.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
import os
from abc import abstractmethod
from collections import deque
from typing import Any, Deque, Dict, List, Optional, Union, cast
from llama_index.core.agent.types import (
BaseAgent,
BaseAgentWorker,
Task,
TaskStep,
TaskStepOutput,
)
from llama_index.core.async_utils import asyncio_run, run_jobs
from llama_index.core.bridge.pydantic import BaseModel, Field
from llama_index.core.callbacks import (
CallbackManager,
CBEventType,
EventPayload,
trace_method,
)
from llama_index.core.chat_engine.types import (
AGENT_CHAT_RESPONSE_TYPE,
AgentChatResponse,
ChatResponseMode,
StreamingAgentChatResponse,
)
from llama_index.core.base.llms.types import ChatMessage
from llama_index.core.llms.llm import LLM
from llama_index.core.memory import BaseMemory, ChatMemoryBuffer
from llama_index.core.memory.types import BaseMemory
from llama_index.core.tools.types import BaseTool
from llama_index.core.instrumentation.events.agent import (
AgentRunStepEndEvent,
AgentRunStepStartEvent,
AgentChatWithStepStartEvent,
AgentChatWithStepEndEvent,
)
import llama_index.core.instrumentation as instrument
dispatcher = instrument.get_dispatcher(__name__)
class BaseAgentRunner(BaseAgent):
"""Base agent runner."""
@abstractmethod
def create_task(self, input: str, **kwargs: Any) -> Task:
"""Create task."""
@abstractmethod
def delete_task(
self,
task_id: str,
) -> None:
"""Delete task.
NOTE: this will not delete any previous executions from memory.
"""
@abstractmethod
def list_tasks(self, **kwargs: Any) -> List[Task]:
"""List tasks."""
@abstractmethod
def get_completed_tasks(self, **kwargs: Any) -> List[Task]:
"""Get completed tasks."""
@abstractmethod
def get_task_output(self, task_id: str, **kwargs: Any) -> TaskStepOutput:
"""Get task output."""
@abstractmethod
def get_task(self, task_id: str, **kwargs: Any) -> Task:
"""Get task."""
@abstractmethod
def get_upcoming_steps(self, task_id: str, **kwargs: Any) -> List[TaskStep]:
"""Get upcoming steps."""
@abstractmethod
def get_completed_steps(self, task_id: str, **kwargs: Any) -> List[TaskStepOutput]:
"""Get completed steps."""
def get_completed_step(
self, task_id: str, step_id: str, **kwargs: Any
) -> TaskStepOutput:
"""Get completed step."""
# call get_completed_steps, and then find the right task
completed_steps = self.get_completed_steps(task_id, **kwargs)
for step_output in completed_steps:
if step_output.task_step.step_id == step_id:
return step_output
raise ValueError(f"Could not find step_id: {step_id}")
@abstractmethod
def run_step(
self,
task_id: str,
input: Optional[str] = None,
step: Optional[TaskStep] = None,
**kwargs: Any,
) -> TaskStepOutput:
"""Run step."""
@abstractmethod
async def arun_step(
self,
task_id: str,
input: Optional[str] = None,
step: Optional[TaskStep] = None,
**kwargs: Any,
) -> TaskStepOutput:
"""Run step (async)."""
@abstractmethod
def stream_step(
self,
task_id: str,
input: Optional[str] = None,
step: Optional[TaskStep] = None,
**kwargs: Any,
) -> TaskStepOutput:
"""Run step (stream)."""
@abstractmethod
async def astream_step(
self,
task_id: str,
input: Optional[str] = None,
step: Optional[TaskStep] = None,
**kwargs: Any,
) -> TaskStepOutput:
"""Run step (async stream)."""
@abstractmethod
def finalize_response(
self,
task_id: str,
step_output: Optional[TaskStepOutput] = None,
) -> AGENT_CHAT_RESPONSE_TYPE:
"""Finalize response."""
@abstractmethod
def undo_step(self, task_id: str) -> None:
"""Undo previous step."""
raise NotImplementedError("undo_step not implemented")
def validate_step_from_args(
task_id: str, input: Optional[str] = None, step: Optional[Any] = None, **kwargs: Any
) -> Optional[TaskStep]:
"""Validate step from args."""
if step is not None:
if input is not None:
raise ValueError("Cannot specify both `step` and `input`")
if not isinstance(step, TaskStep):
raise ValueError(f"step must be TaskStep: {step}")
return step
else:
return None
class TaskState(BaseModel):
"""Task state."""
task: Task = Field(..., description="Task.")
step_queue: Deque[TaskStep] = Field(
default_factory=deque, description="Task step queue."
)
completed_steps: List[TaskStepOutput] = Field(
default_factory=list, description="Completed step outputs."
)
class AgentState(BaseModel):
"""Agent state."""
task_dict: Dict[str, TaskState] = Field(
default_factory=dict, description="Task dictionary."
)
def get_task(self, task_id: str) -> Task:
"""Get task state."""
return self.task_dict[task_id].task
def get_completed_steps(self, task_id: str) -> List[TaskStepOutput]:
"""Get completed steps."""
return self.task_dict[task_id].completed_steps
def get_step_queue(self, task_id: str) -> Deque[TaskStep]:
"""Get step queue."""
return self.task_dict[task_id].step_queue
def reset(self) -> None:
"""Reset."""
self.task_dict = {}
class AgentRunner(BaseAgentRunner):
"""Agent runner.
Top-level agent orchestrator that can create tasks, run each step in a task,
or run a task e2e. Stores state and keeps track of tasks.
Args:
agent_worker (BaseAgentWorker): step executor
chat_history (Optional[List[ChatMessage]], optional): chat history. Defaults to None.
state (Optional[AgentState], optional): agent state. Defaults to None.
memory (Optional[BaseMemory], optional): memory. Defaults to None.
llm (Optional[LLM], optional): LLM. Defaults to None.
callback_manager (Optional[CallbackManager], optional): callback manager. Defaults to None.
init_task_state_kwargs (Optional[dict], optional): init task state kwargs. Defaults to None.
"""
# # TODO: implement this in Pydantic
def __init__(
self,
agent_worker: BaseAgentWorker,
chat_history: Optional[List[ChatMessage]] = None,
state: Optional[AgentState] = None,
memory: Optional[BaseMemory] = None,
llm: Optional[LLM] = None,
callback_manager: Optional[CallbackManager] = None,
init_task_state_kwargs: Optional[dict] = None,
delete_task_on_finish: bool = False,
default_tool_choice: str = "auto",
verbose: bool = False,
) -> None:
"""Initialize."""
self.agent_worker = agent_worker
self.state = state or AgentState()
self.memory = memory or ChatMemoryBuffer.from_defaults(chat_history, llm=llm)
# get and set callback manager
if callback_manager is not None:
self.agent_worker.set_callback_manager(callback_manager)
self.callback_manager = callback_manager
else:
# TODO: This is *temporary*
# Stopgap before having a callback on the BaseAgentWorker interface.
# Doing that requires a bit more refactoring to make sure existing code
# doesn't break.
if hasattr(self.agent_worker, "callback_manager"):
self.callback_manager = (
self.agent_worker.callback_manager or CallbackManager()
)
else:
self.callback_manager = CallbackManager()
self.init_task_state_kwargs = init_task_state_kwargs or {}
self.delete_task_on_finish = delete_task_on_finish
self.default_tool_choice = default_tool_choice
self.verbose = verbose
@staticmethod
def from_llm(
tools: Optional[List[BaseTool]] = None,
llm: Optional[LLM] = None,
**kwargs: Any,
) -> "AgentRunner":
from llama_index.core.agent import ReActAgent
if os.getenv("IS_TESTING"):
return ReActAgent.from_tools(
tools=tools,
llm=llm,
**kwargs,
)
try:
from llama_index.llms.openai import OpenAI # pants: no-infer-dep
from llama_index.llms.openai.utils import (
is_function_calling_model,
) # pants: no-infer-dep
except ImportError:
raise ImportError(
"`llama-index-llms-openai` package not found. Please "
"install by running `pip install llama-index-llms-openai`."
)
if isinstance(llm, OpenAI) and is_function_calling_model(llm.model):
from llama_index.agent.openai import OpenAIAgent # pants: no-infer-dep
return OpenAIAgent.from_tools(
tools=tools,
llm=llm,
**kwargs,
)
else:
return ReActAgent.from_tools(
tools=tools,
llm=llm,
**kwargs,
)
@property
def chat_history(self) -> List[ChatMessage]:
return self.memory.get_all()
def reset(self) -> None:
self.memory.reset()
self.state.reset()
def create_task(self, input: str, **kwargs: Any) -> Task:
"""Create task."""
if not self.init_task_state_kwargs:
extra_state = kwargs.pop("extra_state", {})
else:
if "extra_state" in kwargs:
raise ValueError(
"Cannot specify both `extra_state` and `init_task_state_kwargs`"
)
else:
extra_state = self.init_task_state_kwargs
callback_manager = kwargs.pop("callback_manager", self.callback_manager)
task = Task(
input=input,
memory=self.memory,
extra_state=extra_state,
callback_manager=callback_manager,
**kwargs,
)
# # put input into memory
# self.memory.put(ChatMessage(content=input, role=MessageRole.USER))
# get initial step from task, and put it in the step queue
initial_step = self.agent_worker.initialize_step(task)
task_state = TaskState(
task=task,
step_queue=deque([initial_step]),
)
# add it to state
self.state.task_dict[task.task_id] = task_state
return task
def delete_task(
self,
task_id: str,
) -> None:
"""Delete task.
NOTE: this will not delete any previous executions from memory.
"""
self.state.task_dict.pop(task_id)
def list_tasks(self, **kwargs: Any) -> List[Task]:
"""List tasks."""
return [task_state.task for task_state in self.state.task_dict.values()]
def get_task(self, task_id: str, **kwargs: Any) -> Task:
"""Get task."""
return self.state.get_task(task_id)
def get_upcoming_steps(self, task_id: str, **kwargs: Any) -> List[TaskStep]:
"""Get upcoming steps."""
return list(self.state.get_step_queue(task_id))
def get_completed_steps(self, task_id: str, **kwargs: Any) -> List[TaskStepOutput]:
"""Get completed steps."""
return self.state.get_completed_steps(task_id)
def get_task_output(self, task_id: str, **kwargs: Any) -> TaskStepOutput:
"""Get task output."""
completed_steps = self.get_completed_steps(task_id)
if len(completed_steps) == 0:
raise ValueError(f"No completed steps for task_id: {task_id}")
return completed_steps[-1]
def get_completed_tasks(self, **kwargs: Any) -> List[Task]:
"""Get completed tasks."""
task_states = list(self.state.task_dict.values())
completed_tasks = []
for task_state in task_states:
completed_steps = self.get_completed_steps(task_state.task.task_id)
if len(completed_steps) > 0 and completed_steps[-1].is_last:
completed_tasks.append(task_state.task)
return completed_tasks
@dispatcher.span
def _run_step(
self,
task_id: str,
step: Optional[TaskStep] = None,
input: Optional[str] = None,
mode: ChatResponseMode = ChatResponseMode.WAIT,
**kwargs: Any,
) -> TaskStepOutput:
"""Execute step."""
dispatcher.event(
AgentRunStepStartEvent(task_id=task_id, step=step, input=input)
)
task = self.state.get_task(task_id)
step_queue = self.state.get_step_queue(task_id)
step = step or step_queue.popleft()
if input is not None:
step.input = input
if self.verbose:
print(f"> Running step {step.step_id}. Step input: {step.input}")
# TODO: figure out if you can dynamically swap in different step executors
# not clear when you would do that by theoretically possible
if mode == ChatResponseMode.WAIT:
cur_step_output = self.agent_worker.run_step(step, task, **kwargs)
elif mode == ChatResponseMode.STREAM:
cur_step_output = self.agent_worker.stream_step(step, task, **kwargs)
else:
raise ValueError(f"Invalid mode: {mode}")
# append cur_step_output next steps to queue
next_steps = cur_step_output.next_steps
step_queue.extend(next_steps)
# add cur_step_output to completed steps
completed_steps = self.state.get_completed_steps(task_id)
completed_steps.append(cur_step_output)
dispatcher.event(AgentRunStepEndEvent(step_output=cur_step_output))
return cur_step_output
@dispatcher.span
async def _arun_step(
self,
task_id: str,
step: Optional[TaskStep] = None,
input: Optional[str] = None,
mode: ChatResponseMode = ChatResponseMode.WAIT,
**kwargs: Any,
) -> TaskStepOutput:
"""Execute step."""
dispatcher.event(
AgentRunStepStartEvent(task_id=task_id, step=step, input=input)
)
task = self.state.get_task(task_id)
step_queue = self.state.get_step_queue(task_id)
step = step or step_queue.popleft()
if input is not None:
step.input = input
if self.verbose:
print(f"> Running step {step.step_id}. Step input: {step.input}")
# TODO: figure out if you can dynamically swap in different step executors
# not clear when you would do that by theoretically possible
if mode == ChatResponseMode.WAIT:
cur_step_output = await self.agent_worker.arun_step(step, task, **kwargs)
elif mode == ChatResponseMode.STREAM:
cur_step_output = await self.agent_worker.astream_step(step, task, **kwargs)
else:
raise ValueError(f"Invalid mode: {mode}")
# append cur_step_output next steps to queue
next_steps = cur_step_output.next_steps
step_queue.extend(next_steps)
# add cur_step_output to completed steps
completed_steps = self.state.get_completed_steps(task_id)
completed_steps.append(cur_step_output)
dispatcher.event(AgentRunStepEndEvent(step_output=cur_step_output))
return cur_step_output
@dispatcher.span
def run_step(
self,
task_id: str,
input: Optional[str] = None,
step: Optional[TaskStep] = None,
**kwargs: Any,
) -> TaskStepOutput:
"""Run step."""
step = validate_step_from_args(task_id, input, step, **kwargs)
return self._run_step(
task_id, step, input=input, mode=ChatResponseMode.WAIT, **kwargs
)
@dispatcher.span
async def arun_step(
self,
task_id: str,
input: Optional[str] = None,
step: Optional[TaskStep] = None,
**kwargs: Any,
) -> TaskStepOutput:
"""Run step (async)."""
step = validate_step_from_args(task_id, input, step, **kwargs)
return await self._arun_step(
task_id, step, input=input, mode=ChatResponseMode.WAIT, **kwargs
)
@dispatcher.span
def stream_step(
self,
task_id: str,
input: Optional[str] = None,
step: Optional[TaskStep] = None,
**kwargs: Any,
) -> TaskStepOutput:
"""Run step (stream)."""
step = validate_step_from_args(task_id, input, step, **kwargs)
return self._run_step(
task_id, step, input=input, mode=ChatResponseMode.STREAM, **kwargs
)
@dispatcher.span
async def astream_step(
self,
task_id: str,
input: Optional[str] = None,
step: Optional[TaskStep] = None,
**kwargs: Any,
) -> TaskStepOutput:
"""Run step (async stream)."""
step = validate_step_from_args(task_id, input, step, **kwargs)
return await self._arun_step(
task_id, step, input=input, mode=ChatResponseMode.STREAM, **kwargs
)
@dispatcher.span
def finalize_response(
self,
task_id: str,
step_output: Optional[TaskStepOutput] = None,
) -> AGENT_CHAT_RESPONSE_TYPE:
"""Finalize response."""
if step_output is None:
step_output = self.state.get_completed_steps(task_id)[-1]
if not step_output.is_last:
raise ValueError(
"finalize_response can only be called on the last step output"
)
if not isinstance(
step_output.output,
(AgentChatResponse, StreamingAgentChatResponse),
):
raise ValueError(
"When `is_last` is True, cur_step_output.output must be "
f"AGENT_CHAT_RESPONSE_TYPE: {step_output.output}"
)
# finalize task
self.agent_worker.finalize_task(self.state.get_task(task_id))
if self.delete_task_on_finish:
self.delete_task(task_id)
return cast(AGENT_CHAT_RESPONSE_TYPE, step_output.output)
@dispatcher.span
def _chat(
self,
message: str,
chat_history: Optional[List[ChatMessage]] = None,
tool_choice: Union[str, dict] = "auto",
mode: ChatResponseMode = ChatResponseMode.WAIT,
) -> AGENT_CHAT_RESPONSE_TYPE:
"""Chat with step executor."""
if chat_history is not None:
self.memory.set(chat_history)
task = self.create_task(message)
result_output = None
dispatcher.event(AgentChatWithStepStartEvent(user_msg=message))
while True:
# pass step queue in as argument, assume step executor is stateless
cur_step_output = self._run_step(
task.task_id, mode=mode, tool_choice=tool_choice
)
if cur_step_output.is_last:
result_output = cur_step_output
break
# ensure tool_choice does not cause endless loops
tool_choice = "auto"
result = self.finalize_response(
task.task_id,
result_output,
)
dispatcher.event(AgentChatWithStepEndEvent(response=result))
return result
@dispatcher.span
async def _achat(
self,
message: str,
chat_history: Optional[List[ChatMessage]] = None,
tool_choice: Union[str, dict] = "auto",
mode: ChatResponseMode = ChatResponseMode.WAIT,
) -> AGENT_CHAT_RESPONSE_TYPE:
"""Chat with step executor."""
if chat_history is not None:
self.memory.set(chat_history)
task = self.create_task(message)
result_output = None
dispatcher.event(AgentChatWithStepStartEvent(user_msg=message))
while True:
# pass step queue in as argument, assume step executor is stateless
cur_step_output = await self._arun_step(
task.task_id, mode=mode, tool_choice=tool_choice
)
if cur_step_output.is_last:
result_output = cur_step_output
break
# ensure tool_choice does not cause endless loops
tool_choice = "auto"
result = self.finalize_response(
task.task_id,
result_output,
)
dispatcher.event(AgentChatWithStepEndEvent(response=result))
return result
@dispatcher.span
@trace_method("chat")
def chat(
self,
message: str,
chat_history: Optional[List[ChatMessage]] = None,
tool_choice: Optional[Union[str, dict]] = None,
) -> AgentChatResponse:
# override tool choice is provided as input.
if tool_choice is None:
tool_choice = self.default_tool_choice
with self.callback_manager.event(
CBEventType.AGENT_STEP,
payload={EventPayload.MESSAGES: [message]},
) as e:
chat_response = self._chat(
message=message,
chat_history=chat_history,
tool_choice=tool_choice,
mode=ChatResponseMode.WAIT,
)
assert isinstance(chat_response, AgentChatResponse)
e.on_end(payload={EventPayload.RESPONSE: chat_response})
return chat_response
@dispatcher.span
@trace_method("chat")
async def achat(
self,
message: str,
chat_history: Optional[List[ChatMessage]] = None,
tool_choice: Optional[Union[str, dict]] = None,
) -> AgentChatResponse:
# override tool choice is provided as input.
if tool_choice is None:
tool_choice = self.default_tool_choice
with self.callback_manager.event(
CBEventType.AGENT_STEP,
payload={EventPayload.MESSAGES: [message]},
) as e:
chat_response = await self._achat(
message=message,
chat_history=chat_history,
tool_choice=tool_choice,
mode=ChatResponseMode.WAIT,
)
assert isinstance(chat_response, AgentChatResponse)
e.on_end(payload={EventPayload.RESPONSE: chat_response})
return chat_response
@dispatcher.span
@trace_method("chat")
def stream_chat(
self,
message: str,
chat_history: Optional[List[ChatMessage]] = None,
tool_choice: Optional[Union[str, dict]] = None,
) -> StreamingAgentChatResponse:
# override tool choice is provided as input.
if tool_choice is None:
tool_choice = self.default_tool_choice
with self.callback_manager.event(
CBEventType.AGENT_STEP,
payload={EventPayload.MESSAGES: [message]},
) as e:
chat_response = self._chat(
message, chat_history, tool_choice, mode=ChatResponseMode.STREAM
)
assert isinstance(chat_response, StreamingAgentChatResponse) or (
isinstance(chat_response, AgentChatResponse)
and chat_response.is_dummy_stream
)
e.on_end(payload={EventPayload.RESPONSE: chat_response})
return chat_response
@dispatcher.span
@trace_method("chat")
async def astream_chat(
self,
message: str,
chat_history: Optional[List[ChatMessage]] = None,
tool_choice: Optional[Union[str, dict]] = None,
) -> StreamingAgentChatResponse:
# override tool choice is provided as input.
if tool_choice is None:
tool_choice = self.default_tool_choice
with self.callback_manager.event(
CBEventType.AGENT_STEP,
payload={EventPayload.MESSAGES: [message]},
) as e:
chat_response = await self._achat(
message, chat_history, tool_choice, mode=ChatResponseMode.STREAM
)
assert isinstance(chat_response, StreamingAgentChatResponse) or (
isinstance(chat_response, AgentChatResponse)
and chat_response.is_dummy_stream
)
e.on_end(payload={EventPayload.RESPONSE: chat_response})
return chat_response
def undo_step(self, task_id: str) -> None:
"""Undo previous step."""
raise NotImplementedError("undo_step not implemented")
class BasePlanningAgentRunner(AgentRunner):
@abstractmethod
def create_plan(self, input: str, **kwargs: Any) -> str:
"""Create plan. Returns the plan_id."""
...
@abstractmethod
def get_next_tasks(self, plan_id: str, **kwargs: Any) -> List[str]:
"""Get next task ids for a given plan."""
...
@abstractmethod
def mark_task_complete(self, plan_id: str, task_id: str, **kwargs: Any) -> None:
"""Mark task complete for a given plan."""
...
@abstractmethod
def refine_plan(self, input: str, plan_id: str, **kwargs: Any) -> None:
"""Refine plan."""
...
@abstractmethod
def run_task(self, task_id: str, **kwargs: Any) -> AGENT_CHAT_RESPONSE_TYPE:
"""Run task."""
...
async def acreate_plan(self, input: str, **kwargs: Any) -> str:
"""Create plan (async). Returns the plan_id."""
return self.create_plan(input, **kwargs)
async def arefine_plan(self, input: str, plan_id: str, **kwargs: Any) -> None:
"""Refine plan (async)."""
return self.refine_plan(input, plan_id, **kwargs)
async def arun_task(self, task_id: str, **kwargs: Any) -> AGENT_CHAT_RESPONSE_TYPE:
"""Run task (async)."""
return self.run_task(task_id, **kwargs)
@dispatcher.span
def _chat(
self,
message: str,
chat_history: Optional[List[ChatMessage]] = None,
tool_choice: Union[str, dict] = "auto",
mode: ChatResponseMode = ChatResponseMode.WAIT,
) -> AGENT_CHAT_RESPONSE_TYPE:
"""Chat with step executor."""
if chat_history is not None:
self.memory.set(chat_history)
# create initial set of tasks
plan_id = self.create_plan(message)
results = []
dispatcher.event(AgentChatWithStepStartEvent(user_msg=message))
while True:
# EXIT CONDITION: check if all sub-tasks are completed
next_task_ids = self.get_next_tasks(plan_id)
if len(next_task_ids) == 0:
break
jobs = [
self.arun_task(sub_task_id, mode=mode, tool_choice=tool_choice)
for sub_task_id in next_task_ids
]
results = asyncio_run(run_jobs(jobs, workers=len(jobs)))
for sub_task_id in next_task_ids:
self.mark_task_complete(plan_id, sub_task_id)
# EXIT CONDITION: check if all sub-tasks are completed now
# LLMs have a tendency to add more tasks, so we end if there are no more tasks
# next_sub_tasks = self.state.get_next_sub_tasks(plan_id)
# if len(next_sub_tasks) == 0:
# break
# refine the plan
self.refine_plan(message, plan_id)
dispatcher.event(
AgentChatWithStepEndEvent(
response=results[-1] if len(results) > 0 else None
)
)
return results[-1]
@dispatcher.span
async def _achat(
self,
message: str,
chat_history: Optional[List[ChatMessage]] = None,
tool_choice: Union[str, dict] = "auto",
mode: ChatResponseMode = ChatResponseMode.WAIT,
) -> AGENT_CHAT_RESPONSE_TYPE:
"""Chat with step executor."""
if chat_history is not None:
self.memory.set(chat_history)
# create initial set of tasks
plan_id = self.create_plan(message)
results = []
dispatcher.event(AgentChatWithStepStartEvent(user_msg=message))
while True:
# EXIT CONDITION: check if all sub-tasks are completed
next_task_ids = self.get_next_tasks(plan_id)
if len(next_task_ids) == 0:
break
jobs = [
self.arun_task(sub_task_id, mode=mode, tool_choice=tool_choice)
for sub_task_id in next_task_ids
]
results = await run_jobs(jobs, workers=len(jobs))
for sub_task_id in next_task_ids:
self.mark_task_complete(plan_id, sub_task_id)
# EXIT CONDITION: check if all sub-tasks are completed now
# LLMs have a tendency to add more tasks, so we end if there are no more tasks
# next_sub_tasks = self.state.get_next_sub_tasks(plan_id)
# if len(next_sub_tasks) == 0:
# break
# refine the plan
await self.arefine_plan(message, plan_id)
dispatcher.event(
AgentChatWithStepEndEvent(
response=results[-1] if len(results) > 0 else None
)
)
return results[-1]