File size: 10,392 Bytes
63d903a
e45d4fc
2d75ed4
0b607fb
a7533b2
3890ae0
 
 
 
2594602
64581a6
 
 
781b94b
28ed44f
64581a6
a7533b2
b4dffd4
 
 
2d75ed4
3654925
2d75ed4
b4dffd4
64581a6
b4dffd4
3890ae0
64581a6
3890ae0
9b9a599
3890ae0
64581a6
 
 
 
 
 
 
 
 
5857237
24a7323
 
 
5f389bb
24a7323
 
 
 
 
 
 
 
 
 
 
8052ffa
 
24a7323
8052ffa
 
 
24a7323
 
8052ffa
 
24a7323
5f389bb
24a7323
 
 
 
 
 
 
8052ffa
 
24a7323
8052ffa
3890ae0
64581a6
3890ae0
 
 
 
 
 
64581a6
3890ae0
 
8052ffa
64581a6
3890ae0
9328d2d
 
64581a6
3890ae0
 
 
9328d2d
64581a6
9328d2d
 
 
 
 
64581a6
9328d2d
 
8052ffa
647c306
fb7ae92
 
 
8052ffa
e1a8672
8052ffa
bd71ef9
e1a8672
bd71ef9
 
9b9a599
d9bca78
5860470
 
2d75ed4
5860470
64581a6
5860470
e1a8672
 
 
 
a20790a
2d75ed4
5860470
3fd1094
5860470
 
 
 
 
 
 
 
 
 
2d75ed4
 
 
3890ae0
5860470
64581a6
5860470
 
2d75ed4
a6abb8f
 
3890ae0
 
9328d2d
d1372f5
3890ae0
8052ffa
2ded2ed
8052ffa
2ded2ed
8052ffa
 
3890ae0
 
2d75ed4
64581a6
2d75ed4
3890ae0
 
 
b4dffd4
 
149b538
 
 
 
 
 
 
 
 
b4dffd4
d9bca78
3890ae0
 
64581a6
3890ae0
 
 
 
 
fb7ae92
3890ae0
 
ea8692a
3890ae0
8052ffa
 
3890ae0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204d06f
3890ae0
 
 
 
 
 
 
 
9328d2d
 
 
3890ae0
 
64581a6
3890ae0
b4dffd4
2594602
64581a6
3890ae0
f9f0a5c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
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
232
233
234
235
236
237
238
239
240
241
242
import os
import logging
import asyncio
import gradio as gr
from huggingface_hub import InferenceClient
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.vectorstores import FAISS
from langchain.schema import Document
from duckduckgo_search import DDGS

# Configure logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")

# Environment variables and configurations
huggingface_token = os.environ.get("HUGGINGFACE_TOKEN")
logging.info("Environment variable for HuggingFace token retrieved.")

MODELS = [
    "mistralai/Mistral-7B-Instruct-v0.3",
    "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"
]
logging.info(f"Models list initialized with {len(MODELS)} models.")

def get_embeddings():
    logging.info("Loading HuggingFace embeddings model.")
    return HuggingFaceEmbeddings(model_name="sentence-transformers/stsb-roberta-large")

def duckduckgo_search(query):
    logging.info(f"Initiating DuckDuckGo search for query: {query}")
    try:
        with DDGS() as ddgs:
            results = ddgs.text(query, max_results=10)
        logging.info(f"Search completed, found {len(results)} results.")
        return results
    except Exception as e:
        logging.error(f"Error during DuckDuckGo search: {str(e)}")
        return []

async def rephrase_query(query, context, model):
    # Log the original query for debugging
    logging.info(f"Original query: {query}")

    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:
        1. Determine if the new query is a continuation of the previous conversation or an entirely new topic.
        2. If it's a continuation, rephrase the query by incorporating relevant information from the context to make it more specific and contextual.
        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.
        4. Provide ONLY the rephrased query without any additional explanation or reasoning.
        
        Context: {context}
        
        New query: {query}
        
        Rephrased query:"""

    client = InferenceClient(model, token=huggingface_token)

    try:
        response = await asyncio.to_thread(
            client.text_generation,
            prompt=prompt,
            max_new_tokens=100,
            temperature=0.2,
        )

        # Extract the rephrased query
        rephrased_query = response.strip()

        # Log the rephrased query
        logging.info(f"Rephrased query: {rephrased_query}")

        return rephrased_query

    except Exception as e:
        logging.error(f"Error in rephrase_query: {str(e)}")
        return query  # Fallback to the original query if there's an error

def create_web_search_vectors(search_results):
    logging.info(f"Creating web search vectors from {len(search_results)} search results.")
    embed = get_embeddings()
    documents = []
    for result in search_results:
        if 'body' in result:
            content = f"{result['title']}\n{result['body']}\nSource: {result['href']}"
            documents.append(Document(page_content=content, metadata={"source": result['href']}))
    logging.info(f"{len(documents)} documents created for FAISS vectorization.")
    return FAISS.from_documents(documents, embed)

async def get_response_with_search(query, model, use_embeddings, num_calls=3, temperature=0.2):
    logging.info(f"Performing web search for query: {query}")
    search_results = duckduckgo_search(query)
    
    if not search_results:
        logging.warning("No web search results found.")
        yield "No web search results available. Please try again.", ""
        return

    if use_embeddings:
        logging.info("Using embeddings to retrieve relevant documents.")
        web_search_database = create_web_search_vectors(search_results)
        retriever = 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:
        logging.info("Using raw search results for context.")
        context = "\n".join([f"{result['title']}\n{result['body']}\nSource: {result['href']}" for result in search_results])

    system_message = """ You are a world-class AI system, capable of complex reasoning and reflection. 
    Reason through the query inside <thinking> tags, and then provide your final response inside <output> tags.
    Providing comprehensive and accurate information based on web search results is essential. 
    Your goal is to synthesize the given context into a coherent and detailed response that directly addresses the user's query. 
    Please ensure that your response is well-structured, factual, and cites sources where appropriate.
    If you detect that you made a mistake in your reasoning at any point, correct yourself inside <reflection> tags."""

    user_message = f"""Using the following context from web search results:
{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)
    full_response = ""
    
    try:
        for _ in range(num_calls):
            logging.info(f"Sending request to model with {num_calls} API calls and temperature {temperature}.")
            for response in client.chat_completion(
                messages=[
                    {"role": "system", "content": system_message},
                    {"role": "user", "content": user_message}
                ],
                max_tokens=6000,
                temperature=temperature,
                stream=True,
                top_p=0.8,
            ):
                if isinstance(response, dict) and "choices" in response:
                    for choice in response["choices"]:
                        if "delta" in choice and "content" in choice["delta"]:
                            chunk = choice["delta"]["content"]
                            full_response += chunk
                            yield full_response, ""
                else:
                    logging.error("Unexpected response format or missing attributes in the response object.")
                    break
    except Exception as e:
        logging.error(f"Error in get_response_with_search: {str(e)}")
        yield f"An error occurred while processing your request: {str(e)}", ""

    if not full_response:
        logging.warning("No response generated from the model.")
        yield "No response generated from the model.", ""

async 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"Temperature: {temperature}")
    logging.info(f"Number of API Calls: {num_calls}")
    logging.info(f"Use Embeddings: {use_embeddings}")

    try:
        # Rephrase the query
        rephrased_query = await rephrase_query(message, history, model)
        
        yield f"Rephrased Query: {rephrased_query}\n\nSearching the web...\n\n"
        
        async for main_content, sources in get_response_with_search(rephrased_query, model, use_embeddings, num_calls=num_calls, temperature=temperature):
            response = f"{main_content}\n\n{sources}"
            yield response
    except asyncio.CancelledError:
        logging.warning("Operation cancelled by user.")
        yield "The operation was cancelled. Please try again."
    except Exception as e:
        logging.error(f"Error in respond function: {str(e)}")
        yield f"An error occurred: {str(e)}"

css = """
/* Fine-tune chatbox size */
.chatbot-container {
    height: 600px !important;
    width: 100% !important;
}
.chatbot-container > div {
    height: 100%;
    width: 100%;
}
"""

# Gradio interface setup
def create_gradio_interface():
    logging.info("Setting up Gradio interface.")
    custom_placeholder = "Enter your question here for web search."

    demo = gr.ChatInterface(
        respond,
        additional_inputs=[
            gr.Dropdown(choices=MODELS, label="Select Model", value=MODELS[3]),
            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=False),
        ],
        title="AI-powered Web Search Assistant",
        description="Use web search to answer questions or generate summaries.",
        theme=gr.Theme.from_hub("allenai/gradio-theme"),
        css=css,
        examples=[
            ["What are the latest developments in artificial intelligence?"],
            ["Explain the concept of quantum computing."],
            ["What are the environmental impacts of renewable energy?"]
        ],
        cache_examples=False,
        analytics_enabled=False,
        textbox=gr.Textbox(placeholder=custom_placeholder, container=False, scale=7),
        chatbot=gr.Chatbot(
            show_copy_button=True,
            likeable=True,
            layout="bubble",
            height=400,
        )
    )

    with demo:
        gr.Markdown("""
        ## How to use
        1. Enter your question in the chat interface.
        2. Select the model you want to use from the dropdown.
        3. Adjust the Temperature to control the randomness of the response.
        4. Set the Number of API Calls to determine how many times the model will be queried.
        5. Check or uncheck the "Use Embeddings" box to toggle between using embeddings or direct text summarization.
        6. Press Enter or click the submit button to get your answer.
        7. Use the provided examples or ask your own questions.
        """)

    logging.info("Gradio interface ready.")
    return demo

if __name__ == "__main__":
    logging.info("Launching Gradio application.")
    demo = create_gradio_interface()
    demo.launch(share=True)