Agent¶
Agent ¶
Agent(model: str | Any | 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: Any | None = None, checkpointer: Any | None = None, hooks: list[Any] | None = None, config: AgentConfig | None = None, **kwargs: Any)
Bases: AgentRuntimeMixin, BaseModel
Primary entry point for Locus agents.
Manages the ReAct loop with optional Reflexion and Grounding.
Usage
agent = Agent( model="openai:gpt-4o", # or oci:cohere.command-r-plus 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
|
Additional config options |
{}
|
Source code in src/locus/agent/agent.py
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.
run_sync ¶
run_sync(prompt: str, *, thread_id: str | None = None, metadata: dict[str, Any] | None = None) -> AgentResult
Run the agent synchronously.
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 src/locus/agent/agent.py
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 | |
invoke ¶
invoke(prompt: str, *, thread_id: str | None = None, metadata: dict[str, Any] | None = None) -> AgentResult
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 src/locus/agent/agent.py
cancel ¶
Cancel a running agent from an external thread.
Sets a signal that the agent loop checks at each iteration. The agent will stop gracefully with stop_reason="cancelled".
Thread-safe — can be called from any thread while the agent is running.
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 src/locus/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 src/locus/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.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
response
|
str
|
The user's response to the interrupt question |
required |
Yields:
| Type | Description |
|---|---|
AsyncIterator[LocusEvent]
|
LocusEvent 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 src/locus/agent/agent.py
add_tool ¶
Register a tool on this agent after construction.
Locus compiles config.tools into the runtime ToolRegistry
once, inside __init__ (via :func:locus.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 src/locus/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 src/locus/agent/agent.py
run
async
¶
run(prompt: str, *, thread_id: str | None = None, metadata: dict[str, Any] | None = None) -> AsyncIterator[LocusEvent]
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
|
Yields:
| Type | Description |
|---|---|
AsyncIterator[LocusEvent]
|
LocusEvent instances for each step |
Source code in src/locus/agent/runtime_loop.py
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 | |
AgentConfig¶
AgentConfig ¶
Bases: BaseModel
Configuration for an Agent instance.
All parameters can be validated before agent creation.
validate_model
classmethod
¶
Validate model is a string or ModelProtocol.
Source code in src/locus/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 src/locus/agent/config.py
with_grounding ¶
Return a copy with Grounding configured.
Source code in src/locus/agent/config.py
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;
Locus'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 src/locus/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 src/locus/agent/result.py
AgentState¶
AgentState ¶
Bases: BaseModel
Immutable state for an agent execution.
All updates return a new state instance (functional updates).
has_tool_loop
property
¶
Check if agent is stuck in a tool loop across iterations.
Multiple calls to the same tool in one turn (parallel execution) is normal. A loop is the same call signature — name and arguments — repeating across consecutive iterations. Same name with different arguments (paged discovery, sweeping inputs, retrying with a corrected parameter) counts as forward progress and is not a loop.
last_tool_calls
property
¶
Get tool calls from the last assistant 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 src/locus/core/state.py
with_tool_execution ¶
Record a tool execution.
Source code in src/locus/core/state.py
with_reasoning_step ¶
Add a reasoning step to the trace.
with_confidence ¶
Update confidence score.
Source code in src/locus/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 src/locus/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) -> 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.