daaf 0.1.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.
- daaf-0.1.0/.gitignore +4 -0
- daaf-0.1.0/LICENSE +176 -0
- daaf-0.1.0/PKG-INFO +117 -0
- daaf-0.1.0/README.md +105 -0
- daaf-0.1.0/daaf.py +134 -0
- daaf-0.1.0/pyproject.toml +19 -0
- daaf-0.1.0/test_daaf.py +110 -0
daaf-0.1.0/.gitignore
ADDED
daaf-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
daaf-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: daaf
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Decision-as-a-function: a typed Python function with a docstring, answered by Laya
|
|
5
|
+
Project-URL: Homepage, https://github.com/LilHenri75/daaf
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Keywords: classification,decision,decorator,laya,llm
|
|
9
|
+
Requires-Python: >=3.10
|
|
10
|
+
Requires-Dist: laya>=0.3.27
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
|
|
13
|
+
# daaf — decision-as-a-function
|
|
14
|
+
|
|
15
|
+
Write a typed Python function with a docstring. [Laya](https://github.com/NandhaKishorM/laya) answers it, locally, in any of 100+ languages, in tens of milliseconds.
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
from enum import Enum, IntEnum
|
|
19
|
+
from typing import Literal
|
|
20
|
+
from daaf import decide
|
|
21
|
+
|
|
22
|
+
@decide
|
|
23
|
+
def is_scam(message: str) -> bool:
|
|
24
|
+
"""Is this message a scam trying to get money or credentials?"""
|
|
25
|
+
|
|
26
|
+
class Dept(Enum):
|
|
27
|
+
billing = "invoices, payments, refunds" # the value describes the option to the model
|
|
28
|
+
support = "bugs, outages, login problems"
|
|
29
|
+
sales = "pricing, buying a product"
|
|
30
|
+
|
|
31
|
+
@decide
|
|
32
|
+
def department(message: str) -> Dept:
|
|
33
|
+
"""Which department should handle this message?"""
|
|
34
|
+
|
|
35
|
+
is_scam("Votre colis est bloqué, payez 1,99 € ici") # True
|
|
36
|
+
department("I was billed twice") # Dept.billing
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
The function body is never run: the docstring is the question, the return type is the set of possible answers.
|
|
40
|
+
|
|
41
|
+
## Install
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
pip install daaf
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
The first call downloads the Laya model (a few hundred MB) and loads it, which takes a few seconds. Later calls are fast.
|
|
48
|
+
|
|
49
|
+
## Return types
|
|
50
|
+
|
|
51
|
+
| Annotation | Result |
|
|
52
|
+
|---|---|
|
|
53
|
+
| `bool` | `True` / `False` |
|
|
54
|
+
| `Literal["a", "b", ...]` | one of the values (strings, ints…) |
|
|
55
|
+
| `Enum` subclass | one member; string values describe each option, which helps the model |
|
|
56
|
+
| `IntEnum` subclass | an ordered level (Laya's `score` type); member names are read as the level labels |
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
class Urgency(IntEnum):
|
|
60
|
+
not_urgent = 0
|
|
61
|
+
soon = 1
|
|
62
|
+
blocking = 2
|
|
63
|
+
|
|
64
|
+
@decide
|
|
65
|
+
def urgency(message: str) -> Urgency:
|
|
66
|
+
"""How urgent is this message?"""
|
|
67
|
+
|
|
68
|
+
urgency("Production is down!") # Urgency.blocking
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Arguments
|
|
72
|
+
|
|
73
|
+
- One argument: its value is the text Laya reads.
|
|
74
|
+
- Several arguments: Laya reads them as named fields, for example `def urgent(subject: str, body: str) -> bool`.
|
|
75
|
+
|
|
76
|
+
## Many inputs at once
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
is_scam.batch(["message 1", "message 2", ...]) # one-argument function
|
|
80
|
+
urgent.batch([("subject", "body"), {"subject": "s", "body": "b"}]) # several arguments
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Inputs share forward passes, which is much faster than a loop. Results come back in input order. `batch_size=` caps how many go through the model at once.
|
|
84
|
+
|
|
85
|
+
## Options
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
@decide(min_confidence=0.8) # raise daaf.Undecided below 80% instead of guessing
|
|
89
|
+
def is_scam(message: str) -> bool:
|
|
90
|
+
"""Is this message a scam trying to get money or credentials?"""
|
|
91
|
+
|
|
92
|
+
@decide(model="multilingual", max_len=8192) # anything else goes to laya's Router.predict
|
|
93
|
+
def is_contract(document: str) -> bool:
|
|
94
|
+
"""Is this document a contract?"""
|
|
95
|
+
|
|
96
|
+
@decide(router=my_router) # your own Router, or any object with Laya's .predict / .predict_batch
|
|
97
|
+
def is_spam(text: str) -> bool:
|
|
98
|
+
"""Is this message spam?"""
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
`Undecided` carries Laya's raw answer in `.answer`, so you can hand the case to a person or a larger model. In `.batch(...)`, the first undecided input raises it.
|
|
102
|
+
|
|
103
|
+
`is_scam.question` shows the exact question sent to Laya.
|
|
104
|
+
|
|
105
|
+
## Accuracy
|
|
106
|
+
|
|
107
|
+
daaf adds no intelligence: answers are as good as Laya's zero-shot checkpoints, which can make mistakes, especially on subtle questions. Test on your own examples, and use `min_confidence` where an error costs something. Clear docstrings and `Enum` descriptions help.
|
|
108
|
+
|
|
109
|
+
## License
|
|
110
|
+
|
|
111
|
+
Apache-2.0, like Laya.
|
|
112
|
+
|
|
113
|
+
## Tests
|
|
114
|
+
|
|
115
|
+
```bash
|
|
116
|
+
python test_daaf.py # no model needed, a fake router stands in for Laya
|
|
117
|
+
```
|
daaf-0.1.0/README.md
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
# daaf — decision-as-a-function
|
|
2
|
+
|
|
3
|
+
Write a typed Python function with a docstring. [Laya](https://github.com/NandhaKishorM/laya) answers it, locally, in any of 100+ languages, in tens of milliseconds.
|
|
4
|
+
|
|
5
|
+
```python
|
|
6
|
+
from enum import Enum, IntEnum
|
|
7
|
+
from typing import Literal
|
|
8
|
+
from daaf import decide
|
|
9
|
+
|
|
10
|
+
@decide
|
|
11
|
+
def is_scam(message: str) -> bool:
|
|
12
|
+
"""Is this message a scam trying to get money or credentials?"""
|
|
13
|
+
|
|
14
|
+
class Dept(Enum):
|
|
15
|
+
billing = "invoices, payments, refunds" # the value describes the option to the model
|
|
16
|
+
support = "bugs, outages, login problems"
|
|
17
|
+
sales = "pricing, buying a product"
|
|
18
|
+
|
|
19
|
+
@decide
|
|
20
|
+
def department(message: str) -> Dept:
|
|
21
|
+
"""Which department should handle this message?"""
|
|
22
|
+
|
|
23
|
+
is_scam("Votre colis est bloqué, payez 1,99 € ici") # True
|
|
24
|
+
department("I was billed twice") # Dept.billing
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
The function body is never run: the docstring is the question, the return type is the set of possible answers.
|
|
28
|
+
|
|
29
|
+
## Install
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install daaf
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
The first call downloads the Laya model (a few hundred MB) and loads it, which takes a few seconds. Later calls are fast.
|
|
36
|
+
|
|
37
|
+
## Return types
|
|
38
|
+
|
|
39
|
+
| Annotation | Result |
|
|
40
|
+
|---|---|
|
|
41
|
+
| `bool` | `True` / `False` |
|
|
42
|
+
| `Literal["a", "b", ...]` | one of the values (strings, ints…) |
|
|
43
|
+
| `Enum` subclass | one member; string values describe each option, which helps the model |
|
|
44
|
+
| `IntEnum` subclass | an ordered level (Laya's `score` type); member names are read as the level labels |
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
class Urgency(IntEnum):
|
|
48
|
+
not_urgent = 0
|
|
49
|
+
soon = 1
|
|
50
|
+
blocking = 2
|
|
51
|
+
|
|
52
|
+
@decide
|
|
53
|
+
def urgency(message: str) -> Urgency:
|
|
54
|
+
"""How urgent is this message?"""
|
|
55
|
+
|
|
56
|
+
urgency("Production is down!") # Urgency.blocking
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Arguments
|
|
60
|
+
|
|
61
|
+
- One argument: its value is the text Laya reads.
|
|
62
|
+
- Several arguments: Laya reads them as named fields, for example `def urgent(subject: str, body: str) -> bool`.
|
|
63
|
+
|
|
64
|
+
## Many inputs at once
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
is_scam.batch(["message 1", "message 2", ...]) # one-argument function
|
|
68
|
+
urgent.batch([("subject", "body"), {"subject": "s", "body": "b"}]) # several arguments
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Inputs share forward passes, which is much faster than a loop. Results come back in input order. `batch_size=` caps how many go through the model at once.
|
|
72
|
+
|
|
73
|
+
## Options
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
@decide(min_confidence=0.8) # raise daaf.Undecided below 80% instead of guessing
|
|
77
|
+
def is_scam(message: str) -> bool:
|
|
78
|
+
"""Is this message a scam trying to get money or credentials?"""
|
|
79
|
+
|
|
80
|
+
@decide(model="multilingual", max_len=8192) # anything else goes to laya's Router.predict
|
|
81
|
+
def is_contract(document: str) -> bool:
|
|
82
|
+
"""Is this document a contract?"""
|
|
83
|
+
|
|
84
|
+
@decide(router=my_router) # your own Router, or any object with Laya's .predict / .predict_batch
|
|
85
|
+
def is_spam(text: str) -> bool:
|
|
86
|
+
"""Is this message spam?"""
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
`Undecided` carries Laya's raw answer in `.answer`, so you can hand the case to a person or a larger model. In `.batch(...)`, the first undecided input raises it.
|
|
90
|
+
|
|
91
|
+
`is_scam.question` shows the exact question sent to Laya.
|
|
92
|
+
|
|
93
|
+
## Accuracy
|
|
94
|
+
|
|
95
|
+
daaf adds no intelligence: answers are as good as Laya's zero-shot checkpoints, which can make mistakes, especially on subtle questions. Test on your own examples, and use `min_confidence` where an error costs something. Clear docstrings and `Enum` descriptions help.
|
|
96
|
+
|
|
97
|
+
## License
|
|
98
|
+
|
|
99
|
+
Apache-2.0, like Laya.
|
|
100
|
+
|
|
101
|
+
## Tests
|
|
102
|
+
|
|
103
|
+
```bash
|
|
104
|
+
python test_daaf.py # no model needed, a fake router stands in for Laya
|
|
105
|
+
```
|
daaf-0.1.0/daaf.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""Decision-as-a-function: write a typed Python function with a docstring, Laya answers it.
|
|
2
|
+
|
|
3
|
+
from typing import Literal
|
|
4
|
+
from daaf import decide
|
|
5
|
+
|
|
6
|
+
@decide
|
|
7
|
+
def is_scam(message: str) -> bool:
|
|
8
|
+
\"\"\"Is this message a scam trying to get money or credentials?\"\"\"
|
|
9
|
+
|
|
10
|
+
@decide
|
|
11
|
+
def department(message: str) -> Literal["billing", "support", "sales"]:
|
|
12
|
+
\"\"\"Which department should handle this message?\"\"\"
|
|
13
|
+
|
|
14
|
+
is_scam("Your parcel is held, pay 1.99 EUR here") # True
|
|
15
|
+
department("I was charged twice") # "billing"
|
|
16
|
+
"""
|
|
17
|
+
import functools
|
|
18
|
+
import inspect
|
|
19
|
+
from enum import Enum, IntEnum
|
|
20
|
+
from typing import Literal, get_args, get_origin, get_type_hints
|
|
21
|
+
|
|
22
|
+
__all__ = ["decide", "Undecided"]
|
|
23
|
+
__version__ = "0.1.0"
|
|
24
|
+
|
|
25
|
+
_router = None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _default_router():
|
|
29
|
+
global _router
|
|
30
|
+
if _router is None:
|
|
31
|
+
from laya import Router # imported lazily: loading torch is slow
|
|
32
|
+
_router = Router()
|
|
33
|
+
return _router
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Undecided(Exception):
|
|
37
|
+
"""Laya's confidence fell below the function's `min_confidence`."""
|
|
38
|
+
|
|
39
|
+
def __init__(self, function, answer):
|
|
40
|
+
self.answer = answer
|
|
41
|
+
super().__init__(f"{function}: confidence {answer.get('confidence', 0):.2f} too low")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _question(fn):
|
|
45
|
+
"""Build the Laya question from the docstring and return annotation, plus a decoder."""
|
|
46
|
+
doc = inspect.getdoc(fn)
|
|
47
|
+
if not doc:
|
|
48
|
+
raise TypeError(f"{fn.__name__}: the docstring is the question, it must not be empty")
|
|
49
|
+
ret = get_type_hints(fn).get("return")
|
|
50
|
+
if ret is bool:
|
|
51
|
+
return {"type": "noul", "instructions": doc}, lambda a: a["noul"] >= 0.5
|
|
52
|
+
if get_origin(ret) is Literal:
|
|
53
|
+
values = get_args(ret)
|
|
54
|
+
labels = {str(v): v for v in values}
|
|
55
|
+
if len(labels) != len(values):
|
|
56
|
+
raise TypeError(f"{fn.__name__}: Literal values must be distinct once turned into text")
|
|
57
|
+
question = {"type": "choice", "instructions": doc, "criteria": dict.fromkeys(labels)}
|
|
58
|
+
return question, lambda a: labels[a["choice"]]
|
|
59
|
+
if inspect.isclass(ret) and issubclass(ret, IntEnum):
|
|
60
|
+
# Ordered levels: Laya's `score` type, levels sorted by value, names read as text.
|
|
61
|
+
levels = sorted(ret)
|
|
62
|
+
question = {"type": "score", "instructions": doc,
|
|
63
|
+
"criteria": [m.name.replace("_", " ") for m in levels]}
|
|
64
|
+
return question, lambda a: levels[_level(a)]
|
|
65
|
+
if inspect.isclass(ret) and issubclass(ret, Enum):
|
|
66
|
+
# The member name is the label, its value (a string) describes it to the model.
|
|
67
|
+
criteria = {m.name: m.value if isinstance(m.value, str) else None for m in ret}
|
|
68
|
+
question = {"type": "choice", "instructions": doc, "criteria": criteria}
|
|
69
|
+
return question, lambda a: ret[a["choice"]]
|
|
70
|
+
raise TypeError(f"{fn.__name__}: the return annotation must be bool, Literal[...], an Enum "
|
|
71
|
+
f"or an IntEnum, got {ret!r}")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _level(answer):
|
|
75
|
+
"""Most probable level of a `score` answer (its `score` field is an average, not a level)."""
|
|
76
|
+
probs = answer.get("probabilities")
|
|
77
|
+
if probs:
|
|
78
|
+
return int(max(probs, key=lambda k: float(probs[k])))
|
|
79
|
+
return round(float(answer["score"]))
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def decide(fn=None, *, min_confidence=None, router=None, **predict_kwargs):
|
|
83
|
+
"""Turn a typed, documented function into a Laya decision.
|
|
84
|
+
|
|
85
|
+
`min_confidence`: below it, raise `Undecided` instead of returning a guess.
|
|
86
|
+
`router`: any object with Laya's `predict(state, questions, **kw)` (default: `laya.Router()`).
|
|
87
|
+
Other keyword arguments go to `predict` (for example `model="multilingual"`, `max_len=8192`).
|
|
88
|
+
"""
|
|
89
|
+
if fn is None: # used as @decide(...)
|
|
90
|
+
return lambda f: decide(f, min_confidence=min_confidence, router=router, **predict_kwargs)
|
|
91
|
+
|
|
92
|
+
question, decode = _question(fn)
|
|
93
|
+
signature = inspect.signature(fn)
|
|
94
|
+
if min_confidence is not None:
|
|
95
|
+
predict_kwargs["min_confidence"] = min_confidence
|
|
96
|
+
|
|
97
|
+
def state(*args, **kwargs):
|
|
98
|
+
bound = signature.bind(*args, **kwargs)
|
|
99
|
+
bound.apply_defaults()
|
|
100
|
+
params = bound.arguments
|
|
101
|
+
# One argument: the text itself. Several: Laya reads a dict of named fields.
|
|
102
|
+
return next(iter(params.values())) if len(params) == 1 else dict(params)
|
|
103
|
+
|
|
104
|
+
def answer_of(result):
|
|
105
|
+
answer = result["answers"]["answer"]
|
|
106
|
+
if answer.get("low_confidence"):
|
|
107
|
+
raise Undecided(fn.__name__, answer)
|
|
108
|
+
return decode(answer)
|
|
109
|
+
|
|
110
|
+
@functools.wraps(fn)
|
|
111
|
+
def wrapper(*args, **kwargs):
|
|
112
|
+
result = (router or _default_router()).predict(state(*args, **kwargs), {"answer": question},
|
|
113
|
+
**predict_kwargs)
|
|
114
|
+
return answer_of(result)
|
|
115
|
+
|
|
116
|
+
def batch(items, batch_size=None):
|
|
117
|
+
"""Answer many inputs in shared forward passes, in input order.
|
|
118
|
+
|
|
119
|
+
For a one-argument function each item is that argument; otherwise each item is a dict
|
|
120
|
+
of keyword arguments or a tuple of positional ones.
|
|
121
|
+
"""
|
|
122
|
+
if len(signature.parameters) == 1:
|
|
123
|
+
states = [state(item) for item in items]
|
|
124
|
+
else:
|
|
125
|
+
states = [state(**i) if isinstance(i, dict) else state(*i) for i in items]
|
|
126
|
+
call = {k: v for k, v in predict_kwargs.items() if k == "min_confidence"}
|
|
127
|
+
per_request = {k: v for k, v in predict_kwargs.items() if k != "min_confidence"}
|
|
128
|
+
requests = [{"state": s, "questions": {"answer": question}, **per_request} for s in states]
|
|
129
|
+
results = (router or _default_router()).predict_batch(requests, batch_size=batch_size, **call)
|
|
130
|
+
return [answer_of(r) for r in results]
|
|
131
|
+
|
|
132
|
+
wrapper.question = question
|
|
133
|
+
wrapper.batch = batch
|
|
134
|
+
return wrapper
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "daaf"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Decision-as-a-function: a typed Python function with a docstring, answered by Laya"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "Apache-2.0"
|
|
12
|
+
dependencies = ["laya>=0.3.27"]
|
|
13
|
+
keywords = ["laya", "decision", "classification", "llm", "decorator"]
|
|
14
|
+
|
|
15
|
+
[tool.hatch.version]
|
|
16
|
+
path = "daaf.py"
|
|
17
|
+
|
|
18
|
+
[project.urls]
|
|
19
|
+
Homepage = "https://github.com/LilHenri75/daaf"
|
daaf-0.1.0/test_daaf.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""Tests without the model: a fake router stands in for Laya. Run: python -m pytest (or python test_daaf.py)."""
|
|
2
|
+
from enum import Enum, IntEnum
|
|
3
|
+
from typing import Literal
|
|
4
|
+
|
|
5
|
+
from daaf import Undecided, decide
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class FakeRouter:
|
|
9
|
+
def __init__(self, answer):
|
|
10
|
+
self.answer, self.calls = answer, []
|
|
11
|
+
|
|
12
|
+
def predict(self, state, questions, **kw):
|
|
13
|
+
self.calls.append((state, questions, kw))
|
|
14
|
+
return {"answers": {"answer": self.answer}}
|
|
15
|
+
|
|
16
|
+
def predict_batch(self, requests, **kw):
|
|
17
|
+
return [self.predict(r["state"], r["questions"], **kw) for r in requests]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def test_bool():
|
|
21
|
+
r = FakeRouter({"noul": 0.9})
|
|
22
|
+
|
|
23
|
+
@decide(router=r)
|
|
24
|
+
def is_scam(message: str) -> bool:
|
|
25
|
+
"""Is this a scam?"""
|
|
26
|
+
|
|
27
|
+
assert is_scam("pay now") is True
|
|
28
|
+
assert r.calls[0][:2] == ("pay now", {"answer": {"type": "noul", "instructions": "Is this a scam?"}})
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def test_literal_and_several_arguments():
|
|
32
|
+
r = FakeRouter({"choice": "2"})
|
|
33
|
+
|
|
34
|
+
@decide(router=r)
|
|
35
|
+
def urgency(subject: str, body: str = "") -> Literal[1, 2, 3]:
|
|
36
|
+
"""How urgent?"""
|
|
37
|
+
|
|
38
|
+
assert urgency("help") == 2 # the text label comes back as the original value
|
|
39
|
+
assert r.calls[0][0] == {"subject": "help", "body": ""}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def test_enum_values_describe_options():
|
|
43
|
+
class Dept(Enum):
|
|
44
|
+
billing = "invoices, refunds"
|
|
45
|
+
support = "bugs, outages"
|
|
46
|
+
|
|
47
|
+
r = FakeRouter({"choice": "support"})
|
|
48
|
+
|
|
49
|
+
@decide(router=r)
|
|
50
|
+
def dept(text: str) -> Dept:
|
|
51
|
+
"""Which department?"""
|
|
52
|
+
|
|
53
|
+
assert dept("down") is Dept.support
|
|
54
|
+
assert r.calls[0][1]["answer"]["criteria"] == {"billing": "invoices, refunds", "support": "bugs, outages"}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def test_intenum_is_an_ordered_score():
|
|
58
|
+
class Urgency(IntEnum):
|
|
59
|
+
high = 5
|
|
60
|
+
low = 1
|
|
61
|
+
|
|
62
|
+
r = FakeRouter({"score": 0.4, "probabilities": {"0": 0.3, "1": 0.7}})
|
|
63
|
+
|
|
64
|
+
@decide(router=r)
|
|
65
|
+
def urgency(text: str) -> Urgency:
|
|
66
|
+
"""How urgent?"""
|
|
67
|
+
|
|
68
|
+
assert urgency("x") is Urgency.high # most probable level, not the rounded average
|
|
69
|
+
assert r.calls[0][1]["answer"]["criteria"] == ["low", "high"] # sorted by value
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def test_batch():
|
|
73
|
+
r = FakeRouter({"noul": 0.2})
|
|
74
|
+
|
|
75
|
+
@decide(router=r, min_confidence=0.5, model="multilingual")
|
|
76
|
+
def ok(subject: str, body: str) -> bool:
|
|
77
|
+
"""Ok?"""
|
|
78
|
+
|
|
79
|
+
assert ok.batch([("a", "b"), {"subject": "c", "body": "d"}]) == [False, False]
|
|
80
|
+
assert [c[0] for c in r.calls] == [{"subject": "a", "body": "b"}, {"subject": "c", "body": "d"}]
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def test_low_confidence_raises():
|
|
84
|
+
@decide(router=FakeRouter({"noul": 0.55, "confidence": 0.55, "low_confidence": True}), min_confidence=0.8)
|
|
85
|
+
def f(text: str) -> bool:
|
|
86
|
+
"""Yes?"""
|
|
87
|
+
|
|
88
|
+
try:
|
|
89
|
+
f("x")
|
|
90
|
+
raise AssertionError("expected Undecided")
|
|
91
|
+
except Undecided as e:
|
|
92
|
+
assert e.answer["noul"] == 0.55
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def test_bad_definitions_fail_at_decoration():
|
|
96
|
+
for bad in ("def g(t: str) -> bool: pass", 'def g(t: str) -> str:\n """Q?"""'):
|
|
97
|
+
ns = {}
|
|
98
|
+
exec(bad, ns)
|
|
99
|
+
try:
|
|
100
|
+
decide(ns["g"], router=FakeRouter({}))
|
|
101
|
+
raise AssertionError("expected TypeError")
|
|
102
|
+
except TypeError:
|
|
103
|
+
pass
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
if __name__ == "__main__":
|
|
107
|
+
for name, t in list(globals().items()):
|
|
108
|
+
if name.startswith("test_"):
|
|
109
|
+
t()
|
|
110
|
+
print("ok")
|