85 行
2.7 KiB
Python
85 行
2.7 KiB
Python
"""Prompt expansion service for generation requests."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from typing import Any
|
|
|
|
from backend.dto.profile_dto import CharacterProfile
|
|
from backend.dto.workflow_dto import WorkflowNode
|
|
from core.prompt_pipeline import merge_prompt_sections
|
|
|
|
|
|
class PromptExpansionService:
|
|
def expand_payload(self, payload: dict[str, Any]) -> dict[str, Any]:
|
|
sections = payload.get("sections")
|
|
if not isinstance(sections, list):
|
|
sections = [payload]
|
|
result = merge_prompt_sections(*[section for section in sections if isinstance(section, dict)])
|
|
return {
|
|
**result.to_dict(),
|
|
"source": "payload",
|
|
}
|
|
|
|
def expand_for_node(
|
|
self,
|
|
profile: CharacterProfile,
|
|
node: WorkflowNode,
|
|
payload: dict[str, Any],
|
|
) -> dict[str, Any]:
|
|
variables = {
|
|
"profile_name": profile.name,
|
|
"node_title": node.title,
|
|
**(profile.metadata.get("prompt_variables") if isinstance(profile.metadata.get("prompt_variables"), dict) else {}),
|
|
**(payload.get("variables") if isinstance(payload.get("variables"), dict) else {}),
|
|
}
|
|
result = merge_prompt_sections(
|
|
{
|
|
"parts": [profile.base_prompt, profile.appearance_prompt, profile.style_prompt],
|
|
"negative_parts": [profile.negative_prompt],
|
|
"variables": variables,
|
|
},
|
|
{
|
|
"parts": [node.prompt],
|
|
"negative_parts": [node.negative_prompt],
|
|
"variables": variables,
|
|
},
|
|
{
|
|
"parts": _payload_parts(payload),
|
|
"negative_parts": _payload_negative_parts(payload),
|
|
"variables": variables,
|
|
},
|
|
)
|
|
return {
|
|
**result.to_dict(),
|
|
"source": "profile_node",
|
|
"profile_id": profile.profile_id,
|
|
"node_id": node.node_id,
|
|
}
|
|
|
|
|
|
def _payload_parts(payload: dict[str, Any]) -> list[Any]:
|
|
parts: list[Any] = []
|
|
parts.extend(_as_list(payload.get("prompt_parts")))
|
|
for key in ("prompt_patch", "extra_prompt", "style_prompt"):
|
|
value = payload.get(key)
|
|
if value:
|
|
parts.append(value)
|
|
return parts
|
|
|
|
|
|
def _payload_negative_parts(payload: dict[str, Any]) -> list[Any]:
|
|
parts: list[Any] = []
|
|
parts.extend(_as_list(payload.get("negative_parts")))
|
|
for key in ("negative_prompt", "negative_prompt_patch"):
|
|
value = payload.get(key)
|
|
if value:
|
|
parts.append(value)
|
|
return parts
|
|
|
|
|
|
def _as_list(value: Any) -> list[Any]:
|
|
if value is None:
|
|
return []
|
|
if isinstance(value, list):
|
|
return value
|
|
return [value]
|