lmnr 0.2.6__py3-none-any.whl → 0.2.8__py3-none-any.whl
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.
- lmnr/cli/cli.py +1 -4
- lmnr/cli/parser/nodes/code.py +27 -0
- lmnr/cli/parser/nodes/condition.py +30 -0
- lmnr/cli/parser/nodes/router.py +37 -0
- lmnr/cli/parser/nodes/semantic_search.py +11 -39
- lmnr/cli/parser/nodes/types.py +50 -6
- lmnr/cli/parser/parser.py +4 -4
- lmnr/sdk/remote_debugger.py +1 -0
- lmnr/types.py +8 -3
- {lmnr-0.2.6.dist-info → lmnr-0.2.8.dist-info}/METADATA +5 -5
- lmnr-0.2.8.dist-info/RECORD +24 -0
- lmnr/cli/cookiecutter.json +0 -9
- lmnr/cli/{{cookiecutter.lmnr_pipelines_dir_name}}/__init__.py +0 -0
- lmnr/cli/{{cookiecutter.lmnr_pipelines_dir_name}}/engine/__init__.py +0 -1
- lmnr/cli/{{cookiecutter.lmnr_pipelines_dir_name}}/engine/action.py +0 -14
- lmnr/cli/{{cookiecutter.lmnr_pipelines_dir_name}}/engine/engine.py +0 -262
- lmnr/cli/{{cookiecutter.lmnr_pipelines_dir_name}}/engine/state.py +0 -69
- lmnr/cli/{{cookiecutter.lmnr_pipelines_dir_name}}/engine/task.py +0 -38
- lmnr/cli/{{cookiecutter.lmnr_pipelines_dir_name}}/pipelines/{{cookiecutter.pipeline_dir_name}}/__init__.py +0 -1
- lmnr/cli/{{cookiecutter.lmnr_pipelines_dir_name}}/pipelines/{{cookiecutter.pipeline_dir_name}}/nodes/functions.py +0 -185
- lmnr/cli/{{cookiecutter.lmnr_pipelines_dir_name}}/pipelines/{{cookiecutter.pipeline_dir_name}}/{{cookiecutter.pipeline_dir_name}}.py +0 -87
- lmnr/cli/{{cookiecutter.lmnr_pipelines_dir_name}}/types.py +0 -35
- lmnr-0.2.6.dist-info/RECORD +0 -32
- {lmnr-0.2.6.dist-info → lmnr-0.2.8.dist-info}/LICENSE +0 -0
- {lmnr-0.2.6.dist-info → lmnr-0.2.8.dist-info}/WHEEL +0 -0
- {lmnr-0.2.6.dist-info → lmnr-0.2.8.dist-info}/entry_points.txt +0 -0
lmnr/cli/cli.py
CHANGED
@@ -4,11 +4,9 @@ import os
|
|
4
4
|
import click
|
5
5
|
import logging
|
6
6
|
from cookiecutter.main import cookiecutter
|
7
|
-
from importlib import resources as importlib_resources
|
8
7
|
from pydantic.alias_generators import to_pascal
|
9
8
|
|
10
9
|
from .parser.parser import runnable_graph_to_template_vars
|
11
|
-
import lmnr
|
12
10
|
|
13
11
|
logger = logging.getLogger(__name__)
|
14
12
|
|
@@ -87,11 +85,10 @@ def pull(pipeline_name, pipeline_version_name, project_api_key, loglevel):
|
|
87
85
|
|
88
86
|
logger.info(f"Context:\n{context}")
|
89
87
|
cookiecutter(
|
90
|
-
|
88
|
+
"https://github.com/lmnr-ai/lmnr-python-engine.git",
|
91
89
|
output_dir=".",
|
92
90
|
config_file=None,
|
93
91
|
extra_context=context,
|
94
|
-
directory="cli/",
|
95
92
|
no_input=True,
|
96
93
|
overwrite_if_exists=True,
|
97
94
|
)
|
@@ -0,0 +1,27 @@
|
|
1
|
+
from dataclasses import dataclass
|
2
|
+
import uuid
|
3
|
+
|
4
|
+
from lmnr.cli.parser.nodes import Handle, NodeFunctions
|
5
|
+
from lmnr.cli.parser.utils import map_handles
|
6
|
+
|
7
|
+
|
8
|
+
@dataclass
|
9
|
+
class CodeNode(NodeFunctions):
|
10
|
+
id: uuid.UUID
|
11
|
+
name: str
|
12
|
+
inputs: list[Handle]
|
13
|
+
outputs: list[Handle]
|
14
|
+
inputs_mappings: dict[uuid.UUID, uuid.UUID]
|
15
|
+
|
16
|
+
def handles_mapping(
|
17
|
+
self, output_handle_id_to_node_name: dict[str, str]
|
18
|
+
) -> list[tuple[str, str]]:
|
19
|
+
return map_handles(
|
20
|
+
self.inputs, self.inputs_mappings, output_handle_id_to_node_name
|
21
|
+
)
|
22
|
+
|
23
|
+
def node_type(self) -> str:
|
24
|
+
return "Code"
|
25
|
+
|
26
|
+
def config(self) -> dict:
|
27
|
+
return {}
|
@@ -0,0 +1,30 @@
|
|
1
|
+
from dataclasses import dataclass
|
2
|
+
import uuid
|
3
|
+
|
4
|
+
from lmnr.cli.parser.nodes import Handle, NodeFunctions
|
5
|
+
from lmnr.cli.parser.utils import map_handles
|
6
|
+
|
7
|
+
|
8
|
+
@dataclass
|
9
|
+
class ConditionNode(NodeFunctions):
|
10
|
+
id: uuid.UUID
|
11
|
+
name: str
|
12
|
+
inputs: list[Handle]
|
13
|
+
outputs: list[Handle]
|
14
|
+
inputs_mappings: dict[uuid.UUID, uuid.UUID]
|
15
|
+
condition: str
|
16
|
+
|
17
|
+
def handles_mapping(
|
18
|
+
self, output_handle_id_to_node_name: dict[str, str]
|
19
|
+
) -> list[tuple[str, str]]:
|
20
|
+
return map_handles(
|
21
|
+
self.inputs, self.inputs_mappings, output_handle_id_to_node_name
|
22
|
+
)
|
23
|
+
|
24
|
+
def node_type(self) -> str:
|
25
|
+
return "Condition"
|
26
|
+
|
27
|
+
def config(self) -> dict:
|
28
|
+
return {
|
29
|
+
"condition": self.condition,
|
30
|
+
}
|
@@ -0,0 +1,37 @@
|
|
1
|
+
from dataclasses import dataclass
|
2
|
+
import uuid
|
3
|
+
|
4
|
+
from lmnr.cli.parser.nodes import Handle, NodeFunctions
|
5
|
+
from lmnr.cli.parser.utils import map_handles
|
6
|
+
|
7
|
+
|
8
|
+
@dataclass
|
9
|
+
class Route:
|
10
|
+
name: str
|
11
|
+
|
12
|
+
|
13
|
+
@dataclass
|
14
|
+
class RouterNode(NodeFunctions):
|
15
|
+
id: uuid.UUID
|
16
|
+
name: str
|
17
|
+
inputs: list[Handle]
|
18
|
+
outputs: list[Handle]
|
19
|
+
inputs_mappings: dict[uuid.UUID, uuid.UUID]
|
20
|
+
routes: list[Route]
|
21
|
+
has_default_route: bool
|
22
|
+
|
23
|
+
def handles_mapping(
|
24
|
+
self, output_handle_id_to_node_name: dict[str, str]
|
25
|
+
) -> list[tuple[str, str]]:
|
26
|
+
return map_handles(
|
27
|
+
self.inputs, self.inputs_mappings, output_handle_id_to_node_name
|
28
|
+
)
|
29
|
+
|
30
|
+
def node_type(self) -> str:
|
31
|
+
return "Router"
|
32
|
+
|
33
|
+
def config(self) -> dict:
|
34
|
+
return {
|
35
|
+
"routes": str([route.name for route in self.routes]),
|
36
|
+
"has_default_route": str(self.has_default_route),
|
37
|
+
}
|
@@ -1,5 +1,4 @@
|
|
1
1
|
from dataclasses import dataclass
|
2
|
-
from datetime import datetime
|
3
2
|
|
4
3
|
import uuid
|
5
4
|
|
@@ -7,44 +6,19 @@ from lmnr.cli.parser.nodes import Handle, NodeFunctions
|
|
7
6
|
from lmnr.cli.parser.utils import map_handles
|
8
7
|
|
9
8
|
|
10
|
-
@dataclass
|
11
|
-
class FileMetadata:
|
12
|
-
id: uuid.UUID
|
13
|
-
created_at: datetime
|
14
|
-
project_id: uuid.UUID
|
15
|
-
filename: str
|
16
|
-
|
17
|
-
|
18
9
|
@dataclass
|
19
10
|
class Dataset:
|
20
11
|
id: uuid.UUID
|
21
|
-
created_at: datetime
|
22
|
-
project_id: uuid.UUID
|
23
|
-
name: str
|
24
|
-
|
25
|
-
|
26
|
-
@dataclass
|
27
|
-
class SemanticSearchDatasource:
|
28
|
-
type: str
|
29
|
-
id: uuid.UUID
|
30
|
-
# TODO: Paste other fields here, use Union[FileMetadata, Dataset]
|
12
|
+
# created_at: datetime
|
13
|
+
# project_id: uuid.UUID
|
14
|
+
# name: str
|
15
|
+
# indexed_on: Optional[str]
|
31
16
|
|
32
17
|
@classmethod
|
33
|
-
def from_dict(cls,
|
34
|
-
|
35
|
-
|
36
|
-
|
37
|
-
id=uuid.UUID(datasource_dict["id"]),
|
38
|
-
)
|
39
|
-
elif datasource_dict["type"] == "Dataset":
|
40
|
-
return cls(
|
41
|
-
type="Dataset",
|
42
|
-
id=uuid.UUID(datasource_dict["id"]),
|
43
|
-
)
|
44
|
-
else:
|
45
|
-
raise ValueError(
|
46
|
-
f"Invalid SemanticSearchDatasource type: {datasource_dict['type']}"
|
47
|
-
)
|
18
|
+
def from_dict(cls, dataset_dict: dict) -> "Dataset":
|
19
|
+
return cls(
|
20
|
+
id=uuid.UUID(dataset_dict["id"]),
|
21
|
+
)
|
48
22
|
|
49
23
|
|
50
24
|
@dataclass
|
@@ -57,7 +31,7 @@ class SemanticSearchNode(NodeFunctions):
|
|
57
31
|
limit: int
|
58
32
|
threshold: float
|
59
33
|
template: str
|
60
|
-
|
34
|
+
datasets: list[Dataset]
|
61
35
|
|
62
36
|
def handles_mapping(
|
63
37
|
self, output_handle_id_to_node_name: dict[str, str]
|
@@ -74,8 +48,6 @@ class SemanticSearchNode(NodeFunctions):
|
|
74
48
|
"limit": self.limit,
|
75
49
|
"threshold": self.threshold,
|
76
50
|
"template": self.template,
|
77
|
-
"datasource_ids": [str(
|
78
|
-
"datasource_ids_list": str(
|
79
|
-
[str(datasource.id) for datasource in self.datasources]
|
80
|
-
),
|
51
|
+
"datasource_ids": [str(dataset.id) for dataset in self.datasets],
|
52
|
+
"datasource_ids_list": str([str(dataset.id) for dataset in self.datasets]),
|
81
53
|
}
|
lmnr/cli/parser/nodes/types.py
CHANGED
@@ -2,11 +2,14 @@ from typing import Any, Union
|
|
2
2
|
import uuid
|
3
3
|
|
4
4
|
from lmnr.cli.parser.nodes import Handle
|
5
|
+
from lmnr.cli.parser.nodes.code import CodeNode
|
6
|
+
from lmnr.cli.parser.nodes.condition import ConditionNode
|
5
7
|
from lmnr.cli.parser.nodes.input import InputNode
|
6
8
|
from lmnr.cli.parser.nodes.llm import LLMNode
|
7
9
|
from lmnr.cli.parser.nodes.output import OutputNode
|
10
|
+
from lmnr.cli.parser.nodes.router import Route, RouterNode
|
8
11
|
from lmnr.cli.parser.nodes.semantic_search import (
|
9
|
-
|
12
|
+
Dataset,
|
10
13
|
SemanticSearchNode,
|
11
14
|
)
|
12
15
|
from lmnr.types import NodeInput, ChatMessage
|
@@ -21,7 +24,15 @@ def node_input_from_json(json_val: Any) -> NodeInput:
|
|
21
24
|
raise ValueError(f"Invalid NodeInput value: {json_val}")
|
22
25
|
|
23
26
|
|
24
|
-
Node = Union[
|
27
|
+
Node = Union[
|
28
|
+
InputNode,
|
29
|
+
OutputNode,
|
30
|
+
ConditionNode,
|
31
|
+
LLMNode,
|
32
|
+
RouterNode,
|
33
|
+
SemanticSearchNode,
|
34
|
+
CodeNode,
|
35
|
+
]
|
25
36
|
|
26
37
|
|
27
38
|
def node_from_dict(node_dict: dict) -> Node:
|
@@ -44,6 +55,18 @@ def node_from_dict(node_dict: dict) -> Node:
|
|
44
55
|
for k, v in node_dict["inputsMappings"].items()
|
45
56
|
},
|
46
57
|
)
|
58
|
+
elif node_dict["type"] == "Condition":
|
59
|
+
return ConditionNode(
|
60
|
+
id=uuid.UUID(node_dict["id"]),
|
61
|
+
name=node_dict["name"],
|
62
|
+
inputs=[Handle.from_dict(handle) for handle in node_dict["inputs"]],
|
63
|
+
outputs=[Handle.from_dict(handle) for handle in node_dict["outputs"]],
|
64
|
+
inputs_mappings={
|
65
|
+
uuid.UUID(k): uuid.UUID(v)
|
66
|
+
for k, v in node_dict["inputsMappings"].items()
|
67
|
+
},
|
68
|
+
condition=node_dict["condition"],
|
69
|
+
)
|
47
70
|
elif node_dict["type"] == "LLM":
|
48
71
|
return LLMNode(
|
49
72
|
id=uuid.UUID(node_dict["id"]),
|
@@ -69,6 +92,19 @@ def node_from_dict(node_dict: dict) -> Node:
|
|
69
92
|
structured_output_schema=None,
|
70
93
|
structured_output_schema_target=None,
|
71
94
|
)
|
95
|
+
elif node_dict["type"] == "Router":
|
96
|
+
return RouterNode(
|
97
|
+
id=uuid.UUID(node_dict["id"]),
|
98
|
+
name=node_dict["name"],
|
99
|
+
inputs=[Handle.from_dict(handle) for handle in node_dict["inputs"]],
|
100
|
+
outputs=[Handle.from_dict(handle) for handle in node_dict["outputs"]],
|
101
|
+
inputs_mappings={
|
102
|
+
uuid.UUID(k): uuid.UUID(v)
|
103
|
+
for k, v in node_dict["inputsMappings"].items()
|
104
|
+
},
|
105
|
+
routes=[Route(name=route["name"]) for route in node_dict["routes"]],
|
106
|
+
has_default_route=node_dict["hasDefaultRoute"],
|
107
|
+
)
|
72
108
|
elif node_dict["type"] == "SemanticSearch":
|
73
109
|
return SemanticSearchNode(
|
74
110
|
id=uuid.UUID(node_dict["id"]),
|
@@ -82,10 +118,18 @@ def node_from_dict(node_dict: dict) -> Node:
|
|
82
118
|
limit=node_dict["limit"],
|
83
119
|
threshold=node_dict["threshold"],
|
84
120
|
template=node_dict["template"],
|
85
|
-
|
86
|
-
|
87
|
-
|
88
|
-
|
121
|
+
datasets=[Dataset.from_dict(ds) for ds in node_dict["datasets"]],
|
122
|
+
)
|
123
|
+
elif node_dict["type"] == "Code":
|
124
|
+
return CodeNode(
|
125
|
+
id=uuid.UUID(node_dict["id"]),
|
126
|
+
name=node_dict["name"],
|
127
|
+
inputs=[Handle.from_dict(handle) for handle in node_dict["inputs"]],
|
128
|
+
outputs=[Handle.from_dict(handle) for handle in node_dict["outputs"]],
|
129
|
+
inputs_mappings={
|
130
|
+
uuid.UUID(k): uuid.UUID(v)
|
131
|
+
for k, v in node_dict["inputsMappings"].items()
|
132
|
+
},
|
89
133
|
)
|
90
134
|
else:
|
91
135
|
raise ValueError(f"Node type {node_dict['type']} not supported")
|
lmnr/cli/parser/parser.py
CHANGED
@@ -17,6 +17,9 @@ def runnable_graph_to_template_vars(graph: dict) -> dict:
|
|
17
17
|
node = node_from_dict(node_obj)
|
18
18
|
handles_mapping = node.handles_mapping(output_handle_id_to_node_name)
|
19
19
|
node_type = node.node_type()
|
20
|
+
|
21
|
+
unique_handles = set([handle_name for (handle_name, _) in handles_mapping])
|
22
|
+
|
20
23
|
tasks.append(
|
21
24
|
{
|
22
25
|
"name": node.name,
|
@@ -28,10 +31,7 @@ def runnable_graph_to_template_vars(graph: dict) -> dict:
|
|
28
31
|
handle_name for (handle_name, _) in handles_mapping
|
29
32
|
],
|
30
33
|
"handle_args": ", ".join(
|
31
|
-
[
|
32
|
-
f"{handle_name}: NodeInput"
|
33
|
-
for (handle_name, _) in handles_mapping
|
34
|
-
]
|
34
|
+
[f"{handle_name}: NodeInput" for handle_name in unique_handles]
|
35
35
|
),
|
36
36
|
"prev": [],
|
37
37
|
"next": [],
|
lmnr/sdk/remote_debugger.py
CHANGED
lmnr/types.py
CHANGED
@@ -9,7 +9,12 @@ class ChatMessage(pydantic.BaseModel):
|
|
9
9
|
content: str
|
10
10
|
|
11
11
|
|
12
|
-
|
12
|
+
class ConditionedValue(pydantic.BaseModel):
|
13
|
+
condition: str
|
14
|
+
value: "NodeInput"
|
15
|
+
|
16
|
+
|
17
|
+
NodeInput = Union[str, list[ChatMessage], ConditionedValue] # TypeAlias
|
13
18
|
|
14
19
|
|
15
20
|
class EndpointRunRequest(pydantic.BaseModel):
|
@@ -51,7 +56,7 @@ class SDKError(Exception):
|
|
51
56
|
super().__init__(error_message)
|
52
57
|
|
53
58
|
|
54
|
-
class
|
59
|
+
class ToolCallFunction(pydantic.BaseModel):
|
55
60
|
name: str
|
56
61
|
arguments: str
|
57
62
|
|
@@ -59,7 +64,7 @@ class ToolCallRequest(pydantic.BaseModel):
|
|
59
64
|
class ToolCall(pydantic.BaseModel):
|
60
65
|
id: Optional[str]
|
61
66
|
type: Optional[str]
|
62
|
-
function:
|
67
|
+
function: ToolCallFunction
|
63
68
|
|
64
69
|
|
65
70
|
# TODO: allow snake_case and manually convert to camelCase
|
@@ -1,6 +1,6 @@
|
|
1
1
|
Metadata-Version: 2.1
|
2
2
|
Name: lmnr
|
3
|
-
Version: 0.2.
|
3
|
+
Version: 0.2.8
|
4
4
|
Summary: Python SDK for Laminar AI
|
5
5
|
License: Apache-2.0
|
6
6
|
Author: lmnr.ai
|
@@ -22,7 +22,7 @@ Description-Content-Type: text/markdown
|
|
22
22
|
|
23
23
|
# Laminar AI
|
24
24
|
|
25
|
-
This
|
25
|
+
This repo provides core for code generation, Laminar CLI, and Laminar SDK.
|
26
26
|
|
27
27
|
## Quickstart
|
28
28
|
```sh
|
@@ -166,12 +166,12 @@ res = pipeline.run(
|
|
166
166
|
"OPENAI_API_KEY": <OPENAI_API_KEY>,
|
167
167
|
}
|
168
168
|
)
|
169
|
-
print(f"
|
169
|
+
print(f"Pipeline run result:\n{res}")
|
170
170
|
```
|
171
171
|
|
172
172
|
### Current functionality
|
173
|
-
- Supports graph generation for graphs with Input, Output,
|
174
|
-
- For LLM nodes, it only supports OpenAI and Anthropic models
|
173
|
+
- Supports graph generation for graphs with the following nodes: Input, Output, LLM, Router, Code.
|
174
|
+
- For LLM nodes, it only supports OpenAI and Anthropic models. Structured output in LLM nodes will be supported soon.
|
175
175
|
|
176
176
|
## PROJECT_API_KEY
|
177
177
|
|
@@ -0,0 +1,24 @@
|
|
1
|
+
lmnr/__init__.py,sha256=NWHDZ-KAl3pQGDnKUbBbZaW4es-0-9Xt6gP-UrjyuEQ,207
|
2
|
+
lmnr/cli/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
3
|
+
lmnr/cli/__main__.py,sha256=8hDtWlaFZK24KhfNq_ZKgtXqYHsDQDetukOCMlsbW0Q,59
|
4
|
+
lmnr/cli/cli.py,sha256=0Qw_dxE_N9F38asUB7pMbILJGVi-pPtqiao4aTjQQGM,2769
|
5
|
+
lmnr/cli/parser/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
6
|
+
lmnr/cli/parser/nodes/__init__.py,sha256=BNbbfn0WwbFDA6TNhLOaT_Ji69rCL5voUibqMD7Knng,1163
|
7
|
+
lmnr/cli/parser/nodes/code.py,sha256=GXqOxN6tdiStZGWLbN3WZCmDfzwYIgSRmZ5t72AOIXc,661
|
8
|
+
lmnr/cli/parser/nodes/condition.py,sha256=AJny0ILXbSy1hTwsRvZvDUqts9INNx63yQSkD7Dp7KU,740
|
9
|
+
lmnr/cli/parser/nodes/input.py,sha256=Xwktcih7Mezqv4cEejfPkpG8uJxDsbqRytBvKmlJDYE,578
|
10
|
+
lmnr/cli/parser/nodes/llm.py,sha256=iQWYFnQi5PcQD9WJpTSHbSzClM6s0wBOoEqyN5c4yQo,1674
|
11
|
+
lmnr/cli/parser/nodes/output.py,sha256=1XBppSscxM01kfZhE9oOh2GgdCVzyPVe2RAxLI5HmUc,665
|
12
|
+
lmnr/cli/parser/nodes/router.py,sha256=dmCx4ho8_GdFJXQa8UevMf_uEP7AKBv_MJ2zpLC6Vck,894
|
13
|
+
lmnr/cli/parser/nodes/semantic_search.py,sha256=DWDPpV78XZ7vPIaPd86FbeDFAnKah4e61M1TOzwnt84,1352
|
14
|
+
lmnr/cli/parser/nodes/types.py,sha256=XJQUg5VTbpc8LKN3-DMZkDMDiweGtKlA05edTcMYbr0,5257
|
15
|
+
lmnr/cli/parser/parser.py,sha256=kAZEeg358lyj_Q1IIhQB_bA7LW3Aw6RduShIfUSmLqQ,2173
|
16
|
+
lmnr/cli/parser/utils.py,sha256=wVaqHVOR9VXl8Og9nkVyCVgHIcgbtYGkDOEGPtmjZ8g,715
|
17
|
+
lmnr/sdk/endpoint.py,sha256=0HjcxMUcJz-klFZO2f5xtTaoLjcaEb8vrJ_YldTWUc8,7467
|
18
|
+
lmnr/sdk/remote_debugger.py,sha256=tC8OywEkxzeUCAHrpfhlL-iMP_0Rqh9qC2DtoYEGJjU,5174
|
19
|
+
lmnr/types.py,sha256=OR9xRAQ5uTTwpJTDL_e3jZqxYJWvyX96CCoxr3oo94g,2112
|
20
|
+
lmnr-0.2.8.dist-info/LICENSE,sha256=67b_wJHVV1CBaWkrKFWU1wyqTPSdzH77Ls-59631COg,10411
|
21
|
+
lmnr-0.2.8.dist-info/METADATA,sha256=kfHTeQtkFVsk3JK3LopVuvfr5OQkjG0YGXyoRrrqPq4,5479
|
22
|
+
lmnr-0.2.8.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
|
23
|
+
lmnr-0.2.8.dist-info/entry_points.txt,sha256=Qg7ZRax4k-rcQsZ26XRYQ8YFSBiyY2PNxYfq4a6PYXI,41
|
24
|
+
lmnr-0.2.8.dist-info/RECORD,,
|
lmnr/cli/cookiecutter.json
DELETED
@@ -1,9 +0,0 @@
|
|
1
|
-
{
|
2
|
-
"lmnr_pipelines_dir_name": "lmnr_engine",
|
3
|
-
"pipeline_name": "Laminar Pipeline",
|
4
|
-
"pipeline_dir_name": "{{ cookiecutter['pipeline_name'].lower().replace('-', '_').replace(' ', '_') }}",
|
5
|
-
"class_name": "LaminarPipeline",
|
6
|
-
"pipeline_version_name": "main",
|
7
|
-
"_tasks": {},
|
8
|
-
"_jinja2_env_vars": {"lstrip_blocks": true, "trim_blocks": true}
|
9
|
-
}
|
File without changes
|
@@ -1 +0,0 @@
|
|
1
|
-
from .engine import Engine
|
@@ -1,14 +0,0 @@
|
|
1
|
-
from dataclasses import dataclass
|
2
|
-
from typing import Union
|
3
|
-
|
4
|
-
from lmnr_engine.types import NodeInput
|
5
|
-
|
6
|
-
|
7
|
-
@dataclass
|
8
|
-
class RunOutput:
|
9
|
-
status: str # "Success" | "Termination" TODO: Turn into Enum
|
10
|
-
output: Union[NodeInput, None]
|
11
|
-
|
12
|
-
|
13
|
-
class NodeRunError(Exception):
|
14
|
-
pass
|
@@ -1,262 +0,0 @@
|
|
1
|
-
from concurrent.futures import ThreadPoolExecutor
|
2
|
-
import datetime
|
3
|
-
import logging
|
4
|
-
from typing import Optional
|
5
|
-
import uuid
|
6
|
-
from dataclasses import dataclass
|
7
|
-
import queue
|
8
|
-
|
9
|
-
from .task import Task
|
10
|
-
from .action import NodeRunError, RunOutput
|
11
|
-
from .state import State
|
12
|
-
from lmnr.types import NodeInput
|
13
|
-
from lmnr_engine.types import Message
|
14
|
-
|
15
|
-
|
16
|
-
logger = logging.getLogger(__name__)
|
17
|
-
|
18
|
-
|
19
|
-
@dataclass
|
20
|
-
class ScheduledTask:
|
21
|
-
status: str # "Task" | "Err" TODO: Use an enum
|
22
|
-
task_name: Optional[str]
|
23
|
-
|
24
|
-
|
25
|
-
class RunError(Exception):
|
26
|
-
outputs: dict[str, Message]
|
27
|
-
|
28
|
-
|
29
|
-
@dataclass
|
30
|
-
class Engine:
|
31
|
-
tasks: dict[str, Task]
|
32
|
-
active_tasks: set[str]
|
33
|
-
depths: dict[str, int]
|
34
|
-
outputs: dict[str, Message]
|
35
|
-
env: dict[str, str]
|
36
|
-
thread_pool_executor: ThreadPoolExecutor
|
37
|
-
# TODO: Store thread pool executor's Futures here to have control
|
38
|
-
# over them (e.g. cancel them)
|
39
|
-
|
40
|
-
@classmethod
|
41
|
-
def new(
|
42
|
-
cls, thread_pool_executor: ThreadPoolExecutor, env: dict[str, str] = {}
|
43
|
-
) -> "Engine":
|
44
|
-
return cls(
|
45
|
-
tasks={},
|
46
|
-
active_tasks=set(),
|
47
|
-
depths={},
|
48
|
-
outputs={},
|
49
|
-
env=env,
|
50
|
-
thread_pool_executor=thread_pool_executor,
|
51
|
-
)
|
52
|
-
|
53
|
-
@classmethod
|
54
|
-
def with_tasks(
|
55
|
-
cls,
|
56
|
-
tasks: list[Task],
|
57
|
-
thread_pool_executor: ThreadPoolExecutor,
|
58
|
-
env: dict[str, str] = {},
|
59
|
-
) -> "Engine":
|
60
|
-
dag = cls.new(thread_pool_executor, env=env)
|
61
|
-
|
62
|
-
for task in tasks:
|
63
|
-
dag.tasks[task.name] = task
|
64
|
-
dag.depths[task.name] = 0
|
65
|
-
|
66
|
-
return dag
|
67
|
-
|
68
|
-
def override_inputs(self, inputs: dict[str, NodeInput]) -> None:
|
69
|
-
for task in self.tasks.values():
|
70
|
-
# TODO: Check that it's the Input type task
|
71
|
-
if not task.prev:
|
72
|
-
task.value = inputs[task.name]
|
73
|
-
|
74
|
-
def run(self, inputs: dict[str, NodeInput]) -> dict[str, Message]:
|
75
|
-
self.override_inputs(inputs)
|
76
|
-
|
77
|
-
q = queue.Queue()
|
78
|
-
|
79
|
-
input_tasks = []
|
80
|
-
for task in self.tasks.values():
|
81
|
-
if len(task.prev) == 0:
|
82
|
-
input_tasks.append(task.name)
|
83
|
-
|
84
|
-
for task_id in input_tasks:
|
85
|
-
q.put(ScheduledTask(status="Task", task_name=task_id))
|
86
|
-
|
87
|
-
while True:
|
88
|
-
logger.info("Waiting for task from queue")
|
89
|
-
scheduled_task: ScheduledTask = q.get()
|
90
|
-
logger.info(f"Got task from queue: {scheduled_task}")
|
91
|
-
if scheduled_task.status == "Err":
|
92
|
-
# TODO: Abort all other threads
|
93
|
-
raise RunError(self.outputs)
|
94
|
-
|
95
|
-
task: Task = self.tasks[scheduled_task.task_name] # type: ignore
|
96
|
-
logger.info(f"Task next: {task.next}")
|
97
|
-
|
98
|
-
if not task.next:
|
99
|
-
try:
|
100
|
-
fut = self.execute_task(task, q)
|
101
|
-
fut.result()
|
102
|
-
if not self.active_tasks:
|
103
|
-
return self.outputs
|
104
|
-
except Exception:
|
105
|
-
raise RunError(self.outputs)
|
106
|
-
else:
|
107
|
-
self.execute_task(task, q)
|
108
|
-
|
109
|
-
def execute_task_inner(
|
110
|
-
self,
|
111
|
-
task: Task,
|
112
|
-
queue: queue.Queue,
|
113
|
-
) -> None:
|
114
|
-
task_id = task.name
|
115
|
-
next = task.next
|
116
|
-
input_states = task.input_states
|
117
|
-
active_tasks = self.active_tasks
|
118
|
-
tasks = self.tasks
|
119
|
-
depths = self.depths
|
120
|
-
depth = depths[task.name]
|
121
|
-
outputs = self.outputs
|
122
|
-
|
123
|
-
inputs: dict[str, NodeInput] = {}
|
124
|
-
input_messages = []
|
125
|
-
|
126
|
-
# Wait for inputs for this task to be set
|
127
|
-
for handle_name, input_state in input_states.items():
|
128
|
-
logger.info(f"Task {task_id} waiting for semaphore for {handle_name}")
|
129
|
-
input_state.semaphore.acquire()
|
130
|
-
logger.info(f"Task {task_id} acquired semaphore for {handle_name}")
|
131
|
-
|
132
|
-
# Set the outputs of predecessors as inputs of the current
|
133
|
-
output = input_state.get_state()
|
134
|
-
# If at least one of the inputs is termination,
|
135
|
-
# also terminate this task early and set its state to termination
|
136
|
-
if output.status == "Termination":
|
137
|
-
return
|
138
|
-
message = output.get_out()
|
139
|
-
|
140
|
-
inputs[handle_name] = message.value
|
141
|
-
input_messages.append(message)
|
142
|
-
|
143
|
-
start_time = datetime.datetime.now()
|
144
|
-
|
145
|
-
try:
|
146
|
-
if callable(task.value):
|
147
|
-
res = task.value(**inputs, _env=self.env)
|
148
|
-
else:
|
149
|
-
res = RunOutput(status="Success", output=task.value)
|
150
|
-
|
151
|
-
if res.status == "Success":
|
152
|
-
id = uuid.uuid4()
|
153
|
-
state = State.new(
|
154
|
-
Message(
|
155
|
-
id=id,
|
156
|
-
value=res.output, # type: ignore
|
157
|
-
start_time=start_time,
|
158
|
-
end_time=datetime.datetime.now(),
|
159
|
-
)
|
160
|
-
)
|
161
|
-
else:
|
162
|
-
assert res.status == "Termination"
|
163
|
-
state = State.termination()
|
164
|
-
|
165
|
-
is_termination = state.is_termination()
|
166
|
-
logger.info(f"Task {task_id} executed")
|
167
|
-
|
168
|
-
# remove the task from active tasks once it's done
|
169
|
-
if task_id in active_tasks:
|
170
|
-
active_tasks.remove(task_id)
|
171
|
-
|
172
|
-
if depth > 0:
|
173
|
-
# propagate reset once we enter the loop
|
174
|
-
# TODO: Implement this for cycles
|
175
|
-
raise NotImplementedError()
|
176
|
-
|
177
|
-
if depth == 10:
|
178
|
-
# TODO: Implement this for cycles
|
179
|
-
raise NotImplementedError()
|
180
|
-
|
181
|
-
if not next:
|
182
|
-
# if there are no next tasks, we can terminate the graph
|
183
|
-
outputs[task.name] = state.get_out()
|
184
|
-
|
185
|
-
# push next tasks to the channel only if
|
186
|
-
# the current task is not a termination
|
187
|
-
for next_task_name in next:
|
188
|
-
# we set the inputs of the next tasks
|
189
|
-
# to the outputs of the current task
|
190
|
-
next_task = tasks[next_task_name]
|
191
|
-
|
192
|
-
# in majority of cases there will be only one handle name
|
193
|
-
# however we need to handle the case when single output
|
194
|
-
# is mapped to multiple inputs on the next node
|
195
|
-
handle_names = []
|
196
|
-
for k, v in next_task.handles_mapping:
|
197
|
-
if v == task.name:
|
198
|
-
handle_names.append(k)
|
199
|
-
|
200
|
-
for handle_name in handle_names:
|
201
|
-
next_state = next_task.input_states[handle_name]
|
202
|
-
next_state.set_state_and_permits(state, 1)
|
203
|
-
|
204
|
-
# push next tasks to the channel only if the task is not active
|
205
|
-
# and current task is not a termination
|
206
|
-
if not (next_task_name in active_tasks) and not is_termination:
|
207
|
-
active_tasks.add(next_task_name)
|
208
|
-
queue.put(
|
209
|
-
ScheduledTask(
|
210
|
-
status="Task",
|
211
|
-
task_name=next_task_name,
|
212
|
-
)
|
213
|
-
)
|
214
|
-
|
215
|
-
# increment depth of the finished task
|
216
|
-
depths[task_id] = depth + 1
|
217
|
-
except NodeRunError as e:
|
218
|
-
logger.exception(f"Execution failed [id: {task_id}]")
|
219
|
-
|
220
|
-
error = Message(
|
221
|
-
id=uuid.uuid4(),
|
222
|
-
value=str(e),
|
223
|
-
start_time=start_time,
|
224
|
-
end_time=datetime.datetime.now(),
|
225
|
-
)
|
226
|
-
|
227
|
-
outputs[task.name] = error
|
228
|
-
|
229
|
-
# terminate entire graph by sending err task
|
230
|
-
queue.put(
|
231
|
-
ScheduledTask(
|
232
|
-
status="Err",
|
233
|
-
task_name=None,
|
234
|
-
)
|
235
|
-
)
|
236
|
-
|
237
|
-
except Exception:
|
238
|
-
logger.exception(f"Execution failed [id: {task_id}]")
|
239
|
-
error = Message(
|
240
|
-
id=uuid.uuid4(),
|
241
|
-
value="Unexpected server error",
|
242
|
-
start_time=start_time,
|
243
|
-
end_time=datetime.datetime.now(),
|
244
|
-
)
|
245
|
-
outputs[task.name] = error
|
246
|
-
queue.put(
|
247
|
-
ScheduledTask(
|
248
|
-
status="Err",
|
249
|
-
task_name=None,
|
250
|
-
)
|
251
|
-
)
|
252
|
-
|
253
|
-
def execute_task(
|
254
|
-
self,
|
255
|
-
task: Task,
|
256
|
-
queue: queue.Queue,
|
257
|
-
):
|
258
|
-
return self.thread_pool_executor.submit(
|
259
|
-
self.execute_task_inner,
|
260
|
-
task,
|
261
|
-
queue,
|
262
|
-
)
|
@@ -1,69 +0,0 @@
|
|
1
|
-
import threading
|
2
|
-
from dataclasses import dataclass
|
3
|
-
from typing import Union
|
4
|
-
|
5
|
-
from lmnr_engine.types import Message
|
6
|
-
|
7
|
-
|
8
|
-
@dataclass
|
9
|
-
class State:
|
10
|
-
status: str # "Success", "Empty", "Termination" # TODO: Turn into Enum
|
11
|
-
message: Union[Message, None]
|
12
|
-
|
13
|
-
@classmethod
|
14
|
-
def new(cls, val: Message) -> "State":
|
15
|
-
return cls(
|
16
|
-
status="Success",
|
17
|
-
message=val,
|
18
|
-
)
|
19
|
-
|
20
|
-
@classmethod
|
21
|
-
def empty(cls) -> "State":
|
22
|
-
return cls(
|
23
|
-
status="Empty",
|
24
|
-
message=Message.empty(),
|
25
|
-
)
|
26
|
-
|
27
|
-
@classmethod
|
28
|
-
def termination(cls) -> "State":
|
29
|
-
return cls(
|
30
|
-
status="Termination",
|
31
|
-
message=None,
|
32
|
-
)
|
33
|
-
|
34
|
-
def is_success(self) -> bool:
|
35
|
-
return self.status == "Success"
|
36
|
-
|
37
|
-
def is_termination(self) -> bool:
|
38
|
-
return self.status == "Termination"
|
39
|
-
|
40
|
-
def get_out(self) -> Message:
|
41
|
-
if self.message is None:
|
42
|
-
raise ValueError("Cannot get message from a termination state")
|
43
|
-
|
44
|
-
return self.message
|
45
|
-
|
46
|
-
|
47
|
-
@dataclass
|
48
|
-
class ExecState:
|
49
|
-
output: State
|
50
|
-
semaphore: threading.Semaphore
|
51
|
-
|
52
|
-
@classmethod
|
53
|
-
def new(cls) -> "ExecState":
|
54
|
-
return cls(
|
55
|
-
output=State.empty(),
|
56
|
-
semaphore=threading.Semaphore(0),
|
57
|
-
)
|
58
|
-
|
59
|
-
# Assume this is called by the caller who doesn't need to acquire semaphore
|
60
|
-
def set_state(self, output: State):
|
61
|
-
self.output = output
|
62
|
-
|
63
|
-
# Assume the caller is smart to call this after acquiring the semaphore
|
64
|
-
def get_state(self) -> State:
|
65
|
-
return self.output
|
66
|
-
|
67
|
-
def set_state_and_permits(self, output: State, permits: int):
|
68
|
-
self.output = output
|
69
|
-
self.semaphore.release(permits)
|
@@ -1,38 +0,0 @@
|
|
1
|
-
from typing import Callable, Union
|
2
|
-
|
3
|
-
from .action import RunOutput
|
4
|
-
from .state import ExecState
|
5
|
-
from lmnr_engine.types import NodeInput
|
6
|
-
|
7
|
-
|
8
|
-
class Task:
|
9
|
-
# unique identifier
|
10
|
-
name: str
|
11
|
-
# mapping from current node's handle name to previous node's unique name
|
12
|
-
# assumes nodes have only one output
|
13
|
-
handles_mapping: list[tuple[str, str]]
|
14
|
-
# Value or a function that returns a value
|
15
|
-
# Usually a function which waits for inputs from previous nodes
|
16
|
-
value: Union[NodeInput, Callable[..., RunOutput]] # TODO: Type this fully
|
17
|
-
# unique node names of previous nodes
|
18
|
-
prev: list[str]
|
19
|
-
# unique node names of next nodes
|
20
|
-
next: list[str]
|
21
|
-
input_states: dict[str, ExecState]
|
22
|
-
|
23
|
-
def __init__(
|
24
|
-
self,
|
25
|
-
name: str,
|
26
|
-
handles_mapping: list[tuple[str, str]],
|
27
|
-
value: Union[NodeInput, Callable[..., RunOutput]],
|
28
|
-
prev: list[str],
|
29
|
-
next: list[str],
|
30
|
-
) -> None:
|
31
|
-
self.name = name
|
32
|
-
self.handles_mapping = handles_mapping
|
33
|
-
self.value = value
|
34
|
-
self.prev = prev
|
35
|
-
self.next = next
|
36
|
-
self.input_states = {
|
37
|
-
handle_name: ExecState.new() for (handle_name, _) in self.handles_mapping
|
38
|
-
}
|
@@ -1 +0,0 @@
|
|
1
|
-
from .{{ cookiecutter.pipeline_dir_name }} import {{ cookiecutter.class_name }}
|
@@ -1,185 +0,0 @@
|
|
1
|
-
import requests
|
2
|
-
import json
|
3
|
-
|
4
|
-
from lmnr_engine.engine.action import NodeRunError, RunOutput
|
5
|
-
from lmnr_engine.types import ChatMessage, NodeInput
|
6
|
-
|
7
|
-
|
8
|
-
{% for task in cookiecutter._tasks.values() %}
|
9
|
-
{% if task.node_type == "LLM" %}
|
10
|
-
def {{task.function_name}}({{ task.handle_args }}, _env: dict[str, str]) -> RunOutput:
|
11
|
-
{% set chat_messages_found = false %}
|
12
|
-
{% for input_handle_name in task.input_handle_names %}
|
13
|
-
{% if input_handle_name == 'chat_messages' %}
|
14
|
-
{% set chat_messages_found = true %}
|
15
|
-
{% endif %}
|
16
|
-
{% endfor %}
|
17
|
-
|
18
|
-
{% if chat_messages_found %}
|
19
|
-
input_chat_messages = chat_messages
|
20
|
-
{% else %}
|
21
|
-
input_chat_messages = []
|
22
|
-
{% endif %}
|
23
|
-
|
24
|
-
rendered_prompt = """{{task.config.prompt}}"""
|
25
|
-
{% set prompt_variables = task.input_handle_names|reject("equalto", "chat_messages") %}
|
26
|
-
{% for prompt_variable in prompt_variables %}
|
27
|
-
# TODO: Fix this. Using double curly braces in quotes because normal double curly braces
|
28
|
-
# get replaced during rendering by Cookiecutter. This is a hacky solution.
|
29
|
-
rendered_prompt = rendered_prompt.replace("{{'{{'}}{{prompt_variable}}{{'}}'}}", {{prompt_variable}}) # type: ignore
|
30
|
-
{% endfor %}
|
31
|
-
|
32
|
-
{% if task.config.model_params == none %}
|
33
|
-
params = {}
|
34
|
-
{% else %}
|
35
|
-
params = json.loads(
|
36
|
-
"""{{task.config.model_params}}"""
|
37
|
-
)
|
38
|
-
{% endif %}
|
39
|
-
|
40
|
-
messages = [ChatMessage(role="system", content=rendered_prompt)]
|
41
|
-
messages.extend(input_chat_messages)
|
42
|
-
|
43
|
-
{% if task.config.provider == "openai" %}
|
44
|
-
message_jsons = [
|
45
|
-
{"role": message.role, "content": message.content} for message in messages
|
46
|
-
]
|
47
|
-
|
48
|
-
data = {
|
49
|
-
"model": "{{task.config.model}}",
|
50
|
-
"messages": message_jsons,
|
51
|
-
}
|
52
|
-
data.update(params)
|
53
|
-
|
54
|
-
headers = {
|
55
|
-
"Content-Type": "application/json",
|
56
|
-
"Authorization": f"Bearer {_env['OPENAI_API_KEY']}",
|
57
|
-
}
|
58
|
-
res = requests.post(
|
59
|
-
"https://api.openai.com/v1/chat/completions", json=data, headers=headers
|
60
|
-
)
|
61
|
-
|
62
|
-
if res.status_code != 200:
|
63
|
-
res_json = res.json()
|
64
|
-
raise NodeRunError(f'OpenAI completions request failed: {res_json["error"]["message"]}')
|
65
|
-
|
66
|
-
chat_completion = res.json()
|
67
|
-
|
68
|
-
completion_message = chat_completion["choices"][0]["message"]["content"]
|
69
|
-
|
70
|
-
meta_log = {}
|
71
|
-
meta_log["node_chunk_id"] = None # TODO: Add node chunk id
|
72
|
-
meta_log["model"] = "{{task.config.model}}"
|
73
|
-
meta_log["prompt"] = rendered_prompt
|
74
|
-
meta_log["input_message_count"] = len(messages)
|
75
|
-
meta_log["input_token_count"] = chat_completion["usage"]["prompt_tokens"]
|
76
|
-
meta_log["output_token_count"] = chat_completion["usage"]["completion_tokens"]
|
77
|
-
meta_log["total_token_count"] = (
|
78
|
-
chat_completion["usage"]["prompt_tokens"] + chat_completion["usage"]["completion_tokens"]
|
79
|
-
)
|
80
|
-
meta_log["approximate_cost"] = None # TODO: Add approximate cost
|
81
|
-
{% elif task.config.provider == "anthropic" %}
|
82
|
-
data = {
|
83
|
-
"model": "{{task.config.model}}",
|
84
|
-
"max_tokens": 4096,
|
85
|
-
}
|
86
|
-
data.update(params)
|
87
|
-
|
88
|
-
# TODO: Generate appropriate code based on this if-else block
|
89
|
-
if len(messages) == 1 and messages[0].role == "system":
|
90
|
-
messages[0].role = "user"
|
91
|
-
message_jsons = [
|
92
|
-
{"role": message.role, "content": message.content} for message in messages
|
93
|
-
]
|
94
|
-
data["messages"] = message_jsons
|
95
|
-
else:
|
96
|
-
data["system"] = messages[0].content
|
97
|
-
message_jsons = [
|
98
|
-
{"role": message.role, "content": message.content} for message in messages[1:]
|
99
|
-
]
|
100
|
-
data["messages"] = message_jsons
|
101
|
-
|
102
|
-
headers = {
|
103
|
-
"Content-Type": "application/json",
|
104
|
-
"X-Api-Key": _env['ANTHROPIC_API_KEY'],
|
105
|
-
"Anthropic-Version": "2023-06-01",
|
106
|
-
}
|
107
|
-
res = requests.post(
|
108
|
-
"https://api.anthropic.com/v1/messages", json=data, headers=headers
|
109
|
-
)
|
110
|
-
|
111
|
-
if res.status_code != 200:
|
112
|
-
raise NodeRunError(f"Anthropic message request failed: {res.text}")
|
113
|
-
|
114
|
-
chat_completion = res.json()
|
115
|
-
|
116
|
-
completion_message = chat_completion["content"][0]["text"]
|
117
|
-
|
118
|
-
meta_log = {}
|
119
|
-
meta_log["node_chunk_id"] = None # TODO: Add node chunk id
|
120
|
-
meta_log["model"] = "{{task.config.model}}"
|
121
|
-
meta_log["prompt"] = rendered_prompt
|
122
|
-
meta_log["input_message_count"] = len(messages)
|
123
|
-
meta_log["input_token_count"] = chat_completion["usage"]["input_tokens"]
|
124
|
-
meta_log["output_token_count"] = chat_completion["usage"]["output_tokens"]
|
125
|
-
meta_log["total_token_count"] = (
|
126
|
-
chat_completion["usage"]["input_tokens"] + chat_completion["usage"]["output_tokens"]
|
127
|
-
)
|
128
|
-
meta_log["approximate_cost"] = None # TODO: Add approximate cost
|
129
|
-
{% else %}
|
130
|
-
{% endif %}
|
131
|
-
|
132
|
-
return RunOutput(status="Success", output=completion_message)
|
133
|
-
|
134
|
-
|
135
|
-
{% elif task.node_type == "SemanticSearch" %}
|
136
|
-
def {{task.function_name}}(query: NodeInput, _env: dict[str, str]) -> RunOutput:
|
137
|
-
{% set datasources_length=task.config.datasource_ids|length %}
|
138
|
-
{% if datasources_length == 0 %}
|
139
|
-
raise NodeRunError("No datasources provided")
|
140
|
-
{% endif %}
|
141
|
-
|
142
|
-
headers = {
|
143
|
-
"Authorization": f"Bearer {_env['LMNR_PROJECT_API_KEY']}",
|
144
|
-
}
|
145
|
-
data = {
|
146
|
-
"query": query,
|
147
|
-
"limit": {{ task.config.limit }},
|
148
|
-
"threshold": {{ task.config.threshold }},
|
149
|
-
"datasourceIds": {{ task.config.datasource_ids_list }},
|
150
|
-
}
|
151
|
-
query_res = requests.post("https://api.lmnr.ai/v2/semantic-search", headers=headers, json=data)
|
152
|
-
if query_res.status_code != 200:
|
153
|
-
raise NodeRunError(f"Vector search request failed: {query_res.text}")
|
154
|
-
|
155
|
-
results = query_res.json()
|
156
|
-
|
157
|
-
def render_query_res_point(template: str, point: dict, relevance_index: int) -> str:
|
158
|
-
data = point["data"]
|
159
|
-
data["relevance_index"] = relevance_index
|
160
|
-
res = template
|
161
|
-
for key, value in data.items():
|
162
|
-
res = res.replace("{{'{{'}}" + key + "{{'}}'}}", str(value))
|
163
|
-
return res
|
164
|
-
|
165
|
-
rendered_res_points = [render_query_res_point("""{{task.config.template}}""", res_point, index + 1) for (index, res_point) in enumerate(results)]
|
166
|
-
output = "\n".join(rendered_res_points)
|
167
|
-
|
168
|
-
return RunOutput(status="Success", output=output)
|
169
|
-
|
170
|
-
|
171
|
-
{% elif task.node_type == "Output" %}
|
172
|
-
def {{task.function_name}}(output: NodeInput, _env: dict[str, str]) -> RunOutput:
|
173
|
-
return RunOutput(status="Success", output=output)
|
174
|
-
|
175
|
-
|
176
|
-
{% elif task.node_type == "Input" %}
|
177
|
-
{# Do nothing for Input tasks #}
|
178
|
-
{% else %}
|
179
|
-
def {{task.function_name}}(output: NodeInput, _env: dict[str, str]) -> RunOutput:
|
180
|
-
return RunOutput(status="Success", output=output)
|
181
|
-
|
182
|
-
|
183
|
-
{% endif %}
|
184
|
-
{% endfor %}
|
185
|
-
# Other functions can be added here
|
@@ -1,87 +0,0 @@
|
|
1
|
-
from concurrent.futures import ThreadPoolExecutor
|
2
|
-
from dataclasses import dataclass
|
3
|
-
import logging
|
4
|
-
from typing import Optional, Union
|
5
|
-
|
6
|
-
from lmnr.types import ChatMessage
|
7
|
-
from lmnr_engine.engine import Engine
|
8
|
-
{% set function_names = cookiecutter._tasks.values() | selectattr('node_type', '!=', 'Input') | map(attribute='function_name') | join(', ') %}
|
9
|
-
from .nodes.functions import {{ function_names }}
|
10
|
-
from lmnr_engine.engine.task import Task
|
11
|
-
|
12
|
-
|
13
|
-
logger = logging.getLogger(__name__)
|
14
|
-
|
15
|
-
|
16
|
-
class PipelineRunnerError(Exception):
|
17
|
-
pass
|
18
|
-
|
19
|
-
|
20
|
-
@dataclass
|
21
|
-
class PipelineRunOutput:
|
22
|
-
value: Union[str, list[ChatMessage]]
|
23
|
-
|
24
|
-
|
25
|
-
# This class is not imported in other files and can be renamed to desired name
|
26
|
-
class {{ cookiecutter.class_name }}:
|
27
|
-
thread_pool_executor: ThreadPoolExecutor
|
28
|
-
|
29
|
-
def __init__(
|
30
|
-
self, thread_pool_executor: Optional[ThreadPoolExecutor] = None
|
31
|
-
) -> None:
|
32
|
-
# Set max workers to hard-coded value for now
|
33
|
-
self.thread_pool_executor = (
|
34
|
-
ThreadPoolExecutor(max_workers=10)
|
35
|
-
if thread_pool_executor is None
|
36
|
-
else thread_pool_executor
|
37
|
-
)
|
38
|
-
|
39
|
-
def run(
|
40
|
-
self,
|
41
|
-
inputs: dict[str, Union[str, list]],
|
42
|
-
env: dict[str, str] = {},
|
43
|
-
) -> dict[str, PipelineRunOutput]:
|
44
|
-
"""
|
45
|
-
Run the pipeline with the given graph
|
46
|
-
|
47
|
-
Raises:
|
48
|
-
PipelineRunnerError: if there is an error running the pipeline
|
49
|
-
"""
|
50
|
-
logger.info("Running pipeline {{ cookiecutter.pipeline_name }}, pipeline_version: {{ cookiecutter.pipeline_version_name }}")
|
51
|
-
|
52
|
-
run_inputs = {}
|
53
|
-
for inp_name, inp in inputs.items():
|
54
|
-
if isinstance(inp, str):
|
55
|
-
run_inputs[inp_name] = inp
|
56
|
-
else:
|
57
|
-
assert isinstance(inp, list), f"Invalid input type: {type(inp)}"
|
58
|
-
run_inputs[inp_name] = [ChatMessage.model_validate(msg) for msg in inp]
|
59
|
-
|
60
|
-
tasks = []
|
61
|
-
{% for task in cookiecutter._tasks.values() %}
|
62
|
-
tasks.append(
|
63
|
-
Task(
|
64
|
-
name="{{ task.name }}",
|
65
|
-
value={{ "''" if task.node_type == "Input" else task.function_name }},
|
66
|
-
handles_mapping={{ task.handles_mapping }},
|
67
|
-
prev=[
|
68
|
-
{% for prev in task.prev %}
|
69
|
-
"{{ prev }}",
|
70
|
-
{% endfor %}
|
71
|
-
],
|
72
|
-
next=[
|
73
|
-
{% for next in task.next %}
|
74
|
-
"{{ next }}",
|
75
|
-
{% endfor %}
|
76
|
-
],
|
77
|
-
)
|
78
|
-
)
|
79
|
-
{% endfor %}
|
80
|
-
engine = Engine.with_tasks(tasks, self.thread_pool_executor, env=env)
|
81
|
-
|
82
|
-
# TODO: Raise PipelineRunnerError with node_errors
|
83
|
-
run_res = engine.run(run_inputs)
|
84
|
-
return {
|
85
|
-
name: PipelineRunOutput(value=output.value)
|
86
|
-
for name, output in run_res.items()
|
87
|
-
}
|
@@ -1,35 +0,0 @@
|
|
1
|
-
from dataclasses import dataclass
|
2
|
-
from typing import Union
|
3
|
-
import uuid
|
4
|
-
import datetime
|
5
|
-
from lmnr.types import NodeInput, ChatMessage
|
6
|
-
|
7
|
-
|
8
|
-
@dataclass
|
9
|
-
class Message:
|
10
|
-
id: uuid.UUID
|
11
|
-
# output value of producing node in form of NodeInput
|
12
|
-
# for the following consumer
|
13
|
-
value: NodeInput
|
14
|
-
# all input messages to this node; accumulates previous messages too
|
15
|
-
# input_messages: list["Message"]
|
16
|
-
start_time: datetime.datetime
|
17
|
-
end_time: datetime.datetime
|
18
|
-
# node_id: uuid.UUID
|
19
|
-
# node_name: str
|
20
|
-
# node_type: str
|
21
|
-
# all node per-run metadata that needs to be logged at the end of execution
|
22
|
-
# meta_log: MetaLog | None
|
23
|
-
|
24
|
-
@classmethod
|
25
|
-
def empty(cls) -> "Message":
|
26
|
-
return cls(
|
27
|
-
id=uuid.uuid4(),
|
28
|
-
value="",
|
29
|
-
# input_messages=[],
|
30
|
-
start_time=datetime.datetime.now(),
|
31
|
-
end_time=datetime.datetime.now(),
|
32
|
-
# node_id=uuid.uuid4(),
|
33
|
-
# node_name="",
|
34
|
-
# node_type="",
|
35
|
-
)
|
lmnr-0.2.6.dist-info/RECORD
DELETED
@@ -1,32 +0,0 @@
|
|
1
|
-
lmnr/__init__.py,sha256=NWHDZ-KAl3pQGDnKUbBbZaW4es-0-9Xt6gP-UrjyuEQ,207
|
2
|
-
lmnr/cli/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
3
|
-
lmnr/cli/__main__.py,sha256=8hDtWlaFZK24KhfNq_ZKgtXqYHsDQDetukOCMlsbW0Q,59
|
4
|
-
lmnr/cli/cli.py,sha256=pzr5LUILi7TcaJIkC-CzmT7RG7-HWApQmUpgK9bc7mI,2847
|
5
|
-
lmnr/cli/cookiecutter.json,sha256=PeiMMzCPzDhsapqYoAceYGPI5lOUNimvFzh5KeQv5QE,359
|
6
|
-
lmnr/cli/parser/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
7
|
-
lmnr/cli/parser/nodes/__init__.py,sha256=BNbbfn0WwbFDA6TNhLOaT_Ji69rCL5voUibqMD7Knng,1163
|
8
|
-
lmnr/cli/parser/nodes/input.py,sha256=Xwktcih7Mezqv4cEejfPkpG8uJxDsbqRytBvKmlJDYE,578
|
9
|
-
lmnr/cli/parser/nodes/llm.py,sha256=iQWYFnQi5PcQD9WJpTSHbSzClM6s0wBOoEqyN5c4yQo,1674
|
10
|
-
lmnr/cli/parser/nodes/output.py,sha256=1XBppSscxM01kfZhE9oOh2GgdCVzyPVe2RAxLI5HmUc,665
|
11
|
-
lmnr/cli/parser/nodes/semantic_search.py,sha256=o_XCR7BShAq8VGeKjPTwL6MxLdB07XHSd5CE71sFFiY,2105
|
12
|
-
lmnr/cli/parser/nodes/types.py,sha256=c7jNaR7YlZUkxB9OosAkFH4o6ZPga0Bec1WtOxq9fGs,3505
|
13
|
-
lmnr/cli/parser/parser.py,sha256=UtuupKj2Dh-47HVcYU4PI2s4Erh1gTjKiuGCcc-nkbM,2163
|
14
|
-
lmnr/cli/parser/utils.py,sha256=wVaqHVOR9VXl8Og9nkVyCVgHIcgbtYGkDOEGPtmjZ8g,715
|
15
|
-
lmnr/cli/{{cookiecutter.lmnr_pipelines_dir_name}}/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
16
|
-
lmnr/cli/{{cookiecutter.lmnr_pipelines_dir_name}}/engine/__init__.py,sha256=pLVZqvDnNf9foGR-HXnX2F7WC2TWmyCTNcUctG8SXAI,27
|
17
|
-
lmnr/cli/{{cookiecutter.lmnr_pipelines_dir_name}}/engine/action.py,sha256=mZMQwwPV5LtSfwdwQ7HefI3ttvwuokp4mhVI_Xn1Zck,274
|
18
|
-
lmnr/cli/{{cookiecutter.lmnr_pipelines_dir_name}}/engine/engine.py,sha256=TKmgfXbs_BiuMpzHuPuSfq1mX3UEnQFnpKgU2NsYkB4,8397
|
19
|
-
lmnr/cli/{{cookiecutter.lmnr_pipelines_dir_name}}/engine/state.py,sha256=wTx7jAv7b63-8k34cYfQp_DJxhCCOYT_qRHkmnZfnc0,1686
|
20
|
-
lmnr/cli/{{cookiecutter.lmnr_pipelines_dir_name}}/engine/task.py,sha256=ware5VIrZvluHH3mpH6h7G0YDk5L0buSQ7s09za4Fro,1200
|
21
|
-
lmnr/cli/{{cookiecutter.lmnr_pipelines_dir_name}}/pipelines/{{cookiecutter.pipeline_dir_name}}/__init__.py,sha256=bsfbNUBYtKv37qzc_GLhSAzBam2lnowP_dlr8pubhcg,80
|
22
|
-
lmnr/cli/{{cookiecutter.lmnr_pipelines_dir_name}}/pipelines/{{cookiecutter.pipeline_dir_name}}/nodes/functions.py,sha256=HwK6gKngZi1AhEyu9BVtE5IfD4NScRCdFLXV8uiBD34,6578
|
23
|
-
lmnr/cli/{{cookiecutter.lmnr_pipelines_dir_name}}/pipelines/{{cookiecutter.pipeline_dir_name}}/{{cookiecutter.pipeline_dir_name}}.py,sha256=WG-ZMofPpGXCx5jdWVry3_XBzcKjqn8ZycFSiWEOBPg,2858
|
24
|
-
lmnr/cli/{{cookiecutter.lmnr_pipelines_dir_name}}/types.py,sha256=iWuflMV7TiaBPs6-B-BlrovvWpZgHGGHK0v8rSqER7A,997
|
25
|
-
lmnr/sdk/endpoint.py,sha256=0HjcxMUcJz-klFZO2f5xtTaoLjcaEb8vrJ_YldTWUc8,7467
|
26
|
-
lmnr/sdk/remote_debugger.py,sha256=vCpMz7y3uboOi81qEwr8z3fhQ2H1y2YtJAxXVtb6uCA,5141
|
27
|
-
lmnr/types.py,sha256=IcoKNL1KJ-GIeunrt5fYuB_XhsBrtYZ9d1ShFJqrsUc,2004
|
28
|
-
lmnr-0.2.6.dist-info/LICENSE,sha256=67b_wJHVV1CBaWkrKFWU1wyqTPSdzH77Ls-59631COg,10411
|
29
|
-
lmnr-0.2.6.dist-info/METADATA,sha256=wipVETWwLYjuhdrOpkgUA7iE-kpj5lGph4X7zE0tLvQ,5428
|
30
|
-
lmnr-0.2.6.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
|
31
|
-
lmnr-0.2.6.dist-info/entry_points.txt,sha256=Qg7ZRax4k-rcQsZ26XRYQ8YFSBiyY2PNxYfq4a6PYXI,41
|
32
|
-
lmnr-0.2.6.dist-info/RECORD,,
|
File without changes
|
File without changes
|
File without changes
|