mistralai-capabilities-backend-workflows 0.1.21__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.
- mistralai_capabilities_backend_workflows-0.1.21/LICENSE +201 -0
- mistralai_capabilities_backend_workflows-0.1.21/PKG-INFO +11 -0
- mistralai_capabilities_backend_workflows-0.1.21/pyproject.toml +22 -0
- mistralai_capabilities_backend_workflows-0.1.21/src/mistralai_capabilities/workflows/__init__.py +0 -0
- mistralai_capabilities_backend_workflows-0.1.21/src/mistralai_capabilities/workflows/client.py +315 -0
- mistralai_capabilities_backend_workflows-0.1.21/src/mistralai_capabilities/workflows/py.typed +0 -0
|
@@ -0,0 +1,201 @@
|
|
|
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
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2025 Mistral AI
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: mistralai-capabilities-backend-workflows
|
|
3
|
+
Version: 0.1.21
|
|
4
|
+
Summary: The workflows capability's toolkit: the SDK execution boundary the app imports (`client`).
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Requires-Dist: mistralai[workflow-payload-encryption]>=2.9.4
|
|
8
|
+
Requires-Dist: mistralai-workflows>=3.15.0
|
|
9
|
+
Requires-Dist: pydantic>=2
|
|
10
|
+
Requires-Dist: structlog>=25
|
|
11
|
+
Requires-Python: >=3.12, <3.15
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "mistralai-capabilities-backend-workflows"
|
|
3
|
+
version = "0.1.21"
|
|
4
|
+
description = "The workflows capability's toolkit: the SDK execution boundary the app imports (`client`)."
|
|
5
|
+
requires-python = ">=3.12,<3.15"
|
|
6
|
+
license = "Apache-2.0"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
dependencies = [
|
|
9
|
+
# `mistralai-search-toolkit` caps `mistralai<2.10`; a higher floor breaks uv resolution.
|
|
10
|
+
"mistralai[workflow-payload-encryption]>=2.9.4",
|
|
11
|
+
"mistralai-workflows>=3.15.0",
|
|
12
|
+
"pydantic>=2",
|
|
13
|
+
"structlog>=25",
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
[build-system]
|
|
17
|
+
requires = ["uv_build>=0.8.22,<0.9.0"]
|
|
18
|
+
build-backend = "uv_build"
|
|
19
|
+
|
|
20
|
+
[tool.uv.build-backend]
|
|
21
|
+
module-name = "mistralai_capabilities.workflows"
|
|
22
|
+
namespace = true
|
mistralai_capabilities_backend_workflows-0.1.21/src/mistralai_capabilities/workflows/__init__.py
ADDED
|
File without changes
|
mistralai_capabilities_backend_workflows-0.1.21/src/mistralai_capabilities/workflows/client.py
ADDED
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import inspect
|
|
3
|
+
import os
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from functools import cache
|
|
6
|
+
from typing import Any, get_type_hints
|
|
7
|
+
|
|
8
|
+
import mistralai.workflows as workflows
|
|
9
|
+
from mistralai.workflows import workflow as _wf
|
|
10
|
+
from mistralai.workflows.core.config.config import (
|
|
11
|
+
RESERVED_QUERY_NAMES,
|
|
12
|
+
RESERVED_UPDATE_NAMES,
|
|
13
|
+
PayloadEncryptionConfig,
|
|
14
|
+
WorkerConfig,
|
|
15
|
+
)
|
|
16
|
+
from mistralai.workflows.core.config.config import config as sdk_config
|
|
17
|
+
from mistralai.workflows.protocol.v1.workflow import DeploymentName
|
|
18
|
+
from pydantic import BaseModel, SecretStr, TypeAdapter
|
|
19
|
+
|
|
20
|
+
with _wf.unsafe.imports_passed_through():
|
|
21
|
+
import structlog
|
|
22
|
+
from env.mistral import env
|
|
23
|
+
from env.workflows import env as workflows_env
|
|
24
|
+
from mistralai.client import Mistral
|
|
25
|
+
from mistralai.client.errors import MistralError
|
|
26
|
+
from mistralai.client.models import (
|
|
27
|
+
ScheduleDefinition,
|
|
28
|
+
ScheduleInterval,
|
|
29
|
+
SchedulePolicy,
|
|
30
|
+
)
|
|
31
|
+
from mistralai.extra.workflows.encoding.config import WorkflowEncodingConfig
|
|
32
|
+
from mistralai.extra.workflows.encoding.helpers import configure_workflow_encoding
|
|
33
|
+
from mistralai.extra.workflows.encoding.payload_encoder import PayloadEncoder
|
|
34
|
+
from mistralai.workflows import ScheduleOverlapPolicy
|
|
35
|
+
|
|
36
|
+
_SCHEDULE_CATCHUP_SECONDS = 86400
|
|
37
|
+
|
|
38
|
+
_logger = structlog.get_logger("workflows.encryption")
|
|
39
|
+
|
|
40
|
+
# Assigning a config attribute skips the SDK's validation, so the name is validated here instead.
|
|
41
|
+
_DEPLOYMENT_NAME: TypeAdapter[str | None] = TypeAdapter(DeploymentName)
|
|
42
|
+
|
|
43
|
+
# An SDK internal, not a published contract: it can move on a version bump.
|
|
44
|
+
_ENTRYPOINT_MARKER = "__workflows_workflow_entrypoint"
|
|
45
|
+
|
|
46
|
+
__all__ = [
|
|
47
|
+
"ScheduleTimingError",
|
|
48
|
+
"WorkflowCapabilities",
|
|
49
|
+
"WorkflowRun",
|
|
50
|
+
"get_client",
|
|
51
|
+
"infer_workflow_models",
|
|
52
|
+
"pause_schedule_if_present",
|
|
53
|
+
"payload_encryption",
|
|
54
|
+
"run_worker",
|
|
55
|
+
"start_workflow",
|
|
56
|
+
"upsert_schedule",
|
|
57
|
+
"workflow_capabilities",
|
|
58
|
+
]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@cache
|
|
62
|
+
def payload_encryption() -> PayloadEncryptionConfig | None:
|
|
63
|
+
encryption = WorkerConfig().temporal_payload_encryption
|
|
64
|
+
if encryption is not None:
|
|
65
|
+
PayloadEncoder(WorkflowEncodingConfig(payload_encryption=encryption))
|
|
66
|
+
_logger.info(
|
|
67
|
+
"workflow payload encryption enabled",
|
|
68
|
+
mode=encryption.mode.value,
|
|
69
|
+
key_rotation=encryption.secondary_key is not None,
|
|
70
|
+
)
|
|
71
|
+
return encryption
|
|
72
|
+
_logger.info("workflow payload encryption is off")
|
|
73
|
+
legacy_mode = os.environ.get("WORKFLOWS_ENCRYPTION_MODE", "").strip()
|
|
74
|
+
if legacy_mode not in ("", "off"):
|
|
75
|
+
_logger.warning(
|
|
76
|
+
"WORKFLOWS_ENCRYPTION_MODE is no longer read, so payloads are not encrypted; set "
|
|
77
|
+
"TEMPORAL_PAYLOAD_ENCRYPTION__MODE and TEMPORAL_PAYLOAD_ENCRYPTION__MAIN_KEY to encrypt them",
|
|
78
|
+
workflows_encryption_mode=legacy_mode,
|
|
79
|
+
)
|
|
80
|
+
return None
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
_clients: dict[asyncio.AbstractEventLoop, asyncio.Task[Mistral]] = {}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
async def _build_client() -> Mistral:
|
|
87
|
+
client = Mistral(api_key=env.mistral_api_key, server_url=workflows_env.workflows_base_url)
|
|
88
|
+
encryption = payload_encryption()
|
|
89
|
+
if encryption is not None:
|
|
90
|
+
await configure_workflow_encoding(WorkflowEncodingConfig(payload_encryption=encryption), client=client)
|
|
91
|
+
return client
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
async def get_client() -> Mistral:
|
|
95
|
+
"""The Mistral client, with payload encoding installed before its first use.
|
|
96
|
+
|
|
97
|
+
The SDK keeps the encoding config on the client instance, so the configured client itself is
|
|
98
|
+
what is cached and reused: a fresh ``Mistral`` would carry no config and send cleartext. It is
|
|
99
|
+
built as one task per event loop, so concurrent first calls share one namespace lookup. A
|
|
100
|
+
failed build is evicted, not cached, so a transient blip does not brick the process; it is
|
|
101
|
+
re-raised because proceeding puts cleartext on the wire under ``full``.
|
|
102
|
+
"""
|
|
103
|
+
loop = asyncio.get_running_loop()
|
|
104
|
+
if (task := _clients.get(loop)) is None:
|
|
105
|
+
for other in list(_clients):
|
|
106
|
+
if other.is_closed():
|
|
107
|
+
_clients.pop(other, None)
|
|
108
|
+
task = _clients[loop] = loop.create_task(_build_client())
|
|
109
|
+
task.add_done_callback(_forget_failed)
|
|
110
|
+
return await asyncio.shield(task)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _forget_failed(task: asyncio.Task[Mistral]) -> None:
|
|
114
|
+
if (task.cancelled() or task.exception() is not None) and _clients.get(task.get_loop()) is task:
|
|
115
|
+
del _clients[task.get_loop()]
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _call(**kwargs: Any) -> dict[str, Any]:
|
|
119
|
+
"""The kwargs for one platform call: drop what the caller left unset.
|
|
120
|
+
|
|
121
|
+
Unset optionals are dropped because the SDK distinguishes an omitted parameter from an
|
|
122
|
+
explicit ``None``, which serializes as a null the server may reject.
|
|
123
|
+
"""
|
|
124
|
+
return {name: value for name, value in kwargs.items() if value is not None}
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class ScheduleTimingError(ValueError):
|
|
128
|
+
"""Raised when a schedule declares neither or both of an interval and a cron expression."""
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _validated_timing(interval_seconds: int | None, cron_expressions: list[str] | None) -> None:
|
|
132
|
+
if bool(interval_seconds) == bool(cron_expressions):
|
|
133
|
+
raise ScheduleTimingError(
|
|
134
|
+
"Provide exactly one of interval_seconds or cron_expressions. Prefer cron for a fixed "
|
|
135
|
+
"time of day: an interval is anchored to the epoch, so it drifts against wall-clock time."
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
@dataclass(frozen=True)
|
|
140
|
+
class WorkflowRun:
|
|
141
|
+
"""What starting a workflow gives back: always an id, a result only if we waited."""
|
|
142
|
+
|
|
143
|
+
execution_id: str
|
|
144
|
+
result: Any = None
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
@dataclass(frozen=True)
|
|
148
|
+
class WorkflowCapabilities:
|
|
149
|
+
"""The command handlers a workflow class declares, as names a caller may legitimately invoke."""
|
|
150
|
+
|
|
151
|
+
signals: tuple[str, ...]
|
|
152
|
+
queries: tuple[str, ...]
|
|
153
|
+
updates: tuple[str, ...]
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def workflow_capabilities(workflow_class: type) -> WorkflowCapabilities:
|
|
157
|
+
"""Which of signal, query and update a workflow actually answers.
|
|
158
|
+
|
|
159
|
+
Lets a caller-facing surface publish only the commands a workflow can serve. Framework-reserved
|
|
160
|
+
handlers are excluded: the reserved sets come from the SDK, so a new internal handler drops out
|
|
161
|
+
of the contract on the next bump. The SDK publishes no reserved-signal set, so every declared
|
|
162
|
+
signal belongs to the author. Raises the SDK's ``ValueError`` for a class never ``@workflow.define``d.
|
|
163
|
+
"""
|
|
164
|
+
definition = workflows.get_workflow_definition(workflow_class)
|
|
165
|
+
return WorkflowCapabilities(
|
|
166
|
+
signals=tuple(handler.name for handler in definition.signals),
|
|
167
|
+
queries=tuple(handler.name for handler in definition.queries if handler.name not in RESERVED_QUERY_NAMES),
|
|
168
|
+
updates=tuple(handler.name for handler in definition.updates if handler.name not in RESERVED_UPDATE_NAMES),
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def infer_workflow_models(workflow_class: type) -> tuple[type[BaseModel], Any | None]:
|
|
173
|
+
"""The request and response types a workflow's entrypoint declares.
|
|
174
|
+
|
|
175
|
+
Here rather than in a caller because it needs ``_ENTRYPOINT_MARKER``: ``WorkflowSpec``
|
|
176
|
+
publishes JSON schema, not the model classes. Raises ``ValueError`` like
|
|
177
|
+
:func:`workflow_capabilities`.
|
|
178
|
+
"""
|
|
179
|
+
entrypoint = next(
|
|
180
|
+
(
|
|
181
|
+
method
|
|
182
|
+
for _, method in inspect.getmembers(workflow_class, predicate=inspect.isfunction)
|
|
183
|
+
if getattr(method, _ENTRYPOINT_MARKER, False)
|
|
184
|
+
),
|
|
185
|
+
None,
|
|
186
|
+
)
|
|
187
|
+
if entrypoint is None:
|
|
188
|
+
raise ValueError(f"{workflow_class.__name__} has no workflow entrypoint")
|
|
189
|
+
|
|
190
|
+
original = inspect.unwrap(entrypoint)
|
|
191
|
+
hints = get_type_hints(original)
|
|
192
|
+
parameters = [parameter for name, parameter in inspect.signature(original).parameters.items() if name != "self"]
|
|
193
|
+
if len(parameters) != 1:
|
|
194
|
+
raise ValueError(f"{workflow_class.__name__} must take exactly one entrypoint argument, not {len(parameters)}")
|
|
195
|
+
|
|
196
|
+
request_type = hints.get(parameters[0].name)
|
|
197
|
+
if not inspect.isclass(request_type) or not issubclass(request_type, BaseModel):
|
|
198
|
+
raise ValueError(f"{workflow_class.__name__} entrypoint input must be a Pydantic model")
|
|
199
|
+
|
|
200
|
+
return request_type, hints.get("return")
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
async def start_workflow(
|
|
204
|
+
workflow_class: type,
|
|
205
|
+
workflow_input: BaseModel,
|
|
206
|
+
*,
|
|
207
|
+
wait_for_result: bool,
|
|
208
|
+
timeout_seconds: float | None = None,
|
|
209
|
+
execution_id: str | None = None,
|
|
210
|
+
) -> WorkflowRun:
|
|
211
|
+
"""Start a workflow through the remote execution API.
|
|
212
|
+
|
|
213
|
+
``exclude_unset`` matters: the input models give optional fields defaults the SDK also
|
|
214
|
+
defaults, and sending them explicitly is not the same request.
|
|
215
|
+
|
|
216
|
+
``execution_id`` lets a caller name the execution before it exists, which makes "authorise
|
|
217
|
+
first, then start" possible. Omitted, ``_call`` drops it and the platform generates one.
|
|
218
|
+
"""
|
|
219
|
+
response = await (await get_client()).workflows.execute_workflow_async(
|
|
220
|
+
**_call(
|
|
221
|
+
workflow_identifier=workflows.get_workflow_definition(workflow_class).name,
|
|
222
|
+
execution_id=execution_id,
|
|
223
|
+
input=workflow_input.model_dump(mode="json", exclude_unset=True),
|
|
224
|
+
wait_for_result=wait_for_result,
|
|
225
|
+
timeout_seconds=timeout_seconds,
|
|
226
|
+
deployment_name=workflows_env.deployment_name,
|
|
227
|
+
)
|
|
228
|
+
)
|
|
229
|
+
return WorkflowRun(execution_id=response.execution_id, result=getattr(response, "result", None))
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _configure_worker() -> None:
|
|
233
|
+
"""Point the SDK's module-level config at the app's own settings.
|
|
234
|
+
|
|
235
|
+
The SDK reads its settings from the environment when ``mistralai.workflows`` is imported,
|
|
236
|
+
which can be before ``env`` has loaded the repo-root ``.env``. Its own names differ too
|
|
237
|
+
(``SERVER_URL``), so without this the worker would poll the public host whatever
|
|
238
|
+
``WORKFLOWS_BASE_URL`` says, and run under whatever key and queue the SDK happened to see.
|
|
239
|
+
"""
|
|
240
|
+
worker = sdk_config.worker
|
|
241
|
+
worker.temporal_payload_encryption = payload_encryption()
|
|
242
|
+
# The agent client (and the telemetry endpoint derived from it) defaults to ``server_url`` at
|
|
243
|
+
# construction, so it only follows the move when nobody set it on purpose.
|
|
244
|
+
if worker.agent.mistral_client_server_url in (None, worker.server_url):
|
|
245
|
+
worker.agent.mistral_client_server_url = workflows_env.workflows_base_url
|
|
246
|
+
worker.server_url = workflows_env.workflows_base_url
|
|
247
|
+
if env.mistral_api_key:
|
|
248
|
+
sdk_config.common.mistral_api_key = SecretStr(env.mistral_api_key)
|
|
249
|
+
if workflows_env.deployment_name:
|
|
250
|
+
worker.deployment_name = _DEPLOYMENT_NAME.validate_python(workflows_env.deployment_name)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
async def run_worker(workflow_classes: list[type]) -> Any:
|
|
254
|
+
"""Run the worker, configured from our own settings.
|
|
255
|
+
|
|
256
|
+
The config is assigned immediately before delegating. ``workflows.run_worker`` deep-copies it
|
|
257
|
+
on entry and restores that copy on exit. Config discovery is on, so it authenticates from
|
|
258
|
+
``common.mistral_api_key``: its own ``api_key`` argument applies only with discovery off.
|
|
259
|
+
"""
|
|
260
|
+
_configure_worker()
|
|
261
|
+
return await workflows.run_worker(workflow_classes)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
async def pause_schedule_if_present(*, schedule_id: str, note: str) -> bool:
|
|
265
|
+
"""Pause an existing schedule; return False when there is nothing to pause.
|
|
266
|
+
|
|
267
|
+
Pausing rather than deleting keeps history and allows resume. A missing schedule surfaces as a
|
|
268
|
+
generic SDKError carrying a 404, not a typed not-found, so the status check is deliberate.
|
|
269
|
+
"""
|
|
270
|
+
schedules = (await get_client()).workflows.schedules
|
|
271
|
+
try:
|
|
272
|
+
await schedules.pause_schedule_async(**_call(schedule_id=schedule_id, note=note))
|
|
273
|
+
except MistralError as error:
|
|
274
|
+
if getattr(error, "status_code", None) != 404:
|
|
275
|
+
raise
|
|
276
|
+
return False
|
|
277
|
+
return True
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
async def upsert_schedule(
|
|
281
|
+
*,
|
|
282
|
+
schedule_id: str,
|
|
283
|
+
workflow_identifier: str,
|
|
284
|
+
input: dict[str, Any],
|
|
285
|
+
interval_seconds: int | None = None,
|
|
286
|
+
cron_expressions: list[str] | None = None,
|
|
287
|
+
pause_on_failure: bool = False,
|
|
288
|
+
deployment_name: str | None = None,
|
|
289
|
+
) -> Any:
|
|
290
|
+
"""Idempotently ensure a recurring workflow schedule exists and matches this config.
|
|
291
|
+
|
|
292
|
+
Timing is exactly one of ``interval_seconds`` or ``cron_expressions`` (5-field UTC cron); an
|
|
293
|
+
interval is anchored to the epoch and drifts. Re-running on every deploy converges, because the
|
|
294
|
+
platform resolves an existing ``schedule_id`` to an update. This cannot resume: no create or
|
|
295
|
+
update model carries ``paused``, so a paused schedule stays paused until a caller resumes it.
|
|
296
|
+
"""
|
|
297
|
+
_validated_timing(interval_seconds, cron_expressions)
|
|
298
|
+
schedules = (await get_client()).workflows.schedules
|
|
299
|
+
return await schedules.schedule_workflow_async(
|
|
300
|
+
**_call(
|
|
301
|
+
schedule=ScheduleDefinition(
|
|
302
|
+
schedule_id=schedule_id,
|
|
303
|
+
input=input,
|
|
304
|
+
intervals=[ScheduleInterval(every=f"PT{interval_seconds}S")] if interval_seconds else [],
|
|
305
|
+
cron_expressions=cron_expressions or [],
|
|
306
|
+
policy=SchedulePolicy(
|
|
307
|
+
overlap=ScheduleOverlapPolicy.SKIP,
|
|
308
|
+
catchup_window_seconds=_SCHEDULE_CATCHUP_SECONDS,
|
|
309
|
+
pause_on_failure=pause_on_failure,
|
|
310
|
+
),
|
|
311
|
+
),
|
|
312
|
+
workflow_identifier=workflow_identifier,
|
|
313
|
+
deployment_name=deployment_name,
|
|
314
|
+
)
|
|
315
|
+
)
|
|
File without changes
|