Update app.py
Browse files
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
|
10 |
-
from
|
11 |
-
from
|
12 |
-
|
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 |
-
"
|
24 |
-
"
|
25 |
-
"duckduckgo/llama-3.1-70b",
|
26 |
-
"duckduckgo/mixtral-8x7b"
|
27 |
]
|
28 |
|
29 |
-
|
30 |
-
|
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 |
-
|
44 |
-
|
45 |
-
def duckduckgo_search(query: str, max_results: int = 10) -> List[Dict[str, str]]:
|
46 |
with DDGS() as ddgs:
|
47 |
-
results =
|
48 |
return results
|
49 |
|
50 |
-
def
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
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 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
|
|
|
|
|
|
|
|
154 |
logging.info(f"User Query: {message}")
|
155 |
logging.info(f"Model Used: {model}")
|
156 |
-
logging.info(f"
|
157 |
-
logging.info(f"
|
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 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
|
|
|
|
189 |
|
190 |
css = """
|
191 |
/* Fine-tune chatbox size */
|
@@ -198,47 +101,50 @@ css = """
|
|
198 |
width: 100%;
|
199 |
}
|
200 |
"""
|
201 |
-
|
202 |
-
def
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
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)
|