File size: 7,539 Bytes
63d903a
 
e45d4fc
0b607fb
63d903a
9b9a599
e45d4fc
a7533b2
 
a6abb8f
 
2594602
781b94b
28ed44f
a7533b2
b4dffd4
 
 
9b9a599
 
 
 
b4dffd4
 
9b9a599
 
 
 
 
 
 
 
 
 
 
63d903a
9b9a599
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e45d4fc
a6abb8f
 
9b9a599
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149b538
9b9a599
 
 
a6abb8f
9b9a599
 
e45d4fc
d1372f5
b4dffd4
 
 
63d903a
b4dffd4
 
 
149b538
 
 
 
 
 
 
 
 
b4dffd4
a6c785f
d7187db
 
e45d4fc
 
 
 
 
d7187db
149b538
e45d4fc
570f979
b4dffd4
 
e45d4fc
b4dffd4
 
e45d4fc
b4dffd4
e45d4fc
 
685135d
570f979
b4dffd4
e45d4fc
 
 
 
b4dffd4
 
 
e45d4fc
149b538
204d06f
 
 
 
978efd2
204d06f
b4dffd4
 
2594602
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
import os
import json
import logging
import gradio as gr
from duckduckgo_search import DDGS
from typing import List, Dict
from pydantic import BaseModel
from huggingface_hub import InferenceClient

# Set up basic configuration for logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# Environment variables and configurations
huggingface_token = os.environ.get("HUGGINGFACE_TOKEN")

MODELS = [
    "mistralai/Mistral-7B-Instruct-v0.3",
    "mistralai/Mixtral-8x7B-Instruct-v0.1",
    "duckduckgo/gpt-4o-mini",
    "duckduckgo/claude-3-haiku",
    "duckduckgo/llama-3.1-70b",
    "duckduckgo/mixtral-8x7b"
]

class ConversationManager:
    def __init__(self):
        self.history = []
        self.current_context = None

    def add_interaction(self, query, response):
        self.history.append((query, response))
        self.current_context = f"Previous query: {query}\nPrevious response summary: {response[:200]}..."

    def get_context(self):
        return self.current_context

conversation_manager = ConversationManager()

def get_web_search_results(query: str, max_results: int = 10) -> List[Dict[str, str]]:
    try:
        results = list(DDGS().text(query, max_results=max_results))
        if not results:
            print(f"No results found for query: {query}")
        return results
    except Exception as e:
        print(f"An error occurred during web search: {str(e)}")
        return [{"error": f"An error occurred during web search: {str(e)}"}]

def rephrase_query(original_query: str, conversation_manager: ConversationManager) -> str:
    context = conversation_manager.get_context()
    if context:
        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: {original_query}
        
        Rephrased query:"""
        response = DDGS().chat(prompt, model="llama-3.1-70b")
        rephrased_query = response.split('\n')[0].strip()
        return rephrased_query
    return original_query

def summarize_web_results(query: str, search_results: List[Dict[str, str]], conversation_manager: ConversationManager) -> str:
    try:
        context = conversation_manager.get_context()
        search_context = "\n\n".join([f"Title: {result['title']}\nContent: {result['body']}" for result in search_results])

        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}, 
        You have to create a comprehensive news summary FOCUSING on the context provided to you. 
        Include key facts, relevant statistics, and expert opinions if available. 
        Ensure the article is well-structured with an introduction, main body, and conclusion, IF NECESSARY. 
        Address the query in the context of the ongoing conversation IF APPLICABLE.
        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:

        {search_context}

        Article:"""

        summary = DDGS().chat(prompt, model="llama-3.1-70b")
        return summary
    except Exception as e:
        return f"An error occurred during summarization: {str(e)}"

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"Use Web Search: {use_web_search}")

    if use_web_search:
        original_query = message
        rephrased_query = rephrase_query(message, conversation_manager)
        logging.info(f"Original query: {original_query}")
        logging.info(f"Rephrased query: {rephrased_query}")

        final_summary = ""
        for _ in range(num_calls):
            search_results = get_web_search_results(rephrased_query)
            if not search_results:
                final_summary += f"No search results found for the query: {rephrased_query}\n\n"
            elif "error" in search_results[0]:
                final_summary += search_results[0]["error"] + "\n\n"
            else:
                summary = summarize_web_results(rephrased_query, search_results, conversation_manager)
                final_summary += summary + "\n\n"

        if final_summary:
            conversation_manager.add_interaction(original_query, final_summary)
            yield final_summary
        else:
            yield "Unable to generate a response. Please try a different query."
    else:
        yield "Web search is not enabled. Please enable web search to use this feature."

def vote(data: gr.LikeData):
    if data.liked:
        print(f"You upvoted this response: {data.value}")
    else:
        print(f"You downvoted this response: {data.value}")

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

def initial_conversation():
    return [
        (None, "Welcome! I'm your AI assistant for web search. Here's how you can use me:\n\n"
                "1. Make sure the 'Use Web Search' checkbox is enabled in the Additional Inputs section.\n"
                "2. Ask me any question, and I'll search the web for the most relevant and up-to-date information.\n"
                "3. You can adjust the model, temperature, and number of API calls in the Additional Inputs section to fine-tune your results.\n\n"
                "To get started, just ask me a question!")
    ]

# Create the Gradio interface
demo = gr.ChatInterface(
    respond,
    additional_inputs=[
        gr.Dropdown(choices=MODELS, label="Select Model", value=MODELS[0]),
        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 Web Search", value=True)
    ],
    title="AI-powered Web Search Assistant",
    description="Ask questions and get answers from the latest web information.",
    theme=gr.Theme.from_hub("allenai/gradio-theme"),
    css=css,
    examples=[
        ["What's the latest news about artificial intelligence?"],
        ["Summarize the current global economic situation."],
        ["What are the top environmental concerns right now?"],
        ["What are the recent breakthroughs in quantum computing?"]
    ],
    cache_examples=False,
    analytics_enabled=False,
    textbox=gr.Textbox(placeholder="Ask any question", container=False, scale=7),
    chatbot = gr.Chatbot(  
        show_copy_button=True,
        likeable=True,
        layout="bubble",
        height=400,
        value=initial_conversation()
    )
)

if __name__ == "__main__":
    demo.launch(share=True)