rusticai-ray 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,40 @@
1
+ Metadata-Version: 2.1
2
+ Name: rusticai-ray
3
+ Version: 0.0.1
4
+ Summary: Rustic AI execution engine running on Ray Cluster
5
+ Home-page: https://www.rustic.ai/
6
+ License: Apache-2.0
7
+ Author: Dragonscale Industries Inc.
8
+ Author-email: dev@dragonscale.ai
9
+ Requires-Python: >=3.12,<4.0
10
+ Classifier: License :: OSI Approved :: Apache Software License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Requires-Dist: opentelemetry-exporter-otlp (>=1.31.1,<2.0.0)
15
+ Requires-Dist: opentelemetry-exporter-otlp-proto-grpc (>=1.31.1,<2.0.0)
16
+ Requires-Dist: opentelemetry-sdk (>=1.31.1,<2.0.0)
17
+ Requires-Dist: ray[default] (>=2.44.1,<3.0.0)
18
+ Requires-Dist: rusticai-core (>=0.0.2,<0.1.0)
19
+ Project-URL: Repository, https://github.com/rustic-ai/python-framework
20
+ Project-URL: Rustic AI Core, https://pypi.org/project/rusticai-core/
21
+ Description-Content-Type: text/markdown
22
+
23
+ # Rustic AI Ray
24
+
25
+ This module supports execution of [Rustic AI](https://www.rustic.ai/) on [Ray Cluster](https://docs.ray.io/en/latest/cluster/getting-started.html).
26
+
27
+ ## Installing
28
+
29
+ ```shell
30
+ pip install rusticai-ray
31
+ ```
32
+ **Note:** It depends on [rusticai-core](https://pypi.org/project/rusticai-core/)
33
+
34
+ ## Building from Source
35
+
36
+ ```shell
37
+ poetry install --with dev
38
+ poetry build
39
+ ```
40
+
@@ -0,0 +1,17 @@
1
+ # Rustic AI Ray
2
+
3
+ This module supports execution of [Rustic AI](https://www.rustic.ai/) on [Ray Cluster](https://docs.ray.io/en/latest/cluster/getting-started.html).
4
+
5
+ ## Installing
6
+
7
+ ```shell
8
+ pip install rusticai-ray
9
+ ```
10
+ **Note:** It depends on [rusticai-core](https://pypi.org/project/rusticai-core/)
11
+
12
+ ## Building from Source
13
+
14
+ ```shell
15
+ poetry install --with dev
16
+ poetry build
17
+ ```
@@ -0,0 +1,66 @@
1
+ [build-system]
2
+ requires = ["poetry-core"]
3
+ build-backend = "poetry.core.masonry.api"
4
+
5
+ [tool.poetry]
6
+ name = "rusticai-ray"
7
+ version = "0.0.1"
8
+ description = "Rustic AI execution engine running on Ray Cluster"
9
+ authors = ["Dragonscale Industries Inc. <dev@dragonscale.ai>"]
10
+ license = "Apache-2.0"
11
+ readme = "README.md"
12
+ homepage = "https://www.rustic.ai/"
13
+ repository = "https://github.com/rustic-ai/python-framework"
14
+ packages = [{ include = "rustic_ai", from = "src" }]
15
+
16
+ [tool.poetry.urls]
17
+ "Rustic AI Core" = "https://pypi.org/project/rusticai-core/"
18
+
19
+ [tool.poetry.dependencies]
20
+ python = "^3.12"
21
+ rusticai-core = { version = "0.0.2"}
22
+ ray = { extras = ["default"], version = "^2.44.1" }
23
+ opentelemetry-sdk = "^1.31.1"
24
+ opentelemetry-exporter-otlp = "^1.31.1"
25
+ opentelemetry-exporter-otlp-proto-grpc = "^1.31.1"
26
+
27
+ [tool.poetry-monorepo.deps]
28
+
29
+ [tool.poetry.group.dev.dependencies]
30
+ pytest = "^8.3.4"
31
+ black = { version = "^24.2.0", extras = ["jupyter"] }
32
+ flake8 = "^7.1.2"
33
+ tox = "^4.24.1"
34
+ isort = "^6.0.0"
35
+ mypy = "^1.15.0"
36
+
37
+ [tool.black]
38
+ line-length = 120
39
+ target-version = ['py312']
40
+ include = '\.pyi?$'
41
+ exclude = '''
42
+ /(
43
+ \.git
44
+ | \.mypy_cache
45
+ | \.tox
46
+ | \.venv
47
+ | _build
48
+ | buck-out
49
+ | build
50
+ | dist
51
+ )/
52
+ '''
53
+
54
+ [tool.mypy]
55
+ python_version = "3.12"
56
+ ignore_missing_imports = true
57
+ check_untyped_defs = true
58
+ plugins = "pydantic.mypy"
59
+ explicit_package_bases = true
60
+
61
+
62
+ [tool.isort]
63
+ profile = "black"
64
+ known_third_party = ["pydantic"]
65
+ known_first_party = ["rustic_ai.core"]
66
+
@@ -0,0 +1,3 @@
1
+ from .execution import RayAgentWrapper, RayExecutionEngine
2
+
3
+ __all__ = ["RayAgentWrapper", "RayExecutionEngine"]
@@ -0,0 +1,4 @@
1
+ from .ray_agent_wrapper import RayAgentWrapper
2
+ from .ray_exec_engine import RayExecutionEngine
3
+
4
+ __all__ = ["RayAgentWrapper", "RayExecutionEngine"]
@@ -0,0 +1,85 @@
1
+ import logging
2
+ from typing import Any, Dict, Type, Union
3
+
4
+ from opentelemetry import trace
5
+ from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
6
+ from opentelemetry.sdk.trace import TracerProvider
7
+ from opentelemetry.sdk.trace.export import SimpleSpanProcessor
8
+
9
+ import ray
10
+ from rustic_ai.core.guild.agent import Agent, AgentSpec
11
+ from rustic_ai.core.guild.dsl import GuildSpec
12
+ from rustic_ai.core.guild.execution.agent_wrapper import AgentWrapper
13
+ from rustic_ai.core.messaging import Client, MessageTrackingClient, MessagingConfig
14
+
15
+
16
+ @ray.remote
17
+ class RayAgentWrapper(AgentWrapper):
18
+ def __init__(
19
+ self,
20
+ guild_spec: GuildSpec,
21
+ agent_spec: Union[AgentSpec, Agent],
22
+ messaging_config: MessagingConfig,
23
+ machine_id: int,
24
+ client_type: Type[Client] = MessageTrackingClient,
25
+ client_properties: Dict[str, Any] = {},
26
+ ):
27
+ print("Setting up logging")
28
+ logging_level = "INFO"
29
+ handler = logging.StreamHandler()
30
+ handler.setLevel(logging_level)
31
+
32
+ root_logger = logging.getLogger()
33
+ root_logger.setLevel(logging_level)
34
+ root_logger.addHandler(handler)
35
+
36
+ ray_logger = logging.getLogger("ray")
37
+ ray_logger.setLevel(logging_level)
38
+ ray_logger.addHandler(handler)
39
+
40
+ print("Setting up tracing")
41
+ provider = TracerProvider()
42
+ span_processor = SimpleSpanProcessor(OTLPSpanExporter())
43
+ provider.add_span_processor(span_processor)
44
+ trace.set_tracer_provider(provider)
45
+ print("Tracing setup complete")
46
+
47
+ super().__init__(guild_spec, agent_spec, messaging_config, machine_id, client_type, client_properties)
48
+
49
+ def run(self) -> None:
50
+ """
51
+ Initializes the agent with Messaging and its client, then runs the agent asynchronously using Ray.
52
+ """
53
+
54
+ try:
55
+ # Perform common initialization tasks
56
+ # We skip coverage on this as it is run in a separate process and is not tracked by coverage
57
+ logging.info(
58
+ f"Initializing agent {self.agent_spec.name} from class {self.agent_spec.class_name}"
59
+ ) # pragma: no cover
60
+ logging.info(f"Agent properties: {self.agent_spec.properties}")
61
+ logging.info(f"Agent client properties: {self.client_properties}")
62
+ self.initialize_agent() # pragma: no cover
63
+ logging.info("Agent initialized") # pragma: no cover
64
+
65
+ self._is_running = True
66
+
67
+ except Exception as e:
68
+ logging.error(f"Error initializing agent {self.agent_spec.name}: {e}", exc_info=True)
69
+ raise e
70
+
71
+ def get_agent_spec(self):
72
+ return self.agent_spec # pragma: no cover
73
+
74
+ def is_rustic_agent(self):
75
+ return True
76
+
77
+ def shutdown(self):
78
+ self._is_running = False
79
+ return super().shutdown() # pragma: no cover
80
+
81
+ def is_running(self):
82
+ return self._is_running
83
+
84
+ def __repr__(self):
85
+ return f"[{self.only_agent_class_name} | {self.guild_spec.name} | {self.agent_spec.name}]"
@@ -0,0 +1,115 @@
1
+ from typing import Any, Dict, List, Type, Union
2
+
3
+ import ray
4
+ import ray.util.state
5
+ from rustic_ai.core.guild.agent import Agent, AgentSpec
6
+ from rustic_ai.core.guild.dsl import GuildSpec
7
+ from rustic_ai.core.guild.execution.execution_engine import ExecutionEngine
8
+ from rustic_ai.core.messaging import Client, MessageTrackingClient, MessagingConfig
9
+
10
+ from .ray_agent_wrapper import RayAgentWrapper
11
+
12
+
13
+ class RayExecutionEngine(ExecutionEngine):
14
+ def __init__(self, guild_id: str) -> None:
15
+ super().__init__(guild_id=guild_id)
16
+ # Initialize Ray if not already done
17
+ if not ray.is_initialized():
18
+ raise Exception("Ray must be initialized before using RayExecutionEngine.") # pragma: no cover
19
+ self.agent_wrappers: Dict[str, Dict[str, RayAgentWrapper]] = {}
20
+ self.agent_actors: Dict[str, Dict[str, ray.actor.ActorHandle]] = {}
21
+
22
+ def run_agent(
23
+ self,
24
+ guild_spec: GuildSpec,
25
+ agent_spec: Union[AgentSpec, Agent],
26
+ messaging_config: MessagingConfig,
27
+ machine_id: int,
28
+ client_type: Type[Client] = MessageTrackingClient,
29
+ client_properties: Dict[str, Any] = {},
30
+ default_topic: str = "default_topic",
31
+ ) -> None:
32
+ """
33
+ Wraps the agent in a RayAgentWrapper and runs it asynchronously using Ray.
34
+ """
35
+ # Instantiate the RayAgentWrapper with provided parameters. Note the use of Ray's remote function.
36
+ guild_id = guild_spec.id
37
+ agent_wrapper = RayAgentWrapper.options(name=agent_spec.id, namespace=guild_id, lifetime="detached").remote( # type: ignore
38
+ guild_spec=guild_spec,
39
+ agent_spec=agent_spec,
40
+ messaging_config=messaging_config,
41
+ machine_id=machine_id,
42
+ client_type=client_type,
43
+ client_properties=client_properties,
44
+ )
45
+
46
+ # Execute the agent asynchronously
47
+ actor = ray.get(agent_wrapper.run.remote()) # type: ignore
48
+
49
+ if guild_id not in self.agent_wrappers:
50
+ self.agent_wrappers[guild_id] = {}
51
+
52
+ if guild_id not in self.agent_actors:
53
+ self.agent_actors[guild_id] = {}
54
+
55
+ self.agent_wrappers[guild_id][agent_spec.id] = agent_wrapper
56
+ self.agent_actors[guild_id][agent_spec.id] = actor
57
+
58
+ def get_agents_in_guild(self, guild_id: str) -> Dict[str, AgentSpec]:
59
+ actor_refs = ray.util.list_named_actors(all_namespaces=True)
60
+ agent_specs = {}
61
+ for actor_ref in actor_refs:
62
+ if actor_ref["namespace"] == guild_id:
63
+ actor = ray.get_actor(name=actor_ref["name"], namespace=guild_id) # type: ignore
64
+ if self._is_rustic_agent(actor):
65
+ agent_spec: AgentSpec = ray.get(actor.get_agent_spec.remote()) # type: ignore
66
+ agent_specs[agent_spec.id] = agent_spec
67
+ return agent_specs
68
+
69
+ def is_agent_running(self, guild_id: str, agent_id: str) -> bool:
70
+ try:
71
+ actor = ray.get_actor(name=agent_id, namespace=guild_id)
72
+ if actor is not None:
73
+ if self._is_rustic_agent(actor):
74
+ return ray.get(actor.is_running.remote())
75
+ return False
76
+ except ValueError:
77
+ return False
78
+ except ray.exceptions.RayActorError:
79
+ return False
80
+
81
+ def find_agents_by_name(self, guild_id: str, agent_name: str) -> List[AgentSpec]:
82
+ agents = self.get_agents_in_guild(guild_id)
83
+ return [agent_spec for agent_id, agent_spec in agents.items() if agent_spec.name == agent_name]
84
+
85
+ def stop_agent(self, guild_id: str, agent_id: str) -> None:
86
+ """
87
+ Stops the agent with the given ID in the guild with the given ID.
88
+ """
89
+ agent_wrapper = ray.get_actor(name=agent_id, namespace=guild_id) # type: ignore
90
+ if agent_wrapper is not None:
91
+ if self._is_rustic_agent(agent_wrapper):
92
+ ray.get(agent_wrapper.shutdown.remote())
93
+ ray.kill(agent_wrapper)
94
+
95
+ del self.agent_wrappers[guild_id][agent_id]
96
+ del self.agent_actors[guild_id][agent_id]
97
+
98
+ def _is_rustic_agent(self, agent_wrapper) -> bool:
99
+ if (
100
+ agent_wrapper is not None
101
+ and hasattr(agent_wrapper, "is_rustic_agent")
102
+ and ray.get(agent_wrapper.is_rustic_agent.remote())
103
+ ):
104
+ return True
105
+ else:
106
+ return False
107
+
108
+ def shutdown(self) -> None:
109
+ """
110
+ Shutdown the Ray execution engine.
111
+ """
112
+ actors = ray.util.list_named_actors()
113
+ for actor_name in actors:
114
+ self.stop_agent(guild_id=self.guild_id, agent_id=actor_name)
115
+ ray.shutdown()