smarter-types 0.1.0__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.
@@ -0,0 +1,36 @@
1
+ """
2
+ Smarter-types: the types that the Smarter platform and its Python SDK share.
3
+
4
+ .. code-block:: python
5
+
6
+ from smarter_types import SAMKinds
7
+
8
+ sorted(manifests, key=lambda m: SAMKinds.apply_rank(m["kind"]))
9
+
10
+ See https://docs.smarter-types.smarter.sh/
11
+ """
12
+
13
+ from .__version__ import __version__
14
+ from .enum import SmarterEnumAbstract
15
+ from .exceptions import SmarterTypesError, SmarterTypesValueError
16
+ from .journal import (
17
+ SCLIResponseMetadata,
18
+ SmarterJournalApiResponseErrorKeys,
19
+ SmarterJournalApiResponseKeys,
20
+ SmarterJournalCliCommands,
21
+ SmarterJournalThings,
22
+ )
23
+ from .kinds import SAMKinds
24
+
25
+ __all__ = [
26
+ "SAMKinds",
27
+ "SCLIResponseMetadata",
28
+ "SmarterEnumAbstract",
29
+ "SmarterJournalApiResponseErrorKeys",
30
+ "SmarterJournalApiResponseKeys",
31
+ "SmarterJournalCliCommands",
32
+ "SmarterJournalThings",
33
+ "SmarterTypesError",
34
+ "SmarterTypesValueError",
35
+ "__version__",
36
+ ]
@@ -0,0 +1,3 @@
1
+ # DO NOT EDIT.
2
+ # Managed by semantic-release, through release.config.js.
3
+ __version__ = "0.1.0"
smarter_types/enum.py ADDED
@@ -0,0 +1,113 @@
1
+ """The base class of Smarter's enumerations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from enum import Enum
7
+ from urllib.parse import urlparse
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ class SmarterEnumAbstract(Enum):
13
+ """
14
+ The base class of Smarter's enumerations, whose values are strings.
15
+
16
+ It adds class methods that list the values, and the url slugs made from them. ``str()`` of a
17
+ member is its value.
18
+
19
+ .. code-block:: python
20
+
21
+ from smarter_types import SAMKinds
22
+
23
+ SAMKinds.all() # ["Plugin", "ApiPlugin", ...]
24
+ str(SAMKinds.SECRET) # "Secret"
25
+ """
26
+
27
+ @classmethod
28
+ def all(cls) -> list[str]:
29
+ """
30
+ Return every member's value.
31
+
32
+ :returns: The values, in the order in which the members are defined.
33
+ :rtype: list[str]
34
+ """
35
+ return [member.value for name, member in cls.__members__.items() if not name.startswith("_")]
36
+
37
+ @classmethod
38
+ def list_all(cls) -> str:
39
+ """
40
+ Return every member's value, as one comma-separated string, e.g. for an error message.
41
+
42
+ :returns: The values, separated by ``", "``.
43
+ :rtype: str
44
+ """
45
+ return ", ".join(cls.all())
46
+
47
+ @classmethod
48
+ def all_slugs(cls) -> list[str]:
49
+ """
50
+ Return the url slugs of every value, singular and plural.
51
+
52
+ :returns: :meth:`singular_slugs`, then :meth:`plural_slugs`.
53
+ :rtype: list[str]
54
+ """
55
+ return cls.singular_slugs() + cls.plural_slugs()
56
+
57
+ @classmethod
58
+ def singular_slugs(cls) -> list[str]:
59
+ """
60
+ Return the singular url slug of every value: the value, in lower case.
61
+
62
+ :returns: The slugs, e.g. ``["plugin", "apiplugin", ...]``.
63
+ :rtype: list[str]
64
+ """
65
+ return [slug.lower() for slug in cls.all()]
66
+
67
+ @classmethod
68
+ def plural_slugs(cls) -> list[str]:
69
+ """
70
+ Return the plural url slug of every value: the value, in lower case, with an ``s``.
71
+
72
+ :returns: The slugs, e.g. ``["plugins", "apiplugins", ...]``.
73
+ :rtype: list[str]
74
+ """
75
+ return [f"{slug.lower()}s" for slug in cls.all()]
76
+
77
+ @classmethod
78
+ def from_url(cls, url: str | bytes) -> str | None:
79
+ """
80
+ Return the first slug of a Smarter api url that is one of this enumeration's slugs.
81
+
82
+ .. code-block:: python
83
+
84
+ SAMKinds.from_url("http://localhost:9357/api/v1/cli/example_manifest/Account/") # "account"
85
+ SAMKinds.from_url("http://localhost:9357/api/v1/cli/whoami/") # None
86
+
87
+ :param url: The url.
88
+ :type url: str | bytes
89
+ :returns: The slug, in lower case, or None for a url that is not an api url, that is the
90
+ ``whoami``, ``status`` or ``version`` endpoint, or that has none of the slugs.
91
+ :rtype: str | None
92
+ """
93
+ if isinstance(url, bytes):
94
+ url = url.decode("utf-8")
95
+ slugs = urlparse(url).path.split("/")
96
+ if "api" not in slugs:
97
+ return None
98
+ if "whoami" in slugs or "status" in slugs or "version" in slugs:
99
+ return None
100
+ all_slugs = cls.all_slugs()
101
+ for slug in slugs:
102
+ this_slug = str(slug).lower()
103
+ if this_slug in all_slugs:
104
+ return this_slug
105
+ logger.warning("%s.from_url() could not extract manifest kind from URL: %s", cls.__name__, url)
106
+ return None
107
+
108
+ def __str__(self) -> str:
109
+ """Return the member's value."""
110
+ return str(self.value)
111
+
112
+
113
+ __all__ = ["SmarterEnumAbstract"]
@@ -0,0 +1,12 @@
1
+ """The exceptions that smarter-types raises."""
2
+
3
+
4
+ class SmarterTypesError(Exception):
5
+ """The base class of every exception that smarter-types raises."""
6
+
7
+
8
+ class SmarterTypesValueError(SmarterTypesError, ValueError):
9
+ """A value that is not one of an enumeration's, e.g. a string that is not a SAM kind."""
10
+
11
+
12
+ __all__ = ["SmarterTypesError", "SmarterTypesValueError"]
@@ -0,0 +1,259 @@
1
+ """
2
+ The enumerations of the Smarter Journal: the record of every request to the Smarter api.
3
+
4
+ Each journal entry records the *thing* that a request was about, from :class:`SmarterJournalThings`,
5
+ and the *command* that it ran, from :class:`SmarterJournalCliCommands`. Every SAM kind is a thing,
6
+ so :class:`SmarterJournalThings` takes its kinds from :class:`~smarter_types.kinds.SAMKinds`.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import logging
12
+ from urllib.parse import urlparse
13
+
14
+ from .enum import SmarterEnumAbstract
15
+ from .kinds import SAMKinds
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ class SmarterJournalApiResponseKeys:
21
+ """The keys of a journaled response of the Smarter api."""
22
+
23
+ API = "api"
24
+ THING = "thing"
25
+ METADATA = "metadata"
26
+ DATA = "data"
27
+ ERROR = "error"
28
+ MESSAGE = "message"
29
+
30
+
31
+ class SmarterJournalApiResponseErrorKeys:
32
+ """The keys of the ``error`` of a journaled response of the Smarter api."""
33
+
34
+ ERROR_CLASS = "errorClass"
35
+ STACK_TRACE = "stacktrace"
36
+ DESCRIPTION = "description"
37
+ STATUS = "status"
38
+ ARGS = "args"
39
+ CAUSE = "cause"
40
+ CONTEXT = "context"
41
+ THING = "thing"
42
+ COMMAND = "command"
43
+
44
+
45
+ class SCLIResponseMetadata:
46
+ """The keys of the ``metadata`` of a journaled response of the cli api's ``get`` command."""
47
+
48
+ KEY = "key"
49
+ COMMAND = "command"
50
+
51
+
52
+ class SmarterJournalThings(SmarterEnumAbstract):
53
+ """
54
+ The kinds of objects ("things") that the Smarter Journal records requests about.
55
+
56
+ Every SAM kind is a thing, with the same value. The one thing that is not a SAM kind is
57
+ :attr:`PROMPT_CONFIG`, a chat's configuration, which the platform generates on request.
58
+
59
+ .. code-block:: python
60
+
61
+ thing = SmarterJournalThings("Plugin")
62
+ assert thing == SmarterJournalThings.STATIC_PLUGIN
63
+ assert thing.value == SAMKinds.STATIC_PLUGIN.value
64
+ """
65
+
66
+ ACCOUNT = SAMKinds.ACCOUNT.value
67
+ API_PLUGIN = SAMKinds.API_PLUGIN.value
68
+ AUTH_TOKEN = SAMKinds.AUTH_TOKEN.value
69
+ API_CONNECTION = SAMKinds.API_CONNECTION.value
70
+ BUDGET = SAMKinds.BUDGET.value
71
+ CUSTOM_DOMAIN = SAMKinds.CUSTOM_DOMAIN.value
72
+ GUARDRAIL = SAMKinds.GUARDRAIL.value
73
+ IMAGE_SEARCH_PLUGIN = SAMKinds.IMAGE_SEARCH_PLUGIN.value
74
+ LLM_CLIENT = SAMKinds.LLM_CLIENT.value
75
+ LLMHOST = SAMKinds.LLM_HOST.value
76
+ LLMHOST_COMPUTE = SAMKinds.LLM_HOST_COMPUTE.value
77
+ MCPCLIENT = SAMKinds.MCP_CLIENT.value
78
+ ORCHESTRATOR = SAMKinds.ORCHESTRATOR.value
79
+ PROMPT = SAMKinds.PROMPT.value
80
+ PROVIDER = SAMKinds.PROVIDER.value
81
+ PROXY = SAMKinds.PROXY.value
82
+ SECRET = SAMKinds.SECRET.value
83
+ SQL_CONNECTION = SAMKinds.SQL_CONNECTION.value
84
+ SKILL_PLUGIN = SAMKinds.SKILL_PLUGIN.value
85
+ SQL_PLUGIN = SAMKinds.SQL_PLUGIN.value
86
+ STATIC_PLUGIN = SAMKinds.STATIC_PLUGIN.value
87
+ USER = SAMKinds.USER.value
88
+ VECTORSEARCH = SAMKinds.VECTORSEARCH.value
89
+ VECTORSTORE = SAMKinds.VECTORSTORE.value
90
+ WEBSEARCH_PLUGIN = SAMKinds.WEBSEARCH_PLUGIN.value
91
+
92
+ PROMPT_CONFIG = "ChatConfig"
93
+ """A chat's configuration: a JSON object that the platform generates on request.
94
+
95
+ Not a SAM kind.
96
+ """
97
+
98
+ @classmethod
99
+ def choices(cls) -> list[tuple[str, str]]:
100
+ """
101
+ Return the choices of the platform's journal model's ``thing`` field, as Django expects them.
102
+
103
+ The list is part of the platform's database migrations, so it changes only with a migration.
104
+ It doesn't have ``LLMHost`` or ``LLMHostCompute``.
105
+
106
+ :returns: ``(value, label)`` pairs.
107
+ :rtype: list[tuple[str, str]]
108
+ """
109
+ return [
110
+ (cls.ACCOUNT.value, cls.ACCOUNT.value),
111
+ (cls.API_CONNECTION.value, cls.API_CONNECTION.value),
112
+ (cls.API_PLUGIN.value, cls.API_PLUGIN.value),
113
+ (cls.AUTH_TOKEN.value, cls.AUTH_TOKEN.value),
114
+ (cls.BUDGET.value, cls.BUDGET.value),
115
+ (cls.CUSTOM_DOMAIN.value, cls.CUSTOM_DOMAIN.value),
116
+ (cls.GUARDRAIL.value, cls.GUARDRAIL.value),
117
+ (cls.IMAGE_SEARCH_PLUGIN.value, cls.IMAGE_SEARCH_PLUGIN.value),
118
+ (cls.LLM_CLIENT.value, cls.LLM_CLIENT.value),
119
+ (cls.MCPCLIENT.value, cls.MCPCLIENT.value),
120
+ (cls.ORCHESTRATOR.value, cls.ORCHESTRATOR.value),
121
+ (cls.PROMPT.value, cls.PROMPT.value),
122
+ (cls.PROMPT_CONFIG.value, cls.PROMPT_CONFIG.value),
123
+ (cls.PROXY.value, cls.PROXY.value),
124
+ (cls.PROVIDER.value, cls.PROVIDER.value),
125
+ (cls.SECRET.value, cls.SECRET.value),
126
+ (cls.SKILL_PLUGIN.value, cls.SKILL_PLUGIN.value),
127
+ (cls.SQL_CONNECTION.value, cls.SQL_CONNECTION.value),
128
+ (cls.SQL_PLUGIN.value, cls.SQL_PLUGIN.value),
129
+ (cls.STATIC_PLUGIN.value, cls.STATIC_PLUGIN.value),
130
+ (cls.USER.value, cls.USER.value),
131
+ (cls.VECTORSEARCH.value, cls.VECTORSEARCH.value),
132
+ (cls.VECTORSTORE.value, cls.VECTORSTORE.value),
133
+ (cls.WEBSEARCH_PLUGIN.value, cls.WEBSEARCH_PLUGIN.value),
134
+ ]
135
+
136
+
137
+ class SmarterJournalCliCommands(SmarterEnumAbstract):
138
+ """
139
+ The commands of the Smarter api's ``/api/v1/cli/`` endpoints, which the journal records.
140
+
141
+ .. code-block:: python
142
+
143
+ command = SmarterJournalCliCommands("apply")
144
+ assert command == SmarterJournalCliCommands.APPLY
145
+ """
146
+
147
+ APPLY = "apply"
148
+ DELETE = "delete"
149
+ DEPLOY = "deploy"
150
+ DESCRIBE = "describe"
151
+ ENABLE_JOURNAL = "journal" # FIXNOTE: THIS IS AMBIGUOUS
152
+ GET = "get"
153
+ JSON_SCHEMA = "json_schema"
154
+ LOGS = "logs" # FIXNOTE: THIS IS AMBIGUOUS
155
+ MANIFEST_EXAMPLE = "example_manifest"
156
+ PROMPT = "prompt"
157
+ PROMPT_CONFIG = "chat_config"
158
+ STATUS = "status"
159
+ UNDEPLOY = "undeploy"
160
+ VALIDATE = "validate"
161
+ VERSION = "version"
162
+ WHOAMI = "whoami"
163
+ RESOURCES = "resources"
164
+
165
+ @classmethod
166
+ def choices(cls) -> list[tuple[str, str]]:
167
+ """
168
+ Return the choices of the platform's journal model's ``command`` field, as Django expects them.
169
+
170
+ The list is part of the platform's database migrations, so it changes only with a migration.
171
+
172
+ :returns: ``(value, label)`` pairs.
173
+ :rtype: list[tuple[str, str]]
174
+ """
175
+ return [
176
+ (cls.APPLY.value, cls.APPLY.value),
177
+ (cls.PROMPT.value, cls.PROMPT.value),
178
+ (cls.PROMPT_CONFIG.value, cls.PROMPT_CONFIG.value),
179
+ (cls.DELETE.value, cls.DELETE.value),
180
+ (cls.DEPLOY.value, cls.DEPLOY.value),
181
+ (cls.DESCRIBE.value, cls.DESCRIBE.value),
182
+ (cls.GET.value, cls.GET.value),
183
+ (cls.ENABLE_JOURNAL.value, cls.ENABLE_JOURNAL.value),
184
+ (cls.LOGS.value, cls.LOGS.value),
185
+ (cls.MANIFEST_EXAMPLE.value, cls.MANIFEST_EXAMPLE.value),
186
+ (cls.STATUS.value, cls.STATUS.value),
187
+ (cls.JSON_SCHEMA.value, cls.JSON_SCHEMA.value),
188
+ (cls.VERSION.value, cls.VERSION.value),
189
+ (cls.UNDEPLOY.value, cls.UNDEPLOY.value),
190
+ (cls.VALIDATE.value, cls.VALIDATE.value),
191
+ (cls.WHOAMI.value, cls.WHOAMI.value),
192
+ (cls.RESOURCES.value, cls.RESOURCES.value),
193
+ ]
194
+
195
+ @classmethod
196
+ def past_tense(cls) -> dict[str, str]:
197
+ """
198
+ Return the past tense of each command, for the messages of journaled responses.
199
+
200
+ :returns: The past tense, by command value, e.g. ``{"apply": "applied", ...}``.
201
+ :rtype: dict[str, str]
202
+ """
203
+ return {
204
+ cls.APPLY.value: "applied",
205
+ cls.PROMPT.value: "prompted",
206
+ cls.PROMPT_CONFIG.value: "fetched chat_config",
207
+ cls.DELETE.value: "deleted",
208
+ cls.DEPLOY.value: "deployed",
209
+ cls.DESCRIBE.value: "described",
210
+ cls.GET.value: "got",
211
+ cls.ENABLE_JOURNAL.value: "journaled",
212
+ cls.LOGS.value: "logged",
213
+ cls.MANIFEST_EXAMPLE.value: "fetched example manifest",
214
+ cls.STATUS.value: "fetched status",
215
+ cls.JSON_SCHEMA.value: "fetched json schema",
216
+ cls.VERSION.value: "fetched version",
217
+ cls.UNDEPLOY.value: "undeployed",
218
+ cls.VALIDATE.value: "validated",
219
+ cls.WHOAMI.value: "fetched identity",
220
+ cls.RESOURCES.value: "fetched resources",
221
+ }
222
+
223
+ @classmethod
224
+ def from_url(cls, url: str | bytes) -> str | None:
225
+ """
226
+ Return the command of a Smarter api url.
227
+
228
+ .. code-block:: python
229
+
230
+ SmarterJournalCliCommands.from_url("http://localhost:9357/api/v1/cli/example_manifest/Account/")
231
+ # "example_manifest"
232
+
233
+ :param url: The url.
234
+ :type url: str | bytes
235
+ :returns: The first slug of the url's path that is a command, or None for a url that is not
236
+ an api url, or that has no command.
237
+ :rtype: str | None
238
+ """
239
+ if isinstance(url, bytes):
240
+ url = url.decode("utf-8")
241
+ slugs = urlparse(url).path.split("/")
242
+ if "api" not in slugs:
243
+ return None
244
+ commands = cls.all()
245
+ for slug in slugs:
246
+ this_slug = str(slug).lower()
247
+ if this_slug in commands:
248
+ return this_slug
249
+ logger.warning("SmarterJournalCliCommands.from_url() could not extract a command from URL: %s", url)
250
+ return None
251
+
252
+
253
+ __all__ = [
254
+ "SCLIResponseMetadata",
255
+ "SmarterJournalApiResponseErrorKeys",
256
+ "SmarterJournalApiResponseKeys",
257
+ "SmarterJournalCliCommands",
258
+ "SmarterJournalThings",
259
+ ]