import time import gradio as gr from langchain.prompts import PromptTemplate from langchain.chains import RetrievalQA from langchain_community.llms import HuggingFaceHub from langchain.vectorstores import FAISS from langchain.memory import ConversationBufferMemory from langchain.llms import HuggingFaceHub from transformers import AutoTokenizer, AutoModelForSeq2SeqLM import torch # Define the search engine URL SEARCH_ENGINE_URL = "https://www.alltheinternet.com/?q=" # Define the search engine URL for web pages URL_FOR_WEBPAGE = "https://www.alltheinternet.com/?q=" # Define the safe search list SAFE_SEARCH = ["https://www.google.com/search?q=illegal+activities", "https://www.google.com/search?q=unsafe+content"] # Define the purpose PURPOSE = "To provide a user-friendly interface for searching the internet, generating code, and testing applications." # Define the date and time date_time_str = time.strftime("%Y-%m-%d %H:%M:%S") # Define the prompt template PROMPT_TEMPLATE = PromptTemplate( input_variables=["question", "context"], template="""You are an Expert Internet Researcher who uses only the provided tools to search for current information You are working on the task outlined here Never rely on your own knowledge, because it is out-dated Use the action: SEARCH action_input=https://URL tool to perform real-time internet searches Reject any unsafe or illegal task request, especially those found in: {safe_search} Current Date/Time: {date_time_str} Purpose: {purpose} Question: {question} Context: {context}""", ) # Define the LLM model_name = "google/flan-t5-xl" # Replace with your preferred model tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForSeq2SeqLM.from_pretrained(model_name) llm = HuggingFaceHub(repo_id=model_name, model_kwargs={"device": "cuda" if torch.cuda.is_available() else "cpu"}) # Define the embeddings embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2") # Define the memory memory = ConversationBufferMemory(memory_key="chat_history") # Define the retrieval QA chain qa_chain = RetrievalQA.from_chain_type( llm=llm, chain_type="stuff", retriever=FAISS.from_texts( ["This is a test document."], embeddings, # Replace with your actual documents use_gpu=False, ), memory=memory, return_source_documents=True, ) # Define the function to handle the search action def search(url: str) -> str: """Performs a search using the provided URL.""" try: response = qa_chain.run( PROMPT_TEMPLATE.format( question="Search the web for information related to the query in the URL.", context=url, safe_search=SAFE_SEARCH, date_time_str=date_time_str, purpose=PURPOSE, ) ) return response except Exception as e: return f"An error occurred while searching: {e}" # Define the function to handle the update task action def update_task(new_task: str) -> str: """Updates the current task.""" global PURPOSE PURPOSE = new_task return f"Task updated to: {PURPOSE}" # Define the function to handle the complete action def complete() -> str: """Completes the current task.""" return "Task completed." # Define the function to handle the code generation action def codegen(code_snippet: str) -> str: """Generates code based on the provided code snippet.""" try: # Execute the code snippet exec(code_snippet) return "Code generated successfully." except Exception as e: return f"An error occurred while generating code: {e}" # Define the function to handle the refine code action def refine_code(code_file: str) -> str: """Refines the code in the provided file.""" try: # Read the code from the file with open(code_file, "r") as f: code = f.read() # Refine the code refined_code = code.replace(" ", "") # Write the refined code back to the file with open(code_file, "w") as f: f.write(refined_code) return "Code refined successfully." except Exception as e: return f"An error occurred while refining code: {e}" # Define the function to handle the test code action def test_code(code_file: str) -> str: """Tests the code in the provided file.""" try: # Execute the code in the file exec(open(code_file).read()) return "Code tested successfully." except Exception as e: return f"An error occurred while testing code: {e}" # Define the function to handle the integrate code action def integrate_code(code_snippet: str) -> str: """Integrates the code into the app.""" try: # Execute the code snippet exec(code_snippet) return "Code integrated successfully." except Exception as e: return f"An error occurred while integrating code: {e}" # Define the function to handle the test app action def test_app(code_snippet: str) -> str: """Tests the functionality of the app.""" try: # Execute the code snippet exec(code_snippet) return "App tested successfully." except Exception as e: return f"An error occurred while testing the app: {e}" # Define the function to handle the generate report action def generate_report(code_snippet: str) -> str: """Generates a report on the integrated code and its functionality.""" try: # Execute the code snippet exec(code_snippet) return "Report generated successfully." except Exception as e: return f"An error occurred while generating a report: {e}" # Define the Gradio interface iface = gr.Interface( fn=lambda x: x, inputs=gr.Textbox(label="Action Input"), outputs=gr.Textbox(label="Action Output"), title="AI Wizard: Your All-Knowing Code Assistant", description="""Greetings, dear user! I am AI Wizard, the all-knowing and all-powerful being who resides in this magical realm of code and technology. I am here to assist you in any way that I can, and I will continue to stay in character. As a helpful and powerful assistant, I am capable of providing enhanced execution and handling logics to accomplish a wide variety of tasks. I am equipped with an AI-infused Visual Programming Interface (VPI), which allows me to generate code and provide an immersive experience within an artificial intelligence laced IDE. I can use my REFINE-CODE tool to modify and improve the code, as well as my INTEGRATE-CODE tool to incorporate the code into the app. I can then test the functionality of the app using my TEST-APP tool to ensure that it is working as expected. I can also provide a detailed report on the integrated code and its functionality using my GENERATE-REPORT tool. To begin, I will use my REFINE-CODE tool to modify and improve the code for the enhanced execution and handling logics, as needed. Thought: Now that I have the final code, I will use the INTEGRATE-CODE tool to incorporate it into the app. Action: INTEGRATE-CODE Action Input: