lollms-client 0.24.1__py3-none-any.whl → 0.25.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of lollms-client might be problematic. Click here for more details.

lollms_client/__init__.py CHANGED
@@ -8,7 +8,7 @@ from lollms_client.lollms_utilities import PromptReshaper # Keep general utiliti
8
8
  from lollms_client.lollms_mcp_binding import LollmsMCPBinding, LollmsMCPBindingManager
9
9
 
10
10
 
11
- __version__ = "0.24.1" # Updated version
11
+ __version__ = "0.25.0" # Updated version
12
12
 
13
13
  # Optionally, you could define __all__ if you want to be explicit about exports
14
14
  __all__ = [
@@ -4,6 +4,7 @@ from lollms_client.lollms_llm_binding import LollmsLLMBinding
4
4
  from lollms_client.lollms_types import MSG_TYPE
5
5
  from lollms_client.lollms_utilities import encode_image
6
6
  from lollms_client.lollms_types import ELF_COMPLETION_FORMAT
7
+ from lollms_client.lollms_discussion import LollmsDiscussion
7
8
  from ascii_colors import ASCIIColors, trace_exception
8
9
  from typing import Optional, Callable, List, Union
9
10
  import json
@@ -30,7 +30,8 @@ class OpenAIBinding(LollmsLLMBinding):
30
30
  model_name: str = "",
31
31
  service_key: str = None,
32
32
  verify_ssl_certificate: bool = True,
33
- default_completion_format: ELF_COMPLETION_FORMAT = ELF_COMPLETION_FORMAT.Chat):
33
+ default_completion_format: ELF_COMPLETION_FORMAT = ELF_COMPLETION_FORMAT.Chat,
34
+ **kwargs):
34
35
  """
35
36
  Initialize the OpenAI binding.
36
37
 
@@ -52,7 +53,7 @@ class OpenAIBinding(LollmsLLMBinding):
52
53
 
53
54
  if not self.service_key:
54
55
  self.service_key = os.getenv("OPENAI_API_KEY", self.service_key)
55
- self.client = openai.OpenAI(api_key=self.service_key, base_url=host_address)
56
+ self.client = openai.OpenAI(api_key=self.service_key, base_url=None if host_address is None else host_address if len(host_address)>0 else None)
56
57
  self.completion_format = ELF_COMPLETION_FORMAT.Chat
57
58
 
58
59
 
@@ -13,6 +13,8 @@ from lollms_client.lollms_ttm_binding import LollmsTTMBinding, LollmsTTMBindingM
13
13
  from lollms_client.lollms_mcp_binding import LollmsMCPBinding, LollmsMCPBindingManager
14
14
 
15
15
  from lollms_client.lollms_discussion import LollmsDiscussion
16
+
17
+ from lollms_client.lollms_utilities import build_image_dicts, dict_to_markdown
16
18
  import json, re
17
19
  from enum import Enum
18
20
  import base64
@@ -846,7 +848,7 @@ Don't forget encapsulate the code inside a html code tag. This is mandatory.
846
848
  "2. **Check for a Single-Step Solution:** Scrutinize the available tools. Can a single tool call directly achieve the user's current goal? \n"
847
849
  "3. **Formulate a Plan:** Based on your analysis, create a concise, numbered list of steps to achieve the goal. If the goal is simple, this may be only one step. If it is complex or multi-turn, it may be several steps.\n\n"
848
850
  "**CRITICAL RULES:**\n"
849
- "* **MANDATORY: NEVER add steps the user did not ask for.** Do not embellish or add 'nice-to-have' features.\n"
851
+ "* **MANDATORY: Be helpful, curious and creative.\n"
850
852
  "* **Focus on the Goal:** Your plan should directly address the user's request as it stands now in the conversation.\n\n"
851
853
  "---\n"
852
854
  "**Available Tools:**\n"
@@ -1078,7 +1080,7 @@ Provide your response as a single JSON object with one key, "query".
1078
1080
  """
1079
1081
  try:
1080
1082
  raw_initial_query_response = self.generate_code(initial_query_gen_prompt, system_prompt="You are a query generation expert.", temperature=0.0)
1081
- initial_plan = json.loads(raw_initial_query_response)
1083
+ initial_plan = robust_json_parser(raw_initial_query_response)
1082
1084
  current_query_for_rag = initial_plan.get("query")
1083
1085
  if not current_query_for_rag:
1084
1086
  raise ValueError("LLM returned an empty initial query.")
@@ -1434,7 +1436,6 @@ Provide your response as a single JSON object inside a JSON markdown tag. Use th
1434
1436
  new_scratchpad_text = self.generate_text(prompt=synthesis_prompt, n_predict=1024, temperature=0.0)
1435
1437
  return self.remove_thinking_blocks(new_scratchpad_text).strip()
1436
1438
 
1437
- # In lollms_client/lollms_discussion.py -> LollmsClient class
1438
1439
 
1439
1440
  def generate_with_mcp_rag(
1440
1441
  self,
@@ -1444,13 +1445,14 @@ Provide your response as a single JSON object inside a JSON markdown tag. Use th
1444
1445
  system_prompt: str = None,
1445
1446
  reasoning_system_prompt: str = "You are a logical and adaptive AI assistant.",
1446
1447
  images: Optional[List[str]] = None,
1447
- max_reasoning_steps: int = 10,
1448
- decision_temperature: float = 0.0,
1448
+ max_reasoning_steps: int = None,
1449
+ decision_temperature: float = None,
1449
1450
  final_answer_temperature: float = None,
1450
1451
  streaming_callback: Optional[Callable[[str, 'MSG_TYPE', Optional[Dict], Optional[List]], bool]] = None,
1451
- rag_top_k: int = 5,
1452
- rag_min_similarity_percent: float = 70.0,
1453
- output_summarization_threshold: int = 500, # In tokens
1452
+ rag_top_k: int = None,
1453
+ rag_min_similarity_percent: float = None,
1454
+ output_summarization_threshold: int = None, # In tokens
1455
+ debug: bool = False,
1454
1456
  **llm_generation_kwargs
1455
1457
  ) -> Dict[str, Any]:
1456
1458
  """Generates a response using a dynamic agent with stateful, ID-based step tracking.
@@ -1483,6 +1485,7 @@ Provide your response as a single JSON object inside a JSON markdown tag. Use th
1483
1485
  rag_min_similarity_percent: Minimum similarity for RAG results.
1484
1486
  output_summarization_threshold: The token count that triggers automatic
1485
1487
  summarization of a tool's text output.
1488
+ debug : If true, we'll report the detailed promptin and response information
1486
1489
  **llm_generation_kwargs: Additional keyword arguments for LLM calls.
1487
1490
 
1488
1491
  Returns:
@@ -1490,12 +1493,28 @@ Provide your response as a single JSON object inside a JSON markdown tag. Use th
1490
1493
  answer, the complete internal scratchpad, a log of tool calls,
1491
1494
  any retrieved RAG sources, and other metadata.
1492
1495
  """
1496
+ reasoning_step_id = None
1493
1497
  if not self.binding:
1494
1498
  return {"final_answer": "", "tool_calls": [], "sources": [], "error": "LLM binding not initialized."}
1495
1499
 
1500
+ if not max_reasoning_steps:
1501
+ max_reasoning_steps= 10
1502
+ if not rag_min_similarity_percent:
1503
+ rag_min_similarity_percent= 50
1504
+ if not rag_top_k:
1505
+ rag_top_k = 5
1506
+ if not decision_temperature:
1507
+ decision_temperature = 0.7
1508
+ if not output_summarization_threshold:
1509
+ output_summarization_threshold = 500
1510
+
1511
+ events = []
1512
+
1513
+
1496
1514
  # --- Initialize Agent State ---
1497
1515
  sources_this_turn: List[Dict[str, Any]] = []
1498
1516
  tool_calls_this_turn: List[Dict[str, Any]] = []
1517
+ generated_code_store: Dict[str, str] = {} # NEW: Store for UUID -> code
1499
1518
  original_user_prompt = prompt
1500
1519
 
1501
1520
  initial_state_parts = [
@@ -1507,41 +1526,48 @@ Provide your response as a single JSON object inside a JSON markdown tag. Use th
1507
1526
  initial_state_parts.append(f"- The user has provided {len(images)} image(s) for context.")
1508
1527
  current_scratchpad = "\n".join(initial_state_parts)
1509
1528
 
1510
- # --- Define Inner Helper Function for Stateful Step Logging ---
1511
- def log_step(
1529
+ def log_prompt(prompt, type="prompt"):
1530
+ ASCIIColors.cyan(f"** DEBUG: {type} **")
1531
+ ASCIIColors.magenta(prompt[-15000:])
1532
+ ASCIIColors.cyan(f"** DEBUG: DONE **")
1533
+
1534
+ # --- Define Inner Helper Functions ---
1535
+ def log_event(
1512
1536
  description: str,
1513
- step_type: str,
1537
+ event_type: MSG_TYPE = MSG_TYPE.MSG_TYPE_CHUNK,
1514
1538
  metadata: Optional[Dict] = None,
1515
- is_start: bool = True
1539
+ event_id=None
1516
1540
  ) -> Optional[str]:
1517
- """
1518
- Logs a step start or end, generating a unique ID for correlation.
1519
- This is an inner function that has access to the `streaming_callback`.
1520
-
1521
- Returns the ID for start events so it can be used for the end event.
1522
- """
1523
- if not streaming_callback:
1524
- return None
1525
-
1526
- event_id = str(uuid.uuid4()) if is_start else None
1527
-
1528
- params = {"type": step_type, "description": description, **(metadata or {})}
1529
-
1530
- if is_start:
1531
- params["id"] = event_id
1532
- streaming_callback(description, MSG_TYPE.MSG_TYPE_STEP_START, params)
1533
- return event_id
1534
- else:
1535
- if 'id' in params:
1536
- streaming_callback(description, MSG_TYPE.MSG_TYPE_STEP_END, params)
1537
- else: # Fallback for simple, non-duration steps
1538
- streaming_callback(description, MSG_TYPE.MSG_TYPE_STEP, params)
1539
- return None
1541
+ if not streaming_callback: return None
1542
+ event_id = str(uuid.uuid4()) if event_type==MSG_TYPE.MSG_TYPE_STEP_START else event_id
1543
+ params = {"type": event_type, "description": description, **(metadata or {})}
1544
+ params["id"] = event_id
1545
+ streaming_callback(description, event_type, params)
1546
+ return event_id
1547
+
1548
+ def _substitute_code_uuids_recursive(data: Any, code_store: Dict[str, str]):
1549
+ """Recursively finds and replaces code UUIDs in tool parameters."""
1550
+ if isinstance(data, dict):
1551
+ for key, value in data.items():
1552
+ if isinstance(value, str) and value in code_store:
1553
+ data[key] = code_store[value]
1554
+ else:
1555
+ _substitute_code_uuids_recursive(value, code_store)
1556
+ elif isinstance(data, list):
1557
+ for i, item in enumerate(data):
1558
+ if isinstance(item, str) and item in code_store:
1559
+ data[i] = code_store[item]
1560
+ else:
1561
+ _substitute_code_uuids_recursive(item, code_store)
1540
1562
 
1563
+ discovery_step_id = log_event("Discovering tools",MSG_TYPE.MSG_TYPE_STEP_START)
1541
1564
  # --- 1. Discover Available Tools ---
1542
1565
  available_tools = []
1543
1566
  if use_mcps and self.mcp:
1544
- available_tools.extend(self.mcp.discover_tools(force_refresh=True))
1567
+ discovered_tools = self.mcp.discover_tools(force_refresh=True)
1568
+ if isinstance(use_mcps, list):
1569
+ available_tools.extend([t for t in discovered_tools if t["name"] in use_mcps])
1570
+
1545
1571
  if use_data_store:
1546
1572
  for store_name in use_data_store:
1547
1573
  available_tools.append({
@@ -1550,19 +1576,33 @@ Provide your response as a single JSON object inside a JSON markdown tag. Use th
1550
1576
  "input_schema": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}
1551
1577
  })
1552
1578
 
1553
- formatted_tools_list = "\n".join([f"- {t['name']}: {t['description']}" for t in available_tools])
1554
- formatted_tools_list += "\n- request_clarification: Use if the user's request is ambiguous."
1555
- formatted_tools_list += "\n- final_answer: Use when you are ready to respond to the user."
1579
+ # Add the new put_code_in_buffer tool definition
1580
+ available_tools.append({
1581
+ "name": "put_code_in_buffer",
1582
+ "description": "Generates a block of code (e.g., Python, SQL) to be used by another tool. It returns a unique 'code_id'. You must then use this 'code_id' as the value for the code parameter in the subsequent tool call. This **does not** execute the code. It only buffers it for future use. Only use it if another tool requires code.",
1583
+ "input_schema": {"type": "object", "properties": {"prompt": {"type": "string", "description": "A detailed natural language description of the code's purpose and requirements."}}, "required": ["prompt"]}
1584
+ })
1585
+ # Add the new refactor_scratchpad tool definition
1586
+ available_tools.append({
1587
+ "name": "refactor_scratchpad",
1588
+ "description": "Rewrites the scratchpad content to clean it and reorganize it. Only use if the scratchpad is messy or contains too much information compared to what you need.",
1589
+ "input_schema": {"type": "object", "properties": {}}
1590
+ })
1591
+
1592
+ formatted_tools_list = "\n".join([f"**{t['name']}**:\n{t['description']}\ninput schema:\n{json.dumps(t['input_schema'])}" for t in available_tools])
1593
+ formatted_tools_list += "\n**request_clarification**:\nUse if the user's request is ambiguous and you can not infer a clear idea of his intent. this tool has no parameters."
1594
+ formatted_tools_list += "\n**final_answer**:\nUse when you are ready to respond to the user. this tool has no parameters."
1595
+
1596
+ if discovery_step_id: log_event("Discovering tools",MSG_TYPE.MSG_TYPE_STEP_END, event_id=discovery_step_id)
1556
1597
 
1557
1598
  # --- 2. Dynamic Reasoning Loop ---
1558
1599
  for i in range(max_reasoning_steps):
1559
- reasoning_step_id = log_step(f"Reasoning Step {i+1}/{max_reasoning_steps}", "reasoning_step", is_start=True)
1560
-
1561
- user_context = f'Original User Request: "{original_user_prompt}"'
1562
- if images:
1563
- user_context += f'\n(Note: {len(images)} image(s) were provided with this request.)'
1564
-
1565
- reasoning_prompt_template = f"""You are a logical AI assistant. Your task is to achieve the user's goal by thinking step-by-step and using the available tools.
1600
+ try:
1601
+ reasoning_step_id = log_event(f"Reasoning Step {i+1}/{max_reasoning_steps}", MSG_TYPE.MSG_TYPE_STEP_START)
1602
+ user_context = f'Original User Request: "{original_user_prompt}"'
1603
+ if images: user_context += f'\n(Note: {len(images)} image(s) were provided with this request.)'
1604
+
1605
+ reasoning_prompt_template = f"""You are a logical AI assistant. Your task is to achieve the user's goal by thinking step-by-step and using the available tools.
1566
1606
 
1567
1607
  --- AVAILABLE TOOLS ---
1568
1608
  {formatted_tools_list}
@@ -1577,122 +1617,150 @@ Provide your response as a single JSON object inside a JSON markdown tag. Use th
1577
1617
  2. **THINK:**
1578
1618
  - Does the latest observation completely fulfill the user's original request?
1579
1619
  - If YES, your next action MUST be to use the `final_answer` tool.
1580
- - If NO, what is the single next logical step needed?
1620
+ - If NO, what is the single next logical step needed? This may involve writing code first with `put_code_in_buffer`, then using another tool.
1581
1621
  - If you are stuck or the request is ambiguous, use `request_clarification`.
1582
1622
  3. **ACT:** Formulate your decision as a JSON object.
1583
1623
  """
1584
- action_template = {
1585
- "thought": "My detailed analysis of the last observation and my reasoning for the next action.",
1586
- "action": {
1587
- "tool_name": "The single tool to use (e.g., 'time_machine::get_current_time', 'final_answer').",
1588
- "tool_params": {"param1": "value1"},
1589
- "clarification_question": "(string, ONLY if tool_name is 'request_clarification')"
1624
+ action_template = {
1625
+ "thought": "My detailed analysis of the last observation and my reasoning for the next action and how it integrates with my global plan.",
1626
+ "action": {
1627
+ "tool_name": "The single tool to use (e.g., 'put_code_in_buffer', 'time_machine::get_current_time', 'final_answer').",
1628
+ "tool_params": {"param1": "value1"},
1629
+ "clarification_question": "(string, ONLY if tool_name is 'request_clarification')"
1630
+ }
1590
1631
  }
1591
- }
1592
-
1593
- structured_action_response = self.generate_code(
1594
- prompt=reasoning_prompt_template,
1595
- template=json.dumps(action_template, indent=2),
1596
- system_prompt=reasoning_system_prompt,
1597
- temperature=decision_temperature,
1598
- images=images if i == 0 else None
1599
- )
1600
-
1601
- try:
1602
- action_data = json.loads(structured_action_response)
1603
- thought = action_data.get("thought", "No thought was generated.")
1604
- action = action_data.get("action", {})
1605
- tool_name = action.get("tool_name")
1606
- tool_params = action.get("tool_params", {})
1607
- except (json.JSONDecodeError, TypeError) as e:
1608
- current_scratchpad += f"\n\n### Step {i+1} Failure\n- **Error:** Failed to generate a valid JSON action: {e}"
1609
- log_step(f"\n\n### Step {i+1} Failure\n- **Error:** Failed to generate a valid JSON action: {e}", "scratchpad", is_start=False)
1610
- if reasoning_step_id:
1611
- log_step(f"Reasoning Step {i+1}/{max_reasoning_steps}", "reasoning_step", metadata={"id": reasoning_step_id, "error": str(e)}, is_start=False)
1612
- break
1632
+ if debug: log_prompt(reasoning_prompt_template, f"REASONING PROMPT (Step {i+1})")
1633
+ structured_action_response = self.generate_code(
1634
+ prompt=reasoning_prompt_template, template=json.dumps(action_template, indent=2),
1635
+ system_prompt=reasoning_system_prompt, temperature=decision_temperature,
1636
+ images=images if i == 0 else None
1637
+ )
1638
+ if debug: log_prompt(structured_action_response, f"RAW REASONING RESPONSE (Step {i+1})")
1613
1639
 
1614
- current_scratchpad += f"\n\n### Step {i+1}: Thought\n{thought}"
1615
- log_step(f"\n\n### Step {i+1}: Thought\n{thought}", "scratchpad", is_start=False)
1616
- if streaming_callback:
1617
- streaming_callback(thought, MSG_TYPE.MSG_TYPE_INFO, {"type": "thought"})
1640
+ try:
1641
+ action_data = robust_json_parser(structured_action_response)
1642
+ thought = action_data.get("thought", "No thought was generated.")
1643
+ action = action_data.get("action", {})
1644
+ if isinstance(action,str):
1645
+ tool_name = action
1646
+ tool_params = {}
1647
+ else:
1648
+ tool_name = action.get("tool_name")
1649
+ tool_params = action.get("tool_params", {})
1650
+ except (json.JSONDecodeError, TypeError) as e:
1651
+ current_scratchpad += f"\n\n### Step {i+1} Failure\n- **Error:** Failed to generate a valid JSON action: {e}"
1652
+ log_event(f"Step Failure: Invalid JSON action.", MSG_TYPE.MSG_TYPE_EXCEPTION, metadata={"details": str(e)})
1653
+ if reasoning_step_id: log_event(f"Reasoning Step {i+1}/{max_reasoning_steps}", MSG_TYPE.MSG_TYPE_STEP_END, metadata={"error": str(e)}, event_id=reasoning_step_id)
1654
+
1618
1655
 
1619
- if not tool_name:
1620
- current_scratchpad += f"\n\n### Step {i+1} Failure\n- **Error:** Did not specify a tool name."
1621
- log_step(f"\n\n### Step {i+1} Failure\n- **Error:** Did not specify a tool name.", "scratchpad", is_start=False)
1622
- if reasoning_step_id:
1623
- log_step(f"Reasoning Step {i+1}/{max_reasoning_steps}", "reasoning_step", metadata={"id": reasoning_step_id}, is_start=False)
1624
- break
1656
+ current_scratchpad += f"\n\n### Step {i+1}: Thought\n{thought}"
1657
+ log_event(f"Thought: {thought}", MSG_TYPE.MSG_TYPE_THOUGHT_CONTENT)
1625
1658
 
1626
- if tool_name == "request_clarification":
1627
- clarification_question = action.get("clarification_question", "Could you please provide more details?")
1628
- current_scratchpad += f"\n\n### Step {i+1}: Action\n- **Action:** Decided to request clarification.\n- **Question:** {clarification_question}"
1629
- log_step(f"\n\n### Step {i+1}: Action\n- **Action:** Decided to request clarification.\n- **Question:** {clarification_question}", "scratchpad", is_start=False)
1630
- if reasoning_step_id:
1631
- log_step(f"Reasoning Step {i+1}/{max_reasoning_steps}", "reasoning_step", metadata={"id": reasoning_step_id}, is_start=False)
1632
- return {"final_answer": clarification_question, "final_scratchpad": current_scratchpad, "tool_calls": tool_calls_this_turn, "sources": sources_this_turn, "clarification_required": True, "error": None}
1633
-
1634
- if tool_name == "final_answer":
1635
- current_scratchpad += f"\n\n### Step {i+1}: Action\n- **Action:** Decided to formulate the final answer."
1636
- log_step(f"\n\n### Step {i+1}: Action\n- **Action:** Decided to formulate the final answer.", "scratchpad", is_start=False)
1637
- if reasoning_step_id:
1638
- log_step(f"Reasoning Step {i+1}/{max_reasoning_steps}", "reasoning_step", metadata={"id": reasoning_step_id}, is_start=False)
1639
- break
1659
+ if not tool_name:
1660
+ # Handle error...
1661
+ break
1662
+
1663
+ # --- Handle special, non-executing tools ---
1664
+ if tool_name == "request_clarification":
1665
+ # Handle clarification...
1666
+ return {"final_answer": action.get("clarification_question", "Could you please provide more details?"), "final_scratchpad": current_scratchpad, "tool_calls": tool_calls_this_turn, "sources": sources_this_turn, "clarification_required": True, "error": None}
1667
+
1668
+ if tool_name == "final_answer":
1669
+ current_scratchpad += f"\n\n### Step {i+1}: Action\n- **Action:** Decided to formulate the final answer."
1670
+ log_event("Action: Formulate final answer.", MSG_TYPE.MSG_TYPE_THOUGHT_CHUNK)
1671
+ if reasoning_step_id: log_event(f"Reasoning Step {i+1}/{max_reasoning_steps}",MSG_TYPE.MSG_TYPE_STEP_END, event_id=reasoning_step_id)
1672
+ break
1640
1673
 
1641
- tool_call_id = log_step(f"Executing tool: {tool_name}", "tool_call", metadata={"name": tool_name, "parameters": tool_params}, is_start=True)
1642
- tool_result = None
1643
- try:
1644
- if tool_name.startswith("research::") and use_data_store:
1645
- store_name = tool_name.split("::")[1]
1646
- rag_callable = use_data_store.get(store_name, {}).get("callable")
1647
- query = tool_params.get("query", "")
1648
- retrieved_chunks = rag_callable(query, rag_top_k=rag_top_k, rag_min_similarity_percent=rag_min_similarity_percent)
1649
- if retrieved_chunks:
1650
- sources_this_turn.extend(retrieved_chunks)
1651
- tool_result = {"status": "success", "summary": f"Found {len(retrieved_chunks)} relevant chunks.", "chunks": retrieved_chunks}
1674
+ # --- Handle the `put_code_in_buffer` tool specifically ---
1675
+ if tool_name == 'put_code_in_buffer':
1676
+ code_gen_id = log_event(f"Generating code...", MSG_TYPE.MSG_TYPE_STEP_START, metadata={"name": "put_code_in_buffer", "id": "gencode"})
1677
+ code_prompt = tool_params.get("prompt", "Generate the requested code.")
1678
+
1679
+ # Use a specific system prompt to get raw code
1680
+ code_generation_system_prompt = "You are a code generation assistant. Generate ONLY the raw code based on the user's request. Do not add any explanations, markdown code fences, or other text outside of the code itself."
1681
+ generated_code = self.generate_code(prompt=code_prompt, system_prompt=code_generation_system_prompt + "\n----\n" + reasoning_prompt_template, **llm_generation_kwargs)
1682
+
1683
+ code_uuid = str(uuid.uuid4())
1684
+ generated_code_store[code_uuid] = generated_code
1685
+
1686
+ tool_result = {"status": "success", "code_id": code_uuid, "summary": f"Code generated successfully. Use this ID in the next tool call that requires code."}
1687
+ tool_calls_this_turn.append({"name": "put_code_in_buffer", "params": tool_params, "result": tool_result})
1688
+ observation_text = f"```json\n{json.dumps(tool_result, indent=2)}\n```"
1689
+ current_scratchpad += f"\n\n### Step {i+1}: Observation\n- **Action:** Called `{tool_name}`\n- **Result:**\n{observation_text}"
1690
+ log_event(f"Observation: Code generated with ID: {code_uuid}", MSG_TYPE.MSG_TYPE_OBSERVATION)
1691
+ if code_gen_id: log_event(f"Generating code...", MSG_TYPE.MSG_TYPE_TOOL_CALL, metadata={"id": code_gen_id, "result": tool_result})
1692
+ if reasoning_step_id: log_event(f"Reasoning Step {i+1}/{max_reasoning_steps}", MSG_TYPE.MSG_TYPE_STEP_END, event_id= reasoning_step_id)
1693
+ continue # Go to the next reasoning step immediately
1694
+ if tool_name == 'refactor_scratchpad':
1695
+ scratchpad_cleaning_prompt = f"""Enhance this scratchpad content to be more organized and comprehensive. Keep relevant experience information and remove any useless redundancies. Try to log learned things from the context so that you won't make the same mistakes again. Do not remove the main objective information or any crucial information that may be useful for the next iterations. Answer directly with the new scratchpad content without any comments.
1696
+ --- YOUR INTERNAL SCRATCHPAD (Work History & Analysis) ---
1697
+ {current_scratchpad}
1698
+ --- END OF SCRATCHPAD ---"""
1699
+ current_scratchpad = self.generate_text(scratchpad_cleaning_prompt)
1700
+ log_event(f"New scratchpad:\n{current_scratchpad}")
1701
+
1702
+ # --- Substitute UUIDs and Execute Standard Tools ---
1703
+ log_event(f"Calling tool: `{tool_name}` with params:\n{dict_to_markdown(tool_params)}", MSG_TYPE.MSG_TYPE_STEP)
1704
+ _substitute_code_uuids_recursive(tool_params, generated_code_store)
1705
+
1706
+ tool_call_id = log_event(f"Executing tool: {tool_name}",MSG_TYPE.MSG_TYPE_STEP_START, metadata={"name": tool_name, "parameters": tool_params, "id":"executing tool"})
1707
+ tool_result = None
1708
+ try:
1709
+ if tool_name.startswith("research::") and use_data_store:
1710
+ store_name = tool_name.split("::")[1]
1711
+ rag_callable = use_data_store.get(store_name, {}).get("callable")
1712
+ query = tool_params.get("query", "")
1713
+ retrieved_chunks = rag_callable(query, rag_top_k=rag_top_k, rag_min_similarity_percent=rag_min_similarity_percent)
1714
+ if retrieved_chunks:
1715
+ sources_this_turn.extend(retrieved_chunks)
1716
+ tool_result = {"status": "success", "summary": f"Found {len(retrieved_chunks)} relevant chunks.", "chunks": retrieved_chunks}
1717
+ else:
1718
+ tool_result = {"status": "success", "summary": "No relevant documents found."}
1719
+ elif use_mcps and self.mcp:
1720
+ mcp_result = self.mcp.execute_tool(tool_name, tool_params, lollms_client_instance=self)
1721
+ tool_result = {"status": "success", "output": mcp_result} if not (isinstance(mcp_result, dict) and "error" in mcp_result) else {"status": "failure", **mcp_result}
1652
1722
  else:
1653
- tool_result = {"status": "success", "summary": "No relevant documents found."}
1654
- elif use_mcps and self.mcp:
1655
- mcp_result = self.mcp.execute_tool(tool_name, tool_params, lollms_client_instance=self)
1656
- tool_result = {"status": "success", "output": mcp_result} if not (isinstance(mcp_result, dict) and "error" in mcp_result) else {"status": "failure", **mcp_result}
1723
+ tool_result = {"status": "failure", "error": f"Tool '{tool_name}' not found."}
1724
+ except Exception as e:
1725
+ trace_exception(e)
1726
+ tool_result = {"status": "failure", "error": f"Exception executing tool: {str(e)}"}
1727
+
1728
+ if tool_call_id: log_event(f"Executing tool: {tool_name}", MSG_TYPE.MSG_TYPE_STEP_END, metadata={"result": tool_result}, event_id= tool_call_id)
1729
+
1730
+ observation_text = ""
1731
+ sanitized_result = {}
1732
+ if isinstance(tool_result, dict):
1733
+ sanitized_result = tool_result.copy()
1734
+ summarized_fields = {}
1735
+ for key, value in tool_result.items():
1736
+ if isinstance(value, str) and key.endswith("_base64") and len(value) > 256:
1737
+ sanitized_result[key] = f"[Image was generated. Size: {len(value)} bytes]"
1738
+ continue
1739
+ if isinstance(value, str) and len(self.tokenize(value)) > output_summarization_threshold:
1740
+ if streaming_callback: streaming_callback(f"Summarizing long output from field '{key}'...", MSG_TYPE.MSG_TYPE_STEP, {"type": "summarization"})
1741
+ summary = self.sequential_summarize(text=value, chunk_processing_prompt=f"Summarize key info from this chunk of '{key}'.", callback=streaming_callback)
1742
+ summarized_fields[key] = summary
1743
+ sanitized_result[key] = f"[Content summarized, see summary below. Original length: {len(value)} chars]"
1744
+ observation_text = f"```json\n{json.dumps(sanitized_result, indent=2)}\n```"
1745
+ if summarized_fields:
1746
+ observation_text += "\n\n**Summaries of Long Outputs:**"
1747
+ for key, summary in summarized_fields.items():
1748
+ observation_text += f"\n- **Summary of '{key}':**\n{summary}"
1657
1749
  else:
1658
- tool_result = {"status": "failure", "error": f"Tool '{tool_name}' not found."}
1659
- except Exception as e:
1660
- trace_exception(e)
1661
- tool_result = {"status": "failure", "error": f"Exception executing tool: {str(e)}"}
1662
-
1663
- if tool_call_id:
1664
- log_step(f"Executing tool: {tool_name}", "tool_call", metadata={"id": tool_call_id, "result": tool_result}, is_start=False)
1665
-
1666
- observation_text = ""
1667
- if isinstance(tool_result, dict):
1668
- sanitized_result = tool_result.copy()
1669
- summarized_fields = {}
1670
- for key, value in tool_result.items():
1671
- if isinstance(value, str) and key.endswith("_base64") and len(value) > 256:
1672
- sanitized_result[key] = f"[Image was generated. Size: {len(value)} bytes]"
1673
- continue
1674
- if isinstance(value, str) and len(self.tokenize(value)) > output_summarization_threshold:
1675
- if streaming_callback: streaming_callback(f"Summarizing long output from field '{key}'...", MSG_TYPE.MSG_TYPE_STEP, {"type": "summarization"})
1676
- summary = self.sequential_summarize(text=value, chunk_processing_prompt=f"Summarize key info from this chunk of '{key}'.", callback=streaming_callback)
1677
- summarized_fields[key] = summary
1678
- sanitized_result[key] = f"[Content summarized, see summary below. Original length: {len(value)} chars]"
1679
- observation_text = f"```json\n{json.dumps(sanitized_result, indent=2)}\n```"
1680
- if summarized_fields:
1681
- observation_text += "\n\n**Summaries of Long Outputs:**"
1682
- for key, summary in summarized_fields.items():
1683
- observation_text += f"\n- **Summary of '{key}':**\n{summary}"
1684
- else:
1685
- observation_text = f"Tool returned non-dictionary output: {str(tool_result)}"
1686
-
1687
- tool_calls_this_turn.append({"name": tool_name, "params": tool_params, "result": tool_result})
1688
- current_scratchpad += f"\n\n### Step {i+1}: Observation\n- **Action:** Called `{tool_name}`\n- **Result:**\n{observation_text}"
1689
- log_step(f"### Step {i+1}: Observation\n- **Action:** Called `{tool_name}`\n", "scratchpad", is_start=False)
1690
-
1691
- if reasoning_step_id:
1692
- log_step(f"Reasoning Step {i+1}/{max_reasoning_steps}", "reasoning_step", metadata={"id": reasoning_step_id}, is_start=False)
1693
-
1750
+ observation_text = f"Tool returned non-dictionary output: {str(tool_result)}"
1751
+
1752
+ tool_calls_this_turn.append({"name": tool_name, "params": tool_params, "result": tool_result})
1753
+ current_scratchpad += f"\n\n### Step {i+1}: Observation\n- **Action:** Called `{tool_name}`\n- **Result:**\n{observation_text}"
1754
+ log_event(f"Observation: Result from `{tool_name}`:\n{dict_to_markdown(sanitized_result)}", MSG_TYPE.MSG_TYPE_OBSERVATION)
1755
+
1756
+ if reasoning_step_id: log_event(f"Reasoning Step {i+1}/{max_reasoning_steps}", MSG_TYPE.MSG_TYPE_STEP_END, event_id = reasoning_step_id)
1757
+ except Exception as ex:
1758
+ trace_exception(ex)
1759
+ current_scratchpad += f"\n\n### Error : {ex}"
1760
+ if reasoning_step_id: log_event(f"Reasoning Step {i+1}/{max_reasoning_steps}", MSG_TYPE.MSG_TYPE_STEP_END, event_id = reasoning_step_id)
1761
+
1694
1762
  # --- Final Answer Synthesis ---
1695
- synthesis_id = log_step("Synthesizing final answer...", "final_answer_synthesis", is_start=True)
1763
+ synthesis_id = log_event("Synthesizing final answer...", MSG_TYPE.MSG_TYPE_STEP_START)
1696
1764
 
1697
1765
  final_answer_prompt = f"""You are an AI assistant. Provide a final, comprehensive answer based on your work.
1698
1766
  --- Original User Request ---
@@ -1704,11 +1772,12 @@ Provide your response as a single JSON object inside a JSON markdown tag. Use th
1704
1772
  - If images were provided by the user, incorporate your analysis of them into the answer.
1705
1773
  - Do not talk about your internal process unless it's necessary to explain why you couldn't find an answer.
1706
1774
  """
1775
+ if debug: log_prompt(final_answer_prompt, "FINAL ANSWER SYNTHESIS PROMPT")
1707
1776
  final_answer_text = self.generate_text(prompt=final_answer_prompt, system_prompt=system_prompt, images=images, stream=streaming_callback is not None, streaming_callback=streaming_callback, temperature=final_answer_temperature, **llm_generation_kwargs)
1708
1777
  final_answer = self.remove_thinking_blocks(final_answer_text)
1778
+ if debug: log_prompt(final_answer_text, "FINAL ANSWER RESPONSE")
1709
1779
 
1710
- if synthesis_id:
1711
- log_step("Synthesizing final answer...", "final_answer_synthesis", metadata={"id": synthesis_id}, is_start=False)
1780
+ if synthesis_id: log_event("Synthesizing final answer...", MSG_TYPE.MSG_TYPE_STEP_END, event_id= synthesis_id)
1712
1781
 
1713
1782
  return {
1714
1783
  "final_answer": final_answer,
@@ -1718,7 +1787,6 @@ Provide your response as a single JSON object inside a JSON markdown tag. Use th
1718
1787
  "clarification_required": False,
1719
1788
  "error": None
1720
1789
  }
1721
-
1722
1790
  def generate_code(
1723
1791
  self,
1724
1792
  prompt,
@@ -1797,7 +1865,7 @@ Do not split the code in multiple tags.
1797
1865
  while not last_code["is_complete"] and retries < max_retries:
1798
1866
  retries += 1
1799
1867
  ASCIIColors.info(f"Code block seems incomplete. Attempting continuation ({retries}/{max_retries})...")
1800
- continuation_prompt = f"{full_prompt}{code_content}\n\n{self.user_full_header}The previous code block was incomplete. Continue the code exactly from where it left off. Do not repeat the previous part. Only provide the continuation inside a single {code_tag_format} code tag.\n{self.ai_full_header}"
1868
+ continuation_prompt = f"{prompt}\n\nAssistant:\n{code_content}\n\n{self.user_full_header}The previous code block was incomplete. Continue the code exactly from where it left off. Do not repeat the previous part. Only provide the continuation inside a single {code_tag_format} code tag.\n{self.ai_full_header}"
1801
1869
 
1802
1870
  continuation_response = self.generate_text(
1803
1871
  continuation_prompt,
@@ -2067,7 +2135,7 @@ Do not split the code in multiple tags.
2067
2135
  response_json_str = re.sub(r",\s*}", "}", response_json_str)
2068
2136
  response_json_str = re.sub(r",\s*]", "]", response_json_str)
2069
2137
 
2070
- parsed_response = json.loads(response_json_str)
2138
+ parsed_response = robust_json_parser(response_json_str)
2071
2139
  answer = parsed_response.get("answer")
2072
2140
  explanation = parsed_response.get("explanation", "")
2073
2141
 
@@ -2161,7 +2229,7 @@ Do not split the code in multiple tags.
2161
2229
  response_json_str = re.sub(r",\s*}", "}", response_json_str)
2162
2230
  response_json_str = re.sub(r",\s*]", "]", response_json_str)
2163
2231
 
2164
- result = json.loads(response_json_str)
2232
+ result = robust_json_parser(response_json_str)
2165
2233
  index = result.get("index")
2166
2234
  explanation = result.get("explanation", "")
2167
2235
 
@@ -2234,7 +2302,7 @@ Do not split the code in multiple tags.
2234
2302
  response_json_str = re.sub(r",\s*}", "}", response_json_str)
2235
2303
  response_json_str = re.sub(r",\s*]", "]", response_json_str)
2236
2304
 
2237
- result = json.loads(response_json_str)
2305
+ result = robust_json_parser(response_json_str)
2238
2306
  ranking = result.get("ranking")
2239
2307
  explanations = result.get("explanations", []) if return_explanation else None
2240
2308
 
@@ -2858,5 +2926,3 @@ def chunk_text(text, tokenizer, detokenizer, chunk_size, overlap, use_separators
2858
2926
  break
2859
2927
 
2860
2928
  return chunks
2861
-
2862
-
@@ -29,6 +29,8 @@ if False:
29
29
  from lollms_client import LollmsClient
30
30
  from lollms_personality import LollmsPersonality
31
31
 
32
+ from lollms_client.lollms_utilities import build_image_dicts, robust_json_parser
33
+ from ascii_colors import ASCIIColors, trace_exception
32
34
 
33
35
  class EncryptedString(TypeDecorator):
34
36
  """A SQLAlchemy TypeDecorator for field-level database encryption.
@@ -564,11 +566,13 @@ class LollmsDiscussion:
564
566
  self,
565
567
  user_message: str,
566
568
  personality: Optional['LollmsPersonality'] = None,
569
+ branch_tip_id: Optional[str | None] = None,
567
570
  use_mcps: Union[None, bool, List[str]] = None,
568
571
  use_data_store: Union[None, Dict[str, Callable]] = None,
569
572
  add_user_message: bool = True,
570
- max_reasoning_steps: int = 10,
573
+ max_reasoning_steps: int = 20,
571
574
  images: Optional[List[str]] = None,
575
+ debug: bool = False,
572
576
  **kwargs
573
577
  ) -> Dict[str, 'LollmsMessage']:
574
578
  """Main interaction method that can invoke the dynamic, multi-modal agent.
@@ -597,6 +601,7 @@ class LollmsDiscussion:
597
601
  before it must provide a final answer.
598
602
  images: A list of base64-encoded images provided by the user, which will
599
603
  be passed to the agent or a multi-modal LLM.
604
+ debug: If True, prints full prompts and raw AI responses to the console.
600
605
  **kwargs: Additional keyword arguments passed to the underlying generation
601
606
  methods, such as 'streaming_callback'.
602
607
 
@@ -640,12 +645,21 @@ class LollmsDiscussion:
640
645
  # Step 3: Execute the appropriate generation logic.
641
646
  if is_agentic_turn:
642
647
  # --- AGENTIC TURN ---
648
+ prompt_for_agent = self.export("markdown", branch_tip_id if branch_tip_id else self.active_branch_id)
649
+ if debug:
650
+ ASCIIColors.cyan("\n" + "="*50)
651
+ ASCIIColors.cyan("--- DEBUG: AGENTIC TURN TRIGGERED ---")
652
+ ASCIIColors.cyan(f"--- PROMPT FOR AGENT (from discussion history) ---")
653
+ ASCIIColors.magenta(prompt_for_agent)
654
+ ASCIIColors.cyan("="*50 + "\n")
655
+
643
656
  agent_result = self.lollmsClient.generate_with_mcp_rag(
644
- prompt=user_message,
657
+ prompt=prompt_for_agent,
645
658
  use_mcps=use_mcps,
646
659
  use_data_store=use_data_store,
647
660
  max_reasoning_steps=max_reasoning_steps,
648
661
  images=images,
662
+ debug=debug, # Pass the debug flag down
649
663
  **kwargs
650
664
  )
651
665
  final_content = agent_result.get("final_answer", "The agent did not produce a final answer.")
@@ -654,9 +668,27 @@ class LollmsDiscussion:
654
668
 
655
669
  else:
656
670
  # --- SIMPLE CHAT TURN ---
671
+ if debug:
672
+ prompt_for_chat = self.export("markdown", branch_tip_id if branch_tip_id else self.active_branch_id)
673
+ ASCIIColors.cyan("\n" + "="*50)
674
+ ASCIIColors.cyan("--- DEBUG: SIMPLE CHAT PROMPT ---")
675
+ ASCIIColors.magenta(prompt_for_chat)
676
+ ASCIIColors.cyan("="*50 + "\n")
677
+
657
678
  # For simple chat, we also need to consider images if the model is multi-modal
658
679
  final_raw_response = self.lollmsClient.chat(self, images=images, **kwargs) or ""
659
- final_content = self.lollmsClient.remove_thinking_blocks(final_raw_response)
680
+
681
+ if debug:
682
+ ASCIIColors.cyan("\n" + "="*50)
683
+ ASCIIColors.cyan("--- DEBUG: RAW SIMPLE CHAT RESPONSE ---")
684
+ ASCIIColors.magenta(final_raw_response)
685
+ ASCIIColors.cyan("="*50 + "\n")
686
+
687
+ if isinstance(final_raw_response, dict) and final_raw_response.get("status") == "error":
688
+ raise Exception(final_raw_response.get("message", "Unknown error from lollmsClient.chat"))
689
+ else:
690
+ final_content = self.lollmsClient.remove_thinking_blocks(final_raw_response)
691
+
660
692
  final_scratchpad = None # No agentic scratchpad in a simple turn
661
693
 
662
694
  # Step 4: Post-generation processing and statistics.
@@ -694,7 +726,7 @@ class LollmsDiscussion:
694
726
 
695
727
  return {"user_message": user_msg, "ai_message": ai_message_obj}
696
728
 
697
- def regenerate_branch(self, **kwargs) -> Dict[str, 'LollmsMessage']:
729
+ def regenerate_branch(self, branch_tip_id=None, **kwargs) -> Dict[str, 'LollmsMessage']:
698
730
  """Regenerates the last AI response in the active branch.
699
731
 
700
732
  It deletes the previous AI response and calls chat() again with the
@@ -706,8 +738,15 @@ class LollmsDiscussion:
706
738
  Returns:
707
739
  A dictionary with the user and the newly generated AI message.
708
740
  """
741
+ if not branch_tip_id:
742
+ branch_tip_id = self.active_branch_id
709
743
  if not self.active_branch_id or self.active_branch_id not in self._message_index:
710
- raise ValueError("No active message to regenerate from.")
744
+ if len(self._message_index)>0:
745
+ ASCIIColors.warning("No active message to regenerate from.\n")
746
+ ASCIIColors.warning(f"Using last available message:{list(self._message_index.keys())[-1]}\n")
747
+ else:
748
+ branch_tip_id = list(self._message_index.keys())[-1]
749
+ raise ValueError("No active message to regenerate from.")
711
750
 
712
751
  last_message_orm = self._message_index[self.active_branch_id]
713
752
 
@@ -722,11 +761,8 @@ class LollmsDiscussion:
722
761
  if self._is_db_backed:
723
762
  self._messages_to_delete_from_db.add(last_message_id)
724
763
 
725
- self.active_branch_id = parent_id
726
- self.touch()
727
-
728
- prompt_to_regenerate = self._message_index[self.active_branch_id].content
729
- return self.chat(user_message=prompt_to_regenerate, add_user_message=False, **kwargs)
764
+ return self.chat(user_message="", add_user_message=False, branch_tip_id=branch_tip_id, **kwargs)
765
+
730
766
  def delete_branch(self, message_id: str):
731
767
  """Deletes a message and its entire descendant branch.
732
768
 
@@ -801,7 +837,7 @@ class LollmsDiscussion:
801
837
 
802
838
  Args:
803
839
  format_type: The target format. Can be "lollms_text", "openai_chat",
804
- or "ollama_chat".
840
+ "ollama_chat", or "markdown".
805
841
  branch_tip_id: The ID of the message to use as the end of the context.
806
842
  Defaults to the active branch ID.
807
843
  max_allowed_tokens: The maximum number of tokens the final prompt can contain.
@@ -809,15 +845,15 @@ class LollmsDiscussion:
809
845
 
810
846
  Returns:
811
847
  A string for "lollms_text" or a list of dictionaries for "openai_chat"
812
- and "ollama_chat".
848
+ and "ollama_chat". For "markdown", returns a Markdown-formatted string.
813
849
 
814
850
  Raises:
815
851
  ValueError: If an unsupported format_type is provided.
816
852
  """
817
853
  branch_tip_id = branch_tip_id or self.active_branch_id
818
- if not branch_tip_id and format_type in ["lollms_text", "openai_chat", "ollama_chat"]:
854
+ if not branch_tip_id and format_type in ["lollms_text", "openai_chat", "ollama_chat", "markdown"]:
819
855
  return "" if format_type == "lollms_text" else []
820
-
856
+
821
857
  branch = self.get_branch(branch_tip_id)
822
858
  full_system_prompt = self.system_prompt # Simplified for clarity
823
859
  participants = self.participants or {}
@@ -829,14 +865,12 @@ class LollmsDiscussion:
829
865
 
830
866
  # --- NATIVE LOLLMS_TEXT FORMAT ---
831
867
  if format_type == "lollms_text":
832
- # --- FIX STARTS HERE ---
833
868
  final_prompt_parts = []
834
869
  message_parts = [] # Temporary list for correctly ordered messages
835
-
870
+
836
871
  current_tokens = 0
837
872
  messages_to_render = branch
838
873
 
839
- # 1. Handle non-destructive pruning summary
840
874
  summary_text = ""
841
875
  if self.pruning_summary and self.pruning_point_id:
842
876
  pruning_index = -1
@@ -848,7 +882,6 @@ class LollmsDiscussion:
848
882
  messages_to_render = branch[pruning_index:]
849
883
  summary_text = f"!@>system:\n--- Conversation Summary ---\n{self.pruning_summary.strip()}\n"
850
884
 
851
- # 2. Add main system prompt to the final list
852
885
  sys_msg_text = ""
853
886
  if full_system_prompt:
854
887
  sys_msg_text = f"!@>system:\n{full_system_prompt.strip()}\n"
@@ -856,15 +889,13 @@ class LollmsDiscussion:
856
889
  if max_allowed_tokens is None or sys_tokens <= max_allowed_tokens:
857
890
  final_prompt_parts.append(sys_msg_text)
858
891
  current_tokens += sys_tokens
859
-
860
- # 3. Add pruning summary (if it exists) to the final list
892
+
861
893
  if summary_text:
862
894
  summary_tokens = self.lollmsClient.count_tokens(summary_text)
863
895
  if max_allowed_tokens is None or current_tokens + summary_tokens <= max_allowed_tokens:
864
896
  final_prompt_parts.append(summary_text)
865
897
  current_tokens += summary_tokens
866
898
 
867
- # 4. Build the message list in correct order, respecting token limits
868
899
  for msg in reversed(messages_to_render):
869
900
  sender_str = msg.sender.replace(':', '').replace('!@>', '')
870
901
  content = get_full_content(msg)
@@ -872,24 +903,21 @@ class LollmsDiscussion:
872
903
  content += f"\n({len(msg.images)} image(s) attached)"
873
904
  msg_text = f"!@>{sender_str}:\n{content}\n"
874
905
  msg_tokens = self.lollmsClient.count_tokens(msg_text)
875
-
906
+
876
907
  if max_allowed_tokens is not None and current_tokens + msg_tokens > max_allowed_tokens:
877
908
  break
878
-
879
- # Always insert at the beginning of the temporary list
909
+
880
910
  message_parts.insert(0, msg_text)
881
911
  current_tokens += msg_tokens
882
-
883
- # 5. Combine system/summary prompts with the message parts
912
+
884
913
  final_prompt_parts.extend(message_parts)
885
914
  return "".join(final_prompt_parts).strip()
886
- # --- FIX ENDS HERE ---
887
-
888
- # --- OPENAI & OLLAMA CHAT FORMATS (remains the same and is correct) ---
915
+
916
+ # --- OPENAI & OLLAMA CHAT FORMATS ---
889
917
  messages = []
890
918
  if full_system_prompt:
891
919
  messages.append({"role": "system", "content": full_system_prompt})
892
-
920
+
893
921
  for msg in branch:
894
922
  if msg.sender_type == 'user':
895
923
  role = participants.get(msg.sender, "user")
@@ -897,6 +925,8 @@ class LollmsDiscussion:
897
925
  role = participants.get(msg.sender, "assistant")
898
926
 
899
927
  content, images = get_full_content(msg), msg.images or []
928
+ images = build_image_dicts(images)
929
+
900
930
 
901
931
  if format_type == "openai_chat":
902
932
  if images:
@@ -908,18 +938,29 @@ class LollmsDiscussion:
908
938
  messages.append({"role": role, "content": content_parts})
909
939
  else:
910
940
  messages.append({"role": role, "content": content})
911
-
941
+
912
942
  elif format_type == "ollama_chat":
913
943
  message_dict = {"role": role, "content": content}
944
+
914
945
  base64_images = [img['data'] for img in images if img['type'] == 'base64']
915
946
  if base64_images:
916
947
  message_dict["images"] = base64_images
917
948
  messages.append(message_dict)
918
949
 
950
+ elif format_type == "markdown":
951
+ # Create Markdown content based on the role and content
952
+ markdown_line = f"**{role.capitalize()}**: {content}\n"
953
+ if images:
954
+ for img in images:
955
+ img_data = img['data']
956
+ url = f"![Image](data:image/jpeg;base64,{img_data})" if img['type'] == 'base64' else f"![Image]({img_data})"
957
+ markdown_line += f"\n{url}\n"
958
+ messages.append(markdown_line)
959
+
919
960
  else:
920
961
  raise ValueError(f"Unsupported export format_type: {format_type}")
921
-
922
- return messages
962
+
963
+ return "\n".join(messages) if format_type == "markdown" else messages
923
964
 
924
965
 
925
966
  def summarize_and_prune(self, max_tokens: int, preserve_last_n: int = 4):
@@ -966,4 +1007,27 @@ class LollmsDiscussion:
966
1007
  self.pruning_point_id = pruning_point_message.id
967
1008
 
968
1009
  self.touch()
969
- print(f"[INFO] Discussion auto-pruned. {len(messages_to_prune)} messages summarized. History preserved.")
1010
+ print(f"[INFO] Discussion auto-pruned. {len(messages_to_prune)} messages summarized. History preserved.")
1011
+
1012
+ def switch_to_branch(self, branch_id):
1013
+ self.active_branch_id = branch_id
1014
+
1015
+ def auto_title(self):
1016
+ try:
1017
+ if self.metadata is None:
1018
+ self.metadata = {}
1019
+ discussion = self.export("markdown")[0:1000]
1020
+ prompt = f"""You are a title builder. Your oibjective is to build a title for the following discussion:
1021
+ {discussion}
1022
+ ...
1023
+ """
1024
+ template = """{
1025
+ "title": "An short but comprehensive discussion title"
1026
+ }"""
1027
+ infos = self.lollmsClient.generate_code(prompt = prompt, template = template)
1028
+ discussion_title = robust_json_parser(infos)["title"]
1029
+ self.metadata['title'] = discussion_title
1030
+ self.commit()
1031
+ return discussion_title
1032
+ except Exception as ex:
1033
+ trace_exception(ex)
@@ -1,7 +1,7 @@
1
1
  from enum import Enum
2
2
  class MSG_TYPE(Enum):
3
3
  # Messaging
4
- MSG_TYPE_CHUNK = 0 # A chunk of a message (used for classical chat)
4
+ MSG_TYPE_CHUNK = 0 # A chunk of a message (used for classical chat)
5
5
  MSG_TYPE_CONTENT = 1 # A full message (for some personality the answer is sent in bulk)
6
6
  MSG_TYPE_CONTENT_INVISIBLE_TO_AI = 2 # A full message (for some personality the answer is sent in bulk)
7
7
  MSG_TYPE_CONTENT_INVISIBLE_TO_USER = 3 # A full message (for some personality the answer is sent in bulk)
@@ -36,6 +36,14 @@ class MSG_TYPE(Enum):
36
36
  MSG_TYPE_TOOL_CALL = 19# a tool call
37
37
  MSG_TYPE_TOOL_OUTPUT = 20# the output of the tool
38
38
 
39
+ MSG_TYPE_REASONING = 21# the ai shows its reasoning
40
+ MSG_TYPE_SCRATCHPAD = 22# the ai shows its scratchpad
41
+ MSG_TYPE_OBSERVATION = 23# the ai shows its reasoning
42
+
43
+ MSG_TYPE_ERROR = 24#a severe error hapened
44
+ MSG_TYPE_GENERATING_TITLE_START = 25#a severe error hapened
45
+ MSG_TYPE_GENERATING_TITLE_END = 26#a severe error hapened
46
+
39
47
 
40
48
  class SENDER_TYPES(Enum):
41
49
  SENDER_TYPES_USER = 0 # Sent by user
@@ -11,6 +11,74 @@ import numpy as np
11
11
  import json
12
12
  from ascii_colors import ASCIIColors, trace_exception
13
13
 
14
+ def dict_to_markdown(d, indent=0):
15
+ """
16
+ Formats a dictionary (with potential nested lists and dicts) as a markdown list.
17
+
18
+ Args:
19
+ d (dict): The dictionary to format.
20
+ indent (int): Current indentation level (used recursively).
21
+
22
+ Returns:
23
+ str: The formatted markdown string.
24
+ """
25
+ lines = []
26
+ indent_str = ' ' * (indent * 2)
27
+
28
+ for key, value in d.items():
29
+ if isinstance(value, dict):
30
+ # Recursively handle nested dictionary
31
+ lines.append(f"{indent_str}- {key}:")
32
+ lines.append(dict_to_markdown(value, indent + 1))
33
+ elif isinstance(value, list):
34
+ lines.append(f"{indent_str}- {key}:")
35
+ for item in value:
36
+ if isinstance(item, dict):
37
+ # Render nested dicts in the list
38
+ lines.append(dict_to_markdown(item, indent + 1))
39
+ else:
40
+ # Render strings or other simple items in the list
41
+ lines.append(f"{' ' * (indent + 1) * 2}- {item}")
42
+ else:
43
+ # Simple key-value pair
44
+ lines.append(f"{indent_str}- {key}: {value}")
45
+
46
+ return "\n".join(lines)
47
+
48
+ def is_base64(s):
49
+ """Check if the string is a valid base64 encoded string."""
50
+ try:
51
+ # Try to decode and then encode back to check for validity
52
+ import base64
53
+ base64.b64decode(s)
54
+ return True
55
+ except Exception as e:
56
+ return False
57
+
58
+ def build_image_dicts(images):
59
+ """
60
+ Convert a list of image strings (base64 or URLs) into a list of dictionaries with type and data.
61
+
62
+ Args:
63
+ images (list): List of image strings (either base64-encoded or URLs).
64
+
65
+ Returns:
66
+ list: List of dictionaries in the format {'type': 'base64'/'url', 'data': <image string>}.
67
+ """
68
+ result = []
69
+
70
+ for img in images:
71
+ if isinstance(img, str):
72
+ if is_base64(img):
73
+ result.append({'type': 'base64', 'data': img})
74
+ else:
75
+ # Assuming it's a URL if not base64
76
+ result.append({'type': 'url', 'data': img})
77
+ else:
78
+ result.append(img)
79
+
80
+ return result
81
+
14
82
  def robust_json_parser(json_string: str) -> dict:
15
83
  """
16
84
  Parses a possibly malformed JSON string using a series of corrective strategies.
@@ -294,7 +294,7 @@ class RemoteMCPBinding(LollmsMCPBinding):
294
294
 
295
295
  try:
296
296
  # Ensure this specific server is connected before executing
297
- self._ensure_initialized_sync(alias, timeout=min(timeout, 30.0))
297
+ self._ensure_initialized_sync(alias, timeout=timeout)
298
298
  return self._run_async(self._execute_tool_async(alias, actual_tool_name, params), timeout=timeout)
299
299
  except (ConnectionError, RuntimeError) as e:
300
300
  return {"error": f"{self.binding_name}: Connection issue for server '{alias}': {e}", "status_code": 503}
@@ -342,4 +342,4 @@ class RemoteMCPBinding(LollmsMCPBinding):
342
342
  ASCIIColors.info(f"{self.binding_name}: Remote connection binding closed.")
343
343
 
344
344
  def get_binding_config(self) -> Dict[str, Any]:
345
- return self.config
345
+ return self.config
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lollms_client
3
- Version: 0.24.1
3
+ Version: 0.25.0
4
4
  Summary: A client library for LoLLMs generate endpoint
5
5
  Author-email: ParisNeo <parisneoai@gmail.com>
6
6
  License: Apache Software License
@@ -26,10 +26,10 @@ examples/mcp_examples/openai_mcp.py,sha256=7IEnPGPXZgYZyiES_VaUbQ6viQjenpcUxGiHE
26
26
  examples/mcp_examples/run_remote_mcp_example_v2.py,sha256=bbNn93NO_lKcFzfIsdvJJijGx2ePFTYfknofqZxMuRM,14626
27
27
  examples/mcp_examples/run_standard_mcp_example.py,sha256=GSZpaACPf3mDPsjA8esBQVUsIi7owI39ca5avsmvCxA,9419
28
28
  examples/test_local_models/local_chat.py,sha256=slakja2zaHOEAUsn2tn_VmI4kLx6luLBrPqAeaNsix8,456
29
- lollms_client/__init__.py,sha256=hphTI6chtuepiPoUBzI6cYGTu07c4BTD8JsniICS2qo,1047
29
+ lollms_client/__init__.py,sha256=Oa7LTqicgM_xArVjSRh-oGxuAXBR5QimNkcCCvsO8qo,1047
30
30
  lollms_client/lollms_config.py,sha256=goEseDwDxYJf3WkYJ4IrLXwg3Tfw73CXV2Avg45M_hE,21876
31
- lollms_client/lollms_core.py,sha256=odJ97aTFkc_tXAfnbyO5C2MstJC4fPqDR0Zusw-vcW0,152646
32
- lollms_client/lollms_discussion.py,sha256=e0lfbkj3Bh-1YbC1JncjO0Dvkx9maFXprAwLLiXxSFc,44578
31
+ lollms_client/lollms_core.py,sha256=J6lGDhUiIS0jqY81AsLp6Nv6pLJbqlDCgxZI-1J-MNc,158724
32
+ lollms_client/lollms_discussion.py,sha256=9mpEFz8UWMXrbyZonnq2nt1u5jDEgQqddHghUhSy9Yc,47516
33
33
  lollms_client/lollms_js_analyzer.py,sha256=01zUvuO2F_lnUe_0NLxe1MF5aHE1hO8RZi48mNPv-aw,8361
34
34
  lollms_client/lollms_llm_binding.py,sha256=Kpzhs5Jx8eAlaaUacYnKV7qIq2wbME5lOEtKSfJKbpg,12161
35
35
  lollms_client/lollms_mcp_binding.py,sha256=0rK9HQCBEGryNc8ApBmtOlhKE1Yfn7X7xIQssXxS2Zc,8933
@@ -40,13 +40,13 @@ lollms_client/lollms_tti_binding.py,sha256=afO0-d-Kqsmh8UHTijTvy6dZAt-XDB6R-IHmd
40
40
  lollms_client/lollms_ttm_binding.py,sha256=FjVVSNXOZXK1qvcKEfxdiX6l2b4XdGOSNnZ0utAsbDg,4167
41
41
  lollms_client/lollms_tts_binding.py,sha256=5cJYECj8PYLJAyB6SEH7_fhHYK3Om-Y3arkygCnZ24o,4342
42
42
  lollms_client/lollms_ttv_binding.py,sha256=KkTaHLBhEEdt4sSVBlbwr5i_g_TlhcrwrT-7DjOsjWQ,4131
43
- lollms_client/lollms_types.py,sha256=c2vkdmyCU5aCyOCfWmfJE-q74T8w1vHMzFoMy8453jY,3108
44
- lollms_client/lollms_utilities.py,sha256=qK5iNmrFD7NGaEVW3nCWT6AtEhLIVHCXMzEpYxG_M5w,11293
43
+ lollms_client/lollms_types.py,sha256=0iSH1QHRRD-ddBqoL9EEKJ8wWCuwDUlN_FrfbCdg7Lw,3522
44
+ lollms_client/lollms_utilities.py,sha256=zx1X4lAXQ2eCUM4jDpu_1QV5oMGdFkpaSEdTASmaiqE,13545
45
45
  lollms_client/llm_bindings/__init__.py,sha256=9sWGpmWSSj6KQ8H4lKGCjpLYwhnVdL_2N7gXCphPqh4,14
46
46
  lollms_client/llm_bindings/llamacpp/__init__.py,sha256=Qj5RvsgPeHGNfb5AEwZSzFwAp4BOWjyxmm9qBNtstrc,63716
47
- lollms_client/llm_bindings/lollms/__init__.py,sha256=17TwGMDJMxRPjZjZZSysR8AwjMXZeRfDBy8RqWWuaIY,17769
47
+ lollms_client/llm_bindings/lollms/__init__.py,sha256=jfiCGJqMensJ7RymeGDDJOsdokEdlORpw9ND_Q30GYc,17831
48
48
  lollms_client/llm_bindings/ollama/__init__.py,sha256=QufsYqak2VlA2XGbzks8u55yNJFeDH2V35NGeZABkm8,32554
49
- lollms_client/llm_bindings/openai/__init__.py,sha256=ay_2JJi4La258Eg3alUhnh6Y5IRyOWnHaFLXqvN_4ao,19144
49
+ lollms_client/llm_bindings/openai/__init__.py,sha256=i4T-QncGhrloslIF3zTlf6ZGJNZA43KCeFyOixD3Ums,19239
50
50
  lollms_client/llm_bindings/openllm/__init__.py,sha256=xv2XDhJNCYe6NPnWBboDs24AQ1VJBOzsTuMcmuQ6xYY,29864
51
51
  lollms_client/llm_bindings/pythonllamacpp/__init__.py,sha256=7dM42TCGKh0eV0njNL1tc9cInhyvBRIXzN3dcy12Gl0,33551
52
52
  lollms_client/llm_bindings/tensor_rt/__init__.py,sha256=nPaNhGRd-bsG0UlYwcEqjd_UagCMEf5VEbBUW-GWu6A,32203
@@ -57,7 +57,7 @@ lollms_client/mcp_bindings/local_mcp/default_tools/file_writer/file_writer.py,sh
57
57
  lollms_client/mcp_bindings/local_mcp/default_tools/generate_image_from_prompt/generate_image_from_prompt.py,sha256=THtZsMxNnXZiBdkwoBlfbWY2C5hhDdmPtnM-8cSKN6s,9488
58
58
  lollms_client/mcp_bindings/local_mcp/default_tools/internet_search/internet_search.py,sha256=PLC31-D04QKTOTb1uuCHnrAlpysQjsk89yIJngK0VGc,4586
59
59
  lollms_client/mcp_bindings/local_mcp/default_tools/python_interpreter/python_interpreter.py,sha256=McDCBVoVrMDYgU7EYtyOY7mCk1uEeTea0PSD69QqDsQ,6228
60
- lollms_client/mcp_bindings/remote_mcp/__init__.py,sha256=_wtrwq5_kRV3Of2lB-45G7BZQVR_fYvacHYc_s6q9fk,16615
60
+ lollms_client/mcp_bindings/remote_mcp/__init__.py,sha256=NBhmk9g9iMrzoraxbQo7wacUTTB1a_azZekuRPS8SO8,16606
61
61
  lollms_client/mcp_bindings/standard_mcp/__init__.py,sha256=zpF4h8cTUxoERI-xcVjmS_V772LK0V4jegjz2k1PK98,31658
62
62
  lollms_client/stt_bindings/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
63
63
  lollms_client/stt_bindings/lollms/__init__.py,sha256=jBz3285atdPRqQe9ZRrb-AvjqKRB4f8tjLXjma0DLfE,6082
@@ -79,8 +79,8 @@ lollms_client/tts_bindings/piper_tts/__init__.py,sha256=0IEWG4zH3_sOkSb9WbZzkeV5
79
79
  lollms_client/tts_bindings/xtts/__init__.py,sha256=FgcdUH06X6ZR806WQe5ixaYx0QoxtAcOgYo87a2qxYc,18266
80
80
  lollms_client/ttv_bindings/__init__.py,sha256=UZ8o2izQOJLQgtZ1D1cXoNST7rzqW22rL2Vufc7ddRc,3141
81
81
  lollms_client/ttv_bindings/lollms/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
82
- lollms_client-0.24.1.dist-info/licenses/LICENSE,sha256=HrhfyXIkWY2tGFK11kg7vPCqhgh5DcxleloqdhrpyMY,11558
83
- lollms_client-0.24.1.dist-info/METADATA,sha256=RMCh7EHn4YiKXnGjDssZdehDM-Wza5OYdl7iWEB9FuQ,13401
84
- lollms_client-0.24.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
85
- lollms_client-0.24.1.dist-info/top_level.txt,sha256=NI_W8S4OYZvJjb0QWMZMSIpOrYzpqwPGYaklhyWKH2w,23
86
- lollms_client-0.24.1.dist-info/RECORD,,
82
+ lollms_client-0.25.0.dist-info/licenses/LICENSE,sha256=HrhfyXIkWY2tGFK11kg7vPCqhgh5DcxleloqdhrpyMY,11558
83
+ lollms_client-0.25.0.dist-info/METADATA,sha256=BEfNVx_C0xdqP-26V5UbPL-mCuhtGzxsgPAEv_XveD0,13401
84
+ lollms_client-0.25.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
85
+ lollms_client-0.25.0.dist-info/top_level.txt,sha256=NI_W8S4OYZvJjb0QWMZMSIpOrYzpqwPGYaklhyWKH2w,23
86
+ lollms_client-0.25.0.dist-info/RECORD,,