teff.harness¶
teff.harness
¶
Agent harness — reusable model↔tool loop.
A harness owns the transport and provider plumbing for one model and
drives the agent loop: call the model, execute requested tools, feed
the results back into the conversation. It is shared by the
:class:~teff.node.llm.LLM node (internal multi-round loop) and the
:class:~teff.node.agent.ReActAgent (one step per graph round, so the
loop stays visible as topology). Tools are ordinary
:class:~teff.tool.Tool instances keyed by name, so MCP tools and
built-in tools work unchanged.
Behaviour can be parameterised through the constructor / ``from_config``:
- ``max_rounds`` — stop the ``run()`` loop after this many model calls.
- ``stop_when(messages)`` — extra termination predicate.
- ``parse_text_tool_calls`` — decode tool calls embedded in plain text
(local models often skip the structured ``tool_calls`` field).
- ``tool_error_mode`` — ``"message"`` (default, errors become tool
messages) or ``"raise"`` (a tool failure propagates, e.g. into an
``__error__`` edge).
- ``tool_timeout`` — per-tool execution timeout in seconds.
- ``tool_retries`` — extra attempts per tool call after a failure.
- ``max_retries`` — retry failed HTTP requests (429/5xx/timeouts).
- ``retry_on`` — status codes / error types worth retrying.
- ``fallbacks`` — list of fallback model names used when the primary
transport fails (provider failover).
- ``max_total_tokens`` — stop the loop once total prompt+completion
tokens exceed this budget.
- ``max_context_tokens`` / ``max_context_messages`` — trim the
conversation history before each model call to fit these limits.
- ``cache`` — cache model responses keyed by request so re-runs /
checkpoint resumes do not pay for the same call twice.
- ``on_tool_call`` — async hook ``(name, args) -> Awaitable[None]``
invoked before each tool executes (approval/auditing).
- ``on_step`` / ``on_llm`` / ``on_token`` — observability hooks.
Modules:
| Name | Description |
|---|---|
context |
Context management — token estimation and message trimming. |
formats |
Response parsing and message-format normalisation for LLM providers. |
loop |
The Harness — transport + agent loop for a single model. |
providers |
Backward-compatible alias for :mod: |
schema |
Tool schema conversion — Python signatures to OpenAI-style function schemas. |
tools |
Tool-approval resolution and parallel tool-call execution. |
Classes:
| Name | Description |
|---|---|
ContextLimitError |
Raised when a conversation cannot fit the configured context limits. |
Harness |
Transport + loop for one model, reusable across nodes and flows. |
ModelReply |
A single model call's result. |
Provider |
A named model endpoint: wire protocol + endpoint data. |
Step |
One iteration of the agent loop (model call + any tool execution). |
Functions:
| Name | Description |
|---|---|
execute_tool_calls |
Execute tool_calls against tools in parallel. |
extract_content |
Extract the assistant text from a response. |
extract_message |
Normalise response formats to |
extract_usage |
Extract |
normalize_text_tool_calls |
Turn a text-embedded tool call into the structured |
parse_text_tool_call |
Parse a tool call embedded in plain text content. |
provider_concurrency |
Return the current global concurrency limit for provider (if any). |
resolve_approval |
Resolve a tool-approval decision for one tool call. |
resolve_provider |
Resolve a provider key from an explicit value or a default name. |
resolve_provider_entry |
Resolve the effective :class: |
set_provider_concurrency |
Globally cap concurrent model calls for provider. |
tool_to_schema |
Convert a :class: |
trim_messages |
Trim messages down to fit context limits. |
ContextLimitError
¶
Bases: WorkflowError
Raised when a conversation cannot fit the configured context limits.
Source code in teff/harness/context.py
89 90 | |
Harness
¶
Transport + loop for one model, reusable across nodes and flows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str
|
Model name (e.g. |
required |
provider
|
str | None
|
Provider name ( |
None
|
base_url / api_key_env / chat_path / auth_header / auth_prefix
|
Overrides for the provider defaults. |
required | |
providers
|
'dict[str, Provider] | ProviderRegistry | None'
|
Optional |
None
|
timeout
|
float | None
|
HTTP timeout in seconds. |
120
|
max_rounds
|
int
|
Maximum model calls for :meth: |
10
|
parse_text_tool_calls
|
bool
|
Decode text-embedded tool calls. |
True
|
tool_error_mode
|
str
|
|
'message'
|
stop_when
|
Callable[[list[dict]], bool] | None
|
Optional |
None
|
on_step
|
Callable[[Step], Awaitable[None]] | None
|
Async callback |
None
|
on_llm
|
Callable[[str, str, int, int, float], Awaitable[None]] | None
|
Async callback |
None
|
on_token
|
Callable[[str], Awaitable[None]] | None
|
Token callback for streaming. |
None
|
temperature / max_tokens / response_format
|
Default body extras. |
required | |
stream
|
bool
|
Stream tokens by default (disabled while tools are active). |
False
|
default_provider
|
str | None
|
Fallback provider name (the graph-level default,
e.g. |
None
|
Methods:
| Name | Description |
|---|---|
call |
One model call. |
from_config |
Build a harness from a node config dict. |
manage_context |
Trim messages to the configured context limits. |
run |
Loop :meth: |
step |
One iteration: call the model, execute requested tools, feed back. |
Source code in teff/harness/loop.py
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 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 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 412 413 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 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 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 888 889 890 891 892 893 894 895 896 897 898 | |
call
async
¶
call(messages, *, tools=None, stream=None, content_path='')
One model call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
|
list[dict]
|
Message history. |
required |
tools
|
list[dict] | None
|
Tool schemas to attach (disables streaming). |
None
|
stream
|
bool | None
|
Force streaming on/off (defaults to self.stream and automatically off when tools are attached). |
None
|
content_path
|
str
|
Dot-separated path for content extraction. |
''
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
ModelReply
|
class: |
Source code in teff/harness/loop.py
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 | |
from_config
classmethod
¶
from_config(cfg, *, default_provider=None, default_model=None, providers=None)
Build a harness from a node config dict.
Recognises the transport keys shared by LLM and
ReActAgent plus the loop knobs max_tool_rounds,
tool_error_mode, parse_text_tool_calls, tool_timeout,
tool_retries, max_retries, fallbacks,
max_total_tokens, max_context_tokens and
max_context_messages.
providers is an optional {name: Provider} map or
:class:~teff.provider.ProviderRegistry (custom providers from
the workflow) consulted before the built-in presets.
The model name comes from cfg["model"] or, when absent,
default_model (the graph-level default). When neither is set a
:class:ConfigError is raised — there is no silent model default.
Source code in teff/harness/loop.py
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 | |
manage_context
¶
manage_context(messages)
Trim messages to the configured context limits.
Applies max_context_tokens / max_context_messages
(whichever is set). The leading system message is preserved.
Source code in teff/harness/loop.py
863 864 865 866 867 868 869 870 871 872 873 874 875 | |
run
async
¶
run(messages, tools)
Loop :meth:step until a final answer, stop_when, or max_rounds.
Stops early when the cumulative token budget (max_total_tokens) is exceeded.
Returns the final :class:Step (its content holds the answer;
messages holds the full history).
Source code in teff/harness/loop.py
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 | |
step
async
¶
step(messages, tools)
One iteration: call the model, execute requested tools, feed back.
Returns a :class:Step whose messages is the updated history
(assistant message plus any tool responses). History is
trimmed to max_context_tokens / max_context_messages before
the call.
Source code in teff/harness/loop.py
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 | |
ModelReply
dataclass
¶
A single model call's result.
Source code in teff/harness/loop.py
111 112 113 114 115 116 117 118 119 120 | |
Provider
¶
A named model endpoint: wire protocol + endpoint data.
name is the registry key used by provider= references.
type is the protocol discriminator — openai_compatible /
anthropic_compatible / ollama — and decides the request body,
streaming chunk parsing, and response extraction held by
:class:~teff.harness.Harness.
Built-in presets subclass this and set name (and the other fields)
once; a custom provider is a plain instance. Fields may be overridden
at construction:
Provider(name="my-vllm", type="openai_compatible", base_url="http://vllm:8000/v1")
type is deliberately a distinct concept from name: the name is
just a key and never carries protocol meaning.
Methods:
| Name | Description |
|---|---|
from_mapping |
Build from a config dict, keeping only known fields. |
to_dict |
All provider fields as a plain dict (for YAML serialisation). |
Source code in teff/provider/builtin/base.py
22 23 24 25 26 27 28 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 | |
from_mapping
classmethod
¶
from_mapping(cfg)
Build from a config dict, keeping only known fields.
Source code in teff/provider/builtin/base.py
58 59 60 61 | |
to_dict
¶
to_dict()
All provider fields as a plain dict (for YAML serialisation).
Source code in teff/provider/builtin/base.py
63 64 65 | |
Step
dataclass
¶
One iteration of the agent loop (model call + any tool execution).
Attributes:
| Name | Type | Description |
|---|---|---|
wants_tool |
bool
|
Whether the step ended requesting more tool execution. |
Source code in teff/harness/loop.py
123 124 125 126 127 128 129 130 131 132 133 134 135 | |
execute_tool_calls
async
¶
execute_tool_calls(
tool_calls,
tools,
tool_error_mode="message",
timeout=None,
tool_retries=0,
approver=None,
state=None,
ctx=None,
)
Execute tool_calls against tools in parallel.
Each call resolves to a result string (errors become "Error ..."
messages unless tool_error_mode is "raise"). Each call is
retried up to tool_retries times on failure and bounded by timeout
seconds when set. An optional approver gates each call before it
runs (see :func:resolve_approval); non-"approve" decisions
short-circuit the call with a "not approved" message.
state / ctx are injected into tools that declare __state__ /
__ctx__ runtime kwargs (sub-agent tools), so they can read/write the
enclosing workflow state and forward tracing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool_calls
|
list[dict]
|
List of tool-call dicts. |
required |
tools
|
Mapping[str, Tool]
|
Tool registry (name -> |
required |
tool_error_mode
|
str
|
|
'message'
|
timeout
|
float | None
|
Per-tool timeout in seconds ( |
None
|
tool_retries
|
int
|
Extra attempts per tool call after a failure. |
0
|
approver
|
Any
|
Approval policy (string or callable). |
None
|
state
|
dict | None
|
Workflow state dict to expose to state-aware tools. |
None
|
ctx
|
Any
|
:class: |
None
|
Source code in teff/harness/tools.py
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 | |
extract_content
¶
extract_content(data, provider_type, path='', fallback='')
Extract the assistant text from a response.
path is a dot-separated path into data; otherwise the extraction
follows the wire protocol provider_type (Anthropic content blocks,
Ollama root message).
Source code in teff/harness/formats.py
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 | |
extract_message
¶
extract_message(data)
Normalise response formats to {role, content, tool_calls}.
Handles OpenAI (data["choices"][0]["message"]) and
Ollama (data["message"] at root).
Source code in teff/harness/formats.py
12 13 14 15 16 17 18 19 20 21 22 | |
extract_usage
¶
extract_usage(data)
Extract (prompt_tokens, completion_tokens) from an LLM response.
Handles both OpenAI-style (data["usage"]) and Ollama-style
(data["prompt_eval_count"] / data["eval_count"]) formats.
Source code in teff/harness/formats.py
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 | |
normalize_text_tool_calls
¶
normalize_text_tool_calls(content, msg, *, seq=0)
Turn a text-embedded tool call into the structured tool_calls list.
When content parses as a single {name, arguments|parameters}
object, returns ([tool_call], msg_with_tool_calls); otherwise
returns ([], msg) unchanged. The generated call_id is derived
from seq + the tool name so it is unique within a run.
Returns:
| Type | Description |
|---|---|
list[dict]
|
A |
dict
|
|
Source code in teff/harness/formats.py
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 | |
parse_text_tool_call
¶
parse_text_tool_call(content)
Parse a tool call embedded in plain text content.
Local models sometimes emit {"name": "rag", "parameters": {...}}
or {"name": "rag", "arguments": {...}} as text instead of using
the structured tool_calls field. Returns (name, args) if found.
Source code in teff/harness/formats.py
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 | |
provider_concurrency
¶
provider_concurrency(provider)
Return the current global concurrency limit for provider (if any).
Returns the active semaphore's capacity (explicit or auto-grown via
max_parallel), or None when the provider has no semaphore.
Source code in teff/provider/concurrency.py
44 45 46 47 48 49 50 | |
resolve_approval
async
¶
resolve_approval(approver, name, args)
Resolve a tool-approval decision for one tool call.
approver may be:
"auto"(orNone) →"approve""deny"→"deny"(no call ever runs)"interactive"→ prompt the operator on stdin- a callable
(name, args) -> str | bool(sync or async) returning"approve"/"deny"/"pause"(orTrue/False).
Returns one of "approve", "deny", "pause".
Source code in teff/harness/tools.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | |
resolve_provider
¶
resolve_provider(provider=None, default_provider=None)
Resolve a provider key from an explicit value or a default name.
The explicit provider (node-level) wins; otherwise default_provider (the graph-level default) is used. Model-name auto-detection was removed — a provider must be stated explicitly.
Raises:
| Type | Description |
|---|---|
ConfigError
|
When neither a provider nor a default is configured. |
Source code in teff/provider/resolve.py
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 | |
resolve_provider_entry
¶
resolve_provider_entry(provider_key, providers=None)
Resolve the effective :class:Provider for provider_key.
When providers is a :class:ProviderRegistry or dict it is
authoritative — provider_key must be declared in it. With None
(a bare, standalone Harness) a built-in preset is used. Unknown
names raise a :class:ConfigError — there is no silent fallback to the
OpenAI shape, so typos surface early instead of silently routing to the
wrong wire protocol.
Raises:
| Type | Description |
|---|---|
ConfigError
|
When provider_key is neither declared in providers
nor (with |
Source code in teff/provider/resolve.py
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 | |
set_provider_concurrency
¶
set_provider_concurrency(provider, limit)
Globally cap concurrent model calls for provider.
Overrides any per-harness max_parallel for that provider.
Pass limit <= 0 to remove the cap.
Source code in teff/provider/concurrency.py
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | |
tool_to_schema
¶
tool_to_schema(tool)
Convert a :class:~teff.tool.Tool to an OpenAI-style function schema.
Uses the tool's schema attribute when set (e.g. by MCP tools);
otherwise infers parameters from the run/arun signature.
Nested type hints (list[dict], dict[str, str], dataclasses,
TypedDict) expand to nested JSON Schemas.
Source code in teff/harness/schema.py
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 | |
trim_messages
¶
trim_messages(messages, max_tokens=None, max_messages=None)
Trim messages down to fit context limits.
The leading system message (if any) is always preserved; older
messages are dropped from the front of the conversation until the
estimated token count and message count fit the limits.
A limit <= 0 keeps only the system message(s). When the system
message alone cannot fit max_tokens (and dropping it is not allowed)
a :class:ContextLimitError is raised.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
|
list[dict]
|
The conversation history. |
required |
max_tokens
|
int | None
|
Maximum estimated tokens to keep. |
None
|
max_messages
|
int | None
|
Maximum number of messages to keep. |
None
|
Returns:
| Type | Description |
|---|---|
list[dict]
|
A new list of messages, trimmed from the front (system kept). |
Raises:
| Type | Description |
|---|---|
ContextLimitError
|
When even the system message alone would exceed max_tokens (system is never dropped). |
Source code in teff/harness/context.py
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 | |