Spaces:
Running
Running
File size: 9,554 Bytes
89c7bc8 8534dd6 89c7bc8 8534dd6 89c7bc8 8534dd6 89c7bc8 8534dd6 89c7bc8 31b8f95 89c7bc8 31b8f95 89c7bc8 |
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 180 181 182 183 184 185 186 187 188 189 190 191 192 193 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 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 |
import os
from typing import Any, Dict
import requests
import tavily
from dotenv import load_dotenv
from swarms import Agent, OpenAIChat
from swarms.tools.prebuilt.bing_api import fetch_web_articles_bing_api
from swarms.utils.loguru_logger import logger
load_dotenv()
try:
from openai import OpenAI
from swarms import BaseLLM
except ImportError as e:
raise ImportError(f"Required modules are not available: {e}")
def perplexity_api_key():
try:
api_key = os.getenv("PPLX_API_KEY")
return api_key
except Exception as e:
print(f"Error: {e}")
class Perplexity(BaseLLM):
"""
A class to interact with the Perplexity API using OpenAI's interface.
"""
def __init__(self, api_key: str = perplexity_api_key(), *args, **kwargs):
"""
Initialize the Perplexity class with an API key.
Args:
api_key (str): The API key for authenticating with the OpenAI client.
"""
super().__init__(*args, **kwargs)
self.client = OpenAI(
api_key=api_key,
base_url="https://api.perplexity.ai",
*args,
**kwargs,
)
def run(self, task: str, *args, **kwargs):
"""
Run the model to process the given task.
Args:
task (str): The task to be performed.
Returns:
dict: The processed output from the model.
"""
messages = [
{
"role": "system",
"content": (
"You are an artificial intelligence assistant and you need to "
"engage in a helpful, detailed, polite conversation with a user."
),
},
{
"role": "user",
"content": task,
},
]
try:
response = self.client.chat.completions.create(
model="llama-3-sonar-large-32k-online",
messages=messages,
)
return response
except Exception as e:
raise RuntimeError(f"Error running the model: {e}")
def check_exa_api():
try:
api_key = os.getenv("EXA_API_KEY")
return api_key
except Exception as e:
print(f"Error: {e}")
class ExaAgent(BaseLLM):
"""
A class to interact with the Exa API.
"""
def __init__(self, api_key: str = check_exa_api(), *args, **kwargs):
"""
Initialize the ExaAgent class with an API key.
Args:
api_key (str): The API key for authenticating with the Exa client.
"""
super().__init__(*args, **kwargs)
try:
from exa_py import Exa
self.exa = Exa(api_key=api_key)
except ImportError as e:
raise ImportError(f"Failed to import Exa: {e}")
def run(self, task: str, *args, **kwargs):
"""
Run a search query using the Exa API.
Args:
task (str): The search query.
Returns:
dict: The search results from the Exa API.
"""
try:
results = self.exa.search(task, use_autoprompt=True, *args, **kwargs)
return results
except Exception as e:
raise RuntimeError(f"Error running the search query: {e}")
class ResearchAgent:
"""
A class to represent a research agent that uses an LLM to summarize content from various sources.
"""
def __init__(
self,
api_key: str,
output_dir: str = "research_base",
n_results: int = 2,
temperature: float = 0.2,
max_tokens: int = 3500,
):
"""
Initialize the ResearchAgent class with necessary parameters.
Args:
api_key (str): The API key for the Bing API.
output_dir (str): The directory for storing memory outputs. Default is "research_base".
n_results (int): Number of results to return from the memory. Default is 2.
temperature (float): The temperature setting for the LLM. Default is 0.2.
max_tokens (int): The maximum number of tokens for the LLM. Default is 3500.
"""
self.api_key = api_key
self.llm = OpenAIChat(temperature=temperature, max_tokens=max_tokens)
self.agent = self._initialize_agent()
def _initialize_agent(self):
"""
Initialize the agent with the provided parameters and system prompt.
Returns:
Agent: An initialized Agent instance.
"""
research_system_prompt = """
Research Agent LLM Prompt: Summarizing Sources and Content
Objective: Your task is to summarize the provided sources and the content within those sources. The goal is to create concise, accurate, and informative summaries that capture the key points of the original content.
Instructions:
1. Identify Key Information: ...
2. Summarize Clearly and Concisely: ...
3. Preserve Original Meaning: ...
4. Include Relevant Details: ...
5. Structure: ...
"""
return Agent(
agent_name="Research Agent",
system_prompt=research_system_prompt,
llm=self.llm,
max_loops=1,
autosave=True,
dashboard=False,
# tools=[fetch_web_articles_bing_api],
verbose=True,
)
def run(self, task: str, *args, **kwargs):
"""
Run the research agent to fetch and summarize web articles related to the task.
Args:
task (str): The task or query for the agent to process.
Returns:
str: The agent's response after processing the task.
"""
articles = fetch_web_articles_bing_api(task, subscription_key=self.api_key)
sources_prompts = "".join([task, articles])
agent_response = self.agent.run(sources_prompts)
return agent_response
def check_tavily_api():
try:
api_key = os.getenv("TAVILY_API_KEY")
return api_key
except Exception as e:
print(f"Error: {e}")
class TavilyWrapper:
"""
A wrapper class for the Tavily API to facilitate searches and retrieve relevant information.
"""
def __init__(self, api_key: str = check_tavily_api()):
"""
Initialize the TavilyWrapper with the provided API key.
Args:
api_key (str): The API key for authenticating with the Tavily API.
"""
if not isinstance(api_key, str):
raise TypeError("API key must be a string")
self.api_key = api_key
self.client = self._initialize_client(api_key)
def _initialize_client(self, api_key: str) -> Any:
"""
Initialize the Tavily client with the provided API key.
Args:
api_key (str): The API key for authenticating with the Tavily API.
Returns:
TavilyClient: An initialized Tavily client instance.
"""
try:
return tavily.TavilyClient(api_key=api_key)
except Exception as e:
raise RuntimeError(f"Error initializing Tavily client: {e}")
def run(self, task: str) -> Dict[str, Any]:
"""
Perform a search query using the Tavily API.
Args:
task (str): The search query.
Returns:
dict: The search results from the Tavily API.
"""
if not isinstance(task, str):
raise TypeError("Task must be a string")
try:
response = self.client.search(query=task, search_depth="advanced")
return response
except Exception as e:
raise RuntimeError(f"Error performing search: {e}")
def you_search_api_key():
try:
api_key = os.getenv("YOU_API_KEY")
return api_key
except Exception as e:
print(f"Error: {e}")
class YouSearchAgent:
"""
A wrapper class for the YDC Index API to facilitate fetching AI snippets based on a query.
"""
def __init__(self, api_key: str = you_search_api_key()):
"""
Initialize the AISnippetsWrapper with the provided API key.
Args:
api_key (str): The API key for authenticating with the YDC Index API.
"""
self.api_key = api_key
def run(self, task: str) -> Dict[str, Any]:
"""
Fetch AI snippets for the given query using the YDC Index API.
Args:
task (str): The search query.
Returns:
dict: The search results from the YDC Index API.
"""
if not isinstance(task, str):
raise TypeError("Task must be a string")
headers = {"X-API-Key": self.api_key}
params = {"query": task}
try:
response = requests.get(
"https://api.ydc-index.io/search",
params=params,
headers=headers,
)
response.raise_for_status() # Raise an error for bad status codes
return response.json()
except requests.RequestException as e:
raise RuntimeError(f"Error fetching AI snippets: {e}")
task = "What is the swarmms framework"
# Run all of the agents
agents = [
# Perplexity,
ExaAgent,
# ResearchAgent,
TavilyWrapper,
YouSearchAgent,
]
# Run each agent with the given task
for agent_class in agents:
logger.info(f"Running agent: {agent_class.__name__}")
agent = agent_class()
response = agent.run(task)
print(response)
|