Shreyas094 commited on
Commit
2594602
1 Parent(s): 072458d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +145 -144
app.py CHANGED
@@ -1,10 +1,14 @@
1
  import os
2
  import logging
3
  import gradio as gr
4
- from transformers import pipeline
 
 
 
 
 
5
 
6
- from llama_cpp_agent.providers import LlamaCppPythonProvider
7
- from llama_cpp_agent import LlamaCppAgent, MessagesFormatterType
8
  from llama_cpp_agent.chat_history import BasicChatHistory
9
  from llama_cpp_agent.chat_history.messages import Roles
10
  from llama_cpp_agent.llm_output_settings import (
@@ -13,14 +17,74 @@ from llama_cpp_agent.llm_output_settings import (
13
  )
14
  from llama_cpp_agent.tools import WebSearchTool
15
  from llama_cpp_agent.prompt_templates import web_search_system_prompt, research_system_prompt
16
- from pydantic import BaseModel, Field
17
- from trafilatura import fetch_url, extract
18
- import json
19
- from datetime import datetime, timezone
20
- from typing import List
21
- from langchain_community.llms import HuggingFaceHub
22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  huggingface_token = os.environ.get("HUGGINGFACE_TOKEN")
 
 
24
  examples = [
25
  ["latest news about Yann LeCun"],
26
  ["Latest news site:github.blog"],
@@ -28,36 +92,7 @@ examples = [
28
  ["filetype:pdf intitle:python"]
29
  ]
30
 
31
- def get_context_by_model(model_name):
32
- model_context_limits = {
33
- "Mistral-7B-Instruct-v0.3": 32768,
34
- }
35
- return model_context_limits.get(model_name, None)
36
-
37
- def get_messages_formatter_type(model_name):
38
- if model_name is None:
39
- # Handle the case where model_name is None
40
- logging.warning("Model name is None. Defaulting to CHATML formatter.")
41
- return MessagesFormatterType.CHATML
42
-
43
- model_name = model_name.lower()
44
- if "mistral" in model_name:
45
- return MessagesFormatterType.MISTRAL
46
- else:
47
- return MessagesFormatterType.CHATML
48
-
49
- def get_model(temperature, top_p, repetition_penalty):
50
- return HuggingFaceHub(
51
- repo_id="mistralai/Mistral-7B-Instruct-v0.3",
52
- model_kwargs={
53
- "temperature": temperature,
54
- "top_p": top_p,
55
- "repetition_penalty": repetition_penalty,
56
- "max_length": 1000
57
- },
58
- huggingfacehub_api_token=huggingface_token
59
- )
60
-
61
  def get_server_time():
62
  utc_time = datetime.now(timezone.utc)
63
  return utc_time.strftime("%Y-%m-%d %H:%M:%S")
@@ -80,64 +115,52 @@ class CitingSources(BaseModel):
80
  description="List of sources to cite. Should be an URL of the source. E.g. GitHub URL, Blogpost URL or Newsletter URL."
81
  )
82
 
83
- def write_message_to_user():
84
- return "Please write the message to the user."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
 
 
86
  def respond(
87
  message,
88
  history: list[tuple[str, str]],
89
- model,
90
  system_message,
91
  max_tokens,
92
  temperature,
93
  top_p,
94
- top_k,
95
  repeat_penalty,
96
  ):
97
- if model is None:
98
- logging.error("Model is None. Please select a valid model.")
99
- return "Error: No model selected. Please choose a valid model."
100
-
101
- chat_template = get_messages_formatter_type(model)
102
 
103
- # Create a new model instance for each request
104
- llm = get_model(temperature, top_p, repeat_penalty)
105
 
106
- provider = LlamaCppPythonProvider(llm)
107
- logging.info(f"Loaded chat examples: {chat_template}")
108
  search_tool = WebSearchTool(
109
- llm_provider=provider,
110
  message_formatter_type=chat_template,
111
  max_tokens_search_results=12000,
112
  max_tokens_per_summary=2048,
113
  )
114
 
115
- web_search_agent = LlamaCppAgent(
116
- provider,
117
- system_prompt=web_search_system_prompt,
118
- predefined_messages_formatter_type=chat_template,
119
- debug_output=True,
120
- )
121
-
122
- answer_agent = LlamaCppAgent(
123
- provider,
124
- system_prompt=research_system_prompt,
125
- predefined_messages_formatter_type=chat_template,
126
- debug_output=True,
127
- )
128
-
129
- settings = provider.get_provider_default_settings()
130
- settings.stream = False
131
- settings.temperature = temperature
132
- settings.top_k = top_k
133
- settings.top_p = top_p
134
- settings.max_tokens = max_tokens
135
- settings.repeat_penalty = repeat_penalty
136
-
137
- output_settings = LlmStructuredOutputSettings.from_functions(
138
- [search_tool.get_tool()]
139
- )
140
-
141
  messages = BasicChatHistory()
142
 
143
  for msn in history:
@@ -146,82 +169,49 @@ def respond(
146
  messages.add_message(user)
147
  messages.add_message(assistant)
148
 
149
- result = web_search_agent.get_chat_response(
150
- message,
151
- llm_sampling_settings=settings,
152
- structured_output_settings=output_settings,
153
- add_message_to_chat_history=False,
154
- add_response_to_chat_history=False,
155
- print_output=False,
156
- )
157
 
158
  outputs = ""
159
 
160
- settings.stream = True
161
- response_text = answer_agent.get_chat_response(
162
- 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" +
163
- result[0]["return_value"],
164
- role=Roles.tool,
165
- llm_sampling_settings=settings,
166
- chat_history=messages,
167
- returns_streaming_generator=True,
168
- print_output=False,
169
- )
170
 
171
- for text in response_text:
172
- outputs += text
173
- yield outputs
174
 
175
- output_settings = LlmStructuredOutputSettings.from_pydantic_models(
176
- [CitingSources], LlmStructuredOutputType.object_instance
177
- )
178
 
179
- citing_sources = answer_agent.get_chat_response(
180
- "Cite the sources you used in your response.",
181
- role=Roles.tool,
182
- llm_sampling_settings=settings,
183
- chat_history=messages,
184
- returns_streaming_generator=False,
185
- structured_output_settings=output_settings,
186
- print_output=False,
187
- )
188
  outputs += "\n\nSources:\n"
189
- outputs += "\n".join(citing_sources.sources)
190
- yield outputs
 
 
191
 
 
192
  demo = gr.ChatInterface(
193
  respond,
194
  additional_inputs=[
195
  gr.Dropdown([
196
- 'Mistral-7B-Instruct-v0.3'
 
 
197
  ],
198
- value="Mistral-7B-Instruct-v0.3", # Ensure this matches exactly with the option in the list
199
  label="Model"
200
  ),
201
  gr.Textbox(value=web_search_system_prompt, label="System message"),
202
  gr.Slider(minimum=1, maximum=4096, value=2048, step=1, label="Max tokens"),
203
  gr.Slider(minimum=0.1, maximum=1.0, value=0.45, step=0.1, label="Temperature"),
204
- gr.Slider(
205
- minimum=0.1,
206
- maximum=1.0,
207
- value=0.95,
208
- step=0.05,
209
- label="Top-p",
210
- ),
211
- gr.Slider(
212
- minimum=0,
213
- maximum=100,
214
- value=40,
215
- step=1,
216
- label="Top-k",
217
- ),
218
- gr.Slider(
219
- minimum=0.0,
220
- maximum=2.0,
221
- value=1.1,
222
- step=0.1,
223
- label="Repetition penalty",
224
- ),
225
  ],
226
  theme=gr.themes.Soft(
227
  primary_hue="orange",
@@ -236,14 +226,25 @@ demo = gr.ChatInterface(
236
  button_secondary_background_fill_dark="#140b0b",
237
  border_color_accent_dark="#1b0f0f",
238
  border_color_primary_dark="#1b0f0f",
239
- slider_color="#ff911a",
240
- button_primary_background_fill="#ff911a",
241
- button_primary_background_fill_dark="#ff911a",
242
- button_primary_text_color="#f9f9f9",
243
- button_primary_text_color_dark="#f9f9f9"
244
  ),
 
 
 
 
 
 
245
  examples=examples,
246
- title="llama.cpp agent",
 
 
 
 
 
 
247
  )
248
 
249
- demo.queue().launch()
 
 
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 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 (
 
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
 
21
+ # UI related imports and definitions
22
+ css = """
23
+ .message-row {
24
+ justify-content: space-evenly !important;
25
+ }
26
+ .message-bubble-border {
27
+ border-radius: 6px !important;
28
+ }
29
+ .message-buttons-bot, .message-buttons-user {
30
+ right: 10px !important;
31
+ left: auto !important;
32
+ bottom: 2px !important;
33
+ }
34
+ .dark.message-bubble-border {
35
+ border-color: #1b0f0f !important;
36
+ }
37
+ .dark.user {
38
+ background: #140b0b !important;
39
+ }
40
+ .dark.assistant.dark, .dark.pending.dark {
41
+ background: #0c0505 !important;
42
+ }
43
+ """
44
+
45
+ PLACEHOLDER = """
46
+ <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);">
47
+ <figure style="margin: 0;">
48
+ <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;">
49
+ </figure>
50
+ <div style="padding: .5rem 1.5rem;">
51
+ <h2 style="text-align: left; font-size: 1.5rem; font-weight: 700; margin-bottom: 0.5rem;">llama-cpp-agent</h2>
52
+ <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>
53
+ <div style="display: flex; justify-content: space-between; align-items: center;">
54
+ <div style="display: flex; flex-flow: column; justify-content: space-between;">
55
+ <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;">
56
+ Mistral 7B Instruct v0.3
57
+ </span>
58
+ <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;">
59
+ Mixtral 8x7B Instruct v0.1
60
+ </span>
61
+ <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;">
62
+ Meta Llama 3 8B Instruct
63
+ </span>
64
+ </div>
65
+ <div style="display: flex; justify-content: flex-end; align-items: center;">
66
+ <a href="https://discord.gg/fgr5RycPFP" target="_blank" rel="noreferrer" style="padding: .5rem;">
67
+ <svg width="24" height="24" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 5 30.67 23.25">
68
+ <title>Discord</title>
69
+ <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>
70
+ </svg>
71
+ </a>
72
+ <a href="https://github.com/Maximilian-Winter/llama-cpp-agent" target="_blank" rel="noreferrer" style="padding: .5rem;">
73
+ <svg width="24" height="24" fill="currentColor" viewBox="3 3 18 18">
74
+ <title>GitHub</title>
75
+ <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>
76
+ </svg>
77
+ </a>
78
+ </div>
79
+ </div>
80
+ </div>
81
+ </div>
82
+ """
83
+
84
+ # Global variables
85
  huggingface_token = os.environ.get("HUGGINGFACE_TOKEN")
86
+
87
+ # Example queries
88
  examples = [
89
  ["latest news about Yann LeCun"],
90
  ["Latest news site:github.blog"],
 
92
  ["filetype:pdf intitle:python"]
93
  ]
94
 
95
+ # Utility functions
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  def get_server_time():
97
  utc_time = datetime.now(timezone.utc)
98
  return utc_time.strftime("%Y-%m-%d %H:%M:%S")
 
115
  description="List of sources to cite. Should be an URL of the source. E.g. GitHub URL, Blogpost URL or Newsletter URL."
116
  )
117
 
118
+ # Model function
119
+ def get_model(temperature, top_p, repetition_penalty):
120
+ return HuggingFaceHub(
121
+ repo_id="mistralai/Mistral-7B-Instruct-v0.3",
122
+ model_kwargs={
123
+ "temperature": temperature,
124
+ "top_p": top_p,
125
+ "repetition_penalty": repetition_penalty,
126
+ "max_length": 1000
127
+ },
128
+ huggingfacehub_api_token=huggingface_token
129
+ )
130
+ def get_messages_formatter_type(model_name):
131
+ model_name = model_name.lower()
132
+ if any(keyword in model_name for keyword in ["meta", "aya"]):
133
+ return MessagesFormatterType.LLAMA_3
134
+ elif any(keyword in model_name for keyword in ["mistral", "mixtral"]):
135
+ return MessagesFormatterType.MISTRAL
136
+ elif any(keyword in model_name for keyword in ["einstein", "dolphin"]):
137
+ return MessagesFormatterType.CHATML
138
+ elif "phi" in model_name:
139
+ return MessagesFormatterType.PHI_3
140
+ else:
141
+ return MessagesFormatterType.CHATML
142
 
143
+ # Main response function
144
  def respond(
145
  message,
146
  history: list[tuple[str, str]],
 
147
  system_message,
148
  max_tokens,
149
  temperature,
150
  top_p,
 
151
  repeat_penalty,
152
  ):
153
+ model = get_model(temperature, top_p, repeat_penalty)
 
 
 
 
154
 
155
+ chat_template = MessagesFormatterType.MISTRAL
 
156
 
 
 
157
  search_tool = WebSearchTool(
158
+ llm_provider=model,
159
  message_formatter_type=chat_template,
160
  max_tokens_search_results=12000,
161
  max_tokens_per_summary=2048,
162
  )
163
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
164
  messages = BasicChatHistory()
165
 
166
  for msn in history:
 
169
  messages.add_message(user)
170
  messages.add_message(assistant)
171
 
172
+ # Perform web search
173
+ search_result = search_tool.run(message)
 
 
 
 
 
 
174
 
175
  outputs = ""
176
 
177
+ # Generate response
178
+ response_prompt = f"""Write a detailed and complete research document that fulfills the following user request: '{message}', based on the information from the web below.
 
 
 
 
 
 
 
 
179
 
180
+ {search_result}
 
 
181
 
182
+ Respond in a clear and concise manner, citing sources where appropriate."""
 
 
183
 
184
+ response = model(response_prompt)
185
+ outputs += response
186
+
187
+ # Generate citations
188
+ citation_prompt = "Cite the sources you used in your response."
189
+ citing_sources = model(citation_prompt)
190
+
 
 
191
  outputs += "\n\nSources:\n"
192
+ outputs += citing_sources
193
+
194
+ return outputs
195
+
196
 
197
+ # Gradio interface
198
  demo = gr.ChatInterface(
199
  respond,
200
  additional_inputs=[
201
  gr.Dropdown([
202
+ 'Mistral-7B-Instruct-v0.3-Q6_K.gguf',
203
+ 'mixtral-8x7b-instruct-v0.1.Q5_K_M.gguf',
204
+ 'Meta-Llama-3-8B-Instruct-Q6_K.gguf'
205
  ],
206
+ value="Mistral-7B-Instruct-v0.3-Q6_K.gguf",
207
  label="Model"
208
  ),
209
  gr.Textbox(value=web_search_system_prompt, label="System message"),
210
  gr.Slider(minimum=1, maximum=4096, value=2048, step=1, label="Max tokens"),
211
  gr.Slider(minimum=0.1, maximum=1.0, value=0.45, step=0.1, label="Temperature"),
212
+ gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p"),
213
+ gr.Slider(minimum=0, maximum=100, value=40, step=1, label="Top-k"),
214
+ gr.Slider(minimum=0.0, maximum=2.0, value=1.1, step=0.1, label="Repetition penalty"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
215
  ],
216
  theme=gr.themes.Soft(
217
  primary_hue="orange",
 
226
  button_secondary_background_fill_dark="#140b0b",
227
  border_color_accent_dark="#1b0f0f",
228
  border_color_primary_dark="#1b0f0f",
229
+ background_fill_secondary_dark="#0c0505",
230
+ color_accent_soft_dark="transparent",
231
+ code_background_fill_dark="#140b0b"
 
 
232
  ),
233
+ css=css,
234
+ retry_btn="Retry",
235
+ undo_btn="Undo",
236
+ clear_btn="Clear",
237
+ submit_btn="Send",
238
+ cache_examples=False,
239
  examples=examples,
240
+ description="Llama-cpp-agent: Chat with DuckDuckGo Agent",
241
+ analytics_enabled=False,
242
+ chatbot=gr.Chatbot(
243
+ scale=1,
244
+ placeholder=PLACEHOLDER,
245
+ show_copy_button=True
246
+ )
247
  )
248
 
249
+ if __name__ == "__main__":
250
+ demo.launch()