update to add provider selection
Browse files226 unmodified lines227228229230231232233234235236703 unmodified lines9409419429439449459469479489499509519529539549559569579589594 unmodified lines9649659669679689699709719721 unmodified line97497597697797897998013 unmodified lines9949959969979989991000100110021003100410058 unmodified lines10141015101610171018101910206 unmodified lines10271028102910301031103210337 unmodified lines1041104210431044104510461 unmodified line104810491050105110521053105410551056105710581059106010612 unmodified lines106410651066106710681069107010711072107382 unmodified lines11561157115811591160116189 unmodified lines12511252125312541255125612571 unmodified line12591260126112621263226 unmodified lines# HF Inference ClientHF_TOKEN = os.getenv('HF_TOKEN')def get_inference_client(model_id):"""Return an InferenceClient with provider based on model_id."""provider = "groq" if model_id == "moonshotai/Kimi-K2-Instruct" else "auto"return InferenceClient(provider=provider,api_key=HF_TOKEN,703 unmodified linesexcept Exception as e:return f"Error extracting website content: {str(e)}"def generation_code(query: Optional[str], image: Optional[gr.Image], file: Optional[str], website_url: Optional[str], _setting: Dict[str, str], _history: Optional[History], _current_model: Dict, enable_search: bool = False, language: str = "html"):if query is None:query = ''if _history is None:_history = []# Check if there's existing HTML content in history to determine if this is a modification requesthas_existing_html = Falseif _history:# Check the last assistant message for HTML contentlast_assistant_msg = _history[-1][1] if len(_history) > 0 else ""if '<!DOCTYPE html>' in last_assistant_msg or '<html' in last_assistant_msg:has_existing_html = True# Choose system prompt based on contextif has_existing_html:# Use follow-up prompt for modifying existing HTML4 unmodified linessystem_prompt = HTML_SYSTEM_PROMPT_WITH_SEARCH if enable_search else HTML_SYSTEM_PROMPTelse:system_prompt = GENERIC_SYSTEM_PROMPT_WITH_SEARCH.format(language=language) if enable_search else GENERIC_SYSTEM_PROMPT.format(language=language)messages = history_to_messages(_history, system_prompt)# Extract file text and append to query if file is presentfile_text = ""if file:1 unmodified lineif file_text:file_text = file_text[:5000] # Limit to 5000 chars for prompt sizequery = f"{query}\n\n[Reference file content below]\n{file_text}"# Extract website content and append to query if website URL is presentwebsite_text = ""if website_url and website_url.strip():13 unmodified linesThis will help me create a better design for you."""query = f"{query}\n\n[Error extracting website: {website_text}]{fallback_guidance}"# Enhance query with search if enabledenhanced_query = enhance_query_with_search(query, enable_search)# Use dynamic client based on selected modelclient = get_inference_client(_current_model["id"])if image is not None:messages.append(create_multimodal_message(enhanced_query, image))8 unmodified lines)content = ""for chunk in completion:if chunk.choices[0].delta.content:content += chunk.choices[0].delta.contentclean_code = remove_code_block(content)search_status = " (with web search)" if enable_search and tavily_client else ""6 unmodified linessandbox: send_to_sandbox(clean_code) if language == "html" else "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML. Please download your code using the download button above.</div>",}else:last_html = _history[-1][1] if _history else ""modified_html = apply_search_replace_changes(last_html, clean_code)clean_html = remove_code_block(modified_html)yield {7 unmodified lineshistory_output: history_to_chatbot_messages(_history),sandbox: send_to_sandbox(clean_code) if language == "html" else "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML. Please download your code using the download button above.</div>",}# Handle response based on whether this is a modification or new generationif has_existing_html:# Fallback: If the model returns a full HTML file, use it directly1 unmodified lineif final_code.strip().startswith("<!DOCTYPE html>") or final_code.strip().startswith("<html"):clean_html = final_codeelse:last_html = _history[-1][1] if _history else ""modified_html = apply_search_replace_changes(last_html, final_code)clean_html = remove_code_block(modified_html)# Update history with the cleaned HTML_history = messages_to_history(messages + [{'role': 'assistant','content': clean_html}])yield {code_output: clean_html,history: _history,2 unmodified lines}else:# Regular generation - use the content as is_history = messages_to_history(messages + [{'role': 'assistant','content': content}])yield {code_output: remove_code_block(content),history: _history,82 unmodified lineslabel="Model",visible=True # Always visible)gr.Markdown("**Quick start**", visible=True)with gr.Column(visible=True) as quick_examples_col:for i, demo_item in enumerate(DEMO_LIST[:3]):89 unmodified linesbtn.click(generation_code,inputs=[input, image_input, file_input, website_url_input, setting, history, current_model, search_toggle, language_dropdown],outputs=[code_output, history, sandbox, history_output])# Update preview when code or language changes1 unmodified linelanguage_dropdown.change(preview_logic, inputs=[code_output, language_dropdown], outputs=sandbox)clear_btn.click(clear_history, outputs=[history, history_output, file_input, website_url_input])if __name__ == "__main__":demo.queue(api_open=False, default_concurrency_limit=20).launch(ssr_mode=True, mcp_server=False, show_api=False)226 unmodified lines227228229230231232233234235236237703 unmodified lines9419429439449459469479489499509519529539549559569579589599609619629639644 unmodified lines9699709719729739749759769771 unmodified line97998098198298398498513 unmodified lines999100010011002100310041005100610071008100910108 unmodified lines101910201021102210231024102510266 unmodified lines10331034103510361037103810397 unmodified lines104710481049105010511052105310541 unmodified line105610571058105910601061106210631064106510662 unmodified lines106910701071107210731074107582 unmodified lines115811591160116111621163116411651166116711681169117011711172117389 unmodified lines12631264126512661267126812691 unmodified line12711272127312741275127612771278127912801281128212831284226 unmodified lines# HF Inference ClientHF_TOKEN = os.getenv('HF_TOKEN')if not HF_TOKEN:raise RuntimeError("HF_TOKEN environment variable is not set. Please set it to your Hugging Face API token.")def get_inference_client(model_id, provider="auto"):"""Return an InferenceClient with provider based on model_id and user selection."""return InferenceClient(provider=provider,api_key=HF_TOKEN,703 unmodified linesexcept Exception as e:return f"Error extracting website content: {str(e)}"def generation_code(query: Optional[str], image: Optional[gr.Image], file: Optional[str], website_url: Optional[str], _setting: Dict[str, str], _history: Optional[History], _current_model: Dict, enable_search: bool = False, language: str = "html", provider: str = "auto"):if query is None:query = ''if _history is None:_history = []# Ensure _history is always a list of lists with at least 2 elements per itemif not isinstance(_history, list):_history = []_history = [h for h in _history if isinstance(h, list) and len(h) == 2]# Check if there's existing HTML content in history to determine if this is a modification requesthas_existing_html = Falselast_assistant_msg = ""if _history and len(_history[-1]) > 1:last_assistant_msg = _history[-1][1]if '<!DOCTYPE html>' in last_assistant_msg or '<html' in last_assistant_msg:has_existing_html = True# Choose system prompt based on contextif has_existing_html:# Use follow-up prompt for modifying existing HTML4 unmodified linessystem_prompt = HTML_SYSTEM_PROMPT_WITH_SEARCH if enable_search else HTML_SYSTEM_PROMPTelse:system_prompt = GENERIC_SYSTEM_PROMPT_WITH_SEARCH.format(language=language) if enable_search else GENERIC_SYSTEM_PROMPT.format(language=language)messages = history_to_messages(_history, system_prompt)# Extract file text and append to query if file is presentfile_text = ""if file:1 unmodified lineif file_text:file_text = file_text[:5000] # Limit to 5000 chars for prompt sizequery = f"{query}\n\n[Reference file content below]\n{file_text}"# Extract website content and append to query if website URL is presentwebsite_text = ""if website_url and website_url.strip():13 unmodified linesThis will help me create a better design for you."""query = f"{query}\n\n[Error extracting website: {website_text}]{fallback_guidance}"# Enhance query with search if enabledenhanced_query = enhance_query_with_search(query, enable_search)# Use dynamic client based on selected modelclient = get_inference_client(_current_model["id"], provider)if image is not None:messages.append(create_multimodal_message(enhanced_query, image))8 unmodified lines)content = ""for chunk in completion:# Only process if chunk.choices is non-emptyif hasattr(chunk, "choices") and chunk.choices and hasattr(chunk.choices[0], "delta") and hasattr(chunk.choices[0].delta, "content"):content += chunk.choices[0].delta.contentclean_code = remove_code_block(content)search_status = " (with web search)" if enable_search and tavily_client else ""6 unmodified linessandbox: send_to_sandbox(clean_code) if language == "html" else "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML. Please download your code using the download button above.</div>",}else:last_html = _history[-1][1] if _history and len(_history[-1]) > 1 else ""modified_html = apply_search_replace_changes(last_html, clean_code)clean_html = remove_code_block(modified_html)yield {7 unmodified lineshistory_output: history_to_chatbot_messages(_history),sandbox: send_to_sandbox(clean_code) if language == "html" else "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML. Please download your code using the download button above.</div>",}# Skip chunks with empty choices (end of stream)# Do not treat as error# Handle response based on whether this is a modification or new generationif has_existing_html:# Fallback: If the model returns a full HTML file, use it directly1 unmodified lineif final_code.strip().startswith("<!DOCTYPE html>") or final_code.strip().startswith("<html"):clean_html = final_codeelse:last_html = _history[-1][1] if _history and len(_history[-1]) > 1 else ""modified_html = apply_search_replace_changes(last_html, final_code)clean_html = remove_code_block(modified_html)# Update history with the cleaned HTML_history.append([query, clean_html])yield {code_output: clean_html,history: _history,2 unmodified lines}else:# Regular generation - use the content as is_history.append([query, content])yield {code_output: remove_code_block(content),history: _history,82 unmodified lineslabel="Model",visible=True # Always visible)provider_choices = ["auto", "black-forest-labs", "cerebras", "cohere", "fal-ai", "featherless-ai", "fireworks-ai", "groq", "hf-inference", "hyperbolic", "nebius", "novita", "nscale", "openai", "replicate", "sambanova", "together"]provider_dropdown = gr.Dropdown(choices=provider_choices,value="auto",label="Provider",visible=True)provider_state = gr.State("auto")gr.Markdown("**Quick start**", visible=True)with gr.Column(visible=True) as quick_examples_col:for i, demo_item in enumerate(DEMO_LIST[:3]):89 unmodified linesbtn.click(generation_code,inputs=[input, image_input, file_input, website_url_input, setting, history, current_model, search_toggle, language_dropdown, provider_state],outputs=[code_output, history, sandbox, history_output])# Update preview when code or language changes1 unmodified linelanguage_dropdown.change(preview_logic, inputs=[code_output, language_dropdown], outputs=sandbox)clear_btn.click(clear_history, outputs=[history, history_output, file_input, website_url_input])def on_provider_change(provider):return providerprovider_dropdown.change(on_provider_change,inputs=provider_dropdown,outputs=provider_state)if __name__ == "__main__":demo.queue(api_open=False, default_concurrency_limit=20).launch(ssr_mode=True, mcp_server=False, show_api=False)
app.py+48-27