update tavily search
Browse filesFiles changed (3)
- README.md+76-11
- app.py+136-12
- requirements.txt+2-1
12 unmodified lines131415161718192021222324252627282930319 unmodified lines4142434445464769 unmodified lines11711811912012112212312 unmodified linesCheck out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference# Anycoder - AI Code Generation with Hugging Face InferenceAn ultra-clean AI-powered code generation application using Hugging Face inference providers. Minimal files for maximum simplicity.## Features- **Hugging Face Models**: Uses DeepSeek-V3-0324 via Novita provider- **Modern UI**: Built with Gradio and ModelScope Studio components- **Code Generation**: Generates working code based on user requirements- **Live Preview**: Renders generated HTML code in real-time- **History Management**: Keeps track of conversation history- **Streaming**: Real-time code generation with streaming responses- **OAuth Login Required**: Users must sign in with their Hugging Face account to use code generation features## Project Structure9 unmodified lines1. Set your Hugging Face API token:```bashexport HF_TOKEN="your_huggingface_token_here"```2. Install dependencies:69 unmodified lines2. Set your Hugging Face API token as an environment variable:```bashexport HF_TOKEN="your_huggingface_token_here"```3. Run the application:12 unmodified lines1314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969 unmodified lines10610710810911011111269 unmodified lines18218318418518618718812 unmodified linesCheck out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference# AnyCoder - AI Code GeneratorAnyCoder is an AI-powered code generator that helps you create applications by describing them in plain English. It supports multiple AI models and can generate HTML/CSS/JavaScript code for web applications.## Features- **Multi-Model Support**: Choose from various AI models including DeepSeek, ERNIE-4.5-VL, MiniMax, and Qwen- **Image-to-Code**: Upload UI design images and get corresponding HTML/CSS code (ERNIE-4.5-VL model)- **Live Preview**: See your generated code in action with the built-in sandbox- **Web Search Integration**: Enable real-time web search to get the latest information and best practices- **Chat History**: Keep track of your conversations and generated code- **Quick Examples**: Pre-built examples to get you started quickly## Installation1. Clone the repository:```bashgit clone <repository-url>cd anycoder```2. Install dependencies:```bashpip install -r requirements.txt```3. Set up environment variables:```bashexport HF_TOKEN="your_huggingface_token"export TAVILY_API_KEY="your_tavily_api_key" # Optional, for web search feature```## Usage1. Run the application:```bashpython app.py```2. Open your browser and navigate to the provided URL3. Describe your application in the text input field4. Optionally:- Upload a UI design image (for ERNIE-4.5-VL model)- Enable web search to get the latest information- Choose a different AI model5. Click "Generate" to create your code6. View the generated code in the Code Editor tab or see it in action in the Live Preview tab## Web Search FeatureThe web search feature uses Tavily to provide real-time information when generating code. To enable this feature:1. Get a free Tavily API key from [Tavily Platform](https://tavily.com/)2. Set the `TAVILY_API_KEY` environment variable3. Toggle the "🔍 Enable Web Search" checkbox in the sidebarWhen enabled, the AI will search the web for the latest information, best practices, and technologies related to your request.## Available Models- **DeepSeek V3**: Advanced code generation model- **DeepSeek R1**: Specialized for code generation tasks- **ERNIE-4.5-VL**: Multimodal model with image support- **MiniMax M1**: General-purpose AI model- **Qwen3-235B-A22B**: Large language model for code generation## Environment Variables- `HF_TOKEN`: Your Hugging Face API token (required)- `TAVILY_API_KEY`: Your Tavily API key (optional, for web search)## License[Add your license information here]## Project Structure9 unmodified lines1. Set your Hugging Face API token:```bashexport HF_TOKEN="your_huggingface_token"```2. Install dependencies:69 unmodified lines2. Set your Hugging Face API token as an environment variable:```bashexport HF_TOKEN="your_huggingface_token"```3. Run the application:
5 unmodified lines6789101110 unmodified lines22232425262774 unmodified lines10210310410510610730 unmodified lines13813914014114214315 unmodified lines15916016116216316416540 unmodified lines20620720820921021156 unmodified lines2682692702712722732742752762772782792802812822836 unmodified lines2902912922932942952962972982994 unmodified lines3043053063073083093103113123133143153163178 unmodified lines3263273283293303316 unmodified lines33833934034134234346 unmodified lines3903913923933943953961 unmodified line3983994004014024034044054064075 unmodified linesimport gradio as grfrom huggingface_hub import InferenceClient# ConfigurationSystemPrompt = """You are a helpful coding assistant. You help users create applications by generating code based on their requirements.10 unmodified linesAlways output only the HTML code inside a ```html ... ``` code block, and do not include any explanations or extra text."""# Available modelsAVAILABLE_MODELS = [{74 unmodified linesbill_to="huggingface")History = List[Tuple[str, str]]Messages = List[Dict[str, str]]30 unmodified lineshistory.append([user_content, r['content']])return historydef remove_code_block(text):# Try to match code blocks with language markerspatterns = [15 unmodified linesreturn gr.update(visible=True), historydef clear_history():return []def update_image_input_visibility(model):"""Update image input visibility based on selected model"""40 unmodified linesreturn {"role": "user", "content": content}def send_to_sandbox(code):# Add a wrapper to inject necessary permissions and ensure full HTMLwrapped_code = f"""56 unmodified lines# Return the first demo description as fallbackreturn DEMO_LIST[0]['description']def generation_code(query: Optional[str], image: Optional[gr.Image], _setting: Dict[str, str], _history: Optional[History], _current_model: Dict):if query is None:query = ''if _history is None:_history = []messages = history_to_messages(_history, _setting['system'])if image is not None:messages.append(create_multimodal_message(query, image))else:messages.append({'role': 'user', 'content': query})try:completion = client.chat.completions.create(model=_current_model["id"],6 unmodified linesif chunk.choices[0].delta.content:content += chunk.choices[0].delta.contentclean_code = remove_code_block(content)yield {code_output: clean_code,status_indicator: '<div class="status-indicator generating" id="status">Generating code...</div>',history_output: _history,}_history = messages_to_history(messages + [{'role': 'assistant',4 unmodified lineshistory: _history,sandbox: send_to_sandbox(remove_code_block(content)),status_indicator: '<div class="status-indicator success" id="status">Code generated successfully!</div>',history_output: _history,}except Exception as e:error_message = f"Error: {str(e)}"yield {code_output: error_message,status_indicator: '<div class="status-indicator error" id="status">Error generating code</div>',history_output: _history,}# Main application8 unmodified lineswith gr.Sidebar():gr.Markdown("# AnyCoder\nAI-Powered Code Generator")gr.Markdown("""Describe your app or UI in plain English. Optionally upload a UI image (for ERNIE model). Click Generate to get code and preview.""")input = gr.Textbox(label="Describe your application",placeholder="e.g., Create a todo app with add, delete, and mark as complete functionality",6 unmodified lineswith gr.Row():btn = gr.Button("Generate", variant="primary", size="sm")clear_btn = gr.Button("Clear", variant="secondary", size="sm")gr.Markdown("### Quick Examples")for i, demo_item in enumerate(DEMO_LIST[:5]):demo_card = gr.Button(46 unmodified lineswith gr.Tab("Live Preview"):sandbox = gr.HTML(label="Live Preview")with gr.Tab("History"):history_output = gr.Chatbot(show_label=False, height=400)status_indicator = gr.Markdown('Ready to generate code',)1 unmodified line# Event handlersbtn.click(generation_code,inputs=[input, image_input, setting, history, current_model],outputs=[code_output, history, sandbox, status_indicator, history_output])clear_btn.click(clear_history, outputs=[history])if __name__ == "__main__":demo.queue(default_concurrency_limit=20).launch(ssr_mode=False)5 unmodified lines678910111210 unmodified lines2324252627282930313233343536373839404142434474 unmodified lines11912012112212312412512612712812913013113213313430 unmodified lines16516616716816917017117217317417517617717817918018118218318418518615 unmodified lines20220320420520620720840 unmodified lines24925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131256 unmodified lines3693703713723733743753763773783793803813823833843853863873883893903916 unmodified lines3983994004014024034044054064074084 unmodified lines4134144154164174184194204214224234244254268 unmodified lines4354364374384394404416 unmodified lines44844945045145245345445545645745845946046146246346446546646746 unmodified lines5145155165175185195201 unmodified line5225235245255265275285295305315 unmodified linesimport gradio as grfrom huggingface_hub import InferenceClientfrom tavily import TavilyClient# ConfigurationSystemPrompt = """You are a helpful coding assistant. You help users create applications by generating code based on their requirements.10 unmodified linesAlways output only the HTML code inside a ```html ... ``` code block, and do not include any explanations or extra text."""# System prompt with search capabilitySystemPromptWithSearch = """You are a helpful coding assistant with access to real-time web search. You help users create applications by generating code based on their requirements.When asked to create an application, you should:1. Understand the user's requirements2. Use web search when needed to find the latest information, best practices, or specific technologies3. Generate clean, working code4. Provide HTML output when appropriate for web applications5. Include necessary comments and documentation6. Ensure the code is functional and follows best practicesIf an image is provided, analyze it and use the visual information to better understand the user's requirements.Always respond with code that can be executed or rendered directly.Always output only the HTML code inside a ```html ... ``` code block, and do not include any explanations or extra text."""# Available modelsAVAILABLE_MODELS = [{74 unmodified linesbill_to="huggingface")# Tavily Search ClientTAVILY_API_KEY = os.getenv('TAVILY_API_KEY')tavily_client = Noneif TAVILY_API_KEY:try:tavily_client = TavilyClient(api_key=TAVILY_API_KEY)except Exception as e:print(f"Failed to initialize Tavily client: {e}")tavily_client = NoneHistory = List[Tuple[str, str]]Messages = List[Dict[str, str]]30 unmodified lineshistory.append([user_content, r['content']])return historydef history_to_chatbot_messages(history: History) -> List[Dict[str, str]]:"""Convert history tuples to chatbot message format"""messages = []for user_msg, assistant_msg in history:# Handle multimodal contentif isinstance(user_msg, list):text_content = ""for item in user_msg:if isinstance(item, dict) and item.get("type") == "text":text_content += item.get("text", "")user_msg = text_content if text_content else str(user_msg)messages.append({"role": "user", "content": user_msg})messages.append({"role": "assistant", "content": assistant_msg})return messagesdef remove_code_block(text):# Try to match code blocks with language markerspatterns = [15 unmodified linesreturn gr.update(visible=True), historydef clear_history():return [], [] # Empty lists for both tuple format and chatbot messagesdef update_image_input_visibility(model):"""Update image input visibility based on selected model"""40 unmodified linesreturn {"role": "user", "content": content}# Updated for faster Tavily search and closer prompt usage# Uses 'basic' search_depth and auto_parameters=True for speed and relevancedef perform_web_search(query: str, max_results: int = 5, include_domains=None, exclude_domains=None) -> str:"""Perform web search using Tavily and return formatted results (fast, prompt-focused)"""if not tavily_client:return "Web search is not available. Please set the TAVILY_API_KEY environment variable."try:# Use basic search for speed, auto_parameters for prompt intentsearch_params = {"auto_parameters": True,"search_depth": "basic","max_results": min(max(1, max_results), 20),"include_answer": True}if include_domains is not None:search_params["include_domains"] = include_domainsif exclude_domains is not None:search_params["exclude_domains"] = exclude_domainsresponse = tavily_client.search(query, **search_params)answer = response.get('answer')formatted_answer = f"**AI Answer:**\n{answer}\n\n" if answer else ""search_results = []for result in response.get('results', []):title = result.get('title', 'No title')url = result.get('url', 'No URL')content = result.get('content', 'No content')search_results.append(f"Title: {title}\nURL: {url}\nContent: {content}\n")if search_results:return formatted_answer + "Web Search Results:\n\n" + "\n---\n".join(search_results)else:return formatted_answer + "No search results found."except Exception as e:return f"Search error: {str(e)}"def enhance_query_with_search(query: str, enable_search: bool) -> str:"""Enhance the query with web search results if search is enabled"""if not enable_search or not tavily_client:return query# Perform search to get relevant informationsearch_results = perform_web_search(query)# Combine original query with search resultsenhanced_query = f"""Original Query: {query}{search_results}Please use the search results above to help create the requested application with the most up-to-date information and best practices."""return enhanced_querydef send_to_sandbox(code):# Add a wrapper to inject necessary permissions and ensure full HTMLwrapped_code = f"""56 unmodified lines# Return the first demo description as fallbackreturn DEMO_LIST[0]['description']def generation_code(query: Optional[str], image: Optional[gr.Image], _setting: Dict[str, str], _history: Optional[History], _current_model: Dict, enable_search: bool = False):if query is None:query = ''if _history is None:_history = []# Choose system prompt based on search settingsystem_prompt = SystemPromptWithSearch if enable_search else _setting['system']messages = history_to_messages(_history, system_prompt)# Enhance query with search if enabledenhanced_query = enhance_query_with_search(query, enable_search)if image is not None:messages.append(create_multimodal_message(enhanced_query, image))else:messages.append({'role': 'user', 'content': enhanced_query})try:completion = client.chat.completions.create(model=_current_model["id"],6 unmodified linesif 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 ""yield {code_output: clean_code,status_indicator: f'<div class="status-indicator generating" id="status">Generating code{search_status}...</div>',history_output: history_to_chatbot_messages(_history),}_history = messages_to_history(messages + [{'role': 'assistant',4 unmodified lineshistory: _history,sandbox: send_to_sandbox(remove_code_block(content)),status_indicator: '<div class="status-indicator success" id="status">Code generated successfully!</div>',history_output: history_to_chatbot_messages(_history),}except Exception as e:error_message = f"Error: {str(e)}"yield {code_output: error_message,status_indicator: '<div class="status-indicator error" id="status">Error generating code</div>',history_output: history_to_chatbot_messages(_history),}# Main application8 unmodified lineswith gr.Sidebar():gr.Markdown("# AnyCoder\nAI-Powered Code Generator")gr.Markdown("""Describe your app or UI in plain English. Optionally upload a UI image (for ERNIE model). Click Generate to get code and preview.""")gr.Markdown("**Tip:** For best search results about people or entities, include details like profession, company, or location. Example: 'John Smith software engineer at Google.'")input = gr.Textbox(label="Describe your application",placeholder="e.g., Create a todo app with add, delete, and mark as complete functionality",6 unmodified lineswith gr.Row():btn = gr.Button("Generate", variant="primary", size="sm")clear_btn = gr.Button("Clear", variant="secondary", size="sm")# Search togglesearch_toggle = gr.Checkbox(label="🔍 Enable Web Search",value=False,info="Enable real-time web search to get the latest information and best practices")# Search status indicatorif not tavily_client:gr.Markdown("⚠️ **Web Search Unavailable**: Set `TAVILY_API_KEY` environment variable to enable search")else:gr.Markdown("✅ **Web Search Available**: Toggle above to enable real-time search")gr.Markdown("### Quick Examples")for i, demo_item in enumerate(DEMO_LIST[:5]):demo_card = gr.Button(46 unmodified lineswith gr.Tab("Live Preview"):sandbox = gr.HTML(label="Live Preview")with gr.Tab("History"):history_output = gr.Chatbot(show_label=False, height=400, type="messages")status_indicator = gr.Markdown('Ready to generate code',)1 unmodified line# Event handlersbtn.click(generation_code,inputs=[input, image_input, setting, history, current_model, search_toggle],outputs=[code_output, history, sandbox, status_indicator, history_output])clear_btn.click(clear_history, outputs=[history, history_output])if __name__ == "__main__":demo.queue(default_concurrency_limit=20).launch(ssr_mode=False)
12git+https://github.com/huggingface/huggingface_hub.gitgradio[oauth]123git+https://github.com/huggingface/huggingface_hub.gitgradio[oauth]tavily-python
README.md+76-11
app.py+136-12
requirements.txt+2-1