aisexpr 0.9.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.
@@ -0,0 +1,24 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ build/
6
+ dist/
7
+
8
+ # Virtual environment (uv)
9
+ .venv/
10
+
11
+ # Test and type-check caches
12
+ .pytest_cache/
13
+ .coverage
14
+ htmlcov/
15
+ .mypy_cache/
16
+ .ruff_cache/
17
+
18
+ # JavaScript
19
+ node_modules/
20
+
21
+ # Editors and OS
22
+ .vscode/
23
+ .idea/
24
+ .DS_Store
aisexpr-0.9.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AutomationEdge Technologies Pvt. Ltd.
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.
aisexpr-0.9.0/PKG-INFO ADDED
@@ -0,0 +1,225 @@
1
+ Metadata-Version: 2.5
2
+ Name: aisexpr
3
+ Version: 0.9.0
4
+ Summary: Parser and evaluator for AiStudio expressions (conditions) used in AgentFlow; a rewrite of ddcompiler
5
+ Project-URL: Repository, https://bitbucket.org/yovyom/aisexpr
6
+ Author: Yogesh Ketkar
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Keywords: agentflow,condition,evaluator,expression,parser
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Software Development :: Libraries
13
+ Requires-Python: >=3.10
14
+ Description-Content-Type: text/markdown
15
+
16
+ # aisexpr
17
+
18
+ **AiStudio expressions**: the condition language used by AgentFlow, for
19
+ example
20
+
21
+ ```
22
+ ${flow.order.status} == "shipped" and ${flow.order.total} > 100
23
+ contains(${user.roles}, "admin") and len(${user.roles}) > 1
24
+ ${message.items}[0].qty >= 2 and ${message.items}[0].sku != "B2"
25
+ exists(${flow.coupon}) and ${flow.coupon.discount} > 10 or contains(lower(${conv.__utterance__}), "refund")
26
+ ```
27
+
28
+ aisexpr parses a condition once, tells you what variables it uses, and
29
+ evaluates it against your data. It is a recursive descent parser with no dependencies, and replaces `ddcompiler`.
30
+
31
+ ## Usage
32
+
33
+ Two steps: create an `AISExpression`, which parses it, then `evaluate()` it
34
+ with the variables as nested dicts. `${flow.order.status}` is read from
35
+ `data["flow"]["order"]["status"]`.
36
+
37
+ You always have to pass `variable_prefixes`: the names a variable may start
38
+ with, for example `["flow"]` for `${flow.order.status}`. There is no default,
39
+ since which prefixes are allowed depends on where the expression is used (see
40
+ [Variable prefixes](#variable-prefixes)).
41
+
42
+ ### Example 1: one dict
43
+
44
+ ```python
45
+ from aisexpr import AISExpression
46
+
47
+ expr = AISExpression(
48
+ '${flow.order.status} == "shipped" and ${flow.order.total} > 100',
49
+ variable_prefixes=["flow"],
50
+ )
51
+
52
+ expr.variables
53
+ # frozenset({'flow.order.status', 'flow.order.total'})
54
+
55
+ expr.evaluate({"flow": {"order": {"status": "shipped", "total": 150}}})
56
+ # True
57
+
58
+ expr.evaluate({"flow": {"order": {"status": "pending", "total": 150}}})
59
+ # False
60
+ ```
61
+
62
+ ### Example 2: two dicts
63
+
64
+ Each variable prefix (`flow`, `user`, `conv`, ...) is a top-level key of the
65
+ data, so an expression that uses two prefixes needs both in
66
+ `variable_prefixes` and both dicts in the data:
67
+
68
+ ```python
69
+ from aisexpr import AISExpression
70
+
71
+ expr = AISExpression(
72
+ 'contains(${user.roles}, "admin") or ${flow.retries} < 3',
73
+ variable_prefixes=["user", "flow"],
74
+ )
75
+
76
+ data = {
77
+ "user": {"name": "Ann", "roles": ["dev"]},
78
+ "flow": {"retries": 1},
79
+ }
80
+ expr.evaluate(data)
81
+ # True: not an admin, but retries < 3
82
+
83
+ expr.evaluate({"user": {"roles": ["dev"]}, "flow": {"retries": 5}})
84
+ # False
85
+ ```
86
+
87
+ ### Example 3: Python objects, converted to dicts
88
+
89
+ `evaluate()` only reads dicts, lists, strings, numbers, booleans and `None`;
90
+ it never reads object attributes. Convert objects to dicts first, which is
91
+ what AgentFlow does before evaluating. Nested objects become nested dicts, so
92
+ `${flow.x.y.c}` reads `x.y.c`:
93
+
94
+ ```python
95
+ from dataclasses import asdict, dataclass
96
+
97
+ from aisexpr import AISExpression
98
+
99
+
100
+ @dataclass
101
+ class Y:
102
+ c: str
103
+ d: list[str]
104
+
105
+
106
+ @dataclass
107
+ class X:
108
+ a: int
109
+ b: str
110
+ y: Y
111
+
112
+
113
+ x = X(a=5, b="gold", y=Y(c="Pune", d=["vip", "gift"]))
114
+
115
+ expr = AISExpression(
116
+ '${flow.x.a} > 3 and ${flow.x.b} == "gold" '
117
+ 'and ${flow.x.y.c} == "Pune" and contains(${flow.x.y.d}, "vip")',
118
+ variable_prefixes=["flow"],
119
+ )
120
+
121
+ asdict(x)
122
+ # {'a': 5, 'b': 'gold', 'y': {'c': 'Pune', 'd': ['vip', 'gift']}}
123
+
124
+ expr.evaluate({"flow": {"x": asdict(x)}})
125
+ # True
126
+
127
+ expr.evaluate({"flow": {"x": x}}) # the object itself, not converted
128
+ # EvaluationError: Variable '${flow.x.a}' not found at position 0
129
+ ```
130
+
131
+ `asdict()` works for dataclasses. For a Pydantic model use `x.model_dump()`.
132
+
133
+ Parse once, evaluate many times: in AgentFlow, create the `AISExpression`
134
+ when a condition is saved, so mistakes are reported to the user straight
135
+ away, and evaluate the same `expr` every time the condition runs. For a
136
+ one-off check, do both in one call:
137
+
138
+ ```python
139
+ AISExpression('${flow.retries} < 3', variable_prefixes=["flow"]).evaluate(
140
+ {"flow": {"retries": 1}}
141
+ )
142
+ # True
143
+ ```
144
+
145
+ ## Errors
146
+
147
+ Every error is an `AISExprError` with a `message` and the `pos`
148
+ (0-based) in the expression where it was found:
149
+
150
+ | Error | Raised by | When |
151
+ |---|---|---|
152
+ | `LexerError` | `AISExpression(...)` | Invalid characters or names, e.g. `${flow.x} = 1`, `${foo.x}` |
153
+ | `ParserError` | `AISExpression(...)` | Tokens in the wrong order, e.g. `${flow.x} ==` |
154
+ | `EvaluationError` | `evaluate()` | A missing variable, or values of the wrong type |
155
+
156
+ ```python
157
+ from aisexpr import AISExpression, AISExprError
158
+
159
+ try:
160
+ ok = AISExpression(text, variable_prefixes=["flow"]).evaluate(data)
161
+ except AISExprError as e:
162
+ print(e.message, e.pos)
163
+ ```
164
+
165
+ ```python
166
+ FLOW = ["flow"]
167
+
168
+ AISExpression("${flow.x} ==", variable_prefixes=FLOW)
169
+ # ParserError: Expected a value, got end of expression at position 12
170
+
171
+ AISExpression("${foo.x} == 1", variable_prefixes=FLOW)
172
+ # LexerError: Unknown variable prefix 'foo' in 'foo.x', allowed: flow at position 0
173
+
174
+ AISExpression("${flow.x} == 1", variable_prefixes=FLOW).evaluate({"flow": {}})
175
+ # EvaluationError: Variable '${flow.x}' not found at position 0
176
+
177
+ AISExpression("${flow.x} == 1", variable_prefixes=FLOW).evaluate({"flow": {"x": "1"}})
178
+ # EvaluationError: Can't compare string with number at position 10
179
+ ```
180
+
181
+ ## Variable prefixes
182
+
183
+ A variable must start with one of the prefixes passed in
184
+ `variable_prefixes`, which is required. A variable with any other prefix is a
185
+ `LexerError`. An empty list allows no variables at all.
186
+
187
+ The list depends on where the expression is used. In AgentFlow, for example,
188
+ a node's condition may read `${message.*}` and `${result.*}`, while a dialog
189
+ element may not read `${result.*}`. So the caller decides each time, and a
190
+ forgotten list is an error rather than a silent "allow everything":
191
+
192
+ ```python
193
+ from aisexpr import AISExpression
194
+
195
+ expr = AISExpression("${tool.x} == 1", variable_prefixes=["tool"])
196
+
197
+ AISExpression("${flow.x} == 1")
198
+ # TypeError: AISExpression.__init__() missing 1 required keyword-only argument: 'variable_prefixes'
199
+ ```
200
+
201
+ `DEFAULT_VARIABLE_PREFIXES` (`user`, `conv`, `dialog`, `wf`, `flow`,
202
+ `message` and `result`) is no longer used by the lexer. It is kept for now,
203
+ for code that builds its own list from it.
204
+
205
+ ## In the browser
206
+
207
+ `javascript/aisexpr.js` checks expressions in the UI without evaluating
208
+ them. It accepts and rejects exactly what the Python parser does, with the
209
+ same messages and positions. `variablePrefixes` is required here too:
210
+
211
+ ```js
212
+ import { validateExpression } from "./aisexpr.js";
213
+
214
+ validateExpression('${flow.x} == "yes"', { variablePrefixes: ["flow"] });
215
+ // { valid: true, variables: ["flow.x"] }
216
+ ```
217
+
218
+ See `javascript/usage.js` for more.
219
+
220
+ ## Development
221
+
222
+ ```sh
223
+ uv run pytest # all tests, including the Python/JS comparison (needs node)
224
+ uv run pytest -s # show print() output
225
+ ```
@@ -0,0 +1,210 @@
1
+ # aisexpr
2
+
3
+ **AiStudio expressions**: the condition language used by AgentFlow, for
4
+ example
5
+
6
+ ```
7
+ ${flow.order.status} == "shipped" and ${flow.order.total} > 100
8
+ contains(${user.roles}, "admin") and len(${user.roles}) > 1
9
+ ${message.items}[0].qty >= 2 and ${message.items}[0].sku != "B2"
10
+ exists(${flow.coupon}) and ${flow.coupon.discount} > 10 or contains(lower(${conv.__utterance__}), "refund")
11
+ ```
12
+
13
+ aisexpr parses a condition once, tells you what variables it uses, and
14
+ evaluates it against your data. It is a recursive descent parser with no dependencies, and replaces `ddcompiler`.
15
+
16
+ ## Usage
17
+
18
+ Two steps: create an `AISExpression`, which parses it, then `evaluate()` it
19
+ with the variables as nested dicts. `${flow.order.status}` is read from
20
+ `data["flow"]["order"]["status"]`.
21
+
22
+ You always have to pass `variable_prefixes`: the names a variable may start
23
+ with, for example `["flow"]` for `${flow.order.status}`. There is no default,
24
+ since which prefixes are allowed depends on where the expression is used (see
25
+ [Variable prefixes](#variable-prefixes)).
26
+
27
+ ### Example 1: one dict
28
+
29
+ ```python
30
+ from aisexpr import AISExpression
31
+
32
+ expr = AISExpression(
33
+ '${flow.order.status} == "shipped" and ${flow.order.total} > 100',
34
+ variable_prefixes=["flow"],
35
+ )
36
+
37
+ expr.variables
38
+ # frozenset({'flow.order.status', 'flow.order.total'})
39
+
40
+ expr.evaluate({"flow": {"order": {"status": "shipped", "total": 150}}})
41
+ # True
42
+
43
+ expr.evaluate({"flow": {"order": {"status": "pending", "total": 150}}})
44
+ # False
45
+ ```
46
+
47
+ ### Example 2: two dicts
48
+
49
+ Each variable prefix (`flow`, `user`, `conv`, ...) is a top-level key of the
50
+ data, so an expression that uses two prefixes needs both in
51
+ `variable_prefixes` and both dicts in the data:
52
+
53
+ ```python
54
+ from aisexpr import AISExpression
55
+
56
+ expr = AISExpression(
57
+ 'contains(${user.roles}, "admin") or ${flow.retries} < 3',
58
+ variable_prefixes=["user", "flow"],
59
+ )
60
+
61
+ data = {
62
+ "user": {"name": "Ann", "roles": ["dev"]},
63
+ "flow": {"retries": 1},
64
+ }
65
+ expr.evaluate(data)
66
+ # True: not an admin, but retries < 3
67
+
68
+ expr.evaluate({"user": {"roles": ["dev"]}, "flow": {"retries": 5}})
69
+ # False
70
+ ```
71
+
72
+ ### Example 3: Python objects, converted to dicts
73
+
74
+ `evaluate()` only reads dicts, lists, strings, numbers, booleans and `None`;
75
+ it never reads object attributes. Convert objects to dicts first, which is
76
+ what AgentFlow does before evaluating. Nested objects become nested dicts, so
77
+ `${flow.x.y.c}` reads `x.y.c`:
78
+
79
+ ```python
80
+ from dataclasses import asdict, dataclass
81
+
82
+ from aisexpr import AISExpression
83
+
84
+
85
+ @dataclass
86
+ class Y:
87
+ c: str
88
+ d: list[str]
89
+
90
+
91
+ @dataclass
92
+ class X:
93
+ a: int
94
+ b: str
95
+ y: Y
96
+
97
+
98
+ x = X(a=5, b="gold", y=Y(c="Pune", d=["vip", "gift"]))
99
+
100
+ expr = AISExpression(
101
+ '${flow.x.a} > 3 and ${flow.x.b} == "gold" '
102
+ 'and ${flow.x.y.c} == "Pune" and contains(${flow.x.y.d}, "vip")',
103
+ variable_prefixes=["flow"],
104
+ )
105
+
106
+ asdict(x)
107
+ # {'a': 5, 'b': 'gold', 'y': {'c': 'Pune', 'd': ['vip', 'gift']}}
108
+
109
+ expr.evaluate({"flow": {"x": asdict(x)}})
110
+ # True
111
+
112
+ expr.evaluate({"flow": {"x": x}}) # the object itself, not converted
113
+ # EvaluationError: Variable '${flow.x.a}' not found at position 0
114
+ ```
115
+
116
+ `asdict()` works for dataclasses. For a Pydantic model use `x.model_dump()`.
117
+
118
+ Parse once, evaluate many times: in AgentFlow, create the `AISExpression`
119
+ when a condition is saved, so mistakes are reported to the user straight
120
+ away, and evaluate the same `expr` every time the condition runs. For a
121
+ one-off check, do both in one call:
122
+
123
+ ```python
124
+ AISExpression('${flow.retries} < 3', variable_prefixes=["flow"]).evaluate(
125
+ {"flow": {"retries": 1}}
126
+ )
127
+ # True
128
+ ```
129
+
130
+ ## Errors
131
+
132
+ Every error is an `AISExprError` with a `message` and the `pos`
133
+ (0-based) in the expression where it was found:
134
+
135
+ | Error | Raised by | When |
136
+ |---|---|---|
137
+ | `LexerError` | `AISExpression(...)` | Invalid characters or names, e.g. `${flow.x} = 1`, `${foo.x}` |
138
+ | `ParserError` | `AISExpression(...)` | Tokens in the wrong order, e.g. `${flow.x} ==` |
139
+ | `EvaluationError` | `evaluate()` | A missing variable, or values of the wrong type |
140
+
141
+ ```python
142
+ from aisexpr import AISExpression, AISExprError
143
+
144
+ try:
145
+ ok = AISExpression(text, variable_prefixes=["flow"]).evaluate(data)
146
+ except AISExprError as e:
147
+ print(e.message, e.pos)
148
+ ```
149
+
150
+ ```python
151
+ FLOW = ["flow"]
152
+
153
+ AISExpression("${flow.x} ==", variable_prefixes=FLOW)
154
+ # ParserError: Expected a value, got end of expression at position 12
155
+
156
+ AISExpression("${foo.x} == 1", variable_prefixes=FLOW)
157
+ # LexerError: Unknown variable prefix 'foo' in 'foo.x', allowed: flow at position 0
158
+
159
+ AISExpression("${flow.x} == 1", variable_prefixes=FLOW).evaluate({"flow": {}})
160
+ # EvaluationError: Variable '${flow.x}' not found at position 0
161
+
162
+ AISExpression("${flow.x} == 1", variable_prefixes=FLOW).evaluate({"flow": {"x": "1"}})
163
+ # EvaluationError: Can't compare string with number at position 10
164
+ ```
165
+
166
+ ## Variable prefixes
167
+
168
+ A variable must start with one of the prefixes passed in
169
+ `variable_prefixes`, which is required. A variable with any other prefix is a
170
+ `LexerError`. An empty list allows no variables at all.
171
+
172
+ The list depends on where the expression is used. In AgentFlow, for example,
173
+ a node's condition may read `${message.*}` and `${result.*}`, while a dialog
174
+ element may not read `${result.*}`. So the caller decides each time, and a
175
+ forgotten list is an error rather than a silent "allow everything":
176
+
177
+ ```python
178
+ from aisexpr import AISExpression
179
+
180
+ expr = AISExpression("${tool.x} == 1", variable_prefixes=["tool"])
181
+
182
+ AISExpression("${flow.x} == 1")
183
+ # TypeError: AISExpression.__init__() missing 1 required keyword-only argument: 'variable_prefixes'
184
+ ```
185
+
186
+ `DEFAULT_VARIABLE_PREFIXES` (`user`, `conv`, `dialog`, `wf`, `flow`,
187
+ `message` and `result`) is no longer used by the lexer. It is kept for now,
188
+ for code that builds its own list from it.
189
+
190
+ ## In the browser
191
+
192
+ `javascript/aisexpr.js` checks expressions in the UI without evaluating
193
+ them. It accepts and rejects exactly what the Python parser does, with the
194
+ same messages and positions. `variablePrefixes` is required here too:
195
+
196
+ ```js
197
+ import { validateExpression } from "./aisexpr.js";
198
+
199
+ validateExpression('${flow.x} == "yes"', { variablePrefixes: ["flow"] });
200
+ // { valid: true, variables: ["flow.x"] }
201
+ ```
202
+
203
+ See `javascript/usage.js` for more.
204
+
205
+ ## Development
206
+
207
+ ```sh
208
+ uv run pytest # all tests, including the Python/JS comparison (needs node)
209
+ uv run pytest -s # show print() output
210
+ ```
@@ -0,0 +1,20 @@
1
+ __version__ = "0.9.0"
2
+
3
+ from .errors import AISExprError, EvaluationError, LexerError, ParserError
4
+ from .lexer import DEFAULT_VARIABLE_PREFIXES, Lexer
5
+ from .expression import AISExpression
6
+ from .parser import Parser
7
+ from .tokens import Token, TokenType
8
+
9
+ __all__ = [
10
+ "AISExprError",
11
+ "LexerError",
12
+ "ParserError",
13
+ "EvaluationError",
14
+ "Token",
15
+ "TokenType",
16
+ "Lexer",
17
+ "DEFAULT_VARIABLE_PREFIXES",
18
+ "Parser",
19
+ "AISExpression",
20
+ ]
@@ -0,0 +1,38 @@
1
+ class AISExprError(Exception):
2
+ """Base class for every error aisexpr raises.
3
+
4
+ Catch this to handle any problem with an expression:
5
+ try:
6
+ ...
7
+ except AISExprError as e:
8
+ print(e.message, e.pos)
9
+ """
10
+
11
+ def __init__(self, message: str, pos: int | None = None) -> None:
12
+ self.message = message
13
+ # Position (0-based) in the expression where the error was found, or
14
+ # None when there isn't one (e.g. a missing variable at evaluation).
15
+ self.pos = pos
16
+ if pos is None:
17
+ super().__init__(message)
18
+ else:
19
+ super().__init__(f"{message} at position {pos}")
20
+
21
+
22
+ class LexerError(AISExprError):
23
+ """Invalid characters or tokens, e.g. an unknown keyword or an unclosed string."""
24
+
25
+
26
+ class ParserError(AISExprError):
27
+ """Valid tokens in an invalid order, e.g. ${flow.x} == 1 and ) or True."""
28
+
29
+
30
+ class EvaluationError(AISExprError):
31
+ """Errors found while evaluating, e.g. an index out of range, a type
32
+ mismatch, or a missing variable.
33
+
34
+ For example, the expression ${flow.x.y} == "abc" evaluated with this data,
35
+ which has no key y under x:
36
+ {"flow": {"x": {"z": "abc"}}}
37
+ raises EvaluationError: Variable '${flow.x.y}' not found at position 0
38
+ """