agentcompile 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.
@@ -0,0 +1,21 @@
1
+ name: CI
2
+ on:
3
+ push:
4
+ branches: [main]
5
+ pull_request:
6
+
7
+ jobs:
8
+ test:
9
+ runs-on: ubuntu-latest
10
+ strategy:
11
+ fail-fast: false
12
+ matrix:
13
+ python: ["3.9", "3.10", "3.11", "3.12", "3.13"]
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+ - uses: actions/setup-python@v5
17
+ with:
18
+ python-version: ${{ matrix.python }}
19
+ - run: pip install -e ".[dev]" ruff
20
+ - run: ruff check src tests && ruff format --check src tests
21
+ - run: pytest -q
@@ -0,0 +1,21 @@
1
+ # Publishes to PyPI when a version tag (v0.1.1, ...) is pushed. Uses PyPI trusted publishing:
2
+ # add this repo and workflow (publish.yml, environment "pypi") as a trusted publisher on the
3
+ # agentcompile project at pypi.org, so no token is stored here.
4
+ name: Publish
5
+ on:
6
+ push:
7
+ tags: ["v*"]
8
+
9
+ jobs:
10
+ publish:
11
+ runs-on: ubuntu-latest
12
+ environment: pypi
13
+ permissions:
14
+ id-token: write
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+ - uses: actions/setup-python@v5
18
+ with:
19
+ python-version: "3.12"
20
+ - run: pip install build && python -m build
21
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,7 @@
1
+ __pycache__/
2
+ *.egg-info/
3
+ dist/
4
+ build/
5
+ .venv/
6
+ .pytest_cache/
7
+ .ruff_cache/
@@ -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.
@@ -0,0 +1,87 @@
1
+ Metadata-Version: 2.5
2
+ Name: agentcompile
3
+ Version: 0.1.0
4
+ Summary: Wrap your agent's model client: repeated jobs run compiled, everything else goes to your model unchanged.
5
+ Project-URL: Homepage, https://tryagentcompile.com
6
+ Author-email: AgentCompile <founders@tryagentcompile.com>
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Software Development :: Libraries
13
+ Requires-Python: >=3.9
14
+ Requires-Dist: httpx>=0.25
15
+ Provides-Extra: anthropic
16
+ Requires-Dist: anthropic>=0.40; extra == 'anthropic'
17
+ Provides-Extra: dev
18
+ Requires-Dist: anthropic>=0.40; extra == 'dev'
19
+ Requires-Dist: openai>=1.0; extra == 'dev'
20
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
21
+ Requires-Dist: pytest>=8; extra == 'dev'
22
+ Provides-Extra: openai
23
+ Requires-Dist: openai>=1.0; extra == 'openai'
24
+ Description-Content-Type: text/markdown
25
+
26
+ # agentcompile
27
+
28
+ ```
29
+ pip install agentcompile
30
+ ```
31
+
32
+ Wrap your agent's model client. Jobs your agent repeats run compiled, with no model call; everything else goes to your model unchanged, with your own provider key.
33
+
34
+ ```python
35
+ from openai import OpenAI
36
+ import agentcompile
37
+
38
+ client = agentcompile.wrap(OpenAI(), key="ack_...") # or AGENTCOMPILE_KEY
39
+
40
+ resp = client.chat.completions.create(
41
+ model="gpt-5", messages=messages, tools=tools,
42
+ conversation_id=ticket.id, # one id per conversation
43
+ )
44
+ ```
45
+
46
+ Anthropic works the same way (`agentcompile.wrap(Anthropic())`, then `client.messages.create(...)`). So do async clients, streaming and tool calls. Instead of the keyword, you can set the id for a block of calls:
47
+
48
+ ```python
49
+ with agentcompile.conversation(ticket.id):
50
+ run_agent(client)
51
+ ```
52
+
53
+ ## What happens on each call
54
+
55
+ 1. With a conversation id, the SDK asks AgentCompile for a decision (`/v1/decide`; it waits at most `timeout`, default 2 s).
56
+ 2. **compiled**: the answer (a tool call or a reply) comes back in exactly the provider's response shape; your loop runs the tool as usual.
57
+ 3. **forwarded**: your model is called as normal.
58
+ 4. **fail-open**: AgentCompile errored, was slow or sent something unusable, so your model is called as normal.
59
+ 5. **no conversation id**: your model is called and no decision is made.
60
+
61
+ Your provider key never leaves your process. `mode="shadow"` decides but always calls your model, so you can see what it would have done before you switch it on.
62
+
63
+ ## The trail
64
+
65
+ Every call is written to `~/.agentcompile/trail.jsonl` (`trail=` sets a path, or `False` turns it off; `on_event=` gets each event).
66
+
67
+ ```
68
+ agentcompile trail # recent calls and a summary
69
+ agentcompile trail -f # follow live
70
+ ```
71
+
72
+ ```
73
+ 14:02:11 c1 compiled get_order_details gpt-5 48 ms decide
74
+ 14:02:12 c2 forwarded no job matched gpt-5 51 ms decide
75
+ 2 calls: compiled 1, forwarded 1. Model calls avoided: 1 (50%).
76
+ ```
77
+
78
+ ## Keys
79
+
80
+ Your AgentCompile key (`ack_...`) identifies your company by itself. We show it once and store only its hash; a new key revokes the old one. AgentCompile is pre-launch: to get a key, write to founders@tryagentcompile.com.
81
+
82
+ ## Development
83
+
84
+ ```
85
+ pip install -e ".[dev]"
86
+ pytest tests
87
+ ```
@@ -0,0 +1,62 @@
1
+ # agentcompile
2
+
3
+ ```
4
+ pip install agentcompile
5
+ ```
6
+
7
+ Wrap your agent's model client. Jobs your agent repeats run compiled, with no model call; everything else goes to your model unchanged, with your own provider key.
8
+
9
+ ```python
10
+ from openai import OpenAI
11
+ import agentcompile
12
+
13
+ client = agentcompile.wrap(OpenAI(), key="ack_...") # or AGENTCOMPILE_KEY
14
+
15
+ resp = client.chat.completions.create(
16
+ model="gpt-5", messages=messages, tools=tools,
17
+ conversation_id=ticket.id, # one id per conversation
18
+ )
19
+ ```
20
+
21
+ Anthropic works the same way (`agentcompile.wrap(Anthropic())`, then `client.messages.create(...)`). So do async clients, streaming and tool calls. Instead of the keyword, you can set the id for a block of calls:
22
+
23
+ ```python
24
+ with agentcompile.conversation(ticket.id):
25
+ run_agent(client)
26
+ ```
27
+
28
+ ## What happens on each call
29
+
30
+ 1. With a conversation id, the SDK asks AgentCompile for a decision (`/v1/decide`; it waits at most `timeout`, default 2 s).
31
+ 2. **compiled**: the answer (a tool call or a reply) comes back in exactly the provider's response shape; your loop runs the tool as usual.
32
+ 3. **forwarded**: your model is called as normal.
33
+ 4. **fail-open**: AgentCompile errored, was slow or sent something unusable, so your model is called as normal.
34
+ 5. **no conversation id**: your model is called and no decision is made.
35
+
36
+ Your provider key never leaves your process. `mode="shadow"` decides but always calls your model, so you can see what it would have done before you switch it on.
37
+
38
+ ## The trail
39
+
40
+ Every call is written to `~/.agentcompile/trail.jsonl` (`trail=` sets a path, or `False` turns it off; `on_event=` gets each event).
41
+
42
+ ```
43
+ agentcompile trail # recent calls and a summary
44
+ agentcompile trail -f # follow live
45
+ ```
46
+
47
+ ```
48
+ 14:02:11 c1 compiled get_order_details gpt-5 48 ms decide
49
+ 14:02:12 c2 forwarded no job matched gpt-5 51 ms decide
50
+ 2 calls: compiled 1, forwarded 1. Model calls avoided: 1 (50%).
51
+ ```
52
+
53
+ ## Keys
54
+
55
+ Your AgentCompile key (`ack_...`) identifies your company by itself. We show it once and store only its hash; a new key revokes the old one. AgentCompile is pre-launch: to get a key, write to founders@tryagentcompile.com.
56
+
57
+ ## Development
58
+
59
+ ```
60
+ pip install -e ".[dev]"
61
+ pytest tests
62
+ ```
@@ -0,0 +1,40 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "agentcompile"
7
+ version = "0.1.0"
8
+ description = "Wrap your agent's model client: repeated jobs run compiled, everything else goes to your model unchanged."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "Apache-2.0"
12
+ authors = [{ name = "AgentCompile", email = "founders@tryagentcompile.com" }]
13
+ classifiers = ["Development Status :: 3 - Alpha", "Programming Language :: Python :: 3", "Intended Audience :: Developers", "Topic :: Software Development :: Libraries"]
14
+
15
+ dependencies = ["httpx>=0.25"]
16
+
17
+ [project.urls]
18
+ Homepage = "https://tryagentcompile.com"
19
+
20
+ [project.optional-dependencies]
21
+ openai = ["openai>=1.0"]
22
+ anthropic = ["anthropic>=0.40"]
23
+ dev = ["pytest>=8", "openai>=1.0", "anthropic>=0.40", "pytest-asyncio>=0.23"]
24
+
25
+ [project.scripts]
26
+ agentcompile = "agentcompile.cli:main"
27
+
28
+ [tool.hatch.build.targets.wheel]
29
+ packages = ["src/agentcompile"]
30
+
31
+ [tool.pytest.ini_options]
32
+ asyncio_mode = "auto"
33
+
34
+ [tool.ruff]
35
+ line-length = 96
36
+ target-version = "py39"
37
+ src = ["src", "tests"]
38
+
39
+ [tool.ruff.lint]
40
+ select = ["E", "F", "I", "B", "UP", "SIM", "C4", "RUF"]
@@ -0,0 +1,100 @@
1
+ """AgentCompile: wrap your agent's model client.
2
+
3
+ import agentcompile
4
+ client = agentcompile.wrap(OpenAI(), key="ack_...")
5
+ client.chat.completions.create(model=..., messages=..., conversation_id=ticket.id)
6
+
7
+ Known jobs run compiled (no model call); everything else goes to your model unchanged, with your
8
+ own provider key. If AgentCompile is down or slow, calls go straight to your model. Every call
9
+ is written to the trail (`agentcompile trail`).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import inspect
15
+ import os
16
+ from typing import Any
17
+
18
+ from ._conversation import conversation
19
+ from ._core import LIVE, SHADOW, Proxy, Router, async_create, sync_create
20
+ from ._decide import AsyncDecider, Decider, Settings
21
+ from ._trail import OnEvent, Trail
22
+
23
+ __all__ = ["LIVE", "SHADOW", "conversation", "wrap"]
24
+ __version__ = "0.1.0"
25
+
26
+ DEFAULT_URL = "https://api.tryagentcompile.com"
27
+
28
+
29
+ def wrap(
30
+ client: Any,
31
+ *,
32
+ key: str | None = None,
33
+ base_url: str | None = None,
34
+ mode: str = LIVE,
35
+ timeout: float = 2.0,
36
+ trail: str | bool | None = True,
37
+ on_event: OnEvent | None = None,
38
+ company: str | None = None,
39
+ http_client: Any = None,
40
+ ) -> Any:
41
+ """Wrap an OpenAI- or Anthropic-style client; returns an object you use exactly like it.
42
+
43
+ key: your AgentCompile key (or AGENTCOMPILE_KEY). base_url: AGENTCOMPILE_URL or the default.
44
+ mode: "live" answers known jobs; "shadow" decides but always calls your model, so you can
45
+ see what it would have done. timeout: seconds to wait for a decision before failing open.
46
+ trail: a path, True for ~/.agentcompile/trail.jsonl, or False. on_event: called per call.
47
+ """
48
+ settings = Settings(
49
+ base_url=base_url or os.environ.get("AGENTCOMPILE_URL", DEFAULT_URL),
50
+ key=key or os.environ.get("AGENTCOMPILE_KEY"),
51
+ company=company or os.environ.get("AGENTCOMPILE_COMPANY"),
52
+ timeout=timeout,
53
+ )
54
+ the_trail = Trail(trail, on_event)
55
+
56
+ chat = getattr(client, "chat", None)
57
+ completions = getattr(chat, "completions", None)
58
+ if completions is not None and hasattr(completions, "create"):
59
+ from . import _openai
60
+
61
+ router = _router("openai", completions.create, settings, the_trail, mode, http_client)
62
+ create = _create(router, completions.create, _openai.build)
63
+ return Proxy(
64
+ client,
65
+ {"chat": Proxy(chat, {"completions": Proxy(completions, {"create": create})})},
66
+ )
67
+
68
+ messages = getattr(client, "messages", None)
69
+ if messages is not None and hasattr(messages, "create"):
70
+ from . import _anthropic
71
+
72
+ router = _router("anthropic", messages.create, settings, the_trail, mode, http_client)
73
+ create = _create(router, messages.create, _anthropic.build)
74
+ return Proxy(client, {"messages": Proxy(messages, {"create": create})})
75
+
76
+ raise TypeError("agentcompile.wrap expects an OpenAI- or Anthropic-style client")
77
+
78
+
79
+ def _router(
80
+ provider: str, create: Any, settings: Settings, trail: Trail, mode: str, http_client: Any
81
+ ) -> Router:
82
+ decider: Any = (
83
+ AsyncDecider(settings, http_client)
84
+ if _is_async(create)
85
+ else Decider(settings, http_client)
86
+ )
87
+ return Router(provider, decider, trail, mode)
88
+
89
+
90
+ def _create(router: Router, original: Any, build: Any) -> Any:
91
+ return (
92
+ async_create(router, original, build)
93
+ if _is_async(original)
94
+ else sync_create(router, original, build)
95
+ )
96
+
97
+
98
+ def _is_async(fn: Any) -> bool:
99
+ """The SDKs wrap create() in decorators; look through them."""
100
+ return inspect.iscoroutinefunction(inspect.unwrap(fn))
@@ -0,0 +1,80 @@
1
+ """Anthropic-style clients (Anthropic, AsyncAnthropic, AnthropicBedrock, AnthropicVertex):
2
+ compiled answers shaped exactly like messages.create() results."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import uuid
8
+ from typing import Any
9
+
10
+ from ._decide import Decision
11
+ from ._streams import AsyncCompiledStream, CompiledStream
12
+
13
+
14
+ def _block(decision: Decision) -> dict[str, Any]:
15
+ if decision.action == "tool_call":
16
+ return {
17
+ "type": "tool_use",
18
+ "id": decision.call_id or f"toolu_ac_{uuid.uuid4().hex[:12]}",
19
+ "name": decision.tool,
20
+ "input": decision.args,
21
+ }
22
+ return {"type": "text", "text": decision.text or ""}
23
+
24
+
25
+ def build(decision: Decision, kwargs: dict[str, Any], stream: bool, is_async: bool) -> Any:
26
+ from anthropic.types import (
27
+ Message,
28
+ RawContentBlockDeltaEvent,
29
+ RawContentBlockStartEvent,
30
+ RawContentBlockStopEvent,
31
+ RawMessageDeltaEvent,
32
+ RawMessageStartEvent,
33
+ RawMessageStopEvent,
34
+ )
35
+
36
+ model = str(kwargs.get("model") or "agentcompile")
37
+ block = _block(decision)
38
+ stop = "tool_use" if decision.action == "tool_call" else "end_turn"
39
+ message = {
40
+ "id": f"msg_ac_{uuid.uuid4().hex[:16]}",
41
+ "type": "message",
42
+ "role": "assistant",
43
+ "model": model,
44
+ "content": [block],
45
+ "stop_reason": stop,
46
+ "stop_sequence": None,
47
+ "usage": {"input_tokens": 0, "output_tokens": 0},
48
+ }
49
+ if not stream:
50
+ return Message.model_validate(message)
51
+ if block["type"] == "tool_use":
52
+ start_block = {**block, "input": {}}
53
+ delta = {"type": "input_json_delta", "partial_json": json.dumps(block["input"])}
54
+ else:
55
+ start_block = {"type": "text", "text": ""}
56
+ delta = {"type": "text_delta", "text": block["text"]}
57
+ events: list[Any] = [
58
+ RawMessageStartEvent.model_validate(
59
+ {
60
+ "type": "message_start",
61
+ "message": {**message, "content": [], "stop_reason": None},
62
+ }
63
+ ),
64
+ RawContentBlockStartEvent.model_validate(
65
+ {"type": "content_block_start", "index": 0, "content_block": start_block}
66
+ ),
67
+ RawContentBlockDeltaEvent.model_validate(
68
+ {"type": "content_block_delta", "index": 0, "delta": delta}
69
+ ),
70
+ RawContentBlockStopEvent.model_validate({"type": "content_block_stop", "index": 0}),
71
+ RawMessageDeltaEvent.model_validate(
72
+ {
73
+ "type": "message_delta",
74
+ "delta": {"stop_reason": stop, "stop_sequence": None},
75
+ "usage": {"output_tokens": 0},
76
+ }
77
+ ),
78
+ RawMessageStopEvent.model_validate({"type": "message_stop"}),
79
+ ]
80
+ return AsyncCompiledStream(events) if is_async else CompiledStream(events)
@@ -0,0 +1,29 @@
1
+ """The conversation id: a `conversation_id=` keyword on create(), or a context block."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import contextvars
7
+ from collections.abc import Iterator
8
+
9
+ _current: contextvars.ContextVar[str | None] = contextvars.ContextVar(
10
+ "agentcompile_conversation", default=None
11
+ )
12
+
13
+
14
+ @contextlib.contextmanager
15
+ def conversation(conversation_id: str) -> Iterator[None]:
16
+ """Every model call inside the block belongs to this conversation:
17
+
18
+ with agentcompile.conversation(ticket.id):
19
+ run_agent(...)
20
+ """
21
+ token = _current.set(conversation_id)
22
+ try:
23
+ yield
24
+ finally:
25
+ _current.reset(token)
26
+
27
+
28
+ def current() -> str | None:
29
+ return _current.get()