Agent¶
The high-level entry point — configure an Agent, run it, and read
back a typed AgentResult.
For the concepts, start with Agent and the agent loop.
Agent class¶
Agent(
model: str | ModelProtocol | None = None,
tools: list[Tool] | None = None,
system_prompt: str | None = None,
reflexion: ReflexionConfig | bool | None = None,
grounding: GroundingConfig | bool | None = None,
max_iterations: int = 20,
conversation_manager: ConversationManager | None = None,
checkpointer: Checkpointer | None = None,
hooks: list[HookProvider] | None = None,
config: AgentConfig | None = None,
**kwargs,
)
Agent ¶
Bases: AgentRuntimeMixin, BaseModel
Primary entry point for Tulip agents.
Manages the ReAct loop with optional Reflexion and Grounding.
Usage
agent = Agent( model="openai:gpt-4o", # or anthropic:claude-sonnet-4-6 tools=[search, calculate], system_prompt="You are a helpful assistant.", )
Async streaming¶
async for event in agent.run("What is 2+2?"): print(event)
Sync execution¶
result = agent.run_sync("What is 2+2?") print(result.message)
Initialize an Agent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str | Any | None
|
Model string or ModelProtocol instance |
None
|
tools
|
list[Tool] | None
|
List of tools available to the agent |
None
|
system_prompt
|
str | None
|
System prompt for the agent |
None
|
reflexion
|
ReflexionConfig | bool | None
|
Reflexion config (True for defaults, False/None to disable) |
None
|
grounding
|
GroundingConfig | bool | None
|
Grounding config (True for defaults, False/None to disable) |
None
|
max_iterations
|
int
|
Maximum iterations before stopping |
20
|
conversation_manager
|
Any | None
|
Conversation manager for message pruning |
None
|
checkpointer
|
Any | None
|
Checkpointer for state persistence |
None
|
hooks
|
list[Any] | None
|
Lifecycle hooks |
None
|
config
|
AgentConfig | None
|
Full AgentConfig (overrides other params) |
None
|
**kwargs
|
Any
|
Any other :class:
See :class: |
{}
|
Source code in .sdk/src/tulip/agent/agent.py
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 | |
observation_pack
property
¶
The agent's :class:~tulip.memory.observation_pack.ObservationPack, or None.
Its stats(session) says what it did for a thread (or a thread-less
run, by run id).
is_cancelled
property
¶
Whether a cancel-all (cancel() with no thread id) is pending.
system_prompt
property
¶
Get the configured system prompt as a string.
If the config value is a callable (dynamic prompt), it is
coerced to its repr so this property never returns non-str.
Use self.config.system_prompt directly to access the raw
value (string or callable) when you need to invoke the
dynamic form.
arun
async
¶
Run the agent asynchronously and return a single AgentResult.
This is the async, browser-safe equivalent of :meth:run_sync: it
drives the same event loop (self.run(...)), builds the same
AgentResult, but without spawning a thread or calling
asyncio.run. That makes it usable in environments where threads
are unavailable — notably Pyodide / WebAssembly, where run_sync cannot work.
Unlike run_sync it does NOT close the underlying model client or
checkpointer pool afterward — the caller owns the loop, so those
resources stay bound to it and can be reused across arun calls.
Each call starts from an empty conversation unless you give it
somewhere to remember: prior turns are reloaded only when the agent has
a checkpointer configured and you pass thread_id. Calling
run_sync(prompt) in a loop therefore produces independent turns,
not a conversation — which is the right default for a shared agent, and
a surprise if you expected it to follow along.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompt
|
str
|
User prompt to process |
required |
thread_id
|
str | None
|
Conversation to continue. Required (with a configured checkpointer) for this run to see earlier turns. |
None
|
metadata
|
dict[str, Any] | None
|
Additional metadata for tools |
None
|
Returns:
| Type | Description |
|---|---|
AgentResult
|
AgentResult with final message and state |
Source code in .sdk/src/tulip/agent/agent.py
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 | |
drain_memory
async
¶
Wait for the memory manager's background extractions to finish.
With LLMMemoryManager(extract_mode="background") extraction runs
after a turn's final event; await this at graceful shutdown (and in
tests) so none is lost — bound it with asyncio.timeout(...) if
needed. A no-op without a memory manager or in "inline" mode.
:meth:run_sync calls it before returning.
Source code in .sdk/src/tulip/agent/agent.py
run_sync ¶
Run the agent synchronously.
Blocking wrapper around :meth:arun: it drives self.arun(...) on
a fresh event loop (or a worker thread when a loop is already
running) and closes the model / checkpointer clients bound to that
loop before returning. In thread-less environments (Pyodide / WASM)
this cannot work — call await self.arun(...) directly there.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompt
|
str
|
User prompt to process |
required |
thread_id
|
str | None
|
Optional thread ID for checkpointing |
None
|
metadata
|
dict[str, Any] | None
|
Additional metadata for tools |
None
|
Returns:
| Type | Description |
|---|---|
AgentResult
|
AgentResult with final message and state |
Source code in .sdk/src/tulip/agent/agent.py
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 | |
invoke ¶
Invoke the agent (alias for run_sync).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompt
|
str
|
User prompt to process |
required |
thread_id
|
str | None
|
Optional thread ID for checkpointing |
None
|
metadata
|
dict[str, Any] | None
|
Additional metadata for tools |
None
|
Returns:
| Type | Description |
|---|---|
AgentResult
|
AgentResult with final message and state |
Source code in .sdk/src/tulip/agent/agent.py
cancel ¶
Cancel running agent work from any thread or task.
Sets a signal the agent loop checks at each iteration; the run stops
gracefully with stop_reason="cancelled".
cancel(thread_id="t-42")stops only the in-flight run(s) on that thread — the form a multi-user server wants, where one Agent serves every conversation.cancel()(no argument) keeps the pre-2.17 meaning: stop every in-flight run of this agent, and if none is running yet, the next run to start.
Thread-safe — can be called from any thread while the agent is running.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
thread_id
|
str | None
|
Only cancel runs on this conversation. |
None
|
Returns:
| Type | Description |
|---|---|
int
|
How many in-flight runs were signalled (a no-argument call with |
int
|
nothing running still arms the signal for the next run and |
int
|
returns 0). |
Example
import threading
def run_agent(): result = agent.run_sync("Long task...") print(result.stop_reason) # "cancelled"
t = threading.Thread(target=run_agent) t.start() time.sleep(5) agent.cancel() # Stop from main thread t.join()
Source code in .sdk/src/tulip/agent/agent.py
pending_interrupts ¶
Thread ids that have a paused run held in this process's memory.
A thread paused in another process (or before a restart) is not
listed; resume(thread_id=...) still rehydrates it from the
checkpointer.
Source code in .sdk/src/tulip/agent/agent.py
run_subagent
async
¶
Run an isolated child agent and return its :class:SubagentResult.
Thin binding of :func:tulip.agent.subagent.run_subagent to this
agent: the child defaults to this agent's model, and this agent's
:meth:cancel stops the child — whether the call comes from one of
this agent's tool bodies mid-run or from a harness between runs.
Isolation is the point: the child gets a fresh conversation, its own
system prompt, and ONLY the tools in tools — never this agent's
toolset by inheritance. When called from a tool body during a run,
the child's token usage folds into this run's counters, so
token_budget and TerminateEvent.usage keep counting
delegated spend. See :mod:tulip.agent.subagent for the full
contract and a harness-side task-tool example.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompt
|
str
|
The delegated task. |
required |
tools
|
list[Tool] | None
|
Explicit tool allowlist for the child (default: none). |
None
|
system_prompt
|
str
|
The child's system prompt. |
'You are a focused subagent. Complete the delegated task.'
|
model
|
str | Any | None
|
Child model override; defaults to this agent's model. |
None
|
name
|
str
|
Attribution label stamped on the child's events. |
'subagent'
|
max_iterations
|
int
|
The child's iteration cap. |
10
|
hooks
|
list[Any] | None
|
Lifecycle hooks for the child (policy attaches here). |
None
|
on_event
|
Callable[[TulipEvent], Awaitable[None] | None] | None
|
Callback receiving every child event (sync or async). |
None
|
**agent_kwargs
|
Any
|
Further |
{}
|
Returns:
| Type | Description |
|---|---|
SubagentResult
|
SubagentResult with the child's text, usage, iterations, and |
SubagentResult
|
stop reason. |
Source code in .sdk/src/tulip/agent/agent.py
as_tool ¶
Wrap this agent as a Tool for use by another agent.
The returned tool accepts a prompt string and returns the agent's final response. This enables agent delegation — a parent agent can call a sub-agent as if it were any other tool.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str | None
|
Tool name (defaults to agent_id or "sub_agent") |
None
|
description
|
str | None
|
Tool description (defaults to system prompt excerpt) |
None
|
Returns:
| Type | Description |
|---|---|
Tool
|
A Tool that runs this agent when called |
Example
researcher = Agent( ... model=model, tools=[search], system_prompt="You research topics." ... ) writer = Agent(model=model, tools=[researcher.as_tool("research")]) result = writer.run_sync("Write about quantum computing")
Source code in .sdk/src/tulip/agent/agent.py
resume
async
¶
Resume agent execution after an interrupt.
When a tool calls ask_user() and the agent yields an InterruptEvent, call this method with the user's response to continue execution.
Resume is keyed strictly by thread. Paused runs are held in memory
per thread_id; resume(thread_id="A") only ever continues
thread A — from memory when this process paused it, otherwise
rehydrated from the configured checkpointer (a fresh process: the pod
that paused is gone). It never picks up another thread's pause.
Without thread_id the call is accepted only when exactly one run
is paused in memory (the single-conversation back-compat form); with
several paused it raises rather than guess.
A resumed run continues the SAME turn: its iteration count and budgets carry on from the pause.
perform_dangling closes the gap the 2.11.1 fold left open for
approval holds. The fold answers the dangling call with the human's
verdict TEXT — the model reads "approve" as the call's result and,
reasonably, never re-issues a call that already returned, so nothing
ever performs the action (measured live; see
FINDING-an-approved-action-can-silently-not-happen.md for the first
half of this story). With perform_dangling=True and a dangling
call that is not ask_user, the runtime RE-INVOKES that call —
same tool, same arguments, through the normal executor — and folds
the REAL result instead. A gated tool decides for itself under the
caller's primed decision: approve executes, deny refuses, and either
way the model sees what actually happened. ask_user and the
no-dangling-call case are untouched, so answers behave exactly as
before regardless of the flag.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
response
|
str
|
The user's response to the interrupt question |
required |
thread_id
|
str | None
|
The paused thread to continue. Resumes that thread's in-memory interrupt, or rehydrates it from the checkpointer. |
None
|
perform_dangling
|
bool
|
Re-invoke a dangling non- |
False
|
metadata
|
dict[str, Any] | None
|
Invocation metadata for the resumed segment (what tools
see as |
None
|
Raises:
| Type | Description |
|---|---|
ApprovalPendingError
|
|
RuntimeError
|
Nothing to resume (no paused run for the thread and
no checkpoint), or |
Yields:
| Type | Description |
|---|---|
AsyncGenerator[TulipEvent, None]
|
TulipEvent instances for the remaining execution |
Example
async for event in agent.run("Build an app"): ... if isinstance(event, InterruptEvent): ... answer = input(event.question) ... async for event in agent.resume(answer): ... handle(event)
Source code in .sdk/src/tulip/agent/agent.py
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 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 | |
continue_turn
async
¶
Continue a turn that stopped before it finished, from its checkpoint.
A process killed mid-turn (a deploy, an OOM, a lost pod) leaves the
thread's latest checkpoint inside the turn — with
checkpoint_every_n_iterations set, at the last iteration whose
tool results were saved. run() on that thread would start a NEW
turn with a new user message; this continues the SAME turn instead:
no user message is added, iteration count and budgets carry on, and
every call whose result is in the checkpoint stays done — the model
is called next, with those results in front of it.
A call the checkpoint holds without a result (the process stopped while it ran) is answered with an error saying its outcome is unknown, never re-run: re-running a side effect the first attempt may already have performed is the model's decision to make, with that error in front of it.
A thread paused on an interrupt in this process is answered with
:meth:resume, which folds the human's response; continue_turn
refuses it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
thread_id
|
str
|
The thread whose turn to continue. |
required |
metadata
|
dict[str, Any] | None
|
Invocation metadata for the continued segment. Defaults
to the thread's checkpointed metadata; ephemeral keys
( |
None
|
model_kwargs
|
dict[str, Any] | None
|
Per-call model parameters, as for :meth: |
None
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
No checkpointer, no checkpoint for the thread, the
thread is paused on an in-memory interrupt, or its last turn
already finished with an answer (start a new one with
|
Yields:
| Type | Description |
|---|---|
AsyncGenerator[TulipEvent, None]
|
TulipEvent instances for the rest of the turn. |
Source code in .sdk/src/tulip/agent/agent.py
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 | |
get_state
async
¶
The thread's state at checkpoint_id, or its latest.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
The agent has no checkpointer. |
LookupError
|
No such thread or checkpoint. |
Source code in .sdk/src/tulip/agent/agent.py
get_state_history
async
¶
(checkpoint_id, state) pairs for the thread, newest first.
Source code in .sdk/src/tulip/agent/agent.py
update_state
async
¶
Write a new checkpoint: the given one (or the latest) plus these changes.
The source checkpoint is never modified, so history stays intact and
the edit can itself be inspected or forked. The next run or
resume on the thread continues from the new checkpoint.
Returns:
| Type | Description |
|---|---|
str
|
The new checkpoint's id. |
Source code in .sdk/src/tulip/agent/agent.py
fork
async
¶
Start a new thread from the given checkpoint (or the latest).
The new thread carries the conversation up to that point and nothing after it; running on it never changes the parent thread.
Returns:
| Type | Description |
|---|---|
str
|
The new thread's id. |
Source code in .sdk/src/tulip/agent/agent.py
add_tool ¶
Register a tool on this agent after construction.
Tulip compiles config.tools into the runtime ToolRegistry
once, inside __init__ (via :func:tulip.agent.initializer.
initialize_agent). Mutating self.config.tools directly after
that point is a silent no-op — the model never sees the added
tool because the registry has already been built.
Use this method (or :meth:add_tools) when you want to compose a
specialist fleet at runtime: build each specialist, wrap it via
Agent.as_tool(...), and attach the wrappers to the
orchestrator.
The tool is also appended to self.config.tools so that a
subsequent re-initialisation (e.g. after a config-driven
clone) sees the same shape.
Raises:
| Type | Description |
|---|---|
TypeError
|
if |
ValueError
|
if a tool with the same |
Source code in .sdk/src/tulip/agent/agent.py
add_tools ¶
Register multiple tools at once.
Equivalent to calling :meth:add_tool for each entry. If any
single registration fails (wrong type, duplicate name), the
whole call fails: tools registered before the failing one
remain in the registry. Validate inputs ahead of time when
atomic behaviour is required.
Source code in .sdk/src/tulip/agent/agent.py
run
async
¶
Run the agent with streaming events.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompt
|
str
|
User prompt to process |
required |
thread_id
|
str | None
|
Optional thread ID for checkpointing |
None
|
metadata
|
dict[str, Any] | None
|
Additional metadata for tools |
None
|
model_kwargs
|
dict[str, Any] | None
|
Per-call parameters forwarded to the model for this
run — |
None
|
stream_tokens
|
bool
|
Also yield :class: |
False
|
Yields:
| Type | Description |
|---|---|
AsyncGenerator[TulipEvent, None]
|
TulipEvent instances for each step |
Source code in .sdk/src/tulip/agent/runtime_loop.py
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 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 | |
AgentConfig¶
AgentConfig ¶
Bases: BaseModel
Configuration for an Agent instance.
All parameters can be validated before agent creation.
tool_step_text_needs_the_answer_hold ¶
hold_tool_step_text drops what hold_final_answer_tokens holds;
without that hold nothing is held, and the flag would silently do nothing.
Source code in .sdk/src/tulip/agent/config.py
point_unknown_fields_at_model_kwargs
classmethod
¶
Say where provider configuration goes, instead of only that it cannot go here.
extra="forbid" catches typos, which is worth keeping, but on its
own it answers the wrong question. A reader who writes the documented
one-string form and adds the base_url that provider requires
gets Extra inputs are not permitted and no hint that the setting
is supported at all, one field over. That is how a supported path
reads as a missing feature.
Source code in .sdk/src/tulip/agent/config.py
validate_model
classmethod
¶
Validate model is a string or ModelProtocol.
Source code in .sdk/src/tulip/agent/config.py
validate_tools
classmethod
¶
Ensure tools is a list.
with_reflexion ¶
with_reflexion(enabled: bool = True, confidence_threshold: float = 0.85, **kwargs: Any) -> AgentConfig
Return a copy with Reflexion configured.
Source code in .sdk/src/tulip/agent/config.py
with_grounding ¶
Return a copy with Grounding configured.
Source code in .sdk/src/tulip/agent/config.py
with_hooks ¶
Reasoning configs¶
AgentConfig.reflexion, AgentConfig.grounding, and AgentConfig.gsar accept
typed configuration objects defined alongside the config itself. The boolean
shorthand (reflexion=True) coerces into a default instance — the explicit
form is what to reach for when you want to tune thresholds, swap models, or
override defaults.
ReflexionConfig ¶
Bases: BaseModel
Configuration for Reflexion reasoning pattern.
GroundingConfig ¶
Bases: BaseModel
Configuration for Grounding evaluation.
GSARConfig ¶
Bases: BaseModel
Configuration for the GSAR typed-grounding layer.
Wires the framework from arXiv:2604.23366 onto an Agent. When
set on :class:AgentConfig, the agent runs the configured judge
over its final assistant message + tool-execution history after
the loop completes; the resulting :class:~tulip.reasoning.gsar_judge.JudgeOutput,
scalar score S, and decision δ are surfaced on
:class:~tulip.agent.result.AgentResult.
This is a single-pass v1 — the agent produces an answer, the judge
scores it, and the result is exposed for the caller to act on. The
full Algorithm-1 outer loop with regenerate / replan callbacks
lives separately in :mod:tulip.reasoning.gsar_evaluator; wire it
explicitly when you want the loop dynamics.
AgentResult¶
AgentResult ¶
Bases: BaseModel
Result from an agent execution.
Contains the final message, state, and execution metrics.
text
property
¶
Alias for message.
Many AI SDKs surface the final assistant text as .text;
Tulip's primary field is .message. Both names now work.
last_assistant_message
property
¶
Get the last assistant message content.
parsed_as ¶
Return parsed cast to schema, with a runtime check.
Use this when you want a typed handle on the structured output without casting yourself::
picks = result.parsed_as(VendorList)
for v in picks.vendors:
...
Raises ValueError if parsed is None (parse failed or no schema
configured) and TypeError if parsed is the wrong concrete type.
Source code in .sdk/src/tulip/agent/result.py
to_dict ¶
from_state
classmethod
¶
from_state(state: AgentState, stop_reason: StopReason, metrics: ExecutionMetrics | None = None, started_at: datetime | None = None, error: str | None = None, grounding_score: float | None = None, ungrounded_claims: list[str] | None = None, parsed: BaseModel | None = None, parse_error: str | None = None, message: str | None = None, gsar_judgment: Any = None, gsar_score: float | None = None, gsar_decision: str | None = None) -> AgentResult
Create a result from final state.
Extracts the final message from the last assistant response unless an
explicit message is supplied (used after a structuring re-prompt).
Source code in .sdk/src/tulip/agent/result.py
Result sub-types¶
AgentResult.metrics is an ExecutionMetrics, AgentResult.stop_reason is a
StopReason literal, and the streaming entry point yields StreamingResult
between events.
ExecutionMetrics ¶
StopReason
module-attribute
¶
StopReason = Literal['complete', 'terminal_tool', 'confidence_met', 'max_iterations', 'tool_loop', 'no_tools', 'grounding_failed', 'token_budget', 'cost_budget', 'time_budget', 'context_exhausted', 'interrupted', 'error', 'cancelled']
StreamingResult ¶
Bases: BaseModel
Partial result during streaming.
Used to provide intermediate state during agent execution.
AgentState¶
AgentState ¶
Bases: BaseModel
Immutable state for an agent execution.
All updates return a new state instance (functional updates).
tool_loop
property
¶
The loop the run's last steps are in, or None (see :mod:tulip.core.loops).
A loop is the same step — calls by name and arguments, and their results — repeated back to back, or the same short cycle of steps repeated whole. Re-reading a file between other work, the same tool with other arguments, and a repeat whose result changed are progress.
has_tool_loop
property
¶
Whether the run's last steps are a loop (warned about or not).
tool_loop_persists
property
¶
Whether the run's loop went on past the point where it is warned about.
This is what stops a run. The runtime warns the model when a loop
reaches its threshold (:meth:with_tool_loop_warning); the warning is
the model's chance to change approach, and one more repeat is the
model ignoring it.
last_tool_calls
property
¶
Get tool calls from the last assistant message of the current turn.
The scan stops at the most recent user message: calls made before it
belong to an earlier turn, and treating them as "last" made a new turn
on a thread whose previous turn ended with a terminal tool stop
immediately with terminal_tool before the model saw the message.
should_terminate
property
¶
Check if the agent should terminate.
In "auto" mode: stops on confidence, no_tools, tool_loop, or terminal_tool. In "explicit" mode: only stops on terminal_tool, max_iterations, or budgets. Use "explicit" for multi-step tasks that require verification before completion.
Returns:
| Type | Description |
|---|---|
tuple[bool, str | None]
|
Tuple of (should_stop, reason) |
total_tokens
property
¶
Total tokens used. Returns real count if tracked, else char/4 estimate.
with_message ¶
Add a message to the conversation.
with_messages ¶
Add multiple messages to the conversation.
with_iteration ¶
next_iteration ¶
with_provider_state ¶
Replace the provider continuation state.
Server-stateful transports (e.g. OCIResponsesModel) return
a continuation token in ModelResponse.provider_state; the
agent calls this to thread the token into the next turn.
Source code in .sdk/src/tulip/core/state.py
with_tool_execution ¶
Record a tool execution.
Source code in .sdk/src/tulip/core/state.py
with_reasoning_step ¶
Add a reasoning step to the trace.
Source code in .sdk/src/tulip/core/state.py
with_confidence ¶
Update confidence score.
Source code in .sdk/src/tulip/core/state.py
adjust_confidence ¶
Adjust confidence with optional diminishing returns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delta
|
float
|
Raw confidence adjustment (-1.0 to 1.0) |
required |
diminishing
|
bool
|
If True, positive deltas are scaled by (1 - current_confidence) |
True
|
Source code in .sdk/src/tulip/core/state.py
with_error ¶
with_metadata ¶
with_token_usage ¶
with_token_usage(prompt_tokens: int, completion_tokens: int, cache_creation_tokens: int = 0, cache_read_tokens: int = 0, *, cached_tokens: int = 0, cache_write_tokens: int = 0, reported_cost_usd: float | None = None) -> AgentState
Record token usage from a model response.
cache_creation_tokens and cache_read_tokens are populated
only when Anthropic returns prompt-cache stats on the response
usage (i.e., the AnthropicModel was configured with
prompt_cache=True). Default 0 for other providers.
cached_tokens and cache_write_tokens are the OpenAI-style
counters, already inside prompt_tokens. reported_cost_usd is
the provider's own figure for the call, when it gives one.
Source code in .sdk/src/tulip/core/state.py
with_response_usage ¶
with_response_usage(usage: Mapping[str, Any] | None, reported_cost_usd: float | None = None) -> AgentState
Record a model response's usage dict, every counter it carries.
Source code in .sdk/src/tulip/core/state.py
cost_of ¶
cost_of(prompt_tokens: int, completion_tokens: int, *, cache_creation_tokens: int = 0, cache_read_tokens: int = 0) -> float | None
USD for a call of this size, or None when the prices are unknown.
cache_creation_tokens and cache_read_tokens are the counts
Anthropic (and Bedrock) report beside prompt_tokens, priced at
their published multiples of the input price: a write at 1.25x, a
read at 0.1x. Left out, as they were, a cached Claude run looked
almost free and a max_cost_usd never stopped it. OpenAI-style
cached_tokens are inside prompt_tokens and stay at the full
input price, since the discount differs by provider: that overstates
a cached call rather than understating it.
Source code in .sdk/src/tulip/core/state.py
would_exceed_cost_budget ¶
Whether the next call could cross the spend budget, at its worst case.
The worst case is the current conversation as input (a char/4 estimate)
plus max_output_tokens of output. Checked before the call, which is
what stops one large turn: a check after the call only stops the next one.
Source code in .sdk/src/tulip/core/state.py
tool_loop_warned ¶
with_tool_loop_warning ¶
Record that the model was warned about loop at this step.
Source code in .sdk/src/tulip/core/state.py
to_checkpoint ¶
from_checkpoint
classmethod
¶
State sub-types¶
AgentState.tool_executions is a tuple of ToolExecution,
AgentState.reasoning_steps is a tuple of ReasoningStep. Both are surfaced
on AgentResult via the matching properties.
ToolExecution ¶
Bases: BaseModel
Record of a single tool execution.
ReasoningStep ¶
Bases: BaseModel
A single step in the agent's reasoning trace.
Composition¶
The composition helpers chain or fan-out multiple agents while keeping the
same AgentResult shape at the boundary. See the
Multi-agent composition page for the full pipeline classes;
the functional builders below are the ergonomic entry points.
PipelineResult ¶
Bases: BaseModel
Result from a pipeline execution.
sequential ¶
Create a sequential pipeline from agents.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*agents
|
Any
|
Agents to run in order |
()
|
prompt_template
|
str | None
|
Optional template for passing output between agents |
None
|
Source code in .sdk/src/tulip/agent/composition.py
parallel ¶
Create a parallel pipeline from agents.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*agents
|
Any
|
Agents to run concurrently |
()
|
merge_strategy
|
str
|
How to merge results ('concatenate' or 'last') |
'concatenate'
|
Source code in .sdk/src/tulip/agent/composition.py
loop ¶
loop(agent: Any, condition: Callable[[str], bool], max_loops: int = 5, loop_prompt: str | None = None) -> LoopAgent
Create a loop agent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agent
|
Any
|
Agent to run repeatedly |
required |
condition
|
Callable[[str], bool]
|
Function returning True when loop should stop |
required |
max_loops
|
int
|
Maximum iterations |
5
|
loop_prompt
|
str | None
|
Template for loop iteration prompts |
None
|