Lumpen1 commited on
Commit
0826ff1
1 Parent(s): c584163

Initial Commit

Browse files
Files changed (3) hide show
  1. app.py +220 -0
  2. content.py +43 -0
  3. utils.py +43 -0
app.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Defaults
2
+ import spaces
3
+ import logging
4
+ import gradio as gr
5
+ from llama_cpp import Llama
6
+
7
+ # Locals
8
+ from llama_cpp_agent.providers import LlamaCppPythonProvider
9
+ from content import css, PLACEHOLDER
10
+ from utils import CitingSources
11
+ # Agents
12
+ from llama_cpp_agent import LlamaCppAgent
13
+ from llama_cpp_agent.chat_history import BasicChatHistory
14
+ from llama_cpp_agent.chat_history.messages import Roles
15
+ from llama_cpp_agent.llm_output_settings import (
16
+ LlmStructuredOutputSettings,
17
+ LlmStructuredOutputType,
18
+ )
19
+ # Tools
20
+ from llama_cpp_agent.tools import WebSearchTool
21
+ from llama_cpp_agent.prompt_templates import web_search_system_prompt, research_system_prompt
22
+
23
+ examples = [
24
+ ["Latest uplifting news"],
25
+ ["Latest news site:bloomberg.com"],
26
+ ["Where I can find best hotel in Galapagos, Ecuador intitle:hotel"],
27
+ ["filetype:pdf intitle:python"]
28
+ ]
29
+
30
+ def get_context_by_model(model_name):
31
+ model_context_limits = {
32
+ "Mistral-7B-Instruct-v0.3-Q6_K.gguf": 32768,
33
+ "Meta-Llama-3-8B-Instruct-Q6_K.gguf": 8192
34
+ }
35
+ return model_context_limits.get(model_name, None)
36
+
37
+ def get_messages_formatter_type(model_name):
38
+ from llama_cpp_agent import MessagesFormatterType
39
+ if "Meta" in model_name or "aya" in model_name:
40
+ return MessagesFormatterType.LLAMA_3
41
+ elif "Mistral" in model_name:
42
+ return MessagesFormatterType.MISTRAL
43
+ elif "Einstein-v6-7B" in model_name or "dolphin" in model_name:
44
+ return MessagesFormatterType.CHATML
45
+ elif "Phi" in model_name:
46
+ return MessagesFormatterType.PHI_3
47
+ else:
48
+ return MessagesFormatterType.CHATML
49
+
50
+ ## Run inference
51
+ @spaces.GPU(duration=120)
52
+ def respond(
53
+ message,
54
+ history: list[tuple[str, str]],
55
+ system_message,
56
+ max_tokens,
57
+ temperature,
58
+ top_p,
59
+ top_k,
60
+ repetition_penalty,
61
+ model,
62
+ ):
63
+ chat_template = get_messages_formatter_type(model)
64
+ llm = Llama(
65
+ model_path=f"models/{model}",
66
+ flash_attn=True,
67
+ n_threads=40,
68
+ n_gpu_layers=81,
69
+ n_batch=1024,
70
+ n_ctx=get_context_by_model(model),
71
+ )
72
+ provider = LlamaCppPythonProvider(llm)
73
+ logging.info(f"Loaded chat examples: {chat_template}")
74
+ search_tool = WebSearchTool(
75
+ llm_provider=provider,
76
+ message_formatter_type=chat_template,
77
+ max_tokens_search_results=12000,
78
+ max_tokens_per_summary=2048,
79
+ )
80
+
81
+ web_search_agent = LlamaCppAgent(
82
+ provider,
83
+ system_prompt=web_search_system_prompt,
84
+ predefined_messages_formatter_type=chat_template,
85
+ debug_output=True,
86
+ )
87
+
88
+ answer_agent = LlamaCppAgent(
89
+ provider,
90
+ system_prompt=research_system_prompt,
91
+ predefined_messages_formatter_type=chat_template,
92
+ debug_output=True,
93
+ )
94
+
95
+ settings = provider.get_provider_default_settings()
96
+ settings.stream = False
97
+ settings.temperature = temperature
98
+ settings.top_k = top_k
99
+ settings.top_p = top_p
100
+
101
+ settings.max_tokens = max_tokens
102
+ settings.repeat_penalty = repetition_penalty
103
+
104
+ output_settings = LlmStructuredOutputSettings.from_functions(
105
+ [search_tool.get_tool()]
106
+ )
107
+
108
+ messages = BasicChatHistory()
109
+
110
+ for msn in history:
111
+ user = {"role": Roles.user, "content": msn[0]}
112
+ assistant = {"role": Roles.assistant, "content": msn[1]}
113
+ messages.add_message(user)
114
+ messages.add_message(assistant)
115
+
116
+ result = web_search_agent.get_chat_response(
117
+ message,
118
+ llm_sampling_settings=settings,
119
+ structured_output_settings=output_settings,
120
+ add_message_to_chat_history=False,
121
+ add_response_to_chat_history=False,
122
+ print_output=False,
123
+ )
124
+
125
+ outputs = ""
126
+
127
+ settings.stream = True
128
+ response_text = answer_agent.get_chat_response(
129
+ 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"],
130
+ role=Roles.tool,
131
+ llm_sampling_settings=settings,
132
+ chat_history=messages,
133
+ returns_streaming_generator=True,
134
+ print_output=False,
135
+ )
136
+
137
+ for text in response_text:
138
+ outputs += text
139
+ yield outputs
140
+
141
+ output_settings = LlmStructuredOutputSettings.from_pydantic_models(
142
+ [CitingSources], LlmStructuredOutputType.object_instance
143
+ )
144
+
145
+ citing_sources = answer_agent.get_chat_response(
146
+ "Cite the sources you used in your response.",
147
+ role=Roles.tool,
148
+ llm_sampling_settings=settings,
149
+ chat_history=messages,
150
+ returns_streaming_generator=False,
151
+ structured_output_settings=output_settings,
152
+ print_output=False,
153
+ )
154
+ outputs += "\n\nSources:\n"
155
+ outputs += "\n".join(citing_sources.sources)
156
+ yield outputs
157
+
158
+
159
+ # Begin Gradio UI
160
+ main = gr.ChatInterface(
161
+ respond,
162
+ additional_inputs=[
163
+ gr.Textbox(
164
+ value=web_search_system_prompt,
165
+ label="System message",
166
+ interactive=True,
167
+ ),
168
+ gr.Slider(minimum=1, maximum=4096, value=2048, step=1, label="Max tokens"),
169
+ gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
170
+ gr.Slider(
171
+ minimum=0.1,
172
+ maximum=1.0,
173
+ value=0.95,
174
+ step=0.05,
175
+ label="Top-p",
176
+ ),
177
+ gr.Slider(
178
+ minimum=0,
179
+ maximum=100,
180
+ value=40,
181
+ step=1,
182
+ label="Top-k",
183
+ ),
184
+ gr.Slider(
185
+ minimum=0.0,
186
+ maximum=2.0,
187
+ value=1.1,
188
+ step=0.1,
189
+ label="Repetition penalty",
190
+ ),
191
+ ],
192
+ theme=gr.themes.Soft(
193
+ primary_hue="violet",
194
+ secondary_hue="violet",
195
+ neutral_hue="gray",
196
+ font=[gr.themes.GoogleFont("Exo"), "ui-sans-serif", "system-ui", "sans-serif"],
197
+ ).set(
198
+ body_background_fill_dark="#111111",
199
+ block_background_fill_dark="#111111",
200
+ block_border_width="1px",
201
+ block_title_background_fill_dark="#1e1c26",
202
+ input_background_fill_dark="#292733",
203
+ button_secondary_background_fill_dark="#24212b",
204
+ border_color_primary_dark="#343140",
205
+ background_fill_secondary_dark="#111111",
206
+ color_accent_soft_dark="transparent",
207
+ ),
208
+ css=css,
209
+ retry_btn="Retry",
210
+ undo_btn="Undo",
211
+ clear_btn="Clear",
212
+ submit_btn="Send",
213
+ examples=(examples),
214
+ analytics_enabled=False,
215
+ description="Llama-cpp-agent: Chat Web Search Agent",
216
+ chatbot=gr.Chatbot(scale=1, placeholder=PLACEHOLDER),
217
+ )
218
+
219
+ if __name__ == "__main__":
220
+ main.launch()
content.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ css = """
2
+ .message-row {
3
+ justify-content: space-evenly !important;
4
+ }
5
+ .message-bubble-border {
6
+ border-radius: 6px !important;
7
+ }
8
+ .dark.message-bubble-border {
9
+ border-color: #343140 !important;
10
+ }
11
+ .dark.user {
12
+ background: #1e1c26 !important;
13
+ }
14
+ .dark.assistant.dark, .dark.pending.dark {
15
+ background: #111111 !important;
16
+ }
17
+ """
18
+
19
+ PLACEHOLDER = """
20
+ <div class="message-bubble-border" style="display:flex; max-width: 600px; border-radius: 8px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); backdrop-filter: blur(10px);">
21
+ <figure style="margin: 0;">
22
+ <img src="https://raw.githubusercontent.com/SolidRusT/srt-web-search/9293e546791b3e63b1f8b695865dc4b4ed571728/logo.jpg" alt="Logo" style="width: 100%; height: 100%; border-radius: 8px;">
23
+ </figure>
24
+ <div style="padding: .5rem 1.5rem;">
25
+ <h2 style="text-align: left; font-size: 1.5rem; font-weight: 700; margin-bottom: 0.5rem;">llama-cpp-agent</h2>
26
+ <p style="text-align: left; font-size: 16px; line-height: 1.5; margin-bottom: 15px;">The llama-cpp-agent framework you can engage in seamless conversations with most `open source LLMs`, even small ones. Execute functions using LLMs, single and parallel function calling. Process text using agent chains, with tools.</p>
27
+ <div style="display: flex; justify-content: flex-end;">
28
+ <a href="https://discord.gg/sRMvWKrh" target="_blank" rel="noreferrer" style="padding: .5rem;">
29
+ <svg width="24" height="24" fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 5 30.67 23.25">
30
+ <title>Discord</title>
31
+ <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>
32
+ </svg>
33
+ </a>
34
+ <a href="https://github.com/Maximilian-Winter/llama-cpp-agent" target="_blank" rel="noreferrer" style="padding: .5rem;">
35
+ <svg width="24" height="24" fill="currentColor" viewBox="3 3 18 18">
36
+ <title>GitHub</title>
37
+ <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>
38
+ </svg>
39
+ </a>
40
+ </div>
41
+ </div>
42
+ </div>
43
+ """
utils.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import time
3
+ from typing import List
4
+ from datetime import datetime, timezone
5
+
6
+ from pydantic import BaseModel, Field
7
+ from trafilatura import fetch_url, extract
8
+
9
+ def get_server_time():
10
+ utc_time = datetime.now(timezone.utc)
11
+ return utc_time.strftime("%Y-%m-%d %H:%M:%S")
12
+
13
+ def get_website_content_from_url(url: str) -> str:
14
+ """
15
+ Get website content from a URL using Selenium and BeautifulSoup for improved content extraction and filtering.
16
+ Args:
17
+ url (str): URL to get website content from.
18
+ Returns:
19
+ str: Extracted content including title, main text, and tables.
20
+ """
21
+
22
+ try:
23
+ downloaded = fetch_url(url)
24
+
25
+ result = extract(downloaded, include_formatting=True, include_links=True, output_format='json', url=url)
26
+
27
+ if result:
28
+ result = json.loads(result)
29
+ 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'
30
+ else:
31
+ return ""
32
+ except Exception as e:
33
+ return f"An error occurred: {str(e)}"
34
+
35
+
36
+
37
+ class CitingSources(BaseModel):
38
+ """
39
+ This represents the citing of the sources you used to answer the user query.
40
+ """
41
+ sources: List[str] = Field(...,
42
+ description="List of sources to cite. Should be an URL of the source. E.g. GitHub URL, Blogpost URL or Newsletter URL.")
43
+