martianband1t commited on
Commit
59fd58e
1 Parent(s): 039699f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +167 -129
app.py CHANGED
@@ -1,146 +1,184 @@
1
- import gradio as gr
2
  import os
3
- import spaces
4
- from transformers import GemmaTokenizer, AutoModelForCausalLM
5
- from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
6
- from threading import Thread
7
-
8
- # Set an environment variable
9
- HF_TOKEN = os.environ.get("HF_TOKEN", None)
10
-
11
-
12
- DESCRIPTION = '''
13
- <div>
14
- <h1 style="text-align: center;">Meta Llama3 8B</h1>
15
- <p>This Space demonstrates the instruction-tuned model <a href="https://huggingface.co/meta-llama/Meta-Llama-3-8B-Instruct"><b>Meta Llama3 8b Chat</b></a>. Meta Llama3 is the new open LLM and comes in two sizes: 8b and 70b. Feel free to play with it, or duplicate to run privately!</p>
16
- <p>🔎 For more details about the Llama3 release and how to use the model with <code>transformers</code>, take a look <a href="https://huggingface.co/blog/llama3">at our blog post</a>.</p>
17
- <p>🦕 Looking for an even more powerful model? Check out the <a href="https://huggingface.co/chat/"><b>Hugging Chat</b></a> integration for Meta Llama 3 70b</p>
18
- </div>
19
- '''
20
-
21
- LICENSE = """
22
- <p/>
23
-
24
- ---
25
- Built with Meta Llama 3
26
- """
27
-
28
- PLACEHOLDER = """
29
- <div style="padding: 30px; text-align: center; display: flex; flex-direction: column; align-items: center;">
30
- <img src="https://ysharma-dummy-chat-app.hf.space/file=/tmp/gradio/8e75e61cc9bab22b7ce3dec85ab0e6db1da5d107/Meta_lockup_positive%20primary_RGB.jpg" style="width: 80%; max-width: 550px; height: auto; opacity: 0.55; ">
31
- <h1 style="font-size: 28px; margin-bottom: 2px; opacity: 0.55;">Meta llama3</h1>
32
- <p style="font-size: 18px; margin-bottom: 2px; opacity: 0.65;">Ask me anything...</p>
33
- </div>
34
- """
35
-
36
-
37
- css = """
38
- h1 {
39
- text-align: center;
40
- display: block;
41
- }
42
-
43
- #duplicate-button {
44
- margin: auto;
45
- color: white;
46
- background: #1565c0;
47
- border-radius: 100vh;
48
- }
49
- """
50
-
51
- # Load the tokenizer and model
52
- tokenizer = AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct")
53
- model = AutoModelForCausalLM.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct", device_map="auto") # to("cuda:0")
54
- terminators = [
55
- tokenizer.eos_token_id,
56
- tokenizer.convert_tokens_to_ids("<|eot_id|>")
57
- ]
58
 
59
- @spaces.GPU(duration=120)
60
- def chat_llama3_8b(message: str,
61
- history: list,
62
- temperature: float,
63
- max_new_tokens: int
64
- ) -> str:
65
  """
66
- Generate a streaming response using the llama3-8b model.
 
 
 
67
  Args:
68
- message (str): The input message.
69
- history (list): The conversation history used by ChatInterface.
70
- temperature (float): The temperature for generating the response.
71
- max_new_tokens (int): The maximum number of new tokens to generate.
72
  Returns:
73
- str: The generated response.
74
  """
75
- conversation = []
76
- for user, assistant in history:
77
- conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
78
- conversation.append({"role": "user", "content": message})
 
 
 
 
 
79
 
80
- input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt").to(model.device)
 
 
81
 
82
- streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
 
 
 
 
83
 
84
- generate_kwargs = dict(
85
- input_ids= input_ids,
86
- streamer=streamer,
87
- max_new_tokens=max_new_tokens,
88
- do_sample=True,
89
- temperature=temperature,
90
- eos_token_id=terminators,
91
- )
92
- # This will enforce greedy generation (do_sample=False) when the temperature is passed 0, avoiding the crash.
93
- if temperature == 0:
94
- generate_kwargs['do_sample'] = False
95
-
96
- t = Thread(target=model.generate, kwargs=generate_kwargs)
97
- t.start()
 
 
 
 
 
 
 
 
98
 
99
- outputs = []
100
- for text in streamer:
101
- outputs.append(text)
102
- #print(outputs)
103
- yield "".join(outputs)
104
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
 
106
- # Gradio block
107
- chatbot=gr.Chatbot(height=450, placeholder=PLACEHOLDER, label='Gradio ChatInterface')
108
-
109
- with gr.Blocks(fill_height=True, css=css) as demo:
110
-
111
- gr.Markdown(DESCRIPTION)
112
- gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button")
113
- gr.ChatInterface(
114
- fn=chat_llama3_8b,
115
- chatbot=chatbot,
116
- fill_height=True,
117
- additional_inputs_accordion=gr.Accordion(label="⚙️ Parameters", open=False, render=False),
118
- additional_inputs=[
119
- gr.Slider(minimum=0,
120
- maximum=1,
121
- step=0.1,
122
- value=0.95,
123
- label="Temperature",
124
- render=False),
125
- gr.Slider(minimum=128,
126
- maximum=4096,
127
- step=1,
128
- value=512,
129
- label="Max new tokens",
130
- render=False ),
131
- ],
132
- examples=[
133
- ['How to setup a human base on Mars? Give short answer.'],
134
- ['Explain theory of relativity to me like I’m 8 years old.'],
135
- ['What is 9,000 * 9,000?'],
136
- ['Write a pun-filled happy birthday message to my friend Alex.'],
137
- ['Justify why a penguin might make a good king of the jungle.']
138
- ],
139
- cache_examples=False,
140
- )
141
 
142
- gr.Markdown(LICENSE)
 
 
 
 
 
143
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  if __name__ == "__main__":
145
  demo.launch()
146
 
 
 
1
  import os
2
+ import gradio as gr
3
+ import requests
4
+ from crewai import Agent, Task, Crew, Process
5
+
6
+ from langchain_openai import ChatOpenAI
7
+
8
+ from langchain_community.tools import DuckDuckGoSearchRun, DuckDuckGoSearchResults
9
+ from crewai_tools import tool, SeleniumScrapingTool, ScrapeWebsiteTool
10
+ from duckduckgo_search import DDGS
11
+
12
+ from newspaper import Article
13
+
14
+ # Ensure essential environment variables are set
15
+ openai_api_key = os.getenv('OPENAI_API_KEY')
16
+ if not openai_api_key:
17
+ raise EnvironmentError("OPENAI_API_KEY is not set in environment variables")
18
+
19
+ def fetch_content(url):
20
+ try:
21
+ article = Article(url)
22
+ article.download()
23
+ article.parse()
24
+ return article.text
25
+ except Exception as e:
26
+ print("ERROR: " + str(e))
27
+ return f"Error fetching content: {e}"
28
+
29
+ # Define the DuckDuckGoSearch tool
30
+ @tool('DuckDuckGoSearchResults')
31
+ def search_results(search_query: str) -> dict:
32
+ """
33
+ Performs a web search to gather and return a collection of search results.
34
+ This tool automates the retrieval of web-based information related to a specified query.
35
+ Args:
36
+ - search_query (str): The query string that specifies the information to be searched on the web. This should be a clear and concise expression of the user's information needs.
37
+ Returns:
38
+ - list: A list of dictionaries, where each dictionary represents a search result. Each dictionary includes 'snippet' of the page and the 'link' with the url linking to it.
39
+ """
40
+ results = DDGS().text(search_query, max_results=5, timelimit='m')
41
+ results_list = [{"title": result['title'], "snippet": result['body'], "link": result['href']} for result in results]
42
+ return results_list
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
+ @tool('WebScrapper')
45
+ def web_scrapper(url: str, topic: str) -> str:
 
 
 
 
46
  """
47
+ A tool designed to extract and read the content of a specified link and generate a summary on a specific topic.
48
+ It is capable of handling various types of web pages by making HTTP requests and parsing the received HTML content.
49
+ This tool is particularly useful for web scraping tasks, data collection, or extracting specific information from websites.
50
+
51
  Args:
52
+ - url (str): The URL from which to scrape content.
53
+ - topic (str): The specific topic on which to generate a summary.
 
 
54
  Returns:
55
+ - summary (str): summary of the url on the topic
56
  """
57
+ # Scrape content from the specified URL
58
+ content = fetch_content(url)
59
+
60
+ # Prepare the prompt for generating the summary
61
+ prompt = f"Generate a summary of the following content on the topic ## {topic} ### \n\nCONTENT:\n\n" + content
62
+
63
+ # Generate the summary using OpenAI
64
+ openai_llm = ChatOpenAI(temperature=0.4, model_name="gpt-3.5-turbo")
65
+ response = openai_llm.invoke(prompt)
66
 
67
+ summary_response = f"""###
68
+ Summary:
69
+ {response.content}
70
 
71
+ URL: {url}
72
+ ###
73
+ """
74
+
75
+ return summary_response
76
 
77
+ def kickoff_crew(topic: str, model_choice: str) -> str:
78
+ try:
79
+ # Initialize the OpenAI language model
80
+ openai_llm = ChatOpenAI(temperature=0, model_name=model_choice)
81
+
82
+ # Define Agents with OpenAI LLM
83
+ researcher = Agent(
84
+ role='Researcher',
85
+ goal=f'Search and Collect detailed information on topic ## {topic} ##',
86
+ tools=[search_results, web_scrapper],
87
+ llm=openai_llm,
88
+ backstory=(
89
+ "You are a meticulous researcher, skilled at navigating vast amounts of information to extract essential insights on any given topic. "
90
+ "Your dedication to detail ensures the reliability and thoroughness of your findings. "
91
+ "With a strategic approach, you carefully analyze and document data, aiming to provide accurate and trustworthy results."
92
+ ),
93
+ allow_delegation=False,
94
+ max_iter=15,
95
+ max_rpm=20,
96
+ memory=True,
97
+ verbose=True
98
+ )
99
 
 
 
 
 
 
100
 
101
+ editor = Agent(
102
+ role='Editor',
103
+ goal=f'Compile and refine the information into a comprehensive report on topic ## {topic} ##',
104
+ llm=openai_llm,
105
+ backstory=(
106
+ "As an expert editor, you specialize in transforming raw data into clear, engaging reports. "
107
+ "Your strong command of language and attention to detail ensure that each report not only conveys essential insights "
108
+ "but is also easily understandable and appealing to diverse audiences. "
109
+ ),
110
+ allow_delegation=False,
111
+ max_iter=5,
112
+ max_rpm=15,
113
+ memory=True,
114
+ verbose=True
115
+ )
116
+
117
+ # Define Tasks
118
+ research_task = Task(
119
+ description=(
120
+ f"Use the DuckDuckGoSearchResults tool to collect initial search snippets on ## {topic} ##. "
121
+ f"If more detailed searches are required, generate and execute new queries related to ## {topic} ##. "
122
+ "Subsequently, employ the WebScrapper tool to delve deeper into significant URLs identified from the snippets, extracting further information and insights. "
123
+ "Compile these findings into a preliminary draft, documenting all relevant sources, titles, and links associated with the topic. "
124
+ "Ensure high accuracy throughout the process and avoid any fabrication or misrepresentation of information."
125
+ ),
126
+ expected_output=(
127
+ "A structured draft report about the topic, featuring an introduction, a detailed main body organized by different aspects of the topic, and a conclusion. "
128
+ "Each section should properly cite sources, providing a thorough overview of the information gathered."
129
+ ),
130
+ agent=researcher
131
+ )
132
 
133
+
134
+ edit_task = Task(
135
+ description=(
136
+ "Review and refine the initial draft report from the research task. Organize the content logically to enhance information flow. "
137
+ "Verify the accuracy of all data, correct discrepancies, and update information to ensure it reflects current knowledge and is well-supported by sources. "
138
+ "Improve the report's readability by enhancing language clarity, adjusting sentence structures, and maintaining a consistent tone. "
139
+ "Include a section listing all sources used, formatted as bullet points following this template: "
140
+ "- title: url'."
141
+ ),
142
+ expected_output=(
143
+ f"A polished, comprehensive report on topic ## {topic} ##, with a clear, professional narrative that accurately reflects the research findings. "
144
+ "The report should include an introduction, an extensive discussion section, a concise conclusion, and a well-organized source list. "
145
+ "Ensure the document is grammatically correct and ready for publication or presentation."
146
+ ),
147
+ agent=editor,
148
+ context=[research_task]
149
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
 
151
+ # Forming the Crew
152
+ crew = Crew(
153
+ agents=[researcher, editor],
154
+ tasks=[research_task, edit_task],
155
+ process=Process.sequential,
156
+ )
157
 
158
+ # Kick-off the research process
159
+ result = crew.kickoff()
160
+ if not isinstance(result, str):
161
+ result = str(result)
162
+ return result
163
+ except Exception as e:
164
+ return f"Error: {str(e)}"
165
+
166
+ def main():
167
+ """Set up the Gradio interface for the CrewAI Research Tool."""
168
+ with gr.Blocks() as demo:
169
+ gr.Markdown("## CrewAI Research Tool")
170
+ topic_input = gr.Textbox(label="Enter Topic", placeholder="Type here...")
171
+ model_choice = gr.Radio(choices=["gpt-3.5-turbo", "gpt-4"], label="Choose Model")
172
+ submit_button = gr.Button("Start Research")
173
+ output = gr.Markdown(label="Result")
174
+
175
+ submit_button.click(
176
+ fn=kickoff_crew,
177
+ inputs=[topic_input, model_choice],
178
+ outputs=output
179
+ )
180
+
181
+
182
  if __name__ == "__main__":
183
  demo.launch()
184