Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add Swarmauri QR Code Generator Tool #1075

Merged
merged 4 commits into from
Jan 12, 2025
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pkgs/community/swarmauri_community/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ neo4j = { version = "^5.25.0", optional = true }
#neo4j = { version = "^5.25.0", optional = true }

pandas = "^2.2.3"
psutil = { version = "^6.1.0", optional = true }
#psutil = { version = "^6.1.0", optional = true }
#pygithub = { version = "^2.4.0", optional = true }
qrcode = { version = "^8.0", optional = true }
redis = { version = "^4.0", optional = true }
Expand Down
1 change: 1 addition & 0 deletions pkgs/community/swarmauri_tool_communitypsutil/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Swarmauri Example Community Package
56 changes: 56 additions & 0 deletions pkgs/community/swarmauri_tool_communitypsutil/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
[tool.poetry]
name = "swarmauri_tool_communitypsutil"
version = "0.6.0.dev1"
description = "Swarmauri Psutil Tool."
authors = ["Jacob Stewart <jacob@swarmauri.com>"]
license = "Apache-2.0"
readme = "README.md"
repository = "http://github.com/swarmauri/swarmauri-sdk"
classifiers = [
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12"
]

[tool.poetry.dependencies]
python = ">=3.10,<3.13"

# Swarmauri
swarmauri_core = { path = "../../core" }
swarmauri_base = { path = "../../base" }

# Dependencies
psutil = "^6.1.0"

[tool.poetry.group.dev.dependencies]
flake8 = "^7.0"
pytest = "^8.0"
pytest-asyncio = ">=0.24.0"
pytest-xdist = "^3.6.1"
pytest-json-report = "^1.5.0"
python-dotenv = "*"
requests = "^2.32.3"

[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"

[tool.pytest.ini_options]
norecursedirs = ["combined", "scripts"]

markers = [
"test: standard test",
"unit: Unit tests",
"integration: Integration tests",
"acceptance: Acceptance tests",
"experimental: Experimental tests"
]
log_cli = true
log_cli_level = "INFO"
log_cli_format = "%(asctime)s [%(levelname)s] %(message)s"
log_cli_date_format = "%Y-%m-%d %H:%M:%S"
asyncio_default_fixture_loop_scope = "function"

[tool.poetry.plugins."swarmauri.tools"]
PsutilTool = "swarmauri_tool_communitypsutil.PsutilTool:PsutilTool"
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
# standard/tools/concrete/PsutilTool.py
import psutil
from typing import Dict, Any, Literal, List, Callable
from pydantic import Field
from swarmauri.tools.base.ToolBase import ToolBase
from swarmauri.tools.concrete.Parameter import Parameter


class PsutilTool(ToolBase):
type: Literal["PsutilTool"] = "PsutilTool"
name: str = Field(
"PsutilTool", description="Tool to gather system information using psutil."
)
description: str = Field(
"This tool gathers system information like CPU, memory, disk, network, and sensors using the psutil library.",
description="Description of the PsutilTool",
)

parameters: List[Parameter] = Field(
default_factory=lambda: [
Parameter(
name="info_type",
type="string",
description="Type of system information to retrieve (cpu, memory, disk, network, sensors).",
required=True,
)
]
)

def get_all_cpu_values(self) -> Dict[str, Any]:
return {
"cpu_times": psutil.cpu_times()._asdict(),
"cpu_percent": psutil.cpu_percent(interval=1),
"cpu_times_per_cpu": [
cpu._asdict() for cpu in psutil.cpu_times(percpu=True)
],
"cpu_count": psutil.cpu_count(logical=True),
"cpu_frequency": psutil.cpu_freq()._asdict(),
"cpu_stats": psutil.cpu_stats()._asdict(),
}

def get_all_memory_values(self) -> Dict[str, Any]:
return {
"virtual_memory": psutil.virtual_memory()._asdict(),
"swap_memory": psutil.swap_memory()._asdict(),
}

def get_all_disk_values(self) -> Dict[str, Any]:
partitions = psutil.disk_partitions()
disk_usage = {
partition.device: psutil.disk_usage(partition.mountpoint)._asdict()
for partition in partitions
}
return {
"disk_partitions": [partition._asdict() for partition in partitions],
"disk_usage": disk_usage,
"disk_io_counters": psutil.disk_io_counters()._asdict(),
}

def get_all_network_values(self) -> Dict[str, Any]:
return {
"network_io_counters": psutil.net_io_counters()._asdict(),
"network_connections": [
conn._asdict() for conn in psutil.net_connections()
],
"network_interfaces": {
iface: [addr._asdict() for addr in addrs]
for iface, addrs in psutil.net_if_addrs().items()
},
}

def get_all_sensors_values(self) -> Dict[str, Any]:
battery = psutil.sensors_battery()
temperatures = psutil.sensors_temperatures()
fans = psutil.sensors_fans()

return {
"battery": battery._asdict() if battery else None,
"temperatures": {
name: [temp._asdict() for temp in temps]
for name, temps in (temperatures or {}).items()
},
"fan_speeds": {
name: [fan._asdict() for fan in fans]
for name, fans in (fans or {}).items()
},
}

def __call__(self, info_type: str) -> Dict[str, Any]:
"""
Call the appropriate method based on the provided info_type and return the corresponding system information.

Parameters:
info_type (str): The type of system information requested. Valid options are 'cpu', 'memory', 'disk',
'network', or 'sensors'.

Returns:
Dict[str, Any]: A dictionary where the key is the `info_type` and the value is the result of the corresponding
system information retrieval method.

Raises:
ValueError: If an invalid `info_type` is provided.

Example:
>>> tool = YourToolClass()
>>> result = tool("cpu")
>>> print(result)
{'cpu': {...}}
"""

# Mapping info_type values to the corresponding methods
info_methods: Dict[str, Callable[[], Any]] = {
"cpu": self.get_all_cpu_values,
"memory": self.get_all_memory_values,
"disk": self.get_all_disk_values,
"network": self.get_all_network_values,
"sensors": self.get_all_sensors_values,
}

# Retrieve the appropriate method or raise an error if invalid info_type is provided
if info_type not in info_methods:
raise ValueError(
f"Invalid info_type '{info_type}' specified. Valid options are: {list(info_methods.keys())}."
)

# Execute the corresponding method and return the result
result = info_methods[info_type]()
return result
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from .PsutilTool import PsutilTool
__version__ = "0.6.0.dev26"
__long_desc__ = """

# Swarmauri Psutil Plugin

This repository includes a Psutil of a Swarmauri Plugin.

Visit us at: https://swarmauri.com
Follow us at: https://github.com/swarmauri
Star us at: https://github.com/swarmauri/swarmauri-sdk

"""


Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import pytest
from swarmauri_tool_communitypsutil.PsutilTool import PsutilTool as Tool


@pytest.mark.unit
def test_ubc_resource():
tool = Tool()
assert tool.resource == "Tool"


@pytest.mark.unit
def test_ubc_type():
assert Tool().type == "PsutilTool"


@pytest.mark.unit
def test_initialization():
tool = Tool()
assert type(tool.id) == str


@pytest.mark.unit
def test_serialization():
tool = Tool()
assert tool.id == Tool.model_validate_json(tool.model_dump_json()).id


@pytest.mark.parametrize(
"info_type, expected_keys, should_raise",
[
(
"cpu",
[
"cpu_times",
"cpu_percent",
"cpu_times_per_cpu",
"cpu_count",
"cpu_frequency",
"cpu_stats",
],
False,
),
("memory", ["virtual_memory", "swap_memory"], False),
("disk", ["disk_partitions", "disk_usage", "disk_io_counters"], False),
(
"network",
["network_io_counters", "network_connections", "network_interfaces"],
False,
),
("sensors", ["battery", "temperatures", "fan_speeds"], False),
("invalid", [], True), # This is the invalid case
],
)
@pytest.mark.unit
def test_call(info_type, expected_keys, should_raise):
tool = Tool()
if should_raise:
with pytest.raises(ValueError, match=r"Invalid info_type 'invalid' specified"):
tool(info_type=info_type)
else:
result = tool(info_type=info_type)
assert isinstance(
result, dict
), f"Expected result for {info_type} to be a dictionary"
for key in expected_keys:
assert key in result, f"Expected '{key}' in the result for {info_type}"
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Swarmauri Example Community Package
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
[tool.poetry]
name = "swarmauri_tool_communityqrcodegenerator"
version = "0.6.0.dev1"
description = "Swarmauri QR Code Generator Tool."
authors = ["Jacob Stewart <jacob@swarmauri.com>"]
license = "Apache-2.0"
readme = "README.md"
repository = "http://github.com/swarmauri/swarmauri-sdk"
classifiers = [
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12"
]

[tool.poetry.dependencies]
python = ">=3.10,<3.13"

# Swarmauri
swarmauri_core = { path = "../../core" }
swarmauri_base = { path = "../../base" }

# Dependencies
qrcode = "^7.3.1"

[tool.poetry.group.dev.dependencies]
flake8 = "^7.0"
pytest = "^8.0"
pytest-asyncio = ">=0.24.0"
pytest-xdist = "^3.6.1"
pytest-json-report = "^1.5.0"
python-dotenv = "*"
requests = "^2.32.3"

[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"

[tool.pytest.ini_options]
norecursedirs = ["combined", "scripts"]

markers = [
"test: standard test",
"unit: Unit tests",
"integration: Integration tests",
"acceptance: Acceptance tests",
"experimental: Experimental tests"
]
log_cli = true
log_cli_level = "INFO"
log_cli_format = "%(asctime)s [%(levelname)s] %(message)s"
log_cli_date_format = "%Y-%m-%d %H:%M:%S"
asyncio_default_fixture_loop_scope = "function"

[tool.poetry.plugins."swarmauri.agents"]
QrCodeGeneratorTool = "swarmauri_tool_communityqrcodegenerator.QrCodeGeneratorTool:QrCodeGeneratorTool"
Loading
Loading