Skip to content

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

Python

support more variants

Abi Raja2956f2009b63
diff --git a/VARIANT_EXPANSION_PLAN.md b/VARIANT_EXPANSION_PLAN.md
index e653e9e8..78c24915 100644
--- a/VARIANT_EXPANSION_PLAN.md
+++ b/VARIANT_EXPANSION_PLAN.md
@@ -228,4 +228,7 @@ const baseCommitObject = {
## Abi's Notes
-- Let's set up a number of models that we want. And it will just cycle through those and repeat them. If models are [A, B], then if num = 5, it will be [A, B, A, B, A] and so on.
+- [DONE] Let's set up a number of models that we want. And it will just cycle through those and repeat them. If models are [A, B], then if num = 5, it will be [A, B, A, B, A] and so on.
+
+1. With 3 options, it looks too squished on the front-end.
+2. We need to change hotkey to Option + 1, 2, 3, etc because when focused on textbox, the 1, 2, 3 keys are captured by the textbox.
diff --git a/backend/config.py b/backend/config.py
index f742e70f..6fecd05b 100644
--- a/backend/config.py
+++ b/backend/config.py
@@ -3,7 +3,7 @@
# TODO: Should only be set to true when value is 'True', not any abitrary truthy value
import os
-NUM_VARIANTS = 2
+NUM_VARIANTS = 3
# LLM-related
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", None)
diff --git a/backend/routes/generate_code.py b/backend/routes/generate_code.py
index 29f663fa..5fb04f99 100644
--- a/backend/routes/generate_code.py
+++ b/backend/routes/generate_code.py
@@ -40,7 +40,13 @@ from openai.types.chat import ChatCompletionMessageParam
# WebSocket message types
MessageType = Literal[
- "chunk", "status", "setCode", "error", "variantComplete", "variantError"
+ "chunk",
+ "status",
+ "setCode",
+ "error",
+ "variantComplete",
+ "variantError",
+ "variantCount",
]
from image_generation.core import generate_images
from prompts import create_prompt
@@ -295,46 +301,56 @@ class ModelSelectionStage:
gemini_api_key: str | None = None,
) -> List[Llm]:
"""Select appropriate models based on available API keys"""
- variant_models = []
+ try:
+ variant_models = self._get_variant_models(
+ generation_type, NUM_VARIANTS, openai_api_key, anthropic_api_key
+ )
+
+ # Print the variant models (one per line)
+ print("Variant models:")
+ for index, model in enumerate(variant_models):
+ print(f"Variant {index}: {model.value}")
+
+ return variant_models
+ except Exception:
+ await self.throw_error(
+ "No OpenAI or Anthropic API key found. Please add the environment variable "
+ "OPENAI_API_KEY or ANTHROPIC_API_KEY to backend/.env or in the settings dialog. "
+ "If you add it to .env, make sure to restart the backend server."
+ )
+ raise Exception("No OpenAI or Anthropic key")
+
+ def _get_variant_models(
+ self,
+ generation_type: Literal["create", "update"],
+ num_variants: int,
+ openai_api_key: str | None,
+ anthropic_api_key: str | None,
+ ) -> List[Llm]:
+ """Simple model cycling that scales with num_variants"""
- # Determine Claude model based on generation type
- # For creation, use Claude Sonnet 3.7
- # For updates, use Claude Sonnet 3.5 until we have tested Claude Sonnet 3.7
+ # Determine primary Claude model based on generation type
if generation_type == "create":
claude_model = Llm.CLAUDE_3_7_SONNET_2025_02_19
else:
claude_model = Llm.CLAUDE_3_5_SONNET_2024_06_20
- # Select models based on available API keys
+ # Define model arrays to cycle through
if openai_api_key and anthropic_api_key:
- variant_models = [
- claude_model,
- Llm.GPT_4_1_NANO_2025_04_14,
- ]
- elif openai_api_key:
- variant_models = [
- Llm.GPT_4O_2024_11_20,
- Llm.GPT_4O_2024_11_20,
- ]
+ models = [claude_model, Llm.GPT_4_1_NANO_2025_04_14]
elif anthropic_api_key:
- variant_models = [
- claude_model,
- Llm.CLAUDE_3_5_SONNET_2024_06_20,
- ]
+ models = [claude_model, Llm.CLAUDE_3_5_SONNET_2024_06_20]
+ elif openai_api_key:
+ models = [Llm.GPT_4O_2024_11_20]
else:
- await self.throw_error(
- "No OpenAI or Anthropic API key found. Please add the environment variable "
- "OPENAI_API_KEY or ANTHROPIC_API_KEY to backend/.env or in the settings dialog. "
- "If you add it to .env, make sure to restart the backend server."
- )
raise Exception("No OpenAI or Anthropic key")
- # Print the variant models (one per line)
- print("Variant models:")
- for index, model in enumerate(variant_models):
- print(f"Variant {index}: {model.value}")
+ # Cycle through models: [A, B] with num=5 becomes [A, B, A, B, A]
+ selected_models: List[Llm] = []
+ for i in range(num_variants):
+ selected_models.append(models[i % len(models)])
- return variant_models
+ return selected_models
class PromptCreationStage:
@@ -775,6 +791,9 @@ class StatusBroadcastMiddleware(Middleware):
async def process(
self, context: PipelineContext, next_func: Callable[[], Awaitable[None]]
) -> None:
+ # Tell frontend how many variants we're using
+ await context.send_message("variantCount", str(NUM_VARIANTS), 0)
+
for i in range(NUM_VARIANTS):
await context.send_message("status", "Generating code...", i)
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index c30f51c7..7f82adc6 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -44,6 +44,7 @@ function App() {
resetCommits,
resetHead,
updateVariantStatus,
+ resizeVariants,
// Outputs
appendExecutionConsole,
@@ -177,8 +178,10 @@ function App() {
// Merge settings with params
const updatedParams = { ...params, ...settings };
+ // Create variants dynamically - start with 4 to handle most cases
+ // Backend will use however many it needs (typically 3)
const baseCommitObject = {
- variants: [{ code: "" }, { code: "" }],
+ variants: Array(4).fill(null).map(() => ({ code: "" })),
};
const commitInputObject =
@@ -221,6 +224,10 @@ function App() {
console.error(`Error in variant ${variantIndex}:`, error);
updateVariantStatus(commit.hash, variantIndex, "error", error);
},
+ onVariantCount: (count) => {
+ console.log(`Backend is using ${count} variants`);
+ resizeVariants(commit.hash, count);
+ },
onCancel: () => {
cancelCodeGenerationAndReset(commit);
},
diff --git a/frontend/src/components/variants/Variants.tsx b/frontend/src/components/variants/Variants.tsx
index c4e2dc23..3a1031d4 100644
--- a/frontend/src/components/variants/Variants.tsx
+++ b/frontend/src/components/variants/Variants.tsx
@@ -61,9 +61,24 @@ function Variants() {
return () => document.removeEventListener("keydown", handleKeyDown);
}, [variants.length, commit.isCommitted, selectedVariantIndex, head]);
+ // Dynamic grid layout based on variant count
+ const getGridClass = (variantCount: number) => {
+ if (variantCount <= 2) {
+ return "grid grid-cols-2 gap-2";
+ } else if (variantCount === 3) {
+ return "grid grid-cols-3 gap-2";
+ } else if (variantCount === 4) {
+ return "grid grid-cols-2 gap-2"; // 2x2 grid
+ } else if (variantCount <= 6) {
+ return "grid grid-cols-3 gap-2"; // 3x2 grid
+ } else {
+ return "grid grid-cols-4 gap-2"; // 4x? grid for larger counts
+ }
+ };
+
return (
<div className="mt-4 mb-4">
- <div className="grid grid-cols-2 gap-2">
+ <div className={getGridClass(variants.length)}>
{variants.map((variant, index) => {
// Determine the status indicator
let statusIndicator = null;
diff --git a/frontend/src/generateCode.ts b/frontend/src/generateCode.ts
index a3c7acb0..11130c5c 100644
--- a/frontend/src/generateCode.ts
+++ b/frontend/src/generateCode.ts
@@ -18,7 +18,8 @@ type WebSocketResponse = {
| "setCode"
| "error"
| "variantComplete"
- | "variantError";
+ | "variantError"
+ | "variantCount";
value: string;
variantIndex: number;
};
@@ -29,6 +30,7 @@ interface CodeGenerationCallbacks {
onStatusUpdate: (status: string, variantIndex: number) => void;
onVariantComplete: (variantIndex: number) => void;
onVariantError: (variantIndex: number, error: string) => void;
+ onVariantCount: (count: number) => void;
onCancel: () => void;
onComplete: () => void;
}
@@ -60,6 +62,8 @@ export function generateCode(
callbacks.onVariantComplete(response.variantIndex);
} else if (response.type === "variantError") {
callbacks.onVariantError(response.variantIndex, response.value);
+ } else if (response.type === "variantCount") {
+ callbacks.onVariantCount(parseInt(response.value));
} else if (response.type === "error") {
console.error("Error generating code", response.value);
toast.error(response.value);
diff --git a/frontend/src/store/project-store.ts b/frontend/src/store/project-store.ts
index bfe19e3e..7ae0bda0 100644
--- a/frontend/src/store/project-store.ts
+++ b/frontend/src/store/project-store.ts
@@ -32,6 +32,7 @@ interface ProjectStore {
status: VariantStatus,
errorMessage?: string
) => void;
+ resizeVariants: (hash: CommitHash, count: number) => void;
setHead: (hash: CommitHash) => void;
resetHead: () => void;
@@ -172,6 +173,28 @@ export const useProjectStore = create<ProjectStore>((set) => ({
},
};
}),
+ resizeVariants: (hash: CommitHash, count: number) =>
+ set((state) => {
+ const commit = state.commits[hash];
+ if (!commit) return state; // No change if commit doesn't exist
+
+ // Resize variants array to match backend count
+ const currentVariants = commit.variants;
+ const newVariants = Array(count).fill(null).map((_, index) =>
+ currentVariants[index] || { code: "", status: "generating" as VariantStatus }
+ );
+
+ return {
+ commits: {
+ ...state.commits,
+ [hash]: {
+ ...commit,
+ variants: newVariants,
+ selectedVariantIndex: Math.min(commit.selectedVariantIndex, count - 1),
+ },
+ },
+ };
+ }),
setHead: (hash: CommitHash) => set({ head: hash }),
resetHead: () => set({ head: null }),