Skip to content

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

Python

Review backend image-gen changes

Abi Rajab9d375f69585
diff --git a/backend/agent/tools.py b/backend/agent/tools.py
index 5269cc1a..466f22b1 100644
--- a/backend/agent/tools.py
+++ b/backend/agent/tools.py
@@ -8,7 +8,7 @@ from google.genai import types
from codegen.utils import extract_html_content
from config import REPLICATE_API_KEY
-from image_generation.core import process_tasks
+from image_generation.generation import process_tasks
from image_generation.replicate import remove_background
from agent.state import AgentFileState, ensure_str
diff --git a/backend/image_generation/core.py b/backend/image_generation/core.py
index aada7eb8..98b81e7d 100644
--- a/backend/image_generation/core.py
+++ b/backend/image_generation/core.py
@@ -1,156 +1,12 @@
-import asyncio
-import re
-from typing import Dict, List, Literal, Union
-from openai import AsyncOpenAI
-from bs4 import BeautifulSoup
-
-from image_generation.replicate import call_replicate
-
-
-async def process_tasks(
- prompts: List[str],
- api_key: str,
- base_url: str | None,
- model: Literal["dalle3", "flux"],
-):
- import time
-
- start_time = time.time()
- if model == "dalle3":
- tasks = [generate_image_dalle(prompt, api_key, base_url) for prompt in prompts]
- else:
- tasks = [generate_image_replicate(prompt, api_key) for prompt in prompts]
- results = await asyncio.gather(*tasks, return_exceptions=True)
- end_time = time.time()
- generation_time = end_time - start_time
- print(f"Image generation time: {generation_time:.2f} seconds")
-
- processed_results: List[Union[str, None]] = []
- for result in results:
- if isinstance(result, BaseException):
- print(f"An exception occurred: {result}")
- processed_results.append(None)
- else:
- processed_results.append(result)
-
- return processed_results
-
-
-async def generate_image_dalle(
- prompt: str, api_key: str, base_url: str | None
-) -> Union[str, None]:
- client = AsyncOpenAI(api_key=api_key, base_url=base_url)
- res = await client.images.generate(
- model="dall-e-3",
- quality="standard",
- style="natural",
- n=1,
- size="1024x1024",
- prompt=prompt,
- )
- await client.close()
- return res.data[0].url
-
-
-async def generate_image_replicate(prompt: str, api_key: str) -> str:
-
- # We use Flux 2 Klein
- return await call_replicate(
- {
- "prompt": prompt,
- "aspect_ratio": "1:1",
- "output_format": "png",
- },
- api_key,
- )
-
-
-def extract_dimensions(url: str):
- # Regular expression to match numbers in the format '300x200'
- matches = re.findall(r"(\d+)x(\d+)", url)
-
- if matches:
- width, height = matches[0] # Extract the first match
- width = int(width)
- height = int(height)
- return (width, height)
- else:
- return (100, 100)
-
-
-def create_alt_url_mapping(code: str) -> Dict[str, str]:
- soup = BeautifulSoup(code, "html.parser")
- images = soup.find_all("img")
-
- mapping: Dict[str, str] = {}
-
- for image in images:
- if not image["src"].startswith("https://placehold.co"):
- mapping[image["alt"]] = image["src"]
-
- return mapping
-
-
-async def generate_images(
- code: str,
- api_key: str,
- base_url: Union[str, None],
- image_cache: Dict[str, str],
- model: Literal["dalle3", "flux"] = "dalle3",
-) -> str:
- # Find all images
- soup = BeautifulSoup(code, "html.parser")
- images = soup.find_all("img")
-
- # Extract alt texts as image prompts
- alts: List[str | None] = []
- for img in images:
- # Only include URL if the image starts with https://placehold.co
- # and it's not already in the image_cache
- if (
- img.get("src", None)
- and img["src"].startswith("https://placehold.co")
- and image_cache.get(img.get("alt")) is None
- ):
- alts.append(img.get("alt", None))
-
- # Exclude images with no alt text
- filtered_alts: List[str] = [alt for alt in alts if alt is not None]
-
- # Remove duplicates
- prompts = list(set(filtered_alts))
-
- # Return early if there are no images to replace
- if len(prompts) == 0:
- return code
-
- # Generate images
- results = await process_tasks(prompts, api_key, base_url, model)
-
- # Create a dict mapping alt text to image URL
- mapped_image_urls = dict(zip(prompts, results))
-
- # Merge with image_cache
- mapped_image_urls = {**mapped_image_urls, **image_cache}
-
- # Replace old image URLs with the generated URLs
- for img in images:
- # Skip images that don't start with https://placehold.co (leave them alone)
- if not img["src"].startswith("https://placehold.co"):
- continue
-
- new_url = mapped_image_urls[img.get("alt")]
-
- if new_url:
- # Set width and height attributes
- width, height = extract_dimensions(img["src"])
- img["width"] = width
- img["height"] = height
- # Replace img['src'] with the mapped image URL
- img["src"] = new_url
- else:
- print("Image generation failed for alt text:" + img.get("alt"))
-
- # Return the modified HTML
- # (need to prettify it because BeautifulSoup messes up the formatting)
- return soup.prettify()
+from image_generation.generation import (
+ generate_image_dalle,
+ generate_image_replicate,
+ process_tasks,
+)
+
+
+__all__ = [
+ "process_tasks",
+ "generate_image_dalle",
+ "generate_image_replicate",
+]
diff --git a/backend/image_generation/generation.py b/backend/image_generation/generation.py
new file mode 100644
index 00000000..008ae779
--- /dev/null
+++ b/backend/image_generation/generation.py
@@ -0,0 +1,64 @@
+import asyncio
+import time
+from typing import List, Literal, Union
+
+from openai import AsyncOpenAI
+
+from image_generation.replicate import call_replicate
+
+
+async def process_tasks(
+ prompts: List[str],
+ api_key: str,
+ base_url: str | None,
+ model: Literal["dalle3", "flux"],
+) -> List[Union[str, None]]:
+ start_time = time.time()
+ if model == "dalle3":
+ tasks = [generate_image_dalle(prompt, api_key, base_url) for prompt in prompts]
+ else:
+ tasks = [generate_image_replicate(prompt, api_key) for prompt in prompts]
+ results = await asyncio.gather(*tasks, return_exceptions=True)
+ end_time = time.time()
+ generation_time = end_time - start_time
+ print(f"Image generation time: {generation_time:.2f} seconds")
+
+ processed_results: List[Union[str, None]] = []
+ for result in results:
+ if isinstance(result, BaseException):
+ print(f"An exception occurred: {result}")
+ processed_results.append(None)
+ else:
+ processed_results.append(result)
+
+ return processed_results
+
+
+async def generate_image_dalle(
+ prompt: str, api_key: str, base_url: str | None
+) -> Union[str, None]:
+ client = AsyncOpenAI(api_key=api_key, base_url=base_url)
+ res = await client.images.generate(
+ model="dall-e-3",
+ quality="standard",
+ style="natural",
+ n=1,
+ size="1024x1024",
+ prompt=prompt,
+ )
+ await client.close()
+ if not res.data:
+ return None
+ return res.data[0].url
+
+
+async def generate_image_replicate(prompt: str, api_key: str) -> str:
+ # We use Flux 2 Klein
+ return await call_replicate(
+ {
+ "prompt": prompt,
+ "aspect_ratio": "1:1",
+ "output_format": "png",
+ },
+ api_key,
+ )
diff --git a/backend/image_generation/replicate.py b/backend/image_generation/replicate.py
index 474d199f..843eade9 100644
--- a/backend/image_generation/replicate.py
+++ b/backend/image_generation/replicate.py
@@ -1,131 +1,129 @@
import asyncio
import httpx
-from typing import Any
+from typing import Any, Mapping, cast
-async def call_replicate_model(
- model_path: str, input: dict[str, Any], api_token: str
-) -> Any:
- headers = {
+REPLICATE_API_BASE_URL = "https://api.replicate.com/v1"
+FLUX_MODEL_PATH = "black-forest-labs/flux-2-klein-4b"
+REMOVE_BACKGROUND_VERSION = (
+ "a029dff38972b5fda4ec5d75d7d1cd25aeff621d2cf4946a41055d7db66b80bc"
+)
+POLL_INTERVAL_SECONDS = 0.1
+MAX_POLLS = 100
+
+
+def _build_headers(api_token: str) -> dict[str, str]:
+ return {
"Authorization": f"Bearer {api_token}",
"Content-Type": "application/json",
}
- data = {"input": input}
- async with httpx.AsyncClient() as client:
- try:
- response = await client.post(
- f"https://api.replicate.com/v1/models/{model_path}/predictions",
- headers=headers,
- json=data,
- )
- response.raise_for_status()
- response_json = response.json()
+def _extract_prediction_id(response_json: Mapping[str, Any]) -> str:
+ prediction_id = response_json.get("id")
+ if not isinstance(prediction_id, str) or not prediction_id:
+ raise ValueError("Prediction ID not found in initial response.")
+ return prediction_id
- prediction_id = response_json.get("id")
- if not prediction_id:
- raise ValueError("Prediction ID not found in initial response.")
-
- num_polls = 0
- max_polls = 100
- while num_polls < max_polls:
- num_polls += 1
-
- await asyncio.sleep(0.1)
-
- status_check_url = (
- f"https://api.replicate.com/v1/predictions/{prediction_id}"
- )
- status_response = await client.get(status_check_url, headers=headers)
- status_response.raise_for_status()
- status_response_json = status_response.json()
- status = status_response_json.get("status")
-
- if status == "succeeded":
- return status_response_json["output"]
- elif status == "error":
- raise ValueError(
- f"Inference errored out: {status_response_json.get('error', 'Unknown error')}"
- )
- elif status == "failed":
- raise ValueError("Inference failed")
-
- raise TimeoutError("Inference timed out")
-
- except httpx.HTTPStatusError as e:
- raise ValueError(f"HTTP error occurred: {e}")
- except httpx.RequestError as e:
- raise ValueError(f"An error occurred while requesting: {e}")
- except asyncio.TimeoutError:
- raise TimeoutError("Request timed out")
- except Exception as e:
- raise ValueError(f"An unexpected error occurred: {e}")
+async def _poll_prediction(
+ client: httpx.AsyncClient, prediction_id: str, headers: dict[str, str]
+) -> dict[str, Any]:
+ status_check_url = f"{REPLICATE_API_BASE_URL}/predictions/{prediction_id}"
-async def call_replicate_version(
- version: str, input: dict[str, Any], api_token: str
-) -> Any:
- headers = {
- "Authorization": f"Bearer {api_token}",
- "Content-Type": "application/json",
- }
+ for _ in range(MAX_POLLS):
+ await asyncio.sleep(POLL_INTERVAL_SECONDS)
+ status_response = await client.get(status_check_url, headers=headers)
+ status_response.raise_for_status()
+ status_response_raw: Any = status_response.json()
+ if not isinstance(status_response_raw, dict):
+ raise ValueError("Invalid prediction status response.")
+ status_response_json = cast(dict[str, Any], status_response_raw)
+
+ status = status_response_json.get("status")
+ if status == "succeeded":
+ return cast(dict[str, Any], status_response_json)
+ if status == "error":
+ error_message = str(status_response_json.get("error", "Unknown error"))
+ raise ValueError(f"Inference errored out: {error_message}")
+ if status == "failed":
+ raise ValueError("Inference failed")
+
+ raise TimeoutError("Inference timed out")
- data = {"version": version, "input": input}
+
+async def _run_prediction(
+ endpoint_url: str, payload: dict[str, Any], api_token: str
+) -> Any:
+ headers = _build_headers(api_token)
async with httpx.AsyncClient() as client:
try:
- response = await client.post(
- "https://api.replicate.com/v1/predictions",
- headers=headers,
- json=data,
- )
+ response = await client.post(endpoint_url, headers=headers, json=payload)
response.raise_for_status()
response_json = response.json()
+ if not isinstance(response_json, dict):
+ raise ValueError("Invalid prediction creation response.")
+
+ prediction_id = _extract_prediction_id(response_json)
+ final_response = await _poll_prediction(client, prediction_id, headers)
+ return final_response.get("output")
+ except httpx.HTTPStatusError as exc:
+ raise ValueError(f"HTTP error occurred: {exc}") from exc
+ except httpx.RequestError as exc:
+ raise ValueError(f"An error occurred while requesting: {exc}") from exc
+ except asyncio.TimeoutError as exc:
+ raise TimeoutError("Request timed out") from exc
+ except (TimeoutError, ValueError):
+ raise
+ except Exception as exc:
+ raise ValueError(f"An unexpected error occurred: {exc}") from exc
+
+
+def _extract_output_url(result: Any, context: str) -> str:
+ if isinstance(result, str):
+ return result
+
+ if isinstance(result, dict):
+ url = cast(Any, result.get("url"))
+ if isinstance(url, str) and url:
+ return url
+
+ if isinstance(result, list) and len(result) > 0:
+ first: Any = result[0]
+ if isinstance(first, str) and first:
+ return first
+ if isinstance(first, Mapping):
+ url = cast(Any, first.get("url"))
+ if isinstance(url, str) and url:
+ return url
- prediction_id = response_json.get("id")
- if not prediction_id:
- raise ValueError("Prediction ID not found in initial response.")
-
- num_polls = 0
- max_polls = 100
- while num_polls < max_polls:
- num_polls += 1
-
- await asyncio.sleep(0.1)
-
- status_check_url = (
- f"https://api.replicate.com/v1/predictions/{prediction_id}"
- )
- status_response = await client.get(status_check_url, headers=headers)
- status_response.raise_for_status()
- status_response_json = status_response.json()
- status = status_response_json.get("status")
-
- if status == "succeeded":
- return status_response_json["output"]
- elif status == "error":
- raise ValueError(
- f"Inference errored out: {status_response_json.get('error', 'Unknown error')}"
- )
- elif status == "failed":
- raise ValueError("Inference failed")
-
- raise TimeoutError("Inference timed out")
-
- except httpx.HTTPStatusError as e:
- raise ValueError(f"HTTP error occurred: {e}")
- except httpx.RequestError as e:
- raise ValueError(f"An error occurred while requesting: {e}")
- except asyncio.TimeoutError:
- raise TimeoutError("Request timed out")
- except Exception as e:
- raise ValueError(f"An unexpected error occurred: {e}")
+ raise ValueError(f"Unexpected response from {context}: {result}")
+
+
+async def call_replicate_model(
+ model_path: str, input: dict[str, Any], api_token: str
+) -> Any:
+ return await _run_prediction(
+ f"{REPLICATE_API_BASE_URL}/models/{model_path}/predictions",
+ {"input": input},
+ api_token,
+ )
+
+
+async def call_replicate_version(
+ version: str, input: dict[str, Any], api_token: str
+) -> Any:
+ return await _run_prediction(
+ f"{REPLICATE_API_BASE_URL}/predictions",
+ {"version": version, "input": input},
+ api_token,
+ )
async def remove_background(image_url: str, api_token: str) -> str:
result = await call_replicate_version(
- "a029dff38972b5fda4ec5d75d7d1cd25aeff621d2cf4946a41055d7db66b80bc",
+ REMOVE_BACKGROUND_VERSION,
{
"image": image_url,
"format": "png",
@@ -135,74 +133,9 @@ async def remove_background(image_url: str, api_token: str) -> str:
},
api_token,
)
- # Handle different response formats
- if isinstance(result, str):
- return result
- if isinstance(result, dict) and "url" in result:
- return result["url"]
- if isinstance(result, list) and len(result) > 0:
- return result[0] if isinstance(result[0], str) else result[0].get("url", "")
- raise ValueError(f"Unexpected response from background remover: {result}")
+ return _extract_output_url(result, "background remover")
async def call_replicate(input: dict[str, str | int], api_token: str) -> str:
- headers = {
- "Authorization": f"Bearer {api_token}",
- "Content-Type": "application/json",
- }
-
- data = {"input": input}
-
- async with httpx.AsyncClient() as client:
- try:
- response = await client.post(
- "https://api.replicate.com/v1/models/black-forest-labs/flux-2-klein-4b/predictions",
- headers=headers,
- json=data,
- )
- response.raise_for_status()
- response_json = response.json()
-
- # Extract the id from the response
- prediction_id = response_json.get("id")
- if not prediction_id:
- raise ValueError("Prediction ID not found in initial response.")
-
- # Polling every 0.1 seconds until the status is succeeded or error (upto 10s)
- num_polls = 0
- max_polls = 100
- while num_polls < max_polls:
- num_polls += 1
-
- await asyncio.sleep(0.1)
-
- # Check the status
- status_check_url = (
- f"https://api.replicate.com/v1/predictions/{prediction_id}"
- )
- status_response = await client.get(status_check_url, headers=headers)
- status_response.raise_for_status()
- status_response_json = status_response.json()
- status = status_response_json.get("status")
-
- # If status is succeeded or if there's an error, break out of the loop
- if status == "succeeded":
- return status_response_json["output"][0]
- elif status == "error":
- raise ValueError(
- f"Inference errored out: {status_response_json.get('error', 'Unknown error')}"
- )
- elif status == "failed":
- raise ValueError("Inference failed")
-
- # If we've reached here, it means we've exceeded the max number of polls
- raise TimeoutError("Inference timed out")
-
- except httpx.HTTPStatusError as e:
- raise ValueError(f"HTTP error occurred: {e}")
- except httpx.RequestError as e:
- raise ValueError(f"An error occurred while requesting: {e}")
- except asyncio.TimeoutError:
- raise TimeoutError("Request timed out")
- except Exception as e:
- raise ValueError(f"An unexpected error occurred: {e}")
+ result = await call_replicate_model(FLUX_MODEL_PATH, input, api_token)
+ return _extract_output_url(result, "Flux prediction")
diff --git a/backend/prompts/__init__.py b/backend/prompts/__init__.py
index 330171d7..de508ad0 100644
--- a/backend/prompts/__init__.py
+++ b/backend/prompts/__init__.py
@@ -2,7 +2,6 @@ from typing import Union, Any, cast
from openai.types.chat import ChatCompletionMessageParam, ChatCompletionContentPartParam
from custom_types import InputMode
-from image_generation.core import create_alt_url_mapping
from prompts.imported_code_prompts import IMPORTED_CODE_SYSTEM_PROMPTS
from prompts.screenshot_system_prompts import SYSTEM_PROMPTS
from prompts.text_prompts import SYSTEM_PROMPTS as TEXT_SYSTEM_PROMPTS
@@ -29,9 +28,8 @@ async def create_prompt(
prompt: PromptContent,
history: list[dict[str, Any]],
is_imported_from_code: bool,
-) -> tuple[list[ChatCompletionMessageParam], dict[str, str]]:
+) -> list[ChatCompletionMessageParam]:
- image_cache: dict[str, str] = {}
prompt_messages: list[ChatCompletionMessageParam] = []
# If this generation started off with imported code, we need to assemble the prompt differently
@@ -85,9 +83,7 @@ async def create_prompt(
message = create_message_from_history_item(item, role)
prompt_messages.append(message)
- image_cache = create_alt_url_mapping(history[-2]["text"])
-
- return prompt_messages, image_cache
+ return prompt_messages
def create_message_from_history_item(
diff --git a/backend/routes/generate_code.py b/backend/routes/generate_code.py
index 4db9fc85..482d674a 100644
--- a/backend/routes/generate_code.py
+++ b/backend/routes/generate_code.py
@@ -479,7 +479,7 @@ class PromptCreationStage:
) -> List[ChatCompletionMessageParam]:
"""Create prompt messages"""
try:
- prompt_messages, _ = await create_prompt(
+ prompt_messages = await create_prompt(
stack=extracted_params.stack,
input_mode=extracted_params.input_mode,
generation_type=extracted_params.generation_type,
diff --git a/backend/run_image_generation_evals.py b/backend/run_image_generation_evals.py
index 49e1c43b..42161a3e 100644
--- a/backend/run_image_generation_evals.py
+++ b/backend/run_image_generation_evals.py
@@ -3,7 +3,7 @@ import os
from typing import List, Optional, Literal
from dotenv import load_dotenv
import aiohttp
-from image_generation.core import process_tasks
+from image_generation.generation import process_tasks
EVALS = [
"Romantic Background",
diff --git a/backend/tests/test_image_generation_replicate.py b/backend/tests/test_image_generation_replicate.py
new file mode 100644
index 00000000..469ebf67
--- /dev/null
+++ b/backend/tests/test_image_generation_replicate.py
@@ -0,0 +1,82 @@
+import pytest
+
+from image_generation import replicate
+
+
+def test_extract_output_url_from_string() -> None:
+ assert (
+ replicate._extract_output_url("https://example.com/image.png", "test")
+ == "https://example.com/image.png"
+ )
+
+
+def test_extract_output_url_from_dict() -> None:
+ assert (
+ replicate._extract_output_url({"url": "https://example.com/image.png"}, "test")
+ == "https://example.com/image.png"
+ )
+
+
+def test_extract_output_url_from_list() -> None:
+ assert (
+ replicate._extract_output_url(["https://example.com/image.png"], "test")
+ == "https://example.com/image.png"
+ )
+
+
+def test_extract_output_url_from_list_item_dict() -> None:
+ assert (
+ replicate._extract_output_url(
+ [{"url": "https://example.com/image.png"}], "test"
+ )
+ == "https://example.com/image.png"
+ )
+
+
+def test_extract_output_url_invalid_raises() -> None:
+ with pytest.raises(ValueError):
+ replicate._extract_output_url([], "test")
+
+
+async def test_call_replicate_uses_flux_model(monkeypatch: pytest.MonkeyPatch) -> None:
+ captured: dict[str, object] = {}
+
+ async def fake_call_replicate_model(
+ model_path: str, input: dict[str, object], api_token: str
+ ) -> list[str]:
+ captured["model_path"] = model_path
+ captured["input"] = input
+ captured["api_token"] = api_token
+ return ["https://example.com/flux.png"]
+
+ monkeypatch.setattr(replicate, "call_replicate_model", fake_call_replicate_model)
+
+ result = await replicate.call_replicate({"prompt": "test", "seed": 1}, "token-123")
+
+ assert result == "https://example.com/flux.png"
+ assert captured["model_path"] == replicate.FLUX_MODEL_PATH
+ assert captured["api_token"] == "token-123"
+
+
+async def test_remove_background_uses_version_and_normalizes_output(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ captured: dict[str, object] = {}
+
+ async def fake_call_replicate_version(
+ version: str, input: dict[str, object], api_token: str
+ ) -> dict[str, str]:
+ captured["version"] = version
+ captured["input"] = input
+ captured["api_token"] = api_token
+ return {"url": "https://example.com/no-bg.png"}
+
+ monkeypatch.setattr(replicate, "call_replicate_version", fake_call_replicate_version)
+
+ result = await replicate.remove_background("https://example.com/input.png", "token")
+
+ assert result == "https://example.com/no-bg.png"
+ assert captured["version"] == replicate.REMOVE_BACKGROUND_VERSION
+ assert captured["api_token"] == "token"
diff --git a/backend/tests/test_prompts.py b/backend/tests/test_prompts.py
index f009182b..96ee8e31 100644
--- a/backend/tests/test_prompts.py
+++ b/backend/tests/test_prompts.py
@@ -14,7 +14,6 @@ from prompts.types import Stack
# Type definitions for test structures
class ExpectedResult(TypedDict):
messages: List[ChatCompletionMessageParam]
- image_cache: Dict[str, str]
def assert_structure_match(actual: object, expected: object, path: str = "") -> None:
@@ -97,7 +96,7 @@ class TestCreatePrompt:
with patch("prompts.SYSTEM_PROMPTS", mock_system_prompts):
# Call the function
- messages, image_cache = await create_prompt(
+ messages = await create_prompt(
stack=self.TEST_STACK,
input_mode="image",
generation_type=params["generationType"],
@@ -127,11 +126,10 @@ class TestCreatePrompt:
],
},
],
- "image_cache": {},
}
# Assert the structure matches
- actual: ExpectedResult = {"messages": messages, "image_cache": image_cache}
+ actual: ExpectedResult = {"messages": messages}
assert_structure_match(actual, expected)
@@ -153,11 +151,9 @@ class TestCreatePrompt:
# Mock the system prompts and image cache function
mock_system_prompts = {self.TEST_STACK: self.MOCK_SYSTEM_PROMPT}
- with patch("prompts.SYSTEM_PROMPTS", mock_system_prompts), patch(
- "prompts.create_alt_url_mapping", return_value={"mock": "cache"}
- ):
+ with patch("prompts.SYSTEM_PROMPTS", mock_system_prompts):
# Call the function
- messages, image_cache = await create_prompt(
+ messages = await create_prompt(
stack=self.TEST_STACK,
input_mode="image",
generation_type=params["generationType"],
@@ -191,11 +187,10 @@ class TestCreatePrompt:
{"role": "assistant", "content": "<html>Updated code</html>"},
{"role": "user", "content": "Add a header"},
],
- "image_cache": {"mock": "cache"},
}
# Assert the structure matches
- actual: ExpectedResult = {"messages": messages, "image_cache": image_cache}
+ actual: ExpectedResult = {"messages": messages}
assert_structure_match(actual, expected)
@pytest.mark.asyncio
@@ -218,7 +213,7 @@ class TestCreatePrompt:
with patch('prompts.TEXT_SYSTEM_PROMPTS', mock_text_system_prompts):
# Call the function
- messages, image_cache = await create_prompt(
+ messages = await create_prompt(
stack=self.TEST_STACK,
input_mode="text",
generation_type=params["generationType"],
@@ -239,11 +234,10 @@ class TestCreatePrompt:
"content": f"Generate UI for {text_description}"
}
],
- "image_cache": {}
}
# Assert the structure matches
- actual: ExpectedResult = {"messages": messages, "image_cache": image_cache}
+ actual: ExpectedResult = {"messages": messages}
assert_structure_match(actual, expected)
@pytest.mark.asyncio
@@ -270,10 +264,9 @@ class TestCreatePrompt:
self.TEST_STACK: "Mock Text System Prompt"
}
- with patch('prompts.TEXT_SYSTEM_PROMPTS', mock_text_system_prompts), \
- patch('prompts.create_alt_url_mapping', return_value={"text": "cache"}):
+ with patch('prompts.TEXT_SYSTEM_PROMPTS', mock_text_system_prompts):
# Call the function
- messages, image_cache = await create_prompt(
+ messages = await create_prompt(
stack=self.TEST_STACK,
input_mode="text",
generation_type=params["generationType"],
@@ -310,11 +303,10 @@ class TestCreatePrompt:
"content": "Now add a navigation menu"
}
],
- "image_cache": {"text": "cache"}
}
# Assert the structure matches
- actual: ExpectedResult = {"messages": messages, "image_cache": image_cache}
+ actual: ExpectedResult = {"messages": messages}
assert_structure_match(actual, expected)
@pytest.mark.asyncio
@@ -336,7 +328,7 @@ class TestCreatePrompt:
}
# Call the function
- messages, image_cache = await create_prompt(
+ messages = await create_prompt(
stack=self.TEST_STACK,
input_mode="video",
generation_type=params["generationType"],
@@ -365,11 +357,10 @@ class TestCreatePrompt:
],
},
],
- "image_cache": {}
}
# Assert the structure matches
- actual: ExpectedResult = {"messages": messages, "image_cache": image_cache}
+ actual: ExpectedResult = {"messages": messages}
assert_structure_match(actual, expected)
@@ -391,10 +382,9 @@ class TestCreatePrompt:
# Mock the system prompts and image cache function
mock_system_prompts: Dict[str, str] = {self.TEST_STACK: self.MOCK_SYSTEM_PROMPT}
- with patch("prompts.SYSTEM_PROMPTS", mock_system_prompts), \
- patch("prompts.create_alt_url_mapping", return_value={"mock": "cache"}):
+ with patch("prompts.SYSTEM_PROMPTS", mock_system_prompts):
# Call the function
- messages, image_cache = await create_prompt(
+ messages = await create_prompt(
stack=self.TEST_STACK,
input_mode="image",
generation_type=params["generationType"],
@@ -442,11 +432,10 @@ class TestCreatePrompt:
},
{"role": "assistant", "content": "<html>Code with button</html>"},
],
- "image_cache": {"mock": "cache"},
}
# Assert the structure matches
- actual: ExpectedResult = {"messages": messages, "image_cache": image_cache}
+ actual: ExpectedResult = {"messages": messages}
assert_structure_match(actual, expected)
@pytest.mark.asyncio
@@ -468,10 +457,9 @@ class TestCreatePrompt:
# Mock the system prompts and image cache function
mock_system_prompts: Dict[str, str] = {self.TEST_STACK: self.MOCK_SYSTEM_PROMPT}
- with patch("prompts.SYSTEM_PROMPTS", mock_system_prompts), \
- patch("prompts.create_alt_url_mapping", return_value={"mock": "cache"}):
+ with patch("prompts.SYSTEM_PROMPTS", mock_system_prompts):
# Call the function
- messages, image_cache = await create_prompt(
+ messages = await create_prompt(
stack=self.TEST_STACK,
input_mode="image",
generation_type=params["generationType"],
@@ -526,11 +514,10 @@ class TestCreatePrompt:
},
{"role": "assistant", "content": "<html>Styled code</html>"},
],
- "image_cache": {"mock": "cache"},
}
# Assert the structure matches
- actual: ExpectedResult = {"messages": messages, "image_cache": image_cache}
+ actual: ExpectedResult = {"messages": messages}
assert_structure_match(actual, expected)
@pytest.mark.asyncio
@@ -550,10 +537,9 @@ class TestCreatePrompt:
# Mock the system prompts and image cache function
mock_system_prompts: Dict[str, str] = {self.TEST_STACK: self.MOCK_SYSTEM_PROMPT}
- with patch("prompts.SYSTEM_PROMPTS", mock_system_prompts), \
- patch("prompts.create_alt_url_mapping", return_value={}):
+ with patch("prompts.SYSTEM_PROMPTS", mock_system_prompts):
# Call the function
- messages, image_cache = await create_prompt(
+ messages = await create_prompt(
stack=self.TEST_STACK,
input_mode="image",
generation_type=params["generationType"],
@@ -586,11 +572,10 @@ class TestCreatePrompt:
{"role": "user", "content": "Make it blue"}, # Text-only message
{"role": "assistant", "content": "<html>Blue code</html>"},
],
- "image_cache": {},
}
# Assert the structure matches
- actual: ExpectedResult = {"messages": messages, "image_cache": image_cache}
+ actual: ExpectedResult = {"messages": messages}
assert_structure_match(actual, expected)
@pytest.mark.asyncio
@@ -615,7 +600,7 @@ class TestCreatePrompt:
with patch("prompts.IMPORTED_CODE_SYSTEM_PROMPTS", mock_imported_prompts):
# Call the function
- messages, image_cache = await create_prompt(
+ messages = await create_prompt(
stack=self.TEST_STACK,
input_mode="image",
generation_type=params["generationType"],
@@ -649,9 +634,8 @@ class TestCreatePrompt:
},
{"role": "assistant", "content": "<html>Updated code</html>"},
],
- "image_cache": {},
}
# Assert the structure matches
- actual: ExpectedResult = {"messages": messages, "image_cache": image_cache}
+ actual: ExpectedResult = {"messages": messages}
assert_structure_match(actual, expected)
diff --git a/backend/tests/test_prompts_additional.py b/backend/tests/test_prompts_additional.py
index d17af147..f5a25e57 100644
--- a/backend/tests/test_prompts_additional.py
+++ b/backend/tests/test_prompts_additional.py
@@ -14,7 +14,6 @@ from prompts.types import Stack
# Type definitions for test structures
class ExpectedResult(TypedDict):
messages: List[ChatCompletionMessageParam]
- image_cache: Dict[str, str]
def assert_structure_match(actual: object, expected: object, path: str = "") -> None:
@@ -101,10 +100,9 @@ class TestCreatePromptImageSupport:
# Mock the system prompts and image cache function
mock_system_prompts: Dict[str, str] = {self.TEST_STACK: self.MOCK_SYSTEM_PROMPT}
- with patch("prompts.SYSTEM_PROMPTS", mock_system_prompts), \
- patch("prompts.create_alt_url_mapping", return_value={"mock": "cache"}):
+ with patch("prompts.SYSTEM_PROMPTS", mock_system_prompts):
# Call the function
- messages, image_cache = await create_prompt(
+ messages = await create_prompt(
stack=self.TEST_STACK,
input_mode="image",
generation_type=params["generationType"],
@@ -159,11 +157,10 @@ class TestCreatePromptImageSupport:
},
{"role": "assistant", "content": "<html>Styled code</html>"},
],
- "image_cache": {"mock": "cache"},
}
# Assert the structure matches
- actual: ExpectedResult = {"messages": messages, "image_cache": image_cache}
+ actual: ExpectedResult = {"messages": messages}
assert_structure_match(actual, expected)
@pytest.mark.asyncio
@@ -183,10 +180,9 @@ class TestCreatePromptImageSupport:
# Mock the system prompts and image cache function
mock_system_prompts: Dict[str, str] = {self.TEST_STACK: self.MOCK_SYSTEM_PROMPT}
- with patch("prompts.SYSTEM_PROMPTS", mock_system_prompts), \
- patch("prompts.create_alt_url_mapping", return_value={}):
+ with patch("prompts.SYSTEM_PROMPTS", mock_system_prompts):
# Call the function
- messages, image_cache = await create_prompt(
+ messages = await create_prompt(
stack=self.TEST_STACK,
input_mode="image",
generation_type=params["generationType"],
@@ -219,11 +215,10 @@ class TestCreatePromptImageSupport:
{"role": "user", "content": "Make it blue"}, # Text-only message
{"role": "assistant", "content": "<html>Blue code</html>"},
],
- "image_cache": {},
}
# Assert the structure matches
- actual: ExpectedResult = {"messages": messages, "image_cache": image_cache}
+ actual: ExpectedResult = {"messages": messages}
assert_structure_match(actual, expected)
@pytest.mark.asyncio
@@ -248,7 +243,7 @@ class TestCreatePromptImageSupport:
with patch("prompts.IMPORTED_CODE_SYSTEM_PROMPTS", mock_imported_prompts):
# Call the function
- messages, image_cache = await create_prompt(
+ messages = await create_prompt(
stack=self.TEST_STACK,
input_mode="image",
generation_type=params["generationType"],
@@ -282,9 +277,8 @@ class TestCreatePromptImageSupport:
},
{"role": "assistant", "content": "<html>Updated code</html>"},
],
- "image_cache": {},
}
# Assert the structure matches
- actual: ExpectedResult = {"messages": messages, "image_cache": image_cache}
+ actual: ExpectedResult = {"messages": messages}
assert_structure_match(actual, expected)