agentcompile 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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()
agentcompile/_core.py ADDED
@@ -0,0 +1,182 @@
1
+ """What every wrapped create() does: decide, then answer compiled or call the real method."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from typing import Any, Callable
7
+
8
+ from ._conversation import current
9
+ from ._decide import Decision
10
+ from ._payload import payload
11
+ from ._trail import Trail
12
+
13
+ LIVE, SHADOW = "live", "shadow"
14
+
15
+
16
+ class Router:
17
+ """Holds the decision client, the trail and the mode for one wrapped client."""
18
+
19
+ def __init__(self, provider: str, decider: Any, trail: Trail, mode: str) -> None:
20
+ if mode not in (LIVE, SHADOW):
21
+ raise ValueError("mode must be 'live' or 'shadow'")
22
+ self.provider = provider
23
+ self.decider = decider
24
+ self.trail = trail
25
+ self.mode = mode
26
+
27
+ def prepare(self, kwargs: dict[str, Any]) -> tuple[str | None, dict[str, Any]]:
28
+ """(conversation id, kwargs for the real call): our keyword never reaches the model."""
29
+ kwargs = dict(kwargs)
30
+ conversation_id = kwargs.pop("conversation_id", None) or current()
31
+ return conversation_id, kwargs
32
+
33
+ def plan(
34
+ self, conversation_id: str | None, decision: Decision | None, error: str | None
35
+ ) -> tuple[str, Decision | None]:
36
+ """(route, the decision to answer with or None to forward)."""
37
+ if conversation_id is None:
38
+ return "no-conversation", None
39
+ if decision is None:
40
+ return "fail-open", None
41
+ if decision.action == "forward":
42
+ return "forwarded", None
43
+ if self.mode == SHADOW:
44
+ return "shadow", None
45
+ return "compiled", decision
46
+
47
+ def record(
48
+ self,
49
+ *,
50
+ route: str,
51
+ conversation_id: str | None,
52
+ kwargs: dict[str, Any],
53
+ decision: Decision | None,
54
+ decide_ms: float | None,
55
+ error: str | None,
56
+ started: float,
57
+ stream: bool,
58
+ ) -> None:
59
+ self.trail.record(
60
+ conversation=conversation_id,
61
+ provider=self.provider,
62
+ model=kwargs.get("model"),
63
+ route=route,
64
+ action=decision.action if decision else None,
65
+ tool=decision.tool if decision else None,
66
+ reason=(decision.reason if decision and decision.action == "forward" else None)
67
+ or error,
68
+ decide_ms=round(decide_ms, 1) if decide_ms is not None else None,
69
+ total_ms=round((time.perf_counter() - started) * 1000, 1),
70
+ stream=stream or None,
71
+ )
72
+
73
+
74
+ def sync_create(
75
+ router: Router, original: Callable[..., Any], build: Callable[..., Any]
76
+ ) -> Callable[..., Any]:
77
+ def create(*args: Any, **kwargs: Any) -> Any:
78
+ started = time.perf_counter()
79
+ conversation_id, real_kwargs = router.prepare(kwargs)
80
+ decision = decide_ms = error = None
81
+ if conversation_id is not None:
82
+ decision, decide_ms, error = router.decider.decide(
83
+ router.provider, conversation_id, payload(real_kwargs)
84
+ )
85
+ route, answer = router.plan(conversation_id, decision, error)
86
+ stream = bool(real_kwargs.get("stream"))
87
+ if answer is not None:
88
+ try:
89
+ result = build(answer, real_kwargs, stream, False)
90
+ except (
91
+ Exception
92
+ ) as exc: # fail open: a compiled answer we can't shape goes to the model
93
+ route, error = "fail-open", f"build: {type(exc).__name__}"
94
+ else:
95
+ router.record(
96
+ route=route,
97
+ conversation_id=conversation_id,
98
+ kwargs=real_kwargs,
99
+ decision=decision,
100
+ decide_ms=decide_ms,
101
+ error=error,
102
+ started=started,
103
+ stream=stream,
104
+ )
105
+ return result
106
+ result = original(*args, **real_kwargs)
107
+ router.record(
108
+ route=route,
109
+ conversation_id=conversation_id,
110
+ kwargs=real_kwargs,
111
+ decision=decision,
112
+ decide_ms=decide_ms,
113
+ error=error,
114
+ started=started,
115
+ stream=stream,
116
+ )
117
+ return result
118
+
119
+ return create
120
+
121
+
122
+ def async_create(
123
+ router: Router, original: Callable[..., Any], build: Callable[..., Any]
124
+ ) -> Callable[..., Any]:
125
+ async def create(*args: Any, **kwargs: Any) -> Any:
126
+ started = time.perf_counter()
127
+ conversation_id, real_kwargs = router.prepare(kwargs)
128
+ decision = decide_ms = error = None
129
+ if conversation_id is not None:
130
+ decision, decide_ms, error = await router.decider.decide(
131
+ router.provider, conversation_id, payload(real_kwargs)
132
+ )
133
+ route, answer = router.plan(conversation_id, decision, error)
134
+ stream = bool(real_kwargs.get("stream"))
135
+ if answer is not None:
136
+ try:
137
+ result = build(answer, real_kwargs, stream, True)
138
+ except Exception as exc:
139
+ route, error = "fail-open", f"build: {type(exc).__name__}"
140
+ else:
141
+ router.record(
142
+ route=route,
143
+ conversation_id=conversation_id,
144
+ kwargs=real_kwargs,
145
+ decision=decision,
146
+ decide_ms=decide_ms,
147
+ error=error,
148
+ started=started,
149
+ stream=stream,
150
+ )
151
+ return result
152
+ result = await original(*args, **real_kwargs)
153
+ router.record(
154
+ route=route,
155
+ conversation_id=conversation_id,
156
+ kwargs=real_kwargs,
157
+ decision=decision,
158
+ decide_ms=decide_ms,
159
+ error=error,
160
+ started=started,
161
+ stream=stream,
162
+ )
163
+ return result
164
+
165
+ return create
166
+
167
+
168
+ class Proxy:
169
+ """Everything delegates to the real object except the attributes we override."""
170
+
171
+ def __init__(self, target: Any, overrides: dict[str, Any]) -> None:
172
+ object.__setattr__(self, "_target", target)
173
+ object.__setattr__(self, "_overrides", overrides)
174
+
175
+ def __getattr__(self, name: str) -> Any:
176
+ overrides = object.__getattribute__(self, "_overrides")
177
+ if name in overrides:
178
+ return overrides[name]
179
+ return getattr(object.__getattribute__(self, "_target"), name)
180
+
181
+ def __repr__(self) -> str:
182
+ return f"agentcompile({object.__getattribute__(self, '_target')!r})"
@@ -0,0 +1,116 @@
1
+ """The decision call to AgentCompile. Never raises: any problem is a `None` decision, which the
2
+ wrapper treats as forward (fail open)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import time
7
+ from dataclasses import dataclass, field
8
+ from typing import Any
9
+
10
+ import httpx
11
+
12
+ COMPANY_HEADER = "x-agentcompiler-company"
13
+ CONVERSATION_HEADER = "x-agentcompiler-conversation"
14
+ KEY_HEADER = "x-agentcompiler-key"
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class Decision:
19
+ action: str # "tool_call" | "say" | "forward"
20
+ tool: str | None = None
21
+ args: dict[str, Any] = field(default_factory=dict)
22
+ call_id: str | None = None
23
+ text: str | None = None
24
+ reason: str | None = None
25
+
26
+ @classmethod
27
+ def parse(cls, body: Any) -> Decision | None:
28
+ if not isinstance(body, dict):
29
+ return None
30
+ action = body.get("action")
31
+ if (
32
+ action == "tool_call"
33
+ and isinstance(body.get("tool"), str)
34
+ and isinstance(body.get("args"), dict)
35
+ ):
36
+ return cls(
37
+ action,
38
+ tool=body["tool"],
39
+ args=body["args"],
40
+ call_id=str(body.get("call_id") or ""),
41
+ )
42
+ if action == "say" and isinstance(body.get("text"), str):
43
+ return cls(action, text=body["text"])
44
+ if action == "forward":
45
+ return cls(action, reason=str(body.get("reason") or ""))
46
+ return None
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class Settings:
51
+ base_url: str
52
+ key: str | None
53
+ company: str | None
54
+ timeout: float
55
+
56
+
57
+ def _request(
58
+ settings: Settings, provider: str, conversation_id: str, payload: dict[str, Any]
59
+ ) -> tuple[str, dict[str, str], dict[str, Any]]:
60
+ headers = {CONVERSATION_HEADER: conversation_id}
61
+ if settings.company: # optional: the key names the company
62
+ headers[COMPANY_HEADER] = settings.company
63
+ if settings.key:
64
+ headers[KEY_HEADER] = settings.key
65
+ return (
66
+ f"{settings.base_url.rstrip('/')}/v1/decide",
67
+ headers,
68
+ {"provider": provider, "request": payload},
69
+ )
70
+
71
+
72
+ class Decider:
73
+ def __init__(self, settings: Settings, http: httpx.Client | None = None) -> None:
74
+ self.settings = settings
75
+ self._http = http or httpx.Client(timeout=settings.timeout)
76
+
77
+ def decide(
78
+ self, provider: str, conversation_id: str, payload: dict[str, Any]
79
+ ) -> tuple[Decision | None, float, str | None]:
80
+ """(decision or None, milliseconds, error text)."""
81
+ url, headers, body = _request(self.settings, provider, conversation_id, payload)
82
+ start = time.perf_counter()
83
+ try:
84
+ response = self._http.post(
85
+ url, headers=headers, json=body, timeout=self.settings.timeout
86
+ )
87
+ ms = (time.perf_counter() - start) * 1000
88
+ if response.status_code != 200:
89
+ return None, ms, f"HTTP {response.status_code}"
90
+ decision = Decision.parse(response.json())
91
+ return decision, ms, None if decision else "malformed decision"
92
+ except Exception as exc: # fail open
93
+ return None, (time.perf_counter() - start) * 1000, type(exc).__name__
94
+
95
+
96
+ class AsyncDecider:
97
+ def __init__(self, settings: Settings, http: httpx.AsyncClient | None = None) -> None:
98
+ self.settings = settings
99
+ self._http = http or httpx.AsyncClient(timeout=settings.timeout)
100
+
101
+ async def decide(
102
+ self, provider: str, conversation_id: str, payload: dict[str, Any]
103
+ ) -> tuple[Decision | None, float, str | None]:
104
+ url, headers, body = _request(self.settings, provider, conversation_id, payload)
105
+ start = time.perf_counter()
106
+ try:
107
+ response = await self._http.post(
108
+ url, headers=headers, json=body, timeout=self.settings.timeout
109
+ )
110
+ ms = (time.perf_counter() - start) * 1000
111
+ if response.status_code != 200:
112
+ return None, ms, f"HTTP {response.status_code}"
113
+ decision = Decision.parse(response.json())
114
+ return decision, ms, None if decision else "malformed decision"
115
+ except Exception as exc: # fail open
116
+ return None, (time.perf_counter() - start) * 1000, type(exc).__name__
@@ -0,0 +1,65 @@
1
+ """OpenAI-style clients (OpenAI, AsyncOpenAI, AzureOpenAI and any OpenAI-compatible base_url):
2
+ compiled answers shaped exactly like chat.completions.create() results."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import time
8
+ import uuid
9
+ from typing import Any
10
+
11
+ from ._decide import Decision
12
+ from ._streams import AsyncCompiledStream, CompiledStream
13
+
14
+
15
+ def _message(decision: Decision) -> dict[str, Any]:
16
+ if decision.action == "tool_call":
17
+ return {
18
+ "role": "assistant",
19
+ "content": None,
20
+ "tool_calls": [
21
+ {
22
+ "id": decision.call_id or f"call_ac_{uuid.uuid4().hex[:12]}",
23
+ "type": "function",
24
+ "function": {"name": decision.tool, "arguments": json.dumps(decision.args)},
25
+ }
26
+ ],
27
+ }
28
+ return {"role": "assistant", "content": decision.text}
29
+
30
+
31
+ def build(decision: Decision, kwargs: dict[str, Any], stream: bool, is_async: bool) -> Any:
32
+ from openai.types.chat import ChatCompletion, ChatCompletionChunk
33
+
34
+ model = str(kwargs.get("model") or "agentcompile")
35
+ ident, created = f"chatcmpl-ac-{uuid.uuid4().hex[:16]}", int(time.time())
36
+ message = _message(decision)
37
+ finish = "tool_calls" if decision.action == "tool_call" else "stop"
38
+ if not stream:
39
+ return ChatCompletion.model_validate(
40
+ {
41
+ "id": ident,
42
+ "object": "chat.completion",
43
+ "created": created,
44
+ "model": model,
45
+ "choices": [
46
+ {"index": 0, "message": message, "finish_reason": finish, "logprobs": None}
47
+ ],
48
+ "usage": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0},
49
+ }
50
+ )
51
+ delta: dict[str, Any] = {"role": "assistant", "content": message.get("content")}
52
+ if "tool_calls" in message:
53
+ delta["tool_calls"] = [
54
+ {**call, "index": i} for i, call in enumerate(message["tool_calls"])
55
+ ]
56
+ base = {"id": ident, "object": "chat.completion.chunk", "created": created, "model": model}
57
+ chunks: list[Any] = [
58
+ ChatCompletionChunk.model_validate(
59
+ {**base, "choices": [{"index": 0, "delta": delta, "finish_reason": None}]}
60
+ ),
61
+ ChatCompletionChunk.model_validate(
62
+ {**base, "choices": [{"index": 0, "delta": {}, "finish_reason": finish}]}
63
+ ),
64
+ ]
65
+ return AsyncCompiledStream(chunks) if is_async else CompiledStream(chunks)
@@ -0,0 +1,26 @@
1
+ """Turning create() keyword arguments into the JSON the decision call sends."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ # What the engine reads; everything else stays between the customer and their provider.
8
+ _FIELDS = ("model", "messages", "system", "tools")
9
+
10
+
11
+ def jsonable(value: Any) -> Any:
12
+ """Plain JSON from what agent loops put in messages: dicts, lists, and the SDKs' own
13
+ response objects appended back into the history (pydantic models)."""
14
+ if hasattr(value, "model_dump"):
15
+ return jsonable(value.model_dump(exclude_none=True))
16
+ if isinstance(value, dict):
17
+ return {str(k): jsonable(v) for k, v in value.items()}
18
+ if isinstance(value, (list, tuple)):
19
+ return [jsonable(v) for v in value]
20
+ if isinstance(value, (str, int, float, bool)) or value is None:
21
+ return value
22
+ return str(value)
23
+
24
+
25
+ def payload(kwargs: dict[str, Any]) -> dict[str, Any]:
26
+ return {k: jsonable(kwargs[k]) for k in _FIELDS if k in kwargs and kwargs[k] is not None}
@@ -0,0 +1,47 @@
1
+ """Compiled answers as streams: iterators shaped like the SDKs' Stream objects."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator
6
+ from typing import Any
7
+
8
+
9
+ class CompiledStream:
10
+ def __init__(self, items: list[Any]) -> None:
11
+ self._items = items
12
+
13
+ def __iter__(self) -> Iterator[Any]:
14
+ return iter(self._items)
15
+
16
+ def __enter__(self) -> CompiledStream:
17
+ return self
18
+
19
+ def __exit__(self, *exc: Any) -> None:
20
+ return None
21
+
22
+ def close(self) -> None:
23
+ return None
24
+
25
+
26
+ class AsyncCompiledStream:
27
+ def __init__(self, items: list[Any]) -> None:
28
+ self._items = items
29
+
30
+ def __aiter__(self) -> AsyncCompiledStream:
31
+ self._it = iter(self._items)
32
+ return self
33
+
34
+ async def __anext__(self) -> Any:
35
+ try:
36
+ return next(self._it)
37
+ except StopIteration:
38
+ raise StopAsyncIteration from None
39
+
40
+ async def __aenter__(self) -> AsyncCompiledStream:
41
+ return self
42
+
43
+ async def __aexit__(self, *exc: Any) -> None:
44
+ return None
45
+
46
+ async def close(self) -> None:
47
+ return None
agentcompile/_trail.py ADDED
@@ -0,0 +1,50 @@
1
+ """The trail: one JSON line per model call, so you can see what AgentCompile did with each one.
2
+
3
+ Routes: `compiled` (answered without your model), `forwarded` (sent to your model),
4
+ `fail-open` (AgentCompile failed or was slow; sent to your model), `shadow` (decided but always
5
+ forwarded), `no-conversation` (no conversation id; sent to your model)."""
6
+
7
+ from __future__ import annotations
8
+
9
+ import contextlib
10
+ import json
11
+ import os
12
+ import threading
13
+ import time
14
+ from pathlib import Path
15
+ from typing import Any, Callable
16
+
17
+ DEFAULT_PATH = Path(
18
+ os.environ.get("AGENTCOMPILE_TRAIL", Path.home() / ".agentcompile" / "trail.jsonl")
19
+ )
20
+
21
+ OnEvent = Callable[[dict[str, Any]], None]
22
+
23
+
24
+ class Trail:
25
+ def __init__(
26
+ self, path: str | Path | bool | None = True, on_event: OnEvent | None = None
27
+ ) -> None:
28
+ self.path: Path | None = (
29
+ DEFAULT_PATH if path is True else (Path(path) if path else None)
30
+ )
31
+ self.on_event = on_event
32
+ self._lock = threading.Lock()
33
+
34
+ def record(self, **event: Any) -> dict[str, Any]:
35
+ event = {
36
+ "ts": round(time.time(), 3),
37
+ **{k: v for k, v in event.items() if v is not None},
38
+ }
39
+ if self.path is not None:
40
+ try:
41
+ with self._lock:
42
+ self.path.parent.mkdir(parents=True, exist_ok=True)
43
+ with self.path.open("a", encoding="utf-8") as fh:
44
+ fh.write(json.dumps(event, default=str) + "\n")
45
+ except OSError:
46
+ pass # the trail never breaks the agent
47
+ if self.on_event is not None:
48
+ with contextlib.suppress(Exception):
49
+ self.on_event(event)
50
+ return event
agentcompile/cli.py ADDED
@@ -0,0 +1,100 @@
1
+ """`agentcompile trail`: see what AgentCompile did with each model call."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ import time
9
+ from collections.abc import Iterator
10
+ from datetime import datetime
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ from ._trail import DEFAULT_PATH
15
+
16
+ COLORS = {
17
+ "compiled": "\033[33m",
18
+ "forwarded": "\033[0m",
19
+ "fail-open": "\033[31m",
20
+ "shadow": "\033[36m",
21
+ "no-conversation": "\033[2m",
22
+ }
23
+ RESET = "\033[0m"
24
+
25
+
26
+ def line(event: dict[str, Any], color: bool) -> str:
27
+ ts = datetime.fromtimestamp(event.get("ts", 0)).strftime("%H:%M:%S")
28
+ route = event.get("route", "?")
29
+ what = event.get("tool") or event.get("action") or event.get("reason") or ""
30
+ if route in ("forwarded", "fail-open") and event.get("reason"):
31
+ what = event["reason"]
32
+ timing = f"{event['decide_ms']:.0f} ms decide" if event.get("decide_ms") is not None else ""
33
+ convo = str(event.get("conversation", "-"))[:12]
34
+ model = event.get("model", "")
35
+ text = f"{ts} {convo:<12} {route:<15} {str(what)[:40]:<40} {model} {timing}"
36
+ return f"{COLORS.get(route, '')}{text}{RESET}" if color else text
37
+
38
+
39
+ def follow(path: Path, start_at_end: bool) -> Iterator[str]:
40
+ path.parent.mkdir(parents=True, exist_ok=True)
41
+ path.touch(exist_ok=True)
42
+ with path.open(encoding="utf-8") as fh:
43
+ if start_at_end:
44
+ fh.seek(0, 2)
45
+ while True:
46
+ row = fh.readline()
47
+ if row:
48
+ yield row
49
+ else:
50
+ time.sleep(0.25)
51
+
52
+
53
+ def summary(rows: list) -> str:
54
+ total = len(rows)
55
+ counts: dict[str, int] = {}
56
+ for r in rows:
57
+ counts[r.get("route", "?")] = counts.get(r.get("route", "?"), 0) + 1
58
+ parts = ", ".join(f"{k} {v}" for k, v in sorted(counts.items()))
59
+ compiled = counts.get("compiled", 0)
60
+ share = f"{100 * compiled / total:.0f}%" if total else "0%"
61
+ return f"{total} calls: {parts}. Model calls avoided: {compiled} ({share})."
62
+
63
+
64
+ def main(argv: Any = None) -> int:
65
+ parser = argparse.ArgumentParser(prog="agentcompile")
66
+ sub = parser.add_subparsers(dest="cmd", required=True)
67
+ t = sub.add_parser("trail", help="show the trail of model calls")
68
+ t.add_argument("-f", "--follow", action="store_true", help="keep printing new calls")
69
+ t.add_argument("-n", type=int, default=50, help="how many recent calls to show")
70
+ t.add_argument("--path", type=Path, default=DEFAULT_PATH)
71
+ t.add_argument("--json", action="store_true", help="raw JSON lines")
72
+ args = parser.parse_args(argv)
73
+ color = sys.stdout.isatty() and not args.json
74
+ rows = []
75
+ if args.path.exists():
76
+ for raw in args.path.read_text(encoding="utf-8").splitlines()[-args.n :]:
77
+ try:
78
+ rows.append(json.loads(raw))
79
+ except ValueError:
80
+ continue
81
+ for r in rows:
82
+ print(json.dumps(r) if args.json else line(r, color))
83
+ if not args.follow:
84
+ if not args.json:
85
+ print(summary(rows))
86
+ return 0
87
+ try:
88
+ for raw in follow(args.path, start_at_end=True):
89
+ try:
90
+ event = json.loads(raw)
91
+ except ValueError:
92
+ continue
93
+ print(json.dumps(event) if args.json else line(event, color), flush=True)
94
+ except KeyboardInterrupt:
95
+ return 0
96
+ return 0
97
+
98
+
99
+ if __name__ == "__main__":
100
+ raise SystemExit(main())
@@ -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,15 @@
1
+ agentcompile/__init__.py,sha256=nfgkxePglg0SN9FP_yaDXZM3NJg0YwXgamcl_8C1MFw,3603
2
+ agentcompile/_anthropic.py,sha256=TLUhUfxdf6cBf0jgG4XczHQC5vL4s-xfo8Qpoh5hItQ,2839
3
+ agentcompile/_conversation.py,sha256=VF0sUXXST6W4BJHlTv0n1caaGr6zhRXuHLE9bAtAduU,722
4
+ agentcompile/_core.py,sha256=-V_P6DLaCoj7nGB9dgiAzzv70bZTnD4gKG__x083-w8,6480
5
+ agentcompile/_decide.py,sha256=1njRPUaf24NlX9xtzmT__SvEBwjxqbxj-tGX-sL1XW4,4227
6
+ agentcompile/_openai.py,sha256=gsByu3b9tMXs9CeUd316QdLZzsCOVLlDe3HejsMllpY,2506
7
+ agentcompile/_payload.py,sha256=kskH_qX7c1Qa1MtgNpvDmKMXhT2-C81r_TR4Ic1xKWo,1018
8
+ agentcompile/_streams.py,sha256=HsrkyaM_f4NM77RvcuZ_JhXT9v7aqIylYTmrSTZC58k,1114
9
+ agentcompile/_trail.py,sha256=UxjmdVTFUPjiKN-GSrsftEx4S8oPqe_KFUV7MyddpCY,1715
10
+ agentcompile/cli.py,sha256=UATyVSMDhIGDQCZPBBFkWjo_1nuGo8PNCCwndU5TNYI,3426
11
+ agentcompile-0.1.0.dist-info/METADATA,sha256=RtoJdZ-ripeYVRd0sYrtasBT4Fw-dfwFdOiIXy_y17o,3309
12
+ agentcompile-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
13
+ agentcompile-0.1.0.dist-info/entry_points.txt,sha256=s7G0_-Ni50SGRqUMhjB7FpAt6UtfLX77xPfHjGgghwk,55
14
+ agentcompile-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
15
+ agentcompile-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ agentcompile = agentcompile.cli:main
@@ -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.