Pattern API¶
This page renders signatures and docstrings from the current source. The task-focused pages under Patterns explain when to use each function.
Async patterns¶
consensus¶
executionkit.patterns.consensus.consensus
async
¶
consensus(provider: LLMProvider, prompt: str, *, num_samples: int = 5, strategy: VotingStrategy | str = 'majority', temperature: float = _DEFAULT_TEMPERATURE, max_tokens: int = DEFAULT_MAX_TOKENS, max_concurrency: int = _DEFAULT_CONSENSUS_CONCURRENCY, retry: RetryConfig | None = None, max_cost: TokenUsage | None = None, trace: TraceCallback | None = None) -> PatternResult[str]
Run parallel LLM samples and aggregate via voting.
Fires num_samples concurrent completions and applies the chosen
voting strategy to determine the winning response.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
provider
|
LLMProvider
|
LLM provider to call. |
required |
prompt
|
str
|
User prompt sent identically to every sample. |
required |
num_samples
|
int
|
Number of parallel completions to request. Must be >= 1. |
5
|
strategy
|
VotingStrategy | str
|
|
'majority'
|
temperature
|
float
|
Sampling temperature (higher = more diverse). |
_DEFAULT_TEMPERATURE
|
max_tokens
|
int
|
Maximum tokens per completion. |
DEFAULT_MAX_TOKENS
|
max_concurrency
|
int
|
Semaphore limit for parallel calls. |
_DEFAULT_CONSENSUS_CONCURRENCY
|
retry
|
RetryConfig | None
|
Optional retry configuration per call. |
None
|
max_cost
|
TokenUsage | None
|
Optional token/call budget. Passed to each individual
|
None
|
trace
|
TraceCallback | None
|
Optional structured trace callback. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
PatternResult[str]
|
class: |
PatternResult[str]
|
|
|
PatternResult[str]
|
|
Raises:
| Type | Description |
|---|---|
ConsensusFailedError
|
When |
ValueError
|
If |
Source code in executionkit/patterns/consensus.py
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 | |
refine_loop¶
executionkit.patterns.refine_loop.refine_loop
async
¶
refine_loop(provider: LLMProvider, prompt: str, *, evaluator: Evaluator | None = None, max_eval_chars: int = _DEFAULT_MAX_EVAL_CHARS, target_score: float = 0.9, max_iterations: int = 5, patience: int = 3, delta_threshold: float = 0.01, temperature: float = _DEFAULT_TEMPERATURE, max_tokens: int = DEFAULT_MAX_TOKENS, max_cost: TokenUsage | None = None, retry: RetryConfig | None = None, trace: TraceCallback | None = None, on_checkpoint: CheckpointCallback | None = None) -> PatternResult[str]
Iteratively refine an LLM response until convergence or budget exhaustion.
Generates an initial response, evaluates it, then enters a refinement
loop. Each iteration asks the LLM to improve upon the previous output
given its score. The loop terminates when the
:class:ConvergenceDetector signals convergence (target score reached
or score deltas stall beyond patience) or max_iterations is hit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
provider
|
LLMProvider
|
LLM provider to call. |
required |
prompt
|
str
|
The original user prompt. |
required |
evaluator
|
Evaluator | None
|
Async callable |
None
|
target_score
|
float
|
Convergence target in |
0.9
|
max_iterations
|
int
|
Maximum refinement iterations (excluding the initial generation). |
5
|
patience
|
int
|
Stale-delta iterations before convergence is declared. |
3
|
delta_threshold
|
float
|
Minimum meaningful score improvement. |
0.01
|
temperature
|
float
|
Sampling temperature for generation calls. |
_DEFAULT_TEMPERATURE
|
max_tokens
|
int
|
Maximum tokens per completion. |
DEFAULT_MAX_TOKENS
|
max_cost
|
TokenUsage | None
|
Optional token/call budget. |
None
|
retry
|
RetryConfig | None
|
Optional retry configuration per call. |
None
|
trace
|
TraceCallback | None
|
Optional structured trace callback. |
None
|
on_checkpoint
|
CheckpointCallback | None
|
Optional callback invoked after scoring each candidate
(the initial generation as iteration 0, then each refinement
iteration), receiving |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
PatternResult[str]
|
class: |
PatternResult[str]
|
|
|
PatternResult[str]
|
|
Source code in executionkit/patterns/refine_loop.py
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 | |
react_loop¶
executionkit.patterns.react_loop.react_loop
async
¶
react_loop(provider: ToolCallingProvider, prompt: str | None = None, tools: Sequence[Tool] = (), *, messages: Sequence[dict[str, Any]] | None = None, max_rounds: int = _DEFAULT_MAX_ROUNDS, max_observation_chars: int = _DEFAULT_MAX_OBSERVATION_CHARS, tool_timeout: float | None = None, max_tool_calls_per_round: int = _DEFAULT_MAX_TOOL_CALLS_PER_ROUND, temperature: float = _DEFAULT_TEMPERATURE, max_tokens: int = DEFAULT_MAX_TOKENS, max_cost: TokenUsage | None = None, retry: RetryConfig | None = None, max_history_messages: int | None = None, trace: TraceCallback | None = None, approval_gate: ApprovalGate | None = None, redact_trace_args: bool = True, on_checkpoint: CheckpointCallback | None = None, summarizer: HistorySummarizer | None = None) -> PatternResult[str]
Execute a think-act-observe tool-calling loop.
The LLM is called repeatedly with the conversation history and
available tool schemas. When the LLM returns tool calls, each tool
is executed and its result appended as a tool-role message. The loop
ends when the LLM responds without tool calls (final answer) or
max_rounds is exhausted.
Supply either prompt (a single new user turn) or messages (a
full prior conversation to continue), not both. Passing messages enables
multi-turn assistants: the returned metadata["messages"] holds the
complete updated transcript (the input history plus this run's assistant
turns, tool results, and final answer) ready to feed into the next call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
provider
|
ToolCallingProvider
|
LLM provider to call. |
required |
prompt
|
str | None
|
Initial user prompt. Sugar for |
None
|
tools
|
Sequence[Tool]
|
Sequence of :class: |
()
|
messages
|
Sequence[dict[str, Any]] | None
|
A prior conversation (OpenAI-format message dicts) to continue instead of starting from prompt. The list is copied, never mutated. |
None
|
max_rounds
|
int
|
Maximum think-act-observe cycles. |
_DEFAULT_MAX_ROUNDS
|
max_observation_chars
|
int
|
Truncation limit for each tool result. |
_DEFAULT_MAX_OBSERVATION_CHARS
|
tool_timeout
|
float | None
|
Per-call timeout override. Falls back to
|
None
|
max_tool_calls_per_round
|
int
|
Ceiling on model-requested tool calls executed in a single round (they run concurrently, so this bounds the fan-out). Surplus calls are never executed; each receives a rejection observation telling the model to retry with fewer. |
_DEFAULT_MAX_TOOL_CALLS_PER_ROUND
|
temperature
|
float
|
Sampling temperature (lower = more deterministic). |
_DEFAULT_TEMPERATURE
|
max_tokens
|
int
|
Maximum tokens per LLM completion. |
DEFAULT_MAX_TOKENS
|
max_cost
|
TokenUsage | None
|
Optional token/call budget. |
None
|
retry
|
RetryConfig | None
|
Optional retry configuration per LLM call. |
None
|
max_history_messages
|
int | None
|
When set, trim the message history to at most
this many entries before each LLM call. Always keeps the first
message (the original prompt). |
None
|
trace
|
TraceCallback | None
|
Optional structured trace callback. |
None
|
approval_gate
|
ApprovalGate | None
|
Optional gate checked before each tool execution. |
None
|
redact_trace_args
|
bool
|
When |
True
|
on_checkpoint
|
CheckpointCallback | None
|
Optional callback invoked after each round that dispatched
tool calls, receiving |
None
|
summarizer
|
HistorySummarizer | None
|
Optional async callback used together with
The callback may return either the summary text or a
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
PatternResult[str]
|
class: |
PatternResult[str]
|
response, |
|
PatternResult[str]
|
|
Source code in executionkit/patterns/react_loop.py
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 | |
structured¶
executionkit.patterns.structured.structured
async
¶
structured(provider: LLMProvider, prompt: str, *, validator: StructuredValidator | None = None, max_retries: int = 3, temperature: float = 0.0, max_tokens: int = 4096, max_cost: TokenUsage | None = None, retry: RetryConfig | None = None, trace: TraceCallback | None = None, stream: bool = False) -> PatternResult[StructuredValue]
Request JSON output, parse it, and optionally repair invalid responses.
Validators should return None, True, or "" for success. Any
other value is treated as a validation failure and included in the repair
prompt. max_retries=0 is supported and means "make one parse attempt
with no repair call".
Source code in executionkit/patterns/structured.py
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 | |
pipe¶
executionkit.compose.pipe
async
¶
pipe(provider: LLMProvider, prompt: str, *steps: PatternStep, max_budget: TokenUsage | None = None, **shared_kwargs: Any) -> PatternResult[Any]
Chain reasoning patterns, threading output as the next prompt.
Each step must be an async callable with the signature::
async def step(provider, prompt, **kwargs) -> PatternResult[Any]
The value of each result is converted to a string and passed as the
prompt to the following step. Costs are accumulated and, when
max_budget is given, the remaining budget is forwarded to each step
via the max_cost keyword argument.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
provider
|
LLMProvider
|
LLM provider passed unchanged to every step. |
required |
prompt
|
str
|
Initial input prompt. |
required |
*steps
|
PatternStep
|
Async pattern callables to chain in order. |
()
|
max_budget
|
TokenUsage | None
|
Optional shared token/call budget across all steps. |
None
|
**shared_kwargs
|
Any
|
Extra keyword arguments forwarded to every step. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
The |
PatternResult[Any]
|
class: |
PatternResult[Any]
|
with its |
|
PatternResult[Any]
|
If steps is empty the prompt is returned as-is with zero cost. |
|
PatternResult[Any]
|
The result |
|
PatternResult[Any]
|
class: |
|
PatternResult[Any]
|
error path the same |
|
PatternResult[Any]
|
spend) is attached to the re-raised exception's |
Source code in executionkit/compose.py
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 | |
map_reduce¶
executionkit.patterns.map_reduce.map_reduce
async
¶
map_reduce(provider: LLMProvider, inputs: Sequence[str], *, map_prompt_template: str, reduce_prompt_template: str, max_concurrency: int = DEFAULT_MAX_CONCURRENCY, temperature: float = _DEFAULT_TEMPERATURE, max_tokens: int = DEFAULT_MAX_TOKENS, max_cost: TokenUsage | None = None, retry: RetryConfig | None = None, trace: TraceCallback | None = None, stream: bool = False) -> PatternResult[str]
Fan-out completions over inputs concurrently, then reduce.
Map phase: for each item in inputs, map_prompt_template is
rendered ({item} replaced by the item) and sent to the provider.
All map calls run concurrently up to max_concurrency.
Reduce phase: all map outputs are joined with a separator and
substituted into reduce_prompt_template ({mapped_outputs}
placeholder). A single reduce call produces the final answer.
An empty inputs sequence skips the map phase entirely and calls the
reduce step with an empty string substituted for {mapped_outputs}.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
provider
|
LLMProvider
|
LLM provider to call. |
required |
inputs
|
Sequence[str]
|
Items to map over. Each is substituted into
|
required |
map_prompt_template
|
str
|
Prompt template with an |
required |
reduce_prompt_template
|
str
|
Prompt template with a |
required |
max_concurrency
|
int
|
Maximum simultaneous map calls. Must be >= 1. |
DEFAULT_MAX_CONCURRENCY
|
temperature
|
float
|
Sampling temperature for both map and reduce calls. |
_DEFAULT_TEMPERATURE
|
max_tokens
|
int
|
Maximum tokens per completion. |
DEFAULT_MAX_TOKENS
|
max_cost
|
TokenUsage | None
|
Optional token/call budget shared across all calls. |
None
|
retry
|
RetryConfig | None
|
Optional retry configuration per call. |
None
|
trace
|
TraceCallback | None
|
Optional structured trace callback. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
PatternResult[str]
|
class: |
PatternResult[str]
|
the reduce completion, |
|
PatternResult[str]
|
includes |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
BudgetExhaustedError
|
If |
Source code in executionkit/patterns/map_reduce.py
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 | |
Synchronous wrappers¶
The wrappers accept the same pattern-specific keyword arguments as their async
counterparts. They use asyncio.run() and therefore cannot run inside an
active event loop.
executionkit.consensus_sync ¶
executionkit.refine_loop_sync ¶
Synchronous wrapper for :func:refine_loop.
executionkit.react_loop_sync ¶
react_loop_sync(provider: ToolCallingProvider, prompt: str, tools: Sequence[Tool] = (), **kwargs: Any) -> PatternResult[str]
Synchronous wrapper for :func:react_loop.
Source code in executionkit/__init__.py
executionkit.structured_sync ¶
Synchronous wrapper for :func:structured.
executionkit.pipe_sync ¶
Synchronous wrapper for :func:pipe.
executionkit.map_reduce_sync ¶
Synchronous wrapper for :func:map_reduce.
Results and values¶
executionkit.types.PatternResult
dataclass
¶
PatternResult(value: T, score: float | None = None, cost: TokenUsage = TokenUsage(), metadata: MappingProxyType[str, Any] = (lambda: MappingProxyType({}))())
Bases: Generic[T]
Result returned by every reasoning pattern.
metadata keys vary by pattern. Each pattern documents its own keys in its
function docstring. Do not rely on undocumented keys — they are private.
executionkit.types.StreamingPatternResult
dataclass
¶
StreamingPatternResult(text_stream: AsyncIterator[str], metadata: MappingProxyType[str, Any] = (lambda: MappingProxyType({}))(), _usage_source: Callable[[], TokenUsage] = _empty_usage)
Result of a streaming pattern call — text delivered as live deltas.
Unlike :class:PatternResult, the output arrives incrementally through
:attr:text_stream, an async iterator of text chunks. Token usage is only
known once the provider emits its final usage frame, so :attr:cost is
not meaningful until text_stream has been fully consumed; reading it
earlier returns whatever has been recorded so far (typically zero).
The object itself is immutable — :attr:cost is a live view over the
originating cost tracker rather than a stored snapshot, which is how a
frozen result can surface usage that is populated only after the stream
drains.
cost
property
¶
Token usage recorded so far — accurate once the stream is drained.
executionkit.types.TokenUsage
dataclass
¶
Accumulated token and call counts.
__sub__ ¶
Return the field-wise difference self - other.
Useful for computing the delta between two :class:CostTracker
snapshots (e.g. per-step cost attribution). No clamping is applied,
so callers that subtract a later snapshot from an earlier one can
observe negative fields.
Source code in executionkit/types.py
executionkit.types.Tool
dataclass
¶
Tool(name: str, description: str, parameters: Mapping[str, Any], execute: Callable[..., Awaitable[str]], timeout: float = DEFAULT_TOOL_TIMEOUT_SECONDS)
Describes a tool available for LLM tool-calling.
parameters is a JSON Schema mapping describing the function arguments.
Automatically wrapped in a read-only proxy.
execute is the async callable invoked when the LLM requests this tool.
executionkit.types.VotingStrategy ¶
Bases: StrEnum
Strategy for consensus voting.
executionkit.types.TerminationReason ¶
Bases: StrEnum
Why a loop pattern stopped iterating.
Surfaced in :class:PatternResult metadata["termination_reason"] so
callers can distinguish a clean finish from an iteration-cap truncation
without catching exceptions.
Members
NATURAL: The loop reached a stopping condition before the cap
(e.g. the LLM returned no tool calls in react_loop).
MAX_ITERATIONS: The iteration cap was reached before the loop
stopped naturally. For react_loop this means the LLM never
returned a tool-call-free response within max_rounds.
Evaluator is an async callable:
It must return a finite score in the inclusive range [0.0, 1.0].
CheckpointCallback receives an iteration index and a plain state dictionary.
It may be synchronous or async:
PatternStep is the callable protocol accepted by pipe():
Advanced helpers¶
Most applications should call a pattern or Kit. Custom pattern authors can
use the same completion, budget, retry, and trace path as built-in patterns:
executionkit.patterns.base.checked_complete
async
¶
checked_complete(provider: LLMProvider, messages: Sequence[dict[str, Any]], tracker: CostTracker, budget: TokenUsage | None, retry: RetryConfig | None, trace: TraceCallback | None = None, **kwargs: Any) -> LLMResponse
Budget check, retry-wrapped complete(), and usage recording.
Performs three steps in order:
- Check whether the token/call budget has been exhausted.
- Call
provider.complete()wrapped inwith_retry(). - Record the response usage on the tracker.
Concurrency model: the budget check and reserve_call() in
_before_attempt are a no-await critical section — there is
deliberately no await between _check_budget and
tracker.reserve_call(). Under cooperative asyncio scheduling this
means no other coroutine can be scheduled between the check and the
reservation, so concurrent coroutines sharing the same CostTracker
cannot both pass the budget check before either has incremented the
counter.
This guarantee relies on cooperative scheduling (single event loop) and
does NOT hold under threading. See :mod:executionkit.cost for
the full concurrency contract.
Trace events carry schema-v2 payloads (see
:mod:executionkit.observability): one llm_call_start per physical
attempt and one terminal llm_call_end/llm_call_error per logical
call, correlated by call_id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
provider
|
LLMProvider
|
LLM provider to call. |
required |
messages
|
Sequence[dict[str, Any]]
|
Chat messages to send. |
required |
tracker
|
CostTracker
|
Cost tracker to record usage. |
required |
budget
|
TokenUsage | None
|
Optional token/call budget. |
required |
retry
|
RetryConfig | None
|
Retry configuration. Uses |
required |
trace
|
TraceCallback | None
|
Optional structured trace callback. |
None
|
**kwargs
|
Any
|
Additional arguments forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
LLMResponse
|
The LLM response. |
Raises:
| Type | Description |
|---|---|
BudgetExhaustedError
|
If the budget has been exceeded before the call. |
CancelledError
|
Always propagated (via |
Source code in executionkit/patterns/base.py
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 | |
executionkit.patterns.base.checked_stream
async
¶
checked_stream(provider: StreamingProvider, messages: Sequence[dict[str, Any]], tracker: CostTracker, budget: TokenUsage | None, retry: RetryConfig | None, trace: TraceCallback | None = None, **kwargs: Any) -> StreamingPatternResult
Budget-checked, trace-instrumented streaming completion.
Parallel to :func:checked_complete, but yields live text deltas instead
of returning a single response. Before any token is produced it eagerly:
- Checks the budget — raises :exc:
BudgetExhaustedErrorif exhausted. - Calls
tracker.reserve_call()in the same no-await segment as the budget check (same concurrency contract as :func:checked_complete). - Emits the
llm_call_starttrace event.
The returned :class:StreamingPatternResult wraps the provider stream so
that, once the caller drains it, token usage is recorded
(record_without_call) and llm_call_end is emitted. If the stream
raises mid-flight, llm_call_error is emitted and the exception
propagates to the consumer.
Streaming providers commonly report no usage object at all; in that
case the end event carries usage_reported: False and None token
counts rather than fabricated zeros.
Retry is not supported for streaming — a partial stream cannot be
replayed — so a non-None retry is logged and ignored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
provider
|
StreamingProvider
|
Streaming-capable LLM provider. |
required |
messages
|
Sequence[dict[str, Any]]
|
Chat messages to send. |
required |
tracker
|
CostTracker
|
Cost tracker to record usage on. |
required |
budget
|
TokenUsage | None
|
Optional token/call budget. |
required |
retry
|
RetryConfig | None
|
Ignored (logged) — streaming cannot be retried. |
required |
trace
|
TraceCallback | None
|
Optional structured trace callback. |
None
|
**kwargs
|
Any
|
Forwarded to |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
StreamingPatternResult
|
class: |
StreamingPatternResult
|
and whose |
Raises:
| Type | Description |
|---|---|
BudgetExhaustedError
|
If the budget is exhausted before dispatch. |
Source code in executionkit/patterns/base.py
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 | |
executionkit.patterns.base.validate_score ¶
Validate an evaluator score is in [0.0, 1.0] and not NaN.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
score
|
float
|
The score to validate. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The validated score (unchanged). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the score is NaN or outside [0.0, 1.0]. |
Source code in executionkit/patterns/base.py
executionkit.engine.json_extraction.extract_json ¶
Extract JSON from LLM output using multiple strategies.
Strategies (in order):
1. Raw json.loads(text.strip())
2. Markdown code fences -- the first `json fence, then the first generic
fence whose body looks like JSON. Located withstr.findso an
unterminated fence in untrusted input degrades to a linear scan instead
of the polynomial backtracking a.*?regex would incur under DOTALL.
3. Balanced-brace extraction -- find first{or[``, track nesting
depth respecting string boundaries, find matching closer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Raw LLM response text that may contain JSON. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | list[Any]
|
Parsed JSON as a dict or list. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no valid JSON can be extracted. |
Source code in executionkit/engine/json_extraction.py
checked_complete() and checked_stream() require a caller-owned
CostTracker. Preserve the source ordering of the budget check and call
reservation: their no-await interval prevents concurrent asyncio tasks from
passing the same call-budget slot.