Intent, Response & Tasks¶
Intent¶
Intent
dataclass
¶
Bases: Generic[TParams]
Parsed intent representing a user's request.
Immutable data class serving as the starting point for agent processing.
Generic on a Pydantic payload type TParams so handlers can declare
intent: Intent[OrderFilters] to receive a validated, schema-
constrained payload as intent.params.
Backward compatibility
Handlers using the bare Intent annotation (or no annotation
at all) keep working exactly as before. params defaults to
None for legacy handlers, and the legacy
parameters: dict[str, Any] field is still populated by both
keyword and LLM parsing paths so existing handlers that read
intent.parameters['x'] continue to work.
Attributes:
| Name | Type | Description |
|---|---|---|
raw |
str
|
The original natural language request. |
action |
IntentAction
|
The classified action type. |
domain |
str
|
The domain area (e.g., "order", "product", "user"). |
params |
TParams | None
|
Optional typed payload, populated when the handler
declares |
parameters |
dict[str, Any]
|
Extracted parameters from the request as a plain
dict. Always populated for backward compatibility — when
|
confidence |
float
|
Parsing confidence score (0.0-1.0). |
ambiguities |
list[str]
|
List of detected ambiguities needing clarification. |
session_context |
dict[str, Any]
|
Accumulated session context from prior turns. |
Source code in src/agenticapi/interface/intent.py
IntentAction¶
IntentAction ¶
IntentParser¶
IntentParser ¶
Parses raw natural language into Intent objects.
Can operate in two modes: - Without LLM: basic keyword-based parsing for action classification and simple domain extraction. - With LLM: uses structured prompts for accurate classification and parameter extraction.
Example
parser = IntentParser() intent = await parser.parse("Show me this month's order count") assert intent.action == IntentAction.READ
parser_llm = IntentParser(llm=backend) intent = await parser_llm.parse("Cancel order #1234") assert intent.action == IntentAction.WRITE
Source code in src/agenticapi/interface/intent.py
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 | |
__init__ ¶
Initialize the intent parser.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
llm
|
LLMBackend | None
|
Optional LLM backend for advanced parsing. If None, falls back to keyword-based parsing. |
None
|
parse
async
¶
parse(
raw: str,
*,
session_context: dict[str, Any] | None = None,
schema: type[BaseModel] | None = None,
) -> Intent[Any]
Parse a natural language request into an Intent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw
|
str
|
The raw natural language request string. |
required |
session_context
|
dict[str, Any] | None
|
Optional accumulated session context. |
None
|
schema
|
type[BaseModel] | None
|
Optional Pydantic model the LLM should produce a
payload for. When supplied, the parser asks the LLM
backend to constrain its output to the model's JSON
schema (provider-native structured output) and the
returned :class: |
None
|
Returns:
| Type | Description |
|---|---|
Intent[Any]
|
A parsed Intent object. |
Intent[Any]
|
|
Raises:
| Type | Description |
|---|---|
IntentParseError
|
If parsing fails completely or the LLM response fails schema validation after one retry. |
Source code in src/agenticapi/interface/intent.py
IntentScope¶
IntentScope ¶
Bases: BaseModel
Declarative scope for allowed and denied intents on an endpoint.
Uses wildcard matching (e.g., "order.*" matches "order.create").
Attributes:
| Name | Type | Description |
|---|---|---|
allowed_intents |
list[str]
|
Patterns of allowed intents. ["*"] means all allowed. |
denied_intents |
list[str]
|
Patterns of denied intents. Takes precedence over allowed. |
Source code in src/agenticapi/interface/intent.py
matches ¶
Check whether an intent is allowed by this scope.
Denied patterns take precedence over allowed patterns. The intent key used for matching is "{domain}.{action}".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
intent
|
Intent[Any]
|
The intent to check. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the intent is allowed by this scope. |
Source code in src/agenticapi/interface/intent.py
AgentResponse¶
AgentResponse
dataclass
¶
Response from an agent endpoint.
Captures the result, status, and metadata of an agent operation.
Attributes:
| Name | Type | Description |
|---|---|---|
result |
Any
|
The primary output from the agent operation. |
status |
str
|
Response status. One of "completed", "pending_approval", "error", or "clarification_needed". |
generated_code |
str | None
|
The code that was generated and executed (if any). |
reasoning |
str | None
|
LLM reasoning for the generated code (if any). |
confidence |
float
|
Confidence in the result (0.0-1.0). |
execution_trace_id |
str | None
|
Identifier for the audit trace of this operation. |
follow_up_suggestions |
list[str]
|
Suggested follow-up actions for the user. |
error |
str | None
|
Error message if status is "error". |
approval_request |
dict[str, Any] | None
|
Approval request details if status is "pending_approval". |
Source code in src/agenticapi/interface/response.py
to_dict ¶
Serialize the response to a JSON-compatible dictionary.
Excludes None values for cleaner output.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dictionary representation of the response. |
Source code in src/agenticapi/interface/response.py
ResponseFormatter¶
ResponseFormatter ¶
Formats AgentResponse for different output formats.
Provides methods for JSON and plain-text serialization.
Example
formatter = ResponseFormatter() json_dict = formatter.format_json(response) text = formatter.format_text(response)
Source code in src/agenticapi/interface/response.py
format_json ¶
Format the response as a JSON-compatible dictionary.
Includes all fields, filtering out None values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
response
|
AgentResponse
|
The agent response to format. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A JSON-compatible dictionary. |
Source code in src/agenticapi/interface/response.py
format_text ¶
Format the response as human-readable plain text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
response
|
AgentResponse
|
The agent response to format. |
required |
Returns:
| Type | Description |
|---|---|
str
|
A human-readable text representation. |
Source code in src/agenticapi/interface/response.py
SessionManager¶
SessionManager ¶
In-memory session manager with TTL-based expiration.
Manages creation, retrieval, update, and deletion of sessions. Sessions are stored in a simple dictionary keyed by session ID.
Example
manager = SessionManager(ttl_seconds=1800) session = await manager.get_or_create(None) # Creates new session.add_turn(intent_raw="hello", response_summary="hi") await manager.update(session)
Source code in src/agenticapi/interface/session.py
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 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 | |
__init__ ¶
Initialize the session manager.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ttl_seconds
|
int
|
Default TTL for new sessions in seconds. |
_DEFAULT_TTL_SECONDS
|
Source code in src/agenticapi/interface/session.py
get_or_create
async
¶
Get an existing session or create a new one.
If session_id is None, a new session is always created. If the session exists but is expired, it is deleted and a new one is created with the same ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id
|
str | None
|
The session ID to look up, or None for a new session. |
required |
Returns:
| Type | Description |
|---|---|
Session
|
The existing or newly created Session. |
Source code in src/agenticapi/interface/session.py
get
async
¶
Get an existing session by ID.
Returns None if the session does not exist or is expired.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id
|
str
|
The session ID to look up. |
required |
Returns:
| Type | Description |
|---|---|
Session | None
|
The Session if found and not expired, otherwise None. |
Source code in src/agenticapi/interface/session.py
update
async
¶
Update a session in the store.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
Session
|
The session to update. |
required |
Raises:
| Type | Description |
|---|---|
SessionError
|
If the session is not found in the store. |
Source code in src/agenticapi/interface/session.py
delete
async
¶
Delete a session from the store.
Silently succeeds if the session does not exist.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id
|
str
|
The session ID to delete. |
required |
Source code in src/agenticapi/interface/session.py
Session¶
Session
dataclass
¶
A user session for multi-turn agent conversations.
Tracks conversation history and accumulated context across multiple turns. Sessions expire after a configurable TTL.
Attributes:
| Name | Type | Description |
|---|---|---|
session_id |
str
|
Unique identifier for this session. |
created_at |
datetime
|
When the session was created. |
last_accessed |
datetime
|
When the session was last accessed. |
context |
dict[str, Any]
|
Accumulated context dictionary from prior turns. |
history |
list[dict[str, Any]]
|
List of conversation turn records. |
ttl_seconds |
int
|
Time-to-live in seconds before expiration. |
Source code in src/agenticapi/interface/session.py
add_turn ¶
Record a conversation turn in the session history.
Also updates the last_accessed timestamp.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
intent_raw
|
str
|
The raw user request for this turn. |
required |
response_summary
|
str
|
A summary of the agent's response. |
required |
Source code in src/agenticapi/interface/session.py
AgentTasks¶
AgentTasks ¶
Accumulator for background tasks that run after the response is sent.
Analogous to FastAPI's BackgroundTasks. Agent endpoint handlers
receive an AgentTasks instance as a parameter and call
add_task() to schedule work that should happen after the HTTP
response is returned to the client.
Tasks execute sequentially in the order they were added. If a task fails, subsequent tasks still execute (errors are logged).
Example
async def send_email(to: str, subject: str) -> None: ...
@app.agent_endpoint(name="signup") async def signup(intent: Intent, context: AgentContext, tasks: AgentTasks): tasks.add_task(send_email, to="user@example.com", subject="Welcome!") return {"status": "signed up"}
Source code in src/agenticapi/interface/tasks.py
__init__ ¶
add_task ¶
Schedule a background task.
The task will execute after the HTTP response is sent. Both sync and async callables are supported.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable[..., Any]
|
The callable to execute. Can be sync or async. |
required |
*args
|
Any
|
Positional arguments for the callable. |
()
|
**kwargs
|
Any
|
Keyword arguments for the callable. |
{}
|
Source code in src/agenticapi/interface/tasks.py
execute
async
¶
Execute all accumulated tasks sequentially.
Called by the framework after the response is sent. Individual task failures are logged but do not prevent subsequent tasks from running.