Shreyas094 commited on
Commit
3890ae0
·
verified ·
1 Parent(s): 4e4b34e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +110 -204
app.py CHANGED
@@ -1,191 +1,94 @@
1
  import os
2
- import json
3
  import logging
4
  import gradio as gr
5
- from duckduckgo_search import DDGS
6
- from typing import List, Dict
7
- from pydantic import BaseModel
8
  from huggingface_hub import InferenceClient
9
- from typing import List, Dict
10
- from sentence_transformers import SentenceTransformer
11
- from sklearn.metrics.pairwise import cosine_similarity
12
- import numpy as np
13
-
14
- # Set up basic configuration for logging
15
- logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
16
 
17
  # Environment variables and configurations
18
  huggingface_token = os.environ.get("HUGGINGFACE_TOKEN")
 
 
 
 
 
 
 
19
 
20
  MODELS = [
21
  "mistralai/Mistral-7B-Instruct-v0.3",
22
  "mistralai/Mixtral-8x7B-Instruct-v0.1",
23
- "duckduckgo/gpt-4o-mini",
24
- "duckduckgo/claude-3-haiku",
25
- "duckduckgo/llama-3.1-70b",
26
- "duckduckgo/mixtral-8x7b"
27
  ]
28
 
29
- class ConversationManager:
30
- def __init__(self):
31
- self.history = []
32
- self.current_context = None
33
-
34
- def add_interaction(self, query, response):
35
- self.history.append((query, response))
36
- self.current_context = f"Previous query: {query}\nPrevious response summary: {response[:200]}..."
37
-
38
- def get_context(self):
39
- return self.current_context
40
-
41
- conversation_manager = ConversationManager()
42
 
43
- huggingface_token = os.environ.get("HUGGINGFACE_TOKEN")
44
-
45
- def duckduckgo_search(query: str, max_results: int = 10) -> List[Dict[str, str]]:
46
  with DDGS() as ddgs:
47
- results = list(ddgs.text(query, max_results=max_results))
48
  return results
49
 
50
- def get_web_search_results(query: str, model: str, num_calls: int = 3, temperature: float = 0.2, max_results: int = 10, search_method: str = "DDGS.chat") -> Dict[str, any]:
51
- try:
52
- # Perform web search
53
- if search_method == "DDGS.text":
54
- search_results = duckduckgo_search(query, max_results)
55
- else: # Default to DDGS.chat
56
- with DDGS() as ddgs:
57
- search_results = list(ddgs.text(query, max_results=max_results))
58
-
59
- if not search_results:
60
- return {"error": f"No results found for query: {query}"}
61
-
62
- # Create embeddings for search results
63
- embedder = SentenceTransformer('all-MiniLM-L6-v2')
64
- web_search_vectors = embedder.encode([result['body'] for result in search_results])
65
-
66
- # Retrieve relevant documents
67
- query_vector = embedder.encode([query])
68
- similarities = cosine_similarity(query_vector, web_search_vectors)[0]
69
- top_indices = np.argsort(similarities)[-5:][::-1]
70
- relevant_docs = [search_results[i] for i in top_indices]
71
-
72
- # Prepare context
73
- context = "\n".join([f"Title: {doc['title']}\nContent: {doc['body']}" for doc in relevant_docs])
74
-
75
- # Prepare prompt
76
- prompt = f"""Using the following context from web search results:
77
-
78
  {context}
79
-
80
  Write a detailed and complete research document that fulfills the following user request: '{query}'
81
  After writing the document, please provide a list of sources used in your response."""
82
-
83
- # Generate response based on the selected model
84
- if model == "@cf/meta/llama-3.1-8b-instruct":
85
- # Use Cloudflare API (placeholder, as the actual implementation is not provided)
86
- response = get_response_from_cloudflare(prompt="", context=context, query=query, num_calls=num_calls, temperature=temperature, search_type="web")
87
- else:
88
- # Use Hugging Face API
89
- client = InferenceClient(model, token=huggingface_token)
90
- response = ""
91
- for _ in range(num_calls):
92
- for message in client.chat_completion(
93
- messages=[{"role": "user", "content": prompt}],
94
- max_tokens=10000,
95
- temperature=temperature,
96
- stream=True,
97
- ):
98
- if message.choices and message.choices[0].delta and message.choices[0].delta.content:
99
- response += message.choices[0].delta.content
100
-
101
- return {
102
- "query": query,
103
- "search_results": search_results,
104
- "relevant_docs": relevant_docs,
105
- "response": response
106
- }
107
-
108
- except Exception as e:
109
- return {"error": f"An error occurred during web search and processing: {str(e)}"}
110
-
111
-
112
- def rephrase_query(original_query: str, conversation_manager: ConversationManager) -> str:
113
- context = conversation_manager.get_context()
114
- if context:
115
- prompt = f"""You are a highly intelligent conversational chatbot. Your task is to analyze the given context and new query, then decide whether to rephrase the query with or without incorporating the context. Follow these steps:
116
-
117
- 1. Determine if the new query is a continuation of the previous conversation or an entirely new topic.
118
- 2. If it's a continuation, rephrase the query by incorporating relevant information from the context to make it more specific and contextual.
119
- 3. If it's a new topic, rephrase the query to make it more appropriate for a web search, focusing on clarity and accuracy without using the previous context.
120
- 4. Provide ONLY the rephrased query without any additional explanation or reasoning.
121
-
122
- Context: {context}
123
-
124
- New query: {original_query}
125
-
126
- Rephrased query:"""
127
- response = DDGS().chat(prompt, model="llama-3.1-70b")
128
- rephrased_query = response.split('\n')[0].strip()
129
- return rephrased_query
130
- return original_query
131
-
132
- def summarize_web_results(query: str, search_results: List[Dict[str, str]], conversation_manager: ConversationManager) -> str:
133
- try:
134
- context = conversation_manager.get_context()
135
- search_context = "\n\n".join([f"Title: {result['title']}\nContent: {result['body']}" for result in search_results])
136
 
137
- prompt = f"""You are a highly intelligent & expert analyst and your job is to skillfully articulate the web search results about '{query}' and considering the context: {context},
138
- You have to create a comprehensive news summary FOCUSING on the context provided to you.
139
- Include key facts, relevant statistics, and expert opinions if available.
140
- Ensure the article is well-structured with an introduction, main body, and conclusion, IF NECESSARY.
141
- Address the query in the context of the ongoing conversation IF APPLICABLE.
142
- Cite sources directly within the generated text and not at the end of the generated text, integrating URLs where appropriate to support the information provided:
143
-
144
- {search_context}
145
-
146
- Article:"""
147
-
148
- summary = DDGS().chat(prompt, model="llama-3.1-70b")
149
- return summary
150
- except Exception as e:
151
- return f"An error occurred during summarization: {str(e)}"
152
-
153
- def respond(message, history, model, temperature, num_calls, use_web_search, search_method):
 
 
 
 
154
  logging.info(f"User Query: {message}")
155
  logging.info(f"Model Used: {model}")
156
- logging.info(f"Use Web Search: {use_web_search}")
157
- logging.info(f"Search Method: {search_method}")
158
-
159
- if use_web_search:
160
- original_query = message
161
- rephrased_query = rephrase_query(message, conversation_manager)
162
- logging.info(f"Original query: {original_query}")
163
- logging.info(f"Rephrased query: {rephrased_query}")
164
-
165
- final_summary = ""
166
- for _ in range(num_calls):
167
- search_results = get_web_search_results(rephrased_query, model, num_calls, temperature, max_results=10, search_method=search_method)
168
- if not search_results:
169
- final_summary += f"No search results found for the query: {rephrased_query}\n\n"
170
- elif "error" in search_results[0]:
171
- final_summary += search_results[0]["error"] + "\n\n"
172
- else:
173
- summary = summarize_web_results(rephrased_query, search_results, conversation_manager)
174
- final_summary += summary + "\n\n"
175
-
176
- if final_summary:
177
- conversation_manager.add_interaction(original_query, final_summary)
178
- yield final_summary
179
- else:
180
- yield "Unable to generate a response. Please try a different query."
181
- else:
182
- yield "Web search is not enabled. Please enable web search to use this feature."
183
 
184
- def vote(data: gr.LikeData):
185
- if data.liked:
186
- print(f"You upvoted this response: {data.value}")
187
- else:
188
- print(f"You downvoted this response: {data.value}")
 
 
189
 
190
  css = """
191
  /* Fine-tune chatbox size */
@@ -198,47 +101,50 @@ css = """
198
  width: 100%;
199
  }
200
  """
201
-
202
- def initial_conversation():
203
- return [
204
- (None, "Welcome! I'm your AI assistant for web search. Here's how you can use me:\n\n"
205
- "1. Make sure the 'Use Web Search' checkbox is enabled in the Additional Inputs section.\n"
206
- "2. Ask me any question, and I'll search the web for the most relevant and up-to-date information.\n"
207
- "3. You can adjust the model, temperature, number of API calls, and search method in the Additional Inputs section to fine-tune your results.\n\n"
208
- "To get started, just ask me a question!")
209
- ]
210
-
211
- # Create the Gradio interface
212
- demo = gr.ChatInterface(
213
- respond,
214
- additional_inputs=[
215
- gr.Dropdown(choices=MODELS, label="Select Model", value=MODELS[0]),
216
- gr.Slider(minimum=0.1, maximum=1.0, value=0.2, step=0.1, label="Temperature"),
217
- gr.Slider(minimum=1, maximum=5, value=1, step=1, label="Number of API Calls"),
218
- gr.Checkbox(label="Use Web Search", value=True),
219
- gr.Radio(["DDGS.chat", "DDGS.text"], label="Search Method", value="DDGS.chat")
220
- ],
221
- title="AI-powered Web Search Assistant",
222
- description="Ask questions and get answers from the latest web information.",
223
- theme=gr.Theme.from_hub("allenai/gradio-theme"),
224
- css=css,
225
- examples=[
226
- ["What's the latest news about artificial intelligence?"],
227
- ["Summarize the current global economic situation."],
228
- ["What are the top environmental concerns right now?"],
229
- ["What are the recent breakthroughs in quantum computing?"]
230
- ],
231
- cache_examples=False,
232
- analytics_enabled=False,
233
- textbox=gr.Textbox(placeholder="Ask any question", container=False, scale=7),
234
- chatbot = gr.Chatbot(
235
- show_copy_button=True,
236
- likeable=True,
237
- layout="bubble",
238
- height=400,
239
- value=initial_conversation()
240
  )
241
- )
 
 
 
 
 
 
 
 
 
 
 
 
242
 
243
  if __name__ == "__main__":
 
244
  demo.launch(share=True)
 
1
  import os
 
2
  import logging
3
  import gradio as gr
 
 
 
4
  from huggingface_hub import InferenceClient
5
+ from langchain.embeddings import HuggingFaceEmbeddings
6
+ from langchain.vectorstores import FAISS
7
+ from langchain.schema import Document
8
+ from duckduckgo_search import DDGS
 
 
 
9
 
10
  # Environment variables and configurations
11
  huggingface_token = os.environ.get("HUGGINGFACE_TOKEN")
12
+ llama_cloud_api_key = os.environ.get("LLAMA_CLOUD_API_KEY")
13
+ ACCOUNT_ID = os.environ.get("CLOUDFARE_ACCOUNT_ID")
14
+ API_TOKEN = os.environ.get("CLOUDFLARE_AUTH_TOKEN")
15
+ API_BASE_URL = f"https://api.cloudflare.com/client/v4/accounts/{ACCOUNT_ID}/ai/run/"
16
+
17
+ print(f"ACCOUNT_ID: {ACCOUNT_ID}")
18
+ print(f"CLOUDFLARE_AUTH_TOKEN: {API_TOKEN[:5]}..." if API_TOKEN else "Not set")
19
 
20
  MODELS = [
21
  "mistralai/Mistral-7B-Instruct-v0.3",
22
  "mistralai/Mixtral-8x7B-Instruct-v0.1",
23
+ "@cf/meta/llama-3.1-8b-instruct",
24
+ "mistralai/Mistral-Nemo-Instruct-2407"
 
 
25
  ]
26
 
27
+ def get_embeddings():
28
+ return HuggingFaceEmbeddings(model_name="sentence-transformers/stsb-roberta-large")
 
 
 
 
 
 
 
 
 
 
 
29
 
30
+ def duckduckgo_search(query):
 
 
31
  with DDGS() as ddgs:
32
+ results = ddgs.text(query, max_results=5)
33
  return results
34
 
35
+ def create_web_search_vectors(search_results):
36
+ embed = get_embeddings()
37
+ documents = []
38
+ for result in search_results:
39
+ if 'body' in result:
40
+ content = f"{result['title']}\n{result['body']}\nSource: {result['href']}"
41
+ documents.append(Document(page_content=content, metadata={"source": result['href']}))
42
+ return FAISS.from_documents(documents, embed)
43
+
44
+ def get_response_with_search(query, model, num_calls=3, temperature=0.2):
45
+ search_results = duckduckgo_search(query)
46
+ web_search_database = create_web_search_vectors(search_results)
47
+ if not web_search_database:
48
+ yield "No web search results available. Please try again.", ""
49
+ return
50
+
51
+ retriever = web_search_database.as_retriever(search_kwargs={"k": 5})
52
+ relevant_docs = retriever.get_relevant_documents(query)
53
+ context = "\n".join([doc.page_content for doc in relevant_docs])
54
+ prompt = f"""Using the following context from web search results:
 
 
 
 
 
 
 
 
55
  {context}
 
56
  Write a detailed and complete research document that fulfills the following user request: '{query}'
57
  After writing the document, please provide a list of sources used in your response."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
 
59
+ if model == "@cf/meta/llama-3.1-8b-instruct":
60
+ # Use Cloudflare API
61
+ for response in get_response_from_cloudflare(prompt="", context=context, query=query, num_calls=num_calls, temperature=temperature, search_type="web"):
62
+ yield response, ""
63
+ else:
64
+ # Use Hugging Face API
65
+ client = InferenceClient(model, token=huggingface_token)
66
+ main_content = ""
67
+ for i in range(num_calls):
68
+ for message in client.chat_completion(
69
+ messages=[{"role": "user", "content": prompt}],
70
+ max_tokens=10000,
71
+ temperature=temperature,
72
+ stream=True,
73
+ ):
74
+ if message.choices and message.choices[0].delta and message.choices[0].delta.content:
75
+ chunk = message.choices[0].delta.content
76
+ main_content += chunk
77
+ yield main_content, ""
78
+
79
+ def respond(message, history, model, temperature, num_calls):
80
  logging.info(f"User Query: {message}")
81
  logging.info(f"Model Used: {model}")
82
+ logging.info(f"Temperature: {temperature}")
83
+ logging.info(f"Number of API Calls: {num_calls}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
+ try:
86
+ for main_content, sources in get_response_with_search(message, model, num_calls=num_calls, temperature=temperature):
87
+ response = f"{main_content}\n\n{sources}"
88
+ yield response
89
+ except Exception as e:
90
+ logging.error(f"Error in respond function: {str(e)}")
91
+ yield f"An error occurred: {str(e)}"
92
 
93
  css = """
94
  /* Fine-tune chatbox size */
 
101
  width: 100%;
102
  }
103
  """
104
+ # Gradio interface setup
105
+ def create_gradio_interface():
106
+ custom_placeholder = "Enter your question here for web search."
107
+
108
+ demo = gr.ChatInterface(
109
+ respond,
110
+ additional_inputs=[
111
+ gr.Dropdown(choices=MODELS, label="Select Model", value=MODELS[3]),
112
+ gr.Slider(minimum=0.1, maximum=1.0, value=0.2, step=0.1, label="Temperature"),
113
+ gr.Slider(minimum=1, maximum=5, value=1, step=1, label="Number of API Calls"),
114
+ ],
115
+ title="AI-powered Web Search Assistant",
116
+ description="Use web search to answer questions or generate summaries.",
117
+ theme=gr.Theme.from_hub("allenai/gradio-theme"),
118
+ css=css,
119
+ examples=[
120
+ ["What are the latest developments in artificial intelligence?"],
121
+ ["Explain the concept of quantum computing."],
122
+ ["What are the environmental impacts of renewable energy?"]
123
+ ],
124
+ cache_examples=False,
125
+ analytics_enabled=False,
126
+ textbox=gr.Textbox(placeholder=custom_placeholder, container=False, scale=7),
127
+ chatbot=gr.Chatbot(
128
+ show_copy_button=True,
129
+ likeable=True,
130
+ layout="bubble",
131
+ height=400,
132
+ )
 
 
 
 
 
 
 
 
 
 
133
  )
134
+
135
+ with demo:
136
+ gr.Markdown("""
137
+ ## How to use
138
+ 1. Enter your question in the chat interface.
139
+ 2. Select the model you want to use from the dropdown.
140
+ 3. Adjust the Temperature to control the randomness of the response.
141
+ 4. Set the Number of API Calls to determine how many times the model will be queried.
142
+ 5. Press Enter or click the submit button to get your answer.
143
+ 6. Use the provided examples or ask your own questions.
144
+ """)
145
+
146
+ return demo
147
 
148
  if __name__ == "__main__":
149
+ demo = create_gradio_interface()
150
  demo.launch(share=True)