Update app.py
Browse files22 unmodified lines232425262728293025 unmodified lines5657585960616263646566676869707172737475767778798081828384859 unmodified lines959697989910010110210310410510610710810911020 unmodified lines13113213313413513613741 unmodified lines17918018118218318418518618718818919019119219319419519619722 unmodified lines"mistralai/Mixtral-8x7B-Instruct-v0.1","mistralai/Mistral-Nemo-Instruct-2407","meta-llama/Meta-Llama-3.1-8B-Instruct","meta-llama/Meta-Llama-3.1-70B-Instruct","meta-llama/Meta-Llama-3.1-8B-Instruct","meta-llama/Meta-Llama-3.1-70B-Instruct"]25 unmodified linesdescription="List of sources to cite. Should be an URL of the source.")def chatbot_interface(message, history, model, temperature, num_calls, use_embeddings, system_prompt):if not message.strip():return "", historyhistory = history + [(message, "")]try:for response in respond(message, history, model, temperature, num_calls, use_embeddings, system_prompt):history[-1] = (message, response)yield historyexcept Exception as e:logging.error(f"Unexpected error in chatbot_interface: {str(e)}")history[-1] = (message, f"An unexpected error occurred: {str(e)}")yield historydef respond(message, history, model, temperature, num_calls, use_embeddings, system_prompt):logging.info(f"User Query: {message}")logging.info(f"Model Used: {model}")logging.info(f"Use Embeddings: {use_embeddings}")try:for main_content, sources in get_response_with_search(message, model, num_calls, temperature, use_embeddings, system_prompt):# response = f"{main_content}\n\n{sources}"yield main_contentexcept Exception as e:logging.error(f"Error with {model}: {str(e)}")yield f"An error occurred with the {model} model: {str(e)}. Please try again or select a different model."9 unmodified linesreturn FAISS.from_documents(documents, embed)def get_response_with_search(query, model, num_calls=3, temperature=0.2, use_embeddings=True, system_prompt):search_results = duckduckgo_search(query)if use_embeddings:web_search_database = create_web_search_vectors(search_results)if not web_search_database:yield "No web search results available. Please try again.", ""returnretriever = web_search_database.as_retriever(search_kwargs={"k": 5})relevant_docs = retriever.get_relevant_documents(query)context = "\n".join([doc.page_content for doc in relevant_docs])else:context = "\n".join([f"{result['title']}\n{result['body']}\nSource: {result['href']}" for result in search_results])20 unmodified linestry:response = client.chat_completion(messages=[{"role": "system", "content": system_prompt},{"role": "user", "content": prompt}],max_tokens=max_new_tokens,41 unmodified lines(None, "Welcome! I'm your AI assistant for web search. Here's how you can use me:\n\n""1. Ask me any question, and I'll search the web for information.\n""2. You can adjust the model, temperature, number of API calls, and whether to use embeddings for fine-tuned responses.\n""3. You can also customize the system prompt to guide my behavior.\n""4. For any queries, feel free to reach out @desai.shreyas94@gmail.com or discord - shreyas094\n\n""To get started, ask me a question!")]demo = gr.ChatInterface(chatbot_interface,additional_inputs=[gr.Dropdown(choices=MODELS, label="Select Model", value=MODELS[2]),gr.Slider(minimum=0.1, maximum=1.0, value=0.2, step=0.1, label="Temperature"),gr.Slider(minimum=1, maximum=5, value=1, step=1, label="Number of API Calls"),gr.Checkbox(label="Use Embeddings", value=True),gr.Textbox(label="System Prompt", value=DEFAULT_SYSTEM_PROMPT, lines=5),],title="AI-powered Web Search Assistant",description="Ask questions and get answers from web search results.",22 unmodified lines23242526272825 unmodified lines5455565758596061626364656667686970717273747576777879808182838485868788899091929394959 unmodified lines10510610710810911011111211311411511611711811912012112212320 unmodified lines14414514614714814915041 unmodified lines19219319419519619719819920020120220320420520620720820922 unmodified lines"mistralai/Mixtral-8x7B-Instruct-v0.1","mistralai/Mistral-Nemo-Instruct-2407","meta-llama/Meta-Llama-3.1-8B-Instruct","meta-llama/Meta-Llama-3.1-70B-Instruct"]25 unmodified linesdescription="List of sources to cite. Should be an URL of the source.")def chatbot_interface(message, history, model, temperature, num_calls, use_embeddings):if not message.strip():return "", historyhistory = history + [(message, "")]try:for response in respond(message, history, model, temperature, num_calls, use_embeddings):history[-1] = (message, response)yield historyexcept gr.CanceledError:yield historyexcept Exception as e:logging.error(f"Unexpected error in chatbot_interface: {str(e)}")history[-1] = (message, f"An unexpected error occurred: {str(e)}")yield historydef retry_last_response(history, model, temperature, num_calls, use_embeddings):if not history:return historylast_user_msg = history[-1][0]history = history[:-1] # Remove the last responsereturn chatbot_interface(last_user_msg, history, model, temperature, num_calls, use_embeddings)def respond(message, history, model, temperature, num_calls, use_embeddings):logging.info(f"User Query: {message}")logging.info(f"Model Used: {model}")logging.info(f"Use Embeddings: {use_embeddings}")try:for main_content, sources in get_response_with_search(message, model, num_calls=num_calls, temperature=temperature, use_embeddings=use_embeddings):response = f"{main_content}\n\n{sources}"first_line = response.split('\n')[0] if response else ''yield responseexcept Exception as e:logging.error(f"Error with {model}: {str(e)}")yield f"An error occurred with the {model} model: {str(e)}. Please try again or select a different model."9 unmodified linesreturn FAISS.from_documents(documents, embed)def get_response_with_search(query, model, num_calls=3, temperature=0.2, use_embeddings=True):search_results = duckduckgo_search(query)if use_embeddings:web_search_database = create_web_search_vectors(search_results)if not web_search_database:yield "No web search results available. Please try again.", ""returnretriever = web_search_database.as_retriever(search_kwargs={"k": 5})relevant_docs = retriever.get_relevant_documents(query)context = "\n".join([doc.page_content for doc in relevant_docs])else:context = "\n".join([f"{result['title']}\n{result['body']}\nSource: {result['href']}" for result in search_results])20 unmodified linestry:response = client.chat_completion(messages=[{"role": "system", "content": DEFAULT_SYSTEM_PROMPT},{"role": "user", "content": prompt}],max_tokens=max_new_tokens,41 unmodified lines(None, "Welcome! I'm your AI assistant for web search. Here's how you can use me:\n\n""1. Ask me any question, and I'll search the web for information.\n""2. You can adjust the model, temperature, number of API calls, and whether to use embeddings for fine-tuned responses.\n""3. For any queries, feel free to reach out @desai.shreyas94@gmail.com or discord - shreyas094\n\n""To get started, ask me a question!")]demo = gr.ChatInterface(respond,additional_inputs_accordion=gr.Accordion(label="⚙️ Parameters", open=True, render=False),additional_inputs=[gr.Dropdown(choices=MODELS, label="Select Model", value=MODELS[2]),gr.Slider(minimum=0.1, maximum=1.0, value=0.2, step=0.1, label="Temperature"),gr.Slider(minimum=1, maximum=5, value=1, step=1, label="Number of API Calls"),gr.Checkbox(label="Use Embeddings", value=True),],title="AI-powered Web Search Assistant",description="Ask questions and get answers from web search results.",
app.py+26-14