Skip to content

Commit

Permalink
[DOCS][DOCS]
Browse files Browse the repository at this point in the history
  • Loading branch information
kyegomez committed Jan 21, 2025
1 parent 5e4a600 commit d44fbcd
Show file tree
Hide file tree
Showing 12 changed files with 667 additions and 124 deletions.
1 change: 1 addition & 0 deletions docs/mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,7 @@ nav:
- XAI: "swarms/examples/xai.md"
- Swarms Tools:
- Agent with HTX + CoinGecko: "swarms/examples/swarms_tools_htx.md"
- Agent with HTX + CoinGecko Function Calling: "swarms/examples/swarms_tools_htx_gecko.md"
- Swarm Models:
- Overview: "swarms/models/index.md"
# - Models Available: "swarms/models/index.md"
Expand Down
43 changes: 43 additions & 0 deletions docs/swarms/examples/swarms_tools_htx_gecko.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Swarms Tools Example with HTX + CoinGecko

- `pip3 install swarms swarms-tools`
- Add `OPENAI_API_KEY` to your `.env` file
- Run `swarms_tools_htx_gecko.py`
- Agent will make a function call to the desired tool
- The tool will be executed and the result will be returned to the agent
- The agent will then analyze the result and return the final output


```python
from swarms import Agent
from swarms.prompts.finance_agent_sys_prompt import (
FINANCIAL_AGENT_SYS_PROMPT,
)
from swarms_tools import (
fetch_stock_news,
coin_gecko_coin_api,
fetch_htx_data,
)

# Initialize the agent
agent = Agent(
agent_name="Financial-Analysis-Agent",
agent_description="Personal finance advisor agent",
system_prompt=FINANCIAL_AGENT_SYS_PROMPT,
max_loops=1,
model_name="gpt-4o",
dynamic_temperature_enabled=True,
user_name="swarms_corp",
retry_attempts=3,
context_length=8192,
return_step_meta=False,
output_type="str", # "json", "dict", "csv" OR "string" "yaml" and
auto_generate_prompt=False, # Auto generate prompt for the agent based on name, description, and system prompt, task
max_tokens=4000, # max output tokens
saved_state_path="agent_00.json",
interactive=False,
tools=[fetch_stock_news, coin_gecko_coin_api, fetch_htx_data],
)

agent.run("Analyze the $swarms token on htx")
```
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ build-backend = "poetry.core.masonry.api"

[tool.poetry]
name = "swarms"
version = "6.8.8"
version = "6.9.6"
description = "Swarms - TGSC"
license = "MIT"
authors = ["Kye Gomez <[email protected]>"]
Expand Down
33 changes: 33 additions & 0 deletions swarms/agents/agent_print.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from swarms.utils.formatter import formatter


def agent_print(
agent_name: str,
response: str = None,
loop_count: int = None,
streaming_on: bool = False,
):
"""
Prints the response from an agent based on the streaming mode.
Args:
agent_name (str): The name of the agent.
response (str): The response from the agent.
loop_count (int): The maximum number of loops.
streaming_on (bool): Indicates if streaming is on or off.
Returns:
str: The response from the agent.
"""
if streaming_on:
formatter.print_panel_token_by_token(
f"{agent_name}: {response}",
title=f"Agent Name: {agent_name} [Max Loops: {loop_count}]",
)
else:
formatter.print_panel(
f"{agent_name}: {response}",
f"Agent Name {agent_name} [Max Loops: {loop_count} ]",
)

return response
8 changes: 4 additions & 4 deletions swarms/structs/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from swarms.structs.agent import Agent
from swarms.structs.agents_available import showcase_available_agents
from swarms.structs.async_workflow import AsyncWorkflow
from swarms.structs.auto_swarm import AutoSwarm, AutoSwarmRouter
from swarms.structs.base_structure import BaseStructure
from swarms.structs.base_swarm import BaseSwarm
Expand All @@ -13,10 +14,10 @@
NodeType,
)
from swarms.structs.groupchat import (
GroupChat,
AgentResponse,
ChatHistory,
ChatTurn,
AgentResponse,
GroupChat,
expertise_based,
)
from swarms.structs.majority_voting import (
Expand All @@ -38,6 +39,7 @@
run_agents_with_tasks_concurrently,
run_single_agent,
)
from swarms.structs.multi_agent_orchestrator import MultiAgentRouter
from swarms.structs.queue_swarm import TaskQueueSwarm
from swarms.structs.rearrange import AgentRearrange, rearrange
from swarms.structs.round_robin import RoundRobinSwarm
Expand Down Expand Up @@ -79,8 +81,6 @@
find_token_in_text,
parse_tasks,
)
from swarms.structs.async_workflow import AsyncWorkflow
from swarms.structs.multi_agent_orchestrator import MultiAgentRouter

__all__ = [
"Agent",
Expand Down
120 changes: 56 additions & 64 deletions swarms/structs/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
exec_callable_with_clusterops,
)
from swarms.telemetry.capture_sys_data import log_agent_data
from swarms.agents.agent_print import agent_print


# Utils
Expand Down Expand Up @@ -889,7 +890,33 @@ def _run(

# Check and execute tools
if self.tools is not None:
self.parse_and_execute_tools(response)
out = self.parse_and_execute_tools(
response
)

self.short_memory.add(
role="Tool Executor", content=out
)

agent_print(
f"{self.agent_name} - Tool Executor",
out,
loop_count,
self.streaming_on,
)

out = self.llm.run(out)

agent_print(
f"{self.agent_name} - Agent Analysis",
out,
loop_count,
self.streaming_on,
)

self.short_memory.add(
role=self.agent_name, content=out
)

# Add the response to the memory
self.short_memory.add(
Expand Down Expand Up @@ -1209,31 +1236,35 @@ def dict_to_csv(self, data: dict) -> str:
return output.getvalue()

def parse_and_execute_tools(self, response: str, *args, **kwargs):
try:
logger.info("Executing tool...")

# try to Execute the tool and return a string
out = parse_and_execute_json(
functions=self.tools,
json_string=response,
parse_md=True,
*args,
**kwargs,
)

out = str(out)

logger.info(f"Tool Output: {out}")

# Add the output to the memory
self.short_memory.add(
role="Tool Executor",
content=out,
)
max_retries = 3 # Maximum number of retries
retries = 0
while retries < max_retries:
try:
logger.info("Executing tool...")

except Exception as error:
logger.error(f"Error executing tool: {error}")
raise error
# try to Execute the tool and return a string
out = parse_and_execute_json(
functions=self.tools,
json_string=response,
parse_md=True,
*args,
**kwargs,
)
logger.info(f"Tool Output: {out}")
# Add the output to the memory
# self.short_memory.add(
# role="Tool Executor",
# content=out,
# )
return out
except Exception as error:
retries += 1
logger.error(
f"Attempt {retries}: Error executing tool: {error}"
)
if retries == max_retries:
raise error
time.sleep(1) # Wait for a bit before retrying

def add_memory(self, message: str):
"""Add a memory to the agent
Expand Down Expand Up @@ -2056,45 +2087,6 @@ def tokens_checks(self):

return out

def parse_function_call_and_execute(self, response: str):
"""
Parses a function call from the given response and executes it.
Args:
response (str): The response containing the function call.
Returns:
None
Raises:
Exception: If there is an error parsing and executing the function call.
"""
try:
if self.tools is not None:
tool_call_output = parse_and_execute_json(
self.tools, response, parse_md=True
)

if tool_call_output is not str:
tool_call_output = str(tool_call_output)

logger.info(f"Tool Call Output: {tool_call_output}")
self.short_memory.add(
role=self.agent_name,
content=tool_call_output,
)

return tool_call_output
except Exception as error:
logger.error(
f"Error parsing and executing function call: {error}"
)

# Raise a custom exception with the error message
raise Exception(
"Error parsing and executing function call"
) from error

def activate_agentops(self):
if self.agent_ops_on is True:
try:
Expand Down
Loading

0 comments on commit d44fbcd

Please sign in to comment.