Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@
deployment_buml_to_json,
)
from besser.utilities.web_modeling_editor.backend.services.converters.element_ids import adopt_element_ids
from besser.utilities.web_modeling_editor.backend.services.converters.layout_adoption import adopt_existing_layout

# Backend services - Other services
from besser.utilities.web_modeling_editor.backend.services.utils.agent_generation_utils import (
Expand Down Expand Up @@ -382,9 +383,12 @@ async def export_buml(input_data: DiagramInput, settings: SettingsDep):
)


def _import_repair_warnings(repairs: list[str]) -> list[dict] | None:
"""What the import changed to load a BUML file, in the response's warning shape."""
return [{"code": "buml-import-repaired", "message": message} for message in repairs] or None
def _import_repair_warnings(repairs: list[str], unread: list[str] | None = None) -> list[dict] | None:
"""What the import changed or could not read in a BUML file, in the response's warning shape."""
return (
[{"code": "buml-import-repaired", "message": message} for message in repairs]
+ [{"code": "buml-import-partial", "message": message} for message in unread or []]
) or None


@router.post("/get-project-json-model", response_model=ProjectExportResponse)
Expand All @@ -407,10 +411,16 @@ async def get_project_json_model(buml_file: UploadFile = File(...)):

@router.post("/get-json-model", response_model=DiagramExportResponse)
@handle_endpoint_errors("get_single_json_model")
async def get_single_json_model(buml_file: UploadFile = File(...)):
async def get_single_json_model(buml_file: UploadFile = File(...), existing_model: str = Form(None)):
"""
Convert a BUML Python file to JSON format for single diagram import.
This endpoint handles both full project files and single diagram files.

When `existing_model` is provided (as a stringified v4 diagram JSON of the
diagram the file updates), the imported diagram is laid out like it:
matched elements keep their id, position and size, new ones are placed
next to a neighbour. `warnings` then reports what was kept, added and not
in the file. Class, Agent and State Machine diagrams only.
"""
content = await buml_file.read()
validate_upload(buml_file, max_size=MAX_BUML_SIZE, allowed_extensions=ALLOWED_BUML_EXTENSIONS, content=content)
Expand All @@ -422,6 +432,7 @@ async def get_single_json_model(buml_file: UploadFile = File(...)):
diagram_type = None
parse_error = None
repairs: list[str] = []
unread: list[str] = []
safe_filename = os.path.basename(buml_file.filename) if buml_file.filename else ""
diagram_title = safe_filename.rsplit('.', 1)[0] if safe_filename else "Imported Diagram"

Expand Down Expand Up @@ -539,7 +550,7 @@ def _pick_entry(dtype):
elif is_agent:
try:
logger.info("Detected Agent diagram, parsing...")
agent_json = agent_buml_to_json(buml_content)
agent_json = agent_buml_to_json(buml_content, unread)
diagram_data = {
"title": diagram_title,
"model": agent_json
Expand Down Expand Up @@ -661,17 +672,20 @@ def _pick_entry(dtype):
"KnowledgeGraphDiagram, ComponentDiagram, DeploymentDiagram, or Project."
)

model = {**diagram_data.get("model", {}), "type": diagram_type}
warnings = _import_repair_warnings(repairs, unread) or []
if existing_model is not None:
model, layout_warnings = adopt_existing_layout(existing_model, model, diagram_type)
warnings.extend(layout_warnings)

# Return the diagram in the format expected by the frontend
return {
"title": diagram_title,
"model": {
**diagram_data.get("model", {}),
"type": diagram_type
},
"model": model,
"diagramType": diagram_type,
"exportedAt": datetime.now(timezone.utc).isoformat(),
"version": API_VERSION,
"warnings": _import_repair_warnings(repairs),
"warnings": warnings or None,
}

@router.post("/get-svg")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
import logging
import textwrap
import uuid
from typing import Any, Dict, List
from typing import Any, Dict, List, Optional

from besser.utilities.buml_code_builder.agent_model_builder import GUI_BUILDER_FUNCTION_PREFIX
from ..json_to_buml.a2a_tags import format_a2a_line
Expand Down Expand Up @@ -146,12 +146,19 @@ def analyze_function_node(node: ast.FunctionDef, source_code: str) -> Dict[str,
}


def _agent_buml_to_flat_json(content: str) -> Dict[str, Any]:
def _note_unread(warnings: Optional[List[str]], what: str, error: Exception) -> None:
"""Record that ``what`` was left out of the diagram because reading it failed."""
if warnings is not None:
warnings.append(f"Left out {what} of the agent file that could not be read ({type(error).__name__}: {error}).")


def _agent_buml_to_flat_json(content: str, warnings: Optional[List[str]] = None) -> Dict[str, Any]:
"""
Convert an agent Python file content to JSON format matching the frontend structure.

Args:
content: Agent model Python code as string
warnings: Receives a message for every part of the file that could not be read

Returns:
Dictionary representing the agent diagram in JSON format
Expand Down Expand Up @@ -1839,6 +1846,7 @@ def _collect_llm_kwargs(call: ast.Call) -> Dict[str, Any]:

except Exception as e:
logger.error("Error processing agent body: %s", e, exc_info=True)
_note_unread(warnings, "a state body", e)
continue

# Add handling for fallback bodies
Expand Down Expand Up @@ -1981,9 +1989,11 @@ def _collect_llm_kwargs(call: ast.Call) -> Dict[str, Any]:
elements[state["id"]]["fallbackBodies"].append(body_id)
except Exception as e:
logger.warning("Error processing agent fallback body: %s", e, exc_info=True)
_note_unread(warnings, "a fallback body", e)
continue
except Exception as e:
logger.error("Error processing agent state machine: %s", e, exc_info=True)
_note_unread(warnings, "a statement", e)
continue
# Find initial state and create initial transition
initial_state = None
Expand Down Expand Up @@ -2184,8 +2194,13 @@ def _collect_llm_kwargs(call: ast.Call) -> Dict[str, Any]:
result["config"] = {"default_llm_name": default_llm_name_value}
return result

except Exception:
except Exception as e:
logger.exception("Error converting agent BUML to JSON; returning partial diagram")
if warnings is not None:
warnings.append(
f"The agent file could be read only up to an unsupported statement ({type(e).__name__}: {e}); "
"the diagram holds what was read before it, the rest of the file is not imported."
)
# On error return partial results, also split into canvas / components
_COMPONENT_TYPES_FALLBACK = {
'AgentIntent', 'AgentIntentBody', 'AgentRagElement',
Expand Down Expand Up @@ -2379,7 +2394,7 @@ def _flat_to_v4(flat: Dict[str, Any]) -> Dict[str, Any]:
return result


def agent_buml_to_json(content: str) -> Dict[str, Any]:
def agent_buml_to_json(content: str, warnings: Optional[List[str]] = None) -> Dict[str, Any]:
"""Convert agent B-UML Python code to the v4 AgentDiagram wire shape.

Canvas: ``AgentState`` nodes (inline ``data.bodies`` / ``data.fallbackBodies``
Expand All @@ -2388,8 +2403,12 @@ def agent_buml_to_json(content: str) -> Dict[str, Any]:
``CommentLink`` edges. Off-canvas: intents (+ ``AgentIntentBody`` entries),
LLMs, RAG databases, tools, skills, workspaces and GUIs in the top-level
``components`` map.

``warnings`` receives a message for every part of the file that could not
be read and is missing from the diagram (the parser recognises the forms
the B-UML exporter writes, not every way to build an agent).
"""
model = _flat_to_v4(_agent_buml_to_flat_json(content))
model = _flat_to_v4(_agent_buml_to_flat_json(content, warnings))
_restore_a2a_tags(model, _read_a2a(content))
return model

Expand Down
Loading