Shreyas094
commited on
Commit
•
be913ab
1
Parent(s):
eb3d2d2
Update app.py
Browse files
app.py
CHANGED
@@ -1,384 +1,101 @@
|
|
1 |
-
import os
|
2 |
-
import logging
|
3 |
import gradio as gr
|
|
|
|
|
|
|
4 |
import json
|
5 |
from typing import List
|
6 |
-
from datetime import datetime, timezone
|
7 |
from pydantic import BaseModel, Field
|
8 |
-
from trafilatura import fetch_url, extract
|
9 |
-
from langchain_community.llms import HuggingFaceHub
|
10 |
-
|
11 |
-
from llama_cpp_agent import MessagesFormatterType
|
12 |
-
from llama_cpp_agent.chat_history import BasicChatHistory
|
13 |
-
from llama_cpp_agent.chat_history.messages import Roles
|
14 |
-
from llama_cpp_agent.llm_output_settings import (
|
15 |
-
LlmStructuredOutputSettings,
|
16 |
-
LlmStructuredOutputType,
|
17 |
-
)
|
18 |
-
from llama_cpp_agent.tools import WebSearchTool
|
19 |
-
from llama_cpp_agent.prompt_templates import web_search_system_prompt, research_system_prompt
|
20 |
-
from langchain_community.llms import HuggingFaceHub
|
21 |
-
from llama_cpp_agent.llm_output_settings import LlmStructuredOutputSettings, LlmStructuredOutputType
|
22 |
-
from pydantic import BaseModel, Field
|
23 |
-
from llama_cpp_agent.llm_output_settings import LlmStructuredOutputType
|
24 |
-
from llama_cpp import Llama
|
25 |
-
from llama_cpp_agent.providers import LlamaCppPythonProvider
|
26 |
-
from llama_cpp_agent.chat_history import BasicChatHistory
|
27 |
-
from llama_cpp_agent.chat_history.messages import Roles
|
28 |
-
from llama_cpp_agent.llm_output_settings import LlmStructuredOutputSettings, LlmStructuredOutputType
|
29 |
-
from llama_cpp_agent.tools import WebSearchTool
|
30 |
-
from llama_cpp_agent.prompt_templates import web_search_system_prompt, research_system_prompt
|
31 |
-
from pydantic import BaseModel, Field
|
32 |
-
from typing import List
|
33 |
-
|
34 |
-
print("Available LlmStructuredOutputType options:")
|
35 |
-
for option in LlmStructuredOutputType:
|
36 |
-
print(option)
|
37 |
-
|
38 |
-
# UI related imports and definitions
|
39 |
-
css = """
|
40 |
-
.message-row {
|
41 |
-
justify-content: space-evenly !important;
|
42 |
-
}
|
43 |
-
.message-bubble-border {
|
44 |
-
border-radius: 6px !important;
|
45 |
-
}
|
46 |
-
.message-buttons-bot, .message-buttons-user {
|
47 |
-
right: 10px !important;
|
48 |
-
left: auto !important;
|
49 |
-
bottom: 2px !important;
|
50 |
-
}
|
51 |
-
.dark.message-bubble-border {
|
52 |
-
border-color: #1b0f0f !important;
|
53 |
-
}
|
54 |
-
.dark.user {
|
55 |
-
background: #140b0b !important;
|
56 |
-
}
|
57 |
-
.dark.assistant.dark, .dark.pending.dark {
|
58 |
-
background: #0c0505 !important;
|
59 |
-
}
|
60 |
-
"""
|
61 |
-
|
62 |
-
PLACEHOLDER = """
|
63 |
-
<div class="message-bubble-border" style="display:flex; max-width: 600px; border-width: 1px; border-color: #e5e7eb; border-radius: 8px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); backdrop-filter: blur(10px);">
|
64 |
-
<figure style="margin: 0;">
|
65 |
-
<img src="https://huggingface.co/spaces/poscye/ddg-web-search-chat/resolve/main/logo.jpg" alt="Logo" style="width: 100%; height: 100%; border-radius: 8px;">
|
66 |
-
</figure>
|
67 |
-
<div style="padding: .5rem 1.5rem;">
|
68 |
-
<h2 style="text-align: left; font-size: 1.5rem; font-weight: 700; margin-bottom: 0.5rem;">llama-cpp-agent</h2>
|
69 |
-
<p style="text-align: left; font-size: 16px; line-height: 1.5; margin-bottom: 15px;">DDG Agent allows users to interact with it using natural language, making it easier for them to find the information they need. Offers a convenient and secure way for users to access web-based information.</p>
|
70 |
-
<div style="display: flex; justify-content: space-between; align-items: center;">
|
71 |
-
<div style="display: flex; flex-flow: column; justify-content: space-between;">
|
72 |
-
<span style="display: inline-flex; align-items: center; border-radius: 0.375rem; background-color: rgba(229, 70, 77, 0.1); padding: 0.1rem 0.75rem; font-size: 0.75rem; font-weight: 500; color: #f88181; margin-bottom: 2.5px;">
|
73 |
-
Mistral 7B Instruct v0.3
|
74 |
-
</span>
|
75 |
-
<span style="display: inline-flex; align-items: center; border-radius: 0.375rem; background-color: rgba(229, 70, 77, 0.1); padding: 0.1rem 0.75rem; font-size: 0.75rem; font-weight: 500; color: #f88181; margin-bottom: 2.5px;">
|
76 |
-
Mixtral 8x7B Instruct v0.1
|
77 |
-
</span>
|
78 |
-
<span style="display: inline-flex; align-items: center; border-radius: 0.375rem; background-color: rgba(79, 70, 229, 0.1); padding: 0.1rem 0.75rem; font-size: 0.75rem; font-weight: 500; color: #60a5fa; margin-top: 2.5px;">
|
79 |
-
Meta Llama 3 8B Instruct
|
80 |
-
</span>
|
81 |
-
</div>
|
82 |
-
<div style="display: flex; justify-content: flex-end; align-items: center;">
|
83 |
-
<a href="https://discord.gg/fgr5RycPFP" target="_blank" rel="noreferrer" style="padding: .5rem;">
|
84 |
-
<svg width="24" height="24" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 5 30.67 23.25">
|
85 |
-
<title>Discord</title>
|
86 |
-
<path d="M26.0015 6.9529C24.0021 6.03845 21.8787 5.37198 19.6623 5C19.3833 5.48048 19.0733 6.13144 18.8563 6.64292C16.4989 6.30193 14.1585 6.30193 11.8336 6.64292C11.6166 6.13144 11.2911 5.48048 11.0276 5C8.79575 5.37198 6.67235 6.03845 4.6869 6.9529C0.672601 12.8736 -0.41235 18.6548 0.130124 24.3585C2.79599 26.2959 5.36889 27.4739 7.89682 28.2489C8.51679 27.4119 9.07477 26.5129 9.55525 25.5675C8.64079 25.2265 7.77283 24.808 6.93587 24.312C7.15286 24.1571 7.36986 23.9866 7.57135 23.8161C12.6241 26.1255 18.0969 26.1255 23.0876 23.8161C23.3046 23.9866 23.5061 24.1571 23.7231 24.312C22.8861 24.808 22.0182 25.2265 21.1037 25.5675C21.5842 26.5129 22.1422 27.4119 22.7621 28.2489C25.2885 27.4739 27.8769 26.2959 30.5288 24.3585C31.1952 17.7559 29.4733 12.0212 26.0015 6.9529ZM10.2527 20.8402C8.73376 20.8402 7.49382 19.4608 7.49382 17.7714C7.49382 16.082 8.70276 14.7025 10.2527 14.7025C11.7871 14.7025 13.0425 16.082 13.0115 17.7714C13.0115 19.4608 11.7871 20.8402 10.2527 20.8402ZM20.4373 20.8402C18.9183 20.8402 17.6768 19.4608 17.6768 17.7714C17.6768 16.082 18.8873 14.7025 20.4373 14.7025C21.9717 14.7025 23.2271 16.082 23.1961 17.7714C23.1961 19.4608 21.9872 20.8402 20.4373 20.8402Z"></path>
|
87 |
-
</svg>
|
88 |
-
</a>
|
89 |
-
<a href="https://github.com/Maximilian-Winter/llama-cpp-agent" target="_blank" rel="noreferrer" style="padding: .5rem;">
|
90 |
-
<svg width="24" height="24" fill="currentColor" viewBox="3 3 18 18">
|
91 |
-
<title>GitHub</title>
|
92 |
-
<path d="M12 3C7.0275 3 3 7.12937 3 12.2276C3 16.3109 5.57625 19.7597 9.15374 20.9824C9.60374 21.0631 9.77249 20.7863 9.77249 20.5441C9.77249 20.3249 9.76125 19.5982 9.76125 18.8254C7.5 19.2522 6.915 18.2602 6.735 17.7412C6.63375 17.4759 6.19499 16.6569 5.8125 16.4378C5.4975 16.2647 5.0475 15.838 5.80124 15.8264C6.51 15.8149 7.01625 16.4954 7.18499 16.7723C7.99499 18.1679 9.28875 17.7758 9.80625 17.5335C9.885 16.9337 10.1212 16.53 10.38 16.2993C8.3775 16.0687 6.285 15.2728 6.285 11.7432C6.285 10.7397 6.63375 9.9092 7.20749 9.26326C7.1175 9.03257 6.8025 8.08674 7.2975 6.81794C7.2975 6.81794 8.05125 6.57571 9.77249 7.76377C10.4925 7.55615 11.2575 7.45234 12.0225 7.45234C12.7875 7.45234 13.5525 7.55615 14.2725 7.76377C15.9937 6.56418 16.7475 6.81794 16.7475 6.81794C17.2424 8.08674 16.9275 9.03257 16.8375 9.26326C17.4113 9.9092 17.76 10.7281 17.76 11.7432C17.76 15.2843 15.6563 16.0687 13.6537 16.2993C13.98 16.5877 14.2613 17.1414 14.2613 18.0065C14.2613 19.2407 14.25 20.2326 14.25 20.5441C14.25 20.7863 14.4188 21.0746 14.8688 20.9824C16.6554 20.364 18.2079 19.1866 19.3078 17.6162C20.4077 16.0457 20.9995 14.1611 21 12.2276C21 7.12937 16.9725 3 12 3Z"></path>
|
93 |
-
</svg>
|
94 |
-
</a>
|
95 |
-
</div>
|
96 |
-
</div>
|
97 |
-
</div>
|
98 |
-
</div>
|
99 |
-
"""
|
100 |
|
101 |
# Global variables
|
102 |
huggingface_token = os.environ.get("HUGGINGFACE_TOKEN")
|
103 |
|
104 |
-
#
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
["filetype:pdf intitle:python"]
|
110 |
-
]
|
111 |
-
|
112 |
-
class CustomLLMSettings(BaseModel):
|
113 |
-
structured_output: LlmStructuredOutputSettings
|
114 |
-
temperature: float = Field(default=0.7)
|
115 |
-
top_p: float = Field(default=0.95)
|
116 |
-
repetition_penalty: float = Field(default=1.1)
|
117 |
-
top_k: int = Field(default=50)
|
118 |
-
max_tokens: int = Field(default=1000)
|
119 |
-
stop: list[str] = Field(default_factory=list)
|
120 |
-
echo: bool = Field(default=False)
|
121 |
-
stream: bool = Field(default=False)
|
122 |
-
logprobs: int = Field(default=None)
|
123 |
-
presence_penalty: float = Field(default=0.0)
|
124 |
-
frequency_penalty: float = Field(default=0.0)
|
125 |
-
best_of: int = Field(default=1)
|
126 |
-
logit_bias: dict = Field(default_factory=dict)
|
127 |
-
max_tokens_per_summary: int = Field(default=2048)
|
128 |
-
|
129 |
-
class HuggingFaceHubWrapper:
|
130 |
-
def __init__(self, repo_id, model_kwargs, huggingfacehub_api_token):
|
131 |
-
self.model = HuggingFaceHub(
|
132 |
-
repo_id=repo_id,
|
133 |
-
model_kwargs=model_kwargs,
|
134 |
-
huggingfacehub_api_token=huggingfacehub_api_token
|
135 |
-
)
|
136 |
-
self.temperature = model_kwargs.get('temperature', 0.7)
|
137 |
-
self.top_p = model_kwargs.get('top_p', 0.95)
|
138 |
-
self.repetition_penalty = model_kwargs.get('repetition_penalty', 1.1)
|
139 |
-
self.top_k = model_kwargs.get('top_k', 50)
|
140 |
-
self.max_tokens = model_kwargs.get('max_length', 1000)
|
141 |
-
self.max_tokens_per_summary = model_kwargs.get('max_tokens_per_summary', 2048)
|
142 |
-
|
143 |
-
def get_provider_default_settings(self):
|
144 |
-
return CustomLLMSettings(
|
145 |
-
structured_output=LlmStructuredOutputSettings(
|
146 |
-
output_type=LlmStructuredOutputType.no_structured_output,
|
147 |
-
include_system_prompt=False,
|
148 |
-
include_user_prompt=False,
|
149 |
-
include_assistant_prompt=False,
|
150 |
-
),
|
151 |
-
temperature=self.temperature,
|
152 |
-
top_p=self.top_p,
|
153 |
-
repetition_penalty=self.repetition_penalty,
|
154 |
-
top_k=self.top_k,
|
155 |
-
max_tokens=self.max_tokens,
|
156 |
-
max_tokens_per_summary=self.max_tokens_per_summary
|
157 |
-
)
|
158 |
-
|
159 |
-
def get_provider_identifier(self):
|
160 |
-
return "HuggingFaceHub"
|
161 |
-
|
162 |
-
def __call__(self, *args, **kwargs):
|
163 |
-
return self.model(*args, **kwargs)
|
164 |
-
|
165 |
-
def get_num_tokens(self, text):
|
166 |
-
# This is a placeholder. You might need to implement a proper token counting method
|
167 |
-
return len(text.split())
|
168 |
-
|
169 |
-
def get_max_tokens(self):
|
170 |
-
# This is a placeholder. Return the actual max tokens for your model
|
171 |
-
return 2048
|
172 |
-
|
173 |
-
# Utility functions
|
174 |
-
def get_server_time():
|
175 |
-
utc_time = datetime.now(timezone.utc)
|
176 |
-
return utc_time.strftime("%Y-%m-%d %H:%M:%S")
|
177 |
-
|
178 |
-
def get_website_content_from_url(url: str) -> str:
|
179 |
-
try:
|
180 |
-
downloaded = fetch_url(url)
|
181 |
-
result = extract(downloaded, include_formatting=True, include_links=True, output_format='json', url=url)
|
182 |
-
if result:
|
183 |
-
result = json.loads(result)
|
184 |
-
return f'=========== Website Title: {result["title"]} ===========\n\n=========== Website URL: {url} ===========\n\n=========== Website Content ===========\n\n{result["raw_text"]}\n\n=========== Website Content End ===========\n\n'
|
185 |
-
else:
|
186 |
-
return ""
|
187 |
-
except Exception as e:
|
188 |
-
return f"An error occurred: {str(e)}"
|
189 |
|
190 |
class CitingSources(BaseModel):
|
191 |
sources: List[str] = Field(
|
192 |
...,
|
193 |
-
description="List of sources to cite. Should be an URL of the source.
|
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 |
else:
|
222 |
-
return
|
223 |
-
|
224 |
-
# Main response function
|
225 |
-
def respond(
|
226 |
-
message,
|
227 |
-
history: list[tuple[str, str]],
|
228 |
-
model,
|
229 |
-
system_message,
|
230 |
-
max_tokens,
|
231 |
-
temperature,
|
232 |
-
top_p,
|
233 |
-
top_k,
|
234 |
-
repeat_penalty,
|
235 |
-
):
|
236 |
-
global llm
|
237 |
-
global llm_model
|
238 |
-
|
239 |
-
chat_template = get_messages_formatter_type(model)
|
240 |
-
|
241 |
-
if llm is None or llm_model != model:
|
242 |
-
llm = Llama(
|
243 |
-
model_path=f"models/{model}",
|
244 |
-
flash_attn=True,
|
245 |
-
n_gpu_layers=81,
|
246 |
-
n_batch=1024,
|
247 |
-
n_ctx=get_context_by_model(model),
|
248 |
-
)
|
249 |
-
llm_model = model
|
250 |
-
|
251 |
-
provider = LlamaCppPythonProvider(llm)
|
252 |
-
logging.info(f"Loaded chat examples: {chat_template}")
|
253 |
-
|
254 |
-
search_tool = WebSearchTool(
|
255 |
-
llm_provider=provider,
|
256 |
-
message_formatter_type=chat_template,
|
257 |
-
max_tokens_search_results=12000,
|
258 |
-
max_tokens_per_summary=2048,
|
259 |
-
)
|
260 |
-
|
261 |
-
web_search_agent = LlamaCppAgent(
|
262 |
-
provider,
|
263 |
-
system_prompt=web_search_system_prompt,
|
264 |
-
predefined_messages_formatter_type=chat_template,
|
265 |
-
debug_output=True,
|
266 |
-
)
|
267 |
-
|
268 |
-
answer_agent = LlamaCppAgent(
|
269 |
-
provider,
|
270 |
-
system_prompt=research_system_prompt,
|
271 |
-
predefined_messages_formatter_type=chat_template,
|
272 |
-
debug_output=True,
|
273 |
-
)
|
274 |
-
|
275 |
-
settings = provider.get_provider_default_settings()
|
276 |
-
settings.stream = False
|
277 |
-
settings.temperature = temperature
|
278 |
-
settings.top_k = top_k
|
279 |
-
settings.top_p = top_p
|
280 |
-
settings.max_tokens = max_tokens
|
281 |
-
settings.repeat_penalty = repeat_penalty
|
282 |
-
|
283 |
-
output_settings = LlmStructuredOutputSettings.from_functions(
|
284 |
-
[search_tool.get_tool()]
|
285 |
-
)
|
286 |
-
|
287 |
-
messages = BasicChatHistory()
|
288 |
-
for msn in history:
|
289 |
-
user = {"role": Roles.user, "content": msn[0]}
|
290 |
-
assistant = {"role": Roles.assistant, "content": msn[1]}
|
291 |
-
messages.add_message(user)
|
292 |
-
messages.add_message(assistant)
|
293 |
-
|
294 |
-
result = web_search_agent.get_chat_response(
|
295 |
-
message,
|
296 |
-
llm_sampling_settings=settings,
|
297 |
-
structured_output_settings=output_settings,
|
298 |
-
add_message_to_chat_history=False,
|
299 |
-
add_response_to_chat_history=False,
|
300 |
-
print_output=False,
|
301 |
-
)
|
302 |
-
|
303 |
-
outputs = ""
|
304 |
-
settings.stream = True
|
305 |
-
|
306 |
-
response_text = answer_agent.get_chat_response(
|
307 |
-
f"Write a detailed and complete research document that fulfills the following user request: '{message}', based on the information from the web below.\n\n" + result[0]["return_value"],
|
308 |
-
role=Roles.tool,
|
309 |
-
llm_sampling_settings=settings,
|
310 |
-
chat_history=messages,
|
311 |
-
returns_streaming_generator=True,
|
312 |
-
print_output=False,
|
313 |
-
)
|
314 |
-
|
315 |
-
for text in response_text:
|
316 |
-
outputs += text
|
317 |
-
yield outputs
|
318 |
-
|
319 |
-
output_settings = LlmStructuredOutputSettings.from_pydantic_models(
|
320 |
-
[CitingSources], LlmStructuredOutputType.object_instance
|
321 |
-
)
|
322 |
-
|
323 |
-
citing_sources = answer_agent.get_chat_response(
|
324 |
-
"Cite the sources you used in your response.",
|
325 |
-
role=Roles.tool,
|
326 |
-
llm_sampling_settings=settings,
|
327 |
-
chat_history=messages,
|
328 |
-
returns_streaming_generator=False,
|
329 |
-
structured_output_settings=output_settings,
|
330 |
-
print_output=False,
|
331 |
-
)
|
332 |
-
|
333 |
-
outputs += "\n\nSources:\n"
|
334 |
-
outputs += "\n".join(citing_sources.sources)
|
335 |
-
yield outputs
|
336 |
|
|
|
|
|
|
|
|
|
337 |
|
338 |
# Gradio interface
|
339 |
-
|
340 |
-
|
341 |
-
|
342 |
-
|
343 |
-
|
344 |
-
|
345 |
-
|
346 |
-
|
347 |
-
|
348 |
-
|
349 |
-
|
350 |
-
|
351 |
-
primary_hue="orange",
|
352 |
-
secondary_hue="amber",
|
353 |
-
neutral_hue="gray",
|
354 |
-
font=[gr.themes.GoogleFont("Exo"), "ui-sans-serif", "system-ui", "sans-serif"]).set(
|
355 |
-
body_background_fill_dark="#0c0505",
|
356 |
-
block_background_fill_dark="#0c0505",
|
357 |
-
block_border_width="1px",
|
358 |
-
block_title_background_fill_dark="#1b0f0f",
|
359 |
-
input_background_fill_dark="#140b0b",
|
360 |
-
button_secondary_background_fill_dark="#140b0b",
|
361 |
-
border_color_accent_dark="#1b0f0f",
|
362 |
-
border_color_primary_dark="#1b0f0f",
|
363 |
-
background_fill_secondary_dark="#0c0505",
|
364 |
-
color_accent_soft_dark="transparent",
|
365 |
-
code_background_fill_dark="#140b0b"
|
366 |
-
),
|
367 |
-
css=css,
|
368 |
-
retry_btn="Retry",
|
369 |
-
undo_btn="Undo",
|
370 |
-
clear_btn="Clear",
|
371 |
-
submit_btn="Send",
|
372 |
-
cache_examples=False,
|
373 |
-
examples=examples,
|
374 |
-
description="Mistral-7B: Chat with DuckDuckGo Agent",
|
375 |
-
analytics_enabled=False,
|
376 |
-
chatbot=gr.Chatbot(
|
377 |
-
scale=1,
|
378 |
-
placeholder=PLACEHOLDER,
|
379 |
-
show_copy_button=True
|
380 |
-
)
|
381 |
)
|
382 |
|
383 |
if __name__ == "__main__":
|
384 |
-
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
+
from huggingface_hub import InferenceApi
|
3 |
+
from duckduckgo_search import DDGS
|
4 |
+
import requests
|
5 |
import json
|
6 |
from typing import List
|
|
|
7 |
from pydantic import BaseModel, Field
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
|
9 |
# Global variables
|
10 |
huggingface_token = os.environ.get("HUGGINGFACE_TOKEN")
|
11 |
|
12 |
+
# Function to perform a DuckDuckGo search
|
13 |
+
def duckduckgo_search(query):
|
14 |
+
with DDGS() as ddgs:
|
15 |
+
results = ddgs.text(query, max_results=5)
|
16 |
+
return results
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
|
18 |
class CitingSources(BaseModel):
|
19 |
sources: List[str] = Field(
|
20 |
...,
|
21 |
+
description="List of sources to cite. Should be an URL of the source."
|
22 |
)
|
23 |
|
24 |
+
def get_response_with_search(query):
|
25 |
+
# Perform the web search
|
26 |
+
search_results = duckduckgo_search(query)
|
27 |
+
|
28 |
+
# Use the search results as context for the model
|
29 |
+
context = "\n".join(f"{result['title']}\n{result['body']}\nSource: {result['href']}\n"
|
30 |
+
for result in search_results if 'body' in result)
|
31 |
+
|
32 |
+
# Prompt formatted for Mistral-7B-Instruct
|
33 |
+
prompt = f"""<s>[INST] Using the following context:
|
34 |
+
{context}
|
35 |
+
Write a detailed and complete research document that fulfills the following user request: '{query}'
|
36 |
+
After writing the document, please provide a list of sources used in your response. [/INST]"""
|
37 |
+
|
38 |
+
# API endpoint for Mistral-7B-Instruct-v0.3
|
39 |
+
API_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.3"
|
40 |
+
|
41 |
+
# Headers
|
42 |
+
headers = {"Authorization": f"Bearer {huggingface_token}"}
|
43 |
+
|
44 |
+
# Payload
|
45 |
+
payload = {
|
46 |
+
"inputs": prompt,
|
47 |
+
"parameters": {
|
48 |
+
"max_new_tokens": 1000,
|
49 |
+
"temperature": 0.7,
|
50 |
+
"top_p": 0.95,
|
51 |
+
"top_k": 40,
|
52 |
+
"repetition_penalty": 1.1
|
53 |
+
}
|
54 |
+
}
|
55 |
+
|
56 |
+
# Make the API call
|
57 |
+
response = requests.post(API_URL, headers=headers, json=payload)
|
58 |
+
|
59 |
+
if response.status_code == 200:
|
60 |
+
result = response.json()
|
61 |
+
if isinstance(result, list) and len(result) > 0:
|
62 |
+
generated_text = result[0].get('generated_text', 'No text generated')
|
63 |
+
|
64 |
+
# Remove the instruction part
|
65 |
+
content_start = generated_text.find("[/INST]")
|
66 |
+
if content_start != -1:
|
67 |
+
generated_text = generated_text[content_start + 7:].strip()
|
68 |
+
|
69 |
+
# Split the response into main content and sources
|
70 |
+
parts = generated_text.split("Sources:", 1)
|
71 |
+
main_content = parts[0].strip()
|
72 |
+
sources = parts[1].strip() if len(parts) > 1 else ""
|
73 |
+
|
74 |
+
return main_content, sources
|
75 |
+
else:
|
76 |
+
return f"Unexpected response format: {result}", ""
|
77 |
else:
|
78 |
+
return f"Error: API returned status code {response.status_code}", ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
79 |
|
80 |
+
def gradio_interface(query):
|
81 |
+
main_content, sources = get_response_with_search(query)
|
82 |
+
formatted_response = f"{main_content}\n\nSources:\n{sources}"
|
83 |
+
return formatted_response
|
84 |
|
85 |
# Gradio interface
|
86 |
+
iface = gr.Interface(
|
87 |
+
fn=gradio_interface,
|
88 |
+
inputs=gr.Textbox(lines=2, placeholder="Enter your question here..."),
|
89 |
+
outputs="text",
|
90 |
+
title="AI-powered Web Search Assistant",
|
91 |
+
description="Ask a question, and I'll search the web and provide an answer using the Mistral-7B-Instruct model.",
|
92 |
+
examples=[
|
93 |
+
["Latest news about Yann LeCun"],
|
94 |
+
["Latest news site:github.blog"],
|
95 |
+
["Where I can find best hotel in Galapagos, Ecuador intitle:hotel"],
|
96 |
+
["filetype:pdf intitle:python"]
|
97 |
+
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
98 |
)
|
99 |
|
100 |
if __name__ == "__main__":
|
101 |
+
iface.launch()
|