Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
22 changes: 22 additions & 0 deletions .flake8
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
[flake8]
max-line-length = 88
extend-ignore = E203, W503
exclude =
.git,
__pycache__,
build,
dist,
*.egg-info,
.eggs,
.tox,
.venv,
venv,
.env,
.pytest_cache,
.coverage,
htmlcov,
.mypy_cache,
.ruff_cache
per-file-ignores =
__init__.py: F401
max-complexity = 10
106 changes: 106 additions & 0 deletions examples/typedb_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
from swarms.utils.typedb_wrapper import TypeDBWrapper, TypeDBConfig

def main():
# Initialize TypeDB wrapper with custom configuration
config = TypeDBConfig(
uri="localhost:1729",
database="swarms_example",
username="admin",
password="password"
)

# Define schema for a simple knowledge graph
schema = """
define
person sub entity,
owns name: string,
owns age: long,
plays role;

role sub entity,
owns title: string,
owns department: string;

works_at sub relation,
relates person,
relates role;
"""

# Example data insertion
insert_queries = [
"""
insert
$p isa person, has name "John Doe", has age 30;
$r isa role, has title "Software Engineer", has department "Engineering";
(person: $p, role: $r) isa works_at;
""",
"""
insert
$p isa person, has name "Jane Smith", has age 28;
$r isa role, has title "Data Scientist", has department "Data Science";
(person: $p, role: $r) isa works_at;
"""
]

# Example queries
query_queries = [
# Get all people
"match $p isa person; get;",

# Get people in Engineering department
"""
match
$p isa person;
$r isa role, has department "Engineering";
(person: $p, role: $r) isa works_at;
get $p;
""",

# Get people with their roles
"""
match
$p isa person, has name $n;
$r isa role, has title $t;
(person: $p, role: $r) isa works_at;
get $n, $t;
"""
]

try:
with TypeDBWrapper(config) as db:
# Define schema
print("Defining schema...")
db.define_schema(schema)

# Insert data
print("\nInserting data...")
for query in insert_queries:
db.insert_data(query)

# Query data
print("\nQuerying data...")
for i, query in enumerate(query_queries, 1):
print(f"\nQuery {i}:")
results = db.query_data(query)
print(f"Results: {results}")

# Example of deleting data
print("\nDeleting data...")
delete_query = """
match
$p isa person, has name "John Doe";
delete $p;
"""
db.delete_data(delete_query)

# Verify deletion
print("\nVerifying deletion...")
verify_query = "match $p isa person, has name $n; get $n;"
results = db.query_data(verify_query)
print(f"Remaining people: {results}")

except Exception as e:
print(f"Error: {e}")

if __name__ == "__main__":
main()
4 changes: 4 additions & 0 deletions pyupgrade.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[pyupgrade]
py3-plus = True
py39-plus = True
keep-runtime-typing = True
9 changes: 9 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,12 @@ networkx
aiofiles
httpx
vllm>=0.2.0
flake8>=6.1.0
flake8-bugbear>=23.3.12
flake8-comprehensions>=3.12.0
flake8-simplify>=0.19.3
flake8-unused-arguments>=0.0.4
pyupgrade>=3.15.0
typedb-client>=2.25.0
typedb-protocol>=2.25.0
typedb-driver>=2.25.0
55 changes: 55 additions & 0 deletions scripts/check_code_quality.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
#!/usr/bin/env python3
import subprocess
import sys
from pathlib import Path

def run_command(command: list[str], cwd: Path) -> bool:
"""Run a command and return True if successful."""
try:
result = subprocess.run(
command,
cwd=cwd,
capture_output=True,
text=True,
check=True
)
return True
except subprocess.CalledProcessError as e:
print(f"Error running {' '.join(command)}:")
print(e.stdout)
print(e.stderr, file=sys.stderr)
return False

def main():
"""Run all code quality checks."""
root_dir = Path(__file__).parent.parent
success = True

# Run flake8
print("\nRunning flake8...")
if not run_command(["flake8", "swarms", "tests"], root_dir):
success = False

# Run pyupgrade
print("\nRunning pyupgrade...")
if not run_command(["pyupgrade", "--py39-plus", "swarms", "tests"], root_dir):
success = False

# Run black
print("\nRunning black...")
if not run_command(["black", "--check", "swarms", "tests"], root_dir):
success = False

# Run ruff
print("\nRunning ruff...")
if not run_command(["ruff", "check", "swarms", "tests"], root_dir):
success = False

if not success:
print("\nCode quality checks failed. Please fix the issues and try again.")
sys.exit(1)
else:
print("\nAll code quality checks passed!")

if __name__ == "__main__":
main()
32 changes: 32 additions & 0 deletions swarms/agents/exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from typing import Any, Dict, Optional

class ToolAgentError(Exception):
"""Base exception for all tool agent errors."""
def __init__(self, message: str, details: Optional[Dict[str, Any]] = None):
self.message = message
self.details = details or {}
super().__init__(self.message)

class ToolExecutionError(ToolAgentError):
"""Raised when a tool fails to execute."""
def __init__(self, tool_name: str, error: Exception, details: Optional[Dict[str, Any]] = None):
message = f"Failed to execute tool '{tool_name}': {str(error)}"
super().__init__(message, details)

class ToolValidationError(ToolAgentError):
"""Raised when tool parameters fail validation."""
def __init__(self, tool_name: str, param_name: str, error: str, details: Optional[Dict[str, Any]] = None):
message = f"Validation error for tool '{tool_name}' parameter '{param_name}': {error}"
super().__init__(message, details)

class ToolNotFoundError(ToolAgentError):
"""Raised when a requested tool is not found."""
def __init__(self, tool_name: str, details: Optional[Dict[str, Any]] = None):
message = f"Tool '{tool_name}' not found"
super().__init__(message, details)

class ToolParameterError(ToolAgentError):
"""Raised when tool parameters are invalid."""
def __init__(self, tool_name: str, error: str, details: Optional[Dict[str, Any]] = None):
message = f"Invalid parameters for tool '{tool_name}': {error}"
super().__init__(message, details)
Loading