agent-lyra 0.3.0__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.
- agent_lyra-0.3.0/LICENSE +21 -0
- agent_lyra-0.3.0/PKG-INFO +64 -0
- agent_lyra-0.3.0/README.md +47 -0
- agent_lyra-0.3.0/pyproject.toml +29 -0
- agent_lyra-0.3.0/setup.cfg +4 -0
- agent_lyra-0.3.0/src/agent_lyra.egg-info/PKG-INFO +64 -0
- agent_lyra-0.3.0/src/agent_lyra.egg-info/SOURCES.txt +15 -0
- agent_lyra-0.3.0/src/agent_lyra.egg-info/dependency_links.txt +1 -0
- agent_lyra-0.3.0/src/agent_lyra.egg-info/top_level.txt +1 -0
- agent_lyra-0.3.0/src/lyra/__init__.py +5 -0
- agent_lyra-0.3.0/src/lyra/gated/__init__.py +3 -0
- agent_lyra-0.3.0/src/lyra/gated/hosted_agents.py +54 -0
- agent_lyra-0.3.0/src/lyra/standalone/__init__.py +30 -0
- agent_lyra-0.3.0/src/lyra/standalone/agents.py +53 -0
- agent_lyra-0.3.0/src/lyra/standalone/orchestration.py +54 -0
- agent_lyra-0.3.0/src/lyra/standalone/rag.py +90 -0
- agent_lyra-0.3.0/tests/test_agents.py +42 -0
agent_lyra-0.3.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Lyra
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: agent-lyra
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: Python SDK for local AgentLyra agents, skills, workflows, and retrieval
|
|
5
|
+
Author: Lyra
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://agentlyra.in
|
|
8
|
+
Project-URL: Repository, https://gitlab.com/vibified/agent-lyra
|
|
9
|
+
Keywords: lyra,orchestration,rag,agents,sdk
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Requires-Python: >=3.9
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# AgentLyra SDK for Python
|
|
19
|
+
|
|
20
|
+
Define Python skills, register them with a local agent, and compose them into workflows. The Python SDK also includes retrieval utilities and the existing hosted compatibility client.
|
|
21
|
+
|
|
22
|
+
[AgentLyra](https://agentlyra.in/) · [Source repository](https://gitlab.com/vibified/agent-lyra)
|
|
23
|
+
|
|
24
|
+
## Install
|
|
25
|
+
|
|
26
|
+
Requires Python 3.9 or newer. The distribution name is `agent-lyra` and the import name is `lyra`.
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
python -m pip install agent-lyra
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Run a Python skill
|
|
33
|
+
|
|
34
|
+
A skill wraps a Python function. An agent only runs the registered skill you select. This example runs locally without credentials.
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
import asyncio
|
|
38
|
+
|
|
39
|
+
from lyra.standalone import Agent, Skill
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def classify_ticket(ticket: str) -> str:
|
|
43
|
+
return "billing" if "invoice" in ticket.lower() else "general"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
agent = Agent("support", [Skill("classify-ticket", classify_ticket)])
|
|
47
|
+
print(asyncio.run(agent.run("classify-ticket", "I have a question about my invoice.")))
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
The result is `billing`. Skill handlers can be regular functions or async functions. Pass the data your handler expects as the payload. In an async application, use `await agent.run(...)` directly.
|
|
51
|
+
|
|
52
|
+
## Compose a workflow
|
|
53
|
+
|
|
54
|
+
Use `create_task`, `create_workflow`, and `run_workflow` to run steps in sequence. A step may call an agent skill and read results saved by earlier steps. Retrieval helpers include `KeywordRetriever`, `InMemoryVectorStore`, and `chunk_text`.
|
|
55
|
+
|
|
56
|
+
The standalone API uses Python's standard library. A skill that calls a model or an external service uses the credentials and dependencies configured by your application.
|
|
57
|
+
|
|
58
|
+
## Package scope
|
|
59
|
+
|
|
60
|
+
- Python supports local skill execution, workflow composition, and retrieval.
|
|
61
|
+
- The Node.js App Builder CLI provides the Support IQ preview and export commands. Cloud agent and skill manifests are outside the Python runtime's current scope.
|
|
62
|
+
- `lyra.gated` remains available for deployments that implement the legacy `/agents/<vertical>/invoke` endpoint. Check endpoint compatibility before using it.
|
|
63
|
+
|
|
64
|
+
MIT licensed.
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# AgentLyra SDK for Python
|
|
2
|
+
|
|
3
|
+
Define Python skills, register them with a local agent, and compose them into workflows. The Python SDK also includes retrieval utilities and the existing hosted compatibility client.
|
|
4
|
+
|
|
5
|
+
[AgentLyra](https://agentlyra.in/) · [Source repository](https://gitlab.com/vibified/agent-lyra)
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
Requires Python 3.9 or newer. The distribution name is `agent-lyra` and the import name is `lyra`.
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
python -m pip install agent-lyra
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Run a Python skill
|
|
16
|
+
|
|
17
|
+
A skill wraps a Python function. An agent only runs the registered skill you select. This example runs locally without credentials.
|
|
18
|
+
|
|
19
|
+
```python
|
|
20
|
+
import asyncio
|
|
21
|
+
|
|
22
|
+
from lyra.standalone import Agent, Skill
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def classify_ticket(ticket: str) -> str:
|
|
26
|
+
return "billing" if "invoice" in ticket.lower() else "general"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
agent = Agent("support", [Skill("classify-ticket", classify_ticket)])
|
|
30
|
+
print(asyncio.run(agent.run("classify-ticket", "I have a question about my invoice.")))
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
The result is `billing`. Skill handlers can be regular functions or async functions. Pass the data your handler expects as the payload. In an async application, use `await agent.run(...)` directly.
|
|
34
|
+
|
|
35
|
+
## Compose a workflow
|
|
36
|
+
|
|
37
|
+
Use `create_task`, `create_workflow`, and `run_workflow` to run steps in sequence. A step may call an agent skill and read results saved by earlier steps. Retrieval helpers include `KeywordRetriever`, `InMemoryVectorStore`, and `chunk_text`.
|
|
38
|
+
|
|
39
|
+
The standalone API uses Python's standard library. A skill that calls a model or an external service uses the credentials and dependencies configured by your application.
|
|
40
|
+
|
|
41
|
+
## Package scope
|
|
42
|
+
|
|
43
|
+
- Python supports local skill execution, workflow composition, and retrieval.
|
|
44
|
+
- The Node.js App Builder CLI provides the Support IQ preview and export commands. Cloud agent and skill manifests are outside the Python runtime's current scope.
|
|
45
|
+
- `lyra.gated` remains available for deployments that implement the legacy `/agents/<vertical>/invoke` endpoint. Check endpoint compatibility before using it.
|
|
46
|
+
|
|
47
|
+
MIT licensed.
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=69", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "agent-lyra"
|
|
7
|
+
version = "0.3.0"
|
|
8
|
+
description = "Python SDK for local AgentLyra agents, skills, workflows, and retrieval"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [{ name = "Lyra" }]
|
|
13
|
+
keywords = ["lyra", "orchestration", "rag", "agents", "sdk"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"License :: OSI Approved :: MIT License",
|
|
17
|
+
"Operating System :: OS Independent"
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
[project.urls]
|
|
21
|
+
Homepage = "https://agentlyra.in"
|
|
22
|
+
Repository = "https://gitlab.com/vibified/agent-lyra"
|
|
23
|
+
|
|
24
|
+
[tool.setuptools]
|
|
25
|
+
package-dir = {"" = "src"}
|
|
26
|
+
|
|
27
|
+
[tool.setuptools.packages.find]
|
|
28
|
+
where = ["src"]
|
|
29
|
+
include = ["lyra*"]
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: agent-lyra
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: Python SDK for local AgentLyra agents, skills, workflows, and retrieval
|
|
5
|
+
Author: Lyra
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://agentlyra.in
|
|
8
|
+
Project-URL: Repository, https://gitlab.com/vibified/agent-lyra
|
|
9
|
+
Keywords: lyra,orchestration,rag,agents,sdk
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Requires-Python: >=3.9
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# AgentLyra SDK for Python
|
|
19
|
+
|
|
20
|
+
Define Python skills, register them with a local agent, and compose them into workflows. The Python SDK also includes retrieval utilities and the existing hosted compatibility client.
|
|
21
|
+
|
|
22
|
+
[AgentLyra](https://agentlyra.in/) · [Source repository](https://gitlab.com/vibified/agent-lyra)
|
|
23
|
+
|
|
24
|
+
## Install
|
|
25
|
+
|
|
26
|
+
Requires Python 3.9 or newer. The distribution name is `agent-lyra` and the import name is `lyra`.
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
python -m pip install agent-lyra
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Run a Python skill
|
|
33
|
+
|
|
34
|
+
A skill wraps a Python function. An agent only runs the registered skill you select. This example runs locally without credentials.
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
import asyncio
|
|
38
|
+
|
|
39
|
+
from lyra.standalone import Agent, Skill
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def classify_ticket(ticket: str) -> str:
|
|
43
|
+
return "billing" if "invoice" in ticket.lower() else "general"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
agent = Agent("support", [Skill("classify-ticket", classify_ticket)])
|
|
47
|
+
print(asyncio.run(agent.run("classify-ticket", "I have a question about my invoice.")))
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
The result is `billing`. Skill handlers can be regular functions or async functions. Pass the data your handler expects as the payload. In an async application, use `await agent.run(...)` directly.
|
|
51
|
+
|
|
52
|
+
## Compose a workflow
|
|
53
|
+
|
|
54
|
+
Use `create_task`, `create_workflow`, and `run_workflow` to run steps in sequence. A step may call an agent skill and read results saved by earlier steps. Retrieval helpers include `KeywordRetriever`, `InMemoryVectorStore`, and `chunk_text`.
|
|
55
|
+
|
|
56
|
+
The standalone API uses Python's standard library. A skill that calls a model or an external service uses the credentials and dependencies configured by your application.
|
|
57
|
+
|
|
58
|
+
## Package scope
|
|
59
|
+
|
|
60
|
+
- Python supports local skill execution, workflow composition, and retrieval.
|
|
61
|
+
- The Node.js App Builder CLI provides the Support IQ preview and export commands. Cloud agent and skill manifests are outside the Python runtime's current scope.
|
|
62
|
+
- `lyra.gated` remains available for deployments that implement the legacy `/agents/<vertical>/invoke` endpoint. Check endpoint compatibility before using it.
|
|
63
|
+
|
|
64
|
+
MIT licensed.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/agent_lyra.egg-info/PKG-INFO
|
|
5
|
+
src/agent_lyra.egg-info/SOURCES.txt
|
|
6
|
+
src/agent_lyra.egg-info/dependency_links.txt
|
|
7
|
+
src/agent_lyra.egg-info/top_level.txt
|
|
8
|
+
src/lyra/__init__.py
|
|
9
|
+
src/lyra/gated/__init__.py
|
|
10
|
+
src/lyra/gated/hosted_agents.py
|
|
11
|
+
src/lyra/standalone/__init__.py
|
|
12
|
+
src/lyra/standalone/agents.py
|
|
13
|
+
src/lyra/standalone/orchestration.py
|
|
14
|
+
src/lyra/standalone/rag.py
|
|
15
|
+
tests/test_agents.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
lyra
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import Any, Dict, Iterable
|
|
5
|
+
from urllib import request
|
|
6
|
+
import json
|
|
7
|
+
|
|
8
|
+
LYRA_VERTICALS: Iterable[str] = (
|
|
9
|
+
"hr",
|
|
10
|
+
"sales",
|
|
11
|
+
"support",
|
|
12
|
+
"finance",
|
|
13
|
+
"coding",
|
|
14
|
+
"legal",
|
|
15
|
+
"news",
|
|
16
|
+
"markets",
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
DEFAULT_BASE_URL = "https://api.lyra.ai/v1"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class HostedAgentClient:
|
|
24
|
+
api_key: str
|
|
25
|
+
base_url: str = DEFAULT_BASE_URL
|
|
26
|
+
|
|
27
|
+
def __post_init__(self) -> None:
|
|
28
|
+
if not self.api_key or not isinstance(self.api_key, str):
|
|
29
|
+
raise ValueError("A Lyra API key is required for gated features.")
|
|
30
|
+
|
|
31
|
+
def list_verticals(self) -> list[str]:
|
|
32
|
+
return list(LYRA_VERTICALS)
|
|
33
|
+
|
|
34
|
+
def invoke(self, vertical: str, payload: Dict[str, Any] | None = None) -> Dict[str, Any]:
|
|
35
|
+
if vertical not in LYRA_VERTICALS:
|
|
36
|
+
raise ValueError(f"Unsupported vertical: {vertical}")
|
|
37
|
+
|
|
38
|
+
data = json.dumps(payload or {}).encode("utf-8")
|
|
39
|
+
req = request.Request(
|
|
40
|
+
f"{self.base_url}/agents/{vertical}/invoke",
|
|
41
|
+
data=data,
|
|
42
|
+
method="POST",
|
|
43
|
+
headers={
|
|
44
|
+
"Content-Type": "application/json",
|
|
45
|
+
"Authorization": f"Bearer {self.api_key}",
|
|
46
|
+
},
|
|
47
|
+
)
|
|
48
|
+
with request.urlopen(req) as response: # nosec B310 - expected HTTPS API call
|
|
49
|
+
body = response.read().decode("utf-8")
|
|
50
|
+
return json.loads(body)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def create_hosted_agent_client(api_key: str, base_url: str = DEFAULT_BASE_URL) -> HostedAgentClient:
|
|
54
|
+
return HostedAgentClient(api_key=api_key, base_url=base_url)
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
from .agents import Agent, Skill
|
|
2
|
+
from .orchestration import (
|
|
3
|
+
Task,
|
|
4
|
+
Workflow,
|
|
5
|
+
create_linear_workflow,
|
|
6
|
+
create_task,
|
|
7
|
+
create_workflow,
|
|
8
|
+
run_workflow,
|
|
9
|
+
)
|
|
10
|
+
from .rag import (
|
|
11
|
+
InMemoryVectorStore,
|
|
12
|
+
KeywordRetriever,
|
|
13
|
+
chunk_text,
|
|
14
|
+
cosine_similarity,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"Agent",
|
|
19
|
+
"Skill",
|
|
20
|
+
"Task",
|
|
21
|
+
"Workflow",
|
|
22
|
+
"create_task",
|
|
23
|
+
"create_workflow",
|
|
24
|
+
"run_workflow",
|
|
25
|
+
"create_linear_workflow",
|
|
26
|
+
"chunk_text",
|
|
27
|
+
"cosine_similarity",
|
|
28
|
+
"InMemoryVectorStore",
|
|
29
|
+
"KeywordRetriever",
|
|
30
|
+
]
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Local agents with explicitly registered Python skills."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from inspect import isawaitable
|
|
7
|
+
from typing import Any, Awaitable, Callable, Dict, Iterable, Union
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
SkillHandler = Callable[[Any], Union[Any, Awaitable[Any]]]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True)
|
|
14
|
+
class Skill:
|
|
15
|
+
"""A named Python callable that accepts one payload."""
|
|
16
|
+
|
|
17
|
+
id: str
|
|
18
|
+
handler: SkillHandler
|
|
19
|
+
|
|
20
|
+
def __post_init__(self) -> None:
|
|
21
|
+
if not isinstance(self.id, str) or not self.id.strip():
|
|
22
|
+
raise ValueError("Skill ID must be a non-empty string.")
|
|
23
|
+
if not callable(self.handler):
|
|
24
|
+
raise TypeError("Skill handler must be callable.")
|
|
25
|
+
|
|
26
|
+
async def run(self, payload: Any) -> Any:
|
|
27
|
+
result = self.handler(payload)
|
|
28
|
+
return await result if isawaitable(result) else result
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Agent:
|
|
32
|
+
"""A local agent whose caller chooses which registered skill to invoke."""
|
|
33
|
+
|
|
34
|
+
def __init__(self, agent_id: str, skills: Iterable[Skill]) -> None:
|
|
35
|
+
if not isinstance(agent_id, str) or not agent_id.strip():
|
|
36
|
+
raise ValueError("Agent ID must be a non-empty string.")
|
|
37
|
+
self.id = agent_id
|
|
38
|
+
self._skills: Dict[str, Skill] = {}
|
|
39
|
+
for skill in skills:
|
|
40
|
+
if not isinstance(skill, Skill):
|
|
41
|
+
raise TypeError("Each agent skill must be a Skill.")
|
|
42
|
+
if skill.id in self._skills:
|
|
43
|
+
raise ValueError(f"Duplicate skill ID: {skill.id}")
|
|
44
|
+
self._skills[skill.id] = skill
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def skill_ids(self) -> tuple[str, ...]:
|
|
48
|
+
return tuple(self._skills)
|
|
49
|
+
|
|
50
|
+
async def run(self, skill_id: str, payload: Any) -> Any:
|
|
51
|
+
if skill_id not in self._skills:
|
|
52
|
+
raise KeyError(f"Skill {skill_id!r} is not registered on agent {self.id!r}.")
|
|
53
|
+
return await self._skills[skill_id].run(payload)
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import Any, Awaitable, Callable, Dict, Iterable, List
|
|
5
|
+
|
|
6
|
+
TaskHandler = Callable[[Dict[str, Any]], Awaitable[Any]]
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True)
|
|
10
|
+
class Task:
|
|
11
|
+
id: str
|
|
12
|
+
handler: TaskHandler
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Workflow:
|
|
16
|
+
def __init__(self, tasks: Iterable[Task] | None = None) -> None:
|
|
17
|
+
self._tasks: List[Task] = []
|
|
18
|
+
if tasks:
|
|
19
|
+
for task in tasks:
|
|
20
|
+
self.add(task)
|
|
21
|
+
|
|
22
|
+
def add(self, task: Task) -> "Workflow":
|
|
23
|
+
if not task.id or not isinstance(task.id, str):
|
|
24
|
+
raise ValueError("Task id must be a non-empty string.")
|
|
25
|
+
if not callable(task.handler):
|
|
26
|
+
raise ValueError("Task handler must be callable.")
|
|
27
|
+
self._tasks.append(task)
|
|
28
|
+
return self
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def tasks(self) -> List[Task]:
|
|
32
|
+
return list(self._tasks)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def create_task(task_id: str, handler: TaskHandler) -> Task:
|
|
36
|
+
return Task(id=task_id, handler=handler)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def create_workflow(tasks: Iterable[Task] | None = None) -> Workflow:
|
|
40
|
+
return Workflow(tasks)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
async def run_workflow(workflow: Workflow, initial_context: Dict[str, Any] | None = None) -> Dict[str, Any]:
|
|
44
|
+
context: Dict[str, Any] = dict(initial_context or {})
|
|
45
|
+
for task in workflow.tasks:
|
|
46
|
+
context[task.id] = await task.handler(context)
|
|
47
|
+
return context
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def create_linear_workflow(*handlers: TaskHandler) -> Workflow:
|
|
51
|
+
workflow = Workflow()
|
|
52
|
+
for index, handler in enumerate(handlers, start=1):
|
|
53
|
+
workflow.add(create_task(f"step_{index}", handler))
|
|
54
|
+
return workflow
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from math import sqrt
|
|
5
|
+
from typing import Any, Awaitable, Callable, Dict, Iterable, List
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def chunk_text(text: str, chunk_size: int = 500, overlap: int = 50) -> List[str]:
|
|
9
|
+
if not isinstance(text, str):
|
|
10
|
+
raise ValueError("text must be a string")
|
|
11
|
+
if chunk_size <= 0:
|
|
12
|
+
raise ValueError("chunk_size must be > 0")
|
|
13
|
+
if overlap < 0 or overlap >= chunk_size:
|
|
14
|
+
raise ValueError("overlap must be >= 0 and < chunk_size")
|
|
15
|
+
|
|
16
|
+
chunks: List[str] = []
|
|
17
|
+
start = 0
|
|
18
|
+
while start < len(text):
|
|
19
|
+
end = min(start + chunk_size, len(text))
|
|
20
|
+
chunks.append(text[start:end])
|
|
21
|
+
if end == len(text):
|
|
22
|
+
break
|
|
23
|
+
start = end - overlap
|
|
24
|
+
return chunks
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def cosine_similarity(a: Iterable[float], b: Iterable[float]) -> float:
|
|
28
|
+
list_a = list(a)
|
|
29
|
+
list_b = list(b)
|
|
30
|
+
if len(list_a) != len(list_b):
|
|
31
|
+
raise ValueError("Vectors must have equal length")
|
|
32
|
+
|
|
33
|
+
dot = sum(left * right for left, right in zip(list_a, list_b))
|
|
34
|
+
norm_a = sqrt(sum(x * x for x in list_a))
|
|
35
|
+
norm_b = sqrt(sum(x * x for x in list_b))
|
|
36
|
+
|
|
37
|
+
if norm_a == 0 or norm_b == 0:
|
|
38
|
+
return 0.0
|
|
39
|
+
return dot / (norm_a * norm_b)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass
|
|
43
|
+
class InMemoryVectorStore:
|
|
44
|
+
embedder: Callable[[str], Awaitable[List[float]]]
|
|
45
|
+
_docs: List[Dict[str, Any]] = field(default_factory=list)
|
|
46
|
+
|
|
47
|
+
async def add(self, doc_id: str, text: str, metadata: Dict[str, Any] | None = None) -> str:
|
|
48
|
+
if not doc_id or not isinstance(text, str):
|
|
49
|
+
raise ValueError("Document requires doc_id and text")
|
|
50
|
+
vector = await self.embedder(text)
|
|
51
|
+
self._docs.append({"id": doc_id, "text": text, "metadata": metadata or {}, "vector": vector})
|
|
52
|
+
return doc_id
|
|
53
|
+
|
|
54
|
+
async def search(self, query: str, top_k: int = 5) -> List[Dict[str, Any]]:
|
|
55
|
+
query_vector = await self.embedder(query)
|
|
56
|
+
ranked = []
|
|
57
|
+
for doc in self._docs:
|
|
58
|
+
ranked.append({**doc, "score": cosine_similarity(query_vector, doc["vector"])})
|
|
59
|
+
ranked.sort(key=lambda item: item["score"], reverse=True)
|
|
60
|
+
return ranked[:top_k]
|
|
61
|
+
|
|
62
|
+
def size(self) -> int:
|
|
63
|
+
return len(self._docs)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass
|
|
67
|
+
class KeywordRetriever:
|
|
68
|
+
_docs: List[Dict[str, Any]] = field(default_factory=list)
|
|
69
|
+
|
|
70
|
+
def add(self, doc_id: str, text: str, metadata: Dict[str, Any] | None = None) -> str:
|
|
71
|
+
if not doc_id or not isinstance(text, str):
|
|
72
|
+
raise ValueError("Document requires doc_id and text")
|
|
73
|
+
self._docs.append({"id": doc_id, "text": text, "metadata": metadata or {}})
|
|
74
|
+
return doc_id
|
|
75
|
+
|
|
76
|
+
def search(self, query: str, top_k: int = 5) -> List[Dict[str, Any]]:
|
|
77
|
+
terms = [term for term in query.lower().split() if term]
|
|
78
|
+
ranked = []
|
|
79
|
+
|
|
80
|
+
for doc in self._docs:
|
|
81
|
+
body = doc["text"].lower()
|
|
82
|
+
hits = sum(1 for term in terms if term in body)
|
|
83
|
+
if hits > 0:
|
|
84
|
+
ranked.append({**doc, "score": hits})
|
|
85
|
+
|
|
86
|
+
ranked.sort(key=lambda item: item["score"], reverse=True)
|
|
87
|
+
return ranked[:top_k]
|
|
88
|
+
|
|
89
|
+
def size(self) -> int:
|
|
90
|
+
return len(self._docs)
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import unittest
|
|
2
|
+
|
|
3
|
+
from lyra.standalone import Agent, Skill, create_task, create_workflow, run_workflow
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class AgentTests(unittest.IsolatedAsyncioTestCase):
|
|
7
|
+
async def test_runs_sync_and_async_skills_in_a_workflow(self):
|
|
8
|
+
async def draft(category):
|
|
9
|
+
return f"Send to {category}."
|
|
10
|
+
|
|
11
|
+
agent = Agent("support", [
|
|
12
|
+
Skill("classify", lambda text: "billing" if "invoice" in text else "general"),
|
|
13
|
+
Skill("draft", draft),
|
|
14
|
+
])
|
|
15
|
+
|
|
16
|
+
async def classify(context):
|
|
17
|
+
return await agent.run("classify", context["ticket"])
|
|
18
|
+
|
|
19
|
+
async def make_draft(context):
|
|
20
|
+
return await agent.run("draft", context["category"])
|
|
21
|
+
|
|
22
|
+
workflow = create_workflow([create_task("category", classify), create_task("draft", make_draft)])
|
|
23
|
+
result = await run_workflow(workflow, {"ticket": "Question about my invoice"})
|
|
24
|
+
self.assertEqual(result["draft"], "Send to billing.")
|
|
25
|
+
self.assertEqual(agent.skill_ids, ("classify", "draft"))
|
|
26
|
+
|
|
27
|
+
async def test_unknown_skill_does_not_invoke_handler(self):
|
|
28
|
+
def unexpected(payload):
|
|
29
|
+
self.fail("Unselected skill ran")
|
|
30
|
+
|
|
31
|
+
agent = Agent("support", [Skill("draft", unexpected)])
|
|
32
|
+
with self.assertRaisesRegex(KeyError, "not registered"):
|
|
33
|
+
await agent.run("unknown", None)
|
|
34
|
+
|
|
35
|
+
def test_invalid_or_duplicate_registration(self):
|
|
36
|
+
with self.assertRaises(ValueError):
|
|
37
|
+
Skill(" ", lambda value: value)
|
|
38
|
+
with self.assertRaises(TypeError):
|
|
39
|
+
Skill("bad", None)
|
|
40
|
+
skill = Skill("draft", lambda value: value)
|
|
41
|
+
with self.assertRaisesRegex(ValueError, "Duplicate"):
|
|
42
|
+
Agent("support", [skill, skill])
|