Repository navigation
Expand file tree
/
Copy pathminion.py
More file actions
784 lines (666 loc) · 29.3 KB
/
Copy pathminion.py
File metadata and controls
784 lines (666 loc) · 29.3 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
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
from typing import List, Dict, Any, Optional
import json
import re
import os
import time
from datetime import datetime
from minions.usage import Usage
import mcp
from minions.minions_mcp import SyncMCPClient
from minions.clients import OpenAIClient, TogetherClient, GeminiClient, SambanovaClient
from minions.prompts.minion_mcp import (
SUPERVISOR_INITIAL_PROMPT_MCP,
REMOTE_SYNTHESIS_FINAL_MCP,
WORKER_SYSTEM_PROMPT_MCP,
)
from minions.prompts.minion import (
SUPERVISOR_CONVERSATION_PROMPT,
SUPERVISOR_FINAL_PROMPT,
SUPERVISOR_INITIAL_PROMPT,
WORKER_SYSTEM_PROMPT,
REMOTE_SYNTHESIS_COT,
REMOTE_SYNTHESIS_FINAL,
WORKER_PRIVACY_SHIELD_PROMPT,
REFORMAT_QUERY_PROMPT,
)
from minions.prompts.multi_turn import (
MULTI_TURN_WORKER_SYSTEM_PROMPT,
MULTI_TURN_SUPERVISOR_INITIAL_PROMPT,
MULTI_TURN_SUPERVISOR_CONVERSATION_PROMPT,
MULTI_TURN_SUPERVISOR_FINAL_PROMPT,
MULTI_TURN_CONVERSATION_HISTORY_FORMAT,
)
from minions.usage import Usage
from minions.utils.conversation_history import ConversationHistory, ConversationTurn
def _escape_newlines_in_strings(json_str: str) -> str:
# This regex naively matches any content inside double quotes (including escaped quotes)
# and replaces any literal newline characters within those quotes.
# was especially useful for anthropic client
return re.sub(
r'(".*?")',
lambda m: m.group(1).replace("\n", "\\n"),
json_str,
flags=re.DOTALL,
)
def _extract_json(text: str) -> Dict[str, Any]:
"""Extract JSON from text that may be wrapped in markdown code blocks."""
block_matches = list(re.finditer(r"```(?:json)?\s*(.*?)```", text, re.DOTALL))
bracket_matches = list(re.finditer(r"\{.*?\}", text, re.DOTALL))
if block_matches:
json_str = block_matches[-1].group(1).strip()
elif bracket_matches:
json_str = bracket_matches[-1].group(0)
else:
json_str = text
# Minimal fix: escape newlines only within quoted JSON strings.
json_str = _escape_newlines_in_strings(json_str)
try:
return json.loads(json_str)
except json.JSONDecodeError:
print(f"Failed to parse JSON: {json_str}")
raise
class Minion:
def __init__(
self,
local_client=None,
remote_client=None,
max_rounds=3,
callback=None,
log_dir="minion_logs",
mcp_client: SyncMCPClient | None = None,
is_multi_turn=False,
max_history_turns=10,
):
"""Initialize the Minion with local and remote LLM clients.
Args:
local_client: Client for the local model (e.g. OllamaClient)
remote_client: Client for the remote model (e.g. OpenAIClient)
max_rounds: Maximum number of conversation rounds
callback: Optional callback function to receive message updates
log_dir: Directory for logging conversation history
is_multi_turn: Whether to enable multi-turn conversation support
max_history_turns: Maximum number of turns to keep in conversation history
"""
self.local_client = local_client
self.remote_client = remote_client
self.max_rounds = max_rounds
self.callback = callback
self.log_dir = log_dir
self.mcp_client = mcp_client
self.is_multi_turn = is_multi_turn
# Create log directory if it doesn't exist
os.makedirs(log_dir, exist_ok=True)
# Set up prompts based on whether we have access to an MCP client
self.supervisor_initial_prompt = SUPERVISOR_INITIAL_PROMPT
self.remote_synthesis_final = REMOTE_SYNTHESIS_FINAL
self.worker_system_prompt = WORKER_SYSTEM_PROMPT
if mcp_client is not None:
self.supervisor_initial_prompt = SUPERVISOR_INITIAL_PROMPT_MCP
self.remote_synthesis_final = REMOTE_SYNTHESIS_FINAL_MCP
self.worker_system_prompt = WORKER_SYSTEM_PROMPT_MCP
self.mcp_tools_info = (
None if self.mcp_client is None else self._generate_mcp_tools_info()
)
# Initialize conversation history for multi-turn support
self.conversation_history = (
ConversationHistory(max_turns=max_history_turns) if is_multi_turn else None
)
def __call__(
self,
task: str,
context: List[str],
max_rounds=None,
doc_metadata=None,
logging_id=None, # this is the name/id to give to the logging .json file
is_privacy=False,
images=None,
is_follow_up=False,
):
"""Run the minion protocol to answer a task using local and remote models.
Args:
task: The task/question to answer
context: List of context strings
max_rounds: Override default max_rounds if provided
doc_metadata: Optional metadata about the documents
logging_id: Optional identifier for the task, used for named log files
Returns:
Dict containing final_answer, conversation histories, and usage statistics
"""
print("\n========== MINION TASK STARTED ==========")
print(f"Task: {task}")
print(f"Max rounds: {max_rounds or self.max_rounds}")
print(f"Privacy enabled: {is_privacy}")
print(f"Images provided: {True if images else False}")
# Initialize timing metrics
start_time = time.time()
timing = {
"local_call_time": 0.0,
"remote_call_time": 0.0,
"total_time": 0.0,
}
last_checkpoint = start_time
if max_rounds is None:
max_rounds = self.max_rounds
# Join context sections
context = "\n\n".join(context)
print(f"Context length: {len(context)} characters")
# Initialize the log structure
conversation_log = {
"task": task,
"context": context,
"conversation": [],
"generated_final_answer": "",
"usage": {
"remote": {},
"local": {},
},
"timing": timing, # Add timing to the log structure
}
# Initialize message histories and usage tracking
supervisor_messages = []
worker_messages = []
remote_usage = Usage()
local_usage = Usage()
# Format conversation history for multi-turn mode
formatted_history = ""
if self.is_multi_turn and len(self.conversation_history.turns) > 0:
formatted_history = self._format_conversation_history()
supervisor_messages = [
{
"role": "user",
"content": self.supervisor_initial_prompt.format(
task=task, max_rounds=max_rounds, mcp_tools_info=self.mcp_tools_info
),
}
]
# Add initial supervisor prompt to conversation log
conversation_log["conversation"].append(
{
"user": "remote",
"prompt": self.supervisor_initial_prompt.format(
task=task, max_rounds=max_rounds, mcp_tools_info=self.mcp_tools_info
),
"output": None,
}
)
# print whether privacy is enabled
print("Privacy is enabled: ", is_privacy)
# if privacy import from minions.utils.pii_extraction
if is_privacy:
from minions.utils.pii_extraction import PIIExtractor
# Extract PII from context
pii_extractor = PIIExtractor()
str_context = context
pii_extracted = pii_extractor.extract_pii(str_context)
# Extract PII from query
query_pii_extracted = pii_extractor.extract_pii(task)
reformat_query_task = REFORMAT_QUERY_PROMPT.format(
query=task, pii_extracted=str(query_pii_extracted)
)
# Clean PII from query
reformatted_task, usage, done_reason = self.local_client.chat(
messages=[{"role": "user", "content": reformat_query_task}]
)
local_usage += usage
pii_reformatted_task = reformatted_task[0]
# Log the reformatted task
output = f"""**PII Reformated Task:**
{pii_reformatted_task}
"""
if self.callback:
self.callback("worker", output, is_final=False)
# Initialize message histories based on conversation mode
if self.is_multi_turn:
supervisor_messages = [
{
"role": "user",
"content": MULTI_TURN_SUPERVISOR_INITIAL_PROMPT.format(
task=pii_reformatted_task,
conversation_history=formatted_history,
),
}
]
worker_messages = [
{
"role": "system",
"content": MULTI_TURN_WORKER_SYSTEM_PROMPT.format(
context=context,
task=task,
conversation_history=formatted_history,
),
}
]
else:
supervisor_messages = [
{
"role": "user",
"content": self.supervisor_initial_prompt.format(
task=pii_reformatted_task,
mcp_tools_info=self.mcp_tools_info,
),
}
]
worker_messages = [
{
"role": "system",
"content": WORKER_SYSTEM_PROMPT.format(
context=context, task=task
),
}
]
else:
# Initialize message histories based on conversation mode
if self.is_multi_turn:
supervisor_messages = [
{
"role": "user",
"content": MULTI_TURN_SUPERVISOR_INITIAL_PROMPT.format(
task=task, conversation_history=formatted_history
),
}
]
worker_messages = [
{
"role": "system",
"content": MULTI_TURN_WORKER_SYSTEM_PROMPT.format(
context=context,
task=task,
conversation_history=formatted_history,
),
"images": images,
}
]
else:
supervisor_messages = [
{
"role": "user",
"content": self.supervisor_initial_prompt.format(
task=task, mcp_tools_info=self.mcp_tools_info
),
}
]
worker_messages = [
{
"role": "system",
"content": WORKER_SYSTEM_PROMPT.format(
context=context, task=task
),
"images": images,
}
]
# Add initial supervisor prompt to conversation log
conversation_log["conversation"].append(
{
"user": "remote",
"prompt": supervisor_messages[0]["content"],
"output": None,
}
)
# Initial supervisor call to get first question
if self.callback:
self.callback("supervisor", None, is_final=False)
remote_start_time = time.time()
if isinstance(self.remote_client, (OpenAIClient, TogetherClient)):
supervisor_response, supervisor_usage = self.remote_client.chat(
messages=supervisor_messages, response_format={"type": "json_object"}
)
elif isinstance(self.remote_client, GeminiClient):
from pydantic import BaseModel
class output(BaseModel):
decision: str
message: str
answer: str
# how to make message and answer optional
supervisor_response, supervisor_usage = self.remote_client.chat(
messages=supervisor_messages,
config={
"response_mime_type": "application/json",
"response_schema": output,
},
)
else:
supervisor_response, supervisor_usage = self.remote_client.chat(
messages=supervisor_messages
)
current_time = time.time()
timing["remote_call_time"] += current_time - remote_start_time
remote_usage += supervisor_usage
supervisor_messages.append(
{"role": "assistant", "content": supervisor_response[0]}
)
# Update the last conversation entry with the ouput
conversation_log["conversation"][-1]["output"] = supervisor_response[0]
if self.callback:
self.callback("supervisor", supervisor_messages[-1], is_final=False)
# Extract first question for worker
if isinstance(self.remote_client, (OpenAIClient, TogetherClient, GeminiClient)):
try:
supervisor_json = json.loads(supervisor_response[0])
except:
try:
supervisor_json = _extract_json(supervisor_response[0])
except:
supervisor_json = supervisor_response[0]
else:
supervisor_json = _extract_json(supervisor_response[0])
print(f"💬 SUPERVISOR MESSAGE: {supervisor_json['message']}")
worker_messages.append({"role": "user", "content": supervisor_json["message"]})
if self.mcp_client is not None:
tool_calls = supervisor_json["mcp_tool_calls"]
else:
tool_calls = []
# Add worker prompt to conversation log
conversation_log["conversation"].append(
{
"user": "local",
"prompt": supervisor_json["message"],
"output": None,
"mcp_tool_calls": tool_calls,
"mcp_tool_outputs": [],
}
)
final_answer = None
local_output = None
for round in range(max_rounds):
# Get worker's response
if self.callback:
self.callback("worker", None, is_final=False)
# If the supervisor has specified MCP tools to be called, then we call them
if (
self.mcp_client is not None
and len(supervisor_json["mcp_tool_calls"]) > 0
):
context_to_prepend = f"**New context from MCP tool calls:\n**"
for i, tool_call in enumerate(
supervisor_json["mcp_tool_calls"], start=1
):
# Here, we assume the supervisor has stuck to the format in self._generate_mcp_tools_info()
tool_name = tool_call["tool_name"]
tool_params = tool_call["parameters"]
print(
f"About to call MCP tool '{tool_name}' with params {tool_params}"
)
# if input("OK? (Type 'y' for yes or 'n' to skip): ").lower() != "y":
# conversation_log["conversation"][-1]["mcp_tool_outputs"].append(
# "<skipped>"
# )
# continue
try:
mcp_output = self.mcp_client.execute_tool(
tool_name=tool_name, **tool_params
)
except mcp.McpError as e:
mcp_output = f"MCP Error: {e}"
conversation_log["conversation"][-1]["mcp_tool_outputs"].append(
str(mcp_output)
)
# Provide MCP output to local client
context_to_prepend += f"_MCP tool call {i}:_\n"
context_to_prepend += f"Tool name: {tool_name}\n"
context_to_prepend += f"Tool params: {tool_params}\n"
context_to_prepend += f"Tool output:\n{mcp_output}\n"
context_to_prepend += (
"Please use the output above to help me with the following. "
)
context_to_prepend += "Remember, I can't see the output above.\n"
worker_messages[-1]["content"] = (
context_to_prepend + worker_messages[-1]["content"]
)
conversation_log["conversation"][-1]["prompt"] = worker_messages[-1][
"content"
]
# Track local call time
local_start_time = time.time()
worker_response, worker_usage, done_reason = self.local_client.chat(
messages=worker_messages
)
current_time = time.time()
timing["local_call_time"] += current_time - local_start_time
print(f" 🔨 WORKER RESPONSE: {worker_response[0]}")
local_usage += worker_usage
if is_privacy:
if self.callback:
output = f"""**_My output (pre-privacy shield):_**
{worker_response[0]}
"""
self.callback("worker", output, is_final=False)
worker_privacy_shield_prompt = WORKER_PRIVACY_SHIELD_PROMPT.format(
output=worker_response[0],
pii_extracted=str(pii_extracted),
)
worker_response, worker_usage, done_reason = self.local_client.chat(
messages=[{"role": "user", "content": worker_privacy_shield_prompt}]
)
local_usage += worker_usage
worker_messages.append(
{"role": "assistant", "content": worker_response[0]}
)
# Update the last conversation entry with the output
conversation_log["conversation"][-1]["output"] = worker_response[0]
if self.callback:
output = f"""**_My output (post-privacy shield):_**
{worker_response[0]}
"""
self.callback("worker", output, is_final=False)
else:
worker_messages.append(
{"role": "assistant", "content": worker_response[0]}
)
# Update the last conversation entry with the output
conversation_log["conversation"][-1]["output"] = worker_response[0]
if self.callback:
self.callback("worker", worker_messages[-1], is_final=False)
# Save the local output for conversation history
local_output = worker_response[0]
# Format prompt based on whether this is the final round
if round == max_rounds - 1:
if self.is_multi_turn:
supervisor_prompt = (
MULTI_TURN_SUPERVISOR_FINAL_PROMPT.format(
response=worker_response[0],
conversation_history=formatted_history,
)
+ "\n\nIMPORTANT: Provide a direct answer to the user's question. DO NOT describe what the answer should contain."
)
else:
supervisor_prompt = SUPERVISOR_FINAL_PROMPT.format(
response=worker_response[0]
)
# Add supervisor final prompt to conversation log
conversation_log["conversation"].append(
{"user": "remote", "prompt": supervisor_prompt, "output": None}
)
else:
# First step: Think through the synthesis
cot_prompt = REMOTE_SYNTHESIS_COT.format(
response=worker_response[0]
)
# Add supervisor COT prompt to conversation log
conversation_log["conversation"].append(
{"user": "remote", "prompt": cot_prompt, "output": None}
)
supervisor_messages.append({"role": "user", "content": cot_prompt})
# Track remote call time for step-by-step thinking
remote_start_time = time.time()
step_by_step_response, usage = self.remote_client.chat(
supervisor_messages
)
print(f"🔎 SUPERVISOR RESPONSE: {step_by_step_response[0]}")
current_time = time.time()
timing["remote_call_time"] += current_time - remote_start_time
remote_usage += usage
supervisor_messages.append(
{"role": "assistant", "content": step_by_step_response[0]}
)
# Update the last conversation entry with the output
conversation_log["conversation"][-1]["output"] = step_by_step_response[
0
]
# Second step: Get structured output
if self.is_multi_turn:
supervisor_prompt = (
REMOTE_SYNTHESIS_FINAL.format(response=step_by_step_response[0])
+ "\n\nIMPORTANT: Provide a direct answer to the user's question. DO NOT describe what the answer should contain."
)
else:
supervisor_prompt = self.remote_synthesis_final.format(
response=step_by_step_response[0]
)
# Add supervisor synthesis prompt to conversation log
conversation_log["conversation"].append(
{"user": "remote", "prompt": supervisor_prompt, "output": None}
)
supervisor_messages.append({"role": "user", "content": supervisor_prompt})
if self.callback:
self.callback("supervisor", None, is_final=False)
# Track remote call time
remote_start_time = time.time()
if isinstance(self.remote_client, (OpenAIClient, TogetherClient)):
supervisor_response, supervisor_usage = self.remote_client.chat(
messages=supervisor_messages,
response_format={"type": "json_object"},
)
elif isinstance(self.remote_client, GeminiClient):
from pydantic import BaseModel
class remote_output(BaseModel):
decision: str
message: str
answer: str
supervisor_response, supervisor_usage = self.remote_client.chat(
messages=supervisor_messages,
config={
"response_mime_type": "application/json",
"response_schema": remote_output,
},
)
else:
supervisor_response, supervisor_usage = self.remote_client.chat(
messages=supervisor_messages
)
current_time = time.time()
timing["remote_call_time"] += current_time - remote_start_time
remote_usage += supervisor_usage
supervisor_messages.append(
{"role": "assistant", "content": supervisor_response[0]}
)
if self.callback:
self.callback("supervisor", supervisor_messages[-1], is_final=False)
conversation_log["conversation"][-1]["output"] = supervisor_response[0]
# Parse supervisor's decision
if isinstance(self.remote_client, (OpenAIClient, TogetherClient)):
try:
supervisor_json = json.loads(supervisor_response[0])
except:
supervisor_json = _extract_json(supervisor_response[0])
else:
supervisor_json = _extract_json(supervisor_response[0])
if supervisor_json["decision"] == "provide_final_answer":
final_answer = supervisor_json["answer"]
conversation_log["generated_final_answer"] = final_answer
# Send final answer callback
if self.callback:
self.callback("supervisor", {"role": "assistant", "content": final_answer}, is_final=True)
break
else:
next_question = supervisor_json["message"]
worker_messages.append({"role": "user", "content": next_question})
if self.mcp_client is not None:
tool_calls = supervisor_json["mcp_tool_calls"]
else:
tool_calls = []
# Add next worker prompt to conversation log
conversation_log["conversation"].append(
{
"user": "local",
"prompt": next_question,
"output": None,
"mcp_tool_calls": tool_calls,
"mcp_tool_outputs": [],
}
)
if final_answer is None:
final_answer = "No answer found."
conversation_log["generated_final_answer"] = final_answer
# Update conversation history if in multi-turn mode
if self.is_multi_turn and final_answer:
# Add this turn to conversation history
turn = ConversationTurn(
query=task,
local_output=local_output,
remote_output=final_answer,
timestamp=datetime.now(),
)
self.conversation_history.add_turn(turn, remote_client=self.remote_client)
# Calculate total time and overhead at the end
end_time = time.time()
timing["total_time"] = end_time - start_time
timing["overhead_time"] = timing["total_time"] - (
timing["local_call_time"] + timing["remote_call_time"]
)
# Add usage statistics to the log
conversation_log["usage"]["remote"] = remote_usage.to_dict()
conversation_log["usage"]["local"] = local_usage.to_dict()
# Log the final result
if logging_id:
# use provided logging_id
log_filename = f"{logging_id}_minion.json"
else:
# fall back to timestamp + task abbrev
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
safe_task = re.sub(r"[^a-zA-Z0-9]", "_", task[:15])
log_filename = f"{timestamp}_{safe_task}.json"
log_path = os.path.join(self.log_dir, log_filename)
print(f"\n=== SAVING LOG TO {log_path} ===")
try:
with open(log_path, "w", encoding="utf-8") as f:
json.dump(conversation_log, f, indent=2, ensure_ascii=False)
except Exception as e:
print(f"Error saving log to {log_path}: {e}")
print("\n=== MINION TASK COMPLETED ===")
return {
"final_answer": final_answer,
"supervisor_messages": supervisor_messages,
"worker_messages": worker_messages,
"remote_usage": remote_usage,
"local_usage": local_usage,
"log_file": log_path,
"conversation_log": conversation_log,
"timing": timing,
}
def _generate_mcp_tools_info(self):
"""Generate explanation of available MCP tools for supervisor."""
mcp_tools_info = "### Available MCP Tools\n\n"
for tool in self.mcp_client.available_tools:
mcp_tools_info += f"## {tool['name']}\n\n"
mcp_tools_info += f"**Description**: {tool['description']}\n\n"
# Create parameter list from schema
params = []
if "properties" in tool["input_schema"]:
for param_name in tool["input_schema"]["properties"].keys():
params.append(param_name)
mcp_tools_info += f"""**JSON Format**:
```json
{{
"tool_name": "{tool['name']}",
"parameters": {{{', '.join([f'"{p}": "<{p}_value>"' for p in params])}}}
}}
```
"""
return mcp_tools_info
def _format_conversation_history(self) -> str:
"""Format the conversation history for inclusion in prompts."""
if not self.conversation_history or not self.conversation_history.turns:
return "No previous conversation."
formatted_history = ""
# Include summary if it exists (from older conversation turns)
if (
hasattr(self.conversation_history, "summary")
and self.conversation_history.summary
):
formatted_history += f"### Summary of Earlier Conversation\n{self.conversation_history.summary}\n\n### Recent Conversation\n"
# Add recent conversation turns
for i, turn in enumerate(self.conversation_history.turns):
formatted_history += MULTI_TURN_CONVERSATION_HISTORY_FORMAT.format(
query_index=i + 1, query=turn.query, response=turn.remote_output
)
return formatted_history