-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Expand file tree
/
Copy pathengine.py
More file actions
760 lines (700 loc) · 31.5 KB
/
engine.py
File metadata and controls
760 lines (700 loc) · 31.5 KB
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
import dspy
import os
from dataclasses import dataclass, field, asdict
from typing import List, Union, Literal, Optional, Dict
from .modules import collaborative_storm_utils as collaborative_storm_utils
from .modules.callback import BaseCallbackHandler
from .modules.co_storm_agents import (
SimulatedUser,
PureRAGAgent,
Moderator,
CoStormExpert,
)
from .modules.expert_generation import GenerateExpertModule
from .modules.warmstart_hierarchical_chat import WarmStartModule
from ..dataclass import ConversationTurn, KnowledgeBase
from ..encoder import Encoder
from ..interface import LMConfigs, Agent
from ..logging_wrapper import LoggingWrapper
from ..lm import LitellmModel
from ..rm import BingSearch
class CollaborativeStormLMConfigs(LMConfigs):
"""Configurations for LLM used in different parts of Co-STORM.
Given that different parts in Co-STORM framework have different complexity, we use different LLM configurations
to achieve a balance between quality and efficiency. If no specific configuration is provided, we use the default
setup in the paper.
"""
def __init__(self):
self.question_answering_lm = None
self.discourse_manage_lm = None
self.utterance_polishing_lm = None
self.warmstart_outline_gen_lm = None
self.question_asking_lm = None
self.knowledge_base_lm = None
def init(
self,
lm_type: Literal["openai", "azure", "together"],
temperature: Optional[float] = 1.0,
top_p: Optional[float] = 0.9,
):
if lm_type and lm_type == "openai":
openai_kwargs = {
"api_key": os.getenv("OPENAI_API_KEY"),
"temperature": temperature,
"top_p": top_p,
"api_base": None,
}
self.question_answering_lm = LitellmModel(
model="gpt-4o-2024-05-13", max_tokens=1000, **openai_kwargs
)
self.discourse_manage_lm = LitellmModel(
model="gpt-4o-2024-05-13", max_tokens=500, **openai_kwargs
)
self.utterance_polishing_lm = LitellmModel(
model="gpt-4o-2024-05-13", max_tokens=2000, **openai_kwargs
)
self.warmstart_outline_gen_lm = LitellmModel(
model="gpt-4-1106-preview", max_tokens=500, **openai_kwargs
)
self.question_asking_lm = LitellmModel(
model="gpt-4o-2024-05-13", max_tokens=300, **openai_kwargs
)
self.knowledge_base_lm = LitellmModel(
model="gpt-4o-2024-05-13", max_tokens=1000, **openai_kwargs
)
elif lm_type and lm_type == "azure":
azure_kwargs = {
"api_key": os.getenv("AZURE_API_KEY"),
"temperature": temperature,
"top_p": top_p,
"api_base": os.getenv("AZURE_API_BASE"),
"api_version": os.getenv("AZURE_API_VERSION"),
}
self.question_answering_lm = LitellmModel(
model="azure/gpt-4o", max_tokens=1000, **azure_kwargs, model_type="chat"
)
self.discourse_manage_lm = LitellmModel(
model="azure/gpt-4o", max_tokens=500, **azure_kwargs, model_type="chat"
)
self.utterance_polishing_lm = LitellmModel(
model="azure/gpt-4o", max_tokens=2000, **azure_kwargs, model_type="chat"
)
self.warmstart_outline_gen_lm = LitellmModel(
model="azure/gpt-4o", max_tokens=300, **azure_kwargs, model_type="chat"
)
self.question_asking_lm = LitellmModel(
model="azure/gpt-4o", max_tokens=300, **azure_kwargs, model_type="chat"
)
self.knowledge_base_lm = LitellmModel(
model="azure/gpt-4o", max_tokens=1000, **azure_kwargs, model_type="chat"
)
elif lm_type and lm_type == "together":
together_kwargs = {
"api_key": os.getenv("TOGETHER_API_KEY"),
"temperature": temperature,
"top_p": top_p,
}
self.question_answering_lm = LitellmModel(
model="together_ai/meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo",
max_tokens=1000,
model_type="chat",
**together_kwargs,
)
self.discourse_manage_lm = LitellmModel(
model="together_ai/meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo",
max_tokens=500,
model_type="chat",
**together_kwargs,
)
self.utterance_polishing_lm = LitellmModel(
model="together_ai/meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo",
max_tokens=2000,
model_type="chat",
**together_kwargs,
)
self.warmstart_outline_gen_lm = LitellmModel(
model="together_ai/meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo",
max_tokens=500,
model_type="chat",
**together_kwargs,
)
self.question_asking_lm = LitellmModel(
model="together_ai/meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo",
max_tokens=300,
model_type="chat",
**together_kwargs,
)
self.knowledge_base_lm = LitellmModel(
model="together_ai/meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo",
max_tokens=1000,
model_type="chat",
**together_kwargs,
)
else:
raise Exception(
"No valid OpenAI API provider is provided. Cannot use default LLM configurations."
)
def set_question_answering_lm(self, model: Union[dspy.dsp.LM, dspy.dsp.HFModel]):
self.question_answering_lm = model
def set_discourse_manage_lm(self, model: Union[dspy.dsp.LM, dspy.dsp.HFModel]):
self.discourse_manage_lm = model
def set_utterance_polishing_lm(self, model: Union[dspy.dsp.LM, dspy.dsp.HFModel]):
self.utterance_polishing_lm = model
def set_warmstart_outline_gen_lm(self, model: Union[dspy.dsp.LM, dspy.dsp.HFModel]):
self.warmstart_outline_gen_lm = model
def set_question_asking_lm(self, model: Union[dspy.dsp.LM, dspy.dsp.HFModel]):
self.question_asking_lm = model
def set_knowledge_base_lm(self, model: Union[dspy.dsp.LM, dspy.dsp.HFModel]):
self.knowledge_base_lm = model
def collect_and_reset_lm_usage(self):
lm_usage = {}
for attr_name in self.__dict__:
if "_lm" in attr_name and hasattr(
getattr(self, attr_name), "get_usage_and_reset"
):
usage = getattr(self, attr_name).get_usage_and_reset()
if any(
value["prompt_tokens"] != 0 or value["completion_tokens"] != 0
for value in usage.values()
):
lm_usage[attr_name] = usage
return lm_usage
def to_dict(self):
"""
Converts the CollaborativeStormLMConfigs instance to a dictionary representation.
Returns:
dict: The dictionary representation of the CollaborativeStormLMConfigs.
"""
config_dict = {}
for attr_name in self.__dict__:
config_dict[attr_name] = getattr(self, attr_name).kwargs
return config_dict
@dataclass
class RunnerArgument:
"""Arguments for controlling the STORM Wiki pipeline."""
topic: str = field(
metadata={"help": "Topic of discourse"},
)
retrieve_top_k: int = field(
default=10,
metadata={"help": "retrieve top k results for each query in retriever"},
)
max_search_queries: int = field(
default=2,
metadata={
"help": "Maximum number of search queries to consider for each question."
},
)
total_conv_turn: int = field(
default=20,
metadata={"help": "Maximum number turn in conversation."},
)
max_search_thread: int = field(
default=5,
metadata={"help": "Maximum number of parallel thread for retriever"},
)
max_search_queries_per_turn: int = field(
default=3,
metadata={"help": "Maximum number of search queries to consider in each turn."},
)
warmstart_max_num_experts: int = field(
default=3,
metadata={
"help": "Max number of experts in perspective guided QA in warm start process"
},
)
warmstart_max_turn_per_experts: int = field(
default=2,
metadata={"help": "Max number of turns per perspective in warm start process"},
)
warmstart_max_thread: int = field(
default=3,
metadata={
"help": "Max number thread for parallel perspective guided QA in warm start process"
},
)
max_thread_num: int = field(
default=10,
metadata={
"help": "Maximum number of threads to use. "
"Consider reducing it if keep getting 'Exceed rate limit' error when calling LM API."
},
)
max_num_round_table_experts: int = field(
default=2,
metadata={"help": "Max number of active experts in round table discussion."},
)
moderator_override_N_consecutive_answering_turn: int = field(
default=3,
metadata={
"help": "Number of consecutive experts answering turn before moderator override the conversation"
},
)
node_expansion_trigger_count: int = field(
default=10,
metadata={
"help": "Trigger node expansion for node that contain more than N snippets"
},
)
disable_moderator: bool = field(
default=False,
metadata={"help": "If True, disable moderator."},
)
disable_multi_experts: bool = field(
default=False,
metadata={"help": "If True, disable moderator."},
)
rag_only_baseline_mode: bool = field(
default=False,
metadata={"help": "If True, switch to rag online baseline mode"},
)
def to_dict(self):
"""
Converts the RunnerArgument instance to a dictionary representation.
Returns:
dict: The dictionary representation of the RunnerArgument.
"""
return asdict(self)
@classmethod
def from_dict(cls, data):
"""
Constructs a RunnerArgument instance from a dictionary representation.
Args:
data (dict): The dictionary representation of the RunnerArgument.
Returns:
RunnerArgument: The constructed RunnerArgument instance.
"""
return cls(**data)
@dataclass
class TurnPolicySpec:
"""
Represents the policy specifications for determining the behavior of a conversation turn.
Attributes:
should_reorganize_knowledge_base (bool):
A flag that indicates whether the knowledge base should be reorganized after the current turn.
should_update_experts_list (bool):
A flag that indicates whether the list of experts should be updated based on the conversation context.
should_polish_utterance (bool):
A flag that indicates whether the generated utterance should be polished (e.g., refined or rephrased) before it is used in the conversation.
agent (Agent):
The `Agent` responsible for generating utterances or responses during the conversation turn.
This agent interacts with the knowledge base and the conversation history to produce responses.
"""
should_reorganize_knowledge_base: bool = False
should_update_experts_list: bool = False
should_polish_utterance: bool = False
agent: Agent = None
class DiscourseManager:
def __init__(
self,
logging_wrapper: LoggingWrapper,
lm_config: CollaborativeStormLMConfigs,
runner_argument: RunnerArgument,
rm: dspy.Retrieve,
encoder: Encoder,
callback_handler: BaseCallbackHandler,
):
# parameter management
self.lm_config = lm_config
self.runner_argument = runner_argument
self.logging_wrapper = logging_wrapper
self.callback_handler = callback_handler
self.rm = rm
self.encoder = encoder
# role management
self.experts: List[CoStormExpert] = []
self.simulated_user: SimulatedUser = SimulatedUser(
topic=self.runner_argument.topic,
role_name="Guest",
role_description="",
intent=None,
lm_config=self.lm_config,
runner_argument=self.runner_argument,
logging_wrapper=self.logging_wrapper,
callback_handler=self.callback_handler,
)
self.pure_rag_agent: PureRAGAgent = PureRAGAgent(
topic=self.runner_argument.topic,
role_name="PureRAG",
role_description="",
lm_config=self.lm_config,
runner_argument=self.runner_argument,
logging_wrapper=self.logging_wrapper,
rm=self.rm,
callback_handler=self.callback_handler,
)
self.moderator: Moderator = Moderator(
topic=self.runner_argument.topic,
role_name="Moderator",
role_description="",
lm_config=self.lm_config,
runner_argument=self.runner_argument,
logging_wrapper=self.logging_wrapper,
encoder=self.encoder,
callback_handler=self.callback_handler,
)
self.general_knowledge_provider = CoStormExpert(
topic=self.runner_argument.topic,
role_name="General Knowledge Provider",
role_description="Focus on broadly covering the basic facts about the question.",
lm_config=self.lm_config,
runner_argument=self.runner_argument,
logging_wrapper=self.logging_wrapper,
rm=self.rm,
callback_handler=self.callback_handler,
)
self.generate_expert_module = GenerateExpertModule(
engine=self.lm_config.discourse_manage_lm
)
self.next_turn_moderator_override = False
def serialize_experts(self) -> List[Dict]:
return [
{
"topic": expert.topic,
"role_name": expert.role_name,
"role_description": expert.role_description,
}
for expert in self.experts
]
def deserialize_experts(self, data: List[Dict]):
for expert_data in data:
self.experts.append(
CoStormExpert(
topic=expert_data["topic"],
role_name=expert_data["role_name"],
role_description=expert_data["role_description"],
lm_config=self.lm_config,
runner_argument=self.runner_argument,
logging_wrapper=self.logging_wrapper,
rm=self.rm,
callback_handler=self.callback_handler,
)
)
def _should_generate_question(
self, conversation_history: List[ConversationTurn]
) -> bool:
consecutive_non_questioning_turn = 0
for conv_turn in reversed(conversation_history):
if conv_turn.utterance_type not in [
"Original Question",
"Information Request",
]:
consecutive_non_questioning_turn += 1
else:
break
return (
consecutive_non_questioning_turn
>= self.runner_argument.moderator_override_N_consecutive_answering_turn
)
def _parse_expert_names_to_agent(self, expert_descriptions: Union[str, List[str]]):
if type(expert_descriptions) == str:
expert_descriptions = [expert_descriptions]
agents: CoStormExpert = []
for expert_name in expert_descriptions:
role_name, role_description = expert_name.split(":")
role_name = role_name.strip()
role_description = role_description.strip()
new_costorm_expert = CoStormExpert(
topic=self.runner_argument.topic,
role_name=role_name,
role_description=role_description,
lm_config=self.lm_config,
runner_argument=self.runner_argument,
logging_wrapper=self.logging_wrapper,
rm=self.rm,
callback_handler=self.callback_handler,
)
agents.append(new_costorm_expert)
return agents
def _update_expert_list_from_utterance(self, focus: str, background_info: str):
expert_names = self.generate_expert_module(
topic=self.runner_argument.topic,
background_info=background_info,
focus=focus,
num_experts=self.runner_argument.max_num_round_table_experts,
).experts
self.experts = self._parse_expert_names_to_agent(expert_names)
def _is_last_turn_questioning(self, conversation_history: List[ConversationTurn]):
return conversation_history and conversation_history[-1].utterance_type in [
"Original Question",
"Information Request",
]
def get_next_turn_policy(
self,
conversation_history: List[ConversationTurn],
dry_run=False,
simulate_user=False,
simulate_user_intent: str = None,
) -> TurnPolicySpec:
next_turn_policy = TurnPolicySpec()
if simulate_user:
self.simulated_user.intent = simulate_user_intent
next_turn_policy.agent = self.simulated_user
elif self.runner_argument.rag_only_baseline_mode:
assert self.conversation_history[-1].role == "Guest"
next_turn_policy.agent = self.pure_rag_agent
elif self.next_turn_moderator_override:
next_turn_policy.agent = self.moderator
if not dry_run:
self.next_turn_moderator_override = False
elif (
not self.runner_argument.disable_moderator
and self._should_generate_question(conversation_history)
):
next_turn_policy.agent = self.moderator
next_turn_policy.should_reorganize_knowledge_base = True
# experts RAG gen
else:
next_turn_policy.agent = self.general_knowledge_provider
if (
not self._is_last_turn_questioning(conversation_history)
and not self.runner_argument.disable_multi_experts
):
if dry_run:
next_turn_policy.agent = self.experts[0]
else:
next_turn_policy.agent = self.experts.pop(0)
self.experts.append(next_turn_policy.agent)
next_turn_policy.should_update_experts_list = (
self._is_last_turn_questioning(conversation_history)
and not self.runner_argument.disable_multi_experts
)
next_turn_policy.should_polish_utterance = True
return next_turn_policy
class CoStormRunner:
def __init__(
self,
lm_config: CollaborativeStormLMConfigs,
runner_argument: RunnerArgument,
logging_wrapper: LoggingWrapper,
rm: Optional[dspy.Retrieve] = None,
callback_handler: BaseCallbackHandler = None,
):
self.runner_argument = runner_argument
self.lm_config = lm_config
self.logging_wrapper = logging_wrapper
self.callback_handler = callback_handler
if rm is None:
self.rm = BingSearch(k=runner_argument.retrieve_top_k)
else:
self.rm = rm
self.encoder = Encoder()
self.conversation_history = []
self.warmstart_conv_archive = []
self.knowledge_base = KnowledgeBase(
topic=self.runner_argument.topic,
knowledge_base_lm=self.lm_config.knowledge_base_lm,
node_expansion_trigger_count=self.runner_argument.node_expansion_trigger_count,
encoder=self.encoder,
)
self.discourse_manager = DiscourseManager(
lm_config=self.lm_config,
runner_argument=self.runner_argument,
logging_wrapper=self.logging_wrapper,
rm=self.rm,
encoder=self.encoder,
callback_handler=callback_handler,
)
def to_dict(self):
return {
"runner_argument": self.runner_argument.to_dict(),
"lm_config": self.lm_config.to_dict(),
"conversation_history": [
turn.to_dict() for turn in self.conversation_history
],
"warmstart_conv_archive": [
turn.to_dict() for turn in self.warmstart_conv_archive
],
"experts": self.discourse_manager.serialize_experts(),
"knowledge_base": self.knowledge_base.to_dict(),
}
@classmethod
def from_dict(cls, data, callback_handler: BaseCallbackHandler = None):
# FIXME: does not use the lm_config data but naively use default setting
lm_config = CollaborativeStormLMConfigs()
lm_config.init(lm_type=os.getenv("OPENAI_API_TYPE"))
costorm_runner = cls(
lm_config=lm_config,
runner_argument=RunnerArgument.from_dict(data["runner_argument"]),
logging_wrapper=LoggingWrapper(lm_config),
callback_handler=callback_handler,
)
costorm_runner.encoder = Encoder()
costorm_runner.conversation_history = [
ConversationTurn.from_dict(turn) for turn in data["conversation_history"]
]
costorm_runner.warmstart_conv_archive = [
ConversationTurn.from_dict(turn)
for turn in data.get("warmstart_conv_archive", [])
]
costorm_runner.discourse_manager.deserialize_experts(data["experts"])
costorm_runner.knowledge_base = KnowledgeBase.from_dict(
data=data["knowledge_base"],
knowledge_base_lm=costorm_runner.lm_config.knowledge_base_lm,
node_expansion_trigger_count=costorm_runner.runner_argument.node_expansion_trigger_count,
encoder=costorm_runner.encoder,
)
return costorm_runner
def warm_start(self):
"""
Warm start co-storm system to conduct background information search in order to build shared conceptual space with user.
This stage is a mini-STORM, spawning multiple LLM agent with different perspective and perform multi-round conversation.
The knowledge base (i.e. mind map) will be initialize using the collected information.
It will also generate a first draft of report and use it to produce an engaging and concise conversation presented to the
user to catch up with system's knowledge about the topic.
"""
with self.logging_wrapper.log_pipeline_stage(
pipeline_stage=f"warm start stage"
):
if not self.runner_argument.rag_only_baseline_mode:
warm_start_module = WarmStartModule(
lm_config=self.lm_config,
runner_argument=self.runner_argument,
logging_wrapper=self.logging_wrapper,
rm=self.rm,
callback_handler=self.callback_handler,
)
warmstart_conv, warmstart_revised_conv, warmstart_experts = (
warm_start_module.initiate_warm_start(
topic=self.runner_argument.topic,
knowledge_base=self.knowledge_base,
)
)
self.discourse_manager.experts = (
self.discourse_manager._parse_expert_names_to_agent(
warmstart_experts
)
)
self.discourse_manager.next_turn_moderator_override = True
self.conversation_history = (
warmstart_revised_conv if warmstart_revised_conv else warmstart_conv
)
self.warmstart_conv_archive = warmstart_conv
self.knowledge_base.reogranize()
else:
if self.knowledge_base is None:
self.knowledge_base = KnowledgeBase(
topic=self.runner_argument.topic,
knowledge_base_lm=self.lm_config.knowledge_base_lm,
node_expansion_trigger_count=self.runner_argument.node_expansion_trigger_count,
encoder=self.encoder,
)
if self.conversation_history is None:
self.conversation_history = []
conv_turn = (
self.discourse_manager.pure_rag_agent.generate_topic_background()
)
self.conversation_history.append(conv_turn)
self.knowledge_base.update_from_conv_turn(
conv_turn=conv_turn,
allow_create_new_node=True,
insert_under_root=self.runner_argument.rag_only_baseline_mode,
)
def generate_report(self) -> str:
"""
Generate report leveraging organized collected information in the knowledge base (i.e. mind map).
The article generation follows the paradigm in STORM paper, where it considers mind map nodes as section names, and generate the report section by section.
Returns:
str: A string representing the report, with "#" "##" indicating hierarchical sections and [1][2] indicating references.
"""
with self.logging_wrapper.log_pipeline_stage(
f"report generation after conv turn: {len(self.conversation_history)}"
):
with self.logging_wrapper.log_event(
"report generation stage: generate report"
):
return self.knowledge_base.to_report()
def dump_logging_and_reset(self):
return self.logging_wrapper.dump_logging_and_reset()
def step(
self,
user_utterance: str = "",
simulate_user: bool = False,
simulate_user_intent: str = "",
) -> ConversationTurn:
"""
Yields a single turn in the conversation flow.
This method take a user input when user choose to inject an utterance or generates the next system utterance based on the current conversation history and defined discourse policies.
It handles updating the conversation history, managing expert lists, and interacting with the knowledge base.
Additionally, it logs each stage of the conversation for monitoring and debugging purposes.
Args:
user_utterance (str, optional): The input provided by the user. If provided, this utterance is added directly to the conversation history and returns with no further action.
simulate_user (bool, optional): This is designed for automatic experiments using a LLM agent to simulate user actions. Flag indicating whether to simulate user behavior. When set to `True`, the system will generate user intents based on predefined simulation logic. Defaults to `False`.
simulate_user_intent (str, optional): This is designed for automatic experiments using a LLM agent to simulate user actions. Specifies the intent to simulate for the user. This is used when `simulate_user` is `True` to guide the simulated user's responses,
Returns:
ConversationTurn: An object representing the latest turn in the conversation.
Workflow:
1. User Utterance Handling
- If `user_utterance` is provided, it is appended to the `conversation_history`
2. System Utterance Generation
- If no `user_utterance` is provided, the method proceeds to generate the next system utterance.
- Determines the next turn policy by consulting the `discourse_manager` with the current conversation history.
- Generates a new utterance using the agent defined in the turn policy, leveraging the `knowledge_base` and `conversation_history`.
- If the turn policy indicates that the experts list should be updated, it updates the expert list based on the latest utterances.
4. Knowledge Base Update
- Inserts the new turn into the `knowledge_base`, optionally allowing the creation of new nodes or inserting under the root based on the `rag_only_baseline_mode` flag.
- If the turn policy specifies, it reorganizes the `knowledge_base` to maintain optimal structure and relevance.
"""
last_conv_turn = self.conversation_history[-1]
cur_turn_name = f"conv turn: {len(self.conversation_history) + 1}"
with self.logging_wrapper.log_pipeline_stage(
pipeline_stage=f"{cur_turn_name} stage"
):
conv_turn = None
if user_utterance:
self.discourse_manager.next_turn_moderator_override = False
conv_turn = ConversationTurn(
role="Guest",
raw_utterance=user_utterance,
utterance_type="Original Question",
)
self.conversation_history.append(conv_turn)
else:
with self.logging_wrapper.log_event(
f"{cur_turn_name}: get turn policy"
):
if self.callback_handler is not None:
self.callback_handler.on_turn_policy_planning_start()
turn_policy = self.discourse_manager.get_next_turn_policy(
conversation_history=self.conversation_history,
simulate_user=simulate_user,
simulate_user_intent=simulate_user_intent,
dry_run=False,
)
with self.logging_wrapper.log_event(
f"{cur_turn_name}: generate utterance"
):
conv_turn = turn_policy.agent.generate_utterance(
knowledge_base=self.knowledge_base,
conversation_history=self.conversation_history,
)
if turn_policy.should_update_experts_list:
with self.logging_wrapper.log_event(
f"{cur_turn_name}: update experts list"
):
self.discourse_manager._update_expert_list_from_utterance(
focus=last_conv_turn.raw_utterance,
background_info=conv_turn.raw_utterance,
)
if conv_turn is not None:
self.conversation_history.append(conv_turn)
with self.logging_wrapper.log_event(
f"{cur_turn_name}: insert into knowledge base"
):
if self.callback_handler is not None:
self.callback_handler.on_mindmap_insert_start()
self.knowledge_base.update_from_conv_turn(
conv_turn=conv_turn,
allow_create_new_node=True,
insert_under_root=self.runner_argument.rag_only_baseline_mode,
)
if self.callback_handler is not None:
self.callback_handler.on_mindmap_insert_end()
if turn_policy.should_reorganize_knowledge_base:
with self.logging_wrapper.log_event(
f"{cur_turn_name}: reorganize knowledge base"
):
if self.callback_handler is not None:
self.callback_handler.on_mindmap_reorg_start()
self.knowledge_base.reogranize()
return conv_turn