API Reference
AnthropicAdapter
Bases: ModelProviderAdapter
Adapter for Anthropic Claude models in AWS Bedrock.
This adapter handles: 1. Setting the required anthropic_version 2. Building tool definitions in Anthropic's format 3. Validating tool-use responses from Claude models
Source code in src/llmbo/adapters/anthropic.py
build_tool(output_model)
cached
classmethod
Build a tool definition in Anthropic's format.
Source code in src/llmbo/adapters/anthropic.py
prepare_model_input(model_input, output_model=None)
classmethod
Prepare model input for Anthropic Claude models.
Source code in src/llmbo/adapters/anthropic.py
validate_result(result, output_model)
classmethod
Validate and parse output from Anthropic Claude models.
Source code in src/llmbo/adapters/anthropic.py
BatchInferer
A class to manage batch inference jobs using AWS Bedrock.
This class handles the creation, monitoring, and retrieval of batch inference jobs for large-scale model invocations using AWS Bedrock service.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_name
|
str
|
The name/ID of the AWS Bedrock model to use |
required |
bucket_name
|
str
|
The S3 bucket name for storing input/output data |
required |
region
|
str
|
The region to run the batch inference job in. |
required |
job_name
|
str
|
A unique name for the batch inference job |
required |
role_arn
|
str
|
The AWS IAM role ARN with necessary permissions |
required |
time_out_duration_hours
|
int
|
Maximum job runtime in hours. Defaults to 24. |
24
|
session
|
session
|
A boto3 session to be used for calls to AWS, If one if not provided a new one will be created |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
job_arn |
str
|
The ARN of the created batch inference job |
results |
List[dict]
|
The results of the batch inference job. Available after job completion. |
manifest |
Manifest
|
Job execution statistics. Available after job completion. |
job_status |
str
|
Current status of the batch job. One of VALID_FINISHED_STATUSES. |
Source code in src/llmbo/batch_inferer.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 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 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 | |
unique_id_from_arn
property
Retrieves the id from the job ARN.
Raises:
| Type | Description |
|---|---|
ValueError
|
if no job ARN has been set |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
a unique id portion of the job ARN |
__init__(model_name, bucket_name, region, job_name, role_arn, time_out_duration_hours=24, session=None, output_dir='.')
Initialize a BatchInferer for AWS Bedrock batch processing.
Creates a configured batch inference manager that handles the end-to-end process of submitting and managing batch jobs on AWS Bedrock.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_name
|
str
|
The AWS Bedrock model identifier (e.g., 'anthropic.claude-3-haiku-20240307-v1:0') |
required |
bucket_name
|
str
|
Name of the S3 bucket for storing job inputs and outputs |
required |
region
|
str
|
The region containing the llm to call, must match the bucket |
required |
job_name
|
str
|
Unique identifier for this batch job. Used in file naming. |
required |
role_arn
|
str
|
AWS IAM role ARN with permissions for Bedrock and S3 access |
required |
time_out_duration_hours
|
int
|
Maximum runtime for the batch job. Defaults to 24 hours. |
24
|
session
|
session
|
A boto3 session to be used for AWS calls, If one if not provided a new one will be created |
None
|
output_dir
|
str
|
Directory for local JSONL files (input, output, manifest). Defaults to "." (current working directory). The directory is created if it does not exist. |
'.'
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If AWS_PROFILE environment variable is not set |
ValueError
|
If the provided role_arn doesn't exist or is invalid |
Example:
>>> bi = BatchInferer(
model_name="anthropic.claude-3-haiku-20240307-v1:0",
bucket_name="my-inference-bucket",
job_name="batch-job-2024-01-01",
role_arn="arn:aws:iam::123456789012:role/BedrockBatchRole"
)
Note
- Requires valid AWS credentials and configuration
- The S3 bucket must exist and be accessible via the provided role
- Job name will be used to create unique file names for inputs and outputs
Source code in src/llmbo/batch_inferer.py
_check_arn(role_arn)
Validate if an IAM role exists and is accessible.
Attempts to retrieve the IAM role using the provided ARN to verify its existence and accessibility.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
role_arn
|
str
|
The AWS ARN of the IAM role to check.
Format: 'arn:aws:iam:: |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if the role exists and is accessible. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the role does not exist. |
ClientError: If there are AWS API issues unrelated to role existence.
Source code in src/llmbo/batch_inferer.py
_check_bucket(bucket_name, region)
Validate if the bucket_name provided exists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bucket_name
|
str
|
the name of a bucket |
required |
region
|
str
|
the name of a region |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the bucket is not accessible |
ValueError
|
If the bucket is not in the same region as the LLM. |
Source code in src/llmbo/batch_inferer.py
_get_bucket_location(bucket_name)
Get the location of the s3 bucket.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bucket_name
|
str
|
the name of a bucket |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the bucket is not accessible |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str | None
|
a region, e.g. "eu-west-2" |
Source code in src/llmbo/batch_inferer.py
_local_path(bare_name)
_write_requests_locally()
Write batch inference requests to a local JSONL file.
Creates or overwrites a local JSONL file containing the prepared inference requests. Each line contains a JSON object with recordId and modelInput.
Raises:
| Type | Description |
|---|---|
IOError
|
If unable to write to the file |
AttributeError
|
If called before prepare_requests() |
Note
- File is named according to self.file_name
- Internal method used by push_requests_to_s3()
- Will overwrite existing files with the same name
Source code in src/llmbo/batch_inferer.py
auto(inputs, poll_time_secs=60)
Execute the complete batch inference workflow automatically.
This method combines the preparation, execution, monitoring, and result retrieval steps into a single operation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inputs
|
Dict[str, ModelInput]
|
Dictionary of record IDs mapped to their ModelInput configurations |
required |
poll_time_secs
|
int
|
How often to poll for model progress. Defaults to 60. |
60
|
Returns:
| Type | Description |
|---|---|
dict
|
List[Dict]: The results from the batch inference job |
Source code in src/llmbo/batch_inferer.py
cancel_batch()
Cancel a running batch inference job.
Attempts to stop the currently running batch inference job identified by self.job_arn.
Returns:
| Type | Description |
|---|---|
None
|
None |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the job cancellation request fails |
ValueError
|
If no job_arn is set (i.e., no job has been created) |
Source code in src/llmbo/batch_inferer.py
check_complete()
Check if the batch inference job has completed.
str | None: The job status if the job has finished (one of 'Completed', 'Failed', 'Stopped', or 'Expired'), or None if the job is still in progress.
Source code in src/llmbo/batch_inferer.py
check_for_existing_job(job_arn, region, session=None)
classmethod
Check if a job exists and return its details.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_arn
|
str
|
The AWS ARN of the job to check |
required |
region
|
str
|
The AWS region where the job was created |
required |
session
|
Session
|
A boto3 session to be used for AWS API calls. If not provided, a new session will be created. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dict[str, Any]: The job details from AWS Bedrock |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the job ARN is invalid or the job is not found |
RuntimeError
|
For other AWS API errors |
Source code in src/llmbo/batch_inferer.py
check_for_profile()
Checks if a profile has been set.
Raises:
| Type | Description |
|---|---|
KeyError
|
If AWS_PROFILE does not exist in the env. |
Source code in src/llmbo/batch_inferer.py
create()
Create a new batch inference job in AWS Bedrock.
Initializes a new model invocation job using the configured parameters and uploaded input data.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict[str, Any]
|
The complete response from the create_model_invocation_job API call |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If job creation fails |
ClientError
|
For AWS API errors |
ValueError
|
If required configurations are missing |
Note
- Sets self.job_arn on successful creation
- Input data must be uploaded to S3 before calling this method
- Job will timeout after self.time_out_duration_hours
Source code in src/llmbo/batch_inferer.py
download_results()
Download batch inference results from S3.
Retrieves both the results and manifest files from S3 once the job has completed. Files are downloaded to: - {job_name}_out.jsonl: Contains model outputs - {job_name}_manifest.jsonl: Contains job statistics
Raises:
| Type | Description |
|---|---|
ClientError
|
For S3 download failures |
ValueError
|
If job hasn't completed or job_arn isn't set |
Note
- Only downloads if job status is in VALID_FINISHED_STATUSES
- Files are downloaded to current working directory
- Existing files will be overwritten
- Call check_complete() first to ensure job is finished
Source code in src/llmbo/batch_inferer.py
load_results()
Load batch inference results and manifest from local files.
Reads and parses the output files downloaded from S3, populating: - self.results: List of inference results from the output JSONL file - self.manifest: Statistics about the job execution (total records, success/error counts, etc.)
The method expects two files to exist locally
- {job_name}_out.jsonl: Contains the model outputs
- {job_name}_manifest.jsonl: Contains execution statistics
Raises:
| Type | Description |
|---|---|
FileExistsError
|
If either the results or manifest files are not found locally |
Note
- Must call download_results() before calling this method
- The manifest provides useful metrics like success rate and token counts
Source code in src/llmbo/batch_inferer.py
poll_progress(poll_interval_seconds=60)
Polls the progress of a job.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
poll_interval_seconds
|
int
|
Number of seconds between checks. Defaults to 60. |
60
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if job is complete. |
Source code in src/llmbo/batch_inferer.py
prepare_requests(inputs)
Prepare batch inference requests from a dictionary of model inputs.
Formats model inputs into the required JSONL structure for AWS Bedrock batch processing. Each request is formatted as: { "recordId": str, "modelInput": dict }
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inputs
|
Dict[str, ModelInput]
|
Dictionary mapping record IDs to their corresponding ModelInput configurations. The record IDs will be used to track results. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If len(inputs) < 100, as AWS Bedrock requires minimum batch size of 100 |
Example
inputs = { ... "001": ModelInput( ... messages=[{"role": "user", "content": "Hello"}], ... temperature=0.7 ... ), ... "002": ModelInput( ... messages=[{"role": "user", "content": "Hi"}], ... temperature=0.7 ... ) ... } bi.prepare_requests(inputs)
Note
- This method must be called before push_requests_to_s3()
- The prepared requests are stored in self.requests
- Each ModelInput is converted to a dict using its to_dict() method
Source code in src/llmbo/batch_inferer.py
push_requests_to_s3()
Upload batch inference requests to S3.
Writes the prepared requests to a local JSONL file and uploads it to the configured S3 bucket in the 'input/' prefix.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict[str, Any]
|
The S3 upload response from boto3 |
Raises:
| Type | Description |
|---|---|
IOError
|
If local file operations fail |
ClientError
|
If S3 upload fails |
AttributeError
|
If called before prepare_requests() |
Note
- Creates/overwrites files both locally and in S3
- S3 path: {bucket_name}/input/{job_name}.jsonl
- Sets Content-Type to 'application/json'
Source code in src/llmbo/batch_inferer.py
recover_details_from_job_arn(job_arn, region, session=None, output_dir='.')
classmethod
Recover a BatchInferer instance from an existing job ARN.
Used to reconstruct a BatchInferer object when the original Python process has terminated but the AWS job is still running or complete.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_arn
|
str
|
(str) The AWS ARN of the existing batch inference job |
required |
region
|
str
|
(str) the region where the job was scheduled |
required |
session
|
session
|
A boto3 session to be used for calls to AWS, If one if not provided a new one will be created |
None
|
output_dir
|
str
|
Directory for local JSONL files. Defaults to ".". |
'.'
|
Returns:
| Name | Type | Description |
|---|---|---|
BatchInferer |
BatchInferer
|
A configured instance with the job's details |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the job cannot be found or response is invalid |
Example
job_arn = "arn:aws:bedrock:region:account:job/xyz123" bi = BatchInferer.recover_details_from_job_arn(job_arn) bi.check_complete() 'Completed'
Source code in src/llmbo/batch_inferer.py
DeepSeekAdapter
Bases: OpenAICompatibleAdapter
Adapter for DeepSeek models in AWS Bedrock.
DeepSeek follows the OpenAI function-calling convention but differs in two ways:
build_toolpasses the raw Pydantic schema as parameters (no$defsinlining needed).prepare_model_inputdoes not nullanthropic_versionor migrate the system prompt into the messages array.
Source code in src/llmbo/adapters/deepseek.py
build_tool(output_model)
classmethod
Build a tool definition using the raw Pydantic schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_model
|
type[BaseModel]
|
The Pydantic model to convert. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: A tool definition dict. |
Source code in src/llmbo/adapters/deepseek.py
prepare_model_input(model_input, output_model=None)
classmethod
Prepare model input for DeepSeek models.
Unlike other OpenAI-compatible providers, DeepSeek does not require the system prompt to be moved into the messages array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_input
|
ModelInput
|
The original model input. |
required |
output_model
|
type[BaseModel] | None
|
Optional Pydantic model defining the expected output structure. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
ModelInput |
ModelInput
|
Modified model input. |
Source code in src/llmbo/adapters/deepseek.py
LlamaAdapter
Bases: ModelProviderAdapter
Adapter for Meta Llama models (Llama 3 / 4) in AWS Bedrock.
This adapter handles: 1. Formatting the prompt using Meta's specific header tokens. 2. Enforcing JSON-only schema outputs. 3. Translating 'max_tokens' to Llama's native 'max_gen_len'.
Source code in src/llmbo/adapters/llama.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 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 | |
_schema_to_string(output_model)
staticmethod
Serialise a Pydantic model's JSON schema for prompt injection.
format_llama_prompt(user_prompt, system_prompt=None, tools=None)
staticmethod
Format a prompt using Meta's special header tokens.
Assembles the <|begin_of_text|>, system, user, and assistant
header blocks into a single string that Llama's native endpoint
expects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_prompt
|
str
|
The user's input or question. |
required |
system_prompt
|
str | None
|
Optional system instructions. |
None
|
tools
|
str | None
|
Optional JSON schema string to inject as a structured-output constraint. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The fully formatted prompt string. |
Source code in src/llmbo/adapters/llama.py
prepare_model_input(model_input, output_model=None)
classmethod
Prepare model input for Meta Llama models.
Converts the standard ModelInput into Llama's native format
by building a single prompt string with special header tokens,
translating max_tokens to max_gen_len, and nullifying
fields that Llama's endpoint does not accept.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_input
|
ModelInput
|
The original model input. |
required |
output_model
|
type[BaseModel] | None
|
Optional Pydantic model whose JSON schema is injected into the prompt to enforce structured output. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
ModelInput |
ModelInput
|
Modified model input with Llama-specific fields populated and unsupported fields set to None. |
Source code in src/llmbo/adapters/llama.py
validate_result(result, output_model)
classmethod
Validate and parse output from Llama models.
Llama's native endpoint returns free text in a generation
field. This method extracts the first JSON object found via
regex and validates it against the provided Pydantic model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
dict[str, Any]
|
Raw model output from Llama. |
required |
output_model
|
type[BaseModel]
|
Pydantic model to validate against. |
required |
Returns:
| Type | Description |
|---|---|
BaseModel | None
|
BaseModel | None: Validated model instance, or None if no JSON was found or validation fails. |
Source code in src/llmbo/adapters/llama.py
Manifest
Bases: BaseModel
Job manifest details.
Uses extra="allow" so that new fields returned by the AWS Bedrock API
(e.g. inputAudioSecond) are captured in model_extra instead of
raising TypeError.
Source code in src/llmbo/models.py
MistralAdapter
Bases: ModelProviderAdapter
Adapter for Mistral models in AWS Bedrock.
This adapter handles: 1. Formatting inputs for Mistral models 2. Building tool definitions in Mistral's format 3. Validating tool-use responses from Mistral models
Source code in src/llmbo/adapters/mistral.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 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 | |
build_tool(output_model)
classmethod
Build a tool definition in Mistral's format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_model
|
type[BaseModel]
|
The Pydantic model to convert to a tool definition |
required |
Returns:
| Type | Description |
|---|---|
str
|
Dict with function definition for Mistral's tools format |
Source code in src/llmbo/adapters/mistral.py
format_mistral_prompt(user_prompt, system_prompt=None, tools=None)
staticmethod
Formats the user prompt, system prompt, and tool definitions for Mistral models.
Parameters: - user_prompt (str): The user's input or question. - system_prompt (str, optional): The system's instructions or guidelines. Defaults to None. - tools (str, optional): Schema description. Defaults to None.
Returns: - str: The formatted prompt ready for input into the Mistral model.
Source code in src/llmbo/adapters/mistral.py
prepare_model_input(model_input, output_model=None)
classmethod
Prepare model input for Mistral models.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_input
|
ModelInput
|
The original model input configuration |
required |
output_model
|
type[BaseModel] | None
|
The Pydantic model defining the expected output structure |
None
|
Returns:
| Type | Description |
|---|---|
ModelInput
|
Modified model input with Mistral-specific configurations |
Source code in src/llmbo/adapters/mistral.py
validate_result(result, output_model)
classmethod
Validate and parse output from Mistral models.
Extracts structured data from Mistral's tool-use response format and validates it against the provided Pydantic model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
dict[str, Any]
|
Raw model output from Mistral |
required |
output_model
|
type[BaseModel]
|
Pydantic model to validate against |
required |
Returns:
| Type | Description |
|---|---|
BaseModel | None
|
Validated model instance or None if validation fails |
Source code in src/llmbo/adapters/mistral.py
MistralFunctionAdapter
Bases: ModelProviderAdapter
Adapter for Mistral models using function calling in AWS Bedrock.
This adapter handles: 1. Building tool definitions in Mistral's function-calling format. 2. Migrating the system prompt into the messages array. 3. Enforcing Mistral's 8192 token ceiling. 4. Validating tool-use responses with granular debug logging.
Source code in src/llmbo/adapters/mistral_function_calling.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 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 | |
build_tool(output_model)
classmethod
Build a tool definition in Mistral's function-calling format.
Preserves any $defs block generated by Pydantic, as Mistral
can resolve nested schema references.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_model
|
type[BaseModel]
|
The Pydantic model to convert to a tool definition. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: Tool definition dict with function name, description, and parameters. |
Source code in src/llmbo/adapters/mistral_function_calling.py
prepare_model_input(model_input, output_model=None)
classmethod
Prepare model input for Mistral function-calling models.
Moves the system prompt into the messages array, caps
max_tokens at 8192, and attaches a tool definition when
an output model is provided.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_input
|
ModelInput
|
The original model input. |
required |
output_model
|
type[BaseModel] | None
|
Optional Pydantic model defining the expected output structure. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
ModelInput |
ModelInput
|
Modified model input with Mistral-specific configurations applied. |
Source code in src/llmbo/adapters/mistral_function_calling.py
validate_result(result, output_model)
classmethod
Validate and parse output from Mistral function-calling models.
Performs granular checks on the response structure — finish reason, assistant role, tool call count, and tool name — with debug logging at each step to aid batch failure diagnosis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
dict[str, Any]
|
Raw model output from Mistral. |
required |
output_model
|
type[BaseModel]
|
Pydantic model to validate against. |
required |
Returns:
| Type | Description |
|---|---|
BaseModel | None
|
BaseModel | None: Validated model instance, or None if any check fails. |
Source code in src/llmbo/adapters/mistral_function_calling.py
ModelAdapterRegistry
Registry for model provider adapters.
This registry maps model name patterns to their corresponding adapter classes. Users can register custom adapters for new model providers or to override existing implementations.
Example
Register a custom adapter for a new model
ModelAdapterRegistry.register("my-custom-model", MyCustomAdapter)
Source code in src/llmbo/registry.py
get_adapter(model_name)
classmethod
Get the appropriate adapter for a model name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_name
|
str
|
The model name/ID to find an adapter for |
required |
Returns:
| Type | Description |
|---|---|
type[ModelProviderAdapter]
|
An adapter class for the given model, or the default adapter if no pattern |
type[ModelProviderAdapter]
|
is found |
Source code in src/llmbo/registry.py
register(pattern, adapter_class)
classmethod
Register an adapter class for a specific model pattern.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern
|
str
|
Regex pattern to match against model names |
required |
adapter_class
|
type[ModelProviderAdapter]
|
The adapter class to use for matching models |
required |
Raises:
| Type | Description |
|---|---|
TypeError
|
If adapter_class is not a subclass of ModelProviderAdapter |
Source code in src/llmbo/registry.py
ModelInput
dataclass
Configuration class for AWS Bedrock model inputs.
This class defines the structure and parameters for model invocation requests following AWS Bedrock's expected format. Provider-specific adapters may reshape or nullify fields as needed for their API.
See https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-anthropic-claude-messages.html
Attributes:
| Name | Type | Description |
|---|---|---|
messages |
list[dict] | None
|
List of message objects with role and content. Defaults to None. |
anthropic_version |
str | None
|
Version string for Anthropic models. Defaults to "bedrock-2023-05-31". |
max_tokens |
int | None
|
Maximum number of tokens in the response. Defaults to 2000. |
system |
str | list[dict[str, Any]] | None
|
System message for the model. A string for most providers; reshaped to a list of content blocks for Converse API models (e.g. Nova). |
stop_sequences |
list[str] | None
|
Custom stop sequences. |
temperature |
float | None
|
Sampling temperature. |
top_p |
float | None
|
Nucleus sampling parameter. |
top_k |
int | None
|
Top-k sampling parameter. |
tools |
list[dict] | None
|
Tool definitions for structured outputs. |
tool_choice |
ToolChoice | str | None
|
Tool selection configuration. |
prompt |
str | None
|
Native text prompt for models that use a single string instead of a messages array (e.g. Llama). |
max_gen_len |
int | None
|
Maximum generation length for models that use this parameter instead of max_tokens (e.g. Llama). |
inferenceConfig |
dict[str, Any] | None
|
Inference configuration for Converse API models (e.g. Nova). |
toolConfig |
dict[str, Any] | None
|
Tool configuration for Converse API models (e.g. Nova). |
additionalModelRequestFields |
dict[str, Any] | None
|
Extra provider request fields for Converse API models; used for parameters like topK that live outside inferenceConfig (e.g. Nova). |
Source code in src/llmbo/models.py
to_dict()
NovaAdapter
Bases: ModelProviderAdapter
Adapter for Amazon Nova models using the Bedrock Converse API.
This adapter handles:
1. Building tool definitions in the Converse toolSpec format.
2. Reshaping messages, system prompts, and token limits into
Converse API JSON arrays.
3. Inlining $defs to resolve Pydantic $ref pointers that
Nova cannot follow.
4. Validating toolUse responses from the Converse API.
Source code in src/llmbo/adapters/nova.py
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 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 | |
build_tool(output_model)
classmethod
Build a tool definition in the Converse API toolSpec format.
Inlines any $defs generated by Pydantic and provides a
fallback description if the model's schema has none, since the
Converse API rejects empty description strings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_model
|
type[BaseModel]
|
The Pydantic model to convert to a tool definition. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: A Converse API tool definition with
|
Source code in src/llmbo/adapters/nova.py
prepare_model_input(model_input, output_model=None)
classmethod
Prepare model input for Amazon Nova via the Converse API.
Reshapes the standard ModelInput into the Converse API
format: messages become content-block arrays, the system prompt
becomes a text array, and sampling parameters (max_tokens,
temperature, top_p) move into inferenceConfig. Nova does not
support top_k, so it is dropped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_input
|
ModelInput
|
The original model input. |
required |
output_model
|
type[BaseModel] | None
|
Optional Pydantic model defining the expected output structure. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
ModelInput |
ModelInput
|
Modified model input with Converse API fields populated and legacy fields nullified. |
Source code in src/llmbo/adapters/nova.py
validate_result(result, output_model)
classmethod
Validate and parse output from Amazon Nova's Converse API.
Searches the response content blocks for a toolUse entry
and validates its input against the provided Pydantic model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
dict[str, Any]
|
Raw model output from the Converse API. |
required |
output_model
|
type[BaseModel]
|
Pydantic model to validate against. |
required |
Returns:
| Type | Description |
|---|---|
BaseModel | None
|
BaseModel | None: Validated model instance, or None if no
|
Source code in src/llmbo/adapters/nova.py
OpenAIAdapter
Bases: OpenAICompatibleAdapter
Adapter for OpenAI models in AWS Bedrock.
Source code in src/llmbo/adapters/openai_oss.py
QwenAdapter
Bases: OpenAICompatibleAdapter
Adapter for Alibaba Qwen models in AWS Bedrock.
Source code in src/llmbo/adapters/qwen.py
StructuredBatchInferer
Bases: BatchInferer
A specialized BatchInferer that enforces structured outputs using Pydantic models.
Inspired by the instructor package, see: https://python.useinstructor.com/ This class extends BatchInferer to add schema validation and structured output handling using Pydantic models.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_model
|
BaseModel
|
A Pydantic model defining the expected output structure |
required |
model_name
|
str
|
The name/ID of the AWS Bedrock model to use |
required |
bucket_name
|
str
|
The S3 bucket name for storing input/output data |
required |
region
|
str
|
The region to run the batch inference job in. |
required |
job_name
|
str
|
A unique name for the batch inference job |
required |
role_arn
|
str
|
The AWS IAM role ARN with necessary permissions |
required |
time_out_duration_hours
|
int
|
Maximum job runtime in hours. Defaults to 24. |
24
|
session
|
Session
|
A boto3 session to be used for AWS API calls. If not provided, a new session will be created. |
None
|
Source code in src/llmbo/structured_batch_inferer.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 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 263 264 265 | |
__init__(output_model, model_name, bucket_name, region, job_name, role_arn, time_out_duration_hours=24, session=None, output_dir='.')
Initialize a StructuredBatchInferer for schema-validated batch processing.
Creates a batch inference manager that enforces structured outputs using a Pydantic model schema. Automatically configures the model to use tools for enforcing the output structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_model
|
BaseModel
|
Pydantic model class defining the expected output structure |
required |
model_name
|
str
|
The AWS Bedrock model identifier |
required |
bucket_name
|
str
|
Name of the S3 bucket for storing job inputs and outputs |
required |
region
|
str
|
Region of the LLM must match the bucket |
required |
job_name
|
str
|
Unique identifier for this batch job |
required |
role_arn
|
str
|
AWS IAM role ARN with permissions for Bedrock and S3 access |
required |
time_out_duration_hours
|
int
|
Number of hours before the job times out |
24
|
session
|
Session
|
A boto3 session to be used for AWS API calls. If not provided, a new session will be created. |
None
|
output_dir
|
str
|
Directory for local JSONL files. Defaults to ".". |
'.'
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If AWS_PROFILE environment variable is not set |
ValueError
|
If the provided role_arn doesn't exist or is invalid |
Example
class PersonInfo(BaseModel): ... name: str ... age: int ... sbi = StructuredBatchInferer( ... output_model=PersonInfo, ... model_name="anthropic.claude-3-haiku-20240307-v1:0", ... bucket_name="my-inference-bucket", ... job_name="structured-batch-2024", ... role_arn="arn:aws:iam::123456789012:role/BedrockBatchRole" ... )
Note
- Converts the Pydantic model into a tool definition for the LLM
- All results will be validated against the provided schema
- Failed schema validations will raise errors during result processing
- Inherits all base BatchInferer functionality
Source code in src/llmbo/structured_batch_inferer.py
load_results()
Load and validate batch inference results against the output schema.
Reads the output files downloaded from S3 and validates each result against the Pydantic output_model specified during initialization. Populates: - self.results: Raw inference results from the output JSONL file - self.manifest: Statistics about the job execution - self.instances: List of validated Pydantic model instances
Raises:
| Type | Description |
|---|---|
FileExistsError
|
If either the results or manifest files are not found locally |
ValueError
|
If any result fails schema validation or tool use validation |
Note
- Must call download_results() before calling this method
- All results must conform to the specified output_model schema
- Results must show successful tool use
Source code in src/llmbo/structured_batch_inferer.py
prepare_requests(inputs)
Prepare structured batch inference requests with tool configurations.
Extends the base preparation by adding tool definitions and tool choice parameters to each ModelInput. The tool definition is derived from the Pydantic output_model specified during initialization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inputs
|
Dict[str, ModelInput]
|
Dictionary mapping record IDs to their corresponding ModelInput configurations. The record IDs will be used to track results. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If len(inputs) < 100, as AWS Bedrock requires minimum batch size of 100 |
Example
class PersonInfo(BaseModel): ... name: str ... age: int sbi = StructuredBatchInferer(output_model=PersonInfo, ...) inputs = { ... "001": ModelInput( ... messages=[{"role": "user", "content": "John is 25 years old"}], ... ) ... } sbi.prepare_requests(inputs)
Note
- Automatically adds the output_model schema as a tool definition
- Sets tool_choice to force use of the defined schema
- Original ModelInputs are modified to include tool configurations
Source code in src/llmbo/structured_batch_inferer.py
recover_details_from_job_arn(job_arn, region, session=None, output_dir='.')
classmethod
Placeholder method for interface consistency.
This method exists to maintain compatibility with the parent class but
is not implemented for structured jobs. Use recover_structured_job
instead.
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
Always raised when called. |
Source code in src/llmbo/structured_batch_inferer.py
recover_structured_job(job_arn, region, output_model, session=None, output_dir='.')
classmethod
Recover a StructuredBatchInferer instance from an existing job ARN.
Used to reconstruct a StructuredBatchInferer object when the original Python process has terminated but the AWS job is still running or complete.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_arn
|
str
|
(str) The AWS ARN of the existing batch inference job |
required |
region
|
str
|
(str) the region where the job was scheduled |
required |
output_model
|
type[BaseModel]
|
(type[BaseModel]) A pydantic model describing the required output |
required |
session
|
Session
|
A boto3 session to be used for AWS API calls. If not provided, a new session will be created. |
None
|
output_dir
|
str
|
Directory for local JSONL files. Defaults to ".". |
'.'
|
Returns:
| Name | Type | Description |
|---|---|---|
StructuredBatchInferer |
StructuredBatchInferer
|
A configured instance with the job's details |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the job cannot be found or response is invalid |
Example
job_arn = "arn:aws:bedrock:region:account:job/xyz123" region = us-east-1" sbi = StructuredBatchInferer.recover_structured_job(job_arn, region, some_model) sbi.check_complete() 'Completed'
Source code in src/llmbo/structured_batch_inferer.py
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 | |