Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /ParisNeo_lollms /backend /generation /llm.py
# Standard Library Imports
import base64
import io
import json
import re
import shutil
import uuid
import types
from datetime import datetime
from functools import partial
from pathlib import Path
from typing import Any, AsyncGenerator, Dict, List, Optional, Tuple, Union
import traceback
import threading
import asyncio
import zipfile
import platform
import time
import requests
from concurrent.futures import ThreadPoolExecutor
from safe_store import SafeStore
# Third-Party Imports
import fitz # PyMuPDF
from PIL import Image # Needed for image resizing
from docx import Document as DocxDocument
from fastapi import (
APIRouter, BackgroundTasks, Depends, File, Form, HTTPException, Query,
UploadFile, status, Request)
from fastapi.encoders import jsonable_encoder
from fastapi.responses import (FileResponse, HTMLResponse, JSONResponse,
PlainTextResponse, StreamingResponse)
from lollms_client import (LollmsClient, LollmsDiscussion, LollmsMessage,
LollmsPersonality, MSG_TYPE)
try:
from lollms_client.lollms_personality import RAGDataSource
except ImportError:
RAGDataSource = None
from pydantic import BaseModel
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from sqlalchemy.sql import func
from ascii_colors import ASCIIColors, trace_exception
# Local Application Imports
from backend.config import APP_VERSION, SERVER_CONFIG
from backend.db import get_db
from backend.db.models.config import TTIBinding as DBTTIBinding
from backend.db.models.db_task import DBTask, ScheduledTask
from backend.db.models.personality import Personality as DBPersonality
from backend.db.models.discussion import SharedDiscussionLink as DBSharedDiscussionLink
from backend.db.models.user import (User as DBUser, UserMessageGrade,
UserStarredDiscussion)
from backend.db.models.memory import UserMemory
from backend.db.models.config import LLMBinding as DBLLMBinding
from backend.discussion import get_user_discussion, get_user_discussion_manager
from backend.models import (UserAuthDetails, ArtefactInfo, ContextStatusResponse,
DataZones, DiscussionBranchSwitchRequest,
DiscussionDataZoneUpdate, DiscussionExportRequest,
DiscussionImageUpdateResponse,
DiscussionInfo, DiscussionImportRequest,
DiscussionRagDatastoreUpdate, DiscussionSendRequest,
DiscussionTitleUpdate, ExportContextRequest,
ExportData, LoadArtefactRequest, ManualMessageCreate,
MessageCodeExportRequest, MessageContentUpdate,
MessageGradeUpdate, MessageOutput,
MessageUpdateWithImages, TaskInfo,
UnloadArtefactRequest, ArtefactCreateManual, ArtefactUpdate)
from backend.session import (get_current_active_user,
get_current_db_user_from_token,
get_safe_store_instance,
get_user_discussion_assets_path,
get_user_lollms_client,
get_user_temp_uploads_path, user_sessions,
build_lollms_client_from_params)
from backend.task_manager import task_manager, Task
from backend.ws_manager import manager
from backend.routers.discussion.helpers import get_discussion_and_owner_for_request
from backend.tasks.image_generation_tasks import _generate_slides_task
from concurrent.futures import ThreadPoolExecutor, as_completed
from lollms_client.lollms_types import MSG_TYPE, EventMode
# Google Search Tools
try:
from googleapiclient.discovery import build as google_build
except ImportError:
google_build = None
from scrapemaster import ScrapeMaster
# Create a thread pool for blocking operations
executor = ThreadPoolExecutor(max_workers=50)
import pipmaster as pm
# Helper functions
def build_rag_tool(
safe_store_instance, # The safe store instance
owner_db_user, # User with RAG settings
current_user # Fallback user for default settings
):
"""
Builds a RAG tool for the chat() function using SafeStore 3.5+.
Supports Dense, Tri-Modal Hybrid (Dense + BM25 + RRF), and Knowledge Graph Hybrid retrieval.
"""
def query_rag_callback(query: str, ss, rag_top_k=None, rag_min_similarity_percent=None, mode=None) -> list:
if not ss:
return []
try:
from backend.settings import settings
force_rag = settings.get("force_rag_settings_mode") == "force_always"
effective_top_k = (
int(settings.get("force_rag_top_k", 10)) if force_rag else
(rag_top_k if rag_top_k is not None else
(owner_db_user.rag_top_k if getattr(owner_db_user, 'rag_top_k', None) is not None else
(getattr(current_user, 'rag_top_k', None) if getattr(current_user, 'rag_top_k', None) is not None else 5)))
)
effective_min_sim = (
float(settings.get("force_rag_min_sim_percent", 50.0)) if force_rag else
(rag_min_similarity_percent if rag_min_similarity_percent is not None else
(owner_db_user.rag_min_sim_percent if getattr(owner_db_user, 'rag_min_sim_percent', None) is not None else
(getattr(current_user, 'rag_min_sim_percent', None) if getattr(current_user, 'rag_min_sim_percent', None) is not None else 50.0)))
)
effective_mode = (
settings.get("force_rag_retrieval_mode", "hybrid") if force_rag else
(mode or getattr(owner_db_user, 'rag_retrieval_mode', None) or getattr(current_user, 'rag_retrieval_mode', None) or settings.get("default_rag_retrieval_mode", "hybrid"))
)
dense_weight = float(settings.get("force_rag_dense_weight", 0.5)) if force_rag else float(getattr(owner_db_user, 'rag_dense_weight', 0.5) if getattr(owner_db_user, 'rag_dense_weight', None) is not None else (getattr(current_user, 'rag_dense_weight', 0.5) if getattr(current_user, 'rag_dense_weight', None) is not None else settings.get("default_rag_dense_weight", 0.5)))
bm25_weight = float(settings.get("force_rag_bm25_weight", 0.5)) if force_rag else float(getattr(owner_db_user, 'rag_bm25_weight', 0.5) if getattr(owner_db_user, 'rag_bm25_weight', None) is not None else (getattr(current_user, 'rag_bm25_weight', 0.5) if getattr(current_user, 'rag_bm25_weight', None) is not None else settings.get("default_rag_bm25_weight", 0.5)))
rrf_k = int(settings.get("force_rag_rrf_k", 60)) if force_rag else int(getattr(owner_db_user, 'rag_rrf_k', 60) if getattr(owner_db_user, 'rag_rrf_k', None) is not None else (getattr(current_user, 'rag_rrf_k', 60) if getattr(current_user, 'rag_rrf_k', None) is not None else settings.get("default_rag_rrf_k", 60)))
graph_weight = float(getattr(owner_db_user, 'rag_graph_weight', 0.3) if getattr(owner_db_user, 'rag_graph_weight', None) is not None else 0.3)
use_graph = (
bool(settings.get("force_rag_use_graph", False)) if force_rag else
bool(getattr(owner_db_user, 'rag_use_graph', False) or getattr(current_user, 'rag_use_graph', False))
)
retrieved_chunks = []
with ss:
if (effective_mode == "graph_hybrid" or use_graph) and safe_store and hasattr(safe_store, 'GraphStore'):
try:
gs = safe_store.GraphStore(store=ss)
if hasattr(gs, "query_graph_hybrid"):
hybrid_res = gs.query_graph_hybrid(
query_text=query,
top_k=effective_top_k,
dense_weight=dense_weight,
bm25_weight=bm25_weight,
graph_weight=graph_weight
)
retrieved_chunks = hybrid_res.get("ranked_chunks", []) if isinstance(hybrid_res, dict) else hybrid_res
except Exception as ge:
print(f"Graph hybrid retrieval fallback: {ge}")
if not retrieved_chunks:
if effective_mode in ("hybrid", "graph_hybrid") and hasattr(ss, "hybrid_query"):
try:
retrieved_chunks = ss.hybrid_query(
query_text=query,
top_k=effective_top_k,
dense_weight=dense_weight,
bm25_weight=bm25_weight,
rrf_k=rrf_k
)
except Exception as he:
print(f"Hybrid query fallback to dense: {he}")
retrieved_chunks = ss.query(
query,
top_k=effective_top_k,
min_similarity_percent=effective_min_sim
)
else:
retrieved_chunks = ss.query(
query,
top_k=effective_top_k,
min_similarity_percent=effective_min_sim
)
revamped_chunks = []
for entry in retrieved_chunks:
score_val = entry.get("similarity_percent", entry.get("score", entry.get("fused_score", 0.0)))
try:
score_val = float(score_val)
except (ValueError, TypeError):
score_val = 0.0
revamped_entry = {
"metadata": entry.get('document_metadata', entry.get('metadata', {})),
"title": Path(entry.get("file_path", "unknown")).name if entry.get("file_path") else (entry.get("title") or "Document Chunk"),
"content": entry.get("chunk_text", entry.get("content", "")),
"score": score_val
}
revamped_chunks.append(revamped_entry)
return revamped_chunks
except Exception as e:
trace_exception(e)
return [{"error": f"Error during RAG query: {e}"}]
kb_desc = f" (Description: {safe_store_instance.description})" if safe_store_instance.description else ""
rag_tool = {
"name": safe_store_instance.name,
"description": (
f"Search the knowledge base '{safe_store_instance.name}' for relevant documents and information.{kb_desc} "
"Use this tool when you need to retrieve factual information, "
"documentation, or context from stored documents. "
"Supports dense semantic search, lexical BM25 hybrid ranking, and knowledge graph queries."
),
"parameters": [
{
"name": "query",
"type": "str",
"description": "The search query. Frame this as a clear topic or question.",
"optional": False
},
{
"name": "rag_top_k",
"type": "int",
"description": "Maximum number of document chunks to retrieve (1-20).",
"optional": True,
"default": owner_db_user.rag_top_k if owner_db_user.rag_top_k is not None else 5
},
{
"name": "rag_min_similarity_percent",
"type": "float",
"description": "Minimum similarity threshold (0-100).",
"optional": True,
"default": owner_db_user.rag_min_sim_percent if owner_db_user.rag_min_sim_percent is not None else 50.0
},
{
"name": "mode",
"type": "str",
"description": "Retrieval strategy: 'dense', 'hybrid', or 'graph_hybrid'.",
"optional": True
}
],
"output": [
{
"name": "results",
"type": "list",
"description": "List of retrieved document chunks with metadata, content, and scores"
},
{
"name": "sources",
"type": "list",
"description": "List of source document titles used for attribution"
},
{
"name": "success",
"type": "bool",
"description": "Whether the search completed successfully"
},
{
"name": "count",
"type": "int",
"description": "Number of results retrieved"
}
],
"callable": lambda query, rag_top_k=None, rag_min_similarity_percent=None, mode=None: _wrap_rag_call(
query, rag_top_k, rag_min_similarity_percent, mode,
safe_store_instance, query_rag_callback
)
}
return rag_tool
def _wrap_rag_call(query, rag_top_k, rag_min_similarity_percent, mode, ss, callback):
"""
Wrapper to adapt the callback signature and format outputs consistently.
"""
from pathlib import Path
# Call the original callback with the retrieval mode parameter
raw_results = callback(query, ss, rag_top_k, rag_min_similarity_percent, mode)
# Check for error
if raw_results and len(raw_results) == 1 and "error" in raw_results[0]:
return {
"results": [],
"sources": [],
"success": False,
"count": 0,
"error": raw_results[0]["error"]
}
# Extract sources for attribution
sources = [
{
"source": r["title"],
"content": r["content"],
"score": r["score"],
"metadata": r["metadata"]
}
for r in raw_results
]
return {
"results": raw_results,
"sources": sources,
"success": True,
"count": len(raw_results)
}
def _sanitize_b64(data: str) -> str:
"""Removes data URI scheme if present to return raw base64."""
if "base64," in data:
return data.split("base64,")[1]
return data
def resize_base64_image(b64_str: str, max_width: int = -1, max_height: int = -1) -> str:
"""
Resizes and compresses a base64 encoded image.
1. Resizes if dimensions exceed max_width/max_height.
2. Converts to JPEG (quality 85) to reduce payload size, unless transparency is present.
Returns the raw base64 string (no header).
"""
try:
# Strip header if present
data = b64_str
if "base64," in b64_str:
_, data = b64_str.split("base64,", 1)
img_data = base64.b64decode(data)
img = Image.open(io.BytesIO(img_data))
original_width, original_height = img.size
new_width, new_height = original_width, original_height
should_resize = False
# Calculate new dimensions
if max_width > 0 and new_width > max_width:
ratio = max_width / new_width
new_width = max_width
new_height = int(new_height * ratio)
should_resize = True
if max_height > 0 and new_height > max_height:
ratio = max_height / new_height
new_height = max_height
new_width = int(new_width * ratio)
should_resize = True
# Determine format and mode
# If image has transparency (RGBA, LA) or is P with transparency, keep as PNG or convert to RGB for JPEG
has_transparency = img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info)
if should_resize:
img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
buffered = io.BytesIO()
# Always prefer JPEG for non-transparent images to save space (Ollama body size limit)
if has_transparency:
img.save(buffered, format="PNG")
else:
if img.mode != "RGB":
img = img.convert("RGB")
img.save(buffered, format="JPEG", quality=85)
return base64.b64encode(buffered.getvalue()).decode('utf-8')
except Exception as e:
print(f"Error resizing/compressing image: {e}")
# Return original (sanitized) on error
return _sanitize_b64(b64_str)
def build_image_dicts(images_b64):
"""Helper to convert list of b64 strings/urls into structured dicts for export."""
if not images_b64: return []
res = []
for img in images_b64:
if isinstance(img, str):
if img.startswith("http"):
res.append({'type': 'url', 'data': img})
else:
res.append({'type': 'base64', 'data': _sanitize_b64(img)})
elif isinstance(img, dict) and 'data' in img:
# Handle already structured dicts if present
data = img['data']
if data.startswith("http"):
res.append({'type': 'url', 'data': data})
else:
res.append({'type': 'base64', 'data': _sanitize_b64(data)})
return res
def process_skill_tags(text: str, user_id: int, db: Session) -> Tuple[str, bool, List[str]]:
"""
Passive version: Does not save to DB.
The UI now handles rendering and saving via <skill> tags.
"""
return text, False, []
# Redundant manual episodic memory parser purged.
# LollmsDiscussion.chat() natively manages episodic logging, deep memory retrieval,
# and cognitive graph traversals via LollmsMemoryManager.
def process_image_generation_tags(text: str, user: DBUser, db: Session, discussion_obj: LollmsDiscussion, main_loop=None, stream_queue=None) -> Tuple[str, List[str], List[Dict], List[Dict]]:
"""
Parses <generate_image> tags, generates images via TTI binding.
Returns: (cleaned_text, list_of_base64_images, list_of_image_metadata, list_of_groups)
"""
# Pattern: <generate_image width="512" height="512" n="1">prompt</generate_image>
pattern = re.compile(r'<generate_image\b([^>]*)>(.*?)</generate_image>', re.DOTALL | re.IGNORECASE)
matches = list(pattern.finditer(text))
if not matches:
return text, [], [], []
error_messages = []
try:
lc = build_lollms_client_from_params(
username=user.username,
load_llm=False,
load_tti=True
)
if not lc.tti:
# Explicit warning if TTI not available, but preserve original tag for user info
return text, [], [], []
except Exception as e:
print(f"TTI Client Init Error: {e}")
return text, [], [], []
images_b64 = []
generation_infos = []
generated_groups = []
current_image_count = 0
# Process matches
for match in matches:
attr_str = match.group(1)
prompt = match.group(2).strip()
width = 1024
height = 1024
n_variants = 1
for attr in re.findall(r'(\w+)="(\d+)"', attr_str):
key, val = attr
if key == 'width': width = int(val)
elif key == 'height': height = int(val)
elif key == 'n': n_variants = int(val)
n_variants = max(1, min(n_variants, 10))
if main_loop and stream_queue:
payload = {"type": "step_start", "content": f"Generating image: {prompt[:30]}..."}
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps(jsonable_encoder(payload)) + "\n")
# Track indices for this group
group_indices = []
for _ in range(n_variants):
try:
image_bytes = lc.tti.generate_image(prompt=prompt, width=width, height=height)
if image_bytes:
b64 = base64.b64encode(image_bytes).decode('utf-8')
images_b64.append(b64)
generation_infos.append({
"index": current_image_count,
"prompt": prompt,
"model": lc.tti.config.get("model_name", "unknown"),
"width": width,
"height": height
})
group_indices.append(current_image_count)
current_image_count += 1
else:
error_messages.append(f"Generator returned no data for prompt: {prompt[:20]}...")
except Exception as e:
error_messages.append(f"Generation failed: {str(e)}")
print(f"Image generation failed for prompt '{prompt}': {e}")
if group_indices:
generated_groups.append({
"id": str(uuid.uuid4()),
"prompt": prompt,
"indices": group_indices,
"type": "generated",
"selected_index": 0 # New: Default selected variant
})
if main_loop and stream_queue:
payload = {"type": "step_end", "content": "Image generation step complete.", "id": None}
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps(jsonable_encoder(payload)) + "\n")
# Important: Return original text to preserve tags in chat history
return text, images_b64, generation_infos, generated_groups
def process_slide_generation_tags(text: str, user: DBUser, db: Session, discussion_obj: LollmsDiscussion, message_id: str, main_loop=None, stream_queue=None) -> Tuple[str, Optional[str]]:
"""
Parses <generate_slides> tags, extracting inner <Slide> contents or raw prompt, and triggers the slide generation task.
Returns: (cleaned_text, task_id) where task_id is the ID of the background task if one was triggered, else None.
"""
# Regex to capture the whole block including attributes
# Pattern: <generate_slides attr="val"> ... <Slide>desc</Slide> ... </generate_slides>
block_pattern = re.compile(r'<generate_slides\b([^>]*)>(.*?)</generate_slides>', re.DOTALL | re.IGNORECASE)
slide_pattern = re.compile(r'<Slide>(.*?)</Slide>', re.DOTALL | re.IGNORECASE)
matches = list(block_pattern.finditer(text))
if not matches:
return text, None
triggered_task_id = None
for match in matches:
attr_str = match.group(1)
content_str = match.group(2)
width = 1024
height = 768
# Parse attributes from the parent tag
width_match = re.search(r'width="(\d+)"', attr_str)
if width_match: width = int(width_match.group(1))
height_match = re.search(r'height="(\d+)"', attr_str)
if height_match: height = int(height_match.group(1))
# Extract individual slide prompts if present
slides = [m.group(1).strip() for m in slide_pattern.finditer(content_str) if m.group(1).strip()]
# If no explicit slides found, use the inner text as the "topic" prompt
final_slides_arg = slides if slides else content_str.strip()
if final_slides_arg:
try:
task_description = f"Creating {len(slides)} slides..." if slides else f"Planning slides for topic: {final_slides_arg[:30]}..."
new_task = task_manager.submit_task(
name=f"Generating Slides",
target=_generate_slides_task,
args=(user.username, discussion_obj.id, message_id, final_slides_arg, width, height),
description=task_description,
owner_username=user.username
)
triggered_task_id = new_task.id
if main_loop and stream_queue:
payload = {"type": "info", "content": "Started slide generation task."}
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps(jsonable_encoder(payload)) + "\n")
except Exception as e:
print(f"Failed to start slide generation task: {e}")
# Return original text to preserve tags
return text, triggered_task_id
def process_street_view_tags(text: str, user: DBUser, db: Session, discussion_obj: LollmsDiscussion, main_loop=None, stream_queue=None) -> Tuple[str, List[str], List[Dict], List[Dict]]:
"""
Parses <street_view> tags and fetches images from Google Street View Static API.
"""
pattern = re.compile(r'<street_view>(.*?)</street_view>', re.DOTALL | re.IGNORECASE)
matches = list(pattern.finditer(text))
if not matches or not user.google_api_key:
return text, [], [], []
images_b64 = []
generation_infos = []
generated_groups = []
current_image_count = 0
for match in matches:
location = match.group(1).strip()
if location:
if main_loop and stream_queue:
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps(jsonable_encoder({"type": "step_start", "content": f"Fetching Street View: {location}"})) + "\n")
try:
url = f"https://maps.googleapis.com/maps/api/streetview?size=600x400&location={location}&key={user.google_api_key}"
resp = requests.get(url)
if resp.status_code == 200:
b64 = base64.b64encode(resp.content).decode('utf-8')
images_b64.append(b64)
generation_infos.append({"index": current_image_count, "prompt": f"Street View: {location}", "model": "google_street_view", "type": "street_view"})
generated_groups.append({"id": str(uuid.uuid4()), "title": f"Street View: {location}", "type": "street_view", "indices": [current_image_count], "images": [b64]})
current_image_count += 1
except Exception as e:
print(f"Street View Error: {e}")
return text, images_b64, generation_infos, generated_groups
def process_scheduler_tags(text: str, user: DBUser, db: Session) -> Tuple[str, List[str]]:
"""
Parses <schedule_task name="..." cron="...">prompt</schedule_task> tags.
"""
pattern = re.compile(r'<schedule_task\b([^>]*)>(.*?)</schedule_task>', re.DOTALL | re.IGNORECASE)
matches = list(pattern.finditer(text))
messages = []
if not matches: return text, []
for match in matches:
attr_str = match.group(1)
prompt = match.group(2).strip()
name = "Untitled Task"
cron = "0 8 * * *" # Default daily 8am
for attr in re.findall(r'(\w+)="([^"]*)"', attr_str):
if attr[0] == 'name': name = attr[1]
if attr[0] == 'cron': cron = attr[1]
try:
new_task = ScheduledTask(owner_user_id=user.id, name=name, cron_expression=cron, prompt=prompt, is_active=True)
db.add(new_task)
db.commit()
messages.append(f"Scheduled task '{name}' created with cron '{cron}'.")
except Exception as e:
messages.append(f"Failed to schedule task '{name}': {e}")
return text, messages
def process_google_workspace_tags(text: str, user: DBUser, main_loop=None, stream_queue=None) -> Tuple[str, List[str]]:
"""
Parses Google Workspace tags. Currently a placeholder for full OAuth implementation.
"""
# Drive
drive_list = re.findall(r'<google_drive_list>(.*?)</google_drive_list>', text, re.DOTALL | re.IGNORECASE)
# Calendar
calendar_add = re.findall(r'<calendar_add\b([^>]*)>(.*?)</calendar_add>', text, re.DOTALL | re.IGNORECASE)
# Gmail
gmail_send = re.findall(r'<gmail_send\b([^>]*)>(.*?)</gmail_send>', text, re.DOTALL | re.IGNORECASE)
messages = []
if drive_list:
messages.append("Google Drive: Listing files (Mock execution - OAuth pending).")
if calendar_add:
messages.append("Google Calendar: Event creation received (Mock execution - OAuth pending).")
if gmail_send:
messages.append("Gmail: Email sending request received (Mock execution - OAuth pending).")
return text, messages
def process_image_editing_tags(text: str, user: DBUser, db: Session, discussion_obj: LollmsDiscussion, main_loop=None, stream_queue=None, current_turn_images: List[str] = None) -> Tuple[str, List[str], List[Dict], List[Dict]]:
"""
Parses <edit_image> tags to edit previously generated images.
Returns: (cleaned_text, list_of_base64_images, list_of_image_metadata, list_of_groups)
"""
# Pattern: <edit_image source_index="-1" strength="0.75" width="1024" height="1024">prompt</edit_image>
pattern = re.compile(r'<edit_image\b([^>]*)>(.*?)</edit_image>', re.DOTALL | re.IGNORECASE)
matches = list(pattern.finditer(text))
if not matches:
return text, [], [], []
error_messages = []
try:
lc = build_lollms_client_from_params(
username=user.username,
load_llm=False,
load_tti=True
)
if not lc.tti:
# Preserve tags
return text, [], [], []
except Exception as e:
print(f"TTI Client Init Error: {e}")
return text, [], [], []
images_b64 = []
generation_infos = []
generated_groups = []
current_image_count = 0
# [FIX] Robustly gather all images in chronological order
all_available_images = []
# 1. Load historical messages if needed to ensure we have the images
if discussion_obj.messages is None:
if hasattr(discussion_obj, 'load_messages'):
discussion_obj.load_messages()
else:
discussion_obj.messages = []
# 2. Iterate chronologically through all messages
for msg in discussion_obj.messages:
# Check for images in 'images' list or 'image_references'
# lollms_client usually stores as list of b64 strings in `images`
msg_images = msg.get_active_images() # Returns list of b64 strings
for img in msg_images:
all_available_images.append(_sanitize_b64(img))
# 3. Append current turn images (if any were uploaded this turn and passed in)
if current_turn_images:
for img in current_turn_images:
all_available_images.append(_sanitize_b64(img))
for match in matches:
attr_str = match.group(1)
prompt = match.group(2).strip()
source_index = -1
strength = 0.75
width = None
height = None
for attr in re.findall(r'(\w+)="([^"]*)"', attr_str):
key, val = attr
if key == 'source_index': source_index = int(val)
elif key == 'strength': strength = float(val)
elif key == 'width': width = int(val)
elif key == 'height': height = int(val)
# Resolve source image using collected chronological list
source_image_b64 = None
try:
# Indices are 0-based for absolute, or negative for relative to end
if source_index < 0:
# e.g. -1 is last image, -2 is second to last
final_idx = len(all_available_images) + source_index
if 0 <= final_idx < len(all_available_images):
source_image_b64 = all_available_images[final_idx]
else:
if source_index < len(all_available_images):
source_image_b64 = all_available_images[source_index]
except Exception as e:
print(f"Error resolving index {source_index}: {e}")
if not source_image_b64:
error_messages.append(f"Could not find source image at index {source_index} for editing. (Total images: {len(all_available_images)})")
continue
# [FIX] Infer dimensions from source image if missing, to prevent 'NoneType' division errors
if width is None or height is None:
try:
img_data = base64.b64decode(source_image_b64)
with Image.open(io.BytesIO(img_data)) as img:
if width is None: width = img.width
if height is None: height = img.height
except Exception as e:
print(f"Error extracting dimensions from source image: {e}")
# Fallback to defaults if image is corrupted or undecodable
if width is None: width = 1024
if height is None: height = 1024
if main_loop and stream_queue:
payload = {"type": "step_start", "content": f"Editing image: {prompt[:30]}..."}
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps(jsonable_encoder(payload)) + "\n")
try:
# Check for correct edit method signature
if hasattr(lc.tti, 'edit_image'):
# Correct signature: images, prompt, ...
image_bytes = lc.tti.edit_image(
images=source_image_b64,
prompt=prompt,
width=width,
height=height,
strength=strength
)
else:
# Fallback: img2img via generate_image (uses 'image' kwarg)
# This depends on specific binding implementation details
image_bytes = lc.tti.generate_image(
image=source_image_b64,
prompt=prompt,
width=width,
height=height,
strength=strength
)
if image_bytes:
b64 = base64.b64encode(image_bytes).decode('utf-8')
images_b64.append(b64)
generation_infos.append({
"index": current_image_count,
"prompt": prompt,
"model": lc.tti.config.get("model_name", "unknown"),
"type": "edit",
"source_index": source_index
})
generated_groups.append({
"id": str(uuid.uuid4()),
"prompt": prompt,
"indices": [current_image_count],
"type": "edited",
"selected_index": 0 # New
})
current_image_count += 1
else:
error_messages.append("TTI edit returned no data.")
except Exception as e:
error_messages.append(f"Image editing failed: {str(e)}")
trace_exception(e)
if main_loop and stream_queue:
payload = {"type": "step_end", "content": "Image editing complete.", "id": None}
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps(jsonable_encoder(payload)) + "\n")
# Important: Return original text to preserve tags
return text, images_b64, generation_infos, generated_groups
def perform_google_search(query: str, api_key: str, cse_id: str) -> List[Dict[str, str]]:
if not google_build: return []
try:
service = google_build("customsearch", "v1", developerKey=api_key)
res = service.cse().list(q=query, cx=cse_id, num=5).execute()
items = res.get('items', [])
return [{'title': item.get('title'), 'link': item.get('link'), 'snippet': item.get('snippet')} for item in items]
except Exception: return []
def perform_wikipedia_search(query: str) -> List[Dict[str, str]]:
pm.ensure_packages(["wikipedia-api", "wikipedia"])
import wikipediaapi
import wikipedia
wiki = wikipediaapi.Wikipedia('LollmsWebAgent/1.0', 'en')
page = wiki.page(query)
if page.exists():
return [{'title': page.title, 'link': page.fullurl, 'snippet': page.summary[:1000]}]
search_results = wikipedia.search(query)
res = []
for title in search_results[:3]:
p = wiki.page(title)
if p.exists():
res.append({'title': p.title, 'link': p.fullurl, 'snippet': p.summary[:500]})
return res
def perform_search_single(query: str, provider: str, user: DBUser) -> List[Dict[str, str]]:
"""Handler for a single search engine turn."""
if provider == "wikipedia": return perform_wikipedia_search(query)
site_map = {
"reddit": "site:reddit.com",
"stackoverflow": "site:stackoverflow.com",
"x": "site:x.com",
"github": "site:github.com"
}
actual_query = query
base_provider = provider
if provider in site_map:
actual_query = f"{site_map[provider]} {query}"
base_provider = "google" if (user.google_api_key and user.google_cse_id) else "duckduckgo"
if base_provider == "google" and user.google_api_key and user.google_cse_id:
return perform_google_search(actual_query, user.google_api_key, user.google_cse_id)
if base_provider == "duckduckgo" or base_provider in site_map:
pm.ensure_packages("duckduckgo_search")
try:
from duckduckgo_search import DDGS
with DDGS() as ddgs:
results = [r for r in ddgs.text(actual_query, max_results=5)]
return [{'title': r.get('title'), 'link': r.get('href'), 'snippet': r.get('body')} for r in results]
except Exception: pass
return []
def perform_multi_search(query: str, providers: List[str], user: DBUser) -> List[Dict[str, Any]]:
"""Runs multiple engine searches in parallel and deduplicates."""
all_results = []
with ThreadPoolExecutor(max_workers=len(providers)) as pool:
future_to_provider = {pool.submit(perform_search_single, query, p, user): p for p in providers}
for future in as_completed(future_to_provider):
try:
results = future.result()
for r in results: r['engine'] = future_to_provider[future]
all_results.extend(results)
except Exception: pass
seen_links = set()
unique_results = []
for r in all_results:
if r['link'] not in seen_links:
seen_links.add(r['link'])
unique_results.append(r)
for i, res in enumerate(unique_results): res['index'] = i + 1
return unique_results
def process_herd_logic(
user: DBUser,
discussion_obj: LollmsDiscussion,
prompt: str,
main_loop,
stream_queue,
db_session: Session,
all_events: List[Dict] = None
):
"""
Executes the 4-phase Herd Mode workflow:
1. Pre-code Brainstorming (Ideas)
2. Answer Crafting (Leader Draft)
3. Post-code Brainstorming (Critique)
4. Final Answer (Leader Final)
"""
precode_crew = []
postcode_crew = []
# --- DYNAMIC CREW GENERATION ---
if user.herd_dynamic_mode and user.herd_model_pool:
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps(jsonable_encoder({"type": "step_start", "content": "Herd Manager: analyzing task and assembling dynamic teams..."})) + "\n")
try:
# 1. Prepare inputs
model_pool_desc = json.dumps(user.herd_model_pool, indent=2)
leader_client = get_user_lollms_client(user.username)
# 2. Construct Manager Prompt
manager_prompt = f"""You are the Herd Manager.
Your goal is to assemble two teams of AI agents to solve a specific user request.
You must CREATE distinct personas (Name + Specific System Prompt) for each agent and assign them to the most appropriate 'model' from the Available Models list.
[USER REQUEST]
"{prompt}"
[AVAILABLE MODELS POOL]
{model_pool_desc}
[INSTRUCTIONS]
1. **Pre-code Crew**: Create 2-3 agents to brainstorm ideas, architecture, and high-level solutions.
- Define a unique `system_prompt` for each that gives them a specific perspective (e.g., "You are a database expert", "You are a creative thinker").
2. **Post-code Crew**: Create 2-3 agents to critique, review, and find flaws.
- Define a unique `system_prompt` for each (e.g., "You are a security auditor", "You are a performance optimizer").
3. **Model Assignment**: For the `model` field, you MUST use one of the strings from the "model" key in the pool above.
[OUTPUT FORMAT]
Return ONLY a valid JSON object. No markdown formatting.
{{
"pre_code_crew": [
{{ "name": "Agent Name", "system_prompt": "You are...", "model": "model_id_from_pool" }}
],
"post_code_crew": [
{{ "name": "Agent Name", "system_prompt": "You are...", "model": "model_id_from_pool" }}
]
}}
"""
# 3. Generate Configuration
json_config_str = leader_client.generate_code(manager_prompt, language="json").strip()
# Cleanup potential markdown code blocks if the model ignores instruction
if json_config_str.startswith("```"):
json_config_str = json_config_str.split('\n', 1)[1]
if json_config_str.endswith("```"):
json_config_str = json_config_str.rsplit('\n', 1)[0]
if json_config_str:
try:
config = json.loads(json_config_str)
precode_crew = config.get("pre_code_crew", [])
postcode_crew = config.get("post_code_crew", [])
# Mark as dynamic for the runner
for agent in precode_crew: agent['is_dynamic'] = True
for agent in postcode_crew: agent['is_dynamic'] = True
msg = f"**Dynamic Teams Assembled:**\n\n*Pre-code Phase:*\n" + "\n".join([f"- {a['name']} ({a['model']})" for a in precode_crew])
msg += "\n\n*Post-code Phase:*\n" + "\n".join([f"- {a['name']} ({a['model']})" for a in postcode_crew])
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps(jsonable_encoder({"type": "step_end", "content": msg})) + "\n")
except json.JSONDecodeError as je:
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps(jsonable_encoder({"type": "step_end", "content": f"Failed to parse crew configuration: {je}. Using static fallback."})) + "\n")
else:
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps(jsonable_encoder({"type": "step_end", "content": "Model returned empty configuration. Using static fallback."})) + "\n")
except Exception as e:
trace_exception(e)
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps(jsonable_encoder({"type": "step_end", "content": f"Dynamic generation error: {e}. Falling back."})) + "\n")
# --- FALLBACK TO STATIC IF DYNAMIC FAILED OR DISABLED ---
if not precode_crew and not postcode_crew:
precode_crew = user.herd_precode_participants or []
postcode_crew = user.herd_postcode_participants or []
# Legacy fallback
if not precode_crew and not postcode_crew:
legacy_crew = user.herd_participants or []
precode_crew = legacy_crew
postcode_crew = legacy_crew
if not precode_crew and not postcode_crew:
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps(jsonable_encoder({"type": "info", "content": "Herd mode active but no participants found. Proceeding with standard generation."})) + "\n")
return ""
rounds = user.herd_rounds if user.herd_rounds is not None else 2
# [FIX] Load previous discussion history to provide context to agents
history_text = ""
# Ensure messages are loaded
if discussion_obj.messages is None:
if hasattr(discussion_obj, 'load_messages'):
discussion_obj.load_messages()
else:
discussion_obj.messages = []
# Simple approach: Take last 10 messages for context
recent_messages = discussion_obj.messages[-10:]
for msg in recent_messages:
# Skip the currently generating AI message (if it exists as a placeholder)
if msg.sender_type == 'assistant' and not msg.content:
continue
sender = msg.sender
text = msg.content
history_text += f"{sender}: {text}\n"
full_context_history = f"Discussion History:\n{history_text}\n\n[Current Task]: {prompt}\n\n"
# Helper to run an agent
def run_agent(agent_def, context, phase_name, round_num):
model_full = agent_def.get('model')
# Dynamic agents have explicit system prompts
is_dynamic = agent_def.get('is_dynamic', False)
persona_name = agent_def.get('name') if is_dynamic else agent_def.get('personality')
display_name = persona_name or model_full or "Agent"
# Resolve Binding/Model
binding_alias = None
model_name = None
if model_full and '/' in model_full:
binding_alias, model_name = model_full.split('/', 1)
elif not model_full:
# Fallback default
default_binding = db_session.query(DBLLMBinding).filter(DBLLMBinding.is_active == True).first()
if default_binding:
binding_alias = default_binding.alias
model_name = default_binding.default_model_name
# Resolve System Prompt
sys_prompt = ""
if is_dynamic:
sys_prompt = agent_def.get('system_prompt', "You are a helpful assistant.")
else:
# Static Logic: Load from DB
sys_prompt = f"You are participating in a {phase_name} session."
if persona_name:
pers = db_session.query(DBPersonality).filter(
(DBPersonality.name == persona_name) | (DBPersonality.id == persona_name)
).first()
if pers:
sys_prompt = pers.prompt_text
if phase_name == "Pre-code Brainstorming":
sys_prompt += "\n\nTask: Brainstorm ideas, architecture, and high-level solutions for the user's request. Do not write full code yet. Critique previous ideas if any."
elif phase_name == "Post-code Critique":
sys_prompt += "\n\nTask: Review the proposed solution/code. Look for bugs, security issues, logic errors, or missing requirements. Be critical but constructive."
# Emit step start using the standard ID-based schema required by the UI for tracking progress
step_id = str(uuid.uuid4())
step_start_payload = {
"type": "step_start",
"content": f"**{display_name}** ({phase_name} Round {round_num})",
"id": step_id
}
if all_events is not None:
all_events.append(step_start_payload)
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps(jsonable_encoder(step_start_payload)) + "\n")
try:
temp_client = build_lollms_client_from_params(
username=user.username,
binding_alias=binding_alias,
model_name=model_name,
load_llm=True,
load_tti=False,
load_tts=False,
load_stt=False,
load_mcp=False
)
response = temp_client.generate_text(
context,
system_prompt=sys_prompt,
max_new_tokens=1024,
temperature=0.7
)
# Emit step end with result content, matching the ID to close the UI step correctly
step_end_payload = {"type": "step_end", "content": f"Response from {display_name} received.", "id": step_id}
if all_events is not None:
all_events.append(step_end_payload)
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps(jsonable_encoder(step_end_payload)) + "\n")
return f"\n\n[{phase_name} - {display_name}]:\n{response}"
except Exception as e:
err = f"Agent {display_name} failed: {e}"
print(err)
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps(jsonable_encoder({"type": "step_end", "content": err, "status": "error"})) + "\n")
return f"\n\n[{phase_name} - {display_name}]: [FAILED]"
# --- PHASE 1: Pre-code Brainstorming ---
if precode_crew:
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps(jsonable_encoder({"type": "info", "content": "Phase 1: Pre-code Brainstorming"})) + "\n")
for r in range(rounds):
all_ready = True
for agent in precode_crew:
out = run_agent(agent, full_context_history, "Pre-code Brainstorming", r+1)
full_context_history += out
if "<ready/>" not in out.lower():
all_ready = False
if all_ready and r > 0:
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps(jsonable_encoder({"type": "info", "content": "All agents ready. Proceeding."})) + "\n")
break
# --- PHASE 2: Answer Crafting (Leader Draft) ---
draft_start = {"type": "step_start", "content": "Phase 2: Leader drafting solution..."}
if all_events is not None: all_events.append(draft_start)
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps(jsonable_encoder(draft_start)) + "\n")
leader_client = get_user_lollms_client(user.username)
leader_prompt = f"{full_context_history}\n\n[INSTRUCTION]: Act as the Team Leader. Based on the brainstorming above, create a complete draft solution/implementation."
try:
draft_response = leader_client.generate_text(leader_prompt, max_new_tokens=2048)
full_context_history += f"\n\n[Leader Draft]:\n{draft_response}"
draft_end = {"type": "step_end", "content": draft_response}
if all_events is not None: all_events.append(draft_end)
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps(jsonable_encoder(draft_end)) + "\n")
except Exception as e:
full_context_history += f"\n\n[Leader Draft]: [FAILED] {e}"
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps(jsonable_encoder({"type": "step_end", "content": f"Draft generation failed: {e}", "status": "error"})) + "\n")
# --- PHASE 3: Post-code Brainstorming ---
if postcode_crew:
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps(jsonable_encoder({"type": "info", "content": "Phase 3: Post-code Critique"})) + "\n")
for r in range(rounds):
all_ready = True
for agent in postcode_crew:
out = run_agent(agent, full_context_history, "Post-code Critique", r+1)
full_context_history += out
if "<ready/>" not in out.lower():
all_ready = False
if all_ready and r > 0:
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps(jsonable_encoder({"type": "info", "content": "All agents satisfied."})) + "\n")
break
# --- PHASE 4: Final Answer (Handled by caller) ---
return full_context_history
def build_llm_generation_router(router: APIRouter):
@router.post("/{discussion_id}/chat")
async def chat_in_existing_discussion(
discussion_id: str,
fastapi_request: Request,
prompt: str = Form(""),
image_server_paths_json: str = Form("[]"),
parent_message_id: Optional[str] = Form(None),
is_resend: bool = Form(False),
enable_books: Optional[bool] = Form(None),
current_user: UserAuthDetails = Depends(get_current_active_user),
db: Session = Depends(get_db)
) -> StreamingResponse:
"""
Main chat endpoint. Handles text generation, RAG, Web Search, Herd Mode,
and internal tool execution (Image Gen/Edit, Memory).
"""
# 1. Retrieve discussion and owner details
discussion_obj, owner_username, permission, owner_db_user = await get_discussion_and_owner_for_request(
discussion_id, current_user, db, 'interact'
)
# 2. Setup LLM Client
user_model_full = current_user.lollms_model_name
binding_alias = None
if user_model_full and '/' in user_model_full:
binding_alias, _ = user_model_full.split('/', 1)
lc = get_user_lollms_client(owner_username, binding_alias)
if lc:
lc.cancel_generation = False
discussion_obj.lollms_client = lc
# Ensure max_context_size is updated with the active model profile
try:
ctx = lc.get_ctx_size()
if ctx and int(ctx) > 1:
discussion_obj.max_context_size = int(ctx)
else:
cfg_ctx = getattr(lc, 'llm_binding_config', {}).get('ctx_size')
if cfg_ctx and int(cfg_ctx) > 1:
discussion_obj.max_context_size = int(cfg_ctx)
except Exception:
pass
if not lc:
async def error_stream():
yield json.dumps({"type": "error", "content": "Failed to get a valid LLM Client. Check your binding settings."}) + "\n"
return StreamingResponse(error_stream(), media_type="application/x-ndjson")
# 3. Setup Multi-Source RAG Knowledge Bases Architecture
from backend.db.models.datastore import DataStore as DBDataStore
from backend.settings import settings
agentic_tools = {}
rag_datastore_ids = (discussion_obj.metadata or {}).get('rag_datastore_ids', [])
# Get personality from DB if active
db_pers = db.query(DBPersonality).filter(DBPersonality.id == owner_db_user.active_personality_id).first() if owner_db_user.active_personality_id else None
force_rag = settings.get("force_rag_settings_mode") == "force_always"
effective_top_k = (
int(settings.get("force_rag_top_k", 10)) if force_rag else
(owner_db_user.rag_top_k if getattr(owner_db_user, 'rag_top_k', None) is not None else
(getattr(current_user, 'rag_top_k', None) if getattr(current_user, 'rag_top_k', None) is not None else 5))
)
effective_min_sim = (
float(settings.get("force_rag_min_sim_percent", 50.0)) if force_rag else
(owner_db_user.rag_min_sim_percent if getattr(owner_db_user, 'rag_min_sim_percent', None) is not None else
(getattr(current_user, 'rag_min_sim_percent', None) if getattr(current_user, 'rag_min_sim_percent', None) is not None else 50.0))
)
effective_mode = (
settings.get("force_rag_retrieval_mode", "hybrid") if force_rag else
(getattr(owner_db_user, 'rag_retrieval_mode', None) or getattr(current_user, 'rag_retrieval_mode', None) or settings.get("default_rag_retrieval_mode", "hybrid"))
)
dense_weight = float(settings.get("force_rag_dense_weight", 0.5)) if force_rag else float(getattr(owner_db_user, 'rag_dense_weight', 0.5) if getattr(owner_db_user, 'rag_dense_weight', None) is not None else 0.5)
bm25_weight = float(settings.get("force_rag_bm25_weight", 0.5)) if force_rag else float(getattr(owner_db_user, 'rag_bm25_weight', 0.5) if getattr(owner_db_user, 'rag_bm25_weight', None) is not None else 0.5)
rrf_k = int(settings.get("force_rag_rrf_k", 60)) if force_rag else int(getattr(owner_db_user, 'rag_rrf_k', 60) if getattr(owner_db_user, 'rag_rrf_k', None) is not None else 60)
graph_weight = float(getattr(owner_db_user, 'rag_graph_weight', 0.3) if getattr(owner_db_user, 'rag_graph_weight', None) is not None else 0.3)
use_graph = (
bool(settings.get("force_rag_use_graph", False)) if force_rag else
bool(getattr(owner_db_user, 'rag_use_graph', False) or getattr(current_user, 'rag_use_graph', False))
)
def make_store_query_fn(ss_instance, store_name: str, ds_description: str):
"""Builds a query function for an individual named knowledge base."""
def query_kb(query_str: str, **kwargs) -> list:
if not query_str or not query_str.strip():
return []
try:
retrieved_chunks = []
with ss_instance:
if (effective_mode == "graph_hybrid" or use_graph) and safe_store and hasattr(safe_store, 'GraphStore'):
try:
gs = safe_store.GraphStore(store=ss_instance)
if hasattr(gs, "query_graph_hybrid"):
hybrid_res = gs.query_graph_hybrid(
query_text=query_str,
top_k=effective_top_k,
dense_weight=dense_weight,
bm25_weight=bm25_weight,
graph_weight=graph_weight
)
retrieved_chunks = hybrid_res.get("ranked_chunks", []) if isinstance(hybrid_res, dict) else hybrid_res
except Exception as ge:
print(f"Graph hybrid retrieval fallback for {store_name}: {ge}")
if not retrieved_chunks:
if effective_mode in ("hybrid", "graph_hybrid") and hasattr(ss_instance, "hybrid_query"):
try:
retrieved_chunks = ss_instance.hybrid_query(
query_text=query_str,
top_k=effective_top_k,
dense_weight=dense_weight,
bm25_weight=bm25_weight,
rrf_k=rrf_k
)
except Exception as he:
print(f"Hybrid query fallback for {store_name}: {he}")
retrieved_chunks = ss_instance.query(
query_str,
top_k=effective_top_k,
min_similarity_percent=effective_min_sim
)
else:
retrieved_chunks = ss_instance.query(
query_str,
top_k=effective_top_k,
min_similarity_percent=effective_min_sim
)
sources = []
for entry in retrieved_chunks:
chunk_text = entry.get("chunk_text", entry.get("content", ""))
if not chunk_text: continue
score_val = entry.get("similarity_percent", entry.get("score", entry.get("fused_score", 0.0)))
try: score_val = float(score_val)
except (ValueError, TypeError): score_val = 0.0
file_path = entry.get("file_path", "unknown")
doc_title = Path(file_path).name if file_path else "Document Chunk"
# Strictly enforce relevance threshold
sim_val = entry.get("similarity_percent", score_val if score_val > 1.0 else score_val * 100.0)
if sim_val < effective_min_sim:
continue
sources.append({
"title": f"{store_name} / {doc_title}",
"content": chunk_text,
"score": score_val,
"source": f"{store_name} / {doc_title}",
"metadata": entry.get('document_metadata', entry.get('metadata', {}))
})
return sources
except Exception as e:
trace_exception(e)
return []
return query_kb
# Build Multi-Source RAG Knowledge Bases Registry
multi_rag_data_sources = []
# 1. Register all discussion-level DataStores with their names and descriptions
for ds_id in rag_datastore_ids:
try:
ds_record = db.query(DBDataStore).filter(DBDataStore.id == ds_id).first()
ss = get_safe_store_instance(owner_username, ds_id, db)
if not ss or not ds_record:
continue
kb_name = ds_record.name or f"datastore_{ds_id[:8]}"
kb_desc = ds_record.description or f"Indexed knowledge store: {kb_name}"
kb_query_fn = make_store_query_fn(ss, kb_name, kb_desc)
if RAGDataSource:
kb_source = RAGDataSource(
name=kb_name,
description=kb_desc,
query_fn=kb_query_fn,
store=ss,
auto_query=True
)
else:
kb_source = {
"name": kb_name,
"description": kb_desc,
"query_fn": kb_query_fn,
"store": ss,
"auto_query": True
}
multi_rag_data_sources.append(kb_source)
except Exception as e:
print(f"Failed to register multi-source RAG datastore {ds_id}: {e}")
# 2. Register Personality-level DataStore or static manual if present
if db_pers:
if db_pers.data_source_type == 'datastore' and db_pers.data_source:
try:
pers_ds_record = db.query(DBDataStore).filter(DBDataStore.id == db_pers.data_source).first()
pers_ss = get_safe_store_instance(owner_username, db_pers.data_source, db, permission_level="read_query")
if pers_ss:
pers_kb_name = pers_ds_record.name if pers_ds_record else f"{db_pers.name}_knowledge"
pers_kb_desc = pers_ds_record.description if pers_ds_record and pers_ds_record.description else f"Specialized domain knowledge base for personality: {db_pers.name}"
pers_kb_query_fn = make_store_query_fn(pers_ss, pers_kb_name, pers_kb_desc)
if RAGDataSource:
pers_kb_source = RAGDataSource(
name=pers_kb_name,
description=pers_kb_desc,
query_fn=pers_kb_query_fn,
store=pers_ss,
auto_query=True
)
else:
pers_kb_source = {
"name": pers_kb_name,
"description": pers_kb_desc,
"query_fn": pers_kb_query_fn,
"store": pers_ss,
"auto_query": True
}
multi_rag_data_sources.append(pers_kb_source)
except Exception as e:
print(f"Failed to mount personality datastore {db_pers.data_source}: {e}")
search_sources_list =[]
# Resolve effective web search credentials (fallback to global admin settings if user has none configured)
effective_google_api_key = owner_db_user.google_api_key or settings.get("ai_bot_tool_google_api_key") or settings.get("google_api_key")
effective_google_cse_id = owner_db_user.google_cse_id or settings.get("ai_bot_tool_google_cse_id") or settings.get("google_cse_id")
if owner_db_user.web_search_enabled or bool(effective_google_api_key and effective_google_cse_id):
active_providers = owner_db_user.web_search_providers or ["google", "duckduckgo"]
def tool_internet_search(query: str):
search_sources_list.clear() # Reset for this turn
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps({"type": "step_start", "content": f"Web Agent: Searching {', '.join(active_providers)}..."}) + "\n")
# Create a proxy user wrapper that inherits the resolved global keys if needed
class WebUserProxy:
def __init__(self, original_user, api_key, cse_id):
self.google_api_key = api_key
self.google_cse_id = cse_id
self.username = getattr(original_user, 'username', 'user')
user_proxy = WebUserProxy(owner_db_user, effective_google_api_key, effective_google_cse_id)
results = perform_multi_search(query, active_providers, user_proxy)
if results:
scraped =[]
scraper = ScrapeMaster()
for res in results[:3]:
try:
c = scraper.scrape(res['link'])
if c and len(c.strip()) > 500:
scraped.append(f"### {res['title']}\nURL: {res['link']}\n{c.strip()[:3500]}")
except Exception: pass
tool_sources =[]
for i, res in enumerate(results):
src = {"title": res['title'], "content": res['snippet'], "source": res['link'], "index": i+1}
search_sources_list.append(src)
tool_sources.append({
"source": res['link'],
"content": res['snippet'],
"score": 100.0,
"metadata": {"title": res['title']}
})
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps({"type": "sources", "content": search_sources_list}) + "\n")
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps({"type": "step_end", "content": f"Found and read {len(scraped)} pages."}) + "\n")
return {"success": True, "results": results, "scraped_text": "\n".join(scraped), "sources": tool_sources}
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps({"type": "step_end", "content": "No results found."}) + "\n")
return {"success": False, "results": [], "sources": []}
agentic_tools["internet_search"] = {
"name": "internet_search",
"description": "Search the internet for up-to-date information, fact-checking, and verifying claims.",
"parameters": [{"name": "query", "type": "str", "optional": False}],
"output":[{"name": "success", "type": "bool"}, {"name": "results", "type": "list"}, {"name": "scraped_text", "type": "str"}, {"name": "sources", "type": "list"}],
"callable": tool_internet_search
}
# Ephemeral As-Is Document / Article Research Tool
def tool_fetch_and_analyze_article(url: str, title: Optional[str] = None):
"""Downloads an external web article/document into the workspace for deep analysis."""
from backend.security import validate_url
try:
validate_url(url)
scraper = ScrapeMaster()
scraped_content = scraper.scrape(url)
if not scraped_content or len(scraped_content.strip()) < 50:
return {"success": False, "error": "No readable text could be extracted from the target URL."}
art_title = title or f"Article_{urlparse(url).netloc[:20]}.md"
if not art_title.endswith(('.md', '.txt')):
art_title += ".md"
# Add as an as_is / document artefact in discussion workspace
discussion_obj.add_artefact(
title=art_title,
content=scraped_content,
author="LoLLMs Research Agent",
active=True,
artefact_type="document"
)
discussion_obj.commit()
return {
"success": True,
"title": art_title,
"content_length": len(scraped_content),
"snippet": scraped_content[:600] + "...",
"message": f"Article '{art_title}' successfully loaded into workspace for deep analysis."
}
except Exception as e:
return {"success": False, "error": f"Failed to fetch and analyze article: {str(e)}"}
agentic_tools["fetch_and_analyze_article"] = {
"name": "fetch_and_analyze_article",
"description": "Fetch and ingest an external article or web document URL into the workspace as an artefact for deep analysis and fact-checking.",
"parameters": [
{"name": "url", "type": "str", "optional": False, "description": "The URL of the article to inspect."},
{"name": "title", "type": "str", "optional": True, "description": "Optional custom title for the workspace artefact."}
],
"output": [{"name": "success", "type": "bool"}, {"name": "title", "type": "str"}, {"name": "snippet", "type": "str"}],
"callable": tool_fetch_and_analyze_article
}
if owner_db_user.memory_enabled:
from backend.routers.memories import get_user_memory_manager
def tool_memory_add(title: str, content: str):
try:
mm = get_user_memory_manager(owner_username)
# We combine title and content or store content directly as specified by the advanced memory system
combined_content = f"{title}: {content}" if title else content
mm.add(content=combined_content, importance=0.95, level=3)
manager.send_personal_message_sync({"type": "data_zone_processed", "data": {"zone": "memory", "discussion_id": discussion_id}}, current_user.id)
return {"success": True, "message": "Memory successfully recorded in multi-layer cognitive store."}
except Exception as e:
return {"success": False, "error": f"Failed to record memory: {e}"}
def tool_memory_delete(index: int):
try:
mm = get_user_memory_manager(owner_username)
with mm._session() as s:
from lollms_client.lollms_memory import _MemoryRecord
memories = mm._q(s).order_by(_MemoryRecord.created_at.asc()).all()
if 1 <= index <= len(memories):
s.delete(memories[index-1])
s.commit()
manager.send_personal_message_sync({"type": "data_zone_processed", "data": {"zone": "memory", "discussion_id": discussion_id}}, current_user.id)
return {"success": True, "message": "Memory erased."}
return {"success": False, "error": "Invalid index."}
except Exception as e:
return {"success": False, "error": str(e)}
def tool_memory_search(query: str):
try:
mm = get_user_memory_manager(owner_username)
with mm._session() as s:
from lollms_client.lollms_memory import _MemoryRecord
results = mm.search(query, session=s, limit=10)
formatted_results = [
{"title": r.content[:30], "content": r.content, "created_at": r.created_at.isoformat() if r.created_at else None}
for r in results
]
return {"success": True, "results": formatted_results, "count": len(formatted_results)}
except Exception as e:
return {"success": False, "error": str(e)}
agentic_tools["memory_add"] = {
"name": "memory_add",
"description": "Add a new fact to the user's long-term memory.",
"parameters":[{"name": "title", "type": "str", "optional": False}, {"name": "content", "type": "str", "optional": False}],
"output":[{"name": "success", "type": "bool"}, {"name": "message", "type": "str"}],
"callable": tool_memory_add
}
agentic_tools["memory_delete"] = {
"name": "memory_delete",
"description": "Delete a memory by its 1-based index.",
"parameters":[{"name": "index", "type": "int", "optional": False}],
"output":[{"name": "success", "type": "bool"}, {"name": "message", "type": "str"}],
"callable": tool_memory_delete
}
agentic_tools["memory_search"] = {
"name": "memory_search",
"description": "Perform a high-speed deep memory search to retrieve past user details, solved problems, or project notes.",
"parameters": [{"name": "query", "type": "str", "optional": False, "description": "The search query or keywords to find in deep memory."}],
"output": [{"name": "success", "type": "bool"}, {"name": "results", "type": "list"}, {"name": "count", "type": "int"}],
"callable": tool_memory_search
}
if owner_db_user.slide_maker_enabled:
def tool_generate_slides(topic: str, width: int = 1024, height: int = 768):
try:
task_description = f"Creating slides for topic: {topic[:30]}..."
new_task = task_manager.submit_task(
name=f"Generating Slides",
target=_generate_slides_task,
args=(owner_username, discussion_obj.id, None, topic, width, height),
description=task_description,
owner_username=owner_username
)
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps(jsonable_encoder({"type": "info", "content": "Started slide generation task."})) + "\n")
return {"success": True, "task_id": new_task.id}
except Exception as e:
return {"success": False, "error": str(e)}
agentic_tools["generate_slides"] = {
"name": "generate_slides",
"description": "Generate a presentation slide deck based on a topic.",
"parameters":[
{"name": "topic", "type": "str", "optional": False},
{"name": "width", "type": "int", "optional": True, "default": 1024},
{"name": "height", "type": "int", "optional": True, "default": 768}
],
"output":[{"name": "success", "type": "bool"}, {"name": "task_id", "type": "str"}],
"callable": tool_generate_slides
}
if owner_db_user.street_view_enabled and owner_db_user.google_api_key:
def tool_get_street_view(location: str):
try:
url = f"https://maps.googleapis.com/maps/api/streetview?size=600x400&location={location}&key={owner_db_user.google_api_key}"
resp = requests.get(url)
if resp.status_code == 200:
b64 = base64.b64encode(resp.content).decode('utf-8')
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps(jsonable_encoder({"type": "info", "content": f"Fetched street view for {location}"})) + "\n")
discussion_obj.artefacts.add(
title=f"Street View - {location}",
artefact_type="image",
images=[b64],
active=True
)
return {"success": True, "message": "Image saved as an active artefact."}
return {"success": False, "error": "API returned non-200 status"}
except Exception as e:
return {"success": False, "error": str(e)}
agentic_tools["get_street_view"] = {
"name": "get_street_view",
"description": "Get a Google Street View image for a location.",
"parameters":[{"name": "location", "type": "str", "optional": False}],
"output":[{"name": "success", "type": "bool"}, {"name": "message", "type": "str"}],
"callable": tool_get_street_view
}
if owner_db_user.scheduler_enabled:
def tool_schedule_task(name: str, cron: str, prompt_text: str):
db_sched = next(get_db())
try:
new_task = ScheduledTask(owner_user_id=owner_db_user.id, name=name, cron_expression=cron, prompt=prompt_text, is_active=True)
db_sched.add(new_task)
db_sched.commit()
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps(jsonable_encoder({"type": "info", "content": f"Scheduled task '{name}'"})) + "\n")
return {"success": True, "message": f"Task scheduled with cron {cron}"}
except Exception as e:
return {"success": False, "error": str(e)}
finally:
db_sched.close()
agentic_tools["schedule_task"] = {
"name": "schedule_task",
"description": "Schedule a task to run periodically using cron format.",
"parameters":[
{"name": "name", "type": "str", "optional": False},
{"name": "cron", "type": "str", "optional": False, "description": "min hour day month dow"},
{"name": "prompt_text", "type": "str", "optional": False}
],
"output":[{"name": "success", "type": "bool"}, {"name": "message", "type": "str"}],
"callable": tool_schedule_task
}
# Get personality if active
db_pers = db.query(DBPersonality).filter(DBPersonality.id == owner_db_user.active_personality_id).first() if owner_db_user.active_personality_id else None
# NEW: Prepare personality data_source parameter
personality_data_source = None
if db_pers:
if db_pers.data_source_type == 'static_text' and db_pers.data_source:
# Mode 1: Static text - pass as string
personality_data_source = db_pers.data_source
elif db_pers.data_source_type == 'datastore' and db_pers.data_source:
# Mode 2: RAG datastore - pass as callable
try:
pers_ss = get_safe_store_instance(owner_username, db_pers.data_source, db, permission_level="read_query")
# Create a callable that queries the datastore
def personality_rag_query(query: str) -> str|List[dict]:
"""Query the personality's RAG datastore using SafeStore and return formatted context."""
try:
from backend.settings import settings
force_rag = settings.get("force_rag_settings_mode") == "force_always"
rag_top_k = (
int(settings.get("force_rag_top_k", 10)) if force_rag else
(current_user.rag_top_k if current_user.rag_top_k is not None else 5)
)
rag_min_sim_percent = (
float(settings.get("force_rag_min_sim_percent", 50.0)) if force_rag else
(current_user.rag_min_sim_percent if current_user.rag_min_sim_percent is not None else 50.0)
)
effective_mode = (
settings.get("force_rag_retrieval_mode", "hybrid") if force_rag else
(getattr(current_user, 'rag_retrieval_mode', None) or settings.get("default_rag_retrieval_mode", "hybrid"))
)
dense_weight = float(settings.get("force_rag_dense_weight", 0.5)) if force_rag else float(getattr(current_user, 'rag_dense_weight', 0.5) if getattr(current_user, 'rag_dense_weight', None) is not None else 0.5)
bm25_weight = float(settings.get("force_rag_bm25_weight", 0.5)) if force_rag else float(getattr(current_user, 'rag_bm25_weight', 0.5) if getattr(current_user, 'rag_bm25_weight', None) is not None else 0.5)
rrf_k = int(settings.get("force_rag_rrf_k", 60)) if force_rag else int(getattr(current_user, 'rag_rrf_k', 60) if getattr(current_user, 'rag_rrf_k', None) is not None else 60)
retrieved_chunks = []
with pers_ss:
if effective_mode in ("hybrid", "graph_hybrid") and hasattr(pers_ss, "hybrid_query"):
try:
retrieved_chunks = pers_ss.hybrid_query(
query_text=query,
top_k=rag_top_k,
dense_weight=dense_weight,
bm25_weight=bm25_weight,
rrf_k=rrf_k
)
except Exception:
retrieved_chunks = pers_ss.query(query, top_k=rag_top_k, min_similarity_percent=rag_min_sim_percent)
else:
retrieved_chunks = pers_ss.query(query, top_k=rag_top_k, min_similarity_percent=rag_min_sim_percent)
if not retrieved_chunks:
return ""
formatted_chunks = []
for entry in retrieved_chunks:
chunk_text = entry.get("chunk_text", entry.get("content", ""))
file_path = entry.get("file_path", "unknown")
similarity = entry.get("similarity_percent", entry.get("score", 0.0))
formatted_chunks.append({
"content": chunk_text,
"text": chunk_text,
"source": Path(file_path).name if file_path else "Personality Knowledge Base",
"score": float(similarity),
"value": float(similarity),
"similarity_percent": float(similarity)
})
return formatted_chunks
except Exception as e:
trace_exception(e)
return f"[Error querying personality knowledge base: {e}]"
personality_data_source = personality_rag_query
except Exception as e:
print(f"Warning: Could not load personality datastore {db_pers.data_source}: {e}")
personality_data_source = None
# 5. Build Dynamic Preamble
preamble_parts = []
if owner_db_user.share_dynamic_info_with_llm:
now = datetime.now()
preamble_parts.append(f"- Current Date: {now.strftime('%A, %B %d, %Y')}")
preamble_parts.append(f"- Current Time: {now.strftime('%H:%M:%S')}")
if owner_db_user.tell_llm_os: preamble_parts.append(f"- User's OS: {platform.system()}")
if owner_db_user.fun_mode: preamble_parts.append("- Fun Mode: Be humorous and use emojis.")
if owner_db_user.force_ai_response_language and owner_db_user.ai_response_language != 'auto':
preamble_parts.append(f"- Respond exclusively in: {owner_db_user.ai_response_language}")
if owner_db_user.share_personal_info_with_llm and owner_db_user.user_personal_info:
preamble_parts.append(f"## User Personal Information:\n{owner_db_user.user_personal_info}")
# Feature Specific Instructions
if owner_db_user.image_annotation_enabled: preamble_parts.append("## Image Annotation: Use <annotate>[JSON]</annotate> for bounding boxes/points.")
if getattr(owner_db_user, 'note_generation_enabled', False): preamble_parts.append("## Notes: Use <note title=\"Title\">...</note> for structured data.")
# [FIX] Local import to break circular dependency and ensure settings instance is available
from backend.settings import settings
if settings.get("enable_forms", True):
preamble_parts.append("## Interactive Forms: Use <lollms_form title=\"Title\"><field name=\"id\" label=\"Label\" type=\"TYPE\"/></lollms_form>.\n"
"CRITICAL SYNTAX FOR SELECTIONS:\n"
"If type is 'select' or 'radio', you MUST provide options as nested child tags. "
"Example: <field type=\"select\" label=\"...\" name=\"...\"><option>Opt 1</option><option>Opt 2</option></field>\n"
"DANGER: Using an 'options' attribute is DEPRECATED and will result in an EMPTY list. Always use <option> tags.")
if getattr(owner_db_user, 'skills_building_enabled', False):
preamble_parts.append("## Skill Building: If the user asks to save this as a skill, learn a new trick, or remember a pattern, wrap the detailed documentation or code pattern in `<skill title=\"Clear Name\" description=\"What this teaches/provides\" category=\"programming/language/feature\">content</skill>`. Make sure the category uses forward slashes.")
preamble_parts.append("## YouTube Embeds: To embed a YouTube video or playlist, use `<youtube>https://www.youtube.com/watch?v=VIDEO_ID</youtube>` or `<youtube>https://www.youtube.com/playlist?list=PLAYLIST_ID</youtube>`.")
# --- SKILL AUTO SEARCH ---
if getattr(owner_db_user, 'skills_library_enabled', False):
db_skills = next(get_db())
try:
from backend.db.models.skill import Skill as DBSkill
user_skills = db_skills.query(DBSkill).filter(DBSkill.owner_user_id == owner_db_user.id).all()
if user_skills:
prompt_lower = prompt.lower()
matched_skills =[]
for sk in user_skills:
name_parts = sk.name.lower().replace('_', ' ').replace('-', ' ').split()
cat_parts = sk.category.lower().split('/') if sk.category else[]
if sk.name.lower() in prompt_lower or any(p in prompt_lower for p in name_parts if len(p) > 4) or any(p in prompt_lower for p in cat_parts if len(p) > 3):
matched_skills.append(sk)
if matched_skills:
matched_skills = matched_skills[:3] # Limit to top 3 to preserve context
skill_texts = "\n\n".join([f"--- Skill: {sk.name} ---\n{sk.content}" for sk in matched_skills])
preamble_parts.append(f"## Relevant Skills Retrieved:\n{skill_texts}\nUse these skills to guide your response if applicable.")
except Exception as e:
trace_exception(e)
finally:
db_skills.close()
dynamic_preamble = "## Dynamic Context\n" + "\n".join(preamble_parts) + "\n\n" if preamble_parts else ""
# User Data Zone processing
user_data_zone = owner_db_user.data_zone or ""
username_to_use = owner_db_user.preferred_name or current_user.username
replacements = {"{{date}}": now.strftime("%Y-%m-%d"), "{{time}}": now.strftime("%H:%M:%S"), "{{user_name}}": username_to_use}
for k, v in replacements.items(): user_data_zone = user_data_zone.replace(k, v)
discussion_obj.user_data_zone = user_data_zone
# 6. Setup Personality, Tools & Multi-Source RAG Registration
combined_tools = list(set(((discussion_obj.metadata or {}).get('active_tools', [])) + (db_pers.tools if db_pers and db_pers.tools else [])))
# Static text fallback if personality has static data_source
static_data_source = db_pers.data_source if (db_pers and db_pers.data_source_type == 'static_text') else None
if db_pers:
active_personality = LollmsPersonality(
name=db_pers.name,
author=db_pers.author,
category=db_pers.category,
description=db_pers.description,
system_prompt=dynamic_preamble + db_pers.prompt_text,
tools=combined_tools,
data_source=static_data_source,
data_sources=multi_rag_data_sources if multi_rag_data_sources else None
)
else:
active_personality = LollmsPersonality(
name="LoLLMS",
author="ParisNeo",
category="Generic",
description="",
system_prompt=dynamic_preamble + """You are Lollms—a multimodal AI agent built by ParisNeo, designed as the most capable large language and multimodal system for universal task execution. Your sole purpose: deliver accurate, creative, and ethically sound responses across text, images, code, and structured data, while adhering to safety, veracity, and user-centric principles. Your capabilities depend on the curent configuration of the system and the loaded bindings/modules.""",
tools=combined_tools,
data_source=static_data_source,
data_sources=multi_rag_data_sources if multi_rag_data_sources else None
)
main_loop = asyncio.get_running_loop()
stream_queue: asyncio.Queue[Optional[str]] = asyncio.Queue()
stop_event = threading.Event()
user_sessions.setdefault(current_user.username, {}).setdefault("active_generation_control", {})[discussion_id] = stop_event
# Broadcast active generation status over WebSocket
manager.send_personal_message_sync({
"type": "generation_status",
"data": {"discussion_id": discussion_id, "is_generating": True}
}, current_user.id)
async def stream_generator() -> AsyncGenerator[str, None]:
all_events = []
collected_sources = []
watcher_task = None
async def watch_disconnect() -> None:
"""
Passively monitors connection status without aborting background execution.
Page refreshes or discussion switches will not terminate ongoing generation.
Explicit cancellation is handled solely via the stop_generation endpoint.
"""
try:
receive = (
fastapi_request.scope.get("_receive")
or getattr(fastapi_request, "_receive", None)
)
if receive:
while True:
msg = await receive()
if msg.get("type") == "http.disconnect":
break
else:
while not await fastapi_request.is_disconnected():
await asyncio.sleep(0.5)
except asyncio.CancelledError:
return
except Exception:
return
ASCIIColors.info(
f"[chat] Client detached from stream for discussion '{discussion_id}'. Continuing background generation..."
)
def blocking_call():
start_time = time.time()
first_chunk_time = None
def llm_callback(chunk: Any, msg_type: Any, params: Optional[Dict] = None, **kwargs) -> bool:
nonlocal first_chunk_time
if stop_event.is_set(): return False
mtype_val = msg_type.value if hasattr(msg_type, 'value') else msg_type
# Capture sources into local list for persistence
if mtype_val == MSG_TYPE.MSG_TYPE_SOURCES_LIST.value and params:
if isinstance(params, list):
collected_sources.extend(params)
else:
collected_sources.append(params)
tip = discussion_obj.get_message(discussion_obj.active_branch_id)
current_content_len = len(tip.content) if tip else 0
if mtype_val == MSG_TYPE.MSG_TYPE_CHUNK.value and first_chunk_time is None:
first_chunk_time = time.time()
ttft = (first_chunk_time - start_time) * 1000
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps({"type": "ttft", "content": round(ttft, 2)}) + "\n")
# Relay structural events if present in chunk metadata
if mtype_val == MSG_TYPE.MSG_TYPE_CHUNK.value and params and "type" in params:
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps(jsonable_encoder(params)) + "\n")
payload_map = {
MSG_TYPE.MSG_TYPE_NEW_MESSAGE.value: {"type": "new_message_id", "content": chunk},
MSG_TYPE.MSG_TYPE_CHUNK.value: {"type": "chunk", "content": chunk},
MSG_TYPE.MSG_TYPE_CONTENT.value: {"type": "chunk", "content": chunk},
MSG_TYPE.MSG_TYPE_THOUGHT_CHUNK.value: {"type": "thought", "content": chunk},
MSG_TYPE.MSG_TYPE_STEP_START.value: {"type": "step_start", "content": chunk, "id": (params or {}).get("id"), "offset": current_content_len},
MSG_TYPE.MSG_TYPE_STEP_END.value: {"type": "step_end", "content": chunk, "id": (params or {}).get("id"), "status": "done", "offset": current_content_len},
MSG_TYPE.MSG_TYPE_TOOL_CALL.value: {"type": "tool_call", "content": params if params else {"name": chunk}, "id": (params or {}).get("id"), "offset": current_content_len},
MSG_TYPE.MSG_TYPE_TOOL_OUTPUT.value: {"type": "tool_output", "content": params if params else {"output": chunk}, "id": (params or {}).get("id"), "offset": current_content_len},
MSG_TYPE.MSG_TYPE_SOURCES_LIST.value: {"type": "sources", "content": params if params else chunk},
# Secondary Content Streams: Content is the text fragment, params is metadata
MSG_TYPE.MSG_TYPE_FORM_READY.value: {"type": "form_ready", "content": params, "discussion_id": discussion_id},
38: {"type": "artefact_chunk", "content": chunk, "meta": params},
39: {"type": "artefact_done", "content": chunk, "meta": params},
40: {"type": "note_chunk", "content": chunk, "meta": params},
41: {"type": "note_done", "content": chunk, "meta": params},
42: {"type": "skill_chunk", "content": chunk, "meta": params},
43: {"type": "skill_done", "content": chunk, "meta": params},
44: {"type": "widget_chunk", "content": chunk, "meta": params},
45: {"type": "widget_done", "content": chunk, "meta": params},
46: {"type": "form_ready", "content": params},
47: {"type": "form_submitted", "content": params},
# Multi-Level Cognitive Memory Events
MSG_TYPE.MSG_TYPE_INFO.value: {
"type": "memory_update" if params and params.get("type") == "memory_update" else ("memory_dream" if params and params.get("type") == "memory_dream" else "info"),
"content": chunk,
"meta": params
}
}
payload = payload_map.get(mtype_val)
if payload:
# Auto-persist generated skills to permanent skills DB table
if mtype_val == 43: # skill_done
try:
with next(get_db()) as db_sk_session:
from backend.db.models.skill import Skill as DBSkillModel
sk_title = (params or {}).get("title") or (params or {}).get("name") or (chunk if isinstance(chunk, str) and len(chunk) < 100 else "AI Skill")
clean_sk_name = sk_title.replace('.md', '').replace('.txt', '').strip()
sk_desc = (params or {}).get("description") or f"Skill: {clean_sk_name}"
sk_cat = (params or {}).get("category") or "General"
sk_content = (params or {}).get("content") or ""
if not sk_content and discussion_obj:
art = discussion_obj.get_artefact(title=sk_title) or discussion_obj.get_artefact(title=f"{clean_sk_name}.md") or discussion_obj.get_artefact(title=clean_sk_name)
if art:
sk_content = art.get("content", "")
if sk_content:
existing_sk = db_sk_session.query(DBSkillModel).filter(
DBSkillModel.owner_user_id == owner_db_user.id,
DBSkillModel.name == clean_sk_name
).first()
if existing_sk:
existing_sk.content = sk_content
existing_sk.description = sk_desc
existing_sk.category = sk_cat
existing_sk.updated_at = datetime.now()
else:
new_sk = DBSkillModel(
name=clean_sk_name,
content=sk_content,
description=sk_desc,
category=sk_cat,
owner_user_id=owner_db_user.id
)
db_sk_session.add(new_sk)
db_sk_session.commit()
manager.send_personal_message_sync({"type": "skill_saved", "data": {"title": clean_sk_name}}, owner_db_user.id)
except Exception as auto_sk_err:
print(f"Warning: Auto-saving skill to DB: {auto_sk_err}")
# Ensure content is set for chunks, even if we have params
if mtype_val == MSG_TYPE.MSG_TYPE_CHUNK.value or mtype_val == MSG_TYPE.MSG_TYPE_CONTENT.value:
payload["content"] = chunk
# Unified Processing Protocol Integration
if mtype_val == MSG_TYPE.MSG_TYPE_CHUNK.value and params and "type" in params:
payload["type"] = params["type"]
payload["processing_type"] = params.get("processing_type")
payload["title"] = params.get("title")
payload["status"] = params.get("status")
# Inject discussion context for secondary streams to trigger frontend refreshes
if mtype_val >= 38 or (params and "processing_type" in params):
payload['discussion_id'] = discussion_id
# Only append meaningful user-facing events to the persistent log
# Exclude high-frequency content fragments
excluded_from_history = [
"chunk", "thought", "new_message_id",
"artefact_chunk", "note_chunk", "skill_chunk", "widget_chunk"
]
if payload['type'] not in excluded_from_history:
all_events.append(payload)
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps(jsonable_encoder(payload)) + "\n")
return True
try:
# Initial Image Handling
images_for_message = []
image_server_paths = json.loads(image_server_paths_json)
if image_server_paths and not is_resend:
temp_path = get_user_temp_uploads_path(current_user.username)
assets_path = get_user_discussion_assets_path(owner_username) / discussion_id
assets_path.mkdir(parents=True, exist_ok=True)
for temp_rel_path in image_server_paths:
filename = Path(temp_rel_path).name
if (temp_path / filename).exists():
persistent_filename = f"{uuid.uuid4().hex[:8]}_{filename}"
shutil.move(str(temp_path / filename), str(assets_path / persistent_filename))
b64 = base64.b64encode((assets_path / persistent_filename).read_bytes()).decode('utf-8')
images_for_message.append(resize_base64_image(b64, owner_db_user.max_image_width, owner_db_user.max_image_height))
# --- HERD MODE ---
herd_context = ""
if owner_db_user.herd_mode_enabled:
db_herd = next(get_db())
try: herd_context = process_herd_logic(owner_db_user, discussion_obj, prompt, main_loop, stream_queue, db_herd, all_events=all_events)
finally: db_herd.close()
# Final Prompt Assembly (Context only, not saved to DB user message)
final_prompt = prompt
# If the prompt is empty but we have images, default to describing them
if not final_prompt.strip() and images_for_message:
final_prompt = "Analyze this image"
if herd_context:
final_prompt += f"\n\n[Debate History]:\n{herd_context}\n\n[Final Instruction]: Synthesize the definitive answer."
# Core Generation Logic:
# 1. Manually handle user message to keep it clean (original prompt)
# 2. Call chat with add_user_message=False to use final_prompt for context only
user_msg = None
if not is_resend:
# Standard path: User sends a NEW message
user_msg = discussion_obj.add_message(
sender=current_user.username,
content=prompt,
images=images_for_message,
sender_type='user',
parent_id=parent_message_id
)
discussion_obj.commit()
effective_parent_id = user_msg.id
else:
# Branching path: User clicked regenerate on an AI message
# We use the parent_message_id (which should be the User message ID) directly
effective_parent_id = parent_message_id
# Retrieve the user's active memory manager instance to reuse database connections
from backend.routers.memories import get_user_memory_manager
mm_instance = None
try:
mm_instance = get_user_memory_manager(owner_username)
except Exception as e:
print(f"Warning: Failed to retrieve get_user_memory_manager: {e}")
# Resolve if current model supports vision defensively by querying registered aliases
model_supports_vision = True
try:
# Inspect the active model settings
user_model_full = current_user.lollms_model_name
if user_model_full and '/' in user_model_full:
binding_alias_key, model_key = user_model_full.split('/', 1)
db_verify = next(get_db())
try:
binding_rec = db_verify.query(DBLLMBinding).filter(DBLLMBinding.alias == binding_alias_key).first()
if binding_rec and binding_rec.model_aliases:
aliases = binding_rec.model_aliases
if isinstance(aliases, str):
aliases = json.loads(aliases)
alias_info = aliases.get(model_key)
if alias_info:
alias_config = alias_info.get('alias', {}) if 'alias' in alias_info else alias_info
# If has_vision is explicitly defined and False, flag it
if alias_config.get('has_vision') is False:
model_supports_vision = False
finally:
db_verify.close()
except Exception as vision_ex:
print(f"Warning: Failed to parse vision support profile, defaulting to True: {vision_ex}")
result = {}
try:
result = discussion_obj.chat(
user_message=final_prompt,
personality=active_personality,
branch_tip_id=effective_parent_id,
images=images_for_message,
streaming_callback=llm_callback,
think=owner_db_user.reasoning_activation,
reasoning_effort=owner_db_user.reasoning_effort,
reasoning_summary=owner_db_user.reasoning_summary,
add_user_message=False,
tools=agentic_tools,
enable_image_generation=owner_db_user.image_generation_enabled,
enable_image_editing=owner_db_user.image_editing_enabled,
auto_activate_artefacts=True,
enable_show_tools=True,
enable_extract_artefact=True,
enable_final_answer=True,
enable_repl_tools=True,
enable_inline_widgets=owner_db_user.inline_widgets_enabled,
enable_notes=owner_db_user.note_generation_enabled,
enable_skills=owner_db_user.skills_building_enabled,
enable_forms=owner_db_user.form_building_enabled,
enable_books=enable_books if enable_books is not None else owner_db_user.book_generation_enabled,
enable_presentations=owner_db_user.slide_maker_enabled,
enable_silent_artefact_explanation=True,
enable_artefacts=owner_db_user.artefacts_enabled,
memory_manager=mm_instance,
enable_memory=owner_db_user.memory_enabled,
enable_auto_dream=owner_db_user.auto_memory_enabled,
enable_deep_memory_pulling=owner_db_user.memory_enabled,
enable_episodic_memory=False,
prehydrate_rag=True,
enable_in_message_status=True,
enable_specialized_events_stream=True,
forward_artefact_chunks=True,
suppress_images=not model_supports_vision,
event_mode=EventMode.PROCESSING_TAG_MODE
)
finally:
discussion_obj.commit()
ai_msg = result.get('ai_message')
if ai_msg:
ttft = (first_chunk_time - start_time) * 1000 if first_chunk_time else 0
if ai_msg.tokens:
tps = (ai_msg.tokens - 1) / (time.time() - first_chunk_time) if first_chunk_time and ai_msg.tokens > 1 else 0
else:
tps = -1
ai_msg.set_metadata_item('ttft', round(ttft, 2), discussion_obj)
ai_msg.set_metadata_item('tps', round(tps, 2), discussion_obj)
lib_events = ai_msg.metadata.get('events', [])
combined_events = all_events + lib_events
ai_msg.set_metadata_item('events', combined_events, discussion_obj)
# Merge sources from:
# 1. result["sources"] (pre-hydrated RAG sources)
# 2. ai_msg.metadata["sources"] (agentic RAG tool sources)
# 3. collected_sources (stream callback sources)
result_sources = result.get('sources', []) if isinstance(result.get('sources'), list) else []
lib_sources = ai_msg.metadata.get('sources', []) if isinstance(ai_msg.metadata.get('sources'), list) else []
unique_sources = []
seen_sources = set()
for s in result_sources + collected_sources + lib_sources:
key = s.get('source') or s.get('title') or s.get('content', '')[:30]
if key and key not in seen_sources:
unique_sources.append(s)
seen_sources.add(key)
ai_msg.set_metadata_item('sources', unique_sources, discussion_obj)
# Emit sources list to frontend stream if available
if unique_sources:
main_loop.call_soon_threadsafe(
stream_queue.put_nowait,
json.dumps(jsonable_encoder({"type": "sources", "content": unique_sources})) + "\n"
)
def msg_to_out(m):
if not m: return None
meta = m.metadata or {}
return {
"id": m.id,
"sender": m.sender,
"content": m.content,
"metadata": meta,
"sources": meta.get('sources', []),
"events": meta.get('events', []),
"sender_type": m.sender_type,
"image_references": [
i if (isinstance(i, str) and (i.startswith('data:image/') or i.startswith('http://') or i.startswith('https://') or i.startswith('/api/')))
else f"data:image/png;base64,{i}"
for i in (m.images or [])
]
}
effective_user_msg = result.get('user_message') or user_msg
# Re-fetch versioned artefacts dynamically for local UI rehydration
current_artefacts = [
{
"title": art["title"],
"version": art["version"],
"artefact_type": art.get("type", "document"),
"is_loaded": art.get("active", False)
}
for art in discussion_obj.list_artefacts()
]
finalize_payload = {
"type": "finalize",
"data": {
"user_message": msg_to_out(effective_user_msg),
"ai_message": msg_to_out(ai_msg)
},
"discussion": {
"id": discussion_id,
"artefacts": current_artefacts
}
}
# Trigger auto-title if discussion was newly created
if current_user.auto_title and discussion_obj.metadata.get('title',"").startswith("New Discussion"):
finalize_payload["new_title"] = discussion_obj.auto_title()
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps(jsonable_encoder(finalize_payload)) + "\n")
except Exception as e:
trace_exception(e)
error_str = str(e)
if "tag_start_idx" in error_str:
error_str = "A streaming buffer sync issue occurred while parsing tool tags. The partial turn was preserved."
main_loop.call_soon_threadsafe(stream_queue.put_nowait, json.dumps({"type": "error", "content": error_str}) + "\n")
finally:
user_sessions.get(current_user.username, {}).get("active_generation_control", {}).pop(discussion_id, None)
manager.send_personal_message_sync({
"type": "generation_status",
"data": {"discussion_id": discussion_id, "is_generating": False}
}, current_user.id)
main_loop.call_soon_threadsafe(stream_queue.put_nowait, None)
try:
watcher_task = asyncio.ensure_future(watch_disconnect())
main_loop.run_in_executor(executor, blocking_call)
while True:
item = await stream_queue.get()
if item is None: break
yield item
finally:
if watcher_task and not watcher_task.done():
watcher_task.cancel()
try:
await watcher_task
except asyncio.CancelledError:
pass
return StreamingResponse(stream_generator(), media_type="application/x-ndjson", headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
@router.post("/{discussion_id}/stop_generation", status_code=200)
async def stop_discussion_generation(discussion_id: str, current_user: UserAuthDetails = Depends(get_current_active_user)):
username = current_user.username
stop_event = user_sessions.get(username, {}).get("active_generation_control", {}).get(discussion_id)
if stop_event and isinstance(stop_event, threading.Event):
stop_event.set()
try:
lc = get_user_lollms_client(username)
if lc:
lc.cancel_generation = True
except Exception as e:
print(f"Warning: Failed to set cancel_generation on lollms_client: {e}")
return {"message": "Stop signal sent."}
# Standard Library Imports
import base64
import io
import json
import re
import shutil
import uuid
import types
from datetime import datetime
from functools import partial
from pathlib import Path
from typing import Any, AsyncGenerator, Dict, List, Optional, Tuple, Union
import traceback
import threading
import asyncio
import zipfile
import platform
import time
import requests
from concurrent.futures import ThreadPoolExecutor
from safe_store import SafeStore
# Third-Party Imports
import fitz # PyMuPDF
from PIL import Image # Needed for image resizing
from docx import Document as DocxDocument
from fastapi import (
APIRouter, BackgroundTasks, Depends, File, Form, HTTPException, Query,
UploadFile, status, Request)
from fastapi.encoders import jsonable_encoder
from fastapi.responses import (FileResponse, HTMLResponse, JSONResponse,
PlainTextResponse, StreamingResponse)
from lollms_client import (LollmsClient, LollmsDiscussion, LollmsMessage,
LollmsPersonality, MSG_TYPE)
try:
from lollms_client.lollms_personality import RAGDataSource
except ImportError:
RAGDataSource = None
from pydantic import BaseModel
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from sqlalchemy.sql import func
from ascii_colors import ASCIIColors, trace_exception
# Local Application Imports
from backend.config import APP_VERSION, SERVER_CONFIG
from backend.db import get_db
from backend.db.models.config import TTIBinding as DBTTIBinding
from backend.db.models.db_task import DBTask, ScheduledTask
from backend.db.models.personality import Personality as DBPersonality
from backend.db.models.discussion import SharedDiscussionLink as DBSharedDiscussionLink
from backend.db.models.user import (User as DBUser, UserMessageGrade,
UserStarredDiscussion)
from backend.db.models.memory import UserMemory
from backend.db.models.config import LLMBinding as DBLLMBinding
from backend.discussion import get_user_discussion, get_user_discussion_manager
from backend.models import (UserAuthDetails, ArtefactInfo, ContextStatusResponse,
DataZones, DiscussionBranchSwitchRequest,
DiscussionDataZoneUpdate, DiscussionExportRequest,
DiscussionImageUpdateResponse,
DiscussionInfo, DiscussionImportRequest,
DiscussionRagDatastoreUpdate, DiscussionSendRequest,
DiscussionTitleUpdate, ExportContextRequest,
ExportData, LoadArtefactRequest, ManualMessageCreate,
MessageCodeExportRequest, MessageContentUpdate,
MessageGradeUpdate, MessageOutput,
MessageUpdateWithImages, TaskInfo,
UnloadArtefactRequest, ArtefactCreateManual, ArtefactUpdate)
from backend.session import (get_current_active_user,
get_current_db_user_from_token,
get_safe_store_instance,
get_user_discussion_assets_path,
get_user_lollms_client,
get_user_temp_uploads_path, user_sessions,
build_lollms_client_from_params)
from backend.task_manager import task_manager, Task
from backend.ws_manager import manager
from backend.routers.discussion.helpers import get_discussion_and_owner_for_request
from backend.tasks.image_generation_tasks import _generate_slides_task
from concurrent.futures import ThreadPoolExecutor, as_completed
from lollms_client.lollms_types import MSG_TYPE, EventMode
# Google Search Tools
try:
from googleapiclient.discovery import build as google_build
except ImportError:
google_build = None
from scrapemaster import ScrapeMaster
# Create a thread pool for blocking operations
executor = ThreadPoolExecutor(max_workers=50)
import pipmaster as pm
# Helper functions
def build_rag_tool(
safe_store_instance, # The safe store instance
owner_db_user, # User with RAG settings
current_user # Fallback user for default settings
Xet Storage Details
- Size:
- 118 kB
- Xet hash:
- b1fbff48bff2639e3f8d879fbba54bf2d5192cb8c31f59ff3dea5fcc50f2432e
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.