Update app.py
Browse files13 unmodified lines14151617181920212223242526272850 unmodified lines79808182838485868788899091929394959697989910010110210310410510610710810934 unmodified lines1441451461471481491501511521531541551561571581595 unmodified lines1651661671681691701711721731741751764 unmodified lines1811821831841851861871881891901911921931941951961971981992002017 unmodified lines20921021121221321421521621721821922022122222322422522622722822923023123266 unmodified lines29930030130230330430513 unmodified linesfrom langchain_core.documents import Documentfrom huggingface_hub import InferenceClientimport inspect# Environment variables and configurationshuggingface_token = os.environ.get("HUGGINGFACE_TOKEN")llama_cloud_api_key = os.environ.get("LLAMA_CLOUD_API_KEY")MODELS = ["mistralai/Mistral-7B-Instruct-v0.3","mistralai/Mixtral-8x7B-Instruct-v0.1","microsoft/Phi-3-mini-4k-instruct"]# Initialize LlamaParse50 unmodified linesdef generate_chunked_response(prompt, model, max_tokens=1000, num_calls=3, temperature=0.2, should_stop=False):print(f"Starting generate_chunked_response with {num_calls} calls")client = InferenceClient(model, token=huggingface_token)full_response = ""messages = [{"role": "user", "content": prompt}]for i in range(num_calls):print(f"Starting API call {i+1}")if should_stop:print("Stop clicked, breaking loop")breaktry:for message in client.chat_completion(messages=messages,max_tokens=max_tokens,temperature=temperature,stream=True,):if should_stop:print("Stop clicked during streaming, breaking")breakif message.choices and message.choices[0].delta and message.choices[0].delta.content:chunk = message.choices[0].delta.contentfull_response += chunkprint(f"API call {i+1} completed")except Exception as e:print(f"Error in generating response: {str(e)}")# Clean up the responseclean_response = re.sub(r'<s>\[INST\].*?\[/INST\]\s*', '', full_response, flags=re.DOTALL)34 unmodified lineshistory = history + [(message, "")]try:if use_web_search:for main_content, sources in get_response_with_search(message, model, num_calls=num_calls, temperature=temperature):history[-1] = (message, f"{main_content}\n\n{sources}")yield historyelse:for partial_response in get_response_from_pdf(message, model, num_calls=num_calls, temperature=temperature):history[-1] = (message, partial_response)yield historyexcept gr.CancelledError:yield historydef retry_last_response(history, use_web_search, model, temperature, num_calls):if not history:5 unmodified linesreturn chatbot_interface(last_user_msg, history, use_web_search, model, temperature, num_calls)def respond(message, history, model, temperature, num_calls, use_web_search):if use_web_search:for main_content, sources in get_response_with_search(message, model, num_calls=num_calls, temperature=temperature):yield f"{main_content}\n\n{sources}"else:for partial_response in get_response_from_pdf(message, model, num_calls=num_calls, temperature=temperature):yield partial_responsedef get_response_with_search(query, model, num_calls=3, temperature=0.2):search_results = duckduckgo_search(query)4 unmodified lines{context}Write a detailed and complete research document that fulfills the following user request: '{query}'After writing the document, please provide a list of sources used in your response."""client = InferenceClient(model, token=huggingface_token)main_content = ""for i in range(num_calls):for message in client.chat_completion(messages=[{"role": "user", "content": prompt}],max_tokens=1000,temperature=temperature,stream=True,):if message.choices and message.choices[0].delta and message.choices[0].delta.content:chunk = message.choices[0].delta.contentmain_content += chunkyield main_content, "" # Yield partial main content without sourcesdef get_response_from_pdf(query, model, num_calls=3, temperature=0.2):embed = get_embeddings()7 unmodified linesrelevant_docs = retriever.get_relevant_documents(query)context_str = "\n".join([doc.page_content for doc in relevant_docs])prompt = f"""Using the following context from the PDF documents:{context_str}Write a detailed and complete response that answers the following user question: '{query}'"""client = InferenceClient(model, token=huggingface_token)response = ""for i in range(num_calls):for message in client.chat_completion(messages=[{"role": "user", "content": prompt}],max_tokens=1000,temperature=temperature,stream=True,):if message.choices and message.choices[0].delta and message.choices[0].delta.content:chunk = message.choices[0].delta.contentresponse += chunkyield response # Yield partial responsedef vote(data: gr.LikeData):if data.liked:66 unmodified lines1. Upload PDF documents using the file input at the top.2. Select the PDF parser (pypdf or llamaparse) and click "Upload Document" to update the vector store.3. Ask questions in the chat interface.4. Toggle "Use Web Search" to switch between PDF chat and web search, the toggle box is present inside additional inputs dropdown.5. Adjust Temperature and Number of API Calls to fine-tune the response generation.6. Use the provided examples or ask your own questions."""13 unmodified lines141516171819202122232425262728293031323334353637383950 unmodified lines9091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916034 unmodified lines1951961971981992002012022032042052062072082095 unmodified lines2152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163174 unmodified lines3223233243253263273283293303313323333343353363373383393403413423433443453463473487 unmodified lines35635735835936036136236336436536636736836937037137237337437537637737837938038138238338438566 unmodified lines45245345445545645745813 unmodified linesfrom langchain_core.documents import Documentfrom huggingface_hub import InferenceClientimport inspectimport logging# Set up basic configuration for logginglogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')# Environment variables and configurationshuggingface_token = os.environ.get("HUGGINGFACE_TOKEN")llama_cloud_api_key = os.environ.get("LLAMA_CLOUD_API_KEY")ACCOUNT_ID = os.environ.get("CLOUDFARE_ACCOUNT_ID")API_TOKEN = os.environ.get("CLOUDFLARE_AUTH_TOKEN")API_BASE_URL = "https://api.cloudflare.com/client/v4/accounts/a17f03e0f049ccae0c15cdcf3b9737ce/ai/run/"print(f"ACCOUNT_ID: {ACCOUNT_ID}")print(f"CLOUDFLARE_AUTH_TOKEN: {API_TOKEN[:5]}..." if API_TOKEN else "Not set")MODELS = ["mistralai/Mistral-7B-Instruct-v0.3","mistralai/Mixtral-8x7B-Instruct-v0.1","@cf/meta/llama-3.1-8b-instruct"]# Initialize LlamaParse50 unmodified linesdef generate_chunked_response(prompt, model, max_tokens=1000, num_calls=3, temperature=0.2, should_stop=False):print(f"Starting generate_chunked_response with {num_calls} calls")full_response = ""messages = [{"role": "user", "content": prompt}]if model == "@cf/meta/llama-3.1-8b-instruct":# Cloudflare APIfor i in range(num_calls):print(f"Starting Cloudflare API call {i+1}")if should_stop:print("Stop clicked, breaking loop")breaktry:response = requests.post(f"https://api.cloudflare.com/client/v4/accounts/{ACCOUNT_ID}/ai/run/@cf/meta/llama-3.1-8b-instruct",headers={"Authorization": f"Bearer {API_TOKEN}"},json={"stream": true,"messages": [{"role": "system", "content": "You are a friendly assistant"},{"role": "user", "content": prompt}],"max_tokens": max_tokens,"temperature": temperature},stream=true)for line in response.iter_lines():if should_stop:print("Stop clicked during streaming, breaking")breakif line:try:json_data = json.loads(line.decode('utf-8').split('data: ')[1])chunk = json_data['response']full_response += chunkexcept json.JSONDecodeError:continueprint(f"Cloudflare API call {i+1} completed")except Exception as e:print(f"Error in generating response from Cloudflare: {str(e)}")else:# Original Hugging Face API logicclient = InferenceClient(model, token=huggingface_token)for i in range(num_calls):print(f"Starting Hugging Face API call {i+1}")if should_stop:print("Stop clicked, breaking loop")breaktry:for message in client.chat_completion(messages=messages,max_tokens=max_tokens,temperature=temperature,stream=True,):if should_stop:print("Stop clicked during streaming, breaking")breakif message.choices and message.choices[0].delta and message.choices[0].delta.content:chunk = message.choices[0].delta.contentfull_response += chunkprint(f"Hugging Face API call {i+1} completed")except Exception as e:print(f"Error in generating response from Hugging Face: {str(e)}")# Clean up the responseclean_response = re.sub(r'<s>\[INST\].*?\[/INST\]\s*', '', full_response, flags=re.DOTALL)34 unmodified lineshistory = history + [(message, "")]try:for response in respond(message, history, model, temperature, num_calls, use_web_search):history[-1] = (message, response)yield historyexcept gr.CancelledError: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, use_web_search, model, temperature, num_calls):if not history:5 unmodified linesreturn chatbot_interface(last_user_msg, history, use_web_search, model, temperature, num_calls)def respond(message, history, model, temperature, num_calls, use_web_search):logging.info(f"User Query: {message}")logging.info(f"Model Used: {model}")logging.info(f"Search Type: {'Web Search' if use_web_search else 'PDF Search'}")try:if use_web_search:for main_content, sources in get_response_with_search(message, model, num_calls=num_calls, temperature=temperature):response = f"{main_content}\n\n{sources}"first_line = response.split('\n')[0] if response else ''logging.info(f"Generated Response (first line): {first_line}")yield responseelse:if model == "@cf/meta/llama-3.1-8b-instruct":# Use Cloudflare APIembed = get_embeddings()if os.path.exists("faiss_database"):database = FAISS.load_local("faiss_database", embed, allow_dangerous_deserialization=True)retriever = database.as_retriever()relevant_docs = retriever.get_relevant_documents(message)context_str = "\n".join([doc.page_content for doc in relevant_docs])else:context_str = "No documents available."for partial_response in get_response_from_cloudflare(prompt="", context=context_str, query=message, num_calls=num_calls, temperature=temperature, search_type="pdf"):first_line = partial_response.split('\n')[0] if partial_response else ''logging.info(f"Generated Response (first line): {first_line}")yield partial_responseelse:# Use Hugging Face APIfor partial_response in get_response_from_pdf(message, model, num_calls=num_calls, temperature=temperature):first_line = partial_response.split('\n')[0] if partial_response else ''logging.info(f"Generated Response (first line): {first_line}")yield partial_responseexcept Exception as e:logging.error(f"Error with {model}: {str(e)}")if "microsoft/Phi-3-mini-4k-instruct" in model:logging.info("Falling back to Mistral model due to Phi-3 error")fallback_model = "mistralai/Mistral-7B-Instruct-v0.3"yield from respond(message, history, fallback_model, temperature, num_calls, use_web_search)else:yield f"An error occurred with the {model} model: {str(e)}. Please try again or select a different model."logging.basicConfig(level=logging.DEBUG)def get_response_from_cloudflare(prompt, context, query, num_calls=3, temperature=0.2, search_type="pdf"):headers = {"Authorization": f"Bearer {API_TOKEN}","Content-Type": "application/json"}model = "@cf/meta/llama-3.1-8b-instruct"if search_type == "pdf":instruction = f"""Using the following context:{context}Write a detailed and complete research document that fulfills the following user request: '{query}'"""else: # web searchinstruction = f"""Using the following context:{context}Write a detailed and complete research document that fulfills the following user request: '{query}'After writing the document, please provide a list of sources used in your response."""inputs = [{"role": "system", "content": instruction},{"role": "user", "content": query}]payload = {"messages": inputs,"stream": True,"temperature": temperature}full_response = ""for i in range(num_calls):try:with requests.post(f"{API_BASE_URL}{model}", headers=headers, json=payload, stream=True) as response:if response.status_code == 200:for line in response.iter_lines():if line:try:json_response = json.loads(line.decode('utf-8').split('data: ')[1])if 'response' in json_response:chunk = json_response['response']full_response += chunkyield full_responseexcept (json.JSONDecodeError, IndexError) as e:logging.error(f"Error parsing streaming response: {str(e)}")continueelse:logging.error(f"HTTP Error: {response.status_code}, Response: {response.text}")yield f"I apologize, but I encountered an HTTP error: {response.status_code}. Please try again later."except Exception as e:logging.error(f"Error in generating response from Cloudflare: {str(e)}")yield f"I apologize, but an error occurred: {str(e)}. Please try again later."if not full_response:yield "I apologize, but I couldn't generate a response at this time. Please try again later."def get_response_with_search(query, model, num_calls=3, temperature=0.2):search_results = duckduckgo_search(query)4 unmodified lines{context}Write a detailed and complete research document that fulfills the following user request: '{query}'After writing the document, please provide a list of sources used in your response."""if model == "@cf/meta/llama-3.1-8b-instruct":# Use Cloudflare APIfor response in get_response_from_cloudflare(prompt="", context=context, query=query, num_calls=num_calls, temperature=temperature, search_type="web"):yield response, "" # Yield streaming response without sourceselse:# Use Hugging Face APIclient = InferenceClient(model, token=huggingface_token)main_content = ""for i in range(num_calls):for message in client.chat_completion(messages=[{"role": "user", "content": prompt}],max_tokens=1000,temperature=temperature,stream=True,):if message.choices and message.choices[0].delta and message.choices[0].delta.content:chunk = message.choices[0].delta.contentmain_content += chunkyield main_content, "" # Yield partial main content without sourcesdef get_response_from_pdf(query, model, num_calls=3, temperature=0.2):embed = get_embeddings()7 unmodified linesrelevant_docs = retriever.get_relevant_documents(query)context_str = "\n".join([doc.page_content for doc in relevant_docs])if model == "@cf/meta/llama-3.1-8b-instruct":# Use Cloudflare API with the retrieved contextfor response in get_response_from_cloudflare(prompt="", context=context_str, query=query, num_calls=num_calls, temperature=temperature, search_type="pdf"):yield responseelse:# Use Hugging Face APIprompt = f"""Using the following context from the PDF documents:{context_str}Write a detailed and complete response that answers the following user question: '{query}'"""client = InferenceClient(model, token=huggingface_token)response = ""for i in range(num_calls):for message in client.chat_completion(messages=[{"role": "user", "content": prompt}],max_tokens=1000,temperature=temperature,stream=True,):if message.choices and message.choices[0].delta and message.choices[0].delta.content:chunk = message.choices[0].delta.contentresponse += chunkyield response # Yield partial responsedef vote(data: gr.LikeData):if data.liked:66 unmodified lines1. Upload PDF documents using the file input at the top.2. Select the PDF parser (pypdf or llamaparse) and click "Upload Document" to update the vector store.3. Ask questions in the chat interface.4. Toggle "Use Web Search" to switch between PDF chat and web search.5. Adjust Temperature and Number of API Calls to fine-tune the response generation.6. Use the provided examples or ask your own questions."""
app.py+222-69