Agents API Reference¶
Complete API reference for AI Agents.
Main Classes¶
Agent ¶
Synchronous client for interacting with StackSpot AI Agents.
This client provides a high-level interface for sending messages to Agents and receiving responses, with support for:
- Single message requests (blocking)
- Conversation context for multi-turn interactions
- Knowledge source integration
- Token usage tracking
Example
from stkai.agents import Agent, ChatRequest agent = Agent(agent_id="my-agent-slug") response = agent.chat( ... request=ChatRequest(user_prompt="What is SOLID?") ... ) if response.is_success(): ... print(response.result)
Attributes:
| Name | Type | Description |
|---|---|---|
agent_id |
The Agent ID (slug) to interact with. |
|
base_url |
The base URL for the StackSpot AI API. |
|
options |
Configuration options for the client. |
|
http_client |
HttpClient
|
HTTP client for API calls (default: EnvironmentAwareHttpClient). |
Source code in src/stkai/agents/_agent.py
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 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 | |
Functions¶
chat ¶
Send a message to the Agent and wait for the response (blocking).
This method sends a user prompt to the Agent and blocks until a response is received or an error occurs.
If retry is configured (retry_max_retries > 0), automatically retries on: - HTTP 5xx errors (500, 502, 503, 504) - Network errors (Timeout, ConnectionError)
Does NOT retry on: - HTTP 4xx errors (client errors)
Note
retry_max_retries=0 means 1 attempt (no retry). retry_max_retries=3 means 4 attempts (1 original + 3 retries).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
ChatRequest
|
The request containing the user prompt and options. |
required |
result_handler
|
ChatResultHandler | None
|
Optional handler to process the response message. If None, uses RawResultHandler (returns message as-is). Use JSON_RESULT_HANDLER to parse JSON responses. |
None
|
Returns:
| Type | Description |
|---|---|
ChatResponse
|
ChatResponse with the Agent's reply or error information. |
ChatResponse
|
The |
Raises:
| Type | Description |
|---|---|
ChatResultHandlerError
|
If the result handler fails to process the response. |
Example
Single message (default RawResultHandler)¶
response = agent.chat( ... request=ChatRequest(user_prompt="Hello!") ... ) print(response.result) # Same as response.raw_result
Parse JSON response¶
from stkai.agents import JSON_RESULT_HANDLER response = agent.chat(request, result_handler=JSON_RESULT_HANDLER) print(response.result) # Parsed dict
With conversation context¶
resp1 = agent.chat( ... request=ChatRequest( ... user_prompt="What is Python?", ... use_conversation=True ... ) ... ) resp2 = agent.chat( ... request=ChatRequest( ... user_prompt="What are its main features?", ... conversation_id=resp1.conversation_id, ... use_conversation=True ... ) ... )
Source code in src/stkai/agents/_agent.py
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 | |
chat_many ¶
chat_many(request_list: list[ChatRequest], result_handler: ChatResultHandler | None = None) -> list[ChatResponse]
Send multiple chat messages concurrently, wait for all responses (blocking),
and return them in the same order as request_list.
Each request is executed in parallel threads using the internal thread-pool.
Returns a list of ChatResponse objects in the same order as request_list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request_list
|
list[ChatRequest]
|
List of ChatRequest objects to send. |
required |
result_handler
|
ChatResultHandler | None
|
Optional handler to process the response message. If None, uses RawResultHandler (returns message as-is). |
None
|
Returns:
| Type | Description |
|---|---|
list[ChatResponse]
|
List[ChatResponse]: One response per request, in the same order. |
Example
requests = [ ... ChatRequest(user_prompt="What is Python?"), ... ChatRequest(user_prompt="What is Java?"), ... ] responses = agent.chat_many(requests) for resp in responses: ... print(resp.result)
Source code in src/stkai/agents/_agent.py
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 | |
chat_stream ¶
chat_stream(request: ChatRequest, result_handler: ChatResultHandler | None = None, event_parser: SseEventParser | None = None) -> ChatResponseStream
Send a message to the Agent and return a streaming response.
Returns a ChatResponseStream context manager that yields SSE events
as they arrive from the server. Must be used with with::
with agent.chat_stream(ChatRequest(user_prompt="Hello")) as stream:
for event in stream:
if event.is_delta:
print(event.text, end="", flush=True)
print(f"\nTokens: {stream.response.tokens.total}")
If retry is configured, retries only the initial connection (before the stream begins). Mid-stream errors are not retried.
chat_many + stream is not supported — streaming is real-time
by nature and batch execution defeats its purpose.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
ChatRequest
|
The request containing the user prompt and options. |
required |
result_handler
|
ChatResultHandler | None
|
Optional handler to process the final accumulated text. If None, uses RawResultHandler (returns accumulated text as-is). The handler is applied once after the stream is fully consumed, over the complete accumulated text — not per chunk. |
None
|
event_parser
|
SseEventParser | None
|
Optional SSE event parser. If None, uses the default
|
None
|
Returns:
| Type | Description |
|---|---|
ChatResponseStream
|
A ChatResponseStream context manager for iterating SSE events. |
Raises:
| Type | Description |
|---|---|
HTTPError
|
If the initial HTTP request fails (after retries). |
RuntimeError
|
If the HTTP client does not support streaming. |
Example
with agent.chat_stream(ChatRequest(user_prompt="Hello")) as stream: ... for text in stream.text_stream: ... print(text, end="", flush=True)
With JSON result handler¶
from stkai.agents import JSON_RESULT_HANDLER with agent.chat_stream(request, result_handler=JSON_RESULT_HANDLER) as stream: ... response = stream.get_final_response() ... print(response.result) # Parsed dict
Source code in src/stkai/agents/_agent.py
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 | |
Data Models¶
ChatRequest
dataclass
¶
Represents a chat request to be sent to a StackSpot AI Agent.
This class encapsulates all data needed to send a message to an Agent, including the prompt, conversation context, and knowledge source settings.
Attributes:
| Name | Type | Description |
|---|---|---|
user_prompt |
str
|
The message/prompt to send to the Agent. |
id |
str
|
Unique identifier for this request. Auto-generated as UUID if not provided. |
conversation_id |
str | None
|
Optional ID to continue an existing conversation. |
use_conversation |
bool
|
Whether to maintain conversation context (default: False). |
use_knowledge_sources |
bool
|
Whether to use StackSpot knowledge sources (default: True). |
return_knowledge_sources |
bool
|
Whether to return knowledge source IDs in response (default: False). |
metadata |
dict[str, Any]
|
Optional dictionary for storing custom metadata. |
Example
request = ChatRequest( ... user_prompt="Explain what SOLID principles are", ... use_knowledge_sources=True, ... metadata={"source": "cli"} ... )
Source code in src/stkai/agents/_models.py
Functions¶
to_api_payload ¶
Converts the request to the API payload format.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary formatted for the Agent API. |
Source code in src/stkai/agents/_models.py
ChatResponse
dataclass
¶
Represents a response from a StackSpot AI Agent.
This class encapsulates the Agent's response including the message, token usage, status, and any error information. Properties are lazily extracted from raw_response (source of truth).
Attributes:
| Name | Type | Description |
|---|---|---|
request |
ChatRequest
|
The original request that generated this response. |
status |
ChatStatus
|
The status of the response (SUCCESS, ERROR, TIMEOUT). |
result |
Any | None
|
The processed result from the result handler. By default (RawResultHandler), this is the same as raw_result. When using JsonResultHandler, this is the parsed JSON object. |
error |
str | None
|
Error message if the request failed. |
raw_response |
dict[str, Any] | None
|
The raw API response dictionary (source of truth for properties). |
Properties (derived from raw_response): raw_result: The Agent's response message (raw text from API). stop_reason: Reason why the Agent stopped generating (e.g., "stop"). tokens: Token usage information. conversation_id: ID for continuing the conversation. knowledge_sources: List of knowledge source IDs used in the response.
Example
if response.is_success(): ... print(response.raw_result) # Raw text ... print(response.result) # Processed by handler ... print(f"Tokens used: {response.tokens.total}") ... elif response.is_timeout(): ... print("Request timed out") ... else: ... print(f"Error: {response.error}")
Source code in src/stkai/agents/_models.py
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 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 | |
Attributes¶
raw_result
property
¶
Extracts the 'message' field from the raw API response.
stop_reason
property
¶
Extracts the 'stop_reason' field from the raw API response.
tokens
property
¶
Extracts and parses token usage from the raw API response.
conversation_id
property
¶
Extracts the 'conversation_id' field from the raw API response.
knowledge_sources
property
¶
Extracts the 'knowledge_source_id' field from the raw API response.
Functions¶
is_success ¶
is_error ¶
is_timeout ¶
error_with_details ¶
Returns a dictionary with error details for non-success responses.
Source code in src/stkai/agents/_models.py
ChatStatus ¶
Bases: StrEnum
Status of a chat response.
Attributes:
| Name | Type | Description |
|---|---|---|
SUCCESS |
Response received successfully from the Agent. |
|
ERROR |
Client-side error (HTTP error, network issue, parsing error). |
|
TIMEOUT |
Any timeout, client or server-side (e.g., HTTP request timeout, HTTP 408, or HTTP 504). |
Source code in src/stkai/agents/_models.py
Functions¶
from_exception
classmethod
¶
Determine the appropriate status for an exception.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exc
|
Exception
|
The exception that occurred during the chat request. |
required |
Returns:
| Type | Description |
|---|---|
ChatStatus
|
TIMEOUT for timeout exceptions, ERROR for all others. |
Example
try: ... response = agent.chat(request) ... except Exception as e: ... status = ChatStatus.from_exception(e) ... # status is TIMEOUT if e is a timeout, ERROR otherwise
Source code in src/stkai/agents/_models.py
ChatTokenUsage
dataclass
¶
Token usage information from a chat response.
Tracks the number of tokens consumed in different stages of processing.
Attributes:
| Name | Type | Description |
|---|---|---|
user |
int
|
Tokens from the user prompt. |
enrichment |
int
|
Tokens from knowledge source enrichment. |
output |
int
|
Tokens in the generated output. |
Example
usage = ChatTokenUsage(user=100, enrichment=50, output=200) print(f"Total tokens: {usage.total}") Total tokens: 350
Source code in src/stkai/agents/_models.py
Streaming (Experimental)¶
ChatResponseStream ¶
Context manager and iterator for streaming Agent responses.
Wraps an HTTP response with stream=True and parses SSE events,
providing auto-accumulation and a final ChatResponse after iteration.
Must be used as a context manager to ensure proper cleanup of the underlying HTTP connection::
with agent.chat_stream(request) as stream:
for event in stream:
...
response = stream.response
Error handling: following the SDK principle of "requests in,
responses out", errors during streaming (SSE failures, handler errors)
never propagate as exceptions. Instead, response is always
available after iteration with an appropriate status:
- SUCCESS — stream completed and handler (if any) succeeded.
- ERROR — SSE connection failed or handler raised an exception.
- TIMEOUT — SSE connection timed out.
On error, response.result contains the raw accumulated text
(partial on SSE failure, complete on handler failure) so the caller
can still inspect what the Agent returned.
Attributes:
| Name | Type | Description |
|---|---|---|
request |
ChatRequest
|
The original ChatRequest. |
response |
ChatResponse
|
The final ChatResponse (available after iteration completes). |
accumulated_text |
str
|
Text accumulated so far during iteration. |
Source code in src/stkai/agents/_stream.py
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 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 | |
Attributes¶
response
property
¶
The final ChatResponse, available after iteration completes.
Always present after iteration, even on errors. Check
response.is_success() / response.is_error() /
response.is_timeout() to determine the outcome.
On non-success, response.result holds the raw accumulated
text and response.error describes what went wrong.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If accessed before the stream is fully consumed. |
accumulated_text
property
¶
Text accumulated so far (useful during iteration).
text_stream
property
¶
Convenience iterator that yields only text chunks from DELTA events.
Example
with agent.chat_stream(request) as stream: ... for text in stream.text_stream: ... print(text, end="", flush=True)
Functions¶
until_done ¶
Consume the stream silently, discarding all events.
After this call, self.response is available.
Example
with agent.chat_stream(request) as stream: ... stream.until_done() ... print(stream.response.result)
Source code in src/stkai/agents/_stream.py
get_final_response ¶
Consume the stream and return the final ChatResponse.
Equivalent to calling until_done() followed by self.response.
The returned response is always present — check its status to
determine whether the stream completed successfully.
Example
with agent.chat_stream(request) as stream: ... response = stream.get_final_response() ... if response.is_success(): ... print(response.result) ... else: ... print(f"Error: {response.error}")
Source code in src/stkai/agents/_stream.py
ChatResponseStreamEvent
dataclass
¶
A single event from a streaming Agent response.
Attributes:
| Name | Type | Description |
|---|---|---|
type |
ChatResponseStreamEventType
|
The event type (DELTA, DONE, ERROR). |
text |
str
|
Text content for DELTA events. |
raw_data |
dict[str, Any] | None
|
Raw parsed SSE data dictionary. |
error |
str | None
|
Error message for ERROR events. |
Source code in src/stkai/agents/_stream.py
ChatResponseStreamEventType ¶
SseEventParser ¶
Parses SSE (Server-Sent Events) lines into ChatResponseStreamEvent objects.
Call parse(lines) to iterate over parsed events. Metadata accumulated
from chunks (conversation_id, tokens, stop_reason, etc.) is available via
the metadata property after the returned iterator is fully consumed.
The parser is safe to reuse — each parse() call resets internal state.
Subclass and override _extract_delta_text or _track_chunk_metadata
to handle protocol changes.
Source code in src/stkai/agents/_sse_parser.py
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 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 | |
Attributes¶
metadata
property
¶
Accumulated metadata from chunks (conversation_id, tokens, etc.).
Available after the iterator returned by parse() is fully consumed.
Returns None if no metadata was found in any chunk.
Functions¶
parse ¶
Parse SSE lines and yield events.
Each call resets internal state (including metadata), making the
parser safe to reuse across multiple streams.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lines
|
Iterable[str | bytes]
|
An iterable of SSE lines (typically from
|
required |
Yields:
| Type | Description |
|---|---|
ChatResponseStreamEvent
|
ChatResponseStreamEvent for each parsed SSE event. |
Source code in src/stkai/agents/_sse_parser.py
Conversation¶
UseConversation ¶
Context manager that automatically tracks and propagates conversation_id
across all Agent.chat() calls within the block.
Precedence rules
ChatRequest.conversation_id(explicit) wins overUseConversation(implicit).use_conversation=Trueis automatically set inside the block.- If no
conversation_idis provided, captures from the first successful response.
Nestable: inner UseConversation overrides outer; restores on exit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conversation_id
|
str | None
|
Optional initial conversation ID. If None, auto-captures
from the first successful |
None
|
Example
with UseConversation() as conv: ... r1 = agent.chat(ChatRequest(user_prompt="Hello")) ... print(conv.conversation_id) # captured from r1 ... r2 = agent.chat(ChatRequest(user_prompt="Follow up"))
Source code in src/stkai/agents/_conversation.py
Functions¶
with_generated_id
classmethod
¶
Factory method that creates a UseConversation with a pre-generated
conversation ID in ULID format.
This is useful when you want the conversation ID available before
the first request, especially with chat_many() where concurrent
requests would otherwise race to capture the server-assigned ID.
Example
with UseConversation.with_generated_id() as conv: ... print(conv.conversation_id) # ULID already available ... agent.chat(ChatRequest(user_prompt="Hello"))
Source code in src/stkai/agents/_conversation.py
ConversationContext ¶
Holds the mutable conversation state within a UseConversation block.
Thread-safe: _update_if_absent() uses a lock for safe auto-tracking
from concurrent threads (e.g., chat_many()).
Attributes:
| Name | Type | Description |
|---|---|---|
conversation_id |
str | None
|
The current conversation ID, or None if not yet captured. |
Source code in src/stkai/agents/_conversation.py
Attributes¶
Functions¶
has_conversation_id ¶
enrich ¶
Returns a new ChatRequest enriched with the current conversation state.
Sets use_conversation=True and conversation_id (if already captured).
If the request already has a conversation_id, returns it unchanged
(explicit takes precedence).
The original request is never mutated.
Example
with UseConversation() as conv: ... request = conv.enrich(ChatRequest(user_prompt="Hello")) ... response = agent.chat(request) ... # response.request.conversation_id reflects what was sent
Source code in src/stkai/agents/_conversation.py
update_if_absent ¶
Set the conversation_id only if not already set. Returns the current conversation_id (either the existing one or the newly set one).
Thread-safe via lock so concurrent chat_many() workers
can safely race to capture the first response's conversation_id.
Source code in src/stkai/agents/_conversation.py
File Upload¶
FileUploader ¶
Client for uploading files to the StackSpot platform.
The upload is a two-step process: 1. Request pre-signed S3 credentials from the Data Integration API (authenticated) 2. Upload the file to S3 using the pre-signed form (unauthenticated)
Note: File uploading via API is only available for Enterprise accounts.
Example
from stkai import FileUploader, FileUploadRequest uploader = FileUploader() response = uploader.upload(FileUploadRequest(file_path="doc.pdf")) if response.is_success(): ... print(response.upload_id)
Attributes:
| Name | Type | Description |
|---|---|---|
base_url |
The base URL for the Data Integration API. |
|
options |
Configuration options for the client. |
|
http_client |
HttpClient
|
HTTP client for authenticated API calls. |
Source code in src/stkai/_file_upload.py
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 | |
Functions¶
upload ¶
Upload a file and wait for the response (blocking).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
FileUploadRequest
|
The file upload request. |
required |
Returns:
| Type | Description |
|---|---|
FileUploadResponse
|
FileUploadResponse with the upload_id or error information. |
Example
response = uploader.upload(FileUploadRequest(file_path="doc.pdf")) if response.is_success(): ... print(response.upload_id)
Source code in src/stkai/_file_upload.py
upload_many ¶
Upload multiple files concurrently, wait for all responses (blocking),
and return them in the same order as request_list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request_list
|
list[FileUploadRequest]
|
List of FileUploadRequest objects to upload. |
required |
Returns:
| Type | Description |
|---|---|
list[FileUploadResponse]
|
List[FileUploadResponse]: One response per request, in the same order. |
Example
responses = uploader.upload_many([ ... FileUploadRequest(file_path="doc1.pdf"), ... FileUploadRequest(file_path="doc2.pdf"), ... ]) upload_ids = [r.upload_id for r in responses if r.is_success()]
Source code in src/stkai/_file_upload.py
FileUploadRequest
dataclass
¶
Represents a file upload request.
Attributes:
| Name | Type | Description |
|---|---|---|
file_path |
str | Path
|
Path to the file to upload. |
target_type |
FileUploadTargetType
|
Upload target type (default: CONTEXT). Use CONTEXT for agent chat context, KNOWLEDGE_SOURCE for knowledge sources. |
target_id |
str | None
|
Knowledge source slug. Required when target_type is KNOWLEDGE_SOURCE. |
expiration |
int
|
Expiration in minutes for the uploaded file (default: 60). |
id |
str
|
Unique identifier for this request. Auto-generated as UUID if not provided. |
metadata |
dict[str, Any]
|
Optional dictionary for storing custom metadata. |
Example
request = FileUploadRequest(file_path="document.pdf") request = FileUploadRequest( ... file_path="doc.pdf", ... target_type=FileUploadTargetType.KNOWLEDGE_SOURCE, ... target_id="my-ks-slug", ... )
Source code in src/stkai/_file_upload.py
Attributes¶
Functions¶
to_api_payload ¶
Converts the request to the API payload format for the pre-signed form endpoint.
Source code in src/stkai/_file_upload.py
FileUploadResponse
dataclass
¶
Represents a response from a file upload operation.
Attributes:
| Name | Type | Description |
|---|---|---|
request |
FileUploadRequest
|
The original request that generated this response. |
status |
FileUploadStatus
|
The status of the response (SUCCESS, ERROR, TIMEOUT). |
upload_id |
str | None
|
The upload ID returned by the API on success. |
error |
str | None
|
Error message if the upload failed. |
raw_response |
dict[str, Any] | None
|
Raw API response from Step 1 (pre-signed form request). |
Example
if response.is_success(): ... print(response.upload_id) ... else: ... print(f"Error: {response.error}")
Source code in src/stkai/_file_upload.py
FileUploadStatus ¶
Bases: StrEnum
Status of a file upload response.
Attributes:
| Name | Type | Description |
|---|---|---|
SUCCESS |
File uploaded successfully. |
|
ERROR |
Client-side error (HTTP error, network issue, file not found). |
|
TIMEOUT |
Any timeout, client or server-side. |
Source code in src/stkai/_file_upload.py
Functions¶
from_exception
classmethod
¶
Determine the appropriate status for an exception.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exc
|
Exception
|
The exception that occurred during the upload. |
required |
Returns:
| Type | Description |
|---|---|
FileUploadStatus
|
TIMEOUT for timeout exceptions, ERROR for all others. |
Source code in src/stkai/_file_upload.py
FileUploadOptions
dataclass
¶
Configuration options for the FileUploader client.
Fields set to None will use values from global config (STKAI.config.file_upload).
Attributes:
| Name | Type | Description |
|---|---|---|
request_timeout |
int | None
|
HTTP timeout for Step 1 (get pre-signed form). |
transfer_timeout |
int | None
|
HTTP timeout for Step 2 (file transfer to S3). |
retry_max_retries |
int | None
|
Maximum retry attempts for transient failures. |
retry_initial_delay |
float | None
|
Initial delay for first retry (exponential backoff). |
max_workers |
int | None
|
Maximum threads for upload_many(). |
Example
options = FileUploadOptions(request_timeout=15, transfer_timeout=60) uploader = FileUploader(options=options)
Source code in src/stkai/_file_upload.py
Functions¶
with_defaults_from ¶
Returns a new FileUploadOptions with None values filled from config.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cfg
|
FileUploadConfig
|
The FileUploadConfig to use for default values. |
required |
Returns:
| Type | Description |
|---|---|
FileUploadOptions
|
A new FileUploadOptions with all fields resolved (no None values). |
Source code in src/stkai/_file_upload.py
Configuration¶
AgentOptions
dataclass
¶
Configuration options for the Agent client.
Fields set to None will use values from global config (STKAI.config.agent).
Attributes:
| Name | Type | Description |
|---|---|---|
request_timeout |
int | None
|
HTTP request timeout in seconds. |
retry_max_retries |
int | None
|
Maximum number of retry attempts for failed chat calls. Use 0 to disable retries (single attempt only). Use 3 for 4 total attempts (1 original + 3 retries). |
retry_initial_delay |
float | None
|
Initial delay in seconds for the first retry attempt. Subsequent retries use exponential backoff (delay doubles each attempt). |
max_workers |
int | None
|
Maximum number of threads for batch execution (chat_many). |
Example
Use all defaults from config¶
agent = Agent(agent_id="my-agent")
Customize timeout and enable retry¶
options = AgentOptions(request_timeout=120, retry_max_retries=3) agent = Agent(agent_id="my-agent", options=options)
Source code in src/stkai/agents/_agent.py
Functions¶
with_defaults_from ¶
Returns a new AgentOptions with None values filled from config.
User-provided values take precedence; None values use config defaults. This follows the Single Source of Truth principle where STKAI.config is the authoritative source for default values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cfg
|
AgentConfig
|
The AgentConfig to use for default values. |
required |
Returns:
| Type | Description |
|---|---|
AgentOptions
|
A new AgentOptions with all fields resolved (no None values). |
Example
options = AgentOptions(request_timeout=120) resolved = options.with_defaults_from(STKAI.config.agent) resolved.request_timeout # 120 (user-defined)