cosens-sdk 0.5.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.
- cosens_sdk-0.5.0/.gitignore +16 -0
- cosens_sdk-0.5.0/LICENSE +202 -0
- cosens_sdk-0.5.0/NOTICE +2 -0
- cosens_sdk-0.5.0/PKG-INFO +147 -0
- cosens_sdk-0.5.0/README.md +110 -0
- cosens_sdk-0.5.0/docs/api-reference.md +44 -0
- cosens_sdk-0.5.0/pyproject.toml +47 -0
- cosens_sdk-0.5.0/src/cosens/__init__.py +10 -0
- cosens_sdk-0.5.0/src/cosens/_config.py +34 -0
- cosens_sdk-0.5.0/src/cosens/_structured.py +41 -0
- cosens_sdk-0.5.0/src/cosens/agents_adapter.py +118 -0
- cosens_sdk-0.5.0/src/cosens/atoms.py +167 -0
- cosens_sdk-0.5.0/src/cosens/atoms_helpers.py +27 -0
- cosens_sdk-0.5.0/src/cosens/auto_execution.py +251 -0
- cosens_sdk-0.5.0/src/cosens/auto_learning.py +132 -0
- cosens_sdk-0.5.0/src/cosens/context_render.py +128 -0
- cosens_sdk-0.5.0/src/cosens/decision.py +113 -0
- cosens_sdk-0.5.0/src/cosens/document_atoms.py +123 -0
- cosens_sdk-0.5.0/src/cosens/errors.py +78 -0
- cosens_sdk-0.5.0/src/cosens/factory.py +81 -0
- cosens_sdk-0.5.0/src/cosens/http.py +128 -0
- cosens_sdk-0.5.0/src/cosens/models.py +28 -0
- cosens_sdk-0.5.0/src/cosens/openai_proxy.py +1101 -0
- cosens_sdk-0.5.0/src/cosens/responses_adapter.py +117 -0
- cosens_sdk-0.5.0/src/cosens/session_cursor.py +240 -0
- cosens_sdk-0.5.0/src/cosens/state.py +107 -0
- cosens_sdk-0.5.0/src/cosens/task_runner.py +549 -0
- cosens_sdk-0.5.0/src/cosens/workflow.py +29 -0
- cosens_sdk-0.5.0/src/cosens/workflow_atoms.py +359 -0
- cosens_sdk-0.5.0/src/cosens/workflow_start.py +79 -0
cosens_sdk-0.5.0/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
cosens_sdk-0.5.0/NOTICE
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: cosens-sdk
|
|
3
|
+
Version: 0.5.0
|
|
4
|
+
Summary: CoSens Python SDK: record OpenAI and OpenAI Agents executions and generate reusable Recipes
|
|
5
|
+
Project-URL: Homepage, https://cosens.ai/
|
|
6
|
+
Project-URL: Documentation, https://cosens.ai/docs/
|
|
7
|
+
Project-URL: Repository, https://github.com/PreSeen/CoSens-SDK
|
|
8
|
+
Project-URL: Issues, https://github.com/PreSeen/CoSens-SDK/issues
|
|
9
|
+
License-Expression: Apache-2.0
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
License-File: NOTICE
|
|
12
|
+
Keywords: agents,cosens,llm,openai,recipes
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
22
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
23
|
+
Requires-Python: >=3.10
|
|
24
|
+
Requires-Dist: httpx<1,>=0.27
|
|
25
|
+
Requires-Dist: openai<2.55,>=2.54
|
|
26
|
+
Provides-Extra: agents
|
|
27
|
+
Requires-Dist: openai-agents<0.21,>=0.20; extra == 'agents'
|
|
28
|
+
Provides-Extra: examples
|
|
29
|
+
Requires-Dist: openai-agents<0.21,>=0.20; extra == 'examples'
|
|
30
|
+
Requires-Dist: python-dotenv<2,>=1; extra == 'examples'
|
|
31
|
+
Provides-Extra: test
|
|
32
|
+
Requires-Dist: build>=1; extra == 'test'
|
|
33
|
+
Requires-Dist: hatchling>=1.27; extra == 'test'
|
|
34
|
+
Requires-Dist: pytest-asyncio>=0.24; extra == 'test'
|
|
35
|
+
Requires-Dist: pytest>=8; extra == 'test'
|
|
36
|
+
Description-Content-Type: text/markdown
|
|
37
|
+
|
|
38
|
+
# CoSens Python SDK
|
|
39
|
+
|
|
40
|
+
CoSens records the tasks your application runs through an OpenAI client or an OpenAI Agents agent, and turns a confirmed result into a reusable Recipe.
|
|
41
|
+
|
|
42
|
+
## Install
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
pip install cosens-sdk
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
For OpenAI Agents support: `pip install 'cosens-sdk[agents]'`. Requires Python 3.10+.
|
|
49
|
+
|
|
50
|
+
## Configure
|
|
51
|
+
|
|
52
|
+
| Variable | Read by | Value |
|
|
53
|
+
| --- | --- | --- |
|
|
54
|
+
| `COSENS_API_KEY` | SDK and your model client | Your CoSens API Key |
|
|
55
|
+
| `COSENS_REGION` | SDK | `us` (default and only supported value) |
|
|
56
|
+
| `COSENS_MODEL_BASE_URL` | Your model client | `https://llm.cosens.ai/v1` |
|
|
57
|
+
|
|
58
|
+
The SDK reads the process environment; load any `.env` file in your application. The model IDs you can use are listed in the [CoSens documentation](https://cosens.ai/docs/).
|
|
59
|
+
|
|
60
|
+
## Wrap an OpenAI client
|
|
61
|
+
|
|
62
|
+
Build a standard OpenAI client for your model gateway and pass it to `cosens(...)`:
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
import os
|
|
66
|
+
|
|
67
|
+
from openai import OpenAI
|
|
68
|
+
from cosens import cosens
|
|
69
|
+
|
|
70
|
+
model_client = OpenAI(base_url=os.environ["COSENS_MODEL_BASE_URL"], api_key=os.environ["COSENS_API_KEY"])
|
|
71
|
+
client = cosens(model_client, mode="auto")
|
|
72
|
+
result = client.responses.create(model="<public-model-id>", input="Produce a report")
|
|
73
|
+
turn_id = client.cosens.last_turn_id
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
The response is the native OpenAI result. `AsyncOpenAI` works the same way and exposes async CoSens calls.
|
|
77
|
+
|
|
78
|
+
In `auto` mode the SDK first makes a short structured decision call through your client (Chat Completions with a JSON schema `response_format`), so the model must support structured output. The model writes only `{"activate": ..., "reason": ...}`; the task objective is your user's text. The call is made once, without retries, with a 5-second timeout and a 1024-token output budget (reasoning included). If the decision or the read-only Recipe lookup fails or times out, your request still runs without CoSens capture, and the turn records why: `client.cosens.get_turn(client.cosens.last_turn_id)` has `capture == "decision_failed"` with `decision["error_type"]` and `decision["error"]` (for example a timeout, a gateway error, or output cut off at the token limit). A request without user text is skipped without a model call (`capture == "no_user_text"`).
|
|
79
|
+
|
|
80
|
+
| Option | Default | Effect |
|
|
81
|
+
| --- | --- | --- |
|
|
82
|
+
| `decision_timeout` | `5` | Seconds allowed for the decision and Recipe-match calls |
|
|
83
|
+
| `decision_max_output_tokens` | `1024` | Output budget, reasoning included, for the decision and Recipe-match calls |
|
|
84
|
+
| `decision_client` | the wrapped client | Separate `OpenAI` / `AsyncOpenAI` client (matching the wrapped one) for those calls, e.g. a small fast model |
|
|
85
|
+
| `decision_extra_body` | none | Extra request body for those calls, e.g. `{"enable_thinking": False}` |
|
|
86
|
+
| `max_context_chars` | `4000` | Upper bound for the Recipe/Memory text added to a request or Agent instructions |
|
|
87
|
+
|
|
88
|
+
Both models above reason before answering, which is why the budget is not smaller. Reasoning models that think longer can still hit the timeout or the token budget; the turn then records `decision_failed` with the cause. Use a small non-reasoning `decision_model` (or a separate `decision_client`), raise `decision_timeout` / `decision_max_output_tokens`, or switch reasoning off with `decision_extra_body` if your gateway accepts such a field (vLLM accepts `{"chat_template_kwargs": {"enable_thinking": False}}`; the LiteLLM gateway above rejects it with HTTP 500, which also records `decision_failed`).
|
|
89
|
+
|
|
90
|
+
Measured on 2026-11-06 with the SDK's own decision request (output tokens include reasoning):
|
|
91
|
+
|
|
92
|
+
| Model (gateway) | Decision tokens p50 / max | With linked feedback, max | Success at defaults | Decision latency p50 / max |
|
|
93
|
+
| --- | --- | --- | --- | --- |
|
|
94
|
+
| `deepseek-flash` (llm.cosens.ai) | 50 / 139 | 294 | 24 / 24 | 1.6 s / 3.7 s |
|
|
95
|
+
| `qwen3.8-27b` (vLLM via LiteLLM) | 189 / 469 | 337 | 23 / 24 (one 5 s timeout) | 1.6 s / 5.0 s |
|
|
96
|
+
|
|
97
|
+
The default budget leaves more than 3x headroom over the largest reply measured on the default model.
|
|
98
|
+
|
|
99
|
+
If the decision activates, a Recipe-match call picks a usable Recipe with the same limits. A match that times out or is cut off does not stop the capture: the turn is recorded without a Recipe and `turn["recipe_match_error"]` says why. With 20 usable Recipes, `deepseek-flash` matched within 5 s in 9 of 12 measured calls.
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
client = cosens(model_client, mode="auto", decision_model="<small-non-reasoning-model-id>")
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
When a usable Recipe matches, the SDK adds it as plain text: its title, when/when-not, numbered steps, related Memory text and, if room remains, lesson actions. The block never exceeds `max_context_chars`; a final line states what was omitted. A list with no usable Recipe is remembered for 60 seconds, so routine requests skip the lookup.
|
|
106
|
+
|
|
107
|
+
## Generate a Recipe after confirmation
|
|
108
|
+
|
|
109
|
+
Check that the turn has a submitted Revision before offering Recipe generation. After your application obtains user confirmation of that artifact, call from its confirmation handler:
|
|
110
|
+
|
|
111
|
+
```python
|
|
112
|
+
turn = client.cosens.get_turn(turn_id) if turn_id else None
|
|
113
|
+
if turn and turn.get("revision_id"):
|
|
114
|
+
receipt = client.cosens.generate_recipe(turn_id, request_key="confirmed-report-1")
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
This is the only generation action. It creates the first Recipe version or updates the associated Recipe, always reads relevant Memory, and performs feedback attribution internally. `feedback` records feedback; it does not update a Recipe.
|
|
118
|
+
|
|
119
|
+
`client.cosens.wait_learning(turn_id)` raises `cosens.RSICandidateFailed` when generation fails. The error has `code`, `phase`, `retryable`, `upstream_status`, `upstream_code`, `candidate_id` and `request_id`. When `retryable` is true, `client.cosens.resume_learning(turn_id)` retries the same candidate. Older servers report only `code`; `retryable` is then `None`.
|
|
120
|
+
|
|
121
|
+
## Run an OpenAI Agents agent
|
|
122
|
+
|
|
123
|
+
```python
|
|
124
|
+
import os
|
|
125
|
+
|
|
126
|
+
from agents import Agent, set_default_openai_client
|
|
127
|
+
from openai import AsyncOpenAI
|
|
128
|
+
from cosens import cosens
|
|
129
|
+
|
|
130
|
+
set_default_openai_client(AsyncOpenAI(base_url=os.environ["COSENS_MODEL_BASE_URL"], api_key=os.environ["COSENS_API_KEY"]))
|
|
131
|
+
agent = Agent(name="assistant", instructions="Complete the requested task.", model="<public-model-id>")
|
|
132
|
+
client = cosens(agent, mode="auto")
|
|
133
|
+
result = await client.run(agent, "Produce a report")
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
## Atomic operations
|
|
137
|
+
|
|
138
|
+
`CoSensClient().atoms` (async) and `.sync_atoms` (sync) expose Task, Execution, Revision, feedback, Recipe, Session and Memory operations directly. Keep stable idempotency keys across retries.
|
|
139
|
+
|
|
140
|
+
- Returned JSON objects are dicts with a `request_id` attribute holding the response's `x-request-id`, for support requests.
|
|
141
|
+
- `start_recipe_candidate(task_id, revision_id=...)` may omit `key`; the default is derived from the task, revision and `max_completion_tokens`, so repeating the call returns the same candidate.
|
|
142
|
+
- `wait_workflow_job("recipe_candidate", id)` raises `RSICandidateFailed` when the candidate failed.
|
|
143
|
+
|
|
144
|
+
## More
|
|
145
|
+
|
|
146
|
+
- Documentation: https://cosens.ai/docs/
|
|
147
|
+
- Source, examples and issues: https://github.com/PreSeen/CoSens-SDK
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
# CoSens Python SDK
|
|
2
|
+
|
|
3
|
+
CoSens records the tasks your application runs through an OpenAI client or an OpenAI Agents agent, and turns a confirmed result into a reusable Recipe.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install cosens-sdk
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
For OpenAI Agents support: `pip install 'cosens-sdk[agents]'`. Requires Python 3.10+.
|
|
12
|
+
|
|
13
|
+
## Configure
|
|
14
|
+
|
|
15
|
+
| Variable | Read by | Value |
|
|
16
|
+
| --- | --- | --- |
|
|
17
|
+
| `COSENS_API_KEY` | SDK and your model client | Your CoSens API Key |
|
|
18
|
+
| `COSENS_REGION` | SDK | `us` (default and only supported value) |
|
|
19
|
+
| `COSENS_MODEL_BASE_URL` | Your model client | `https://llm.cosens.ai/v1` |
|
|
20
|
+
|
|
21
|
+
The SDK reads the process environment; load any `.env` file in your application. The model IDs you can use are listed in the [CoSens documentation](https://cosens.ai/docs/).
|
|
22
|
+
|
|
23
|
+
## Wrap an OpenAI client
|
|
24
|
+
|
|
25
|
+
Build a standard OpenAI client for your model gateway and pass it to `cosens(...)`:
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
import os
|
|
29
|
+
|
|
30
|
+
from openai import OpenAI
|
|
31
|
+
from cosens import cosens
|
|
32
|
+
|
|
33
|
+
model_client = OpenAI(base_url=os.environ["COSENS_MODEL_BASE_URL"], api_key=os.environ["COSENS_API_KEY"])
|
|
34
|
+
client = cosens(model_client, mode="auto")
|
|
35
|
+
result = client.responses.create(model="<public-model-id>", input="Produce a report")
|
|
36
|
+
turn_id = client.cosens.last_turn_id
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
The response is the native OpenAI result. `AsyncOpenAI` works the same way and exposes async CoSens calls.
|
|
40
|
+
|
|
41
|
+
In `auto` mode the SDK first makes a short structured decision call through your client (Chat Completions with a JSON schema `response_format`), so the model must support structured output. The model writes only `{"activate": ..., "reason": ...}`; the task objective is your user's text. The call is made once, without retries, with a 5-second timeout and a 1024-token output budget (reasoning included). If the decision or the read-only Recipe lookup fails or times out, your request still runs without CoSens capture, and the turn records why: `client.cosens.get_turn(client.cosens.last_turn_id)` has `capture == "decision_failed"` with `decision["error_type"]` and `decision["error"]` (for example a timeout, a gateway error, or output cut off at the token limit). A request without user text is skipped without a model call (`capture == "no_user_text"`).
|
|
42
|
+
|
|
43
|
+
| Option | Default | Effect |
|
|
44
|
+
| --- | --- | --- |
|
|
45
|
+
| `decision_timeout` | `5` | Seconds allowed for the decision and Recipe-match calls |
|
|
46
|
+
| `decision_max_output_tokens` | `1024` | Output budget, reasoning included, for the decision and Recipe-match calls |
|
|
47
|
+
| `decision_client` | the wrapped client | Separate `OpenAI` / `AsyncOpenAI` client (matching the wrapped one) for those calls, e.g. a small fast model |
|
|
48
|
+
| `decision_extra_body` | none | Extra request body for those calls, e.g. `{"enable_thinking": False}` |
|
|
49
|
+
| `max_context_chars` | `4000` | Upper bound for the Recipe/Memory text added to a request or Agent instructions |
|
|
50
|
+
|
|
51
|
+
Both models above reason before answering, which is why the budget is not smaller. Reasoning models that think longer can still hit the timeout or the token budget; the turn then records `decision_failed` with the cause. Use a small non-reasoning `decision_model` (or a separate `decision_client`), raise `decision_timeout` / `decision_max_output_tokens`, or switch reasoning off with `decision_extra_body` if your gateway accepts such a field (vLLM accepts `{"chat_template_kwargs": {"enable_thinking": False}}`; the LiteLLM gateway above rejects it with HTTP 500, which also records `decision_failed`).
|
|
52
|
+
|
|
53
|
+
Measured on 2026-11-06 with the SDK's own decision request (output tokens include reasoning):
|
|
54
|
+
|
|
55
|
+
| Model (gateway) | Decision tokens p50 / max | With linked feedback, max | Success at defaults | Decision latency p50 / max |
|
|
56
|
+
| --- | --- | --- | --- | --- |
|
|
57
|
+
| `deepseek-flash` (llm.cosens.ai) | 50 / 139 | 294 | 24 / 24 | 1.6 s / 3.7 s |
|
|
58
|
+
| `qwen3.8-27b` (vLLM via LiteLLM) | 189 / 469 | 337 | 23 / 24 (one 5 s timeout) | 1.6 s / 5.0 s |
|
|
59
|
+
|
|
60
|
+
The default budget leaves more than 3x headroom over the largest reply measured on the default model.
|
|
61
|
+
|
|
62
|
+
If the decision activates, a Recipe-match call picks a usable Recipe with the same limits. A match that times out or is cut off does not stop the capture: the turn is recorded without a Recipe and `turn["recipe_match_error"]` says why. With 20 usable Recipes, `deepseek-flash` matched within 5 s in 9 of 12 measured calls.
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
client = cosens(model_client, mode="auto", decision_model="<small-non-reasoning-model-id>")
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
When a usable Recipe matches, the SDK adds it as plain text: its title, when/when-not, numbered steps, related Memory text and, if room remains, lesson actions. The block never exceeds `max_context_chars`; a final line states what was omitted. A list with no usable Recipe is remembered for 60 seconds, so routine requests skip the lookup.
|
|
69
|
+
|
|
70
|
+
## Generate a Recipe after confirmation
|
|
71
|
+
|
|
72
|
+
Check that the turn has a submitted Revision before offering Recipe generation. After your application obtains user confirmation of that artifact, call from its confirmation handler:
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
turn = client.cosens.get_turn(turn_id) if turn_id else None
|
|
76
|
+
if turn and turn.get("revision_id"):
|
|
77
|
+
receipt = client.cosens.generate_recipe(turn_id, request_key="confirmed-report-1")
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
This is the only generation action. It creates the first Recipe version or updates the associated Recipe, always reads relevant Memory, and performs feedback attribution internally. `feedback` records feedback; it does not update a Recipe.
|
|
81
|
+
|
|
82
|
+
`client.cosens.wait_learning(turn_id)` raises `cosens.RSICandidateFailed` when generation fails. The error has `code`, `phase`, `retryable`, `upstream_status`, `upstream_code`, `candidate_id` and `request_id`. When `retryable` is true, `client.cosens.resume_learning(turn_id)` retries the same candidate. Older servers report only `code`; `retryable` is then `None`.
|
|
83
|
+
|
|
84
|
+
## Run an OpenAI Agents agent
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
import os
|
|
88
|
+
|
|
89
|
+
from agents import Agent, set_default_openai_client
|
|
90
|
+
from openai import AsyncOpenAI
|
|
91
|
+
from cosens import cosens
|
|
92
|
+
|
|
93
|
+
set_default_openai_client(AsyncOpenAI(base_url=os.environ["COSENS_MODEL_BASE_URL"], api_key=os.environ["COSENS_API_KEY"]))
|
|
94
|
+
agent = Agent(name="assistant", instructions="Complete the requested task.", model="<public-model-id>")
|
|
95
|
+
client = cosens(agent, mode="auto")
|
|
96
|
+
result = await client.run(agent, "Produce a report")
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
## Atomic operations
|
|
100
|
+
|
|
101
|
+
`CoSensClient().atoms` (async) and `.sync_atoms` (sync) expose Task, Execution, Revision, feedback, Recipe, Session and Memory operations directly. Keep stable idempotency keys across retries.
|
|
102
|
+
|
|
103
|
+
- Returned JSON objects are dicts with a `request_id` attribute holding the response's `x-request-id`, for support requests.
|
|
104
|
+
- `start_recipe_candidate(task_id, revision_id=...)` may omit `key`; the default is derived from the task, revision and `max_completion_tokens`, so repeating the call returns the same candidate.
|
|
105
|
+
- `wait_workflow_job("recipe_candidate", id)` raises `RSICandidateFailed` when the candidate failed.
|
|
106
|
+
|
|
107
|
+
## More
|
|
108
|
+
|
|
109
|
+
- Documentation: https://cosens.ai/docs/
|
|
110
|
+
- Source, examples and issues: https://github.com/PreSeen/CoSens-SDK
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# Current algorithm API
|
|
2
|
+
|
|
3
|
+
`CoSensClient.atoms` is async; `.sync_atoms` offers the same operations synchronously. Identity comes from authentication.
|
|
4
|
+
|
|
5
|
+
| Operation | Python method |
|
|
6
|
+
| --- | --- |
|
|
7
|
+
| Artifact upload/read | `artifact`, `get_artifact` |
|
|
8
|
+
| Task create/list/read/context | `create_task`, `list_tasks`, `get_task`, `supplement_task_context` |
|
|
9
|
+
| Prepare/read execution | `start_execution`, `get_execution` |
|
|
10
|
+
| Submit/read revision | `submit_execution`, `get_revision` |
|
|
11
|
+
| Feedback/correction | `record_feedback`, `start_revision` |
|
|
12
|
+
| Explicit Recipe generation/update | `start_recipe_candidate(task_id, revision_id=..., key=None, model=..., max_completion_tokens=...)` |
|
|
13
|
+
| Read/list/resume generation | `get_recipe_candidate`, `list_recipe_candidates`, `resume_recipe_candidate` |
|
|
14
|
+
| Associated Recipe/version chain | `get_task_recipe`, `get_recipe_versions` |
|
|
15
|
+
| Poll generation | `wait_workflow_job("recipe_candidate", id)` (raises `RSICandidateFailed` on failure) |
|
|
16
|
+
| Sessions | `start_session`, `append_session_events`, `get_session_context`, `end_session` |
|
|
17
|
+
| Memory | `user_get`, `memory_recall`, `memory_get`, `timeline_get`, `memory_write`, `memory_delete`, `document_upload` |
|
|
18
|
+
|
|
19
|
+
Call generation only after external artifact confirmation. It creates V1 if no Recipe exists, otherwise a new version. Related Memory is read only when the execution behind the revision was started with `recall_memory=True`; generation has no Memory parameter. `record_feedback` requires `source`: `human`, `evaluator`, `reference`, `automated_check` or `downstream`. Feedback attribution happens inside generation. A failed candidate does not replace the usable current version. Resume retries the same candidate; polling does not create one.
|
|
20
|
+
|
|
21
|
+
`create_task` requires `source="new_task"` or `source="external_artifact"`. `start_revision` takes the previous revision and a request key, without an attribution ID. `submit_execution` takes the exact frozen request SHA, actual outcome, artifacts and optional events. Stable keys and event IDs are required for reliable retries. The public model ID is supplied with `model`. Model calls reuse the existing Authorization API Key, with the gateway URL and auth type determined internally. There is no `model_api` connection object or second credential.
|
|
22
|
+
|
|
23
|
+
Without `key`, `start_recipe_candidate` uses `"recipe-" + sha256("recipe:<task_id>:<revision_id>:<max_completion_tokens or empty>")`, the same key the TypeScript SDK derives. A failed candidate raises `RSICandidateFailed` from the wait helpers with the service's stable `code`, `phase`, `retryable`, `upstream_status` and `upstream_code` (from `error_detail`; older servers give only `code`). Every returned JSON object exposes the response's `x-request-id` as `.request_id`.
|
|
24
|
+
|
|
25
|
+
Current HTTP and MCP schemas are supplied by the algorithm service. Old Run, attribution, acceptance, rubric, learning-job and administrative Recipe publication operations are absent.
|
|
26
|
+
|
|
27
|
+
### Recipe completion budget
|
|
28
|
+
|
|
29
|
+
`start_recipe_candidate(..., max_completion_tokens=200000)` and
|
|
30
|
+
`resume_recipe_candidate(..., max_completion_tokens=300000)` accept an optional integer
|
|
31
|
+
from 1 through 1,000,000. Omitting it leaves the initial default to the algorithm service
|
|
32
|
+
(200,000 in the updated service); a resumed candidate keeps its stored budget unless
|
|
33
|
+
explicitly overridden. The same budget applies to both feedback attribution and Recipe
|
|
34
|
+
creation/update. Model/gateway limits still apply; an accepted SDK value is not a promise
|
|
35
|
+
that every upstream model supports it.
|
|
36
|
+
|
|
37
|
+
The sync/async auto wrapper exposes the same option on
|
|
38
|
+
`client.cosens.generate_recipe(turn_id, max_completion_tokens=200000)` and
|
|
39
|
+
`client.cosens.resume_learning(turn_id, max_completion_tokens=300000)`. Task/Agent Runner
|
|
40
|
+
wrappers forward it from `generate_recipe` as well. It does not change business response
|
|
41
|
+
limits or `decision_max_output_tokens`. Reusing a generation key with a different explicit
|
|
42
|
+
budget is rejected; use resume to adjust a failed candidate, or a new generation key for
|
|
43
|
+
a new version. The Recipe service must be upgraded before using this field; older servers
|
|
44
|
+
reject unknown request fields. Published packages are not updated by a source checkout.
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.27"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "cosens-sdk"
|
|
7
|
+
version = "0.5.0"
|
|
8
|
+
description = "CoSens Python SDK: record OpenAI and OpenAI Agents executions and generate reusable Recipes"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "Apache-2.0"
|
|
11
|
+
license-files = ["LICENSE", "NOTICE"]
|
|
12
|
+
requires-python = ">=3.10"
|
|
13
|
+
dependencies = ["httpx>=0.27,<1", "openai>=2.54,<2.55"]
|
|
14
|
+
keywords = ["cosens", "openai", "agents", "llm", "recipes"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
21
|
+
"Programming Language :: Python :: 3.10",
|
|
22
|
+
"Programming Language :: Python :: 3.11",
|
|
23
|
+
"Programming Language :: Python :: 3.12",
|
|
24
|
+
"Programming Language :: Python :: 3.13",
|
|
25
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
[project.urls]
|
|
29
|
+
Homepage = "https://cosens.ai/"
|
|
30
|
+
Documentation = "https://cosens.ai/docs/"
|
|
31
|
+
Repository = "https://github.com/PreSeen/CoSens-SDK"
|
|
32
|
+
Issues = "https://github.com/PreSeen/CoSens-SDK/issues"
|
|
33
|
+
|
|
34
|
+
[project.optional-dependencies]
|
|
35
|
+
agents = ["openai-agents>=0.20,<0.21"]
|
|
36
|
+
examples = ["openai-agents>=0.20,<0.21", "python-dotenv>=1,<2"]
|
|
37
|
+
test = ["pytest>=8", "pytest-asyncio>=0.24", "build>=1", "hatchling>=1.27"]
|
|
38
|
+
|
|
39
|
+
[tool.hatch.build.targets.wheel]
|
|
40
|
+
packages = ["src/cosens"]
|
|
41
|
+
|
|
42
|
+
[tool.hatch.build.targets.sdist]
|
|
43
|
+
only-include = ["src/cosens", "README.md", "LICENSE", "NOTICE", "pyproject.toml", "docs/api-reference.md"]
|
|
44
|
+
|
|
45
|
+
[tool.pytest.ini_options]
|
|
46
|
+
testpaths = ["tests"]
|
|
47
|
+
asyncio_mode = "auto"
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""CoSens Python SDK public API."""
|
|
2
|
+
|
|
3
|
+
from .atoms import CoSensClient
|
|
4
|
+
from .auto_learning import AutoLearning
|
|
5
|
+
from .errors import RSICandidateFailed, RSIError, RSIHTTPError, RSIRecoveryRequired
|
|
6
|
+
from .factory import cosens
|
|
7
|
+
from .task_runner import TaskWorkflowRunner
|
|
8
|
+
|
|
9
|
+
__all__ = ["AutoLearning", "CoSensClient", "RSICandidateFailed", "RSIError", "RSIHTTPError", "RSIRecoveryRequired",
|
|
10
|
+
"TaskWorkflowRunner", "cosens"]
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Private, allowlisted service endpoints. No public arbitrary base_url option."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@dataclass(frozen=True)
|
|
8
|
+
class Service:
|
|
9
|
+
region: str
|
|
10
|
+
url: str
|
|
11
|
+
identity: str
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
_SERVICES = {
|
|
15
|
+
'us': Service('us', 'https://rsi.cosens.ai/api', 'rsi.cosens.ai/api'),
|
|
16
|
+
}
|
|
17
|
+
SERVICE_URL = _SERVICES['us'].url
|
|
18
|
+
SERVICE_ID = _SERVICES['us'].identity
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def resolve_service(region=None):
|
|
22
|
+
region = os.getenv('COSENS_REGION', 'us') if region is None else region
|
|
23
|
+
if not isinstance(region, str):
|
|
24
|
+
raise ValueError('region must be us')
|
|
25
|
+
region = region.strip().lower()
|
|
26
|
+
if region not in _SERVICES:
|
|
27
|
+
raise ValueError('COSENS_REGION must be us')
|
|
28
|
+
return _SERVICES[region]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def resolve_api_key(api_key):
|
|
32
|
+
if api_key is not None:
|
|
33
|
+
return api_key
|
|
34
|
+
return os.getenv('COSENS_API_KEY')
|