Skip to content

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

Python

Complete remaining agentic runner refactor cleanup

Abi Raja6a95f0c5b618
diff --git a/backend/agentic/runner.py b/backend/agentic/runner.py
index 5ac5f45c..af8e95d0 100644
--- a/backend/agentic/runner.py
+++ b/backend/agentic/runner.py
@@ -11,7 +11,6 @@ from codegen.utils import extract_html_content
from llm import (
ANTHROPIC_MODELS,
GEMINI_MODELS,
- OPENAI_CODEX_MODELS,
OPENAI_MODELS,
Llm,
)
@@ -21,7 +20,6 @@ from agentic.streaming import (
AnthropicAdapter,
ExecutedToolCall,
GeminiAdapter,
- OpenAIChatAdapter,
OpenAIResponsesAdapter,
ProviderAdapter,
StreamEvent,
@@ -33,7 +31,6 @@ from agentic.tools import (
extract_path_from_args,
serialize_anthropic_tools,
serialize_gemini_tools,
- serialize_openai_chat_tools,
serialize_openai_responses_tools,
summarize_text,
summarize_tool_input,
@@ -53,7 +50,6 @@ class AgenticRunner:
anthropic_api_key: Optional[str],
gemini_api_key: Optional[str],
should_generate_images: bool,
- image_cache: Dict[str, str],
initial_file_state: Optional[Dict[str, str]] = None,
option_codes: Optional[List[str]] = None,
):
@@ -71,7 +67,6 @@ class AgenticRunner:
self.toolbox = AgentToolbox(
self.file_state,
- image_cache,
should_generate_images,
openai_api_key,
openai_base_url,
@@ -270,22 +265,13 @@ class AgenticRunner:
canonical_tools = canonical_tool_definitions()
try:
- if model in OPENAI_CODEX_MODELS:
- tools = serialize_openai_responses_tools(canonical_tools)
- adapter: ProviderAdapter = OpenAIResponsesAdapter(
- client=client,
- model=model,
- prompt_messages=prompt_messages,
- tools=tools,
- )
- else:
- tools = serialize_openai_chat_tools(canonical_tools)
- adapter = OpenAIChatAdapter(
- client=client,
- model=model,
- prompt_messages=prompt_messages,
- tools=tools,
- )
+ tools = serialize_openai_responses_tools(canonical_tools)
+ adapter: ProviderAdapter = OpenAIResponsesAdapter(
+ client=client,
+ model=model,
+ prompt_messages=prompt_messages,
+ tools=tools,
+ )
return await self._run_with_adapter(adapter)
finally:
await client.close()
diff --git a/backend/agentic/streaming/__init__.py b/backend/agentic/streaming/__init__.py
index 42dfac00..755a2ce1 100644
--- a/backend/agentic/streaming/__init__.py
+++ b/backend/agentic/streaming/__init__.py
@@ -1,7 +1,6 @@
from agentic.streaming.anthropic import AnthropicAdapter
from agentic.streaming.base import ProviderAdapter
from agentic.streaming.gemini import GeminiAdapter
-from agentic.streaming.openai_chat import OpenAIChatAdapter
from agentic.streaming.openai_responses import OpenAIResponsesAdapter
from agentic.streaming.types import EventSink, ExecutedToolCall, StepResult, StreamEvent
@@ -9,7 +8,6 @@ __all__ = [
"AnthropicAdapter",
"ProviderAdapter",
"GeminiAdapter",
- "OpenAIChatAdapter",
"OpenAIResponsesAdapter",
"EventSink",
"ExecutedToolCall",
diff --git a/backend/agentic/streaming/openai_chat.py b/backend/agentic/streaming/openai_chat.py
deleted file mode 100644
index 41c01001..00000000
--- a/backend/agentic/streaming/openai_chat.py
+++ /dev/null
@@ -1,138 +0,0 @@
-# pyright: reportUnknownVariableType=false
-import json
-import uuid
-from typing import Any, Dict, List
-
-from openai import AsyncOpenAI
-from openai.types.chat import ChatCompletionChunk, ChatCompletionMessageParam
-
-from agentic.streaming.types import EventSink, ExecutedToolCall, StepResult, StreamEvent
-from agentic.tools import ToolCall, parse_json_arguments
-from llm import Llm, get_openai_api_name
-
-
-class OpenAIChatAdapter:
- def __init__(
- self,
- client: AsyncOpenAI,
- model: Llm,
- prompt_messages: List[ChatCompletionMessageParam],
- tools: List[Dict[str, Any]],
- ):
- self._client = client
- self._model = model
- self._tools = tools
- self._messages: List[Dict[str, Any]] = [dict(m) for m in prompt_messages]
-
- async def run_step(self, on_event: EventSink) -> StepResult:
- assistant_text = ""
- tool_calls: Dict[int, Dict[str, Any]] = {}
-
- params: Dict[str, Any] = {
- "model": get_openai_api_name(self._model),
- "messages": self._messages,
- "tools": self._tools,
- "tool_choice": "auto",
- "temperature": 0,
- "stream": True,
- "max_tokens": 30000,
- }
-
- stream = await self._client.chat.completions.create(**params)
-
- async for chunk in stream: # type: ignore
- assert isinstance(chunk, ChatCompletionChunk)
- if not chunk.choices:
- continue
-
- delta = chunk.choices[0].delta
- if delta.content:
- assistant_text += delta.content
- await on_event(StreamEvent(type="assistant_delta", text=delta.content))
-
- if not delta.tool_calls:
- continue
-
- for tc in delta.tool_calls:
- idx = tc.index or 0
- entry = tool_calls.setdefault(
- idx,
- {
- "id": tc.id or f"tool-{idx}-{uuid.uuid4().hex[:6]}",
- "name": None,
- "arguments": "",
- },
- )
- if tc.id:
- entry["id"] = tc.id
- if tc.function and tc.function.name:
- entry["name"] = tc.function.name
- if tc.function and tc.function.arguments:
- entry["arguments"] += tc.function.arguments
- await on_event(
- StreamEvent(
- type="tool_call_delta",
- tool_call_id=entry["id"],
- tool_name=entry.get("name"),
- tool_arguments=entry.get("arguments"),
- )
- )
-
- tool_call_list: List[ToolCall] = []
- for entry in tool_calls.values():
- args, error = parse_json_arguments(entry.get("arguments"))
- if error:
- args = {"_raw": entry.get("arguments")}
- tool_call_id = entry.get("id") or f"tool-{uuid.uuid4().hex[:6]}"
- tool_call_list.append(
- ToolCall(
- id=tool_call_id,
- name=entry.get("name") or "unknown_tool",
- arguments=args,
- )
- )
-
- provider_state = None
- if tool_call_list:
- provider_state = {
- "assistant_message": {
- "role": "assistant",
- "content": assistant_text or None,
- "tool_calls": [
- {
- "id": tc.id,
- "type": "function",
- "function": {
- "name": tc.name,
- "arguments": json.dumps(tc.arguments),
- },
- }
- for tc in tool_call_list
- ],
- }
- }
-
- return StepResult(
- assistant_text=assistant_text,
- tool_calls=tool_call_list,
- provider_state=provider_state,
- )
-
- def apply_tool_results(
- self,
- step_result: StepResult,
- executed_tool_calls: list[ExecutedToolCall],
- ) -> None:
- provider_state = step_result.provider_state or {}
- assistant_message = provider_state.get("assistant_message")
- if assistant_message:
- self._messages.append(assistant_message)
-
- for executed in executed_tool_calls:
- self._messages.append(
- {
- "role": "tool",
- "tool_call_id": executed.tool_call.id,
- "content": json.dumps(executed.result.result),
- }
- )
diff --git a/backend/agentic/tools.py b/backend/agentic/tools.py
index cadccc92..cfede107 100644
--- a/backend/agentic/tools.py
+++ b/backend/agentic/tools.py
@@ -279,22 +279,6 @@ def _copy_schema(schema: Dict[str, Any]) -> Dict[str, Any]:
return copy.deepcopy(schema)
-def serialize_openai_chat_tools(
- tools: List[CanonicalToolDefinition],
-) -> List[Dict[str, Any]]:
- return [
- {
- "type": "function",
- "function": {
- "name": tool.name,
- "description": tool.description,
- "parameters": _copy_schema(tool.parameters),
- },
- }
- for tool in tools
- ]
-
-
def _nullable_type(type_value: Any) -> Any:
if isinstance(type_value, list):
if "null" not in type_value:
@@ -441,14 +425,12 @@ class AgentToolbox:
def __init__(
self,
file_state: AgentFileState,
- image_cache: Dict[str, str],
should_generate_images: bool,
openai_api_key: Optional[str],
openai_base_url: Optional[str],
option_codes: Optional[List[str]] = None,
):
self.file_state = file_state
- self.image_cache = image_cache
self.should_generate_images = should_generate_images
self.openai_api_key = openai_api_key
self.openai_base_url = openai_base_url
@@ -616,40 +598,25 @@ class AgentToolbox:
result={"error": "No valid prompts provided"},
summary={"error": "No valid prompts"},
)
+ if REPLICATE_API_KEY:
+ model = "flux"
+ api_key = REPLICATE_API_KEY
+ base_url = None
+ else:
+ if not self.openai_api_key:
+ return ToolExecutionResult(
+ ok=False,
+ result={"error": "No API key available for image generation."},
+ summary={"error": "Missing image generation API key"},
+ )
+ model = "dalle3"
+ api_key = self.openai_api_key
+ base_url = self.openai_base_url
- cached_results: Dict[str, Optional[str]] = {}
- to_generate: List[str] = []
- for prompt in unique_prompts:
- if prompt in self.image_cache:
- cached_results[prompt] = self.image_cache[prompt]
- else:
- to_generate.append(prompt)
-
- generated_results: Dict[str, Optional[str]] = {}
-
- if to_generate:
- if REPLICATE_API_KEY:
- model = "flux"
- api_key = REPLICATE_API_KEY
- base_url = None
- else:
- if not self.openai_api_key:
- return ToolExecutionResult(
- ok=False,
- result={"error": "No API key available for image generation."},
- summary={"error": "Missing image generation API key"},
- )
- model = "dalle3"
- api_key = self.openai_api_key
- base_url = self.openai_base_url
-
- generated = await process_tasks(to_generate, api_key, base_url, model) # type: ignore
- for prompt, url in zip(to_generate, generated):
- generated_results[prompt] = url
- if url:
- self.image_cache[prompt] = url
-
- merged_results = {**cached_results, **generated_results}
+ generated = await process_tasks(unique_prompts, api_key, base_url, model) # type: ignore
+ merged_results = {
+ prompt: url for prompt, url in zip(unique_prompts, generated)
+ }
summary_items = [
{
"prompt": summarize_text(prompt, 160),
diff --git a/backend/evals/core.py b/backend/evals/core.py
index 0c7a397d..0f0e0668 100644
--- a/backend/evals/core.py
+++ b/backend/evals/core.py
@@ -56,7 +56,6 @@ async def generate_code_core(
anthropic_api_key=ANTHROPIC_API_KEY,
gemini_api_key=GEMINI_API_KEY,
should_generate_images=True,
- image_cache={},
initial_file_state=None,
option_codes=None,
)
diff --git a/backend/llm.py b/backend/llm.py
index 56be6624..03160793 100644
--- a/backend/llm.py
+++ b/backend/llm.py
@@ -61,9 +61,3 @@ def get_openai_api_name(model: Llm) -> str:
def get_openai_reasoning_effort(model: Llm) -> str | None:
return OPENAI_MODEL_CONFIG.get(model, {}).get("reasoning_effort")
-
-
-OPENAI_CODEX_MODELS = {
- Llm.GPT_5_2_CODEX_MEDIUM,
- Llm.GPT_5_2_CODEX_HIGH,
-}
diff --git a/backend/models/openai_client.py b/backend/models/openai_client.py
index f40e51fa..e5de718f 100644
--- a/backend/models/openai_client.py
+++ b/backend/models/openai_client.py
@@ -1,8 +1,8 @@
import time
from typing import Awaitable, Callable, List, Any, Dict
from openai import AsyncOpenAI
-from openai.types.chat import ChatCompletionMessageParam, ChatCompletionChunk
-from llm import Completion, Llm, get_openai_api_name, get_openai_reasoning_effort, OPENAI_CODEX_MODELS
+from openai.types.chat import ChatCompletionMessageParam
+from llm import Completion, Llm, get_openai_api_name, get_openai_reasoning_effort
def _convert_message_to_responses_input(
@@ -45,60 +45,35 @@ async def stream_openai_response(
client = AsyncOpenAI(api_key=api_key, base_url=base_url)
full_response = ""
- if model in OPENAI_CODEX_MODELS:
- input_items = [_convert_message_to_responses_input(msg) for msg in messages]
- reasoning_effort = get_openai_reasoning_effort(model)
- params: Dict[str, Any] = {
- "model": get_openai_api_name(model),
- "input": input_items,
- "stream": True,
- "max_output_tokens": 30000,
- }
- if reasoning_effort:
- params["reasoning"] = {"effort": reasoning_effort}
+ input_items = [_convert_message_to_responses_input(msg) for msg in messages]
+ reasoning_effort = get_openai_reasoning_effort(model)
+ params: Dict[str, Any] = {
+ "model": get_openai_api_name(model),
+ "input": input_items,
+ "stream": True,
+ "max_output_tokens": 30000,
+ }
+ if reasoning_effort:
+ params["reasoning"] = {"effort": reasoning_effort}
- responses_client = getattr(client, "responses", None)
- if responses_client is None:
- raise Exception(
- "OpenAI SDK is too old for GPT-5.2 Codex. Please upgrade the 'openai' package to a version that supports the Responses API."
- )
- stream = await responses_client.create(**params) # type: ignore
- async for event in stream: # type: ignore
- event_type = getattr(event, "type", None)
- if event_type is None and isinstance(event, dict):
- event_type = event.get("type")
- if event_type == "response.output_text.delta":
- delta = getattr(event, "delta", None)
- if delta is None and isinstance(event, dict):
- delta = event.get("delta", "")
- if not delta:
- continue
- full_response += delta
- await callback(delta)
- else:
- # Base parameters
- params = {
- "model": get_openai_api_name(model),
- "messages": messages,
- "timeout": 600,
- }
-
- params["temperature"] = 0
- params["stream"] = True
- params["max_tokens"] = 30000
-
- stream = await client.chat.completions.create(**params) # type: ignore
- async for chunk in stream: # type: ignore
- assert isinstance(chunk, ChatCompletionChunk)
- if (
- chunk.choices
- and len(chunk.choices) > 0
- and chunk.choices[0].delta
- and chunk.choices[0].delta.content
- ):
- content = chunk.choices[0].delta.content or ""
- full_response += content
- await callback(content)
+ responses_client = getattr(client, "responses", None)
+ if responses_client is None:
+ raise Exception(
+ "OpenAI SDK is too old for GPT-5.2 Codex. Please upgrade the 'openai' package to a version that supports the Responses API."
+ )
+ stream = await responses_client.create(**params) # type: ignore
+ async for event in stream: # type: ignore
+ event_type = getattr(event, "type", None)
+ if event_type is None and isinstance(event, dict):
+ event_type = event.get("type")
+ if event_type == "response.output_text.delta":
+ delta = getattr(event, "delta", None)
+ if delta is None and isinstance(event, dict):
+ delta = event.get("delta", "")
+ if not delta:
+ continue
+ full_response += delta
+ await callback(delta)
await client.close()
diff --git a/backend/routes/generate_code.py b/backend/routes/generate_code.py
index c212b7e1..0bbf931a 100644
--- a/backend/routes/generate_code.py
+++ b/backend/routes/generate_code.py
@@ -71,10 +71,9 @@ class PipelineContext:
websocket: WebSocket
ws_comm: "WebSocketCommunicator | None" = None
- params: Dict[str, str] = field(default_factory=dict)
+ params: Dict[str, Any] = field(default_factory=dict)
extracted_params: "ExtractedParams | None" = None
prompt_messages: List[ChatCompletionMessageParam] = field(default_factory=list)
- image_cache: Dict[str, str] = field(default_factory=dict)
variant_models: List[Llm] = field(default_factory=list)
completions: List[str] = field(default_factory=list)
variant_completions: Dict[int, str] = field(default_factory=dict)
@@ -198,9 +197,9 @@ class WebSocketCommunicator:
print("WebSocket already closed by client")
self.is_closed = True
- async def receive_params(self) -> Dict[str, str]:
+ async def receive_params(self) -> Dict[str, Any]:
"""Receive parameters from the client"""
- params: Dict[str, str] = await self.websocket.receive_json()
+ params: Dict[str, Any] = await self.websocket.receive_json()
print("Received params")
return params
@@ -236,7 +235,7 @@ class ParameterExtractionStage:
def __init__(self, throw_error: Callable[[str], Coroutine[Any, Any, None]]):
self.throw_error = throw_error
- async def extract_and_validate(self, params: Dict[str, str]) -> ExtractedParams:
+ async def extract_and_validate(self, params: Dict[str, Any]) -> ExtractedParams:
"""Extract and validate all parameters from the request"""
# Read the code config settings (stack) from the request.
generated_code_config = params.get("generatedCodeConfig", "")
@@ -284,13 +283,28 @@ class ParameterExtractionStage:
generation_type = cast(Literal["create", "update"], generation_type)
# Extract prompt content
- prompt = params.get("prompt", {"text": "", "images": []})
+ prompt: PromptContent = {"text": "", "images": []}
+ raw_prompt = params.get("prompt")
+ if isinstance(raw_prompt, dict):
+ text = raw_prompt.get("text")
+ images = raw_prompt.get("images")
+ prompt = {
+ "text": text if isinstance(text, str) else "",
+ "images": [img for img in images if isinstance(img, str)]
+ if isinstance(images, list)
+ else [],
+ }
# Extract history (default to empty list)
- history = params.get("history", [])
+ history: List[Dict[str, Any]] = []
+ raw_history = params.get("history")
+ if isinstance(raw_history, list):
+ for item in raw_history:
+ if isinstance(item, dict):
+ history.append(item)
# Extract imported code flag
- is_imported_from_code = params.get("isImportedFromCode", False)
+ is_imported_from_code = bool(params.get("isImportedFromCode", False))
# Extract file state for agentic edits
raw_file_state = params.get("fileState")
@@ -328,7 +342,7 @@ class ParameterExtractionStage:
)
def _get_from_settings_dialog_or_env(
- self, params: dict[str, str], key: str, env_var: str | None
+ self, params: dict[str, Any], key: str, env_var: str | None
) -> str | None:
"""Get value from client settings or environment variable"""
value = params.get(key)
@@ -462,10 +476,10 @@ class PromptCreationStage:
async def create_prompt(
self,
extracted_params: ExtractedParams,
- ) -> tuple[List[ChatCompletionMessageParam], Dict[str, str]]:
- """Create prompt messages and return image cache"""
+ ) -> List[ChatCompletionMessageParam]:
+ """Create prompt messages"""
try:
- prompt_messages, image_cache = await create_prompt(
+ prompt_messages, _ = await create_prompt(
stack=extracted_params.stack,
input_mode=extracted_params.input_mode,
generation_type=extracted_params.generation_type,
@@ -476,7 +490,7 @@ class PromptCreationStage:
print_prompt_summary(prompt_messages, truncate=False)
- return prompt_messages, image_cache
+ return prompt_messages
except Exception:
await self.throw_error(
"Error assembling prompt. Contact support at [email protected]"
@@ -503,7 +517,7 @@ class MockResponseStage:
"""Generate mock response for testing"""
async def process_chunk(content: str, variantIndex: int):
- await self.send_message("chunk", content, variantIndex)
+ await self.send_message("chunk", content, variantIndex, None, None)
completion_results = [
await mock_completion(process_chunk, input_mode=input_mode)
@@ -511,8 +525,14 @@ class MockResponseStage:
completions = [result["code"] for result in completion_results]
# Send the complete variant back to the client
- await self.send_message("setCode", completions[0], 0)
- await self.send_message("variantComplete", "Variant generation complete", 0)
+ await self.send_message("setCode", completions[0], 0, None, None)
+ await self.send_message(
+ "variantComplete",
+ "Variant generation complete",
+ 0,
+ None,
+ None,
+ )
return completions
@@ -553,7 +573,6 @@ class AgenticGenerationStage:
anthropic_api_key: str | None,
gemini_api_key: str | None,
should_generate_images: bool,
- image_cache: Dict[str, str],
file_state: Dict[str, str] | None,
option_codes: List[str] | None,
):
@@ -563,7 +582,6 @@ class AgenticGenerationStage:
self.anthropic_api_key = anthropic_api_key
self.gemini_api_key = gemini_api_key
self.should_generate_images = should_generate_images
- self.image_cache = image_cache
self.file_state = file_state
self.option_codes = option_codes or []
@@ -598,15 +616,29 @@ class AgenticGenerationStage:
prompt_messages: List[ChatCompletionMessageParam],
) -> str:
try:
+ async def send_runner_message(
+ type: str,
+ value: str | None,
+ variant_index: int,
+ data: Dict[str, Any] | None,
+ event_id: str | None,
+ ) -> None:
+ await self.send_message(
+ cast(MessageType, type),
+ value,
+ variant_index,
+ data,
+ event_id,
+ )
+
runner = AgenticRunner(
- send_message=self.send_message,
+ send_message=send_runner_message,
variant_index=index,
openai_api_key=self.openai_api_key,
openai_base_url=self.openai_base_url,
anthropic_api_key=self.anthropic_api_key,
gemini_api_key=self.gemini_api_key,
should_generate_images=self.should_generate_images,
- image_cache=self.image_cache,
initial_file_state=self.file_state,
option_codes=self.option_codes,
)
@@ -743,16 +775,17 @@ class PromptCreationMiddleware(Middleware):
) -> None:
prompt_creator = PromptCreationStage(context.throw_error)
assert context.extracted_params is not None
- context.prompt_messages, context.image_cache = (
- await prompt_creator.create_prompt(
- context.extracted_params,
- )
+ context.prompt_messages = await prompt_creator.create_prompt(
+ context.extracted_params,
)
- if context.prompt_messages and context.prompt_messages[0].get("content"):
- context.prompt_messages[0]["content"] = apply_tool_instructions(
- str(context.prompt_messages[0]["content"]),
- context.extracted_params.should_generate_images,
- )
+ if context.prompt_messages:
+ first_message = cast(Dict[str, Any], context.prompt_messages[0])
+ first_content = first_message.get("content")
+ if first_content:
+ first_message["content"] = apply_tool_instructions(
+ str(first_content),
+ context.extracted_params.should_generate_images,
+ )
await next_func()
@@ -798,7 +831,6 @@ class CodeGenerationMiddleware(Middleware):
anthropic_api_key=context.extracted_params.anthropic_api_key,
gemini_api_key=GEMINI_API_KEY,
should_generate_images=context.extracted_params.should_generate_images,
- image_cache=context.image_cache,
file_state=context.extracted_params.file_state,
option_codes=context.extracted_params.option_codes,
)