Skip to content

Drop in a screenshot and convert it to clean code (HTML/Tailwind/React/Vue)

Python

refactor: improve create_prompt architecture to use extracted params with clean separation

Abi Raja1bbf0089e033
diff --git a/backend/prompts/__init__.py b/backend/prompts/__init__.py
index ae832027..46cbc546 100644
--- a/backend/prompts/__init__.py
+++ b/backend/prompts/__init__.py
@@ -20,28 +20,31 @@ Generate code for a SVG that looks exactly like this.
async def create_prompt(
- params: dict[str, Any], stack: Stack, input_mode: InputMode
+ stack: Stack,
+ input_mode: InputMode,
+ generation_type: str,
+ prompt: PromptContent,
+ history: list[dict[str, Any]],
+ is_imported_from_code: bool,
+ result_image: str | None,
) -> tuple[list[ChatCompletionMessageParam], dict[str, str]]:
image_cache: dict[str, str] = {}
# If this generation started off with imported code, we need to assemble the prompt differently
- if params.get("isImportedFromCode"):
- original_imported_code = params["history"][0]["text"]
+ if is_imported_from_code:
+ original_imported_code = history[0]["text"]
prompt_messages = assemble_imported_code_prompt(original_imported_code, stack)
- for index, item in enumerate(params["history"][1:]):
+ for index, item in enumerate(history[1:]):
role = "user" if index % 2 == 0 else "assistant"
message = create_message_from_history_item(item, role)
prompt_messages.append(message)
else:
# Assemble the prompt for non-imported code
- prompt: PromptContent = params["prompt"]
if input_mode == "image":
image_url = prompt["images"][0]
- if params.get("resultImage"):
- prompt_messages = assemble_prompt(
- image_url, stack, params["resultImage"]
- )
+ if result_image:
+ prompt_messages = assemble_prompt(image_url, stack, result_image)
else:
prompt_messages = assemble_prompt(image_url, stack)
elif input_mode == "text":
@@ -49,24 +52,22 @@ async def create_prompt(
else:
# Default to image mode for backward compatibility
image_url = prompt["images"][0]
- if params.get("resultImage"):
- prompt_messages = assemble_prompt(
- image_url, stack, params["resultImage"]
- )
+ if result_image:
+ prompt_messages = assemble_prompt(image_url, stack, result_image)
else:
prompt_messages = assemble_prompt(image_url, stack)
- if params["generationType"] == "update":
+ if generation_type == "update":
# Transform the history tree into message format
- for index, item in enumerate(params["history"]):
+ for index, item in enumerate(history):
role = "assistant" if index % 2 == 0 else "user"
message = create_message_from_history_item(item, role)
prompt_messages.append(message)
- image_cache = create_alt_url_mapping(params["history"][-2]["text"])
+ image_cache = create_alt_url_mapping(history[-2]["text"])
if input_mode == "video":
- video_data_url = params["prompt"]["images"][0]
+ video_data_url = prompt["images"][0]
prompt_messages = await assemble_claude_prompt_video(video_data_url)
return prompt_messages, image_cache
@@ -83,30 +84,40 @@ def create_message_from_history_item(
if role == "user" and item.get("images") and len(item["images"]) > 0:
# Create multipart content for user messages with images
user_content: list[ChatCompletionContentPartParam] = []
-
+
# Add all images first
for image_url in item["images"]:
- user_content.append({
- "type": "image_url",
- "image_url": {"url": image_url, "detail": "high"},
- })
-
+ user_content.append(
+ {
+ "type": "image_url",
+ "image_url": {"url": image_url, "detail": "high"},
+ }
+ )
+
# Add text content
- user_content.append({
- "type": "text",
- "text": item["text"],
- })
-
- return cast(ChatCompletionMessageParam, {
- "role": role,
- "content": user_content,
- })
+ user_content.append(
+ {
+ "type": "text",
+ "text": item["text"],
+ }
+ )
+
+ return cast(
+ ChatCompletionMessageParam,
+ {
+ "role": role,
+ "content": user_content,
+ },
+ )
else:
# Regular text-only message
- return cast(ChatCompletionMessageParam, {
- "role": role,
- "content": item["text"],
- })
+ return cast(
+ ChatCompletionMessageParam,
+ {
+ "role": role,
+ "content": item["text"],
+ },
+ )
def assemble_imported_code_prompt(
diff --git a/backend/routes/generate_code.py b/backend/routes/generate_code.py
index 31781ace..2d3daec7 100644
--- a/backend/routes/generate_code.py
+++ b/backend/routes/generate_code.py
@@ -53,7 +53,7 @@ MessageType = Literal[
from image_generation.core import generate_images
from prompts import create_prompt
from prompts.claude_prompts import VIDEO_PROMPT
-from prompts.types import Stack
+from prompts.types import Stack, PromptContent
# from utils import pprint_prompt
from ws.constants import APP_ERROR_WEB_SOCKET_CODE # type: ignore
@@ -208,6 +208,10 @@ class ExtractedParams:
anthropic_api_key: str | None
openai_base_url: str | None
generation_type: Literal["create", "update"]
+ prompt: PromptContent
+ history: List[Dict[str, Any]]
+ is_imported_from_code: bool
+ result_image: str | None
class ParameterExtractionStage:
@@ -263,6 +267,18 @@ class ParameterExtractionStage:
raise ValueError(f"Invalid generation type: {generation_type}")
generation_type = cast(Literal["create", "update"], generation_type)
+ # Extract prompt content
+ prompt = params.get("prompt", {"text": "", "images": []})
+
+ # Extract history (default to empty list)
+ history = params.get("history", [])
+
+ # Extract imported code flag
+ is_imported_from_code = params.get("isImportedFromCode", False)
+
+ # Extract result image
+ result_image = params.get("resultImage")
+
return ExtractedParams(
stack=validated_stack,
input_mode=validated_input_mode,
@@ -271,6 +287,10 @@ class ParameterExtractionStage:
anthropic_api_key=anthropic_api_key,
openai_base_url=openai_base_url,
generation_type=generation_type,
+ prompt=prompt,
+ history=history,
+ is_imported_from_code=is_imported_from_code,
+ result_image=result_image,
)
def _get_from_settings_dialog_or_env(
@@ -392,14 +412,18 @@ class PromptCreationStage:
async def create_prompt(
self,
- params: Dict[str, str],
- stack: Stack,
- input_mode: InputMode,
+ extracted_params: ExtractedParams,
) -> tuple[List[ChatCompletionMessageParam], Dict[str, str]]:
"""Create prompt messages and return image cache"""
try:
prompt_messages, image_cache = await create_prompt(
- params, stack, input_mode
+ stack=extracted_params.stack,
+ input_mode=extracted_params.input_mode,
+ generation_type=extracted_params.generation_type,
+ prompt=extracted_params.prompt,
+ history=extracted_params.history,
+ is_imported_from_code=extracted_params.is_imported_from_code,
+ result_image=extracted_params.result_image,
)
print_prompt_summary(prompt_messages, truncate=False)
@@ -844,9 +868,7 @@ class PromptCreationMiddleware(Middleware):
assert context.extracted_params is not None
context.prompt_messages, context.image_cache = (
await prompt_creator.create_prompt(
- context.params,
- context.extracted_params.stack,
- context.extracted_params.input_mode,
+ context.extracted_params,
)
)