concordat 0.0.1__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.
concordat/__init__.py ADDED
@@ -0,0 +1,24 @@
1
+ """Typed sessions for AI agents."""
2
+
3
+ from importlib.metadata import version as _version
4
+
5
+ from .agent import Action, Agent, Approver, cli_approver, human, tool
6
+ from .budget import Budget, BudgetExceeded
7
+ from .protocol import Protocol, ProtocolError
8
+ from .session import ProtocolViolation, Session
9
+
10
+ __all__ = [
11
+ "Action",
12
+ "Agent",
13
+ "Approver",
14
+ "Budget",
15
+ "BudgetExceeded",
16
+ "Protocol",
17
+ "ProtocolError",
18
+ "ProtocolViolation",
19
+ "Session",
20
+ "cli_approver",
21
+ "human",
22
+ "tool",
23
+ ]
24
+ __version__ = _version("concordat") # set in pyproject.toml
concordat/_runner.py ADDED
@@ -0,0 +1,105 @@
1
+ """Provider-neutral parts of the model runners. Needs pydantic, which every provider SDK ships."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+ import typing
7
+ from dataclasses import dataclass
8
+ from typing import Any, Literal
9
+
10
+ import pydantic
11
+ import pydantic_core
12
+
13
+ from .agent import Action, Agent
14
+ from .budget import Budget
15
+
16
+ STEPWISE_NOTE = (
17
+ "This conversation follows a fixed process. Each turn you are offered only the "
18
+ "actions allowed at the current step, so tools you used earlier may no longer be "
19
+ "listed and new ones may appear. That is expected: earlier results remain valid."
20
+ )
21
+
22
+ Status = Literal["done", "waiting", "refused", "max_tokens", "out_of_budget", "max_turns"]
23
+
24
+
25
+ @dataclass
26
+ class RunResult:
27
+ """How a run ended.
28
+
29
+ ``done``: the protocol reached a final state. ``waiting``: the model ended its turn
30
+ before that, usually to ask the user something; append a user message to
31
+ ``messages`` and call ``run`` again to continue.
32
+ """
33
+
34
+ status: Status
35
+ text: str
36
+ messages: list[Any]
37
+
38
+
39
+ def system_prompt(agent: Agent) -> str:
40
+ return f"{agent.instructions}\n\n{STEPWISE_NOTE}" if agent.instructions else STEPWISE_NOTE
41
+
42
+
43
+ def with_next_step(agent: Agent, content: str) -> str:
44
+ """Append what the model may do next, so a changing tool list is never a surprise."""
45
+ if agent.done:
46
+ return f"{content}\n\n[The process is complete.]"
47
+ allowed = ", ".join(agent.allowed_tools())
48
+ return f"{content}\n\n[Now allowed: {allowed}.]"
49
+
50
+
51
+ def exhausted(budget: Budget) -> bool:
52
+ return (budget.tokens is not None and budget.tokens <= 0) or (
53
+ budget.tool_calls is not None and budget.tool_calls <= 0
54
+ )
55
+
56
+
57
+ def cap(budget: Budget, max_tokens: int) -> int:
58
+ """The output limit for the next response: never more than the tokens left."""
59
+ return max_tokens if budget.tokens is None else min(max_tokens, budget.tokens)
60
+
61
+
62
+ def charge(budget: Budget, used: int) -> bool:
63
+ """Charge the tokens a request processed; on overspend, empty the budget instead."""
64
+ if budget.tokens is not None and used > budget.tokens:
65
+ budget.tokens = 0
66
+ return False
67
+ budget.spend(tokens=used)
68
+ return True
69
+
70
+
71
+ def arguments(action: Action) -> type[pydantic.BaseModel]:
72
+ """A model of the action's parameters, from its signature and type hints."""
73
+ hints = typing.get_type_hints(action.call)
74
+ fields: dict[str, Any] = {
75
+ name: (hints.get(name, Any), ... if p.default is p.empty else p.default)
76
+ for name, p in inspect.signature(action.call).parameters.items()
77
+ }
78
+ return pydantic.create_model(f"{action.name}_arguments", **fields)
79
+
80
+
81
+ def description(action: Action) -> str:
82
+ if action.human:
83
+ return (
84
+ "Ask a human to decide; returns 'approved' or 'rejected'. " + action.description
85
+ ).strip()
86
+ return action.description
87
+
88
+
89
+ def invoke(actions: dict[str, Action], name: str, raw: Any) -> tuple[str, bool]:
90
+ """Validate and run one call. Returns the result text and whether it is an error.
91
+
92
+ ``raw`` is the call's arguments as a dict, or as a JSON string.
93
+ """
94
+ action = actions.get(name)
95
+ if action is None:
96
+ return f"{name!r} is not allowed in the current state.", True
97
+ try:
98
+ model = arguments(action)
99
+ args = model.model_validate_json(raw) if isinstance(raw, str) else model.model_validate(raw)
100
+ result = action.call(**{f: getattr(args, f) for f in type(args).model_fields})
101
+ except Exception as e: # the model sees the error and can correct itself
102
+ return f"{type(e).__name__}: {e}", True
103
+ if action.human:
104
+ return ("approved" if result else "rejected"), False
105
+ return (result if isinstance(result, str) else pydantic_core.to_json(result).decode()), False
concordat/agent.py ADDED
@@ -0,0 +1,197 @@
1
+ from __future__ import annotations
2
+
3
+ import functools
4
+ import inspect
5
+ from collections.abc import Callable, Collection, Iterable, Mapping
6
+ from dataclasses import dataclass, replace
7
+ from typing import Any, ClassVar, Concatenate, Generic, ParamSpec, TypeVar, overload
8
+
9
+ from .budget import Budget
10
+ from .protocol import Protocol, ProtocolError
11
+ from .session import ProtocolViolation, Session
12
+
13
+ P = ParamSpec("P")
14
+ R = TypeVar("R")
15
+
16
+ Approver = Callable[[str, Any], bool]
17
+ """Decides a human step: gets the step name and the method's return value, returns approval."""
18
+
19
+
20
+ def cli_approver(step: str, request: Any) -> bool:
21
+ answer = input(f"[{step}] {request}\nApprove? [y/N] ")
22
+ return answer.strip().lower() in {"y", "yes"}
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class Action:
27
+ """Something the model may do in the current state: call a tool, or ask a human."""
28
+
29
+ name: str
30
+ description: str
31
+ call: Callable[..., Any]
32
+ human: bool
33
+
34
+
35
+ class _Step(Generic[P, R]):
36
+ """An agent method that is also a protocol action, legal only in state ``when``."""
37
+
38
+ def __init__(self, fn: Callable[Concatenate[Any, P], Any], when: str, targets: Iterable[str]):
39
+ self.fn = fn
40
+ self.when = when
41
+ self.targets = frozenset(targets)
42
+ self.name = fn.__name__
43
+ signature = inspect.signature(fn)
44
+ self.signature = signature.replace(parameters=list(signature.parameters.values())[1:])
45
+
46
+ def __set_name__(self, owner: type, name: str) -> None:
47
+ self.name = name
48
+
49
+ @overload
50
+ def __get__(self, agent: None, owner: type | None = None) -> _Step[P, R]: ...
51
+ @overload
52
+ def __get__(self, agent: Agent, owner: type | None = None) -> Callable[P, R]: ...
53
+ def __get__(
54
+ self, agent: Agent | None, owner: type | None = None
55
+ ) -> _Step[P, R] | Callable[P, R]:
56
+ if agent is None:
57
+ return self
58
+
59
+ @functools.wraps(self.fn)
60
+ def bound(*args: P.args, **kwargs: P.kwargs) -> R:
61
+ agent.session.check(self.name) # before any side effect
62
+ return self._run(agent, *args, **kwargs)
63
+
64
+ bound.__signature__ = self.signature # type: ignore[attr-defined] # without self
65
+ return bound
66
+
67
+ def _run(self, agent: Agent, *args: P.args, **kwargs: P.kwargs) -> R:
68
+ raise NotImplementedError
69
+
70
+
71
+ class _Tool(_Step[P, R]):
72
+ def __init__(
73
+ self, fn: Callable[Concatenate[Any, P], R], when: str, then: str | Mapping[Any, str]
74
+ ):
75
+ super().__init__(fn, when, {then} if isinstance(then, str) else then.values())
76
+ self.then = then
77
+
78
+ def _run(self, agent: Agent, *args: P.args, **kwargs: P.kwargs) -> R:
79
+ agent.budget.spend(tool_calls=1)
80
+ result: R = self.fn(agent, *args, **kwargs)
81
+ agent.session.step(self.name, self._target(result))
82
+ return result
83
+
84
+ def _target(self, result: object) -> str:
85
+ if isinstance(self.then, str):
86
+ return self.then
87
+ try:
88
+ return self.then[result]
89
+ except (KeyError, TypeError):
90
+ raise ProtocolViolation(
91
+ f"{self.name!r} returned {result!r}, which leads to no state; "
92
+ f"expected one of {list(self.then)}"
93
+ ) from None
94
+
95
+
96
+ class _Human(_Step[P, bool]):
97
+ def __init__(
98
+ self, fn: Callable[Concatenate[Any, P], Any], when: str, approve: str, reject: str
99
+ ):
100
+ super().__init__(fn, when, {approve, reject})
101
+ self.approve = approve
102
+ self.reject = reject
103
+
104
+ def _run(self, agent: Agent, *args: P.args, **kwargs: P.kwargs) -> bool:
105
+ request = self.fn(agent, *args, **kwargs)
106
+ approved = agent.approver(self.name, request)
107
+ agent.session.step(self.name, self.approve if approved else self.reject)
108
+ return approved
109
+
110
+
111
+ def tool(
112
+ when: str, then: str | Mapping[Any, str]
113
+ ) -> Callable[[Callable[Concatenate[Any, P], R]], _Tool[P, R]]:
114
+ """A tool the model may call in state ``when``.
115
+
116
+ ``then`` is the next state, or a mapping from the method's return value to it.
117
+ """
118
+
119
+ def decorate(fn: Callable[Concatenate[Any, P], R]) -> _Tool[P, R]:
120
+ return _Tool(fn, when, then)
121
+
122
+ return decorate
123
+
124
+
125
+ def human(
126
+ when: str, approve: str, reject: str
127
+ ) -> Callable[[Callable[Concatenate[Any, P], Any]], _Human[P]]:
128
+ """A decision a human makes in state ``when``.
129
+
130
+ The model may request it, but only the approver decides: the method's return value
131
+ is shown to the approver, and calling the method returns the decision.
132
+ """
133
+
134
+ def decorate(fn: Callable[Concatenate[Any, P], Any]) -> _Human[P]:
135
+ return _Human(fn, when, approve, reject)
136
+
137
+ return decorate
138
+
139
+
140
+ class Agent:
141
+ """Base class whose ``@tool`` and ``@human`` methods define its protocol.
142
+
143
+ Declaring ``final`` makes a class concrete: its protocol is built and checked when
144
+ the class is defined. Classes without ``final`` are abstract bases to inherit from.
145
+ """
146
+
147
+ instructions: ClassVar[str] = "" # the system prompt for model-driven runs
148
+ initial: ClassVar[str] = "start"
149
+ final: ClassVar[Collection[str]] = ()
150
+ budget: Budget = Budget() # a template: each instance gets its own copy
151
+ protocol: ClassVar[Protocol]
152
+ _steps: ClassVar[dict[str, _Step[Any, Any]]] = {}
153
+
154
+ def __init_subclass__(cls, **kwargs: Any) -> None:
155
+ super().__init_subclass__(**kwargs)
156
+ steps: dict[str, _Step[Any, Any]] = {}
157
+ for klass in reversed(cls.__mro__):
158
+ for name, attr in vars(klass).items():
159
+ if isinstance(attr, _Step):
160
+ steps[name] = attr
161
+ else:
162
+ steps.pop(name, None) # overridden by a plain method
163
+ cls._steps = steps
164
+ if not cls.final:
165
+ return
166
+ transitions: dict[str, dict[str, frozenset[str]]] = {}
167
+ for name, step in steps.items():
168
+ transitions.setdefault(step.when, {})[name] = step.targets
169
+ try:
170
+ cls.protocol = Protocol(cls.initial, transitions, cls.final)
171
+ except ProtocolError as e:
172
+ raise ProtocolError(f"{cls.__name__}: {e}") from None
173
+
174
+ def __init__(self, approver: Approver = cli_approver) -> None:
175
+ if not self.final:
176
+ raise TypeError(f"{type(self).__name__} is abstract: declare its final states")
177
+ self.approver = approver
178
+ self.budget = replace(type(self).budget)
179
+ self.session = Session(self.protocol, self.budget)
180
+
181
+ @property
182
+ def state(self) -> str:
183
+ return self.session.state
184
+
185
+ @property
186
+ def done(self) -> bool:
187
+ return self.session.done
188
+
189
+ def allowed_tools(self) -> dict[str, Action]:
190
+ """What the model may do right now; everything else is withheld from it."""
191
+ actions = {}
192
+ for name in sorted(self.session.allowed_actions()):
193
+ step = self._steps[name]
194
+ description = inspect.getdoc(step.fn) or ""
195
+ human = isinstance(step, _Human)
196
+ actions[name] = Action(name, description, getattr(self, name), human)
197
+ return actions
concordat/anthropic.py ADDED
@@ -0,0 +1,126 @@
1
+ """Run an agent against Claude through the Anthropic SDK (``pip install concordat[anthropic]``)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import anthropic
8
+
9
+ from ._runner import (
10
+ RunResult,
11
+ Status,
12
+ arguments,
13
+ cap,
14
+ charge,
15
+ description,
16
+ exhausted,
17
+ invoke,
18
+ system_prompt,
19
+ with_next_step,
20
+ )
21
+ from .agent import Action, Agent
22
+
23
+ __all__ = ["DEFAULT_MODEL", "FALLBACK_BETA", "RunResult", "run"]
24
+
25
+ DEFAULT_MODEL = "claude-opus-5-5"
26
+ FALLBACK_BETA = "server-side-fallback-2026-07-01"
27
+
28
+
29
+ def run(
30
+ agent: Agent,
31
+ client: anthropic.Anthropic,
32
+ prompt: str | list[Any],
33
+ *,
34
+ model: str = DEFAULT_MODEL,
35
+ max_tokens: int = 16000,
36
+ max_turns: int = 20,
37
+ fallbacks: bool = True,
38
+ **request: Any,
39
+ ) -> RunResult:
40
+ """Drive ``agent`` with Claude until its protocol finishes or a limit is hit.
41
+
42
+ Each turn, Claude is offered only the actions legal in the agent's current state,
43
+ and every response's tokens are charged to ``agent.budget``. ``fallbacks`` re-runs
44
+ refused requests on Anthropic's recommended fallback model (a beta feature; turn it
45
+ off on platforms without server-side fallbacks). Extra keyword arguments are passed
46
+ to ``messages.create``.
47
+ """
48
+ messages = [{"role": "user", "content": prompt}] if isinstance(prompt, str) else list(prompt)
49
+ text = ""
50
+ for _ in range(max_turns):
51
+ if agent.done:
52
+ return RunResult("done", text, messages)
53
+ budget = agent.budget
54
+ if exhausted(budget):
55
+ return RunResult("out_of_budget", text, messages)
56
+
57
+ actions = agent.allowed_tools()
58
+ params: dict[str, Any] = {
59
+ "model": model,
60
+ "max_tokens": cap(budget, max_tokens),
61
+ "messages": messages,
62
+ "system": system_prompt(agent),
63
+ **request,
64
+ }
65
+ if actions:
66
+ params["tools"] = [_tool_param(action) for action in actions.values()]
67
+ # One call per response, so each call sees the state the previous one left.
68
+ params["tool_choice"] = {"type": "auto", "disable_parallel_tool_use": True}
69
+ if fallbacks:
70
+ response: Any = client.beta.messages.create(
71
+ betas=[FALLBACK_BETA], fallbacks="default", **params
72
+ )
73
+ else:
74
+ response = client.messages.create(**params)
75
+
76
+ if response.stop_reason == "refusal":
77
+ return RunResult("refused", text, messages)
78
+ messages.append({"role": "assistant", "content": response.content})
79
+ text = "".join(b.text for b in response.content if b.type == "text") or text
80
+ calls = [b for b in response.content if b.type == "tool_use"]
81
+
82
+ stop: Status | None = None
83
+ if not charge(budget, _tokens(response.usage)):
84
+ stop = "out_of_budget"
85
+ elif response.stop_reason == "max_tokens":
86
+ stop = "max_tokens"
87
+ if stop is not None:
88
+ if calls: # every tool_use needs a result, or the conversation can't continue
89
+ results = [_result(c.id, f"Not run: {stop}.", error=True) for c in calls]
90
+ messages.append({"role": "user", "content": results})
91
+ return RunResult(stop, text, messages)
92
+ if not calls:
93
+ return RunResult("done" if agent.done else "waiting", text, messages)
94
+
95
+ results = []
96
+ for c in calls:
97
+ content, error = invoke(actions, c.name, c.input)
98
+ results.append(_result(c.id, with_next_step(agent, content), error))
99
+ messages.append({"role": "user", "content": results})
100
+ return RunResult("done" if agent.done else "max_turns", text, messages)
101
+
102
+
103
+ def _tokens(usage: Any) -> int:
104
+ return int(
105
+ usage.input_tokens
106
+ + usage.output_tokens
107
+ + (usage.cache_creation_input_tokens or 0)
108
+ + (usage.cache_read_input_tokens or 0)
109
+ )
110
+
111
+
112
+ def _tool_param(action: Action) -> dict[str, Any]:
113
+ return {
114
+ "name": action.name,
115
+ "description": description(action),
116
+ "input_schema": arguments(action).model_json_schema(),
117
+ }
118
+
119
+
120
+ def _result(tool_use_id: str, content: str, error: bool = False) -> dict[str, Any]:
121
+ return {
122
+ "type": "tool_result",
123
+ "tool_use_id": tool_use_id,
124
+ "content": content,
125
+ "is_error": error,
126
+ }
concordat/budget.py ADDED
@@ -0,0 +1,41 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+
5
+ _KINDS = ("tokens", "tool_calls", "usd")
6
+
7
+
8
+ class BudgetExceeded(RuntimeError):
9
+ """A spend or split would exceed what is left."""
10
+
11
+
12
+ @dataclass
13
+ class Budget:
14
+ """What a session may still spend. ``None`` means unlimited."""
15
+
16
+ tokens: int | None = None
17
+ tool_calls: int | None = None
18
+ usd: float | None = None
19
+
20
+ def spend(self, *, tokens: int = 0, tool_calls: int = 0, usd: float = 0.0) -> None:
21
+ """Deduct the amounts, or raise without deducting anything."""
22
+ amounts = {"tokens": tokens, "tool_calls": tool_calls, "usd": usd}
23
+ for kind, amount in amounts.items():
24
+ left = getattr(self, kind)
25
+ if left is not None and amount > left:
26
+ raise BudgetExceeded(f"{kind}: need {amount}, {left} left")
27
+ for kind, amount in amounts.items():
28
+ left = getattr(self, kind)
29
+ if left is not None:
30
+ setattr(self, kind, left - amount)
31
+
32
+ def split(
33
+ self, *, tokens: int | None = None, tool_calls: int | None = None, usd: float | None = None
34
+ ) -> Budget:
35
+ """Carve out a child budget, e.g. for a handoff. The parent loses what the child gets."""
36
+ child = Budget(tokens=tokens, tool_calls=tool_calls, usd=usd)
37
+ for kind in _KINDS:
38
+ if getattr(self, kind) is not None and getattr(child, kind) is None:
39
+ raise BudgetExceeded(f"{kind}: child can't be unlimited when the parent is limited")
40
+ self.spend(tokens=tokens or 0, tool_calls=tool_calls or 0, usd=usd or 0.0)
41
+ return child
concordat/openai.py ADDED
@@ -0,0 +1,125 @@
1
+ """Run an agent through the OpenAI Responses API (``pip install concordat[openai]``)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import openai
8
+
9
+ from ._runner import (
10
+ RunResult,
11
+ Status,
12
+ arguments,
13
+ cap,
14
+ charge,
15
+ description,
16
+ exhausted,
17
+ invoke,
18
+ system_prompt,
19
+ with_next_step,
20
+ )
21
+ from .agent import Action, Agent
22
+
23
+ __all__ = ["RunResult", "run"]
24
+
25
+
26
+ def run(
27
+ agent: Agent,
28
+ client: openai.OpenAI,
29
+ prompt: str | list[Any],
30
+ *,
31
+ model: str,
32
+ max_output_tokens: int = 16000,
33
+ max_turns: int = 20,
34
+ **request: Any,
35
+ ) -> RunResult:
36
+ """Drive ``agent`` with an OpenAI model until its protocol finishes or a limit is hit.
37
+
38
+ Each turn, the model is offered only the actions legal in the agent's current state,
39
+ and every response's tokens are charged to ``agent.budget``. ``messages`` in the
40
+ result are Responses API input items. Extra keyword arguments are passed to
41
+ ``responses.create``.
42
+ """
43
+ items = [{"role": "user", "content": prompt}] if isinstance(prompt, str) else list(prompt)
44
+ text = ""
45
+ for _ in range(max_turns):
46
+ if agent.done:
47
+ return RunResult("done", text, items)
48
+ budget = agent.budget
49
+ if exhausted(budget):
50
+ return RunResult("out_of_budget", text, items)
51
+
52
+ actions = agent.allowed_tools()
53
+ params: dict[str, Any] = {
54
+ "model": model,
55
+ "input": items,
56
+ "max_output_tokens": cap(budget, max_output_tokens),
57
+ "instructions": system_prompt(agent),
58
+ **request,
59
+ }
60
+ if actions:
61
+ params["tools"] = [_tool_param(action) for action in actions.values()]
62
+ # One call per response, so each call sees the state the previous one left.
63
+ params["tool_choice"] = "auto"
64
+ params["parallel_tool_calls"] = False
65
+ response: Any = client.responses.create(**params)
66
+
67
+ if _refused(response):
68
+ return RunResult("refused", text, items)
69
+ items.extend(response.output)
70
+ text = response.output_text or text
71
+ calls = [item for item in response.output if item.type == "function_call"]
72
+
73
+ stop: Status | None = None
74
+ if not charge(budget, response.usage.total_tokens if response.usage else 0):
75
+ stop = "out_of_budget"
76
+ elif _incomplete(response) == "max_output_tokens":
77
+ stop = "max_tokens"
78
+ if stop is not None:
79
+ # every function call needs an output, or the conversation can't continue
80
+ items.extend(_output(c.call_id, f"Not run: {stop}.", error=True) for c in calls)
81
+ return RunResult(stop, text, items)
82
+ if not calls:
83
+ return RunResult("done" if agent.done else "waiting", text, items)
84
+
85
+ for c in calls:
86
+ content, error = invoke(actions, c.name, c.arguments)
87
+ items.append(_output(c.call_id, with_next_step(agent, content), error))
88
+ return RunResult("done" if agent.done else "max_turns", text, items)
89
+
90
+
91
+ def _tool_param(action: Action) -> dict[str, Any]:
92
+ return {
93
+ "type": "function",
94
+ "name": action.name,
95
+ "description": description(action),
96
+ "parameters": arguments(action).model_json_schema(),
97
+ "strict": False, # strict mode requires every parameter; arguments are validated here
98
+ }
99
+
100
+
101
+ def _incomplete(response: Any) -> str | None:
102
+ if response.status != "incomplete" or response.incomplete_details is None:
103
+ return None
104
+ reason: str | None = response.incomplete_details.reason
105
+ return reason
106
+
107
+
108
+ def _refused(response: Any) -> bool:
109
+ if _incomplete(response) == "content_filter":
110
+ return True
111
+ return any(
112
+ part.type == "refusal"
113
+ for item in response.output
114
+ if item.type == "message"
115
+ for part in item.content
116
+ )
117
+
118
+
119
+ def _output(call_id: str, content: str, error: bool = False) -> dict[str, Any]:
120
+ # Function outputs have no error flag, so errors are marked in the text.
121
+ return {
122
+ "type": "function_call_output",
123
+ "call_id": call_id,
124
+ "output": f"Error: {content}" if error else content,
125
+ }
concordat/protocol.py ADDED
@@ -0,0 +1,78 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Iterable, Mapping
4
+
5
+
6
+ class ProtocolError(ValueError):
7
+ """The protocol definition is inconsistent."""
8
+
9
+
10
+ class Protocol:
11
+ """States, the actions legal in each state, and where each action may lead.
12
+
13
+ Checked when constructed: every state must be reachable from ``initial`` and
14
+ must still be able to reach a final state, so a session can never get stuck.
15
+ """
16
+
17
+ def __init__(
18
+ self,
19
+ initial: str,
20
+ transitions: Mapping[str, Mapping[str, Iterable[str]]],
21
+ final: Iterable[str],
22
+ ) -> None:
23
+ self.initial = initial
24
+ self.final = frozenset(final)
25
+ self.transitions: dict[str, dict[str, frozenset[str]]] = {
26
+ state: {action: frozenset(targets) for action, targets in actions.items()}
27
+ for state, actions in transitions.items()
28
+ }
29
+ self._check()
30
+
31
+ @property
32
+ def states(self) -> frozenset[str]:
33
+ targets = (
34
+ t for actions in self.transitions.values() for ts in actions.values() for t in ts
35
+ )
36
+ return frozenset({self.initial, *self.final, *self.transitions, *targets})
37
+
38
+ def actions(self, state: str) -> frozenset[str]:
39
+ return frozenset(self.transitions.get(state, {}))
40
+
41
+ def targets(self, state: str, action: str) -> frozenset[str]:
42
+ return self.transitions.get(state, {}).get(action, frozenset())
43
+
44
+ def _check(self) -> None:
45
+ problems = []
46
+ if not self.final:
47
+ problems.append("no final states")
48
+ for state in sorted(self.final):
49
+ if self.transitions.get(state):
50
+ problems.append(f"final state {state!r} has actions")
51
+ for state, actions in self.transitions.items():
52
+ for action, targets in actions.items():
53
+ if not targets:
54
+ problems.append(f"action {action!r} in {state!r} leads nowhere")
55
+
56
+ reachable = {self.initial}
57
+ frontier = [self.initial]
58
+ while frontier:
59
+ for targets in self.transitions.get(frontier.pop(), {}).values():
60
+ for target in targets - reachable:
61
+ reachable.add(target)
62
+ frontier.append(target)
63
+ if unreachable := self.states - reachable:
64
+ problems.append(f"unreachable states: {sorted(unreachable)}")
65
+
66
+ can_finish = set(self.final)
67
+ changed = True
68
+ while changed:
69
+ changed = False
70
+ for state, actions in self.transitions.items():
71
+ if state not in can_finish and any(ts & can_finish for ts in actions.values()):
72
+ can_finish.add(state)
73
+ changed = True
74
+ if stuck := self.states - can_finish:
75
+ problems.append(f"states that can never finish: {sorted(stuck)}")
76
+
77
+ if problems:
78
+ raise ProtocolError("; ".join(problems))
concordat/py.typed ADDED
File without changes
concordat/session.py ADDED
@@ -0,0 +1,46 @@
1
+ from __future__ import annotations
2
+
3
+ from .budget import Budget
4
+ from .protocol import Protocol
5
+
6
+
7
+ class ProtocolViolation(RuntimeError):
8
+ """An action that the protocol does not allow in the current state."""
9
+
10
+
11
+ class Session:
12
+ """A live run of a protocol: tracks the state and rejects illegal actions."""
13
+
14
+ def __init__(self, protocol: Protocol, budget: Budget | None = None) -> None:
15
+ self.protocol = protocol
16
+ self.budget = budget if budget is not None else Budget()
17
+ self.state = protocol.initial
18
+ self.history: list[tuple[str, str, str]] = []
19
+
20
+ @property
21
+ def done(self) -> bool:
22
+ return self.state in self.protocol.final
23
+
24
+ def allowed_actions(self) -> frozenset[str]:
25
+ return self.protocol.actions(self.state)
26
+
27
+ def check(self, action: str) -> None:
28
+ """Raise ``ProtocolViolation`` unless ``action`` is allowed in the current state."""
29
+ if action not in self.allowed_actions():
30
+ raise ProtocolViolation(
31
+ f"{action!r} is not allowed in state {self.state!r}; "
32
+ f"allowed: {sorted(self.allowed_actions())}"
33
+ )
34
+
35
+ def step(self, action: str, to: str | None = None) -> None:
36
+ """Take ``action`` and move to ``to`` (optional when the action has one target)."""
37
+ self.check(action)
38
+ targets = self.protocol.targets(self.state, action)
39
+ if to is None and len(targets) == 1:
40
+ (to,) = targets
41
+ if to is None or to not in targets:
42
+ raise ProtocolViolation(
43
+ f"{action!r} in {self.state!r} can lead to {sorted(targets)}, not {to!r}"
44
+ )
45
+ self.history.append((self.state, action, to))
46
+ self.state = to
@@ -0,0 +1,143 @@
1
+ Metadata-Version: 2.5
2
+ Name: concordat
3
+ Version: 0.0.1
4
+ Summary: Typed sessions for AI agents: protocols the runtime enforces on the model.
5
+ Project-URL: Homepage, https://github.com/miladsikaroudi/concordat
6
+ Project-URL: Repository, https://github.com/miladsikaroudi/concordat
7
+ Project-URL: Issues, https://github.com/miladsikaroudi/concordat/issues
8
+ Project-URL: Documentation, https://github.com/miladsikaroudi/concordat/blob/main/docs/design.md
9
+ Author: miladsikaroudi
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: agents,claude,llm,openai,protocols,session types,typestate
13
+ Classifier: Development Status :: 2 - Pre-Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.10
24
+ Provides-Extra: anthropic
25
+ Requires-Dist: anthropic<2,>=1.12; extra == 'anthropic'
26
+ Provides-Extra: openai
27
+ Requires-Dist: openai<4,>=3.26; extra == 'openai'
28
+ Description-Content-Type: text/markdown
29
+
30
+ # concordat
31
+
32
+ **Typed sessions for AI agents.** Agents are objects whose interfaces are protocols,
33
+ and the runtime enforces those protocols on the model.
34
+
35
+ > Status: pre-alpha. Agent classes, the protocol/session/budget kernel, and runners for
36
+ > Claude (Anthropic) and OpenAI work. See [docs/design.md](https://github.com/miladsikaroudi/concordat/blob/main/docs/design.md).
37
+
38
+ ## Why
39
+
40
+ "Never refund before verifying identity" usually lives in a prompt and is hoped for.
41
+ Concordat makes it a checked protocol:
42
+
43
+ - **Protocol fidelity:** the session follows the declared order of turns.
44
+ - **Least privilege per step:** the model only gets the tools legal in the current state.
45
+ - **Bounded spend:** tokens, tool calls and dollars stay within budget, even across handoffs.
46
+
47
+ ## Example
48
+
49
+ ```python
50
+ from concordat import Agent, Budget, human, tool
51
+
52
+ class RefundAgent(Agent):
53
+ final = {"refunded", "denied"}
54
+ budget = Budget(tool_calls=10)
55
+
56
+ @tool(when="start", then={True: "verified", False: "denied"})
57
+ def verify_identity(self, user_id: str) -> bool:
58
+ return lookup(user_id).verified
59
+
60
+ @tool(when="verified", then="awaiting_approval")
61
+ def propose_refund(self, amount: float) -> float:
62
+ return amount
63
+
64
+ @human(when="awaiting_approval", approve="refunded", reject="denied")
65
+ def approve_refund(self, amount: float) -> str:
66
+ return f"Refund ${amount}?" # shown to the human approver
67
+
68
+ agent = RefundAgent() # protocol already checked when the class was defined
69
+ agent.allowed_tools() # {'verify_identity': ...}: all the model gets to see
70
+ agent.propose_refund(5000) # ProtocolViolation, raised before the body runs
71
+ ```
72
+
73
+ ### Running it with Claude
74
+
75
+ ```bash
76
+ pip install "concordat[anthropic]"
77
+ ```
78
+
79
+ ```python
80
+ import anthropic
81
+ from concordat.anthropic import run
82
+
83
+ result = run(RefundAgent(), anthropic.Anthropic(), "Please refund order A-100.")
84
+ result.status # "done", or "waiting" if Claude asked the user something
85
+ ```
86
+
87
+ Each turn Claude is offered only the actions legal in the current state (a human
88
+ step appears as a request that only the approver can decide), one call per
89
+ response. Every response's tokens are charged to the agent's budget, and the next
90
+ response is capped to what is left. Illegal or invalid calls go back to Claude as
91
+ errors so it can correct itself. See [examples/refund.py](https://github.com/miladsikaroudi/concordat/blob/main/examples/refund.py).
92
+
93
+ ### Running it with OpenAI
94
+
95
+ The same loop over the Responses API (`pip install "concordat[openai]"`):
96
+
97
+ ```python
98
+ import openai
99
+ from concordat.openai import run
100
+
101
+ result = run(RefundAgent(), openai.OpenAI(), "Please refund order A-100.", model="...")
102
+ ```
103
+
104
+ ### Without classes
105
+
106
+ The same protocol, using the kernel directly:
107
+
108
+ ```python
109
+ from concordat import Budget, Protocol, Session
110
+
111
+ refund = Protocol(
112
+ "start",
113
+ {
114
+ "start": {"verify_identity": {"verified", "denied"}},
115
+ "verified": {"propose_refund": {"awaiting_approval"}},
116
+ "awaiting_approval": {"human.approve": {"refunded"}, "human.reject": {"denied"}},
117
+ },
118
+ final={"refunded", "denied"},
119
+ ) # checked here: no dead ends, no unreachable states
120
+
121
+ session = Session(refund, Budget(tokens=50_000, tool_calls=10))
122
+ session.allowed_actions() # {'verify_identity'}: only these tools go to the model
123
+ session.step("propose_refund") # ProtocolViolation: not allowed in state 'start'
124
+ ```
125
+
126
+ Handing work to another agent splits the budget, and the parent can't spend it twice:
127
+
128
+ ```python
129
+ child_budget = session.budget.split(tokens=10_000, tool_calls=3)
130
+ ```
131
+
132
+ ## Development
133
+
134
+ ```bash
135
+ uv sync
136
+ uv run pytest
137
+ uv run mypy src
138
+ uv run ruff check
139
+ ```
140
+
141
+ ## License
142
+
143
+ Apache-2.0
@@ -0,0 +1,13 @@
1
+ concordat/__init__.py,sha256=Wz5UNqaMGKxqfCpKiEXNbGpuch_9ahrAHyVXDJT0kcE,573
2
+ concordat/_runner.py,sha256=vbCrqPGDZcipeuz9lOt9TJb860keS2to4JxUxWgF1ow,3766
3
+ concordat/agent.py,sha256=JxBw19MLARSI3kBSK7r6P_Wzlr9guy71-5Ofyn7n020,7019
4
+ concordat/anthropic.py,sha256=1alIS-YbW8BRBcCOIzf59CVb5__mZuhiqvBH6wgKaiA,4320
5
+ concordat/budget.py,sha256=w8RVwu1OQWumh_cg7cdG3eoNyH3IhxLgMHLwU1Fl4dc,1622
6
+ concordat/openai.py,sha256=M0w9woHeKX5F-8dp8TRTMibiSrGPj0x45GRRqKIuP7s,4168
7
+ concordat/protocol.py,sha256=Ql_SG-cbGr1GT1s8bMaXImh7H1s4CtNwvILCZIVS0Dw,2908
8
+ concordat/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ concordat/session.py,sha256=8SBJVycXPAK6RNNlSPgSNYX7lLGBECKzdfRtR3u2NXA,1721
10
+ concordat-0.0.1.dist-info/METADATA,sha256=mK3iQwRZsAg5sY5An3_3Z79fD_3x9ckj2b92obAaz-8,4984
11
+ concordat-0.0.1.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
12
+ concordat-0.0.1.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
13
+ concordat-0.0.1.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,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.